This repository has been archived by the owner on Apr 21, 2021. It is now read-only.
forked from giantswarm/aws-operator
/
instance.go
255 lines (221 loc) · 5.87 KB
/
instance.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
package aws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/cenkalti/backoff"
microerror "github.com/giantswarm/microkit/error"
micrologger "github.com/giantswarm/microkit/logger"
awsutil "github.com/giantswarm/aws-operator/client/aws"
)
type EC2StateCode int
const (
// http://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#InstanceState
EC2PendingState EC2StateCode = 0
EC2RunningState EC2StateCode = 16
EC2ShuttingDownState EC2StateCode = 32
EC2TerminatedState EC2StateCode = 48
EC2StoppingState EC2StateCode = 64
EC2StoppedState EC2StateCode = 80
)
type Instance struct {
Name string
ClusterName string
ImageID string
InstanceType string
KeyName string
MinCount int
MaxCount int
UserData string
SmallCloudconfig string
IamInstanceProfileName string
PlacementAZ string
SecurityGroupID string
SubnetID string
id string
// Dependencies.
Logger micrologger.Logger
AWSEntity
}
func statePendingOrRunning(instance *ec2.Instance) bool {
stateCode := *instance.State.Code
switch stateCode {
case int64(EC2PendingState), int64(EC2RunningState):
return true
}
return false
}
func (i Instance) findExisting() (*ec2.Instance, error) {
filters := []*ec2.Filter{}
if i.ClusterName != "" {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", tagKeyCluster)),
Values: []*string{
aws.String(i.ClusterName),
},
})
}
if i.Name != "" {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", tagKeyName)),
Values: []*string{
aws.String(i.Name),
},
})
}
if i.id != "" {
filters = append(filters, &ec2.Filter{
Name: aws.String("instance-id"),
Values: []*string{
aws.String(i.id),
},
})
}
reservations, err := i.Clients.EC2.DescribeInstances(&ec2.DescribeInstancesInput{
Filters: filters,
})
if err != nil {
return nil, microerror.MaskAny(err)
}
for _, reservation := range reservations.Reservations {
for _, instance := range reservation.Instances {
if statePendingOrRunning(instance) {
return instance, nil
}
}
}
return nil, microerror.MaskAnyf(notFoundError, notFoundErrorFormat, InstanceType, i.Name)
}
func (i *Instance) checkIfExists() (bool, error) {
instance, err := i.findExisting()
if IsNotFound(err) {
return false, nil
} else if err != nil {
return false, microerror.MaskAny(err)
}
i.id = *instance.InstanceId
return true, nil
}
func (i *Instance) CreateIfNotExists() (bool, error) {
exists, err := i.checkIfExists()
if err != nil {
return false, microerror.MaskAny(err)
}
if exists {
return false, nil
}
if err := i.CreateOrFail(); err != nil {
return false, microerror.MaskAny(err)
}
return true, nil
}
func (i *Instance) CreateOrFail() error {
var reservation *ec2.Reservation
reserveOperation := func() error {
var err error
reservation, err = i.Clients.EC2.RunInstances(&ec2.RunInstancesInput{
ImageId: aws.String(i.ImageID),
InstanceType: aws.String(i.InstanceType),
KeyName: aws.String(i.KeyName),
MinCount: aws.Int64(int64(1)),
MaxCount: aws.Int64(int64(1)),
UserData: aws.String(i.SmallCloudconfig),
IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
Name: aws.String(i.IamInstanceProfileName),
},
Placement: &ec2.Placement{
AvailabilityZone: aws.String(i.PlacementAZ),
},
SecurityGroupIds: []*string{
aws.String(i.SecurityGroupID),
},
SubnetId: aws.String(i.SubnetID),
})
if err != nil {
return microerror.MaskAny(err)
}
return nil
}
reserveNotify := NewNotify(i.Logger, "creating instance")
if err := backoff.RetryNotify(reserveOperation, NewCustomExponentialBackoff(), reserveNotify); err != nil {
return microerror.MaskAny(err)
}
for _, rawInstance := range reservation.Instances {
i.id = *rawInstance.InstanceId
if _, err := i.Clients.EC2.CreateTags(&ec2.CreateTagsInput{
Resources: []*string{rawInstance.InstanceId},
Tags: []*ec2.Tag{
{
Key: aws.String(tagKeyName),
Value: aws.String(i.Name),
},
{
Key: aws.String(tagKeyCluster),
Value: aws.String(i.ClusterName),
},
},
}); err != nil {
return microerror.MaskAny(err)
}
}
return nil
}
func (i *Instance) Delete() error {
instance, err := i.findExisting()
if err != nil {
return microerror.MaskAny(err)
}
if _, err := i.Clients.EC2.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{
instance.InstanceId,
},
}); err != nil {
return microerror.MaskAny(err)
}
if err := i.Clients.EC2.WaitUntilInstanceTerminated(&ec2.DescribeInstancesInput{
InstanceIds: []*string{
instance.InstanceId,
},
}); err != nil {
return microerror.MaskAny(err)
}
return nil
}
func (i Instance) ID() string {
return i.id
}
type FindInstancesInput struct {
Clients awsutil.Clients
Logger micrologger.Logger
Pattern string
}
func FindInstances(input FindInstancesInput) ([]*Instance, error) {
reservations, err := input.Clients.EC2.DescribeInstances(&ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", tagKeyName)),
Values: []*string{
aws.String(fmt.Sprintf("%s*", input.Pattern)),
},
},
},
})
if err != nil {
return nil, microerror.MaskAny(err)
}
instances := make([]*Instance, 0, len(reservations.Reservations))
for _, reservation := range reservations.Reservations {
for _, rawInstance := range reservation.Instances {
if !statePendingOrRunning(rawInstance) {
continue
}
instances = append(instances, &Instance{
id: *rawInstance.InstanceId,
// Dependencies.
Logger: input.Logger,
AWSEntity: AWSEntity{Clients: input.Clients},
})
}
}
return instances, nil
}