container_linux.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. st := StateInfo{
  130. CommonStateInfo: CommonStateInfo{
  131. State: e.Type,
  132. ExitCode: e.Status,
  133. },
  134. OOMKilled: e.Type == StateExit && ctr.oom,
  135. }
  136. if e.Type == StateOOM {
  137. ctr.oom = true
  138. }
  139. if e.Type == StateExit && e.Pid != InitFriendlyName {
  140. st.ProcessID = e.Pid
  141. st.State = StateExitProcess
  142. }
  143. if st.State == StateExit && ctr.restartManager != nil {
  144. restart, wait, err := ctr.restartManager.ShouldRestart(e.Status, false, time.Since(ctr.startedAt))
  145. if err != nil {
  146. logrus.Warnf("libcontainerd: container %s %v", ctr.containerID, err)
  147. } else if restart {
  148. st.State = StateRestart
  149. ctr.restarting = true
  150. ctr.client.deleteContainer(e.Id)
  151. go func() {
  152. err := <-wait
  153. ctr.client.lock(ctr.containerID)
  154. defer ctr.client.unlock(ctr.containerID)
  155. ctr.restarting = false
  156. if err != nil {
  157. st.State = StateExit
  158. ctr.clean()
  159. ctr.client.q.append(e.Id, func() {
  160. if err := ctr.client.backend.StateChanged(e.Id, st); err != nil {
  161. logrus.Errorf("libcontainerd: %v", err)
  162. }
  163. })
  164. if err != restartmanager.ErrRestartCanceled {
  165. logrus.Errorf("libcontainerd: %v", err)
  166. }
  167. } else {
  168. ctr.start()
  169. }
  170. }()
  171. }
  172. }
  173. // Remove process from list if we have exited
  174. // We need to do so here in case the Message Handler decides to restart it.
  175. switch st.State {
  176. case StateExit:
  177. ctr.clean()
  178. ctr.client.deleteContainer(e.Id)
  179. case StateExitProcess:
  180. ctr.cleanProcess(st.ProcessID)
  181. }
  182. ctr.client.q.append(e.Id, func() {
  183. if err := ctr.client.backend.StateChanged(e.Id, st); err != nil {
  184. logrus.Errorf("libcontainerd: backend.StateChanged(): %v", err)
  185. }
  186. if e.Type == StatePause || e.Type == StateResume {
  187. ctr.pauseMonitor.handle(e.Type)
  188. }
  189. if e.Type == StateExit {
  190. if en := ctr.client.getExitNotifier(e.Id); en != nil {
  191. en.close()
  192. }
  193. }
  194. })
  195. default:
  196. logrus.Debugf("libcontainerd: event unhandled: %+v", e)
  197. }
  198. return nil
  199. }
  200. // discardFifos attempts to fully read the container fifos to unblock processes
  201. // that may be blocked on the writer side.
  202. func (ctr *container) discardFifos() {
  203. for _, i := range []int{syscall.Stdout, syscall.Stderr} {
  204. f := ctr.fifo(i)
  205. c := make(chan struct{})
  206. go func() {
  207. r := openReaderFromFifo(f)
  208. close(c) // this channel is used to not close the writer too early, before readonly open has been called.
  209. io.Copy(ioutil.Discard, r)
  210. }()
  211. <-c
  212. closeReaderFifo(f) // avoid blocking permanently on open if there is no writer side
  213. }
  214. }