forked from kubernetes/autoscaler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
azure_util.go
604 lines (510 loc) · 18.1 KB
/
azure_util.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
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
/*
Copyright 2017 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 azure
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
azStorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/glog"
"golang.org/x/crypto/pkcs12"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider"
"k8s.io/client-go/pkg/version"
)
const (
//Field names
customDataFieldName = "customData"
dependsOnFieldName = "dependsOn"
hardwareProfileFieldName = "hardwareProfile"
imageReferenceFieldName = "imageReference"
nameFieldName = "name"
osProfileFieldName = "osProfile"
propertiesFieldName = "properties"
resourcesFieldName = "resources"
storageProfileFieldName = "storageProfile"
typeFieldName = "type"
vmSizeFieldName = "vmSize"
// ARM resource Types
nsgResourceType = "Microsoft.Network/networkSecurityGroups"
rtResourceType = "Microsoft.Network/routeTables"
vmResourceType = "Microsoft.Compute/virtualMachines"
vmExtensionType = "Microsoft.Compute/virtualMachines/extensions"
// resource ids
nsgID = "nsgID"
rtID = "routeTableID"
k8sLinuxVMNamingFormat = "^[0-9a-zA-Z]{3}-(.+)-([0-9a-fA-F]{8})-{0,2}([0-9]+)$"
k8sLinuxVMAgentPoolNameIndex = 1
k8sLinuxVMAgentClusterIDIndex = 2
k8sLinuxVMAgentIndexArrayIndex = 3
k8sWindowsVMNamingFormat = "^([a-fA-F0-9]{5})([0-9a-zA-Z]{3})([a-zA-Z0-9]{4,6})$"
k8sWindowsVMAgentPoolPrefixIndex = 1
k8sWindowsVMAgentOrchestratorNameIndex = 2
k8sWindowsVMAgentPoolInfoIndex = 3
)
var (
vmnameLinuxRegexp = regexp.MustCompile(k8sLinuxVMNamingFormat)
vmnameWindowsRegexp = regexp.MustCompile(k8sWindowsVMNamingFormat)
)
//AzUtil consists of utility functions which utilizes clients to different services.
//Since they span across various clients they cannot be fitted into individual client structs
//so adding them here.
type AzUtil struct {
manager *AzureManager
}
// DeleteBlob deletes the blob using the storage storage client.
func (util *AzUtil) DeleteBlob(accountName, vhdContainer, vhdBlob string) error {
ctx, cancel := getContextWithCancel()
defer cancel()
storageKeysResult, err := util.manager.azClient.storageAccountsClient.ListKeys(ctx, util.manager.config.ResourceGroup, accountName)
if err != nil {
return err
}
keys := *storageKeysResult.Keys
client, err := azStorage.NewBasicClientOnSovereignCloud(accountName, to.String(keys[0].Value), util.manager.env)
if err != nil {
return err
}
bs := client.GetBlobService()
containerRef := bs.GetContainerReference(vhdContainer)
blobRef := containerRef.GetBlobReference(vhdBlob)
return blobRef.Delete(&azStorage.DeleteBlobOptions{})
}
// DeleteVirtualMachine deletes a VM and any associated OS disk
func (util *AzUtil) DeleteVirtualMachine(rg string, name string) error {
ctx, cancel := getContextWithCancel()
defer cancel()
vm, err := util.manager.azClient.virtualMachinesClient.Get(ctx, rg, name, "")
if err != nil {
if exists, _ := checkResourceExistsFromError(err); !exists {
glog.V(2).Infof("VirtualMachine %s/%s has already been removed", rg, name)
return nil
}
glog.Errorf("failed to get VM: %s/%s: %s", rg, name, err.Error())
return err
}
vhd := vm.VirtualMachineProperties.StorageProfile.OsDisk.Vhd
managedDisk := vm.VirtualMachineProperties.StorageProfile.OsDisk.ManagedDisk
if vhd == nil && managedDisk == nil {
glog.Errorf("failed to get a valid os disk URI for VM: %s/%s", rg, name)
return fmt.Errorf("os disk does not have a VHD URI")
}
osDiskName := vm.VirtualMachineProperties.StorageProfile.OsDisk.Name
var nicName string
nicID := (*vm.VirtualMachineProperties.NetworkProfile.NetworkInterfaces)[0].ID
if nicID == nil {
glog.Warningf("NIC ID is not set for VM (%s/%s)", rg, name)
} else {
nicName, err = resourceName(*nicID)
if err != nil {
return err
}
glog.Infof("found nic name for VM (%s/%s): %s", rg, name, nicName)
}
glog.Infof("deleting VM: %s/%s", rg, name)
deleteCtx, deleteCancel := getContextWithCancel()
defer deleteCancel()
glog.Infof("waiting for VirtualMachine deletion: %s/%s", rg, name)
_, err = util.manager.azClient.virtualMachinesClient.Delete(deleteCtx, rg, name)
_, realErr := checkResourceExistsFromError(err)
if realErr != nil {
return realErr
}
glog.V(2).Infof("VirtualMachine %s/%s removed", rg, name)
if len(nicName) > 0 {
glog.Infof("deleting nic: %s/%s", rg, nicName)
interfaceCtx, interfaceCancel := getContextWithCancel()
defer interfaceCancel()
glog.Infof("waiting for nic deletion: %s/%s", rg, nicName)
_, nicErr := util.manager.azClient.interfacesClient.Delete(interfaceCtx, rg, nicName)
_, realErr := checkResourceExistsFromError(nicErr)
if realErr != nil {
return realErr
}
glog.V(2).Infof("interface %s/%s removed", rg, nicName)
}
if vhd != nil {
accountName, vhdContainer, vhdBlob, err := splitBlobURI(*vhd.URI)
if err != nil {
return err
}
glog.Infof("found os disk storage reference: %s %s %s", accountName, vhdContainer, vhdBlob)
glog.Infof("deleting blob: %s/%s", vhdContainer, vhdBlob)
if err = util.DeleteBlob(accountName, vhdContainer, vhdBlob); err != nil {
_, realErr := checkResourceExistsFromError(err)
if realErr != nil {
return realErr
}
glog.V(2).Infof("Blob %s/%s removed", rg, vhdBlob)
}
} else if managedDisk != nil {
if osDiskName == nil {
glog.Warningf("osDisk is not set for VM %s/%s", rg, name)
} else {
glog.Infof("deleting managed disk: %s/%s", rg, *osDiskName)
disksCtx, disksCancel := getContextWithCancel()
defer disksCancel()
_, diskErr := util.manager.azClient.disksClient.Delete(disksCtx, rg, *osDiskName)
_, realErr := checkResourceExistsFromError(diskErr)
if realErr != nil {
return realErr
}
glog.V(2).Infof("disk %s/%s removed", rg, *osDiskName)
}
}
return nil
}
// decodePkcs12 decodes a PKCS#12 client certificate by extracting the public certificate and
// the private RSA key
func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) {
privateKey, certificate, err := pkcs12.Decode(pkcs, password)
if err != nil {
return nil, nil, fmt.Errorf("decoding the PKCS#12 client certificate: %v", err)
}
rsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey)
if !isRsaKey {
return nil, nil, fmt.Errorf("PKCS#12 certificate must contain a RSA private key")
}
return certificate, rsaPrivateKey, nil
}
// configureUserAgent configures the autorest client with a user agent that
// includes "autoscaler" and the full client version string
// example:
// Azure-SDK-for-Go/7.0.1-beta arm-network/2016-09-01; cluster-autoscaler/v1.7.0-alpha.2.711+a2fadef8170bb0-dirty;
func configureUserAgent(client *autorest.Client) {
k8sVersion := version.Get().GitVersion
client.UserAgent = fmt.Sprintf("%s; cluster-autoscaler/%s", client.UserAgent, k8sVersion)
}
// normalizeForK8sVMASScalingUp takes a template and removes elements that are unwanted in a K8s VMAS scale up/down case
func normalizeForK8sVMASScalingUp(templateMap map[string]interface{}) error {
if err := normalizeMasterResourcesForScaling(templateMap); err != nil {
return err
}
rtIndex := -1
nsgIndex := -1
resources := templateMap[resourcesFieldName].([]interface{})
for index, resource := range resources {
resourceMap, ok := resource.(map[string]interface{})
if !ok {
glog.Warning("Template improperly formatted for resource")
continue
}
resourceType, ok := resourceMap[typeFieldName].(string)
if ok && resourceType == nsgResourceType {
if nsgIndex != -1 {
err := fmt.Errorf("Found 2 resources with type %s in the template. There should only be 1", nsgResourceType)
glog.Errorf(err.Error())
return err
}
nsgIndex = index
}
if ok && resourceType == rtResourceType {
if rtIndex != -1 {
err := fmt.Errorf("Found 2 resources with type %s in the template. There should only be 1", rtResourceType)
glog.Warningf(err.Error())
return err
}
rtIndex = index
}
dependencies, ok := resourceMap[dependsOnFieldName].([]interface{})
if !ok {
continue
}
for dIndex := len(dependencies) - 1; dIndex >= 0; dIndex-- {
dependency := dependencies[dIndex].(string)
if strings.Contains(dependency, nsgResourceType) || strings.Contains(dependency, nsgID) ||
strings.Contains(dependency, rtResourceType) || strings.Contains(dependency, rtID) {
dependencies = append(dependencies[:dIndex], dependencies[dIndex+1:]...)
}
}
if len(dependencies) > 0 {
resourceMap[dependsOnFieldName] = dependencies
} else {
delete(resourceMap, dependsOnFieldName)
}
}
indexesToRemove := []int{}
if nsgIndex == -1 {
err := fmt.Errorf("Found no resources with type %s in the template. There should have been 1", nsgResourceType)
glog.Errorf(err.Error())
return err
}
if rtIndex == -1 {
glog.Infof("Found no resources with type %s in the template.", rtResourceType)
} else {
indexesToRemove = append(indexesToRemove, rtIndex)
}
indexesToRemove = append(indexesToRemove, nsgIndex)
templateMap[resourcesFieldName] = removeIndexesFromArray(resources, indexesToRemove)
return nil
}
func removeIndexesFromArray(array []interface{}, indexes []int) []interface{} {
sort.Sort(sort.Reverse(sort.IntSlice(indexes)))
for _, index := range indexes {
array = append(array[:index], array[index+1:]...)
}
return array
}
// normalizeMasterResourcesForScaling takes a template and removes elements that are unwanted in any scale up/down case
func normalizeMasterResourcesForScaling(templateMap map[string]interface{}) error {
resources := templateMap[resourcesFieldName].([]interface{})
indexesToRemove := []int{}
//update master nodes resources
for index, resource := range resources {
resourceMap, ok := resource.(map[string]interface{})
if !ok {
glog.Warning("Template improperly formatted")
continue
}
resourceType, ok := resourceMap[typeFieldName].(string)
if !ok || resourceType != vmResourceType {
resourceName, ok := resourceMap[nameFieldName].(string)
if !ok {
glog.Warning("Template improperly formatted")
continue
}
if strings.Contains(resourceName, "variables('masterVMNamePrefix')") && resourceType == vmExtensionType {
indexesToRemove = append(indexesToRemove, index)
}
continue
}
resourceName, ok := resourceMap[nameFieldName].(string)
if !ok {
glog.Warning("Template improperly formatted")
continue
}
// make sure this is only modifying the master vms
if !strings.Contains(resourceName, "variables('masterVMNamePrefix')") {
continue
}
resourceProperties, ok := resourceMap[propertiesFieldName].(map[string]interface{})
if !ok {
glog.Warning("Template improperly formatted")
continue
}
hardwareProfile, ok := resourceProperties[hardwareProfileFieldName].(map[string]interface{})
if !ok {
glog.Warning("Template improperly formatted")
continue
}
if hardwareProfile[vmSizeFieldName] != nil {
delete(hardwareProfile, vmSizeFieldName)
}
if !removeCustomData(resourceProperties) || !removeImageReference(resourceProperties) {
continue
}
}
templateMap[resourcesFieldName] = removeIndexesFromArray(resources, indexesToRemove)
return nil
}
func removeCustomData(resourceProperties map[string]interface{}) bool {
osProfile, ok := resourceProperties[osProfileFieldName].(map[string]interface{})
if !ok {
glog.Warning("Template improperly formatted")
return ok
}
if osProfile[customDataFieldName] != nil {
delete(osProfile, customDataFieldName)
}
return ok
}
func removeImageReference(resourceProperties map[string]interface{}) bool {
storageProfile, ok := resourceProperties[storageProfileFieldName].(map[string]interface{})
if !ok {
glog.Warningf("Template improperly formatted. Could not find: %s", storageProfileFieldName)
return ok
}
if storageProfile[imageReferenceFieldName] != nil {
delete(storageProfile, imageReferenceFieldName)
}
return ok
}
// resourceName returns the last segment (the resource name) for the specified resource identifier.
func resourceName(ID string) (string, error) {
parts := strings.Split(ID, "/")
name := parts[len(parts)-1]
if len(name) == 0 {
return "", fmt.Errorf("resource name was missing from identifier")
}
return name, nil
}
// splitBlobURI returns a decomposed blob URI parts: accountName, containerName, blobName.
func splitBlobURI(URI string) (string, string, string, error) {
uri, err := url.Parse(URI)
if err != nil {
return "", "", "", err
}
accountName := strings.Split(uri.Host, ".")[0]
urlParts := strings.Split(uri.Path, "/")
containerName := urlParts[1]
blobPath := strings.Join(urlParts[2:], "/")
return accountName, containerName, blobPath, nil
}
// k8sLinuxVMNameParts returns parts of Linux VM name e.g: k8s-agentpool1-11290731-0
func k8sLinuxVMNameParts(vmName string) (poolIdentifier, nameSuffix string, agentIndex int, err error) {
vmNameParts := vmnameLinuxRegexp.FindStringSubmatch(vmName)
if len(vmNameParts) != 4 {
return "", "", -1, fmt.Errorf("resource name was missing from identifier")
}
vmNum, err := strconv.Atoi(vmNameParts[k8sLinuxVMAgentIndexArrayIndex])
if err != nil {
return "", "", -1, fmt.Errorf("Error parsing VM Name: %v", err)
}
return vmNameParts[k8sLinuxVMAgentPoolNameIndex], vmNameParts[k8sLinuxVMAgentClusterIDIndex], vmNum, nil
}
// windowsVMNameParts returns parts of Windows VM name e.g: 50621k8s9000
func windowsVMNameParts(vmName string) (poolPrefix string, acsStr string, poolIndex int, agentIndex int, err error) {
vmNameParts := vmnameWindowsRegexp.FindStringSubmatch(vmName)
if len(vmNameParts) != 4 {
return "", "", -1, -1, fmt.Errorf("resource name was missing from identifier")
}
poolPrefix = vmNameParts[k8sWindowsVMAgentPoolPrefixIndex]
acsStr = vmNameParts[k8sWindowsVMAgentOrchestratorNameIndex]
poolInfo := vmNameParts[k8sWindowsVMAgentPoolInfoIndex]
poolIndex, err = strconv.Atoi(poolInfo[:3])
if err != nil {
return "", "", -1, -1, fmt.Errorf("Error parsing VM Name: %v", err)
}
agentIndex, err = strconv.Atoi(poolInfo[3:])
if err != nil {
return "", "", -1, -1, fmt.Errorf("Error parsing VM Name: %v", err)
}
return poolPrefix, acsStr, poolIndex, agentIndex, nil
}
// GetVMNameIndex return the index of VM in the node pools.
func GetVMNameIndex(osType compute.OperatingSystemTypes, vmName string) (int, error) {
var agentIndex int
var err error
if osType == compute.Linux {
_, _, agentIndex, err = k8sLinuxVMNameParts(vmName)
if err != nil {
return 0, err
}
} else if osType == compute.Windows {
_, _, _, agentIndex, err = windowsVMNameParts(vmName)
if err != nil {
return 0, err
}
}
return agentIndex, nil
}
func matchDiscoveryConfig(labels map[string]*string, configs []cloudprovider.LabelAutoDiscoveryConfig) bool {
if len(configs) == 0 {
return false
}
for _, c := range configs {
if len(c.Selector) == 0 {
return false
}
for k, v := range c.Selector {
value, ok := labels[k]
if !ok {
return false
}
if len(v) > 0 {
if value == nil || *value != v {
return false
}
}
}
}
return true
}
func validateConfig(cfg *Config) error {
if cfg.ResourceGroup == "" {
return fmt.Errorf("resource group not set")
}
if cfg.SubscriptionID == "" {
return fmt.Errorf("subscription ID not set")
}
if cfg.UseManagedIdentityExtension {
return nil
}
if cfg.TenantID == "" {
return fmt.Errorf("tenant ID not set")
}
if cfg.AADClientID == "" {
return fmt.Errorf("ARM Client ID not set")
}
if cfg.VMType == vmTypeStandard {
if cfg.Deployment == "" {
return fmt.Errorf("deployment not set")
}
if len(cfg.DeploymentParameters) == 0 {
return fmt.Errorf("deploymentParameters not set")
}
}
if cfg.VMType == vmTypeACS || cfg.VMType == vmTypeAKS {
// Cluster name is a mandatory param to proceed.
if cfg.ClusterName == "" {
return fmt.Errorf("Cluster name not set for type %+v", cfg.VMType)
}
}
return nil
}
// getLastSegment gets the last segment (splitting by '/'.)
func getLastSegment(ID string) (string, error) {
parts := strings.Split(strings.TrimSpace(ID), "/")
name := parts[len(parts)-1]
if len(name) == 0 {
return "", fmt.Errorf("identifier '/' not found in resource name %q", ID)
}
return name, nil
}
// readDeploymentParameters gets deployment parameters from paramFilePath.
func readDeploymentParameters(paramFilePath string) (map[string]interface{}, error) {
contents, err := ioutil.ReadFile(paramFilePath)
if err != nil {
glog.Errorf("Failed to read deployment parameters from file %q: %v", paramFilePath, err)
return nil, err
}
deploymentParameters := make(map[string]interface{})
if err := json.Unmarshal(contents, &deploymentParameters); err != nil {
glog.Errorf("Failed to unmarshal deployment parameters from file %q: %v", paramFilePath, err)
return nil, err
}
if v, ok := deploymentParameters["parameters"]; ok {
return v.(map[string]interface{}), nil
}
return nil, fmt.Errorf("failed to get deployment parameters from file %s", paramFilePath)
}
func getContextWithCancel() (context.Context, context.CancelFunc) {
return context.WithCancel(context.Background())
}
// checkExistsFromError inspects an error and returns a true if err is nil,
// false if error is an autorest.Error with StatusCode=404 and will return the
// error back if error is another status code or another type of error.
func checkResourceExistsFromError(err error) (bool, error) {
if err == nil {
return true, nil
}
v, ok := err.(autorest.DetailedError)
if !ok {
return false, err
}
if v.StatusCode == http.StatusNotFound {
return false, nil
}
return false, v
}