health.go 10 KB

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