Debian Codegraph @

fs/source/source.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 source
18
19 import (
20 "context"
21 "fmt"
22 "strings"
23
24 "github.com/containerd/containerd/images"
25 "github.com/containerd/containerd/labels"
26 "github.com/containerd/containerd/reference"
27 "github.com/containerd/containerd/remotes/docker"
28 "github.com/containerd/stargz-snapshotter/fs/config"
29 digest "github.com/opencontainers/go-digest"
30 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
31 )
32
33 // GetSources is a function for converting snapshot labels into typed blob sources
34 // information. This package defines a default converter which provides source
35 // information based on some labels but implementations aren't required to use labels.
36 // Implementations are allowed to return several sources (registry config + image refs)
37 // about the blob.
38 type GetSources func(labels map[string]string) (source []Source, err error)
39
40 // RegistryHosts returns a list of registries that provides the specified image.
41 type RegistryHosts func(reference.Spec) ([]docker.RegistryHost, error)
42
43 // Source is a typed blob source information. This contains information about
44 // a blob stored in registries and some contexts of the blob.
45 type Source struct {
46
47 // Hosts is a registry configuration where this blob is stored.
48 Hosts RegistryHosts
49
50 // Name is an image reference which contains this blob.
51 Name reference.Spec
52
53 // Target is a descriptor of this blob.
54 Target ocispec.Descriptor
55
56 // Manifest is an image manifest which contains the blob. This will
57 // be used by the filesystem to pre-resolve some layers contained in
58 // the manifest.
59 // Currently, only layer digests (Manifest.Layers.Digest) will be used.
60 Manifest ocispec.Manifest
61 }
62
63 const (
64 // targetRefLabel is a label which contains image reference.
65 targetRefLabel = "containerd.io/snapshot/remote/stargz.reference"
66
67 // targetDigestLabel is a label which contains layer digest.
68 targetDigestLabel = "containerd.io/snapshot/remote/stargz.digest"
69
70 // targetImageLayersLabel is a label which contains layer digests contained in
71 // the target image.
72 targetImageLayersLabel = "containerd.io/snapshot/remote/stargz.layers"
73
74 // targetImageURLsLabelPrefix is a label prefix which constructs a map from the layer index to
75 // urls of the layer descriptor.
76 targetImageURLsLabelPrefix = "containerd.io/snapshot/remote/urls."
77
78 // targetURsLLabel is a label which contains layer URL. This is only used to pass URL from containerd
79 // to snapshotter.
80 targetURLsLabel = "containerd.io/snapshot/remote/urls"
81 )
82
83 // FromDefaultLabels returns a function for converting snapshot labels to
84 // source information based on labels.
85 func FromDefaultLabels(hosts RegistryHosts) GetSources {
86 return func(labels map[string]string) ([]Source, error) {
87 refStr, ok := labels[targetRefLabel]
88 if !ok {
89 return nil, fmt.Errorf("reference hasn't been passed")
90 }
91 refspec, err := reference.Parse(refStr)
92 if err != nil {
93 return nil, err
94 }
95
96 digestStr, ok := labels[targetDigestLabel]
97 if !ok {
98 return nil, fmt.Errorf("digest hasn't been passed")
99 }
100 target, err := digest.Parse(digestStr)
101 if err != nil {
102 return nil, err
103 }
104
105 var neighboringLayers []ocispec.Descriptor
106 if l, ok := labels[targetImageLayersLabel]; ok {
107 layersStr := strings.Split(l, ",")
108 for i, l := range layersStr {
109 d, err := digest.Parse(l)
110 if err != nil {
111 return nil, err
112 }
113 if d.String() != target.String() {
114 desc := ocispec.Descriptor{Digest: d}
115 if urls, ok := labels[targetImageURLsLabelPrefix+fmt.Sprintf("%d", i)]; ok {
116 desc.URLs = strings.Split(urls, ",")
117 }
118 neighboringLayers = append(neighboringLayers, desc)
119 }
120 }
121 }
122
123 targetDesc := ocispec.Descriptor{
124 Digest: target,
125 Annotations: labels,
126 }
127 if targetURLs, ok := labels[targetURLsLabel]; ok {
128 targetDesc.URLs = append(targetDesc.URLs, strings.Split(targetURLs, ",")...)
129 }
130
131 return []Source{
132 {
133 Hosts: hosts,
134 Name: refspec,
135 Target: targetDesc,
136 Manifest: ocispec.Manifest{Layers: append([]ocispec.Descriptor{targetDesc}, neighboringLayers...)},
137 },
138 }, nil
139 }
140 }
141
142 // AppendDefaultLabelsHandlerWrapper makes a handler which appends image's basic
143 // information to each layer descriptor as annotations during unpack. These
144 // annotations will be passed to this remote snapshotter as labels and used to
145 // construct source information.
146 func AppendDefaultLabelsHandlerWrapper(ref string, prefetchSize int64) func(f images.Handler) images.Handler {
147 return func(f images.Handler) images.Handler {
148 return images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
149 children, err := f.Handle(ctx, desc)
150 if err != nil {
151 return nil, err
152 }
153 switch desc.MediaType {
154 case ocispec.MediaTypeImageManifest, images.MediaTypeDockerSchema2Manifest:
155 for i := range children {
156 c := &children[i]
157 if images.IsLayerType(c.MediaType) {
158 if c.Annotations == nil {
159 c.Annotations = make(map[string]string)
160 }
161 c.Annotations[targetRefLabel] = ref
162 c.Annotations[targetDigestLabel] = c.Digest.String()
163 var layers string
164 for i, l := range children[i:] {
165 if images.IsLayerType(l.MediaType) {
166 ls := fmt.Sprintf("%s,", l.Digest.String())
167 // This avoids the label hits the size limitation.
168 // Skipping layers is allowed here and only affects performance.
169 if err := labels.Validate(targetImageLayersLabel, layers+ls); err != nil {
170 break
171 }
172 layers += ls
173
174 // Store URLs of the neighbouring layer as well.
175 urlsKey := targetImageURLsLabelPrefix + fmt.Sprintf("%d", i)
176 c.Annotations[urlsKey] = appendWithValidation(urlsKey, l.URLs)
177 }
178 }
179 c.Annotations[targetImageLayersLabel] = strings.TrimSuffix(layers, ",")
180 c.Annotations[config.TargetPrefetchSizeLabel] = fmt.Sprintf("%d", prefetchSize)
181
182 // store URL in annotation to let containerd to pass it to the snapshotter
183 c.Annotations[targetURLsLabel] = appendWithValidation(targetURLsLabel, c.URLs)
184 }
185 }
186 }
187 return children, nil
188 })
189 }
190 }
191
192 func appendWithValidation(key string, values []string) string {
193 var v string
194 for _, u := range values {
195 s := fmt.Sprintf("%s,", u)
196 if err := labels.Validate(key, v+s); err != nil {
197 break
198 }
199 v += s
200 }
201 return strings.TrimSuffix(v, ",")
202 }
203
204 // TODO: switch to "github.com/containerd/containerd/pkg/snapshotters" once all tools using
205 //
206 // stargz-snapshotter (e.g. k3s) move to containerd version where that pkg is available.
207 const (
208 // targetImageLayersLabel is a label which contains layer digests contained in
209 // the target image and will be passed to snapshotters for preparing layers in
210 // parallel. Skipping some layers is allowed and only affects performance.
211 targetImageLayersLabelContainerd = "containerd.io/snapshot/cri.image-layers"
212 )
213
214 // AppendExtraLabelsHandler adds optional labels that aren't provided by
215 // "github.com/containerd/containerd/pkg/snapshotters" but can be used for stargz snapshotter's extra functionalities.
216 func AppendExtraLabelsHandler(prefetchSize int64, wrapper func(images.Handler) images.Handler) func(images.Handler) images.Handler {
217 return func(f images.Handler) images.Handler {
218 return images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
219 children, err := wrapper(f).Handle(ctx, desc)
220 if err != nil {
221 return nil, err
222 }
223 switch desc.MediaType {
224 case ocispec.MediaTypeImageManifest, images.MediaTypeDockerSchema2Manifest:
225 for i := range children {
226 c := &children[i]
227 if !images.IsLayerType(c.MediaType) {
228 continue
229 }
230 if _, ok := c.Annotations[targetURLsLabel]; !ok { // nop if this key is already set
231 c.Annotations[targetURLsLabel] = appendWithValidation(targetURLsLabel, c.URLs)
232 }
233
234 if _, ok := c.Annotations[config.TargetPrefetchSizeLabel]; !ok { // nop if this key is already set
235 c.Annotations[config.TargetPrefetchSizeLabel] = fmt.Sprintf("%d", prefetchSize)
236 }
237
238 // Store URLs of the neighbouring layer as well.
239 nlayers, ok := c.Annotations[targetImageLayersLabelContainerd]
240 if !ok {
241 continue
242 }
243 for j, dstr := range strings.Split(nlayers, ",") {
244 d, err := digest.Parse(dstr)
245 if err != nil {
246 return nil, err
247 }
248 l, ok := layerFromDigest(children, d)
249 if !ok {
250 continue
251 }
252 urlsKey := targetImageURLsLabelPrefix + fmt.Sprintf("%d", j)
253 if _, ok := c.Annotations[urlsKey]; !ok { // nop if this key is already set
254 c.Annotations[urlsKey] = appendWithValidation(urlsKey, l.URLs)
255 }
256 }
257 }
258 }
259 return children, nil
260 })
261 }
262 }
263
264 func layerFromDigest(layers []ocispec.Descriptor, target digest.Digest) (ocispec.Descriptor, bool) {
265 for _, l := range layers {
266 if l.Digest == target {
267 return l, images.IsLayerType(l.MediaType)
268 }
269 }
270 return ocispec.Descriptor{}, false
271 }