/
autoscalinggroup.go
393 lines (335 loc) · 12.4 KB
/
autoscalinggroup.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
package capacity
import (
"fmt"
"log"
"sort"
"strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"golang.org/x/xerrors"
"github.com/abicky/ecsmec/internal/const/autoscalingconst"
"github.com/abicky/ecsmec/internal/sliceutil"
)
type AutoScalingGroup struct {
OriginalDesiredCapacity *int64
OriginalMaxSize *int64
StateSavedAt *time.Time
*autoscaling.Group
asSvc autoscalingiface.AutoScalingAPI
ec2Svc ec2iface.EC2API
name string
}
func NewAutoScalingGroup(name string, asSvc autoscalingiface.AutoScalingAPI, ec2Svc ec2iface.EC2API) (*AutoScalingGroup, error) {
asg := AutoScalingGroup{asSvc: asSvc, ec2Svc: ec2Svc, name: name}
if err := asg.reload(); err != nil {
return nil, err
}
return &asg, nil
}
func (asg *AutoScalingGroup) ReplaceInstances(drainer Drainer) error {
oldInstanceIDs := make([]string, 0)
baseTime := asg.StateSavedAt
if baseTime == nil {
baseTime = aws.Time(time.Now())
}
err := asg.fetchInstances(func(i *ec2.Instance) error {
if i.LaunchTime.Before(*baseTime) {
oldInstanceIDs = append(oldInstanceIDs, *i.InstanceId)
}
return nil
})
if err != nil {
return xerrors.Errorf("failed to fetch old instance IDs: %w", err)
}
if err := asg.launchNewInstances(len(oldInstanceIDs)); err != nil {
return xerrors.Errorf("failed to launch new instances: %w", err)
}
if err := asg.terminateInstances(*asg.DesiredCapacity-*asg.OriginalDesiredCapacity, drainer); err != nil {
return xerrors.Errorf("failed to terminate instances: %w", err)
}
if err := asg.restoreState(); err != nil {
return xerrors.Errorf("failed to restore the auto scaling group: %w", err)
}
return nil
}
func (asg *AutoScalingGroup) ReduceCapacity(amount int64, drainer Drainer) error {
return asg.terminateInstances(amount, drainer)
}
func (asg *AutoScalingGroup) reload() error {
resp, err := asg.asSvc.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{aws.String(asg.name)},
})
if err != nil {
return xerrors.Errorf("failed to describe the auto scaling group: %w", err)
}
if resp.AutoScalingGroups == nil {
return xerrors.Errorf("the auto scaling group \"%s\" doesn't exist", asg.name)
}
asg.Group = resp.AutoScalingGroups[0]
asg.OriginalDesiredCapacity = asg.DesiredCapacity
asg.OriginalMaxSize = asg.MaxSize
for _, t := range asg.Tags {
switch *t.Key {
case "ecsmec:OriginalDesiredCapacity":
originalDesiredCapacity, err := strconv.ParseInt(*t.Value, 10, 64)
if err != nil {
return xerrors.Errorf("ecsmec:OriginalDesiredCapacity is invalid (%s): %w", *t.Value, err)
}
asg.OriginalDesiredCapacity = &originalDesiredCapacity
case "ecsmec:OriginalMaxSize":
originalMaxSize, err := strconv.ParseInt(*t.Value, 10, 64)
if err != nil {
return xerrors.Errorf("ecsmec:OriginalMaxSize is invalid (%s): %w", *t.Value, err)
}
asg.OriginalMaxSize = &originalMaxSize
case "ecsmec:StateSavedAt":
stateSavedAt, err := time.Parse(time.RFC3339, *t.Value)
if err != nil {
return xerrors.Errorf("ecsmec:StateSavedAt is invalid (%s): %w", *t.Value, err)
}
asg.StateSavedAt = &stateSavedAt
}
}
return nil
}
func (asg *AutoScalingGroup) fetchInstances(callback func(*ec2.Instance) error) error {
ids := make([]*string, len(asg.Instances))
for i, instance := range asg.Instances {
ids[i] = instance.InstanceId
}
resp, err := asg.ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: ids,
})
if err != nil {
return xerrors.Errorf("failed to describe instances: %w", err)
}
for _, r := range resp.Reservations {
for _, i := range r.Instances {
if err := callback(i); err != nil {
return err
}
}
}
return nil
}
func (asg *AutoScalingGroup) launchNewInstances(oldInstanceCount int) error {
if oldInstanceCount == 0 {
return nil
}
requiredCount := int64(oldInstanceCount)
if len(asg.AvailabilityZones) > 2 && *asg.OriginalDesiredCapacity%int64(len(asg.AvailabilityZones)) > 0 {
// If there are more than two availability zones, the new desired capacity must be a multiple of the number of
// availability zones, otherwise AZRebalance will terminate some instances unexpectedly.
// Assume that there are following instances in each availability zone:
// ap-northeast-1a: 2, ap-northeast-1c: 1, ap-northeast-1d: 2
// After increasing the desired capacity to 10, that is, launching new instances as many as the old instances,
// the number of instances will change as below:
// ap-northeast-1a: 3 (old: 2, new: 1), ap-northeast-1c: 4 (old: 1, new: 3), ap-northeast-1d: 3 (old: 2, new: 1)
// After terminating old instances, the number of instances will change as below:
// ap-northeast-1a: 1, ap-northeast-1c: 3, ap-northeast-1d: 1
// AZRebalance will launch another instance in ap-northeast-1a or ap-northeast-1d and terminate one
// in ap-northeast-1c without draining it.
requiredCount += int64(len(asg.AvailabilityZones)) - *asg.OriginalDesiredCapacity%int64(len(asg.AvailabilityZones))
}
if err := asg.waitUntilInstancesInService(*asg.DesiredCapacity); err != nil {
return xerrors.Errorf("failed to wait until %d instances are in service: %w", *asg.DesiredCapacity, err)
}
newDesiredCapacity := *asg.OriginalDesiredCapacity + requiredCount
if newDesiredCapacity <= *asg.DesiredCapacity {
return nil
}
newDesiredMaxSize := *asg.MaxSize
if newDesiredCapacity > newDesiredMaxSize {
newDesiredMaxSize = newDesiredCapacity
}
if err := asg.saveCurrentState(); err != nil {
return xerrors.Errorf("failed to save the current state: %w", err)
}
log.Printf("Update the auto scaling group \"%s\": DesirdCapacity: %d, MaxSize: %d\n",
*asg.AutoScalingGroupName, newDesiredCapacity, newDesiredMaxSize)
_, err := asg.asSvc.UpdateAutoScalingGroup(&autoscaling.UpdateAutoScalingGroupInput{
AutoScalingGroupName: asg.AutoScalingGroupName,
DesiredCapacity: aws.Int64(newDesiredCapacity),
MaxSize: aws.Int64(newDesiredMaxSize),
})
if err != nil {
return xerrors.Errorf("failed to update the auto scaling group: %w", err)
}
if err := asg.waitUntilInstancesInService(newDesiredCapacity); err != nil {
return xerrors.Errorf("failed to wait until %d instances are in service: %w", newDesiredCapacity, err)
}
return asg.reload()
}
func (asg *AutoScalingGroup) terminateInstances(count int64, drainer Drainer) error {
if count == 0 {
return nil
}
// Sort instanceIDs to prevent AZRebalance from terminating instances unexpectedly
sortedInstanceIDs, err := asg.fetchSortedInstanceIDs(count)
if err != nil {
return xerrors.Errorf("failed to fetch sorted instance IDs: %w", err)
}
if err := drainer.Drain(sortedInstanceIDs); err != nil {
return xerrors.Errorf("failed to drain instances: %w", err)
}
for ids := range sliceutil.ChunkSlice(aws.StringSlice(sortedInstanceIDs), autoscalingconst.MaxDetachableInstances) {
log.Println("Detach instances:", aws.StringValueSlice(ids))
_, err := asg.asSvc.DetachInstances(&autoscaling.DetachInstancesInput{
AutoScalingGroupName: asg.AutoScalingGroupName,
InstanceIds: ids,
ShouldDecrementDesiredCapacity: aws.Bool(true),
})
if err != nil {
return xerrors.Errorf("failed to detach instances: %w", err)
}
}
log.Println("Terminate instances:", sortedInstanceIDs)
_, err = asg.ec2Svc.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: aws.StringSlice(sortedInstanceIDs),
})
if err != nil {
return xerrors.Errorf("failed to terminate the instances: %w", err)
}
err = asg.ec2Svc.WaitUntilInstanceTerminated(&ec2.DescribeInstancesInput{
InstanceIds: aws.StringSlice(sortedInstanceIDs),
})
if err != nil {
return xerrors.Errorf("failed to terminate the instances: %w", err)
}
return asg.reload()
}
func (asg *AutoScalingGroup) restoreState() error {
if *asg.DesiredCapacity != *asg.OriginalDesiredCapacity {
return xerrors.Errorf("can't restore the state unless the desired capacity is %d", *asg.OriginalDesiredCapacity)
}
log.Printf("Update the auto scaling group \"%s\": MaxSize: %d\n", *asg.AutoScalingGroupName, *asg.OriginalMaxSize)
_, err := asg.asSvc.UpdateAutoScalingGroup(&autoscaling.UpdateAutoScalingGroupInput{
AutoScalingGroupName: asg.AutoScalingGroupName,
MaxSize: asg.OriginalMaxSize,
})
if err != nil {
return xerrors.Errorf("failed to update the auto scaling group: %w", err)
}
_, err = asg.asSvc.DeleteTags(&autoscaling.DeleteTagsInput{
Tags: []*autoscaling.Tag{
asg.createTag("ecsmec:OriginalDesiredCapacity", fmt.Sprint(*asg.OriginalDesiredCapacity)),
asg.createTag("ecsmec:OriginalMaxSize", fmt.Sprint(*asg.OriginalMaxSize)),
asg.createTag("ecsmec:StateSavedAt", fmt.Sprint(asg.StateSavedAt.Format(time.RFC3339))),
},
})
if err != nil {
return xerrors.Errorf("failed to delete tags: %w", err)
}
return asg.reload()
}
func (asg *AutoScalingGroup) saveCurrentState() error {
var stateSavedAt time.Time
if asg.StateSavedAt != nil {
stateSavedAt = *asg.StateSavedAt
} else {
stateSavedAt = time.Now().UTC()
}
_, err := asg.asSvc.CreateOrUpdateTags(&autoscaling.CreateOrUpdateTagsInput{
Tags: []*autoscaling.Tag{
asg.createTag("ecsmec:OriginalDesiredCapacity", fmt.Sprint(*asg.OriginalDesiredCapacity)),
asg.createTag("ecsmec:OriginalMaxSize", fmt.Sprint(*asg.OriginalMaxSize)),
asg.createTag("ecsmec:StateSavedAt", stateSavedAt.Format(time.RFC3339)),
},
})
if err != nil {
return xerrors.Errorf("failed to create or update tags: %w", err)
}
return nil
}
func (asg *AutoScalingGroup) createTag(key string, value string) *autoscaling.Tag {
return &autoscaling.Tag{
Key: aws.String(key),
PropagateAtLaunch: aws.Bool(false),
ResourceId: asg.AutoScalingGroupName,
ResourceType: aws.String("auto-scaling-group"),
Value: aws.String(value),
}
}
func (asg *AutoScalingGroup) waitUntilInstancesInService(capacity int64) error {
// WaitUntilGroupInService doesn't work even if the MinSize is equal to the DesiredCapacity
// (https://github.com/aws/aws-sdk-go/issues/2478),
// so wait manually
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
timeout := 5 * time.Minute
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
resp, err := asg.asSvc.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{asg.AutoScalingGroupName},
})
if err != nil {
return xerrors.Errorf("failed to describe the auto scaling group: %w", err)
}
healthyInstanceCnt := int64(0)
for _, i := range resp.AutoScalingGroups[0].Instances {
if *i.LifecycleState == "InService" {
healthyInstanceCnt++
if healthyInstanceCnt == capacity {
return nil
}
}
}
select {
case <-ticker.C:
continue
case <-timer.C:
return xerrors.Errorf("can't prepare at least %d in-service instances within %v", capacity, timeout)
}
}
}
func (asg *AutoScalingGroup) fetchSortedInstanceIDs(count int64) ([]string, error) {
instances := make([]*ec2.Instance, 0, *asg.DesiredCapacity)
err := asg.fetchInstances(func(i *ec2.Instance) error {
instances = append(instances, i)
return nil
})
if err != nil {
return nil, xerrors.Errorf("failed to fetch instances: %w", err)
}
sort.SliceStable(instances, func(i, j int) bool {
return instances[i].LaunchTime.Before(*instances[j].LaunchTime)
})
azs := make([]string, 0)
azToInstances := make(map[string][]*ec2.Instance)
azToOldInstanceCount := make(map[string]int)
for _, i := range instances {
az := *i.Placement.AvailabilityZone
if !sliceutil.Contains(azs, az) {
azs = append(azs, az)
}
azToInstances[az] = append(azToInstances[az], i)
if asg.StateSavedAt != nil && i.LaunchTime.Before(*asg.StateSavedAt) {
azToOldInstanceCount[az] += 1
}
}
sort.SliceStable(azs, func(i, j int) bool {
if len(azToInstances[azs[i]]) == len(azToInstances[azs[j]]) {
return azToOldInstanceCount[azs[i]] > azToOldInstanceCount[azs[j]]
} else {
return len(azToInstances[azs[i]]) > len(azToInstances[azs[j]])
}
})
sortedInstanceIDs := make([]string, 0, count)
Loop:
for {
for _, az := range azs {
if int64(len(sortedInstanceIDs)) == count {
break Loop
}
var i *ec2.Instance
i, azToInstances[az] = azToInstances[az][0], azToInstances[az][1:]
sortedInstanceIDs = append(sortedInstanceIDs, *i.InstanceId)
}
}
return sortedInstanceIDs, nil
}