docker_utils_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/url"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/docker/docker/api/types"
  21. "github.com/docker/docker/integration-cli/checker"
  22. "github.com/docker/docker/integration-cli/daemon"
  23. "github.com/docker/docker/integration-cli/environment"
  24. "github.com/docker/docker/integration-cli/registry"
  25. "github.com/docker/docker/integration-cli/request"
  26. "github.com/docker/docker/pkg/stringutils"
  27. icmd "github.com/docker/docker/pkg/testutil/cmd"
  28. "github.com/go-check/check"
  29. )
  30. // Deprecated
  31. func daemonHost() string {
  32. return environment.DaemonHost()
  33. }
  34. // FIXME(vdemeester) move this away are remove ignoreNoSuchContainer bool
  35. func deleteContainer(ignoreNoSuchContainer bool, container ...string) error {
  36. result := icmd.RunCommand(dockerBinary, append([]string{"rm", "-fv"}, container...)...)
  37. if ignoreNoSuchContainer && result.Error != nil {
  38. // If the error is "No such container: ..." this means the container doesn't exists anymore,
  39. // we can safely ignore that one.
  40. if strings.Contains(result.Stderr(), "No such container") {
  41. return nil
  42. }
  43. }
  44. return result.Compare(icmd.Success)
  45. }
  46. func getAllContainers(c *check.C) string {
  47. result := icmd.RunCommand(dockerBinary, "ps", "-q", "-a")
  48. result.Assert(c, icmd.Success)
  49. return result.Combined()
  50. }
  51. // Deprecated
  52. func deleteAllContainers(c *check.C) {
  53. containers := getAllContainers(c)
  54. if containers != "" {
  55. err := deleteContainer(true, strings.Split(strings.TrimSpace(containers), "\n")...)
  56. c.Assert(err, checker.IsNil)
  57. }
  58. }
  59. func getPausedContainers(c *check.C) []string {
  60. result := icmd.RunCommand(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  61. result.Assert(c, icmd.Success)
  62. return strings.Fields(result.Combined())
  63. }
  64. func unpauseContainer(c *check.C, container string) {
  65. dockerCmd(c, "unpause", container)
  66. }
  67. // Deprecated
  68. func unpauseAllContainers(c *check.C) {
  69. containers := getPausedContainers(c)
  70. for _, value := range containers {
  71. unpauseContainer(c, value)
  72. }
  73. }
  74. func deleteImages(images ...string) error {
  75. args := []string{dockerBinary, "rmi", "-f"}
  76. return icmd.RunCmd(icmd.Cmd{Command: append(args, images...)}).Error
  77. }
  78. func dockerCmdWithError(args ...string) (string, int, error) {
  79. if err := validateArgs(args...); err != nil {
  80. return "", 0, err
  81. }
  82. result := icmd.RunCommand(dockerBinary, args...)
  83. if result.Error != nil {
  84. return result.Combined(), result.ExitCode, result.Compare(icmd.Success)
  85. }
  86. return result.Combined(), result.ExitCode, result.Error
  87. }
  88. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  89. if err := validateArgs(args...); err != nil {
  90. c.Fatalf(err.Error())
  91. }
  92. result := icmd.RunCommand(dockerBinary, args...)
  93. c.Assert(result, icmd.Matches, icmd.Success)
  94. return result.Stdout(), result.Stderr(), result.ExitCode
  95. }
  96. func dockerCmd(c *check.C, args ...string) (string, int) {
  97. if err := validateArgs(args...); err != nil {
  98. c.Fatalf(err.Error())
  99. }
  100. result := icmd.RunCommand(dockerBinary, args...)
  101. c.Assert(result, icmd.Matches, icmd.Success)
  102. return result.Combined(), result.ExitCode
  103. }
  104. func dockerCmdWithResult(args ...string) *icmd.Result {
  105. return icmd.RunCommand(dockerBinary, args...)
  106. }
  107. func binaryWithArgs(args ...string) []string {
  108. return append([]string{dockerBinary}, args...)
  109. }
  110. // execute a docker command with a timeout
  111. func dockerCmdWithTimeout(timeout time.Duration, args ...string) *icmd.Result {
  112. if err := validateArgs(args...); err != nil {
  113. return &icmd.Result{Error: err}
  114. }
  115. return icmd.RunCmd(icmd.Cmd{Command: binaryWithArgs(args...), Timeout: timeout})
  116. }
  117. // execute a docker command in a directory
  118. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  119. if err := validateArgs(args...); err != nil {
  120. c.Fatalf(err.Error())
  121. }
  122. result := icmd.RunCmd(icmd.Cmd{Command: binaryWithArgs(args...), Dir: path})
  123. return result.Combined(), result.ExitCode, result.Error
  124. }
  125. // validateArgs is a checker to ensure tests are not running commands which are
  126. // not supported on platforms. Specifically on Windows this is 'busybox top'.
  127. func validateArgs(args ...string) error {
  128. if testEnv.DaemonPlatform() != "windows" {
  129. return nil
  130. }
  131. foundBusybox := -1
  132. for key, value := range args {
  133. if strings.ToLower(value) == "busybox" {
  134. foundBusybox = key
  135. }
  136. if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
  137. return errors.New("cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
  138. }
  139. }
  140. return nil
  141. }
  142. func findContainerIP(c *check.C, id string, network string) string {
  143. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  144. return strings.Trim(out, " \r\n'")
  145. }
  146. func getContainerCount(c *check.C) int {
  147. const containers = "Containers:"
  148. result := icmd.RunCommand(dockerBinary, "info")
  149. result.Assert(c, icmd.Success)
  150. lines := strings.Split(result.Combined(), "\n")
  151. for _, line := range lines {
  152. if strings.Contains(line, containers) {
  153. output := strings.TrimSpace(line)
  154. output = strings.TrimLeft(output, containers)
  155. output = strings.Trim(output, " ")
  156. containerCount, err := strconv.Atoi(output)
  157. c.Assert(err, checker.IsNil)
  158. return containerCount
  159. }
  160. }
  161. return 0
  162. }
  163. // FakeContext creates directories that can be used as a build context
  164. type FakeContext struct {
  165. Dir string
  166. }
  167. // Add a file at a path, creating directories where necessary
  168. func (f *FakeContext) Add(file, content string) error {
  169. return f.addFile(file, []byte(content))
  170. }
  171. func (f *FakeContext) addFile(file string, content []byte) error {
  172. fp := filepath.Join(f.Dir, filepath.FromSlash(file))
  173. dirpath := filepath.Dir(fp)
  174. if dirpath != "." {
  175. if err := os.MkdirAll(dirpath, 0755); err != nil {
  176. return err
  177. }
  178. }
  179. return ioutil.WriteFile(fp, content, 0644)
  180. }
  181. // Delete a file at a path
  182. func (f *FakeContext) Delete(file string) error {
  183. fp := filepath.Join(f.Dir, filepath.FromSlash(file))
  184. return os.RemoveAll(fp)
  185. }
  186. // Close deletes the context
  187. func (f *FakeContext) Close() error {
  188. return os.RemoveAll(f.Dir)
  189. }
  190. func fakeContextFromNewTempDir(c *check.C) *FakeContext {
  191. tmp, err := ioutil.TempDir("", "fake-context")
  192. c.Assert(err, checker.IsNil)
  193. if err := os.Chmod(tmp, 0755); err != nil {
  194. c.Fatal(err)
  195. }
  196. return fakeContextFromDir(tmp)
  197. }
  198. func fakeContextFromDir(dir string) *FakeContext {
  199. return &FakeContext{dir}
  200. }
  201. func fakeContextWithFiles(c *check.C, files map[string]string) *FakeContext {
  202. ctx := fakeContextFromNewTempDir(c)
  203. for file, content := range files {
  204. if err := ctx.Add(file, content); err != nil {
  205. ctx.Close()
  206. c.Fatal(err)
  207. }
  208. }
  209. return ctx
  210. }
  211. func fakeContextAddDockerfile(c *check.C, ctx *FakeContext, dockerfile string) {
  212. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  213. ctx.Close()
  214. c.Fatal(err)
  215. }
  216. }
  217. func fakeContext(c *check.C, dockerfile string, files map[string]string) *FakeContext {
  218. ctx := fakeContextWithFiles(c, files)
  219. fakeContextAddDockerfile(c, ctx, dockerfile)
  220. return ctx
  221. }
  222. // FakeStorage is a static file server. It might be running locally or remotely
  223. // on test host.
  224. type FakeStorage interface {
  225. Close() error
  226. URL() string
  227. CtxDir() string
  228. }
  229. func fakeBinaryStorage(c *check.C, archives map[string]*bytes.Buffer) FakeStorage {
  230. ctx := fakeContextFromNewTempDir(c)
  231. for name, content := range archives {
  232. if err := ctx.addFile(name, content.Bytes()); err != nil {
  233. c.Fatal(err)
  234. }
  235. }
  236. return fakeStorageWithContext(c, ctx)
  237. }
  238. // fakeStorage returns either a local or remote (at daemon machine) file server
  239. func fakeStorage(c *check.C, files map[string]string) FakeStorage {
  240. ctx := fakeContextWithFiles(c, files)
  241. return fakeStorageWithContext(c, ctx)
  242. }
  243. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  244. func fakeStorageWithContext(c *check.C, ctx *FakeContext) FakeStorage {
  245. if testEnv.LocalDaemon() {
  246. return newLocalFakeStorage(c, ctx)
  247. }
  248. return newRemoteFileServer(c, ctx)
  249. }
  250. // localFileStorage is a file storage on the running machine
  251. type localFileStorage struct {
  252. *FakeContext
  253. *httptest.Server
  254. }
  255. func (s *localFileStorage) URL() string {
  256. return s.Server.URL
  257. }
  258. func (s *localFileStorage) CtxDir() string {
  259. return s.FakeContext.Dir
  260. }
  261. func (s *localFileStorage) Close() error {
  262. defer s.Server.Close()
  263. return s.FakeContext.Close()
  264. }
  265. func newLocalFakeStorage(c *check.C, ctx *FakeContext) *localFileStorage {
  266. handler := http.FileServer(http.Dir(ctx.Dir))
  267. server := httptest.NewServer(handler)
  268. return &localFileStorage{
  269. FakeContext: ctx,
  270. Server: server,
  271. }
  272. }
  273. // remoteFileServer is a containerized static file server started on the remote
  274. // testing machine to be used in URL-accepting docker build functionality.
  275. type remoteFileServer struct {
  276. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  277. container string
  278. image string
  279. ctx *FakeContext
  280. }
  281. func (f *remoteFileServer) URL() string {
  282. u := url.URL{
  283. Scheme: "http",
  284. Host: f.host}
  285. return u.String()
  286. }
  287. func (f *remoteFileServer) CtxDir() string {
  288. return f.ctx.Dir
  289. }
  290. func (f *remoteFileServer) Close() error {
  291. defer func() {
  292. if f.ctx != nil {
  293. f.ctx.Close()
  294. }
  295. if f.image != "" {
  296. deleteImages(f.image)
  297. }
  298. }()
  299. if f.container == "" {
  300. return nil
  301. }
  302. return deleteContainer(false, f.container)
  303. }
  304. func newRemoteFileServer(c *check.C, ctx *FakeContext) *remoteFileServer {
  305. var (
  306. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  307. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  308. )
  309. ensureHTTPServerImage(c)
  310. // Build the image
  311. fakeContextAddDockerfile(c, ctx, `FROM httpserver
  312. COPY . /static`)
  313. buildImageSuccessfully(c, image, withoutCache, withExternalBuildContext(ctx))
  314. // Start the container
  315. dockerCmd(c, "run", "-d", "-P", "--name", container, image)
  316. // Find out the system assigned port
  317. out, _ := dockerCmd(c, "port", container, "80/tcp")
  318. fileserverHostPort := strings.Trim(out, "\n")
  319. _, port, err := net.SplitHostPort(fileserverHostPort)
  320. if err != nil {
  321. c.Fatalf("unable to parse file server host:port: %v", err)
  322. }
  323. dockerHostURL, err := url.Parse(daemonHost())
  324. if err != nil {
  325. c.Fatalf("unable to parse daemon host URL: %v", err)
  326. }
  327. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  328. if err != nil {
  329. c.Fatalf("unable to parse docker daemon host:port: %v", err)
  330. }
  331. return &remoteFileServer{
  332. container: container,
  333. image: image,
  334. host: fmt.Sprintf("%s:%s", host, port),
  335. ctx: ctx}
  336. }
  337. func inspectFieldAndUnmarshall(c *check.C, name, field string, output interface{}) {
  338. str := inspectFieldJSON(c, name, field)
  339. err := json.Unmarshal([]byte(str), output)
  340. if c != nil {
  341. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  342. }
  343. }
  344. func inspectFilter(name, filter string) (string, error) {
  345. format := fmt.Sprintf("{{%s}}", filter)
  346. result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name)
  347. if result.Error != nil || result.ExitCode != 0 {
  348. return "", fmt.Errorf("failed to inspect %s: %s", name, result.Combined())
  349. }
  350. return strings.TrimSpace(result.Combined()), nil
  351. }
  352. func inspectFieldWithError(name, field string) (string, error) {
  353. return inspectFilter(name, fmt.Sprintf(".%s", field))
  354. }
  355. func inspectField(c *check.C, name, field string) string {
  356. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  357. if c != nil {
  358. c.Assert(err, check.IsNil)
  359. }
  360. return out
  361. }
  362. func inspectFieldJSON(c *check.C, name, field string) string {
  363. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  364. if c != nil {
  365. c.Assert(err, check.IsNil)
  366. }
  367. return out
  368. }
  369. func inspectFieldMap(c *check.C, name, path, field string) string {
  370. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  371. if c != nil {
  372. c.Assert(err, check.IsNil)
  373. }
  374. return out
  375. }
  376. func inspectMountSourceField(name, destination string) (string, error) {
  377. m, err := inspectMountPoint(name, destination)
  378. if err != nil {
  379. return "", err
  380. }
  381. return m.Source, nil
  382. }
  383. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  384. out, err := inspectFilter(name, "json .Mounts")
  385. if err != nil {
  386. return types.MountPoint{}, err
  387. }
  388. return inspectMountPointJSON(out, destination)
  389. }
  390. var errMountNotFound = errors.New("mount point not found")
  391. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  392. var mp []types.MountPoint
  393. if err := json.Unmarshal([]byte(j), &mp); err != nil {
  394. return types.MountPoint{}, err
  395. }
  396. var m *types.MountPoint
  397. for _, c := range mp {
  398. if c.Destination == destination {
  399. m = &c
  400. break
  401. }
  402. }
  403. if m == nil {
  404. return types.MountPoint{}, errMountNotFound
  405. }
  406. return *m, nil
  407. }
  408. func inspectImage(c *check.C, name, filter string) string {
  409. args := []string{"inspect", "--type", "image"}
  410. if filter != "" {
  411. format := fmt.Sprintf("{{%s}}", filter)
  412. args = append(args, "-f", format)
  413. }
  414. args = append(args, name)
  415. result := icmd.RunCommand(dockerBinary, args...)
  416. result.Assert(c, icmd.Success)
  417. return strings.TrimSpace(result.Combined())
  418. }
  419. func getIDByName(c *check.C, name string) string {
  420. id, err := inspectFieldWithError(name, "Id")
  421. c.Assert(err, checker.IsNil)
  422. return id
  423. }
  424. func buildImageSuccessfully(c *check.C, name string, cmdOperators ...func(*icmd.Cmd) func()) {
  425. buildImage(name, cmdOperators...).Assert(c, icmd.Success)
  426. }
  427. func buildImage(name string, cmdOperators ...func(*icmd.Cmd) func()) *icmd.Result {
  428. cmd := icmd.Command(dockerBinary, "build", "-t", name)
  429. for _, op := range cmdOperators {
  430. deferFn := op(&cmd)
  431. if deferFn != nil {
  432. defer deferFn()
  433. }
  434. }
  435. return icmd.RunCmd(cmd)
  436. }
  437. func withBuildContextPath(path string) func(*icmd.Cmd) func() {
  438. return func(cmd *icmd.Cmd) func() {
  439. cmd.Command = append(cmd.Command, path)
  440. return nil
  441. }
  442. }
  443. func withExternalBuildContext(ctx *FakeContext) func(*icmd.Cmd) func() {
  444. return func(cmd *icmd.Cmd) func() {
  445. cmd.Dir = ctx.Dir
  446. cmd.Command = append(cmd.Command, ".")
  447. return nil
  448. }
  449. }
  450. func withBuildContext(c *check.C, contextOperators ...func(*FakeContext) error) func(*icmd.Cmd) func() {
  451. ctx := fakeContextFromNewTempDir(c)
  452. for _, op := range contextOperators {
  453. if err := op(ctx); err != nil {
  454. c.Fatal(err)
  455. }
  456. }
  457. return func(cmd *icmd.Cmd) func() {
  458. cmd.Dir = ctx.Dir
  459. cmd.Command = append(cmd.Command, ".")
  460. return closeBuildContext(c, ctx)
  461. }
  462. }
  463. func withBuildFlags(flags ...string) func(*icmd.Cmd) func() {
  464. return func(cmd *icmd.Cmd) func() {
  465. cmd.Command = append(cmd.Command, flags...)
  466. return nil
  467. }
  468. }
  469. func withoutCache(cmd *icmd.Cmd) func() {
  470. cmd.Command = append(cmd.Command, "--no-cache")
  471. return nil
  472. }
  473. func withFile(name, content string) func(*FakeContext) error {
  474. return func(ctx *FakeContext) error {
  475. return ctx.Add(name, content)
  476. }
  477. }
  478. func closeBuildContext(c *check.C, ctx *FakeContext) func() {
  479. return func() {
  480. if err := ctx.Close(); err != nil {
  481. c.Fatal(err)
  482. }
  483. }
  484. }
  485. func withDockerfile(dockerfile string) func(*icmd.Cmd) func() {
  486. return func(cmd *icmd.Cmd) func() {
  487. cmd.Command = append(cmd.Command, "-")
  488. cmd.Stdin = strings.NewReader(dockerfile)
  489. return nil
  490. }
  491. }
  492. func trustedBuild(cmd *icmd.Cmd) func() {
  493. trustedCmd(cmd)
  494. return nil
  495. }
  496. func withEnvironmentVariales(envs ...string) func(cmd *icmd.Cmd) func() {
  497. return func(cmd *icmd.Cmd) func() {
  498. cmd.Env = envs
  499. return nil
  500. }
  501. }
  502. type gitServer interface {
  503. URL() string
  504. Close() error
  505. }
  506. type localGitServer struct {
  507. *httptest.Server
  508. }
  509. func (r *localGitServer) Close() error {
  510. r.Server.Close()
  511. return nil
  512. }
  513. func (r *localGitServer) URL() string {
  514. return r.Server.URL
  515. }
  516. type fakeGit struct {
  517. root string
  518. server gitServer
  519. RepoURL string
  520. }
  521. func (g *fakeGit) Close() {
  522. g.server.Close()
  523. os.RemoveAll(g.root)
  524. }
  525. func newFakeGit(c *check.C, name string, files map[string]string, enforceLocalServer bool) *fakeGit {
  526. ctx := fakeContextWithFiles(c, files)
  527. defer ctx.Close()
  528. curdir, err := os.Getwd()
  529. if err != nil {
  530. c.Fatal(err)
  531. }
  532. defer os.Chdir(curdir)
  533. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  534. c.Fatalf("error trying to init repo: %s (%s)", err, output)
  535. }
  536. err = os.Chdir(ctx.Dir)
  537. if err != nil {
  538. c.Fatal(err)
  539. }
  540. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  541. c.Fatalf("error trying to set 'user.name': %s (%s)", err, output)
  542. }
  543. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  544. c.Fatalf("error trying to set 'user.email': %s (%s)", err, output)
  545. }
  546. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  547. c.Fatalf("error trying to add files to repo: %s (%s)", err, output)
  548. }
  549. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  550. c.Fatalf("error trying to commit to repo: %s (%s)", err, output)
  551. }
  552. root, err := ioutil.TempDir("", "docker-test-git-repo")
  553. if err != nil {
  554. c.Fatal(err)
  555. }
  556. repoPath := filepath.Join(root, name+".git")
  557. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  558. os.RemoveAll(root)
  559. c.Fatalf("error trying to clone --bare: %s (%s)", err, output)
  560. }
  561. err = os.Chdir(repoPath)
  562. if err != nil {
  563. os.RemoveAll(root)
  564. c.Fatal(err)
  565. }
  566. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  567. os.RemoveAll(root)
  568. c.Fatalf("error trying to git update-server-info: %s (%s)", err, output)
  569. }
  570. err = os.Chdir(curdir)
  571. if err != nil {
  572. os.RemoveAll(root)
  573. c.Fatal(err)
  574. }
  575. var server gitServer
  576. if !enforceLocalServer {
  577. // use fakeStorage server, which might be local or remote (at test daemon)
  578. server = fakeStorageWithContext(c, fakeContextFromDir(root))
  579. } else {
  580. // always start a local http server on CLI test machine
  581. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  582. server = &localGitServer{httpServer}
  583. }
  584. return &fakeGit{
  585. root: root,
  586. server: server,
  587. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  588. }
  589. }
  590. // Write `content` to the file at path `dst`, creating it if necessary,
  591. // as well as any missing directories.
  592. // The file is truncated if it already exists.
  593. // Fail the test when error occurs.
  594. func writeFile(dst, content string, c *check.C) {
  595. // Create subdirectories if necessary
  596. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  597. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  598. c.Assert(err, check.IsNil)
  599. defer f.Close()
  600. // Write content (truncate if it exists)
  601. _, err = io.Copy(f, strings.NewReader(content))
  602. c.Assert(err, check.IsNil)
  603. }
  604. // Return the contents of file at path `src`.
  605. // Fail the test when error occurs.
  606. func readFile(src string, c *check.C) (content string) {
  607. data, err := ioutil.ReadFile(src)
  608. c.Assert(err, check.IsNil)
  609. return string(data)
  610. }
  611. func containerStorageFile(containerID, basename string) string {
  612. return filepath.Join(testEnv.ContainerStoragePath(), containerID, basename)
  613. }
  614. // docker commands that use this function must be run with the '-d' switch.
  615. func runCommandAndReadContainerFile(c *check.C, filename string, command string, args ...string) []byte {
  616. result := icmd.RunCommand(command, args...)
  617. result.Assert(c, icmd.Success)
  618. contID := strings.TrimSpace(result.Combined())
  619. if err := waitRun(contID); err != nil {
  620. c.Fatalf("%v: %q", contID, err)
  621. }
  622. return readContainerFile(c, contID, filename)
  623. }
  624. func readContainerFile(c *check.C, containerID, filename string) []byte {
  625. f, err := os.Open(containerStorageFile(containerID, filename))
  626. c.Assert(err, checker.IsNil)
  627. defer f.Close()
  628. content, err := ioutil.ReadAll(f)
  629. c.Assert(err, checker.IsNil)
  630. return content
  631. }
  632. func readContainerFileWithExec(c *check.C, containerID, filename string) []byte {
  633. result := icmd.RunCommand(dockerBinary, "exec", containerID, "cat", filename)
  634. result.Assert(c, icmd.Success)
  635. return []byte(result.Combined())
  636. }
  637. // daemonTime provides the current time on the daemon host
  638. func daemonTime(c *check.C) time.Time {
  639. if testEnv.LocalDaemon() {
  640. return time.Now()
  641. }
  642. status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
  643. c.Assert(err, check.IsNil)
  644. c.Assert(status, check.Equals, http.StatusOK)
  645. type infoJSON struct {
  646. SystemTime string
  647. }
  648. var info infoJSON
  649. err = json.Unmarshal(body, &info)
  650. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  651. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  652. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  653. return dt
  654. }
  655. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  656. // It return the time formatted how the client sends timestamps to the server.
  657. func daemonUnixTime(c *check.C) string {
  658. return parseEventTime(daemonTime(c))
  659. }
  660. func parseEventTime(t time.Time) string {
  661. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  662. }
  663. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *registry.V2 {
  664. reg, err := registry.NewV2(schema1, auth, tokenURL, privateRegistryURL)
  665. c.Assert(err, check.IsNil)
  666. // Wait for registry to be ready to serve requests.
  667. for i := 0; i != 50; i++ {
  668. if err = reg.Ping(); err == nil {
  669. break
  670. }
  671. time.Sleep(100 * time.Millisecond)
  672. }
  673. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  674. return reg
  675. }
  676. func setupNotary(c *check.C) *testNotary {
  677. ts, err := newTestNotary(c)
  678. c.Assert(err, check.IsNil)
  679. return ts
  680. }
  681. // appendBaseEnv appends the minimum set of environment variables to exec the
  682. // docker cli binary for testing with correct configuration to the given env
  683. // list.
  684. func appendBaseEnv(isTLS bool, env ...string) []string {
  685. preserveList := []string{
  686. // preserve remote test host
  687. "DOCKER_HOST",
  688. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  689. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  690. "SystemRoot",
  691. // testing help text requires the $PATH to dockerd is set
  692. "PATH",
  693. }
  694. if isTLS {
  695. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  696. }
  697. for _, key := range preserveList {
  698. if val := os.Getenv(key); val != "" {
  699. env = append(env, fmt.Sprintf("%s=%s", key, val))
  700. }
  701. }
  702. return env
  703. }
  704. func createTmpFile(c *check.C, content string) string {
  705. f, err := ioutil.TempFile("", "testfile")
  706. c.Assert(err, check.IsNil)
  707. filename := f.Name()
  708. err = ioutil.WriteFile(filename, []byte(content), 0644)
  709. c.Assert(err, check.IsNil)
  710. return filename
  711. }
  712. func waitForContainer(contID string, args ...string) error {
  713. args = append([]string{dockerBinary, "run", "--name", contID}, args...)
  714. result := icmd.RunCmd(icmd.Cmd{Command: args})
  715. if result.Error != nil {
  716. return result.Error
  717. }
  718. return waitRun(contID)
  719. }
  720. // waitRestart will wait for the specified container to restart once
  721. func waitRestart(contID string, duration time.Duration) error {
  722. return waitInspect(contID, "{{.RestartCount}}", "1", duration)
  723. }
  724. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  725. func waitRun(contID string) error {
  726. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  727. }
  728. // waitExited will wait for the specified container to state exit, subject
  729. // to a maximum time limit in seconds supplied by the caller
  730. func waitExited(contID string, duration time.Duration) error {
  731. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  732. }
  733. // waitInspect will wait for the specified container to have the specified string
  734. // in the inspect output. It will wait until the specified timeout (in seconds)
  735. // is reached.
  736. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  737. return waitInspectWithArgs(name, expr, expected, timeout)
  738. }
  739. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  740. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  741. }
  742. func getInspectBody(c *check.C, version, id string) []byte {
  743. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  744. status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
  745. c.Assert(err, check.IsNil)
  746. c.Assert(status, check.Equals, http.StatusOK)
  747. return body
  748. }
  749. // Run a long running idle task in a background container using the
  750. // system-specific default image and command.
  751. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  752. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  753. }
  754. // Run a long running idle task in a background container using the specified
  755. // image and the system-specific command.
  756. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  757. args := []string{"run", "-d"}
  758. args = append(args, extraArgs...)
  759. args = append(args, image)
  760. args = append(args, sleepCommandForDaemonPlatform()...)
  761. return dockerCmd(c, args...)
  762. }
  763. // minimalBaseImage returns the name of the minimal base image for the current
  764. // daemon platform.
  765. func minimalBaseImage() string {
  766. return testEnv.MinimalBaseImage()
  767. }
  768. func getGoroutineNumber() (int, error) {
  769. i := struct {
  770. NGoroutines int
  771. }{}
  772. status, b, err := request.SockRequest("GET", "/info", nil, daemonHost())
  773. if err != nil {
  774. return 0, err
  775. }
  776. if status != http.StatusOK {
  777. return 0, fmt.Errorf("http status code: %d", status)
  778. }
  779. if err := json.Unmarshal(b, &i); err != nil {
  780. return 0, err
  781. }
  782. return i.NGoroutines, nil
  783. }
  784. func waitForGoroutines(expected int) error {
  785. t := time.After(30 * time.Second)
  786. for {
  787. select {
  788. case <-t:
  789. n, err := getGoroutineNumber()
  790. if err != nil {
  791. return err
  792. }
  793. if n > expected {
  794. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  795. }
  796. default:
  797. n, err := getGoroutineNumber()
  798. if err != nil {
  799. return err
  800. }
  801. if n <= expected {
  802. return nil
  803. }
  804. time.Sleep(200 * time.Millisecond)
  805. }
  806. }
  807. }
  808. // getErrorMessage returns the error message from an error API response
  809. func getErrorMessage(c *check.C, body []byte) string {
  810. var resp types.ErrorResponse
  811. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  812. return strings.TrimSpace(resp.Message)
  813. }
  814. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  815. after := time.After(timeout)
  816. for {
  817. v, comment := f(c)
  818. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  819. select {
  820. case <-after:
  821. assert = true
  822. default:
  823. }
  824. if assert {
  825. if comment != nil {
  826. args = append(args, comment)
  827. }
  828. c.Assert(v, checker, args...)
  829. return
  830. }
  831. time.Sleep(100 * time.Millisecond)
  832. }
  833. }
  834. type checkF func(*check.C) (interface{}, check.CommentInterface)
  835. type reducer func(...interface{}) interface{}
  836. func reducedCheck(r reducer, funcs ...checkF) checkF {
  837. return func(c *check.C) (interface{}, check.CommentInterface) {
  838. var values []interface{}
  839. var comments []string
  840. for _, f := range funcs {
  841. v, comment := f(c)
  842. values = append(values, v)
  843. if comment != nil {
  844. comments = append(comments, comment.CheckCommentString())
  845. }
  846. }
  847. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  848. }
  849. }
  850. func sumAsIntegers(vals ...interface{}) interface{} {
  851. var s int
  852. for _, v := range vals {
  853. s += v.(int)
  854. }
  855. return s
  856. }