-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathmaster.go
More file actions
1080 lines (964 loc) · 38.9 KB
/
Copy pathmaster.go
File metadata and controls
1080 lines (964 loc) · 38.9 KB
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 machines
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"net"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
baremetalhost "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
ipamv1 "sigs.k8s.io/cluster-api/api/ipam/v1beta1" //nolint:staticcheck //CORS-3563
"sigs.k8s.io/yaml"
configv1 "github.com/openshift/api/config/v1"
"github.com/openshift/api/features"
machinev1 "github.com/openshift/api/machine/v1"
machinev1alpha1 "github.com/openshift/api/machine/v1alpha1"
machinev1beta1 "github.com/openshift/api/machine/v1beta1"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
baremetalapi "github.com/openshift/cluster-api-provider-baremetal/pkg/apis"
baremetalprovider "github.com/openshift/cluster-api-provider-baremetal/pkg/apis/baremetal/v1alpha1"
libvirtapi "github.com/openshift/cluster-api-provider-libvirt/pkg/apis"
libvirtprovider "github.com/openshift/cluster-api-provider-libvirt/pkg/apis/libvirtproviderconfig/v1beta1"
ovirtproviderapi "github.com/openshift/cluster-api-provider-ovirt/pkg/apis"
ovirtprovider "github.com/openshift/cluster-api-provider-ovirt/pkg/apis/ovirtprovider/v1beta1"
"github.com/openshift/installer/pkg/asset"
"github.com/openshift/installer/pkg/asset/ignition/machine"
"github.com/openshift/installer/pkg/asset/installconfig"
"github.com/openshift/installer/pkg/asset/machines/aws"
"github.com/openshift/installer/pkg/asset/machines/azure"
"github.com/openshift/installer/pkg/asset/machines/baremetal"
"github.com/openshift/installer/pkg/asset/machines/gcp"
"github.com/openshift/installer/pkg/asset/machines/ibmcloud"
"github.com/openshift/installer/pkg/asset/machines/machineconfig"
"github.com/openshift/installer/pkg/asset/machines/nutanix"
"github.com/openshift/installer/pkg/asset/machines/openstack"
"github.com/openshift/installer/pkg/asset/machines/ovirt"
"github.com/openshift/installer/pkg/asset/machines/powervs"
"github.com/openshift/installer/pkg/asset/machines/vsphere"
"github.com/openshift/installer/pkg/asset/manifests/capiutils"
"github.com/openshift/installer/pkg/asset/rhcos"
rhcosutils "github.com/openshift/installer/pkg/rhcos"
"github.com/openshift/installer/pkg/types"
awstypes "github.com/openshift/installer/pkg/types/aws"
awsdefaults "github.com/openshift/installer/pkg/types/aws/defaults"
azuretypes "github.com/openshift/installer/pkg/types/azure"
azuredefaults "github.com/openshift/installer/pkg/types/azure/defaults"
baremetaltypes "github.com/openshift/installer/pkg/types/baremetal"
externaltypes "github.com/openshift/installer/pkg/types/external"
gcptypes "github.com/openshift/installer/pkg/types/gcp"
ibmcloudtypes "github.com/openshift/installer/pkg/types/ibmcloud"
nonetypes "github.com/openshift/installer/pkg/types/none"
nutanixtypes "github.com/openshift/installer/pkg/types/nutanix"
openstacktypes "github.com/openshift/installer/pkg/types/openstack"
ovirttypes "github.com/openshift/installer/pkg/types/ovirt"
powervctypes "github.com/openshift/installer/pkg/types/powervc"
powervstypes "github.com/openshift/installer/pkg/types/powervs"
powervsdefaults "github.com/openshift/installer/pkg/types/powervs/defaults"
vspheretypes "github.com/openshift/installer/pkg/types/vsphere"
ibmcloudapi "github.com/openshift/machine-api-provider-ibmcloud/pkg/apis"
ibmcloudprovider "github.com/openshift/machine-api-provider-ibmcloud/pkg/apis/ibmcloudprovider/v1"
)
// Master generates the machines for the `master` machine pool.
type Master struct {
UserDataFile *asset.File
MachineConfigFiles []*asset.File
MachineFiles []*asset.File
ControlPlaneMachineSet *asset.File
IPClaimFiles []*asset.File
IPAddrFiles []*asset.File
// SecretFiles is used by the baremetal platform to register the
// credential information for communicating with management
// controllers on hosts.
SecretFiles []*asset.File
// NetworkConfigSecretFiles is used by the baremetal platform to
// store the networking configuration per host
NetworkConfigSecretFiles []*asset.File
// HostFiles is the list of baremetal hosts provided in the
// installer configuration.
HostFiles []*asset.File
// FencingCredentialsSecretFiles is a collection of secrets
// that will be used to fence machines to enable safe recovery
// in Two Node OpenShift with Fencing (TNF) deployments
FencingCredentialsSecretFiles []*asset.File
}
const (
directory = "openshift"
// secretFileName is the format string for constructing the Secret
// filenames for baremetal clusters.
secretFileName = "99_openshift-cluster-api_host-bmc-secrets-%s.yaml"
// networkConfigSecretFileName is the format string for constructing
// the networking configuration Secret filenames for baremetal
// clusters.
networkConfigSecretFileName = "99_openshift-cluster-api_host-network-config-secrets-%s.yaml"
// hostFileName is the format string for constucting the Host
// filenames for baremetal clusters.
hostFileName = "99_openshift-cluster-api_hosts-%s.yaml"
// masterMachineFileName is the format string for constucting the
// master Machine filenames.
masterMachineFileName = "99_openshift-cluster-api_master-machines-%s.yaml"
// masterUserDataFileName is the filename used for the master
// user-data secret.
masterUserDataFileName = "99_openshift-cluster-api_master-user-data-secret.yaml"
// controlPlaneMachineSetFileName is the filename used for the control plane machine sets.
controlPlaneMachineSetFileName = "99_openshift-machine-api_master-control-plane-machine-set.yaml"
// ipClaimFileName is the filename used for the ip claims list.
ipClaimFileName = "99_openshift-machine-api_claim-%s.yaml"
// ipAddressFileName is the filename used for the ip addresses list.
ipAddressFileName = "99_openshift-machine-api_address-%s.yaml"
// fencingCredentialsSecretFileName is the format string for constructing the
// secret filenames for Two Node OpenShift with Fencing (TNF) clusters.
fencingCredentialsSecretFileName = "99_openshift-etcd_fencing-credentials-secrets-%s.yaml" // #nosec G101
)
var (
secretFileNamePattern = fmt.Sprintf(secretFileName, "*")
networkConfigSecretFileNamePattern = fmt.Sprintf(networkConfigSecretFileName, "*")
hostFileNamePattern = fmt.Sprintf(hostFileName, "*")
masterMachineFileNamePattern = fmt.Sprintf(masterMachineFileName, "*")
masterIPClaimFileNamePattern = fmt.Sprintf(ipClaimFileName, "*master*")
masterIPAddressFileNamePattern = fmt.Sprintf(ipAddressFileName, "*master*")
fencingCredentialsFilenamePattern = fmt.Sprintf(fencingCredentialsSecretFileName, "*")
_ asset.WritableAsset = (*Master)(nil)
)
// Name returns a human friendly name for the Master Asset.
func (m *Master) Name() string {
return "Master Machines"
}
// Dependencies returns all of the dependencies directly needed by the
// Master asset
func (m *Master) Dependencies() []asset.Asset {
return []asset.Asset{
&installconfig.ClusterID{},
// PlatformCredsCheck just checks the creds (and asks, if needed)
// We do not actually use it in this asset directly, hence
// it is put in the dependencies but not fetched in Generate
&installconfig.PlatformCredsCheck{},
&installconfig.InstallConfig{},
new(rhcos.Image),
&machine.Master{},
}
}
// Generate generates the Master asset.
//
//nolint:gocyclo
func (m *Master) Generate(ctx context.Context, dependencies asset.Parents) error {
clusterID := &installconfig.ClusterID{}
installConfig := &installconfig.InstallConfig{}
rhcosImage := new(rhcos.Image)
mign := &machine.Master{}
dependencies.Get(clusterID, installConfig, rhcosImage, mign)
masterUserDataSecretName := "master-user-data"
ic := installConfig.Config
pool := *ic.ControlPlane
var err error
machines := []machinev1beta1.Machine{}
var ipClaims []ipamv1.IPAddressClaim
var ipAddrs []ipamv1.IPAddress
var controlPlaneMachineSet *machinev1.ControlPlaneMachineSet
// Check if SNO topology is supported on this platform
if pool.Replicas != nil && *pool.Replicas == 1 {
bootstrapInPlace := false
if ic.BootstrapInPlace != nil && ic.BootstrapInPlace.InstallationDisk != "" {
bootstrapInPlace = true
}
if !supportedSingleNodePlatform(bootstrapInPlace, ic.Platform.Name()) {
return fmt.Errorf("this install method does not support Single Node installation on platform %s", ic.Platform.Name())
}
}
switch ic.Platform.Name() {
case awstypes.Name:
subnets, err := aws.MachineSubnetsByZones(ctx, installConfig, awstypes.ClusterNodeSubnetRole)
if err != nil {
return err
}
mpool := defaultAWSMachinePoolPlatform("master")
osImage := strings.SplitN(rhcosImage.ControlPlane, ",", 2)
osImageID := osImage[0]
if len(osImage) == 2 {
osImageID = "" // the AMI will be generated later on
}
mpool.AMIID = osImageID
mpool.Set(ic.Platform.AWS.DefaultMachinePlatform)
mpool.Set(pool.Platform.AWS)
zoneDefaults := false
if len(mpool.Zones) == 0 {
if len(subnets) > 0 {
for zone := range subnets {
mpool.Zones = append(mpool.Zones, zone)
}
// Since zones are extracted from map keys, order is not guaranteed.
// Thus, sort the zones by lexical order to ensure CAPI and MAPI machines
// are distributed to zones in the same order.
slices.Sort(mpool.Zones)
} else {
mpool.Zones, err = installConfig.AWS.AvailabilityZones(ctx)
if err != nil {
return err
}
zoneDefaults = true
}
}
if mpool.InstanceType == "" {
topology := configv1.HighlyAvailableTopologyMode
if pool.Replicas != nil && *pool.Replicas == 1 {
topology = configv1.SingleReplicaTopologyMode
}
mpool.InstanceType, err = aws.PreferredInstanceType(ctx, installConfig.AWS, awsdefaults.InstanceTypes(installConfig.Config.Platform.AWS.Region, installConfig.Config.ControlPlane.Architecture, topology), mpool.Zones)
if err != nil {
logrus.Warn(errors.Wrap(err, "failed to find default instance type"))
mpool.InstanceType = awsdefaults.InstanceTypes(installConfig.Config.Platform.AWS.Region, installConfig.Config.ControlPlane.Architecture, topology)[0]
}
}
// if the list of zones is the default we need to try to filter the list in case there are some zones where the instance might not be available
if zoneDefaults {
mpool.Zones, err = aws.FilterZonesBasedOnInstanceType(ctx, installConfig.AWS, mpool.InstanceType, mpool.Zones)
if err != nil {
logrus.Warn(errors.Wrap(err, "failed to filter zone list"))
}
// Sort the zones by lexical order to ensure CAPI and MAPI machines
// are distributed to zones in the same order.
slices.Sort(mpool.Zones)
}
pool.Platform.AWS = &mpool
machines, controlPlaneMachineSet, err = aws.Machines(
clusterID.InfraID,
installConfig.Config.Platform.AWS.Region,
subnets,
&pool,
"master",
masterUserDataSecretName,
installConfig.Config.Platform.AWS.UserTags,
awstypes.IsPublicOnlySubnetsEnabled(),
installConfig.Config,
)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
aws.ConfigMasters(machines, controlPlaneMachineSet, clusterID.InfraID, ic.Publish)
case gcptypes.Name:
mpool := defaultGCPMachinePoolPlatform(pool.Architecture, ic.Platform.GCP.ProjectID)
mpool.Set(ic.Platform.GCP.DefaultMachinePlatform)
mpool.Set(pool.Platform.GCP)
if len(mpool.Zones) == 0 {
azs, err := gcp.ZonesForInstanceType(ic.Platform.GCP.ProjectID, ic.Platform.GCP.Region, mpool.InstanceType, ic.Platform.GCP.Endpoint)
if err != nil {
return errors.Wrap(err, "failed to fetch availability zones")
}
mpool.Zones = azs
}
pool.Platform.GCP = &mpool
controlPlaneImage := rhcosImage.ControlPlane
if gcptypes.NeedsRHCOSUpload(ic.Platform.GCP.ProjectID, &mpool) {
controlPlaneImage = gcptypes.RHCOSImageRef(ic.Platform.GCP.ProjectID, clusterID.InfraID)
}
machines, controlPlaneMachineSet, err = gcp.Machines(clusterID.InfraID, ic, &pool, controlPlaneImage, "master", masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
err := gcp.ConfigMasters(machines, controlPlaneMachineSet, clusterID.InfraID, ic.Publish)
if err != nil {
return err
}
// CAPG-based installs will use only backend services--no target pools,
// so we don't want to include target pools in the control plane machineset.
// TODO(padillon): once this feature gate is the default and we are
// no longer using Terraform, we can update ConfigMasters not to populate this.
if capiutils.IsEnabled(installConfig) {
for _, machine := range machines {
providerSpec, ok := machine.Spec.ProviderSpec.Value.Object.(*machinev1beta1.GCPMachineProviderSpec)
if !ok {
return errors.New("unable to convert ProviderSpec to GCPMachineProviderSpec")
}
providerSpec.TargetPools = nil
}
cpms := controlPlaneMachineSet.Spec.Template.OpenShiftMachineV1Beta1Machine.Spec.ProviderSpec.Value.Object
providerSpec, ok := cpms.(*machinev1beta1.GCPMachineProviderSpec)
if !ok {
return errors.New("Unable to set target pools to control plane machine set")
}
providerSpec.TargetPools = nil
}
case ibmcloudtypes.Name:
subnets := map[string]string{}
if len(ic.Platform.IBMCloud.ControlPlaneSubnets) > 0 {
subnetMetas, err := installConfig.IBMCloud.ControlPlaneSubnets(ctx)
if err != nil {
return err
}
for _, subnet := range subnetMetas {
subnets[subnet.Zone] = subnet.Name
}
}
mpool := defaultIBMCloudMachinePoolPlatform()
mpool.Set(ic.Platform.IBMCloud.DefaultMachinePlatform)
mpool.Set(pool.Platform.IBMCloud)
if len(mpool.Zones) == 0 {
azs, err := ibmcloud.AvailabilityZones(ic.Platform.IBMCloud.Region, ic.Platform.IBMCloud.ServiceEndpoints)
if err != nil {
return errors.Wrap(err, "failed to fetch availability zones")
}
mpool.Zones = azs
}
pool.Platform.IBMCloud = &mpool
machines, err = ibmcloud.Machines(clusterID.InfraID, ic, subnets, &pool, "master", masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
// TODO: IBM: implement ConfigMasters() if needed
// ibmcloud.ConfigMasters(machines, clusterID.InfraID, ic.Publish)
case openstacktypes.Name, powervctypes.Name:
mpool := defaultOpenStackMachinePoolPlatform()
mpool.Set(ic.Platform.OpenStack.DefaultMachinePlatform)
mpool.Set(pool.Platform.OpenStack)
pool.Platform.OpenStack = &mpool
imageName, _ := rhcosutils.GenerateOpenStackImageName(rhcosImage.ControlPlane, clusterID.InfraID)
machines, controlPlaneMachineSet, err = openstack.Machines(ctx, clusterID.InfraID, ic, &pool, imageName, "master", masterUserDataSecretName)
if err != nil {
return fmt.Errorf("failed to create master machine objects: %w", err)
}
openstack.ConfigMasters(machines, clusterID.InfraID)
case azuretypes.Name:
mpool := defaultAzureMachinePoolPlatform(installConfig.Config.Platform.Azure.CloudName)
mpool.InstanceType = azuredefaults.ControlPlaneInstanceType(
installConfig.Config.Platform.Azure.CloudName,
installConfig.Config.Platform.Azure.Region,
installConfig.Config.ControlPlane.Architecture,
)
mpool.OSDisk.DiskSizeGB = 1024
if installConfig.Config.Platform.Azure.CloudName == azuretypes.StackCloud {
mpool.OSDisk.DiskSizeGB = azuredefaults.AzurestackMinimumDiskSize
}
mpool.Set(ic.Platform.Azure.DefaultMachinePlatform)
mpool.Set(pool.Platform.Azure)
client, err := installConfig.Azure.Client()
if err != nil {
return err
}
if len(mpool.Zones) == 0 {
azs, err := installConfig.Azure.VMAvailabilityZones(ctx, mpool.InstanceType)
if err != nil {
return errors.Wrap(err, "failed to fetch availability zones")
}
mpool.Zones = azs
if len(azs) == 0 {
// if no azs are given we set to []string{""} for convenience over later operations.
// It means no-zoned for the machine API
mpool.Zones = []string{""}
}
}
if mpool.OSImage.Publisher != "" {
img, ierr := client.GetMarketplaceImage(ctx, ic.Platform.Azure.Region, mpool.OSImage.Publisher, mpool.OSImage.Offer, mpool.OSImage.SKU, mpool.OSImage.Version)
if ierr != nil {
return fmt.Errorf("failed to fetch marketplace image: %w", ierr)
}
// Publisher is case-sensitive and matched against exactly. Also the
// Plan's publisher might not be exactly the same as the Image's
// publisher
if img.Plan != nil && img.Plan.Publisher != nil {
mpool.OSImage.Publisher = *img.Plan.Publisher
}
}
pool.Platform.Azure = &mpool
capabilities, err := installConfig.Azure.ControlPlaneCapabilities()
if err != nil {
return err
}
session, err := installConfig.Azure.Session()
if err != nil {
return err
}
machines, controlPlaneMachineSet, err = azure.Machines(clusterID.InfraID, ic, &pool, rhcosImage.ControlPlane, "master", masterUserDataSecretName, capabilities, session)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
err = azure.ConfigMasters(machines, controlPlaneMachineSet, clusterID.InfraID)
if err != nil {
return err
}
case baremetaltypes.Name:
mpool := defaultBareMetalMachinePoolPlatform()
mpool.Set(ic.Platform.BareMetal.DefaultMachinePlatform)
mpool.Set(pool.Platform.BareMetal)
pool.Platform.BareMetal = &mpool
// Use managed user data secret, since we always have up to date images
// available in the cluster
masterUserDataSecretName = "master-user-data-managed"
enabledCaps := installConfig.Config.GetEnabledCapabilities()
if !enabledCaps.Has(configv1.ClusterVersionCapabilityMachineAPI) {
break
}
machines, err = baremetal.Machines(clusterID.InfraID, ic, &pool, "master", masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
hostSettings, err := baremetal.Hosts(ic, machines, masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to assemble host data")
}
hosts, err := createHostAssetFiles(hostSettings.Hosts, hostFileName)
if err != nil {
return err
}
m.HostFiles = append(m.HostFiles, hosts...)
secrets, err := createSecretAssetFiles(hostSettings.Secrets, secretFileName)
if err != nil {
return err
}
m.SecretFiles = append(m.SecretFiles, secrets...)
networkSecrets, err := createSecretAssetFiles(hostSettings.NetworkConfigSecrets, networkConfigSecretFileName)
if err != nil {
return err
}
m.NetworkConfigSecretFiles = append(m.NetworkConfigSecretFiles, networkSecrets...)
case ovirttypes.Name:
mpool := defaultOvirtMachinePoolPlatform()
mpool.VMType = ovirttypes.VMTypeHighPerformance
mpool.Set(ic.Platform.Ovirt.DefaultMachinePlatform)
mpool.Set(pool.Platform.Ovirt)
pool.Platform.Ovirt = &mpool
imageName, _ := rhcosutils.GenerateOpenStackImageName(rhcosImage.ControlPlane, clusterID.InfraID)
machines, err = ovirt.Machines(clusterID.InfraID, ic, &pool, imageName, "master", masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects for ovirt provider")
}
case vspheretypes.Name:
mpool := defaultVSphereMachinePoolPlatform()
mpool.NumCPUs = 4
mpool.NumCoresPerSocket = 4
mpool.MemoryMiB = 16384
mpool.Set(ic.Platform.VSphere.DefaultMachinePlatform)
mpool.Set(pool.Platform.VSphere)
// The machinepool has no zones defined, there are FailureDomains
// This is a vSphere zonal installation. Generate machinepool zone
// list.
fdCount := int64(len(ic.Platform.VSphere.FailureDomains))
var idx int64
if len(mpool.Zones) == 0 && len(ic.VSphere.FailureDomains) != 0 {
for i := int64(0); i < *(ic.ControlPlane.Replicas); i++ {
idx = i
if idx >= fdCount {
idx = i % fdCount
}
mpool.Zones = append(mpool.Zones, ic.VSphere.FailureDomains[idx].Name)
}
}
pool.Platform.VSphere = &mpool
data, err := vsphere.Machines(clusterID.InfraID, ic, &pool, "master", masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
machines = data.Machines
controlPlaneMachineSet = data.ControlPlaneMachineSet
ipClaims = data.IPClaims
ipAddrs = data.IPAddresses
vsphere.ConfigMasters(machines, clusterID.InfraID)
case powervstypes.Name:
mpool := defaultPowerVSMachinePoolPlatform(ic)
mpool.Set(ic.Platform.PowerVS.DefaultMachinePlatform)
mpool.Set(pool.Platform.PowerVS)
// Only the service instance is guaranteed to exist and be passed via the install config
// The other two, we should standardize a name including the cluster id. At this point, all
// we have are names.
pool.Platform.PowerVS = &mpool
machines, controlPlaneMachineSet, err = powervs.Machines(clusterID.InfraID, ic, &pool, "master", "master-user-data")
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
if err := powervs.ConfigMasters(machines, controlPlaneMachineSet, clusterID.InfraID, ic.Publish); err != nil {
return errors.Wrap(err, "failed to to configure master machine objects")
}
case externaltypes.Name, nonetypes.Name:
case nutanixtypes.Name:
mpool := defaultNutanixMachinePoolPlatform()
mpool.NumCPUs = 8
mpool.Set(ic.Platform.Nutanix.DefaultMachinePlatform)
mpool.Set(pool.Platform.Nutanix)
if err = mpool.ValidateConfig(ic.Platform.Nutanix, "master"); err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
pool.Platform.Nutanix = &mpool
templateName := nutanixtypes.RHCOSImageName(ic.Platform.Nutanix, clusterID.InfraID)
machines, controlPlaneMachineSet, err = nutanix.Machines(clusterID.InfraID, ic, &pool, templateName, "master", masterUserDataSecretName)
if err != nil {
return errors.Wrap(err, "failed to create master machine objects")
}
nutanix.ConfigMasters(machines, clusterID.InfraID)
default:
return fmt.Errorf("invalid Platform")
}
data, err := UserDataSecret(masterUserDataSecretName, mign.File.Data)
if err != nil {
return errors.Wrap(err, "failed to create user-data secret for master machines")
}
m.UserDataFile = &asset.File{
Filename: filepath.Join(directory, masterUserDataFileName),
Data: data,
}
machineConfigs := []*mcfgv1.MachineConfig{}
if pool.Hyperthreading == types.HyperthreadingDisabled {
ignHT, err := machineconfig.ForHyperthreadingDisabled("master")
if err != nil {
return errors.Wrap(err, "failed to create ignition for hyperthreading disabled for master machines")
}
machineConfigs = append(machineConfigs, ignHT)
}
if ic.SSHKey != "" {
ignSSH, err := machineconfig.ForAuthorizedKeys(ic.SSHKey, "master")
if err != nil {
return errors.Wrap(err, "failed to create ignition for authorized SSH keys for master machines")
}
machineConfigs = append(machineConfigs, ignSSH)
}
if ic.FIPS {
ignFIPS, err := machineconfig.ForFIPSEnabled("master")
if err != nil {
return errors.Wrap(err, "failed to create ignition for FIPS enabled for master machines")
}
machineConfigs = append(machineConfigs, ignFIPS)
}
if ic.Platform.Name() == powervstypes.Name {
// always enable multipath for powervs.
ignMultipath, err := machineconfig.ForMultipathEnabled("master")
if err != nil {
return errors.Wrap(err, "failed to create ignition for Multipath enabled for master machines")
}
machineConfigs = append(machineConfigs, ignMultipath)
// set SMT level if specified for powervs.
if pool.Platform.PowerVS.SMTLevel != "" {
ignPowerSMT, err := machineconfig.ForPowerSMT("master", pool.Platform.PowerVS.SMTLevel)
if err != nil {
return errors.Wrap(err, "failed to create ignition for Power SMT for master machines")
}
machineConfigs = append(machineConfigs, ignPowerSMT)
}
if installConfig.Config.Publish == types.InternalPublishingStrategy &&
(len(installConfig.Config.ImageDigestSources) > 0 || len(installConfig.Config.DeprecatedImageContentSources) > 0) {
ignChrony, err := machineconfig.ForCustomNTP("master", powervsdefaults.DefaultNTPServer)
if err != nil {
return errors.Wrap(err, "failed to create ignition for custom NTP for master machines")
}
machineConfigs = append(machineConfigs, ignChrony)
ignRoutes, err := machineconfig.ForExtraRoutes("master", powervsdefaults.DefaultExtraRoutes(), ic.MachineNetwork[0].CIDR.String())
if err != nil {
return errors.Wrap(err, "failed to create ignition for extra routes for master machines")
}
machineConfigs = append(machineConfigs, ignRoutes)
}
}
// The maximum number of networks supported on ServiceNetwork is two, one IPv4 and one IPv6 network.
// The cluster-network-operator handles the validation of this field.
// Reference: https://github.com/openshift/cluster-network-operator/blob/fc3e0e25b4cfa43e14122bdcdd6d7f2585017d75/pkg/network/cluster_config.go#L45-L52
if ic.Networking != nil && len(ic.Networking.ServiceNetwork) == 2 {
// Only configure kernel args for dual-stack clusters.
ignIPv6, err := machineconfig.ForDualStackAddresses("master")
if err != nil {
return errors.Wrap(err, "failed to create ignition to configure IPv6 for master machines")
}
machineConfigs = append(machineConfigs, ignIPv6)
}
if installConfig.Config.Enabled(features.FeatureGateMultiDiskSetup) {
for i, diskSetup := range installConfig.Config.ControlPlane.DiskSetup {
var dataDisk any
var diskName string
switch diskSetup.Type {
case types.Etcd:
diskName = diskSetup.Etcd.PlatformDiskID
case types.Swap:
diskName = diskSetup.Etcd.PlatformDiskID
case types.UserDefined:
diskName = diskSetup.UserDefined.PlatformDiskID
default:
// We shouldn't get here, but just in case
return errors.Errorf("disk setup type %s is not supported", diskSetup.Type)
}
switch ic.Platform.Name() {
case azuretypes.Name:
azureControlPlaneMachinePool := ic.ControlPlane.Platform.Azure
if i < len(azureControlPlaneMachinePool.DataDisks) {
dataDisk = azureControlPlaneMachinePool.DataDisks[i]
}
case vspheretypes.Name:
vsphereControlPlaneMachinePool := ic.ControlPlane.Platform.VSphere
for index, disk := range vsphereControlPlaneMachinePool.DataDisks {
if disk.Name == diskName {
dataDisk = vsphere.DiskInfo{
Index: index,
Disk: disk,
}
break
}
}
default:
return errors.Errorf("disk setup for %s is not supported", ic.Platform.Name())
}
if dataDisk != nil {
diskSetupIgn, err := NodeDiskSetup(installConfig, "master", diskSetup, dataDisk)
if err != nil {
return errors.Wrap(err, "failed to create ignition to setup disks for control plane")
}
machineConfigs = append(machineConfigs, diskSetupIgn)
}
}
}
m.MachineConfigFiles, err = machineconfig.Manifests(machineConfigs, "master", directory)
if err != nil {
return errors.Wrap(err, "failed to create MachineConfig manifests for master machines")
}
m.MachineFiles = make([]*asset.File, len(machines))
if controlPlaneMachineSet != nil && *pool.Replicas > 1 {
data, err := yaml.Marshal(controlPlaneMachineSet)
if err != nil {
return errors.Wrapf(err, "marshal control plane machine set")
}
m.ControlPlaneMachineSet = &asset.File{
Filename: filepath.Join(directory, controlPlaneMachineSetFileName),
Data: data,
}
}
m.IPClaimFiles = make([]*asset.File, len(ipClaims))
for i, claim := range ipClaims {
data, err := yaml.Marshal(claim)
if err != nil {
return errors.Wrapf(err, "unable to marshal ip claim %v", claim.Name)
}
m.IPClaimFiles[i] = &asset.File{
Filename: filepath.Join(directory, fmt.Sprintf(ipClaimFileName, claim.Name)),
Data: data,
}
}
m.IPAddrFiles = make([]*asset.File, len(ipAddrs))
for i, address := range ipAddrs {
data, err := yaml.Marshal(address)
if err != nil {
return errors.Wrapf(err, "unable to marshal ip claim %v", address.Name)
}
m.IPAddrFiles[i] = &asset.File{
Filename: filepath.Join(directory, fmt.Sprintf(ipAddressFileName, address.Name)),
Data: data,
}
}
padFormat := fmt.Sprintf("%%0%dd", len(fmt.Sprintf("%d", len(machines))))
for i, machine := range machines {
data, err := yaml.Marshal(machine)
if err != nil {
return errors.Wrapf(err, "marshal master %d", i)
}
padded := fmt.Sprintf(padFormat, i)
m.MachineFiles[i] = &asset.File{
Filename: filepath.Join(directory, fmt.Sprintf(masterMachineFileName, padded)),
Data: data,
}
}
// This is only used by Two Node OpenShift with Fencing (TNF)
// The credentials are rendered into secrets that will be consumed by the
// cluster-etcd operator to enable recovery via fencing
if pool.Fencing != nil && len(pool.Fencing.Credentials) > 0 {
credentials, err := gatherFencingCredentials(pool.Fencing.Credentials)
if err != nil {
return err
}
secrets, err := createSecretAssetFiles(credentials, fencingCredentialsSecretFileName)
if err != nil {
return fmt.Errorf("failed to gather fencing credentials for control plane hosts: %w", err)
}
m.FencingCredentialsSecretFiles = append(m.FencingCredentialsSecretFiles, secrets...)
}
return nil
}
func gatherFencingCredentials(credentials []*types.Credential) ([]corev1.Secret, error) {
secrets := []corev1.Secret{}
for i, credential := range credentials {
var name string
var annotations map[string]string
switch {
case credential.HostName != "":
name = credential.HostName
annotations = map[string]string{
"openshift.io/fencing-credentials": "hostname",
}
case credential.MACAddress != "":
parsedMAC, err := net.ParseMAC(credential.MACAddress)
if err != nil {
return nil, fmt.Errorf("credential at index %d has invalid MAC address: %w", i, err)
}
mac := strings.ReplaceAll(strings.ToLower(parsedMAC.String()), ":", "")
hash := sha256.Sum256([]byte(mac))
name = hex.EncodeToString(hash[:])
annotations = map[string]string{
"openshift.io/fencing-credentials": "mac-address",
}
default:
return nil, fmt.Errorf("cannot generate fencing secret for credential at index %d: no hostName or macAddress provided", i)
}
secret := &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("fencing-credentials-%s", name),
Namespace: "openshift-etcd",
Annotations: annotations,
},
Data: map[string][]byte{
"username": []byte(credential.Username),
"password": []byte(credential.Password),
"address": []byte(credential.Address),
"certificateVerification": []byte(credential.CertificateVerification),
},
}
secrets = append(secrets, *secret)
}
return secrets, nil
}
// Files returns the files generated by the asset.
func (m *Master) Files() []*asset.File {
files := make([]*asset.File, 0, 1+len(m.MachineConfigFiles)+len(m.MachineFiles))
if m.UserDataFile != nil {
files = append(files, m.UserDataFile)
}
files = append(files, m.MachineConfigFiles...)
// Hosts refer to secrets, so place the secrets before the hosts
// to avoid unnecessary reconciliation errors.
files = append(files, m.SecretFiles...)
files = append(files, m.NetworkConfigSecretFiles...)
// Machines are linked to hosts via the machineRef, so we create
// the hosts first to ensure if the operator starts trying to
// reconcile a machine it can pick up the related host.
files = append(files, m.HostFiles...)
files = append(files, m.MachineFiles...)
if m.ControlPlaneMachineSet != nil {
files = append(files, m.ControlPlaneMachineSet)
}
files = append(files, m.IPClaimFiles...)
files = append(files, m.IPAddrFiles...)
files = append(files, m.FencingCredentialsSecretFiles...)
return files
}
// Load reads the asset files from disk.
func (m *Master) Load(f asset.FileFetcher) (found bool, err error) {
file, err := f.FetchByName(filepath.Join(directory, masterUserDataFileName))
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
m.UserDataFile = file
m.MachineConfigFiles, err = machineconfig.Load(f, "master", directory)
if err != nil {
return true, err
}
var fileList []*asset.File
fileList, err = f.FetchByPattern(filepath.Join(directory, secretFileNamePattern))
if err != nil {
return true, err
}
m.SecretFiles = fileList
fileList, err = f.FetchByPattern(filepath.Join(directory, networkConfigSecretFileNamePattern))
if err != nil {
return true, err
}
m.NetworkConfigSecretFiles = fileList
fileList, err = f.FetchByPattern(filepath.Join(directory, hostFileNamePattern))
if err != nil {
return true, err
}
m.HostFiles = fileList
fileList, err = f.FetchByPattern(filepath.Join(directory, masterMachineFileNamePattern))
if err != nil {
return true, err
}
m.MachineFiles = fileList
file, err = f.FetchByName(filepath.Join(directory, controlPlaneMachineSetFileName))
if err != nil {
// Throw the error only if the file was present, since UPI and baremetal
// deployments do not use CPMS. We ignore this file if it's missing.
if !os.IsNotExist(err) {
return true, err
}
logrus.Debugf("CPMS file missing. Ignoring it while loading machine asset.")
}
m.ControlPlaneMachineSet = file
fileList, err = f.FetchByPattern(filepath.Join(directory, masterIPClaimFileNamePattern))
if err != nil {
return true, err
}
m.IPClaimFiles = fileList
fileList, err = f.FetchByPattern(filepath.Join(directory, masterIPAddressFileNamePattern))
if err != nil {
return true, err
}
m.IPAddrFiles = fileList
fileList, err = f.FetchByPattern(filepath.Join(directory, fencingCredentialsFilenamePattern))
if err != nil {
// Throw the error only if the file was present, since fencing credentials
// are apply only to Two Node OpenShift with Fencing (TNF) deployments.
// All other deployments will ignore this file.
if !os.IsNotExist(err) {
return true, err
}
}
m.FencingCredentialsSecretFiles = fileList
return true, nil
}
// Machines returns master Machine manifest structures.
func (m *Master) Machines() ([]machinev1beta1.Machine, error) {
scheme := runtime.NewScheme()
baremetalapi.AddToScheme(scheme)
ibmcloudapi.AddToScheme(scheme)
libvirtapi.AddToScheme(scheme)
ovirtproviderapi.AddToScheme(scheme)
scheme.AddKnownTypes(machinev1alpha1.GroupVersion,
&machinev1alpha1.OpenstackProviderSpec{},
)
scheme.AddKnownTypes(machinev1beta1.SchemeGroupVersion,
&machinev1beta1.AWSMachineProviderConfig{},
&machinev1beta1.VSphereMachineProviderSpec{},
&machinev1beta1.AzureMachineProviderSpec{},
&machinev1beta1.GCPMachineProviderSpec{},
)
scheme.AddKnownTypes(machinev1.GroupVersion,
&machinev1.NutanixMachineProviderConfig{},
&machinev1.PowerVSMachineProviderConfig{},
&machinev1.ControlPlaneMachineSet{},
)
machinev1beta1.AddToScheme(scheme)
machinev1.Install(scheme)
decoder := serializer.NewCodecFactory(scheme).UniversalDecoder(
machinev1.GroupVersion,
baremetalprovider.SchemeGroupVersion,
ibmcloudprovider.SchemeGroupVersion,
libvirtprovider.SchemeGroupVersion,
machinev1alpha1.GroupVersion,
machinev1beta1.SchemeGroupVersion,
ovirtprovider.SchemeGroupVersion,
)
machines := []machinev1beta1.Machine{}
for i, file := range m.MachineFiles {
machine := &machinev1beta1.Machine{}
err := yaml.Unmarshal(file.Data, &machine)
if err != nil {
return machines, errors.Wrapf(err, "unmarshal master %d", i)
}
obj, _, err := decoder.Decode(machine.Spec.ProviderSpec.Value.Raw, nil, nil)
if err != nil {
return machines, errors.Wrapf(err, "unmarshal master %d", i)
}
machine.Spec.ProviderSpec.Value = &runtime.RawExtension{Object: obj}
machines = append(machines, *machine)
}
return machines, nil
}
// IsMachineManifest tests whether a file is a manifest that belongs to the
// Master Machines or Worker Machines asset.
func IsMachineManifest(file *asset.File) bool {
if filepath.Dir(file.Filename) != directory {
return false
}
filename := filepath.Base(file.Filename)
if filename == masterUserDataFileName || filename == workerUserDataFileName || filename == controlPlaneMachineSetFileName {
return true
}
if matched, err := machineconfig.IsManifest(filename); err != nil {
panic(err)
} else if matched {
return true
}
for _, pattern := range []struct {
Pattern string
Type string
}{
{Pattern: secretFileNamePattern, Type: "secret"},
{Pattern: networkConfigSecretFileNamePattern, Type: "network config secret"},
{Pattern: hostFileNamePattern, Type: "host"},
{Pattern: masterMachineFileNamePattern, Type: "master machine"},
{Pattern: workerMachineSetFileNamePattern, Type: "worker machineset"},
{Pattern: masterIPAddressFileNamePattern, Type: "master ip address"},
{Pattern: masterIPClaimFileNamePattern, Type: "master ip address claim"},
{Pattern: fencingCredentialsFilenamePattern, Type: "fencing credentials secret"},
} {
if matched, err := filepath.Match(pattern.Pattern, filename); err != nil {
panic(fmt.Sprintf("bad format for %s file name pattern", pattern.Type))
} else if matched {
return true
}
}
return false
}