Debian Codegraph @

analyzer/recorder/recorder.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 recorder
18
19 import (
20 "archive/tar"
21 "context"
22 "encoding/json"
23 "fmt"
24 "io"
25 "path"
26 "strings"
27 "sync"
28
29 "github.com/containerd/containerd/archive/compression"
30 "github.com/containerd/containerd/content"
31 "github.com/containerd/containerd/errdefs"
32 "github.com/containerd/containerd/images"
33 "github.com/containerd/containerd/images/converter/uncompress"
34 "github.com/containerd/containerd/log"
35 "github.com/containerd/containerd/platforms"
36 "github.com/containerd/stargz-snapshotter/recorder"
37 "github.com/containerd/stargz-snapshotter/util/containerdutil"
38 "github.com/opencontainers/go-digest"
39 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
40 "github.com/rs/xid"
41 "golang.org/x/sync/errgroup"
42 )
43
44 const (
45 whiteoutPrefix = ".wh."
46 whiteoutOpaqueDir = whiteoutPrefix + whiteoutPrefix + ".opq"
47 )
48
49 // ImageRecorder is a wrapper of recorder.Recroder. This holds the relationship
50 // between files and layer index in the specified image. So the client can record
51 // files without knowing about which layer this file belongs to.
52 type ImageRecorder struct {
53 r *recorder.Recorder
54 index []map[string]struct{}
55 manifestDigest digest.Digest
56 recordW content.Writer
57 recordWMu sync.Mutex
58 }
59
60 func NewImageRecorder(ctx context.Context, cs content.Store, img images.Image, platformMC platforms.MatchComparer) (*ImageRecorder, error) {
61 manifestDesc, err := containerdutil.ManifestDesc(ctx, cs, img.Target, platformMC)
62 if err != nil {
63 return nil, err
64 }
65 p, err := content.ReadBlob(ctx, cs, manifestDesc)
66 if err != nil {
67 return nil, err
68 }
69 var manifest ocispec.Manifest
70 if err := json.Unmarshal(p, &manifest); err != nil {
71 return nil, err
72 }
73 return imageRecorderFromManifest(ctx, cs, manifestDesc, manifest)
74 }
75
76 func imageRecorderFromManifest(ctx context.Context, cs content.Store, manifestDesc ocispec.Descriptor, manifest ocispec.Manifest) (*ImageRecorder, error) {
77 var eg errgroup.Group
78 filesMap := make([]map[string]struct{}, len(manifest.Layers))
79 for i, desc := range manifest.Layers {
80 i, desc := i, desc
81 filesMap[i] = make(map[string]struct{})
82
83 // Create the index from the layer blob.
84 // TODO: During optimization, we uncompress the blob several times (here and during
85 // creating eStargz layer). We should unify this process for better optimization
86 // performance.
87 log.G(ctx).Infof("analyzing blob %q", desc.Digest)
88 readerAt, err := cs.ReaderAt(ctx, desc)
89 if err != nil {
90 return nil, fmt.Errorf("failed to get reader blob %v: %w", desc.Digest, err)
91 }
92 defer readerAt.Close()
93 r := io.Reader(io.NewSectionReader(readerAt, 0, desc.Size))
94 if !uncompress.IsUncompressedType(desc.MediaType) {
95 r, err = compression.DecompressStream(r)
96 if err != nil {
97 return nil, fmt.Errorf("cannot decompress layer %v: %w", desc.Digest, err)
98 }
99 }
100 eg.Go(func() error {
101 tr := tar.NewReader(r)
102 for {
103 h, err := tr.Next()
104 if err != nil {
105 if err == io.EOF {
106 break
107 }
108 return err
109 }
110 filesMap[i][cleanEntryName(h.Name)] = struct{}{}
111 }
112 return nil
113 })
114 }
115 if err := eg.Wait(); err != nil {
116 return nil, err
117 }
118
119 recordW, err := content.OpenWriter(ctx, cs,
120 content.WithRef(fmt.Sprintf("recorder-%v", xid.New().String())))
121 if err != nil {
122 return nil, fmt.Errorf("failed to open writer for recorder: %w", err)
123 }
124 return &ImageRecorder{
125 r: recorder.New(recordW),
126 index: filesMap,
127 recordW: recordW,
128 manifestDigest: manifestDesc.Digest,
129 }, nil
130 }
131
132 func (r *ImageRecorder) Record(name string) error {
133 if name == "" {
134 return nil
135 }
136 r.recordWMu.Lock()
137 defer r.recordWMu.Unlock()
138
139 name = cleanEntryName(name)
140 index := -1
141 for i := len(r.index) - 1; i >= 0; i-- {
142 if _, ok := r.index[i][name]; ok {
143 index = i
144 break
145 }
146
147 // If this is deleted by a whiteout file or directory, return error.
148 wh := cleanEntryName(path.Join(path.Dir("/"+name), whiteoutPrefix+path.Base("/"+name)))
149 if _, ok := r.index[i][wh]; ok {
150 return fmt.Errorf("%q is a deleted file", name)
151 }
152 whDir := cleanEntryName(path.Join(path.Dir("/"+name), whiteoutOpaqueDir))
153 if _, ok := r.index[i][whDir]; ok {
154 return fmt.Errorf("Parent dir of %q is a deleted directory", name)
155 }
156 }
157 if index < 0 {
158 return fmt.Errorf("file %q not found in index", name)
159 }
160 return r.r.Record(&recorder.Entry{
161 Path: name,
162 ManifestDigest: r.manifestDigest.String(),
163 LayerIndex: &index,
164 })
165 }
166
167 func (r *ImageRecorder) Commit(ctx context.Context) (digest.Digest, error) {
168 r.recordWMu.Lock()
169 defer r.recordWMu.Unlock()
170
171 if err := r.recordW.Commit(ctx, 0, ""); err != nil && !errdefs.IsAlreadyExists(err) {
172 return "", err
173 }
174 return r.recordW.Digest(), nil
175 }
176
177 func (r *ImageRecorder) Close() error {
178 r.recordWMu.Lock()
179 defer r.recordWMu.Unlock()
180
181 return r.recordW.Close()
182 }
183
184 func cleanEntryName(name string) string {
185 // Use path.Clean to consistently deal with path separators across platforms.
186 return strings.TrimPrefix(path.Clean("/"+name), "/")
187 }