Browse code

Introduce support for docker commit

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
Co-authored-by: Laura Brehm <laurabrehm@hey.com>
Co-authored-by: Sebastiaan van Stijn <github@gone.nl>
Co-authored-by: Paweł Gronowski <pawel.gronowski@docker.com>
Co-authored-by: Nicolas De Loof <nicolas.deloof@gmail.com>

Nicolas De Loof authored on 2022/08/04 17:37:04
Showing 3 changed files
... ...
@@ -1,17 +1,296 @@
1 1
 package containerd
2 2
 
3 3
 import (
4
+	"bytes"
4 5
 	"context"
6
+	"crypto/rand"
7
+	"encoding/base64"
8
+	"encoding/json"
5 9
 	"errors"
10
+	"fmt"
11
+	"runtime"
12
+	"time"
6 13
 
14
+	"github.com/containerd/containerd/content"
15
+	"github.com/containerd/containerd/diff"
16
+	cerrdefs "github.com/containerd/containerd/errdefs"
17
+	"github.com/containerd/containerd/images"
18
+	"github.com/containerd/containerd/leases"
19
+	"github.com/containerd/containerd/platforms"
20
+	"github.com/containerd/containerd/rootfs"
21
+	"github.com/containerd/containerd/snapshots"
7 22
 	"github.com/docker/docker/api/types/backend"
23
+	containerapi "github.com/docker/docker/api/types/container"
8 24
 	"github.com/docker/docker/errdefs"
9 25
 	"github.com/docker/docker/image"
26
+	"github.com/opencontainers/go-digest"
27
+	"github.com/opencontainers/image-spec/identity"
28
+	"github.com/opencontainers/image-spec/specs-go"
29
+	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
30
+	"github.com/sirupsen/logrus"
10 31
 )
11 32
 
33
+/*
34
+This code is based on `commit` support in nerdctl, under Apache License
35
+https://github.com/containerd/nerdctl/blob/master/pkg/imgutil/commit/commit.go
36
+with adaptations to match the Moby data model and services.
37
+*/
38
+
12 39
 // CommitImage creates a new image from a commit config.
