docker_utils_test.go 14 KB

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