-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
convert_kubeup_cluster.go
504 lines (413 loc) · 13.5 KB
/
convert_kubeup_cluster.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
/*
Copyright 2019 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 kutil
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"k8s.io/klog/v2"
"k8s.io/kops"
api "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/registry"
"k8s.io/kops/pkg/assets"
"k8s.io/kops/pkg/client/simple"
awsresources "k8s.io/kops/pkg/resources/aws"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
)
// ConvertKubeupCluster performs a conversion of a cluster that was imported from kube-up
type ConvertKubeupCluster struct {
OldClusterName string
NewClusterName string
Cloud fi.Cloud
Clientset simple.Clientset
ClusterConfig *api.Cluster
InstanceGroups []*api.InstanceGroup
// Channel is the channel that we are upgrading to
Channel *api.Channel
}
func (x *ConvertKubeupCluster) Upgrade(ctx context.Context) error {
awsCloud := x.Cloud.(awsup.AWSCloud)
cluster := x.ClusterConfig
newClusterName := x.NewClusterName
if newClusterName == "" {
return fmt.Errorf("NewClusterName must be specified")
}
oldClusterName := x.OldClusterName
if oldClusterName == "" {
return fmt.Errorf("OldClusterName must be specified")
}
oldKeyStore, err := x.Clientset.KeyStore(cluster)
if err != nil {
return err
}
oldTags := awsCloud.Tags()
newTags := awsCloud.Tags()
newTags["KubernetesCluster"] = newClusterName
// Build completed cluster (force errors asap)
cluster.ObjectMeta.Name = newClusterName
newConfigBase, err := x.Clientset.ConfigBaseFor(cluster)
if err != nil {
return fmt.Errorf("error building ConfigBase for cluster: %v", err)
}
cluster.Spec.ConfigBase = newConfigBase.Path()
newKeyStore, err := x.Clientset.KeyStore(cluster)
if err != nil {
return err
}
// Set KubernetesVersion from channel
if x.Channel != nil {
kubernetesVersion := api.RecommendedKubernetesVersion(x.Channel, kops.Version)
if kubernetesVersion != nil {
cluster.Spec.KubernetesVersion = kubernetesVersion.String()
}
}
err = cloudup.PerformAssignments(cluster, awsCloud)
if err != nil {
return fmt.Errorf("error populating cluster defaults: %v", err)
}
if cluster.ObjectMeta.Annotations != nil {
// Remove the management annotation for the new cluster
delete(cluster.ObjectMeta.Annotations, api.AnnotationNameManagement)
}
assetBuilder := assets.NewAssetBuilder(cluster, "")
fullCluster, err := cloudup.PopulateClusterSpec(x.Clientset, cluster, x.Cloud, assetBuilder)
if err != nil {
return err
}
// Try to pre-query as much as possible before doing anything destructive
instances, err := findInstances(awsCloud)
if err != nil {
return fmt.Errorf("error finding instances: %v", err)
}
subnets, err := awsresources.DescribeSubnets(x.Cloud)
if err != nil {
return fmt.Errorf("error finding subnets: %v", err)
}
securityGroups, err := awsresources.DescribeSecurityGroups(x.Cloud, x.OldClusterName)
if err != nil {
return fmt.Errorf("error finding security groups: %v", err)
}
volumes, err := awsresources.DescribeVolumes(x.Cloud)
if err != nil {
return err
}
dhcpOptions, err := awsresources.DescribeDhcpOptions(x.Cloud)
if err != nil {
return err
}
routeTables, err := awsresources.DescribeRouteTables(x.Cloud, oldClusterName)
if err != nil {
return err
}
autoscalingGroups, err := awsup.FindAutoscalingGroups(awsCloud, oldTags)
if err != nil {
return err
}
elbs, _, err := awsresources.DescribeELBs(x.Cloud)
if err != nil {
return err
}
// Find masters
var masters []*ec2.Instance
for _, instance := range instances {
role, _ := awsup.FindEC2Tag(instance.Tags, "Role")
if role == oldClusterName+"-master" {
masters = append(masters, instance)
}
}
if len(masters) == 0 {
return fmt.Errorf("could not find masters")
}
// Stop autoscalingGroups
for _, group := range autoscalingGroups {
name := aws.StringValue(group.AutoScalingGroupName)
klog.Infof("Stopping instances in autoscaling group %q", name)
request := &autoscaling.UpdateAutoScalingGroupInput{
AutoScalingGroupName: group.AutoScalingGroupName,
DesiredCapacity: aws.Int64(0),
MinSize: aws.Int64(0),
MaxSize: aws.Int64(0),
}
_, err := awsCloud.Autoscaling().UpdateAutoScalingGroup(request)
if err != nil {
return fmt.Errorf("error updating autoscaling group %q: %v", name, err)
}
}
var waitStopped []string
// Stop masters
for _, master := range masters {
masterInstanceID := aws.StringValue(master.InstanceId)
masterState := aws.StringValue(master.State.Name)
if masterState == "terminated" {
klog.Infof("master already terminated: %q", masterInstanceID)
continue
}
klog.Infof("Stopping master: %q", masterInstanceID)
request := &ec2.StopInstancesInput{
InstanceIds: []*string{master.InstanceId},
}
_, err := awsCloud.EC2().StopInstances(request)
if err != nil {
return fmt.Errorf("error stopping master instance: %v", err)
}
waitStopped = append(waitStopped, aws.StringValue(master.InstanceId))
}
if len(waitStopped) != 0 {
for {
instances, err := findInstances(awsCloud)
if err != nil {
return fmt.Errorf("error finding instances: %v", err)
}
instanceMap := make(map[string]*ec2.Instance)
for _, i := range instances {
instanceMap[aws.StringValue(i.InstanceId)] = i
}
allStopped := true
for _, id := range waitStopped {
instance := instanceMap[id]
if instance != nil {
state := aws.StringValue(instance.State.Name)
switch state {
case "terminated", "stopped":
klog.Infof("instance %v no longer running (%v)", id, state)
default:
klog.Infof("waiting for instance %v to stop (currently %v)", id, state)
allStopped = false
}
}
}
if allStopped {
break
}
time.Sleep(5 * time.Second)
}
}
// Detach volumes from masters
for _, master := range masters {
for _, bdm := range master.BlockDeviceMappings {
if bdm.Ebs == nil || bdm.Ebs.VolumeId == nil {
continue
}
volumeID := aws.StringValue(bdm.Ebs.VolumeId)
masterInstanceID := aws.StringValue(master.InstanceId)
klog.Infof("Detaching volume %q from instance %q", volumeID, masterInstanceID)
request := &ec2.DetachVolumeInput{
VolumeId: bdm.Ebs.VolumeId,
InstanceId: master.InstanceId,
}
for {
_, err := awsCloud.EC2().DetachVolume(request)
if err != nil {
if awsup.AWSErrorCode(err) == "IncorrectState" {
klog.Infof("will retry volume detach (master has probably not stopped yet): %q", err)
time.Sleep(5 * time.Second)
continue
}
return fmt.Errorf("error detaching volume %q from master instance %q: %v", volumeID, masterInstanceID, err)
}
break
}
}
}
// Retag VPC
// We have to be careful because VPCs can be shared
{
vpcID := cluster.Spec.NetworkID
retagGateway := false
if vpcID != "" {
tags, err := awsCloud.GetTags(vpcID)
if err != nil {
return fmt.Errorf("error getting VPC tags: %v", err)
}
clusterTag := tags[awsup.TagClusterName]
if clusterTag != "" {
if clusterTag != oldClusterName {
return fmt.Errorf("VPC is tagged with a different cluster: %v", clusterTag)
}
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
klog.Infof("Retagging VPC %q", vpcID)
err := awsCloud.CreateTags(vpcID, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging VPC: %v", err)
}
// The VPC was tagged as ours, so make sure the gateway is consistently retagged
retagGateway = true
}
}
if retagGateway {
gateways, err := awsresources.DescribeInternetGatewaysIgnoreTags(x.Cloud)
if err != nil {
return fmt.Errorf("error listing gateways: %v", err)
}
for _, igw := range gateways {
match := false
for _, a := range igw.Attachments {
if vpcID == aws.StringValue(a.VpcId) {
match = true
}
}
if !match {
continue
}
id := aws.StringValue(igw.InternetGatewayId)
clusterTag, _ := awsup.FindEC2Tag(igw.Tags, awsup.TagClusterName)
if clusterTag == "" || clusterTag == oldClusterName {
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
klog.Infof("Retagging InternetGateway %q", id)
err := awsCloud.CreateTags(id, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging InternetGateway: %v", err)
}
}
}
}
}
// Retag subnets
for _, s := range subnets {
id := aws.StringValue(s.SubnetId)
klog.Infof("Retagging Subnet %q", id)
err := awsCloud.AddAWSTags(id, newTags)
if err != nil {
return fmt.Errorf("error re-tagging Subnet %q: %v", id, err)
}
}
// Retag route tables
for _, routeTable := range routeTables {
id := aws.StringValue(routeTable.RouteTableId)
clusterTag, _ := awsup.FindEC2Tag(routeTable.Tags, awsup.TagClusterName)
if clusterTag != "" {
if clusterTag != oldClusterName {
return fmt.Errorf("RouteTable is tagged with a different cluster: %v", clusterTag)
}
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
// Set the same name so we use the same route table
// As otherwise we don't attach the route table because the subnet is considered shared
replaceTags["Name"] = newClusterName
klog.Infof("Retagging RouteTable %q", id)
err := awsCloud.CreateTags(id, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging RouteTable: %v", err)
}
}
}
// Retag security groups
for _, s := range securityGroups {
id := aws.StringValue(s.GroupId)
klog.Infof("Retagging SecurityGroup %q", id)
err := awsCloud.AddAWSTags(id, newTags)
if err != nil {
return fmt.Errorf("error re-tagging SecurityGroup %q: %v", id, err)
}
}
// Retag DHCP options
// We have to be careful because DHCP options can be shared
for _, dhcpOption := range dhcpOptions {
id := aws.StringValue(dhcpOption.DhcpOptionsId)
clusterTag, _ := awsup.FindEC2Tag(dhcpOption.Tags, awsup.TagClusterName)
if clusterTag != "" {
if clusterTag != oldClusterName {
return fmt.Errorf("DHCP options are tagged with a different cluster: %v", clusterTag)
}
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
klog.Infof("Retagging DHCPOptions %q", id)
err := awsCloud.CreateTags(id, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging DHCP options: %v", err)
}
}
}
// Adopt LoadBalancers & LoadBalancer Security Groups
for _, elb := range elbs {
id := aws.StringValue(elb.LoadBalancerName)
// TODO: Batch re-tag?
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
klog.Infof("Retagging ELB %q", id)
err := awsCloud.CreateELBTags(id, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging ELB %q: %v", id, err)
}
}
for _, elb := range elbs {
for _, sg := range elb.SecurityGroups {
id := aws.StringValue(sg)
// TODO: Batch re-tag?
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
klog.Infof("Retagging ELB security group %q", id)
err := awsCloud.CreateTags(id, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging ELB security group %q: %v", id, err)
}
}
}
// Adopt Volumes
for _, volume := range volumes {
id := aws.StringValue(volume.VolumeId)
// TODO: Batch re-tag?
replaceTags := make(map[string]string)
replaceTags[awsup.TagClusterName] = newClusterName
name, _ := awsup.FindEC2Tag(volume.Tags, "Name")
if name == oldClusterName+"-master-pd" {
klog.Infof("Found master volume %q: %s", id, name)
az := aws.StringValue(volume.AvailabilityZone)
replaceTags["Name"] = az + ".etcd-main." + newClusterName
}
klog.Infof("Retagging volume %q", id)
err := awsCloud.CreateTags(id, replaceTags)
if err != nil {
return fmt.Errorf("error re-tagging volume %q: %v", id, err)
}
}
err = registry.CreateClusterConfig(ctx, x.Clientset, cluster, x.InstanceGroups, nil)
if err != nil {
return fmt.Errorf("error writing updated configuration: %v", err)
}
// TODO: No longer needed?
err = registry.WriteConfigDeprecated(cluster, newConfigBase.Join(registry.PathClusterCompleted), fullCluster)
if err != nil {
return fmt.Errorf("error writing completed cluster spec: %v", err)
}
if err != nil {
return fmt.Errorf("error writing completed cluster spec: %v", err)
}
oldCACertPool, err := oldKeyStore.FindCertificatePool(fi.CertificateIDCA)
if err != nil {
return fmt.Errorf("error reading old CA certs: %v", err)
}
if oldCACertPool == nil {
return fmt.Errorf("cannot find certificate pool %q", fi.CertificateIDCA)
}
for _, ca := range oldCACertPool.Secondary {
err := newKeyStore.AddCert(fi.CertificateIDCA, ca)
if err != nil {
return fmt.Errorf("error importing old CA certs: %v", err)
}
}
if oldCACertPool.Primary != nil {
err := newKeyStore.AddCert(fi.CertificateIDCA, oldCACertPool.Primary)
if err != nil {
return fmt.Errorf("error importing old CA certs: %v", err)
}
}
return nil
}