forked from Azure/aks-engine
/
scale.go
493 lines (423 loc) · 15.5 KB
/
scale.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package cmd
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/Azure/aks-engine/pkg/api"
"github.com/Azure/aks-engine/pkg/armhelpers"
"github.com/Azure/aks-engine/pkg/armhelpers/utils"
"github.com/Azure/aks-engine/pkg/engine"
"github.com/Azure/aks-engine/pkg/engine/transform"
"github.com/Azure/aks-engine/pkg/helpers"
"github.com/Azure/aks-engine/pkg/i18n"
"github.com/Azure/aks-engine/pkg/operations"
"github.com/leonelquinteros/gotext"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type scaleCmd struct {
authArgs
// user input
apiModelPath string
resourceGroupName string
newDesiredAgentCount int
deploymentDirectory string
location string
agentPoolToScale string
masterFQDN string
// derived
containerService *api.ContainerService
apiVersion string
agentPool *api.AgentPoolProfile
client armhelpers.AKSEngineClient
locale *gotext.Locale
nameSuffix string
agentPoolIndex int
logger *log.Entry
}
const (
scaleName = "scale"
scaleShortDescription = "Scale an existing Kubernetes cluster"
scaleLongDescription = "Scale an existing Kubernetes cluster by specifying increasing or decreasing the node count of an agentpool"
apiModelFilename = "apimodel.json"
)
// NewScaleCmd run a command to upgrade a Kubernetes cluster
func newScaleCmd() *cobra.Command {
sc := scaleCmd{}
scaleCmd := &cobra.Command{
Use: scaleName,
Short: scaleShortDescription,
Long: scaleLongDescription,
RunE: sc.run,
}
f := scaleCmd.Flags()
f.StringVarP(&sc.location, "location", "l", "", "location the cluster is deployed in")
f.StringVarP(&sc.resourceGroupName, "resource-group", "g", "", "the resource group where the cluster is deployed")
f.StringVarP(&sc.apiModelPath, "api-model", "m", "", "path to the generated apimodel.json file")
f.StringVar(&sc.deploymentDirectory, "deployment-dir", "", "the location of the output from `generate`")
f.IntVarP(&sc.newDesiredAgentCount, "new-node-count", "c", 0, "desired number of nodes")
f.StringVar(&sc.agentPoolToScale, "node-pool", "", "node pool to scale")
f.StringVar(&sc.masterFQDN, "master-FQDN", "", "FQDN for the master load balancer, Needed to scale down Kubernetes agent pools")
f.MarkDeprecated("deployment-dir", "deployment-dir is no longer required for scale or upgrade. Please use --api-model.")
addAuthFlags(&sc.authArgs, f)
return scaleCmd
}
func (sc *scaleCmd) validate(cmd *cobra.Command) error {
log.Infoln("validating...")
var err error
sc.locale, err = i18n.LoadTranslations()
if err != nil {
return errors.Wrap(err, "error loading translation files")
}
if sc.resourceGroupName == "" {
cmd.Usage()
return errors.New("--resource-group must be specified")
}
if sc.location == "" {
cmd.Usage()
return errors.New("--location must be specified")
}
sc.location = helpers.NormalizeAzureRegion(sc.location)
if sc.newDesiredAgentCount == 0 {
cmd.Usage()
return errors.New("--new-node-count must be specified")
}
if sc.apiModelPath == "" && sc.deploymentDirectory == "" {
cmd.Usage()
return errors.New("--api-model must be specified")
}
if sc.apiModelPath != "" && sc.deploymentDirectory != "" {
cmd.Usage()
return errors.New("ambiguous, please specify only one of --api-model and --deployment-dir")
}
return nil
}
func (sc *scaleCmd) load() error {
sc.logger = log.New().WithField("source", "scaling command line")
var err error
ctx, cancel := context.WithTimeout(context.Background(), armhelpers.DefaultARMOperationTimeout)
defer cancel()
if sc.apiModelPath == "" {
sc.apiModelPath = filepath.Join(sc.deploymentDirectory, apiModelFilename)
}
if _, err = os.Stat(sc.apiModelPath); os.IsNotExist(err) {
return errors.Errorf("specified api model does not exist (%s)", sc.apiModelPath)
}
apiloader := &api.Apiloader{
Translator: &i18n.Translator{
Locale: sc.locale,
},
}
sc.containerService, sc.apiVersion, err = apiloader.LoadContainerServiceFromFile(sc.apiModelPath, true, true, nil)
if err != nil {
return errors.Wrap(err, "error parsing the api model")
}
if sc.containerService.Properties.IsAzureStackCloud() {
writeCustomCloudProfile(sc.containerService)
err = sc.containerService.Properties.SetAzureStackCloudSpec()
if err != nil {
return errors.Wrap(err, "error parsing the api model")
}
}
if err = sc.authArgs.validateAuthArgs(); err != nil {
return err
}
if sc.client, err = sc.authArgs.getClient(); err != nil {
return errors.Wrap(err, "failed to get client")
}
_, err = sc.client.EnsureResourceGroup(ctx, sc.resourceGroupName, sc.location, nil)
if err != nil {
return err
}
if sc.containerService.Location == "" {
sc.containerService.Location = sc.location
} else if sc.containerService.Location != sc.location {
return errors.New("--location does not match api model location")
}
if sc.agentPoolToScale == "" {
agentPoolCount := len(sc.containerService.Properties.AgentPoolProfiles)
if agentPoolCount > 1 {
return errors.New("--node-pool is required if more than one agent pool is defined in the container service")
} else if agentPoolCount == 1 {
sc.agentPool = sc.containerService.Properties.AgentPoolProfiles[0]
sc.agentPoolIndex = 0
sc.agentPoolToScale = sc.containerService.Properties.AgentPoolProfiles[0].Name
} else {
return errors.New("No node pools found to scale")
}
} else {
agentPoolIndex := -1
for i, pool := range sc.containerService.Properties.AgentPoolProfiles {
if pool.Name == sc.agentPoolToScale {
agentPoolIndex = i
sc.agentPool = pool
sc.agentPoolIndex = i
}
}
if agentPoolIndex == -1 {
return errors.Errorf("node pool %s was not found in the deployed api model", sc.agentPoolToScale)
}
}
//allows to identify VMs in the resource group that belong to this cluster.
sc.nameSuffix = sc.containerService.Properties.GetClusterID()
log.Infof("Name suffix: %s", sc.nameSuffix)
return nil
}
func (sc *scaleCmd) run(cmd *cobra.Command, args []string) error {
if err := sc.validate(cmd); err != nil {
return errors.Wrap(err, "failed to validate scale command")
}
if err := sc.load(); err != nil {
return errors.Wrap(err, "failed to load existing container service")
}
ctx, cancel := context.WithTimeout(context.Background(), armhelpers.DefaultARMOperationTimeout)
defer cancel()
orchestratorInfo := sc.containerService.Properties.OrchestratorProfile
var currentNodeCount, highestUsedIndex, index, winPoolIndex int
winPoolIndex = -1
indexes := make([]int, 0)
indexToVM := make(map[int]string)
if sc.agentPool.IsAvailabilitySets() {
for vmsListPage, err := sc.client.ListVirtualMachines(ctx, sc.resourceGroupName); vmsListPage.NotDone(); err = vmsListPage.Next() {
if err != nil {
return errors.Wrap(err, "failed to get vms in the resource group")
} else if len(vmsListPage.Values()) < 1 {
return errors.New("The provided resource group does not contain any vms")
}
for _, vm := range vmsListPage.Values() {
vmName := *vm.Name
if !sc.vmInAgentPool(vmName, vm.Tags) {
continue
}
osPublisher := vm.StorageProfile.ImageReference.Publisher
if osPublisher != nil && strings.EqualFold(*osPublisher, "MicrosoftWindowsServer") {
_, _, winPoolIndex, index, err = utils.WindowsVMNameParts(vmName)
} else {
_, _, index, err = utils.K8sLinuxVMNameParts(vmName)
}
if err != nil {
return err
}
indexToVM[index] = vmName
indexes = append(indexes, index)
}
}
sortedIndexes := sort.IntSlice(indexes)
sortedIndexes.Sort()
indexes = []int(sortedIndexes)
currentNodeCount = len(indexes)
if currentNodeCount == sc.newDesiredAgentCount {
log.Info("Cluster is currently at the desired agent count.")
return nil
}
highestUsedIndex = indexes[len(indexes)-1]
// Scale down Scenario
if currentNodeCount > sc.newDesiredAgentCount {
if sc.masterFQDN == "" {
cmd.Usage()
return errors.New("master-FQDN is required to scale down a kubernetes cluster's agent pool")
}
vmsToDelete := make([]string, 0)
for i := currentNodeCount - 1; i >= sc.newDesiredAgentCount; i-- {
index = indexes[i]
vmsToDelete = append(vmsToDelete, indexToVM[index])
}
if orchestratorInfo.OrchestratorType == api.Kubernetes {
kubeConfig, err := engine.GenerateKubeConfig(sc.containerService.Properties, sc.location)
if err != nil {
return errors.Wrap(err, "failed to generate kube config")
}
err = sc.drainNodes(kubeConfig, vmsToDelete)
if err != nil {
return errors.Wrap(err, "Got error while draining the nodes to be deleted")
}
}
errList := operations.ScaleDownVMs(sc.client, sc.logger, sc.SubscriptionID.String(), sc.resourceGroupName, vmsToDelete...)
if errList != nil {
var err error
format := "Node '%s' failed to delete with error: '%s'"
for element := errList.Front(); element != nil; element = element.Next() {
vmError, ok := element.Value.(*operations.VMScalingErrorDetails)
if ok {
if err == nil {
err = errors.Errorf(format, vmError.Name, vmError.Error.Error())
} else {
err = errors.Wrapf(err, format, vmError.Name, vmError.Error.Error())
}
}
}
return err
}
return sc.saveAPIModel()
}
} else {
for vmssListPage, err := sc.client.ListVirtualMachineScaleSets(ctx, sc.resourceGroupName); vmssListPage.NotDone(); err = vmssListPage.NextWithContext(ctx) {
if err != nil {
return errors.Wrap(err, "failed to get VMSS list in the resource group")
}
for _, vmss := range vmssListPage.Values() {
vmName := *vmss.Name
if !sc.vmInAgentPool(vmName, vmss.Tags) {
continue
}
osPublisher := vmss.VirtualMachineProfile.StorageProfile.ImageReference.Publisher
if osPublisher != nil && strings.EqualFold(*osPublisher, "MicrosoftWindowsServer") {
_, _, winPoolIndex, _, err = utils.WindowsVMNameParts(vmName)
log.Errorln(err)
}
currentNodeCount = int(*vmss.Sku.Capacity)
highestUsedIndex = 0
}
}
}
translator := engine.Context{
Translator: &i18n.Translator{
Locale: sc.locale,
},
}
templateGenerator, err := engine.InitializeTemplateGenerator(translator)
if err != nil {
return errors.Wrap(err, "failed to initialize template generator")
}
// Our templates generate a range of nodes based on a count and offset, it is possible for there to be holes in the template
// So we need to set the count in the template to get enough nodes for the range, if there are holes that number will be larger than the desired count
countForTemplate := sc.newDesiredAgentCount
if highestUsedIndex != 0 {
countForTemplate += highestUsedIndex + 1 - currentNodeCount
}
sc.agentPool.Count = countForTemplate
sc.containerService.Properties.AgentPoolProfiles = []*api.AgentPoolProfile{sc.agentPool}
_, err = sc.containerService.SetPropertiesDefaults(false, true)
if err != nil {
return errors.Wrapf(err, "error in SetPropertiesDefaults template %s", sc.apiModelPath)
}
template, parameters, err := templateGenerator.GenerateTemplateV2(sc.containerService, engine.DefaultGeneratorCode, BuildTag)
if err != nil {
return errors.Wrapf(err, "error generating template %s", sc.apiModelPath)
}
if template, err = transform.PrettyPrintArmTemplate(template); err != nil {
return errors.Wrap(err, "error pretty printing template")
}
templateJSON := make(map[string]interface{})
parametersJSON := make(map[string]interface{})
err = json.Unmarshal([]byte(template), &templateJSON)
if err != nil {
return errors.Wrap(err, "error unmarshaling template")
}
err = json.Unmarshal([]byte(parameters), ¶metersJSON)
if err != nil {
return errors.Wrap(err, "error unmarshaling parameters")
}
transformer := transform.Transformer{Translator: translator.Translator}
addValue(parametersJSON, sc.agentPool.Name+"Count", countForTemplate)
// The agent pool is set to index 0 for the scale operation, we need to overwrite the template variables that rely on pool index.
if winPoolIndex != -1 {
templateJSON["variables"].(map[string]interface{})[sc.agentPool.Name+"Index"] = winPoolIndex
templateJSON["variables"].(map[string]interface{})[sc.agentPool.Name+"VMNamePrefix"] = sc.containerService.Properties.GetAgentVMPrefix(sc.agentPool, winPoolIndex)
}
if orchestratorInfo.OrchestratorType == api.Kubernetes {
err = transformer.NormalizeForK8sVMASScalingUp(sc.logger, templateJSON)
if err != nil {
return errors.Wrapf(err, "error transforming the template for scaling template %s", sc.apiModelPath)
}
if sc.agentPool.IsAvailabilitySets() {
addValue(parametersJSON, fmt.Sprintf("%sOffset", sc.agentPool.Name), highestUsedIndex+1)
}
}
random := rand.New(rand.NewSource(time.Now().UnixNano()))
deploymentSuffix := random.Int31()
_, err = sc.client.DeployTemplate(
ctx,
sc.resourceGroupName,
fmt.Sprintf("%s-%d", sc.resourceGroupName, deploymentSuffix),
templateJSON,
parametersJSON)
if err != nil {
return err
}
return sc.saveAPIModel()
}
func (sc *scaleCmd) saveAPIModel() error {
var err error
apiloader := &api.Apiloader{
Translator: &i18n.Translator{
Locale: sc.locale,
},
}
var apiVersion string
sc.containerService, apiVersion, err = apiloader.LoadContainerServiceFromFile(sc.apiModelPath, false, true, nil)
if err != nil {
return err
}
sc.containerService.Properties.AgentPoolProfiles[sc.agentPoolIndex].Count = sc.newDesiredAgentCount
b, err := apiloader.SerializeContainerService(sc.containerService, apiVersion)
if err != nil {
return err
}
f := helpers.FileSaver{
Translator: &i18n.Translator{
Locale: sc.locale,
},
}
dir, file := filepath.Split(sc.apiModelPath)
return f.SaveFile(dir, file, b)
}
func (sc *scaleCmd) vmInAgentPool(vmName string, tags map[string]*string) bool {
// Try to locate the VM's agent pool by expected tags.
if tags != nil {
if poolName, ok := tags["poolName"]; ok {
if nameSuffix, ok := tags["resourceNameSuffix"]; ok {
// Use strings.Contains for the nameSuffix as the Windows Agent Pools use only
// a substring of the first 5 characters of the entire nameSuffix.
if strings.EqualFold(*poolName, sc.agentPoolToScale) && strings.Contains(sc.nameSuffix, *nameSuffix) {
return true
}
}
}
}
// Fall back to checking the VM name to see if it fits the naming pattern.
return strings.Contains(vmName, sc.nameSuffix[:5]) && strings.Contains(vmName, sc.agentPoolToScale)
}
type paramsMap map[string]interface{}
func addValue(m paramsMap, k string, v interface{}) {
m[k] = paramsMap{
"value": v,
}
}
func (sc *scaleCmd) drainNodes(kubeConfig string, vmsToDelete []string) error {
masterURL := sc.masterFQDN
if !strings.HasPrefix(masterURL, "https://") {
masterURL = fmt.Sprintf("https://%s", masterURL)
}
numVmsToDrain := len(vmsToDelete)
errChan := make(chan *operations.VMScalingErrorDetails, numVmsToDrain)
defer close(errChan)
for _, vmName := range vmsToDelete {
go func(vmName string) {
err := operations.SafelyDrainNode(sc.client, sc.logger,
masterURL, kubeConfig, vmName, time.Duration(60)*time.Minute)
if err != nil {
log.Errorf("Failed to drain node %s, got error %v", vmName, err)
errChan <- &operations.VMScalingErrorDetails{Error: err, Name: vmName}
return
}
errChan <- nil
}(vmName)
}
for i := 0; i < numVmsToDrain; i++ {
errDetails := <-errChan
if errDetails != nil {
return errors.Wrapf(errDetails.Error, "Node %q failed to drain with error", errDetails.Name)
}
}
return nil
}