docker_utils_test.go 13 KB

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