monitor.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "github.com/containerd/containerd/log"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/container"
  9. "github.com/docker/docker/daemon/config"
  10. "github.com/docker/docker/errdefs"
  11. libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
  12. "github.com/docker/docker/restartmanager"
  13. "github.com/pkg/errors"
  14. )
  15. func (daemon *Daemon) setStateCounter(c *container.Container) {
  16. switch c.StateString() {
  17. case "paused":
  18. stateCtr.set(c.ID, "paused")
  19. case "running":
  20. stateCtr.set(c.ID, "running")
  21. default:
  22. stateCtr.set(c.ID, "stopped")
  23. }
  24. }
  25. func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontainerdtypes.EventInfo) error {
  26. var exitStatus container.ExitStatus
  27. c.Lock()
  28. cfg := daemon.config()
  29. // Health checks will be automatically restarted if/when the
  30. // container is started again.
  31. daemon.stopHealthchecks(c)
  32. tsk, ok := c.Task()
  33. if ok {
  34. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  35. es, err := tsk.Delete(ctx)
  36. cancel()
  37. if err != nil {
  38. log.G(ctx).WithFields(log.Fields{
  39. "error": err,
  40. "container": c.ID,
  41. }).Warn("failed to delete container from containerd")
  42. } else {
  43. exitStatus = container.ExitStatus{
  44. ExitCode: int(es.ExitCode()),
  45. ExitedAt: es.ExitTime(),
  46. }
  47. }
  48. }
  49. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  50. c.StreamConfig.Wait(ctx)
  51. cancel()
  52. c.Reset(false)
  53. if e != nil {
  54. exitStatus.ExitCode = int(e.ExitCode)
  55. exitStatus.ExitedAt = e.ExitedAt
  56. if e.Error != nil {
  57. c.SetError(e.Error)
  58. }
  59. }
  60. daemonShutdown := daemon.IsShuttingDown()
  61. execDuration := time.Since(c.StartedAt)
  62. restart, wait, err := c.RestartManager().ShouldRestart(uint32(exitStatus.ExitCode), daemonShutdown || c.HasBeenManuallyStopped, execDuration)
  63. if err != nil {
  64. log.G(ctx).WithFields(log.Fields{
  65. "error": err,
  66. "container": c.ID,
  67. "restartCount": c.RestartCount,
  68. "exitStatus": exitStatus,
  69. "daemonShuttingDown": daemonShutdown,
  70. "hasBeenManuallyStopped": c.HasBeenManuallyStopped,
  71. "execDuration": execDuration,
  72. }).Warn("ShouldRestart failed, container will not be restarted")
  73. restart = false
  74. }
  75. attributes := map[string]string{
  76. "exitCode": strconv.Itoa(exitStatus.ExitCode),
  77. "execDuration": strconv.Itoa(int(execDuration.Seconds())),
  78. }
  79. daemon.Cleanup(c)
  80. if restart {
  81. c.RestartCount++
  82. log.G(ctx).WithFields(log.Fields{
  83. "container": c.ID,
  84. "restartCount": c.RestartCount,
  85. "exitStatus": exitStatus,
  86. "manualRestart": c.HasBeenManuallyRestarted,
  87. }).Debug("Restarting container")
  88. c.SetRestarting(&exitStatus)
  89. } else {
  90. c.SetStopped(&exitStatus)
  91. if !c.HasBeenManuallyRestarted {
  92. defer daemon.autoRemove(&cfg.Config, c)
  93. }
  94. }
  95. defer c.Unlock() // needs to be called before autoRemove
  96. daemon.setStateCounter(c)
  97. checkpointErr := c.CheckpointTo(daemon.containersReplica)
  98. daemon.LogContainerEventWithAttributes(c, "die", attributes)
  99. if restart {
  100. go func() {
  101. err := <-wait
  102. if err == nil {
  103. // daemon.netController is initialized when daemon is restoring containers.
  104. // But containerStart will use daemon.netController segment.
  105. // So to avoid panic at startup process, here must wait util daemon restore done.
  106. daemon.waitForStartupDone()
  107. cfg := daemon.config() // Apply the most up-to-date daemon config to the restarted container.
  108. // update the error if we fail to start the container, so that the cleanup code
  109. // below can handle updating the container's status, and auto-remove (if set).
  110. err = daemon.containerStart(context.Background(), cfg, c, "", "", false)
  111. if err != nil {
  112. log.G(ctx).Debugf("failed to restart container: %+v", err)
  113. }
  114. }
  115. if err != nil {
  116. c.Lock()
  117. c.SetStopped(&exitStatus)
  118. daemon.setStateCounter(c)
  119. c.CheckpointTo(daemon.containersReplica)
  120. c.Unlock()
  121. defer daemon.autoRemove(&cfg.Config, c)
  122. if err != restartmanager.ErrRestartCanceled {
  123. log.G(ctx).Errorf("restartmanger wait error: %+v", err)
  124. }
  125. }
  126. }()
  127. }
  128. return checkpointErr
  129. }
  130. // ProcessEvent is called by libcontainerd whenever an event occurs
  131. func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
  132. c, err := daemon.GetContainer(id)
  133. if err != nil {
  134. return errors.Wrapf(err, "could not find container %s", id)
  135. }
  136. switch e {
  137. case libcontainerdtypes.EventOOM:
  138. // StateOOM is Linux specific and should never be hit on Windows
  139. if isWindows {
  140. return errors.New("received StateOOM from libcontainerd on Windows. This should never happen")
  141. }
  142. c.Lock()
  143. defer c.Unlock()
  144. c.OOMKilled = true
  145. daemon.updateHealthMonitor(c)
  146. if err := c.CheckpointTo(daemon.containersReplica); err != nil {
  147. return err
  148. }
  149. daemon.LogContainerEvent(c, "oom")
  150. case libcontainerdtypes.EventExit:
  151. if ei.ProcessID == ei.ContainerID {
  152. return daemon.handleContainerExit(c, &ei)
  153. }
  154. exitCode := 127
  155. if execConfig := c.ExecCommands.Get(ei.ProcessID); execConfig != nil {
  156. ec := int(ei.ExitCode)
  157. execConfig.Lock()
  158. defer execConfig.Unlock()
  159. // Remove the exec command from the container's store only and not the
  160. // daemon's store so that the exec command can be inspected. Remove it
  161. // before mutating execConfig to maintain the invariant that
  162. // c.ExecCommands only contains execs that have not exited.
  163. c.ExecCommands.Delete(execConfig.ID)
  164. execConfig.ExitCode = &ec
  165. execConfig.Running = false
  166. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  167. execConfig.StreamConfig.Wait(ctx)
  168. cancel()
  169. if err := execConfig.CloseStreams(); err != nil {
  170. log.G(ctx).Errorf("failed to cleanup exec %s streams: %s", c.ID, err)
  171. }
  172. exitCode = ec
  173. // If the exec failed at start in such a way that containerd
  174. // publishes an exit event for it, we will race processing the event
  175. // with daemon.ContainerExecStart() removing the exec from
  176. // c.ExecCommands. If we win the race, we will find that there is no
  177. // process to clean up. (And ContainerExecStart will clobber the
  178. // exit code we set.) Prevent a nil-dereferenc panic in that
  179. // situation to restore the status quo where this is merely a
  180. // logical race condition.
  181. if execConfig.Process != nil {
  182. go func() {
  183. if _, err := execConfig.Process.Delete(context.Background()); err != nil {
  184. log.G(ctx).WithFields(log.Fields{
  185. "error": err,
  186. "container": ei.ContainerID,
  187. "process": ei.ProcessID,
  188. }).Warn("failed to delete process")
  189. }
  190. }()
  191. }
  192. }
  193. daemon.LogContainerEventWithAttributes(c, "exec_die", map[string]string{
  194. "execID": ei.ProcessID,
  195. "exitCode": strconv.Itoa(exitCode),
  196. })
  197. case libcontainerdtypes.EventStart:
  198. c.Lock()
  199. defer c.Unlock()
  200. // This is here to handle start not generated by docker
  201. if !c.Running {
  202. ctr, err := daemon.containerd.LoadContainer(context.Background(), c.ID)
  203. if err != nil {
  204. if errdefs.IsNotFound(err) {
  205. // The container was started by not-docker and so could have been deleted by
  206. // not-docker before we got around to loading it from containerd.
  207. log.G(context.TODO()).WithFields(log.Fields{
  208. "error": err,
  209. "container": c.ID,
  210. }).Debug("could not load containerd container for start event")
  211. return nil
  212. }
  213. return err
  214. }
  215. tsk, err := ctr.Task(context.Background())
  216. if err != nil {
  217. if errdefs.IsNotFound(err) {
  218. log.G(context.TODO()).WithFields(log.Fields{
  219. "error": err,
  220. "container": c.ID,
  221. }).Debug("failed to load task for externally-started container")
  222. return nil
  223. }
  224. return err
  225. }
  226. c.SetRunning(ctr, tsk, false)
  227. c.HasBeenManuallyStopped = false
  228. c.HasBeenStartedBefore = true
  229. daemon.setStateCounter(c)
  230. daemon.initHealthMonitor(c)
  231. if err := c.CheckpointTo(daemon.containersReplica); err != nil {
  232. return err
  233. }
  234. daemon.LogContainerEvent(c, "start")
  235. }
  236. case libcontainerdtypes.EventPaused:
  237. c.Lock()
  238. defer c.Unlock()
  239. if !c.Paused {
  240. c.Paused = true
  241. daemon.setStateCounter(c)
  242. daemon.updateHealthMonitor(c)
  243. if err := c.CheckpointTo(daemon.containersReplica); err != nil {
  244. return err
  245. }
  246. daemon.LogContainerEvent(c, "pause")
  247. }
  248. case libcontainerdtypes.EventResumed:
  249. c.Lock()
  250. defer c.Unlock()
  251. if c.Paused {
  252. c.Paused = false
  253. daemon.setStateCounter(c)
  254. daemon.updateHealthMonitor(c)
  255. if err := c.CheckpointTo(daemon.containersReplica); err != nil {
  256. return err
  257. }
  258. daemon.LogContainerEvent(c, "unpause")
  259. }
  260. }
  261. return nil
  262. }
  263. func (daemon *Daemon) autoRemove(cfg *config.Config, c *container.Container) {
  264. c.Lock()
  265. ar := c.HostConfig.AutoRemove
  266. c.Unlock()
  267. if !ar {
  268. return
  269. }
  270. err := daemon.containerRm(cfg, c.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true})
  271. if err == nil {
  272. return
  273. }
  274. if c := daemon.containers.Get(c.ID); c == nil {
  275. return
  276. }
  277. log.G(context.TODO()).WithFields(log.Fields{"error": err, "container": c.ID}).Error("error removing container")
  278. }