docker_utils_test.go 14 KB

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