-
Notifications
You must be signed in to change notification settings - Fork 2
/
run.go
84 lines (78 loc) · 2.75 KB
/
run.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
package cage
import (
"context"
"time"
"github.com/apex/log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ecs"
ecstypes "github.com/aws/aws-sdk-go-v2/service/ecs/types"
"github.com/loilo-inc/canarycage/awsiface"
"github.com/loilo-inc/canarycage/env"
"github.com/loilo-inc/canarycage/key"
"github.com/loilo-inc/canarycage/types"
"golang.org/x/xerrors"
)
func containerExistsInDefinition(td *ecs.RegisterTaskDefinitionInput, container *string) bool {
for _, v := range td.ContainerDefinitions {
if *v.Name == *container {
return true
}
}
return false
}
func (c *cage) Run(ctx context.Context, input *types.RunInput) (*types.RunResult, error) {
env := c.di.Get(key.Env).(*env.Envars)
if !containerExistsInDefinition(env.TaskDefinitionInput, input.Container) {
return nil, xerrors.Errorf("🚫 '%s' not found in container definitions", *input.Container)
}
td, err := c.CreateNextTaskDefinition(ctx)
if err != nil {
return nil, err
}
ecsCli := c.di.Get(key.EcsCli).(awsiface.EcsClient)
o, err := ecsCli.RunTask(ctx, &ecs.RunTaskInput{
Cluster: &env.Cluster,
TaskDefinition: td.TaskDefinitionArn,
LaunchType: ecstypes.LaunchTypeFargate,
NetworkConfiguration: env.ServiceDefinitionInput.NetworkConfiguration,
PlatformVersion: env.ServiceDefinitionInput.PlatformVersion,
Overrides: input.Overrides,
Group: aws.String("cage:run-task"),
})
if err != nil {
return nil, err
}
taskArn := o.Tasks[0].TaskArn
// NOTE: https://github.com/loilo-inc/canarycage/issues/93
// wait for the task to be running
time.Sleep(2 * time.Second)
log.Infof("waiting for task '%s' to start...", *taskArn)
if err := ecs.NewTasksRunningWaiter(ecsCli).Wait(ctx, &ecs.DescribeTasksInput{
Cluster: &env.Cluster,
Tasks: []string{*taskArn},
}, env.GetTaskRunningWait()); err != nil {
return nil, xerrors.Errorf("task failed to start: %w", err)
}
log.Infof("task '%s' is running", *taskArn)
log.Infof("waiting for task '%s' to stop...", *taskArn)
if result, err := ecs.NewTasksStoppedWaiter(ecsCli).WaitForOutput(ctx, &ecs.DescribeTasksInput{
Cluster: &env.Cluster,
Tasks: []string{*taskArn},
}, env.GetTaskStoppedWait()); err != nil {
return nil, xerrors.Errorf("task failed to stop: %w", err)
} else {
task := result.Tasks[0]
for _, c := range task.Containers {
if *c.Name == *input.Container {
if c.ExitCode == nil {
return nil, xerrors.Errorf("container '%s' hasn't exit", *input.Container)
} else if *c.ExitCode != 0 {
return nil, xerrors.Errorf("task exited with %d", *c.ExitCode)
}
return &types.RunResult{ExitCode: *c.ExitCode}, nil
}
}
// Never reached?
return nil, xerrors.Errorf("task '%s' not found in result", *taskArn)
}
}