-
Notifications
You must be signed in to change notification settings - Fork 180
/
Copy pathclient.go
225 lines (184 loc) · 5.54 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
package aws
import (
"errors"
"fmt"
"sort"
"strings"
awslib "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
awsec2 "github.com/aws/aws-sdk-go/service/ec2"
awsroute53 "github.com/aws/aws-sdk-go/service/route53"
"github.com/cloudfoundry/bosh-bootloader/storage"
)
type EC2Client interface {
DescribeAvailabilityZones(*awsec2.DescribeAvailabilityZonesInput) (*awsec2.DescribeAvailabilityZonesOutput, error)
DescribeInstances(*awsec2.DescribeInstancesInput) (*awsec2.DescribeInstancesOutput, error)
DescribeVpcs(*awsec2.DescribeVpcsInput) (*awsec2.DescribeVpcsOutput, error)
}
type Route53Client interface {
ListHostedZonesByName(*awsroute53.ListHostedZonesByNameInput) (*awsroute53.ListHostedZonesByNameOutput, error)
}
type logger interface {
Step(string, ...interface{})
}
type AvailabilityZones interface {
RetrieveAZs(region string) ([]string, error)
}
type DNSZones interface {
RetrieveDNS(domain string) string
}
type Client struct {
ec2Client EC2Client
route53Client Route53Client
logger logger
}
func NewClient(creds storage.AWS, logger logger) Client {
config := awslib.NewConfig().
WithCredentials(credentials.NewStaticCredentials(creds.AccessKeyID, creds.SecretAccessKey, "")).
WithRegion(creds.Region)
awsSession := session.Must(session.NewSession(config))
if creds.AssumeRoleArn != "" {
stsCredentials := stscreds.NewCredentials(awsSession, creds.AssumeRoleArn)
awsSession = session.Must(session.NewSession(awslib.NewConfig().WithCredentials(stsCredentials).WithRegion(creds.Region)))
}
return Client{
ec2Client: awsec2.New(awsSession),
route53Client: awsroute53.New(awsSession),
logger: logger,
}
}
// If the parent domain for the provided url exists
// in AWS Route53, return that zone's name.
func (c Client) RetrieveDNS(url string) string {
parentDomain := fmt.Sprintf("%s.", strings.Join(strings.Split(url, ".")[1:], "."))
list, err := c.route53Client.ListHostedZonesByName(&awsroute53.ListHostedZonesByNameInput{
DNSName: awslib.String(parentDomain),
})
if err != nil || len(list.HostedZones) == 0 {
return ""
}
var found awsroute53.HostedZone
for _, zone := range list.HostedZones {
if *zone.Name == parentDomain {
found = *zone
}
}
if found.Id == nil {
return ""
}
return parentDomain
}
// Return the AWS Availability Zones for a given region.
func (c Client) RetrieveAZs(region string) ([]string, error) {
output, err := c.ec2Client.DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
Filters: []*awsec2.Filter{{
Name: awslib.String("region-name"),
Values: []*string{awslib.String(region)},
}},
})
if err != nil {
return []string{}, err
}
azList := []string{}
for _, az := range output.AvailabilityZones {
if az == nil {
return []string{}, errors.New("aws returned nil availability zone")
}
if az.ZoneName == nil {
return []string{}, errors.New("aws returned availability zone with nil zone name")
}
azList = append(azList, *az.ZoneName)
}
sort.Strings(azList)
return azList, nil
}
// Return true if the network with the provided name exists.
func (c Client) CheckExists(networkName string) (bool, error) {
vpcs, err := c.ec2Client.DescribeVpcs(&awsec2.DescribeVpcsInput{
Filters: []*awsec2.Filter{{
Name: awslib.String("tag:Name"),
Values: []*string{
awslib.String(networkName),
}},
},
})
if err != nil {
return false, fmt.Errorf("Failed to check vpc existence: %s", err)
}
if len(vpcs.Vpcs) > 0 {
return true, nil
}
return false, nil
}
func (c Client) ValidateSafeToDelete(vpcID, envID string) error {
output, err := c.ec2Client.DescribeInstances(&awsec2.DescribeInstancesInput{
Filters: []*awsec2.Filter{{
Name: awslib.String("vpc-id"),
Values: []*string{awslib.String(vpcID)},
}},
})
if err != nil {
return err
}
vms := c.flattenVMs(output.Reservations)
vms = c.removeAll(vms, fmt.Sprintf("%s-nat", envID))
vms = c.removeOneVM(vms, "NAT")
vms = c.removeOneVM(vms, "bosh/0")
vms = c.removeOneVM(vms, "jumpbox/0")
if len(vms) > 0 {
return fmt.Errorf("vpc %s is not safe to delete; vms still exist: [%s]", vpcID, strings.Join(vms, ", "))
}
return nil
}
func (c Client) flattenVMs(reservations []*awsec2.Reservation) []string {
vms := []string{}
for _, reservation := range reservations {
for _, instance := range reservation.Instances {
vms = append(vms, c.vmName(instance))
}
}
return vms
}
func (c Client) vmName(instance *awsec2.Instance) string {
name := "unnamed"
for _, tag := range instance.Tags {
if awslib.StringValue(tag.Key) == "Name" && awslib.StringValue(tag.Value) != "" {
name = awslib.StringValue(tag.Value)
}
}
return name
}
func (c Client) removeOneVM(vms []string, vmToRemove string) []string {
for index, vm := range vms {
if vm == vmToRemove {
return append(vms[:index], vms[index+1:]...)
}
}
return vms
}
func (c Client) removeAll(vms []string, vmToRemove string) []string {
result := []string{}
for _, vm := range vms {
if vm != vmToRemove {
result = append(result, vm)
}
}
return result
}
func (c Client) GetVPC(vpcName string) (*string, error) {
vpcs, err := c.ec2Client.DescribeVpcs(&awsec2.DescribeVpcsInput{
Filters: []*awsec2.Filter{{
Name: awslib.String("tag:Name"),
Values: []*string{awslib.String(vpcName)},
}},
})
if err != nil {
return nil, err
}
if len(vpcs.Vpcs) != 1 {
return nil, fmt.Errorf("expected to receive exactly one VPC with name %s", vpcName)
}
return vpcs.Vpcs[0].VpcId, nil
}