-
Notifications
You must be signed in to change notification settings - Fork 71
/
inventory.go
2864 lines (2490 loc) · 75.5 KB
/
inventory.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
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package inventory
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/google/go-containerregistry/pkg/crane"
ggcrV1 "github.com/google/go-containerregistry/pkg/v1"
ggcrV1Google "github.com/google/go-containerregistry/pkg/v1/google"
ggcrV1Types "github.com/google/go-containerregistry/pkg/v1/types"
"github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
"sigs.k8s.io/k8s-container-image-promoter/legacy/gcloud"
cipJson "sigs.k8s.io/k8s-container-image-promoter/legacy/json"
"sigs.k8s.io/k8s-container-image-promoter/legacy/reqcounter"
"sigs.k8s.io/k8s-container-image-promoter/legacy/stream"
)
// GetSrcRegistry gets the source registry.
func GetSrcRegistry(rcs []RegistryContext) (*RegistryContext, error) {
for _, registry := range rcs {
registry := registry
if registry.Src {
return ®istry, nil
}
}
return nil, fmt.Errorf("could not find source registry")
}
// MakeSyncContext creates a SyncContext.
func MakeSyncContext(
mfests []Manifest,
threads int,
dryRun, useSvcAcc bool,
) (SyncContext, error) {
sc := SyncContext{
Threads: threads,
DryRun: dryRun,
UseServiceAccount: useSvcAcc,
Inv: make(MasterInventory),
InvIgnore: []ImageName{},
Tokens: make(map[RootRepo]gcloud.Token),
RegistryContexts: make([]RegistryContext, 0),
DigestMediaType: make(DigestMediaType),
DigestImageSize: make(DigestImageSize),
ParentDigest: make(ParentDigest),
}
registriesSeen := make(map[RegistryContext]interface{})
for _, mfest := range mfests {
for _, r := range mfest.Registries {
registriesSeen[r] = nil
}
}
// Populate SyncContext with registries found across all manifests.
for r := range registriesSeen {
sc.RegistryContexts = append(sc.RegistryContexts, r)
}
// Sort the list for determinism. We first sort it alphabetically, then sort
// it by length (reverse order, so that the longest registry names come
// first). This is so that we try to match the leading prefix against the
// longest registry names first. We sort alphabetically first because we
// want the final order to be deterministic.
sort.Slice(
sc.RegistryContexts,
func(i, j int) bool {
return sc.RegistryContexts[i].Name < sc.RegistryContexts[j].Name
},
)
sort.Slice(
sc.RegistryContexts,
func(i, j int) bool {
return len(sc.RegistryContexts[i].Name) > len(sc.RegistryContexts[j].Name)
},
)
// Populate access tokens for all registries listed in the manifest.
if useSvcAcc {
err := sc.PopulateTokens()
if err != nil {
return SyncContext{}, err
}
}
return sc, nil
}
// LogJSONSummary logs the SyncContext's Logs as a prettified JSON.
func (sc *SyncContext) LogJSONSummary() {
marshalled, err := json.MarshalIndent(sc.Logs, "", " ")
if err != nil {
logrus.Infof("There was a problem generating the JSON summary: %v",
err)
} else {
logrus.Info(string(marshalled))
}
}
// ParseManifestFromFile parses a Manifest from a filepath.
func ParseManifestFromFile(filePath string) (Manifest, error) {
var mfest Manifest
var empty Manifest
b, err := ioutil.ReadFile(filePath)
if err != nil {
return empty, err
}
mfest, err = ParseManifestYAML(b)
if err != nil {
return empty, err
}
mfest.Filepath = filePath
err = mfest.Finalize()
if err != nil {
return empty, err
}
return mfest, nil
}
// ParseThinManifestFromFile parses a ThinManifest from a filepath and generates
// a Manifest.
func ParseThinManifestFromFile(filePath string) (Manifest, error) {
var thinManifest ThinManifest
var mfest Manifest
var empty Manifest
b, err := ioutil.ReadFile(filePath)
if err != nil {
return empty, err
}
thinManifest, err = ParseThinManifestYAML(b)
if err != nil {
return empty, err
}
// Get directory name holding this thin manifest.
subProject := filepath.Base(filepath.Dir(filePath))
imagesPath := filepath.Join(filepath.Dir(filePath),
"../../images",
subProject,
"images.yaml")
images, err := ParseImagesFromFile(imagesPath)
if err != nil {
return empty, err
}
mfest.Filepath = filePath
mfest.Images = images
mfest.Registries = thinManifest.Registries
err = mfest.Finalize()
if err != nil {
return empty, err
}
return mfest, nil
}
// ParseImagesFromFile parses an Images type from a file.
func ParseImagesFromFile(filePath string) (Images, error) {
var images Images
var empty Images
b, err := ioutil.ReadFile(filePath)
if err != nil {
return empty, err
}
images, err = ParseImagesYAML(b)
if err != nil {
return empty, err
}
return images, nil
}
// Finalize finalizes a Manifest by populating extra fields.
// TODO: ST1016: methods on the same type should have the same receiver name
// nolint: stylecheck
func (m *Manifest) Finalize() error {
// Perform semantic checks (beyond just YAML validation).
srcRegistry, err := GetSrcRegistry(m.Registries)
if err != nil {
return err
}
m.SrcRegistry = srcRegistry
return nil
}
// ParseThinManifestsFromDir parses all thin Manifest files within a directory.
// We effectively have to create a map of manifests, keyed by the source
// registry (there can only be 1 source registry).
func ParseThinManifestsFromDir(
dir string,
) ([]Manifest, error) {
mfests := make([]Manifest, 0)
// Check that the thin manifests dir follows a regular, predefined format.
// This is to ensure that there isn't any funny business going on around
// paths.
if err := ValidateThinManifestDirectoryStructure(dir); err != nil {
return mfests, err
}
var parseAsManifest filepath.WalkFunc = func(
path string,
info os.FileInfo,
err error,
) error {
if err != nil {
// Prevent panic in case of incoming errors accessing this path.
logrus.Errorf("failure accessing a path %q: %v\n", path, err)
}
// Skip directories (because they are not YAML files).
if info.IsDir() {
return nil
}
// First try to parse the path as a manifest file, which must be named
// "promoter-manifest.yaml". This restriction is in place to limit the
// scope of what is read in as a promoter manifest.
if filepath.Base(path) != "promoter-manifest.yaml" {
return nil
}
// If there are any files named "promoter-manifest.yaml", they must be
// inside a subfolder within "manifests/<dir>" --- any other paths are
// forbidden.
shortened := strings.TrimPrefix(path, dir)
shortenedList := strings.Split(shortened, "/")
if len(shortenedList) != ThinManifestDepth {
return fmt.Errorf("unexpected manifest path %q",
path)
}
mfest, errParse := ParseThinManifestFromFile(path)
if errParse != nil {
logrus.Errorf("could not parse manifest file '%s'\n", path)
return errParse
}
// Save successful parse result.
mfests = append(mfests, mfest)
return nil
}
// Only look at manifests starting with the "manifests" subfolder (no need
// to walk any other toplevel subfolder).
if err := filepath.Walk(filepath.Join(dir, "manifests"), parseAsManifest); err != nil {
return mfests, err
}
if len(mfests) == 0 {
return nil, fmt.Errorf("no manifests found in dir: %s", dir)
}
return mfests, nil
}
// ValidateThinManifestDirectoryStructure enforces a particular directory
// structure for thin manifests. Most importantly, it requires that if a file
// named "foo/manifests/bar/promoter-manifest.yaml" exists, that a corresponding
// file named "foo/images/bar/promoter-manifest.yaml" must also exist.
func ValidateThinManifestDirectoryStructure(
dir string,
) error {
// First, enforce that there are directories named "images" and "manifests".
if err := validateIsDirectory(filepath.Join(dir, "images")); err != nil {
return err
}
manifestDir := filepath.Join(dir, "manifests")
if err := validateIsDirectory(manifestDir); err != nil {
return err
}
// For every subfolder in <dir>/manifests, ensure that a
// "promoter-manifest.yaml" file exists, and also that a corresponding file
// exists in the "images" folder.
files, err := ioutil.ReadDir(manifestDir)
if err != nil {
return err
}
logrus.Infof("*looking at %q", dir)
for _, file := range files {
p, err := os.Stat(filepath.Join(manifestDir, file.Name()))
if err != nil {
return err
}
// Skip non-directory sub-paths.
if !p.IsDir() {
continue
}
// Search for a "promoter-manifest.yaml" file under this directory.
manifestInfo, err := os.Stat(
filepath.Join(manifestDir,
file.Name(),
"promoter-manifest.yaml"))
if err != nil {
logrus.Warningln(err)
continue
}
if !manifestInfo.Mode().IsRegular() {
logrus.Warnf("ignoring irregular file %q", manifestInfo)
continue
}
// "promoter-manifest.yaml" exists, so check for corresponding images
// file, which MUST exist. This is why we fail early if we detect an
// error here.
imagesPath := filepath.Join(dir,
"images",
file.Name(),
"images.yaml")
imagesInfo, err := os.Stat(imagesPath)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("corresponding file %q does not exist",
imagesPath)
}
return err
}
if !imagesInfo.Mode().IsRegular() {
return fmt.Errorf("corresponding file %q is not a regular file",
imagesPath)
}
}
return nil
}
// validateIsDirectory returns nil if it does exist, otherwise a non-nil error.
func validateIsDirectory(dir string) error {
p, err := os.Stat(filepath.Join(dir))
if err != nil {
return err
}
if !p.IsDir() {
return fmt.Errorf("%q is not a directory", dir)
}
return nil
}
// ToPromotionEdges converts a list of manifests to a set of edges we want to
// try promoting.
func ToPromotionEdges(mfests []Manifest) (map[PromotionEdge]interface{}, error) {
edges := make(map[PromotionEdge]interface{})
for _, mfest := range mfests {
for _, image := range mfest.Images {
for digest, tagArray := range image.Dmap {
for _, destRC := range mfest.Registries {
if destRC == *mfest.SrcRegistry {
continue
}
if len(tagArray) > 0 {
for _, tag := range tagArray {
edge := mkPromotionEdge(
*mfest.SrcRegistry,
destRC,
image.ImageName,
digest,
tag)
edges[edge] = nil
}
} else {
// If this digest does not have any associated tags, still create
// a promotion edge for it (tagless promotion).
edge := mkPromotionEdge(
*mfest.SrcRegistry,
destRC,
image.ImageName,
digest,
"",
)
edges[edge] = nil
}
}
}
}
}
return CheckOverlappingEdges(edges)
}
func mkPromotionEdge(
srcRC, dstRC RegistryContext,
srcImageName ImageName,
digest Digest,
tag Tag,
) PromotionEdge {
edge := PromotionEdge{
SrcRegistry: srcRC,
SrcImageTag: ImageTag{
ImageName: srcImageName,
Tag: tag,
},
Digest: digest,
DstRegistry: dstRC,
}
// The name in the destination is the same as the name in the source.
edge.DstImageTag = ImageTag{
ImageName: srcImageName,
Tag: tag,
}
return edge
}
// This filters out those edges from ToPromotionEdges (found in []Manifest), to
// only those PromotionEdges that makes sense to keep around. For example, we
// want to remove all edges that have already been promoted.
func (sc *SyncContext) GetPromotionCandidates(edges map[PromotionEdge]interface{}) (
map[PromotionEdge]interface{},
bool,
) {
clean := true
// Create lookup-optimized structure for images to ignore.
ignoreMap := make(map[ImageName]interface{})
for _, ignoreMe := range sc.InvIgnore {
ignoreMap[ignoreMe] = nil
}
toPromote := make(map[PromotionEdge]interface{})
for edge := range edges {
// If the edge should be ignored because of a bad read in sc.Inv,
// drop it.
if img, ok := ignoreMap[edge.SrcImageTag.ImageName]; ok {
logrus.Warnf(
"edge %v: ignoring because src image could not be read: %s\n",
edge,
img,
)
continue
}
sp, dp := edge.VertexProps(&sc.Inv)
// If dst vertex exists, NOP.
if dp.PqinDigestMatch {
logrus.Infof("edge %v: skipping because it was already promoted (case 1)\n", edge)
continue
}
// If this edge is for a tagless promotion, skip if the digest exists in
// the destination.
if edge.DstImageTag.Tag == "" && dp.DigestExists {
// Still, log a warning if the source is missing the image.
if !sp.DigestExists {
logrus.Errorf("edge %v: skipping %s/%s@%s because it was already promoted, but it is still _LOST_ (can't find it in src registry! please backfill it!)\n", edge, edge.SrcRegistry.Name, edge.SrcImageTag.ImageName, edge.Digest)
}
continue
}
// If src vertex missing, LOST && NOP. We just need the digest to exist
// in src (we don't care if it points to the wrong tag).
if !sp.DigestExists {
logrus.Errorf("edge %v: skipping %s/%s@%s because it is _LOST_ (can't find it in src registry!)\n", edge, edge.SrcRegistry.Name, edge.SrcImageTag.ImageName, edge.Digest)
continue
}
if dp.PqinExists {
if dp.DigestExists {
// If the destination already has the digest, but is pointing to
// a different tag, then it's an error.
if dp.PqinDigestMatch {
// NOP (already promoted).
logrus.Infof("edge %v: skipping because it was already promoted (case 2)\n", edge)
continue
} else {
logrus.Errorf("edge %v: tag %s: ERROR: tag move detected from %s to %s", edge, edge.DstImageTag.Tag, edge.Digest, *sc.getDigestForTag(edge.DstImageTag.Tag))
clean = false
// We continue instead of returning early, because we want
// to see and log as many errors as possible as we go
// through each promotion edge.
continue
}
} else {
// Pqin points to the wrong digest.
logrus.Warnf("edge %v: tag %s points to the wrong digest; moving\n", edge, dp.BadDigest)
}
} else {
if dp.DigestExists {
// Digest exists in dst, but the pqin we desire does not
// exist. Just add the pqin to this existing digest.
logrus.Infof("edge %v: digest %q already exists, but does not have the pqin we want (%s)\n", edge, edge.Digest, dp.OtherTags)
} else {
// Neither the digest nor the pqin exists in dst.
logrus.Infof("edge %v: regular promotion (neither digest nor pqin exists in dst)\n", edge)
}
}
toPromote[edge] = nil
}
return toPromote, clean
}
func (sc *SyncContext) getDigestForTag(inputTag Tag) *Digest {
for _, rii := range sc.Inv {
for _, digestTags := range rii {
for digest, tagSlice := range digestTags {
for _, tag := range tagSlice {
if tag == inputTag {
return &digest
}
}
}
}
}
return nil
}
// CheckOverlappingEdges checks to ensure that all the edges taken together as a
// whole are consistent. It checks that there are no duplicate promotions
// desired to the same destination vertex (same destination PQIN). If the
// digests are the same for those edges, ignore because by definition the
// digests are cryptographically guaranteed to be the same thing (it doesn't
// matter if 2 different parties want the same exact image to become promoted to
// the same destination --- in many ways this is actually a good thing because
// it's a form of redundancy). However, return an error if the digests are
// different, because most likely this is at best just human error and at worst
// a malicious attack (someone trying to push an image to an endpoint they
// shouldn't own).
func CheckOverlappingEdges(
edges map[PromotionEdge]interface{}) (map[PromotionEdge]interface{}, error) {
// Build up a "promotionIntent". This will be checked below.
promotionIntent := make(map[string]map[Digest][]PromotionEdge)
checked := make(map[PromotionEdge]interface{})
for edge := range edges {
// Skip overlap checks for edges that are tagless, because by definition
// they cannot overlap with another edge.
if edge.DstImageTag.Tag == "" {
checked[edge] = nil
continue
}
dstPQIN := ToPQIN(edge.DstRegistry.Name,
edge.DstImageTag.ImageName,
edge.DstImageTag.Tag)
digestToEdges, ok := promotionIntent[dstPQIN]
if ok {
// Store the edge.
digestToEdges[edge.Digest] = append(digestToEdges[edge.Digest], edge)
promotionIntent[dstPQIN] = digestToEdges
} else {
// Make this edge lay claim to this destination vertex.
edgeList := make([]PromotionEdge, 0)
edgeList = append(edgeList, edge)
digestToEdges := make(map[Digest][]PromotionEdge)
digestToEdges[edge.Digest] = edgeList
promotionIntent[dstPQIN] = digestToEdges
}
}
// Review the promotionIntent to ensure that there are no issues.
overlapError := false
emptyEdgeListError := false
for pqin, digestToEdges := range promotionIntent {
if len(digestToEdges) < 2 {
for _, edgeList := range digestToEdges {
switch len(edgeList) {
case 0:
logrus.Errorf("no edges for %v", pqin)
emptyEdgeListError = true
case 1:
checked[edgeList[0]] = nil
default:
logrus.Infof("redundant promotion: multiple edges want to promote the same digest to the same destination endpoint %v:", pqin)
// TODO(lint): rangeValCopy: each iteration copies 192 bytes (consider pointers or indexing)
//nolint:gocritic
for _, edge := range edgeList {
logrus.Infof("%v", edge)
}
logrus.Infof("using the first one: %v", edgeList[0])
checked[edgeList[0]] = nil
}
}
} else {
logrus.Errorf("multiple edges want to promote *different* images (digests) to the same destination endpoint %v:", pqin)
for digest, edgeList := range digestToEdges {
logrus.Errorf(" for digest %v:\n", digest)
// TODO(lint): rangeValCopy: each iteration copies 192 bytes (consider pointers or indexing)
//nolint:gocritic
for _, edge := range edgeList {
logrus.Errorf("%v\n", edge)
}
}
overlapError = true
}
}
if overlapError {
return nil, fmt.Errorf("overlapping edges detected")
}
if emptyEdgeListError {
return nil, fmt.Errorf("empty edgeList(s) detected")
}
return checked, nil
}
// VertexProps determines the properties of each vertex (src and dst) in the
// edge, depending on the state of the world in the MasterInventory.
func (edge *PromotionEdge) VertexProps(
mi *MasterInventory,
) (d, s VertexProperty) {
return edge.VertexPropsFor(&edge.SrcRegistry, &edge.SrcImageTag, mi),
edge.VertexPropsFor(&edge.DstRegistry, &edge.DstImageTag, mi)
}
// VertexPropsFor examines one of the two vertices (src or dst) of a
// PromotionEdge.
func (edge *PromotionEdge) VertexPropsFor(
rc *RegistryContext,
imageTag *ImageTag,
mi *MasterInventory,
) VertexProperty {
p := VertexProperty{}
rii, ok := (*mi)[rc.Name]
if !ok {
return p
}
digestTags, ok := rii[imageTag.ImageName]
if !ok {
return p
}
if tagSlice, ok := digestTags[edge.Digest]; ok {
p.DigestExists = true
// Record the tags that are associated with this digest; it may turn out
// that within this tagslice, we indeed have the correct digest, in
// which we set it back to an empty slice.
p.OtherTags = tagSlice
}
for digest, tagSlice := range digestTags {
for _, tag := range tagSlice {
if tag == imageTag.Tag {
p.PqinExists = true
if digest == edge.Digest {
p.PqinDigestMatch = true
// Both the digest and tag match what we wanted in the
// imageTag, so there are no extraneous tags to bother with.
p.OtherTags = TagSlice{}
} else {
p.BadDigest = digest
}
}
}
}
return p
}
// ParseManifestYAML parses a Manifest from a byteslice. This function is
// separate from ParseManifestFromFile() so that it can be tested independently.
func ParseManifestYAML(b []byte) (Manifest, error) {
var m Manifest
if err := yaml.UnmarshalStrict(b, &m); err != nil {
return m, err
}
return m, m.Validate()
}
// ParseThinManifestYAML parses a ThinManifest from a byteslice.
func ParseThinManifestYAML(b []byte) (ThinManifest, error) {
var m ThinManifest
if err := yaml.UnmarshalStrict(b, &m); err != nil {
return m, err
}
return m, nil
}
// ParseImagesYAML parses Images from a byteslice.
func ParseImagesYAML(b []byte) (Images, error) {
var images Images
if err := yaml.UnmarshalStrict(b, &images); err != nil {
return images, err
}
return images, nil
}
// Validate checks for semantic errors in the yaml fields (the structure of the
// yaml is checked during unmarshaling).
func (m Manifest) Validate() error {
if err := validateRequiredComponents(m); err != nil {
return err
}
return validateImages(m.Images)
}
func validateImages(images []Image) error {
for _, image := range images {
for digest, tagSlice := range image.Dmap {
if err := ValidateDigest(digest); err != nil {
return err
}
for _, tag := range tagSlice {
if err := ValidateTag(tag); err != nil {
return err
}
}
}
}
return nil
}
// ValidateDigest validates the digest.
func ValidateDigest(digest Digest) error {
validDigest := regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
if !validDigest.Match([]byte(digest)) {
return fmt.Errorf("invalid digest: %v", digest)
}
return nil
}
// ValidateTag validates the tag.
func ValidateTag(tag Tag) error {
validTag := regexp.MustCompile(`^[\w][\w.-]{0,127}$`)
if !validTag.Match([]byte(tag)) {
return fmt.Errorf("invalid tag: %v", tag)
}
return nil
}
// ValidateRegistryImagePath validates the RegistryImagePath.
func ValidateRegistryImagePath(rip RegistryImagePath) error {
// \w is [0-9a-zA-Z_]
validRegistryImagePath := regexp.MustCompile(`^[\w-]+(\.[\w-]+)+(/[\w-]+)+$`)
if !validRegistryImagePath.Match([]byte(rip)) {
return fmt.Errorf("invalid registry image path: %v", rip)
}
return nil
}
func (m Manifest) srcRegistryCount() int {
var count int
for _, registry := range m.Registries {
if registry.Src {
count++
}
}
return count
}
func (m Manifest) srcRegistryName() RegistryName {
for _, registry := range m.Registries {
if registry.Src {
return registry.Name
}
}
return RegistryName("")
}
func validateRequiredComponents(m Manifest) error {
// TODO: Should we return []error here instead?
errs := make([]string, 0)
srcRegistryName := RegistryName("")
if len(m.Registries) > 0 {
if m.srcRegistryCount() > 1 {
errs = append(errs, "cannot have more than 1 source registry")
}
srcRegistryName = m.srcRegistryName()
if len(srcRegistryName) == 0 {
errs = append(errs, "source registry must be set")
}
}
knownRegistries := make([]RegistryName, 0)
if len(m.Registries) == 0 {
errs = append(errs, "'registries' field cannot be empty")
}
for _, registry := range m.Registries {
if len(registry.Name) == 0 {
errs = append(
errs,
"registries: 'name' field cannot be empty",
)
}
// TODO(lint): SA4010: this result of append is never used, except maybe in other appends
//nolint:staticcheck
knownRegistries = append(knownRegistries, registry.Name)
}
for _, image := range m.Images {
if len(image.ImageName) == 0 {
errs = append(
errs,
"images: 'name' field cannot be empty",
)
}
if len(image.Dmap) == 0 {
errs = append(
errs,
"images: 'dmap' field cannot be empty",
)
}
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf(strings.Join(errs, "\n"))
}
// PrettyValue creates a prettified string representation of MasterInventory.
func (mi *MasterInventory) PrettyValue() string {
var b strings.Builder
regNames := []RegistryName{}
for regName := range *mi {
regNames = append(regNames, regName)
}
sort.Slice(
regNames,
func(i, j int) bool {
return regNames[i] < regNames[j]
},
)
for _, regName := range regNames {
v, ok := (*mi)[regName]
if !ok {
logrus.Error("corrupt MasterInventory")
return ""
}
fmt.Fprintln(&b, regName)
imageNamesSorted := make([]string, 0)
for imageName := range v {
imageNamesSorted = append(imageNamesSorted, string(imageName))
}
sort.Strings(imageNamesSorted)
for _, imageName := range imageNamesSorted {
fmt.Fprintf(&b, " %v\n", imageName)
digestTags, ok := v[ImageName(imageName)]
if !ok {
continue
}
digestSorted := make([]string, 0)
for digest := range digestTags {
digestSorted = append(digestSorted, string(digest))
}
sort.Strings(digestSorted)
for _, digest := range digestSorted {
fmt.Fprintf(&b, " %v\n", digest)
tags, ok := digestTags[Digest(digest)]
if !ok {
continue
}
for _, tag := range tags {
fmt.Fprintf(&b, " %v\n", tag)
}
}
}
}
return b.String()
}
// PrettyValue converts a Registry to a prettified string representation.
func (r *Registry) PrettyValue() string {
var b strings.Builder
fmt.Fprintf(&b, "%v (%v)\n", r.RegistryNameLong, r.RegistryName)
fmt.Fprintln(&b, r.RegInvImageDigest.PrettyValue())
return b.String()
}
// PrettyValue converts a RegInvImageDigest to a prettified string
// representation.
func (riid *RegInvImageDigest) PrettyValue() string {
var b strings.Builder
ids := make([]ImageDigest, 0)
for id := range *riid {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool {
iID := string(ids[i].ImageName) + string(ids[i].Digest)
jID := string(ids[j].ImageName) + string(ids[i].Digest)
return iID < jID
})
for _, id := range ids {
fmt.Fprintf(&b, " %v\n", id.ImageName)
fmt.Fprintf(&b, " %v\n", id.Digest)
tagArray, ok := (*riid)[id]
if !ok {
continue
}
tagArraySorted := make([]string, 0)
for _, tag := range tagArray {
tagArraySorted = append(tagArraySorted, string(tag))
}
sort.Strings(tagArraySorted)
for _, tag := range tagArraySorted {
fmt.Fprintf(&b, " %v\n", tag)
}
}
return b.String()
}
func getRegistryTagsWrapper(
req stream.ExternalRequest,
) (*ggcrV1Google.Tags, error) {
var googleTags *ggcrV1Google.Tags
retryFn := func() error {
var retryErr error
googleTags, retryErr = getRegistryTagsFrom(req)
return retryErr
}
b := stream.BackoffDefault()
notify := func(err error, t time.Duration) {
logrus.Errorf("error: %v happened at time: %v", err, t)
}
err := backoff.RetryNotify(
retryFn,
b,
notify,
)
if err != nil {
logrus.Error(err)