forked from openfresh/ecs-formation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
478 lines (376 loc) · 11.9 KB
/
service.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package service
import (
"errors"
"fmt"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/stormcat24/ecs-formation/aws"
"github.com/stormcat24/ecs-formation/logger"
"github.com/stormcat24/ecs-formation/util"
"github.com/str1ngs/ansi/color"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
type TaskWatchStatus int
const (
WatchContinue TaskWatchStatus = iota
WatchFinish
WatchTerminate
)
type ServiceController struct {
manager *aws.AwsManager
targetResources []string
clusters []Cluster
params map[string]string
}
func NewServiceController(manager *aws.AwsManager, projectDir string, targetResources []string, params map[string]string) (*ServiceController, error) {
con := &ServiceController{
manager: manager,
params: params,
targetResources: targetResources,
}
clusters, err := con.searchServices(projectDir)
if err != nil {
return nil, err
}
con.clusters = clusters
return con, nil
}
func (self *ServiceController) searchServices(projectDir string) ([]Cluster, error) {
clusterDir := projectDir + "/service"
clusters := []Cluster{}
filePattern := regexp.MustCompile(`^.+\/(.+)\.yml$`)
filepath.Walk(clusterDir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() || !strings.HasSuffix(path, ".yml") {
return nil
}
if len(self.targetResources) > 0 {
flg := false
for _, res := range self.targetResources {
if strings.HasSuffix(path, fmt.Sprintf("%s.yml", res)) {
flg = true
}
}
if !flg {
return nil
}
}
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
merged := util.MergeYamlWithParameters(content, self.params)
tokens := filePattern.FindStringSubmatch(path)
clusterName := tokens[1]
serviceMap, err := CreateServiceMap(merged)
if err != nil {
return err
}
cluster := Cluster{
Name: clusterName,
Services: serviceMap,
}
clusters = append(clusters, cluster)
return nil
})
return clusters, nil
}
func (self *ServiceController) GetClusters() []Cluster {
return self.clusters
}
func (self *ServiceController) CreateServiceUpdatePlans() ([]*ServiceUpdatePlan, error) {
plans := []*ServiceUpdatePlan{}
for _, cluster := range self.GetClusters() {
cp, err := self.CreateServiceUpdatePlan(cluster)
if err != nil {
return plans, err
}
if cp != nil {
plans = append(plans, cp)
}
}
return plans, nil
}
func (self *ServiceController) CreateServiceUpdatePlan(cluster Cluster) (*ServiceUpdatePlan, error) {
api := self.manager.EcsApi()
output, err := api.DescribeClusters([]*string{&cluster.Name})
if err != nil {
return nil, err
}
if len(output.Failures) > 0 {
return nil, errors.New(fmt.Sprintf("Cluster '%s' not found", cluster.Name))
} else {
logger.Main.Infof("Cluster '%v' is found.", cluster.Name)
}
rlci, errlci := api.ListContainerInstances(cluster.Name)
if errlci != nil {
return nil, errlci
}
if len(rlci.ContainerInstanceArns) == 0 {
logger.Main.Warnf("ECS instances not found in cluster '%s' not found", cluster.Name)
return nil, nil
} else {
target := output.Clusters[0]
if *target.Status != "ACTIVE" {
return &ServiceUpdatePlan{}, errors.New(fmt.Sprintf("Cluster '%s' is not ACTIVE.", cluster.Name))
}
resListServices, errls := api.ListServices(cluster.Name)
if errls != nil {
return &ServiceUpdatePlan{}, errls
}
currentServices := map[string]*ecs.Service{}
if len(resListServices.ServiceArns) > 0 {
resDescribeService, errds := api.DescribeService(cluster.Name, resListServices.ServiceArns)
if errds != nil {
return &ServiceUpdatePlan{}, errds
}
for _, service := range resDescribeService.Services {
currentServices[*service.ServiceName] = service
}
}
newServices := map[string]*Service{}
for name, newService := range cluster.Services {
s := newService
newServices[name] = &s
}
return &ServiceUpdatePlan{
Name: cluster.Name,
InstanceARNs: rlci.ContainerInstanceArns,
CurrentServices: currentServices,
NewServices: newServices,
}, nil
}
}
func (self *ServiceController) ApplyServicePlans(plans []*ServiceUpdatePlan) {
logger.Main.Info("Start apply serivces...")
for _, plan := range plans {
if err := self.ApplyServicePlan(plan); err != nil {
logger.Main.Error(color.Red(err.Error()))
os.Exit(1)
}
}
}
func (self *ServiceController) ApplyServicePlan(plan *ServiceUpdatePlan) error {
api := self.manager.EcsApi()
// currentにあってnewにない(削除)
for _, current := range plan.CurrentServices {
if _, ok := plan.NewServices[*current.ServiceName]; !ok {
logger.Main.Infof("Delating '%s' service on '%s' ...", *current.ServiceName, plan.Name)
// set desired_count = 0
if _, err := api.UpdateService(plan.Name, *current.ServiceName, 0, *current.TaskDefinition); err != nil {
return err
}
logger.Main.Infof("Updated desired count = 0 of '%s' service on '%s' ...", *current.ServiceName, plan.Name)
// wait to stop service
logger.Main.Infof("Waiting to stop '%s' service on '%s' ...", *current.ServiceName, plan.Name)
if err := self.waitStoppingService(plan.Name, *current.ServiceName); err != nil {
return err
}
logger.Main.Infof("Stoped '%s' service on '%s'.", *current.ServiceName, plan.Name)
// delete service
dsrv, err := api.DeleteService(plan.Name, *current.ServiceArn)
if err != nil {
return err
}
if err := self.waitStoppingService(plan.Name, *current.ServiceName); err != nil {
return err
}
logger.Main.Infof("Deleted service '%s' completely.", *dsrv.Service.ServiceArn)
}
}
// newにあってcurrentにない(新規追加)
for _, add := range plan.NewServices {
if _, ok := plan.CurrentServices[add.Name]; !ok {
logger.Main.Infof("Creating '%s' service on '%s' ...", add.Name, plan.Name)
csrv, err := api.CreateService(plan.Name, add.Name, add.DesiredCount, toLoadBalancers(&add.LoadBalancers), add.TaskDefinition, add.Role)
if err != nil {
return err
}
logger.Main.Infof("Created service '%s', task-definition is '%s'.", *csrv.Service.ServiceArn, *csrv.Service.TaskDefinition)
if err := self.WaitActiveService(plan.Name, add.Name); err != nil {
return err
}
logger.Main.Infof("Started service '%s' completely.", *csrv.Service.ServiceArn)
}
}
// update
for _, add := range plan.NewServices {
current, ok := plan.CurrentServices[add.Name]
if ok {
logger.Main.Infof("Updating '%s' service on '%s' ...", add.Name, plan.Name)
var nextDesiredCount int64
if add.KeepDesiredCount {
nextDesiredCount = *current.DesiredCount
logger.Main.Infof("Keep DesiredCount = %d at '%s'", nextDesiredCount, add.Name)
} else {
nextDesiredCount = add.DesiredCount
logger.Main.Infof("Next DesiredCount = %d at '%s'", nextDesiredCount, add.Name)
}
svc, err := api.UpdateService(plan.Name, add.Name, nextDesiredCount, add.TaskDefinition)
if err != nil {
return err
}
logger.Main.Infof("Created service '%v', task-definition is '%v'.", *svc.Service.ServiceArn, *svc.Service.TaskDefinition)
logger.Main.Infof("Launching task definition '%s' ...", *svc.Service.TaskDefinition)
var targetServiceId string
if len(svc.Service.Deployments) > 1 {
for _, dep := range svc.Service.Deployments {
if *dep.Status == "ACTIVE" {
targetServiceId = *dep.Id
}
}
} else {
for _, dep := range svc.Service.Deployments {
targetServiceId = *dep.Id
}
}
tasks, err := api.ListTasks(plan.Name, add.Name)
if err != nil {
return err
}
taskIds := []*string{}
for _, tarn := range tasks.TaskArns {
tokens := strings.Split(*tarn, "/")
if len(tokens) == 2 {
s := tokens[1]
taskIds = append(taskIds, &s)
}
}
if len(taskIds) > 0 {
dts, err := api.DescribeTasks(plan.Name, taskIds)
if err != nil {
return err
}
for _, t := range dts.Tasks {
if *t.StartedBy == targetServiceId {
if _, err := api.StopTask(plan.Name, *t.TaskArn); err != nil {
logger.Main.Warnf("Task '%s' is not found, so cannot stop.", *t.TaskArn)
} else {
logger.Main.Infof("Stopped Task '%s'", *t.TaskArn)
}
}
}
}
if err := self.WaitActiveService(plan.Name, add.Name); err != nil {
return err
}
logger.Main.Infof("Started service '%s' completely.", *svc.Service.ServiceArn)
}
}
return nil
}
func toLoadBalancers(values *[]LoadBalancer) []*ecs.LoadBalancer {
loadBalancers := []*ecs.LoadBalancer{}
for _, lb := range *values {
loadBalancers = append(loadBalancers, &ecs.LoadBalancer{
LoadBalancerName: &lb.Name,
ContainerName: &lb.ContainerName,
ContainerPort: &lb.ContainerPort,
})
}
return loadBalancers
}
func (self *ServiceController) waitStoppingService(cluster string, service string) error {
api := self.manager.EcsApi()
for {
time.Sleep(10 * time.Second)
result, err := api.DescribeService(cluster, []*string{&service})
if err != nil {
return err
}
if len(result.Services) == 0 {
return nil
}
target := result.Services[0]
logger.Main.Infof("service '%s@%s' current status = %s", service, cluster, *target.Status)
if *target.RunningCount == 0 && *target.Status != "DRAINING" {
return nil
}
}
}
func (self *ServiceController) WaitActiveService(cluster string, service string) error {
api := self.manager.EcsApi()
var flag = false
var taskARNs []*string
for {
time.Sleep(10 * time.Second)
result, err := api.DescribeService(cluster, []*string{&service})
if err != nil {
return err
}
if len(result.Services) == 0 {
continue
}
target := result.Services[0]
// The status of the service. The valid values are ACTIVE, DRAINING, or INACTIVE.
logger.Main.Infof("service '%s@%s' status = %s ...", service, cluster, *target.Status)
if *target.Status == "ACTIVE" {
if len(target.Events) > 0 && strings.Contains(*target.Events[0].Message, "was unable to place a task") {
return errors.New(*target.Events[0].Message)
}
if !flag {
reslt, errlt := api.ListTasks(cluster, service)
if errlt != nil {
return errlt
}
if len(reslt.TaskArns) == 0 {
continue
} else {
taskARNs = reslt.TaskArns
flag = true
}
}
resdt, errdt := api.DescribeTasks(cluster, taskARNs)
if errdt != nil {
return errdt
}
watchStatus := self.checkRunningTask(resdt)
if watchStatus == WatchFinish {
logger.Main.Info("At least one of task has started successfully.")
return nil
} else if watchStatus == WatchTerminate {
logger.Main.Error("Stopped watching task, because task has stopped.")
return errors.New("Task has been stopped for some reason.")
}
}
}
}
func (self *ServiceController) checkRunningTask(dto *ecs.DescribeTasksOutput) TaskWatchStatus {
logger.Main.Info("Current task conditions as follows:")
status := []string{}
for _, task := range dto.Tasks {
util.Println(fmt.Sprintf(" %s:", *task.TaskArn))
util.Println(fmt.Sprintf(" LastStatus:%s", self.RoundColorStatus(*task.LastStatus)))
util.Println(" Containers:")
for _, con := range task.Containers {
util.Println(fmt.Sprintf(" ----------[%s]----------", *con.Name))
util.Println(fmt.Sprintf(" ContainerARN:%s", *con.ContainerArn))
util.Println(fmt.Sprintf(" Status:%s", self.RoundColorStatus(*con.LastStatus)))
util.Println()
}
status = append(status, *task.LastStatus)
}
// if RUNNING at least one, ecs-formation deals with ok.
for _, s := range status {
if s == "RUNNING" {
return WatchFinish
} else if s == "STOPPED" {
return WatchTerminate
}
}
return WatchContinue
}
func (self *ServiceController) RoundColorStatus(status string) *color.Escape {
if status == "RUNNING" {
return color.Green(status)
} else if status == "PENDING" {
return color.Yellow(status)
} else if status == "STOPPED" {
return color.Red(status)
} else {
return color.Magenta(status)
}
}