-
Notifications
You must be signed in to change notification settings - Fork 82
/
image.go
1858 lines (1770 loc) · 53 KB
/
image.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package regclient
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
"github.com/regclient/regclient/pkg/archive"
"github.com/regclient/regclient/scheme"
"github.com/regclient/regclient/types"
"github.com/regclient/regclient/types/blob"
"github.com/regclient/regclient/types/descriptor"
"github.com/regclient/regclient/types/docker/schema2"
"github.com/regclient/regclient/types/errs"
"github.com/regclient/regclient/types/manifest"
"github.com/regclient/regclient/types/mediatype"
v1 "github.com/regclient/regclient/types/oci/v1"
"github.com/regclient/regclient/types/platform"
"github.com/regclient/regclient/types/ref"
"github.com/regclient/regclient/types/warning"
)
const (
dockerManifestFilename = "manifest.json"
ociLayoutVersion = "1.0.0"
ociIndexFilename = "index.json"
ociLayoutFilename = "oci-layout"
annotationRefName = "org.opencontainers.image.ref.name"
annotationImageName = "io.containerd.image.name"
)
// used by import/export to match docker tar expected format
type dockerTarManifest struct {
Config string
RepoTags []string
Layers []string
Parent digest.Digest `json:",omitempty"`
LayerSources map[digest.Digest]descriptor.Descriptor `json:",omitempty"`
}
type tarFileHandler func(header *tar.Header, trd *tarReadData) error
type tarReadData struct {
tr *tar.Reader
name string
handleAdded bool
handlers map[string]tarFileHandler
links map[string][]string
processed map[string]bool
finish []func() error
// data processed from various handlers
manifests map[digest.Digest]manifest.Manifest
ociIndex v1.Index
ociManifest manifest.Manifest
dockerManifestFound bool
dockerManifestList []dockerTarManifest
dockerManifest schema2.Manifest
}
type tarWriteData struct {
tw *tar.Writer
dirs map[string]bool
files map[string]bool
// uid, gid int
mode int64
timestamp time.Time
}
type imageOpt struct {
callback func(kind types.CallbackKind, instance string, state types.CallbackState, cur, total int64)
checkBaseDigest string
checkBaseRef string
checkSkipConfig bool
child bool
exportCompress bool
exportRef ref.Ref
fastCheck bool
forceRecursive bool
importName string
includeExternal bool
digestTags bool
platform string
platforms []string
referrerConfs []scheme.ReferrerConfig
tagList []string
mu sync.Mutex
seen map[string]*imageSeen
finalFn []func(context.Context) error
}
type imageSeen struct {
done chan struct{}
err error
}
// ImageOpts define options for the Image* commands.
type ImageOpts func(*imageOpt)
// ImageWithCallback provides progress data to a callback function.
func ImageWithCallback(callback func(kind types.CallbackKind, instance string, state types.CallbackState, cur, total int64)) ImageOpts {
return func(opts *imageOpt) {
opts.callback = callback
}
}
// ImageWithCheckBaseDigest provides a base digest to compare in ImageCheckBase.
func ImageWithCheckBaseDigest(d string) ImageOpts {
return func(opts *imageOpt) {
opts.checkBaseDigest = d
}
}
// ImageWithCheckBaseRef provides a base reference to compare in ImageCheckBase.
func ImageWithCheckBaseRef(r string) ImageOpts {
return func(opts *imageOpt) {
opts.checkBaseRef = r
}
}
// ImageWithCheckSkipConfig skips the configuration check in ImageCheckBase.
func ImageWithCheckSkipConfig() ImageOpts {
return func(opts *imageOpt) {
opts.checkSkipConfig = true
}
}
// ImageWithChild attempts to copy every manifest and blob even if parent manifests already exist in ImageCopy.
func ImageWithChild() ImageOpts {
return func(opts *imageOpt) {
opts.child = true
}
}
// ImageWithExportCompress adds gzip compression to tar export output in ImageExport.
func ImageWithExportCompress() ImageOpts {
return func(opts *imageOpt) {
opts.exportCompress = true
}
}
// ImageWithExportRef overrides the image name embedded in the export file in ImageExport.
func ImageWithExportRef(r ref.Ref) ImageOpts {
return func(opts *imageOpt) {
opts.exportRef = r
}
}
// ImageWithFastCheck skips check for referrers when manifest has already been copied in ImageCopy.
func ImageWithFastCheck() ImageOpts {
return func(opts *imageOpt) {
opts.fastCheck = true
}
}
// ImageWithForceRecursive attempts to copy every manifest and blob even if parent manifests already exist in ImageCopy.
func ImageWithForceRecursive() ImageOpts {
return func(opts *imageOpt) {
opts.forceRecursive = true
}
}
// ImageWithImportName selects the name of the image to import when multiple images are included in ImageImport.
func ImageWithImportName(name string) ImageOpts {
return func(opts *imageOpt) {
opts.importName = name
}
}
// ImageWithIncludeExternal attempts to copy every manifest and blob even if parent manifests already exist in ImageCopy.
func ImageWithIncludeExternal() ImageOpts {
return func(opts *imageOpt) {
opts.includeExternal = true
}
}
// ImageWithDigestTags looks for "sha-<digest>.*" tags in the repo to copy with any manifest in ImageCopy.
// These are used by some artifact systems like sigstore/cosign.
func ImageWithDigestTags() ImageOpts {
return func(opts *imageOpt) {
opts.digestTags = true
}
}
// ImageWithPlatform requests specific platforms from a manifest list in ImageCheckBase.
func ImageWithPlatform(p string) ImageOpts {
return func(opts *imageOpt) {
opts.platform = p
}
}
// ImageWithPlatforms only copies specific platforms from a manifest list in ImageCopy.
// This will result in a failure on many registries that validate manifests.
// Use the empty string to indicate images without a platform definition should be copied.
func ImageWithPlatforms(p []string) ImageOpts {
return func(opts *imageOpt) {
opts.platforms = p
}
}
// ImageWithReferrers recursively recursively includes referrer images in ImageCopy.
func ImageWithReferrers(rOpts ...scheme.ReferrerOpts) ImageOpts {
return func(opts *imageOpt) {
if opts.referrerConfs == nil {
opts.referrerConfs = []scheme.ReferrerConfig{}
}
rConf := scheme.ReferrerConfig{}
for _, rOpt := range rOpts {
rOpt(&rConf)
}
opts.referrerConfs = append(opts.referrerConfs, rConf)
}
}
// ImageCheckBase returns nil if the base image is unchanged.
// A base image mismatch returns an error that wraps errs.ErrMismatch.
func (rc *RegClient) ImageCheckBase(ctx context.Context, r ref.Ref, opts ...ImageOpts) error {
var opt imageOpt
for _, optFn := range opts {
optFn(&opt)
}
var m manifest.Manifest
var err error
// if the base name is not provided, check image for base annotations
if opt.checkBaseRef == "" {
m, err = rc.ManifestGet(ctx, r)
if err != nil {
return err
}
ma, ok := m.(manifest.Annotator)
if !ok {
return fmt.Errorf("image does not support annotations, base image must be provided%.0w", errs.ErrMissingAnnotation)
}
annot, err := ma.GetAnnotations()
if err != nil {
return err
}
if baseName, ok := annot[types.AnnotationBaseImageName]; ok {
opt.checkBaseRef = baseName
} else {
return fmt.Errorf("image does not have a base annotation, base image must be provided%.0w", errs.ErrMissingAnnotation)
}
if baseDig, ok := annot[types.AnnotationBaseImageDigest]; ok {
opt.checkBaseDigest = baseDig
}
}
baseR, err := ref.New(opt.checkBaseRef)
if err != nil {
return err
}
defer rc.Close(ctx, baseR)
// if the digest is available, check if that matches the base name
if opt.checkBaseDigest != "" {
baseMH, err := rc.ManifestHead(ctx, baseR, WithManifestRequireDigest())
if err != nil {
return err
}
expectDig, err := digest.Parse(opt.checkBaseDigest)
if err != nil {
return err
}
if baseMH.GetDescriptor().Digest == expectDig {
rc.log.WithFields(logrus.Fields{
"name": baseR.CommonName(),
"digest": baseMH.GetDescriptor().Digest.String(),
}).Debug("base image digest matches")
return nil
} else {
rc.log.WithFields(logrus.Fields{
"name": baseR.CommonName(),
"digest": baseMH.GetDescriptor().Digest.String(),
"expected": expectDig.String(),
}).Debug("base image digest changed")
return fmt.Errorf("base digest changed, %s, expected %s, received %s%.0w",
baseR.CommonName(), expectDig.String(), baseMH.GetDescriptor().Digest.String(), errs.ErrMismatch)
}
}
// if the digest is not available, compare layers of each manifest
if m == nil {
m, err = rc.ManifestGet(ctx, r)
if err != nil {
return err
}
}
if m.IsList() && opt.platform != "" {
p, err := platform.Parse(opt.platform)
if err != nil {
return err
}
d, err := manifest.GetPlatformDesc(m, &p)
if err != nil {
return err
}
rp := r
rp.Digest = d.Digest.String()
m, err = rc.ManifestGet(ctx, rp)
if err != nil {
return err
}
}
if m.IsList() {
// loop through each platform
ml, ok := m.(manifest.Indexer)
if !ok {
return fmt.Errorf("manifest list is not an Indexer")
}
dl, err := ml.GetManifestList()
if err != nil {
return err
}
rp := r
for _, d := range dl {
rp.Digest = d.Digest.String()
optP := append(opts, ImageWithPlatform(d.Platform.String()))
err = rc.ImageCheckBase(ctx, rp, optP...)
if err != nil {
return fmt.Errorf("platform %s mismatch: %w", d.Platform.String(), err)
}
}
return nil
}
img, ok := m.(manifest.Imager)
if !ok {
return fmt.Errorf("manifest must be an image")
}
layers, err := img.GetLayers()
if err != nil {
return err
}
baseM, err := rc.ManifestGet(ctx, baseR)
if err != nil {
return err
}
if baseM.IsList() && opt.platform != "" {
p, err := platform.Parse(opt.platform)
if err != nil {
return err
}
d, err := manifest.GetPlatformDesc(baseM, &p)
if err != nil {
return err
}
rp := baseR
rp.Digest = d.Digest.String()
baseM, err = rc.ManifestGet(ctx, rp)
if err != nil {
return err
}
}
baseImg, ok := baseM.(manifest.Imager)
if !ok {
return fmt.Errorf("base image manifest must be an image")
}
baseLayers, err := baseImg.GetLayers()
if err != nil {
return err
}
if len(baseLayers) <= 0 {
return fmt.Errorf("base image has no layers")
}
for i := range baseLayers {
if i >= len(layers) {
return fmt.Errorf("image has fewer layers than base image")
}
if !layers[i].Same(baseLayers[i]) {
rc.log.WithFields(logrus.Fields{
"layer": i,
"expected": layers[i].Digest.String(),
"digest": baseLayers[i].Digest.String(),
}).Debug("image layer changed")
return fmt.Errorf("base layer changed, %s[%d], expected %s, received %s%.0w",
baseR.CommonName(), i, layers[i].Digest.String(), baseLayers[i].Digest.String(), errs.ErrMismatch)
}
}
if opt.checkSkipConfig {
return nil
}
// if the layers match, compare the config history
confDesc, err := img.GetConfig()
if err != nil {
return err
}
conf, err := rc.BlobGetOCIConfig(ctx, r, confDesc)
if err != nil {
return err
}
confOCI := conf.GetConfig()
baseConfDesc, err := baseImg.GetConfig()
if err != nil {
return err
}
baseConf, err := rc.BlobGetOCIConfig(ctx, baseR, baseConfDesc)
if err != nil {
return err
}
baseConfOCI := baseConf.GetConfig()
for i := range baseConfOCI.History {
if i >= len(confOCI.History) {
return fmt.Errorf("image has fewer history entries than base image")
}
if baseConfOCI.History[i].Author != confOCI.History[i].Author ||
baseConfOCI.History[i].Comment != confOCI.History[i].Comment ||
!baseConfOCI.History[i].Created.Equal(*confOCI.History[i].Created) ||
baseConfOCI.History[i].CreatedBy != confOCI.History[i].CreatedBy ||
baseConfOCI.History[i].EmptyLayer != confOCI.History[i].EmptyLayer {
rc.log.WithFields(logrus.Fields{
"index": i,
"expected": confOCI.History[i],
"history": baseConfOCI.History[i],
}).Debug("image history changed")
return fmt.Errorf("base history changed, %s[%d], expected %v, received %v%.0w",
baseR.CommonName(), i, confOCI.History[i], baseConfOCI.History[i], errs.ErrMismatch)
}
}
rc.log.WithFields(logrus.Fields{
"base": baseR.CommonName(),
}).Debug("base image layers and history matches")
return nil
}
// ImageConfig returns the OCI config of a given image.
// Use [ImageWithPlatform] to select a platform from an Index or Manifest List.
func (rc *RegClient) ImageConfig(ctx context.Context, r ref.Ref, opts ...ImageOpts) (*blob.BOCIConfig, error) {
opt := imageOpt{
platform: "local",
}
for _, optFn := range opts {
optFn(&opt)
}
m, err := rc.ManifestGet(ctx, r)
if err != nil {
return nil, fmt.Errorf("failed to get manifest: %w", err)
}
for m.IsList() {
mi, ok := m.(manifest.Indexer)
if !ok {
return nil, fmt.Errorf("unsupported manifest type: %s", m.GetDescriptor().MediaType)
}
ml, err := mi.GetManifestList()
if err != nil {
return nil, fmt.Errorf("failed to get manifest list: %w", err)
}
p, err := platform.Parse(opt.platform)
if err != nil {
return nil, fmt.Errorf("failed to parse platform %s: %w", opt.platform, err)
}
d, err := descriptor.DescriptorListSearch(ml, descriptor.MatchOpt{Platform: &p})
if err != nil {
return nil, fmt.Errorf("failed to find platform in manifest list: %w", err)
}
m, err = rc.ManifestGet(ctx, r, WithManifestDesc(d))
if err != nil {
return nil, fmt.Errorf("failed to get manifest: %w", err)
}
}
mi, ok := m.(manifest.Imager)
if !ok {
return nil, fmt.Errorf("unsupported manifest type: %s", m.GetDescriptor().MediaType)
}
d, err := mi.GetConfig()
if err != nil {
return nil, fmt.Errorf("failed to get image config: %w", err)
}
if d.MediaType != mediatype.OCI1ImageConfig && d.MediaType != mediatype.Docker2ImageConfig {
return nil, fmt.Errorf("unsupported config media type %s: %w", d.MediaType, errs.ErrUnsupportedMediaType)
}
return rc.BlobGetOCIConfig(ctx, r, d)
}
// ImageCopy copies an image.
// This will retag an image in the same repository, only pushing and pulling the top level manifest.
// On the same registry, it will attempt to use cross-repository blob mounts to avoid pulling blobs.
// Blobs are only pulled when they don't exist on the target and a blob mount fails.
// Referrers are optionally copied recursively.
func (rc *RegClient) ImageCopy(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, opts ...ImageOpts) error {
opt := imageOpt{
seen: map[string]*imageSeen{},
finalFn: []func(context.Context) error{},
}
for _, optFn := range opts {
optFn(&opt)
}
// dedup warnings
if w := warning.FromContext(ctx); w == nil {
ctx = warning.NewContext(ctx, &warning.Warning{Hook: warning.DefaultHook()})
}
// block GC from running (in OCIDir) during the copy
schemeTgtAPI, err := rc.schemeGet(refTgt.Scheme)
if err != nil {
return err
}
if tgtGCLocker, isGCLocker := schemeTgtAPI.(scheme.GCLocker); isGCLocker {
tgtGCLocker.GCLock(refTgt)
defer tgtGCLocker.GCUnlock(refTgt)
}
// run the copy of manifests and blobs recursively
err = rc.imageCopyOpt(ctx, refSrc, refTgt, descriptor.Descriptor{}, opt.child, []digest.Digest{}, &opt)
if err != nil {
return err
}
// run any final functions, digest-tags and referrers that detected loops are retried here
for _, fn := range opt.finalFn {
err := fn(ctx)
if err != nil {
return err
}
}
return nil
}
// imageCopyOpt is a thread safe copy of a manifest and nested content.
func (rc *RegClient) imageCopyOpt(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, d descriptor.Descriptor, child bool, parents []digest.Digest, opt *imageOpt) (err error) {
var mSrc, mTgt manifest.Manifest
var sDig digest.Digest
seenCB := func(error) {}
defer func() {
if seenCB != nil {
seenCB(err)
}
}()
// if digest is provided and we are already copying it, wait
if d.Digest != "" {
sDig = d.Digest
} else if refSrc.Digest != "" {
sDig = digest.Digest(refSrc.Digest)
}
if sDig != "" {
if seenCB, err = imageSeenOrWait(ctx, opt, refTgt.Tag, sDig, parents); seenCB == nil {
return err
}
}
// check target with head request
mTgt, err = rc.ManifestHead(ctx, refTgt, WithManifestRequireDigest())
var urlError *url.Error
if err != nil && errors.As(err, &urlError) {
return fmt.Errorf("failed to access target registry: %w", err)
}
// for non-recursive copies, compare to source digest
if err == nil && (opt.fastCheck || (!opt.forceRecursive && opt.referrerConfs == nil && !opt.digestTags)) {
if sDig == "" {
mSrc, err = rc.ManifestHead(ctx, refSrc, WithManifestRequireDigest())
if err != nil {
return fmt.Errorf("copy failed, error getting source: %w", err)
}
sDig = mSrc.GetDescriptor().Digest
if seenCB, err = imageSeenOrWait(ctx, opt, refTgt.Tag, sDig, parents); seenCB == nil {
return err
}
}
if sDig == mTgt.GetDescriptor().Digest {
if opt.callback != nil {
opt.callback(types.CallbackManifest, d.Digest.String(), types.CallbackSkipped, mTgt.GetDescriptor().Size, mTgt.GetDescriptor().Size)
}
return nil
}
}
// when copying/updating digest tags or referrers, only the source digest is needed for an image
if mTgt != nil && mSrc == nil && !opt.forceRecursive && sDig == "" {
mSrc, err = rc.ManifestHead(ctx, refSrc, WithManifestRequireDigest())
if err != nil {
return fmt.Errorf("copy failed, error getting source: %w", err)
}
sDig = mSrc.GetDescriptor().Digest
if seenCB, err = imageSeenOrWait(ctx, opt, refTgt.Tag, sDig, parents); seenCB == nil {
return err
}
}
// get the source manifest when a copy is needed or recursion into the content is needed
if sDig == "" || mTgt == nil || sDig != mTgt.GetDescriptor().Digest || opt.forceRecursive || mTgt.IsList() {
mSrc, err = rc.ManifestGet(ctx, refSrc, WithManifestDesc(d))
if err != nil {
return fmt.Errorf("copy failed, error getting source: %w", err)
}
if sDig == "" {
sDig = mSrc.GetDescriptor().Digest
if seenCB, err = imageSeenOrWait(ctx, opt, refTgt.Tag, sDig, parents); seenCB == nil {
return err
}
}
}
// setup vars for a copy
mOpts := []ManifestOpts{}
if child {
mOpts = append(mOpts, WithManifestChild())
}
bOpt := []BlobOpts{}
if opt.callback != nil {
bOpt = append(bOpt, BlobWithCallback(opt.callback))
}
waitCh := make(chan error)
waitCount := 0
ctx, cancel := context.WithCancel(ctx)
defer cancel()
parentsNew := make([]digest.Digest, len(parents)+1)
copy(parentsNew, parents)
parentsNew[len(parentsNew)-1] = sDig
if opt.callback != nil {
opt.callback(types.CallbackManifest, d.Digest.String(), types.CallbackStarted, 0, d.Size)
}
// process entries in an index
if mSrcIndex, ok := mSrc.(manifest.Indexer); ok && mSrc.IsSet() && !ref.EqualRepository(refSrc, refTgt) {
// manifest lists need to recursively copy nested images by digest
dList, err := mSrcIndex.GetManifestList()
if err != nil {
return err
}
for _, dEntry := range dList {
// skip copy of platforms not specifically included
if len(opt.platforms) > 0 {
match, err := imagePlatformInList(dEntry.Platform, opt.platforms)
if err != nil {
return err
}
if !match {
rc.log.WithFields(logrus.Fields{
"platform": dEntry.Platform,
}).Debug("Platform excluded from copy")
continue
}
}
dEntry := dEntry
waitCount++
go func() {
var err error
rc.log.WithFields(logrus.Fields{
"platform": dEntry.Platform,
"digest": dEntry.Digest.String(),
}).Debug("Copy platform")
entrySrc := refSrc.SetDigest(dEntry.Digest.String())
entryTgt := refTgt.SetDigest(dEntry.Digest.String())
switch dEntry.MediaType {
case mediatype.Docker1Manifest, mediatype.Docker1ManifestSigned,
mediatype.Docker2Manifest, mediatype.Docker2ManifestList,
mediatype.OCI1Manifest, mediatype.OCI1ManifestList:
// known manifest media type
err = rc.imageCopyOpt(ctx, entrySrc, entryTgt, dEntry, true, parentsNew, opt)
case mediatype.Docker2ImageConfig, mediatype.OCI1ImageConfig,
mediatype.Docker2Layer, mediatype.Docker2LayerGzip, mediatype.Docker2LayerZstd,
mediatype.OCI1Layer, mediatype.OCI1LayerGzip, mediatype.OCI1LayerZstd,
mediatype.BuildkitCacheConfig:
// known blob media type
err = rc.imageCopyBlob(ctx, entrySrc, entryTgt, dEntry, opt, bOpt...)
default:
// unknown media type, first try an image copy
err = rc.imageCopyOpt(ctx, entrySrc, entryTgt, dEntry, true, parentsNew, opt)
if err != nil {
// fall back to trying to copy a blob
err = rc.imageCopyBlob(ctx, entrySrc, entryTgt, dEntry, opt, bOpt...)
}
}
waitCh <- err
}()
}
}
// copy referrers
referrerTags := []string{}
if opt.referrerConfs != nil {
rl, err := rc.ReferrerList(ctx, refSrc)
if err != nil {
return err
}
referrerTags = append(referrerTags, rl.Tags...)
descList := []descriptor.Descriptor{}
if len(opt.referrerConfs) == 0 {
descList = rl.Descriptors
} else {
for _, rConf := range opt.referrerConfs {
rlFilter := scheme.ReferrerFilter(rConf, rl)
descList = append(descList, rlFilter.Descriptors...)
}
}
for _, rDesc := range descList {
opt.mu.Lock()
seen := opt.seen[":"+rDesc.Digest.String()]
opt.mu.Unlock()
if seen != nil {
continue // skip referrers that have been seen
}
referrerSrc := refSrc.SetDigest(rDesc.Digest.String())
referrerTgt := refTgt.SetDigest(rDesc.Digest.String())
rDesc := rDesc
waitCount++
go func() {
err := rc.imageCopyOpt(ctx, referrerSrc, referrerTgt, rDesc, true, parentsNew, opt)
if errors.Is(err, errs.ErrLoopDetected) {
// if a loop is detected, push the referrers copy to the end
opt.mu.Lock()
opt.finalFn = append(opt.finalFn, func(ctx context.Context) error {
return rc.imageCopyOpt(ctx, referrerSrc, referrerTgt, rDesc, true, []digest.Digest{}, opt)
})
opt.mu.Unlock()
waitCh <- nil
} else {
if err != nil && !errors.Is(err, context.Canceled) {
rc.log.WithFields(logrus.Fields{
"digest": rDesc.Digest.String(),
"src": referrerSrc.CommonName(),
"tgt": referrerTgt.CommonName(),
}).Warn("Failed to copy referrer")
}
waitCh <- err
}
}()
}
}
// lookup digest tags to include artifacts with image
if opt.digestTags {
// load tag listing for digest tag copy
opt.mu.Lock()
if opt.tagList == nil {
tl, err := rc.TagList(ctx, refSrc)
if err != nil {
opt.mu.Unlock()
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"err": err,
}).Warn("Failed to list tags for digest-tag copy")
return err
}
tags, err := tl.GetTags()
if err != nil {
opt.mu.Unlock()
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"err": err,
}).Warn("Failed to list tags for digest-tag copy")
return err
}
if tags == nil {
tags = []string{}
}
opt.tagList = tags
}
opt.mu.Unlock()
prefix := fmt.Sprintf("%s-%s", sDig.Algorithm(), sDig.Encoded())
for _, tag := range opt.tagList {
if strings.HasPrefix(tag, prefix) {
// skip referrers that were copied above
found := false
for _, referrerTag := range referrerTags {
if referrerTag == tag {
found = true
break
}
}
if found {
continue
}
refTagSrc := refSrc.SetTag(tag)
refTagTgt := refTgt.SetTag(tag)
tag := tag
waitCount++
go func() {
err := rc.imageCopyOpt(ctx, refTagSrc, refTagTgt, descriptor.Descriptor{}, false, parentsNew, opt)
if errors.Is(err, errs.ErrLoopDetected) {
// if a loop is detected, push the digest tag copy back to the end
opt.mu.Lock()
opt.finalFn = append(opt.finalFn, func(ctx context.Context) error {
return rc.imageCopyOpt(ctx, refTagSrc, refTagTgt, descriptor.Descriptor{}, false, []digest.Digest{}, opt)
})
opt.mu.Unlock()
waitCh <- nil
} else {
if err != nil && !errors.Is(err, context.Canceled) {
rc.log.WithFields(logrus.Fields{
"tag": tag,
"src": refTagSrc.CommonName(),
"tgt": refTagTgt.CommonName(),
}).Warn("Failed to copy digest-tag")
}
waitCh <- err
}
}()
}
}
}
// check for any errors and abort early if found
err = nil
done := false
for !done && waitCount > 0 {
if err == nil {
select {
case err = <-waitCh:
if err != nil {
cancel()
}
default:
done = true // happy path
}
} else {
if errors.Is(err, context.Canceled) {
// try to find a better error message than context canceled
err = <-waitCh
} else {
<-waitCh
}
}
if !done {
waitCount--
}
}
if err != nil {
rc.log.WithFields(logrus.Fields{
"err": err,
"sDig": sDig,
}).Debug("child manifest copy failed")
return err
}
// If source is image, copy blobs
if mSrcImg, ok := mSrc.(manifest.Imager); ok && mSrc.IsSet() && !ref.EqualRepository(refSrc, refTgt) {
// copy the config
cd, err := mSrcImg.GetConfig()
if err != nil {
// docker schema v1 does not have a config object, ignore if it's missing
if !errors.Is(err, errs.ErrUnsupportedMediaType) {
rc.log.WithFields(logrus.Fields{
"ref": refSrc.Reference,
"err": err,
}).Warn("Failed to get config digest from manifest")
return fmt.Errorf("failed to get config digest for %s: %w", refSrc.CommonName(), err)
}
} else {
waitCount++
go func() {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"digest": cd.Digest.String(),
}).Info("Copy config")
err := rc.imageCopyBlob(ctx, refSrc, refTgt, cd, opt, bOpt...)
if err != nil && !errors.Is(err, context.Canceled) {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"digest": cd.Digest.String(),
"err": err,
}).Warn("Failed to copy config")
}
waitCh <- err
}()
}
// copy filesystem layers
l, err := mSrcImg.GetLayers()
if err != nil {
return err
}
for _, layerSrc := range l {
if len(layerSrc.URLs) > 0 && !opt.includeExternal {
// skip blobs where the URLs are defined, these aren't hosted and won't be pulled from the source
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"layer": layerSrc.Digest.String(),
"external-urls": layerSrc.URLs,
}).Debug("Skipping external layer")
continue
}
waitCount++
layerSrc := layerSrc
go func() {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"layer": layerSrc.Digest.String(),
}).Info("Copy layer")
err := rc.imageCopyBlob(ctx, refSrc, refTgt, layerSrc, opt, bOpt...)
if err != nil && !errors.Is(err, context.Canceled) {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"layer": layerSrc.Digest.String(),
"err": err,
}).Warn("Failed to copy layer")
}
waitCh <- err
}()
}
}
// wait for background tasks to finish
err = nil
for waitCount > 0 {
if err == nil {
err = <-waitCh
if err != nil {
cancel()
}
} else {
if errors.Is(err, context.Canceled) {
// try to find a better error message than context canceled
err = <-waitCh
} else {
<-waitCh
}
}
waitCount--
}
if err != nil {
return err
}
// push manifest
if mTgt == nil || sDig != mTgt.GetDescriptor().Digest || opt.forceRecursive {
err = rc.ManifestPut(ctx, refTgt, mSrc, mOpts...)
if err != nil {
if !errors.Is(err, context.Canceled) {
rc.log.WithFields(logrus.Fields{
"target": refTgt.Reference,
"err": err,
}).Warn("Failed to push manifest")
}
return err
}
if opt.callback != nil {
opt.callback(types.CallbackManifest, d.Digest.String(), types.CallbackFinished, d.Size, d.Size)
}
} else {
if opt.callback != nil {
opt.callback(types.CallbackManifest, d.Digest.String(), types.CallbackSkipped, d.Size, d.Size)
}
}
if seenCB != nil {
seenCB(nil)
seenCB = nil
}
return nil
}
func (rc *RegClient) imageCopyBlob(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, d descriptor.Descriptor, opt *imageOpt, bOpt ...BlobOpts) error {
seenCB, err := imageSeenOrWait(ctx, opt, "", d.Digest, []digest.Digest{})
if seenCB == nil {
return err
}
err = rc.BlobCopy(ctx, refSrc, refTgt, d, bOpt...)
seenCB(err)
return err
}
// imageSeenOrWait returns either a callback to report the error when the digest hasn't been seen before
// or it will wait for the previous copy to run and return the error from that copy
func imageSeenOrWait(ctx context.Context, opt *imageOpt, tag string, dig digest.Digest, parents []digest.Digest) (func(error), error) {
var seenNew *imageSeen
key := tag + ":" + dig.String()
opt.mu.Lock()
seen := opt.seen[key]
if seen == nil {
seenNew = &imageSeen{
done: make(chan struct{}),
}
opt.seen[key] = seenNew
}
opt.mu.Unlock()
if seen != nil {
// quick check for the previous copy already done
select {
case <-seen.done:
return nil, seen.err
default:
}
// look for loops in parents
for _, p := range parents {
if key == tag+":"+p.String() {
return nil, errs.ErrLoopDetected
}
}
// wait for copy to finish or context to cancel
done := ctx.Done()
select {
case <-seen.done:
return nil, seen.err
case <-done:
return nil, ctx.Err()
}
} else {
return func(err error) {