Debian Codegraph @

nativeconverter/estargz/externaltoc/converter.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package externaltoc
18
19 import (
20 "context"
21 "encoding/json"
22 "fmt"
23 "io"
24 "sort"
25 "time"
26
27 "github.com/containerd/containerd/archive/compression"
28 "github.com/containerd/containerd/content"
29 "github.com/containerd/containerd/errdefs"
30 "github.com/containerd/containerd/images"
31 "github.com/containerd/containerd/images/converter"
32 "github.com/containerd/containerd/images/converter/uncompress"
33 "github.com/containerd/containerd/labels"
34 "github.com/containerd/containerd/reference"
35 "github.com/containerd/stargz-snapshotter/estargz"
36 esgzexternaltoc "github.com/containerd/stargz-snapshotter/estargz/externaltoc"
37 estargzconvert "github.com/containerd/stargz-snapshotter/nativeconverter/estargz"
38 "github.com/containerd/stargz-snapshotter/util/ioutils"
39 "github.com/opencontainers/go-digest"
40 ocispecspec "github.com/opencontainers/image-spec/specs-go"
41 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
42 )
43
44 // LayerConvertFunc converts legacy tar.gz layers into eStargz tar.gz layers.
45 //
46 // finalize() callback function returned by this function will return the image that contains
47 // external TOC of each layer. Note that the returned image by isn't stored to the containerd image
48 // store so far so the caller needs to do it.
49 //
50 // Media type is unchanged.
51 //
52 // Should be used in conjunction with WithDockerToOCI().
53 //
54 // Otherwise "containerd.io/snapshot/stargz/toc.digest" annotation will be lost,
55 // because the Docker media type does not support layer annotations.
56 //
57 // WithCompression() in esgzOpts will be ignored but used the one for external TOC instead.
58 func LayerConvertFunc(esgzOpts []estargz.Option, compressionLevel int) (convertFunc converter.ConvertFunc, finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error)) {
59 return layerConvert(func(c estargz.Compression) converter.ConvertFunc {
60 return estargzconvert.LayerConvertFunc(append(esgzOpts, estargz.WithCompression(c))...)
61 }, compressionLevel)
62 }
63
64 // LayerConvertWithLayerAndCommonOptsFunc converts legacy tar.gz layers into eStargz.
65 // Media type is unchanged. Should be used in conjunction with WithDockerToOCI(). See
66 // LayerConvertFunc for more details. The difference between this function and
67 // LayerConvertFunc is that this allows to specify additional eStargz options per layer.
68 func LayerConvertWithLayerAndCommonOptsFunc(opts map[digest.Digest][]estargz.Option, commonOpts []estargz.Option, compressionLevel int) (convertFunc converter.ConvertFunc, finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error)) {
69 return layerConvert(func(c estargz.Compression) converter.ConvertFunc {
70 return estargzconvert.LayerConvertWithLayerAndCommonOptsFunc(opts, append(commonOpts,
71 estargz.WithCompression(c),
72 )...)
73 }, compressionLevel)
74 }
75
76 // LayerConvertLossLessConfig is configuration for LayerConvertLossLessFunc.
77 type LayerConvertLossLessConfig struct {
78 CompressionLevel int
79 ChunkSize int
80 MinChunkSize int
81 }
82
83 // LayerConvertLossLessFunc converts legacy tar.gz layers into eStargz tar.gz layers without changing
84 // the diffIDs (i.e. uncompressed digest).
85 //
86 // finalize() callback function returned by this function will return the image that contains
87 // external TOC of each layer. Note that the returned image by isn't stored to the containerd image
88 // store so far so the caller needs to do it.
89 //
90 // Media type is unchanged.
91 //
92 // Should be used in conjunction with WithDockerToOCI().
93 //
94 // Otherwise "containerd.io/snapshot/stargz/toc.digest" annotation will be lost,
95 // because the Docker media type does not support layer annotations.
96 //
97 // WithCompression() in esgzOpts will be ignored but used the one for external TOC instead.
98 func LayerConvertLossLessFunc(cfg LayerConvertLossLessConfig) (convertFunc converter.ConvertFunc, finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error)) {
99 return layerConvert(func(c estargz.Compression) converter.ConvertFunc {
100 return layerLossLessConvertFunc(c, cfg.ChunkSize, cfg.MinChunkSize)
101 }, cfg.CompressionLevel)
102 }
103
104 func layerConvert(layerConvertFunc func(estargz.Compression) converter.ConvertFunc, compressionLevel int) (convertFunc converter.ConvertFunc, finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error)) {
105 type tocInfo struct {
106 digest digest.Digest
107 size int64
108 }
109 esgzDigest2TOC := make(map[digest.Digest]tocInfo)
110 // TODO: currently, all layers of all platforms are combined to one TOC manifest. Maybe we can consider
111 // having a separated TOC manifest per platform.
112 converterFunc := func(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (*ocispec.Descriptor, error) {
113 cm := esgzexternaltoc.NewGzipCompressionWithLevel(nil, compressionLevel)
114 c := cm.(*esgzexternaltoc.GzipCompression)
115 cf := layerConvertFunc(c)
116 desc2, err := cf(ctx, cs, desc)
117 if err != nil {
118 return desc2, err
119 }
120 var layerDgst digest.Digest
121 if desc2 != nil {
122 layerDgst = desc2.Digest
123 } else {
124 layerDgst = desc.Digest // no conversion happened
125 }
126 dgst, size, err := writeTOCTo(ctx, c, cs)
127 if err != nil {
128 return nil, err
129 }
130 esgzDigest2TOC[layerDgst] = tocInfo{dgst, size}
131 return desc2, nil
132 }
133 finalizeFunc := func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error) {
134 var layers []ocispec.Descriptor
135 for esgzDigest, toc := range esgzDigest2TOC {
136 layers = append(layers, ocispec.Descriptor{
137 MediaType: ocispec.MediaTypeImageLayerGzip,
138 Digest: toc.digest,
139 Size: toc.size,
140 Annotations: map[string]string{
141 "containerd.io/snapshot/stargz/layer.digest": esgzDigest.String(),
142 },
143 })
144 }
145 sort.Slice(layers, func(i, j int) bool {
146 return layers[i].Digest.String() < layers[j].Digest.String()
147 })
148 mfst, err := createManifest(ctx, cs, ocispec.ImageConfig{}, layers)
149 if err != nil {
150 return nil, err
151 }
152 tocImgRef, err := getTOCReference(ref)
153 if err != nil {
154 return nil, err
155 }
156 return &images.Image{
157 Name: tocImgRef,
158 Target: *mfst,
159 }, nil
160 }
161 return converterFunc, finalizeFunc
162 }
163
164 func getTOCReference(ref string) (string, error) {
165 refspec, err := reference.Parse(ref)
166 if err != nil {
167 return "", err
168 }
169 refspec.Object = refspec.Object + "-esgztoc" // TODO: support custom location
170 return refspec.String(), nil
171 }
172
173 func layerLossLessConvertFunc(compressor estargz.Compressor, chunkSize int, minChunkSize int) converter.ConvertFunc {
174 return func(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (*ocispec.Descriptor, error) {
175 if !images.IsLayerType(desc.MediaType) {
176 // No conversion. No need to return an error here.
177 return nil, nil
178 }
179 info, err := cs.Info(ctx, desc.Digest)
180 if err != nil {
181 return nil, err
182 }
183 labelz := info.Labels
184 if labelz == nil {
185 labelz = make(map[string]string)
186 }
187
188 ra, err := cs.ReaderAt(ctx, desc)
189 if err != nil {
190 return nil, err
191 }
192 defer ra.Close()
193 sr := io.NewSectionReader(ra, 0, desc.Size)
194 ref := fmt.Sprintf("convert-estargz-from-%s", desc.Digest)
195 w, err := content.OpenWriter(ctx, cs, content.WithRef(ref))
196 if err != nil {
197 return nil, err
198 }
199 defer w.Close()
200
201 // Reset the writing position
202 // Old writer possibly remains without aborted
203 // (e.g. conversion interrupted by a signal)
204 if err := w.Truncate(0); err != nil {
205 return nil, err
206 }
207
208 // Copy and count the contents
209 esgzUW, esgzUncompressedInfoCh := calcUncompression()
210 orgUW, orgUncompressedInfoCh := calcUncompression()
211 countW := new(ioutils.CountWriter)
212 mw := io.MultiWriter(io.MultiWriter(w, countW), esgzUW)
213 var ew *estargz.Writer
214 if compressor != nil {
215 ew = estargz.NewWriterWithCompressor(mw, compressor)
216 } else {
217 ew = estargz.NewWriter(mw)
218 }
219 if chunkSize > 0 {
220 ew.ChunkSize = chunkSize
221 }
222 ew.MinChunkSize = minChunkSize
223 if err := ew.AppendTarLossLess(io.TeeReader(sr, orgUW)); err != nil {
224 return nil, fmt.Errorf("cannot perform compression in lossless way: %w", err)
225 }
226 tocDgst, err := ew.Close()
227 if err != nil {
228 return nil, err
229 }
230 n := countW.Size()
231 if err := esgzUW.Close(); err != nil {
232 return nil, err
233 }
234 if err := orgUW.Close(); err != nil {
235 return nil, err
236 }
237 esgzUncompressedInfo := <-esgzUncompressedInfoCh
238 orgUncompressedInfo := <-orgUncompressedInfoCh
239
240 // check the lossless conversion
241 if esgzUncompressedInfo.diffID.String() != orgUncompressedInfo.diffID.String() {
242 return nil, fmt.Errorf("unexpected diffID %q; want %q",
243 esgzUncompressedInfo.diffID.String(), orgUncompressedInfo.diffID.String())
244 }
245 if esgzUncompressedInfo.size != orgUncompressedInfo.size {
246 return nil, fmt.Errorf("unexpected uncompressed size %q; want %q",
247 esgzUncompressedInfo.size, orgUncompressedInfo.size)
248 }
249
250 // write diffID label
251 labelz[labels.LabelUncompressed] = esgzUncompressedInfo.diffID.String()
252 if err = w.Commit(ctx, n, "", content.WithLabels(labelz)); err != nil && !errdefs.IsAlreadyExists(err) {
253 return nil, err
254 }
255 if err := w.Close(); err != nil {
256 return nil, err
257 }
258 newDesc := desc
259 if uncompress.IsUncompressedType(newDesc.MediaType) {
260 if images.IsDockerType(newDesc.MediaType) {
261 newDesc.MediaType += ".gzip"
262 } else {
263 newDesc.MediaType += "+gzip"
264 }
265 }
266 newDesc.Digest = w.Digest()
267 newDesc.Size = n
268 if newDesc.Annotations == nil {
269 newDesc.Annotations = make(map[string]string, 1)
270 }
271 newDesc.Annotations[estargz.TOCJSONDigestAnnotation] = tocDgst.String()
272 newDesc.Annotations[estargz.StoreUncompressedSizeAnnotation] = fmt.Sprintf("%d", esgzUncompressedInfo.size)
273 return &newDesc, nil
274 }
275 }
276
277 type uncompressedInfo struct {
278 diffID digest.Digest
279 size int64
280 }
281
282 func calcUncompression() (*io.PipeWriter, chan uncompressedInfo) {
283 pr, pw := io.Pipe()
284 infoCh := make(chan uncompressedInfo)
285 go func() {
286 defer pr.Close()
287
288 c := new(ioutils.CountWriter)
289 diffID := digest.Canonical.Digester()
290 decompressR, err := compression.DecompressStream(pr)
291 if err != nil {
292 pr.CloseWithError(err)
293 close(infoCh)
294 return
295 }
296 defer decompressR.Close()
297 if _, err := io.Copy(io.MultiWriter(c, diffID.Hash()), decompressR); err != nil {
298 pr.CloseWithError(err)
299 close(infoCh)
300 return
301 }
302 infoCh <- uncompressedInfo{
303 diffID: diffID.Digest(),
304 size: c.Size(),
305 }
306 }()
307 return pw, infoCh
308 }
309
310 func writeTOCTo(ctx context.Context, gc *esgzexternaltoc.GzipCompression, cs content.Store) (digest.Digest, int64, error) {
311 ref := "external-toc" + time.Now().String()
312 w, err := content.OpenWriter(ctx, cs, content.WithRef(ref))
313 if err != nil {
314 return "", 0, err
315 }
316 defer w.Close()
317 if err := w.Truncate(0); err != nil {
318 return "", 0, err
319 }
320 c := new(ioutils.CountWriter)
321 dgstr := digest.Canonical.Digester()
322 n, err := gc.WriteTOCTo(io.MultiWriter(io.MultiWriter(w, dgstr.Hash()), c))
323 if err != nil {
324 return "", 0, err
325 }
326 if err := w.Commit(ctx, int64(n), ""); err != nil && !errdefs.IsAlreadyExists(err) {
327 return "", 0, err
328 }
329 if err := w.Close(); err != nil {
330 return "", 0, err
331 }
332
333 return dgstr.Digest(), c.Size(), nil
334 }
335
336 func createManifest(ctx context.Context, cs content.Store, config ocispec.ImageConfig, layers []ocispec.Descriptor) (*ocispec.Descriptor, error) {
337 // Create config
338 configDgst, configSize, err := writeJSON(ctx, cs, &config, nil)
339 if err != nil {
340 return nil, err
341 }
342
343 // Create manifest
344 mfst := ocispec.Manifest{
345 Versioned: ocispecspec.Versioned{
346 SchemaVersion: 2,
347 },
348 MediaType: ocispec.MediaTypeImageManifest,
349 Config: ocispec.Descriptor{
350 MediaType: ocispec.MediaTypeImageConfig,
351 Digest: configDgst,
352 Size: configSize,
353 },
354 Layers: layers,
355 }
356 mfstLabels := make(map[string]string)
357 for i, ld := range mfst.Layers {
358 mfstLabels[fmt.Sprintf("containerd.io/gc.ref.content.l.%d", i)] = ld.Digest.String()
359 }
360 mfstLabels["containerd.io/gc.ref.content.c.0"] = configDgst.String()
361 mfstDgst, mfstSize, err := writeJSON(ctx, cs, &mfst, mfstLabels)
362 if err != nil {
363 return nil, err
364 }
365
366 return &ocispec.Descriptor{
367 MediaType: ocispec.MediaTypeImageManifest,
368 Digest: mfstDgst,
369 Size: mfstSize,
370 }, nil
371 }
372 func writeJSON(ctx context.Context, cs content.Store, data interface{}, labels map[string]string) (digest.Digest, int64, error) {
373 raw, err := json.Marshal(data)
374 if err != nil {
375 return "", 0, err
376 }
377 size := len(raw)
378 ref := "write-json-ref" + digest.FromBytes(raw).String()
379 w, err := content.OpenWriter(ctx, cs, content.WithRef(ref))
380 if err != nil {
381 return "", 0, err
382 }
383 defer w.Close()
384 if err := w.Truncate(0); err != nil {
385 return "", 0, err
386 }
387 if _, err := w.Write(raw); err != nil {
388 return "", 0, err
389 }
390 if err = w.Commit(ctx, int64(size), "", content.WithLabels(labels)); err != nil && !errdefs.IsAlreadyExists(err) {
391 return "", 0, err
392 }
393 dgst := w.Digest()
394 if err := w.Close(); err != nil {
395 return "", 0, err
396 }
397 return dgst, int64(size), nil
398 }