docker_cli_pull_local_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "github.com/docker/distribution"
  11. "github.com/docker/distribution/manifest"
  12. "github.com/docker/distribution/manifest/manifestlist"
  13. "github.com/docker/distribution/manifest/schema2"
  14. "github.com/docker/docker/integration-cli/checker"
  15. "github.com/docker/docker/integration-cli/cli/build"
  16. "github.com/go-check/check"
  17. "github.com/opencontainers/go-digest"
  18. "gotest.tools/assert"
  19. "gotest.tools/icmd"
  20. )
  21. // testPullImageWithAliases pulls a specific image tag and verifies that any aliases (i.e., other
  22. // tags for the same image) are not also pulled down.
  23. //
  24. // Ref: docker/docker#8141
  25. func testPullImageWithAliases(c *check.C) {
  26. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  27. var repos []string
  28. for _, tag := range []string{"recent", "fresh"} {
  29. repos = append(repos, fmt.Sprintf("%v:%v", repoName, tag))
  30. }
  31. // Tag and push the same image multiple times.
  32. for _, repo := range repos {
  33. dockerCmd(c, "tag", "busybox", repo)
  34. dockerCmd(c, "push", repo)
  35. }
  36. // Clear local images store.
  37. args := append([]string{"rmi"}, repos...)
  38. dockerCmd(c, args...)
  39. // Pull a single tag and verify it doesn't bring down all aliases.
  40. dockerCmd(c, "pull", repos[0])
  41. dockerCmd(c, "inspect", repos[0])
  42. for _, repo := range repos[1:] {
  43. _, _, err := dockerCmdWithError("inspect", repo)
  44. assert.ErrorContains(c, err, "", "Image %v shouldn't have been pulled down", repo)
  45. }
  46. }
  47. func (s *DockerRegistrySuite) TestPullImageWithAliases(c *check.C) {
  48. testPullImageWithAliases(c)
  49. }
  50. // testConcurrentPullWholeRepo pulls the same repo concurrently.
  51. func testConcurrentPullWholeRepo(c *check.C) {
  52. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  53. var repos []string
  54. for _, tag := range []string{"recent", "fresh", "todays"} {
  55. repo := fmt.Sprintf("%v:%v", repoName, tag)
  56. buildImageSuccessfully(c, repo, build.WithDockerfile(fmt.Sprintf(`
  57. FROM busybox
  58. ENTRYPOINT ["/bin/echo"]
  59. ENV FOO foo
  60. ENV BAR bar
  61. CMD echo %s
  62. `, repo)))
  63. dockerCmd(c, "push", repo)
  64. repos = append(repos, repo)
  65. }
  66. // Clear local images store.
  67. args := append([]string{"rmi"}, repos...)
  68. dockerCmd(c, args...)
  69. // Run multiple re-pulls concurrently
  70. results := make(chan error)
  71. numPulls := 3
  72. for i := 0; i != numPulls; i++ {
  73. go func() {
  74. result := icmd.RunCommand(dockerBinary, "pull", "-a", repoName)
  75. results <- result.Error
  76. }()
  77. }
  78. // These checks are separate from the loop above because the check
  79. // package is not goroutine-safe.
  80. for i := 0; i != numPulls; i++ {
  81. err := <-results
  82. assert.NilError(c, err, "concurrent pull failed with error: %v", err)
  83. }
  84. // Ensure all tags were pulled successfully
  85. for _, repo := range repos {
  86. dockerCmd(c, "inspect", repo)
  87. out, _ := dockerCmd(c, "run", "--rm", repo)
  88. assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo)
  89. }
  90. }
  91. func (s *DockerRegistrySuite) testConcurrentPullWholeRepo(c *check.C) {
  92. testConcurrentPullWholeRepo(c)
  93. }
  94. // testConcurrentFailingPull tries a concurrent pull that doesn't succeed.
  95. func testConcurrentFailingPull(c *check.C) {
  96. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  97. // Run multiple pulls concurrently
  98. results := make(chan error)
  99. numPulls := 3
  100. for i := 0; i != numPulls; i++ {
  101. go func() {
  102. result := icmd.RunCommand(dockerBinary, "pull", repoName+":asdfasdf")
  103. results <- result.Error
  104. }()
  105. }
  106. // These checks are separate from the loop above because the check
  107. // package is not goroutine-safe.
  108. for i := 0; i != numPulls; i++ {
  109. err := <-results
  110. assert.ErrorContains(c, err, "", "expected pull to fail")
  111. }
  112. }
  113. func (s *DockerRegistrySuite) testConcurrentFailingPull(c *check.C) {
  114. testConcurrentFailingPull(c)
  115. }
  116. // testConcurrentPullMultipleTags pulls multiple tags from the same repo
  117. // concurrently.
  118. func testConcurrentPullMultipleTags(c *check.C) {
  119. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  120. var repos []string
  121. for _, tag := range []string{"recent", "fresh", "todays"} {
  122. repo := fmt.Sprintf("%v:%v", repoName, tag)
  123. buildImageSuccessfully(c, repo, build.WithDockerfile(fmt.Sprintf(`
  124. FROM busybox
  125. ENTRYPOINT ["/bin/echo"]
  126. ENV FOO foo
  127. ENV BAR bar
  128. CMD echo %s
  129. `, repo)))
  130. dockerCmd(c, "push", repo)
  131. repos = append(repos, repo)
  132. }
  133. // Clear local images store.
  134. args := append([]string{"rmi"}, repos...)
  135. dockerCmd(c, args...)
  136. // Re-pull individual tags, in parallel
  137. results := make(chan error)
  138. for _, repo := range repos {
  139. go func(repo string) {
  140. result := icmd.RunCommand(dockerBinary, "pull", repo)
  141. results <- result.Error
  142. }(repo)
  143. }
  144. // These checks are separate from the loop above because the check
  145. // package is not goroutine-safe.
  146. for range repos {
  147. err := <-results
  148. assert.NilError(c, err, "concurrent pull failed with error: %v", err)
  149. }
  150. // Ensure all tags were pulled successfully
  151. for _, repo := range repos {
  152. dockerCmd(c, "inspect", repo)
  153. out, _ := dockerCmd(c, "run", "--rm", repo)
  154. assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo)
  155. }
  156. }
  157. func (s *DockerRegistrySuite) TestConcurrentPullMultipleTags(c *check.C) {
  158. testConcurrentPullMultipleTags(c)
  159. }
  160. // testPullIDStability verifies that pushing an image and pulling it back
  161. // preserves the image ID.
  162. func testPullIDStability(c *check.C) {
  163. derivedImage := privateRegistryURL + "/dockercli/id-stability"
  164. baseImage := "busybox"
  165. buildImageSuccessfully(c, derivedImage, build.WithDockerfile(fmt.Sprintf(`
  166. FROM %s
  167. ENV derived true
  168. ENV asdf true
  169. RUN dd if=/dev/zero of=/file bs=1024 count=1024
  170. CMD echo %s
  171. `, baseImage, derivedImage)))
  172. originalID := getIDByName(c, derivedImage)
  173. dockerCmd(c, "push", derivedImage)
  174. // Pull
  175. out, _ := dockerCmd(c, "pull", derivedImage)
  176. if strings.Contains(out, "Pull complete") {
  177. c.Fatalf("repull redownloaded a layer: %s", out)
  178. }
  179. derivedIDAfterPull := getIDByName(c, derivedImage)
  180. if derivedIDAfterPull != originalID {
  181. c.Fatal("image's ID unexpectedly changed after a repush/repull")
  182. }
  183. // Make sure the image runs correctly
  184. out, _ = dockerCmd(c, "run", "--rm", derivedImage)
  185. if strings.TrimSpace(out) != derivedImage {
  186. c.Fatalf("expected %s; got %s", derivedImage, out)
  187. }
  188. // Confirm that repushing and repulling does not change the computed ID
  189. dockerCmd(c, "push", derivedImage)
  190. dockerCmd(c, "rmi", derivedImage)
  191. dockerCmd(c, "pull", derivedImage)
  192. derivedIDAfterPull = getIDByName(c, derivedImage)
  193. if derivedIDAfterPull != originalID {
  194. c.Fatal("image's ID unexpectedly changed after a repush/repull")
  195. }
  196. // Make sure the image still runs
  197. out, _ = dockerCmd(c, "run", "--rm", derivedImage)
  198. if strings.TrimSpace(out) != derivedImage {
  199. c.Fatalf("expected %s; got %s", derivedImage, out)
  200. }
  201. }
  202. func (s *DockerRegistrySuite) TestPullIDStability(c *check.C) {
  203. testPullIDStability(c)
  204. }
  205. // #21213
  206. func testPullNoLayers(c *check.C) {
  207. repoName := fmt.Sprintf("%v/dockercli/scratch", privateRegistryURL)
  208. buildImageSuccessfully(c, repoName, build.WithDockerfile(`
  209. FROM scratch
  210. ENV foo bar`))
  211. dockerCmd(c, "push", repoName)
  212. dockerCmd(c, "rmi", repoName)
  213. dockerCmd(c, "pull", repoName)
  214. }
  215. func (s *DockerRegistrySuite) TestPullNoLayers(c *check.C) {
  216. testPullNoLayers(c)
  217. }
  218. func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) {
  219. testRequires(c, NotArm)
  220. pushDigest, err := setupImage(c)
  221. assert.NilError(c, err, "error setting up image")
  222. // Inject a manifest list into the registry
  223. manifestList := &manifestlist.ManifestList{
  224. Versioned: manifest.Versioned{
  225. SchemaVersion: 2,
  226. MediaType: manifestlist.MediaTypeManifestList,
  227. },
  228. Manifests: []manifestlist.ManifestDescriptor{
  229. {
  230. Descriptor: distribution.Descriptor{
  231. Digest: "sha256:1a9ec845ee94c202b2d5da74a24f0ed2058318bfa9879fa541efaecba272e86b",
  232. Size: 3253,
  233. MediaType: schema2.MediaTypeManifest,
  234. },
  235. Platform: manifestlist.PlatformSpec{
  236. Architecture: "bogus_arch",
  237. OS: "bogus_os",
  238. },
  239. },
  240. {
  241. Descriptor: distribution.Descriptor{
  242. Digest: pushDigest,
  243. Size: 3253,
  244. MediaType: schema2.MediaTypeManifest,
  245. },
  246. Platform: manifestlist.PlatformSpec{
  247. Architecture: runtime.GOARCH,
  248. OS: runtime.GOOS,
  249. },
  250. },
  251. },
  252. }
  253. manifestListJSON, err := json.MarshalIndent(manifestList, "", " ")
  254. assert.NilError(c, err, "error marshalling manifest list")
  255. manifestListDigest := digest.FromBytes(manifestListJSON)
  256. hexDigest := manifestListDigest.Hex()
  257. registryV2Path := s.reg.Path()
  258. // Write manifest list to blob store
  259. blobDir := filepath.Join(registryV2Path, "blobs", "sha256", hexDigest[:2], hexDigest)
  260. err = os.MkdirAll(blobDir, 0755)
  261. assert.NilError(c, err, "error creating blob dir")
  262. blobPath := filepath.Join(blobDir, "data")
  263. err = ioutil.WriteFile(blobPath, []byte(manifestListJSON), 0644)
  264. assert.NilError(c, err, "error writing manifest list")
  265. // Add to revision store
  266. revisionDir := filepath.Join(registryV2Path, "repositories", remoteRepoName, "_manifests", "revisions", "sha256", hexDigest)
  267. err = os.Mkdir(revisionDir, 0755)
  268. c.Assert(err, checker.IsNil, check.Commentf("error creating revision dir"))
  269. revisionPath := filepath.Join(revisionDir, "link")
  270. err = ioutil.WriteFile(revisionPath, []byte(manifestListDigest.String()), 0644)
  271. c.Assert(err, checker.IsNil, check.Commentf("error writing revision link"))
  272. // Update tag
  273. tagPath := filepath.Join(registryV2Path, "repositories", remoteRepoName, "_manifests", "tags", "latest", "current", "link")
  274. err = ioutil.WriteFile(tagPath, []byte(manifestListDigest.String()), 0644)
  275. assert.NilError(c, err, "error writing tag link")
  276. // Verify that the image can be pulled through the manifest list.
  277. out, _ := dockerCmd(c, "pull", repoName)
  278. // The pull output includes "Digest: <digest>", so find that
  279. matches := digestRegex.FindStringSubmatch(out)
  280. c.Assert(matches, checker.HasLen, 2, check.Commentf("unable to parse digest from pull output: %s", out))
  281. pullDigest := matches[1]
  282. // Make sure the pushed and pull digests match
  283. assert.Equal(c, manifestListDigest.String(), pullDigest)
  284. // Was the image actually created?
  285. dockerCmd(c, "inspect", repoName)
  286. dockerCmd(c, "rmi", repoName)
  287. }
  288. // #23100
  289. func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithScheme(c *check.C) {
  290. osPath := os.Getenv("PATH")
  291. defer os.Setenv("PATH", osPath)
  292. workingDir, err := os.Getwd()
  293. assert.NilError(c, err)
  294. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  295. assert.NilError(c, err)
  296. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  297. os.Setenv("PATH", testPath)
  298. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  299. tmp, err := ioutil.TempDir("", "integration-cli-")
  300. assert.NilError(c, err)
  301. externalAuthConfig := `{ "credsStore": "shell-test" }`
  302. configPath := filepath.Join(tmp, "config.json")
  303. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  304. assert.NilError(c, err)
  305. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  306. b, err := ioutil.ReadFile(configPath)
  307. assert.NilError(c, err)
  308. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  309. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  310. dockerCmd(c, "--config", tmp, "push", repoName)
  311. dockerCmd(c, "--config", tmp, "logout", privateRegistryURL)
  312. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), "https://"+privateRegistryURL)
  313. dockerCmd(c, "--config", tmp, "pull", repoName)
  314. // likewise push should work
  315. repoName2 := fmt.Sprintf("%v/dockercli/busybox:nocreds", privateRegistryURL)
  316. dockerCmd(c, "tag", repoName, repoName2)
  317. dockerCmd(c, "--config", tmp, "push", repoName2)
  318. // logout should work w scheme also because it will be stripped
  319. dockerCmd(c, "--config", tmp, "logout", "https://"+privateRegistryURL)
  320. }
  321. func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *check.C) {
  322. osPath := os.Getenv("PATH")
  323. defer os.Setenv("PATH", osPath)
  324. workingDir, err := os.Getwd()
  325. assert.NilError(c, err)
  326. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  327. assert.NilError(c, err)
  328. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  329. os.Setenv("PATH", testPath)
  330. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  331. tmp, err := ioutil.TempDir("", "integration-cli-")
  332. assert.NilError(c, err)
  333. externalAuthConfig := `{ "credsStore": "shell-test" }`
  334. configPath := filepath.Join(tmp, "config.json")
  335. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  336. assert.NilError(c, err)
  337. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  338. b, err := ioutil.ReadFile(configPath)
  339. assert.NilError(c, err)
  340. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  341. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  342. dockerCmd(c, "--config", tmp, "push", repoName)
  343. dockerCmd(c, "--config", tmp, "pull", repoName)
  344. }
  345. // TestRunImplicitPullWithNoTag should pull implicitly only the default tag (latest)
  346. func (s *DockerRegistrySuite) TestRunImplicitPullWithNoTag(c *check.C) {
  347. testRequires(c, DaemonIsLinux)
  348. repo := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  349. repoTag1 := fmt.Sprintf("%v:latest", repo)
  350. repoTag2 := fmt.Sprintf("%v:t1", repo)
  351. // tag the image and upload it to the private registry
  352. dockerCmd(c, "tag", "busybox", repoTag1)
  353. dockerCmd(c, "tag", "busybox", repoTag2)
  354. dockerCmd(c, "push", repo)
  355. dockerCmd(c, "rmi", repoTag1)
  356. dockerCmd(c, "rmi", repoTag2)
  357. out, _ := dockerCmd(c, "run", repo)
  358. c.Assert(out, checker.Contains, fmt.Sprintf("Unable to find image '%s:latest' locally", repo))
  359. // There should be only one line for repo, the one with repo:latest
  360. outImageCmd, _ := dockerCmd(c, "images", repo)
  361. splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n")
  362. c.Assert(splitOutImageCmd, checker.HasLen, 2)
  363. }