driver.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. "time"
  15. log "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/daemon/execdriver"
  17. "github.com/docker/docker/pkg/reexec"
  18. sysinfo "github.com/docker/docker/pkg/system"
  19. "github.com/docker/docker/pkg/term"
  20. "github.com/docker/libcontainer"
  21. "github.com/docker/libcontainer/apparmor"
  22. "github.com/docker/libcontainer/cgroups/systemd"
  23. "github.com/docker/libcontainer/configs"
  24. "github.com/docker/libcontainer/system"
  25. "github.com/docker/libcontainer/utils"
  26. )
  27. const (
  28. DriverName = "native"
  29. Version = "0.2"
  30. )
  31. type driver struct {
  32. root string
  33. initPath string
  34. activeContainers map[string]libcontainer.Container
  35. machineMemory int64
  36. factory libcontainer.Factory
  37. sync.Mutex
  38. }
  39. func NewDriver(root, initPath string) (*driver, error) {
  40. meminfo, err := sysinfo.ReadMemInfo()
  41. if err != nil {
  42. return nil, err
  43. }
  44. if err := os.MkdirAll(root, 0700); err != nil {
  45. return nil, err
  46. }
  47. // native driver root is at docker_root/execdriver/native. Put apparmor at docker_root
  48. if err := apparmor.InstallDefaultProfile(); err != nil {
  49. return nil, err
  50. }
  51. cgm := libcontainer.Cgroupfs
  52. if systemd.UseSystemd() {
  53. cgm = libcontainer.SystemdCgroups
  54. }
  55. f, err := libcontainer.New(root, cgm, libcontainer.InitPath(reexec.Self(), DriverName))
  56. if err != nil {
  57. return nil, err
  58. }
  59. return &driver{
  60. root: root,
  61. initPath: initPath,
  62. activeContainers: make(map[string]libcontainer.Container),
  63. machineMemory: meminfo.MemTotal,
  64. factory: f,
  65. }, nil
  66. }
  67. type execOutput struct {
  68. exitCode int
  69. err error
  70. }
  71. func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
  72. // take the Command and populate the libcontainer.Config from it
  73. container, err := d.createContainer(c)
  74. if err != nil {
  75. return execdriver.ExitStatus{ExitCode: -1}, err
  76. }
  77. var term execdriver.Terminal
  78. p := &libcontainer.Process{
  79. Args: append([]string{c.ProcessConfig.Entrypoint}, c.ProcessConfig.Arguments...),
  80. Env: c.ProcessConfig.Env,
  81. Cwd: c.WorkingDir,
  82. User: c.ProcessConfig.User,
  83. }
  84. if c.ProcessConfig.Tty {
  85. rootuid, err := container.HostUID()
  86. if err != nil {
  87. return execdriver.ExitStatus{ExitCode: -1}, err
  88. }
  89. cons, err := p.NewConsole(rootuid)
  90. if err != nil {
  91. return execdriver.ExitStatus{ExitCode: -1}, err
  92. }
  93. term, err = NewTtyConsole(cons, pipes, rootuid)
  94. } else {
  95. p.Stdout = pipes.Stdout
  96. p.Stderr = pipes.Stderr
  97. r, w, err := os.Pipe()
  98. if err != nil {
  99. return execdriver.ExitStatus{ExitCode: -1}, err
  100. }
  101. if pipes.Stdin != nil {
  102. go func() {
  103. io.Copy(w, pipes.Stdin)
  104. w.Close()
  105. }()
  106. p.Stdin = r
  107. }
  108. term = &execdriver.StdConsole{}
  109. }
  110. if err != nil {
  111. return execdriver.ExitStatus{ExitCode: -1}, err
  112. }
  113. c.ProcessConfig.Terminal = term
  114. cont, err := d.factory.Create(c.ID, container)
  115. if err != nil {
  116. return execdriver.ExitStatus{ExitCode: -1}, err
  117. }
  118. d.Lock()
  119. d.activeContainers[c.ID] = cont
  120. d.Unlock()
  121. defer func() {
  122. cont.Destroy()
  123. d.cleanContainer(c.ID)
  124. }()
  125. if err := cont.Start(p); err != nil {
  126. return execdriver.ExitStatus{ExitCode: -1}, err
  127. }
  128. if startCallback != nil {
  129. pid, err := p.Pid()
  130. if err != nil {
  131. p.Signal(os.Kill)
  132. p.Wait()
  133. return execdriver.ExitStatus{ExitCode: -1}, err
  134. }
  135. startCallback(&c.ProcessConfig, pid)
  136. }
  137. oomKillNotification, err := cont.NotifyOOM()
  138. if err != nil {
  139. oomKillNotification = nil
  140. log.Warnf("WARNING: Your kernel does not support OOM notifications: %s", err)
  141. }
  142. waitF := p.Wait
  143. if nss := cont.Config().Namespaces; nss.Contains(configs.NEWPID) {
  144. // we need such hack for tracking processes with inerited fds,
  145. // because cmd.Wait() waiting for all streams to be copied
  146. waitF = waitInPIDHost(p, cont)
  147. }
  148. ps, err := waitF()
  149. if err != nil {
  150. if err, ok := err.(*exec.ExitError); !ok {
  151. return execdriver.ExitStatus{ExitCode: -1}, err
  152. } else {
  153. ps = err.ProcessState
  154. }
  155. }
  156. cont.Destroy()
  157. _, oomKill := <-oomKillNotification
  158. return execdriver.ExitStatus{ExitCode: utils.ExitStatus(ps.Sys().(syscall.WaitStatus)), OOMKilled: oomKill}, nil
  159. }
  160. func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*os.ProcessState, error) {
  161. return func() (*os.ProcessState, error) {
  162. pid, err := p.Pid()
  163. if err != nil {
  164. return nil, err
  165. }
  166. process, err := os.FindProcess(pid)
  167. s, err := process.Wait()
  168. if err != nil {
  169. if err, ok := err.(*exec.ExitError); !ok {
  170. return s, err
  171. } else {
  172. s = err.ProcessState
  173. }
  174. }
  175. processes, err := c.Processes()
  176. if err != nil {
  177. return s, err
  178. }
  179. for _, pid := range processes {
  180. process, err := os.FindProcess(pid)
  181. if err != nil {
  182. log.Errorf("Failed to kill process: %d", pid)
  183. continue
  184. }
  185. process.Kill()
  186. }
  187. p.Wait()
  188. return s, err
  189. }
  190. }
  191. func (d *driver) Kill(c *execdriver.Command, sig int) error {
  192. active := d.activeContainers[c.ID]
  193. if active == nil {
  194. return fmt.Errorf("active container for %s does not exist", c.ID)
  195. }
  196. state, err := active.State()
  197. if err != nil {
  198. return err
  199. }
  200. return syscall.Kill(state.InitProcessPid, syscall.Signal(sig))
  201. }
  202. func (d *driver) Pause(c *execdriver.Command) error {
  203. active := d.activeContainers[c.ID]
  204. if active == nil {
  205. return fmt.Errorf("active container for %s does not exist", c.ID)
  206. }
  207. return active.Pause()
  208. }
  209. func (d *driver) Unpause(c *execdriver.Command) error {
  210. active := d.activeContainers[c.ID]
  211. if active == nil {
  212. return fmt.Errorf("active container for %s does not exist", c.ID)
  213. }
  214. return active.Resume()
  215. }
  216. func (d *driver) Terminate(c *execdriver.Command) error {
  217. // lets check the start time for the process
  218. active := d.activeContainers[c.ID]
  219. if active == nil {
  220. return fmt.Errorf("active container for %s does not exist", c.ID)
  221. }
  222. state, err := active.State()
  223. if err != nil {
  224. return err
  225. }
  226. pid := state.InitProcessPid
  227. currentStartTime, err := system.GetProcessStartTime(pid)
  228. if err != nil {
  229. return err
  230. }
  231. if state.InitProcessStartTime == currentStartTime {
  232. err = syscall.Kill(pid, 9)
  233. syscall.Wait4(pid, nil, 0, nil)
  234. }
  235. d.cleanContainer(c.ID)
  236. return err
  237. }
  238. func (d *driver) Info(id string) execdriver.Info {
  239. return &info{
  240. ID: id,
  241. driver: d,
  242. }
  243. }
  244. func (d *driver) Name() string {
  245. return fmt.Sprintf("%s-%s", DriverName, Version)
  246. }
  247. func (d *driver) GetPidsForContainer(id string) ([]int, error) {
  248. d.Lock()
  249. active := d.activeContainers[id]
  250. d.Unlock()
  251. if active == nil {
  252. return nil, fmt.Errorf("active container for %s does not exist", id)
  253. }
  254. return active.Processes()
  255. }
  256. func (d *driver) writeContainerFile(container *configs.Config, id string) error {
  257. data, err := json.Marshal(container)
  258. if err != nil {
  259. return err
  260. }
  261. return ioutil.WriteFile(filepath.Join(d.root, id, "container.json"), data, 0655)
  262. }
  263. func (d *driver) cleanContainer(id string) error {
  264. d.Lock()
  265. delete(d.activeContainers, id)
  266. d.Unlock()
  267. return os.RemoveAll(filepath.Join(d.root, id, "container.json"))
  268. }
  269. func (d *driver) createContainerRoot(id string) error {
  270. return os.MkdirAll(filepath.Join(d.root, id), 0655)
  271. }
  272. func (d *driver) Clean(id string) error {
  273. return os.RemoveAll(filepath.Join(d.root, id))
  274. }
  275. func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) {
  276. c := d.activeContainers[id]
  277. if c == nil {
  278. return nil, execdriver.ErrNotRunning
  279. }
  280. now := time.Now()
  281. stats, err := c.Stats()
  282. if err != nil {
  283. return nil, err
  284. }
  285. memoryLimit := c.Config().Cgroups.Memory
  286. // if the container does not have any memory limit specified set the
  287. // limit to the machines memory
  288. if memoryLimit == 0 {
  289. memoryLimit = d.machineMemory
  290. }
  291. return &execdriver.ResourceStats{
  292. Stats: stats,
  293. Read: now,
  294. MemoryLimit: memoryLimit,
  295. }, nil
  296. }
  297. func getEnv(key string, env []string) string {
  298. for _, pair := range env {
  299. parts := strings.Split(pair, "=")
  300. if parts[0] == key {
  301. return parts[1]
  302. }
  303. }
  304. return ""
  305. }
  306. type TtyConsole struct {
  307. console libcontainer.Console
  308. }
  309. func NewTtyConsole(console libcontainer.Console, pipes *execdriver.Pipes, rootuid int) (*TtyConsole, error) {
  310. tty := &TtyConsole{
  311. console: console,
  312. }
  313. if err := tty.AttachPipes(pipes); err != nil {
  314. tty.Close()
  315. return nil, err
  316. }
  317. return tty, nil
  318. }
  319. func (t *TtyConsole) Master() libcontainer.Console {
  320. return t.console
  321. }
  322. func (t *TtyConsole) Resize(h, w int) error {
  323. return term.SetWinsize(t.console.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
  324. }
  325. func (t *TtyConsole) AttachPipes(pipes *execdriver.Pipes) error {
  326. go func() {
  327. if wb, ok := pipes.Stdout.(interface {
  328. CloseWriters() error
  329. }); ok {
  330. defer wb.CloseWriters()
  331. }
  332. io.Copy(pipes.Stdout, t.console)
  333. }()
  334. if pipes.Stdin != nil {
  335. go func() {
  336. io.Copy(t.console, pipes.Stdin)
  337. pipes.Stdin.Close()
  338. }()
  339. }
  340. return nil
  341. }
  342. func (t *TtyConsole) Close() error {
  343. return t.console.Close()
  344. }