forked from kubernetes/kops
/
aws.go
2097 lines (1754 loc) · 55.1 KB
/
aws.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 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 aws
import (
"bufio"
"bytes"
"fmt"
"strings"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kops/pkg/dns"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/pkg/resources"
"k8s.io/kops/pkg/resources/spotinst"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
)
const (
TypeAutoscalingLaunchConfig = "autoscaling-config"
TypeNatGateway = "nat-gateway"
TypeElasticIp = "elastic-ip"
TypeLoadBalancer = "load-balancer"
TypeTargetGroup = "target-group"
)
type listFn func(fi.Cloud, string) ([]*resources.Resource, error)
func ListResourcesAWS(cloud awsup.AWSCloud, clusterName string) (map[string]*resources.Resource, error) {
resourceTrackers := make(map[string]*resources.Resource)
// These are the functions that are used for looking up
// cluster resources by their tags.
listFunctions := []listFn{
// CloudFormation
//ListCloudFormationStacks,
// EC2
ListInstances,
ListKeypairs,
ListSecurityGroups,
ListVolumes,
// EC2 VPC
ListDhcpOptions,
ListInternetGateways,
ListRouteTables,
ListSubnets,
ListVPCs,
// ELBs
ListELBs,
ListELBV2s,
ListTargetGroups,
// Route 53
ListRoute53Records,
// IAM
ListIAMInstanceProfiles,
ListIAMRoles,
}
if featureflag.Spotinst.Enabled() {
// Spotinst Elastigroups
listFunctions = append(listFunctions, ListSpotinstElastigroups)
} else {
// AutoScaling Groups
listFunctions = append(listFunctions, ListAutoScalingGroups)
}
for _, fn := range listFunctions {
rt, err := fn(cloud, clusterName)
if err != nil {
return nil, err
}
for _, t := range rt {
resourceTrackers[t.Type+":"+t.ID] = t
}
}
{
// Gateways weren't tagged in kube-up
// If we are deleting the VPC, we should delete the attached gateway
// (no real reason not to; easy to recreate; no real state etc)
gateways, err := DescribeInternetGatewaysIgnoreTags(cloud)
if err != nil {
return nil, err
}
for _, igw := range gateways {
for _, attachment := range igw.Attachments {
vpcID := aws.StringValue(attachment.VpcId)
igwID := aws.StringValue(igw.InternetGatewayId)
if vpcID == "" || igwID == "" {
continue
}
vpc := resourceTrackers["vpc:"+vpcID]
if vpc != nil && resourceTrackers["internet-gateway:"+igwID] == nil {
resourceTrackers["internet-gateway:"+igwID] = &resources.Resource{
Name: FindName(igw.Tags),
ID: igwID,
Type: "internet-gateway",
Deleter: DeleteInternetGateway,
Shared: vpc.Shared, // Shared iff the VPC is shared
}
}
}
}
}
{
// We delete a launch configuration if it is bound to one of the tagged security groups
securityGroups := sets.NewString()
for k := range resourceTrackers {
if !strings.HasPrefix(k, "security-group:") {
continue
}
id := strings.TrimPrefix(k, "security-group:")
securityGroups.Insert(id)
}
lcs, err := FindAutoScalingLaunchConfigurations(cloud, securityGroups)
if err != nil {
return nil, err
}
for _, t := range lcs {
resourceTrackers[t.Type+":"+t.ID] = t
}
}
if err := addUntaggedRouteTables(cloud, clusterName, resourceTrackers); err != nil {
return nil, err
}
{
// We delete a NAT gateway if it is linked to our route table
routeTableIds := make(map[string]*resources.Resource)
for _, resource := range resourceTrackers {
if resource.Type != ec2.ResourceTypeRouteTable {
continue
}
id := resource.ID
routeTableIds[id] = resource
}
natGateways, err := FindNatGateways(cloud, routeTableIds, clusterName)
if err != nil {
return nil, err
}
for _, t := range natGateways {
resourceTrackers[t.Type+":"+t.ID] = t
}
}
for k, t := range resourceTrackers {
if t.Done {
delete(resourceTrackers, k)
}
}
return resourceTrackers, nil
}
func BuildEC2Filters(cloud fi.Cloud) []*ec2.Filter {
awsCloud := cloud.(awsup.AWSCloud)
tags := awsCloud.Tags()
var filters []*ec2.Filter
for k, v := range tags {
filter := awsup.NewEC2Filter("tag:"+k, v)
filters = append(filters, filter)
}
return filters
}
func addUntaggedRouteTables(cloud awsup.AWSCloud, clusterName string, resources map[string]*resources.Resource) error {
// We sometimes have trouble tagging the route table (eventual consistency, e.g. #597)
// If we are deleting the VPC, we should delete the route table
// (no real reason not to; easy to recreate; no real state etc)
routeTables, err := DescribeRouteTablesIgnoreTags(cloud)
if err != nil {
return err
}
for _, rt := range routeTables {
rtID := aws.StringValue(rt.RouteTableId)
vpcID := aws.StringValue(rt.VpcId)
if vpcID == "" || rtID == "" {
continue
}
if resources["vpc:"+vpcID] == nil || resources["vpc:"+vpcID].Shared {
// Not deleting this VPC; ignore
continue
}
clusterTag, _ := awsup.FindEC2Tag(rt.Tags, awsup.TagClusterName)
if clusterTag != "" && clusterTag != clusterName {
glog.Infof("Skipping route table in VPC, but with wrong cluster tag (%q)", clusterTag)
continue
}
isMain := false
for _, a := range rt.Associations {
if aws.BoolValue(a.Main) == true {
isMain = true
}
}
if isMain {
glog.V(4).Infof("ignoring main routetable %q", rtID)
continue
}
t := buildTrackerForRouteTable(rt, clusterName)
if resources[t.Type+":"+t.ID] == nil {
resources[t.Type+":"+t.ID] = t
}
}
return nil
}
// FindAutoscalingLaunchConfiguration finds an AWS launch configuration given its name
func FindAutoscalingLaunchConfiguration(cloud awsup.AWSCloud, name string) (*autoscaling.LaunchConfiguration, error) {
glog.V(2).Infof("Retrieving Autoscaling LaunchConfigurations %q", name)
var results []*autoscaling.LaunchConfiguration
request := &autoscaling.DescribeLaunchConfigurationsInput{
LaunchConfigurationNames: []*string{&name},
}
err := cloud.Autoscaling().DescribeLaunchConfigurationsPages(request, func(p *autoscaling.DescribeLaunchConfigurationsOutput, lastPage bool) bool {
for _, t := range p.LaunchConfigurations {
results = append(results, t)
}
return true
})
if err != nil {
return nil, fmt.Errorf("error listing autoscaling LaunchConfigurations: %v", err)
}
if len(results) == 0 {
return nil, nil
}
if len(results) != 1 {
return nil, fmt.Errorf("Found multiple LaunchConfigurations with name %q", name)
}
return results[0], nil
}
func matchesElbTags(tags map[string]string, actual []*elb.Tag) bool {
for k, v := range tags {
found := false
for _, a := range actual {
if aws.StringValue(a.Key) == k {
if aws.StringValue(a.Value) == v {
found = true
break
}
}
}
if !found {
return false
}
}
return true
}
func matchesElbV2Tags(tags map[string]string, actual []*elbv2.Tag) bool {
for k, v := range tags {
found := false
for _, a := range actual {
if aws.StringValue(a.Key) == k {
if aws.StringValue(a.Value) == v {
found = true
break
}
}
}
if !found {
return false
}
}
return true
}
//type DeletableResource interface {
// Delete(cloud fi.Cloud) error
//}
func DeleteInstance(cloud fi.Cloud, t *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := t.ID
glog.V(2).Infof("Deleting EC2 instance %q", id)
request := &ec2.TerminateInstancesInput{
InstanceIds: []*string{&id},
}
_, err := c.EC2().TerminateInstances(request)
if err != nil {
if awsup.AWSErrorCode(err) == "InvalidInstanceID.NotFound" {
glog.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)
}
}
return nil
}
func DeleteCloudFormationStack(cloud fi.Cloud, t *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := t.ID
glog.V(2).Infof("deleting CloudFormation stack %q %q", t.Name, id)
request := &cloudformation.DeleteStackInput{}
request.StackName = &t.Name
_, err := c.CloudFormation().DeleteStack(request)
if err != nil {
return fmt.Errorf("error deleting CloudFormation stack %q: %v", id, err)
}
return nil
}
func DumpCloudFormationStack(op *resources.DumpOperation, r *resources.Resource) error {
data := make(map[string]interface{})
data["id"] = r.ID
data["type"] = r.Type
data["raw"] = r.Obj
op.Dump.Resources = append(op.Dump.Resources, data)
return nil
}
func ListCloudFormationStacks(cloud fi.Cloud, clusterName string) ([]*resources.Resource, error) {
var resourceTrackers []*resources.Resource
request := &cloudformation.ListStacksInput{}
c := cloud.(awsup.AWSCloud)
response, err := c.CloudFormation().ListStacks(request)
if err != nil {
return nil, fmt.Errorf("Unable to list CloudFormation stacks: %v", err)
}
for _, stack := range response.StackSummaries {
if *stack.StackName == clusterName {
resourceTracker := &resources.Resource{
Name: *stack.StackName,
ID: *stack.StackId,
Type: "cloud-formation",
Deleter: DeleteCloudFormationStack,
Dumper: DumpCloudFormationStack,
Obj: stack,
}
resourceTrackers = append(resourceTrackers, resourceTracker)
}
}
return resourceTrackers, nil
}
func ListInstances(cloud fi.Cloud, clusterName string) ([]*resources.Resource, error) {
c := cloud.(awsup.AWSCloud)
glog.V(2).Infof("Querying EC2 instances")
request := &ec2.DescribeInstancesInput{
Filters: BuildEC2Filters(cloud),
}
var resourceTrackers []*resources.Resource
err := c.EC2().DescribeInstancesPages(request, func(p *ec2.DescribeInstancesOutput, lastPage bool) bool {
for _, reservation := range p.Reservations {
for _, instance := range reservation.Instances {
id := aws.StringValue(instance.InstanceId)
if instance.State != nil {
stateName := aws.StringValue(instance.State.Name)
switch stateName {
case "terminated", "shutting-down":
continue
case "running", "stopped":
// We need to delete
glog.V(4).Infof("instance %q has state=%q", id, stateName)
default:
glog.Infof("unknown instance state for %q: %q", id, stateName)
}
}
resourceTracker := &resources.Resource{
Name: FindName(instance.Tags),
ID: id,
Type: ec2.ResourceTypeInstance,
Deleter: DeleteInstance,
Dumper: DumpInstance,
Obj: instance,
}
var blocks []string
blocks = append(blocks, "subnet:"+aws.StringValue(instance.SubnetId))
blocks = append(blocks, "vpc:"+aws.StringValue(instance.VpcId))
for _, volume := range instance.BlockDeviceMappings {
if volume.Ebs == nil {
continue
}
blocks = append(blocks, "volume:"+aws.StringValue(volume.Ebs.VolumeId))
}
for _, sg := range instance.SecurityGroups {
blocks = append(blocks, "security-group:"+aws.StringValue(sg.GroupId))
}
resourceTracker.Blocks = blocks
resourceTrackers = append(resourceTrackers, resourceTracker)
}
}
return true
})
if err != nil {
return nil, fmt.Errorf("error describing instances: %v", err)
}
return resourceTrackers, nil
}
// getDumpState gets the dumpState from the dump context, or creates one if not yet initialized
func getDumpState(dumpContext *resources.DumpOperation) *dumpState {
if dumpContext.CloudState == nil {
dumpContext.CloudState = &dumpState{
cloud: dumpContext.Cloud.(awsup.AWSCloud),
}
}
return dumpContext.CloudState.(*dumpState)
}
type imageInfo struct {
SSHUser string
}
type dumpState struct {
cloud awsup.AWSCloud
mutex sync.Mutex
images map[string]*imageInfo
}
func (s *dumpState) getImageInfo(imageID string) (*imageInfo, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.images == nil {
s.images = make(map[string]*imageInfo)
}
info := s.images[imageID]
if info == nil {
image, err := s.cloud.ResolveImage(imageID)
if err != nil {
return nil, err
}
info = &imageInfo{}
if image != nil {
sshUser := guessSSHUser(image)
if sshUser == "" {
glog.Warningf("unable to guess SSH user for image: %+v", image)
}
info.SSHUser = sshUser
}
s.images[imageID] = info
}
return info, nil
}
func guessSSHUser(image *ec2.Image) string {
owner := aws.StringValue(image.OwnerId)
switch owner {
case awsup.WellKnownAccountAmazonSystemLinux2:
return "ec2-user"
case awsup.WellKnownAccountCoreOS:
return "core"
case awsup.WellKnownAccountKopeio:
return "admin"
case awsup.WellKnownAccountUbuntu:
return "ubuntu"
}
return ""
}
func DumpInstance(op *resources.DumpOperation, r *resources.Resource) error {
data := make(map[string]interface{})
data["id"] = r.ID
data["type"] = ec2.ResourceTypeInstance
data["raw"] = r.Obj
op.Dump.Resources = append(op.Dump.Resources, data)
ec2Instance := r.Obj.(*ec2.Instance)
i := &resources.Instance{
Name: r.ID,
}
for _, networkInterface := range ec2Instance.NetworkInterfaces {
if networkInterface.Association != nil {
publicIP := aws.StringValue(networkInterface.Association.PublicIp)
if publicIP != "" {
i.PublicAddresses = append(i.PublicAddresses, publicIP)
}
}
}
for _, tag := range ec2Instance.Tags {
key := aws.StringValue(tag.Key)
if !strings.HasPrefix(key, awsup.TagNameRolePrefix) {
continue
}
role := strings.TrimPrefix(key, awsup.TagNameRolePrefix)
i.Roles = append(i.Roles, role)
}
imageID := aws.StringValue(ec2Instance.ImageId)
imageInfo, err := getDumpState(op).getImageInfo(imageID)
if err != nil {
glog.Warningf("unable to fetch image %q: %v", imageID, err)
} else if imageInfo != nil {
i.SSHUser = imageInfo.SSHUser
}
op.Dump.Instances = append(op.Dump.Instances, i)
return nil
}
func DeleteVolume(cloud fi.Cloud, r *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := r.ID
glog.V(2).Infof("Deleting EC2 Volume %q", id)
request := &ec2.DeleteVolumeInput{
VolumeId: &id,
}
_, err := c.EC2().DeleteVolume(request)
if err != nil {
if IsDependencyViolation(err) {
return err
}
if awsup.AWSErrorCode(err) == "InvalidVolume.NotFound" {
// Concurrently deleted
return nil
}
return fmt.Errorf("error deleting Volume %q: %v", id, err)
}
return nil
}
func ListVolumes(cloud fi.Cloud, clusterName string) ([]*resources.Resource, error) {
c := cloud.(awsup.AWSCloud)
volumes, err := DescribeVolumes(cloud)
if err != nil {
return nil, err
}
var resourceTrackers []*resources.Resource
elasticIPs := make(map[string]bool)
for _, volume := range volumes {
id := aws.StringValue(volume.VolumeId)
resourceTracker := &resources.Resource{
Name: FindName(volume.Tags),
ID: id,
Type: "volume",
Deleter: DeleteVolume,
}
var blocks []string
//blocks = append(blocks, "vpc:" + aws.StringValue(rt.VpcId))
resourceTracker.Blocks = blocks
resourceTrackers = append(resourceTrackers, resourceTracker)
// Check for an elastic IP tag
for _, tag := range volume.Tags {
name := aws.StringValue(tag.Key)
ip := ""
if name == "kubernetes.io/master-ip" {
ip = aws.StringValue(tag.Value)
}
if ip != "" {
elasticIPs[ip] = true
}
}
}
if len(elasticIPs) != 0 {
glog.V(2).Infof("Querying EC2 Elastic IPs")
request := &ec2.DescribeAddressesInput{}
response, err := c.EC2().DescribeAddresses(request)
if err != nil {
return nil, fmt.Errorf("error describing addresses: %v", err)
}
for _, address := range response.Addresses {
ip := aws.StringValue(address.PublicIp)
if !elasticIPs[ip] {
continue
}
resourceTrackers = append(resourceTrackers, buildElasticIPResource(address, false, clusterName))
}
}
return resourceTrackers, nil
}
func DescribeVolumes(cloud fi.Cloud) ([]*ec2.Volume, error) {
c := cloud.(awsup.AWSCloud)
var volumes []*ec2.Volume
glog.V(2).Infof("Listing EC2 Volumes")
request := &ec2.DescribeVolumesInput{
Filters: BuildEC2Filters(c),
}
err := c.EC2().DescribeVolumesPages(request, func(p *ec2.DescribeVolumesOutput, lastPage bool) bool {
for _, volume := range p.Volumes {
volumes = append(volumes, volume)
}
return true
})
if err != nil {
return nil, fmt.Errorf("error describing volumes: %v", err)
}
return volumes, nil
}
func DeleteKeypair(cloud fi.Cloud, r *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
name := r.Name
glog.V(2).Infof("Deleting EC2 Keypair %q", name)
request := &ec2.DeleteKeyPairInput{
KeyName: &name,
}
_, err := c.EC2().DeleteKeyPair(request)
if err != nil {
return fmt.Errorf("error deleting KeyPair %q: %v", name, err)
}
return nil
}
func ListKeypairs(cloud fi.Cloud, clusterName string) ([]*resources.Resource, error) {
if !strings.Contains(clusterName, ".") {
glog.Infof("cluster %q is legacy (kube-up) cluster; won't delete keypairs", clusterName)
return nil, nil
}
c := cloud.(awsup.AWSCloud)
keypairName := "kubernetes." + clusterName
glog.V(2).Infof("Listing EC2 Keypairs")
// TODO: We need to match both the name and a prefix
// TODO: usee 'Filters: []*ec2.Filter{awsup.NewEC2Filter("key-name", keypairName)},'
request := &ec2.DescribeKeyPairsInput{}
response, err := c.EC2().DescribeKeyPairs(request)
if err != nil {
return nil, fmt.Errorf("error listing KeyPairs: %v", err)
}
var resourceTrackers []*resources.Resource
for _, keypair := range response.KeyPairs {
name := aws.StringValue(keypair.KeyName)
if name != keypairName && !strings.HasPrefix(name, keypairName+"-") {
continue
}
resourceTracker := &resources.Resource{
Name: name,
ID: name,
Type: "keypair",
Deleter: DeleteKeypair,
}
resourceTrackers = append(resourceTrackers, resourceTracker)
}
return resourceTrackers, nil
}
func DeleteSubnet(cloud fi.Cloud, tracker *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := tracker.ID
glog.V(2).Infof("Deleting EC2 Subnet %q", id)
request := &ec2.DeleteSubnetInput{
SubnetId: &id,
}
_, err := c.EC2().DeleteSubnet(request)
if err != nil {
if awsup.AWSErrorCode(err) == "InvalidSubnetID.NotFound" {
glog.V(2).Infof("Got InvalidSubnetID.NotFound error deleting subnet %q; will treat as already-deleted", id)
return nil
} else if IsDependencyViolation(err) {
return err
}
return fmt.Errorf("error deleting Subnet %q: %v", id, err)
}
return nil
}
func ListSubnets(cloud fi.Cloud, clusterName string) ([]*resources.Resource, error) {
c := cloud.(awsup.AWSCloud)
subnets, err := DescribeSubnets(cloud)
if err != nil {
return nil, fmt.Errorf("error listing subnets: %v", err)
}
var resourceTrackers []*resources.Resource
elasticIPs := sets.NewString()
ownedElasticIPs := sets.NewString()
natGatewayIds := sets.NewString()
ownedNatGatewayIds := sets.NewString()
for _, subnet := range subnets {
subnetID := aws.StringValue(subnet.SubnetId)
shared := HasSharedTag("subnet:"+subnetID, subnet.Tags, clusterName)
resourceTracker := &resources.Resource{
Name: FindName(subnet.Tags),
ID: subnetID,
Type: ec2.ResourceTypeSubnet,
Deleter: DeleteSubnet,
Dumper: DumpSubnet,
Shared: shared,
Obj: subnet,
}
resourceTracker.Blocks = append(resourceTracker.Blocks, "vpc:"+aws.StringValue(subnet.VpcId))
resourceTrackers = append(resourceTrackers, resourceTracker)
// Get tags and append with EIPs/NGWs as needed
for _, tag := range subnet.Tags {
name := aws.StringValue(tag.Key)
if name == "AssociatedElasticIp" {
eip := aws.StringValue(tag.Value)
if eip != "" {
elasticIPs.Insert(eip)
// A shared subnet means the EIP is not owned
if !shared {
ownedElasticIPs.Insert(eip)
}
}
}
if name == "AssociatedNatgateway" {
ngwID := aws.StringValue(tag.Value)
if ngwID != "" {
natGatewayIds.Insert(ngwID)
// A shared subnet means the NAT gateway is not owned
if !shared {
ownedNatGatewayIds.Insert(ngwID)
}
}
}
}
}
// Associated Elastic IPs
if elasticIPs.Len() != 0 {
glog.V(2).Infof("Querying EC2 Elastic IPs")
request := &ec2.DescribeAddressesInput{}
response, err := c.EC2().DescribeAddresses(request)
if err != nil {
return nil, fmt.Errorf("error describing addresses: %v", err)
}
for _, address := range response.Addresses {
ip := aws.StringValue(address.PublicIp)
if !elasticIPs.Has(ip) {
continue
}
resourceTrackers = append(resourceTrackers, buildElasticIPResource(address, ownedElasticIPs.Has(ip), clusterName))
}
}
// Associated Nat Gateways
// Note: we must not delete any shared NAT Gateways here.
// Since we don't have tagging on the NGWs, we have to read the route tables
if natGatewayIds.Len() != 0 {
rtRequest := &ec2.DescribeRouteTablesInput{}
rtResponse, err := c.EC2().DescribeRouteTables(rtRequest)
if err != nil {
return nil, fmt.Errorf("error describing RouteTables: %v", err)
}
// sharedNgwIds is the set of IDs for shared NGWs, that we should not delete
sharedNgwIds := sets.NewString()
{
for _, rt := range rtResponse.RouteTables {
for _, t := range rt.Tags {
k := aws.StringValue(t.Key)
v := aws.StringValue(t.Value)
if k == "AssociatedNatgateway" {
sharedNgwIds.Insert(v)
}
}
}
}
glog.V(2).Infof("Querying Nat Gateways")
request := &ec2.DescribeNatGatewaysInput{}
response, err := c.EC2().DescribeNatGateways(request)
if err != nil {
return nil, fmt.Errorf("error describing NatGateways: %v", err)
}
for _, ngw := range response.NatGateways {
id := aws.StringValue(ngw.NatGatewayId)
if !natGatewayIds.Has(id) {
continue
}
forceShared := sharedNgwIds.Has(id) || !ownedNatGatewayIds.Has(id)
r := buildNatGatewayResource(ngw, forceShared, clusterName)
resourceTrackers = append(resourceTrackers, r)
}
}
return resourceTrackers, nil
}
func DescribeSubnets(cloud fi.Cloud) ([]*ec2.Subnet, error) {
c := cloud.(awsup.AWSCloud)
glog.V(2).Infof("Listing EC2 subnets")
request := &ec2.DescribeSubnetsInput{
Filters: BuildEC2Filters(cloud),
}
response, err := c.EC2().DescribeSubnets(request)
if err != nil {
return nil, fmt.Errorf("error listing subnets: %v", err)
}
return response.Subnets, nil
}
func DeleteRouteTable(cloud fi.Cloud, r *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := r.ID
glog.V(2).Infof("Deleting EC2 RouteTable %q", id)
request := &ec2.DeleteRouteTableInput{
RouteTableId: &id,
}
_, err := c.EC2().DeleteRouteTable(request)
if err != nil {
if awsup.AWSErrorCode(err) == "InvalidRouteTableID.NotFound" {
glog.V(2).Infof("Got InvalidRouteTableID.NotFound error describing RouteTable %q; will treat as already-deleted", id)
return nil
}
if IsDependencyViolation(err) {
return err
}
return fmt.Errorf("error deleting RouteTable %q: %v", id, err)
}
return nil
}
// DescribeRouteTablesIgnoreTags returns all ec2.RouteTable, ignoring tags
func DescribeRouteTablesIgnoreTags(cloud fi.Cloud) ([]*ec2.RouteTable, error) {
c := cloud.(awsup.AWSCloud)
glog.V(2).Infof("Listing all RouteTables")
request := &ec2.DescribeRouteTablesInput{}
response, err := c.EC2().DescribeRouteTables(request)
if err != nil {
return nil, fmt.Errorf("error listing RouteTables: %v", err)
}
return response.RouteTables, nil
}
func DeleteDhcpOptions(cloud fi.Cloud, r *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := r.ID
glog.V(2).Infof("Deleting EC2 DhcpOptions %q", id)
request := &ec2.DeleteDhcpOptionsInput{
DhcpOptionsId: &id,
}
_, err := c.EC2().DeleteDhcpOptions(request)
if err != nil {
if IsDependencyViolation(err) {
return err
}
return fmt.Errorf("error deleting DhcpOptions %q: %v", id, err)
}
return nil
}
func ListDhcpOptions(cloud fi.Cloud, clusterName string) ([]*resources.Resource, error) {
dhcpOptions, err := DescribeDhcpOptions(cloud)
if err != nil {
return nil, err
}
var resourceTrackers []*resources.Resource
for _, o := range dhcpOptions {
resourceTracker := &resources.Resource{
Name: FindName(o.Tags),
ID: aws.StringValue(o.DhcpOptionsId),
Type: "dhcp-options",
Deleter: DeleteDhcpOptions,
Shared: HasSharedTag(ec2.ResourceTypeDhcpOptions+":"+aws.StringValue(o.DhcpOptionsId), o.Tags, clusterName),
}
var blocks []string
resourceTracker.Blocks = blocks
resourceTrackers = append(resourceTrackers, resourceTracker)
}
return resourceTrackers, nil
}
func DescribeDhcpOptions(cloud fi.Cloud) ([]*ec2.DhcpOptions, error) {
c := cloud.(awsup.AWSCloud)
glog.V(2).Infof("Listing EC2 DhcpOptions")
request := &ec2.DescribeDhcpOptionsInput{
Filters: BuildEC2Filters(cloud),
}
response, err := c.EC2().DescribeDhcpOptions(request)
if err != nil {
return nil, fmt.Errorf("error listing DhcpOptions: %v", err)
}
return response.DhcpOptions, nil
}
func DeleteInternetGateway(cloud fi.Cloud, r *resources.Resource) error {
c := cloud.(awsup.AWSCloud)
id := r.ID
var igw *ec2.InternetGateway
{
request := &ec2.DescribeInternetGatewaysInput{
InternetGatewayIds: []*string{&id},
}
response, err := c.EC2().DescribeInternetGateways(request)
if err != nil {
if awsup.AWSErrorCode(err) == "InvalidInternetGatewayID.NotFound" {
glog.Infof("Internet gateway %q not found; assuming already deleted", id)
return nil
}
return fmt.Errorf("error describing InternetGateway %q: %v", id, err)
}
if response == nil || len(response.InternetGateways) == 0 {
return nil
}
if len(response.InternetGateways) != 1 {
return fmt.Errorf("found multiple InternetGateways with id %q", id)