Debian Codegraph @

copy.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 "errors"
21 "fmt"
22 "io"
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/errdef"
28 "oras.land/oras-go/v2/internal/cas"
29 "oras.land/oras-go/v2/internal/descriptor"
30 "oras.land/oras-go/v2/internal/platform"
31 "oras.land/oras-go/v2/internal/registryutil"
32 "oras.land/oras-go/v2/internal/status"
33 "oras.land/oras-go/v2/internal/syncutil"
34 "oras.land/oras-go/v2/registry"
35 )
36
37 // defaultConcurrency is the default value of CopyGraphOptions.Concurrency.
38 const defaultConcurrency int = 3 // This value is consistent with dockerd and containerd.
39
40 // SkipNode signals to stop copying a node. When returned from PreCopy the blob must exist in the target.
41 // This can be used to signal that a blob has been made available in the target repository by "Mount()" or some other technique.
42 var SkipNode = errors.New("skip node")
43
44 // DefaultCopyOptions provides the default CopyOptions.
45 var DefaultCopyOptions CopyOptions = CopyOptions{
46 CopyGraphOptions: DefaultCopyGraphOptions,
47 }
48
49 // CopyOptions contains parameters for [oras.Copy].
50 type CopyOptions struct {
51 CopyGraphOptions
52 // MapRoot maps the resolved root node to a desired root node for copy.
53 // When MapRoot is provided, the descriptor resolved from the source
54 // reference will be passed to MapRoot, and the mapped descriptor will be
55 // used as the root node for copy.
56 MapRoot func(ctx context.Context, src content.ReadOnlyStorage, root ocispec.Descriptor) (ocispec.Descriptor, error)
57 }
58
59 // WithTargetPlatform configures opts.MapRoot to select the manifest whose
60 // platform matches the given platform. When MapRoot is provided, the platform
61 // selection will be applied on the mapped root node.
62 // - If the given platform is nil, no platform selection will be applied.
63 // - If the root node is a manifest, it will remain the same if platform
64 // matches, otherwise ErrNotFound will be returned.
65 // - If the root node is a manifest list, it will be mapped to the first
66 // matching manifest if exists, otherwise ErrNotFound will be returned.
67 // - Otherwise ErrUnsupported will be returned.
68 func (opts *CopyOptions) WithTargetPlatform(p *ocispec.Platform) {
69 if p == nil {
70 return
71 }
72 mapRoot := opts.MapRoot
73 opts.MapRoot = func(ctx context.Context, src content.ReadOnlyStorage, root ocispec.Descriptor) (desc ocispec.Descriptor, err error) {
74 if mapRoot != nil {
75 if root, err = mapRoot(ctx, src, root); err != nil {
76 return ocispec.Descriptor{}, err
77 }
78 }
79 return platform.SelectManifest(ctx, src, root, p)
80 }
81 }
82
83 // defaultCopyMaxMetadataBytes is the default value of
84 // CopyGraphOptions.MaxMetadataBytes.
85 const defaultCopyMaxMetadataBytes int64 = 4 * 1024 * 1024 // 4 MiB
86
87 // DefaultCopyGraphOptions provides the default CopyGraphOptions.
88 var DefaultCopyGraphOptions CopyGraphOptions
89
90 // CopyGraphOptions contains parameters for [oras.CopyGraph].
91 type CopyGraphOptions struct {
92 // Concurrency limits the maximum number of concurrent copy tasks.
93 // If less than or equal to 0, a default (currently 3) is used.
94 Concurrency int
95 // MaxMetadataBytes limits the maximum size of the metadata that can be
96 // cached in the memory.
97 // If less than or equal to 0, a default (currently 4 MiB) is used.
98 MaxMetadataBytes int64
99 // PreCopy handles the current descriptor before it is copied. PreCopy can
100 // return a SkipNode to signal that desc should be skipped when it already
101 // exists in the target.
102 PreCopy func(ctx context.Context, desc ocispec.Descriptor) error
103 // PostCopy handles the current descriptor after it is copied.
104 PostCopy func(ctx context.Context, desc ocispec.Descriptor) error
105 // OnCopySkipped will be called when the sub-DAG rooted by the current node
106 // is skipped.
107 OnCopySkipped func(ctx context.Context, desc ocispec.Descriptor) error
108 // MountFrom returns the candidate repositories that desc may be mounted from.
109 // The OCI references will be tried in turn. If mounting fails on all of them,
110 // then it falls back to a copy.
111 MountFrom func(ctx context.Context, desc ocispec.Descriptor) ([]string, error)
112 // OnMounted will be invoked when desc is mounted.
113 OnMounted func(ctx context.Context, desc ocispec.Descriptor) error
114 // FindSuccessors finds the successors of the current node.
115 // fetcher provides cached access to the source storage, and is suitable
116 // for fetching non-leaf nodes like manifests. Since anything fetched from
117 // fetcher will be cached in the memory, it is recommended to use original
118 // source storage to fetch large blobs.
119 // If FindSuccessors is nil, content.Successors will be used.
120 FindSuccessors func(ctx context.Context, fetcher content.Fetcher, desc ocispec.Descriptor) ([]ocispec.Descriptor, error)
121 }
122
123 // Copy copies a rooted directed acyclic graph (DAG), such as an artifact,
124 // from the source Target to the destination Target.
125 //
126 // The root node (e.g. a tagged manifest of the artifact) is identified by the
127 // source reference.
128 // The destination reference will be the same as the source reference if the
129 // destination reference is left blank.
130 //
131 // Returns the descriptor of the root node on successful copy.
132 func Copy(ctx context.Context, src ReadOnlyTarget, srcRef string, dst Target, dstRef string, opts CopyOptions) (ocispec.Descriptor, error) {
133 if src == nil {
134 return ocispec.Descriptor{}, newCopyError("Copy", CopyErrorOriginSource, errors.New("nil source target"))
135 }
136 if dst == nil {
137 return ocispec.Descriptor{}, newCopyError("Copy", CopyErrorOriginDestination, errors.New("nil destination target"))
138 }
139 if dstRef == "" {
140 dstRef = srcRef
141 }
142
143 // use caching proxy on non-leaf nodes
144 if opts.MaxMetadataBytes <= 0 {
145 opts.MaxMetadataBytes = defaultCopyMaxMetadataBytes
146 }
147 proxy := cas.NewProxyWithLimit(src, cas.NewMemory(), opts.MaxMetadataBytes)
148 root, err := resolveRoot(ctx, src, srcRef, proxy)
149 if err != nil {
150 return ocispec.Descriptor{}, err
151 }
152
153 if opts.MapRoot != nil {
154 proxy.StopCaching = true
155 root, err = opts.MapRoot(ctx, proxy, root)
156 if err != nil {
157 return ocispec.Descriptor{}, newCopyError("MapRoot", CopyErrorOriginSource, err)
158 }
159 proxy.StopCaching = false
160 }
161
162 if err := prepareCopy(ctx, dst, dstRef, proxy, root, &opts); err != nil {
163 return ocispec.Descriptor{}, err
164 }
165
166 if err := copyGraph(ctx, src, dst, root, proxy, nil, nil, opts.CopyGraphOptions); err != nil {
167 return ocispec.Descriptor{}, err
168 }
169
170 return root, nil
171 }
172
173 // CopyGraph copies a rooted directed acyclic graph (DAG), such as an artifact,
174 // from the source CAS to the destination CAS.
175 // The root node (e.g. a manifest of the artifact) is identified by a descriptor.
176 func CopyGraph(ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, root ocispec.Descriptor, opts CopyGraphOptions) error {
177 if src == nil {
178 return newCopyError("CopyGraph", CopyErrorOriginSource, errors.New("nil source target"))
179 }
180 if dst == nil {
181 return newCopyError("CopyGraph", CopyErrorOriginDestination, errors.New("nil destination target"))
182 }
183 return copyGraph(ctx, src, dst, root, nil, nil, nil, opts)
184 }
185
186 // copyGraph copies a rooted directed acyclic graph (DAG) from the source CAS to
187 // the destination CAS with specified caching, concurrency limiter and tracker.
188 func copyGraph(ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, root ocispec.Descriptor,
189 proxy *cas.Proxy, limiter *semaphore.Weighted, tracker *status.Tracker, opts CopyGraphOptions) error {
190 if proxy == nil {
191 // use caching proxy on non-leaf nodes
192 if opts.MaxMetadataBytes <= 0 {
193 opts.MaxMetadataBytes = defaultCopyMaxMetadataBytes
194 }
195 proxy = cas.NewProxyWithLimit(src, cas.NewMemory(), opts.MaxMetadataBytes)
196 }
197 if limiter == nil {
198 // if Concurrency is not set or invalid, use the default concurrency
199 if opts.Concurrency <= 0 {
200 opts.Concurrency = defaultConcurrency
201 }
202 limiter = semaphore.NewWeighted(int64(opts.Concurrency))
203 }
204 if tracker == nil {
205 // track content status
206 tracker = status.NewTracker()
207 }
208 // if FindSuccessors is not provided, use the default one
209 if opts.FindSuccessors == nil {
210 opts.FindSuccessors = content.Successors
211 }
212
213 // traverse the graph
214 var fn syncutil.GoFunc[ocispec.Descriptor]
215 fn = func(ctx context.Context, region *syncutil.LimitedRegion, desc ocispec.Descriptor) (err error) {
216 // skip the descriptor if other go routine is working on it
217 done, committed := tracker.TryCommit(desc)
218 if !committed {
219 return nil
220 }
221 defer func() {
222 if err == nil {
223 // mark the content as done on success
224 close(done)
225 }
226 }()
227
228 // skip if a rooted sub-DAG exists
229 exists, err := dst.Exists(ctx, desc)
230 if err != nil {
231 return newCopyError("Exists", CopyErrorOriginDestination, err)
232 }
233 if exists {
234 if opts.OnCopySkipped != nil {
235 if err := opts.OnCopySkipped(ctx, desc); err != nil {
236 return err
237 }
238 }
239 return nil
240 }
241
242 // find successors while non-leaf nodes will be fetched and cached
243 successors, err := opts.FindSuccessors(ctx, proxy, desc)
244 if err != nil {
245 return newCopyError("FindSuccessors", CopyErrorOriginSource, err)
246 }
247 successors = removeForeignLayers(successors)
248
249 if len(successors) != 0 {
250 // for non-leaf nodes, process successors and wait for them to complete
251 region.End()
252 if err := syncutil.Go(ctx, limiter, fn, successors...); err != nil {
253 return err
254 }
255 for _, node := range successors {
256 done, committed := tracker.TryCommit(node)
257 if committed {
258 return fmt.Errorf("%s: %s: successor not committed", desc.Digest, node.Digest)
259 }
260 select {
261 case <-done:
262 case <-ctx.Done():
263 return ctx.Err()
264 }
265 }
266 if err := region.Start(); err != nil {
267 return err
268 }
269 }
270
271 exists, err = proxy.Cache.Exists(ctx, desc)
272 if err != nil {
273 return fmt.Errorf("failed to check cache existence: %s: %w", desc.Digest, err)
274 }
275 if exists {
276 return copyNode(ctx, proxy.Cache, dst, desc, opts)
277 }
278 return mountOrCopyNode(ctx, src, dst, desc, opts)
279 }
280
281 return syncutil.Go(ctx, limiter, fn, root)
282 }
283
284 // mountOrCopyNode tries to mount the node, if not falls back to copying.
285 func mountOrCopyNode(ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, desc ocispec.Descriptor, opts CopyGraphOptions) error {
286 // Need MountFrom and it must be a blob
287 if opts.MountFrom == nil || descriptor.IsManifest(desc) {
288 return copyNode(ctx, src, dst, desc, opts)
289 }
290
291 mounter, ok := dst.(registry.Mounter)
292 if !ok {
293 // mounting is not supported by the destination
294 return copyNode(ctx, src, dst, desc, opts)
295 }
296
297 sourceRepositories, err := opts.MountFrom(ctx, desc)
298 if err != nil {
299 // Technically this error is not fatal, we can still attempt to copy the node
300 // But for consistency with the other callbacks we bail out.
301 return err
302 }
303
304 if len(sourceRepositories) == 0 {
305 return copyNode(ctx, src, dst, desc, opts)
306 }
307
308 skipSource := errors.New("skip source")
309 for i, sourceRepository := range sourceRepositories {
310 // try mounting this source repository
311 var mountFailed bool
312 getContent := func() (io.ReadCloser, error) {
313 // the invocation of getContent indicates that mounting has failed
314 mountFailed = true
315
316 if i < len(sourceRepositories)-1 {
317 // If this is not the last one, skip this source and try next one
318 // We want to return an error that we will test for from mounter.Mount()
319 return nil, skipSource
320 }
321 // this is the last iteration so we need to actually get the content and do the copy
322 // but first call the PreCopy function
323 if opts.PreCopy != nil {
324 if err := opts.PreCopy(ctx, desc); err != nil {
325 return nil, err
326 }
327 }
328 return src.Fetch(ctx, desc)
329 }
330
331 // Mount or copy
332 if err := mounter.Mount(ctx, desc, sourceRepository, getContent); err != nil && !errors.Is(err, skipSource) {
333 return newCopyError("Mount", CopyErrorOriginDestination, err)
334 }
335
336 if !mountFailed {
337 // mounted, success
338 if opts.OnMounted != nil {
339 if err := opts.OnMounted(ctx, desc); err != nil {
340 return err
341 }
342 }
343 return nil
344 }
345 }
346
347 // we copied it
348 if opts.PostCopy != nil {
349 if err := opts.PostCopy(ctx, desc); err != nil {
350 return err
351 }
352 }
353
354 return nil
355 }
356
357 // doCopyNode copies a single content from the source CAS to the destination CAS.
358 func doCopyNode(ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, desc ocispec.Descriptor) error {
359 rc, err := src.Fetch(ctx, desc)
360 if err != nil {
361 return newCopyError("Fetch", CopyErrorOriginSource, err)
362 }
363 defer rc.Close()
364 err = dst.Push(ctx, desc, rc)
365 if err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
366 return newCopyError("Push", CopyErrorOriginDestination, err)
367 }
368 return nil
369 }
370
371 // copyNode copies a single content from the source CAS to the destination CAS,
372 // and apply the given options.
373 func copyNode(ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, desc ocispec.Descriptor, opts CopyGraphOptions) error {
374 if opts.PreCopy != nil {
375 if err := opts.PreCopy(ctx, desc); err != nil {
376 if err == SkipNode {
377 return nil
378 }
379 return err
380 }
381 }
382
383 if err := doCopyNode(ctx, src, dst, desc); err != nil {
384 return err
385 }
386
387 if opts.PostCopy != nil {
388 return opts.PostCopy(ctx, desc)
389 }
390 return nil
391 }
392
393 // copyCachedNodeWithReference copies a single content with a reference from the
394 // source cache to the destination ReferencePusher.
395 func copyCachedNodeWithReference(ctx context.Context, src *cas.Proxy, dst registry.ReferencePusher, desc ocispec.Descriptor, dstRef string) error {
396 rc, err := src.FetchCached(ctx, desc)
397 if err != nil {
398 return newCopyError("Fetch", CopyErrorOriginSource, err)
399 }
400 defer rc.Close()
401
402 err = dst.PushReference(ctx, desc, rc, dstRef)
403 if err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
404 return newCopyError("PushReference", CopyErrorOriginDestination, err)
405 }
406 return nil
407 }
408
409 // resolveRoot resolves the source reference to the root node.
410 func resolveRoot(ctx context.Context, src ReadOnlyTarget, srcRef string, proxy *cas.Proxy) (ocispec.Descriptor, error) {
411 refFetcher, ok := src.(registry.ReferenceFetcher)
412 if !ok {
413 desc, err := src.Resolve(ctx, srcRef)
414 if err != nil {
415 return ocispec.Descriptor{}, newCopyError("Resolve", CopyErrorOriginSource, err)
416 }
417 return desc, nil
418 }
419
420 // optimize performance for ReferenceFetcher targets
421 refProxy := &registryutil.Proxy{
422 ReferenceFetcher: refFetcher,
423 Proxy: proxy,
424 }
425 root, rc, err := refProxy.FetchReference(ctx, srcRef)
426 if err != nil {
427 return ocispec.Descriptor{}, newCopyError("FetchReference", CopyErrorOriginSource, err)
428 }
429 defer rc.Close()
430 // cache root if it is a non-leaf node
431 fetcher := content.FetcherFunc(func(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {
432 if content.Equal(target, root) {
433 return rc, nil
434 }
435 return nil, errors.New("fetching only root node expected")
436 })
437 if _, err = content.Successors(ctx, fetcher, root); err != nil {
438 return ocispec.Descriptor{}, newCopyError("Successors", CopyErrorOriginSource, err)
439 }
440
441 // TODO: optimize special case where root is a leaf node (i.e. a blob)
442 // and dst is a ReferencePusher.
443 return root, nil
444 }
445
446 // prepareCopy prepares the hooks for copy.
447 func prepareCopy(_ context.Context, dst Target, dstRef string, proxy *cas.Proxy, root ocispec.Descriptor, opts *CopyOptions) error {
448 if refPusher, ok := dst.(registry.ReferencePusher); ok {
449 // optimize performance for ReferencePusher targets
450 preCopy := opts.PreCopy
451 opts.PreCopy = func(ctx context.Context, desc ocispec.Descriptor) error {
452 if preCopy != nil {
453 if err := preCopy(ctx, desc); err != nil {
454 return err
455 }
456 }
457 if !content.Equal(desc, root) {
458 // for non-root node, do nothing
459 return nil
460 }
461
462 // for root node, prepare optimized copy
463 if err := copyCachedNodeWithReference(ctx, proxy, refPusher, desc, dstRef); err != nil {
464 return err
465 }
466 if opts.PostCopy != nil {
467 if err := opts.PostCopy(ctx, desc); err != nil {
468 return err
469 }
470 }
471 // skip the regular copy workflow
472 return SkipNode
473 }
474 } else {
475 postCopy := opts.PostCopy
476 opts.PostCopy = func(ctx context.Context, desc ocispec.Descriptor) error {
477 if content.Equal(desc, root) {
478 // for root node, tag it after copying it
479 if err := dst.Tag(ctx, root, dstRef); err != nil {
480 return newCopyError("Tag", CopyErrorOriginDestination, err)
481 }
482 }
483 if postCopy != nil {
484 return postCopy(ctx, desc)
485 }
486 return nil
487 }
488 }
489
490 onCopySkipped := opts.OnCopySkipped
491 opts.OnCopySkipped = func(ctx context.Context, desc ocispec.Descriptor) error {
492 if !content.Equal(desc, root) {
493 if onCopySkipped != nil {
494 return onCopySkipped(ctx, desc)
495 }
496 return nil
497 }
498
499 // enforce tagging when the skipped node is root
500 if refPusher, ok := dst.(registry.ReferencePusher); ok {
501 // NOTE: refPusher tags the node by copying it with the reference,
502 // so onCopySkipped shouldn't be invoked in this case
503 return copyCachedNodeWithReference(ctx, proxy, refPusher, desc, dstRef)
504 }
505
506 // invoke onCopySkipped before tagging
507 if onCopySkipped != nil {
508 if err := onCopySkipped(ctx, desc); err != nil {
509 return err
510 }
511 }
512 if err := dst.Tag(ctx, root, dstRef); err != nil {
513 return newCopyError("Tag", CopyErrorOriginDestination, err)
514 }
515 return nil
516 }
517
518 return nil
519 }
520
521 // removeForeignLayers in-place removes all foreign layers in the given slice.
522 func removeForeignLayers(descs []ocispec.Descriptor) []ocispec.Descriptor {
523 var j int
524 for i, desc := range descs {
525 if !descriptor.IsForeignLayer(desc) {
526 if i != j {
527 descs[j] = desc
528 }
529 j++
530 }
531 }
532 return descs[:j]
533 }