monitor.go 8.9 KB

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