docker_utils_test.go 14 KB

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