docker_cli_save_load_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package main
  2. import (
  3. "archive/tar"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "reflect"
  11. "regexp"
  12. "sort"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/docker/docker/integration-cli/cli/build"
  17. "github.com/opencontainers/go-digest"
  18. "gotest.tools/v3/assert"
  19. is "gotest.tools/v3/assert/cmp"
  20. "gotest.tools/v3/icmd"
  21. )
  22. type DockerCLISaveLoadSuite struct {
  23. ds *DockerSuite
  24. }
  25. func (s *DockerCLISaveLoadSuite) TearDownTest(c *testing.T) {
  26. s.ds.TearDownTest(c)
  27. }
  28. func (s *DockerCLISaveLoadSuite) OnTimeout(c *testing.T) {
  29. s.ds.OnTimeout(c)
  30. }
  31. // save a repo using gz compression and try to load it using stdout
  32. func (s *DockerCLISaveLoadSuite) TestSaveXzAndLoadRepoStdout(c *testing.T) {
  33. testRequires(c, DaemonIsLinux)
  34. name := "test-save-xz-and-load-repo-stdout"
  35. dockerCmd(c, "run", "--name", name, "busybox", "true")
  36. repoName := "foobar-save-load-test-xz-gz"
  37. out, _ := dockerCmd(c, "commit", name, repoName)
  38. dockerCmd(c, "inspect", repoName)
  39. repoTarball, err := RunCommandPipelineWithOutput(
  40. exec.Command(dockerBinary, "save", repoName),
  41. exec.Command("xz", "-c"),
  42. exec.Command("gzip", "-c"))
  43. assert.NilError(c, err, "failed to save repo: %v %v", out, err)
  44. deleteImages(repoName)
  45. icmd.RunCmd(icmd.Cmd{
  46. Command: []string{dockerBinary, "load"},
  47. Stdin: strings.NewReader(repoTarball),
  48. }).Assert(c, icmd.Expected{
  49. ExitCode: 1,
  50. })
  51. after, _, err := dockerCmdWithError("inspect", repoName)
  52. assert.ErrorContains(c, err, "", "the repo should not exist: %v", after)
  53. }
  54. // save a repo using xz+gz compression and try to load it using stdout
  55. func (s *DockerCLISaveLoadSuite) TestSaveXzGzAndLoadRepoStdout(c *testing.T) {
  56. testRequires(c, DaemonIsLinux)
  57. name := "test-save-xz-gz-and-load-repo-stdout"
  58. dockerCmd(c, "run", "--name", name, "busybox", "true")
  59. repoName := "foobar-save-load-test-xz-gz"
  60. dockerCmd(c, "commit", name, repoName)
  61. dockerCmd(c, "inspect", repoName)
  62. out, err := RunCommandPipelineWithOutput(
  63. exec.Command(dockerBinary, "save", repoName),
  64. exec.Command("xz", "-c"),
  65. exec.Command("gzip", "-c"))
  66. assert.NilError(c, err, "failed to save repo: %v %v", out, err)
  67. deleteImages(repoName)
  68. icmd.RunCmd(icmd.Cmd{
  69. Command: []string{dockerBinary, "load"},
  70. Stdin: strings.NewReader(out),
  71. }).Assert(c, icmd.Expected{
  72. ExitCode: 1,
  73. })
  74. after, _, err := dockerCmdWithError("inspect", repoName)
  75. assert.ErrorContains(c, err, "", "the repo should not exist: %v", after)
  76. }
  77. func (s *DockerCLISaveLoadSuite) TestSaveSingleTag(c *testing.T) {
  78. testRequires(c, DaemonIsLinux)
  79. repoName := "foobar-save-single-tag-test"
  80. dockerCmd(c, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName))
  81. out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName)
  82. cleanedImageID := strings.TrimSpace(out)
  83. out, err := RunCommandPipelineWithOutput(
  84. exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", repoName)),
  85. exec.Command("tar", "t"),
  86. exec.Command("grep", "-E", fmt.Sprintf("(^repositories$|%v)", cleanedImageID)))
  87. assert.NilError(c, err, "failed to save repo with image ID and 'repositories' file: %s, %v", out, err)
  88. }
  89. func (s *DockerCLISaveLoadSuite) TestSaveCheckTimes(c *testing.T) {
  90. testRequires(c, DaemonIsLinux)
  91. repoName := "busybox:latest"
  92. out, _ := dockerCmd(c, "inspect", repoName)
  93. var data []struct {
  94. ID string
  95. Created time.Time
  96. }
  97. err := json.Unmarshal([]byte(out), &data)
  98. assert.NilError(c, err, "failed to marshal from %q: err %v", repoName, err)
  99. assert.Assert(c, len(data) != 0, "failed to marshal the data from %q", repoName)
  100. tarTvTimeFormat := "2006-01-02 15:04"
  101. out, err = RunCommandPipelineWithOutput(
  102. exec.Command(dockerBinary, "save", repoName),
  103. exec.Command("tar", "tv"),
  104. exec.Command("grep", "-E", fmt.Sprintf("%s %s", data[0].Created.Format(tarTvTimeFormat), digest.Digest(data[0].ID).Encoded())))
  105. assert.NilError(c, err, "failed to save repo with image ID and 'repositories' file: %s, %v", out, err)
  106. }
  107. func (s *DockerCLISaveLoadSuite) TestSaveImageId(c *testing.T) {
  108. testRequires(c, DaemonIsLinux)
  109. repoName := "foobar-save-image-id-test"
  110. dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName))
  111. out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName)
  112. cleanedLongImageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:")
  113. out, _ = dockerCmd(c, "images", "-q", repoName)
  114. cleanedShortImageID := strings.TrimSpace(out)
  115. // Make sure IDs are not empty
  116. assert.Assert(c, cleanedLongImageID != "", "Id should not be empty.")
  117. assert.Assert(c, cleanedShortImageID != "", "Id should not be empty.")
  118. saveCmd := exec.Command(dockerBinary, "save", cleanedShortImageID)
  119. tarCmd := exec.Command("tar", "t")
  120. var err error
  121. tarCmd.Stdin, err = saveCmd.StdoutPipe()
  122. assert.Assert(c, err == nil, "cannot set stdout pipe for tar: %v", err)
  123. grepCmd := exec.Command("grep", cleanedLongImageID)
  124. grepCmd.Stdin, err = tarCmd.StdoutPipe()
  125. assert.Assert(c, err == nil, "cannot set stdout pipe for grep: %v", err)
  126. assert.Assert(c, tarCmd.Start() == nil, "tar failed with error: %v", err)
  127. assert.Assert(c, saveCmd.Start() == nil, "docker save failed with error: %v", err)
  128. defer func() {
  129. saveCmd.Wait()
  130. tarCmd.Wait()
  131. dockerCmd(c, "rmi", repoName)
  132. }()
  133. out, _, err = runCommandWithOutput(grepCmd)
  134. assert.Assert(c, err == nil, "failed to save repo with image ID: %s, %v", out, err)
  135. }
  136. // save a repo and try to load it using flags
  137. func (s *DockerCLISaveLoadSuite) TestSaveAndLoadRepoFlags(c *testing.T) {
  138. testRequires(c, DaemonIsLinux)
  139. name := "test-save-and-load-repo-flags"
  140. dockerCmd(c, "run", "--name", name, "busybox", "true")
  141. repoName := "foobar-save-load-test"
  142. deleteImages(repoName)
  143. dockerCmd(c, "commit", name, repoName)
  144. before, _ := dockerCmd(c, "inspect", repoName)
  145. out, err := RunCommandPipelineWithOutput(
  146. exec.Command(dockerBinary, "save", repoName),
  147. exec.Command(dockerBinary, "load"))
  148. assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err)
  149. after, _ := dockerCmd(c, "inspect", repoName)
  150. assert.Equal(c, before, after, "inspect is not the same after a save / load")
  151. }
  152. func (s *DockerCLISaveLoadSuite) TestSaveWithNoExistImage(c *testing.T) {
  153. testRequires(c, DaemonIsLinux)
  154. imgName := "foobar-non-existing-image"
  155. out, _, err := dockerCmdWithError("save", "-o", "test-img.tar", imgName)
  156. assert.ErrorContains(c, err, "", "save image should fail for non-existing image")
  157. assert.Assert(c, strings.Contains(out, fmt.Sprintf("No such image: %s", imgName)))
  158. }
  159. func (s *DockerCLISaveLoadSuite) TestSaveMultipleNames(c *testing.T) {
  160. testRequires(c, DaemonIsLinux)
  161. repoName := "foobar-save-multi-name-test"
  162. // Make one image
  163. dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v-one:latest", repoName))
  164. // Make two images
  165. dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v-two:latest", repoName))
  166. out, err := RunCommandPipelineWithOutput(
  167. exec.Command(dockerBinary, "save", fmt.Sprintf("%v-one", repoName), fmt.Sprintf("%v-two:latest", repoName)),
  168. exec.Command("tar", "xO", "repositories"),
  169. exec.Command("grep", "-q", "-E", "(-one|-two)"),
  170. )
  171. assert.NilError(c, err, "failed to save multiple repos: %s, %v", out, err)
  172. }
  173. func (s *DockerCLISaveLoadSuite) TestSaveRepoWithMultipleImages(c *testing.T) {
  174. testRequires(c, DaemonIsLinux)
  175. makeImage := func(from string, tag string) string {
  176. var (
  177. out string
  178. )
  179. out, _ = dockerCmd(c, "run", "-d", from, "true")
  180. cleanedContainerID := strings.TrimSpace(out)
  181. out, _ = dockerCmd(c, "commit", cleanedContainerID, tag)
  182. imageID := strings.TrimSpace(out)
  183. return imageID
  184. }
  185. repoName := "foobar-save-multi-images-test"
  186. tagFoo := repoName + ":foo"
  187. tagBar := repoName + ":bar"
  188. idFoo := makeImage("busybox:latest", tagFoo)
  189. idBar := makeImage("busybox:latest", tagBar)
  190. deleteImages(repoName)
  191. // create the archive
  192. out, err := RunCommandPipelineWithOutput(
  193. exec.Command(dockerBinary, "save", repoName, "busybox:latest"),
  194. exec.Command("tar", "t"))
  195. assert.NilError(c, err, "failed to save multiple images: %s, %v", out, err)
  196. lines := strings.Split(strings.TrimSpace(out), "\n")
  197. var actual []string
  198. for _, l := range lines {
  199. if regexp.MustCompile(`^[a-f0-9]{64}\.json$`).Match([]byte(l)) {
  200. actual = append(actual, strings.TrimSuffix(l, ".json"))
  201. }
  202. }
  203. // make the list of expected layers
  204. out = inspectField(c, "busybox:latest", "Id")
  205. expected := []string{strings.TrimSpace(out), idFoo, idBar}
  206. // prefixes are not in tar
  207. for i := range expected {
  208. expected[i] = digest.Digest(expected[i]).Encoded()
  209. }
  210. sort.Strings(actual)
  211. sort.Strings(expected)
  212. assert.Assert(c, is.DeepEqual(actual, expected), "archive does not contains the right layers: got %v, expected %v, output: %q", actual, expected, out)
  213. }
  214. // Issue #6722 #5892 ensure directories are included in changes
  215. func (s *DockerCLISaveLoadSuite) TestSaveDirectoryPermissions(c *testing.T) {
  216. testRequires(c, DaemonIsLinux)
  217. layerEntries := []string{"opt/", "opt/a/", "opt/a/b/", "opt/a/b/c"}
  218. layerEntriesAUFS := []string{"./", ".wh..wh.aufs", ".wh..wh.orph/", ".wh..wh.plnk/", "opt/", "opt/a/", "opt/a/b/", "opt/a/b/c"}
  219. name := "save-directory-permissions"
  220. tmpDir, err := os.MkdirTemp("", "save-layers-with-directories")
  221. assert.Assert(c, err == nil, "failed to create temporary directory: %s", err)
  222. extractionDirectory := filepath.Join(tmpDir, "image-extraction-dir")
  223. os.Mkdir(extractionDirectory, 0777)
  224. defer os.RemoveAll(tmpDir)
  225. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  226. RUN adduser -D user && mkdir -p /opt/a/b && chown -R user:user /opt/a
  227. RUN touch /opt/a/b/c && chown user:user /opt/a/b/c`))
  228. out, err := RunCommandPipelineWithOutput(
  229. exec.Command(dockerBinary, "save", name),
  230. exec.Command("tar", "-xf", "-", "-C", extractionDirectory),
  231. )
  232. assert.NilError(c, err, "failed to save and extract image: %s", out)
  233. dirs, err := os.ReadDir(extractionDirectory)
  234. assert.NilError(c, err, "failed to get a listing of the layer directories: %s", err)
  235. found := false
  236. for _, entry := range dirs {
  237. var entriesSansDev []string
  238. if entry.IsDir() {
  239. layerPath := filepath.Join(extractionDirectory, entry.Name(), "layer.tar")
  240. f, err := os.Open(layerPath)
  241. assert.NilError(c, err, "failed to open %s: %s", layerPath, err)
  242. defer f.Close()
  243. entries, err := listTar(f)
  244. for _, e := range entries {
  245. if !strings.Contains(e, "dev/") {
  246. entriesSansDev = append(entriesSansDev, e)
  247. }
  248. }
  249. assert.NilError(c, err, "encountered error while listing tar entries: %s", err)
  250. if reflect.DeepEqual(entriesSansDev, layerEntries) || reflect.DeepEqual(entriesSansDev, layerEntriesAUFS) {
  251. found = true
  252. break
  253. }
  254. }
  255. }
  256. assert.Assert(c, found, "failed to find the layer with the right content listing")
  257. }
  258. func listTar(f io.Reader) ([]string, error) {
  259. tr := tar.NewReader(f)
  260. var entries []string
  261. for {
  262. th, err := tr.Next()
  263. if err == io.EOF {
  264. // end of tar archive
  265. return entries, nil
  266. }
  267. if err != nil {
  268. return entries, err
  269. }
  270. entries = append(entries, th.Name)
  271. }
  272. }
  273. // Test loading a weird image where one of the layers is of zero size.
  274. // The layer.tar file is actually zero bytes, no padding or anything else.
  275. // See issue: 18170
  276. func (s *DockerCLISaveLoadSuite) TestLoadZeroSizeLayer(c *testing.T) {
  277. // this will definitely not work if using remote daemon
  278. // very weird test
  279. testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  280. dockerCmd(c, "load", "-i", "testdata/emptyLayer.tar")
  281. }
  282. func (s *DockerCLISaveLoadSuite) TestSaveLoadParents(c *testing.T) {
  283. testRequires(c, DaemonIsLinux)
  284. makeImage := func(from string, addfile string) string {
  285. var (
  286. out string
  287. )
  288. out, _ = dockerCmd(c, "run", "-d", from, "touch", addfile)
  289. cleanedContainerID := strings.TrimSpace(out)
  290. out, _ = dockerCmd(c, "commit", cleanedContainerID)
  291. imageID := strings.TrimSpace(out)
  292. dockerCmd(c, "rm", "-f", cleanedContainerID)
  293. return imageID
  294. }
  295. idFoo := makeImage("busybox", "foo")
  296. idBar := makeImage(idFoo, "bar")
  297. tmpDir, err := os.MkdirTemp("", "save-load-parents")
  298. assert.NilError(c, err)
  299. defer os.RemoveAll(tmpDir)
  300. c.Log("tmpdir", tmpDir)
  301. outfile := filepath.Join(tmpDir, "out.tar")
  302. dockerCmd(c, "save", "-o", outfile, idBar, idFoo)
  303. dockerCmd(c, "rmi", idBar)
  304. dockerCmd(c, "load", "-i", outfile)
  305. inspectOut := inspectField(c, idBar, "Parent")
  306. assert.Equal(c, inspectOut, idFoo)
  307. inspectOut = inspectField(c, idFoo, "Parent")
  308. assert.Equal(c, inspectOut, "")
  309. }
  310. func (s *DockerCLISaveLoadSuite) TestSaveLoadNoTag(c *testing.T) {
  311. testRequires(c, DaemonIsLinux)
  312. name := "saveloadnotag"
  313. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENV foo=bar"))
  314. id := inspectField(c, name, "Id")
  315. // Test to make sure that save w/o name just shows imageID during load
  316. out, err := RunCommandPipelineWithOutput(
  317. exec.Command(dockerBinary, "save", id),
  318. exec.Command(dockerBinary, "load"))
  319. assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err)
  320. // Should not show 'name' but should show the image ID during the load
  321. assert.Assert(c, !strings.Contains(out, "Loaded image: "))
  322. assert.Assert(c, strings.Contains(out, "Loaded image ID:"))
  323. assert.Assert(c, strings.Contains(out, id))
  324. // Test to make sure that save by name shows that name during load
  325. out, err = RunCommandPipelineWithOutput(
  326. exec.Command(dockerBinary, "save", name),
  327. exec.Command(dockerBinary, "load"))
  328. assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err)
  329. assert.Assert(c, strings.Contains(out, "Loaded image: "+name+":latest"))
  330. assert.Assert(c, !strings.Contains(out, "Loaded image ID:"))
  331. }