-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
aws_cloud.go
2417 lines (2032 loc) · 73.1 KB
/
aws_cloud.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 awsup
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/eventbridge"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"golang.org/x/sync/errgroup"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/aws/aws-sdk-go-v2/aws/retry"
stscredsv2 "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/autoscaling"
autoscalingtypes "github.com/aws/aws-sdk-go-v2/service/autoscaling/types"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
elb "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing"
elbtypes "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing/types"
elbv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/aws/aws-sdk-go-v2/service/route53"
"github.com/aws/aws-sdk-go-v2/service/sts"
"k8s.io/klog/v2"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kops/dnsprovider/pkg/dnsprovider"
dnsproviderroute53 "k8s.io/kops/dnsprovider/pkg/dnsprovider/providers/aws/route53"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/model"
"k8s.io/kops/pkg/cloudinstances"
"k8s.io/kops/pkg/featureflag"
identity_aws "k8s.io/kops/pkg/nodeidentity/aws"
"k8s.io/kops/pkg/resources/spotinst"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/util/pkg/awsinterfaces"
)
// By default, aws-sdk-go-v2 only retries 3 times, which doesn't give
// much time for exponential backoff to work for serious issues. At 13
// retries, we'll try a given request for up to ~6m with exponential
// backoff along the way.
const ClientMaxRetries = 13
const (
DescribeTagsMaxAttempts = 120
DescribeTagsRetryInterval = 2 * time.Second
DescribeTagsLogInterval = 10 // this is in "retry intervals"
)
const (
CreateTagsMaxAttempts = 120
CreateTagsRetryInterval = 2 * time.Second
CreateTagsLogInterval = 10 // this is in "retry intervals"
)
const (
DeleteTagsMaxAttempts = 120
DeleteTagsRetryInterval = 2 * time.Second
DeleteTagsLogInterval = 10 // this is in "retry intervals"
)
const (
TagClusterName = "KubernetesCluster"
TagNameRolePrefix = "k8s.io/role/"
TagNameEtcdClusterPrefix = "k8s.io/etcd/"
)
const TagRoleControlPlane = "control-plane"
const TagRoleMaster = "master"
// TagNameKopsRole is the AWS tag used to identify the role an object plays for a cluster
const TagNameKopsRole = "kubernetes.io/kops/role"
// TagNameClusterOwnershipPrefix is the AWS tag used for ownership
const TagNameClusterOwnershipPrefix = "kubernetes.io/cluster/"
const tagNameDetachedInstance = "kops.k8s.io/detached-from-asg"
const (
WellKnownAccountAmazonLinux2 = "137112412989"
WellKnownAccountDebian = "136693071363"
WellKnownAccountFlatcar = "075585003325"
WellKnownAccountRedhat = "309956199498"
WellKnownAccountUbuntu = "099720109477"
)
const instanceInServiceState = "InService"
// AWSErrCodeInvalidAction is returned in AWS partitions that don't support certain actions
const AWSErrCodeInvalidAction = "InvalidAction"
type AWSCloud interface {
fi.Cloud
Config() aws.Config
EC2() awsinterfaces.EC2API
IAM() awsinterfaces.IAMAPI
ELB() awsinterfaces.ELBAPI
ELBV2() awsinterfaces.ELBV2API
Autoscaling() awsinterfaces.AutoScalingAPI
Route53() awsinterfaces.Route53API
Spotinst() spotinst.Cloud
SQS() awsinterfaces.SQSAPI
EventBridge() awsinterfaces.EventBridgeAPI
SSM() awsinterfaces.SSMAPI
// TODO: Document and rationalize these tags/filters methods
AddTags(name *string, tags map[string]string)
BuildFilters(name *string) []ec2types.Filter
BuildTags(name *string) map[string]string
Tags() map[string]string
// GetTags will fetch the tags for the specified resource, retrying (up to MaxDescribeTagsAttempts) if it hits an eventual-consistency type error
GetTags(resourceId string) (map[string]string, error)
// CreateTags will add/modify tags to the specified resource, retrying up to MaxCreateTagsAttempts times if it hits an eventual-consistency type error
CreateTags(resourceId string, tags map[string]string) error
// DeleteTags will remove tags from the specified resource, retrying up to MaxCreateTagsAttempts times if it hits an eventual-consistency type error
DeleteTags(resourceId string, tags map[string]string) error
// UpdateTags will update tags of the specified resource to match tags, using getTags(), createTags() and deleteTags()
UpdateTags(resourceId string, tags map[string]string) error
AddAWSTags(id string, expected map[string]string) error
GetELBTags(loadBalancerName string) (map[string]string, error)
GetELBV2Tags(ResourceArn string) (map[string]string, error)
// CreateELBTags will add tags to the specified loadBalancer, retrying up to MaxCreateTagsAttempts times if it hits an eventual-consistency type error
CreateELBTags(loadBalancerName string, tags map[string]string) error
CreateELBV2Tags(ResourceArn string, tags map[string]string) error
// RemoveELBTags will remove tags from the specified loadBalancer, retrying up to MaxCreateTagsAttempts times if it hits an eventual-consistency type error
RemoveELBTags(loadBalancerName string, tags map[string]string) error
RemoveELBV2Tags(ResourceArn string, tags map[string]string) error
FindELBByNameTag(findNameTag string) (*elbtypes.LoadBalancerDescription, error)
DescribeELBTags(loadBalancerNames []string) (map[string][]elbtypes.Tag, error)
// TODO: Remove, replace with awsup.ListELBV2LoadBalancers
DescribeELBV2Tags(loadBalancerNames []string) (map[string][]elbv2types.Tag, error)
FindELBV2NetworkInterfacesByName(vpcID string, loadBalancerName string) ([]ec2types.NetworkInterface, error)
// DescribeInstance is a helper that queries for the specified instance by id
DescribeInstance(instanceID string) (*ec2types.Instance, error)
// DescribeVPC is a helper that queries for the specified vpc by id
DescribeVPC(vpcID string) (*ec2types.Vpc, error)
DescribeAvailabilityZones() ([]ec2types.AvailabilityZone, error)
// ResolveImage finds an AMI image based on the given name.
// The name can be one of:
// `ami-...` in which case it is presumed to be an id
// owner/name in which case we find the image with the specified name, owned by owner
// name in which case we find the image with the specified name, with the current owner
ResolveImage(name string) (*ec2types.Image, error)
// WithTags created a copy of AWSCloud with the specified default-tags bound
WithTags(tags map[string]string) AWSCloud
// DefaultInstanceType determines a suitable instance type for the specified instance group
DefaultInstanceType(cluster *kops.Cluster, ig *kops.InstanceGroup) (string, error)
// DescribeInstanceType calls ec2.DescribeInstanceType to get information for a particular instance type
DescribeInstanceType(instanceType string) (*ec2types.InstanceTypeInfo, error)
// AccountInfo returns the AWS account ID and AWS partition that we are deploying into
AccountInfo(ctx context.Context) (string, string, error)
}
// GetCloud returns the AWSCloud in the CloudupContext.
// It panics if the CloudupContext has not been initialized with an AWSCloud.
func GetCloud(c *fi.CloudupContext) AWSCloud {
awsCloud, ok := c.T.Cloud.(AWSCloud)
if ok {
return awsCloud
}
klog.Fatalf("cannot find instance of AWSCloud in context")
return nil
}
type awsCloudImplementation struct {
ec2 *ec2.Client
iam *iam.Client
elb *elb.Client
elbv2 *elbv2.Client
autoscaling *autoscaling.Client
route53 *route53.Client
spotinst spotinst.Cloud
sts *sts.Client
sqs *sqs.Client
eventbridge *eventbridge.Client
ssm *ssm.Client
region string
tags map[string]string
instanceTypes *instanceTypes
config aws.Config
}
type instanceTypes struct {
mutex sync.Mutex
typeMap map[string]*ec2types.InstanceTypeInfo
}
var _ fi.Cloud = &awsCloudImplementation{}
func (c *awsCloudImplementation) ProviderID() kops.CloudProviderID {
return kops.CloudProviderAWS
}
func (c *awsCloudImplementation) Region() string {
return c.region
}
type awsCloudInstancesRegionMap struct {
mutex sync.Mutex
regionMap map[string]AWSCloud
}
func newAwsCloudInstancesRegionMap() *awsCloudInstancesRegionMap {
return &awsCloudInstancesRegionMap{
regionMap: make(map[string]AWSCloud),
}
}
var awsCloudInstances *awsCloudInstancesRegionMap = newAwsCloudInstancesRegionMap()
func ResetAWSCloudInstances() {
awsCloudInstances.mutex.Lock()
awsCloudInstances.regionMap = make(map[string]AWSCloud)
awsCloudInstances.mutex.Unlock()
}
func updateAwsCloudInstances(region string, cloud AWSCloud) {
awsCloudInstances.mutex.Lock()
awsCloudInstances.regionMap[region] = cloud
awsCloudInstances.mutex.Unlock()
}
func getCloudInstancesFromRegion(region string) AWSCloud {
awsCloudInstances.mutex.Lock()
defer awsCloudInstances.mutex.Unlock()
cloud, ok := awsCloudInstances.regionMap[region]
if !ok {
return nil
}
return cloud
}
func loadAWSConfig(ctx context.Context, region string) (aws.Config, error) {
loadOptions := []func(*awsconfig.LoadOptions) error{
awsconfig.WithRegion(region),
awsconfig.WithClientLogMode(aws.LogRetries),
awsconfig.WithLogger(awsLogger{}),
awsconfig.WithRetryer(func() aws.Retryer {
return retry.NewAdaptiveMode(func(ao *retry.AdaptiveModeOptions) {
ao.StandardOptions = append(ao.StandardOptions, func(so *retry.StandardOptions) {
so.MaxAttempts = ClientMaxRetries
})
})
}),
}
// assumes the role before executing commands
roleARN := os.Getenv("KOPS_AWS_ROLE_ARN")
if roleARN != "" {
cfg, err := awsconfig.LoadDefaultConfig(ctx, loadOptions...)
if err != nil {
return aws.Config{}, fmt.Errorf("failed to load default aws config: %w", err)
}
stsClient := sts.NewFromConfig(cfg)
assumeRoleProvider := stscredsv2.NewAssumeRoleProvider(stsClient, roleARN)
loadOptions = append(loadOptions, awsconfig.WithCredentialsProvider(assumeRoleProvider))
}
return awsconfig.LoadDefaultConfig(ctx, loadOptions...)
}
func NewAWSCloud(region string, tags map[string]string) (AWSCloud, error) {
ctx := context.TODO()
raw := getCloudInstancesFromRegion(region)
if raw == nil {
c := &awsCloudImplementation{
region: region,
instanceTypes: &instanceTypes{
typeMap: make(map[string]*ec2types.InstanceTypeInfo),
},
}
cfg, err := loadAWSConfig(ctx, region)
if err != nil {
return c, fmt.Errorf("failed to load default aws config: %w", err)
}
c.config = cfg
c.ec2 = ec2.NewFromConfig(cfg)
c.iam = iam.NewFromConfig(cfg)
c.elb = elb.NewFromConfig(cfg)
c.elbv2 = elbv2.NewFromConfig(cfg)
c.sts = sts.NewFromConfig(cfg)
c.autoscaling = autoscaling.NewFromConfig(cfg)
c.route53 = route53.NewFromConfig(cfg)
if featureflag.Spotinst.Enabled() {
c.spotinst, err = spotinst.NewCloud(kops.CloudProviderAWS)
if err != nil {
return c, err
}
}
c.sqs = sqs.NewFromConfig(cfg)
c.eventbridge = eventbridge.NewFromConfig(cfg)
c.ssm = ssm.NewFromConfig(cfg)
updateAwsCloudInstances(region, c)
raw = c
}
i := raw.WithTags(tags)
return i, nil
}
func (c *awsCloudImplementation) Config() aws.Config {
return c.config
}
func NewEC2Filter(name string, values ...string) ec2types.Filter {
filter := ec2types.Filter{
Name: aws.String(name),
Values: values,
}
return filter
}
// DeleteGroup deletes an aws autoscaling group
func (c *awsCloudImplementation) DeleteGroup(g *cloudinstances.CloudInstanceGroup) error {
ctx := context.TODO()
if g.InstanceGroup != nil && g.InstanceGroup.Spec.Manager == kops.InstanceManagerKarpenter {
return nil
}
if c.spotinst != nil {
if featureflag.SpotinstHybrid.Enabled() {
if _, ok := g.Raw.(*autoscalingtypes.AutoScalingGroup); ok {
return deleteGroup(ctx, c, g)
}
}
return spotinst.DeleteInstanceGroup(c.spotinst, g)
}
return deleteGroup(ctx, c, g)
}
func deleteGroup(ctx context.Context, c AWSCloud, g *cloudinstances.CloudInstanceGroup) error {
asg := g.Raw.(*autoscalingtypes.AutoScalingGroup)
name := aws.ToString(asg.AutoScalingGroupName)
template := aws.ToString(asg.LaunchConfigurationName)
launchTemplate := ""
if asg.LaunchTemplate != nil {
launchTemplate = aws.ToString(asg.LaunchTemplate.LaunchTemplateName)
}
// Delete detached instances
{
detached, err := findDetachedInstances(ctx, c, asg)
if err != nil {
return fmt.Errorf("error searching for detached instances for autoscaling group %q: %v", name, err)
}
if len(detached) > 0 {
klog.V(2).Infof("Deleting detached instances for autoscaling group %q", name)
req := &ec2.TerminateInstancesInput{
InstanceIds: detached,
}
if _, err := c.EC2().TerminateInstances(ctx, req); err != nil {
return fmt.Errorf("error deleting detached instances for autoscaling group %q: %v", name, err)
}
}
}
// Delete ASG
{
klog.V(2).Infof("Deleting autoscaling group %q", name)
request := &autoscaling.DeleteAutoScalingGroupInput{
AutoScalingGroupName: aws.String(name),
ForceDelete: aws.Bool(true),
}
_, err := c.Autoscaling().DeleteAutoScalingGroup(ctx, request)
if err != nil {
return fmt.Errorf("error deleting autoscaling group %q: %v", name, err)
}
}
// Delete LaunchConfig
if launchTemplate != "" {
// Delete launchTemplate
{
klog.V(2).Infof("Deleting autoscaling launch template %q", launchTemplate)
req := &ec2.DeleteLaunchTemplateInput{
LaunchTemplateName: aws.String(launchTemplate),
}
_, err := c.EC2().DeleteLaunchTemplate(ctx, req)
if err != nil {
return fmt.Errorf("error deleting autoscaling launch template %q: %v", launchTemplate, err)
}
}
} else if template != "" {
// Delete LaunchConfig
{
klog.V(2).Infof("Deleting autoscaling launch configuration %q", template)
request := &autoscaling.DeleteLaunchConfigurationInput{
LaunchConfigurationName: aws.String(template),
}
_, err := c.Autoscaling().DeleteLaunchConfiguration(ctx, request)
if err != nil {
return fmt.Errorf("error deleting autoscaling launch configuration %q: %v", template, err)
}
}
}
klog.V(8).Infof("deleted aws autoscaling group: %q", name)
return nil
}
// DeleteInstance deletes an aws instance
func (c *awsCloudImplementation) DeleteInstance(i *cloudinstances.CloudInstance) error {
ctx := context.TODO()
if c.spotinst != nil {
if featureflag.SpotinstHybrid.Enabled() {
if _, ok := i.CloudInstanceGroup.Raw.(*autoscalingtypes.AutoScalingGroup); ok {
return deleteInstance(ctx, c, i)
}
}
return spotinst.DeleteInstance(c.spotinst, i)
}
return deleteInstance(ctx, c, i)
}
// DeregisterInstance drains a cloud instance and load balancers.
func (c *awsCloudImplementation) DeregisterInstance(i *cloudinstances.CloudInstance) error {
ctx := context.TODO()
if c.spotinst != nil || i.CloudInstanceGroup.InstanceGroup.Spec.Manager == kops.InstanceManagerKarpenter {
return nil
}
err := deregisterInstance(ctx, c, i)
if err != nil {
return fmt.Errorf("failed to deregister instance from loadBalancer before terminating: %v", err)
}
return nil
}
func deleteInstance(ctx context.Context, c AWSCloud, i *cloudinstances.CloudInstance) error {
id := i.ID
if id == "" {
return fmt.Errorf("id was not set on CloudInstance: %v", i)
}
request := &ec2.TerminateInstancesInput{
InstanceIds: []string{id},
}
if _, err := c.EC2().TerminateInstances(ctx, request); err != nil {
if AWSErrorCode(err) == "InvalidInstanceID.NotFound" {
klog.V(2).Infof("Got InvalidInstanceID.NotFound error deleting instance %q; will treat as already-deleted", id)
} else {
return fmt.Errorf("error deleting instance %q: %v", id, err)
}
}
klog.V(8).Infof("deleted aws ec2 instance %q", id)
return nil
}
// deregisterInstance ensures that the instance is fully drained/removed from all associated loadBalancers and targetGroups before termination.
func deregisterInstance(ctx context.Context, c AWSCloud, i *cloudinstances.CloudInstance) error {
asg := i.CloudInstanceGroup.Raw.(*autoscalingtypes.AutoScalingGroup)
asgDetails, err := c.Autoscaling().DescribeAutoScalingGroups(ctx, &autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []string{aws.ToString(asg.AutoScalingGroupName)},
})
if err != nil {
return fmt.Errorf("error describing autoScalingGroups: %v", err)
}
if len(asgDetails.AutoScalingGroups) == 0 {
return nil
}
// there will always be only one ASG in the DescribeAutoScalingGroups response.
loadBalancerNames := asgDetails.AutoScalingGroups[0].LoadBalancerNames
targetGroupArns := asgDetails.AutoScalingGroups[0].TargetGroupARNs
eg, _ := errgroup.WithContext(context.Background())
if len(loadBalancerNames) != 0 {
eg.Go(func() error {
return deregisterInstanceFromClassicLoadBalancer(ctx, c, loadBalancerNames, i.ID)
})
}
if len(targetGroupArns) != 0 {
eg.Go(func() error {
return deregisterInstanceFromTargetGroups(ctx, c, targetGroupArns, i.ID)
})
}
if err := eg.Wait(); err != nil {
return fmt.Errorf("failed to deregister instance from load balancers: %v", err)
}
return nil
}
// deregisterInstanceFromClassicLoadBalancer ensures that connectionDraining completes for the associated classic loadBalancer to ensure no dropped connections.
func deregisterInstanceFromClassicLoadBalancer(ctx context.Context, c AWSCloud, loadBalancerNames []string, instanceId string) error {
klog.Infof("Deregistering instance from classic loadBalancers: %v", loadBalancerNames)
for {
instanceDraining := false
for _, loadBalancerName := range loadBalancerNames {
response, err := c.ELB().DescribeInstanceHealth(ctx, &elb.DescribeInstanceHealthInput{
LoadBalancerName: aws.String(loadBalancerName),
Instances: []elbtypes.Instance{{
InstanceId: aws.String(instanceId),
}},
})
if err != nil {
return fmt.Errorf("error describing instance health: %v", err)
}
// describeInstanceHealth can return an empty list if the instance was already terminated.
if len(response.InstanceStates) == 0 {
continue
}
// there will be only one instance in the DescribeInstanceHealth response.
if aws.ToString(response.InstanceStates[0].State) == instanceInServiceState {
c.ELB().DeregisterInstancesFromLoadBalancer(ctx, &elb.DeregisterInstancesFromLoadBalancerInput{
LoadBalancerName: aws.String(loadBalancerName),
Instances: []elbtypes.Instance{{
InstanceId: aws.String(instanceId),
}},
})
instanceDraining = true
}
}
if !instanceDraining {
break
}
time.Sleep(5 * time.Second)
}
return nil
}
// deregisterInstanceFromTargetGroups ensures that instances are fully unused in the corresponding targetGroups before instance termination.
// this ensures that connections are fully drained from the instance before terminating.
func deregisterInstanceFromTargetGroups(ctx context.Context, c AWSCloud, targetGroupArns []string, instanceId string) error {
eg, _ := errgroup.WithContext(context.Background())
for _, targetGroupArn := range targetGroupArns {
arn := targetGroupArn
eg.Go(func() error {
return deregisterInstanceFromTargetGroup(ctx, c, arn, instanceId)
})
}
if err := eg.Wait(); err != nil {
return fmt.Errorf("failed to register instance from targetGroups: %w", err)
}
return nil
}
func deregisterInstanceFromTargetGroup(ctx context.Context, c AWSCloud, targetGroupArn string, instanceId string) error {
klog.Infof("Deregistering instance from targetGroup: %s", targetGroupArn)
for {
instanceDraining := false
response, err := c.ELBV2().DescribeTargetHealth(ctx, &elbv2.DescribeTargetHealthInput{
TargetGroupArn: aws.String(targetGroupArn),
Targets: []elbv2types.TargetDescription{{
Id: aws.String(instanceId),
}},
})
if err != nil {
return fmt.Errorf("error describing target health: %w", err)
}
// there will be only one target in the DescribeTargetHealth response.
// DescribeTargetHealth response will contain a target even if the targetId doesn't exist.
// all other states besides TargetHealthStateUnused means that the instance may still be serving traffic.
if response.TargetHealthDescriptions[0].TargetHealth.State != elbv2types.TargetHealthStateEnumUnused {
_, err = c.ELBV2().DeregisterTargets(ctx, &elbv2.DeregisterTargetsInput{
TargetGroupArn: aws.String(targetGroupArn),
Targets: []elbv2types.TargetDescription{{
Id: aws.String(instanceId),
}},
})
if err != nil {
return fmt.Errorf("error deregistering target: %w", err)
}
instanceDraining = true
}
if !instanceDraining {
break
}
time.Sleep(5 * time.Second)
}
klog.Infof("Successfully drained instance from targetGroup: %s", targetGroupArn)
return nil
}
// DetachInstance causes an aws instance to no longer be counted against the ASG's size limits.
func (c *awsCloudImplementation) DetachInstance(i *cloudinstances.CloudInstance) error {
ctx := context.TODO()
if i.Status == cloudinstances.CloudInstanceStatusDetached {
return nil
}
if c.spotinst != nil {
return spotinst.DetachInstance(c.spotinst, i)
}
return detachInstance(ctx, c, i)
}
func detachInstance(ctx context.Context, c AWSCloud, i *cloudinstances.CloudInstance) error {
id := i.ID
if id == "" {
return fmt.Errorf("id was not set on CloudInstance: %v", i)
}
asg := i.CloudInstanceGroup.Raw.(*autoscalingtypes.AutoScalingGroup)
if err := c.CreateTags(id, map[string]string{tagNameDetachedInstance: *asg.AutoScalingGroupName}); err != nil {
return fmt.Errorf("error tagging instance %q: %v", id, err)
}
// TODO this also deregisters the instance from any ELB attached to the ASG. Do we care?
input := &autoscaling.DetachInstancesInput{
AutoScalingGroupName: aws.String(i.CloudInstanceGroup.HumanName),
InstanceIds: []string{id},
ShouldDecrementDesiredCapacity: aws.Bool(false),
}
if _, err := c.Autoscaling().DetachInstances(ctx, input); err != nil {
return fmt.Errorf("error detaching instance %q: %v", id, err)
}
klog.V(8).Infof("detached aws ec2 instance %q", id)
return nil
}
// GetCloudGroups returns a groups of instances that back a kops instance groups
func (c *awsCloudImplementation) GetCloudGroups(cluster *kops.Cluster, instancegroups []*kops.InstanceGroup, warnUnmatched bool, nodes []v1.Node) (map[string]*cloudinstances.CloudInstanceGroup, error) {
ctx := context.TODO()
if c.spotinst != nil {
sgroups, err := spotinst.GetCloudGroups(c.spotinst, cluster, instancegroups, warnUnmatched, nodes)
if err != nil {
return nil, err
}
if featureflag.SpotinstHybrid.Enabled() {
agroups, err := getCloudGroups(ctx, c, cluster, instancegroups, warnUnmatched, nodes)
if err != nil {
return nil, err
}
for name, group := range agroups {
sgroups[name] = group
}
}
return sgroups, nil
}
cloudGroups, err := getCloudGroups(ctx, c, cluster, instancegroups, warnUnmatched, nodes)
if err != nil {
return nil, err
}
karpenterGroups, err := getKarpenterGroups(c, cluster, instancegroups, nodes)
if err != nil {
return nil, err
}
for name, group := range karpenterGroups {
cloudGroups[name] = group
}
return cloudGroups, nil
}
func getKarpenterGroups(c AWSCloud, cluster *kops.Cluster, instancegroups []*kops.InstanceGroup, nodes []v1.Node) (map[string]*cloudinstances.CloudInstanceGroup, error) {
cloudGroups := make(map[string]*cloudinstances.CloudInstanceGroup)
for _, ig := range instancegroups {
if ig.Spec.Manager == kops.InstanceManagerKarpenter {
group, err := buildKarpenterGroup(c, cluster, ig, nodes)
if err != nil {
return nil, err
}
cloudGroups[ig.ObjectMeta.Name] = group
}
}
return cloudGroups, nil
}
func buildKarpenterGroup(c AWSCloud, cluster *kops.Cluster, ig *kops.InstanceGroup, nodes []v1.Node) (*cloudinstances.CloudInstanceGroup, error) {
ctx := context.TODO()
nodeMap := cloudinstances.GetNodeMap(nodes, cluster)
instances := make(map[string]*ec2types.Instance)
updatedInstances := make(map[string]*ec2types.Instance)
clusterName := c.Tags()[TagClusterName]
var version string
{
input := &ec2.DescribeLaunchTemplatesInput{
Filters: []ec2types.Filter{
NewEC2Filter("tag:"+identity_aws.CloudTagInstanceGroupName, ig.ObjectMeta.Name),
NewEC2Filter("tag:"+TagClusterName, clusterName),
},
}
var list []ec2types.LaunchTemplate
paginator := ec2.NewDescribeLaunchTemplatesPaginator(c.EC2(), input)
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("error listing launch templates: %v", err)
}
list = append(list, page.LaunchTemplates...)
}
lt := list[0]
versionNumber := *lt.LatestVersionNumber
version = strconv.Itoa(int(versionNumber))
}
karpenterGroup := &cloudinstances.CloudInstanceGroup{
InstanceGroup: ig,
HumanName: ig.ObjectMeta.Name,
}
{
req := &ec2.DescribeInstancesInput{
Filters: []ec2types.Filter{
NewEC2Filter("tag:"+identity_aws.CloudTagInstanceGroupName, ig.ObjectMeta.Name),
NewEC2Filter("tag:"+TagClusterName, clusterName),
NewEC2Filter("instance-state-name", "pending", "running", "stopping", "stopped"),
},
}
result, err := c.EC2().DescribeInstances(ctx, req)
if err != nil {
return nil, err
}
for _, r := range result.Reservations {
for _, i := range r.Instances {
id := aws.ToString(i.InstanceId)
instances[id] = &i
}
}
}
klog.V(2).Infof("found %d karpenter instances", len(instances))
{
req := &ec2.DescribeInstancesInput{
Filters: []ec2types.Filter{
NewEC2Filter("tag:"+identity_aws.CloudTagInstanceGroupName, ig.ObjectMeta.Name),
NewEC2Filter("tag:"+TagClusterName, clusterName),
NewEC2Filter("instance-state-name", "pending", "running", "stopping", "stopped"),
NewEC2Filter("tag:aws:ec2launchtemplate:version", version),
},
}
result, err := c.EC2().DescribeInstances(ctx, req)
if err != nil {
return nil, err
}
for _, r := range result.Reservations {
for _, i := range r.Instances {
id := aws.ToString(i.InstanceId)
updatedInstances[id] = &i
}
}
}
klog.V(2).Infof("found %d updated instances", len(updatedInstances))
{
for _, instance := range instances {
id := *instance.InstanceId
_, ready := updatedInstances[id]
var status string
if ready {
status = cloudinstances.CloudInstanceStatusUpToDate
} else {
status = cloudinstances.CloudInstanceStatusNeedsUpdate
}
cloudInstance, _ := karpenterGroup.NewCloudInstance(id, status, nodeMap[id])
addCloudInstanceData(cloudInstance, instance)
}
}
return karpenterGroup, nil
}
func getCloudGroups(ctx context.Context, c AWSCloud, cluster *kops.Cluster, instancegroups []*kops.InstanceGroup, warnUnmatched bool, nodes []v1.Node) (map[string]*cloudinstances.CloudInstanceGroup, error) {
nodeMap := cloudinstances.GetNodeMap(nodes, cluster)
groups := make(map[string]*cloudinstances.CloudInstanceGroup)
asgs, err := FindAutoscalingGroups(c, c.Tags())
if err != nil {
return nil, fmt.Errorf("unable to find autoscale groups: %v", err)
}
for _, asg := range asgs {
name := aws.ToString(asg.AutoScalingGroupName)
instancegroup, err := matchInstanceGroup(name, cluster.ObjectMeta.Name, instancegroups)
if err != nil {
return nil, fmt.Errorf("error getting instance group for ASG %q", name)
}
if instancegroup == nil {
if warnUnmatched {
klog.Warningf("Found ASG with no corresponding instance group %q", name)
}
continue
}
groups[instancegroup.ObjectMeta.Name], err = awsBuildCloudInstanceGroup(ctx, c, cluster, instancegroup, asg, nodeMap)
if err != nil {
return nil, fmt.Errorf("error getting cloud instance group %q: %v", instancegroup.ObjectMeta.Name, err)
}
}
return groups, nil
}
// FindAutoscalingGroups finds autoscaling groups matching the specified tags
// This isn't entirely trivial because autoscaling doesn't let us filter with as much precision as we would like
func FindAutoscalingGroups(c AWSCloud, tags map[string]string) ([]*autoscalingtypes.AutoScalingGroup, error) {
ctx := context.TODO()
var asgs []*autoscalingtypes.AutoScalingGroup
klog.V(2).Infof("Listing all Autoscaling groups matching cluster tags")
var asgNames []string
{
var asFilters []autoscalingtypes.Filter
for _, v := range tags {
// Not an exact match, but likely the best we can do
asFilters = append(asFilters, autoscalingtypes.Filter{
Name: aws.String("value"),
Values: []string{v},
})
}
request := &autoscaling.DescribeTagsInput{
Filters: asFilters,
}
paginator := autoscaling.NewDescribeTagsPaginator(c.Autoscaling(), request)
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("error listing autoscaling cluster tags: %v", err)
}
for _, t := range page.Tags {
switch *t.ResourceType {
case "auto-scaling-group":
asgNames = append(asgNames, aws.ToString(t.ResourceId))
default:
klog.Warningf("Unknown resource type: %v", *t.ResourceType)
}
}
}
}
if len(asgNames) != 0 {
for i := 0; i < len(asgNames); i += 50 {
batch := asgNames[i:minInt(i+50, len(asgNames))]
request := &autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: batch,
}
paginator := autoscaling.NewDescribeAutoScalingGroupsPaginator(c.Autoscaling(), request)
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("error listing autoscaling groups: %v", err)
}
for _, asg := range page.AutoScalingGroups {
if !matchesAsgTags(tags, asg.Tags) {
// We used an inexact filter above
continue
}
// Check for "Delete in progress" (the only use of .Status)
if asg.Status != nil {
klog.Warningf("Skipping ASG %v (which matches tags): %v", *asg.AutoScalingGroupARN, *asg.Status)
continue
}
asgs = append(asgs, &asg)
}
}
}
}
return asgs, nil
}
// Returns the minimum of two ints
func minInt(a int, b int) int {
if a < b {
return a
}
return b
}
// matchesAsgTags is used to filter an asg by tags
func matchesAsgTags(tags map[string]string, actual []autoscalingtypes.TagDescription) bool {
for k, v := range tags {
found := false
for _, a := range actual {
if aws.ToString(a.Key) == k {
if aws.ToString(a.Value) == v {
found = true
break
}
}
}
if !found {
return false
}
}
return true
}
// findAutoscalingGroupLaunchConfiguration is responsible for finding the launch - which could be a launchconfiguration, a template or a mixed instance policy template
func findAutoscalingGroupLaunchConfiguration(ctx context.Context, c AWSCloud, g *autoscalingtypes.AutoScalingGroup) (string, error) {
name := aws.ToString(g.LaunchConfigurationName)
if name != "" {
return name, nil
}
// @check the launch template then
var launchTemplate *autoscalingtypes.LaunchTemplateSpecification
if g.LaunchTemplate != nil {
launchTemplate = g.LaunchTemplate
} else if g.MixedInstancesPolicy != nil && g.MixedInstancesPolicy.LaunchTemplate != nil && g.MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification != nil {
launchTemplate = g.MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification
} else {
return "", fmt.Errorf("error finding launch template or configuration for autoscaling group: %s", aws.ToString(g.AutoScalingGroupName))
}