driver.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // +build linux,cgo
  2. package native
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. log "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/pkg/term"
  17. "github.com/docker/libcontainer"
  18. "github.com/docker/libcontainer/apparmor"
  19. "github.com/docker/libcontainer/cgroups/fs"
  20. "github.com/docker/libcontainer/cgroups/systemd"
  21. consolepkg "github.com/docker/libcontainer/console"
  22. "github.com/docker/libcontainer/namespaces"
  23. _ "github.com/docker/libcontainer/namespaces/nsenter"
  24. "github.com/docker/libcontainer/system"
  25. )
  26. const (
  27. DriverName = "native"
  28. Version = "0.2"
  29. )
  30. type activeContainer struct {
  31. container *libcontainer.Config
  32. cmd *exec.Cmd
  33. }
  34. type driver struct {
  35. root string
  36. initPath string
  37. activeContainers map[string]*activeContainer
  38. sync.Mutex
  39. }
  40. func NewDriver(root, initPath string) (*driver, error) {
  41. if err := os.MkdirAll(root, 0700); err != nil {
  42. return nil, err
  43. }
  44. // native driver root is at docker_root/execdriver/native. Put apparmor at docker_root
  45. if err := apparmor.InstallDefaultProfile(); err != nil {
  46. return nil, err
  47. }
  48. return &driver{
  49. root: root,
  50. initPath: initPath,
  51. activeContainers: make(map[string]*activeContainer),
  52. }, nil
  53. }
  54. type execOutput struct {
  55. exitCode int
  56. err error
  57. }
  58. func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
  59. // take the Command and populate the libcontainer.Config from it
  60. container, err := d.createContainer(c)
  61. if err != nil {
  62. return execdriver.ExitStatus{ExitCode: -1}, err
  63. }
  64. var term execdriver.Terminal
  65. if c.ProcessConfig.Tty {
  66. term, err = NewTtyConsole(&c.ProcessConfig, pipes)
  67. } else {
  68. term, err = execdriver.NewStdConsole(&c.ProcessConfig, pipes)
  69. }
  70. if err != nil {
  71. return execdriver.ExitStatus{ExitCode: -1}, err
  72. }
  73. c.ProcessConfig.Terminal = term
  74. d.Lock()
  75. d.activeContainers[c.ID] = &activeContainer{
  76. container: container,
  77. cmd: &c.ProcessConfig.Cmd,
  78. }
  79. d.Unlock()
  80. var (
  81. dataPath = filepath.Join(d.root, c.ID)
  82. args = append([]string{c.ProcessConfig.Entrypoint}, c.ProcessConfig.Arguments...)
  83. )
  84. if err := d.createContainerRoot(c.ID); err != nil {
  85. return execdriver.ExitStatus{ExitCode: -1}, err
  86. }
  87. defer d.cleanContainer(c.ID)
  88. if err := d.writeContainerFile(container, c.ID); err != nil {
  89. return execdriver.ExitStatus{ExitCode: -1}, err
  90. }
  91. execOutputChan := make(chan execOutput, 1)
  92. waitForStart := make(chan struct{})
  93. go func() {
  94. exitCode, err := namespaces.Exec(container, c.ProcessConfig.Stdin, c.ProcessConfig.Stdout, c.ProcessConfig.Stderr, c.ProcessConfig.Console, dataPath, args, func(container *libcontainer.Config, console, dataPath, init string, child *os.File, args []string) *exec.Cmd {
  95. c.ProcessConfig.Path = d.initPath
  96. c.ProcessConfig.Args = append([]string{
  97. DriverName,
  98. "-console", console,
  99. "-pipe", "3",
  100. "-root", filepath.Join(d.root, c.ID),
  101. "--",
  102. }, args...)
  103. // set this to nil so that when we set the clone flags anything else is reset
  104. c.ProcessConfig.SysProcAttr = &syscall.SysProcAttr{
  105. Cloneflags: uintptr(namespaces.GetNamespaceFlags(container.Namespaces)),
  106. }
  107. c.ProcessConfig.ExtraFiles = []*os.File{child}
  108. c.ProcessConfig.Env = container.Env
  109. c.ProcessConfig.Dir = container.RootFs
  110. return &c.ProcessConfig.Cmd
  111. }, func() {
  112. close(waitForStart)
  113. if startCallback != nil {
  114. c.ContainerPid = c.ProcessConfig.Process.Pid
  115. startCallback(&c.ProcessConfig, c.ContainerPid)
  116. }
  117. })
  118. execOutputChan <- execOutput{exitCode, err}
  119. }()
  120. select {
  121. case execOutput := <-execOutputChan:
  122. return execdriver.ExitStatus{ExitCode: execOutput.exitCode}, execOutput.err
  123. case <-waitForStart:
  124. break
  125. }
  126. oomKill := false
  127. state, err := libcontainer.GetState(filepath.Join(d.root, c.ID))
  128. if err == nil {
  129. oomKillNotification, err := libcontainer.NotifyOnOOM(state)
  130. if err == nil {
  131. _, oomKill = <-oomKillNotification
  132. } else {
  133. log.Warnf("WARNING: Your kernel does not support OOM notifications: %s", err)
  134. }
  135. } else {
  136. log.Warnf("Failed to get container state, oom notify will not work: %s", err)
  137. }
  138. // wait for the container to exit.
  139. execOutput := <-execOutputChan
  140. return execdriver.ExitStatus{ExitCode: execOutput.exitCode, OOMKilled: oomKill}, execOutput.err
  141. }
  142. func (d *driver) Kill(p *execdriver.Command, sig int) error {
  143. return syscall.Kill(p.ProcessConfig.Process.Pid, syscall.Signal(sig))
  144. }
  145. func (d *driver) Pause(c *execdriver.Command) error {
  146. active := d.activeContainers[c.ID]
  147. if active == nil {
  148. return fmt.Errorf("active container for %s does not exist", c.ID)
  149. }
  150. active.container.Cgroups.Freezer = "FROZEN"
  151. if systemd.UseSystemd() {
  152. return systemd.Freeze(active.container.Cgroups, active.container.Cgroups.Freezer)
  153. }
  154. return fs.Freeze(active.container.Cgroups, active.container.Cgroups.Freezer)
  155. }
  156. func (d *driver) Unpause(c *execdriver.Command) error {
  157. active := d.activeContainers[c.ID]
  158. if active == nil {
  159. return fmt.Errorf("active container for %s does not exist", c.ID)
  160. }
  161. active.container.Cgroups.Freezer = "THAWED"
  162. if systemd.UseSystemd() {
  163. return systemd.Freeze(active.container.Cgroups, active.container.Cgroups.Freezer)
  164. }
  165. return fs.Freeze(active.container.Cgroups, active.container.Cgroups.Freezer)
  166. }
  167. func (d *driver) Terminate(p *execdriver.Command) error {
  168. // lets check the start time for the process
  169. state, err := libcontainer.GetState(filepath.Join(d.root, p.ID))
  170. if err != nil {
  171. if !os.IsNotExist(err) {
  172. return err
  173. }
  174. // TODO: Remove this part for version 1.2.0
  175. // This is added only to ensure smooth upgrades from pre 1.1.0 to 1.1.0
  176. data, err := ioutil.ReadFile(filepath.Join(d.root, p.ID, "start"))
  177. if err != nil {
  178. // if we don't have the data on disk then we can assume the process is gone
  179. // because this is only removed after we know the process has stopped
  180. if os.IsNotExist(err) {
  181. return nil
  182. }
  183. return err
  184. }
  185. state = &libcontainer.State{InitStartTime: string(data)}
  186. }
  187. currentStartTime, err := system.GetProcessStartTime(p.ProcessConfig.Process.Pid)
  188. if err != nil {
  189. return err
  190. }
  191. if state.InitStartTime == currentStartTime {
  192. err = syscall.Kill(p.ProcessConfig.Process.Pid, 9)
  193. syscall.Wait4(p.ProcessConfig.Process.Pid, nil, 0, nil)
  194. }
  195. d.cleanContainer(p.ID)
  196. return err
  197. }
  198. func (d *driver) Info(id string) execdriver.Info {
  199. return &info{
  200. ID: id,
  201. driver: d,
  202. }
  203. }
  204. func (d *driver) Name() string {
  205. return fmt.Sprintf("%s-%s", DriverName, Version)
  206. }
  207. func (d *driver) GetPidsForContainer(id string) ([]int, error) {
  208. d.Lock()
  209. active := d.activeContainers[id]
  210. d.Unlock()
  211. if active == nil {
  212. return nil, fmt.Errorf("active container for %s does not exist", id)
  213. }
  214. c := active.container.Cgroups
  215. if systemd.UseSystemd() {
  216. return systemd.GetPids(c)
  217. }
  218. return fs.GetPids(c)
  219. }
  220. func (d *driver) writeContainerFile(container *libcontainer.Config, id string) error {
  221. data, err := json.Marshal(container)
  222. if err != nil {
  223. return err
  224. }
  225. return ioutil.WriteFile(filepath.Join(d.root, id, "container.json"), data, 0655)
  226. }
  227. func (d *driver) cleanContainer(id string) error {
  228. d.Lock()
  229. delete(d.activeContainers, id)
  230. d.Unlock()
  231. return os.RemoveAll(filepath.Join(d.root, id, "container.json"))
  232. }
  233. func (d *driver) createContainerRoot(id string) error {
  234. return os.MkdirAll(filepath.Join(d.root, id), 0655)
  235. }
  236. func (d *driver) Clean(id string) error {
  237. return os.RemoveAll(filepath.Join(d.root, id))
  238. }
  239. func getEnv(key string, env []string) string {
  240. for _, pair := range env {
  241. parts := strings.Split(pair, "=")
  242. if parts[0] == key {
  243. return parts[1]
  244. }
  245. }
  246. return ""
  247. }
  248. type TtyConsole struct {
  249. MasterPty *os.File
  250. }
  251. func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes) (*TtyConsole, error) {
  252. ptyMaster, console, err := consolepkg.CreateMasterAndConsole()
  253. if err != nil {
  254. return nil, err
  255. }
  256. tty := &TtyConsole{
  257. MasterPty: ptyMaster,
  258. }
  259. if err := tty.AttachPipes(&processConfig.Cmd, pipes); err != nil {
  260. tty.Close()
  261. return nil, err
  262. }
  263. processConfig.Console = console
  264. return tty, nil
  265. }
  266. func (t *TtyConsole) Master() *os.File {
  267. return t.MasterPty
  268. }
  269. func (t *TtyConsole) Resize(h, w int) error {
  270. return term.SetWinsize(t.MasterPty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
  271. }
  272. func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error {
  273. go func() {
  274. if wb, ok := pipes.Stdout.(interface {
  275. CloseWriters() error
  276. }); ok {
  277. defer wb.CloseWriters()
  278. }
  279. io.Copy(pipes.Stdout, t.MasterPty)
  280. }()
  281. if pipes.Stdin != nil {
  282. go func() {
  283. io.Copy(t.MasterPty, pipes.Stdin)
  284. pipes.Stdin.Close()
  285. }()
  286. }
  287. return nil
  288. }
  289. func (t *TtyConsole) Close() error {
  290. return t.MasterPty.Close()
  291. }