forked from gardener-attic/gardener-extensions
/
client.go
253 lines (229 loc) · 8.32 KB
/
client.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
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 client
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/sts"
)
// NewClient creates a new Client for the given AWS credentials <accessKeyID>, <secretAccessKey>, and
// the AWS region <region>.
// It initializes the clients for the various services like EC2, ELB, etc.
func NewClient(accessKeyID, secretAccessKey, region string) (Interface, error) {
var (
awsConfig = &aws.Config{
Credentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, ""),
}
config = &aws.Config{Region: aws.String(region)}
)
s, err := session.NewSession(awsConfig)
if err != nil {
return nil, err
}
return &Client{
EC2: ec2.New(s, config),
ELB: elb.New(s, config),
STS: sts.New(s, config),
S3: s3.New(s, config),
}, nil
}
// GetAccountID returns the ID of the AWS account the Client is interacting with.
func (c *Client) GetAccountID(ctx context.Context) (string, error) {
getCallerIdentityOutput, err := c.STS.GetCallerIdentityWithContext(ctx, &sts.GetCallerIdentityInput{})
if err != nil {
return "", err
}
return *getCallerIdentityOutput.Account, nil
}
// GetInternetGateway returns the ID of the internet gateway attached to the given VPC <vpcID>.
// If there is no internet gateway attached, the returned string will be empty.
func (c *Client) GetInternetGateway(ctx context.Context, vpcID string) (string, error) {
describeInternetGatewaysInput := &ec2.DescribeInternetGatewaysInput{
Filters: []*ec2.Filter{
{
Name: aws.String("attachment.vpc-id"),
Values: []*string{
aws.String(vpcID),
},
},
},
}
describeInternetGatewaysOutput, err := c.EC2.DescribeInternetGatewaysWithContext(ctx, describeInternetGatewaysInput)
if err != nil {
return "", err
}
if describeInternetGatewaysOutput.InternetGateways != nil {
if *describeInternetGatewaysOutput.InternetGateways[0].InternetGatewayId == "" {
return "", fmt.Errorf("no attached internet gateway found for vpc %s", vpcID)
}
return *describeInternetGatewaysOutput.InternetGateways[0].InternetGatewayId, nil
}
return "", fmt.Errorf("no attached internet gateway found for vpc %s", vpcID)
}
// The following functions are only temporary needed due to https://github.com/gardener/gardener/issues/129.
// ListKubernetesELBs returns the list of load balancers in the given <vpcID> tagged with <clusterName>.
func (c *Client) ListKubernetesELBs(ctx context.Context, vpcID, clusterName string) ([]string, error) {
output, err := c.ELB.DescribeLoadBalancersWithContext(ctx, &elb.DescribeLoadBalancersInput{})
if err != nil {
return nil, err
}
var results []string
for _, lb := range output.LoadBalancerDescriptions {
if lb.VPCId != nil && *lb.VPCId == vpcID {
// TODO: DescribeTagsWithContext can take multiple LoadBalancers, make just 1 call to collect all Tags
tags, err := c.ELB.DescribeTagsWithContext(ctx, &elb.DescribeTagsInput{
LoadBalancerNames: []*string{lb.LoadBalancerName},
})
if err != nil {
return nil, err
}
for _, description := range tags.TagDescriptions {
for _, tag := range description.Tags {
if tag.Key != nil && *tag.Key == fmt.Sprintf("kubernetes.io/cluster/%s", clusterName) && tag.Value != nil && *tag.Value == "owned" {
results = append(results, *lb.LoadBalancerName)
}
}
}
}
}
return results, nil
}
// DeleteELB deletes the load balancer with the specific <name>. If it does not exist,
// no error is returned.
func (c *Client) DeleteELB(ctx context.Context, name string) error {
if _, err := c.ELB.DeleteLoadBalancerWithContext(ctx, &elb.DeleteLoadBalancerInput{LoadBalancerName: aws.String(name)}); err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == elb.ErrCodeAccessPointNotFoundException {
return nil
}
return err
}
return nil
}
// ListKubernetesSecurityGroups returns the list of security groups in the given <vpcID> tagged with <clusterName>.
func (c *Client) ListKubernetesSecurityGroups(ctx context.Context, vpcID, clusterName string) ([]string, error) {
groups, err := c.EC2.DescribeSecurityGroupsWithContext(ctx, &ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(vpcID)},
},
{
Name: aws.String("tag-key"),
Values: []*string{aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", clusterName))},
},
{
Name: aws.String("tag-value"),
Values: []*string{aws.String("owned")},
},
},
})
if err != nil {
return nil, err
}
var results []string
for _, group := range groups.SecurityGroups {
results = append(results, *group.GroupId)
}
return results, nil
}
// DeleteSecurityGroup deletes the security group with the specific <id>. If it does not exist,
// no error is returned.
func (c *Client) DeleteSecurityGroup(ctx context.Context, id string) error {
if _, err := c.EC2.DeleteSecurityGroupWithContext(ctx, &ec2.DeleteSecurityGroupInput{GroupId: aws.String(id)}); err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidGroup.NotFound" {
return nil
}
return err
}
return nil
}
// DeleteObjectsWithPrefix deletes the s3 objects with the specific <prefix> from <bucket>. If it does not exist,
// no error is returned.
func (c *Client) DeleteObjectsWithPrefix(ctx context.Context, bucket, prefix string) error {
in := &s3.ListObjectsInput{
Bucket: aws.String(bucket),
Prefix: aws.String(prefix),
}
objectIDs := make([]*s3.ObjectIdentifier, 0)
if err := c.S3.ListObjectsPagesWithContext(ctx, in, func(page *s3.ListObjectsOutput, lastPage bool) bool {
for _, key := range page.Contents {
obj := &s3.ObjectIdentifier{
Key: key.Key,
}
objectIDs = append(objectIDs, obj)
}
return !lastPage
}); err != nil {
return err
}
if len(objectIDs) == 0 {
return nil
}
if _, err := c.S3.DeleteObjectsWithContext(ctx, &s3.DeleteObjectsInput{
Bucket: aws.String(bucket),
Delete: &s3.Delete{
Objects: objectIDs,
},
}); err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchKey {
return nil
}
return err
}
return nil
}
// CreateBucketIfNotExists creates the s3 bucket with name <bucket> in <region>. If it already exist,
// no error is returned.
func (c *Client) CreateBucketIfNotExists(ctx context.Context, bucket, region string) error {
createBucketInput := &s3.CreateBucketInput{
Bucket: aws.String(bucket),
ACL: aws.String(s3.BucketCannedACLPrivate),
CreateBucketConfiguration: &s3.CreateBucketConfiguration{
LocationConstraint: aws.String(region),
},
}
if _, err := c.S3.CreateBucketWithContext(ctx, createBucketInput); err != nil {
if aerr, ok := err.(awserr.Error); ok && (aerr.Code() == s3.ErrCodeBucketAlreadyExists || aerr.Code() == s3.ErrCodeBucketAlreadyOwnedByYou) {
return nil
}
return err
}
return nil
}
// DeleteBucketIfExists deletes the s3 bucket with name <bucket>. If it does not exist,
// no error is returned.
func (c *Client) DeleteBucketIfExists(ctx context.Context, bucket string) error {
if _, err := c.S3.DeleteBucketWithContext(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)}); err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == s3.ErrCodeNoSuchBucket {
return nil
}
if aerr.Code() == errCodeBucketNotEmpty {
if err := c.DeleteObjectsWithPrefix(ctx, bucket, ""); err != nil {
return err
}
return c.DeleteBucketIfExists(ctx, bucket)
}
}
return err
}
return nil
}