forked from Azure/aks-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upgrade.go
283 lines (233 loc) · 8.63 KB
/
upgrade.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package cmd
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"time"
"github.com/Azure/aks-engine/pkg/api"
"github.com/Azure/aks-engine/pkg/armhelpers"
"github.com/Azure/aks-engine/pkg/engine"
"github.com/Azure/aks-engine/pkg/helpers"
"github.com/Azure/aks-engine/pkg/i18n"
"github.com/Azure/aks-engine/pkg/operations/kubernetesupgrade"
"github.com/leonelquinteros/gotext"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const (
upgradeName = "upgrade"
upgradeShortDescription = "Upgrade an existing Kubernetes cluster"
upgradeLongDescription = "Upgrade an existing Kubernetes cluster, one minor version at a time"
)
type upgradeCmd struct {
authArgs
// user input
resourceGroupName string
deploymentDirectory string
upgradeVersion string
location string
timeoutInMinutes int
// derived
containerService *api.ContainerService
apiVersion string
client armhelpers.AKSEngineClient
locale *gotext.Locale
nameSuffix string
agentPoolsToUpgrade []string
timeout *time.Duration
}
// NewUpgradeCmd run a command to upgrade a Kubernetes cluster
func newUpgradeCmd() *cobra.Command {
uc := upgradeCmd{}
upgradeCmd := &cobra.Command{
Use: upgradeName,
Short: upgradeShortDescription,
Long: upgradeLongDescription,
RunE: func(cmd *cobra.Command, args []string) error {
return uc.run(cmd, args)
},
}
f := upgradeCmd.Flags()
f.StringVarP(&uc.location, "location", "l", "", "location the cluster is deployed in (required)")
f.StringVarP(&uc.resourceGroupName, "resource-group", "g", "", "the resource group where the cluster is deployed (required)")
f.StringVar(&uc.deploymentDirectory, "deployment-dir", "", "the location of the output from `generate` (required)")
f.StringVarP(&uc.upgradeVersion, "upgrade-version", "k", "", "desired kubernetes version (required)")
f.IntVar(&uc.timeoutInMinutes, "vm-timeout", -1, "how long to wait for each vm to be upgraded in minutes")
addAuthFlags(&uc.authArgs, f)
return upgradeCmd
}
func (uc *upgradeCmd) validate(cmd *cobra.Command) error {
log.Infoln("validating...")
var err error
uc.locale, err = i18n.LoadTranslations()
if err != nil {
return errors.Wrap(err, "error loading translation files")
}
if uc.resourceGroupName == "" {
cmd.Usage()
return errors.New("--resource-group must be specified")
}
if uc.location == "" {
cmd.Usage()
return errors.New("--location must be specified")
}
uc.location = helpers.NormalizeAzureRegion(uc.location)
if uc.timeoutInMinutes != -1 {
timeout := time.Duration(uc.timeoutInMinutes) * time.Minute
uc.timeout = &timeout
}
// TODO(colemick): add in the cmd annotation to help enable autocompletion
if uc.upgradeVersion == "" {
cmd.Usage()
return errors.New("--upgrade-version must be specified")
}
if uc.deploymentDirectory == "" {
cmd.Usage()
return errors.New("--deployment-dir must be specified")
}
return nil
}
func (uc *upgradeCmd) loadCluster(cmd *cobra.Command) error {
var err error
if err = uc.authArgs.validateAuthArgs(); err != nil {
return err
}
if uc.client, err = uc.authArgs.getClient(); err != nil {
return errors.Wrap(err, "failed to get client")
}
ctx, cancel := context.WithTimeout(context.Background(), armhelpers.DefaultARMOperationTimeout)
defer cancel()
_, err = uc.client.EnsureResourceGroup(ctx, uc.resourceGroupName, uc.location, nil)
if err != nil {
return errors.Wrap(err, "error ensuring resource group")
}
// load apimodel from the deployment directory
apiModelPath := path.Join(uc.deploymentDirectory, "apimodel.json")
if _, err = os.Stat(apiModelPath); os.IsNotExist(err) {
return errors.Errorf("specified api model does not exist (%s)", apiModelPath)
}
apiloader := &api.Apiloader{
Translator: &i18n.Translator{
Locale: uc.locale,
},
}
// load the container service
uc.containerService, uc.apiVersion, err = apiloader.LoadContainerServiceFromFile(apiModelPath, true, true, nil)
if err != nil {
return errors.Wrap(err, "error parsing the api model")
}
if uc.containerService.Location == "" {
uc.containerService.Location = uc.location
} else if uc.containerService.Location != uc.location {
return errors.New("--location does not match api model location")
}
// get available upgrades for container service
orchestratorInfo, err := api.GetOrchestratorVersionProfile(uc.containerService.Properties.OrchestratorProfile, uc.containerService.Properties.HasWindows())
if err != nil {
return errors.Wrap(err, "error getting list of available upgrades")
}
// add the current version if upgrade has failed
orchestratorInfo.Upgrades = append(orchestratorInfo.Upgrades, &api.OrchestratorProfile{
OrchestratorType: uc.containerService.Properties.OrchestratorProfile.OrchestratorType,
OrchestratorVersion: uc.containerService.Properties.OrchestratorProfile.OrchestratorVersion})
// validate desired upgrade version and set goal state
found := false
for _, up := range orchestratorInfo.Upgrades {
if up.OrchestratorVersion == uc.upgradeVersion {
uc.containerService.Properties.OrchestratorProfile.OrchestratorVersion = uc.upgradeVersion
found = true
break
}
}
if !found {
return errors.Errorf("upgrading to version %s is not supported. To see a list of available upgrades, use 'aks-engine orchestrators --orchestrator kubernetes --version %s'", uc.upgradeVersion, uc.containerService.Properties.OrchestratorProfile.OrchestratorVersion)
}
// Read name suffix to identify nodes in the resource group that belong
// to this cluster.
// TODO: Also update to read namesuffix from the parameters file as
// user could have specified a name suffix instead of using the default
// value generated by AKS Engine
templatePath := path.Join(uc.deploymentDirectory, "azuredeploy.json")
contents, err := ioutil.ReadFile(templatePath)
if err != nil {
return errors.Wrap(err, "error reading ARM file")
}
var template interface{}
json.Unmarshal(contents, &template)
var templateMap, templateParameters, nameSuffixParam map[string]interface{}
var okType bool
if templateMap, okType = template.(map[string]interface{}); !okType {
return errors.Errorf("error asserting data from file %q", templatePath)
}
const (
parametersKey = "parameters"
nameSuffixKey = "nameSuffix"
defaultValueKey = "defaultValue"
)
if templateParameters, okType = templateMap[parametersKey].(map[string]interface{}); !okType {
return errors.Errorf("error asserting data from key \"%s\" in file %q",
parametersKey, templatePath)
}
if nameSuffixParam, okType = templateParameters[nameSuffixKey].(map[string]interface{}); !okType {
return errors.Errorf("error asserting data from key \"%s.%s\" in file %q",
parametersKey, nameSuffixKey, templatePath)
}
if uc.nameSuffix, okType = nameSuffixParam[defaultValueKey].(string); !okType {
return errors.Errorf("error asserting data from key \"%s.%s.%s\" in file %q",
parametersKey, nameSuffixKey, defaultValueKey, templatePath)
}
log.Infoln(fmt.Sprintf("Name suffix: %s", uc.nameSuffix))
uc.agentPoolsToUpgrade = []string{}
log.Infoln(fmt.Sprintf("Gathering agent pool names..."))
for _, agentPool := range uc.containerService.Properties.AgentPoolProfiles {
uc.agentPoolsToUpgrade = append(uc.agentPoolsToUpgrade, agentPool.Name)
}
return nil
}
func (uc *upgradeCmd) run(cmd *cobra.Command, args []string) error {
err := uc.validate(cmd)
if err != nil {
log.Fatalf("Error validating upgrade command: %v", err)
}
err = uc.loadCluster(cmd)
if err != nil {
log.Fatalf("Error loading existing cluster: %v", err)
}
upgradeCluster := kubernetesupgrade.UpgradeCluster{
Translator: &i18n.Translator{
Locale: uc.locale,
},
Logger: log.NewEntry(log.New()),
Client: uc.client,
StepTimeout: uc.timeout,
}
kubeConfig, err := engine.GenerateKubeConfig(uc.containerService.Properties, uc.location)
if err != nil {
log.Fatalf("Failed to generate kube config: %v", err) // TODO: cleanup
}
if err = upgradeCluster.UpgradeCluster(uc.authArgs.SubscriptionID, uc.client, kubeConfig, uc.resourceGroupName,
uc.containerService, uc.nameSuffix, uc.agentPoolsToUpgrade, BuildTag); err != nil {
log.Fatalf("Error upgrading cluster: %v\n", err)
}
apiloader := &api.Apiloader{
Translator: &i18n.Translator{
Locale: uc.locale,
},
}
b, err := apiloader.SerializeContainerService(uc.containerService, uc.apiVersion)
if err != nil {
return err
}
f := helpers.FileSaver{
Translator: &i18n.Translator{
Locale: uc.locale,
},
}
return f.SaveFile(uc.deploymentDirectory, "apimodel.json", b)
}