-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
331 lines (313 loc) · 9.62 KB
/
main.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
package main
import (
"strings"
"github.com/juju/loggo"
"fmt"
"math"
"os"
"time"
)
// logging
var mainLogger = loggo.GetLogger("ecs-upgrade")
func main() {
if os.Getenv("DEBUG") == "true" {
loggo.ConfigureLoggers(`<root>=DEBUG`)
} else {
loggo.ConfigureLoggers(`<root>=INFO`)
}
os.Exit(mainWithReturnCode())
}
func mainWithReturnCode() int {
// initialize
e := ECS{}
var err error
asgName := os.Getenv("ECS_ASG")
if len(asgName) == 0 {
fmt.Printf("ECS_ASG not set\n")
return 1
}
clusterName := os.Getenv("ECS_CLUSTER")
if len(clusterName) == 0 {
fmt.Printf("ECS_CLUSTER not set\n")
return 1
}
useLaunchTemplates := os.Getenv("LAUNCH_TEMPLATES")
a := NewAutoscaling()
// get asg
asg, err := a.describeAutoscalingGroup(asgName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
var newLaunchIdentifier string
if useLaunchTemplates == "true" {
newLaunchIdentifier, err = scaleWithLaunchTemplate(a, asg)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
} else {
newLaunchIdentifier, err = scaleWithLaunchConfig(a, asg)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
}
if newLaunchIdentifier == "" {
fmt.Printf("Launch configuration is already at latest version")
return 0
}
// wait until new instances are healthy
var healthy bool
var instances []AutoscalingInstance
for i := 0; !healthy && i < 25; i++ {
instances, err = a.getAutoscalingInstanceHealth(asgName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
var healthyInstances int64
for _, instance := range instances {
if checkInstanceLaunchConfigOrTemplate(useLaunchTemplates, instance, newLaunchIdentifier) {
if instance.HealthStatus == "HEALTHY" {
healthyInstances += 1
} else {
mainLogger.Debugf("Waiting for instance %s to become healthy (currently %s)", instance.InstanceId, instance.HealthStatus)
}
}
}
if healthyInstances >= asg.DesiredCapacity {
healthy = true
} else {
waitTime := int(math.Max(float64(len(instances)), 30))
mainLogger.Debugf("Checking autoscaling instances health: Waiting %ds", waitTime)
time.Sleep(time.Duration(waitTime) * time.Second)
}
}
// wait for new nodes to attach
err = e.waitForNewNodes(clusterName, len(instances))
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
// drain
mainLogger.Debugf("Draining instances")
drainedContainerArns, err := drain(clusterName, instances, newLaunchIdentifier, useLaunchTemplates)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
// wait until nodes are drained
mainLogger.Debugf("Wait for Drained instances")
err = e.waitForDrainedNode(clusterName, drainedContainerArns)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
// check target health
mainLogger.Debugf("Checking targets health")
err = checkTargetHealth(a, asgName, newLaunchIdentifier, useLaunchTemplates, clusterName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
// scale down
mainLogger.Debugf("Scaling down")
err = a.scaleAutoscalingGroup(asgName, asg.DesiredCapacity)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
// delete old launchconfig
if useLaunchTemplates != "true" {
err = a.deleteLaunchConfig(asg.LaunchConfigurationName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return 1
}
}
fmt.Printf("Upgrade completed\n")
return 0
}
func drain(clusterName string, instances []AutoscalingInstance, newLaunchIdentifier string, useLaunchTemplates string) ([]string, error) {
var drainedContainerArns []string
var instancesToDrain []string
e := ECS{}
for _, instance := range instances {
if !checkInstanceLaunchConfigOrTemplate(useLaunchTemplates, instance, newLaunchIdentifier) {
instancesToDrain = append(instancesToDrain, instance.InstanceId)
mainLogger.Debugf("Going to drain %s", instance.InstanceId)
}
}
if float64(len(instancesToDrain)) > math.Ceil(float64(len(instances)/2)) {
return drainedContainerArns, fmt.Errorf("Going to drain %d instances out of %d, which is more than 50%%", len(instancesToDrain), len(instances))
}
containerInstanceArns, err := e.listContainerInstances(clusterName)
if err != nil {
return drainedContainerArns, err
}
containerInstances, err := e.describeContainerInstances(clusterName, containerInstanceArns)
if err != nil {
return drainedContainerArns, err
}
for _, instanceId := range instancesToDrain {
if containerId, ok := containerInstances[instanceId]; ok {
err = e.drainNode(clusterName, containerId)
if err != nil {
return drainedContainerArns, err
}
drainedContainerArns = append(drainedContainerArns, containerId)
} else {
return drainedContainerArns, fmt.Errorf("Couldn't drain instance %s", instanceId)
}
}
return drainedContainerArns, nil
}
func checkTargetHealth(a Autoscaling, asgName, newLaunchIdentifier, useLaunchTemplates, clusterName string) error {
lb := LB{}
e := ECS{}
targetGroups, err := lb.getTargets()
if err != nil {
return err
}
var allHealthy bool
// get container instances
containerInstanceArns, err := e.listContainerInstances(clusterName)
if err != nil {
return err
}
containerInstances, err := e.describeContainerInstances(clusterName, containerInstanceArns)
if err != nil {
return err
}
for i := 0; !allHealthy && i < 25; i++ {
// refresh instances
instances, err := a.getAutoscalingInstanceHealth(asgName)
if err != nil {
return err
}
// get tasks
tasks, err := e.ListTasks(clusterName, "RUNNING")
if err != nil {
return err
}
IPsPerContainerInstance, err := e.getTaskIPsPerContainerInstance(clusterName, tasks)
// print instances
for _, instance := range instances {
if checkInstanceLaunchConfigOrTemplate(useLaunchTemplates, instance, newLaunchIdentifier) {
instanceIPList := getInstanceIPList(containerInstances, instance.InstanceId, IPsPerContainerInstance)
autoscalingLogger.Debugf("checkTargetHealth: retrieved instance %s with IPs (%s) and AWSVPC IPs (%s)", instance.InstanceId, strings.Join(instance.IPs, ","), strings.Join(instanceIPList, ","))
}
}
// check health
var unhealthy, healthy int64
for _, targetGroup := range targetGroups {
targetsHealth, err := lb.getTargetHealth(targetGroup)
if err != nil {
return err
}
for id, targetHealth := range targetsHealth {
for _, instance := range instances {
// id without awsvpc is instanceID, id with awsVPC is IP address. Let's compare both
instanceIPList := getInstanceIPList(containerInstances, instance.InstanceId, IPsPerContainerInstance)
if (instance.InstanceId == id || stringInSlice(id, instance.IPs) || stringInSlice(id, instanceIPList)) && checkInstanceLaunchConfigOrTemplate(useLaunchTemplates, instance, newLaunchIdentifier) {
mainLogger.Debugf("Found instance %s in target group %s with health %s", id, targetGroup, targetHealth)
if targetHealth == "healthy" {
healthy++
} else {
unhealthy++
}
}
}
}
}
if healthy > 0 && unhealthy == 0 {
mainLogger.Debugf("All instances of target groups are healthy")
allHealthy = true
} else {
mainLogger.Debugf("Checking loadbalancer target instances health: Waiting 30s (healthy: %d, unhealthy: %d)", healthy, unhealthy)
time.Sleep(30 * time.Second)
}
}
return nil
}
func getInstanceIPList(containerInstances map[string]string, instanceID string, IPsPerContainerInstance map[string][]string) []string {
if containerARN, ok := containerInstances[instanceID]; ok {
if instanceIPList, ok2 := IPsPerContainerInstance[containerARN]; ok2 {
return instanceIPList
}
}
return []string{}
}
func scaleWithLaunchConfig(a Autoscaling, asg AutoscalingGroup) (string, error) {
// create new launch config
newLaunchConfigName, err := a.newLaunchConfigFromExisting(asg.LaunchConfigurationName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return "", err
}
if newLaunchConfigName == "" {
return "", fmt.Errorf("New Launch config name is empty (previous launch config name: %s)", asg.LaunchConfigurationName)
}
// update autoscaling group
err = a.updateAutoscalingLaunchConfig(asg.AutoscalingGroupName, newLaunchConfigName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return "", err
}
// scale
err = a.scaleAutoscalingGroup(asg.AutoscalingGroupName, asg.DesiredCapacity*2)
if err != nil {
fmt.Printf("Error: %v\n", err)
return "", err
}
return newLaunchConfigName, nil
}
func scaleWithLaunchTemplate(a Autoscaling, asg AutoscalingGroup) (string, error) {
// create new launch config
_, newLaunchTemplateName, newLaunchTemplateVersion, err := a.newLaunchTemplateVersion(asg.LaunchTemplateName)
if err != nil {
fmt.Printf("Error: %v\n", err)
return "", err
}
if newLaunchTemplateName == "" {
return "", nil
}
// update autoscaling group
err = a.updateAutoscalingLaunchTemplate(asg.AutoscalingGroupName, newLaunchTemplateName, newLaunchTemplateVersion)
if err != nil {
fmt.Printf("Error: %v\n", err)
return "", err
}
// scale
err = a.scaleAutoscalingGroup(asg.AutoscalingGroupName, asg.DesiredCapacity*2)
if err != nil {
fmt.Printf("Error: %v\n", err)
return "", err
}
return newLaunchTemplateName + ":" + newLaunchTemplateVersion, nil
}
func checkInstanceLaunchConfigOrTemplate(useLaunchTemplates string, instance AutoscalingInstance, newName string) bool {
if useLaunchTemplates == "true" {
s := strings.Split(newName, ":")
if len(s) != 2 {
return false
}
if instance.LaunchTemplateName == s[0] && instance.LaunchTemplateVersion == s[1] {
return true
}
} else {
if instance.LaunchConfig == newName {
return true
}
}
return false
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}