/
azuremachine_default.go
255 lines (222 loc) · 8.74 KB
/
azuremachine_default.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
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1beta1
import (
"context"
"encoding/base64"
"fmt"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/uuid"
utilSSH "sigs.k8s.io/cluster-api-provider-azure/util/ssh"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// ContributorRoleID is the ID of the built-in "Contributor" role.
const ContributorRoleID = "b24988ac-6180-42a0-ab88-20f7382dd24c"
// SetDefaultSSHPublicKey sets the default SSHPublicKey for an AzureMachine.
func (s *AzureMachineSpec) SetDefaultSSHPublicKey() error {
if sshKeyData := s.SSHPublicKey; sshKeyData == "" {
_, publicRsaKey, err := utilSSH.GenerateSSHKey()
if err != nil {
return err
}
s.SSHPublicKey = base64.StdEncoding.EncodeToString(ssh.MarshalAuthorizedKey(publicRsaKey))
}
return nil
}
// SetDefaultCachingType sets the default cache type for an AzureMachine.
func (s *AzureMachineSpec) SetDefaultCachingType() {
if s.OSDisk.CachingType == "" {
s.OSDisk.CachingType = "None"
}
}
// SetDataDisksDefaults sets the data disk defaults for an AzureMachine.
func (s *AzureMachineSpec) SetDataDisksDefaults() {
set := make(map[int32]struct{})
// populate all the existing values in the set
for _, disk := range s.DataDisks {
if disk.Lun != nil {
set[*disk.Lun] = struct{}{}
}
}
// Look for unique values for unassigned LUNs
for i, disk := range s.DataDisks {
if disk.Lun == nil {
for l := range s.DataDisks {
lun := int32(l)
if _, ok := set[lun]; !ok {
s.DataDisks[i].Lun = &lun
set[lun] = struct{}{}
break
}
}
}
if disk.CachingType == "" {
if s.DataDisks[i].ManagedDisk != nil &&
s.DataDisks[i].ManagedDisk.StorageAccountType == string(armcompute.StorageAccountTypesUltraSSDLRS) {
s.DataDisks[i].CachingType = string(armcompute.CachingTypesNone)
} else {
s.DataDisks[i].CachingType = string(armcompute.CachingTypesReadWrite)
}
}
}
}
// SetIdentityDefaults sets the defaults for VM Identity.
func (s *AzureMachineSpec) SetIdentityDefaults(subscriptionID string) {
// Ensure the deprecated fields and new fields are not populated simultaneously
if s.RoleAssignmentName != "" && s.SystemAssignedIdentityRole != nil && s.SystemAssignedIdentityRole.Name != "" {
// Both the deprecated and the new fields are both set, return without changes
// and reject the request in the validating webhook which runs later.
return
}
if s.Identity == VMIdentitySystemAssigned {
if s.SystemAssignedIdentityRole == nil {
s.SystemAssignedIdentityRole = &SystemAssignedIdentityRole{}
}
if s.RoleAssignmentName != "" {
// Move the existing value from the deprecated RoleAssignmentName field.
s.SystemAssignedIdentityRole.Name = s.RoleAssignmentName
s.RoleAssignmentName = ""
} else if s.SystemAssignedIdentityRole.Name == "" {
// Default role name to a generated UUID.
s.SystemAssignedIdentityRole.Name = string(uuid.NewUUID())
}
if s.SystemAssignedIdentityRole.Scope == "" && subscriptionID != "" {
// Default scope to the subscription.
s.SystemAssignedIdentityRole.Scope = fmt.Sprintf("/subscriptions/%s/", subscriptionID)
}
if s.SystemAssignedIdentityRole.DefinitionID == "" && subscriptionID != "" {
// Default role definition ID to Contributor role.
s.SystemAssignedIdentityRole.DefinitionID = fmt.Sprintf("/subscriptions/%s/providers/Microsoft.Authorization/roleDefinitions/%s", subscriptionID, ContributorRoleID)
}
}
}
// SetSpotEvictionPolicyDefaults sets the defaults for the spot VM eviction policy.
func (s *AzureMachineSpec) SetSpotEvictionPolicyDefaults() {
if s.SpotVMOptions != nil && s.SpotVMOptions.EvictionPolicy == nil {
defaultPolicy := SpotEvictionPolicyDeallocate
if s.OSDisk.DiffDiskSettings != nil && s.OSDisk.DiffDiskSettings.Option == "Local" {
defaultPolicy = SpotEvictionPolicyDelete
}
s.SpotVMOptions.EvictionPolicy = &defaultPolicy
}
}
// SetDiagnosticsDefaults sets the defaults for Diagnostic settings for an AzureMachinePool.
func (s *AzureMachineSpec) SetDiagnosticsDefaults() {
bootDiagnosticsDefault := &BootDiagnostics{
StorageAccountType: ManagedDiagnosticsStorage,
}
diagnosticsDefault := &Diagnostics{Boot: bootDiagnosticsDefault}
if s.Diagnostics == nil {
s.Diagnostics = diagnosticsDefault
}
if s.Diagnostics.Boot == nil {
s.Diagnostics.Boot = bootDiagnosticsDefault
}
}
// SetNetworkInterfacesDefaults sets the defaults for the network interfaces.
func (s *AzureMachineSpec) SetNetworkInterfacesDefaults() {
// Ensure the deprecated fields and new fields are not populated simultaneously
if (s.SubnetName != "" || s.AcceleratedNetworking != nil) && len(s.NetworkInterfaces) > 0 {
// Both the deprecated and the new fields are both set, return without changes
// and reject the request in the validating webhook which runs later.
return
}
if len(s.NetworkInterfaces) == 0 {
s.NetworkInterfaces = []NetworkInterface{
{
SubnetName: s.SubnetName,
AcceleratedNetworking: s.AcceleratedNetworking,
},
}
s.SubnetName = ""
s.AcceleratedNetworking = nil
}
// Ensure that PrivateIPConfigs defaults to 1 if not specified.
for i := 0; i < len(s.NetworkInterfaces); i++ {
if s.NetworkInterfaces[i].PrivateIPConfigs == 0 {
s.NetworkInterfaces[i].PrivateIPConfigs = 1
}
}
}
// GetOwnerAzureClusterNameAndNamespace returns the owner azure cluster's name and namespace for the given cluster name and namespace.
func GetOwnerAzureClusterNameAndNamespace(cli client.Client, clusterName string, namespace string, maxAttempts int) (azureClusterName string, azureClusterNamespace string, err error) {
ctx := context.Background()
ownerCluster := &clusterv1.Cluster{}
key := client.ObjectKey{
Namespace: namespace,
Name: clusterName,
}
for i := 1; ; i++ {
if err := cli.Get(ctx, key, ownerCluster); err != nil {
if i > maxAttempts {
return "", "", errors.Wrapf(err, "failed to find owner cluster for %s/%s", namespace, clusterName)
}
time.Sleep(1 * time.Second)
continue
}
break
}
return ownerCluster.Spec.InfrastructureRef.Name, ownerCluster.Spec.InfrastructureRef.Namespace, nil
}
// GetSubscriptionID returns the subscription ID for the AzureCluster given the cluster name and namespace.
func GetSubscriptionID(cli client.Client, ownerAzureClusterName string, ownerAzureClusterNamespace string, maxAttempts int) (string, error) {
ctx := context.Background()
ownerAzureCluster := &AzureCluster{}
key := client.ObjectKey{
Namespace: ownerAzureClusterNamespace,
Name: ownerAzureClusterName,
}
for i := 1; ; i++ {
if err := cli.Get(ctx, key, ownerAzureCluster); err != nil {
if i >= maxAttempts {
return "", errors.Wrapf(err, "failed to find AzureCluster for owner cluster %s/%s", ownerAzureClusterNamespace, ownerAzureClusterName)
}
time.Sleep(1 * time.Second)
continue
}
break
}
return ownerAzureCluster.Spec.SubscriptionID, nil
}
// SetDefaults sets to the defaults for the AzureMachineSpec.
func (m *AzureMachine) SetDefaults(client client.Client) error {
var errs []error
if err := m.Spec.SetDefaultSSHPublicKey(); err != nil {
errs = append(errs, errors.Wrap(err, "failed to set default SSH public key"))
}
// Fetch the Cluster.
clusterName, ok := m.Labels[clusterv1.ClusterNameLabel]
if !ok {
errs = append(errs, errors.Errorf("failed to fetch ClusterName for AzureMachine %s/%s", m.Namespace, m.Name))
}
ownerAzureClusterName, ownerAzureClusterNamespace, err := GetOwnerAzureClusterNameAndNamespace(client, clusterName, m.Namespace, 5)
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to fetch owner cluster for AzureMachine %s/%s", m.Namespace, m.Name))
}
subscriptionID, err := GetSubscriptionID(client, ownerAzureClusterName, ownerAzureClusterNamespace, 5)
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to fetch subscription ID for AzureMachine %s/%s", m.Namespace, m.Name))
}
m.Spec.SetDefaultCachingType()
m.Spec.SetDataDisksDefaults()
m.Spec.SetIdentityDefaults(subscriptionID)
m.Spec.SetSpotEvictionPolicyDefaults()
m.Spec.SetDiagnosticsDefaults()
m.Spec.SetNetworkInterfacesDefaults()
return kerrors.NewAggregate(errs)
}