docker_cli_save_load_test.go 13 KB

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