forked from containerd/nerdctl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.go
More file actions
394 lines (360 loc) · 12.4 KB
/
convert.go
File metadata and controls
394 lines (360 loc) · 12.4 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package image
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/klauspost/compress/zstd"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
overlaybdconvert "github.com/containerd/accelerated-container-image/pkg/convertor"
containerd "github.com/containerd/containerd/v2/client"
"github.com/containerd/containerd/v2/core/content"
"github.com/containerd/containerd/v2/core/images"
"github.com/containerd/containerd/v2/core/images/converter"
"github.com/containerd/containerd/v2/core/images/converter/uncompress"
"github.com/containerd/log"
nydusconvert "github.com/containerd/nydus-snapshotter/pkg/converter"
"github.com/containerd/stargz-snapshotter/estargz"
estargzconvert "github.com/containerd/stargz-snapshotter/nativeconverter/estargz"
estargzexternaltocconvert "github.com/containerd/stargz-snapshotter/nativeconverter/estargz/externaltoc"
zstdchunkedconvert "github.com/containerd/stargz-snapshotter/nativeconverter/zstdchunked"
"github.com/containerd/stargz-snapshotter/recorder"
"github.com/containerd/nerdctl/v2/pkg/api/types"
"github.com/containerd/nerdctl/v2/pkg/clientutil"
converterutil "github.com/containerd/nerdctl/v2/pkg/imgutil/converter"
"github.com/containerd/nerdctl/v2/pkg/platformutil"
"github.com/containerd/nerdctl/v2/pkg/referenceutil"
"github.com/containerd/nerdctl/v2/pkg/snapshotterutil"
)
func Convert(ctx context.Context, client *containerd.Client, srcRawRef, targetRawRef string, options types.ImageConvertOptions) error {
var (
convertOpts = []converter.Opt{}
)
if srcRawRef == "" || targetRawRef == "" {
return errors.New("src and target image need to be specified")
}
parsedReference, err := referenceutil.Parse(srcRawRef)
if err != nil {
return err
}
srcRef := parsedReference.String()
parsedReference, err = referenceutil.Parse(targetRawRef)
if err != nil {
return err
}
targetRef := parsedReference.String()
platMC, err := platformutil.NewMatchComparer(options.AllPlatforms, options.Platforms)
if err != nil {
return err
}
convertOpts = append(convertOpts, converter.WithPlatform(platMC))
// Ensure all the layers are here: https://github.com/containerd/nerdctl/issues/3425
err = EnsureAllContent(ctx, client, srcRef, platMC, options.GOptions)
if err != nil {
return err
}
estargz := options.Estargz
zstd := options.Zstd
zstdchunked := options.ZstdChunked
overlaybd := options.Overlaybd
nydus := options.Nydus
soci := options.Soci
var finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error)
if estargz || zstd || zstdchunked || overlaybd || nydus || soci {
convertCount := 0
if estargz {
convertCount++
}
if zstd {
convertCount++
}
if zstdchunked {
convertCount++
}
if overlaybd {
convertCount++
}
if nydus {
convertCount++
}
if soci {
convertCount++
}
if convertCount > 1 {
return errors.New("options --estargz, --zstdchunked, --overlaybd, --nydus and --soci lead to conflict, only one of them can be used")
}
var convertFunc converter.ConvertFunc
var convertType string
switch {
case estargz:
convertFunc, finalize, err = getESGZConverter(options)
if err != nil {
return err
}
convertType = "estargz"
case zstd:
convertFunc, err = getZstdConverter(options)
if err != nil {
return err
}
convertType = "zstd"
case zstdchunked:
convertFunc, err = getZstdchunkedConverter(options)
if err != nil {
return err
}
convertType = "zstdchunked"
case overlaybd:
obdOpts, err := getOBDConvertOpts(options)
if err != nil {
return err
}
obdOpts = append(obdOpts, overlaybdconvert.WithClient(client))
obdOpts = append(obdOpts, overlaybdconvert.WithImageRef(srcRef))
convertFunc = overlaybdconvert.IndexConvertFunc(obdOpts...)
convertOpts = append(convertOpts, converter.WithIndexConvertFunc(convertFunc))
convertType = "overlaybd"
case nydus:
nydusOpts, err := getNydusConvertOpts(options)
if err != nil {
return err
}
convertHooks := converter.ConvertHooks{
PostConvertHook: nydusconvert.ConvertHookFunc(nydusconvert.MergeOption{
WorkDir: nydusOpts.WorkDir,
BuilderPath: nydusOpts.BuilderPath,
FsVersion: nydusOpts.FsVersion,
ChunkDictPath: nydusOpts.ChunkDictPath,
PrefetchPatterns: nydusOpts.PrefetchPatterns,
OCI: true,
}),
}
convertOpts = append(convertOpts, converter.WithIndexConvertFunc(
converter.IndexConvertFuncWithHook(
nydusconvert.LayerConvertFunc(*nydusOpts),
true,
platMC,
convertHooks,
)),
)
convertType = "nydus"
case soci:
// Convert image to SOCI format
convertedRef, err := snapshotterutil.ConvertSociIndexV2(ctx, client, srcRef, targetRef, options.GOptions, options.Platforms, options.SociOptions)
if err != nil {
return fmt.Errorf("failed to convert image to SOCI format: %w", err)
}
res := converterutil.ConvertedImageInfo{
Image: convertedRef,
}
return printConvertedImage(options.Stdout, options, res)
}
if convertType != "overlaybd" {
convertOpts = append(convertOpts, converter.WithLayerConvertFunc(convertFunc))
}
if !options.Oci {
if nydus || overlaybd {
log.G(ctx).Warnf("option --%s should be used in conjunction with --oci, forcibly enabling on oci mediatype for %s conversion", convertType, convertType)
} else {
log.G(ctx).Warnf("option --%s should be used in conjunction with --oci", convertType)
}
}
if options.Uncompress {
return fmt.Errorf("option --%s conflicts with --uncompress", convertType)
}
}
if options.Uncompress {
convertOpts = append(convertOpts, converter.WithLayerConvertFunc(uncompress.LayerConvertFunc))
}
if options.Oci {
convertOpts = append(convertOpts, converter.WithDockerToOCI(true))
}
// converter.Convert() gains the lease by itself
newImg, err := converterutil.Convert(ctx, client, targetRef, srcRef, convertOpts...)
if err != nil {
return err
}
res := converterutil.ConvertedImageInfo{
Image: newImg.Name + "@" + newImg.Target.Digest.String(),
}
if finalize != nil {
ctx, done, err := client.WithLease(ctx)
if err != nil {
return err
}
defer done(ctx)
newI, err := finalize(ctx, client.ContentStore(), targetRef, &newImg.Target)
if err != nil {
return err
}
is := client.ImageService()
finimg, err := is.Update(ctx, *newI)
if err != nil {
return err
}
res.ExtraImages = append(res.ExtraImages, finimg.Name+"@"+finimg.Target.Digest.String())
}
return printConvertedImage(options.Stdout, options, res)
}
func getESGZConverter(options types.ImageConvertOptions) (convertFunc converter.ConvertFunc, finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error), _ error) {
if options.EstargzExternalToc && !options.GOptions.Experimental {
return nil, nil, fmt.Errorf("estargz-external-toc requires experimental mode to be enabled")
}
if options.EstargzKeepDiffID && !options.GOptions.Experimental {
return nil, nil, fmt.Errorf("option --estargz-keep-diff-id must be specified with --estargz-external-toc")
}
if options.EstargzExternalToc {
if !options.EstargzKeepDiffID {
esgzOpts, err := getESGZConvertOpts(options)
if err != nil {
return nil, nil, err
}
convertFunc, finalize = estargzexternaltocconvert.LayerConvertFunc(esgzOpts, options.EstargzCompressionLevel)
} else {
convertFunc, finalize = estargzexternaltocconvert.LayerConvertLossLessFunc(estargzexternaltocconvert.LayerConvertLossLessConfig{
CompressionLevel: options.EstargzCompressionLevel,
ChunkSize: options.EstargzChunkSize,
MinChunkSize: options.EstargzMinChunkSize,
})
}
} else {
esgzOpts, err := getESGZConvertOpts(options)
if err != nil {
return nil, nil, err
}
convertFunc = estargzconvert.LayerConvertFunc(esgzOpts...)
}
return convertFunc, finalize, nil
}
func getESGZConvertOpts(options types.ImageConvertOptions) ([]estargz.Option, error) {
esgzOpts := []estargz.Option{
estargz.WithCompressionLevel(options.EstargzCompressionLevel),
estargz.WithChunkSize(options.EstargzChunkSize),
estargz.WithMinChunkSize(options.EstargzMinChunkSize),
}
if options.EstargzRecordIn != "" {
if !options.GOptions.Experimental {
return nil, fmt.Errorf("estargz-record-in requires experimental mode to be enabled")
}
log.L.Warn("--estargz-record-in flag is experimental and subject to change")
paths, err := readPathsFromRecordFile(options.EstargzRecordIn)
if err != nil {
return nil, err
}
esgzOpts = append(esgzOpts, estargz.WithPrioritizedFiles(paths))
var ignored []string
esgzOpts = append(esgzOpts, estargz.WithAllowPrioritizeNotFound(&ignored))
}
return esgzOpts, nil
}
func getZstdConverter(options types.ImageConvertOptions) (converter.ConvertFunc, error) {
return converterutil.ZstdLayerConvertFunc(options)
}
func getZstdchunkedConverter(options types.ImageConvertOptions) (converter.ConvertFunc, error) {
esgzOpts := []estargz.Option{
estargz.WithChunkSize(options.ZstdChunkedChunkSize),
}
if options.ZstdChunkedRecordIn != "" {
if !options.GOptions.Experimental {
return nil, fmt.Errorf("zstdchunked-record-in requires experimental mode to be enabled")
}
log.L.Warn("--zstdchunked-record-in flag is experimental and subject to change")
paths, err := readPathsFromRecordFile(options.ZstdChunkedRecordIn)
if err != nil {
return nil, err
}
esgzOpts = append(esgzOpts, estargz.WithPrioritizedFiles(paths))
var ignored []string
esgzOpts = append(esgzOpts, estargz.WithAllowPrioritizeNotFound(&ignored))
}
return zstdchunkedconvert.LayerConvertFuncWithCompressionLevel(zstd.EncoderLevelFromZstd(options.ZstdChunkedCompressionLevel), esgzOpts...), nil
}
func getNydusConvertOpts(options types.ImageConvertOptions) (*nydusconvert.PackOption, error) {
workDir := options.NydusWorkDir
if workDir == "" {
var err error
workDir, err = clientutil.DataStore(options.GOptions.DataRoot, options.GOptions.Address)
if err != nil {
return nil, err
}
}
return &nydusconvert.PackOption{
BuilderPath: options.NydusBuilderPath,
// the path will finally be used is <NERDCTL_DATA_ROOT>/nydus-converter-<hash>,
// for example: /var/lib/nerdctl/1935db59/nydus-converter-3269662176/,
// and it will be deleted after the conversion
WorkDir: workDir,
PrefetchPatterns: options.NydusPrefetchPatterns,
Compressor: options.NydusCompressor,
FsVersion: "6",
}, nil
}
func getOBDConvertOpts(options types.ImageConvertOptions) ([]overlaybdconvert.Option, error) {
obdOpts := []overlaybdconvert.Option{
overlaybdconvert.WithFsType(options.OverlayFsType),
overlaybdconvert.WithDbstr(options.OverlaydbDBStr),
}
return obdOpts, nil
}
func readPathsFromRecordFile(filename string) ([]string, error) {
r, err := os.Open(filename)
if err != nil {
return nil, err
}
defer r.Close()
dec := json.NewDecoder(r)
var paths []string
added := make(map[string]struct{})
for dec.More() {
var e recorder.Entry
if err := dec.Decode(&e); err != nil {
return nil, err
}
if _, ok := added[e.Path]; !ok {
paths = append(paths, e.Path)
added[e.Path] = struct{}{}
}
}
return paths, nil
}
func printConvertedImage(stdout io.Writer, options types.ImageConvertOptions, img converterutil.ConvertedImageInfo) error {
switch options.Format {
case "json":
b, err := json.MarshalIndent(img, "", " ")
if err != nil {
return err
}
fmt.Fprintln(stdout, string(b))
default:
for i, e := range img.ExtraImages {
elems := strings.SplitN(e, "@", 2)
if len(elems) < 2 {
log.L.Errorf("extra reference %q doesn't contain digest", e)
} else {
log.L.Infof("Extra image(%d) %s", i, elems[0])
}
}
elems := strings.SplitN(img.Image, "@", 2)
if len(elems) < 2 {
log.L.Errorf("reference %q doesn't contain digest", img.Image)
} else {
fmt.Fprintln(stdout, elems[1])
}
}
return nil
}