-
Notifications
You must be signed in to change notification settings - Fork 950
/
Copy pathimage_commit.go
373 lines (318 loc) · 10.1 KB
/
image_commit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package ctrd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"runtime"
"strings"
"time"
"github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/pkg/log"
"github.com/alibaba/pouch/pkg/randomid"
"github.com/alibaba/pouch/pkg/utils"
"github.com/containerd/containerd"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/diff"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/images"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/platforms"
"github.com/containerd/containerd/snapshots"
digest "github.com/opencontainers/go-digest"
"github.com/opencontainers/image-spec/identity"
specs "github.com/opencontainers/image-spec/specs-go"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
var (
emptyGZLayer = digest.Digest("sha256:4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1")
containerdUncompressed = "containerd.io/uncompressed"
manifestType = images.MediaTypeDockerSchema2Manifest
configType = images.MediaTypeDockerSchema2Config
layerType = images.MediaTypeDockerSchema2LayerGzip
)
// CommitConfig defines options for committing a container image
type CommitConfig struct {
// author
Author string
// comment
Comment string
// container config
ContainerConfig *types.ContainerConfig
// container ID
ContainerID string
// parent reference
ParentReference string
// reference
Reference string
// repository
Repository string
// containerd format image
CImage containerd.Image
// image-spec format image
Image ocispec.Image
}
// Commit commits an image from a container.
func (c *Client) Commit(ctx context.Context, config *CommitConfig) (_ digest.Digest, err0 error) {
// get a containerd client
wrapperCli, err := c.Get(ctx)
if err != nil {
return "", fmt.Errorf("failed to get a containerd grpc client: %v", err)
}
client := wrapperCli.client
// NOTE: make sure that gc scheduler doesn't remove content/snapshot during commmit
ctx, done, err := client.WithLease(ctx)
if err != nil {
return "", errors.Wrapf(err, "failed to create lease for commit")
}
defer done(ctx)
var (
sn = client.SnapshotService(CurrentSnapshotterName(ctx))
cs = client.ContentStore()
differ = client.DiffService()
)
// export new layer
snapshot, err := c.GetSnapshot(ctx, config.ContainerID)
if err != nil {
return "", errors.Wrap(err, "failed to get snapshot")
}
layer, diffID, err := exportLayer(ctx, snapshot.Name, sn, cs, differ)
if err != nil {
return "", errors.Wrap(err, "failed to export layer")
}
childImg := newChildImage(ctx, config, diffID)
// create new snapshot for new layer
rootfsID := identity.ChainID(childImg.RootFS.DiffIDs).String()
if err = newSnapshot(ctx, rootfsID, config.Image, sn, differ, layer); err != nil {
return "", err
}
defer func() {
if err0 != nil {
log.With(ctx).Warnf("remove snapshot %s cause commit image failed", rootfsID)
client.SnapshotService(CurrentSnapshotterName(ctx)).Remove(ctx, rootfsID)
}
}()
imgJSON, err := json.Marshal(childImg)
if err != nil {
return "", err
}
// new config descriptor
configDesc := ocispec.Descriptor{
MediaType: configType,
Digest: digest.FromBytes(imgJSON),
Size: int64(len(imgJSON)),
}
// get parent image layer descriptor
pmfst, err := images.Manifest(ctx, cs, config.CImage.Target(), platforms.Default())
if err != nil {
return "", err
}
// new layer descriptor
layers := append(pmfst.Layers, layer)
labels := map[string]string{
"containerd.io/gc.ref.content.0": configDesc.Digest.String(),
}
for i, l := range layers {
labels[fmt.Sprintf("containerd.io/gc.ref.content.%d", i+1)] = l.Digest.String()
}
// new manifest descriptor
mfst := struct {
MediaType string `json:"mediaType,omitempty"`
ocispec.Manifest
}{
MediaType: manifestType,
Manifest: ocispec.Manifest{
Versioned: specs.Versioned{
SchemaVersion: 2,
},
Config: configDesc,
Layers: layers,
},
}
mfstJSON, err := json.MarshalIndent(mfst, "", " ")
if err != nil {
return "", errors.Wrap(err, "failed to marshal manifest")
}
mfstDigest := digest.FromBytes(mfstJSON)
mfstDesc := ocispec.Descriptor{
Digest: mfstDigest,
Size: int64(len(mfstJSON)),
}
desc := ocispec.Descriptor{
MediaType: manifestType,
Digest: mfstDigest,
Size: int64(len(mfstJSON)),
}
// image create
img := images.Image{
Name: config.Reference,
Target: desc,
CreatedAt: time.Now(),
}
// register containerd image metadata.
if _, err := client.ImageService().Update(ctx, img); err != nil {
if !errdefs.IsNotFound(err) {
return "", fmt.Errorf("failed to cover exist image %s", err)
}
if _, err := client.ImageService().Create(ctx, img); err != nil {
return "", fmt.Errorf("failed to create new image %s", err)
}
}
// write manifest content
ref := mfstDigest.String()
if err := content.WriteBlob(ctx, cs, ref, bytes.NewReader(mfstJSON), mfstDesc, content.WithLabels(labels)); err != nil {
return "", errors.Wrapf(err, "error writing manifest blob %s", mfstDigest)
}
// write config content
ref = configDesc.Digest.String()
labelOpt := content.WithLabels(map[string]string{
fmt.Sprintf("containerd.io/gc.ref.snapshot.%s", CurrentSnapshotterName(ctx)): rootfsID,
})
if err := content.WriteBlob(ctx, cs, ref, bytes.NewReader(imgJSON), configDesc, labelOpt); err != nil {
return "", errors.Wrap(err, "error writing config blob")
}
// pouch record config descriptor digest as image id.
return configDesc.Digest, nil
}
// export a new layer from a container
func exportLayer(ctx context.Context, name string, sn snapshots.Snapshotter, cs content.Store, comparer diff.Comparer) (ocispec.Descriptor, digest.Digest, error) {
// export new layer
rwDesc, err := createDiff(ctx, name, sn, comparer)
if err != nil {
return ocispec.Descriptor{}, digest.Digest(""), fmt.Errorf("failed to diff: %s", err)
}
info, err := cs.Info(ctx, rwDesc.Digest)
if err != nil {
return ocispec.Descriptor{}, digest.Digest(""), fmt.Errorf("failed to get exported layer info: %s", err)
}
diffIDStr, ok := info.Labels[containerdUncompressed]
if !ok {
return ocispec.Descriptor{}, digest.Digest(""), fmt.Errorf("invalid differ response with no diffID")
}
diffID, err := digest.Parse(diffIDStr)
if err != nil {
return ocispec.Descriptor{}, digest.Digest(""), err
}
layer := ocispec.Descriptor{
MediaType: layerType,
Digest: rwDesc.Digest,
Size: info.Size,
}
return layer, diffID, nil
}
// createDiff copied from containerd vendor and fix two things:
//
// 1. don't use canceled context
// 2. add the random string to lowdir
func createDiff(ctx context.Context, snapshotID string, sn snapshots.Snapshotter, d diff.Comparer, opts ...diff.Opt) (ocispec.Descriptor, error) {
// NOTE: the passthrough context might be canceled and we can't use
// the ctx to do any cleanup things.
//
// in pouch, we set default ns to containerd client so that we don't
// need set namespace to clean context.
cctx := context.TODO()
info, err := sn.Stat(ctx, snapshotID)
if err != nil {
return ocispec.Descriptor{}, err
}
randKey := utils.RandString(5, "", "")
lowerKey := fmt.Sprintf("%s-parent-view-%s", info.Parent, randKey)
lower, err := sn.View(ctx, lowerKey, info.Parent)
if err != nil {
return ocispec.Descriptor{}, err
}
defer func() {
if err := sn.Remove(cctx, lowerKey); err != nil {
log.With(cctx).Warnf("failed to cleanup diff lower snapshotter(key=%s): %v", lowerKey, err)
}
}()
var upper []mount.Mount
if info.Kind == snapshots.KindActive {
upper, err = sn.Mounts(ctx, snapshotID)
if err != nil {
return ocispec.Descriptor{}, err
}
} else {
upperKey := fmt.Sprintf("%s-view-%s", snapshotID, randKey)
upper, err = sn.View(ctx, upperKey, snapshotID)
if err != nil {
return ocispec.Descriptor{}, err
}
defer func() {
if err := sn.Remove(cctx, upperKey); err != nil {
log.With(cctx).Warnf("failed to cleanup diff upper snapshotter(key=%s): %v", upperKey, err)
}
}()
}
return d.Compare(ctx, lower, upper, opts...)
}
// create a new child image descriptor
func newChildImage(ctx context.Context, config *CommitConfig, diffID digest.Digest) ocispec.Image {
createdTime := time.Now()
emptyLayer := (diffID == emptyGZLayer)
history := ocispec.History{
Created: &createdTime,
CreatedBy: strings.Join(config.ContainerConfig.Cmd, " "),
Author: config.Author,
Comment: config.Comment,
EmptyLayer: emptyLayer,
}
// new child image
pImg := config.Image
return ocispec.Image{
Architecture: runtime.GOARCH,
OS: runtime.GOOS,
Created: &createdTime,
Author: config.Author,
Config: newImageConfig(config.ContainerConfig),
RootFS: ocispec.RootFS{
Type: "layers",
DiffIDs: append(pImg.RootFS.DiffIDs, diffID),
},
History: append(pImg.History, history),
}
}
// create a new snapshot for exported layer
func newSnapshot(ctx context.Context, name string, pImg ocispec.Image, sn snapshots.Snapshotter, differ diff.Applier, layer ocispec.Descriptor) error {
var (
key = randomid.Generate()
parent = identity.ChainID(pImg.RootFS.DiffIDs).String()
)
mount, err := sn.Prepare(ctx, key, parent)
if err != nil {
return err
}
// apply diff
if _, err = differ.Apply(ctx, layer, mount); err != nil {
return fmt.Errorf("failed to apply layer: %s", err)
}
if err = sn.Commit(ctx, name, key); err != nil {
if !errdefs.IsAlreadyExists(err) {
return fmt.Errorf("failed to commit snapshot %s: %s", key, err)
}
// Destination already exists, cleanup key and return without error
if err := sn.Remove(ctx, key); err != nil {
return fmt.Errorf("failed to cleanup aborted apply %s: %s", key, err)
}
}
return nil
}
// create a new image config descriptor
func newImageConfig(c *types.ContainerConfig) ocispec.ImageConfig {
volumes := make(map[string]struct{})
for i, v := range c.Volumes {
if nv, ok := v.(struct{}); ok {
volumes[i] = struct{}(nv)
}
}
return ocispec.ImageConfig{
User: c.User,
Env: c.Env,
Entrypoint: c.Entrypoint,
Cmd: c.Cmd,
Volumes: volumes,
WorkingDir: c.WorkingDir,
Labels: c.Labels,
}
}