forked from Azure/AgentBaker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vmss.go
340 lines (305 loc) · 11.7 KB
/
vmss.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
package e2e_test
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
mrand "math/rand"
"testing"
"github.com/Azure/agentbakere2e/scenario"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute"
"golang.org/x/crypto/ssh"
)
const (
vmssNameTemplate = "abtest%s"
listVMSSNetworkInterfaceURLTemplate = "https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%d/networkInterfaces?api-version=2018-10-01"
loadBalancerBackendAddressPoolIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers/kubernetes/backendAddressPools/aksOutboundBackendPool"
)
func bootstrapVMSS(ctx context.Context, t *testing.T, r *mrand.Rand, vmssName string, opts *scenarioRunOpts, publicKeyBytes []byte) (*armcompute.VirtualMachineScaleSet, func(), error) {
nodeBootstrapping, err := getNodeBootstrapping(ctx, opts.nbc)
if err != nil {
return nil, nil, fmt.Errorf("unable to get node bootstrapping: %w", err)
}
cleanupVMSS := func() {
log.Printf("deleting vmss %q", vmssName)
poller, err := opts.cloud.vmssClient.BeginDelete(ctx, *opts.clusterConfig.cluster.Properties.NodeResourceGroup, vmssName, nil)
if err != nil {
t.Error("error deleting vmss", vmssName, err)
return
}
_, err = poller.PollUntilDone(ctx, nil)
if err != nil {
t.Error("error polling deleting vmss", vmssName, err)
}
log.Printf("finished deleting vmss %q", vmssName)
}
vmssModel, err := createVMSSWithPayload(ctx, nodeBootstrapping.CustomData, nodeBootstrapping.CSE, vmssName, publicKeyBytes, opts)
if err != nil {
return nil, nil, fmt.Errorf("unable to create VMSS with payload: %w", err)
}
return vmssModel, cleanupVMSS, nil
}
func createVMSSWithPayload(ctx context.Context, customData, cseCmd, vmssName string, publicKeyBytes []byte, opts *scenarioRunOpts) (*armcompute.VirtualMachineScaleSet, error) {
model := getBaseVMSSModel(vmssName, opts.suiteConfig.location, opts.suiteConfig.subscription, *opts.clusterConfig.cluster.Properties.NodeResourceGroup, opts.clusterConfig.subnetId, string(publicKeyBytes), customData, cseCmd)
isAzureCNI, err := opts.clusterConfig.isAzureCNI()
if err != nil {
return nil, fmt.Errorf("failed to determine whether chosen cluster uses Azure CNI from cluster model: %w", err)
}
if isAzureCNI {
if err := addPodIPConfigsForAzureCNI(&model, vmssName, opts); err != nil {
return nil, fmt.Errorf("failed to create pod IP configs for azure CNI scenario: %w", err)
}
}
if opts.scenario.VMConfigMutator != nil {
opts.scenario.VMConfigMutator(&model)
}
pollerResp, err := opts.cloud.vmssClient.BeginCreateOrUpdate(
ctx,
*opts.clusterConfig.cluster.Properties.NodeResourceGroup,
vmssName,
model,
nil,
)
if err != nil {
return nil, err
}
vmssResp, err := pollerResp.PollUntilDone(ctx, nil)
if err != nil {
return nil, err
}
return &vmssResp.VirtualMachineScaleSet, nil
}
// Adds additional IP configs to the passed in vmss model based on the chosen cluster's setting of "maxPodsPerNode",
// as we need be able to allow AKS to allocate an additional IP config for each pod running on the given node.
// Additional info: https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni
func addPodIPConfigsForAzureCNI(vmss *armcompute.VirtualMachineScaleSet, vmssName string, opts *scenarioRunOpts) error {
maxPodsPerNode, err := opts.clusterConfig.maxPodsPerNode()
if err != nil {
return fmt.Errorf("failed to read agentpool MaxPods value from chosen cluster model: %w", err)
}
var podIPConfigs []*armcompute.VirtualMachineScaleSetIPConfiguration
for i := 1; i <= maxPodsPerNode; i++ {
ipConfig := &armcompute.VirtualMachineScaleSetIPConfiguration{
Name: to.Ptr(fmt.Sprintf("%s%d", vmssName, i)),
Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{
Subnet: &armcompute.APIEntityReference{
ID: to.Ptr(opts.clusterConfig.subnetId),
},
},
}
podIPConfigs = append(podIPConfigs, ipConfig)
}
vmssNICConfig, err := getVMSSNICConfig(vmss)
if err != nil {
return fmt.Errorf("unable to get vmss nic: %w", err)
}
vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0].Properties.IPConfigurations =
append(vmssNICConfig.Properties.IPConfigurations, podIPConfigs...)
return nil
}
func getVMPrivateIPAddress(ctx context.Context, cloud *azureClient, subscription, mcResourceGroupName, vmssName string) (string, error) {
pl := cloud.coreClient.Pipeline()
url := fmt.Sprintf(listVMSSNetworkInterfaceURLTemplate,
subscription,
mcResourceGroupName,
vmssName,
0,
)
req, err := runtime.NewRequest(ctx, "GET", url)
if err != nil {
return "", err
}
resp, err := pl.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var instanceNICResult listVMSSVMNetworkInterfaceResult
if err := json.Unmarshal(respBytes, &instanceNICResult); err != nil {
return "", err
}
privateIP, err := getPrivateIP(instanceNICResult)
if err != nil {
return "", err
}
return privateIP, nil
}
// Returns a newly generated RSA public/private key pair with the private key in PEM format.
func getNewRSAKeyPair(r *mrand.Rand) (privatePEMBytes []byte, publicKeyBytes []byte, e error) {
privateKey, err := rsa.GenerateKey(r, 4096)
if err != nil {
return nil, nil, fmt.Errorf("failed to create rsa private key: %w", err)
}
err = privateKey.Validate()
if err != nil {
return nil, nil, fmt.Errorf("failed to validate rsa private key: %w", err)
}
publicRsaKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to convert private to public key: %w", err)
}
publicKeyBytes = ssh.MarshalAuthorizedKey(publicRsaKey)
// Get ASN.1 DER format
privDER := x509.MarshalPKCS1PrivateKey(privateKey)
// pem.Block
privBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDER,
}
// Private key in PEM format
privatePEMBytes = pem.EncodeToMemory(&privBlock)
return
}
func getVmssName(r *mrand.Rand) string {
return fmt.Sprintf(vmssNameTemplate, randomLowercaseString(r, 4))
}
func getBaseVMSSModel(name, location, subscription, mcResourceGroupName, subnetID, sshPublicKey, customData, cseCmd string) armcompute.VirtualMachineScaleSet {
return armcompute.VirtualMachineScaleSet{
Location: to.Ptr(location),
SKU: &armcompute.SKU{
Name: to.Ptr("Standard_DS2_v2"),
Capacity: to.Ptr[int64](1),
},
Properties: &armcompute.VirtualMachineScaleSetProperties{
Overprovision: to.Ptr(false),
UpgradePolicy: &armcompute.UpgradePolicy{
Mode: to.Ptr(armcompute.UpgradeModeManual),
},
VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{
ExtensionProfile: &armcompute.VirtualMachineScaleSetExtensionProfile{
Extensions: []*armcompute.VirtualMachineScaleSetExtension{
{
Name: to.Ptr("vmssCSE"),
Properties: &armcompute.VirtualMachineScaleSetExtensionProperties{
Publisher: to.Ptr("Microsoft.Azure.Extensions"),
Type: to.Ptr("CustomScript"),
TypeHandlerVersion: to.Ptr("2.0"),
AutoUpgradeMinorVersion: to.Ptr(true),
Settings: map[string]interface{}{},
ProtectedSettings: map[string]interface{}{
"commandToExecute": cseCmd,
},
},
},
},
},
OSProfile: &armcompute.VirtualMachineScaleSetOSProfile{
ComputerNamePrefix: to.Ptr(name),
AdminUsername: to.Ptr("azureuser"),
CustomData: &customData,
LinuxConfiguration: &armcompute.LinuxConfiguration{
SSH: &armcompute.SSHConfiguration{
PublicKeys: []*armcompute.SSHPublicKey{
{
KeyData: to.Ptr(sshPublicKey),
Path: to.Ptr("/home/azureuser/.ssh/authorized_keys"),
},
},
},
},
},
StorageProfile: &armcompute.VirtualMachineScaleSetStorageProfile{
ImageReference: &armcompute.ImageReference{
ID: to.Ptr(scenario.DefaultImageVersionIDs["ubuntu1804"]),
},
OSDisk: &armcompute.VirtualMachineScaleSetOSDisk{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
DiskSizeGB: to.Ptr(int32(512)),
OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
},
},
NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{
NetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{
{
Name: to.Ptr(name),
Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.Ptr(true),
EnableIPForwarding: to.Ptr(true),
IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{
{
Name: to.Ptr(fmt.Sprintf("%s0", name)),
Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.Ptr(true),
LoadBalancerBackendAddressPools: []*armcompute.SubResource{
{
ID: to.Ptr(
fmt.Sprintf(
loadBalancerBackendAddressPoolIDTemplate,
subscription,
mcResourceGroupName,
),
),
},
},
Subnet: &armcompute.APIEntityReference{
ID: to.Ptr(subnetID),
},
},
},
},
},
},
},
},
},
},
}
}
type listVMSSVMNetworkInterfaceResult struct {
Value []struct {
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
Properties struct {
ProvisioningState string `json:"provisioningState,omitempty"`
IPConfigurations []struct {
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
Properties struct {
ProvisioningState string `json:"provisioningState,omitempty"`
PrivateIPAddress string `json:"privateIPAddress,omitempty"`
PrivateIPAllocationMethod string `json:"privateIPAllocationMethod,omitempty"`
PublicIPAddress struct {
ID string `json:"id,omitempty"`
} `json:"publicIPAddress,omitempty"`
Subnet struct {
ID string `json:"id,omitempty"`
} `json:"subnet,omitempty"`
Primary bool `json:"primary,omitempty"`
PrivateIPAddressVersion string `json:"privateIPAddressVersion,omitempty"`
LoadBalancerBackendAddressPools []struct {
ID string `json:"id,omitempty"`
} `json:"loadBalancerBackendAddressPools,omitempty"`
LoadBalancerInboundNatRules []struct {
ID string `json:"id,omitempty"`
} `json:"loadBalancerInboundNatRules,omitempty"`
} `json:"properties,omitempty"`
} `json:"ipConfigurations,omitempty"`
DNSSettings struct {
DNSServers []interface{} `json:"dnsServers,omitempty"`
AppliedDNSServers []interface{} `json:"appliedDnsServers,omitempty"`
InternalDomainNameSuffix string `json:"internalDomainNameSuffix,omitempty"`
} `json:"dnsSettings,omitempty"`
MacAddress string `json:"macAddress,omitempty"`
EnableAcceleratedNetworking bool `json:"enableAcceleratedNetworking,omitempty"`
EnableIPForwarding bool `json:"enableIPForwarding,omitempty"`
NetworkSecurityGroup struct {
ID string `json:"id,omitempty"`
} `json:"networkSecurityGroup,omitempty"`
Primary bool `json:"primary,omitempty"`
VirtualMachine struct {
ID string `json:"id,omitempty"`
} `json:"virtualMachine,omitempty"`
} `json:"properties,omitempty"`
} `json:"value,omitempty"`
}