Skip to content

Commit

Permalink
Merge pull request #3023 from yankay/add-image-label
Browse files Browse the repository at this point in the history
feat: Support creating container with labels defined by image
  • Loading branch information
AkihiroSuda authored May 20, 2024
2 parents b5758f5 + cf5073b commit 3dfdf55
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
13 changes: 13 additions & 0 deletions cmd/nerdctl/container_create_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@ func TestCreate(t *testing.T) {
base.Cmd("logs", tID).AssertOutContains("foo")
}

func TestCreateWithLabel(t *testing.T) {
t.Parallel()
base := testutil.NewBase(t)
tID := testutil.Identifier(t)

base.Cmd("create", "--name", tID, "--label", "foo=bar", testutil.NginxAlpineImage, "echo", "foo").AssertOK()
defer base.Cmd("rm", "-f", tID).Run()
inspect := base.InspectContainer(tID)
assert.Equal(base.T, "bar", inspect.Config.Labels["foo"])
// the label `maintainer`` is defined by image
assert.Equal(base.T, "NGINX Docker Maintainers <docker-maint@nginx.com>", inspect.Config.Labels["maintainer"])
}

func TestCreateWithMACAddress(t *testing.T) {
base := testutil.NewBase(t)
tID := testutil.Identifier(t)
Expand Down
16 changes: 13 additions & 3 deletions pkg/cmd/container/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func Create(ctx context.Context, client *containerd.Client, args []string, netMa
}
cOpts = append(cOpts, rtCOpts...)

lCOpts, err := withContainerLabels(options.Label, options.LabelFile)
lCOpts, err := withContainerLabels(options.Label, options.LabelFile, ensuredImage)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -504,7 +504,15 @@ func withNerdctlOCIHook(cmd string, args []string) (oci.SpecOpts, error) {
}, nil
}

func withContainerLabels(label, labelFile []string) ([]containerd.NewContainerOpts, error) {
func withContainerLabels(label, labelFile []string, ensuredImage *imgutil.EnsuredImage) ([]containerd.NewContainerOpts, error) {
var opts []containerd.NewContainerOpts

// add labels defined by image
if ensuredImage != nil {
imageLabelOpts := containerd.WithAdditionalContainerLabels(ensuredImage.ImageConfig.Labels)
opts = append(opts, imageLabelOpts)
}

labelMap, err := readKVStringsMapfFromLabel(label, labelFile)
if err != nil {
return nil, err
Expand All @@ -517,7 +525,9 @@ func withContainerLabels(label, labelFile []string) ([]containerd.NewContainerOp
}
}
o := containerd.WithAdditionalContainerLabels(labelMap)
return []containerd.NewContainerOpts{o}, nil
opts = append(opts, o)

return opts, nil
}

func readKVStringsMapfFromLabel(label, labelFile []string) (map[string]string, error) {
Expand Down

0 comments on commit 3dfdf55

Please sign in to comment.