health.go 11 KB

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