driver.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package native
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "github.com/dotcloud/docker/daemon/execdriver"
  13. "github.com/dotcloud/docker/pkg/apparmor"
  14. "github.com/dotcloud/docker/pkg/libcontainer"
  15. "github.com/dotcloud/docker/pkg/libcontainer/cgroups"
  16. "github.com/dotcloud/docker/pkg/libcontainer/nsinit"
  17. "github.com/dotcloud/docker/pkg/system"
  18. )
  19. const (
  20. DriverName = "native"
  21. Version = "0.2"
  22. BackupApparmorProfilePath = "apparmor/docker.back" // relative to docker root
  23. )
  24. func init() {
  25. execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error {
  26. var container *libcontainer.Container
  27. f, err := os.Open(filepath.Join(args.Root, "container.json"))
  28. if err != nil {
  29. return err
  30. }
  31. if err := json.NewDecoder(f).Decode(&container); err != nil {
  32. f.Close()
  33. return err
  34. }
  35. f.Close()
  36. rootfs, err := os.Getwd()
  37. if err != nil {
  38. return err
  39. }
  40. syncPipe, err := nsinit.NewSyncPipeFromFd(0, uintptr(args.Pipe))
  41. if err != nil {
  42. return err
  43. }
  44. if err := nsinit.Init(container, rootfs, args.Console, syncPipe, args.Args); err != nil {
  45. return err
  46. }
  47. return nil
  48. })
  49. }
  50. type driver struct {
  51. root string
  52. initPath string
  53. activeContainers map[string]*exec.Cmd
  54. }
  55. func NewDriver(root, initPath string) (*driver, error) {
  56. if err := os.MkdirAll(root, 0700); err != nil {
  57. return nil, err
  58. }
  59. // native driver root is at docker_root/execdriver/native. Put apparmor at docker_root
  60. if err := apparmor.InstallDefaultProfile(filepath.Join(root, "../..", BackupApparmorProfilePath)); err != nil {
  61. return nil, err
  62. }
  63. return &driver{
  64. root: root,
  65. initPath: initPath,
  66. activeContainers: make(map[string]*exec.Cmd),
  67. }, nil
  68. }
  69. func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
  70. // take the Command and populate the libcontainer.Container from it
  71. container, err := d.createContainer(c)
  72. if err != nil {
  73. return -1, err
  74. }
  75. d.activeContainers[c.ID] = &c.Cmd
  76. var (
  77. dataPath = filepath.Join(d.root, c.ID)
  78. args = append([]string{c.Entrypoint}, c.Arguments...)
  79. )
  80. if err := d.createContainerRoot(c.ID); err != nil {
  81. return -1, err
  82. }
  83. defer d.removeContainerRoot(c.ID)
  84. if err := d.writeContainerFile(container, c.ID); err != nil {
  85. return -1, err
  86. }
  87. term := getTerminal(c, pipes)
  88. return nsinit.Exec(container, term, c.Rootfs, dataPath, args, func(container *libcontainer.Container, console, rootfs, dataPath, init string, child *os.File, args []string) *exec.Cmd {
  89. // we need to join the rootfs because nsinit will setup the rootfs and chroot
  90. initPath := filepath.Join(c.Rootfs, c.InitPath)
  91. c.Path = d.initPath
  92. c.Args = append([]string{
  93. initPath,
  94. "-driver", DriverName,
  95. "-console", console,
  96. "-pipe", "3",
  97. "-root", filepath.Join(d.root, c.ID),
  98. "--",
  99. }, args...)
  100. // set this to nil so that when we set the clone flags anything else is reset
  101. c.SysProcAttr = nil
  102. system.SetCloneFlags(&c.Cmd, uintptr(nsinit.GetNamespaceFlags(container.Namespaces)))
  103. c.ExtraFiles = []*os.File{child}
  104. c.Env = container.Env
  105. c.Dir = c.Rootfs
  106. return &c.Cmd
  107. }, func() {
  108. if startCallback != nil {
  109. c.ContainerPid = c.Process.Pid
  110. startCallback(c)
  111. }
  112. })
  113. }
  114. func (d *driver) Kill(p *execdriver.Command, sig int) error {
  115. return syscall.Kill(p.Process.Pid, syscall.Signal(sig))
  116. }
  117. func (d *driver) Terminate(p *execdriver.Command) error {
  118. // lets check the start time for the process
  119. started, err := d.readStartTime(p)
  120. if err != nil {
  121. // if we don't have the data on disk then we can assume the process is gone
  122. // because this is only removed after we know the process has stopped
  123. if os.IsNotExist(err) {
  124. return nil
  125. }
  126. return err
  127. }
  128. currentStartTime, err := system.GetProcessStartTime(p.Process.Pid)
  129. if err != nil {
  130. return err
  131. }
  132. if started == currentStartTime {
  133. err = syscall.Kill(p.Process.Pid, 9)
  134. }
  135. d.removeContainerRoot(p.ID)
  136. return err
  137. }
  138. func (d *driver) readStartTime(p *execdriver.Command) (string, error) {
  139. data, err := ioutil.ReadFile(filepath.Join(d.root, p.ID, "start"))
  140. if err != nil {
  141. return "", err
  142. }
  143. return string(data), nil
  144. }
  145. func (d *driver) Info(id string) execdriver.Info {
  146. return &info{
  147. ID: id,
  148. driver: d,
  149. }
  150. }
  151. func (d *driver) Name() string {
  152. return fmt.Sprintf("%s-%s", DriverName, Version)
  153. }
  154. // TODO: this can be improved with our driver
  155. // there has to be a better way to do this
  156. func (d *driver) GetPidsForContainer(id string) ([]int, error) {
  157. pids := []int{}
  158. subsystem := "devices"
  159. cgroupRoot, err := cgroups.FindCgroupMountpoint(subsystem)
  160. if err != nil {
  161. return pids, err
  162. }
  163. cgroupDir, err := cgroups.GetThisCgroupDir(subsystem)
  164. if err != nil {
  165. return pids, err
  166. }
  167. filename := filepath.Join(cgroupRoot, cgroupDir, id, "tasks")
  168. if _, err := os.Stat(filename); os.IsNotExist(err) {
  169. filename = filepath.Join(cgroupRoot, cgroupDir, "docker", id, "tasks")
  170. }
  171. output, err := ioutil.ReadFile(filename)
  172. if err != nil {
  173. return pids, err
  174. }
  175. for _, p := range strings.Split(string(output), "\n") {
  176. if len(p) == 0 {
  177. continue
  178. }
  179. pid, err := strconv.Atoi(p)
  180. if err != nil {
  181. return pids, fmt.Errorf("Invalid pid '%s': %s", p, err)
  182. }
  183. pids = append(pids, pid)
  184. }
  185. return pids, nil
  186. }
  187. func (d *driver) writeContainerFile(container *libcontainer.Container, id string) error {
  188. data, err := json.Marshal(container)
  189. if err != nil {
  190. return err
  191. }
  192. return ioutil.WriteFile(filepath.Join(d.root, id, "container.json"), data, 0655)
  193. }
  194. func (d *driver) createContainerRoot(id string) error {
  195. return os.MkdirAll(filepath.Join(d.root, id), 0655)
  196. }
  197. func (d *driver) removeContainerRoot(id string) error {
  198. return os.RemoveAll(filepath.Join(d.root, id))
  199. }
  200. func getEnv(key string, env []string) string {
  201. for _, pair := range env {
  202. parts := strings.Split(pair, "=")
  203. if parts[0] == key {
  204. return parts[1]
  205. }
  206. }
  207. return ""
  208. }
  209. func getTerminal(c *execdriver.Command, pipes *execdriver.Pipes) nsinit.Terminal {
  210. var term nsinit.Terminal
  211. if c.Tty {
  212. term = &dockerTtyTerm{
  213. pipes: pipes,
  214. }
  215. } else {
  216. term = &dockerStdTerm{
  217. pipes: pipes,
  218. }
  219. }
  220. c.Terminal = term
  221. return term
  222. }