13
-func (i *ImageService) CommitImage(ctx context.Context, c backend.CommitConfig) (image.ID, error) {
14
-	return "", errdefs.NotImplemented(errors.New("not implemented"))
40
+func (i *ImageService) CommitImage(ctx context.Context, cc backend.CommitConfig) (image.ID, error) {
41
+	container := i.containers.Get(cc.ContainerID)
42
+
43
+	desc, err := i.resolveDescriptor(ctx, container.Config.Image)
44
+	if err != nil {
45
+		return "", err
46
+	}
47
+
48
+	cs := i.client.ContentStore()
49
+
50
+	ocimanifest, err := images.Manifest(ctx, cs, desc, platforms.DefaultStrict())
51
+	if err != nil {
52
+		return "", err
53
+	}
54
+
55
+	imageConfigBytes, err := content.ReadBlob(ctx, cs, ocimanifest.Config)
56
+	if err != nil {
57
+		return "", err
58
+	}
59
+	var ociimage ocispec.Image
60
+	if err := json.Unmarshal(imageConfigBytes, &ociimage); err != nil {
61
+		return "", err
62
+	}
63
+
64
+	var (
65
+		differ = i.client.DiffService()
66
+		sn     = i.client.SnapshotService(i.snapshotter)
67
+	)
68
+
69
+	// Don't gc me and clean the dirty data after 1 hour!
70
+	ctx, done, err := i.client.WithLease(ctx, leases.WithRandomID(), leases.WithExpiration(1*time.Hour))
71
+	if err != nil {
72
+		return "", fmt.Errorf("failed to create lease for commit: %w", err)
73
+	}
74
+	defer done(ctx)
75
+
76
+	diffLayerDesc, diffID, err := createDiff(ctx, cc.ContainerID, sn, cs, differ)
77
+	if err != nil {
78
+		return "", fmt.Errorf("failed to export layer: %w", err)
79
+	}
80
+
81
+	imageConfig, err := generateCommitImageConfig(ctx, container.Config, ociimage, diffID, cc)
82
+	if err != nil {
83
+		return "", fmt.Errorf("failed to generate commit image config: %w", err)
84
+	}
85
+
86
+	rootfsID := identity.ChainID(imageConfig.RootFS.DiffIDs).String()
87
+	if err := applyDiffLayer(ctx, rootfsID, ociimage, sn, differ, diffLayerDesc); err != nil {
88
+		return "", fmt.Errorf("failed to apply diff: %w", err)
89
+	}
90
+
91
+	layers := append(ocimanifest.Layers, diffLayerDesc)
92
+	commitManifestDesc, configDigest, err := writeContentsForImage(ctx, i.snapshotter, cs, imageConfig, layers)
93
+	if err != nil {
94
+		return "", err
95
+	}
96
+
97
+	// image create
98
+	img := images.Image{
99
+		Name:      configDigest.String(),
100
+		Target:    commitManifestDesc,
101
+		CreatedAt: time.Now(),
102
+	}
103
+
104
+	if _, err := i.client.ImageService().Update(ctx, img); err != nil {
105
+		if !cerrdefs.IsNotFound(err) {
106
+			return "", err
107
+		}
108
+
109
+		if _, err := i.client.ImageService().Create(ctx, img); err != nil {
110
+			return "", fmt.Errorf("failed to create new image: %w", err)
111
+		}
112
+	}
113
+	return image.ID(img.Target.Digest), nil
114
+}
115
+
116
+// generateCommitImageConfig returns commit oci image config based on the container's image.
117
+func generateCommitImageConfig(ctx context.Context, container *containerapi.Config, baseConfig ocispec.Image, diffID digest.Digest, opts backend.CommitConfig) (ocispec.Image, error) {
118
+	if opts.Config.Cmd != nil {
119
+		baseConfig.Config.Cmd = opts.Config.Cmd
120
+	}
121
+	if opts.Config.Entrypoint != nil {
122
+		baseConfig.Config.Entrypoint = opts.Config.Entrypoint
123
+	}
124
+	if opts.Author == "" {
125
+		opts.Author = baseConfig.Author
126
+	}
127
+
128
+	createdTime := time.Now()
129
+	arch := baseConfig.Architecture
130
+	if arch == "" {
131
+		arch = runtime.GOARCH
132
+		logrus.Warnf("assuming arch=%q", arch)
133
+	}
134
+	os := baseConfig.OS
135
+	if os == "" {
136
+		os = runtime.GOOS
137
+		logrus.Warnf("assuming os=%q", os)
138
+	}
139
+	logrus.Debugf("generateCommitImageConfig(): arch=%q, os=%q", arch, os)
140
+	return ocispec.Image{
141
+		Architecture: arch,
142
+		OS:           os,
143
+		Created:      &createdTime,
144
+		Author:       opts.Author,
145
+		Config:       baseConfig.Config,
146
+		RootFS: ocispec.RootFS{
147
+			Type:    "layers",
148
+			DiffIDs: append(baseConfig.RootFS.DiffIDs, diffID),
149
+		},
150
+		History: append(baseConfig.History, ocispec.History{
151
+			Created:    &createdTime,
152
+			CreatedBy:  "", // FIXME(ndeloof) ?
153
+			Author:     opts.Author,
154
+			Comment:    opts.Comment,
155
+			EmptyLayer: diffID == "",
156
+		}),
157
+	}, nil
158
+}
159
+
160
+// writeContentsForImage will commit oci image config and manifest into containerd's content store.
161
+func writeContentsForImage(ctx context.Context, snName string, cs content.Store, newConfig ocispec.Image, layers []ocispec.Descriptor) (ocispec.Descriptor, image.ID, error) {
162
+	newConfigJSON, err := json.Marshal(newConfig)
163
+	if err != nil {
164
+		return ocispec.Descriptor{}, "", err
165
+	}
166
+
167
+	configDesc := ocispec.Descriptor{
168
+		MediaType: ocispec.MediaTypeImageConfig,
169
+		Digest:    digest.FromBytes(newConfigJSON),
170
+		Size:      int64(len(newConfigJSON)),
171
+	}
172
+
173
+	newMfst := struct {
174
+		MediaType string `json:"mediaType,omitempty"`
175
+		ocispec.Manifest
176
+	}{
177
+		MediaType: ocispec.MediaTypeImageManifest,
178
+		Manifest: ocispec.Manifest{
179
+			Versioned: specs.Versioned{
180
+				SchemaVersion: 2,
181
+			},
182
+			Config: configDesc,
183
+			Layers: layers,
184
+		},
185
+	}
186
+
187
+	newMfstJSON, err := json.MarshalIndent(newMfst, "", "    ")
188
+	if err != nil {
189
+		return ocispec.Descriptor{}, "", err
190
+	}
191
+
192
+	newMfstDesc := ocispec.Descriptor{
193
+		MediaType: ocispec.MediaTypeImageManifest,
194
+		Digest:    digest.FromBytes(newMfstJSON),
195
+		Size:      int64(len(newMfstJSON)),
196
+	}
197
+
198
+	// new manifest should reference the layers and config content
199
+	labels := map[string]string{
200
+		"containerd.io/gc.ref.content.0": configDesc.Digest.String(),
201
+	}
202
+	for i, l := range layers {
203
+		labels[fmt.Sprintf("containerd.io/gc.ref.content.%d", i+1)] = l.Digest.String()
204
+	}
205
+
206
+	err = content.WriteBlob(ctx, cs, newMfstDesc.Digest.String(), bytes.NewReader(newMfstJSON), newMfstDesc, content.WithLabels(labels))
207
+	if err != nil {
208
+		return ocispec.Descriptor{}, "", err
209
+	}
210
+
211
+	// config should reference to snapshotter
212
+	labelOpt := content.WithLabels(map[string]string{
213
+		fmt.Sprintf("containerd.io/gc.ref.snapshot.%s", snName): identity.ChainID(newConfig.RootFS.DiffIDs).String(),
214
+	})
215
+	err = content.WriteBlob(ctx, cs, configDesc.Digest.String(), bytes.NewReader(newConfigJSON), configDesc, labelOpt)
216
+	if err != nil {
217
+		return ocispec.Descriptor{}, "", err
218
+	}
219
+
220
+	return newMfstDesc, image.ID(configDesc.Digest), nil
221
+}
222
+
223
+// createDiff creates a layer diff into containerd's content store.
224
+func createDiff(ctx context.Context, name string, sn snapshots.Snapshotter, cs content.Store, comparer diff.Comparer) (ocispec.Descriptor, digest.Digest, error) {
225
+	newDesc, err := rootfs.CreateDiff(ctx, name, sn, comparer)
226
+	if err != nil {
227
+		return ocispec.Descriptor{}, "", err
228
+	}
229
+
230
+	info, err := cs.Info(ctx, newDesc.Digest)
231
+	if err != nil {
232
+		return ocispec.Descriptor{}, "", err
233
+	}
234
+
235
+	diffIDStr, ok := info.Labels["containerd.io/uncompressed"]
236
+	if !ok {
237
+		return ocispec.Descriptor{}, "", fmt.Errorf("invalid differ response with no diffID")
238
+	}
239
+
240
+	diffID, err := digest.Parse(diffIDStr)
241
+	if err != nil {
242
+		return ocispec.Descriptor{}, "", err
243
+	}
244
+
245
+	return ocispec.Descriptor{
246
+		MediaType: ocispec.MediaTypeImageLayerGzip,
247
+		Digest:    newDesc.Digest,
248
+		Size:      info.Size,
249
+	}, diffID, nil
250
+}
251
+
252
+// applyDiffLayer will apply diff layer content created by createDiff into the snapshotter.
253
+func applyDiffLayer(ctx context.Context, name string, baseImg ocispec.Image, sn snapshots.Snapshotter, differ diff.Applier, diffDesc ocispec.Descriptor) (retErr error) {
254
+	var (
255
+		key    = uniquePart() + "-" + name
256
+		parent = identity.ChainID(baseImg.RootFS.DiffIDs).String()
257
+	)
258
+
259
+	mount, err := sn.Prepare(ctx, key, parent)
260
+	if err != nil {
261
+		return err
262
+	}
263
+
264
+	defer func() {
265
+		if retErr != nil {
266
+			// NOTE: the snapshotter should be hold by lease. Even
267
+			// if the cleanup fails, the containerd gc can delete it.
268
+			if err := sn.Remove(ctx, key); err != nil {
269
+				logrus.Warnf("failed to cleanup aborted apply %s: %s", key, err)
270
+			}
271
+		}
272
+	}()
273
+
274
+	if _, err = differ.Apply(ctx, diffDesc, mount); err != nil {
275
+		return err
276
+	}
277
+
278
+	if err = sn.Commit(ctx, name, key); err != nil {
279
+		if cerrdefs.IsAlreadyExists(err) {
280
+			return nil
281
+		}
282
+		return err
283
+	}
284
+	return nil
285
+}
286
+
287
+// copied from github.com/containerd/containerd/rootfs/apply.go
288
+func uniquePart() string {
289
+	t := time.Now()
290
+	var b [3]byte
291
+	// Ignore read failures, just decreases uniqueness
292
+	rand.Read(b[:])
293
+	return fmt.Sprintf("%d-%s", t.Nanosecond(), base64.URLEncoding.EncodeToString(b[:]))
15 294
 }
16 295
 
17 296
 // CommitBuildStep is used by the builder to create an image for each step in
... ...
@@ -19,6 +19,7 @@ import (
19 19
 // ImageService implements daemon.ImageService
20 20
 type ImageService struct {
21 21
 	client          *containerd.Client
22
+	containers      container.Store
22 23
 	snapshotter     string
23 24
 	registryHosts   RegistryHostsProvider
24 25
 	registryService registry.Service
... ...
@@ -29,9 +30,10 @@ type RegistryHostsProvider interface {
29 29
 }
30 30
 
31 31
 // NewService creates a new ImageService.
32
-func NewService(c *containerd.Client, snapshotter string, hostsProvider RegistryHostsProvider, registry registry.Service) *ImageService {
32
+func NewService(c *containerd.Client, containers container.Store, snapshotter string, hostsProvider RegistryHostsProvider, registry registry.Service) *ImageService {
33 33
 	return &ImageService{
34 34
 		client:          c,
35
+		containers:      containers,
35 36
 		snapshotter:     snapshotter,
36 37
 		registryHosts:   hostsProvider,
37 38
 		registryService: registry,
... ...
@@ -1005,7 +1005,7 @@ func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
1005 1005
 		if err := configureKernelSecuritySupport(config, driverName); err != nil {
1006 1006
 			return nil, err
1007 1007
 		}
1008
-		d.imageService = ctrd.NewService(d.containerdCli, driverName, d, d.registryService)
1008
+		d.imageService = ctrd.NewService(d.containerdCli, d.containers, driverName, d, d.registryService)
1009 1009
 	} else {
1010 1010
 		layerStore, err := layer.NewStoreFromOptions(layer.StoreOptions{
1011 1011
 			Root:                      config.Root,