-
Notifications
You must be signed in to change notification settings - Fork 377
/
extract_tools.go
1286 lines (1131 loc) · 42.2 KB
/
extract_tools.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"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"syscall"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/crypto/openpgp"
"k8s.io/klog/v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/cli-runtime/pkg/genericiooptions"
appsv1client "k8s.io/client-go/kubernetes/typed/apps/v1"
"k8s.io/client-go/rest"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
"github.com/MakeNowJust/heredoc"
configv1 "github.com/openshift/api/config/v1"
configv1client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1"
imagereference "github.com/openshift/library-go/pkg/image/reference"
"github.com/openshift/library-go/pkg/manifest"
"github.com/openshift/oc/pkg/cli/admin/internal/codesign"
"github.com/openshift/oc/pkg/cli/image/extract"
"github.com/openshift/oc/pkg/cli/image/imagesource"
"github.com/openshift/oc/pkg/version"
)
// extractTarget describes how a file in the release image can be extracted to disk.
type extractTarget struct {
OS string
Arch string
Command string
Optional bool
NewArch bool
InjectReleaseImage bool
InjectReleaseVersion bool
InjectReleaseArchitecture bool
SignMachOBinary bool
ArchiveFormat string
AsArchive bool
AsZip bool
Readme string
LinkTo []string
TargetCommandName string
Mapping extract.Mapping
}
// installConfig is a stub for loading what we need from install-configs without having to vendor all of github.com/openshift/installer/pkg/types.
type installConfig struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
Platform map[string]interface{} `json:"platform"`
Capabilities *configv1.ClusterVersionCapabilitiesSpec `json:"capabilities,omitempty"`
FeatureSet configv1.FeatureSet `json:"featureSet,omitempty"`
}
// manifestInclusionConfiguration configures manifest inclusion, so
// callers can opt in to new filtering options instead of having to
// update existing call-sites, even if they do not need a new
// filtering option.
type manifestInclusionConfiguration struct {
// ExcludeIdentifier, if non-nil, excludes manifests that match the exclusion identifier.
ExcludeIdentifier *string
// RequiredFeatureSet, if non-nil, excludes manifests unless they match the desired feature set.
RequiredFeatureSet *string
// Profile, if non-nil, excludes manifests unless they match the cluster profile.
Profile *string
// Capabilities, if non-nil, excludes manifests unless they match the enabled cluster capabilities.
Capabilities *configv1.ClusterVersionCapabilitiesStatus
// Overrides excludes manifests for overridden resources.
Overrides []configv1.ComponentOverride
// Platform, if non-nil, excludes CredentialsRequests manifests unless they match the infrastructure platform.
Platform *string
}
type includer func(m *manifest.Manifest) error
// extractTools extracts all referenced commands as archives in the target dir.
func (o *ExtractOptions) extractTools() error {
return o.extractCommand("")
}
var (
readmeInstallUnix = heredoc.Doc(`
# OpenShift Install
The OpenShift installer \u0060openshift-install\u0060 makes it easy to get a cluster
running on the public cloud or your local infrastructure.
To learn more about installing OpenShift, visit [docs.openshift.com](https://docs.openshift.com)
and select the version of OpenShift you are using.
## Installing the tools
After extracting this archive, you can move the \u0060openshift-install\u0060 binary
to a location on your PATH such as \u0060/usr/local/bin\u0060, or keep it in a temporary
directory and reference it via \u0060./openshift-install\u0060.
## License
OpenShift is licensed under the Apache Public License 2.0. The source code for this
program is [located on github](https://github.com/openshift/installer).
`)
readmeCLIUnix = heredoc.Doc(`
# OpenShift Clients
The OpenShift client \u0060oc\u0060 simplifies working with Kubernetes and OpenShift
clusters, offering a number of advantages over \u0060kubectl\u0060 such as easy login,
kube config file management, and access to developer tools. The \u0060kubectl\u0060
binary is included alongside for when strict Kubernetes compliance is necessary.
To learn more about OpenShift, visit [docs.openshift.com](https://docs.openshift.com)
and select the version of OpenShift you are using.
## Installing the tools
After extracting this archive, move the \u0060oc\u0060 and \u0060kubectl\u0060 binaries
to a location on your PATH such as \u0060/usr/local/bin\u0060. Then run:
oc login [API_URL]
to start a session against an OpenShift cluster. After login, run \u0060oc\u0060 and
\u0060oc help\u0060 to learn more about how to get started with OpenShift.
## License
OpenShift is licensed under the Apache Public License 2.0. The source code for this
program is [located on github](https://github.com/openshift/oc).
`)
readmeCLIWindows = heredoc.Doc(`
# OpenShift Clients
The OpenShift client \u0060oc.exe\u0060 simplifies working with Kubernetes and OpenShift
clusters, offering a number of advantages over \u0060kubectl.exe\u0060 such as easy login,
kube config file management, and access to developer tools.
To learn more about OpenShift, visit [docs.openshift.com](https://docs.openshift.com)
and select the version of OpenShift you are using.
## Installing the tools
After extracting this archive, move the \u0060oc.exe\u0060 binary to a location on your
PATH. Then run:
oc login [API_URL]
to start a session against an OpenShift cluster. After login, run \u0060oc.exe\u0060 and
\u0060oc.exe help\u0060 to learn more about how to get started with OpenShift.
If you would like to use \u0060kubectl.exe\u0060 instead, copy the \u0060oc.exe\u0060 file
and rename it to \u0060kubectl.exe\u0060. The interface will follow the conventions of that
CLI.
## License
OpenShift is licensed under the Apache Public License 2.0. The source code for this
program is [located on github](https://github.com/openshift/oc).
`)
readmeCCOUnix = heredoc.Doc(`
# Cloud Credential Operator utility
The ccoctl tool provides various commands to assist with the creating and maintenance of
cloud credentials from outside the cluster (necessary when CCO is put in "Manual" mode).
To learn more about OpenShift, visit [docs.openshift.com](https://docs.openshift.com)
and select the version of OpenShift you are using.
## Installing the tools
After extracting this archive, move the \u0060ccoctl\u0060 binary to a location on your
PATH such as \u0060/usr/local/bin\u0060, or keep it in a temporary directory and
reference it via \u0060./ccoctl\u0060.
## License
OpenShift is licensed under the Apache Public License 2.0. The source code for this
program is [located on github](https://github.com/openshift/cloud-credential-operator).
`)
// indicates that the architecture of the binary matches the release payload
targetReleaseArch = "release-arch"
)
// extractTools extracts specific commands out of images referenced by the release image.
// TODO: in the future the metadata this command contains might be loaded from the release
//
// image, but we must maintain compatibility with older payloads if so
func (o *ExtractOptions) extractCommand(command string) error {
// Available targets is treated as a GA API and may not be changed without backwards
// compatibility of at least N-2 releases.
availableTargets := []extractTarget{
{
OS: "darwin",
Arch: "amd64",
Command: "oc",
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/mac/oc"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-mac-%s.tar.gz",
},
{
OS: "darwin",
Arch: "arm64",
Command: "oc",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/mac_arm64/oc"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
SignMachOBinary: true,
ArchiveFormat: "openshift-client-mac-arm64-%s.tar.gz",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "oc",
Mapping: extract.Mapping{Image: "cli", From: "usr/bin/oc"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-%s.tar.gz",
},
{
OS: "linux",
Arch: "amd64",
Command: "oc",
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_amd64/oc"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-amd64-%s.tar.gz",
},
{
OS: "linux",
Arch: "amd64",
Command: "oc.rhel9",
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_amd64/oc.rhel9"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-amd64-rhel9-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "amd64",
Command: "oc.rhel8",
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_amd64/oc.rhel8"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-amd64-rhel8-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "arm64",
Command: "oc",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_arm64/oc"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-arm64-%s.tar.gz",
},
{
OS: "linux",
Arch: "arm64",
Command: "oc.rhel9",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_arm64/oc.rhel9"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-arm64-rhel9-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "arm64",
Command: "oc.rhel8",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_arm64/oc.rhel8"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-arm64-rhel8-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "ppc64le",
Command: "oc",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_ppc64le/oc"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-ppc64le-%s.tar.gz",
},
{
OS: "linux",
Arch: "ppc64le",
Command: "oc.rhel9",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_ppc64le/oc.rhel9"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-ppc64le-rhel9-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "ppc64le",
Command: "oc.rhel8",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_ppc64le/oc.rhel8"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-ppc64le-rhel8-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "s390x",
Command: "oc.rhel9",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_s390x/oc.rhel9"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-s390x-rhel9-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "linux",
Arch: "s390x",
Command: "oc.rhel8",
NewArch: true,
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/linux_s390x/oc.rhel8"},
LinkTo: []string{"kubectl"},
Readme: readmeCLIUnix,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-linux-s390x-rhel8-%s.tar.gz",
TargetCommandName: "oc",
},
{
OS: "windows",
Arch: "amd64",
Command: "oc",
Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/windows/oc.exe"},
Readme: readmeCLIWindows,
InjectReleaseVersion: true,
ArchiveFormat: "openshift-client-windows-%s.zip",
AsZip: true,
},
{
OS: "darwin",
Arch: "amd64",
Command: "openshift-install",
Mapping: extract.Mapping{Image: "installer-artifacts", From: "usr/share/openshift/mac/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
ArchiveFormat: "openshift-install-mac-%s.tar.gz",
},
{
OS: "darwin",
Arch: "arm64",
Command: "openshift-install",
NewArch: true,
Mapping: extract.Mapping{Image: "installer-artifacts", From: "usr/share/openshift/mac_arm64/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
SignMachOBinary: true,
ArchiveFormat: "openshift-install-mac-arm64-%s.tar.gz",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "openshift-install",
Mapping: extract.Mapping{Image: "installer", From: "usr/bin/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
ArchiveFormat: "openshift-install-linux-%s.tar.gz",
},
{
OS: "linux",
Arch: "amd64",
Command: "openshift-install",
NewArch: true,
Mapping: extract.Mapping{Image: "installer-artifacts", From: "usr/share/openshift/linux_amd64/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
ArchiveFormat: "openshift-install-linux-amd64-%s.tar.gz",
},
{
OS: "linux",
Arch: "arm64",
Command: "openshift-install",
NewArch: true,
Mapping: extract.Mapping{Image: "installer-artifacts", From: "usr/share/openshift/linux_arm64/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
ArchiveFormat: "openshift-install-linux-arm64-%s.tar.gz",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "openshift-baremetal-install",
Optional: true,
Mapping: extract.Mapping{Image: "baremetal-installer", From: "usr/bin/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
ArchiveFormat: "openshift-baremetal-install-linux-%s.tar.gz",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "openshift-install-fips",
Optional: true,
Mapping: extract.Mapping{Image: "baremetal-installer", From: "usr/bin/openshift-install"},
Readme: readmeInstallUnix,
InjectReleaseImage: true,
InjectReleaseVersion: true,
InjectReleaseArchitecture: true,
ArchiveFormat: "openshift-install-rhel-%s.tar.gz",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "ccoctl",
NewArch: true,
Mapping: extract.Mapping{Image: "cloud-credential-operator", From: "usr/bin/ccoctl"},
Readme: readmeCCOUnix,
ArchiveFormat: "ccoctl-linux-%s.tar.gz",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "ccoctl.rhel8",
NewArch: true,
Mapping: extract.Mapping{Image: "cloud-credential-operator", From: "usr/bin/ccoctl.rhel8"},
Readme: readmeCCOUnix,
ArchiveFormat: "ccoctl-linux-rhel8-%s.tar.gz",
TargetCommandName: "ccoctl",
},
{
OS: "linux",
Arch: targetReleaseArch,
Command: "ccoctl.rhel9",
NewArch: true,
Mapping: extract.Mapping{Image: "cloud-credential-operator", From: "usr/bin/ccoctl.rhel9"},
Readme: readmeCCOUnix,
ArchiveFormat: "ccoctl-linux-rhel9-%s.tar.gz",
TargetCommandName: "ccoctl",
},
}
currentArch := runtime.GOARCH
currentOS := runtime.GOOS
if len(o.CommandOperatingSystem) > 0 {
currentOS = o.CommandOperatingSystem
if currentOS == "*" {
currentArch = "*"
} else {
parsed := strings.Split(currentOS, "/")
switch len(parsed) {
case 1:
// --command-os=linux
currentArch = "amd64"
case 2:
// --command-os=linux/amd64
currentOS = parsed[0]
currentArch = parsed[1]
default:
return fmt.Errorf("invalid --command-os value")
}
}
}
if currentOS == "mac" {
currentOS = "darwin"
}
// Select the subset of targets based on command line input
var willArchive bool
var targets []extractTarget
// Filter by command, or gather all non-optional targets
if len(command) > 0 {
for _, target := range availableTargets {
if target.Command == command {
targets = append(targets, target)
}
}
} else {
for _, target := range availableTargets {
if !target.Optional {
targets = append(targets, target)
}
}
}
// If the user didn't specify a command, or the operating system is set
// to '*', we'll produce an archive
if len(command) == 0 || o.CommandOperatingSystem == "*" {
for i := range targets {
targets[i].AsArchive = true
targets[i].AsZip = targets[i].OS == "windows"
}
}
if len(targets) == 0 {
switch {
case len(command) > 0 && currentOS != "*":
return fmt.Errorf("command %q does not exist in targets or does not support the operating system %q", o.Command, currentOS)
case len(command) > 0:
return fmt.Errorf("the supported commands are 'oc', 'openshift-install', `openshift-baremetal-install` and 'ccoctl'")
default:
return fmt.Errorf("no available commands")
}
}
var hashFn = sha256.New
var signer *openpgp.Entity
if willArchive && len(o.SigningKey) > 0 {
key, err := os.ReadFile(o.SigningKey)
if err != nil {
return err
}
keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(key))
if err != nil {
return err
}
for _, key := range keyring {
if !key.PrivateKey.CanSign() {
continue
}
fmt.Fprintf(o.Out, "Enter password for private key: ")
password, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Fprintln(o.Out)
if err != nil {
return err
}
if err := key.PrivateKey.Decrypt(password); err != nil {
return fmt.Errorf("unable to decrypt signing key: %v", err)
}
for i, subkey := range key.Subkeys {
if err := subkey.PrivateKey.Decrypt(password); err != nil {
return fmt.Errorf("unable to decrypt signing subkey %d: %v", i, err)
}
}
signer = key
break
}
if signer == nil {
return fmt.Errorf("no private key exists in %s capable of signing the output", o.SigningKey)
}
}
// load the release image
dir := o.Directory
infoOptions := NewInfoOptions(o.IOStreams)
infoOptions.SecurityOptions = o.SecurityOptions
infoOptions.FilterOptions = o.FilterOptions
infoOptions.FileDir = o.FileDir
infoOptions.ICSPFile = o.ICSPFile
infoOptions.IDMSFile = o.IDMSFile
release, err := infoOptions.LoadReleaseInfo(o.From, false)
if err != nil {
return err
}
releaseArch := release.Config.Architecture
releaseName := release.PreferredName()
refExact := release.ImageRef
releaseArchitecture := release.Platform()
refExact.Ref.Tag = ""
// if the release image is manifestlist image, we'll not change digest with
// arch based sha. Because we want that the extracted tool can be used for all archs.
if len(release.ManifestListDigest) == 0 {
refExact.Ref.ID = release.Digest.String()
} else {
// if the image is manifestlisted, use the manifestlist digest.
refExact.Ref.ID = release.ManifestListDigest.String()
}
exactReleaseImage := refExact.String()
targetArchCommands := make(map[string]struct{})
// resolve target image references to their pull specs
missing := sets.NewString()
var validTargets []extractTarget
for _, target := range targets {
if currentOS != "*" && target.OS != currentOS {
klog.V(2).Infof("Skipping %s, does not match current OS %s", target.ArchiveFormat, target.OS)
continue
}
if currentArch != "*" && target.Arch != currentArch {
if currentArch != releaseArch || target.Arch != targetReleaseArch {
klog.V(2).Infof("Skipping %s, does not match current architecture %s", target.ArchiveFormat, target.Arch)
continue
}
}
if target.Arch == targetReleaseArch {
targetArchCommands[target.Command] = struct{}{}
}
if target.OS == "linux" && target.Arch == releaseArch {
if _, ok := targetArchCommands[target.Command]; ok {
// Some target commands have release-arch types that defines extracting
// the command in whatever release architecture type is set(e.g. linux/amd64)
// But there is also another target type for these commands specifically set to
// each architecture type(linux/amd64, linux/arm64) and it is expected that
// one of these arch types collide with release-arch type. Thus,
// to prevent duplicate extraction, we have to skip the one colliding with release-arch type.
// However, we need to skip per command name because some command may not have release-arch type.
klog.V(2).Infof("Skipping duplicate %s", target.ArchiveFormat)
continue
}
}
spec, err := findImageSpec(release.References, target.Mapping.Image, o.From)
if err != nil && !target.NewArch {
missing.Insert(target.Mapping.Image)
continue
}
klog.V(2).Infof("Will extract %s from %s", target.Mapping.From, spec)
ref, err := imagereference.Parse(spec)
if err != nil {
return err
}
target.Mapping.Image = spec
target.Mapping.ImageRef = imagesource.TypedImageReference{Ref: ref, Type: imagesource.DestinationRegistry}
// if the name of the extracted binary is set to different from the
// actual command name, we set it to new target command name.
if target.TargetCommandName != "" {
target.Command = target.TargetCommandName
}
if target.AsArchive {
willArchive = true
target.Mapping.Name = fmt.Sprintf(target.ArchiveFormat, releaseName)
target.Mapping.To = filepath.Join(dir, target.Mapping.Name)
} else {
target.Mapping.To = filepath.Join(dir, target.Command)
target.Mapping.Name = fmt.Sprintf("%s-%s-%s", target.OS, target.Arch, target.Command)
}
validTargets = append(validTargets, target)
}
if len(validTargets) == 0 {
if len(missing) == 1 {
return fmt.Errorf("the image %q containing the desired command is not available", missing.List()[0])
}
if len(missing) > 1 {
return fmt.Errorf("some required images are missing: %s", strings.Join(missing.List(), ", "))
}
return fmt.Errorf("the command '%s' is not available for %s/%s on %s", command, currentOS, currentArch, o.From)
}
if len(missing) > 0 {
fmt.Fprintf(o.ErrOut, "warning: Some commands can not be extracted due to missing images: %s\n", strings.Join(missing.List(), ", "))
}
// will extract in parallel
opts := extract.NewExtractOptions(genericiooptions.IOStreams{Out: o.Out, ErrOut: o.ErrOut})
opts.ParallelOptions = o.ParallelOptions
opts.SecurityOptions = o.SecurityOptions
opts.FilterOptions = o.FilterOptions
opts.ICSPFile = o.ICSPFile
opts.IDMSFile = o.IDMSFile
opts.OnlyFiles = true
// create the mapping lookup of the valid targets
var extractLock sync.Mutex
targetsByName := make(map[string]extractTarget)
for _, target := range validTargets {
targetsByName[target.Mapping.Name] = target
opts.Mappings = append(opts.Mappings, target.Mapping)
}
hashByTargetName := make(map[string]string)
// ensure to is a directory
if err := os.MkdirAll(dir, 0777); err != nil {
return err
}
// as each layer is extracted, take the output binary and write it to disk
opts.TarEntryCallback = func(hdr *tar.Header, layer extract.LayerInfo, r io.Reader) (bool, error) {
// ensure we don't process the same mapping twice due to programmer error
target, ok := func() (extractTarget, bool) {
extractLock.Lock()
defer extractLock.Unlock()
target, ok := targetsByName[layer.Mapping.Name]
return target, ok
}()
if !ok {
return false, fmt.Errorf("unable to find target with mapping name %s", layer.Mapping.Name)
}
// open the file
f, err := os.OpenFile(layer.Mapping.To, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
if err != nil {
return false, err
}
// if we need to write an archive, wrap the file appropriately to create a single
// entry
var w io.Writer = f
bw := bufio.NewWriterSize(w, 16*1024)
w = bw
var hash hash.Hash
closeFn := func() error { return nil }
if target.AsArchive {
text := strings.Replace(target.Readme, `\u0060`, "`", -1)
hash = hashFn()
w = io.MultiWriter(hash, w)
if target.AsZip {
klog.V(2).Infof("Writing %s as a ZIP archive %s", hdr.Name, layer.Mapping.To)
zw := zip.NewWriter(w)
if len(text) > 0 {
text = strings.Replace(text, "\n", "\r\n", -1)
zh := &zip.FileHeader{
Method: zip.Deflate,
Name: "README.md",
UncompressedSize64: uint64(len(text)),
Modified: hdr.ModTime,
}
zh.SetMode(os.FileMode(0755))
fw, err := zw.CreateHeader(zh)
if err != nil {
return false, err
}
if _, err := fmt.Fprintf(fw, text); err != nil {
return false, err
}
}
zh := &zip.FileHeader{
Method: zip.Deflate,
Name: target.Command + ".exe",
UncompressedSize64: uint64(hdr.Size),
Modified: hdr.ModTime,
}
zh.SetMode(os.FileMode(0755))
fw, err := zw.CreateHeader(zh)
if err != nil {
return false, err
}
w = fw
closeFn = func() error { return zw.Close() }
} else {
klog.V(2).Infof("Writing %s as a tar.gz archive %s", hdr.Name, layer.Mapping.To)
gw, err := gzip.NewWriterLevel(w, 3)
if err != nil {
return false, err
}
tw := tar.NewWriter(gw)
if len(text) > 0 {
if err := tw.WriteHeader(&tar.Header{
Name: "README.md",
Mode: int64(os.FileMode(0644).Perm()),
Size: int64(len(text)),
Typeflag: tar.TypeReg,
ModTime: hdr.ModTime,
}); err != nil {
return false, err
}
if _, err := fmt.Fprintf(tw, text); err != nil {
return false, err
}
}
if err := tw.WriteHeader(&tar.Header{
Name: target.Command,
Mode: int64(os.FileMode(0755).Perm()),
Size: hdr.Size,
Typeflag: tar.TypeReg,
ModTime: hdr.ModTime,
}); err != nil {
return false, err
}
w = tw
closeFn = func() error {
for _, link := range target.LinkTo {
if err := tw.WriteHeader(&tar.Header{
Name: link,
Mode: int64(os.FileMode(0755).Perm()),
Size: 0,
Typeflag: tar.TypeLink,
ModTime: hdr.ModTime,
Linkname: target.Command,
}); err != nil {
return err
}
}
if err := tw.Close(); err != nil {
return err
}
return gw.Close()
}
}
}
// copy the input to disk
replacements := []replacement{}
if target.InjectReleaseImage {
replacements = append(replacements, replacement{
name: "release image",
marker: append([]byte{0}, []byte(releaseImageMarker[1:])...),
value: exactReleaseImage,
})
}
if target.InjectReleaseVersion {
replacements = append(replacements, replacement{
name: "release version",
marker: append([]byte{0}, []byte(releaseVersionMarker[1:])...),
value: releaseName,
})
}
if target.InjectReleaseArchitecture {
replacements = append(replacements, replacement{
name: "release architecture",
marker: append([]byte{0}, []byte(releaseArchitectureMarker[1:])...),
value: releaseArchitecture,
})
}
err = copyAndReplace(o.ErrOut, w, r, 4*1024, replacements, target.Command)
if err != nil {
closeFn()
f.Close()
os.Remove(f.Name())
return false, err
}
// ensure the file is written to disk
if err := closeFn(); err != nil {
return false, err
}
if err := bw.Flush(); err != nil {
return false, err
}
if err := f.Close(); err != nil {
return false, err
}
if err := os.Chtimes(f.Name(), hdr.ModTime, hdr.ModTime); err != nil {
klog.V(2).Infof("Unable to set extracted file modification time: %v", err)
}
if (target.InjectReleaseVersion || target.InjectReleaseImage || target.InjectReleaseArchitecture) && target.SignMachOBinary {
if err = codesign.ResignMacho(layer.Mapping.To, target.AsArchive, target.Command, target.LinkTo); err != nil {
klog.Infof("Unable to resign macho binaries: %v", err)
} else {
if target.AsArchive {
// Since we rewrite tarball after signing mach-o files in darwin/arm64,
// we should reflect the modified hash sum of this tarball to prevent mismatches.
h := hashFn()
archived, err := os.Open(layer.Mapping.To)
if err != nil {
return false, err
}
if _, err = io.Copy(h, archived); err != nil {
archived.Close()
return false, err
}
hash = h
archived.Close()
}
}
}
func() {
extractLock.Lock()
defer extractLock.Unlock()
delete(targetsByName, layer.Mapping.Name)
if hash != nil {
hashByTargetName[layer.Mapping.To] = hex.EncodeToString(hash.Sum(nil))
}
}()
return false, nil
}
if err := opts.Run(); err != nil {
return err
}
if willArchive {
buf := &bytes.Buffer{}
fmt.Fprintf(buf, heredoc.Doc(`
Client tools for OpenShift
--------------------------
These archives contain the client tooling for [OpenShift](https://docs.openshift.com).
To verify the contents of this directory, use the 'gpg' and 'shasum' tools to
ensure the archives you have downloaded match those published from this location.
The openshift-install binary has been preconfigured to install the following release:
---
`))
if err := describeReleaseInfo(buf, release, false, false, true, false); err != nil {
return err
}
filename := "release.txt"
if err := os.WriteFile(filepath.Join(dir, filename), buf.Bytes(), 0644); err != nil {
return err
}
hash := hashFn()
hash.Write(buf.Bytes())
hashByTargetName[filename] = hex.EncodeToString(hash.Sum(nil))
}
// write a checksum of the tar files to disk as sha256sum.txt.asc
if len(hashByTargetName) > 0 {
var keys []string
for k := range hashByTargetName {
keys = append(keys, k)
}
sort.Strings(keys)
var lines []string