Debian Codegraph @

cmd/ctr-remote/commands/optimize.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 commands
18
19 import (
20 "compress/gzip"
21 "context"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "os"
27 "os/signal"
28 "time"
29
30 "github.com/containerd/containerd"
31 "github.com/containerd/containerd/cmd/ctr/commands"
32 "github.com/containerd/containerd/content"
33 "github.com/containerd/containerd/images"
34 "github.com/containerd/containerd/images/converter"
35 "github.com/containerd/containerd/platforms"
36 "github.com/containerd/stargz-snapshotter/analyzer"
37 "github.com/containerd/stargz-snapshotter/estargz"
38 "github.com/containerd/stargz-snapshotter/estargz/zstdchunked"
39 estargzconvert "github.com/containerd/stargz-snapshotter/nativeconverter/estargz"
40 esgzexternaltocconvert "github.com/containerd/stargz-snapshotter/nativeconverter/estargz/externaltoc"
41 zstdchunkedconvert "github.com/containerd/stargz-snapshotter/nativeconverter/zstdchunked"
42 "github.com/containerd/stargz-snapshotter/recorder"
43 "github.com/containerd/stargz-snapshotter/util/containerdutil"
44 "github.com/klauspost/compress/zstd"
45 "github.com/opencontainers/go-digest"
46 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
47 "github.com/sirupsen/logrus"
48 "github.com/urfave/cli"
49 )
50
51 const defaultPeriod = 10
52
53 // OptimizeCommand converts and optimizes an image
54 var OptimizeCommand = cli.Command{
55 Name: "optimize",
56 Usage: "optimize an image with user-specified workload",
57 ArgsUsage: "[flags] <source_ref> <target_ref>...",
58 Flags: append([]cli.Flag{
59 cli.BoolFlag{
60 Name: "reuse",
61 Usage: "reuse eStargz (already optimized) layers without further conversion",
62 },
63 cli.StringSliceFlag{
64 Name: "platform",
65 Usage: "Pull content from a specific platform",
66 Value: &cli.StringSlice{},
67 },
68 cli.BoolFlag{
69 Name: "all-platforms",
70 Usage: "targeting all platform of the source image",
71 },
72 cli.BoolFlag{
73 Name: "wait-on-signal",
74 Usage: "ignore context cancel and keep the container running until it receives SIGINT (Ctrl + C) sent manually",
75 },
76 cli.StringFlag{
77 Name: "wait-on-line",
78 Usage: "Substring of a stdout line to be waited. When this string is detected, the container will be killed.",
79 },
80 cli.BoolFlag{
81 Name: "no-optimize",
82 Usage: "convert image without optimization",
83 },
84 cli.StringFlag{
85 Name: "record-out",
86 Usage: "record the monitor log to the specified file",
87 },
88 cli.BoolFlag{
89 Name: "oci",
90 Usage: "convert Docker media types to OCI media types",
91 },
92 cli.IntFlag{
93 Name: "estargz-compression-level",
94 Usage: "eStargz compression level",
95 Value: gzip.BestCompression,
96 },
97 cli.BoolFlag{
98 Name: "estargz-external-toc",
99 Usage: "Separate TOC JSON into another image (called \"TOC image\"). The name of TOC image is the original + \"-esgztoc\" suffix. Both eStargz and the TOC image should be pushed to the same registry. stargz-snapshotter refers to the TOC image when it pulls the result eStargz image.",
100 },
101 cli.IntFlag{
102 Name: "estargz-chunk-size",
103 Usage: "eStargz chunk size (not applied to zstd:chunked)",
104 Value: 0,
105 },
106 cli.IntFlag{
107 Name: "estargz-min-chunk-size",
108 Usage: "The minimal number of bytes of data must be written in one gzip stream. Note that this adds a TOC property that old reader doesn't understand (not applied to zstd:chunked)",
109 Value: 0,
110 },
111 cli.BoolFlag{
112 Name: "zstdchunked",
113 Usage: "use zstd compression instead of gzip (a.k.a zstd:chunked)",
114 },
115 cli.IntFlag{
116 Name: "zstdchunked-compression-level",
117 Usage: "zstd:chunked compression level",
118 Value: 3, // SpeedDefault; see also https://pkg.go.dev/github.com/klauspost/compress/zstd#EncoderLevel
119 },
120 }, samplerFlags...),
121 Action: func(clicontext *cli.Context) error {
122 convertOpts := []converter.Opt{}
123 srcRef := clicontext.Args().Get(0)
124 targetRef := clicontext.Args().Get(1)
125 if srcRef == "" || targetRef == "" {
126 return errors.New("src and target image need to be specified")
127 }
128
129 var platformMC platforms.MatchComparer
130 if clicontext.Bool("all-platforms") {
131 platformMC = platforms.All
132 } else {
133 if pss := clicontext.StringSlice("platform"); len(pss) > 0 {
134 var all []ocispec.Platform
135 for _, ps := range pss {
136 p, err := platforms.Parse(ps)
137 if err != nil {
138 return fmt.Errorf("invalid platform %q: %w", ps, err)
139 }
140 all = append(all, p)
141 }
142 platformMC = platforms.Ordered(all...)
143 } else {
144 platformMC = platforms.DefaultStrict()
145 }
146 }
147 convertOpts = append(convertOpts, converter.WithPlatform(platformMC))
148
149 if clicontext.Bool("oci") {
150 convertOpts = append(convertOpts, converter.WithDockerToOCI(true))
151 } else if clicontext.Bool("zstdchunked") {
152 return errors.New("option --zstdchunked must be used in conjunction with --oci")
153 }
154
155 client, ctx, cancel, err := commands.NewClient(clicontext)
156 if err != nil {
157 return err
158 }
159 defer cancel()
160
161 ctx, done, err := client.WithLease(ctx)
162 if err != nil {
163 return err
164 }
165 defer done(ctx)
166
167 recordOut, esgzOptsPerLayer, wrapper, err := analyze(ctx, clicontext, client, srcRef)
168 if err != nil {
169 return err
170 }
171 if recordOutFile := clicontext.String("record-out"); recordOutFile != "" {
172 if err := writeContentFile(ctx, client, recordOut, recordOutFile); err != nil {
173 return fmt.Errorf("failed output record file: %w", err)
174 }
175 }
176 var f converter.ConvertFunc
177 var finalize func(ctx context.Context, cs content.Store, ref string, desc *ocispec.Descriptor) (*images.Image, error)
178 if clicontext.Bool("zstdchunked") {
179 f = zstdchunkedconvert.LayerConvertWithLayerOptsFuncWithCompressionLevel(
180 zstd.EncoderLevelFromZstd(clicontext.Int("zstdchunked-compression-level")), esgzOptsPerLayer)
181 } else if !clicontext.Bool("estargz-external-toc") {
182 f = estargzconvert.LayerConvertWithLayerAndCommonOptsFunc(esgzOptsPerLayer,
183 estargz.WithCompressionLevel(clicontext.Int("estargz-compression-level")),
184 estargz.WithChunkSize(clicontext.Int("estargz-chunk-size")),
185 estargz.WithMinChunkSize(clicontext.Int("estargz-min-chunk-size")))
186 } else {
187 if clicontext.Bool("reuse") {
188 // We require that the layer conversion is triggerd for each layer
189 // to make sure that "finalize" function has the information of all layers.
190 return fmt.Errorf("\"estargz-external-toc\" can't be used with \"reuse\" flag")
191 }
192 f, finalize = esgzexternaltocconvert.LayerConvertWithLayerAndCommonOptsFunc(esgzOptsPerLayer, []estargz.Option{
193 estargz.WithChunkSize(clicontext.Int("estargz-chunk-size")),
194 estargz.WithMinChunkSize(clicontext.Int("estargz-min-chunk-size")),
195 }, clicontext.Int("estargz-compression-level"))
196 }
197 if wrapper != nil {
198 f = wrapper(f)
199 }
200 layerConvertFunc := logWrapper(f)
201
202 sigCh := make(chan os.Signal, 1)
203 signal.Notify(sigCh, os.Interrupt)
204 go func() {
205 // Cleanly cancel conversion
206 select {
207 case s := <-sigCh:
208 logrus.Infof("Got %v", s)
209 cancel()
210 case <-ctx.Done():
211 }
212 }()
213 convertOpts = append(convertOpts, converter.WithLayerConvertFunc(layerConvertFunc))
214 newImg, err := converter.Convert(ctx, client, targetRef, srcRef, convertOpts...)
215 if err != nil {
216 return err
217 }
218 if finalize != nil {
219 newI, err := finalize(ctx, client.ContentStore(), targetRef, &newImg.Target)
220 if err != nil {
221 return err
222 }
223 is := client.ImageService()
224 _ = is.Delete(ctx, newI.Name)
225 finimg, err := is.Create(ctx, *newI)
226 if err != nil {
227 return err
228 }
229 fmt.Fprintln(clicontext.App.Writer, "extra image:", finimg.Name)
230 }
231 fmt.Fprintln(clicontext.App.Writer, newImg.Target.Digest.String())
232 return nil
233 },
234 }
235
236 func writeContentFile(ctx context.Context, client *containerd.Client, dgst digest.Digest, targetFile string) error {
237 fw, err := os.Create(targetFile)
238 if err != nil {
239 return err
240 }
241 defer fw.Close()
242 ra, err := client.ContentStore().ReaderAt(ctx, ocispec.Descriptor{Digest: dgst})
243 if err != nil {
244 return err
245 }
246 defer ra.Close()
247 _, err = io.Copy(fw, io.NewSectionReader(ra, 0, ra.Size()))
248 return err
249 }
250
251 func analyze(ctx context.Context, clicontext *cli.Context, client *containerd.Client, srcRef string) (digest.Digest, map[digest.Digest][]estargz.Option, func(converter.ConvertFunc) converter.ConvertFunc, error) {
252 if clicontext.Bool("no-optimize") {
253 return "", nil, nil, nil
254 }
255
256 // Do analysis only when the target platforms contain the current platform
257 if !clicontext.Bool("all-platforms") {
258 if pss := clicontext.StringSlice("platform"); len(pss) > 0 {
259 containsDefault := false
260 for _, ps := range pss {
261 p, err := platforms.Parse(ps)
262 if err != nil {
263 return "", nil, nil, fmt.Errorf("invalid platform %q: %w", ps, err)
264 }
265 if platforms.DefaultStrict().Match(p) {
266 containsDefault = true
267 }
268 }
269 if !containsDefault {
270 return "", nil, nil, nil // do not run analyzer
271 }
272 }
273 }
274
275 cs := client.ContentStore()
276 is := client.ImageService()
277
278 // Analyze layers and get prioritized files
279 aOpts := []analyzer.Option{analyzer.WithSpecOpts(getSpecOpts(clicontext))}
280 if clicontext.Bool("wait-on-signal") && clicontext.Bool("terminal") {
281 return "", nil, nil, fmt.Errorf("wait-on-signal can't be used with terminal flag")
282 }
283 if clicontext.Bool("wait-on-signal") {
284 aOpts = append(aOpts, analyzer.WithWaitOnSignal())
285 } else {
286 aOpts = append(aOpts,
287 analyzer.WithPeriod(time.Duration(clicontext.Int("period"))*time.Second),
288 analyzer.WithWaitLineOut(clicontext.String("wait-on-line")))
289 }
290 if clicontext.Bool("terminal") {
291 if !clicontext.Bool("i") {
292 return "", nil, nil, fmt.Errorf("terminal flag must be specified with \"-i\"")
293 }
294 aOpts = append(aOpts, analyzer.WithTerminal())
295 }
296 if clicontext.Bool("i") {
297 aOpts = append(aOpts, analyzer.WithStdin())
298 }
299 recordOut, err := analyzer.Analyze(ctx, client, srcRef, aOpts...)
300 if err != nil {
301 return "", nil, nil, err
302 }
303
304 // Parse record file
305 srcImg, err := is.Get(ctx, srcRef)
306 if err != nil {
307 return "", nil, nil, err
308 }
309 manifestDesc, err := containerdutil.ManifestDesc(ctx, cs, srcImg.Target, platforms.DefaultStrict())
310 if err != nil {
311 return "", nil, nil, err
312 }
313 p, err := content.ReadBlob(ctx, cs, manifestDesc)
314 if err != nil {
315 return "", nil, nil, err
316 }
317 var manifest ocispec.Manifest
318 if err := json.Unmarshal(p, &manifest); err != nil {
319 return "", nil, nil, err
320 }
321 // TODO: this should be indexed by layer "index" (not "digest")
322 layerLogs := make(map[digest.Digest][]string, len(manifest.Layers))
323 ra, err := cs.ReaderAt(ctx, ocispec.Descriptor{Digest: recordOut})
324 if err != nil {
325 return "", nil, nil, err
326 }
327 defer ra.Close()
328 dec := json.NewDecoder(io.NewSectionReader(ra, 0, ra.Size()))
329 added := make(map[digest.Digest]map[string]struct{}, len(manifest.Layers))
330 for dec.More() {
331 var e recorder.Entry
332 if err := dec.Decode(&e); err != nil {
333 return "", nil, nil, err
334 }
335 if *e.LayerIndex < len(manifest.Layers) &&
336 e.ManifestDigest == manifestDesc.Digest.String() {
337 dgst := manifest.Layers[*e.LayerIndex].Digest
338 if added[dgst] == nil {
339 added[dgst] = map[string]struct{}{}
340 }
341 if _, ok := added[dgst][e.Path]; !ok {
342 added[dgst][e.Path] = struct{}{}
343 layerLogs[dgst] = append(layerLogs[dgst], e.Path)
344 }
345 }
346 }
347
348 // Create a converter wrapper for skipping layer conversion. This skip occurs
349 // if "reuse" option is specified, the source layer is already valid estargz
350 // and no access occur to that layer.
351 var excludes []digest.Digest
352 layerOpts := make(map[digest.Digest][]estargz.Option, len(manifest.Layers))
353 for _, desc := range manifest.Layers {
354 if layerLog, ok := layerLogs[desc.Digest]; ok && len(layerLog) > 0 {
355 layerOpts[desc.Digest] = []estargz.Option{estargz.WithPrioritizedFiles(layerLog)}
356 } else if clicontext.Bool("reuse") && isReusableESGZLayer(ctx, desc, cs) {
357 excludes = append(excludes, desc.Digest) // reuse layer without conversion
358 }
359 }
360 return recordOut, layerOpts, excludeWrapper(excludes), nil
361 }
362
363 func isReusableESGZLayer(ctx context.Context, desc ocispec.Descriptor, cs content.Store) bool {
364 dgstStr, ok := desc.Annotations[estargz.TOCJSONDigestAnnotation]
365 if !ok {
366 return false
367 }
368 tocdgst, err := digest.Parse(dgstStr)
369 if err != nil {
370 return false
371 }
372 ra, err := cs.ReaderAt(ctx, desc)
373 if err != nil {
374 return false
375 }
376 defer ra.Close()
377 r, err := estargz.Open(io.NewSectionReader(ra, 0, desc.Size), estargz.WithDecompressors(new(zstdchunked.Decompressor)))
378 if err != nil {
379 return false
380 }
381 if _, err := r.VerifyTOC(tocdgst); err != nil {
382 return false
383 }
384 return true
385 }
386
387 func excludeWrapper(excludes []digest.Digest) func(converter.ConvertFunc) converter.ConvertFunc {
388 return func(convertFunc converter.ConvertFunc) converter.ConvertFunc {
389 return func(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (*ocispec.Descriptor, error) {
390 for _, e := range excludes {
391 if e == desc.Digest {
392 logrus.Warnf("reusing %q without conversion", e)
393 return nil, nil
394 }
395 }
396 return convertFunc(ctx, cs, desc)
397 }
398 }
399 }
400
401 func logWrapper(convertFunc converter.ConvertFunc) converter.ConvertFunc {
402 return func(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (*ocispec.Descriptor, error) {
403 logrus.WithField("digest", desc.Digest).Infof("converting...")
404 return convertFunc(ctx, cs, desc)
405 }
406 }