docker_utils_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/client"
  17. "github.com/docker/docker/integration-cli/cli"
  18. "github.com/docker/docker/integration-cli/daemon"
  19. "github.com/go-check/check"
  20. "gotest.tools/assert"
  21. "gotest.tools/icmd"
  22. )
  23. func deleteImages(images ...string) error {
  24. args := []string{dockerBinary, "rmi", "-f"}
  25. return icmd.RunCmd(icmd.Cmd{Command: append(args, images...)}).Error
  26. }
  27. // Deprecated: use cli.Docker or cli.DockerCmd
  28. func dockerCmdWithError(args ...string) (string, int, error) {
  29. result := cli.Docker(cli.Args(args...))
  30. if result.Error != nil {
  31. return result.Combined(), result.ExitCode, result.Compare(icmd.Success)
  32. }
  33. return result.Combined(), result.ExitCode, result.Error
  34. }
  35. // Deprecated: use cli.Docker or cli.DockerCmd
  36. func dockerCmd(c *check.C, args ...string) (string, int) {
  37. result := cli.DockerCmd(c, args...)
  38. return result.Combined(), result.ExitCode
  39. }
  40. // Deprecated: use cli.Docker or cli.DockerCmd
  41. func dockerCmdWithResult(args ...string) *icmd.Result {
  42. return cli.Docker(cli.Args(args...))
  43. }
  44. func findContainerIP(c *check.C, id string, network string) string {
  45. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  46. return strings.Trim(out, " \r\n'")
  47. }
  48. func getContainerCount(c *check.C) int {
  49. const containers = "Containers:"
  50. result := icmd.RunCommand(dockerBinary, "info")
  51. result.Assert(c, icmd.Success)
  52. lines := strings.Split(result.Combined(), "\n")
  53. for _, line := range lines {
  54. if strings.Contains(line, containers) {
  55. output := strings.TrimSpace(line)
  56. output = strings.TrimPrefix(output, containers)
  57. output = strings.Trim(output, " ")
  58. containerCount, err := strconv.Atoi(output)
  59. assert.NilError(c, err)
  60. return containerCount
  61. }
  62. }
  63. return 0
  64. }
  65. func inspectFieldAndUnmarshall(c *check.C, name, field string, output interface{}) {
  66. str := inspectFieldJSON(c, name, field)
  67. err := json.Unmarshal([]byte(str), output)
  68. if c != nil {
  69. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  70. }
  71. }
  72. // Deprecated: use cli.Inspect
  73. func inspectFilter(name, filter string) (string, error) {
  74. format := fmt.Sprintf("{{%s}}", filter)
  75. result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name)
  76. if result.Error != nil || result.ExitCode != 0 {
  77. return "", fmt.Errorf("failed to inspect %s: %s", name, result.Combined())
  78. }
  79. return strings.TrimSpace(result.Combined()), nil
  80. }
  81. // Deprecated: use cli.Inspect
  82. func inspectFieldWithError(name, field string) (string, error) {
  83. return inspectFilter(name, fmt.Sprintf(".%s", field))
  84. }
  85. // Deprecated: use cli.Inspect
  86. func inspectField(c *check.C, name, field string) string {
  87. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  88. if c != nil {
  89. assert.NilError(c, err)
  90. }
  91. return out
  92. }
  93. // Deprecated: use cli.Inspect
  94. func inspectFieldJSON(c *check.C, name, field string) string {
  95. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  96. if c != nil {
  97. assert.NilError(c, err)
  98. }
  99. return out
  100. }
  101. // Deprecated: use cli.Inspect
  102. func inspectFieldMap(c *check.C, name, path, field string) string {
  103. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  104. if c != nil {
  105. assert.NilError(c, err)
  106. }
  107. return out
  108. }
  109. // Deprecated: use cli.Inspect
  110. func inspectMountSourceField(name, destination string) (string, error) {
  111. m, err := inspectMountPoint(name, destination)
  112. if err != nil {
  113. return "", err
  114. }
  115. return m.Source, nil
  116. }
  117. // Deprecated: use cli.Inspect
  118. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  119. out, err := inspectFilter(name, "json .Mounts")
  120. if err != nil {
  121. return types.MountPoint{}, err
  122. }
  123. return inspectMountPointJSON(out, destination)
  124. }
  125. var errMountNotFound = errors.New("mount point not found")
  126. // Deprecated: use cli.Inspect
  127. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  128. var mp []types.MountPoint
  129. if err := json.Unmarshal([]byte(j), &mp); err != nil {
  130. return types.MountPoint{}, err
  131. }
  132. var m *types.MountPoint
  133. for _, c := range mp {
  134. if c.Destination == destination {
  135. m = &c
  136. break
  137. }
  138. }
  139. if m == nil {
  140. return types.MountPoint{}, errMountNotFound
  141. }
  142. return *m, nil
  143. }
  144. // Deprecated: use cli.Inspect
  145. func inspectImage(c *check.C, name, filter string) string {
  146. args := []string{"inspect", "--type", "image"}
  147. if filter != "" {
  148. format := fmt.Sprintf("{{%s}}", filter)
  149. args = append(args, "-f", format)
  150. }
  151. args = append(args, name)
  152. result := icmd.RunCommand(dockerBinary, args...)
  153. result.Assert(c, icmd.Success)
  154. return strings.TrimSpace(result.Combined())
  155. }
  156. func getIDByName(c *check.C, name string) string {
  157. id, err := inspectFieldWithError(name, "Id")
  158. assert.NilError(c, err)
  159. return id
  160. }
  161. // Deprecated: use cli.Build
  162. func buildImageSuccessfully(c *check.C, name string, cmdOperators ...cli.CmdOperator) {
  163. buildImage(name, cmdOperators...).Assert(c, icmd.Success)
  164. }
  165. // Deprecated: use cli.Build
  166. func buildImage(name string, cmdOperators ...cli.CmdOperator) *icmd.Result {
  167. return cli.Docker(cli.Build(name), cmdOperators...)
  168. }
  169. // Write `content` to the file at path `dst`, creating it if necessary,
  170. // as well as any missing directories.
  171. // The file is truncated if it already exists.
  172. // Fail the test when error occurs.
  173. func writeFile(dst, content string, c *check.C) {
  174. // Create subdirectories if necessary
  175. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  176. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  177. assert.NilError(c, err)
  178. defer f.Close()
  179. // Write content (truncate if it exists)
  180. _, err = io.Copy(f, strings.NewReader(content))
  181. assert.NilError(c, err)
  182. }
  183. // Return the contents of file at path `src`.
  184. // Fail the test when error occurs.
  185. func readFile(src string, c *check.C) (content string) {
  186. data, err := ioutil.ReadFile(src)
  187. assert.NilError(c, err)
  188. return string(data)
  189. }
  190. func containerStorageFile(containerID, basename string) string {
  191. return filepath.Join(testEnv.PlatformDefaults.ContainerStoragePath, containerID, basename)
  192. }
  193. // docker commands that use this function must be run with the '-d' switch.
  194. func runCommandAndReadContainerFile(c *check.C, filename string, command string, args ...string) []byte {
  195. result := icmd.RunCommand(command, args...)
  196. result.Assert(c, icmd.Success)
  197. contID := strings.TrimSpace(result.Combined())
  198. if err := waitRun(contID); err != nil {
  199. c.Fatalf("%v: %q", contID, err)
  200. }
  201. return readContainerFile(c, contID, filename)
  202. }
  203. func readContainerFile(c *check.C, containerID, filename string) []byte {
  204. f, err := os.Open(containerStorageFile(containerID, filename))
  205. assert.NilError(c, err)
  206. defer f.Close()
  207. content, err := ioutil.ReadAll(f)
  208. assert.NilError(c, err)
  209. return content
  210. }
  211. func readContainerFileWithExec(c *check.C, containerID, filename string) []byte {
  212. result := icmd.RunCommand(dockerBinary, "exec", containerID, "cat", filename)
  213. result.Assert(c, icmd.Success)
  214. return []byte(result.Combined())
  215. }
  216. // daemonTime provides the current time on the daemon host
  217. func daemonTime(c *check.C) time.Time {
  218. if testEnv.IsLocalDaemon() {
  219. return time.Now()
  220. }
  221. cli, err := client.NewClientWithOpts(client.FromEnv)
  222. assert.NilError(c, err)
  223. defer cli.Close()
  224. info, err := cli.Info(context.Background())
  225. assert.NilError(c, err)
  226. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  227. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  228. return dt
  229. }
  230. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  231. // It return the time formatted how the client sends timestamps to the server.
  232. func daemonUnixTime(c *check.C) string {
  233. return parseEventTime(daemonTime(c))
  234. }
  235. func parseEventTime(t time.Time) string {
  236. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  237. }
  238. // appendBaseEnv appends the minimum set of environment variables to exec the
  239. // docker cli binary for testing with correct configuration to the given env
  240. // list.
  241. func appendBaseEnv(isTLS bool, env ...string) []string {
  242. preserveList := []string{
  243. // preserve remote test host
  244. "DOCKER_HOST",
  245. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  246. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  247. "SystemRoot",
  248. // testing help text requires the $PATH to dockerd is set
  249. "PATH",
  250. }
  251. if isTLS {
  252. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  253. }
  254. for _, key := range preserveList {
  255. if val := os.Getenv(key); val != "" {
  256. env = append(env, fmt.Sprintf("%s=%s", key, val))
  257. }
  258. }
  259. return env
  260. }
  261. func createTmpFile(c *check.C, content string) string {
  262. f, err := ioutil.TempFile("", "testfile")
  263. assert.NilError(c, err)
  264. filename := f.Name()
  265. err = ioutil.WriteFile(filename, []byte(content), 0644)
  266. assert.NilError(c, err)
  267. return filename
  268. }
  269. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  270. // Deprecated: use cli.WaitFor
  271. func waitRun(contID string) error {
  272. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  273. }
  274. // waitInspect will wait for the specified container to have the specified string
  275. // in the inspect output. It will wait until the specified timeout (in seconds)
  276. // is reached.
  277. // Deprecated: use cli.WaitFor
  278. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  279. return waitInspectWithArgs(name, expr, expected, timeout)
  280. }
  281. // Deprecated: use cli.WaitFor
  282. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  283. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  284. }
  285. func getInspectBody(c *check.C, version, id string) []byte {
  286. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion(version))
  287. assert.NilError(c, err)
  288. defer cli.Close()
  289. _, body, err := cli.ContainerInspectWithRaw(context.Background(), id, false)
  290. assert.NilError(c, err)
  291. return body
  292. }
  293. // Run a long running idle task in a background container using the
  294. // system-specific default image and command.
  295. func runSleepingContainer(c *check.C, extraArgs ...string) string {
  296. return runSleepingContainerInImage(c, "busybox", extraArgs...)
  297. }
  298. // Run a long running idle task in a background container using the specified
  299. // image and the system-specific command.
  300. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) string {
  301. args := []string{"run", "-d"}
  302. args = append(args, extraArgs...)
  303. args = append(args, image)
  304. args = append(args, sleepCommandForDaemonPlatform()...)
  305. return strings.TrimSpace(cli.DockerCmd(c, args...).Combined())
  306. }
  307. // minimalBaseImage returns the name of the minimal base image for the current
  308. // daemon platform.
  309. func minimalBaseImage() string {
  310. return testEnv.PlatformDefaults.BaseImage
  311. }
  312. func getGoroutineNumber() (int, error) {
  313. cli, err := client.NewClientWithOpts(client.FromEnv)
  314. if err != nil {
  315. return 0, err
  316. }
  317. defer cli.Close()
  318. info, err := cli.Info(context.Background())
  319. if err != nil {
  320. return 0, err
  321. }
  322. return info.NGoroutines, nil
  323. }
  324. func waitForGoroutines(expected int) error {
  325. t := time.After(30 * time.Second)
  326. for {
  327. select {
  328. case <-t:
  329. n, err := getGoroutineNumber()
  330. if err != nil {
  331. return err
  332. }
  333. if n > expected {
  334. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  335. }
  336. default:
  337. n, err := getGoroutineNumber()
  338. if err != nil {
  339. return err
  340. }
  341. if n <= expected {
  342. return nil
  343. }
  344. time.Sleep(200 * time.Millisecond)
  345. }
  346. }
  347. }
  348. // getErrorMessage returns the error message from an error API response
  349. func getErrorMessage(c *check.C, body []byte) string {
  350. var resp types.ErrorResponse
  351. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  352. return strings.TrimSpace(resp.Message)
  353. }
  354. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  355. t1 := time.Now()
  356. defer func() {
  357. t2 := time.Now()
  358. c.Logf("waited for %v (out of %v)", t2.Sub(t1), timeout)
  359. }()
  360. after := time.After(timeout)
  361. for {
  362. v, comment := f(c)
  363. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  364. select {
  365. case <-after:
  366. assert = true
  367. default:
  368. }
  369. if assert {
  370. if comment != nil {
  371. args = append(args, comment)
  372. }
  373. c.Assert(v, checker, args...)
  374. return
  375. }
  376. time.Sleep(100 * time.Millisecond)
  377. }
  378. }
  379. type checkF func(*check.C) (interface{}, check.CommentInterface)
  380. type reducer func(...interface{}) interface{}
  381. func reducedCheck(r reducer, funcs ...checkF) checkF {
  382. return func(c *check.C) (interface{}, check.CommentInterface) {
  383. var values []interface{}
  384. var comments []string
  385. for _, f := range funcs {
  386. v, comment := f(c)
  387. values = append(values, v)
  388. if comment != nil {
  389. comments = append(comments, comment.CheckCommentString())
  390. }
  391. }
  392. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  393. }
  394. }
  395. func sumAsIntegers(vals ...interface{}) interface{} {
  396. var s int
  397. for _, v := range vals {
  398. s += v.(int)
  399. }
  400. return s
  401. }