container_linux.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package libcontainerd
  2. import (
  3. "encoding/json"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "github.com/Sirupsen/logrus"
  12. containerd "github.com/docker/containerd/api/grpc/types"
  13. "github.com/docker/docker/pkg/ioutils"
  14. "github.com/docker/docker/restartmanager"
  15. "github.com/opencontainers/specs/specs-go"
  16. "github.com/tonistiigi/fifo"
  17. "golang.org/x/net/context"
  18. )
  19. type container struct {
  20. containerCommon
  21. // Platform specific fields are below here.
  22. pauseMonitor
  23. oom bool
  24. runtime string
  25. runtimeArgs []string
  26. }
  27. type runtime struct {
  28. path string
  29. args []string
  30. }
  31. // WithRuntime sets the runtime to be used for the created container
  32. func WithRuntime(path string, args []string) CreateOption {
  33. return runtime{path, args}
  34. }
  35. func (rt runtime) Apply(p interface{}) error {
  36. if pr, ok := p.(*container); ok {
  37. pr.runtime = rt.path
  38. pr.runtimeArgs = rt.args
  39. }
  40. return nil
  41. }
  42. func (ctr *container) clean() error {
  43. if os.Getenv("LIBCONTAINERD_NOCLEAN") == "1" {
  44. return nil
  45. }
  46. if _, err := os.Lstat(ctr.dir); err != nil {
  47. if os.IsNotExist(err) {
  48. return nil
  49. }
  50. return err
  51. }
  52. if err := os.RemoveAll(ctr.dir); err != nil {
  53. return err
  54. }
  55. return nil
  56. }
  57. // cleanProcess removes the fifos used by an additional process.
  58. // Caller needs to lock container ID before calling this method.
  59. func (ctr *container) cleanProcess(id string) {
  60. if p, ok := ctr.processes[id]; ok {
  61. for _, i := range []int{syscall.Stdin, syscall.Stdout, syscall.Stderr} {
  62. if err := os.Remove(p.fifo(i)); err != nil {
  63. logrus.Warnf("libcontainerd: failed to remove %v for process %v: %v", p.fifo(i), id, err)
  64. }
  65. }
  66. }
  67. delete(ctr.processes, id)
  68. }
  69. func (ctr *container) spec() (*specs.Spec, error) {
  70. var spec specs.Spec
  71. dt, err := ioutil.ReadFile(filepath.Join(ctr.dir, configFilename))
  72. if err != nil {
  73. return nil, err
  74. }
  75. if err := json.Unmarshal(dt, &spec); err != nil {
  76. return nil, err
  77. }
  78. return &spec, nil
  79. }
  80. func (ctr *container) start() error {
  81. spec, err := ctr.spec()
  82. if err != nil {
  83. return nil
  84. }
  85. ctx, cancel := context.WithCancel(context.Background())
  86. defer cancel()
  87. ready := make(chan struct{})
  88. iopipe, err := ctr.openFifos(spec.Process.Terminal)
  89. if err != nil {
  90. return err
  91. }
  92. var stdinOnce sync.Once
  93. // we need to delay stdin closure after container start or else "stdin close"
  94. // event will be rejected by containerd.
  95. // stdin closure happens in AttachStreams
  96. stdin := iopipe.Stdin
  97. iopipe.Stdin = ioutils.NewWriteCloserWrapper(stdin, func() error {
  98. var err error
  99. stdinOnce.Do(func() { // on error from attach we don't know if stdin was already closed
  100. err = stdin.Close()
  101. go func() {
  102. select {
  103. case <-ready:
  104. if err := ctr.sendCloseStdin(); err != nil {
  105. logrus.Warnf("failed to close stdin: %+v")
  106. }
  107. case <-ctx.Done():
  108. }
  109. }()
  110. })
  111. return err
  112. })
  113. r := &containerd.CreateContainerRequest{
  114. Id: ctr.containerID,
  115. BundlePath: ctr.dir,
  116. Stdin: ctr.fifo(syscall.Stdin),
  117. Stdout: ctr.fifo(syscall.Stdout),
  118. Stderr: ctr.fifo(syscall.Stderr),
  119. // check to see if we are running in ramdisk to disable pivot root
  120. NoPivotRoot: os.Getenv("DOCKER_RAMDISK") != "",
  121. Runtime: ctr.runtime,
  122. RuntimeArgs: ctr.runtimeArgs,
  123. }
  124. ctr.client.appendContainer(ctr)
  125. if err := ctr.client.backend.AttachStreams(ctr.containerID, *iopipe); err != nil {
  126. ctr.closeFifos(iopipe)
  127. return err
  128. }
  129. resp, err := ctr.client.remote.apiClient.CreateContainer(context.Background(), r)
  130. if err != nil {
  131. ctr.closeFifos(iopipe)
  132. return err
  133. }
  134. ctr.startedAt = time.Now()
  135. ctr.systemPid = systemPid(resp.Container)
  136. close(ready)
  137. return ctr.client.backend.StateChanged(ctr.containerID, StateInfo{
  138. CommonStateInfo: CommonStateInfo{
  139. State: StateStart,
  140. Pid: ctr.systemPid,
  141. }})
  142. }
  143. func (ctr *container) newProcess(friendlyName string) *process {
  144. return &process{
  145. dir: ctr.dir,
  146. processCommon: processCommon{
  147. containerID: ctr.containerID,
  148. friendlyName: friendlyName,
  149. client: ctr.client,
  150. },
  151. }
  152. }
  153. func (ctr *container) handleEvent(e *containerd.Event) error {
  154. ctr.client.lock(ctr.containerID)
  155. defer ctr.client.unlock(ctr.containerID)
  156. switch e.Type {
  157. case StateExit, StatePause, StateResume, StateOOM:
  158. var waitRestart chan error
  159. st := StateInfo{
  160. CommonStateInfo: CommonStateInfo{
  161. State: e.Type,
  162. ExitCode: e.Status,
  163. },
  164. OOMKilled: e.Type == StateExit && ctr.oom,
  165. }
  166. if e.Type == StateOOM {
  167. ctr.oom = true
  168. }
  169. if e.Type == StateExit && e.Pid != InitFriendlyName {
  170. st.ProcessID = e.Pid
  171. st.State = StateExitProcess
  172. }
  173. if st.State == StateExit && ctr.restartManager != nil {
  174. restart, wait, err := ctr.restartManager.ShouldRestart(e.Status, false, time.Since(ctr.startedAt))
  175. if err != nil {
  176. logrus.Warnf("libcontainerd: container %s %v", ctr.containerID, err)
  177. } else if restart {
  178. st.State = StateRestart
  179. ctr.restarting = true
  180. ctr.client.deleteContainer(e.Id)
  181. waitRestart = wait
  182. }
  183. }
  184. // Remove process from list if we have exited
  185. // We need to do so here in case the Message Handler decides to restart it.
  186. switch st.State {
  187. case StateExit:
  188. ctr.clean()
  189. ctr.client.deleteContainer(e.Id)
  190. case StateExitProcess:
  191. ctr.cleanProcess(st.ProcessID)
  192. }
  193. ctr.client.q.append(e.Id, func() {
  194. if err := ctr.client.backend.StateChanged(e.Id, st); err != nil {
  195. logrus.Errorf("libcontainerd: backend.StateChanged(): %v", err)
  196. }
  197. if st.State == StateRestart {
  198. go func() {
  199. err := <-waitRestart
  200. ctr.client.lock(ctr.containerID)
  201. defer ctr.client.unlock(ctr.containerID)
  202. ctr.restarting = false
  203. if err == nil {
  204. if err = ctr.start(); err != nil {
  205. logrus.Errorf("libcontainerd: error restarting %v", err)
  206. }
  207. }
  208. if err != nil {
  209. st.State = StateExit
  210. ctr.clean()
  211. ctr.client.q.append(e.Id, func() {
  212. if err := ctr.client.backend.StateChanged(e.Id, st); err != nil {
  213. logrus.Errorf("libcontainerd: %v", err)
  214. }
  215. })
  216. if err != restartmanager.ErrRestartCanceled {
  217. logrus.Errorf("libcontainerd: %v", err)
  218. }
  219. }
  220. }()
  221. }
  222. if e.Type == StatePause || e.Type == StateResume {
  223. ctr.pauseMonitor.handle(e.Type)
  224. }
  225. if e.Type == StateExit {
  226. if en := ctr.client.getExitNotifier(e.Id); en != nil {
  227. en.close()
  228. }
  229. }
  230. })
  231. default:
  232. logrus.Debugf("libcontainerd: event unhandled: %+v", e)
  233. }
  234. return nil
  235. }
  236. // discardFifos attempts to fully read the container fifos to unblock processes
  237. // that may be blocked on the writer side.
  238. func (ctr *container) discardFifos() {
  239. ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)
  240. for _, i := range []int{syscall.Stdout, syscall.Stderr} {
  241. f, err := fifo.OpenFifo(ctx, ctr.fifo(i), syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
  242. if err != nil {
  243. logrus.Warnf("error opening fifo %v for discarding: %+v", f, err)
  244. continue
  245. }
  246. go func() {
  247. io.Copy(ioutil.Discard, f)
  248. }()
  249. }
  250. }