docker_cli_pull_local_test.go 14 KB

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