states.go 1.8 KB

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