utils.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package container
  2. import (
  3. "fmt"
  4. "strconv"
  5. "golang.org/x/net/context"
  6. "github.com/Sirupsen/logrus"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/api/types/events"
  9. "github.com/docker/docker/api/types/filters"
  10. "github.com/docker/docker/cli/command"
  11. "github.com/docker/docker/cli/command/system"
  12. clientapi "github.com/docker/docker/client"
  13. )
  14. func waitExitOrRemoved(dockerCli *command.DockerCli, ctx context.Context, containerID string, waitRemove bool) (chan int, error) {
  15. if len(containerID) == 0 {
  16. // containerID can never be empty
  17. panic("Internal Error: waitExitOrRemoved needs a containerID as parameter")
  18. }
  19. statusChan := make(chan int)
  20. exitCode := 125
  21. eventProcessor := func(e events.Message, err error) error {
  22. if err != nil {
  23. statusChan <- exitCode
  24. return fmt.Errorf("failed to decode event: %v", err)
  25. }
  26. stopProcessing := false
  27. switch e.Status {
  28. case "die":
  29. if v, ok := e.Actor.Attributes["exitCode"]; ok {
  30. code, cerr := strconv.Atoi(v)
  31. if cerr != nil {
  32. logrus.Errorf("failed to convert exitcode '%q' to int: %v", v, cerr)
  33. } else {
  34. exitCode = code
  35. }
  36. }
  37. if !waitRemove {
  38. stopProcessing = true
  39. }
  40. case "detach":
  41. exitCode = 0
  42. stopProcessing = true
  43. case "destroy":
  44. stopProcessing = true
  45. }
  46. if stopProcessing {
  47. statusChan <- exitCode
  48. // stop the loop processing
  49. return fmt.Errorf("done")
  50. }
  51. return nil
  52. }
  53. // Get events via Events API
  54. f := filters.NewArgs()
  55. f.Add("type", "container")
  56. f.Add("container", containerID)
  57. options := types.EventsOptions{
  58. Filters: f,
  59. }
  60. resBody, err := dockerCli.Client().Events(ctx, options)
  61. if err != nil {
  62. return nil, fmt.Errorf("can't get events from daemon: %v", err)
  63. }
  64. go system.DecodeEvents(resBody, eventProcessor)
  65. return statusChan, nil
  66. }
  67. // getExitCode performs an inspect on the container. It returns
  68. // the running state and the exit code.
  69. func getExitCode(dockerCli *command.DockerCli, ctx context.Context, containerID string) (bool, int, error) {
  70. c, err := dockerCli.Client().ContainerInspect(ctx, containerID)
  71. if err != nil {
  72. // If we can't connect, then the daemon probably died.
  73. if err != clientapi.ErrConnectionFailed {
  74. return false, -1, err
  75. }
  76. return false, -1, nil
  77. }
  78. return c.State.Running, c.State.ExitCode, nil
  79. }