docker_utils_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/http/httptest"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/integration-cli/checker"
  19. "github.com/docker/docker/integration-cli/cli"
  20. "github.com/docker/docker/integration-cli/cli/build/fakecontext"
  21. "github.com/docker/docker/integration-cli/cli/build/fakestorage"
  22. "github.com/docker/docker/integration-cli/daemon"
  23. "github.com/docker/docker/integration-cli/registry"
  24. "github.com/docker/docker/integration-cli/request"
  25. icmd "github.com/docker/docker/pkg/testutil/cmd"
  26. "github.com/go-check/check"
  27. )
  28. // Deprecated
  29. func daemonHost() string {
  30. return request.DaemonHost()
  31. }
  32. func deleteImages(images ...string) error {
  33. args := []string{dockerBinary, "rmi", "-f"}
  34. return icmd.RunCmd(icmd.Cmd{Command: append(args, images...)}).Error
  35. }
  36. // Deprecated: use cli.Docker or cli.DockerCmd
  37. func dockerCmdWithError(args ...string) (string, int, error) {
  38. result := cli.Docker(cli.Args(args...))
  39. if result.Error != nil {
  40. return result.Combined(), result.ExitCode, result.Compare(icmd.Success)
  41. }
  42. return result.Combined(), result.ExitCode, result.Error
  43. }
  44. // Deprecated: use cli.Docker or cli.DockerCmd
  45. func dockerCmd(c *check.C, args ...string) (string, int) {
  46. result := cli.DockerCmd(c, args...)
  47. return result.Combined(), result.ExitCode
  48. }
  49. // Deprecated: use cli.Docker or cli.DockerCmd
  50. func dockerCmdWithResult(args ...string) *icmd.Result {
  51. return cli.Docker(cli.Args(args...))
  52. }
  53. func findContainerIP(c *check.C, id string, network string) string {
  54. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  55. return strings.Trim(out, " \r\n'")
  56. }
  57. func getContainerCount(c *check.C) int {
  58. const containers = "Containers:"
  59. result := icmd.RunCommand(dockerBinary, "info")
  60. result.Assert(c, icmd.Success)
  61. lines := strings.Split(result.Combined(), "\n")
  62. for _, line := range lines {
  63. if strings.Contains(line, containers) {
  64. output := strings.TrimSpace(line)
  65. output = strings.TrimLeft(output, containers)
  66. output = strings.Trim(output, " ")
  67. containerCount, err := strconv.Atoi(output)
  68. c.Assert(err, checker.IsNil)
  69. return containerCount
  70. }
  71. }
  72. return 0
  73. }
  74. func inspectFieldAndUnmarshall(c *check.C, name, field string, output interface{}) {
  75. str := inspectFieldJSON(c, name, field)
  76. err := json.Unmarshal([]byte(str), output)
  77. if c != nil {
  78. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  79. }
  80. }
  81. // Deprecated: use cli.Inspect
  82. func inspectFilter(name, filter string) (string, error) {
  83. format := fmt.Sprintf("{{%s}}", filter)
  84. result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name)
  85. if result.Error != nil || result.ExitCode != 0 {
  86. return "", fmt.Errorf("failed to inspect %s: %s", name, result.Combined())
  87. }
  88. return strings.TrimSpace(result.Combined()), nil
  89. }
  90. // Deprecated: use cli.Inspect
  91. func inspectFieldWithError(name, field string) (string, error) {
  92. return inspectFilter(name, fmt.Sprintf(".%s", field))
  93. }
  94. // Deprecated: use cli.Inspect
  95. func inspectField(c *check.C, name, field string) string {
  96. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  97. if c != nil {
  98. c.Assert(err, check.IsNil)
  99. }
  100. return out
  101. }
  102. // Deprecated: use cli.Inspect
  103. func inspectFieldJSON(c *check.C, name, field string) string {
  104. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  105. if c != nil {
  106. c.Assert(err, check.IsNil)
  107. }
  108. return out
  109. }
  110. // Deprecated: use cli.Inspect
  111. func inspectFieldMap(c *check.C, name, path, field string) string {
  112. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  113. if c != nil {
  114. c.Assert(err, check.IsNil)
  115. }
  116. return out
  117. }
  118. // Deprecated: use cli.Inspect
  119. func inspectMountSourceField(name, destination string) (string, error) {
  120. m, err := inspectMountPoint(name, destination)
  121. if err != nil {
  122. return "", err
  123. }
  124. return m.Source, nil
  125. }
  126. // Deprecated: use cli.Inspect
  127. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  128. out, err := inspectFilter(name, "json .Mounts")
  129. if err != nil {
  130. return types.MountPoint{}, err
  131. }
  132. return inspectMountPointJSON(out, destination)
  133. }
  134. var errMountNotFound = errors.New("mount point not found")
  135. // Deprecated: use cli.Inspect
  136. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  137. var mp []types.MountPoint
  138. if err := json.Unmarshal([]byte(j), &mp); err != nil {
  139. return types.MountPoint{}, err
  140. }
  141. var m *types.MountPoint
  142. for _, c := range mp {
  143. if c.Destination == destination {
  144. m = &c
  145. break
  146. }
  147. }
  148. if m == nil {
  149. return types.MountPoint{}, errMountNotFound
  150. }
  151. return *m, nil
  152. }
  153. // Deprecated: use cli.Inspect
  154. func inspectImage(c *check.C, name, filter string) string {
  155. args := []string{"inspect", "--type", "image"}
  156. if filter != "" {
  157. format := fmt.Sprintf("{{%s}}", filter)
  158. args = append(args, "-f", format)
  159. }
  160. args = append(args, name)
  161. result := icmd.RunCommand(dockerBinary, args...)
  162. result.Assert(c, icmd.Success)
  163. return strings.TrimSpace(result.Combined())
  164. }
  165. func getIDByName(c *check.C, name string) string {
  166. id, err := inspectFieldWithError(name, "Id")
  167. c.Assert(err, checker.IsNil)
  168. return id
  169. }
  170. // Deprecated: use cli.Build
  171. func buildImageSuccessfully(c *check.C, name string, cmdOperators ...cli.CmdOperator) {
  172. buildImage(name, cmdOperators...).Assert(c, icmd.Success)
  173. }
  174. // Deprecated: use cli.Build
  175. func buildImage(name string, cmdOperators ...cli.CmdOperator) *icmd.Result {
  176. return cli.Docker(cli.Build(name), cmdOperators...)
  177. }
  178. // Deprecated: use trustedcmd
  179. func trustedBuild(cmd *icmd.Cmd) func() {
  180. trustedCmd(cmd)
  181. return nil
  182. }
  183. type gitServer interface {
  184. URL() string
  185. Close() error
  186. }
  187. type localGitServer struct {
  188. *httptest.Server
  189. }
  190. func (r *localGitServer) Close() error {
  191. r.Server.Close()
  192. return nil
  193. }
  194. func (r *localGitServer) URL() string {
  195. return r.Server.URL
  196. }
  197. type fakeGit struct {
  198. root string
  199. server gitServer
  200. RepoURL string
  201. }
  202. func (g *fakeGit) Close() {
  203. g.server.Close()
  204. os.RemoveAll(g.root)
  205. }
  206. func newFakeGit(c *check.C, name string, files map[string]string, enforceLocalServer bool) *fakeGit {
  207. ctx := fakecontext.New(c, "", fakecontext.WithFiles(files))
  208. defer ctx.Close()
  209. curdir, err := os.Getwd()
  210. if err != nil {
  211. c.Fatal(err)
  212. }
  213. defer os.Chdir(curdir)
  214. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  215. c.Fatalf("error trying to init repo: %s (%s)", err, output)
  216. }
  217. err = os.Chdir(ctx.Dir)
  218. if err != nil {
  219. c.Fatal(err)
  220. }
  221. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  222. c.Fatalf("error trying to set 'user.name': %s (%s)", err, output)
  223. }
  224. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  225. c.Fatalf("error trying to set 'user.email': %s (%s)", err, output)
  226. }
  227. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  228. c.Fatalf("error trying to add files to repo: %s (%s)", err, output)
  229. }
  230. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  231. c.Fatalf("error trying to commit to repo: %s (%s)", err, output)
  232. }
  233. root, err := ioutil.TempDir("", "docker-test-git-repo")
  234. if err != nil {
  235. c.Fatal(err)
  236. }
  237. repoPath := filepath.Join(root, name+".git")
  238. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  239. os.RemoveAll(root)
  240. c.Fatalf("error trying to clone --bare: %s (%s)", err, output)
  241. }
  242. err = os.Chdir(repoPath)
  243. if err != nil {
  244. os.RemoveAll(root)
  245. c.Fatal(err)
  246. }
  247. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  248. os.RemoveAll(root)
  249. c.Fatalf("error trying to git update-server-info: %s (%s)", err, output)
  250. }
  251. err = os.Chdir(curdir)
  252. if err != nil {
  253. os.RemoveAll(root)
  254. c.Fatal(err)
  255. }
  256. var server gitServer
  257. if !enforceLocalServer {
  258. // use fakeStorage server, which might be local or remote (at test daemon)
  259. server = fakestorage.New(c, root)
  260. } else {
  261. // always start a local http server on CLI test machine
  262. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  263. server = &localGitServer{httpServer}
  264. }
  265. return &fakeGit{
  266. root: root,
  267. server: server,
  268. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  269. }
  270. }
  271. // Write `content` to the file at path `dst`, creating it if necessary,
  272. // as well as any missing directories.
  273. // The file is truncated if it already exists.
  274. // Fail the test when error occurs.
  275. func writeFile(dst, content string, c *check.C) {
  276. // Create subdirectories if necessary
  277. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  278. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  279. c.Assert(err, check.IsNil)
  280. defer f.Close()
  281. // Write content (truncate if it exists)
  282. _, err = io.Copy(f, strings.NewReader(content))
  283. c.Assert(err, check.IsNil)
  284. }
  285. // Return the contents of file at path `src`.
  286. // Fail the test when error occurs.
  287. func readFile(src string, c *check.C) (content string) {
  288. data, err := ioutil.ReadFile(src)
  289. c.Assert(err, check.IsNil)
  290. return string(data)
  291. }
  292. func containerStorageFile(containerID, basename string) string {
  293. return filepath.Join(testEnv.ContainerStoragePath(), containerID, basename)
  294. }
  295. // docker commands that use this function must be run with the '-d' switch.
  296. func runCommandAndReadContainerFile(c *check.C, filename string, command string, args ...string) []byte {
  297. result := icmd.RunCommand(command, args...)
  298. result.Assert(c, icmd.Success)
  299. contID := strings.TrimSpace(result.Combined())
  300. if err := waitRun(contID); err != nil {
  301. c.Fatalf("%v: %q", contID, err)
  302. }
  303. return readContainerFile(c, contID, filename)
  304. }
  305. func readContainerFile(c *check.C, containerID, filename string) []byte {
  306. f, err := os.Open(containerStorageFile(containerID, filename))
  307. c.Assert(err, checker.IsNil)
  308. defer f.Close()
  309. content, err := ioutil.ReadAll(f)
  310. c.Assert(err, checker.IsNil)
  311. return content
  312. }
  313. func readContainerFileWithExec(c *check.C, containerID, filename string) []byte {
  314. result := icmd.RunCommand(dockerBinary, "exec", containerID, "cat", filename)
  315. result.Assert(c, icmd.Success)
  316. return []byte(result.Combined())
  317. }
  318. // daemonTime provides the current time on the daemon host
  319. func daemonTime(c *check.C) time.Time {
  320. if testEnv.LocalDaemon() {
  321. return time.Now()
  322. }
  323. status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
  324. c.Assert(err, check.IsNil)
  325. c.Assert(status, check.Equals, http.StatusOK)
  326. type infoJSON struct {
  327. SystemTime string
  328. }
  329. var info infoJSON
  330. err = json.Unmarshal(body, &info)
  331. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  332. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  333. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  334. return dt
  335. }
  336. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  337. // It return the time formatted how the client sends timestamps to the server.
  338. func daemonUnixTime(c *check.C) string {
  339. return parseEventTime(daemonTime(c))
  340. }
  341. func parseEventTime(t time.Time) string {
  342. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  343. }
  344. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *registry.V2 {
  345. reg, err := registry.NewV2(schema1, auth, tokenURL, privateRegistryURL)
  346. c.Assert(err, check.IsNil)
  347. // Wait for registry to be ready to serve requests.
  348. for i := 0; i != 50; i++ {
  349. if err = reg.Ping(); err == nil {
  350. break
  351. }
  352. time.Sleep(100 * time.Millisecond)
  353. }
  354. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  355. return reg
  356. }
  357. func setupNotary(c *check.C) *testNotary {
  358. ts, err := newTestNotary(c)
  359. c.Assert(err, check.IsNil)
  360. return ts
  361. }
  362. // appendBaseEnv appends the minimum set of environment variables to exec the
  363. // docker cli binary for testing with correct configuration to the given env
  364. // list.
  365. func appendBaseEnv(isTLS bool, env ...string) []string {
  366. preserveList := []string{
  367. // preserve remote test host
  368. "DOCKER_HOST",
  369. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  370. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  371. "SystemRoot",
  372. // testing help text requires the $PATH to dockerd is set
  373. "PATH",
  374. }
  375. if isTLS {
  376. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  377. }
  378. for _, key := range preserveList {
  379. if val := os.Getenv(key); val != "" {
  380. env = append(env, fmt.Sprintf("%s=%s", key, val))
  381. }
  382. }
  383. return env
  384. }
  385. func createTmpFile(c *check.C, content string) string {
  386. f, err := ioutil.TempFile("", "testfile")
  387. c.Assert(err, check.IsNil)
  388. filename := f.Name()
  389. err = ioutil.WriteFile(filename, []byte(content), 0644)
  390. c.Assert(err, check.IsNil)
  391. return filename
  392. }
  393. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  394. // Deprecated: use cli.WaitFor
  395. func waitRun(contID string) error {
  396. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  397. }
  398. // waitInspect will wait for the specified container to have the specified string
  399. // in the inspect output. It will wait until the specified timeout (in seconds)
  400. // is reached.
  401. // Deprecated: use cli.WaitFor
  402. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  403. return waitInspectWithArgs(name, expr, expected, timeout)
  404. }
  405. // Deprecated: use cli.WaitFor
  406. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  407. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  408. }
  409. func getInspectBody(c *check.C, version, id string) []byte {
  410. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  411. status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
  412. c.Assert(err, check.IsNil)
  413. c.Assert(status, check.Equals, http.StatusOK)
  414. return body
  415. }
  416. // Run a long running idle task in a background container using the
  417. // system-specific default image and command.
  418. func runSleepingContainer(c *check.C, extraArgs ...string) string {
  419. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  420. }
  421. // Run a long running idle task in a background container using the specified
  422. // image and the system-specific command.
  423. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) string {
  424. args := []string{"run", "-d"}
  425. args = append(args, extraArgs...)
  426. args = append(args, image)
  427. args = append(args, sleepCommandForDaemonPlatform()...)
  428. return cli.DockerCmd(c, args...).Combined()
  429. }
  430. // minimalBaseImage returns the name of the minimal base image for the current
  431. // daemon platform.
  432. func minimalBaseImage() string {
  433. return testEnv.MinimalBaseImage()
  434. }
  435. func getGoroutineNumber() (int, error) {
  436. i := struct {
  437. NGoroutines int
  438. }{}
  439. status, b, err := request.SockRequest("GET", "/info", nil, daemonHost())
  440. if err != nil {
  441. return 0, err
  442. }
  443. if status != http.StatusOK {
  444. return 0, fmt.Errorf("http status code: %d", status)
  445. }
  446. if err := json.Unmarshal(b, &i); err != nil {
  447. return 0, err
  448. }
  449. return i.NGoroutines, nil
  450. }
  451. func waitForGoroutines(expected int) error {
  452. t := time.After(30 * time.Second)
  453. for {
  454. select {
  455. case <-t:
  456. n, err := getGoroutineNumber()
  457. if err != nil {
  458. return err
  459. }
  460. if n > expected {
  461. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  462. }
  463. default:
  464. n, err := getGoroutineNumber()
  465. if err != nil {
  466. return err
  467. }
  468. if n <= expected {
  469. return nil
  470. }
  471. time.Sleep(200 * time.Millisecond)
  472. }
  473. }
  474. }
  475. // getErrorMessage returns the error message from an error API response
  476. func getErrorMessage(c *check.C, body []byte) string {
  477. var resp types.ErrorResponse
  478. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  479. return strings.TrimSpace(resp.Message)
  480. }
  481. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  482. after := time.After(timeout)
  483. for {
  484. v, comment := f(c)
  485. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  486. select {
  487. case <-after:
  488. assert = true
  489. default:
  490. }
  491. if assert {
  492. if comment != nil {
  493. args = append(args, comment)
  494. }
  495. c.Assert(v, checker, args...)
  496. return
  497. }
  498. time.Sleep(100 * time.Millisecond)
  499. }
  500. }
  501. type checkF func(*check.C) (interface{}, check.CommentInterface)
  502. type reducer func(...interface{}) interface{}
  503. func reducedCheck(r reducer, funcs ...checkF) checkF {
  504. return func(c *check.C) (interface{}, check.CommentInterface) {
  505. var values []interface{}
  506. var comments []string
  507. for _, f := range funcs {
  508. v, comment := f(c)
  509. values = append(values, v)
  510. if comment != nil {
  511. comments = append(comments, comment.CheckCommentString())
  512. }
  513. }
  514. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  515. }
  516. }
  517. func sumAsIntegers(vals ...interface{}) interface{} {
  518. var s int
  519. for _, v := range vals {
  520. s += v.(int)
  521. }
  522. return s
  523. }