container_linux.go 6.0 KB

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