monitor.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package daemon
  2. import (
  3. "io"
  4. "os/exec"
  5. "sync"
  6. "time"
  7. log "github.com/Sirupsen/logrus"
  8. "github.com/docker/docker/daemon/execdriver"
  9. "github.com/docker/docker/runconfig"
  10. "github.com/docker/docker/utils"
  11. )
  12. const defaultTimeIncrement = 100
  13. // containerMonitor monitors the execution of a container's main process.
  14. // If a restart policy is specified for the container the monitor will ensure that the
  15. // process is restarted based on the rules of the policy. When the container is finally stopped
  16. // the monitor will reset and cleanup any of the container resources such as networking allocations
  17. // and the rootfs
  18. type containerMonitor struct {
  19. mux sync.Mutex
  20. // container is the container being monitored
  21. container *Container
  22. // restartPolicy is the current policy being applied to the container monitor
  23. restartPolicy runconfig.RestartPolicy
  24. // failureCount is the number of times the container has failed to
  25. // start in a row
  26. failureCount int
  27. // shouldStop signals the monitor that the next time the container exits it is
  28. // either because docker or the user asked for the container to be stopped
  29. shouldStop bool
  30. // startSignal is a channel that is closes after the container initially starts
  31. startSignal chan struct{}
  32. // stopChan is used to signal to the monitor whenever there is a wait for the
  33. // next restart so that the timeIncrement is not honored and the user is not
  34. // left waiting for nothing to happen during this time
  35. stopChan chan struct{}
  36. // timeIncrement is the amount of time to wait between restarts
  37. // this is in milliseconds
  38. timeIncrement int
  39. // lastStartTime is the time which the monitor last exec'd the container's process
  40. lastStartTime time.Time
  41. }
  42. // newContainerMonitor returns an initialized containerMonitor for the provided container
  43. // honoring the provided restart policy
  44. func newContainerMonitor(container *Container, policy runconfig.RestartPolicy) *containerMonitor {
  45. return &containerMonitor{
  46. container: container,
  47. restartPolicy: policy,
  48. timeIncrement: defaultTimeIncrement,
  49. stopChan: make(chan struct{}),
  50. startSignal: make(chan struct{}),
  51. }
  52. }
  53. // Stop signals to the container monitor that it should stop monitoring the container
  54. // for exits the next time the process dies
  55. func (m *containerMonitor) ExitOnNext() {
  56. m.mux.Lock()
  57. // we need to protect having a double close of the channel when stop is called
  58. // twice or else we will get a panic
  59. if !m.shouldStop {
  60. m.shouldStop = true
  61. close(m.stopChan)
  62. }
  63. m.mux.Unlock()
  64. }
  65. // Close closes the container's resources such as networking allocations and
  66. // unmounts the contatiner's root filesystem
  67. func (m *containerMonitor) Close() error {
  68. // Cleanup networking and mounts
  69. m.container.cleanup()
  70. // FIXME: here is race condition between two RUN instructions in Dockerfile
  71. // because they share same runconfig and change image. Must be fixed
  72. // in builder/builder.go
  73. if err := m.container.toDisk(); err != nil {
  74. log.Errorf("Error dumping container %s state to disk: %s", m.container.ID, err)
  75. return err
  76. }
  77. return nil
  78. }
  79. // Start starts the containers process and monitors it according to the restart policy
  80. func (m *containerMonitor) Start() error {
  81. var (
  82. err error
  83. exitStatus execdriver.ExitStatus
  84. // this variable indicates where we in execution flow:
  85. // before Run or after
  86. afterRun bool
  87. )
  88. // ensure that when the monitor finally exits we release the networking and unmount the rootfs
  89. defer func() {
  90. if afterRun {
  91. m.container.Lock()
  92. m.container.setStopped(&exitStatus)
  93. defer m.container.Unlock()
  94. }
  95. m.Close()
  96. }()
  97. // reset the restart count
  98. m.container.RestartCount = -1
  99. for {
  100. m.container.RestartCount++
  101. if err := m.container.startLoggingToDisk(); err != nil {
  102. m.resetContainer(false)
  103. return err
  104. }
  105. pipes := execdriver.NewPipes(m.container.stdin, m.container.stdout, m.container.stderr, m.container.Config.OpenStdin)
  106. m.container.LogEvent("start")
  107. m.lastStartTime = time.Now()
  108. if exitStatus, err = m.container.daemon.Run(m.container, pipes, m.callback); err != nil {
  109. // if we receive an internal error from the initial start of a container then lets
  110. // return it instead of entering the restart loop
  111. if m.container.RestartCount == 0 {
  112. m.container.ExitCode = -1
  113. m.resetContainer(false)
  114. return err
  115. }
  116. log.Errorf("Error running container: %s", err)
  117. }
  118. // here container.Lock is already lost
  119. afterRun = true
  120. m.resetMonitor(err == nil && exitStatus.ExitCode == 0)
  121. if m.shouldRestart(exitStatus.ExitCode) {
  122. m.container.SetRestarting(&exitStatus)
  123. if exitStatus.OOMKilled {
  124. m.container.LogEvent("oom")
  125. }
  126. m.container.LogEvent("die")
  127. m.resetContainer(true)
  128. // sleep with a small time increment between each restart to help avoid issues cased by quickly
  129. // restarting the container because of some types of errors ( networking cut out, etc... )
  130. m.waitForNextRestart()
  131. // we need to check this before reentering the loop because the waitForNextRestart could have
  132. // been terminated by a request from a user
  133. if m.shouldStop {
  134. m.container.ExitCode = exitStatus.ExitCode
  135. return err
  136. }
  137. continue
  138. }
  139. m.container.ExitCode = exitStatus.ExitCode
  140. if exitStatus.OOMKilled {
  141. m.container.LogEvent("oom")
  142. }
  143. m.container.LogEvent("die")
  144. m.resetContainer(true)
  145. return err
  146. }
  147. }
  148. // resetMonitor resets the stateful fields on the containerMonitor based on the
  149. // previous runs success or failure. Reguardless of success, if the container had
  150. // an execution time of more than 10s then reset the timer back to the default
  151. func (m *containerMonitor) resetMonitor(successful bool) {
  152. executionTime := time.Now().Sub(m.lastStartTime).Seconds()
  153. if executionTime > 10 {
  154. m.timeIncrement = defaultTimeIncrement
  155. } else {
  156. // otherwise we need to increment the amount of time we wait before restarting
  157. // the process. We will build up by multiplying the increment by 2
  158. m.timeIncrement *= 2
  159. }
  160. // the container exited successfully so we need to reset the failure counter
  161. if successful {
  162. m.failureCount = 0
  163. } else {
  164. m.failureCount++
  165. }
  166. }
  167. // waitForNextRestart waits with the default time increment to restart the container unless
  168. // a user or docker asks for the container to be stopped
  169. func (m *containerMonitor) waitForNextRestart() {
  170. select {
  171. case <-time.After(time.Duration(m.timeIncrement) * time.Millisecond):
  172. case <-m.stopChan:
  173. }
  174. }
  175. // shouldRestart checks the restart policy and applies the rules to determine if
  176. // the container's process should be restarted
  177. func (m *containerMonitor) shouldRestart(exitCode int) bool {
  178. m.mux.Lock()
  179. defer m.mux.Unlock()
  180. // do not restart if the user or docker has requested that this container be stopped
  181. if m.shouldStop {
  182. return false
  183. }
  184. switch m.restartPolicy.Name {
  185. case "always":
  186. return true
  187. case "on-failure":
  188. // the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count
  189. if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount > max {
  190. log.Debugf("stopping restart of container %s because maximum failure could of %d has been reached",
  191. utils.TruncateID(m.container.ID), max)
  192. return false
  193. }
  194. return exitCode != 0
  195. }
  196. return false
  197. }
  198. // callback ensures that the container's state is properly updated after we
  199. // received ack from the execution drivers
  200. func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid int) {
  201. if processConfig.Tty {
  202. // The callback is called after the process Start()
  203. // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
  204. // which we close here.
  205. if c, ok := processConfig.Stdout.(io.Closer); ok {
  206. c.Close()
  207. }
  208. }
  209. m.container.setRunning(pid)
  210. // signal that the process has started
  211. // close channel only if not closed
  212. select {
  213. case <-m.startSignal:
  214. default:
  215. close(m.startSignal)
  216. }
  217. if err := m.container.ToDisk(); err != nil {
  218. log.Debugf("%s", err)
  219. }
  220. }
  221. // resetContainer resets the container's IO and ensures that the command is able to be executed again
  222. // by copying the data into a new struct
  223. // if lock is true, then container locked during reset
  224. func (m *containerMonitor) resetContainer(lock bool) {
  225. container := m.container
  226. if lock {
  227. container.Lock()
  228. defer container.Unlock()
  229. }
  230. if container.Config.OpenStdin {
  231. if err := container.stdin.Close(); err != nil {
  232. log.Errorf("%s: Error close stdin: %s", container.ID, err)
  233. }
  234. }
  235. if err := container.stdout.Clean(); err != nil {
  236. log.Errorf("%s: Error close stdout: %s", container.ID, err)
  237. }
  238. if err := container.stderr.Clean(); err != nil {
  239. log.Errorf("%s: Error close stderr: %s", container.ID, err)
  240. }
  241. if container.command != nil && container.command.ProcessConfig.Terminal != nil {
  242. if err := container.command.ProcessConfig.Terminal.Close(); err != nil {
  243. log.Errorf("%s: Error closing terminal: %s", container.ID, err)
  244. }
  245. }
  246. // Re-create a brand new stdin pipe once the container exited
  247. if container.Config.OpenStdin {
  248. container.stdin, container.stdinPipe = io.Pipe()
  249. }
  250. c := container.command.ProcessConfig.Cmd
  251. container.command.ProcessConfig.Cmd = exec.Cmd{
  252. Stdin: c.Stdin,
  253. Stdout: c.Stdout,
  254. Stderr: c.Stderr,
  255. Path: c.Path,
  256. Env: c.Env,
  257. ExtraFiles: c.ExtraFiles,
  258. Args: c.Args,
  259. Dir: c.Dir,
  260. SysProcAttr: c.SysProcAttr,
  261. }
  262. }