-
Notifications
You must be signed in to change notification settings - Fork 8
/
service.go
239 lines (213 loc) · 6.48 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
package deploy
import (
"context"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/service/ecs/ecsiface"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// Service has target ECS information, client of aws-sdk-go, tasks information and timeout seconds.
type Service struct {
awsECS ecsiface.ECSAPI
// Name of ECS cluster.
Cluster string
// Name of ECS service.
Name string
// Name of base task definition of deploy.
BaseTaskDefinition *string
// TaskDefinition struct to call aws API.
TaskDefinition *TaskDefinition
// New image for deploy.
NewImage *Image
// Wait time when update service.
// This script monitors ECS service for new task definition to be running after call update service API.
Timeout time.Duration
// If deploy failed, rollback to current task definition.
EnableRollback bool
// When check whether deploy completed, confirm only new task status.
// If this flag is true, confirm service deployments status.
SkipCheckDeployments bool
verbose bool
}
// NewService returns a new Service struct, and initialize aws ecs API client.
// Separates imageWithTag into repository and tag, then sets a NewImage for deploy.
func NewService(cluster, name, imageWithTag string, baseTaskDefinition *string, timeout time.Duration, enableRollback bool, skipCheckDeployments bool, profile, region string, verbose bool) (*Service, error) {
awsECS := ecs.New(session.New(), newConfig(profile, region))
taskDefinition := NewTaskDefinition(profile, region, verbose)
if !verbose {
log.SetLevel(log.ErrorLevel)
}
var newImage *Image
if len(imageWithTag) > 0 {
var err error
repository, tag, err := divideImageAndTag(imageWithTag)
if err != nil {
return nil, err
}
newImage = &Image{
*repository,
*tag,
}
}
return &Service{
awsECS,
cluster,
name,
baseTaskDefinition,
taskDefinition,
newImage,
timeout,
enableRollback,
skipCheckDeployments,
verbose,
}, nil
}
// DescribeService gets a current service in the cluster.
func (s *Service) DescribeService() (*ecs.Service, error) {
params := &ecs.DescribeServicesInput{
Services: []*string{
aws.String(s.Name),
},
Cluster: aws.String(s.Cluster),
}
resp, err := s.awsECS.DescribeServices(params)
if err != nil {
return nil, err
}
return resp.Services[0], nil
}
// UpdateService updates the service with a new task definition, and wait during update action.
func (s *Service) UpdateService(service *ecs.Service, taskDefinition *ecs.TaskDefinition) error {
params := &ecs.UpdateServiceInput{}
if *service.SchedulingStrategy == "DAEMON" {
// If the service type is DAEMON, we can not specify desired count.
params = &ecs.UpdateServiceInput{
Service: aws.String(s.Name),
Cluster: aws.String(s.Cluster),
DeploymentConfiguration: service.DeploymentConfiguration,
TaskDefinition: taskDefinition.TaskDefinitionArn,
}
} else {
params = &ecs.UpdateServiceInput{
Service: aws.String(s.Name),
Cluster: aws.String(s.Cluster),
DeploymentConfiguration: service.DeploymentConfiguration,
DesiredCount: service.DesiredCount,
TaskDefinition: taskDefinition.TaskDefinitionArn,
}
}
resp, err := s.awsECS.UpdateService(params)
if err != nil {
return err
}
newService := resp.Service
if *newService.DesiredCount <= 0 {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), s.Timeout)
defer cancel()
return s.waitUpdating(ctx, taskDefinition)
}
// waitUpdating waits the new task definition is deployed.
func (s *Service) waitUpdating(ctx context.Context, newTaskDefinition *ecs.TaskDefinition) error {
log.Info("Waiting for new task running...")
errCh := make(chan error, 1)
done := make(chan struct{}, 1)
go func() {
err := s.waitSwitchTask(newTaskDefinition)
if err != nil {
errCh <- err
}
close(done)
}()
select {
case err := <-errCh:
if err != nil {
return err
}
case <-done:
log.Info("New task is running")
case <-ctx.Done():
return errors.New("process timeout")
}
return nil
}
func (s *Service) waitSwitchTask(newTaskDefinition *ecs.TaskDefinition) error {
for {
time.Sleep(5 * time.Second)
service, err := s.DescribeService()
if err != nil {
return err
}
if s.checkCompleteDeploy(service, newTaskDefinition) {
return nil
}
}
}
func (s *Service) checkCompleteDeploy(service *ecs.Service, newTaskDefinition *ecs.TaskDefinition) bool {
if s.SkipCheckDeployments {
return s.checkNewTaskRunning(service, newTaskDefinition)
}
return s.checkDeployments(service.Deployments, newTaskDefinition)
}
func (s *Service) checkDeployments(deployments []*ecs.Deployment, newTaskDefinition *ecs.TaskDefinition) bool {
if len(deployments) != 1 {
return false
}
for _, deploy := range deployments {
if *deploy.TaskDefinition == *newTaskDefinition.TaskDefinitionArn && *deploy.Status == "PRIMARY" && *deploy.DesiredCount == *deploy.RunningCount {
return true
}
}
return false
}
func (s *Service) checkNewTaskRunning(service *ecs.Service, newTaskDefinition *ecs.TaskDefinition) bool {
input := &ecs.ListTasksInput{
Cluster: service.ClusterArn,
ServiceName: service.ServiceName,
DesiredStatus: aws.String("RUNNING"),
}
runningTasks, err := s.awsECS.ListTasks(input)
if err != nil {
log.Error(err)
return false
}
params := &ecs.DescribeTasksInput{
Cluster: service.ClusterArn,
Tasks: runningTasks.TaskArns,
}
resp, err := s.awsECS.DescribeTasks(params)
if err != nil {
log.Error(err)
return false
}
for _, task := range resp.Tasks {
if *task.LastStatus == "RUNNING" && *task.TaskDefinitionArn == *newTaskDefinition.TaskDefinitionArn {
return true
}
}
return false
}
// Rollback updates the service with current task definition.
// This method call update-service API and does not wait for execution to end.
func (s *Service) Rollback(service *ecs.Service, currentTaskDefinition *ecs.TaskDefinition) error {
if currentTaskDefinition == nil {
return errors.New("old task definition is not exist")
}
params := &ecs.UpdateServiceInput{
Service: aws.String(s.Name),
Cluster: aws.String(s.Cluster),
DeploymentConfiguration: service.DeploymentConfiguration,
DesiredCount: service.DesiredCount,
TaskDefinition: currentTaskDefinition.TaskDefinitionArn,
}
_, err := s.awsECS.UpdateService(params)
if err != nil {
return err
}
log.Info("Rolled back")
return nil
}