docker_utils_test.go 13 KB

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