-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathmachine_webhook.go
More file actions
2470 lines (2118 loc) · 101 KB
/
machine_webhook.go
File metadata and controls
2470 lines (2118 loc) · 101 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 webhooks
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
goruntime "runtime"
"strconv"
"strings"
"k8s.io/component-base/featuregate"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
"k8s.io/utils/strings/slices"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/kube-storage-version-migrator/pkg/clients/clientset/scheme"
"sigs.k8s.io/yaml"
osconfigv1 "github.com/openshift/api/config/v1"
apifeatures "github.com/openshift/api/features"
machinev1 "github.com/openshift/api/machine/v1"
machinev1beta1 "github.com/openshift/api/machine/v1beta1"
osclientset "github.com/openshift/client-go/config/clientset/versioned"
"github.com/openshift/machine-api-operator/pkg/util/lifecyclehooks"
)
type systemSpecifications struct {
minMemoryGiB int32
maxMemoryGiB int32
minProcessorSharedCapped float64
minProcessorDedicated float64
maxProcessor float64
}
type machineArch string
var (
// Azure Defaults
defaultAzureVnet = func(clusterID string) string {
return fmt.Sprintf("%s-vnet", clusterID)
}
defaultAzureSubnet = func(clusterID string) string {
return fmt.Sprintf("%s-worker-subnet", clusterID)
}
defaultAzureNetworkResourceGroup = func(clusterID string) string {
return fmt.Sprintf("%s-rg", clusterID)
}
defaultAzureImageResourceID = func(clusterID string) string {
// image gallery names cannot have dashes
galleryName := strings.Replace(clusterID, "-", "_", -1)
imageName := clusterID
if arch == ARM64 {
// append gen2 to the image name for ARM64.
// Although the installer creates a gen2 image for AMD64, we cannot guarantee that clusters created
// before that change will have a -gen2 image.
imageName = fmt.Sprintf("%s-gen2", clusterID)
}
return fmt.Sprintf("/resourceGroups/%s/providers/Microsoft.Compute/galleries/gallery_%s/images/%s/versions/%s", clusterID+"-rg", galleryName, imageName, azureRHCOSVersion)
}
defaultAzureManagedIdentiy = func(clusterID string) string {
return fmt.Sprintf("%s-identity", clusterID)
}
defaultAzureResourceGroup = func(clusterID string) string {
return fmt.Sprintf("%s-rg", clusterID)
}
// GCP Defaults
defaultGCPNetwork = func(clusterID string) string {
return fmt.Sprintf("%s-network", clusterID)
}
defaultGCPSubnetwork = func(clusterID string) string {
return fmt.Sprintf("%s-worker-subnet", clusterID)
}
defaultGCPTags = func(clusterID string) []string {
return []string{fmt.Sprintf("%s-worker", clusterID)}
}
defaultGCPDiskImage = func() string {
if arch == ARM64 {
return defaultGCPARMDiskImage
}
return defaultGCPX86DiskImage
}
// Power VS variables
//powerVSMachineConfigurations contains the known Power VS system types and their allowed configuration limits
powerVSMachineConfigurations = map[string]systemSpecifications{
"s922": {
minMemoryGiB: 32,
maxMemoryGiB: 942,
minProcessorSharedCapped: 0.5,
minProcessorDedicated: 1,
maxProcessor: 15,
},
"e880": {
minMemoryGiB: 32,
maxMemoryGiB: 7463,
minProcessorSharedCapped: 0.5,
minProcessorDedicated: 1,
maxProcessor: 143,
},
"e980": {
minMemoryGiB: 32,
maxMemoryGiB: 15307,
minProcessorSharedCapped: 0.5,
minProcessorDedicated: 1,
maxProcessor: 143,
},
}
// VSphere variables
// tagUrnPattern is helps validate the format of a given tag URN
tagUrnPattern = regexp.MustCompile(`^(urn):(vmomi):(InventoryServiceTag):([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}):([^:]+)$`)
// vSphereDataDiskNamePattern is used to validate the name of a data disk
vSphereDataDiskNamePattern = regexp.MustCompile(`^[a-zA-Z0-9]([-_a-zA-Z0-9]*[a-zA-Z0-9])?$`)
// validProvisioningModes lists all valid data disk provisioning modes
validProvisioningModes = []machinev1beta1.ProvisioningMode{
machinev1beta1.ProvisioningModeThin,
machinev1beta1.ProvisioningModeThick,
machinev1beta1.ProvisioningModeEagerlyZeroed,
}
)
const (
arch = machineArch(goruntime.GOARCH)
ARM64 machineArch = "arm64"
AMD64 machineArch = "amd64"
defaultUserDataSecret = "worker-user-data"
defaultSecretNamespace = "openshift-machine-api"
// AWS Defaults
defaultAWSCredentialsSecret = "aws-cloud-credentials"
defaultAWSX86InstanceType = "m5.large"
defaultAWSARMInstanceType = "m6g.large"
// Azure Defaults
defaultAzureX86VMSize = "Standard_D4s_V3"
defaultAzureARMVMSize = "Standard_D4ps_V5"
defaultAzureCredentialsSecret = "azure-cloud-credentials"
defaultAzureOSDiskOSType = "Linux"
defaultAzureOSDiskStorageType = "Premium_LRS"
// Azure OSDisk constants
azureMaxDiskSizeGB = 32768
azureEphemeralStorageLocationLocal = "Local"
azureCachingTypeNone = "None"
azureCachingTypeReadOnly = "ReadOnly"
azureCachingTypeReadWrite = "ReadWrite"
azureRHCOSVersion = "latest" // The installer only sets up one version but its name may vary, using latest will pull it no matter the name.
// GCP Defaults
defaultGCPX86MachineType = "n1-standard-4"
defaultGCPARMMachineType = "t2a-standard-4"
defaultGCPCredentialsSecret = "gcp-cloud-credentials"
defaultGCPDiskSizeGb = 128
defaultGCPDiskType = "pd-standard"
// https://releases-rhcos-art.apps.ocp-virt.prod.psi.redhat.com/?stream=prod/streams/4.14-9.2&release=414.92.202307070025-0&arch=x86_64#414.92.202307070025-0
// https://github.com/openshift/installer/commit/0cec4e1403d78387729f21f04d0f764f63fc552e
defaultGCPX86DiskImage = "projects/rhcos-cloud/global/images/rhcos-414-92-202307070025-0-gcp-x86-64"
defaultGCPARMDiskImage = "projects/rhcos-cloud/global/images/rhcos-414-92-202307070025-0-gcp-aarch64"
defaultGCPGPUCount = 1
// vSphere Defaults
defaultVSphereCredentialsSecret = "vsphere-cloud-credentials"
// Minimum vSphere values taken from vSphere reconciler
minVSphereCPU = 2
minVSphereMemoryMiB = 2048
// https://docs.openshift.com/container-platform/4.1/installing/installing_vsphere/installing-vsphere.html#minimum-resource-requirements_installing-vsphere
minVSphereDiskGiB = 120
// Maximum number of data disks allowed to be added to a VM
maxVSphereDataDisks = 29
// Max length of a DataDisk name
maxVSphereDataDiskNameLength = 80
// Max size of any data disk in vSphere is 62 TiB. We are currently limiting to 16TiB (16384 GiB) as a starting point.
maxVSphereDataDiskSize = 16384
// Max number of networks allowed per machine
maxVSphereNetworkCount = 10
// Nutanix Defaults
// Minimum Nutanix values taken from Nutanix reconciler
defaultNutanixCredentialsSecret = "nutanix-credentials"
minNutanixCPUSockets = 1
minNutanixCPUPerSocket = 1
minNutanixMemoryMiB = 2048
minNutanixDiskGiB = 20
// PowerVS Defaults
defaultPowerVSCredentialsSecret = "powervs-credentials"
defaultPowerVSSysType = "s922"
defaultPowerVSProcType = "Shared"
defaultPowerVSProcessor = "0.5"
defaultPowerVSMemory = 32
powerVSServiceInstance = "serviceInstance"
powerVSNetwork = "network"
powerVSImage = "image"
powerVSSystemTypeE880 = "e880"
powerVSSystemTypeE980 = "e980"
azureProviderIDPrefix = "azure://"
azureProvidersKey = "providers"
azureSubscriptionsKey = "subscriptions"
azureResourceGroupsLowerKey = "resourcegroups"
azureLocationsKey = "locations"
azureBuiltInResourceNamespace = "Microsoft.Resources"
)
// GCP Confidential VM supports Compute Engine machine types in the following series:
// reference: https://cloud.google.com/compute/confidential-vm/docs/os-and-machine-type#machine-type
var gcpConfidentialTypeMachineSeriesSupportingSEV = []string{"n2d", "c2d", "c3d"}
var gcpConfidentialTypeMachineSeriesSupportingSEVSNP = []string{"n2d"}
var gcpConfidentialTypeMachineSeriesSupportingTDX = []string{"c3"}
// GCP onHostMaintenance Migrate with Confidential Compute is supported only on certain series:
// reference: https://cloud.google.com/confidential-computing/confidential-vm/docs/troubleshoot-live-migration
var gcpConfidentialTypeMachineSeriesSupportingOnHostMaintenanceMigrate = []string{"n2d"}
// defaultInstanceTypeForCloudProvider returns the default instance type for the given cloud provider and architecture.
// If the cloud provider is not supported, an empty string is returned.
// If the architecture is not supported, the default instance type for AMD64 is returned as a fallback.
// The function also takes a pointer to a slice of strings to append warnings to.
func defaultInstanceTypeForCloudProvider(cloudProvider osconfigv1.PlatformType, arch machineArch, warnings *[]string) string {
cloudProviderArchMachineTypes := map[osconfigv1.PlatformType]map[machineArch]string{
osconfigv1.AWSPlatformType: {
AMD64: defaultAWSX86InstanceType,
ARM64: defaultAWSARMInstanceType,
},
osconfigv1.AzurePlatformType: {
AMD64: defaultAzureX86VMSize,
ARM64: defaultAzureARMVMSize,
},
osconfigv1.GCPPlatformType: {
AMD64: defaultGCPX86MachineType,
ARM64: defaultGCPARMMachineType,
},
}
if cloudProviderMap, ok := cloudProviderArchMachineTypes[cloudProvider]; ok {
if instanceType, ok := cloudProviderArchMachineTypes[cloudProvider][arch]; ok {
*warnings = append(*warnings, fmt.Sprintf("setting the default instance type %q "+
"for cloud provider %q, based on the control plane architecture (%q)", instanceType, cloudProvider, arch))
return instanceType
}
// If the arch is not supported, return the default for AMD64.
warning := fmt.Sprintf("no default instance type found for provider %q, arch %q. "+
"Defaulting to the amd64 one: %q", cloudProvider, arch, cloudProviderMap[AMD64])
*warnings = append(*warnings, warning)
klog.Warningln(warning)
return cloudProviderMap[AMD64]
}
// If the cloud provider is not supported, return an empty string.
klog.Errorf("no default instance types found for cloud provider %q", cloudProvider)
return ""
}
func secretExists(c client.Client, name, namespace string) (bool, error) {
key := client.ObjectKey{
Name: name,
Namespace: namespace,
}
obj := &corev1.Secret{}
if err := c.Get(context.Background(), key, obj); err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
func credentialsSecretExists(c client.Client, name, namespace string) []string {
secretExists, err := secretExists(c, name, namespace)
if err != nil {
return []string{
field.Invalid(
field.NewPath("providerSpec", "credentialsSecret"),
name,
fmt.Sprintf("failed to get credentialsSecret: %v", err),
).Error(),
}
}
if !secretExists {
return []string{
field.Invalid(
field.NewPath("providerSpec", "credentialsSecret"),
name,
"not found. Expected CredentialsSecret to exist",
).Error(),
}
}
return []string{}
}
func getInfra() (*osconfigv1.Infrastructure, error) {
cfg, err := ctrl.GetConfig()
if err != nil {
return nil, err
}
client, err := osclientset.NewForConfig(cfg)
if err != nil {
return nil, err
}
infra, err := client.ConfigV1().Infrastructures().Get(context.Background(), "cluster", metav1.GetOptions{})
if err != nil {
return nil, err
}
return infra, nil
}
func getDNS() (*osconfigv1.DNS, error) {
cfg, err := ctrl.GetConfig()
if err != nil {
return nil, err
}
client, err := osclientset.NewForConfig(cfg)
if err != nil {
return nil, err
}
dns, err := client.ConfigV1().DNSes().Get(context.Background(), "cluster", metav1.GetOptions{})
if err != nil {
return nil, err
}
return dns, nil
}
type machineAdmissionFn func(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList)
type admissionConfig struct {
clusterID string
platformStatus *osconfigv1.PlatformStatus
dnsDisconnected bool
client client.Client
featureGates featuregate.MutableFeatureGate
}
type admissionHandler struct {
*admissionConfig
webhookOperations machineAdmissionFn
decoder *admission.Decoder
}
// InjectDecoder injects the decoder.
func (a *admissionHandler) InjectDecoder(d *admission.Decoder) error {
a.decoder = d
return nil
}
// machineValidatorHandler validates Machine API resources.
// implements type Handler interface.
// https://godoc.org/github.com/kubernetes-sigs/controller-runtime/pkg/webhook/admission#Handler
type machineValidatorHandler struct {
*admissionHandler
}
// machineDefaulterHandler defaults Machine API resources.
// implements type Handler interface.
// https://godoc.org/github.com/kubernetes-sigs/controller-runtime/pkg/webhook/admission#Handler
type machineDefaulterHandler struct {
*admissionHandler
}
// NewValidator returns a new machineValidatorHandler.
func NewMachineValidator(client client.Client, featureGate featuregate.MutableFeatureGate) (*admission.Webhook, error) {
infra, err := getInfra()
if err != nil {
return nil, err
}
dns, err := getDNS()
if err != nil {
return nil, err
}
return admission.WithCustomValidator(scheme.Scheme, &machinev1beta1.Machine{}, createMachineValidator(infra, client, dns, featureGate)), nil
}
func createMachineValidator(infra *osconfigv1.Infrastructure, client client.Client, dns *osconfigv1.DNS, featureGate featuregate.MutableFeatureGate) *machineValidatorHandler {
admissionConfig := &admissionConfig{
dnsDisconnected: dns.Spec.PublicZone == nil,
clusterID: infra.Status.InfrastructureName,
platformStatus: infra.Status.PlatformStatus,
client: client,
featureGates: featureGate,
}
return &machineValidatorHandler{
admissionHandler: &admissionHandler{
admissionConfig: admissionConfig,
webhookOperations: getMachineValidatorOperation(infra.Status.PlatformStatus.Type),
},
}
}
func getMachineValidatorOperation(platform osconfigv1.PlatformType) machineAdmissionFn {
switch platform {
case osconfigv1.AWSPlatformType:
return validateAWS
case osconfigv1.AzurePlatformType:
return validateAzure
case osconfigv1.GCPPlatformType:
return validateGCP
case osconfigv1.VSpherePlatformType:
return validateVSphere
case osconfigv1.PowerVSPlatformType:
return validatePowerVS
case osconfigv1.NutanixPlatformType:
return validateNutanix
default:
// just no-op
return func(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList) {
return true, []string{}, nil
}
}
}
// NewDefaulter returns a new machineDefaulterHandler.
func NewMachineDefaulter() (*admission.Webhook, error) {
infra, err := getInfra()
if err != nil {
return nil, err
}
return admission.WithCustomDefaulter(scheme.Scheme, &machinev1beta1.Machine{}, createMachineDefaulter(infra.Status.PlatformStatus, infra.Status.InfrastructureName)), nil
}
func createMachineDefaulter(platformStatus *osconfigv1.PlatformStatus, clusterID string) *machineDefaulterHandler {
return &machineDefaulterHandler{
admissionHandler: &admissionHandler{
admissionConfig: &admissionConfig{clusterID: clusterID},
webhookOperations: getMachineDefaulterOperation(platformStatus),
},
}
}
func getMachineDefaulterOperation(platformStatus *osconfigv1.PlatformStatus) machineAdmissionFn {
switch platformStatus.Type {
case osconfigv1.AWSPlatformType:
region := ""
if platformStatus.AWS != nil {
region = platformStatus.AWS.Region
}
return awsDefaulter{region: region}.defaultAWS
case osconfigv1.AzurePlatformType:
return defaultAzure
case osconfigv1.GCPPlatformType:
return defaultGCP
case osconfigv1.VSpherePlatformType:
return defaultVSphere
case osconfigv1.PowerVSPlatformType:
return defaultPowerVS
case osconfigv1.NutanixPlatformType:
return defaultNutanix
default:
// just no-op
return func(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList) {
return true, []string{}, nil
}
}
}
func (h *machineValidatorHandler) validateMachine(m, oldM *machinev1beta1.Machine) (bool, []string, field.ErrorList) {
// Skip validation if we just remove the finalizer.
// For more information: https://issues.redhat.com/browse/OCPCLOUD-1426
if !m.DeletionTimestamp.IsZero() {
isFinalizerOnly, err := isFinalizerOnlyRemoval(m, oldM)
if err != nil {
return false, nil, field.ErrorList{field.InternalError(field.NewPath(""), err)}
}
if isFinalizerOnly {
return true, nil, nil
}
}
errs := validateMachineLifecycleHooks(m, oldM)
ok, warnings, opErrs := h.webhookOperations(m, h.admissionConfig)
if !ok {
errs = append(errs, opErrs...)
}
if len(errs) > 0 {
return false, warnings, errs
}
return true, warnings, nil
}
// Handle handles HTTP requests for admission webhook servers.
func (h *machineValidatorHandler) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
m, ok := obj.(*machinev1beta1.Machine)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a Machine but got a %T", obj))
}
klog.V(3).Infof("Validate webhook called for Machine: %s", m.GetName())
ok, warnings, errs := h.validateMachine(m, nil)
if !ok {
return warnings, errs.ToAggregate()
}
return warnings, nil
}
// Handle handles HTTP requests for admission webhook servers.
func (h *machineValidatorHandler) ValidateUpdate(ctx context.Context, oldObj, obj runtime.Object) (admission.Warnings, error) {
m, ok := obj.(*machinev1beta1.Machine)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a Machine but got a %T", obj))
}
mOld, ok := oldObj.(*machinev1beta1.Machine)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a Machine but got a %T", oldObj))
}
klog.V(3).Infof("Validate webhook called for Machine: %s", m.GetName())
ok, warnings, errs := h.validateMachine(m, mOld)
if !ok {
return warnings, errs.ToAggregate()
}
return warnings, nil
}
// Handle handles HTTP requests for admission webhook servers.
func (h *machineValidatorHandler) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
m, ok := obj.(*machinev1beta1.Machine)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a Machine but got a %T", obj))
}
klog.V(3).Infof("Validate webhook called for Machine: %s", m.GetName())
ok, warnings, errs := h.validateMachine(m, nil)
if !ok {
return warnings, errs.ToAggregate()
}
return warnings, nil
}
// Handle handles HTTP requests for admission webhook servers.
func (h *machineDefaulterHandler) Default(ctx context.Context, obj runtime.Object) error {
m, ok := obj.(*machinev1beta1.Machine)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a MachineSet but got a %T", obj))
}
klog.V(3).Infof("Mutate webhook called for Machine: %s", m.GetName())
// Only enforce the clusterID if it's not set.
// Otherwise a discrepancy on the value would leave the machine orphan
// and would trigger a new machine creation by the machineSet.
// https://bugzilla.redhat.com/show_bug.cgi?id=1857175
if m.Labels == nil {
m.Labels = make(map[string]string)
}
if _, ok := m.Labels[machinev1beta1.MachineClusterIDLabel]; !ok {
m.Labels[machinev1beta1.MachineClusterIDLabel] = h.clusterID
}
ok, _, errs := h.webhookOperations(m, h.admissionConfig)
if !ok {
return errs.ToAggregate()
}
return nil
}
type awsDefaulter struct {
region string
}
func (a awsDefaulter) defaultAWS(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList) {
klog.V(3).Infof("Defaulting AWS providerSpec")
var errs field.ErrorList
var warnings []string
providerSpec := new(machinev1beta1.AWSMachineProviderConfig)
if err := unmarshalInto(m, providerSpec); err != nil {
errs = append(errs, err)
return false, warnings, errs
}
if providerSpec.InstanceType == "" {
providerSpec.InstanceType = defaultInstanceTypeForCloudProvider(osconfigv1.AWSPlatformType, arch, &warnings)
}
if providerSpec.InstanceType == "" {
// this should never happen
errs = append(errs, field.Required(field.NewPath("instanceType"), "instanceType is required and no "+
"default value was found"))
}
if providerSpec.Placement.Region == "" {
providerSpec.Placement.Region = a.region
}
if providerSpec.UserDataSecret == nil {
providerSpec.UserDataSecret = &corev1.LocalObjectReference{Name: defaultUserDataSecret}
} else if providerSpec.UserDataSecret.Name == "" {
providerSpec.UserDataSecret.Name = defaultUserDataSecret
}
if providerSpec.CredentialsSecret == nil {
providerSpec.CredentialsSecret = &corev1.LocalObjectReference{Name: defaultAWSCredentialsSecret}
}
rawBytes, err := json.Marshal(providerSpec)
if err != nil {
errs = append(errs, field.InternalError(field.NewPath("providerSpec", "value"), err))
}
if len(errs) > 0 {
return false, warnings, errs
}
m.Spec.ProviderSpec.Value = &kruntime.RawExtension{Raw: rawBytes}
return true, warnings, nil
}
func unmarshalInto(m *machinev1beta1.Machine, providerSpec interface{}) *field.Error {
if m.Spec.ProviderSpec.Value == nil {
return field.Required(field.NewPath("providerSpec", "value"), "a value must be provided")
}
if err := yaml.Unmarshal(m.Spec.ProviderSpec.Value.Raw, &providerSpec); err != nil {
return field.Invalid(field.NewPath("providerSpec", "value"), providerSpec, err.Error())
}
return nil
}
func validateUnknownFields(m *machinev1beta1.Machine, providerSpec interface{}) error {
if err := yaml.Unmarshal(m.Spec.ProviderSpec.Value.Raw, &providerSpec, yaml.DisallowUnknownFields); err != nil {
if strings.Contains(err.Error(), "unknown field") {
unknownField := strings.Replace(strings.Split(err.Error(), "unknown field ")[1], "\"", "", -1)
return &field.Error{
Type: field.ErrorTypeNotSupported,
Field: field.NewPath("providerSpec", "value").String(),
BadValue: unknownField,
Detail: fmt.Sprintf("Unknown field (%s) will be ignored", unknownField),
}
}
}
return nil
}
func validateAWS(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList) {
klog.V(3).Infof("Validating AWS providerSpec")
var errs field.ErrorList
var warnings []string
providerSpec := new(machinev1beta1.AWSMachineProviderConfig)
if err := unmarshalInto(m, providerSpec); err != nil {
errs = append(errs, err)
return false, warnings, errs
}
if err := validateUnknownFields(m, providerSpec); err != nil {
warnings = append(warnings, err.Error())
}
if !validateGVK(providerSpec.GroupVersionKind(), osconfigv1.AWSPlatformType) {
warnings = append(warnings, fmt.Sprintf("incorrect GroupVersionKind for AWSMachineProviderConfig object: %s", providerSpec.GroupVersionKind()))
}
if providerSpec.AMI.ID == nil {
errs = append(
errs,
field.Required(
field.NewPath("providerSpec", "ami"),
"expected providerSpec.ami.id to be populated",
),
)
}
if providerSpec.AMI.ARN != nil {
warnings = append(
warnings,
"can't use providerSpec.ami.arn, only providerSpec.ami.id can be used to reference AMI",
)
}
if providerSpec.AMI.Filters != nil {
warnings = append(
warnings,
"can't use providerSpec.ami.filters, only providerSpec.ami.id can be used to reference AMI",
)
}
if providerSpec.Placement.Region == "" {
errs = append(
errs,
field.Required(
field.NewPath("providerSpec", "placement", "region"),
"expected providerSpec.placement.region to be populated",
),
)
}
if providerSpec.InstanceType == "" {
errs = append(
errs,
field.Required(
field.NewPath("providerSpec", "instanceType"),
"expected providerSpec.instanceType to be populated",
),
)
}
if providerSpec.UserDataSecret == nil {
errs = append(errs, field.Required(field.NewPath("providerSpec", "userDataSecret"), "expected providerSpec.userDataSecret to be populated"))
} else if providerSpec.UserDataSecret.Name == "" {
errs = append(errs, field.Required(field.NewPath("providerSpec", "userDataSecret", "name"), "expected providerSpec.userDataSecret.name to be provided"))
}
if providerSpec.CredentialsSecret == nil {
errs = append(
errs,
field.Required(
field.NewPath("providerSpec", "credentialsSecret"),
"expected providerSpec.credentialsSecret to be populated",
),
)
} else {
warnings = append(warnings, credentialsSecretExists(config.client, providerSpec.CredentialsSecret.Name, m.GetNamespace())...)
}
if providerSpec.Subnet.ARN == nil && providerSpec.Subnet.ID == nil && providerSpec.Subnet.Filters == nil {
warnings = append(
warnings,
"providerSpec.subnet: No subnet has been provided. Instances may be created in an unexpected subnet and may not join the cluster.",
)
}
if providerSpec.Subnet.ARN != nil {
warnings = append(
warnings,
"can't use providerSpec.subnet.arn, only providerSpec.subnet.id or providerSpec.subnet.filters can be used to reference Subnet",
)
}
if providerSpec.IAMInstanceProfile == nil {
warnings = append(warnings, "providerSpec.iamInstanceProfile: no IAM instance profile provided: nodes may be unable to join the cluster")
} else {
if providerSpec.IAMInstanceProfile.ARN != nil {
warnings = append(
warnings,
"can't use providerSpec.iamInstanceProfile.arn, only providerSpec.iamInstanceProfile.id can be used to reference IAMInstanceProfile",
)
}
if providerSpec.IAMInstanceProfile.Filters != nil {
warnings = append(
warnings,
"can't use providerSpec.iamInstanceProfile.filters, only providerSpec.iamInstanceProfile.id can be used to reference IAMInstanceProfile",
)
}
}
if providerSpec.CapacityReservationID != "" {
if err := validateAwsCapacityReservationId(providerSpec.CapacityReservationID); err != nil {
errs = append(errs, field.Invalid(field.NewPath("providerSpec", "capacityReservationId"), providerSpec.CapacityReservationID, err.Error()))
}
}
if providerSpec.MarketType != "" {
if err := validateAWSInstanceMarketType(providerSpec); err != nil {
errs = append(errs, field.Invalid(field.NewPath("providerSpec", "marketType"), providerSpec.MarketType, err.Error()))
}
}
if providerSpec.MarketType == "" && providerSpec.SpotMarketOptions != nil && providerSpec.CapacityReservationID != "" {
errs = append(errs, field.Invalid(field.NewPath("providerSpec", "capacityReservationId"), providerSpec.CapacityReservationID, "spotMarketOptions and capacityReservationID may not be used together"))
}
// TODO(alberto): Validate providerSpec.BlockDevices.
// https://github.com/openshift/cluster-api-provider-aws/pull/299#discussion_r433920532
switch providerSpec.Placement.Tenancy {
case "", machinev1beta1.DefaultTenancy, machinev1beta1.DedicatedTenancy, machinev1beta1.HostTenancy:
// Do nothing, valid values
default:
errs = append(
errs,
field.Invalid(
field.NewPath("providerSpec", "tenancy"),
providerSpec.Placement.Tenancy,
fmt.Sprintf("Invalid providerSpec.tenancy, the only allowed options are: %s, %s, %s", machinev1beta1.DefaultTenancy, machinev1beta1.DedicatedTenancy, machinev1beta1.HostTenancy),
),
)
}
if providerSpec.PlacementGroupPartition != nil {
partition := *providerSpec.PlacementGroupPartition
// placementGroupPartition must be between 1 and 7
if partition < 1 || partition > 7 {
errs = append(
errs,
field.Invalid(
field.NewPath("providerSpec", "placementGroupPartition"),
partition,
"providerSpec.placementGroupPartition must be between 1 and 7",
),
)
}
// placementGroupName must be set
if providerSpec.PlacementGroupName == "" {
errs = append(
errs,
field.Invalid(
field.NewPath("providerSpec", "placementGroupPartition"),
partition,
"providerSpec.placementGroupPartition is set but providerSpec.placementGroupName is empty",
),
)
}
}
duplicatedTags := getDuplicatedTags(providerSpec.Tags)
if len(duplicatedTags) > 0 {
warnings = append(warnings, fmt.Sprintf("providerSpec.tags: duplicated tag names (%s): only the first value will be used.", strings.Join(duplicatedTags, ",")))
}
switch providerSpec.NetworkInterfaceType {
case "", machinev1beta1.AWSENANetworkInterfaceType, machinev1beta1.AWSEFANetworkInterfaceType:
// Do nothing, valid values
default:
errs = append(
errs,
field.Invalid(
field.NewPath("providerSpec", "networkInterfaceType"),
providerSpec.NetworkInterfaceType,
fmt.Sprintf("Valid values are: %s, %s and omitted", machinev1beta1.AWSENANetworkInterfaceType, machinev1beta1.AWSEFANetworkInterfaceType),
),
)
}
switch providerSpec.MetadataServiceOptions.Authentication {
case "", machinev1beta1.MetadataServiceAuthenticationOptional, machinev1beta1.MetadataServiceAuthenticationRequired:
// Valid values
default:
errs = append(
errs,
field.Invalid(
field.NewPath("providerSpec", "metadataServiceOptions", "authentication"),
providerSpec.MetadataServiceOptions.Authentication,
fmt.Sprintf("Allowed values are either '%s' or '%s'", machinev1beta1.MetadataServiceAuthenticationOptional, machinev1beta1.MetadataServiceAuthenticationRequired),
),
)
}
if len(errs) > 0 {
return false, warnings, errs
}
return true, warnings, nil
}
// getDuplicatedTags iterates through the AWS TagSpecifications
// to determine if any tag Name is duplicated within the list.
// A list of duplicated names will be returned.
func getDuplicatedTags(tagSpecs []machinev1beta1.TagSpecification) []string {
tagNames := map[string]int{}
duplicatedTags := []string{}
for _, spec := range tagSpecs {
tagNames[spec.Name] += 1
// Only append the duplicated tag on the second occurrence to prevent it
// being listed multiple times when there are more than 2 occurrences.
if tagNames[spec.Name] == 2 {
duplicatedTags = append(duplicatedTags, spec.Name)
}
}
return duplicatedTags
}
func defaultAzure(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList) {
klog.V(3).Infof("Defaulting Azure providerSpec")
var errs field.ErrorList
var warnings []string
providerSpec := new(machinev1beta1.AzureMachineProviderSpec)
if err := unmarshalInto(m, providerSpec); err != nil {
errs = append(errs, err)
return false, warnings, errs
}
if providerSpec.VMSize == "" {
providerSpec.VMSize = defaultInstanceTypeForCloudProvider(osconfigv1.AzurePlatformType, arch, &warnings)
}
if providerSpec.VMSize == "" {
// this should never happen
errs = append(errs, field.Required(field.NewPath("vmSize"), "vmSize is required and no "+
"default value was found"))
}
// Vnet and Subnet need to be provided together by the user
if providerSpec.Vnet == "" && providerSpec.Subnet == "" {
providerSpec.Vnet = defaultAzureVnet(config.clusterID)
providerSpec.Subnet = defaultAzureSubnet(config.clusterID)
}
if providerSpec.Image == (machinev1beta1.Image{}) {
providerSpec.Image.ResourceID = defaultAzureImageResourceID(config.clusterID)
}
if providerSpec.UserDataSecret == nil {
providerSpec.UserDataSecret = &corev1.SecretReference{Name: defaultUserDataSecret}
} else if providerSpec.UserDataSecret.Name == "" {
providerSpec.UserDataSecret.Name = defaultUserDataSecret
}
if providerSpec.CredentialsSecret == nil {
providerSpec.CredentialsSecret = &corev1.SecretReference{Name: defaultAzureCredentialsSecret, Namespace: defaultSecretNamespace}
} else {
if providerSpec.CredentialsSecret.Namespace == "" {
providerSpec.CredentialsSecret.Namespace = defaultSecretNamespace
}
if providerSpec.CredentialsSecret.Name == "" {
providerSpec.CredentialsSecret.Name = defaultAzureCredentialsSecret
}
}
rawBytes, err := json.Marshal(providerSpec)
if err != nil {
errs = append(errs, field.InternalError(field.NewPath("providerSpec", "value"), err))
}
if len(errs) > 0 {
return false, warnings, errs
}
m.Spec.ProviderSpec.Value = &kruntime.RawExtension{Raw: rawBytes}
return true, warnings, nil
}
func validateAzure(m *machinev1beta1.Machine, config *admissionConfig) (bool, []string, field.ErrorList) {
klog.V(3).Infof("Validating Azure providerSpec")
var errs field.ErrorList
var warnings []string
providerSpec := new(machinev1beta1.AzureMachineProviderSpec)
if err := unmarshalInto(m, providerSpec); err != nil {
errs = append(errs, err)
return false, warnings, errs
}
if err := validateUnknownFields(m, providerSpec); err != nil {
warnings = append(warnings, err.Error())
}
if !validateGVK(providerSpec.GroupVersionKind(), osconfigv1.AzurePlatformType) {
warnings = append(warnings, fmt.Sprintf("incorrect GroupVersionKind for AzureMachineProviderSpec object: %s", providerSpec.GroupVersionKind()))
}
if providerSpec.VMSize == "" {
errs = append(errs, field.Required(field.NewPath("providerSpec", "vmSize"), "vmSize should be set to one of the supported Azure VM sizes"))
}
if providerSpec.PublicIP && config.dnsDisconnected {
errs = append(errs, field.Forbidden(field.NewPath("providerSpec", "publicIP"), "publicIP is not allowed in Azure disconnected installation with publish strategy as internal"))
}
// Vnet requires Subnet
if providerSpec.Vnet != "" && providerSpec.Subnet == "" {
errs = append(errs, field.Required(field.NewPath("providerSpec", "subnet"), "must provide a subnet when a virtual network is specified"))
}
// Subnet requires Vnet
if providerSpec.Subnet != "" && providerSpec.Vnet == "" {
errs = append(errs, field.Required(field.NewPath("providerSpec", "vnet"), "must provide a virtual network when supplying subnets"))
}
errs = append(errs, validateAzureImage(providerSpec.Image)...)
if providerSpec.UserDataSecret == nil {
errs = append(errs, field.Required(field.NewPath("providerSpec", "userDataSecret"), "userDataSecret must be provided"))
} else if providerSpec.UserDataSecret.Name == "" {