-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoscaling.go
221 lines (191 loc) · 7.32 KB
/
autoscaling.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
package awscommons
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/autoscaling"
autoscalingTypes "github.com/aws/aws-sdk-go-v2/service/autoscaling/types"
"github.com/biptec/go-commons/collections"
"github.com/biptec/go-commons/errors"
"github.com/biptec/go-commons/logging"
"github.com/biptec/go-commons/retry"
)
// GetAsgByName finds the Auto Scaling Group matching the given name. Returns an error if it cannot find a match.
func GetAsgByName(opts *Options, asgName string) (*autoscalingTypes.AutoScalingGroup, error) {
client, err := NewAutoScalingClient(opts)
if err != nil {
return nil, errors.WithStackTrace(err)
}
input := &autoscaling.DescribeAutoScalingGroupsInput{AutoScalingGroupNames: []string{asgName}}
output, err := client.DescribeAutoScalingGroups(opts.Context, input)
if err != nil {
return nil, errors.WithStackTrace(err)
}
groups := output.AutoScalingGroups
if len(groups) == 0 {
return nil, errors.WithStackTrace(NewLookupError("ASG", asgName, "detailed data"))
}
return &groups[0], nil
}
// ScaleUp sets the desired capacity, waits until all the instances are available, and returns the new instance IDs.
func ScaleUp(
opts *Options,
asgName string,
originalInstanceIds []string,
desiredCapacity int32,
maxRetries int,
sleepBetweenRetries time.Duration,
) ([]string, error) {
logger := logging.GetProjectLogger()
client, err := NewAutoScalingClient(opts)
if err != nil {
return nil, err
}
err = setAsgCapacity(client, opts, asgName, desiredCapacity)
if err != nil {
logger.Errorf("Failed to set ASG desired capacity to %d", desiredCapacity)
logger.Errorf("If the capacity is set in AWS, undo by lowering back to the original desired capacity. If the desired capacity is not yet set, triage the error message below and try again.")
return nil, err
}
err = waitForCapacity(opts, asgName, maxRetries, sleepBetweenRetries)
if err != nil {
logger.Errorf("Timed out waiting for ASG to reach desired capacity.")
logger.Errorf("Undo by terminating all the new instances and trying again.")
return nil, err
}
newInstanceIds, err := getLaunchedInstanceIds(opts, asgName, originalInstanceIds)
if err != nil {
logger.Errorf("Error retrieving information about the ASG.")
logger.Errorf("Undo by terminating all the new instances and trying again.")
return nil, err
}
return newInstanceIds, nil
}
// getLaunchedInstanceIds returns a list of the newly launched instance IDs in the ASG, given a list of the old instance
// IDs before any change was made.
func getLaunchedInstanceIds(opts *Options, asgName string, existingInstanceIds []string) ([]string, error) {
asg, err := GetAsgByName(opts, asgName)
if err != nil {
return nil, err
}
allInstances := asg.Instances
allInstanceIds := idsFromAsgInstances(allInstances)
newInstanceIds := []string{}
for _, instanceId := range allInstanceIds {
if !collections.ListContainsElement(existingInstanceIds, instanceId) {
newInstanceIds = append(newInstanceIds, instanceId)
}
}
return newInstanceIds, nil
}
// setAsgCapacity sets the desired capacity on the auto scaling group. This will not wait for the ASG to expand or
// shrink to that size. See waitForCapacity.
func setAsgCapacity(client *autoscaling.Client, opts *Options, asgName string, desiredCapacity int32) error {
logger := logging.GetProjectLogger()
logger.Infof("Updating ASG %s desired capacity to %d.", asgName, desiredCapacity)
input := &autoscaling.SetDesiredCapacityInput{
AutoScalingGroupName: aws.String(asgName),
DesiredCapacity: aws.Int32(desiredCapacity),
}
_, err := client.SetDesiredCapacity(opts.Context, input)
if err != nil {
return errors.WithStackTrace(err)
}
logger.Infof("Requested ASG %s desired capacity to be %d.", asgName, desiredCapacity)
return nil
}
// SetAsgMaxSize sets the max size on the auto scaling group. Note that updating the max size does not typically
// change the cluster size.
func SetAsgMaxSize(client *autoscaling.Client, opts *Options, asgName string, maxSize int32) error {
logger := logging.GetProjectLogger()
logger.Infof("Updating ASG %s max size to %d.", asgName, maxSize)
input := &autoscaling.UpdateAutoScalingGroupInput{
AutoScalingGroupName: aws.String(asgName),
MaxSize: aws.Int32(maxSize),
}
_, err := client.UpdateAutoScalingGroup(opts.Context, input)
if err != nil {
return errors.WithStackTrace(err)
}
logger.Infof("Requested ASG %s max size to be %d.", asgName, maxSize)
return nil
}
// waitForCapacity waits for the desired capacity to be reached.
func waitForCapacity(
opts *Options,
asgName string,
maxRetries int,
sleepBetweenRetries time.Duration,
) error {
logger := logging.GetProjectLogger()
logger.Infof("Waiting for ASG %s to reach desired capacity.", asgName)
err := retry.DoWithRetry(
logger,
"Waiting for desired capacity to be reached.",
maxRetries, sleepBetweenRetries,
func() error {
logger.Infof("Checking ASG %s capacity.", asgName)
asg, err := GetAsgByName(opts, asgName)
if err != nil {
// TODO: Should we retry this lookup or fail right away?
return retry.FatalError{Underlying: err}
}
currentCapacity := int32(len(asg.Instances))
desiredCapacity := *asg.DesiredCapacity
if currentCapacity == desiredCapacity {
logger.Infof("ASG %s met desired capacity!", asgName)
return nil
}
logger.Infof("ASG %s not yet at desired capacity %d (current %d).", asgName, desiredCapacity, currentCapacity)
logger.Infof("Waiting for %s...", sleepBetweenRetries)
return errors.WithStackTrace(fmt.Errorf("still waiting for desired capacity to be reached"))
},
)
if err != nil {
return NewCouldNotMeetASGCapacityError(
asgName,
"Error waiting for ASG desired capacity to be reached.",
)
}
return nil
}
// DetachInstances requests AWS to detach the instances, removing them from the ASG. It will also
// request to auto decrement the desired capacity.
func DetachInstances(opts *Options, asgName string, idList []string) error {
logger := logging.GetProjectLogger()
logger.Infof("Detaching %d instances from ASG %s", len(idList), asgName)
client, err := NewAutoScalingClient(opts)
if err != nil {
return errors.WithStackTrace(err)
}
// AWS has a 20 instance limit for this, so we detach in groups of 20 ids
for _, smallIDList := range collections.BatchListIntoGroupsOf(idList, 20) {
input := &autoscaling.DetachInstancesInput{
AutoScalingGroupName: aws.String(asgName),
InstanceIds: smallIDList,
ShouldDecrementDesiredCapacity: aws.Bool(true),
}
_, err := client.DetachInstances(opts.Context, input)
if err != nil {
return errors.WithStackTrace(err)
}
}
logger.Infof("Detached %d instances from ASG %s", len(idList), asgName)
return nil
}
// idsFromAsgInstances returns a list of the instance IDs given a list of instance representations from the ASG API.
func idsFromAsgInstances(instances []autoscalingTypes.Instance) []string {
idList := []string{}
for _, inst := range instances {
idList = append(idList, aws.ToString(inst.InstanceId))
}
return idList
}
// NewAutoscalingClient returns a new AWS SDK client for interacting with AWS Autoscaling.
func NewAutoScalingClient(opts *Options) (*autoscaling.Client, error) {
cfg, err := NewDefaultConfig(opts)
if err != nil {
return nil, errors.WithStackTrace(err)
}
return autoscaling.NewFromConfig(cfg), nil
}