restart_test.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. "github.com/docker/docker/api/types/container"
  9. "github.com/docker/docker/client"
  10. testContainer "github.com/docker/docker/integration/internal/container"
  11. "github.com/docker/docker/testutil/daemon"
  12. "gotest.tools/v3/assert"
  13. "gotest.tools/v3/poll"
  14. "gotest.tools/v3/skip"
  15. )
  16. func TestDaemonRestartKillContainers(t *testing.T) {
  17. skip.If(t, testEnv.IsRemoteDaemon, "cannot start daemon on remote test run")
  18. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  19. skip.If(t, testEnv.IsRootless, "rootless mode doesn't support live-restore")
  20. type testCase struct {
  21. desc string
  22. config *container.Config
  23. hostConfig *container.HostConfig
  24. xRunning bool
  25. xRunningLiveRestore bool
  26. xStart bool
  27. xHealthCheck bool
  28. }
  29. for _, tc := range []testCase{
  30. {
  31. desc: "container without restart policy",
  32. config: &container.Config{Image: "busybox", Cmd: []string{"top"}},
  33. xRunningLiveRestore: true,
  34. xStart: true,
  35. },
  36. {
  37. desc: "container with restart=always",
  38. config: &container.Config{Image: "busybox", Cmd: []string{"top"}},
  39. hostConfig: &container.HostConfig{RestartPolicy: container.RestartPolicy{Name: "always"}},
  40. xRunning: true,
  41. xRunningLiveRestore: true,
  42. xStart: true,
  43. },
  44. {
  45. desc: "container with restart=always and with healthcheck",
  46. config: &container.Config{
  47. Image: "busybox", Cmd: []string{"top"},
  48. Healthcheck: &container.HealthConfig{
  49. Test: []string{"CMD-SHELL", "sleep 1"},
  50. Interval: time.Second,
  51. },
  52. },
  53. hostConfig: &container.HostConfig{RestartPolicy: container.RestartPolicy{Name: "always"}},
  54. xRunning: true,
  55. xRunningLiveRestore: true,
  56. xStart: true,
  57. xHealthCheck: true,
  58. },
  59. {
  60. desc: "container created should not be restarted",
  61. config: &container.Config{Image: "busybox", Cmd: []string{"top"}},
  62. hostConfig: &container.HostConfig{RestartPolicy: container.RestartPolicy{Name: "always"}},
  63. },
  64. } {
  65. for _, liveRestoreEnabled := range []bool{false, true} {
  66. for fnName, stopDaemon := range map[string]func(*testing.T, *daemon.Daemon){
  67. "kill-daemon": func(t *testing.T, d *daemon.Daemon) {
  68. err := d.Kill()
  69. assert.NilError(t, err)
  70. },
  71. "stop-daemon": func(t *testing.T, d *daemon.Daemon) {
  72. d.Stop(t)
  73. },
  74. } {
  75. tc := tc
  76. liveRestoreEnabled := liveRestoreEnabled
  77. stopDaemon := stopDaemon
  78. t.Run(fmt.Sprintf("live-restore=%v/%s/%s", liveRestoreEnabled, tc.desc, fnName), func(t *testing.T) {
  79. t.Parallel()
  80. d := daemon.New(t)
  81. apiClient := d.NewClientT(t)
  82. args := []string{"--iptables=false"}
  83. if liveRestoreEnabled {
  84. args = append(args, "--live-restore")
  85. }
  86. d.StartWithBusybox(t, args...)
  87. defer d.Stop(t)
  88. ctx := context.Background()
  89. resp, err := apiClient.ContainerCreate(ctx, tc.config, tc.hostConfig, nil, nil, "")
  90. assert.NilError(t, err)
  91. defer apiClient.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{Force: true})
  92. if tc.xStart {
  93. err = apiClient.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
  94. assert.NilError(t, err)
  95. }
  96. stopDaemon(t, d)
  97. d.Start(t, args...)
  98. expected := tc.xRunning
  99. if liveRestoreEnabled {
  100. expected = tc.xRunningLiveRestore
  101. }
  102. var running bool
  103. for i := 0; i < 30; i++ {
  104. inspect, err := apiClient.ContainerInspect(ctx, resp.ID)
  105. assert.NilError(t, err)
  106. running = inspect.State.Running
  107. if running == expected {
  108. break
  109. }
  110. time.Sleep(2 * time.Second)
  111. }
  112. assert.Equal(t, expected, running, "got unexpected running state, expected %v, got: %v", expected, running)
  113. if tc.xHealthCheck {
  114. startTime := time.Now()
  115. ctxPoll, cancel := context.WithTimeout(ctx, 30*time.Second)
  116. defer cancel()
  117. poll.WaitOn(t, pollForNewHealthCheck(ctxPoll, apiClient, startTime, resp.ID), poll.WithDelay(100*time.Millisecond))
  118. }
  119. // TODO(cpuguy83): test pause states... this seems to be rather undefined currently
  120. })
  121. }
  122. }
  123. }
  124. }
  125. func pollForNewHealthCheck(ctx context.Context, client *client.Client, startTime time.Time, containerID string) func(log poll.LogT) poll.Result {
  126. return func(log poll.LogT) poll.Result {
  127. inspect, err := client.ContainerInspect(ctx, containerID)
  128. if err != nil {
  129. return poll.Error(err)
  130. }
  131. healthChecksTotal := len(inspect.State.Health.Log)
  132. if healthChecksTotal > 0 {
  133. if inspect.State.Health.Log[healthChecksTotal-1].Start.After(startTime) {
  134. return poll.Success()
  135. }
  136. }
  137. return poll.Continue("waiting for a new container healthcheck")
  138. }
  139. }
  140. // Container started with --rm should be able to be restarted.
  141. // It should be removed only if killed or stopped
  142. func TestContainerWithAutoRemoveCanBeRestarted(t *testing.T) {
  143. defer setupTest(t)()
  144. apiClient := testEnv.APIClient()
  145. ctx := context.Background()
  146. noWaitTimeout := 0
  147. for _, tc := range []struct {
  148. desc string
  149. doSth func(ctx context.Context, containerID string) error
  150. }{
  151. {
  152. desc: "kill",
  153. doSth: func(ctx context.Context, containerID string) error {
  154. return apiClient.ContainerKill(ctx, containerID, "SIGKILL")
  155. },
  156. },
  157. {
  158. desc: "stop",
  159. doSth: func(ctx context.Context, containerID string) error {
  160. return apiClient.ContainerStop(ctx, containerID, container.StopOptions{Timeout: &noWaitTimeout})
  161. },
  162. },
  163. } {
  164. tc := tc
  165. t.Run(tc.desc, func(t *testing.T) {
  166. cID := testContainer.Run(ctx, t, apiClient,
  167. testContainer.WithName("autoremove-restart-and-"+tc.desc),
  168. testContainer.WithAutoRemove,
  169. )
  170. defer func() {
  171. err := apiClient.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
  172. if t.Failed() && err != nil {
  173. t.Logf("Cleaning up test container failed with error: %v", err)
  174. }
  175. }()
  176. err := apiClient.ContainerRestart(ctx, cID, container.StopOptions{Timeout: &noWaitTimeout})
  177. assert.NilError(t, err)
  178. inspect, err := apiClient.ContainerInspect(ctx, cID)
  179. assert.NilError(t, err)
  180. assert.Assert(t, inspect.State.Status != "removing", "Container should not be removing yet")
  181. poll.WaitOn(t, testContainer.IsInState(ctx, apiClient, cID, "running"))
  182. err = tc.doSth(ctx, cID)
  183. assert.NilError(t, err)
  184. poll.WaitOn(t, testContainer.IsRemoved(ctx, apiClient, cID))
  185. })
  186. }
  187. }