monitor.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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/pkg/common"
  10. "github.com/docker/docker/runconfig"
  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.startLogging(); 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. return err
  135. }
  136. continue
  137. }
  138. if exitStatus.OOMKilled {
  139. m.container.LogEvent("oom")
  140. }
  141. m.container.LogEvent("die")
  142. m.resetContainer(true)
  143. return err
  144. }
  145. }
  146. // resetMonitor resets the stateful fields on the containerMonitor based on the
  147. // previous runs success or failure. Regardless of success, if the container had
  148. // an execution time of more than 10s then reset the timer back to the default
  149. func (m *containerMonitor) resetMonitor(successful bool) {
  150. executionTime := time.Now().Sub(m.lastStartTime).Seconds()
  151. if executionTime > 10 {
  152. m.timeIncrement = defaultTimeIncrement
  153. } else {
  154. // otherwise we need to increment the amount of time we wait before restarting
  155. // the process. We will build up by multiplying the increment by 2
  156. m.timeIncrement *= 2
  157. }
  158. // the container exited successfully so we need to reset the failure counter
  159. if successful {
  160. m.failureCount = 0
  161. } else {
  162. m.failureCount++
  163. }
  164. }
  165. // waitForNextRestart waits with the default time increment to restart the container unless
  166. // a user or docker asks for the container to be stopped
  167. func (m *containerMonitor) waitForNextRestart() {
  168. select {
  169. case <-time.After(time.Duration(m.timeIncrement) * time.Millisecond):
  170. case <-m.stopChan:
  171. }
  172. }
  173. // shouldRestart checks the restart policy and applies the rules to determine if
  174. // the container's process should be restarted
  175. func (m *containerMonitor) shouldRestart(exitCode int) bool {
  176. m.mux.Lock()
  177. defer m.mux.Unlock()
  178. // do not restart if the user or docker has requested that this container be stopped
  179. if m.shouldStop {
  180. return false
  181. }
  182. switch m.restartPolicy.Name {
  183. case "always":
  184. return true
  185. case "on-failure":
  186. // the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count
  187. if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount > max {
  188. log.Debugf("stopping restart of container %s because maximum failure could of %d has been reached",
  189. common.TruncateID(m.container.ID), max)
  190. return false
  191. }
  192. return exitCode != 0
  193. }
  194. return false
  195. }
  196. // callback ensures that the container's state is properly updated after we
  197. // received ack from the execution drivers
  198. func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid int) {
  199. if processConfig.Tty {
  200. // The callback is called after the process Start()
  201. // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
  202. // which we close here.
  203. if c, ok := processConfig.Stdout.(io.Closer); ok {
  204. c.Close()
  205. }
  206. }
  207. m.container.setRunning(pid)
  208. // signal that the process has started
  209. // close channel only if not closed
  210. select {
  211. case <-m.startSignal:
  212. default:
  213. close(m.startSignal)
  214. }
  215. if err := m.container.ToDisk(); err != nil {
  216. log.Debugf("%s", err)
  217. }
  218. }
  219. // resetContainer resets the container's IO and ensures that the command is able to be executed again
  220. // by copying the data into a new struct
  221. // if lock is true, then container locked during reset
  222. func (m *containerMonitor) resetContainer(lock bool) {
  223. container := m.container
  224. if lock {
  225. container.Lock()
  226. defer container.Unlock()
  227. }
  228. if container.Config.OpenStdin {
  229. if err := container.stdin.Close(); err != nil {
  230. log.Errorf("%s: Error close stdin: %s", container.ID, err)
  231. }
  232. }
  233. if err := container.stdout.Clean(); err != nil {
  234. log.Errorf("%s: Error close stdout: %s", container.ID, err)
  235. }
  236. if err := container.stderr.Clean(); err != nil {
  237. log.Errorf("%s: Error close stderr: %s", container.ID, err)
  238. }
  239. if container.command != nil && container.command.ProcessConfig.Terminal != nil {
  240. if err := container.command.ProcessConfig.Terminal.Close(); err != nil {
  241. log.Errorf("%s: Error closing terminal: %s", container.ID, err)
  242. }
  243. }
  244. // Re-create a brand new stdin pipe once the container exited
  245. if container.Config.OpenStdin {
  246. container.stdin, container.stdinPipe = io.Pipe()
  247. }
  248. if container.logDriver != nil {
  249. if container.logCopier != nil {
  250. exit := make(chan struct{})
  251. go func() {
  252. container.logCopier.Wait()
  253. close(exit)
  254. }()
  255. select {
  256. case <-time.After(1 * time.Second):
  257. log.Warnf("Logger didn't exit in time: logs may be truncated")
  258. case <-exit:
  259. }
  260. }
  261. container.logDriver.Close()
  262. container.logCopier = nil
  263. container.logDriver = nil
  264. }
  265. c := container.command.ProcessConfig.Cmd
  266. container.command.ProcessConfig.Cmd = exec.Cmd{
  267. Stdin: c.Stdin,
  268. Stdout: c.Stdout,
  269. Stderr: c.Stderr,
  270. Path: c.Path,
  271. Env: c.Env,
  272. ExtraFiles: c.ExtraFiles,
  273. Args: c.Args,
  274. Dir: c.Dir,
  275. SysProcAttr: c.SysProcAttr,
  276. }
  277. }