docker_utils_test.go 14 KB

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