driver.go 8.8 KB

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