states.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package container
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/docker/docker/client"
  6. "github.com/docker/docker/errdefs"
  7. "github.com/pkg/errors"
  8. "gotest.tools/v3/poll"
  9. )
  10. // IsStopped verifies the container is in stopped state.
  11. func IsStopped(ctx context.Context, apiClient client.APIClient, containerID string) func(log poll.LogT) poll.Result {
  12. return func(log poll.LogT) poll.Result {
  13. inspect, err := apiClient.ContainerInspect(ctx, containerID)
  14. switch {
  15. case err != nil:
  16. return poll.Error(err)
  17. case !inspect.State.Running:
  18. return poll.Success()
  19. default:
  20. return poll.Continue("waiting for container to be stopped")
  21. }
  22. }
  23. }
  24. // IsInState verifies the container is in one of the specified state, e.g., "running", "exited", etc.
  25. func IsInState(ctx context.Context, apiClient client.APIClient, containerID string, state ...string) func(log poll.LogT) poll.Result {
  26. return func(log poll.LogT) poll.Result {
  27. inspect, err := apiClient.ContainerInspect(ctx, containerID)
  28. if err != nil {
  29. return poll.Error(err)
  30. }
  31. for _, v := range state {
  32. if inspect.State.Status == v {
  33. return poll.Success()
  34. }
  35. }
  36. return poll.Continue("waiting for container to be one of (%s), currently %s", strings.Join(state, ", "), inspect.State.Status)
  37. }
  38. }
  39. // IsSuccessful verifies state.Status == "exited" && state.ExitCode == 0
  40. func IsSuccessful(ctx context.Context, apiClient client.APIClient, containerID string) func(log poll.LogT) poll.Result {
  41. return func(log poll.LogT) poll.Result {
  42. inspect, err := apiClient.ContainerInspect(ctx, containerID)
  43. if err != nil {
  44. return poll.Error(err)
  45. }
  46. if inspect.State.Status == "exited" {
  47. if inspect.State.ExitCode == 0 {
  48. return poll.Success()
  49. }
  50. return poll.Error(errors.Errorf("expected exit code 0, got %d", inspect.State.ExitCode))
  51. }
  52. return poll.Continue("waiting for container to be \"exited\", currently %s", inspect.State.Status)
  53. }
  54. }
  55. // IsRemoved verifies the container has been removed
  56. func IsRemoved(ctx context.Context, apiClient client.APIClient, containerID string) func(log poll.LogT) poll.Result {
  57. return func(log poll.LogT) poll.Result {
  58. inspect, err := apiClient.ContainerInspect(ctx, containerID)
  59. if err != nil {
  60. if errdefs.IsNotFound(err) {
  61. return poll.Success()
  62. }
  63. return poll.Error(err)
  64. }
  65. return poll.Continue("waiting for container to be removed, currently %s", inspect.State.Status)
  66. }
  67. }