docker_cli_save_load_test.go 13 KB

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