docker_cli_save_load_test.go 13 KB

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