-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
vmscaleset.go
393 lines (354 loc) · 12.1 KB
/
vmscaleset.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
/*
Copyright 2020 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 azuretasks
import (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/klog/v2"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/azure"
)
// SubnetID contains the resource ID/names required to construct a subnet ID.
type SubnetID struct {
SubscriptionID string
ResourceGroupName string
VirtualNetworkName string
SubnetName string
}
// String returns the subnet ID in the path format.
func (s *SubnetID) String() string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s",
s.SubscriptionID,
s.ResourceGroupName,
s.VirtualNetworkName,
s.SubnetName)
}
// ParseSubnetID parses a given subnet ID string and returns a SubnetID.
func ParseSubnetID(s string) (*SubnetID, error) {
l := strings.Split(s, "/")
if len(l) != 11 {
return nil, fmt.Errorf("malformed format of subnet ID: %s, %d", s, len(l))
}
return &SubnetID{
SubscriptionID: l[2],
ResourceGroupName: l[4],
VirtualNetworkName: l[8],
SubnetName: l[10],
}, nil
}
// loadBalancerID contains the resource ID/names required to construct a loadbalancer ID.
type loadBalancerID struct {
SubscriptionID string
ResourceGroupName string
LoadBalancerName string
}
// String returns the loadbalancer ID in the path format.
func (lb *loadBalancerID) String() string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadbalancers/%s/backendAddressPools/LoadBalancerBackEnd",
lb.SubscriptionID,
lb.ResourceGroupName,
lb.LoadBalancerName,
)
}
// parseLoadBalancerID parses a given loadbalancer ID string and returns a loadBalancerID.
func parseLoadBalancerID(lb string) (*loadBalancerID, error) {
l := strings.Split(lb, "/")
if len(l) != 11 {
return nil, fmt.Errorf("malformed format of loadbalancer ID: %s, %d", lb, len(l))
}
return &loadBalancerID{
SubscriptionID: l[2],
ResourceGroupName: l[4],
LoadBalancerName: l[8],
}, nil
}
// VMScaleSet is an Azure VM Scale Set.
// +kops:fitask
type VMScaleSet struct {
Name *string
Lifecycle fi.Lifecycle
ResourceGroup *ResourceGroup
VirtualNetwork *VirtualNetwork
Subnet *Subnet
StorageProfile *VMScaleSetStorageProfile
// RequirePublicIP is set to true when VMs require public IPs.
RequirePublicIP *bool
// LoadBalancer is the Load Balancer object the VMs will use.
LoadBalancer *LoadBalancer
// SKUName specifies the SKU of of the VM Scale Set
SKUName *string
// Capacity specifies the number of virtual machines the VM Scale Set.
Capacity *int64
// ComputerNamePrefix is the prefix of each VM name of the form <prefix><base-36-instance-id>.
// See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-instance-ids.
ComputerNamePrefix *string
// AdmnUser specifies the name of the administrative account.
AdminUser *string
SSHPublicKey *string
// UserData is the user data configuration
UserData fi.Resource
Tags map[string]*string
Zones []string
PrincipalID *string
}
var _ fi.CloudupTaskNormalize = &VMScaleSet{}
// VMScaleSetStorageProfile wraps *compute.VirtualMachineScaleSetStorageProfile
// and implements fi.HasDependencies.
//
// If we don't implement the interface and directly use
// compute.VirtualMachineScaleSetStorageProfile in VMScaleSet, the
// topological sort on VMScaleSet will fail as StorageProfile doesn't
// implement a proper interface.
type VMScaleSetStorageProfile struct {
*compute.VirtualMachineScaleSetStorageProfile
}
var _ fi.CloudupHasDependencies = &VMScaleSetStorageProfile{}
// GetDependencies returns a slice of tasks on which the tasks depends on.
func (p *VMScaleSetStorageProfile) GetDependencies(tasks map[string]fi.CloudupTask) []fi.CloudupTask {
return nil
}
var (
_ fi.CloudupTask = &VMScaleSet{}
_ fi.CompareWithID = &VMScaleSet{}
)
// CompareWithID returns the Name of the VM Scale Set.
func (s *VMScaleSet) CompareWithID() *string {
return s.Name
}
// Find discovers the VMScaleSet in the cloud provider.
func (s *VMScaleSet) Find(c *fi.CloudupContext) (*VMScaleSet, error) {
cloud := c.T.Cloud.(azure.AzureCloud)
found, err := cloud.VMScaleSet().Get(context.TODO(), *s.ResourceGroup.Name, *s.Name)
if err != nil && !strings.Contains(err.Error(), "ResourceNotFound") {
return nil, err
}
if found == nil {
return nil, nil
}
profile := found.VirtualMachineProfile
nwConfigs := *profile.NetworkProfile.NetworkInterfaceConfigurations
if len(nwConfigs) != 1 {
return nil, fmt.Errorf("unexpected number of network configs found for VM ScaleSet %s: %d", *s.Name, len(nwConfigs))
}
nwConfig := nwConfigs[0]
ipConfigs := *nwConfig.VirtualMachineScaleSetNetworkConfigurationProperties.IPConfigurations
if len(ipConfigs) != 1 {
return nil, fmt.Errorf("unexpected number of IP configs found for VM ScaleSet %s: %d", *s.Name, len(ipConfigs))
}
ipConfig := ipConfigs[0]
subnetID, err := ParseSubnetID(*ipConfig.Subnet.ID)
if err != nil {
return nil, fmt.Errorf("failed to parse subnet ID %s", *ipConfig.Subnet.ID)
}
var loadBalancerID *loadBalancerID
if ipConfig.LoadBalancerBackendAddressPools != nil {
for _, i := range *ipConfig.LoadBalancerBackendAddressPools {
if !strings.Contains(*i.ID, "api") {
continue
}
loadBalancerID, err = parseLoadBalancerID(*i.ID)
if err != nil {
return nil, fmt.Errorf("failed to parse loadbalancer ID %s", *ipConfig.Subnet.ID)
}
}
}
osProfile := profile.OsProfile
sshKeys := *osProfile.LinuxConfiguration.SSH.PublicKeys
if len(sshKeys) != 1 {
return nil, fmt.Errorf("unexpected number of SSH keys found for VM ScaleSet %s: %d", *s.Name, len(sshKeys))
}
userData, err := base64.StdEncoding.DecodeString(*profile.UserData)
if err != nil {
return nil, fmt.Errorf("failed to decode user data: %w", err)
}
vmss := &VMScaleSet{
Name: s.Name,
Lifecycle: s.Lifecycle,
ResourceGroup: &ResourceGroup{
Name: s.ResourceGroup.Name,
},
VirtualNetwork: &VirtualNetwork{
Name: to.StringPtr(subnetID.VirtualNetworkName),
},
Subnet: &Subnet{
Name: to.StringPtr(subnetID.SubnetName),
},
StorageProfile: &VMScaleSetStorageProfile{
VirtualMachineScaleSetStorageProfile: profile.StorageProfile,
},
RequirePublicIP: to.BoolPtr(ipConfig.PublicIPAddressConfiguration != nil),
SKUName: found.Sku.Name,
Capacity: found.Sku.Capacity,
ComputerNamePrefix: osProfile.ComputerNamePrefix,
AdminUser: osProfile.AdminUsername,
SSHPublicKey: sshKeys[0].KeyData,
UserData: fi.NewBytesResource(userData),
Tags: found.Tags,
PrincipalID: found.Identity.PrincipalID,
}
if loadBalancerID != nil {
vmss.LoadBalancer = &LoadBalancer{
Name: to.StringPtr(loadBalancerID.LoadBalancerName),
}
}
if found.Zones != nil {
vmss.Zones = *found.Zones
}
s.PrincipalID = found.Identity.PrincipalID
return vmss, nil
}
func (s *VMScaleSet) Normalize(c *fi.CloudupContext) error {
c.T.Cloud.(azure.AzureCloud).AddClusterTags(s.Tags)
return nil
}
// Run implements fi.Task.Run.
func (s *VMScaleSet) Run(c *fi.CloudupContext) error {
return fi.CloudupDefaultDeltaRunMethod(s, c)
}
// CheckChanges returns an error if a change is not allowed.
func (s *VMScaleSet) CheckChanges(a, e, changes *VMScaleSet) error {
if a == nil {
// Check if required fields are set when a new resource is created.
if e.Name == nil {
return fi.RequiredField("Name")
}
return nil
}
// Check if unchangeable fields won't be changed.
if changes.Name != nil {
return fi.CannotChangeField("Name")
}
return nil
}
// RenderAzure creates or updates a VM Scale Set.
func (s *VMScaleSet) RenderAzure(t *azure.AzureAPITarget, a, e, changes *VMScaleSet) error {
if a == nil {
klog.Infof("Creating a new VM Scale Set with name: %s", fi.ValueOf(e.Name))
} else {
klog.Infof("Updating a VM Scale Set with name: %s", fi.ValueOf(e.Name))
}
name := *e.Name
var customData *string
if e.UserData != nil {
d, err := fi.ResourceAsBytes(e.UserData)
if err != nil {
return fmt.Errorf("error rendering UserData: %s", err)
}
customData = to.StringPtr(base64.StdEncoding.EncodeToString(d))
}
osProfile := &compute.VirtualMachineScaleSetOSProfile{
ComputerNamePrefix: e.ComputerNamePrefix,
AdminUsername: e.AdminUser,
LinuxConfiguration: &compute.LinuxConfiguration{
SSH: &compute.SSHConfiguration{
PublicKeys: &[]compute.SSHPublicKey{
{
Path: to.StringPtr(fmt.Sprintf("/home/%s/.ssh/authorized_keys", *e.AdminUser)),
KeyData: to.StringPtr(*e.SSHPublicKey),
},
},
},
DisablePasswordAuthentication: to.BoolPtr(true),
},
}
subnetID := SubnetID{
SubscriptionID: t.Cloud.SubscriptionID(),
ResourceGroupName: *e.ResourceGroup.Name,
VirtualNetworkName: *e.VirtualNetwork.Name,
SubnetName: *e.Subnet.Name,
}
ipConfigProperties := &compute.VirtualMachineScaleSetIPConfigurationProperties{
Subnet: &compute.APIEntityReference{
ID: to.StringPtr(subnetID.String()),
},
Primary: to.BoolPtr(true),
PrivateIPAddressVersion: compute.IPv4,
}
if *e.RequirePublicIP {
ipConfigProperties.PublicIPAddressConfiguration = &compute.VirtualMachineScaleSetPublicIPAddressConfiguration{
Name: to.StringPtr(name + "-publicipconfig"),
VirtualMachineScaleSetPublicIPAddressConfigurationProperties: &compute.VirtualMachineScaleSetPublicIPAddressConfigurationProperties{
PublicIPAddressVersion: compute.IPv4,
},
}
}
if e.LoadBalancer != nil {
loadBalancerID := loadBalancerID{
SubscriptionID: t.Cloud.SubscriptionID(),
ResourceGroupName: *e.ResourceGroup.Name,
LoadBalancerName: *e.LoadBalancer.Name,
}
ipConfigProperties.LoadBalancerBackendAddressPools = &[]compute.SubResource{
{
ID: to.StringPtr(loadBalancerID.String()),
},
}
}
networkConfig := compute.VirtualMachineScaleSetNetworkConfiguration{
Name: to.StringPtr(name + "-netconfig"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(true),
EnableIPForwarding: to.BoolPtr(true),
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{
Name: to.StringPtr(name + "-ipconfig"),
VirtualMachineScaleSetIPConfigurationProperties: ipConfigProperties,
},
},
},
}
vmss := compute.VirtualMachineScaleSet{
Location: to.StringPtr(t.Cloud.Region()),
Sku: &compute.Sku{
Name: e.SKUName,
Capacity: e.Capacity,
},
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
UpgradePolicy: &compute.UpgradePolicy{
Mode: compute.UpgradeModeManual,
},
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{
OsProfile: osProfile,
StorageProfile: e.StorageProfile.VirtualMachineScaleSetStorageProfile,
UserData: customData,
NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{
NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{
networkConfig,
},
},
},
},
// Assign a system-assigned managed identity so that
// Azure creates an identity for VMs and provision
// its credentials on the VMs.
Identity: &compute.VirtualMachineScaleSetIdentity{
Type: compute.ResourceIdentityTypeSystemAssigned,
},
Tags: e.Tags,
Zones: &e.Zones,
}
result, err := t.Cloud.VMScaleSet().CreateOrUpdate(
context.TODO(),
*e.ResourceGroup.Name,
name,
vmss)
if err != nil {
return err
}
e.PrincipalID = result.Identity.PrincipalID
return nil
}