docker_utils_test.go 13 KB

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