forked from kubernetes/kops
/
rollingupdatecluster.go
409 lines (336 loc) · 13 KB
/
rollingupdatecluster.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
/*
Copyright 2016 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 main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"github.com/golang/glog"
"github.com/spf13/cobra"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/kops/cmd/kops/util"
api "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/cloudinstances"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/pkg/instancegroups"
"k8s.io/kops/pkg/pretty"
"k8s.io/kops/upup/pkg/fi/cloudup"
"k8s.io/kops/util/pkg/tables"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
var (
rollingupdateLong = pretty.LongDesc(i18n.T(`
This command updates a kubernetes cluster to match the cloud and kops specifications.
To perform a rolling update, you need to update the cloud resources first with the command
` + pretty.Bash("kops update cluster") + `.
If rolling-update does not report that the cluster needs to be rolled, you can force the cluster to be
rolled with the force flag. Rolling update drains and validates the cluster by default. A cluster is
deemed validated when all required nodes are running and all pods in the kube-system namespace are operational.
When a node is deleted, rolling-update sleeps the interval for the node type, and then tries for the same period
of time for the cluster to be validated. For instance, setting --master-interval=3m causes rolling-update
to wait for 3 minutes after a master is rolled, and another 3 minutes for the cluster to stabilize and pass
validation.
Note: terraform users will need to run all of the following commands from the same directory
` + pretty.Bash("kops update cluster --target=terraform") + ` then ` + pretty.Bash("terraform plan") + ` then
` + pretty.Bash("terraform apply") + ` prior to running ` + pretty.Bash("kops rolling-update cluster") + `.`))
rollingupdateExample = templates.Examples(i18n.T(`
# Preview a rolling-update.
kops rolling-update cluster
# Roll the currently selected kops cluster with defaults.
# Nodes will be drained and the cluster will be validated between node replacement.
kops rolling-update cluster --yes
# Roll the k8s-cluster.example.com kops cluster,
# do not fail if the cluster does not validate,
# wait 8 min to create new node, and wait at least
# 8 min to validate the cluster.
kops rolling-update cluster k8s-cluster.example.com --yes \
--fail-on-validate-error="false" \
--master-interval=8m \
--node-interval=8m
# Roll the k8s-cluster.example.com kops cluster,
# do not validate the cluster because of the cloudonly flag.
# Force the entire cluster to roll, even if rolling update
# reports that the cluster does not need to be rolled.
kops rolling-update cluster k8s-cluster.example.com --yes \
--cloudonly \
--force
# Roll the k8s-cluster.example.com kops cluster,
# only roll the node instancegroup,
# use the new drain and validate functionality.
kops rolling-update cluster k8s-cluster.example.com --yes \
--fail-on-validate-error="false" \
--node-interval 8m \
--instance-group nodes
`))
rollingupdateShort = i18n.T(`Rolling update a cluster.`)
)
// RollingUpdateOptions is the command Object for a Rolling Update.
type RollingUpdateOptions struct {
Yes bool
Force bool
CloudOnly bool
// The following two variables are when kops is validating a cluster
// during a rolling update.
// FailOnDrainError fail rolling-update if drain errors.
FailOnDrainError bool
// FailOnValidate fail the cluster rolling-update when the cluster
// does not validate, after a validation period.
FailOnValidate bool
// PostDrainDelay is the duration of a pause after a drain operation
PostDrainDelay time.Duration
// ValidationTimeout is the timeout for validation to succeed after the drain and pause
ValidationTimeout time.Duration
// MasterInterval is the minimum time to wait after stopping a master node. This does not include drain and validate time.
MasterInterval time.Duration
// NodeInterval is the minimum time to wait after stopping a (non-master) node. This does not include drain and validate time.
NodeInterval time.Duration
// BastionInterval is the minimum time to wait after stopping a bastion. This does not include drain and validate time.
BastionInterval time.Duration
// Interactive rolling-update prompts user to continue after each instances is updated.
Interactive bool
ClusterName string
// InstanceGroups is the list of instance groups to rolling-update;
// if not specified, all instance groups will be updated
InstanceGroups []string
// InstanceGroupRoles is the list of roles we should rolling-update
// if not specified, all instance groups will be updated
InstanceGroupRoles []string
}
func (o *RollingUpdateOptions) InitDefaults() {
o.Yes = false
o.Force = false
o.CloudOnly = false
o.FailOnDrainError = false
o.FailOnValidate = true
o.MasterInterval = 5 * time.Minute
o.NodeInterval = 4 * time.Minute
o.BastionInterval = 5 * time.Minute
o.Interactive = false
o.PostDrainDelay = 90 * time.Second
o.ValidationTimeout = 5 * time.Minute
}
func NewCmdRollingUpdateCluster(f *util.Factory, out io.Writer) *cobra.Command {
var options RollingUpdateOptions
options.InitDefaults()
cmd := &cobra.Command{
Use: "cluster",
Short: rollingupdateShort,
Long: rollingupdateLong,
Example: rollingupdateExample,
}
cmd.Flags().BoolVarP(&options.Yes, "yes", "y", options.Yes, "Perform rolling update immediately, without --yes rolling-update executes a dry-run")
cmd.Flags().BoolVar(&options.Force, "force", options.Force, "Force rolling update, even if no changes")
cmd.Flags().BoolVar(&options.CloudOnly, "cloudonly", options.CloudOnly, "Perform rolling update without confirming progress with k8s")
cmd.Flags().DurationVar(&options.MasterInterval, "master-interval", options.MasterInterval, "Time to wait between restarting masters")
cmd.Flags().DurationVar(&options.NodeInterval, "node-interval", options.NodeInterval, "Time to wait between restarting nodes")
cmd.Flags().DurationVar(&options.BastionInterval, "bastion-interval", options.BastionInterval, "Time to wait between restarting bastions")
cmd.Flags().BoolVarP(&options.Interactive, "interactive", "i", options.Interactive, "Prompt to continue after each instance is updated")
cmd.Flags().StringSliceVar(&options.InstanceGroups, "instance-group", options.InstanceGroups, "List of instance groups to update (defaults to all if not specified)")
cmd.Flags().StringSliceVar(&options.InstanceGroupRoles, "instance-group-roles", options.InstanceGroupRoles, "If specified, only instance groups of the specified role will be updated (e.g. Master,Node,Bastion)")
if featureflag.DrainAndValidateRollingUpdate.Enabled() {
cmd.Flags().BoolVar(&options.FailOnDrainError, "fail-on-drain-error", true, "The rolling-update will fail if draining a node fails.")
cmd.Flags().BoolVar(&options.FailOnValidate, "fail-on-validate-error", true, "The rolling-update will fail if the cluster fails to validate.")
}
cmd.Run = func(cmd *cobra.Command, args []string) {
err := rootCommand.ProcessArgs(args)
if err != nil {
exitWithError(err)
return
}
clusterName := rootCommand.ClusterName()
if clusterName == "" {
exitWithError(fmt.Errorf("--name is required"))
return
}
options.ClusterName = clusterName
err = RunRollingUpdateCluster(f, os.Stdout, &options)
if err != nil {
exitWithError(err)
return
}
}
return cmd
}
func RunRollingUpdateCluster(f *util.Factory, out io.Writer, options *RollingUpdateOptions) error {
clientset, err := f.Clientset()
if err != nil {
return err
}
cluster, err := GetCluster(f, options.ClusterName)
if err != nil {
return err
}
contextName := cluster.ObjectMeta.Name
clientGetter := genericclioptions.NewConfigFlags()
clientGetter.Context = &contextName
config, err := clientGetter.ToRESTConfig()
if err != nil {
return fmt.Errorf("cannot load kubecfg settings for %q: %v", contextName, err)
}
var nodes []v1.Node
var k8sClient kubernetes.Interface
if !options.CloudOnly {
k8sClient, err = kubernetes.NewForConfig(config)
if err != nil {
return fmt.Errorf("cannot build kube client for %q: %v", contextName, err)
}
nodeList, err := k8sClient.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to reach the kubernetes API.\n")
fmt.Fprintf(os.Stderr, "Use --cloudonly to do a rolling-update without confirming progress with the k8s API\n\n")
return fmt.Errorf("error listing nodes in cluster: %v", err)
}
if nodeList != nil {
nodes = nodeList.Items
}
}
list, err := clientset.InstanceGroupsFor(cluster).List(metav1.ListOptions{})
if err != nil {
return err
}
var instanceGroups []*api.InstanceGroup
for i := range list.Items {
instanceGroups = append(instanceGroups, &list.Items[i])
}
warnUnmatched := true
if len(options.InstanceGroups) != 0 {
var filtered []*api.InstanceGroup
for _, instanceGroupName := range options.InstanceGroups {
var found *api.InstanceGroup
for _, ig := range instanceGroups {
if ig.ObjectMeta.Name == instanceGroupName {
found = ig
break
}
}
if found == nil {
return fmt.Errorf("InstanceGroup %q not found", instanceGroupName)
}
filtered = append(filtered, found)
}
instanceGroups = filtered
// Don't warn if we find more ASGs than IGs
warnUnmatched = false
}
if len(options.InstanceGroupRoles) != 0 {
var filtered []*api.InstanceGroup
for _, ig := range instanceGroups {
for _, role := range options.InstanceGroupRoles {
if ig.Spec.Role == api.InstanceGroupRole(strings.Title(strings.ToLower(role))) {
filtered = append(filtered, ig)
continue
}
}
}
instanceGroups = filtered
// Don't warn if we find more ASGs than IGs
warnUnmatched = false
}
cloud, err := cloudup.BuildCloud(cluster)
if err != nil {
return err
}
groups, err := cloud.GetCloudGroups(cluster, instanceGroups, warnUnmatched, nodes)
if err != nil {
return err
}
{
t := &tables.Table{}
t.AddColumn("NAME", func(r *cloudinstances.CloudInstanceGroup) string {
return r.InstanceGroup.ObjectMeta.Name
})
t.AddColumn("STATUS", func(r *cloudinstances.CloudInstanceGroup) string {
return r.Status()
})
t.AddColumn("NEEDUPDATE", func(r *cloudinstances.CloudInstanceGroup) string {
return strconv.Itoa(len(r.NeedUpdate))
})
t.AddColumn("READY", func(r *cloudinstances.CloudInstanceGroup) string {
return strconv.Itoa(len(r.Ready))
})
t.AddColumn("MIN", func(r *cloudinstances.CloudInstanceGroup) string {
return strconv.Itoa(r.MinSize)
})
t.AddColumn("MAX", func(r *cloudinstances.CloudInstanceGroup) string {
return strconv.Itoa(r.MaxSize)
})
t.AddColumn("NODES", func(r *cloudinstances.CloudInstanceGroup) string {
var nodes []*v1.Node
for _, i := range r.Ready {
if i.Node != nil {
nodes = append(nodes, i.Node)
}
}
for _, i := range r.NeedUpdate {
if i.Node != nil {
nodes = append(nodes, i.Node)
}
}
return strconv.Itoa(len(nodes))
})
var l []*cloudinstances.CloudInstanceGroup
for _, v := range groups {
l = append(l, v)
}
columns := []string{"NAME", "STATUS", "NEEDUPDATE", "READY", "MIN", "MAX"}
if !options.CloudOnly {
columns = append(columns, "NODES")
}
err := t.Render(l, out, columns...)
if err != nil {
return err
}
}
needUpdate := false
for _, group := range groups {
if len(group.NeedUpdate) != 0 {
needUpdate = true
}
}
if !needUpdate && !options.Force {
fmt.Printf("\nNo rolling-update required.\n")
return nil
}
if !options.Yes {
fmt.Printf("\nMust specify --yes to rolling-update.\n")
return nil
}
if featureflag.DrainAndValidateRollingUpdate.Enabled() {
glog.V(2).Infof("Rolling update with drain and validate enabled.")
}
d := &instancegroups.RollingUpdateCluster{
MasterInterval: options.MasterInterval,
NodeInterval: options.NodeInterval,
BastionInterval: options.BastionInterval,
Interactive: options.Interactive,
Force: options.Force,
Cloud: cloud,
K8sClient: k8sClient,
ClientGetter: clientGetter,
FailOnDrainError: options.FailOnDrainError,
FailOnValidate: options.FailOnValidate,
CloudOnly: options.CloudOnly,
ClusterName: options.ClusterName,
PostDrainDelay: options.PostDrainDelay,
ValidationTimeout: options.ValidationTimeout,
}
return d.RollingUpdate(groups, cluster, list)
}