forked from convox/rack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathagent.go
229 lines (187 loc) · 5.79 KB
/
agent.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
package models
import (
"crypto/sha256"
"encoding/base32"
"fmt"
"html/template"
"regexp"
"sort"
"strings"
"github.com/convox/rack/manifest"
)
// Agent represents a Service which runs exactly once on every ECS agent
type Agent struct {
Service *manifest.Service
App *App
}
//Agents is a wrapper for sorting
type Agents []Agent
func (a Agents) Len() int { return len(a) }
func (a Agents) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a Agents) Less(i, j int) bool { return a[i].Service.Name < a[j].Service.Name }
var shortNameRegex = regexp.MustCompile("[^A-Za-z0-9]+")
// ShortName returns the name of the Agent Service, sans any invalid characters
func (d *Agent) ShortName() string {
shortName := strings.Title(d.Service.Name)
return shortNameRegex.ReplaceAllString(shortName, "")
}
// LongName returns the name of the Agent Service in [stack name]-[service name]-[hash] format
func (d *Agent) LongName() string {
prefix := fmt.Sprintf("%s-%s", d.App.StackName(), d.Service.Name)
hash := sha256.Sum256([]byte(prefix))
suffix := "-" + base32.StdEncoding.EncodeToString(hash[:])[:7]
// $prefix-$suffix-change" needs to be <= 64 characters
if len(prefix) > 57-len(suffix) {
prefix = prefix[:57-len(suffix)]
}
return prefix + suffix
}
// Agents returns any Agent Services defined in the given Manifest
func (a App) Agents(m manifest.Manifest) []Agent {
agents := Agents{}
for _, entry := range m.Services {
if !entry.IsAgent() {
continue
}
e := entry
agent := Agent{
Service: &e,
App: &a,
}
agents = append(agents, agent)
}
sort.Sort(agents)
return agents
}
// AgentFunctionCode returns the Node.js code used by the AgentFunction lambda
func (a App) AgentFunctionCode() map[string]template.HTML {
code := `
'use strict';
const aws = require('aws-sdk');
const ecs = new aws.ECS({ maxRetries: 10 });
const STARTED_BY = 'convox agent';
const STOPPED_REASON = 'convox agent convergence';
// arn:aws:ecs:<region>:<aws_account_id>:task-definition/<task name>:<task def revision>
const TASK_DEF_ARNS = [
/* TASK DEFINITION ARNs */
];
// Task Definition ARN, minus revision
function tdName(td) {
return td.split(':').slice(0, -1).join(':');
}
// Only the revision
function tdRev(td) {
return parseInt(td.split(':').slice(-1)[0]);
}
function startTask(event, desiredTD) {
let options = {
containerInstances: [event.detail.containerInstanceArn],
taskDefinition: desiredTD,
cluster: event.detail.clusterArn,
startedBy: STARTED_BY
};
return ecs.startTask(options).promise()
.then(data => {
if (data.tasks.length === 0) {
throw new Error('Task not started');
}
console.log('startTask Data: ', data);
return data.tasks[0].taskArn;
});
}
function stopTask(event, runningTask) {
if (runningTask.startedBy !== STARTED_BY) {
console.log('Warning: Non-agent task running (scale count > 0?)');
return;
}
let options = {
task: runningTask.taskArn,
cluster: event.detail.clusterArn,
reason: STOPPED_REASON
};
return ecs.stopTask(options).promise()
.then(data => {
console.log('stopTask Data: ', data);
return data.task.taskArn;
});
}
exports.handler = (event, context, callback) => {
console.log('Event: ', event);
if (event.detail.stoppedReason === STOPPED_REASON) {
return callback(null, 'Ignored');
}
let options = {
cluster: event.detail.clusterArn,
containerInstance: event.detail.containerInstanceArn
};
ecs.listTasks(options).promise()
.then(data => {
console.log('listTasks Data: ', data);
// Can't call ecs.describeTasks if data.taskArns is empty
if (!data.taskArns || !data.taskArns.length) {
return {
tasks: []
};
}
let options = {
cluster: event.detail.clusterArn,
tasks: data.taskArns
};
return ecs.describeTasks(options).promise();
})
.then(data => {
console.log('describeTasks Data: ', data);
let tasksToStop = [];
let tasksToStart = [];
for (let tdArn of TASK_DEF_ARNS) {
let alreadyRunning = false;
for (let task of data.tasks) {
if (tdName(tdArn) !== tdName(task.taskDefinitionArn)) {
continue;
}
if (tdRev(tdArn) === tdRev(task.taskDefinitionArn)) {
alreadyRunning = true;
} else {
tasksToStop.push(task);
}
}
if (!alreadyRunning) {
tasksToStart.push(tdArn);
}
}
// Stop all tasks, then start new ones (to try and avoid port conflicts)
return Promise.all(tasksToStop.map(t => stopTask(event, t)))
.then( () => Promise.all(tasksToStart.map(t => startTask(event, t))) );
})
.then(() => {
console.log('Success');
return callback(null, 'Success');
})
.catch(err => {
console.log('Error: ', err);
return callback(err);
});
};
`
// Format JS code for embedding in app.tmpl
halves := strings.Split(code, "/* TASK DEFINITION ARNs */")
for i := range halves {
oldLines := strings.Split(halves[i], "\n")
newLines := []string{}
for _, v := range oldLines {
// Skip empty/comment lines (inline lambda code is limited to 4096 chars)
t := strings.TrimSpace(v)
if t == "" || strings.HasPrefix(t, "//") {
continue
}
newLines = append(newLines, fmt.Sprintf(`"%s",`, v))
}
halves[i] = strings.Join(newLines, "\n")
}
// Remove trailing comma
halves[1] = strings.TrimSuffix(halves[1], ",")
return map[string]template.HTML{
"head": template.HTML(halves[0]),
"body": template.HTML(halves[1]),
}
}