daemon.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package daemon // import "github.com/docker/docker/integration-cli/daemon"
  2. import (
  3. "fmt"
  4. "os/exec"
  5. "strings"
  6. "time"
  7. "github.com/docker/docker/integration-cli/checker"
  8. "github.com/docker/docker/internal/test/daemon"
  9. "github.com/go-check/check"
  10. "github.com/gotestyourself/gotestyourself/assert"
  11. "github.com/gotestyourself/gotestyourself/icmd"
  12. "github.com/pkg/errors"
  13. )
  14. type testingT interface {
  15. assert.TestingT
  16. logT
  17. Fatalf(string, ...interface{})
  18. }
  19. type logT interface {
  20. Logf(string, ...interface{})
  21. }
  22. // Daemon represents a Docker daemon for the testing framework.
  23. type Daemon struct {
  24. *daemon.Daemon
  25. dockerBinary string
  26. }
  27. // New returns a Daemon instance to be used for testing.
  28. // This will create a directory such as d123456789 in the folder specified by $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
  29. // The daemon will not automatically start.
  30. func New(t testingT, dockerBinary string, dockerdBinary string, ops ...func(*daemon.Daemon)) *Daemon {
  31. ops = append(ops, daemon.WithDockerdBinary(dockerdBinary))
  32. d := daemon.New(t, ops...)
  33. return &Daemon{
  34. Daemon: d,
  35. dockerBinary: dockerBinary,
  36. }
  37. }
  38. // Cmd executes a docker CLI command against this daemon.
  39. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  40. func (d *Daemon) Cmd(args ...string) (string, error) {
  41. result := icmd.RunCmd(d.Command(args...))
  42. return result.Combined(), result.Error
  43. }
  44. // Command creates a docker CLI command against this daemon, to be executed later.
  45. // Example: d.Command("version") creates a command to run "docker -H unix://path/to/unix.sock version"
  46. func (d *Daemon) Command(args ...string) icmd.Cmd {
  47. return icmd.Command(d.dockerBinary, d.PrependHostArg(args)...)
  48. }
  49. // PrependHostArg prepend the specified arguments by the daemon host flags
  50. func (d *Daemon) PrependHostArg(args []string) []string {
  51. for _, arg := range args {
  52. if arg == "--host" || arg == "-H" {
  53. return args
  54. }
  55. }
  56. return append([]string{"--host", d.Sock()}, args...)
  57. }
  58. // GetIDByName returns the ID of an object (container, volume, …) given its name
  59. func (d *Daemon) GetIDByName(name string) (string, error) {
  60. return d.inspectFieldWithError(name, "Id")
  61. }
  62. // ActiveContainers returns the list of ids of the currently running containers
  63. func (d *Daemon) ActiveContainers() (ids []string) {
  64. // FIXME(vdemeester) shouldn't ignore the error
  65. out, _ := d.Cmd("ps", "-q")
  66. for _, id := range strings.Split(out, "\n") {
  67. if id = strings.TrimSpace(id); id != "" {
  68. ids = append(ids, id)
  69. }
  70. }
  71. return
  72. }
  73. // InspectField returns the field filter by 'filter'
  74. func (d *Daemon) InspectField(name, filter string) (string, error) {
  75. return d.inspectFilter(name, filter)
  76. }
  77. func (d *Daemon) inspectFilter(name, filter string) (string, error) {
  78. format := fmt.Sprintf("{{%s}}", filter)
  79. out, err := d.Cmd("inspect", "-f", format, name)
  80. if err != nil {
  81. return "", errors.Errorf("failed to inspect %s: %s", name, out)
  82. }
  83. return strings.TrimSpace(out), nil
  84. }
  85. func (d *Daemon) inspectFieldWithError(name, field string) (string, error) {
  86. return d.inspectFilter(name, fmt.Sprintf(".%s", field))
  87. }
  88. // FindContainerIP returns the ip of the specified container
  89. func (d *Daemon) FindContainerIP(id string) (string, error) {
  90. out, err := d.Cmd("inspect", "--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'", id)
  91. if err != nil {
  92. return "", err
  93. }
  94. return strings.Trim(out, " \r\n'"), nil
  95. }
  96. // BuildImageWithOut builds an image with the specified dockerfile and options and returns the output
  97. func (d *Daemon) BuildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, int, error) {
  98. buildCmd := BuildImageCmdWithHost(d.dockerBinary, name, dockerfile, d.Sock(), useCache, buildFlags...)
  99. result := icmd.RunCmd(icmd.Cmd{
  100. Command: buildCmd.Args,
  101. Env: buildCmd.Env,
  102. Dir: buildCmd.Dir,
  103. Stdin: buildCmd.Stdin,
  104. Stdout: buildCmd.Stdout,
  105. })
  106. return result.Combined(), result.ExitCode, result.Error
  107. }
  108. // CheckActiveContainerCount returns the number of active containers
  109. // FIXME(vdemeester) should re-use ActivateContainers in some way
  110. func (d *Daemon) CheckActiveContainerCount(c *check.C) (interface{}, check.CommentInterface) {
  111. out, err := d.Cmd("ps", "-q")
  112. c.Assert(err, checker.IsNil)
  113. if len(strings.TrimSpace(out)) == 0 {
  114. return 0, nil
  115. }
  116. return len(strings.Split(strings.TrimSpace(out), "\n")), check.Commentf("output: %q", string(out))
  117. }
  118. // WaitRun waits for a container to be running for 10s
  119. func (d *Daemon) WaitRun(contID string) error {
  120. args := []string{"--host", d.Sock()}
  121. return WaitInspectWithArgs(d.dockerBinary, contID, "{{.State.Running}}", "true", 10*time.Second, args...)
  122. }
  123. // CmdRetryOutOfSequence tries the specified command against the current daemon for 10 times
  124. func (d *Daemon) CmdRetryOutOfSequence(args ...string) (string, error) {
  125. for i := 0; ; i++ {
  126. out, err := d.Cmd(args...)
  127. if err != nil {
  128. if strings.Contains(out, "update out of sequence") {
  129. if i < 10 {
  130. continue
  131. }
  132. }
  133. }
  134. return out, err
  135. }
  136. }
  137. // WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
  138. // Deprecated: use cli.WaitCmd instead
  139. func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error {
  140. after := time.After(timeout)
  141. args := append(arg, "inspect", "-f", expr, name)
  142. for {
  143. result := icmd.RunCommand(dockerBinary, args...)
  144. if result.Error != nil {
  145. if !strings.Contains(strings.ToLower(result.Stderr()), "no such") {
  146. return errors.Errorf("error executing docker inspect: %v\n%s",
  147. result.Stderr(), result.Stdout())
  148. }
  149. select {
  150. case <-after:
  151. return result.Error
  152. default:
  153. time.Sleep(10 * time.Millisecond)
  154. continue
  155. }
  156. }
  157. out := strings.TrimSpace(result.Stdout())
  158. if out == expected {
  159. break
  160. }
  161. select {
  162. case <-after:
  163. return errors.Errorf("condition \"%q == %q\" not true in time (%v)", out, expected, timeout)
  164. default:
  165. }
  166. time.Sleep(100 * time.Millisecond)
  167. }
  168. return nil
  169. }
  170. // BuildImageCmdWithHost create a build command with the specified arguments.
  171. // Deprecated
  172. // FIXME(vdemeester) move this away
  173. func BuildImageCmdWithHost(dockerBinary, name, dockerfile, host string, useCache bool, buildFlags ...string) *exec.Cmd {
  174. args := []string{}
  175. if host != "" {
  176. args = append(args, "--host", host)
  177. }
  178. args = append(args, "build", "-t", name)
  179. if !useCache {
  180. args = append(args, "--no-cache")
  181. }
  182. args = append(args, buildFlags...)
  183. args = append(args, "-")
  184. buildCmd := exec.Command(dockerBinary, args...)
  185. buildCmd.Stdin = strings.NewReader(dockerfile)
  186. return buildCmd
  187. }