health.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "runtime"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/strslice"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/exec"
  14. "github.com/sirupsen/logrus"
  15. )
  16. const (
  17. // Longest healthcheck probe output message to store. Longer messages will be truncated.
  18. maxOutputLen = 4096
  19. // Default interval between probe runs (from the end of the first to the start of the second).
  20. // Also the time before the first probe.
  21. defaultProbeInterval = 30 * time.Second
  22. // The maximum length of time a single probe run should take. If the probe takes longer
  23. // than this, the check is considered to have failed.
  24. defaultProbeTimeout = 30 * time.Second
  25. // The time given for the container to start before the health check starts considering
  26. // the container unstable. Defaults to none.
  27. defaultStartPeriod = 0 * time.Second
  28. // Default number of consecutive failures of the health check
  29. // for the container to be considered unhealthy.
  30. defaultProbeRetries = 3
  31. // Maximum number of entries to record
  32. maxLogEntries = 5
  33. )
  34. const (
  35. // Exit status codes that can be returned by the probe command.
  36. exitStatusHealthy = 0 // Container is healthy
  37. )
  38. // probe implementations know how to run a particular type of probe.
  39. type probe interface {
  40. // Perform one run of the check. Returns the exit code and an optional
  41. // short diagnostic string.
  42. run(context.Context, *Daemon, *container.Container) (*types.HealthcheckResult, error)
  43. }
  44. // cmdProbe implements the "CMD" probe type.
  45. type cmdProbe struct {
  46. // Run the command with the system's default shell instead of execing it directly.
  47. shell bool
  48. }
  49. // exec the healthcheck command in the container.
  50. // Returns the exit code and probe output (if any)
  51. func (p *cmdProbe) run(ctx context.Context, d *Daemon, cntr *container.Container) (*types.HealthcheckResult, error) {
  52. cmdSlice := strslice.StrSlice(cntr.Config.Healthcheck.Test)[1:]
  53. if p.shell {
  54. cmdSlice = append(getShell(cntr), cmdSlice...)
  55. }
  56. entrypoint, args := d.getEntrypointAndArgs(strslice.StrSlice{}, cmdSlice)
  57. execConfig := exec.NewConfig()
  58. execConfig.OpenStdin = false
  59. execConfig.OpenStdout = true
  60. execConfig.OpenStderr = true
  61. execConfig.ContainerID = cntr.ID
  62. execConfig.DetachKeys = []byte{}
  63. execConfig.Entrypoint = entrypoint
  64. execConfig.Args = args
  65. execConfig.Tty = false
  66. execConfig.Privileged = false
  67. execConfig.User = cntr.Config.User
  68. execConfig.WorkingDir = cntr.Config.WorkingDir
  69. linkedEnv, err := d.setupLinkedContainers(cntr)
  70. if err != nil {
  71. return nil, err
  72. }
  73. execConfig.Env = container.ReplaceOrAppendEnvValues(cntr.CreateDaemonEnvironment(execConfig.Tty, linkedEnv), execConfig.Env)
  74. d.registerExecCommand(cntr, execConfig)
  75. attributes := map[string]string{
  76. "execID": execConfig.ID,
  77. }
  78. d.LogContainerEventWithAttributes(cntr, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "), attributes)
  79. output := &limitedBuffer{}
  80. err = d.ContainerExecStart(ctx, execConfig.ID, nil, output, output)
  81. if err != nil {
  82. return nil, err
  83. }
  84. info, err := d.getExecConfig(execConfig.ID)
  85. if err != nil {
  86. return nil, err
  87. }
  88. if info.ExitCode == nil {
  89. return nil, fmt.Errorf("healthcheck for container %s has no exit code", cntr.ID)
  90. }
  91. // Note: Go's json package will handle invalid UTF-8 for us
  92. out := output.String()
  93. return &types.HealthcheckResult{
  94. End: time.Now(),
  95. ExitCode: *info.ExitCode,
  96. Output: out,
  97. }, nil
  98. }
  99. // Update the container's Status.Health struct based on the latest probe's result.
  100. func handleProbeResult(d *Daemon, c *container.Container, result *types.HealthcheckResult, done chan struct{}) {
  101. c.Lock()
  102. defer c.Unlock()
  103. // probe may have been cancelled while waiting on lock. Ignore result then
  104. select {
  105. case <-done:
  106. return
  107. default:
  108. }
  109. retries := c.Config.Healthcheck.Retries
  110. if retries <= 0 {
  111. retries = defaultProbeRetries
  112. }
  113. h := c.State.Health
  114. oldStatus := h.Status()
  115. if len(h.Log) >= maxLogEntries {
  116. h.Log = append(h.Log[len(h.Log)+1-maxLogEntries:], result)
  117. } else {
  118. h.Log = append(h.Log, result)
  119. }
  120. if result.ExitCode == exitStatusHealthy {
  121. h.FailingStreak = 0
  122. h.SetStatus(types.Healthy)
  123. } else { // Failure (including invalid exit code)
  124. shouldIncrementStreak := true
  125. // If the container is starting (i.e. we never had a successful health check)
  126. // then we check if we are within the start period of the container in which
  127. // case we do not increment the failure streak.
  128. if h.Status() == types.Starting {
  129. startPeriod := timeoutWithDefault(c.Config.Healthcheck.StartPeriod, defaultStartPeriod)
  130. timeSinceStart := result.Start.Sub(c.State.StartedAt)
  131. // If still within the start period, then don't increment failing streak.
  132. if timeSinceStart < startPeriod {
  133. shouldIncrementStreak = false
  134. }
  135. }
  136. if shouldIncrementStreak {
  137. h.FailingStreak++
  138. if h.FailingStreak >= retries {
  139. h.SetStatus(types.Unhealthy)
  140. }
  141. }
  142. // Else we're starting or healthy. Stay in that state.
  143. }
  144. // replicate Health status changes
  145. if err := c.CheckpointTo(d.containersReplica); err != nil {
  146. // queries will be inconsistent until the next probe runs or other state mutations
  147. // checkpoint the container
  148. logrus.Errorf("Error replicating health state for container %s: %v", c.ID, err)
  149. }
  150. current := h.Status()
  151. if oldStatus != current {
  152. d.LogContainerEvent(c, "health_status: "+current)
  153. }
  154. }
  155. // Run the container's monitoring thread until notified via "stop".
  156. // There is never more than one monitor thread running per container at a time.
  157. func monitor(d *Daemon, c *container.Container, stop chan struct{}, probe probe) {
  158. probeTimeout := timeoutWithDefault(c.Config.Healthcheck.Timeout, defaultProbeTimeout)
  159. probeInterval := timeoutWithDefault(c.Config.Healthcheck.Interval, defaultProbeInterval)
  160. intervalTimer := time.NewTimer(probeInterval)
  161. defer intervalTimer.Stop()
  162. for {
  163. intervalTimer.Reset(probeInterval)
  164. select {
  165. case <-stop:
  166. logrus.Debugf("Stop healthcheck monitoring for container %s (received while idle)", c.ID)
  167. return
  168. case <-intervalTimer.C:
  169. logrus.Debugf("Running health check for container %s ...", c.ID)
  170. startTime := time.Now()
  171. ctx, cancelProbe := context.WithTimeout(context.Background(), probeTimeout)
  172. results := make(chan *types.HealthcheckResult, 1)
  173. go func() {
  174. healthChecksCounter.Inc()
  175. result, err := probe.run(ctx, d, c)
  176. if err != nil {
  177. healthChecksFailedCounter.Inc()
  178. logrus.Warnf("Health check for container %s error: %v", c.ID, err)
  179. results <- &types.HealthcheckResult{
  180. ExitCode: -1,
  181. Output: err.Error(),
  182. Start: startTime,
  183. End: time.Now(),
  184. }
  185. } else {
  186. result.Start = startTime
  187. logrus.Debugf("Health check for container %s done (exitCode=%d)", c.ID, result.ExitCode)
  188. results <- result
  189. }
  190. close(results)
  191. }()
  192. select {
  193. case <-stop:
  194. logrus.Debugf("Stop healthcheck monitoring for container %s (received while probing)", c.ID)
  195. cancelProbe()
  196. // Wait for probe to exit (it might take a while to respond to the TERM
  197. // signal and we don't want dying probes to pile up).
  198. <-results
  199. return
  200. case result := <-results:
  201. handleProbeResult(d, c, result, stop)
  202. // Stop timeout
  203. cancelProbe()
  204. case <-ctx.Done():
  205. logrus.Debugf("Health check for container %s taking too long", c.ID)
  206. handleProbeResult(d, c, &types.HealthcheckResult{
  207. ExitCode: -1,
  208. Output: fmt.Sprintf("Health check exceeded timeout (%v)", probeTimeout),
  209. Start: startTime,
  210. End: time.Now(),
  211. }, stop)
  212. cancelProbe()
  213. // Wait for probe to exit (it might take a while to respond to the TERM
  214. // signal and we don't want dying probes to pile up).
  215. <-results
  216. }
  217. }
  218. }
  219. }
  220. // Get a suitable probe implementation for the container's healthcheck configuration.
  221. // Nil will be returned if no healthcheck was configured or NONE was set.
  222. func getProbe(c *container.Container) probe {
  223. config := c.Config.Healthcheck
  224. if config == nil || len(config.Test) == 0 {
  225. return nil
  226. }
  227. switch config.Test[0] {
  228. case "CMD":
  229. return &cmdProbe{shell: false}
  230. case "CMD-SHELL":
  231. return &cmdProbe{shell: true}
  232. case "NONE":
  233. return nil
  234. default:
  235. logrus.Warnf("Unknown healthcheck type '%s' (expected 'CMD') in container %s", config.Test[0], c.ID)
  236. return nil
  237. }
  238. }
  239. // Ensure the health-check monitor is running or not, depending on the current
  240. // state of the container.
  241. // Called from monitor.go, with c locked.
  242. func (daemon *Daemon) updateHealthMonitor(c *container.Container) {
  243. h := c.State.Health
  244. if h == nil {
  245. return // No healthcheck configured
  246. }
  247. probe := getProbe(c)
  248. wantRunning := c.Running && !c.Paused && probe != nil
  249. if wantRunning {
  250. if stop := h.OpenMonitorChannel(); stop != nil {
  251. go monitor(daemon, c, stop, probe)
  252. }
  253. } else {
  254. h.CloseMonitorChannel()
  255. }
  256. }
  257. // Reset the health state for a newly-started, restarted or restored container.
  258. // initHealthMonitor is called from monitor.go and we should never be running
  259. // two instances at once.
  260. // Called with c locked.
  261. func (daemon *Daemon) initHealthMonitor(c *container.Container) {
  262. // If no healthcheck is setup then don't init the monitor
  263. if getProbe(c) == nil {
  264. return
  265. }
  266. // This is needed in case we're auto-restarting
  267. daemon.stopHealthchecks(c)
  268. if h := c.State.Health; h != nil {
  269. h.SetStatus(types.Starting)
  270. h.FailingStreak = 0
  271. } else {
  272. h := &container.Health{}
  273. h.SetStatus(types.Starting)
  274. c.State.Health = h
  275. }
  276. daemon.updateHealthMonitor(c)
  277. }
  278. // Called when the container is being stopped (whether because the health check is
  279. // failing or for any other reason).
  280. func (daemon *Daemon) stopHealthchecks(c *container.Container) {
  281. h := c.State.Health
  282. if h != nil {
  283. h.CloseMonitorChannel()
  284. }
  285. }
  286. // Buffer up to maxOutputLen bytes. Further data is discarded.
  287. type limitedBuffer struct {
  288. buf bytes.Buffer
  289. mu sync.Mutex
  290. truncated bool // indicates that data has been lost
  291. }
  292. // Append to limitedBuffer while there is room.
  293. func (b *limitedBuffer) Write(data []byte) (int, error) {
  294. b.mu.Lock()
  295. defer b.mu.Unlock()
  296. bufLen := b.buf.Len()
  297. dataLen := len(data)
  298. keep := min(maxOutputLen-bufLen, dataLen)
  299. if keep > 0 {
  300. b.buf.Write(data[:keep])
  301. }
  302. if keep < dataLen {
  303. b.truncated = true
  304. }
  305. return dataLen, nil
  306. }
  307. // The contents of the buffer, with "..." appended if it overflowed.
  308. func (b *limitedBuffer) String() string {
  309. b.mu.Lock()
  310. defer b.mu.Unlock()
  311. out := b.buf.String()
  312. if b.truncated {
  313. out = out + "..."
  314. }
  315. return out
  316. }
  317. // If configuredValue is zero, use defaultValue instead.
  318. func timeoutWithDefault(configuredValue time.Duration, defaultValue time.Duration) time.Duration {
  319. if configuredValue == 0 {
  320. return defaultValue
  321. }
  322. return configuredValue
  323. }
  324. func min(x, y int) int {
  325. if x < y {
  326. return x
  327. }
  328. return y
  329. }
  330. func getShell(cntr *container.Container) []string {
  331. if len(cntr.Config.Shell) != 0 {
  332. return cntr.Config.Shell
  333. }
  334. if runtime.GOOS != "windows" {
  335. return []string{"/bin/sh", "-c"}
  336. }
  337. if cntr.OS != runtime.GOOS {
  338. return []string{"/bin/sh", "-c"}
  339. }
  340. return []string{"cmd", "/S", "/C"}
  341. }