docker_utils_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. // Deprecated: use trustedcmd
  176. func trustedBuild(cmd *icmd.Cmd) func() {
  177. trustedCmd(cmd)
  178. return nil
  179. }
  180. // Write `content` to the file at path `dst`, creating it if necessary,
  181. // as well as any missing directories.
  182. // The file is truncated if it already exists.
  183. // Fail the test when error occurs.
  184. func writeFile(dst, content string, c *check.C) {
  185. // Create subdirectories if necessary
  186. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  187. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  188. c.Assert(err, check.IsNil)
  189. defer f.Close()
  190. // Write content (truncate if it exists)
  191. _, err = io.Copy(f, strings.NewReader(content))
  192. c.Assert(err, check.IsNil)
  193. }
  194. // Return the contents of file at path `src`.
  195. // Fail the test when error occurs.
  196. func readFile(src string, c *check.C) (content string) {
  197. data, err := ioutil.ReadFile(src)
  198. c.Assert(err, check.IsNil)
  199. return string(data)
  200. }
  201. func containerStorageFile(containerID, basename string) string {
  202. return filepath.Join(testEnv.PlatformDefaults.ContainerStoragePath, containerID, basename)
  203. }
  204. // docker commands that use this function must be run with the '-d' switch.
  205. func runCommandAndReadContainerFile(c *check.C, filename string, command string, args ...string) []byte {
  206. result := icmd.RunCommand(command, args...)
  207. result.Assert(c, icmd.Success)
  208. contID := strings.TrimSpace(result.Combined())
  209. if err := waitRun(contID); err != nil {
  210. c.Fatalf("%v: %q", contID, err)
  211. }
  212. return readContainerFile(c, contID, filename)
  213. }
  214. func readContainerFile(c *check.C, containerID, filename string) []byte {
  215. f, err := os.Open(containerStorageFile(containerID, filename))
  216. c.Assert(err, checker.IsNil)
  217. defer f.Close()
  218. content, err := ioutil.ReadAll(f)
  219. c.Assert(err, checker.IsNil)
  220. return content
  221. }
  222. func readContainerFileWithExec(c *check.C, containerID, filename string) []byte {
  223. result := icmd.RunCommand(dockerBinary, "exec", containerID, "cat", filename)
  224. result.Assert(c, icmd.Success)
  225. return []byte(result.Combined())
  226. }
  227. // daemonTime provides the current time on the daemon host
  228. func daemonTime(c *check.C) time.Time {
  229. if testEnv.IsLocalDaemon() {
  230. return time.Now()
  231. }
  232. cli, err := client.NewEnvClient()
  233. c.Assert(err, check.IsNil)
  234. defer cli.Close()
  235. info, err := cli.Info(context.Background())
  236. c.Assert(err, check.IsNil)
  237. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  238. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  239. return dt
  240. }
  241. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  242. // It return the time formatted how the client sends timestamps to the server.
  243. func daemonUnixTime(c *check.C) string {
  244. return parseEventTime(daemonTime(c))
  245. }
  246. func parseEventTime(t time.Time) string {
  247. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  248. }
  249. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *registry.V2 {
  250. reg, err := registry.NewV2(schema1, auth, tokenURL, privateRegistryURL)
  251. c.Assert(err, check.IsNil)
  252. // Wait for registry to be ready to serve requests.
  253. for i := 0; i != 50; i++ {
  254. if err = reg.Ping(); err == nil {
  255. break
  256. }
  257. time.Sleep(100 * time.Millisecond)
  258. }
  259. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  260. return reg
  261. }
  262. func setupNotary(c *check.C) *testNotary {
  263. ts, err := newTestNotary(c)
  264. c.Assert(err, check.IsNil)
  265. return ts
  266. }
  267. // appendBaseEnv appends the minimum set of environment variables to exec the
  268. // docker cli binary for testing with correct configuration to the given env
  269. // list.
  270. func appendBaseEnv(isTLS bool, env ...string) []string {
  271. preserveList := []string{
  272. // preserve remote test host
  273. "DOCKER_HOST",
  274. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  275. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  276. "SystemRoot",
  277. // testing help text requires the $PATH to dockerd is set
  278. "PATH",
  279. }
  280. if isTLS {
  281. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  282. }
  283. for _, key := range preserveList {
  284. if val := os.Getenv(key); val != "" {
  285. env = append(env, fmt.Sprintf("%s=%s", key, val))
  286. }
  287. }
  288. return env
  289. }
  290. func createTmpFile(c *check.C, content string) string {
  291. f, err := ioutil.TempFile("", "testfile")
  292. c.Assert(err, check.IsNil)
  293. filename := f.Name()
  294. err = ioutil.WriteFile(filename, []byte(content), 0644)
  295. c.Assert(err, check.IsNil)
  296. return filename
  297. }
  298. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  299. // Deprecated: use cli.WaitFor
  300. func waitRun(contID string) error {
  301. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  302. }
  303. // waitInspect will wait for the specified container to have the specified string
  304. // in the inspect output. It will wait until the specified timeout (in seconds)
  305. // is reached.
  306. // Deprecated: use cli.WaitFor
  307. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  308. return waitInspectWithArgs(name, expr, expected, timeout)
  309. }
  310. // Deprecated: use cli.WaitFor
  311. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  312. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  313. }
  314. func getInspectBody(c *check.C, version, id string) []byte {
  315. cli, err := NewEnvClientWithVersion(version)
  316. c.Assert(err, check.IsNil)
  317. defer cli.Close()
  318. _, body, err := cli.ContainerInspectWithRaw(context.Background(), id, false)
  319. c.Assert(err, check.IsNil)
  320. return body
  321. }
  322. // Run a long running idle task in a background container using the
  323. // system-specific default image and command.
  324. func runSleepingContainer(c *check.C, extraArgs ...string) string {
  325. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  326. }
  327. // Run a long running idle task in a background container using the specified
  328. // image and the system-specific command.
  329. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) string {
  330. args := []string{"run", "-d"}
  331. args = append(args, extraArgs...)
  332. args = append(args, image)
  333. args = append(args, sleepCommandForDaemonPlatform()...)
  334. return strings.TrimSpace(cli.DockerCmd(c, args...).Combined())
  335. }
  336. // minimalBaseImage returns the name of the minimal base image for the current
  337. // daemon platform.
  338. func minimalBaseImage() string {
  339. return testEnv.MinimalBaseImage()
  340. }
  341. func getGoroutineNumber() (int, error) {
  342. cli, err := client.NewEnvClient()
  343. if err != nil {
  344. return 0, err
  345. }
  346. defer cli.Close()
  347. info, err := cli.Info(context.Background())
  348. if err != nil {
  349. return 0, err
  350. }
  351. return info.NGoroutines, nil
  352. }
  353. func waitForGoroutines(expected int) error {
  354. t := time.After(30 * time.Second)
  355. for {
  356. select {
  357. case <-t:
  358. n, err := getGoroutineNumber()
  359. if err != nil {
  360. return err
  361. }
  362. if n > expected {
  363. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  364. }
  365. default:
  366. n, err := getGoroutineNumber()
  367. if err != nil {
  368. return err
  369. }
  370. if n <= expected {
  371. return nil
  372. }
  373. time.Sleep(200 * time.Millisecond)
  374. }
  375. }
  376. }
  377. // getErrorMessage returns the error message from an error API response
  378. func getErrorMessage(c *check.C, body []byte) string {
  379. var resp types.ErrorResponse
  380. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  381. return strings.TrimSpace(resp.Message)
  382. }
  383. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  384. after := time.After(timeout)
  385. for {
  386. v, comment := f(c)
  387. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  388. select {
  389. case <-after:
  390. assert = true
  391. default:
  392. }
  393. if assert {
  394. if comment != nil {
  395. args = append(args, comment)
  396. }
  397. c.Assert(v, checker, args...)
  398. return
  399. }
  400. time.Sleep(100 * time.Millisecond)
  401. }
  402. }
  403. type checkF func(*check.C) (interface{}, check.CommentInterface)
  404. type reducer func(...interface{}) interface{}
  405. func reducedCheck(r reducer, funcs ...checkF) checkF {
  406. return func(c *check.C) (interface{}, check.CommentInterface) {
  407. var values []interface{}
  408. var comments []string
  409. for _, f := range funcs {
  410. v, comment := f(c)
  411. values = append(values, v)
  412. if comment != nil {
  413. comments = append(comments, comment.CheckCommentString())
  414. }
  415. }
  416. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  417. }
  418. }
  419. func sumAsIntegers(vals ...interface{}) interface{} {
  420. var s int
  421. for _, v := range vals {
  422. s += v.(int)
  423. }
  424. return s
  425. }