-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
176 lines (147 loc) · 5.14 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"strings"
"time"
"text/template"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
"gopkg.in/alecthomas/kingpin.v2"
)
func logErrorAndFail(err error) {
if err != nil {
log.Fatal(err)
}
}
func mapTasks(vs []*ecs.Task, f func(*ecs.Task) *string) []*string {
vsm := make([]*string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}
func shortDur(d time.Duration) string {
s := d.String()
if strings.HasSuffix(s, "m0s") {
s = s[:len(s)-2]
}
if strings.HasSuffix(s, "h0m") {
s = s[:len(s)-2]
}
return s
}
var (
debug = kingpin.Flag("debug", "Enable debug mode.").Bool()
cluster = kingpin.Flag("cluster", "Name of the ECS cluster").Short('c').Required().String()
waitDuration = kingpin.Flag("wait", "How long to wait for task to finish").Short('t').Default("5m").Duration()
taskName = kingpin.Flag("task-name", "Name of the task to create in the cluster").Default("oneshot").Short('n').String()
taskJSON = kingpin.Flag("task-json", "JSON file with task definition describing the container running the task").Required().Short('j').File()
passAwsKeys = kingpin.Flag("pass-aws-keys", "Add AWS keys to task's environment.").Bool()
params = kingpin.Flag("params", "Parameter that can be used inside the JSON file using Go templating").Short('p').StringMap()
awsKey = kingpin.Flag("aws-access-key-id", "AWS Access Key ID to use (overrides environment)").Short('k').Envar("AWS_ACCESS_KEY_ID").Required().String()
awsSecret = kingpin.Flag("aws-secret-key", "AWS Secret Access Key to use (overrides environment)").Short('s').Envar("AWS_SECRET_ACCESS_KEY").Required().String()
awsRegion = kingpin.Flag("aws-region", "AWS Region to user (overrides environment)").Short('r').Envar("AWS_REGION").Required().String()
)
func deregisterTask(svc *ecs.ECS, taskArn *string) {
_, err := svc.DeregisterTaskDefinition(&ecs.DeregisterTaskDefinitionInput{
TaskDefinition: taskArn,
})
logErrorAndFail(err)
log.Printf("DeRegistered %v successfully", *taskArn)
}
func main() {
kingpin.Version("0.0.1")
kingpin.Parse()
logLevel := aws.LogLevel(aws.LogOff)
var err error
if *debug {
logLevel = aws.LogLevel(aws.LogDebugWithRequestErrors | aws.LogDebugWithHTTPBody)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(*taskJSON)
logErrorAndFail(err)
tmpl, err := template.New("json").Parse(buf.String())
if err != nil {
panic(err)
}
templatedBuf := &bytes.Buffer{}
err = tmpl.Execute(templatedBuf, *params)
logErrorAndFail(err)
creds := credentials.NewStaticCredentials(*awsKey, *awsSecret, "")
sess, err := session.NewSession(&aws.Config{Credentials: creds, Region: awsRegion, LogLevel: logLevel})
logErrorAndFail(err)
svc := ecs.New(sess)
maxResults := int64(1)
taskList, err := svc.ListTaskDefinitions(&ecs.ListTaskDefinitionsInput{
FamilyPrefix: aws.String(*taskName),
MaxResults: &maxResults,
Sort: aws.String("DESC"),
Status: aws.String("ACTIVE"),
})
logErrorAndFail(err)
if len(taskList.TaskDefinitionArns) > 0 {
log.Printf("A previous task family with such name (%v) already exists!", *taskName)
deregisterTask(svc, taskList.TaskDefinitionArns[0])
}
def := ecs.RegisterTaskDefinitionInput{}
if *debug {
log.Printf("resulted json task: %v", templatedBuf.String())
}
err = json.Unmarshal(templatedBuf.Bytes(), &def)
logErrorAndFail(err)
def.Family = taskName
if *passAwsKeys {
def.ContainerDefinitions[0].Environment = append(def.ContainerDefinitions[0].Environment, &ecs.KeyValuePair{
Name: aws.String("AWS_ACCESS_KEY_ID"),
Value: awsKey,
}, &ecs.KeyValuePair{
Name: aws.String("AWS_SECRET_ACCESS_KEY"),
Value: awsSecret,
}, &ecs.KeyValuePair{
Name: aws.String("AWS_REGION"),
Value: awsRegion,
})
}
log.Printf("Registering task definition...")
registrationResult, err := svc.RegisterTaskDefinition(&def)
logErrorAndFail(err)
log.Printf("Registered %v successfully", *taskName)
taskArn := aws.String(fmt.Sprintf("%s:%d", *taskName, *registrationResult.TaskDefinition.Revision))
defer deregisterTask(svc, taskArn)
clusterName := aws.String(*cluster)
result, err := svc.RunTask(&ecs.RunTaskInput{
Cluster: clusterName,
TaskDefinition: taskArn,
})
logErrorAndFail(err)
failureCount := len(result.Failures)
if failureCount > 0 {
log.Printf("Failed to run task. %d failures detected:", failureCount)
for i := 0; i < failureCount; i++ {
log.Print(result.Failures[i])
}
} else {
log.Printf("Waiting for task %v to finish...", *taskArn)
startWaitTime := time.Now()
taskArns := mapTasks(result.Tasks, func(v *ecs.Task) *string { return v.TaskArn })
waitParam := &ecs.DescribeTasksInput{
Cluster: clusterName,
Tasks: taskArns,
}
for {
if err = svc.WaitUntilTasksStopped(waitParam); err == nil {
break
}
waitedTime := time.Since(startWaitTime)
if waitedTime > *waitDuration {
log.Fatalf("Aborting due to time out, task still running after %s or another error: %v", shortDur(waitedTime), err)
}
}
log.Printf("Done! Removing the task definition...")
}
}