/
new.go
1596 lines (1434 loc) · 49.3 KB
/
new.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 release
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/blang/semver"
"github.com/docker/docker/pkg/archive"
"github.com/ghodss/yaml"
digest "github.com/opencontainers/go-digest"
"github.com/spf13/cobra"
"k8s.io/klog"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/pkg/version"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/util/templates"
imageapi "github.com/openshift/api/image/v1"
imageclient "github.com/openshift/client-go/image/clientset/versioned"
"github.com/openshift/origin/pkg/image/apis/image/docker10"
imagereference "github.com/openshift/origin/pkg/image/apis/image/reference"
imageappend "github.com/openshift/origin/pkg/oc/cli/image/append"
"github.com/openshift/origin/pkg/oc/cli/image/extract"
imagemanifest "github.com/openshift/origin/pkg/oc/cli/image/manifest"
)
func NewNewOptions(streams genericclioptions.IOStreams) *NewOptions {
return &NewOptions{
IOStreams: streams,
ParallelOptions: imagemanifest.ParallelOptions{MaxPerRegistry: 4},
// TODO: only cluster-version-operator and maybe CLI should be in this list,
// the others should always be referenced by the cluster-bootstrap or
// another operator.
AlwaysInclude: []string{"cluster-version-operator", "cli", "installer"},
ToImageBaseTag: "cluster-version-operator",
// We strongly control the set of allowed component versions to prevent confusion
// about what component versions may be used for. Changing this list requires
// approval from the release architects.
AllowedComponents: []string{"kubernetes"},
}
}
func NewRelease(f kcmdutil.Factory, parentName string, streams genericclioptions.IOStreams) *cobra.Command {
o := NewNewOptions(streams)
cmd := &cobra.Command{
Use: "new [SRC=DST ...]",
Short: "Create a new OpenShift release",
Long: templates.LongDesc(`
Build a new OpenShift release image that will update a cluster
OpenShift uses long-running active management processes called "operators" to
keep the cluster running and manage component lifecycle. This command
composes a set of images with operator definitions into a single update payload
that can be used to install or update a cluster.
Operators are expected to host the config they need to be installed to a cluster
in the '/manifests' directory in their image. This command iterates over a set of
operator images and extracts those manifests into a single, ordered list of
Kubernetes objects that can then be iteratively updated on a cluster by the
cluster version operator when it is time to perform an update. Manifest files are
renamed to '0000_70_<image_name>_<filename>' by default, and an operator author that
needs to provide a global-ordered file (before or after other operators) should
prepend '0000_NN_<component>_' to their filename, which instructs the release builder
to not assign a component prefix. Only images in the input that have the image label
'io.openshift.release.operator=true' will have manifests loaded.
If an image is in the input but is not referenced by an operator's image-references
file, the image will not be included in the final release image unless
--include=NAME is provided.
Mappings specified via SRC=DST positional arguments allows overriding particular
operators with a specific image. For example:
cluster-version-operator=registry.example.com/openshift/cluster-version-operator:test-123
will override the default cluster-version-operator image with one pulled from
registry.example.com.
`),
Example: templates.Examples(fmt.Sprintf(`
# Create a release from the latest origin images and push to a DockerHub repo
%[1]s new --from-image-stream=4.1 -n origin --to-image docker.io/mycompany/myrepo:latest
# Create a new release with updated metadata from a previous release
%[1]s new --from-release registry.svc.ci.openshift.org/origin/release:v4.1 --name 4.1.1 \
--previous 4.1.0 --metadata ... --to-image docker.io/mycompany/myrepo:latest
# Create a new release and override a single image
%[1]s new --from-release registry.svc.ci.openshift.org/origin/release:v4.1 \
cli=docker.io/mycompany/cli:latest --to-image docker.io/mycompany/myrepo:latest
# Run a verification pass to ensure the release can be reproduced
%[1]s new --from-release registry.svc.ci.openshift.org/origin/release:v4.1
`, parentName)),
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(f, cmd, args))
kcmdutil.CheckErr(o.Validate())
kcmdutil.CheckErr(o.Run())
},
}
flags := cmd.Flags()
o.SecurityOptions.Bind(flags)
o.ParallelOptions.Bind(flags)
// image inputs
flags.StringSliceVar(&o.MappingFilenames, "mapping-file", o.MappingFilenames, "A file defining a mapping of input images to use to build the release")
flags.StringVar(&o.FromImageStream, "from-image-stream", o.FromImageStream, "Look at all tags in the provided image stream and build a release payload from them.")
flags.StringVarP(&o.FromImageStreamFile, "from-image-stream-file", "f", o.FromImageStreamFile, "Take the provided image stream on disk and build a release payload from it.")
flags.StringVar(&o.FromDirectory, "from-dir", o.FromDirectory, "Use this directory as the source for the release payload.")
flags.StringVar(&o.FromReleaseImage, "from-release", o.FromReleaseImage, "Use an existing release image as input.")
flags.StringVar(&o.ReferenceMode, "reference-mode", o.ReferenceMode, "By default, the image reference from an image stream points to the public registry for the stream and the image digest. Pass 'source' to build references to the originating image.")
flags.StringVar(&o.ExtraComponentVersions, "component-versions", o.ExtraComponentVersions, "Supply additional version strings to the release in key=value[,key=value] form.")
// properties of the release
flags.StringVar(&o.Name, "name", o.Name, "The name of the release. Will default to the current time.")
flags.StringSliceVar(&o.PreviousVersions, "previous", o.PreviousVersions, "A list of semantic versions that should preceed this version in the release manifest.")
flags.StringVar(&o.ReleaseMetadata, "metadata", o.ReleaseMetadata, "A JSON object to attach as the metadata for the release manifest.")
flags.BoolVar(&o.ForceManifest, "release-manifest", o.ForceManifest, "If true, a release manifest will be created using --name as the semantic version.")
// validation
flags.BoolVar(&o.AllowMissingImages, "allow-missing-images", o.AllowMissingImages, "Ignore errors when an operator references a release image that is not included.")
flags.BoolVar(&o.SkipManifestCheck, "skip-manifest-check", o.SkipManifestCheck, "Ignore errors when an operator includes a yaml/yml/json file that is not parseable.")
flags.StringSliceVar(&o.Exclude, "exclude", o.Exclude, "A list of image names or tags to exclude. It is applied after all inputs. Comma separated or individual arguments.")
flags.StringSliceVar(&o.AlwaysInclude, "include", o.AlwaysInclude, "A list of image tags that should not be pruned. Excluding a tag takes precedence. Comma separated or individual arguments.")
// destination
flags.BoolVar(&o.DryRun, "dry-run", o.DryRun, "Skips changes to external registries via mirroring or pushing images.")
flags.StringVar(&o.Mirror, "mirror", o.Mirror, "Mirror the contents of the release to this repository.")
flags.StringVar(&o.ToDir, "to-dir", o.ToDir, "Output the release manifests to a directory instead of creating an image.")
flags.StringVar(&o.ToFile, "to-file", o.ToFile, "Output the release to a tar file instead of creating an image.")
flags.StringVar(&o.ToImage, "to-image", o.ToImage, "The location to upload the release image to.")
flags.StringVar(&o.ToImageBase, "to-image-base", o.ToImageBase, "If specified, the image to add the release layer on top of.")
flags.StringVar(&o.ToImageBaseTag, "to-image-base-tag", o.ToImageBaseTag, "If specified, the image tag in the input to add the release layer on top of. Defaults to cluster-version-operator.")
flags.StringVar(&o.ToSignature, "to-signature", o.ToSignature, "If specified, output a message that can be signed that describes this release. Requires --to-image.")
// misc
flags.StringVarP(&o.Output, "output", "o", o.Output, "Output the mapping definition in this format.")
flags.StringVar(&o.Directory, "dir", o.Directory, "Directory to write release contents to, will default to a temporary directory.")
return cmd
}
type NewOptions struct {
genericclioptions.IOStreams
SecurityOptions imagemanifest.SecurityOptions
ParallelOptions imagemanifest.ParallelOptions
FromDirectory string
Directory string
MappingFilenames []string
Output string
Name string
FromReleaseImage string
FromImageStream string
FromImageStreamFile string
Namespace string
ReferenceMode string
ExtraComponentVersions string
AllowedComponents []string
Exclude []string
AlwaysInclude []string
ForceManifest bool
ReleaseMetadata string
PreviousVersions []string
DryRun bool
ToFile string
ToDir string
ToImage string
ToImageBase string
ToImageBaseTag string
ToSignature string
Mirror string
AllowMissingImages bool
SkipManifestCheck bool
Mappings []Mapping
ImageClient imageclient.Interface
VerifyOutputFn func(dgst digest.Digest) error
cleanupFns []func()
}
func (o *NewOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string) error {
overlap := make(map[string]string)
var mappings []Mapping
for _, filename := range o.MappingFilenames {
fileMappings, err := parseFile(filename, overlap)
if err != nil {
return err
}
mappings = append(mappings, fileMappings...)
}
argMappings, err := parseArgs(args, overlap)
if err != nil {
return err
}
mappings = append(mappings, argMappings...)
o.Mappings = mappings
if len(o.FromImageStream) > 0 {
cfg, err := f.ToRESTConfig()
if err != nil {
return err
}
client, err := imageclient.NewForConfig(cfg)
if err != nil {
return err
}
o.ImageClient = client
if len(o.Namespace) == 0 {
namespace, _, err := f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
o.Namespace = namespace
}
}
return nil
}
func (o *NewOptions) Validate() error {
sources := 0
if len(o.FromImageStream) > 0 {
sources++
}
if len(o.FromImageStreamFile) > 0 {
sources++
}
if len(o.FromReleaseImage) > 0 {
sources++
}
if len(o.FromDirectory) > 0 {
sources++
}
if sources > 1 {
return fmt.Errorf("only one of --from-image-stream, --from-image-stream-file, --from-release, or --from-dir may be specified")
}
if sources == 0 {
if len(o.Mappings) == 0 {
return fmt.Errorf("must specify image mappings when no other source is defined")
}
}
if len(o.ToSignature) > 0 && len(o.ToImage) == 0 {
return fmt.Errorf("--to-signature requires --to-image")
}
if len(o.Mirror) > 0 && o.ReferenceMode != "" && o.ReferenceMode != "public" {
return fmt.Errorf("--reference-mode must be public or empty when using --mirror")
}
return nil
}
type imageData struct {
Ref imagereference.DockerImageReference
Config *docker10.DockerImageConfig
Digest digest.Digest
ContentDigest digest.Digest
Directory string
}
func findStatusTagEvents(tags []imageapi.NamedTagEventList, name string) *imageapi.NamedTagEventList {
for i := range tags {
tag := &tags[i]
if tag.Tag != name {
continue
}
return tag
}
return nil
}
func findStatusTagEvent(tags []imageapi.NamedTagEventList, name string) *imageapi.TagEvent {
events := findStatusTagEvents(tags, name)
if events == nil || len(events.Items) == 0 {
return nil
}
return &events.Items[0]
}
func findSpecTag(tags []imageapi.TagReference, name string) *imageapi.TagReference {
for i, tag := range tags {
if tag.Name != name {
continue
}
return &tags[i]
}
return nil
}
type CincinnatiMetadata struct {
Kind string `json:"kind"`
Version string `json:"version"`
Previous []string `json:"previous"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
func (o *NewOptions) cleanup() {
for _, fn := range o.cleanupFns {
fn()
}
o.cleanupFns = nil
}
func (o *NewOptions) Run() error {
defer o.cleanup()
// check parameters
extraComponentVersions, err := parseComponentVersionsLabel(o.ExtraComponentVersions)
if err != nil {
return fmt.Errorf("--component-versions is invalid: %v", err)
}
if len(o.Name) > 0 {
if _, err := semver.Parse(o.Name); err != nil {
return fmt.Errorf("--name must be a semantic version: %v", err)
}
}
if len(o.ReleaseMetadata) > 0 {
if err := json.Unmarshal([]byte(o.ReleaseMetadata), &CincinnatiMetadata{}); err != nil {
return fmt.Errorf("invalid --metadata: %v", err)
}
}
hasMetadataOverrides := len(o.Name) > 0 &&
len(o.ReleaseMetadata) > 0 &&
len(o.PreviousVersions) > 0 &&
len(o.ToImageBase) > 0 &&
len(o.ExtraComponentVersions) > 0
exclude := sets.NewString()
for _, s := range o.Exclude {
exclude.Insert(s)
}
metadata := make(map[string]imageData)
var ordered []string
var is *imageapi.ImageStream
now := time.Now().UTC().Truncate(time.Second)
switch {
case len(o.FromReleaseImage) > 0:
ref, err := imagereference.Parse(o.FromReleaseImage)
if err != nil {
return fmt.Errorf("--from-release was not a valid pullspec: %v", err)
}
verifier := imagemanifest.NewVerifier()
var releaseDigest digest.Digest
var baseDigest string
var imageReferencesData, releaseMetadata []byte
buf := &bytes.Buffer{}
extractOpts := extract.NewOptions(genericclioptions.IOStreams{Out: buf, ErrOut: o.ErrOut})
extractOpts.SecurityOptions = o.SecurityOptions
extractOpts.OnlyFiles = true
extractOpts.Mappings = []extract.Mapping{
{
ImageRef: ref,
From: "release-manifests/",
},
}
extractOpts.ImageMetadataCallback = func(m *extract.Mapping, dgst, contentDigest digest.Digest, config *docker10.DockerImageConfig) {
verifier.Verify(dgst, contentDigest)
releaseDigest = contentDigest
if config.Config != nil {
baseDigest = config.Config.Labels[annotationReleaseBaseImageDigest]
klog.V(4).Infof("Release image was built on top of %s", baseDigest)
}
}
extractOpts.TarEntryCallback = func(hdr *tar.Header, _ extract.LayerInfo, r io.Reader) (bool, error) {
var err error
if hdr.Name == "image-references" {
imageReferencesData, err = ioutil.ReadAll(r)
if err != nil {
return false, err
}
}
if hdr.Name == "release-metadata" {
releaseMetadata, err = ioutil.ReadAll(r)
if err != nil {
return false, err
}
}
if len(imageReferencesData) > 0 && len(releaseMetadata) > 0 {
return false, nil
}
return true, nil
}
if err := extractOpts.Run(); err != nil {
return err
}
if len(imageReferencesData) == 0 {
return fmt.Errorf("release image did not contain any image-references content")
}
if !verifier.Verified() {
err := fmt.Errorf("the input release image failed content verification and may have been tampered with")
if !o.SecurityOptions.SkipVerification {
return err
}
fmt.Fprintf(o.ErrOut, "warning: %v\n", err)
}
inputIS, err := readReleaseImageReferences(imageReferencesData)
if err != nil {
return fmt.Errorf("unable to load image-references from release contents: %v", err)
}
var cm CincinnatiMetadata
if err := json.Unmarshal(releaseMetadata, &cm); err != nil {
return fmt.Errorf("unable to load release-metadata from release contents: %v", err)
}
is = inputIS.DeepCopy()
for _, tag := range is.Spec.Tags {
ordered = append(ordered, tag.Name)
}
// default the base image to a matching release payload digest or error
if len(o.ToImageBase) == 0 && len(baseDigest) > 0 {
for _, tag := range is.Spec.Tags {
if tag.From == nil || tag.From.Kind != "DockerImage" {
continue
}
ref, err := imagereference.Parse(tag.From.Name)
if err != nil {
return fmt.Errorf("release image contains unparseable reference for %q: %v", tag.Name, err)
}
if ref.ID == baseDigest {
o.ToImageBase = tag.From.Name
break
}
}
if len(o.ToImageBase) == 0 {
return fmt.Errorf("unable to find an image within the release that matches the base image manifest %q, please specify --to-image-base", baseDigest)
}
}
if len(o.Name) == 0 {
o.Name = is.Name
}
if len(o.ReleaseMetadata) == 0 && cm.Metadata != nil {
data, err := json.Marshal(cm.Metadata)
if err != nil {
return fmt.Errorf("unable to marshal release metadata: %v", err)
}
o.ReleaseMetadata = string(data)
}
if o.PreviousVersions == nil {
o.PreviousVersions = cm.Previous
}
if hasMetadataOverrides {
if is.Annotations == nil {
is.Annotations = map[string]string{}
}
is.Annotations[annotationReleaseFromRelease] = o.FromReleaseImage
fmt.Fprintf(o.ErrOut, "info: Found %d images in release\n", len(is.Spec.Tags))
} else {
klog.V(2).Infof("No metadata changes, building canonical release")
now = is.CreationTimestamp.Time.UTC()
if o.VerifyOutputFn == nil {
o.VerifyOutputFn = func(actual digest.Digest) error {
// TODO: check contents, digests, image stream, the layers, and the manifest
if actual != releaseDigest {
return fmt.Errorf("the release could not be reproduced from its inputs")
}
return nil
}
}
if len(ref.Tag) > 0 {
fmt.Fprintf(o.ErrOut, "info: Release %s built from %d images\n", releaseDigest, len(is.Spec.Tags))
} else {
fmt.Fprintf(o.ErrOut, "info: Release built from %d images\n", len(is.Spec.Tags))
}
}
case len(o.FromImageStream) > 0, len(o.FromImageStreamFile) > 0:
is = &imageapi.ImageStream{}
is.Annotations = map[string]string{}
if len(o.FromImageStream) > 0 && len(o.Namespace) > 0 {
is.Annotations[annotationReleaseFromImageStream] = fmt.Sprintf("%s/%s", o.Namespace, o.FromImageStream)
}
var inputIS *imageapi.ImageStream
if len(o.FromImageStreamFile) > 0 {
data, err := filenameContents(o.FromImageStreamFile, o.IOStreams.In)
if os.IsNotExist(err) {
return err
}
if err != nil {
return fmt.Errorf("unable to read input image stream file: %v", err)
}
is := &imageapi.ImageStream{}
if err := yaml.Unmarshal(data, &is); err != nil {
return fmt.Errorf("unable to load input image stream file: %v", err)
}
if is.Kind != "ImageStream" || is.APIVersion != "image.openshift.io/v1" {
return fmt.Errorf("unrecognized input image stream file, must be an ImageStream in image.openshift.io/v1")
}
inputIS = is
} else {
is, err := o.ImageClient.ImageV1().ImageStreams(o.Namespace).Get(o.FromImageStream, metav1.GetOptions{})
if err != nil {
return err
}
inputIS = is
}
if inputIS.Annotations == nil {
inputIS.Annotations = make(map[string]string)
}
inputIS.Annotations[annotationBuildVersions] = extraComponentVersions.String()
if err := resolveImageStreamTagsToReferenceMode(inputIS, is, o.ReferenceMode, exclude); err != nil {
return err
}
for _, tag := range is.Spec.Tags {
ordered = append(ordered, tag.Name)
}
fmt.Fprintf(o.ErrOut, "info: Found %d images in image stream\n", len(is.Spec.Tags))
case len(o.FromDirectory) > 0:
fmt.Fprintf(o.ErrOut, "info: Using %s as the input to the release\n", o.FromDirectory)
files, err := ioutil.ReadDir(o.FromDirectory)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() {
name := f.Name()
if exclude.Has(name) {
klog.V(2).Infof("Excluded directory %#v", f)
continue
}
metadata[name] = imageData{Directory: filepath.Join(o.FromDirectory, f.Name())}
ordered = append(ordered, name)
}
if f.Name() == "image-references" {
data, err := ioutil.ReadFile(filepath.Join(o.FromDirectory, "image-references"))
if err != nil {
return err
}
overrideIS := &imageapi.ImageStream{}
if err := json.Unmarshal(data, overrideIS); err != nil {
return fmt.Errorf("unable to load image data from release directory")
}
if overrideIS.TypeMeta.Kind != "ImageStream" || overrideIS.APIVersion != "image.openshift.io/v1" {
return fmt.Errorf("could not parse images: invalid kind/apiVersion")
}
is = overrideIS
continue
}
}
fmt.Fprintf(o.ErrOut, "info: Found %d operator manifest directories on disk\n", len(ordered))
default:
for _, m := range o.Mappings {
if exclude.Has(m.Source) {
klog.V(2).Infof("Excluded mapping %s", m.Source)
continue
}
ordered = append(ordered, m.Source)
}
}
name := o.Name
if len(name) == 0 {
name = "0.0.1-" + now.Format("2006-01-02-150405")
}
cm := &CincinnatiMetadata{Kind: "cincinnati-metadata-v0"}
semverName, err := semver.Parse(name)
if err != nil {
return fmt.Errorf("--name must be a semantic version")
}
cm.Version = semverName.String()
if len(o.ReleaseMetadata) > 0 {
if err := json.Unmarshal([]byte(o.ReleaseMetadata), &cm.Metadata); err != nil {
return fmt.Errorf("invalid --metadata: %v", err)
}
}
for _, previous := range o.PreviousVersions {
if len(previous) == 0 {
continue
}
v, err := semver.Parse(previous)
if err != nil {
return fmt.Errorf("%q is not a valid semantic version: %v", previous, err)
}
cm.Previous = append(cm.Previous, v.String())
}
sort.Strings(cm.Previous)
if cm.Previous == nil {
cm.Previous = []string{}
}
klog.V(4).Infof("Release metadata:\n%s", toJSONString(cm))
if is == nil {
is = &imageapi.ImageStream{
ObjectMeta: metav1.ObjectMeta{},
}
}
is.TypeMeta = metav1.TypeMeta{APIVersion: "image.openshift.io/v1", Kind: "ImageStream"}
is.CreationTimestamp = metav1.Time{Time: now}
is.Name = name
if is.Annotations == nil {
is.Annotations = make(map[string]string)
}
// update any custom mappings and then sort the spec tags
for _, m := range o.Mappings {
if exclude.Has(m.Source) {
klog.V(2).Infof("Excluded mapping %s", m.Source)
continue
}
tag := hasTag(is.Spec.Tags, m.Source)
if tag == nil {
is.Spec.Tags = append(is.Spec.Tags, imageapi.TagReference{
Name: m.Source,
})
tag = &is.Spec.Tags[len(is.Spec.Tags)-1]
} else {
// when we override the spec, we have to reset any annotations
tag.Annotations = nil
}
if tag.Annotations == nil {
tag.Annotations = make(map[string]string)
}
tag.Annotations[annotationReleaseOverride] = "true"
tag.From = &corev1.ObjectReference{
Name: m.Destination,
Kind: "DockerImage",
}
}
sort.Slice(is.Spec.Tags, func(i, j int) bool {
return is.Spec.Tags[i].Name < is.Spec.Tags[j].Name
})
if o.Output == "json" {
data, err := json.MarshalIndent(is, "", " ")
if err != nil {
return err
}
fmt.Fprintf(o.Out, "%s\n", string(data))
return nil
}
if len(o.FromDirectory) == 0 {
if err := o.extractManifests(is, name, metadata); err != nil {
return err
}
var filteredNames []string
for _, s := range ordered {
if _, ok := metadata[s]; ok {
filteredNames = append(filteredNames, s)
}
}
ordered = filteredNames
}
if len(o.Mirror) > 0 {
if err := o.mirrorImages(is); err != nil {
return err
}
}
var verifiers []PayloadVerifier
if !o.SkipManifestCheck {
verifiers = append(verifiers, func(filename string, data []byte) error {
for _, suffix := range []string{".json", ".yml", ".yaml"} {
if !strings.HasSuffix(filename, suffix) {
continue
}
var obj interface{}
if err := yaml.Unmarshal(data, &obj); err != nil {
// strip the slightly verbose prefix for the error message
msg := err.Error()
for _, s := range []string{"error converting YAML to JSON: ", "error unmarshaling JSON: ", "yaml: "} {
msg = strings.TrimPrefix(msg, s)
}
return fmt.Errorf("%s: invalid YAML/JSON: %s", filename, msg)
}
s := string(data)
if len(s) > 30 {
s = s[:30] + "..."
}
m, ok := obj.(map[string]interface{})
if !ok {
return fmt.Errorf("%s: not a valid YAML/JSON object, got: %s", filename, s)
}
if s, ok := m["kind"].(string); !ok || s == "" {
return fmt.Errorf("%s: manifests must contain Kubernetes API objects with 'kind' and 'apiVersion' set: %s", filename, s)
}
if s, ok := m["apiVersion"].(string); !ok || s == "" {
return fmt.Errorf("%s: manifests must contain Kubernetes API objects with 'kind' and 'apiVersion' set: %s", filename, s)
}
break
}
return nil
})
}
// any input image with content, referenced in AlwaysInclude, or referenced from image-references is
// included, which guarantees the content of a payload can be reproduced
forceInclude := append(append([]string{}, o.AlwaysInclude...), ordered...)
if err := pruneUnreferencedImageStreams(o.ErrOut, is, metadata, forceInclude); err != nil {
return err
}
// use a stable ordering for operators
sort.Strings(ordered)
var operators []string
pr, pw := io.Pipe()
go func() {
var err error
operators, err = writePayload(pw, is, cm, ordered, metadata, o.AllowMissingImages, verifiers)
pw.CloseWithError(err)
}()
br := bufio.NewReaderSize(pr, 500*1024)
if _, err := br.Peek(br.Size()); err != nil && err != io.EOF {
return fmt.Errorf("unable to create a release: %v", err)
}
if err := o.write(br, is, now); err != nil {
return err
}
sort.Strings(operators)
switch {
case operators == nil:
case len(operators) == 0:
fmt.Fprintf(o.ErrOut, "warning: No operator metadata was found, no operators will be part of the release.\n")
}
return nil
}
func resolveImageStreamTagsToReferenceMode(inputIS, is *imageapi.ImageStream, referenceMode string, exclude sets.String) error {
switch referenceMode {
case "public", "", "source":
forceExternal := referenceMode == "public" || referenceMode == ""
internal := inputIS.Status.DockerImageRepository
external := inputIS.Status.PublicDockerImageRepository
if forceExternal && len(external) == 0 {
return fmt.Errorf("only image streams or releases with public image repositories can be the source for releases when using the default --reference-mode")
}
externalFn := func(source, image string) string {
// filter source URLs
if len(source) > 0 && len(internal) > 0 && strings.HasPrefix(source, internal) {
klog.V(2).Infof("Can't use source %s because it points to the internal registry", source)
source = ""
}
// default to the external registry name
if (forceExternal || len(source) == 0) && len(external) > 0 {
return external + "@" + image
}
return source
}
covered := sets.NewString()
for _, ref := range inputIS.Spec.Tags {
if exclude.Has(ref.Name) {
klog.V(2).Infof("Excluded spec tag %s", ref.Name)
continue
}
if ref.From != nil && ref.From.Kind == "DockerImage" {
switch from, err := imagereference.Parse(ref.From.Name); {
case err != nil:
return err
case len(from.ID) > 0:
source := externalFn(ref.From.Name, from.ID)
if len(source) == 0 {
klog.V(2).Infof("Can't use spec tag %q because we cannot locate or calculate a source location", ref.Name)
continue
}
ref := ref.DeepCopy()
ref.From = &corev1.ObjectReference{Kind: "DockerImage", Name: source}
is.Spec.Tags = append(is.Spec.Tags, *ref)
covered.Insert(ref.Name)
case len(from.Tag) > 0:
tag := findStatusTagEvents(inputIS.Status.Tags, ref.Name)
if tag == nil {
continue
}
if len(tag.Items) == 0 {
for _, condition := range tag.Conditions {
if condition.Type == imageapi.ImportSuccess && condition.Status != metav1.StatusSuccess {
return fmt.Errorf("the tag %q in the source input stream has not been imported yet", tag.Tag)
}
}
continue
}
if ref.Generation != nil && *ref.Generation != tag.Items[0].Generation {
return fmt.Errorf("the tag %q in the source input stream has not been imported yet", tag.Tag)
}
if len(tag.Items[0].Image) == 0 {
return fmt.Errorf("the tag %q in the source input stream has no image id", tag.Tag)
}
source := externalFn(tag.Items[0].DockerImageReference, tag.Items[0].Image)
ref := ref.DeepCopy()
ref.From = &corev1.ObjectReference{Kind: "DockerImage", Name: source}
is.Spec.Tags = append(is.Spec.Tags, *ref)
covered.Insert(ref.Name)
}
continue
}
// TODO: support ImageStreamTag and ImageStreamImage
}
for _, tag := range inputIS.Status.Tags {
if covered.Has(tag.Tag) {
continue
}
if exclude.Has(tag.Tag) {
klog.V(2).Infof("Excluded status tag %s", tag.Tag)
continue
}
// error if we haven't imported anything to this tag, or skip otherwise
if len(tag.Items) == 0 {
for _, condition := range tag.Conditions {
if condition.Type == imageapi.ImportSuccess && condition.Status != metav1.StatusSuccess {
return fmt.Errorf("the tag %q in the source input stream has not been imported yet", tag.Tag)
}
}
continue
}
// skip rather than error (user created a reference spec tag, then deleted it)
if len(tag.Items[0].Image) == 0 {
klog.V(2).Infof("the tag %q in the source input stream has no image id", tag.Tag)
continue
}
// attempt to identify the source image
source := externalFn(tag.Items[0].DockerImageReference, tag.Items[0].Image)
if len(source) == 0 {
klog.V(2).Infof("Can't use tag %q because we cannot locate or calculate a source location", tag.Tag)
continue
}
sourceRef, err := imagereference.Parse(source)
if err != nil {
return fmt.Errorf("the tag %q points to source %q which is not valid", tag.Tag, source)
}
sourceRef.Tag = ""
sourceRef.ID = tag.Items[0].Image
source = sourceRef.Exact()
ref := &imageapi.TagReference{Name: tag.Tag}
ref.From = &corev1.ObjectReference{Kind: "DockerImage", Name: source}
is.Spec.Tags = append(is.Spec.Tags, *ref)
}
return nil
default:
return fmt.Errorf("supported reference modes are: \"public\" (default) and \"source\"")
}
}
func (o *NewOptions) extractManifests(is *imageapi.ImageStream, name string, metadata map[string]imageData) error {
if len(is.Spec.Tags) == 0 {
return fmt.Errorf("no component images defined, unable to build a release payload")
}
klog.V(4).Infof("Extracting manifests for release from input images")
dir := o.Directory
if len(dir) == 0 {
var err error
dir, err = ioutil.TempDir("", fmt.Sprintf("release-image-%s", name))
if err != nil {
return err
}
o.cleanupFns = append(o.cleanupFns, func() { os.RemoveAll(dir) })
klog.V(2).Infof("Manifests will be extracted to %s\n", dir)
}
verifier := imagemanifest.NewVerifier()
var lock sync.Mutex
opts := extract.NewOptions(genericclioptions.IOStreams{Out: o.Out, ErrOut: o.ErrOut})
opts.SecurityOptions = o.SecurityOptions
opts.OnlyFiles = true
opts.ParallelOptions = o.ParallelOptions
opts.ImageMetadataCallback = func(m *extract.Mapping, dgst, contentDigest digest.Digest, config *docker10.DockerImageConfig) {
verifier.Verify(dgst, contentDigest)
lock.Lock()
defer lock.Unlock()
metadata[m.Name] = imageData{
Directory: m.To,
Ref: m.ImageRef,
Config: config,
Digest: dgst,
ContentDigest: contentDigest,
}
}
for i := range is.Spec.Tags {
tag := &is.Spec.Tags[i]
dstDir := filepath.Join(dir, tag.Name)
if tag.From.Kind != "DockerImage" {
continue
}
src := tag.From.Name
ref, err := imagereference.Parse(src)
if err != nil {
return err
}
// when the user provides an override, look at all layers for manifests
// in case the user did a layered build and overrode only one. This is
// an unsupported release configuration
var custom bool
filter := extract.NewPositionLayerFilter(-1)
if tag.Annotations[annotationReleaseOverride] == "true" {
custom = true
filter = nil
}
opts.Mappings = append(opts.Mappings, extract.Mapping{
Name: tag.Name,
ImageRef: ref,
From: "manifests/",
To: dstDir,
LayerFilter: filter,
ConditionFn: func(m *extract.Mapping, dgst digest.Digest, imageConfig *docker10.DockerImageConfig) (bool, error) {
var labels map[string]string
if imageConfig.Config != nil {
labels = imageConfig.Config.Labels
}
if tag.Annotations == nil {
tag.Annotations = make(map[string]string)
}
tag.Annotations[annotationBuildSourceCommit] = labels[annotationBuildSourceCommit]
tag.Annotations[annotationBuildSourceRef] = labels[annotationBuildSourceRef]
tag.Annotations[annotationBuildSourceLocation] = labels[annotationBuildSourceLocation]
if versions := labels[annotationBuildVersions]; len(versions) > 0 {
components, err := parseComponentVersionsLabel(versions)
if err != nil {
return false, fmt.Errorf("tag %q has an invalid %s label: %v", tag.Name, annotationBuildVersions, err)
}
// TODO: eventually this can be relaxed
for component := range components {
if !stringArrContains(o.AllowedComponents, component) {
return false, fmt.Errorf("tag %q references a component version %q which is not in the allowed list", tag.Name, component)
}
}
tag.Annotations[annotationBuildVersions] = versions
}
if len(labels[annotationReleaseOperator]) == 0 {
klog.V(2).Infof("Image %s has no %s label, skipping", m.ImageRef, annotationReleaseOperator)
return false, nil
}
if err := os.MkdirAll(dstDir, 0777); err != nil {