From f24d6fb2e51c8be9147d6939e3b33d85bbe05129 Mon Sep 17 00:00:00 2001 From: Valentin Rothberg Date: Tue, 6 Jul 2021 14:17:32 +0200 Subject: [PATCH] libimage: import: fix tags When importing, first create the image and tag it afterwards. This also makes sure that an imported image *without* a tag is correctly listed as "". Previously, such images were tagged as "docker.io/library/sha256:$ID" (inherited from older Podman code). Context: containers/podman/issues/10854 Signed-off-by: Valentin Rothberg --- libimage/import.go | 28 +++++++++++++++++++--------- libimage/import_test.go | 20 ++++++++++++++------ 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/libimage/import.go b/libimage/import.go index 2addfdf98..9926aaec7 100644 --- a/libimage/import.go +++ b/libimage/import.go @@ -86,16 +86,12 @@ func (r *Runtime) Import(ctx context.Context, path string, options *ImportOption return "", err } - name := options.Tag - if name == "" { - name, err = getImageDigest(ctx, srcRef, r.systemContextCopy()) - if err != nil { - return "", err - } - name = "sha256:" + name[1:] // strip leading "@" + id, err := getImageDigest(ctx, srcRef, r.systemContextCopy()) + if err != nil { + return "", err } - destRef, err := storageTransport.Transport.ParseStoreReference(r.store, name) + destRef, err := storageTransport.Transport.ParseStoreReference(r.store, id) if err != nil { return "", err } @@ -110,5 +106,19 @@ func (r *Runtime) Import(ctx context.Context, path string, options *ImportOption return "", err } - return name, nil + // Strip the leading @ off the id. + name := id[1:] + + // If requested, tag the imported image. + if options.Tag != "" { + image, _, err := r.LookupImage(name, nil) + if err != nil { + return "", errors.Wrap(err, "looking up imported image") + } + if err := image.Tag(options.Tag); err != nil { + return "", err + } + } + + return "sha256:" + name, nil } diff --git a/libimage/import_test.go b/libimage/import_test.go index 8d6160235..d4ae4d0b3 100644 --- a/libimage/import_test.go +++ b/libimage/import_test.go @@ -16,11 +16,19 @@ func TestImport(t *testing.T) { importOptions := &ImportOptions{} importOptions.Writer = os.Stdout - imported, err := runtime.Import(ctx, "testdata/exported-container.tar", importOptions) - require.NoError(t, err) + for _, tag := range []string{"", "foobar"} { + importOptions.Tag = tag + imported, err := runtime.Import(ctx, "testdata/exported-container.tar", importOptions) + require.NoError(t, err) - image, resolvedName, err := runtime.LookupImage(imported, nil) - require.NoError(t, err) - require.Equal(t, imported, resolvedName) - require.Equal(t, imported, "sha256:"+image.ID()) + image, resolvedName, err := runtime.LookupImage(imported, nil) + require.NoError(t, err) + require.Equal(t, imported, resolvedName) + require.Equal(t, "sha256:"+image.ID(), imported) + + if tag != "" { + _, _, err := runtime.LookupImage(tag, nil) + require.NoError(t, err) + } + } }