This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
forked from regclient/regclient
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimage.go
1135 lines (1073 loc) · 33.2 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"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"path/filepath"
"strings"
"time"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
digest "github.com/opencontainers/go-digest"
"github.com/regclient/regclient/pkg/archive"
"github.com/regclient/regclient/scheme"
"github.com/regclient/regclient/types"
"github.com/regclient/regclient/types/docker/schema2"
"github.com/regclient/regclient/types/manifest"
v1 "github.com/regclient/regclient/types/oci/v1"
"github.com/regclient/regclient/types/platform"
"github.com/regclient/regclient/types/ref"
"github.com/sirupsen/logrus"
)
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]types.Descriptor `json:",omitempty"`
}
type tarFileHandler func(header *tar.Header, trd *tarReadData) error
type tarReadData struct {
tr *tar.Reader
handleAdded bool
handlers map[string]tarFileHandler
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 {
child bool
forceRecursive bool
includeExternal bool
digestTags bool
platforms []string
referrers bool
tagList []string
}
// ImageOpts define options for the Image* commands
type ImageOpts func(*imageOpt)
// ImageWithChild attempts to copy every manifest and blob even if parent manifests already exist.
func ImageWithChild() ImageOpts {
return func(opts *imageOpt) {
opts.child = true
}
}
// ImageWithForceRecursive attempts to copy every manifest and blob even if parent manifests already exist.
func ImageWithForceRecursive() ImageOpts {
return func(opts *imageOpt) {
opts.forceRecursive = true
}
}
// ImageWithIncludeExternal attempts to copy every manifest and blob even if parent manifests already exist.
func ImageWithIncludeExternal() ImageOpts {
return func(opts *imageOpt) {
opts.includeExternal = true
}
}
// ImageWithDigestTags looks for "sha-<digest>.*" tags in the repo to copy with any manifest.
// These are used by some artifact systems like sigstore/cosign.
func ImageWithDigestTags() ImageOpts {
return func(opts *imageOpt) {
opts.digestTags = true
}
}
// ImageWithPlatforms only copies specific platforms from a manifest list.
// 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 includes images that refer to this.
// EXPERIMENTAL: referrers implementation is considered experimental.
func ImageWithReferrers() ImageOpts {
return func(opts *imageOpt) {
opts.referrers = true
}
}
// 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
func (rc *RegClient) ImageCopy(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, opts ...ImageOpts) error {
var opt imageOpt
for _, optFn := range opts {
optFn(&opt)
}
return rc.imageCopyOpt(ctx, refSrc, refTgt, types.Descriptor{}, opt.child, &opt)
}
func (rc *RegClient) imageCopyOpt(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, d types.Descriptor, child bool, opt *imageOpt) error {
mOpts := []scheme.ManifestOpts{}
if child {
mOpts = append(mOpts, scheme.WithManifestChild())
}
// check if scheme/refTgt prefers parent manifests pushed first
// if so, this should automatically set forceRecursive
tgtSI, err := rc.schemeInfo(refTgt)
if err != nil {
return fmt.Errorf("failed looking up scheme for %s: %v", refTgt.CommonName(), err)
}
if tgtSI.ManifestPushFirst {
opt.forceRecursive = true
}
// check if source and destination already match
mdh, errD := rc.ManifestHead(ctx, refTgt)
if opt.forceRecursive {
// copy forced, unable to run below skips
} else if errD == nil && refTgt.Digest != "" && digest.Digest(refTgt.Digest) == mdh.GetDescriptor().Digest {
rc.log.WithFields(logrus.Fields{
"target": refTgt.Reference,
"digest": mdh.GetDescriptor().Digest.String(),
}).Info("Copy not needed, target already up to date")
return nil
} else if errD == nil && refTgt.Digest == "" {
msh, errS := rc.ManifestHead(ctx, refSrc)
if errS == nil && msh.GetDescriptor().Digest == mdh.GetDescriptor().Digest {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"digest": mdh.GetDescriptor().Digest.String(),
}).Info("Copy not needed, target already up to date")
return nil
}
}
// get the manifest for the source
m, err := rc.ManifestGet(ctx, refSrc, ManifestWithDesc(d))
if err != nil {
rc.log.WithFields(logrus.Fields{
"ref": refSrc.Reference,
"err": err,
}).Warn("Failed to get source manifest")
return err
}
if tgtSI.ManifestPushFirst {
// push manifest to target
err = rc.ManifestPut(ctx, refTgt, m, mOpts...)
if err != nil {
rc.log.WithFields(logrus.Fields{
"target": refTgt.Reference,
"err": err,
}).Warn("Failed to push manifest")
return err
}
}
if !ref.EqualRepository(refSrc, refTgt) {
// copy components of the image if the repository is different
if mi, ok := m.(manifest.Indexer); ok {
// manifest lists need to recursively copy nested images by digest
pd, err := mi.GetManifestList()
if err != nil {
return err
}
for _, entry := range pd {
// skip copy of platforms not specifically included
if len(opt.platforms) > 0 {
match, err := imagePlatformInList(entry.Platform, opt.platforms)
if err != nil {
return err
}
if !match {
rc.log.WithFields(logrus.Fields{
"platform": entry.Platform,
}).Debug("Platform excluded from copy")
continue
}
}
rc.log.WithFields(logrus.Fields{
"platform": entry.Platform,
"digest": entry.Digest.String(),
}).Debug("Copy platform")
entrySrc := refSrc
entryTgt := refTgt
entrySrc.Tag = ""
entryTgt.Tag = ""
entrySrc.Digest = entry.Digest.String()
entryTgt.Digest = entry.Digest.String()
switch entry.MediaType {
case types.MediaTypeDocker1Manifest, types.MediaTypeDocker1ManifestSigned,
types.MediaTypeDocker2Manifest, types.MediaTypeDocker2ManifestList,
types.MediaTypeOCI1Manifest, types.MediaTypeOCI1ManifestList:
// known manifest media type
err = rc.imageCopyOpt(ctx, entrySrc, entryTgt, entry, true, opt)
case types.MediaTypeDocker2ImageConfig, types.MediaTypeOCI1ImageConfig,
types.MediaTypeDocker2LayerGzip, types.MediaTypeOCI1Layer, types.MediaTypeOCI1LayerGzip,
types.MediaTypeBuildkitCacheConfig:
// known blob media type
err = rc.BlobCopy(ctx, entrySrc, entryTgt, entry)
default:
// unknown media type, first try an image copy
err = rc.imageCopyOpt(ctx, entrySrc, entryTgt, entry, true, opt)
if err != nil {
// fall back to trying to copy a blob
err = rc.BlobCopy(ctx, entrySrc, entryTgt, entry)
}
}
if err != nil {
return err
}
}
}
if mi, ok := m.(manifest.Imager); ok {
// copy components of an image
// transfer the config
cd, err := mi.GetConfig()
if err != nil {
// docker schema v1 does not have a config object, ignore if it's missing
if !errors.Is(err, types.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 {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"digest": cd.Digest.String(),
}).Info("Copy config")
if err := rc.BlobCopy(ctx, refSrc, refTgt, cd); err != nil {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"digest": cd.Digest.String(),
"err": err,
}).Warn("Failed to copy config")
return err
}
}
// copy filesystem layers
l, err := mi.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
}
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"layer": layerSrc.Digest.String(),
}).Info("Copy layer")
if err := rc.BlobCopy(ctx, refSrc, refTgt, layerSrc); err != nil {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"target": refTgt.Reference,
"layer": layerSrc.Digest.String(),
"err": err,
}).Warn("Failed to copy layer")
return err
}
}
}
}
if !tgtSI.ManifestPushFirst {
// push manifest to target
err = rc.ManifestPut(ctx, refTgt, m, mOpts...)
if err != nil {
rc.log.WithFields(logrus.Fields{
"target": refTgt.Reference,
"err": err,
}).Warn("Failed to push manifest")
return err
}
}
// experimental support for referrers
referTags := []string{}
if opt.referrers {
rl, err := rc.ReferrerList(ctx, refSrc)
if err != nil {
return err
}
referTags = append(referTags, rl.Tags...)
for _, rDesc := range rl.Descriptors {
referSrc := refSrc
referSrc.Tag = ""
referSrc.Digest = rDesc.Digest.String()
referTgt := refTgt
referTgt.Tag = ""
referTgt.Digest = rDesc.Digest.String()
err = rc.imageCopyOpt(ctx, referSrc, referTgt, rDesc, true, opt)
if err != nil {
rc.log.WithFields(logrus.Fields{
"digest": rDesc.Digest.String(),
"src": referSrc.CommonName(),
"tgt": referTgt.CommonName(),
}).Warn("Failed to copy referrer")
return err
}
referM, err := rc.ManifestGet(ctx, referTgt)
if err != nil {
rc.log.WithFields(logrus.Fields{
"digest": rDesc.Digest.String(),
"src": referSrc.CommonName(),
"tgt": referTgt.CommonName(),
}).Warn("Failed to copy referrer")
return err
}
err = rc.ReferrerPut(ctx, refTgt, referM)
if err != nil {
return err
}
}
}
// lookup digest tags to include artifacts with image
if opt.digestTags {
if len(opt.tagList) == 0 {
tl, err := rc.TagList(ctx, refSrc)
if err != nil {
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 {
rc.log.WithFields(logrus.Fields{
"source": refSrc.Reference,
"err": err,
}).Warn("Failed to list tags for digest-tag copy")
return err
}
opt.tagList = tags
}
prefix := fmt.Sprintf("%s-%s", m.GetDescriptor().Digest.Algorithm(), m.GetDescriptor().Digest.Encoded())
for _, tag := range opt.tagList {
if strings.HasPrefix(tag, prefix) {
// skip referrers that were copied above
for _, referTag := range referTags {
if referTag == tag {
continue
}
}
refTagSrc := refSrc
refTagSrc.Tag = tag
refTagSrc.Digest = ""
refTagTgt := refTgt
refTagTgt.Tag = tag
refTagTgt.Digest = ""
err = rc.imageCopyOpt(ctx, refTagSrc, refTagTgt, types.Descriptor{}, false, opt)
if err != nil {
rc.log.WithFields(logrus.Fields{
"tag": tag,
"src": refTagSrc.CommonName(),
"tgt": refTagTgt.CommonName(),
}).Warn("Failed to copy digest-tag")
return err
}
}
}
}
return nil
}
// ImageExport exports an image to an output stream.
// The format is compatible with "docker load" if a single image is selected and not a manifest list.
// The ref must include a tag for exporting to docker (defaults to latest), and may also include a digest.
// The export is also formatted according to OCI layout which supports multi-platform images.
// <https://github.com/opencontainers/image-spec/blob/master/image-layout.md>
// A tar file will be sent to outStream.
//
// Resulting filesystem:
// oci-layout: created at top level, can be done at the start
// index.json: created at top level, single descriptor with org.opencontainers.image.ref.name annotation pointing to the tag
// manifest.json: created at top level, based on every layer added, only works for a single arch image
// blobs/$algo/$hash: each content addressable object (manifest, config, or layer), created recursively
func (rc *RegClient) ImageExport(ctx context.Context, r ref.Ref, outStream io.Writer) error {
var ociIndex v1.Index
// create tar writer object
tw := tar.NewWriter(outStream)
defer tw.Close()
twd := &tarWriteData{
tw: tw,
dirs: map[string]bool{},
files: map[string]bool{},
mode: 0644,
}
// retrieve image manifest
m, err := rc.ManifestGet(ctx, r)
if err != nil {
rc.log.WithFields(logrus.Fields{
"ref": r.CommonName(),
"err": err,
}).Warn("Failed to get manifest")
return err
}
// build/write oci-layout
ociLayout := v1.ImageLayout{Version: ociLayoutVersion}
err = twd.tarWriteFileJSON(ociLayoutFilename, ociLayout)
if err != nil {
return err
}
// create a manifest descriptor
mDesc := m.GetDescriptor()
if mDesc.Annotations == nil {
mDesc.Annotations = map[string]string{}
}
mDesc.Annotations[annotationImageName] = r.CommonName()
mDesc.Annotations[annotationRefName] = r.Tag
// generate/write an OCI index
ociIndex.Versioned = v1.IndexSchemaVersion
ociIndex.Manifests = []types.Descriptor{mDesc} // initialize with the descriptor to the manifest list
err = twd.tarWriteFileJSON(ociIndexFilename, ociIndex)
if err != nil {
return err
}
// append to docker manifest with tag, config filename, each layer filename, and layer descriptors
if mi, ok := m.(manifest.Imager); ok {
conf, err := mi.GetConfig()
if err != nil {
return err
}
refTag := r.ToReg()
if refTag.Digest != "" {
refTag.Digest = ""
}
if refTag.Tag == "" {
refTag.Tag = "latest"
}
dockerManifest := dockerTarManifest{
RepoTags: []string{refTag.CommonName()},
Config: tarOCILayoutDescPath(conf),
Layers: []string{},
LayerSources: map[digest.Digest]types.Descriptor{},
}
dl, err := mi.GetLayers()
if err != nil {
return err
}
for _, d := range dl {
dockerManifest.Layers = append(dockerManifest.Layers, tarOCILayoutDescPath(d))
dockerManifest.LayerSources[d.Digest] = d
}
// marshal manifest and write manifest.json
err = twd.tarWriteFileJSON(dockerManifestFilename, []dockerTarManifest{dockerManifest})
if err != nil {
return err
}
}
// recursively include manifests and nested blobs
err = rc.imageExportDescriptor(ctx, r, mDesc, twd)
if err != nil {
return err
}
return nil
}
// imageExportDescriptor pulls a manifest or blob, outputs to a tar file, and recursively processes any nested manifests or blobs
func (rc *RegClient) imageExportDescriptor(ctx context.Context, ref ref.Ref, desc types.Descriptor, twd *tarWriteData) error {
tarFilename := tarOCILayoutDescPath(desc)
if twd.files[tarFilename] {
// blob has already been imported into tar, skip
return nil
}
switch desc.MediaType {
case types.MediaTypeDocker1Manifest, types.MediaTypeDocker1ManifestSigned, types.MediaTypeDocker2Manifest, types.MediaTypeOCI1Manifest:
// Handle single platform manifests
// retrieve manifest
m, err := rc.ManifestGet(ctx, ref, ManifestWithDesc(desc))
if err != nil {
return err
}
mi, ok := m.(manifest.Imager)
if !ok {
return fmt.Errorf("manifest doesn't support image methods%.0w", types.ErrUnsupportedMediaType)
}
// write manifest body by digest
mBody, err := m.RawBody()
if err != nil {
return err
}
err = twd.tarWriteHeader(tarFilename, int64(len(mBody)))
if err != nil {
return err
}
_, err = twd.tw.Write(mBody)
if err != nil {
return err
}
// add config
confD, err := mi.GetConfig()
// ignore unsupported media type errors
if err != nil && !errors.Is(err, types.ErrUnsupportedMediaType) {
return err
}
if err == nil {
err = rc.imageExportDescriptor(ctx, ref, confD, twd)
if err != nil {
return err
}
}
// loop over layers
layerDL, err := mi.GetLayers()
// ignore unsupported media type errors
if err != nil && !errors.Is(err, types.ErrUnsupportedMediaType) {
return err
}
if err == nil {
for _, layerD := range layerDL {
err = rc.imageExportDescriptor(ctx, ref, layerD, twd)
if err != nil {
return err
}
}
}
case types.MediaTypeDocker2ManifestList, types.MediaTypeOCI1ManifestList:
// handle OCI index and Docker manifest list
// retrieve manifest
m, err := rc.ManifestGet(ctx, ref, ManifestWithDesc(desc))
if err != nil {
return err
}
mi, ok := m.(manifest.Indexer)
if !ok {
return fmt.Errorf("manifest doesn't support index methods%.0w", types.ErrUnsupportedMediaType)
}
// write manifest body by digest
mBody, err := m.RawBody()
if err != nil {
return err
}
err = twd.tarWriteHeader(tarFilename, int64(len(mBody)))
if err != nil {
return err
}
_, err = twd.tw.Write(mBody)
if err != nil {
return err
}
// recurse over entries in the list/index
mdl, err := mi.GetManifestList()
if err != nil {
return err
}
for _, md := range mdl {
err = rc.imageExportDescriptor(ctx, ref, md, twd)
if err != nil {
return err
}
}
default:
// get blob
blobR, err := rc.BlobGet(ctx, ref, desc)
if err != nil {
return err
}
defer blobR.Close()
// write blob by digest
err = twd.tarWriteHeader(tarFilename, int64(desc.Size))
if err != nil {
return err
}
size, err := io.Copy(twd.tw, blobR)
if err != nil {
return fmt.Errorf("failed to export blob %s: %w", desc.Digest.String(), err)
}
if size != desc.Size {
return fmt.Errorf("blob size mismatch, descriptor %d, received %d", desc.Size, size)
}
}
return nil
}
// ImageImport pushes an image from a tar file to a registry
func (rc *RegClient) ImageImport(ctx context.Context, ref ref.Ref, rs io.ReadSeeker) error {
trd := &tarReadData{
handlers: map[string]tarFileHandler{},
processed: map[string]bool{},
finish: []func() error{},
manifests: map[digest.Digest]manifest.Manifest{},
}
// add handler for oci-layout, index.json, and manifest.json
rc.imageImportOCIAddHandler(ctx, ref, trd)
rc.imageImportDockerAddHandler(trd)
// process tar file looking for oci-layout and index.json, load manifests/blobs on success
err := trd.tarReadAll(rs)
if err != nil && errors.Is(err, types.ErrNotFound) && trd.dockerManifestFound {
// import failed but manifest.json found, fall back to manifest.json processing
// add handlers for the docker manifest layers
rc.imageImportDockerAddLayerHandlers(ctx, ref, trd)
// reprocess the tar looking for manifest.json files
err = trd.tarReadAll(rs)
if err != nil {
return fmt.Errorf("failed to import layers from docker tar: %w", err)
}
// push docker manifest
m, err := manifest.New(manifest.WithOrig(trd.dockerManifest))
if err != nil {
return err
}
err = rc.ManifestPut(ctx, ref, m)
if err != nil {
return err
}
} else if err != nil {
// unhandled error from tar read
return err
} else {
// successful load of OCI blobs, now push manifest and tag
err = rc.imageImportOCIPushManifests(ctx, ref, trd)
if err != nil {
return err
}
}
return nil
}
func (rc *RegClient) imageImportBlob(ctx context.Context, ref ref.Ref, desc types.Descriptor, trd *tarReadData) error {
// skip if blob already exists
_, err := rc.BlobHead(ctx, ref, desc)
if err == nil {
return nil
}
// upload blob
_, err = rc.BlobPut(ctx, ref, desc, trd.tr)
if err != nil {
return err
}
return nil
}
// imageImportDockerAddHandler processes tar files generated by docker
func (rc *RegClient) imageImportDockerAddHandler(trd *tarReadData) {
trd.handlers[dockerManifestFilename] = func(header *tar.Header, trd *tarReadData) error {
err := trd.tarReadFileJSON(&trd.dockerManifestList)
if err != nil {
return err
}
trd.dockerManifestFound = true
return nil
}
}
// imageImportDockerAddLayerHandlers imports the docker layers when OCI import fails and docker manifest found
func (rc *RegClient) imageImportDockerAddLayerHandlers(ctx context.Context, ref ref.Ref, trd *tarReadData) {
// remove handlers for OCI
delete(trd.handlers, ociLayoutFilename)
delete(trd.handlers, ociIndexFilename)
// make a docker v2 manifest from first json array entry (can only tag one image)
trd.dockerManifest.SchemaVersion = 2
trd.dockerManifest.MediaType = types.MediaTypeDocker2Manifest
trd.dockerManifest.Layers = make([]types.Descriptor, len(trd.dockerManifestList[0].Layers))
// add handler for config
trd.handlers[trd.dockerManifestList[0].Config] = func(header *tar.Header, trd *tarReadData) error {
// upload blob, digest is unknown
d, err := rc.BlobPut(ctx, ref, types.Descriptor{Size: header.Size}, trd.tr)
if err != nil {
return err
}
// save the resulting descriptor to the manifest
if od, ok := trd.dockerManifestList[0].LayerSources[d.Digest]; ok {
trd.dockerManifest.Config = od
} else {
d.MediaType = types.MediaTypeDocker2ImageConfig
trd.dockerManifest.Config = d
}
return nil
}
// add handlers for each layer
for i, layerFile := range trd.dockerManifestList[0].Layers {
func(i int) {
trd.handlers[layerFile] = func(header *tar.Header, trd *tarReadData) error {
// ensure blob is compressed with gzip to match media type
gzipR, err := archive.Compress(trd.tr, archive.CompressGzip)
if err != nil {
return err
}
// upload blob, digest and size is unknown
d, err := rc.BlobPut(ctx, ref, types.Descriptor{}, gzipR)
if err != nil {
return err
}
// save the resulting descriptor in the appropriate layer
if od, ok := trd.dockerManifestList[0].LayerSources[d.Digest]; ok {
trd.dockerManifest.Layers[i] = od
} else {
d.MediaType = types.MediaTypeDocker2LayerGzip
trd.dockerManifest.Layers[i] = d
}
return nil
}
}(i)
}
trd.handleAdded = true
}
// imageImportOCIAddHandler adds handlers for oci-layout and index.json found in OCI layout tar files
func (rc *RegClient) imageImportOCIAddHandler(ctx context.Context, ref ref.Ref, trd *tarReadData) {
// add handler for oci-layout, index.json, and manifest.json
var err error
var foundLayout, foundIndex bool
// common handler code when both oci-layout and index.json have been processed
ociHandler := func(trd *tarReadData) error {
// no need to process docker manifest.json when OCI layout is available
delete(trd.handlers, dockerManifestFilename)
// create a manifest from the index
trd.ociManifest, err = manifest.New(manifest.WithOrig(trd.ociIndex))
if err != nil {
return err
}
// start recursively processing manifests starting with the index
// there's no need to push the index.json by digest, it will be pushed by tag if needed
err = rc.imageImportOCIHandleManifest(ctx, ref, trd.ociManifest, trd, false, false)
if err != nil {
return err
}
return nil
}
trd.handlers[ociLayoutFilename] = func(header *tar.Header, trd *tarReadData) error {
var ociLayout v1.ImageLayout
err := trd.tarReadFileJSON(&ociLayout)
if err != nil {
return err
}
if ociLayout.Version != ociLayoutVersion {
// unknown version, ignore
rc.log.WithFields(logrus.Fields{
"version": ociLayout.Version,
}).Warn("Unsupported oci-layout version")
return nil
}
foundLayout = true
if foundIndex {
err = ociHandler(trd)
if err != nil {
return err
}
}
return nil
}
trd.handlers[ociIndexFilename] = func(header *tar.Header, trd *tarReadData) error {
err := trd.tarReadFileJSON(&trd.ociIndex)
if err != nil {
return err
}
foundIndex = true
if foundLayout {
err = ociHandler(trd)
if err != nil {
return err
}
}
return nil
}
}
// imageImportOCIHandleManifest recursively processes index and manifest entries from an OCI layout tar
func (rc *RegClient) imageImportOCIHandleManifest(ctx context.Context, ref ref.Ref, m manifest.Manifest, trd *tarReadData, push bool, child bool) error {
// cache the manifest to avoid needing to pull again later, this is used if index.json is a wrapper around some other manifest
trd.manifests[m.GetDescriptor().Digest] = m
handleManifest := func(d types.Descriptor, child bool) {
filename := tarOCILayoutDescPath(d)
if !trd.processed[filename] && trd.handlers[filename] == nil {
trd.handlers[filename] = func(header *tar.Header, trd *tarReadData) error {
b, err := ioutil.ReadAll(trd.tr)
if err != nil {
return err
}
switch d.MediaType {
case types.MediaTypeDocker1Manifest, types.MediaTypeDocker1ManifestSigned,
types.MediaTypeDocker2Manifest, types.MediaTypeDocker2ManifestList,
types.MediaTypeOCI1Manifest, types.MediaTypeOCI1ManifestList:
// known manifest media types
md, err := manifest.New(manifest.WithDesc(d), manifest.WithRaw(b))
if err != nil {
return err
}
return rc.imageImportOCIHandleManifest(ctx, ref, md, trd, true, child)
case types.MediaTypeDocker2ImageConfig, types.MediaTypeOCI1ImageConfig,
types.MediaTypeDocker2LayerGzip, types.MediaTypeOCI1Layer, types.MediaTypeOCI1LayerGzip,
types.MediaTypeBuildkitCacheConfig:
// known blob media types
return rc.imageImportBlob(ctx, ref, d, trd)
default:
// attempt manifest import, fall back to blob import
md, err := manifest.New(manifest.WithDesc(d), manifest.WithRaw(b))
if err == nil {
return rc.imageImportOCIHandleManifest(ctx, ref, md, trd, true, child)
}
return rc.imageImportBlob(ctx, ref, d, trd)
}
}
}
}
if !push {
mi, ok := m.(manifest.Indexer)
if !ok {
return fmt.Errorf("manifest doesn't support image methods%.0w", types.ErrUnsupportedMediaType)
}
// for root index, add handler for matching reference (or only reference)
dl, err := mi.GetManifestList()
if err != nil {
return err
}
// locate the digest in the index
var d types.Descriptor
if len(dl) == 1 {
d = dl[0]
} else if ref.Digest != "" {
d.Digest = digest.Digest(ref.Digest)
} else {
if ref.Tag == "" {
ref.Tag = "latest"
}
// if more than one digest is in the index, use the first matching tag
for _, cur := range dl {
if cur.Annotations[annotationRefName] == ref.Tag {
d = cur
break
}
}
}
if d.Digest.String() == "" {
return fmt.Errorf("could not find requested tag in index.json, %s", ref.Tag)
}
handleManifest(d, false)
// add a finish step to tag the selected digest
trd.finish = append(trd.finish, func() error {
mRef, ok := trd.manifests[d.Digest]
if !ok {
return fmt.Errorf("could not find manifest to tag, ref: %s, digest: %s", ref.CommonName(), d.Digest)
}
return rc.ManifestPut(ctx, ref, mRef)
})
} else if m.IsList() {
// for index/manifest lists, add handlers for each embedded manifest
mi, ok := m.(manifest.Indexer)
if !ok {
return fmt.Errorf("manifest doesn't support index methods%.0w", types.ErrUnsupportedMediaType)
}
dl, err := mi.GetManifestList()
if err != nil {
return err
}
for _, d := range dl {
handleManifest(d, true)
}
} else {
// else if a single image/manifest
mi, ok := m.(manifest.Imager)
if !ok {
return fmt.Errorf("manifest doesn't support image methods%.0w", types.ErrUnsupportedMediaType)
}
// add handler for the config descriptor if it's defined
cd, err := mi.GetConfig()
if err == nil {
filename := tarOCILayoutDescPath(cd)
if !trd.processed[filename] && trd.handlers[filename] == nil {
func(cd types.Descriptor) {
trd.handlers[filename] = func(header *tar.Header, trd *tarReadData) error {
return rc.imageImportBlob(ctx, ref, cd, trd)
}
}(cd)
}
}
// add handlers for each layer
layers, err := mi.GetLayers()
if err != nil {
return err
}
for _, d := range layers {
filename := tarOCILayoutDescPath(d)
if !trd.processed[filename] && trd.handlers[filename] == nil {
func(d types.Descriptor) {
trd.handlers[filename] = func(header *tar.Header, trd *tarReadData) error {
return rc.imageImportBlob(ctx, ref, d, trd)
}
}(d)
}
}
}
// add a finish func to push the manifest, this gets skipped for the index.json
if push {
trd.finish = append(trd.finish, func() error {
mRef := ref
mRef.Digest = string(m.GetDescriptor().Digest)
_, err := rc.ManifestHead(ctx, mRef)
if err == nil {
return nil
}
opts := []scheme.ManifestOpts{}
if child {
opts = append(opts, scheme.WithManifestChild())
}
return rc.ManifestPut(ctx, mRef, m, opts...)
})
}
trd.handleAdded = true
return nil
}
// imageImportOCIPushManifests uploads manifests after OCI blobs were successfully loaded
func (rc *RegClient) imageImportOCIPushManifests(ctx context.Context, ref ref.Ref, trd *tarReadData) error {
// run finish handlers in reverse order to upload nested manifests
for i := len(trd.finish) - 1; i >= 0; i-- {
err := trd.finish[i]()
if err != nil {
return err
}
}
return nil
}
func imagePlatformInList(target *platform.Platform, list []string) (bool, error) {
// special case for an unset platform
if target == nil || target.OS == "" {
for _, entry := range list {