health_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package container // import "github.com/docker/docker/integration/container"
  2. import (
  3. "context"
  4. "fmt"
  5. "testing"
  6. "time"
  7. "github.com/docker/docker/api/types"
  8. containertypes "github.com/docker/docker/api/types/container"
  9. "github.com/docker/docker/client"
  10. "github.com/docker/docker/integration/internal/container"
  11. "gotest.tools/v3/assert"
  12. "gotest.tools/v3/poll"
  13. "gotest.tools/v3/skip"
  14. )
  15. // TestHealthCheckWorkdir verifies that health-checks inherit the containers'
  16. // working-dir.
  17. func TestHealthCheckWorkdir(t *testing.T) {
  18. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME")
  19. ctx := setupTest(t)
  20. apiClient := testEnv.APIClient()
  21. cID := container.Run(ctx, t, apiClient, container.WithTty(true), container.WithWorkingDir("/foo"), func(c *container.TestContainerConfig) {
  22. c.Config.Healthcheck = &containertypes.HealthConfig{
  23. Test: []string{"CMD-SHELL", "if [ \"$PWD\" = \"/foo\" ]; then exit 0; else exit 1; fi;"},
  24. Interval: 50 * time.Millisecond,
  25. Retries: 3,
  26. }
  27. })
  28. poll.WaitOn(t, pollForHealthStatus(ctx, apiClient, cID, types.Healthy), poll.WithDelay(100*time.Millisecond))
  29. }
  30. // GitHub #37263
  31. // Do not stop healthchecks just because we sent a signal to the container
  32. func TestHealthKillContainer(t *testing.T) {
  33. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "Windows only supports SIGKILL and SIGTERM? See https://github.com/moby/moby/issues/39574")
  34. ctx := setupTest(t)
  35. apiClient := testEnv.APIClient()
  36. id := container.Run(ctx, t, apiClient, func(c *container.TestContainerConfig) {
  37. cmd := `
  38. # Set the initial HEALTH value so the healthcheck passes
  39. HEALTH="1"
  40. echo $HEALTH > /health
  41. # Any time doHealth is run we flip the value
  42. # This lets us use kill signals to determine when healtchecks have run.
  43. doHealth() {
  44. case "$HEALTH" in
  45. "0")
  46. HEALTH="1"
  47. ;;
  48. "1")
  49. HEALTH="0"
  50. ;;
  51. esac
  52. echo $HEALTH > /health
  53. }
  54. trap 'doHealth' USR1
  55. while true; do sleep 1; done
  56. `
  57. c.Config.Cmd = []string{"/bin/sh", "-c", cmd}
  58. c.Config.Healthcheck = &containertypes.HealthConfig{
  59. Test: []string{"CMD-SHELL", `[ "$(cat /health)" = "1" ]`},
  60. Interval: time.Second,
  61. Retries: 5,
  62. }
  63. })
  64. ctxPoll, cancel := context.WithTimeout(ctx, 30*time.Second)
  65. defer cancel()
  66. poll.WaitOn(t, pollForHealthStatus(ctxPoll, apiClient, id, "healthy"), poll.WithDelay(100*time.Millisecond))
  67. err := apiClient.ContainerKill(ctx, id, "SIGUSR1")
  68. assert.NilError(t, err)
  69. ctxPoll, cancel = context.WithTimeout(ctx, 30*time.Second)
  70. defer cancel()
  71. poll.WaitOn(t, pollForHealthStatus(ctxPoll, apiClient, id, "unhealthy"), poll.WithDelay(100*time.Millisecond))
  72. err = apiClient.ContainerKill(ctx, id, "SIGUSR1")
  73. assert.NilError(t, err)
  74. ctxPoll, cancel = context.WithTimeout(ctx, 30*time.Second)
  75. defer cancel()
  76. poll.WaitOn(t, pollForHealthStatus(ctxPoll, apiClient, id, "healthy"), poll.WithDelay(100*time.Millisecond))
  77. }
  78. // TestHealthCheckProcessKilled verifies that health-checks exec get killed on time-out.
  79. func TestHealthCheckProcessKilled(t *testing.T) {
  80. ctx := setupTest(t)
  81. apiClient := testEnv.APIClient()
  82. cID := container.Run(ctx, t, apiClient, func(c *container.TestContainerConfig) {
  83. c.Config.Healthcheck = &containertypes.HealthConfig{
  84. Test: []string{"CMD", "sh", "-c", `echo "logs logs logs"; sleep 60`},
  85. Interval: 100 * time.Millisecond,
  86. Timeout: 50 * time.Millisecond,
  87. Retries: 1,
  88. }
  89. })
  90. poll.WaitOn(t, pollForHealthCheckLog(ctx, apiClient, cID, "Health check exceeded timeout (50ms): logs logs logs\n"))
  91. }
  92. func TestHealthStartInterval(t *testing.T) {
  93. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "The shell commands used in the test healthcheck do not work on Windows")
  94. ctx := setupTest(t)
  95. apiClient := testEnv.APIClient()
  96. // Note: Windows is much slower than linux so this use longer intervals/timeouts
  97. id := container.Run(ctx, t, apiClient, func(c *container.TestContainerConfig) {
  98. c.Config.Healthcheck = &containertypes.HealthConfig{
  99. Test: []string{"CMD-SHELL", `count="$(cat /tmp/health)"; if [ -z "${count}" ]; then let count=0; fi; let count=${count}+1; echo -n ${count} | tee /tmp/health; if [ ${count} -lt 3 ]; then exit 1; fi`},
  100. Interval: 30 * time.Second,
  101. StartInterval: time.Second,
  102. StartPeriod: 30 * time.Second,
  103. }
  104. })
  105. ctxPoll, cancel := context.WithTimeout(ctx, 30*time.Second)
  106. defer cancel()
  107. dl, _ := ctxPoll.Deadline()
  108. poll.WaitOn(t, func(log poll.LogT) poll.Result {
  109. if ctxPoll.Err() != nil {
  110. return poll.Error(ctxPoll.Err())
  111. }
  112. inspect, err := apiClient.ContainerInspect(ctxPoll, id)
  113. if err != nil {
  114. return poll.Error(err)
  115. }
  116. if inspect.State.Health.Status != "healthy" {
  117. if len(inspect.State.Health.Log) > 0 {
  118. t.Log(inspect.State.Health.Log[len(inspect.State.Health.Log)-1])
  119. }
  120. return poll.Continue("waiting on container to be ready")
  121. }
  122. return poll.Success()
  123. }, poll.WithDelay(100*time.Millisecond), poll.WithTimeout(time.Until(dl)))
  124. cancel()
  125. ctxPoll, cancel = context.WithTimeout(ctx, 2*time.Minute)
  126. defer cancel()
  127. dl, _ = ctxPoll.Deadline()
  128. poll.WaitOn(t, func(log poll.LogT) poll.Result {
  129. inspect, err := apiClient.ContainerInspect(ctxPoll, id)
  130. if err != nil {
  131. return poll.Error(err)
  132. }
  133. hLen := len(inspect.State.Health.Log)
  134. if hLen < 2 {
  135. return poll.Continue("waiting for more healthcheck results")
  136. }
  137. h1 := inspect.State.Health.Log[hLen-1]
  138. h2 := inspect.State.Health.Log[hLen-2]
  139. if h1.Start.Sub(h2.Start) >= inspect.Config.Healthcheck.Interval {
  140. return poll.Success()
  141. }
  142. t.Log(h1.Start.Sub(h2.Start))
  143. return poll.Continue("waiting for health check interval to switch from the start interval")
  144. }, poll.WithDelay(time.Second), poll.WithTimeout(time.Until(dl)))
  145. }
  146. func pollForHealthCheckLog(ctx context.Context, client client.APIClient, containerID string, expected string) func(log poll.LogT) poll.Result {
  147. return func(log poll.LogT) poll.Result {
  148. inspect, err := client.ContainerInspect(ctx, containerID)
  149. if err != nil {
  150. return poll.Error(err)
  151. }
  152. healthChecksTotal := len(inspect.State.Health.Log)
  153. if healthChecksTotal > 0 {
  154. output := inspect.State.Health.Log[healthChecksTotal-1].Output
  155. if output == expected {
  156. return poll.Success()
  157. }
  158. return poll.Error(fmt.Errorf("expected %q, got %q", expected, output))
  159. }
  160. return poll.Continue("waiting for container healthcheck logs")
  161. }
  162. }
  163. func pollForHealthStatus(ctx context.Context, client client.APIClient, containerID string, healthStatus string) func(log poll.LogT) poll.Result {
  164. return func(log poll.LogT) poll.Result {
  165. inspect, err := client.ContainerInspect(ctx, containerID)
  166. switch {
  167. case err != nil:
  168. return poll.Error(err)
  169. case inspect.State.Health.Status == healthStatus:
  170. return poll.Success()
  171. default:
  172. return poll.Continue("waiting for container to become %s", healthStatus)
  173. }
  174. }
  175. }