-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathengine.ts
More file actions
607 lines (542 loc) · 14.5 KB
/
engine.ts
File metadata and controls
607 lines (542 loc) · 14.5 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
import * as core from "@actions/core";
import { exec } from "@actions/exec";
import { dump, load } from "js-yaml";
import type { ComposeSpec } from "./compose.js";
import type { Settings } from "./settings.js";
import type { TaskInfo } from "./types.js";
import { mapToObject } from "./utils";
/**
* Deploy the stack
*/
export async function deployStack(
spec: ComposeSpec,
{ stack, variables }: Pick<Readonly<Settings>, "stack" | "variables">,
) {
await executeDockerCommand(
[
"stack",
"deploy",
"--prune",
"--quiet",
"--detach=true",
"--with-registry-auth",
"--resolve-image=always",
"--compose-file",
"-",
stack,
],
{
stdin: dump(spec),
env: {
...mapToObject(variables),
},
},
);
core.info(`Deployed stack ${stack}`);
}
export async function normalizeComposeSpecification(
composeFiles: string[],
{ variables }: Pick<Readonly<Settings>, "variables">,
skipInterpolation = false,
pinImages = false,
) {
const composeFileFlags = composeFiles.map((file) => `--compose-file=${file}`);
const content = await executeDockerCommand(
[
"compose",
"config",
...composeFileFlags,
"--format=json",
skipInterpolation ? "--no-interpolate" : "",
pinImages ? "--resolve-image-digests" : "",
],
{
env: {
...mapToObject(variables),
},
},
);
if (!content) {
throw new Error(
"Failed to load compose file(s): No content produced. This is " +
"most likely a bug in the deployment action. Please report it to " +
"the action issues.",
);
}
try {
return JSON.parse(content) as ComposeSpec | undefined;
} catch (cause) {
throw new Error(
"Failed to load compose file(s): Failed to parse JSON output. " +
"This is most likely a bug in the deployment action. Please report " +
"it to the action issues.",
{ cause },
);
}
}
export async function normalizeStackSpecification(
composeFiles: string[],
{ variables }: Pick<Readonly<Settings>, "variables">,
skipInterpolation = false,
) {
const composeFileFlags = composeFiles.map((file) => `--compose-file=${file}`);
const content = await executeDockerCommand(
[
"stack",
"config",
...composeFileFlags,
skipInterpolation ? "--skip-interpolation" : "",
],
{
env: {
...mapToObject(variables),
},
silent: true,
},
);
if (!content) {
throw new Error(
"Failed to load compose file(s): No content produced. This is " +
"most likely a bug in the deployment action. Please report it to " +
"the action issues.",
);
}
let spec: ComposeSpec | undefined;
try {
spec = load(content, {
filename: "docker-compose.yaml",
json: true,
onWarning: (error) => core.warning(error),
}) as ComposeSpec;
} catch (cause) {
throw new Error(
"Failed to load compose file(s): Failed to parse YAML output: " +
`${cause}: This is most likely a bug in the deployment action. ` +
"Please report it to the action issues.",
{ cause },
);
}
if (!spec) {
throw new Error(
"Failed to load compose file(s): Failed to parse YAML output. " +
"This is most likely a bug in the deployment action. Please report " +
"it to the action issues.",
);
}
return spec;
}
type ServiceFilters = {
id?: ValueFilter;
labels?: KeyValueFilter;
mode?: ValueFilter<"replicated" | "global">;
name?: ValueFilter;
};
export async function listServices(
filters: ServiceFilters,
inspect?: false,
): Promise<ServiceMetadata[]>;
export async function listServices(
filters: ServiceFilters,
inspect: true,
): Promise<ServiceWithMetadata[]>;
export async function listServices(
filters: ServiceFilters,
inspect?: boolean,
): Promise<ServiceMetadata[] | ServiceWithMetadata[]> {
core.debug("Listing services");
const filterFlags = buildFilters(
{
id: filters.id,
label: filters.labels ? parseLabelFilter(filters.labels) : undefined,
mode: filters.mode,
name: filters.name,
},
"--filter",
);
try {
const output = await executeDockerCommand(
["service", "ls", "--format=json", ...filterFlags],
{ silent: true },
);
const services = parseLineDelimitedJson<ServiceMetadata>(output);
if (!inspect) {
return services;
}
const inspectedServices: ServiceWithMetadata[] = [];
for (const metadata of services) {
const service = await inspectService(metadata.ID);
inspectedServices.push({ ...metadata, ...service });
}
return inspectedServices;
} catch (cause) {
const message = cause instanceof Error ? cause.message : String(cause);
throw new Error(`Failed to list services: ${message}`, { cause });
}
}
export async function inspectService(id: string) {
const output = await executeDockerCommand(
["service", "inspect", "--format=json", id],
{ silent: true },
);
try {
const result = JSON.parse(output) as Service | Service[];
if (Array.isArray(result)) {
if (result.length === 0) {
throw new Error(`Service "${id}" not found`);
}
return result[0];
}
return result;
} catch (cause) {
throw new Error(
`Failed to inspect service ${id}: Failed to parse JSON output. ` +
"This is most likely a bug in the deployment action. Please report " +
"it to the action issues.",
{ cause },
);
}
}
export async function getServiceLogs(
id: string,
{ tail, since }: { tail?: number; since?: Date },
) {
try {
const output = await executeDockerCommand(
[
"service",
"logs",
"--raw",
"--no-trunc",
"--details",
"--timestamps",
tail ? `--tail=${tail}` : "",
since ? `--since=${since.toISOString()}` : "",
id,
],
{ silent: true },
);
return output
.trim()
.split("\n")
.filter((line) => !!line?.trim())
.map((line) => {
const [rawTimestamp, metadata, ...rest] = line.split(" ");
let timestamp: Date | null;
try {
timestamp = new Date(rawTimestamp);
if (Number.isNaN(timestamp.getTime())) {
throw new Error("Invalid date");
}
} catch {
core.warning(`Unexpected invalid timestamp: ${rawTimestamp}`);
timestamp = null;
}
return {
timestamp,
metadata: parseLabels(metadata),
message: rest.join(" "),
};
});
} catch (cause) {
throw new Error(`Failed to get logs for service "${id}": ${cause}`, {
cause,
});
}
}
/**
* List tasks for a service
*
* This function retrieves the list of tasks for a service, which includes
* information about task states, errors, and failure reasons.
*
* @param serviceId The ID or name of the service
* @returns Array of task information objects
*/
export async function listServiceTasks(serviceId: string) {
try {
const output = await executeDockerCommand(
["service", "ps", "--format=json", "--no-trunc", serviceId],
{ silent: true },
);
return parseLineDelimitedJson<TaskInfo>(output);
} catch (cause) {
throw new Error(`Failed to list tasks for service "${serviceId}": ${cause}`, {
cause,
});
}
}
export async function listSecrets(filters: {
id?: ValueFilter;
name?: ValueFilter;
labels?: KeyValueFilter;
}) {
core.info("Listing secrets");
const filterFlags = buildFilters({
id: filters.id,
name: filters.name,
label: filters.labels ? parseLabelFilter(filters.labels) : undefined,
});
try {
const output = await executeDockerCommand(
["secret", "ls", "--format=json", ...filterFlags],
{ silent: true },
);
return parseLineDelimitedJson<StoredVariable>(output).map<SecretMetadata>(
(secret) => ({
...secret,
Labels: parseLabels(secret.Labels ?? ""),
}),
);
} catch (cause) {
throw new Error(`Failed to list secrets: ${cause}`, { cause });
}
}
export async function listConfigs(filters: {
id?: ValueFilter;
name?: ValueFilter;
labels?: KeyValueFilter;
}) {
core.debug("Listing configs");
const filterFlags = buildFilters({
id: filters.id,
name: filters.name,
label: filters.labels ? parseLabelFilter(filters.labels) : undefined,
});
try {
const output = await executeDockerCommand(
["config", "ls", "--format=json", ...filterFlags],
{ silent: true },
);
return parseLineDelimitedJson<StoredVariable>(output).map<ConfigMetadata>(
(config) => ({
...config,
Labels: parseLabels(config.Labels ?? ""),
}),
);
} catch (cause) {
throw new Error(`Failed to list configs: ${cause}`, { cause });
}
}
/**
* Remove an unused secret
*
* This function removes a secret from the Swarm.
*
* @param id The ID of the secret to remove
*/
export async function removeSecret(id: string) {
core.info(`Removing unused secret "${id}"`);
try {
await executeDockerCommand(["secret", "rm", id], { silent: true });
} catch (cause) {
throw new Error(`Failed to remove secret "${id}": ${cause}`, { cause });
}
}
/**
* Remove an unused config value
*
* This function removes a config value from the Swarm.
*
* @param id The ID of the config to remove
*/
export async function removeConfig(id: string) {
core.info(`Removing unused config "${id}"`);
try {
await executeDockerCommand(["config", "rm", id], { silent: true });
} catch (cause) {
throw new Error(`Failed to remove config "${id}": ${cause}`, { cause });
}
}
/**
* Execute a Docker command
*
* This function executes a Docker command with the given arguments and options.
* It captures the output from stdout and returns it as a string.
*
* @param args The arguments to pass to the Docker command
* @param [stdin] Optional input to pass to the command's stdin
* @param [env] Optional environment variables to set for the command
* @param [silent] If true, suppresses the output of the command to the action
* log output
*/
async function executeDockerCommand(
args: [string, ...string[]],
{
stdin = undefined,
env = undefined,
silent = false,
}: {
stdin?: Buffer | string;
env?: Record<string, string>;
silent?: boolean;
} = {},
) {
const input = stdin
? Buffer.isBuffer(stdin)
? stdin
: Buffer.from(stdin)
: undefined;
let output = "";
let errorOutput = "";
core.startGroup(`docker ${args.join(" ")}`);
try {
await exec(
"docker",
args.filter((arg) => arg !== "" && arg !== undefined),
{
input,
silent,
env,
listeners: {
stdout: (data) => {
output += data.toString();
},
stderr: (data) => {
errorOutput += data.toString();
},
},
},
);
core.info(output);
} catch (cause) {
const message = cause instanceof Error ? cause.message : String(cause);
core.error(`Command failed: ${message}`);
core.error(output);
core.error(errorOutput);
throw new Error(`Failed to execute Docker Command: ${message}`, { cause });
} finally {
core.endGroup();
}
return output;
}
function buildFilters<
T extends Record<K, ValueFilter<V>>,
K extends string = string,
V extends string = string,
>(filters: Partial<T>, flag = "--filter") {
return Object.entries(filters)
.filter((filter): filter is [K, ValueFilter<V>] => Boolean(filter[1]))
.flatMap(([name, values]) => parseFilter(name, values))
.flatMap((value) => [flag, value] as const);
}
export function parseFilter<K extends string, V extends string>(
name: K,
values: V | V[],
): string[] {
const filter = Array.isArray(values) ? values : ([values] as const);
return filter.map((value) => `${name}=${value}` as const);
}
export function parseLabelFilter(
labels:
| string
| string[]
| { [key: string]: string }
| Array<string | { [key: string]: string }>,
) {
if (typeof labels === "string") {
return [labels];
}
if (Array.isArray(labels)) {
return labels.flatMap((label) => {
if (typeof label === "string") {
return [label];
}
if (typeof label === "object") {
return Object.entries(label).map(([key, value]) => `${key}=${value}`);
}
return [];
});
}
return Object.entries(labels).map(([key, value]) => `${key}=${value}`);
}
function parseLineDelimitedJson<
T extends Record<string, unknown> = Record<string, unknown>,
>(data: string): Array<T> {
return data
.trim()
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line) as T);
}
function parseLabels(labels: string = "") {
return labels
.split(",")
.map((label) => {
const [key, ...values] = label.split("=");
return [key, values.join("=")];
})
.reduce<Record<string, string>>(
(acc, [key, value]) => ({
// biome-ignore lint/performance/noAccumulatingSpread: Spreading is the best way to merge here
...acc,
[key]: value,
}),
{},
);
}
export type ServiceMetadata = {
ID: string;
Name: string;
Mode: "replicated" | "global";
Replicas: string;
Image: string;
Ports: string;
};
export type Service = {
ID: string;
CreatedAt: Date;
UpdatedAt: Date;
Version: {
Index: number;
};
Spec?: {
Name: string;
Labels: Record<string, string>;
TaskTemplate: Record<string, unknown>;
};
PreviousSpec?: {
Name: string;
Labels: Record<string, string>;
TaskTemplate: Record<string, unknown>;
};
Endpoint: Record<string, unknown>;
UpdateStatus?: {
StartedAt?: string | undefined;
CompletedAt?: string | undefined;
Message?: string | undefined;
State:
| "updating"
| "paused"
| "completed"
| "rollback_started"
| "rollback_paused"
| "rollback_completed";
};
};
export type ServiceWithMetadata = ServiceMetadata & Service;
export type SecretMetadata = {
ID: string;
Name: string;
Labels: Record<string, string>;
CreatedAt: string;
UpdatedAt: string;
};
export type ConfigMetadata = {
ID: string;
Name: string;
Labels: Record<string, string>;
CreatedAt: string;
UpdatedAt: string;
};
type StoredVariable = {
ID: string;
Name: string;
Labels: string;
CreatedAt: string;
UpdatedAt: string;
};
type ValueFilter<T extends string = string> = T | T[];
type KeyValueFilter<K extends string = string, V extends string = string> =
| ValueFilter<K>
| Record<K, V>
| Array<K | Record<K, V>>;