container_unix.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // +build linux solaris
  2. package libcontainerd
  3. import (
  4. "encoding/json"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "sync"
  10. "syscall"
  11. "time"
  12. "github.com/Sirupsen/logrus"
  13. containerd "github.com/containerd/containerd/api/grpc/types"
  14. "github.com/docker/docker/pkg/ioutils"
  15. specs "github.com/opencontainers/runtime-spec/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 && !os.IsNotExist(err) {
  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(checkpoint string, checkpointDir string, attachStdio StdioCallback) (err 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. fifoCtx, cancel := context.WithCancel(context.Background())
  89. defer func() {
  90. if err != nil {
  91. cancel()
  92. }
  93. }()
  94. iopipe, err := ctr.openFifos(fifoCtx, spec.Process.Terminal)
  95. if err != nil {
  96. return err
  97. }
  98. var stdinOnce sync.Once
  99. // we need to delay stdin closure after container start or else "stdin close"
  100. // event will be rejected by containerd.
  101. // stdin closure happens in attachStdio
  102. stdin := iopipe.Stdin
  103. iopipe.Stdin = ioutils.NewWriteCloserWrapper(stdin, func() error {
  104. var err error
  105. stdinOnce.Do(func() { // on error from attach we don't know if stdin was already closed
  106. err = stdin.Close()
  107. go func() {
  108. select {
  109. case <-ready:
  110. case <-ctx.Done():
  111. }
  112. select {
  113. case <-ready:
  114. if err := ctr.sendCloseStdin(); err != nil {
  115. logrus.Warnf("failed to close stdin: %+v", err)
  116. }
  117. default:
  118. }
  119. }()
  120. })
  121. return err
  122. })
  123. r := &containerd.CreateContainerRequest{
  124. Id: ctr.containerID,
  125. BundlePath: ctr.dir,
  126. Stdin: ctr.fifo(syscall.Stdin),
  127. Stdout: ctr.fifo(syscall.Stdout),
  128. Stderr: ctr.fifo(syscall.Stderr),
  129. Checkpoint: checkpoint,
  130. CheckpointDir: checkpointDir,
  131. // check to see if we are running in ramdisk to disable pivot root
  132. NoPivotRoot: os.Getenv("DOCKER_RAMDISK") != "",
  133. Runtime: ctr.runtime,
  134. RuntimeArgs: ctr.runtimeArgs,
  135. }
  136. ctr.client.appendContainer(ctr)
  137. if err := attachStdio(*iopipe); err != nil {
  138. ctr.closeFifos(iopipe)
  139. return err
  140. }
  141. resp, err := ctr.client.remote.apiClient.CreateContainer(context.Background(), r)
  142. if err != nil {
  143. ctr.closeFifos(iopipe)
  144. return err
  145. }
  146. ctr.systemPid = systemPid(resp.Container)
  147. close(ready)
  148. return ctr.client.backend.StateChanged(ctr.containerID, StateInfo{
  149. CommonStateInfo: CommonStateInfo{
  150. State: StateStart,
  151. Pid: ctr.systemPid,
  152. }})
  153. }
  154. func (ctr *container) newProcess(friendlyName string) *process {
  155. return &process{
  156. dir: ctr.dir,
  157. processCommon: processCommon{
  158. containerID: ctr.containerID,
  159. friendlyName: friendlyName,
  160. client: ctr.client,
  161. },
  162. }
  163. }
  164. func (ctr *container) handleEvent(e *containerd.Event) error {
  165. ctr.client.lock(ctr.containerID)
  166. defer ctr.client.unlock(ctr.containerID)
  167. switch e.Type {
  168. case StateExit, StatePause, StateResume, StateOOM:
  169. st := StateInfo{
  170. CommonStateInfo: CommonStateInfo{
  171. State: e.Type,
  172. ExitCode: e.Status,
  173. },
  174. OOMKilled: e.Type == StateExit && ctr.oom,
  175. }
  176. if e.Type == StateOOM {
  177. ctr.oom = true
  178. }
  179. if e.Type == StateExit && e.Pid != InitFriendlyName {
  180. st.ProcessID = e.Pid
  181. st.State = StateExitProcess
  182. }
  183. // Remove process from list if we have exited
  184. switch st.State {
  185. case StateExit:
  186. ctr.clean()
  187. ctr.client.deleteContainer(e.Id)
  188. case StateExitProcess:
  189. ctr.cleanProcess(st.ProcessID)
  190. }
  191. ctr.client.q.append(e.Id, func() {
  192. if err := ctr.client.backend.StateChanged(e.Id, st); err != nil {
  193. logrus.Errorf("libcontainerd: backend.StateChanged(): %v", err)
  194. }
  195. if e.Type == StatePause || e.Type == StateResume {
  196. ctr.pauseMonitor.handle(e.Type)
  197. }
  198. if e.Type == StateExit {
  199. if en := ctr.client.getExitNotifier(e.Id); en != nil {
  200. en.close()
  201. }
  202. }
  203. })
  204. default:
  205. logrus.Debugf("libcontainerd: event unhandled: %+v", e)
  206. }
  207. return nil
  208. }
  209. // discardFifos attempts to fully read the container fifos to unblock processes
  210. // that may be blocked on the writer side.
  211. func (ctr *container) discardFifos() {
  212. ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)
  213. for _, i := range []int{syscall.Stdout, syscall.Stderr} {
  214. f, err := fifo.OpenFifo(ctx, ctr.fifo(i), syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
  215. if err != nil {
  216. logrus.Warnf("error opening fifo %v for discarding: %+v", f, err)
  217. continue
  218. }
  219. go func() {
  220. io.Copy(ioutil.Discard, f)
  221. }()
  222. }
  223. }