Skip to content

Commit b3539bc

Browse files
authored
Add utilities for autoscaling. (#72)
1 parent 50a97de commit b3539bc

File tree

6 files changed

+544
-4
lines changed

6 files changed

+544
-4
lines changed

awscommons/v2/autoscaling.go

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
package awscommons
2+
3+
import (
4+
"fmt"
5+
"time"
6+
7+
"github.com/aws/aws-sdk-go-v2/aws"
8+
"github.com/aws/aws-sdk-go-v2/service/autoscaling"
9+
autoscalingTypes "github.com/aws/aws-sdk-go-v2/service/autoscaling/types"
10+
"github.com/gruntwork-io/go-commons/collections"
11+
"github.com/gruntwork-io/go-commons/errors"
12+
"github.com/gruntwork-io/go-commons/logging"
13+
"github.com/gruntwork-io/go-commons/retry"
14+
)
15+
16+
// GetAsgByName finds the Auto Scaling Group matching the given name. Returns an error if it cannot find a match.
17+
func GetAsgByName(opts *Options, asgName string) (*autoscalingTypes.AutoScalingGroup, error) {
18+
client, err := NewAutoScalingClient(opts)
19+
if err != nil {
20+
return nil, errors.WithStackTrace(err)
21+
}
22+
23+
input := &autoscaling.DescribeAutoScalingGroupsInput{AutoScalingGroupNames: []string{asgName}}
24+
output, err := client.DescribeAutoScalingGroups(opts.Context, input)
25+
if err != nil {
26+
return nil, errors.WithStackTrace(err)
27+
}
28+
groups := output.AutoScalingGroups
29+
if len(groups) == 0 {
30+
return nil, errors.WithStackTrace(NewLookupError("ASG", asgName, "detailed data"))
31+
}
32+
return &groups[0], nil
33+
}
34+
35+
// ScaleUp sets the desired capacity, waits until all the instances are available, and returns the new instance IDs.
36+
func ScaleUp(
37+
opts *Options,
38+
asgName string,
39+
originalInstanceIds []string,
40+
desiredCapacity int32,
41+
maxRetries int,
42+
sleepBetweenRetries time.Duration,
43+
) ([]string, error) {
44+
logger := logging.GetProjectLogger()
45+
46+
client, err := NewAutoScalingClient(opts)
47+
if err != nil {
48+
return nil, err
49+
}
50+
51+
err = setAsgCapacity(client, opts, asgName, desiredCapacity)
52+
if err != nil {
53+
logger.Errorf("Failed to set ASG desired capacity to %d", desiredCapacity)
54+
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.")
55+
return nil, err
56+
}
57+
58+
err = waitForCapacity(opts, asgName, maxRetries, sleepBetweenRetries)
59+
if err != nil {
60+
logger.Errorf("Timed out waiting for ASG to reach desired capacity.")
61+
logger.Errorf("Undo by terminating all the new instances and trying again.")
62+
return nil, err
63+
}
64+
65+
newInstanceIds, err := getLaunchedInstanceIds(opts, asgName, originalInstanceIds)
66+
if err != nil {
67+
logger.Errorf("Error retrieving information about the ASG.")
68+
logger.Errorf("Undo by terminating all the new instances and trying again.")
69+
return nil, err
70+
}
71+
72+
return newInstanceIds, nil
73+
}
74+
75+
// getLaunchedInstanceIds returns a list of the newly launched instance IDs in the ASG, given a list of the old instance
76+
// IDs before any change was made.
77+
func getLaunchedInstanceIds(opts *Options, asgName string, existingInstanceIds []string) ([]string, error) {
78+
asg, err := GetAsgByName(opts, asgName)
79+
if err != nil {
80+
return nil, err
81+
}
82+
allInstances := asg.Instances
83+
allInstanceIds := idsFromAsgInstances(allInstances)
84+
newInstanceIds := []string{}
85+
for _, instanceId := range allInstanceIds {
86+
if !collections.ListContainsElement(existingInstanceIds, instanceId) {
87+
newInstanceIds = append(newInstanceIds, instanceId)
88+
}
89+
}
90+
return newInstanceIds, nil
91+
}
92+
93+
// setAsgCapacity sets the desired capacity on the auto scaling group. This will not wait for the ASG to expand or
94+
// shrink to that size. See waitForCapacity.
95+
func setAsgCapacity(client *autoscaling.Client, opts *Options, asgName string, desiredCapacity int32) error {
96+
logger := logging.GetProjectLogger()
97+
logger.Infof("Updating ASG %s desired capacity to %d.", asgName, desiredCapacity)
98+
99+
input := &autoscaling.SetDesiredCapacityInput{
100+
AutoScalingGroupName: aws.String(asgName),
101+
DesiredCapacity: aws.Int32(desiredCapacity),
102+
}
103+
_, err := client.SetDesiredCapacity(opts.Context, input)
104+
if err != nil {
105+
return errors.WithStackTrace(err)
106+
}
107+
108+
logger.Infof("Requested ASG %s desired capacity to be %d.", asgName, desiredCapacity)
109+
return nil
110+
}
111+
112+
// SetAsgMaxSize sets the max size on the auto scaling group. Note that updating the max size does not typically
113+
// change the cluster size.
114+
func SetAsgMaxSize(client *autoscaling.Client, opts *Options, asgName string, maxSize int32) error {
115+
logger := logging.GetProjectLogger()
116+
logger.Infof("Updating ASG %s max size to %d.", asgName, maxSize)
117+
118+
input := &autoscaling.UpdateAutoScalingGroupInput{
119+
AutoScalingGroupName: aws.String(asgName),
120+
MaxSize: aws.Int32(maxSize),
121+
}
122+
_, err := client.UpdateAutoScalingGroup(opts.Context, input)
123+
if err != nil {
124+
return errors.WithStackTrace(err)
125+
}
126+
127+
logger.Infof("Requested ASG %s max size to be %d.", asgName, maxSize)
128+
return nil
129+
}
130+
131+
// waitForCapacity waits for the desired capacity to be reached.
132+
func waitForCapacity(
133+
opts *Options,
134+
asgName string,
135+
maxRetries int,
136+
sleepBetweenRetries time.Duration,
137+
) error {
138+
logger := logging.GetProjectLogger()
139+
logger.Infof("Waiting for ASG %s to reach desired capacity.", asgName)
140+
141+
err := retry.DoWithRetry(
142+
logger.Logger,
143+
"Waiting for desired capacity to be reached.",
144+
maxRetries, sleepBetweenRetries,
145+
func() error {
146+
logger.Infof("Checking ASG %s capacity.", asgName)
147+
asg, err := GetAsgByName(opts, asgName)
148+
if err != nil {
149+
// TODO: Should we retry this lookup or fail right away?
150+
return retry.FatalError{Underlying: err}
151+
}
152+
153+
currentCapacity := int32(len(asg.Instances))
154+
desiredCapacity := *asg.DesiredCapacity
155+
156+
if currentCapacity == desiredCapacity {
157+
logger.Infof("ASG %s met desired capacity!", asgName)
158+
return nil
159+
}
160+
161+
logger.Infof("ASG %s not yet at desired capacity %d (current %d).", asgName, desiredCapacity, currentCapacity)
162+
logger.Infof("Waiting for %s...", sleepBetweenRetries)
163+
return errors.WithStackTrace(fmt.Errorf("still waiting for desired capacity to be reached"))
164+
},
165+
)
166+
167+
if err != nil {
168+
return NewCouldNotMeetASGCapacityError(
169+
asgName,
170+
"Error waiting for ASG desired capacity to be reached.",
171+
)
172+
}
173+
174+
return nil
175+
}
176+
177+
// DetachInstances requests AWS to detach the instances, removing them from the ASG. It will also
178+
// request to auto decrement the desired capacity.
179+
func DetachInstances(opts *Options, asgName string, idList []string) error {
180+
logger := logging.GetProjectLogger()
181+
logger.Infof("Detaching %d instances from ASG %s", len(idList), asgName)
182+
183+
client, err := NewAutoScalingClient(opts)
184+
if err != nil {
185+
return errors.WithStackTrace(err)
186+
}
187+
188+
// AWS has a 20 instance limit for this, so we detach in groups of 20 ids
189+
for _, smallIDList := range collections.BatchListIntoGroupsOf(idList, 20) {
190+
input := &autoscaling.DetachInstancesInput{
191+
AutoScalingGroupName: aws.String(asgName),
192+
InstanceIds: smallIDList,
193+
ShouldDecrementDesiredCapacity: aws.Bool(true),
194+
}
195+
_, err := client.DetachInstances(opts.Context, input)
196+
if err != nil {
197+
return errors.WithStackTrace(err)
198+
}
199+
}
200+
201+
logger.Infof("Detached %d instances from ASG %s", len(idList), asgName)
202+
return nil
203+
}
204+
205+
// idsFromAsgInstances returns a list of the instance IDs given a list of instance representations from the ASG API.
206+
func idsFromAsgInstances(instances []autoscalingTypes.Instance) []string {
207+
idList := []string{}
208+
for _, inst := range instances {
209+
idList = append(idList, aws.ToString(inst.InstanceId))
210+
}
211+
return idList
212+
}
213+
214+
// NewAutoscalingClient returns a new AWS SDK client for interacting with AWS Autoscaling.
215+
func NewAutoScalingClient(opts *Options) (*autoscaling.Client, error) {
216+
cfg, err := NewDefaultConfig(opts)
217+
if err != nil {
218+
return nil, errors.WithStackTrace(err)
219+
}
220+
return autoscaling.NewFromConfig(cfg), nil
221+
}

0 commit comments

Comments
 (0)