@@ -18,14 +18,19 @@ package containerd
1818
1919import (
2020 "context"
21+ "encoding/json"
22+ "fmt"
2123
2224 "github.com/containerd/containerd/containers"
25+ "github.com/containerd/containerd/content"
2326 "github.com/containerd/containerd/errdefs"
27+ "github.com/containerd/containerd/images"
2428 "github.com/containerd/containerd/oci"
2529 "github.com/containerd/containerd/snapshots"
2630 "github.com/containerd/typeurl"
2731 "github.com/gogo/protobuf/types"
2832 "github.com/opencontainers/image-spec/identity"
33+ v1 "github.com/opencontainers/image-spec/specs-go/v1"
2934 "github.com/pkg/errors"
3035)
3136
@@ -95,6 +100,39 @@ func WithContainerLabels(labels map[string]string) NewContainerOpts {
95100 }
96101}
97102
103+ // WithImageConfigLabels sets the image config labels on the container.
104+ // The existing labels are cleared as this is expected to be the first
105+ // operation in setting up a container's labels. Use WithAdditionalContainerLabels
106+ // to add/overwrite the existing image config labels.
107+ func WithImageConfigLabels (image Image ) NewContainerOpts {
108+ return func (ctx context.Context , _ * Client , c * containers.Container ) error {
109+ ic , err := image .Config (ctx )
110+ if err != nil {
111+ return err
112+ }
113+ var (
114+ ociimage v1.Image
115+ config v1.ImageConfig
116+ )
117+ switch ic .MediaType {
118+ case v1 .MediaTypeImageConfig , images .MediaTypeDockerSchema2Config :
119+ p , err := content .ReadBlob (ctx , image .ContentStore (), ic )
120+ if err != nil {
121+ return err
122+ }
123+
124+ if err := json .Unmarshal (p , & ociimage ); err != nil {
125+ return err
126+ }
127+ config = ociimage .Config
128+ default :
129+ return fmt .Errorf ("unknown image config media type %s" , ic .MediaType )
130+ }
131+ c .Labels = config .Labels
132+ return nil
133+ }
134+ }
135+
98136// WithAdditionalContainerLabels adds the provided labels to the container
99137// The existing labels are preserved as long as they do not conflict with the added labels.
100138func WithAdditionalContainerLabels (labels map [string ]string ) NewContainerOpts {
0 commit comments