docker_utils_test.go 13 KB

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