Debian Codegraph @

extendedcopy.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package oras
17
18 import (
19 "context"
20 "encoding/json"
21 "errors"
22 "regexp"
23
24 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
25 "golang.org/x/sync/semaphore"
26 "oras.land/oras-go/v2/content"
27 "oras.land/oras-go/v2/internal/cas"
28 "oras.land/oras-go/v2/internal/container/set"
29 "oras.land/oras-go/v2/internal/copyutil"
30 "oras.land/oras-go/v2/internal/descriptor"
31 "oras.land/oras-go/v2/internal/docker"
32 "oras.land/oras-go/v2/internal/spec"
33 "oras.land/oras-go/v2/internal/status"
34 "oras.land/oras-go/v2/internal/syncutil"
35 "oras.land/oras-go/v2/registry"
36 )
37
38 // DefaultExtendedCopyOptions provides the default ExtendedCopyOptions.
39 var DefaultExtendedCopyOptions ExtendedCopyOptions = ExtendedCopyOptions{
40 ExtendedCopyGraphOptions: DefaultExtendedCopyGraphOptions,
41 }
42
43 // ExtendedCopyOptions contains parameters for [oras.ExtendedCopy].
44 type ExtendedCopyOptions struct {
45 ExtendedCopyGraphOptions
46 }
47
48 // DefaultExtendedCopyGraphOptions provides the default ExtendedCopyGraphOptions.
49 var DefaultExtendedCopyGraphOptions ExtendedCopyGraphOptions = ExtendedCopyGraphOptions{
50 CopyGraphOptions: DefaultCopyGraphOptions,
51 }
52
53 // ExtendedCopyGraphOptions contains parameters for [oras.ExtendedCopyGraph].
54 type ExtendedCopyGraphOptions struct {
55 CopyGraphOptions
56 // Depth limits the maximum depth of the directed acyclic graph (DAG) that
57 // will be extended-copied.
58 // If Depth is no specified, or the specified value is less than or
59 // equal to 0, the depth limit will be considered as infinity.
60 Depth int
61 // FindPredecessors finds the predecessors of the current node.
62 // If FindPredecessors is nil, src.Predecessors will be adapted and used.
63 FindPredecessors func(ctx context.Context, src content.ReadOnlyGraphStorage, desc ocispec.Descriptor) ([]ocispec.Descriptor, error)
64 }
65
66 // ExtendedCopy copies the directed acyclic graph (DAG) that are reachable from
67 // the given tagged node from the source GraphTarget to the destination Target.
68 // In other words, it copies a tagged artifact along with its referrers or
69 // other predecessor manifests referencing it.
70 //
71 // The tagged node (e.g. a tagged manifest of the artifact) is identified by the
72 // source reference.
73 // The destination reference will be the same as the source reference if the
74 // destination reference is left blank.
75 //
76 // Returns the descriptor of the tagged node on successful copy.
77 func ExtendedCopy(ctx context.Context, src ReadOnlyGraphTarget, srcRef string, dst Target, dstRef string, opts ExtendedCopyOptions) (ocispec.Descriptor, error) {
78 if src == nil {
79 return ocispec.Descriptor{}, newCopyError("ExtendedCopy", CopyErrorOriginSource, errors.New("nil source target"))
80 }
81 if dst == nil {
82 return ocispec.Descriptor{}, newCopyError("ExtendedCopy", CopyErrorOriginDestination, errors.New("nil destination target"))
83 }
84 if dstRef == "" {
85 dstRef = srcRef
86 }
87
88 node, err := src.Resolve(ctx, srcRef)
89 if err != nil {
90 return ocispec.Descriptor{}, newCopyError("Resolve", CopyErrorOriginSource, err)
91 }
92
93 if err := ExtendedCopyGraph(ctx, src, dst, node, opts.ExtendedCopyGraphOptions); err != nil {
94 return ocispec.Descriptor{}, err
95 }
96
97 if err := dst.Tag(ctx, node, dstRef); err != nil {
98 return ocispec.Descriptor{}, newCopyError("Tag", CopyErrorOriginDestination, err)
99 }
100
101 return node, nil
102 }
103
104 // ExtendedCopyGraph copies the directed acyclic graph (DAG) that are reachable
105 // from the given node from the source GraphStorage to the destination Storage.
106 // In other words, it copies an artifact along with its referrers or other
107 // predecessor manifests referencing it.
108 // The node (e.g. a manifest of the artifact) is identified by a descriptor.
109 func ExtendedCopyGraph(ctx context.Context, src content.ReadOnlyGraphStorage, dst content.Storage, node ocispec.Descriptor, opts ExtendedCopyGraphOptions) error {
110 if src == nil {
111 return newCopyError("ExtendedCopyGraph", CopyErrorOriginSource, errors.New("nil source target"))
112 }
113 if dst == nil {
114 return newCopyError("ExtendedCopyGraph", CopyErrorOriginDestination, errors.New("nil destination target"))
115 }
116
117 roots, err := findRoots(ctx, src, node, opts)
118 if err != nil {
119 return err
120 }
121
122 // if Concurrency is not set or invalid, use the default concurrency
123 if opts.Concurrency <= 0 {
124 opts.Concurrency = defaultConcurrency
125 }
126 limiter := semaphore.NewWeighted(int64(opts.Concurrency))
127 // use caching proxy on non-leaf nodes
128 if opts.MaxMetadataBytes <= 0 {
129 opts.MaxMetadataBytes = defaultCopyMaxMetadataBytes
130 }
131 proxy := cas.NewProxyWithLimit(src, cas.NewMemory(), opts.MaxMetadataBytes)
132 // track content status
133 tracker := status.NewTracker()
134
135 // copy the sub-DAGs rooted by the root nodes
136 return syncutil.Go(ctx, limiter, func(ctx context.Context, region *syncutil.LimitedRegion, root ocispec.Descriptor) error {
137 // As a root can be a predecessor of other roots, release the limit here
138 // for dispatching, to avoid dead locks where predecessor roots are
139 // handled first and are waiting for its successors to complete.
140 region.End()
141 if err := copyGraph(ctx, src, dst, root, proxy, limiter, tracker, opts.CopyGraphOptions); err != nil {
142 return err
143 }
144 return region.Start()
145 }, roots...)
146 }
147
148 // findRoots finds the root nodes reachable from the given node through a
149 // depth-first search.
150 func findRoots(ctx context.Context, storage content.ReadOnlyGraphStorage, node ocispec.Descriptor, opts ExtendedCopyGraphOptions) ([]ocispec.Descriptor, error) {
151 visited := set.New[descriptor.Descriptor]()
152 rootMap := make(map[descriptor.Descriptor]ocispec.Descriptor)
153 addRoot := func(key descriptor.Descriptor, val ocispec.Descriptor) {
154 if _, exists := rootMap[key]; !exists {
155 rootMap[key] = val
156 }
157 }
158
159 // if FindPredecessors is not provided, use the default one
160 if opts.FindPredecessors == nil {
161 opts.FindPredecessors = func(ctx context.Context, src content.ReadOnlyGraphStorage, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
162 return src.Predecessors(ctx, desc)
163 }
164 }
165
166 var stack copyutil.Stack
167 // push the initial node to the stack, set the depth to 0
168 stack.Push(copyutil.NodeInfo{Node: node, Depth: 0})
169 for {
170 current, ok := stack.Pop()
171 if !ok {
172 // empty stack
173 break
174 }
175 currentNode := current.Node
176 currentKey := descriptor.FromOCI(currentNode)
177
178 if visited.Contains(currentKey) {
179 // skip the current node if it has been visited
180 continue
181 }
182 visited.Add(currentKey)
183
184 // stop finding predecessors if the target depth is reached
185 if opts.Depth > 0 && current.Depth == opts.Depth {
186 addRoot(currentKey, currentNode)
187 continue
188 }
189
190 predecessors, err := opts.FindPredecessors(ctx, storage, currentNode)
191 if err != nil {
192 return nil, newCopyError("FindPredecessors", CopyErrorOriginSource, err)
193 }
194
195 // The current node has no predecessor node,
196 // which means it is a root node of a sub-DAG.
197 if len(predecessors) == 0 {
198 addRoot(currentKey, currentNode)
199 continue
200 }
201
202 // The current node has predecessor nodes, which means it is NOT a root node.
203 // Push the predecessor nodes to the stack and keep finding from there.
204 for _, predecessor := range predecessors {
205 predecessorKey := descriptor.FromOCI(predecessor)
206 if !visited.Contains(predecessorKey) {
207 // push the predecessor node with increased depth
208 stack.Push(copyutil.NodeInfo{Node: predecessor, Depth: current.Depth + 1})
209 }
210 }
211 }
212
213 roots := make([]ocispec.Descriptor, 0, len(rootMap))
214 for _, root := range rootMap {
215 roots = append(roots, root)
216 }
217 return roots, nil
218 }
219
220 // FilterAnnotation configures opts.FindPredecessors to filter the predecessors
221 // whose annotation matches a given regex pattern.
222 //
223 // A predecessor is kept if key is in its annotations and the annotation value
224 // matches regex.
225 // If regex is nil, predecessors whose annotations contain key will be kept,
226 // no matter of the annotation value.
227 //
228 // For performance consideration, when using both FilterArtifactType and
229 // FilterAnnotation, it's recommended to call FilterArtifactType first.
230 func (opts *ExtendedCopyGraphOptions) FilterAnnotation(key string, regex *regexp.Regexp) {
231 keep := func(desc ocispec.Descriptor) bool {
232 value, ok := desc.Annotations[key]
233 return ok && (regex == nil || regex.MatchString(value))
234 }
235
236 fp := opts.FindPredecessors
237 opts.FindPredecessors = func(ctx context.Context, src content.ReadOnlyGraphStorage, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
238 var predecessors []ocispec.Descriptor
239 var err error
240 if fp == nil {
241 if rf, ok := src.(registry.ReferrerLister); ok {
242 // if src is a ReferrerLister, use Referrers() for possible memory saving
243 if err := rf.Referrers(ctx, desc, "", func(referrers []ocispec.Descriptor) error {
244 // for each page of the results, filter the referrers
245 for _, r := range referrers {
246 if keep(r) {
247 predecessors = append(predecessors, r)
248 }
249 }
250 return nil
251 }); err != nil {
252 return nil, err
253 }
254 return predecessors, nil
255 }
256 predecessors, err = src.Predecessors(ctx, desc)
257 } else {
258 predecessors, err = fp(ctx, src, desc)
259 }
260 if err != nil {
261 return nil, err
262 }
263
264 // Predecessor descriptors that are not from Referrers API are not
265 // guaranteed to include the annotations of the corresponding manifests.
266 var kept []ocispec.Descriptor
267 for _, p := range predecessors {
268 if p.Annotations == nil {
269 // If the annotations are not present in the descriptors,
270 // fetch it from the manifest content.
271 switch p.MediaType {
272 case docker.MediaTypeManifest, ocispec.MediaTypeImageManifest,
273 docker.MediaTypeManifestList, ocispec.MediaTypeImageIndex,
274 spec.MediaTypeArtifactManifest:
275 annotations, err := fetchAnnotations(ctx, src, p)
276 if err != nil {
277 return nil, err
278 }
279 p.Annotations = annotations
280 }
281 }
282 if keep(p) {
283 kept = append(kept, p)
284 }
285 }
286 return kept, nil
287 }
288 }
289
290 // fetchAnnotations fetches the annotations of the manifest described by desc.
291 func fetchAnnotations(ctx context.Context, src content.ReadOnlyGraphStorage, desc ocispec.Descriptor) (map[string]string, error) {
292 rc, err := src.Fetch(ctx, desc)
293 if err != nil {
294 return nil, err
295 }
296 defer rc.Close()
297
298 var manifest struct {
299 Annotations map[string]string `json:"annotations"`
300 }
301 if err := json.NewDecoder(rc).Decode(&manifest); err != nil {
302 return nil, err
303 }
304 if manifest.Annotations == nil {
305 // to differentiate with nil
306 return make(map[string]string), nil
307 }
308 return manifest.Annotations, nil
309 }
310
311 // FilterArtifactType configures opts.FindPredecessors to filter the
312 // predecessors whose artifact type matches a given regex pattern.
313 //
314 // A predecessor is kept if its artifact type matches regex.
315 // If regex is nil, all predecessors will be kept.
316 //
317 // For performance consideration, when using both FilterArtifactType and
318 // FilterAnnotation, it's recommended to call FilterArtifactType first.
319 func (opts *ExtendedCopyGraphOptions) FilterArtifactType(regex *regexp.Regexp) {
320 if regex == nil {
321 return
322 }
323 keep := func(desc ocispec.Descriptor) bool {
324 return regex.MatchString(desc.ArtifactType)
325 }
326
327 fp := opts.FindPredecessors
328 opts.FindPredecessors = func(ctx context.Context, src content.ReadOnlyGraphStorage, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
329 var predecessors []ocispec.Descriptor
330 var err error
331 if fp == nil {
332 if rf, ok := src.(registry.ReferrerLister); ok {
333 // if src is a ReferrerLister, use Referrers() for possible memory saving
334 if err := rf.Referrers(ctx, desc, "", func(referrers []ocispec.Descriptor) error {
335 // for each page of the results, filter the referrers
336 for _, r := range referrers {
337 if keep(r) {
338 predecessors = append(predecessors, r)
339 }
340 }
341 return nil
342 }); err != nil {
343 return nil, err
344 }
345 return predecessors, nil
346 }
347 predecessors, err = src.Predecessors(ctx, desc)
348 } else {
349 predecessors, err = fp(ctx, src, desc)
350 }
351 if err != nil {
352 return nil, err
353 }
354
355 // predecessor descriptors that are not from Referrers API are not
356 // guaranteed to include the artifact type of the corresponding
357 // manifests.
358 var kept []ocispec.Descriptor
359 for _, p := range predecessors {
360 if p.ArtifactType == "" {
361 // if the artifact type is not present in the descriptors,
362 // fetch it from the manifest content.
363 switch p.MediaType {
364 case spec.MediaTypeArtifactManifest, ocispec.MediaTypeImageManifest:
365 artifactType, err := fetchArtifactType(ctx, src, p)
366 if err != nil {
367 return nil, err
368 }
369 p.ArtifactType = artifactType
370 }
371 }
372 if keep(p) {
373 kept = append(kept, p)
374 }
375 }
376 return kept, nil
377 }
378 }
379
380 // fetchArtifactType fetches the artifact type of the manifest described by desc.
381 func fetchArtifactType(ctx context.Context, src content.ReadOnlyGraphStorage, desc ocispec.Descriptor) (string, error) {
382 rc, err := src.Fetch(ctx, desc)
383 if err != nil {
384 return "", err
385 }
386 defer rc.Close()
387
388 switch desc.MediaType {
389 case spec.MediaTypeArtifactManifest:
390 var manifest spec.Artifact
391 if err := json.NewDecoder(rc).Decode(&manifest); err != nil {
392 return "", err
393 }
394 return manifest.ArtifactType, nil
395 case ocispec.MediaTypeImageManifest:
396 var manifest ocispec.Manifest
397 if err := json.NewDecoder(rc).Decode(&manifest); err != nil {
398 return "", err
399 }
400 return manifest.Config.MediaType, nil
401 default:
402 return "", nil
403 }
404 }