-
Notifications
You must be signed in to change notification settings - Fork 4
/
asg.go
241 lines (217 loc) · 7.52 KB
/
asg.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
package awsecs
import (
"errors"
"fmt"
"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/ecs"
"github.com/cenkalti/backoff"
"log"
"strings"
"sync"
)
func listASGInstaces(ASAPI autoscalingiface.AutoScalingAPI, asgName string) ([]*autoscaling.Instance, *string, error) {
output, err := ASAPI.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{aws.String(asgName)},
})
if err != nil {
return []*autoscaling.Instance{}, nil, err
}
for _, autoScalingGroup := range output.AutoScalingGroups {
return autoScalingGroup.Instances, autoScalingGroup.LaunchConfigurationName, nil
}
return []*autoscaling.Instance{}, nil, errors.New("asg not found")
}
func needReplacement(expectedLaunchConfig string, instance autoscaling.Instance) bool {
if instance.LaunchConfigurationName == nil {
return true
}
if *instance.LaunchConfigurationName != expectedLaunchConfig {
return true
}
return false
}
func filterInstancesToReplace(expectedLaunchConfig *string, instances []*autoscaling.Instance) (filtered []autoscaling.Instance) {
if expectedLaunchConfig == nil {
return
}
for _, instance := range instances {
if instance != nil {
if needReplacement(*expectedLaunchConfig, *instance) {
filtered = append(filtered, *instance)
}
}
}
return
}
type ecsEC2Instance struct {
ec2InstanceID string
ecsContainerInstanceID string
}
func containerInstanceArnsToContainerInstanceIds(input []*string) (output []*string) {
for _, arn := range input {
output = append(output, aws.String(containerInstanceArnToContainerInstanceID(*arn)))
}
return
}
func containerInstanceArnToContainerInstanceID(input string) (output string) {
parts := strings.Split(input, "/")
output = strings.Join(parts[len(parts)-1:], "")
return
}
func instancesToContainerInstances(ECSAPI ecs.ECS, instances []autoscaling.Instance, clusterName string) ([]ecsEC2Instance, error) {
var ecsEC2Instances []ecsEC2Instance
var describeContainerInstancesInputs []*ecs.DescribeContainerInstancesInput
err := ECSAPI.ListContainerInstancesPages(
&ecs.ListContainerInstancesInput{Cluster: aws.String(clusterName)},
func(page *ecs.ListContainerInstancesOutput, lastPage bool) bool {
describeContainerInstancesInputs = append(describeContainerInstancesInputs, &ecs.DescribeContainerInstancesInput{
Cluster: aws.String(clusterName),
ContainerInstances: containerInstanceArnsToContainerInstanceIds(page.ContainerInstanceArns),
})
return true
})
if err != nil {
return []ecsEC2Instance{}, err
}
for _, input := range describeContainerInstancesInputs {
output, err := ECSAPI.DescribeContainerInstances(input)
if err != nil {
return []ecsEC2Instance{}, err
}
for _, instance := range instances {
for _, containerInstance := range output.ContainerInstances {
if *containerInstance.Ec2InstanceId == *instance.InstanceId {
ecsEC2Instances = append(ecsEC2Instances, ecsEC2Instance{
ec2InstanceID: *instance.InstanceId,
ecsContainerInstanceID: containerInstanceArnToContainerInstanceID(*containerInstance.ContainerInstanceArn),
})
goto gotobreak
}
}
gotobreak:
}
}
return ecsEC2Instances, nil
}
func detachAndDrain(ASAPI autoscaling.AutoScaling, ECSAPI ecs.ECS, instance ecsEC2Instance, asgName, clusterName string) error {
output, err := ASAPI.DetachInstances(&autoscaling.DetachInstancesInput{
AutoScalingGroupName: aws.String(asgName),
InstanceIds: []*string{aws.String(instance.ec2InstanceID)},
ShouldDecrementDesiredCapacity: aws.Bool(false),
})
if err != nil {
return fmt.Errorf("%v %v", instance, err)
}
for _, activity := range output.Activities {
log.Printf("%v %v", instance, *activity.Description)
}
_, err = ECSAPI.UpdateContainerInstancesState(&ecs.UpdateContainerInstancesStateInput{
Cluster: aws.String(clusterName),
ContainerInstances: []*string{aws.String(instance.ecsContainerInstanceID)},
Status: aws.String("DRAINING"),
})
reAttach := func() {
_, err2 := ASAPI.AttachInstances(&autoscaling.AttachInstancesInput{
AutoScalingGroupName: aws.String(asgName),
InstanceIds: []*string{aws.String(instance.ec2InstanceID)},
})
if err2 != nil {
log.Printf("[ACTIONABLE ACTION REQUIRED] instance re-attachment failed!")
log.Printf("%v %v", instance, err2)
}
}
if err != nil {
reAttach()
return fmt.Errorf("%v %v", instance, err)
}
operation := func() error {
err := drainingContainerInstanceIsDrained(ECSAPI, clusterName, instance.ecsContainerInstanceID)
if err != nil {
log.Printf("%v %v", instance, err)
}
return err
}
err = backoff.Retry(operation, backoff.NewExponentialBackOff())
if err != nil {
reAttach()
log.Printf("[ACTIONABLE ACTION REQUIRED] instance left in DRAINING status!")
return fmt.Errorf("%v %v", instance, err)
}
return nil
}
func drainingContainerInstanceIsDrained(ECSAPI ecs.ECS, clusterName, containerInstanceID string) error {
output, err := ECSAPI.DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{
Cluster: aws.String(clusterName),
ContainerInstances: []*string{aws.String(containerInstanceID)},
})
if err != nil {
return err
}
for _, containerInstance := range output.ContainerInstances {
if *containerInstance.Status != "DRAINING" {
return backoff.Permanent(errors.New("the instance should be DRAINING but is not"))
}
if *containerInstance.RunningTasksCount != 0 {
return errors.New("container instance still DRAINING")
}
return nil
}
return backoff.Permanent(errors.New("container instance not found"))
}
func drainAll(ASAPI autoscaling.AutoScaling, ECSAPI ecs.ECS, EC2API ec2.EC2, instances []ecsEC2Instance, asgName, clusterName string) error {
errors := make([]error, len(instances))
var wg sync.WaitGroup
for i, instance := range instances {
wg.Add(1)
go func(thatInstance ecsEC2Instance, index int) {
defer wg.Done()
errors[index] = detachAndDrain(ASAPI, ECSAPI, thatInstance, asgName, clusterName)
if errors[index] == nil {
_, err := EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{
aws.String(thatInstance.ec2InstanceID),
},
})
errors[index] = err
}
}(instance, i)
}
wg.Wait()
var onlyErrors []error
for _, err := range errors {
if err != nil {
onlyErrors = append(onlyErrors, err)
}
}
if len(onlyErrors) > 0 {
return fmt.Errorf("%v", onlyErrors)
}
return nil
}
func enforceLaunchConfig(ECSAPI ecs.ECS, ASAPI autoscaling.AutoScaling, EC2API ec2.EC2, asgName, clusterName string, bo backoff.BackOff) error {
asgInstances, expectedLaunchConfig, err := listASGInstaces(&ASAPI, asgName)
if err != nil {
return err
}
instances, err := instancesToContainerInstances(ECSAPI, filterInstancesToReplace(expectedLaunchConfig, asgInstances), clusterName)
if err != nil {
return err
}
return drainAll(ASAPI, ECSAPI, EC2API, instances, asgName, clusterName)
}
// EnforceLaunchConfig encapsulates the attributes of a LaunchConfig enforcement
type EnforceLaunchConfig struct {
ECSAPI ecs.ECS
ASAPI autoscaling.AutoScaling
EC2API ec2.EC2
ASGName string
ECSClusterName string
BackOff backoff.BackOff
}
// Apply the LaunchConfig enforcement
func (e *EnforceLaunchConfig) Apply() error {
return enforceLaunchConfig(e.ECSAPI, e.ASAPI, e.EC2API, e.ASGName, e.ECSClusterName, e.BackOff)
}