@ericminassian/platform-engine 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients.d.ts +0 -4
- package/dist/clients.js +1 -14
- package/dist/clients.js.map +1 -1
- package/dist/compat.d.ts +9 -21
- package/dist/compat.js +6 -26
- package/dist/compat.js.map +1 -1
- package/dist/drivers/cognito.d.ts +18 -0
- package/dist/drivers/cognito.js +58 -17
- package/dist/drivers/cognito.js.map +1 -1
- package/dist/drivers/index.d.ts +0 -2
- package/dist/drivers/index.js +0 -2
- package/dist/drivers/index.js.map +1 -1
- package/dist/drivers/logs.d.ts +11 -0
- package/dist/drivers/logs.js +15 -1
- package/dist/drivers/logs.js.map +1 -1
- package/dist/drivers/scheduler.d.ts +0 -21
- package/dist/drivers/scheduler.js +0 -43
- package/dist/drivers/scheduler.js.map +1 -1
- package/dist/index.d.ts +2 -81
- package/dist/index.js +0 -5
- package/dist/index.js.map +1 -1
- package/dist/local.js +2 -140
- package/dist/local.js.map +1 -1
- package/dist/login-branding.d.ts +27 -0
- package/dist/login-branding.js +329 -0
- package/dist/login-branding.js.map +1 -0
- package/dist/login-glyphs.d.ts +12 -0
- package/dist/login-glyphs.js +903 -0
- package/dist/login-glyphs.js.map +1 -0
- package/dist/policy.d.ts +2 -26
- package/dist/policy.js +2 -107
- package/dist/policy.js.map +1 -1
- package/dist/stage.d.ts +1 -2
- package/dist/stage.js +16 -86
- package/dist/stage.js.map +1 -1
- package/dist/util.d.ts +0 -22
- package/dist/util.js +0 -16
- package/dist/util.js.map +1 -1
- package/package.json +10 -7
- package/src/clients.ts +1 -15
- package/src/compat.ts +9 -32
- package/src/drivers/cognito.ts +79 -14
- package/src/drivers/index.ts +0 -2
- package/src/drivers/logs.ts +21 -0
- package/src/drivers/scheduler.ts +0 -69
- package/src/index.ts +3 -78
- package/src/local.ts +2 -152
- package/src/login-branding.ts +407 -0
- package/src/login-glyphs.ts +911 -0
- package/src/policy.ts +2 -132
- package/src/stage.ts +16 -101
- package/src/util.ts +0 -34
- package/dist/drivers/ecr.d.ts +0 -109
- package/dist/drivers/ecr.js +0 -303
- package/dist/drivers/ecr.js.map +0 -1
- package/dist/drivers/ecs.d.ts +0 -163
- package/dist/drivers/ecs.js +0 -447
- package/dist/drivers/ecs.js.map +0 -1
- package/dist/images.d.ts +0 -104
- package/dist/images.js +0 -182
- package/dist/images.js.map +0 -1
- package/dist/services.d.ts +0 -155
- package/dist/services.js +0 -464
- package/dist/services.js.map +0 -1
- package/src/drivers/ecr.ts +0 -457
- package/src/drivers/ecs.ts +0 -661
- package/src/images.ts +0 -254
- package/src/services.ts +0 -663
package/src/drivers/ecs.ts
DELETED
|
@@ -1,661 +0,0 @@
|
|
|
1
|
-
import { GetLogEventsCommand } from '@aws-sdk/client-cloudwatch-logs';
|
|
2
|
-
import {
|
|
3
|
-
type CapacityProviderStrategyItem,
|
|
4
|
-
CreateClusterCommand,
|
|
5
|
-
CreateServiceCommand,
|
|
6
|
-
DeleteServiceCommand,
|
|
7
|
-
DeleteTaskDefinitionsCommand,
|
|
8
|
-
DeregisterTaskDefinitionCommand,
|
|
9
|
-
DescribeClustersCommand,
|
|
10
|
-
DescribeServicesCommand,
|
|
11
|
-
DescribeTaskDefinitionCommand,
|
|
12
|
-
DescribeTasksCommand,
|
|
13
|
-
type Deployment,
|
|
14
|
-
ListServicesCommand,
|
|
15
|
-
ListTaskDefinitionFamiliesCommand,
|
|
16
|
-
ListTaskDefinitionsCommand,
|
|
17
|
-
ListTasksCommand,
|
|
18
|
-
PutClusterCapacityProvidersCommand,
|
|
19
|
-
type RegisterTaskDefinitionCommandInput,
|
|
20
|
-
RegisterTaskDefinitionCommand,
|
|
21
|
-
type Service,
|
|
22
|
-
TagResourceCommand,
|
|
23
|
-
type Task,
|
|
24
|
-
UpdateServiceCommand,
|
|
25
|
-
} from '@aws-sdk/client-ecs';
|
|
26
|
-
import { fargateCpuUnits } from '@ericminassian/platform-core';
|
|
27
|
-
import {
|
|
28
|
-
type EngineContext,
|
|
29
|
-
errorMessage,
|
|
30
|
-
errorName,
|
|
31
|
-
ignoreNotFound,
|
|
32
|
-
isNotFound,
|
|
33
|
-
mapLimit,
|
|
34
|
-
retry,
|
|
35
|
-
sleep,
|
|
36
|
-
tagListLower,
|
|
37
|
-
waitFor,
|
|
38
|
-
} from '../util.ts';
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Fargate through the ECS API: task definitions, services of at most one
|
|
42
|
-
* task, and what happened to their tasks. Generic: nothing here knows about
|
|
43
|
-
* stages (see `services.ts` for that).
|
|
44
|
-
*/
|
|
45
|
-
|
|
46
|
-
const FARGATE_PROVIDERS = ['FARGATE', 'FARGATE_SPOT'];
|
|
47
|
-
|
|
48
|
-
/** A cluster that can run Fargate and Fargate Spot tasks. */
|
|
49
|
-
export async function ensureCluster(
|
|
50
|
-
ctx: EngineContext,
|
|
51
|
-
spec: { name: string; tags?: Record<string, string> },
|
|
52
|
-
): Promise<string> {
|
|
53
|
-
const ecs = ctx.clients.ecs;
|
|
54
|
-
const found = await ecs.send(new DescribeClustersCommand({ clusters: [spec.name] }));
|
|
55
|
-
let cluster = found.clusters?.find((c) => c.status === 'ACTIVE');
|
|
56
|
-
if (!cluster) {
|
|
57
|
-
cluster = (
|
|
58
|
-
await ecs.send(
|
|
59
|
-
new CreateClusterCommand({
|
|
60
|
-
clusterName: spec.name,
|
|
61
|
-
...(spec.tags ? { tags: tagListLower(spec.tags) } : {}),
|
|
62
|
-
}),
|
|
63
|
-
)
|
|
64
|
-
).cluster;
|
|
65
|
-
ctx.log('info', 'created cluster', `cluster ${spec.name}`);
|
|
66
|
-
}
|
|
67
|
-
const providers = cluster?.capacityProviders ?? [];
|
|
68
|
-
if (!FARGATE_PROVIDERS.every((p) => providers.includes(p))) {
|
|
69
|
-
await ecs.send(
|
|
70
|
-
new PutClusterCapacityProvidersCommand({
|
|
71
|
-
cluster: spec.name,
|
|
72
|
-
capacityProviders: [...new Set([...providers, ...FARGATE_PROVIDERS])],
|
|
73
|
-
defaultCapacityProviderStrategy: [{ capacityProvider: 'FARGATE', weight: 1 }],
|
|
74
|
-
}),
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
return cluster!.clusterArn!;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// ------------------------------------------------------------------ task definitions
|
|
81
|
-
|
|
82
|
-
export interface TaskDefinitionSpec {
|
|
83
|
-
family: string;
|
|
84
|
-
/** vCPUs (0.25 … 4). */
|
|
85
|
-
cpu: number;
|
|
86
|
-
memoryMb: number;
|
|
87
|
-
/** What the container's code runs as. */
|
|
88
|
-
taskRoleArn: string;
|
|
89
|
-
/** What ECS pulls the image and ships logs with. */
|
|
90
|
-
executionRoleArn: string;
|
|
91
|
-
image: string;
|
|
92
|
-
environment: Record<string, string>;
|
|
93
|
-
/** Overrides the image's Cmd. */
|
|
94
|
-
command?: string[];
|
|
95
|
-
/** awslogs group; streams are `ecs/app/<task id>`. */
|
|
96
|
-
logGroup: string;
|
|
97
|
-
region: string;
|
|
98
|
-
/** SIGTERM → SIGKILL grace period. Default 30. */
|
|
99
|
-
stopTimeoutSeconds?: number;
|
|
100
|
-
tags?: Record<string, string>;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** Name of the one container in every task definition the platform registers. */
|
|
104
|
-
export const CONTAINER_NAME = 'app';
|
|
105
|
-
|
|
106
|
-
/** Exported for tests. */
|
|
107
|
-
export function taskDefinitionInput(spec: TaskDefinitionSpec): RegisterTaskDefinitionCommandInput {
|
|
108
|
-
return {
|
|
109
|
-
family: spec.family,
|
|
110
|
-
cpu: String(fargateCpuUnits(spec.cpu)),
|
|
111
|
-
memory: String(spec.memoryMb),
|
|
112
|
-
networkMode: 'awsvpc',
|
|
113
|
-
requiresCompatibilities: ['FARGATE'],
|
|
114
|
-
runtimePlatform: { cpuArchitecture: 'ARM64', operatingSystemFamily: 'LINUX' },
|
|
115
|
-
taskRoleArn: spec.taskRoleArn,
|
|
116
|
-
executionRoleArn: spec.executionRoleArn,
|
|
117
|
-
containerDefinitions: [
|
|
118
|
-
{
|
|
119
|
-
name: CONTAINER_NAME,
|
|
120
|
-
image: spec.image,
|
|
121
|
-
essential: true,
|
|
122
|
-
environment: Object.entries(spec.environment)
|
|
123
|
-
.toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
124
|
-
.map(([name, value]) => ({ name, value })),
|
|
125
|
-
...(spec.command ? { command: spec.command } : {}),
|
|
126
|
-
stopTimeout: spec.stopTimeoutSeconds ?? 30,
|
|
127
|
-
// A crash after the container has run 60 s restarts it in place (seconds, same task);
|
|
128
|
-
// an earlier one fails the task and ECS replaces it, so a crash loop shows up as failed
|
|
129
|
-
// tasks (and trips the deployment circuit breaker) instead of restarting forever.
|
|
130
|
-
restartPolicy: { enabled: true, restartAttemptPeriod: 60 },
|
|
131
|
-
logConfiguration: {
|
|
132
|
-
logDriver: 'awslogs',
|
|
133
|
-
options: {
|
|
134
|
-
'awslogs-group': spec.logGroup,
|
|
135
|
-
'awslogs-region': spec.region,
|
|
136
|
-
'awslogs-stream-prefix': 'ecs',
|
|
137
|
-
// A slow log pipe must never block the process (lines are dropped instead).
|
|
138
|
-
mode: 'non-blocking',
|
|
139
|
-
},
|
|
140
|
-
},
|
|
141
|
-
},
|
|
142
|
-
],
|
|
143
|
-
...(spec.tags ? { tags: tagListLower(spec.tags) } : {}),
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/** Register a new revision of the family; returns its ARN. */
|
|
148
|
-
export async function registerTaskDefinition(ctx: EngineContext, spec: TaskDefinitionSpec): Promise<string> {
|
|
149
|
-
const res = await retry(
|
|
150
|
-
() => ctx.clients.ecs.send(new RegisterTaskDefinitionCommand(taskDefinitionInput(spec))),
|
|
151
|
-
{
|
|
152
|
-
// A role created moments ago may not be visible to ECS yet.
|
|
153
|
-
when: (e) => errorName(e) === 'ClientException' && /role/i.test(errorMessage(e)),
|
|
154
|
-
attempts: 10,
|
|
155
|
-
},
|
|
156
|
-
);
|
|
157
|
-
const arn = res.taskDefinition!.taskDefinitionArn!;
|
|
158
|
-
ctx.log('info', `registered revision ${res.taskDefinition!.revision}`, `task-definition ${spec.family}`);
|
|
159
|
-
return arn;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
export interface TaskDefinitionInfo {
|
|
163
|
-
arn: string;
|
|
164
|
-
family: string;
|
|
165
|
-
revision: number;
|
|
166
|
-
image?: string;
|
|
167
|
-
tags: Record<string, string>;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** Revisions of one family (newest first) with their tags. */
|
|
171
|
-
export async function listTaskDefinitions(
|
|
172
|
-
ctx: EngineContext,
|
|
173
|
-
family: string,
|
|
174
|
-
status: 'ACTIVE' | 'INACTIVE' = 'ACTIVE',
|
|
175
|
-
): Promise<TaskDefinitionInfo[]> {
|
|
176
|
-
const arns = await listTaskDefinitionArns(ctx, family, status);
|
|
177
|
-
const out = await mapLimit(arns, 4, (arn) => describeTaskDefinition(ctx, arn));
|
|
178
|
-
return out.filter((t) => t !== undefined).toSorted((a, b) => b.revision - a.revision);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/** ARNs of one family's revisions in a status, newest first. */
|
|
182
|
-
export async function listTaskDefinitionArns(
|
|
183
|
-
ctx: EngineContext,
|
|
184
|
-
family: string,
|
|
185
|
-
status: 'ACTIVE' | 'INACTIVE' = 'ACTIVE',
|
|
186
|
-
): Promise<string[]> {
|
|
187
|
-
const arns: string[] = [];
|
|
188
|
-
let nextToken: string | undefined;
|
|
189
|
-
do {
|
|
190
|
-
const res = await ctx.clients.ecs.send(
|
|
191
|
-
new ListTaskDefinitionsCommand({ familyPrefix: family, status, sort: 'DESC', nextToken }),
|
|
192
|
-
);
|
|
193
|
-
for (const arn of res.taskDefinitionArns ?? [])
|
|
194
|
-
if (parseTaskDefinitionArn(arn)?.family === family) arns.push(arn);
|
|
195
|
-
nextToken = res.nextToken;
|
|
196
|
-
} while (nextToken);
|
|
197
|
-
return arns;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/** One revision with its tags, or undefined when ECS doesn't know it (deleted). */
|
|
201
|
-
export async function describeTaskDefinition(
|
|
202
|
-
ctx: EngineContext,
|
|
203
|
-
arn: string,
|
|
204
|
-
): Promise<TaskDefinitionInfo | undefined> {
|
|
205
|
-
let res;
|
|
206
|
-
try {
|
|
207
|
-
res = await ctx.clients.ecs.send(
|
|
208
|
-
new DescribeTaskDefinitionCommand({ taskDefinition: arn, include: ['TAGS'] }),
|
|
209
|
-
);
|
|
210
|
-
} catch (e) {
|
|
211
|
-
if (
|
|
212
|
-
errorName(e) === 'ClientException' &&
|
|
213
|
-
/unable to describe|not found|does not exist/i.test(errorMessage(e))
|
|
214
|
-
)
|
|
215
|
-
return undefined;
|
|
216
|
-
throw e;
|
|
217
|
-
}
|
|
218
|
-
const td = res.taskDefinition!;
|
|
219
|
-
return {
|
|
220
|
-
arn: td.taskDefinitionArn ?? arn,
|
|
221
|
-
family: td.family!,
|
|
222
|
-
revision: td.revision!,
|
|
223
|
-
...(td.containerDefinitions?.[0]?.image ? { image: td.containerDefinitions[0].image } : {}),
|
|
224
|
-
tags: Object.fromEntries((res.tags ?? []).map((t) => [t.key!, t.value ?? ''])),
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Task definition families starting with `prefix`: with an ACTIVE revision,
|
|
230
|
-
* or (`ALL`) with any revision ECS still lists.
|
|
231
|
-
*/
|
|
232
|
-
export async function listTaskDefinitionFamilies(
|
|
233
|
-
ctx: EngineContext,
|
|
234
|
-
prefix: string,
|
|
235
|
-
status: 'ACTIVE' | 'ALL' = 'ACTIVE',
|
|
236
|
-
): Promise<string[]> {
|
|
237
|
-
const out: string[] = [];
|
|
238
|
-
let nextToken: string | undefined;
|
|
239
|
-
do {
|
|
240
|
-
const res = await ctx.clients.ecs.send(
|
|
241
|
-
new ListTaskDefinitionFamiliesCommand({ familyPrefix: prefix, status, nextToken }),
|
|
242
|
-
);
|
|
243
|
-
for (const f of res.families ?? []) if (f.startsWith(prefix)) out.push(f);
|
|
244
|
-
nextToken = res.nextToken;
|
|
245
|
-
} while (nextToken);
|
|
246
|
-
return out;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/** Deregister and delete revisions (ECS finishes deleting one once no task uses it). */
|
|
250
|
-
export async function deleteTaskDefinitions(ctx: EngineContext, arns: readonly string[]): Promise<void> {
|
|
251
|
-
const ecs = ctx.clients.ecs;
|
|
252
|
-
for (const arn of arns) {
|
|
253
|
-
try {
|
|
254
|
-
await ecs.send(new DeregisterTaskDefinitionCommand({ taskDefinition: arn }));
|
|
255
|
-
} catch (e) {
|
|
256
|
-
// Already deregistered (an earlier cleanup stopped halfway): delete it all the same.
|
|
257
|
-
if (errorName(e) !== 'ClientException' && !isNotFound(e)) throw e;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
for (let i = 0; i < arns.length; i += 10) {
|
|
261
|
-
const batch = arns.slice(i, i + 10);
|
|
262
|
-
const res = await ecs.send(new DeleteTaskDefinitionsCommand({ taskDefinitions: [...batch] }));
|
|
263
|
-
const failed = new Set<string>();
|
|
264
|
-
for (const f of res.failures ?? []) {
|
|
265
|
-
if (f.arn) failed.add(f.arn);
|
|
266
|
-
ctx.log('warn', `couldn't delete: ${f.reason ?? 'unknown reason'}`, `task-definition ${f.arn}`);
|
|
267
|
-
}
|
|
268
|
-
for (const arn of batch)
|
|
269
|
-
if (!failed.has(arn)) ctx.log('info', 'deleted', `task-definition ${shortTaskDefinition(arn)}`);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** `family:revision` from a task definition ARN. */
|
|
274
|
-
export function shortTaskDefinition(arn: string): string {
|
|
275
|
-
return arn.slice(arn.lastIndexOf('/') + 1);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
export function parseTaskDefinitionArn(arn: string): { family: string; revision: number } | undefined {
|
|
279
|
-
const m = /task-definition\/([^:/]+):(\d+)$/.exec(arn);
|
|
280
|
-
return m ? { family: m[1]!, revision: Number(m[2]) } : undefined;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
// ------------------------------------------------------------------ services
|
|
284
|
-
|
|
285
|
-
export interface ServiceSpec {
|
|
286
|
-
cluster: string;
|
|
287
|
-
name: string;
|
|
288
|
-
taskDefinition: string;
|
|
289
|
-
desiredCount: number;
|
|
290
|
-
/** Fargate Spot instead of on-demand Fargate. */
|
|
291
|
-
spot: boolean;
|
|
292
|
-
/** Public subnets: tasks get a public IPv4 address (there is no NAT). */
|
|
293
|
-
subnets: readonly string[];
|
|
294
|
-
securityGroups: readonly string[];
|
|
295
|
-
tags?: Record<string, string>;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
export interface ServiceState {
|
|
299
|
-
arn: string;
|
|
300
|
-
created: boolean;
|
|
301
|
-
/** The task definition the service ran before this update. */
|
|
302
|
-
previousTaskDefinition?: string;
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
const isServiceGone = (e: unknown) => isNotFound(e) || errorName(e) === 'ServiceNotActiveException';
|
|
306
|
-
|
|
307
|
-
function capacityStrategy(spot: boolean): CapacityProviderStrategyItem[] {
|
|
308
|
-
return [{ capacityProvider: spot ? 'FARGATE_SPOT' : 'FARGATE', weight: 1 }];
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/** Exported for tests. */
|
|
312
|
-
export function serviceSettings(spec: ServiceSpec) {
|
|
313
|
-
return {
|
|
314
|
-
taskDefinition: spec.taskDefinition,
|
|
315
|
-
desiredCount: spec.desiredCount,
|
|
316
|
-
capacityProviderStrategy: capacityStrategy(spec.spot),
|
|
317
|
-
networkConfiguration: {
|
|
318
|
-
awsvpcConfiguration: {
|
|
319
|
-
subnets: [...spec.subnets],
|
|
320
|
-
securityGroups: [...spec.securityGroups],
|
|
321
|
-
assignPublicIp: 'ENABLED' as const,
|
|
322
|
-
},
|
|
323
|
-
},
|
|
324
|
-
// At most one task: the old one stops before the new one starts. The circuit breaker
|
|
325
|
-
// fails a deployment whose tasks keep failing and goes back to the last good one.
|
|
326
|
-
deploymentConfiguration: {
|
|
327
|
-
minimumHealthyPercent: 0,
|
|
328
|
-
maximumPercent: 100,
|
|
329
|
-
deploymentCircuitBreaker: { enable: true, rollback: true },
|
|
330
|
-
},
|
|
331
|
-
propagateTags: 'SERVICE' as const,
|
|
332
|
-
enableECSManagedTags: true,
|
|
333
|
-
};
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
/**
|
|
337
|
-
* Create the service, or update it to `spec`. A deleted service keeps its
|
|
338
|
-
* name while it drains; creating one with the same name waits that out.
|
|
339
|
-
*/
|
|
340
|
-
export async function ensureService(ctx: EngineContext, spec: ServiceSpec): Promise<ServiceState> {
|
|
341
|
-
const ecs = ctx.clients.ecs;
|
|
342
|
-
const resource = `ecs-service ${spec.name}`;
|
|
343
|
-
let existing = await getService(ctx, spec.cluster, spec.name);
|
|
344
|
-
if (existing?.status === 'DRAINING') {
|
|
345
|
-
ctx.log('info', 'waiting for the deleted service of the same name to drain', resource);
|
|
346
|
-
await waitFor(
|
|
347
|
-
`${spec.name} to finish draining`,
|
|
348
|
-
async () => {
|
|
349
|
-
const s = await getService(ctx, spec.cluster, spec.name);
|
|
350
|
-
return !s || s.status === 'INACTIVE';
|
|
351
|
-
},
|
|
352
|
-
{ timeoutMs: 600_000 },
|
|
353
|
-
);
|
|
354
|
-
existing = undefined;
|
|
355
|
-
}
|
|
356
|
-
const settings = serviceSettings(spec);
|
|
357
|
-
if (existing?.status === 'ACTIVE') {
|
|
358
|
-
const strategy = existing.capacityProviderStrategy?.map((s) => s.capacityProvider).join(',');
|
|
359
|
-
const res = await ecs.send(
|
|
360
|
-
new UpdateServiceCommand({
|
|
361
|
-
cluster: spec.cluster,
|
|
362
|
-
service: spec.name,
|
|
363
|
-
...settings,
|
|
364
|
-
// ECS only switches capacity providers with a new deployment.
|
|
365
|
-
forceNewDeployment: strategy !== settings.capacityProviderStrategy[0]!.capacityProvider,
|
|
366
|
-
}),
|
|
367
|
-
);
|
|
368
|
-
const arn = res.service?.serviceArn ?? existing.serviceArn!;
|
|
369
|
-
if (spec.tags)
|
|
370
|
-
await ecs.send(new TagResourceCommand({ resourceArn: arn, tags: tagListLower(spec.tags) }));
|
|
371
|
-
ctx.log(
|
|
372
|
-
'info',
|
|
373
|
-
`updated (${shortTaskDefinition(spec.taskDefinition)}, desired ${spec.desiredCount})`,
|
|
374
|
-
resource,
|
|
375
|
-
);
|
|
376
|
-
return {
|
|
377
|
-
arn,
|
|
378
|
-
created: false,
|
|
379
|
-
...(existing.taskDefinition ? { previousTaskDefinition: existing.taskDefinition } : {}),
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
const res = await ecs.send(
|
|
383
|
-
new CreateServiceCommand({
|
|
384
|
-
cluster: spec.cluster,
|
|
385
|
-
serviceName: spec.name,
|
|
386
|
-
...settings,
|
|
387
|
-
schedulingStrategy: 'REPLICA',
|
|
388
|
-
...(spec.tags ? { tags: tagListLower(spec.tags) } : {}),
|
|
389
|
-
}),
|
|
390
|
-
);
|
|
391
|
-
ctx.log(
|
|
392
|
-
'info',
|
|
393
|
-
`created (${shortTaskDefinition(spec.taskDefinition)}, desired ${spec.desiredCount})`,
|
|
394
|
-
resource,
|
|
395
|
-
);
|
|
396
|
-
return { arn: res.service!.serviceArn!, created: true };
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
/** The service in any status (ACTIVE, DRAINING, INACTIVE), or undefined when ECS has none by that name. */
|
|
400
|
-
export async function getService(
|
|
401
|
-
ctx: EngineContext,
|
|
402
|
-
cluster: string,
|
|
403
|
-
name: string,
|
|
404
|
-
): Promise<Service | undefined> {
|
|
405
|
-
const res = await ignoreNotFound(
|
|
406
|
-
ctx.clients.ecs.send(new DescribeServicesCommand({ cluster, services: [name], include: ['TAGS'] })),
|
|
407
|
-
);
|
|
408
|
-
return res?.services?.[0];
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
/** ACTIVE services of the cluster whose name starts with `prefix`, with their tags. */
|
|
412
|
-
export async function listServices(ctx: EngineContext, cluster: string, prefix: string): Promise<Service[]> {
|
|
413
|
-
const ecs = ctx.clients.ecs;
|
|
414
|
-
const names: string[] = [];
|
|
415
|
-
let nextToken: string | undefined;
|
|
416
|
-
do {
|
|
417
|
-
const res = await ignoreNotFound(
|
|
418
|
-
ecs.send(new ListServicesCommand({ cluster, nextToken, maxResults: 100 })),
|
|
419
|
-
);
|
|
420
|
-
if (!res) return [];
|
|
421
|
-
for (const arn of res.serviceArns ?? []) {
|
|
422
|
-
const name = arn.slice(arn.lastIndexOf('/') + 1);
|
|
423
|
-
if (name.startsWith(prefix)) names.push(name);
|
|
424
|
-
}
|
|
425
|
-
nextToken = res.nextToken;
|
|
426
|
-
} while (nextToken);
|
|
427
|
-
const out: Service[] = [];
|
|
428
|
-
for (let i = 0; i < names.length; i += 10) {
|
|
429
|
-
const res = await ecs.send(
|
|
430
|
-
new DescribeServicesCommand({ cluster, services: names.slice(i, i + 10), include: ['TAGS'] }),
|
|
431
|
-
);
|
|
432
|
-
for (const s of res.services ?? []) if (s.status === 'ACTIVE') out.push(s);
|
|
433
|
-
}
|
|
434
|
-
return out.toSorted((a, b) => (a.serviceName! < b.serviceName! ? -1 : 1));
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
export async function setDesiredCount(
|
|
438
|
-
ctx: EngineContext,
|
|
439
|
-
cluster: string,
|
|
440
|
-
service: string,
|
|
441
|
-
desiredCount: number,
|
|
442
|
-
): Promise<void> {
|
|
443
|
-
await ctx.clients.ecs.send(new UpdateServiceCommand({ cluster, service, desiredCount }));
|
|
444
|
-
ctx.log('info', `desired count ${desiredCount}`, `ecs-service ${service}`);
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/** Point the service at a task definition without waiting for the rollout. */
|
|
448
|
-
export async function setTaskDefinition(
|
|
449
|
-
ctx: EngineContext,
|
|
450
|
-
cluster: string,
|
|
451
|
-
service: string,
|
|
452
|
-
taskDefinition: string,
|
|
453
|
-
): Promise<void> {
|
|
454
|
-
await ctx.clients.ecs.send(new UpdateServiceCommand({ cluster, service, taskDefinition }));
|
|
455
|
-
ctx.log('info', `now runs ${shortTaskDefinition(taskDefinition)}`, `ecs-service ${service}`);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
/** Replace the running task with a fresh one of the same task definition. */
|
|
459
|
-
export async function restartService(ctx: EngineContext, cluster: string, service: string): Promise<void> {
|
|
460
|
-
await ctx.clients.ecs.send(new UpdateServiceCommand({ cluster, service, forceNewDeployment: true }));
|
|
461
|
-
ctx.log('info', 'restarting', `ecs-service ${service}`);
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
/** Stop the service's tasks and delete it (it drains in the background). */
|
|
465
|
-
export async function deleteService(ctx: EngineContext, cluster: string, name: string): Promise<void> {
|
|
466
|
-
const ecs = ctx.clients.ecs;
|
|
467
|
-
const svc = await getService(ctx, cluster, name);
|
|
468
|
-
if (svc?.status !== 'ACTIVE') return;
|
|
469
|
-
try {
|
|
470
|
-
if (svc.desiredCount)
|
|
471
|
-
await ecs.send(new UpdateServiceCommand({ cluster, service: name, desiredCount: 0 }));
|
|
472
|
-
await ecs.send(new DeleteServiceCommand({ cluster, service: name, force: true }));
|
|
473
|
-
} catch (e) {
|
|
474
|
-
if (!isServiceGone(e)) throw e;
|
|
475
|
-
}
|
|
476
|
-
ctx.log('info', 'deleted', `ecs-service ${name}`);
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
/** The service's tasks in one desired status, newest first. ECS keeps stopped tasks for about an hour. */
|
|
480
|
-
export async function listTasks(
|
|
481
|
-
ctx: EngineContext,
|
|
482
|
-
cluster: string,
|
|
483
|
-
service: string,
|
|
484
|
-
desiredStatus: 'RUNNING' | 'STOPPED',
|
|
485
|
-
): Promise<Task[]> {
|
|
486
|
-
const ecs = ctx.clients.ecs;
|
|
487
|
-
const arns: string[] = [];
|
|
488
|
-
let nextToken: string | undefined;
|
|
489
|
-
do {
|
|
490
|
-
const res = await ignoreNotFound(
|
|
491
|
-
ecs.send(new ListTasksCommand({ cluster, serviceName: service, desiredStatus, nextToken })),
|
|
492
|
-
);
|
|
493
|
-
if (!res) return [];
|
|
494
|
-
arns.push(...(res.taskArns ?? []));
|
|
495
|
-
nextToken = res.nextToken;
|
|
496
|
-
} while (nextToken);
|
|
497
|
-
const tasks: Task[] = [];
|
|
498
|
-
for (let i = 0; i < arns.length; i += 100) {
|
|
499
|
-
const res = await ecs.send(new DescribeTasksCommand({ cluster, tasks: arns.slice(i, i + 100) }));
|
|
500
|
-
tasks.push(...(res.tasks ?? []));
|
|
501
|
-
}
|
|
502
|
-
const at = (t: Task) => (t.stoppedAt ?? t.startedAt ?? t.createdAt)?.getTime() ?? 0;
|
|
503
|
-
return tasks.toSorted((a, b) => at(b) - at(a));
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
/** Every task `deployment` asks for runs on its task definition, has for `stableMs`, and none failed. */
|
|
507
|
-
async function settled(ctx: EngineContext, spec: RolloutSpec, deployment: Deployment): Promise<boolean> {
|
|
508
|
-
const desired = deployment.desiredCount ?? 0;
|
|
509
|
-
if (desired === 0 || (deployment.runningCount ?? 0) < desired || (deployment.failedTasks ?? 0) > 0)
|
|
510
|
-
return false;
|
|
511
|
-
const since = Date.now() - (spec.stableMs ?? ROLLOUT_STABLE_MS);
|
|
512
|
-
const stable = (await listTasks(ctx, spec.cluster, spec.service, 'RUNNING')).filter(
|
|
513
|
-
(t) =>
|
|
514
|
-
t.taskDefinitionArn === spec.taskDefinition &&
|
|
515
|
-
t.lastStatus === 'RUNNING' &&
|
|
516
|
-
(t.startedAt?.getTime() ?? Number.POSITIVE_INFINITY) <= since,
|
|
517
|
-
);
|
|
518
|
-
return stable.length >= desired;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
export function taskId(taskArn: string): string {
|
|
522
|
-
return taskArn.slice(taskArn.lastIndexOf('/') + 1);
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
/** The newest ECS deployment of a service (a service has one per rollout in progress). */
|
|
526
|
-
export function newestDeployment(deployments: readonly Deployment[] | undefined): Deployment | undefined {
|
|
527
|
-
return (deployments ?? []).toSorted(
|
|
528
|
-
(a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),
|
|
529
|
-
)[0];
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
// ------------------------------------------------------------------ rollouts
|
|
533
|
-
|
|
534
|
-
export type RolloutFailure =
|
|
535
|
-
/** ECS gave up on the deployment (its circuit breaker rolls the service back). */
|
|
536
|
-
| 'failed'
|
|
537
|
-
/** Tasks keep stopping; the wait gave up before ECS did. */
|
|
538
|
-
| 'failing'
|
|
539
|
-
/** It didn't finish in time. */
|
|
540
|
-
| 'timeout'
|
|
541
|
-
/** The deployment is gone: rolled back or replaced by a newer one. */
|
|
542
|
-
| 'replaced';
|
|
543
|
-
|
|
544
|
-
export class RolloutError extends Error {
|
|
545
|
-
override readonly name = 'RolloutError';
|
|
546
|
-
readonly service: string;
|
|
547
|
-
readonly failure: RolloutFailure;
|
|
548
|
-
constructor(service: string, failure: RolloutFailure, message: string) {
|
|
549
|
-
super(message);
|
|
550
|
-
this.service = service;
|
|
551
|
-
this.failure = failure;
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
export interface RolloutSpec {
|
|
556
|
-
cluster: string;
|
|
557
|
-
service: string;
|
|
558
|
-
taskDefinition: string;
|
|
559
|
-
/** Where the container logs, to quote the failed tasks' last lines. */
|
|
560
|
-
logGroup?: string;
|
|
561
|
-
/** Give up at this time (ms since the epoch). */
|
|
562
|
-
deadline: number;
|
|
563
|
-
/** Poll interval. Default 5 s. */
|
|
564
|
-
intervalMs?: number;
|
|
565
|
-
/** How long the new tasks must have run, none failing, to count as started. Default {@link ROLLOUT_STABLE_MS}. */
|
|
566
|
-
stableMs?: number;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
/**
|
|
570
|
-
* A rollout counts as done once every task it asks for has run this long
|
|
571
|
-
* and none has failed. ECS marks it COMPLETED only at its next steady-state
|
|
572
|
-
* check, about two minutes after the task started; a container that can't
|
|
573
|
-
* start fails well within this.
|
|
574
|
-
*/
|
|
575
|
-
export const ROLLOUT_STABLE_MS = 30_000;
|
|
576
|
-
|
|
577
|
-
/**
|
|
578
|
-
* Wait until the service's deployment of `taskDefinition` has COMPLETED, or
|
|
579
|
-
* its tasks have all run for `stableMs` with none failed. Fails as soon as
|
|
580
|
-
* ECS marks it FAILED or two of its tasks have failed, with the stopped
|
|
581
|
-
* tasks' reasons and last log lines in the error.
|
|
582
|
-
*/
|
|
583
|
-
export async function waitForRollout(ctx: EngineContext, spec: RolloutSpec): Promise<void> {
|
|
584
|
-
const interval = spec.intervalMs ?? 5_000;
|
|
585
|
-
for (;;) {
|
|
586
|
-
const svc = await getService(ctx, spec.cluster, spec.service);
|
|
587
|
-
const deployment = newestDeployment(
|
|
588
|
-
svc?.deployments?.filter((d) => d.taskDefinition === spec.taskDefinition),
|
|
589
|
-
);
|
|
590
|
-
let failure: RolloutFailure | undefined;
|
|
591
|
-
if (!svc || svc.status !== 'ACTIVE' || !deployment) failure = 'replaced';
|
|
592
|
-
else if (deployment.rolloutState === 'COMPLETED') return;
|
|
593
|
-
else if (deployment.rolloutState === 'FAILED') failure = 'failed';
|
|
594
|
-
else if ((deployment.failedTasks ?? 0) >= 2) failure = 'failing';
|
|
595
|
-
else if (await settled(ctx, spec, deployment)) return;
|
|
596
|
-
else if (Date.now() >= spec.deadline) failure = 'timeout';
|
|
597
|
-
if (failure) throw await rolloutError(ctx, spec, failure, svc, deployment);
|
|
598
|
-
await sleep(Math.max(0, Math.min(interval, spec.deadline - Date.now())));
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
const SUMMARY: Record<RolloutFailure, string> = {
|
|
603
|
-
failed: 'ECS stopped the rollout because its tasks failed',
|
|
604
|
-
failing: 'its tasks keep stopping',
|
|
605
|
-
timeout: "it didn't finish rolling out in time",
|
|
606
|
-
replaced: 'its deployment was rolled back or replaced',
|
|
607
|
-
};
|
|
608
|
-
|
|
609
|
-
async function rolloutError(
|
|
610
|
-
ctx: EngineContext,
|
|
611
|
-
spec: RolloutSpec,
|
|
612
|
-
failure: RolloutFailure,
|
|
613
|
-
svc: Service | undefined,
|
|
614
|
-
deployment: Deployment | undefined,
|
|
615
|
-
): Promise<RolloutError> {
|
|
616
|
-
const lines = [
|
|
617
|
-
`${spec.service} (${shortTaskDefinition(spec.taskDefinition)}) didn't start: ${SUMMARY[failure]}.`,
|
|
618
|
-
];
|
|
619
|
-
const stopped = (await listTasks(ctx, spec.cluster, spec.service, 'STOPPED')).filter(
|
|
620
|
-
(t) => t.taskDefinitionArn === spec.taskDefinition,
|
|
621
|
-
);
|
|
622
|
-
for (const [i, task] of stopped.slice(0, 3).entries()) {
|
|
623
|
-
const container = task.containers?.find((c) => c.name === CONTAINER_NAME);
|
|
624
|
-
const exit = container?.exitCode !== undefined ? ` (exit code ${container.exitCode})` : '';
|
|
625
|
-
const reason = [task.stoppedReason, container?.reason].filter(Boolean).join(': ') || 'no reason given';
|
|
626
|
-
lines.push(` task ${taskId(task.taskArn!)} stopped${exit}: ${reason}`);
|
|
627
|
-
if (i === 0 && spec.logGroup) {
|
|
628
|
-
const tail = await logTail(ctx, spec.logGroup, `ecs/${CONTAINER_NAME}/${taskId(task.taskArn!)}`, 20);
|
|
629
|
-
if (tail.length) lines.push(' its last log lines:', ...tail.map((l) => ` | ${l}`));
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
if (!stopped.length) {
|
|
633
|
-
if (deployment?.rolloutStateReason) lines.push(` ${deployment.rolloutStateReason}`);
|
|
634
|
-
for (const e of (svc?.events ?? []).slice(0, 3)) lines.push(` ${e.message}`);
|
|
635
|
-
}
|
|
636
|
-
return new RolloutError(spec.service, failure, lines.join('\n'));
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Longest log line a rollout error quotes. Node prints the source line of an
|
|
641
|
-
* uncaught error, which in a minified bundle is the whole bundle (150 KB on
|
|
642
|
-
* the first real failure), and the error lands in the deployment's record.
|
|
643
|
-
*/
|
|
644
|
-
const QUOTED_LINE_MAX = 300;
|
|
645
|
-
|
|
646
|
-
/** The stream's last lines, each cut to a readable length. Best effort: the rollout error matters more than its logs. */
|
|
647
|
-
async function logTail(ctx: EngineContext, group: string, stream: string, limit: number): Promise<string[]> {
|
|
648
|
-
try {
|
|
649
|
-
const res = await ctx.clients.logs.send(
|
|
650
|
-
new GetLogEventsCommand({ logGroupName: group, logStreamName: stream, limit, startFromHead: false }),
|
|
651
|
-
);
|
|
652
|
-
return (res.events ?? []).map((e) => {
|
|
653
|
-
const line = (e.message ?? '').trimEnd();
|
|
654
|
-
return line.length > QUOTED_LINE_MAX
|
|
655
|
-
? `${line.slice(0, QUOTED_LINE_MAX)}… (${line.length} chars)`
|
|
656
|
-
: line;
|
|
657
|
-
});
|
|
658
|
-
} catch (e) {
|
|
659
|
-
return isNotFound(e) ? [] : [`(its logs couldn't be read: ${errorMessage(e)})`];
|
|
660
|
-
}
|
|
661
|
-
}
|