-
Notifications
You must be signed in to change notification settings - Fork 0
/
instances.go
369 lines (332 loc) · 12.4 KB
/
instances.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
package machine
import (
"encoding/base64"
"fmt"
"sort"
"time"
"github.com/golang/glog"
machinev1 "github.com/openshift/cluster-api/pkg/apis/machine/v1beta1"
providerconfigv1 "github.com/openshift/cluster-api-provider-aws/pkg/apis/awsproviderconfig/v1beta1"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
awsclient "github.com/openshift/cluster-api-provider-aws/pkg/client"
)
// Scan machine tags, and return a deduped tags list
func removeDuplicatedTags(tags []*ec2.Tag) []*ec2.Tag {
m := make(map[string]bool)
result := []*ec2.Tag{}
// look for duplicates
for _, entry := range tags {
if _, value := m[*entry.Key]; !value {
m[*entry.Key] = true
result = append(result, entry)
}
}
return result
}
// removeStoppedMachine removes all instances of a specific machine that are in a stopped state.
func removeStoppedMachine(machine *machinev1.Machine, client awsclient.Client) error {
instances, err := getStoppedInstances(machine, client)
if err != nil {
glog.Errorf("Error getting stopped instances: %v", err)
return fmt.Errorf("error getting stopped instances: %v", err)
}
if len(instances) == 0 {
glog.Infof("No stopped instances found for machine %v", machine.Name)
return nil
}
return terminateInstances(client, instances)
}
func buildEC2Filters(inputFilters []providerconfigv1.Filter) []*ec2.Filter {
filters := make([]*ec2.Filter, len(inputFilters))
for i, f := range inputFilters {
values := make([]*string, len(f.Values))
for j, v := range f.Values {
values[j] = aws.String(v)
}
filters[i] = &ec2.Filter{
Name: aws.String(f.Name),
Values: values,
}
}
return filters
}
func getSecurityGroupsIDs(securityGroups []providerconfigv1.AWSResourceReference, client awsclient.Client) ([]*string, error) {
var securityGroupIDs []*string
for _, g := range securityGroups {
// ID has priority
if g.ID != nil {
securityGroupIDs = append(securityGroupIDs, g.ID)
} else if g.Filters != nil {
glog.Info("Describing security groups based on filters")
// Get groups based on filters
describeSecurityGroupsRequest := ec2.DescribeSecurityGroupsInput{
Filters: buildEC2Filters(g.Filters),
}
describeSecurityGroupsResult, err := client.DescribeSecurityGroups(&describeSecurityGroupsRequest)
if err != nil {
glog.Errorf("error describing security groups: %v", err)
return nil, fmt.Errorf("error describing security groups: %v", err)
}
for _, g := range describeSecurityGroupsResult.SecurityGroups {
groupID := *g.GroupId
securityGroupIDs = append(securityGroupIDs, &groupID)
}
}
}
if len(securityGroups) == 0 {
glog.Info("No security group found")
}
return securityGroupIDs, nil
}
func getSubnetIDs(subnet providerconfigv1.AWSResourceReference, availabilityZone string, client awsclient.Client) ([]*string, error) {
var subnetIDs []*string
// ID has priority
if subnet.ID != nil {
subnetIDs = append(subnetIDs, subnet.ID)
} else {
var filters []providerconfigv1.Filter
if availabilityZone != "" {
// Improve error logging for better user experience.
// Otherwise, during the process of minimizing API calls, this is a good
// candidate for removal.
_, err := client.DescribeAvailabilityZones(&ec2.DescribeAvailabilityZonesInput{
ZoneNames: []*string{aws.String(availabilityZone)},
})
if err != nil {
glog.Errorf("error describing availability zones: %v", err)
return nil, fmt.Errorf("error describing availability zones: %v", err)
}
filters = append(filters, providerconfigv1.Filter{Name: "availabilityZone", Values: []string{availabilityZone}})
}
filters = append(filters, subnet.Filters...)
glog.Info("Describing subnets based on filters")
describeSubnetRequest := ec2.DescribeSubnetsInput{
Filters: buildEC2Filters(filters),
}
describeSubnetResult, err := client.DescribeSubnets(&describeSubnetRequest)
if err != nil {
glog.Errorf("error describing subnetes: %v", err)
return nil, fmt.Errorf("error describing subnets: %v", err)
}
for _, n := range describeSubnetResult.Subnets {
subnetID := *n.SubnetId
subnetIDs = append(subnetIDs, &subnetID)
}
}
if len(subnetIDs) == 0 {
return nil, fmt.Errorf("no subnet IDs were found")
}
return subnetIDs, nil
}
func getAMI(AMI providerconfigv1.AWSResourceReference, client awsclient.Client) (*string, error) {
if AMI.ID != nil {
amiID := AMI.ID
glog.Infof("Using AMI %s", *amiID)
return amiID, nil
}
if len(AMI.Filters) > 0 {
glog.Info("Describing AMI based on filters")
describeImagesRequest := ec2.DescribeImagesInput{
Filters: buildEC2Filters(AMI.Filters),
}
describeAMIResult, err := client.DescribeImages(&describeImagesRequest)
if err != nil {
glog.Errorf("error describing AMI: %v", err)
return nil, fmt.Errorf("error describing AMI: %v", err)
}
if len(describeAMIResult.Images) < 1 {
glog.Errorf("no image for given filters not found")
return nil, fmt.Errorf("no image for given filters not found")
}
latestImage := describeAMIResult.Images[0]
latestTime, err := time.Parse(time.RFC3339, *latestImage.CreationDate)
if err != nil {
glog.Errorf("unable to parse time for %q AMI: %v", *latestImage.ImageId, err)
return nil, fmt.Errorf("unable to parse time for %q AMI: %v", *latestImage.ImageId, err)
}
for _, image := range describeAMIResult.Images[1:] {
imageTime, err := time.Parse(time.RFC3339, *image.CreationDate)
if err != nil {
glog.Errorf("unable to parse time for %q AMI: %v", *image.ImageId, err)
return nil, fmt.Errorf("unable to parse time for %q AMI: %v", *image.ImageId, err)
}
if latestTime.Before(imageTime) {
latestImage = image
latestTime = imageTime
}
}
return latestImage.ImageId, nil
}
return nil, fmt.Errorf("AMI ID or AMI filters need to be specified")
}
func getBlockDeviceMappings(blockDeviceMappings []providerconfigv1.BlockDeviceMappingSpec, AMI string, client awsclient.Client) ([]*ec2.BlockDeviceMapping, error) {
if len(blockDeviceMappings) == 0 {
return []*ec2.BlockDeviceMapping{}, nil
}
// Get image object to get the RootDeviceName
describeImagesRequest := ec2.DescribeImagesInput{
ImageIds: []*string{&AMI},
}
describeAMIResult, err := client.DescribeImages(&describeImagesRequest)
if err != nil {
glog.Errorf("Error describing AMI: %v", err)
return nil, fmt.Errorf("error describing AMI: %v", err)
}
if len(describeAMIResult.Images) < 1 {
glog.Errorf("No image for given AMI was found")
return nil, fmt.Errorf("no image for given AMI not found")
}
deviceName := describeAMIResult.Images[0].RootDeviceName
// Only support one blockDeviceMapping
volumeSize := blockDeviceMappings[0].EBS.VolumeSize
volumeType := blockDeviceMappings[0].EBS.VolumeType
blockDeviceMapping := ec2.BlockDeviceMapping{
DeviceName: deviceName,
Ebs: &ec2.EbsBlockDevice{
VolumeSize: volumeSize,
VolumeType: volumeType,
},
}
if *volumeType == "io1" {
blockDeviceMapping.Ebs.Iops = blockDeviceMappings[0].EBS.Iops
}
return []*ec2.BlockDeviceMapping{&blockDeviceMapping}, nil
}
func launchInstance(machine *machinev1.Machine, machineProviderConfig *providerconfigv1.AWSMachineProviderConfig, userData []byte, client awsclient.Client) (*ec2.Instance, error) {
amiID, err := getAMI(machineProviderConfig.AMI, client)
if err != nil {
return nil, fmt.Errorf("error getting AMI: %v,", err)
}
securityGroupsIDs, err := getSecurityGroupsIDs(machineProviderConfig.SecurityGroups, client)
if err != nil {
return nil, fmt.Errorf("error getting security groups IDs: %v,", err)
}
subnetIDs, err := getSubnetIDs(machineProviderConfig.Subnet, machineProviderConfig.Placement.AvailabilityZone, client)
if err != nil {
return nil, fmt.Errorf("error getting subnet IDs: %v,", err)
}
if len(subnetIDs) > 1 {
glog.Warningf("More than one subnet id returned, only first one will be used")
}
// build list of networkInterfaces (just 1 for now)
var networkInterfaces = []*ec2.InstanceNetworkInterfaceSpecification{
{
DeviceIndex: aws.Int64(machineProviderConfig.DeviceIndex),
AssociatePublicIpAddress: machineProviderConfig.PublicIP,
SubnetId: subnetIDs[0],
Groups: securityGroupsIDs,
},
}
blockDeviceMappings, err := getBlockDeviceMappings(machineProviderConfig.BlockDevices, *amiID, client)
if err != nil {
return nil, fmt.Errorf("error getting blockDeviceMappings: %v,", err)
}
clusterID, ok := getClusterID(machine)
if !ok {
glog.Errorf("Unable to get cluster ID for machine: %q", machine.Name)
return nil, err
}
// Add tags to the created machine
rawTagList := []*ec2.Tag{}
for _, tag := range machineProviderConfig.Tags {
rawTagList = append(rawTagList, &ec2.Tag{Key: aws.String(tag.Name), Value: aws.String(tag.Value)})
}
rawTagList = append(rawTagList, []*ec2.Tag{
{Key: aws.String("kubernetes.io/cluster/" + clusterID), Value: aws.String("owned")},
{Key: aws.String("Name"), Value: aws.String(machine.Name)},
}...)
tagList := removeDuplicatedTags(rawTagList)
tagInstance := &ec2.TagSpecification{
ResourceType: aws.String("instance"),
Tags: tagList,
}
tagVolume := &ec2.TagSpecification{
ResourceType: aws.String("volume"),
Tags: tagList,
}
userDataEnc := base64.StdEncoding.EncodeToString(userData)
var iamInstanceProfile *ec2.IamInstanceProfileSpecification
if machineProviderConfig.IAMInstanceProfile != nil && machineProviderConfig.IAMInstanceProfile.ID != nil {
iamInstanceProfile = &ec2.IamInstanceProfileSpecification{
Name: aws.String(*machineProviderConfig.IAMInstanceProfile.ID),
}
}
var placement *ec2.Placement
if machineProviderConfig.Placement.AvailabilityZone != "" && machineProviderConfig.Subnet.ID == nil {
placement = &ec2.Placement{
AvailabilityZone: aws.String(machineProviderConfig.Placement.AvailabilityZone),
}
}
InstanceMarketOptions := buildInstanceMarketOptions(machineProviderConfig)
inputConfig := ec2.RunInstancesInput{
ImageId: amiID,
InstanceType: aws.String(machineProviderConfig.InstanceType),
// Only a single instance of the AWS instance allowed
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
KeyName: machineProviderConfig.KeyName,
IamInstanceProfile: iamInstanceProfile,
TagSpecifications: []*ec2.TagSpecification{tagInstance, tagVolume},
NetworkInterfaces: networkInterfaces,
UserData: &userDataEnc,
Placement: placement,
InstanceMarketOptions: InstanceMarketOptions,
}
if len(blockDeviceMappings) > 0 {
inputConfig.BlockDeviceMappings = blockDeviceMappings
}
runResult, err := client.RunInstances(&inputConfig)
if err != nil {
glog.Errorf("Error creating EC2 instance: %v", err)
return nil, fmt.Errorf("error creating EC2 instance: %v", err)
}
if runResult == nil || len(runResult.Instances) != 1 {
glog.Errorf("Unexpected reservation creating instances: %v", runResult)
return nil, fmt.Errorf("unexpected reservation creating instance")
}
return runResult.Instances[0], nil
}
func buildInstanceMarketOptions(machineProviderConfig *providerconfigv1.AWSMachineProviderConfig) *ec2.InstanceMarketOptionsRequest {
// only support these options for spot types.
if machineProviderConfig.MarketType == nil || *machineProviderConfig.MarketType != ec2.MarketTypeSpot{
return nil
}
InstanceMarketOptions := &ec2.InstanceMarketOptionsRequest {
MarketType: machineProviderConfig.MarketType,
}
if machineProviderConfig.SpotOptions != nil {
SpotMarketOptions := &ec2.SpotMarketOptions{
SpotInstanceType: machineProviderConfig.SpotOptions.SpotInstanceType,
MaxPrice: machineProviderConfig.SpotOptions.MaxPrice,
}
InstanceMarketOptions.SpotOptions = SpotMarketOptions
}
return InstanceMarketOptions
}
type instanceList []*ec2.Instance
func (il instanceList) Len() int {
return len(il)
}
func (il instanceList) Swap(i, j int) {
il[i], il[j] = il[j], il[i]
}
func (il instanceList) Less(i, j int) bool {
if il[i].LaunchTime == nil && il[j].LaunchTime == nil {
return false
}
if il[i].LaunchTime != nil && il[j].LaunchTime == nil {
return false
}
if il[i].LaunchTime == nil && il[j].LaunchTime != nil {
return true
}
return (*il[i].LaunchTime).After(*il[j].LaunchTime)
}
// sortInstances will sort a list of instance based on an instace launch time
// from the newest to the oldest.
// This function should only be called with running instances, not those which are stopped or
// terminated.
func sortInstances(instances []*ec2.Instance) {
sort.Sort(instanceList(instances))
}