All checks were successful
Docker image / publish (push) Successful in 59s
Update the shadcn preset and visual Compose editor. Add deployment previews, history, attention notices, and cleanup safeguards. Use the supplied icon in the app header and authentication screens.
740 lines
33 KiB
TypeScript
740 lines
33 KiB
TypeScript
import { execFile } from "node:child_process";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { existsSync, promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { promisify } from "node:util";
|
|
import { analyzeEnv } from "../common/env-file";
|
|
import type { DockgeServer } from "./dockge-server";
|
|
import type { ImageScan } from "./image-vulnerability-scan";
|
|
import { log } from "./log";
|
|
import { Stack } from "./stack";
|
|
import { ValidationError } from "./util-server";
|
|
|
|
const exec = promisify(execFile);
|
|
const stackNamePattern = /^[a-z0-9_-]+$/;
|
|
const serviceNamePattern = /^[a-zA-Z0-9_.-]+$/;
|
|
const imageIdPattern = /^sha256:[a-f0-9]{64}$/;
|
|
const historyLimit = 12;
|
|
const maximumConfigSize = 2 * 1024 * 1024;
|
|
|
|
type Phase = "preparing" | "pulling" | "scanning" | "ready" | "applying" | "deployed" | "rejected" | "failed";
|
|
type Mode = "deploy" | "start" | "update" | "service" | "scheduled";
|
|
type Draft = { yaml: string; env: string; isAdd: boolean; revision?: string };
|
|
type Service = { image?: string; build?: unknown; platform?: string; pull_policy?: string; depends_on?: Record<string, unknown> | string[] };
|
|
type Config = { name: string; services: Record<string, Service>; [key: string]: unknown };
|
|
type Runtime = { id: string; name: string; service: string; image: string; hash: string; state: string; health: string };
|
|
type Candidate = { imageIds: string[]; containers: string[] };
|
|
type PreparedImage = { reference: string; platform?: string; id: string; previous?: string; fresh: boolean; retagged: boolean };
|
|
type Change = { name: string; action: "create" | "recreate" | "start" | "keep" | "remove"; reference?: string; imageId?: string; previousImageIds?: string[] };
|
|
|
|
interface Deployment {
|
|
id: string;
|
|
name: string;
|
|
mode: Mode;
|
|
phase: Phase;
|
|
startedAt: string;
|
|
finishedAt?: string;
|
|
error?: string;
|
|
field?: string;
|
|
project?: string;
|
|
approved?: boolean;
|
|
notBefore?: string;
|
|
service?: string;
|
|
draft?: Draft;
|
|
revision?: string;
|
|
fingerprint?: string;
|
|
runtimeFingerprint?: string;
|
|
changes: Change[];
|
|
images: PreparedImage[];
|
|
scans: ImageScan[];
|
|
scanReportId?: string;
|
|
sourceHashes: Record<string, string>;
|
|
appliedHashes?: Record<string, string>;
|
|
scale?: Record<string, number>;
|
|
cleanup?: { removed: number; retained: number };
|
|
}
|
|
|
|
type Store = { pending?: Deployment; history: Deployment[] };
|
|
|
|
function digest(value: unknown) {
|
|
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
}
|
|
|
|
function publicRecord(record: Deployment, includeScans = true) {
|
|
const { id, name, mode, phase, startedAt, finishedAt, error, field, notBefore, changes, scans, cleanup } = record;
|
|
return { id,
|
|
name,
|
|
mode,
|
|
phase,
|
|
startedAt,
|
|
finishedAt,
|
|
error,
|
|
field,
|
|
notBefore,
|
|
changes,
|
|
scans: includeScans ? scans : [],
|
|
cleanup };
|
|
}
|
|
|
|
class ComposeValidationError extends ValidationError {
|
|
constructor(readonly field: string | undefined) {
|
|
super("editorComposeInvalid");
|
|
}
|
|
}
|
|
|
|
function operationError(error: unknown, fallback: string) {
|
|
if (error instanceof ValidationError) {
|
|
return error.message;
|
|
}
|
|
const stderr = typeof error === "object" && error && "stderr" in error ? String(error.stderr) : "";
|
|
if (/port is already allocated|address already in use/i.test(stderr)) {
|
|
return "deployPortInUse";
|
|
}
|
|
if (/unhealthy|dependency failed to start/i.test(stderr)) {
|
|
return "deployUnhealthy";
|
|
}
|
|
if (/no matching manifest/i.test(stderr)) {
|
|
return "deployPlatformUnavailable";
|
|
}
|
|
return fallback;
|
|
}
|
|
|
|
export class StackDeployments {
|
|
private readonly stores = new Map<string, Store>();
|
|
private readonly jobs = new Map<string, Promise<void>>();
|
|
private readonly shutdown = new AbortController();
|
|
private loading?: Promise<void>;
|
|
private pullQueue: Promise<unknown> = Promise.resolve();
|
|
|
|
constructor(private readonly server: DockgeServer) {}
|
|
|
|
private get directory() {
|
|
return path.resolve(this.server.config.dataDir, "stack-deployments");
|
|
}
|
|
|
|
async initialize() {
|
|
this.loading ??= this.load();
|
|
await this.loading;
|
|
}
|
|
|
|
private async load() {
|
|
await fs.mkdir(this.directory, { recursive: true,
|
|
mode: 0o700 });
|
|
for (const entry of await fs.readdir(this.directory, { withFileTypes: true })) {
|
|
const name = entry.name;
|
|
if (entry.isDirectory() && /^\.(apply|preview)-[a-zA-Z0-9]{6}$/.test(name)) {
|
|
await fs.rm(path.join(this.directory, name), { recursive: true,
|
|
force: true }).catch(() => {});
|
|
continue;
|
|
}
|
|
if (entry.isFile() && /^[a-z0-9_-]+\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
|
|
await fs.rm(path.join(this.directory, name), { force: true }).catch(() => {});
|
|
continue;
|
|
}
|
|
if (!entry.isFile() || !/^[a-z0-9_-]+\.json$/.test(name)) {
|
|
continue;
|
|
}
|
|
try {
|
|
const stack = name.slice(0, -5);
|
|
const store = JSON.parse(await fs.readFile(path.join(this.directory, name), "utf8")) as Store;
|
|
if (!Array.isArray(store.history)) {
|
|
continue;
|
|
}
|
|
this.stores.set(stack, store);
|
|
if (store.pending && ![ "ready", "failed" ].includes(store.pending.phase)) {
|
|
store.pending.phase = "failed";
|
|
store.pending.error = "deployInterrupted";
|
|
await this.write(stack);
|
|
}
|
|
} catch {
|
|
log.warn("deploy", "Could not load a deployment record");
|
|
}
|
|
}
|
|
}
|
|
|
|
async stop() {
|
|
this.shutdown.abort();
|
|
await Promise.allSettled(this.jobs.values());
|
|
}
|
|
|
|
private store(name: string) {
|
|
if (!this.stores.has(name)) {
|
|
this.stores.set(name, { history: [] });
|
|
}
|
|
return this.stores.get(name)!;
|
|
}
|
|
|
|
private async write(name: string) {
|
|
const file = path.join(this.directory, name + ".json");
|
|
const temp = file + "." + randomUUID() + ".tmp";
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify(this.store(name)), { flag: "wx",
|
|
mode: 0o600 });
|
|
await fs.rename(temp, file);
|
|
} finally {
|
|
await fs.rm(temp, { force: true });
|
|
}
|
|
}
|
|
|
|
private name(value: unknown) {
|
|
if (typeof value !== "string" || value.length > 128 || !stackNamePattern.test(value)) {
|
|
throw new ValidationError("deployInvalidRequest");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
async status(value: unknown) {
|
|
await this.initialize();
|
|
const store = this.stores.get(this.name(value));
|
|
const record = store?.pending;
|
|
const runtime = record?.approved && record.project && record.phase === "applying"
|
|
? await this.runtime(record.project).catch(() => []) : [];
|
|
const progress = runtime.filter(row => record?.changes.some(change => change.name === row.service && change.imageId === row.image))
|
|
.map(({ service, state, health }) => ({ service,
|
|
state,
|
|
health }));
|
|
return {
|
|
pending: record ? { ...publicRecord(record),
|
|
progress } : null,
|
|
history: store?.history.map((item, index) => publicRecord(item, index === 0)) ?? [],
|
|
};
|
|
}
|
|
|
|
async restore(value: unknown, id: unknown) {
|
|
await this.initialize();
|
|
const record = this.stores.get(this.name(value))?.history.find(item => item.id === id && item.phase === "deployed");
|
|
if (!record?.draft) {
|
|
throw new ValidationError("deployHistoryMissing");
|
|
}
|
|
return { yaml: record.draft.yaml,
|
|
env: record.draft.env };
|
|
}
|
|
|
|
async forget(value: unknown) {
|
|
await this.initialize();
|
|
const name = this.name(value);
|
|
await fs.rm(path.join(this.directory, name + ".json"), { force: true });
|
|
this.stores.delete(name);
|
|
}
|
|
|
|
async prepare(value: unknown, mode: Mode, input?: unknown, service?: unknown) {
|
|
await this.initialize();
|
|
const name = this.name(value);
|
|
let draft: Draft | undefined;
|
|
if (mode === "deploy") {
|
|
const data = input as Draft | undefined;
|
|
if (!data || typeof data.yaml !== "string" || typeof data.env !== "string" || typeof data.isAdd !== "boolean"
|
|
|| (data.revision !== undefined && (typeof data.revision !== "string" || !/^[a-f0-9]{64}$/.test(data.revision)))
|
|
|| Buffer.byteLength(data.yaml) + Buffer.byteLength(data.env) > maximumConfigSize) {
|
|
throw new ValidationError("deployInvalidRequest");
|
|
}
|
|
if (analyzeEnv(data.env).some(issue => issue.severity === "error")) {
|
|
throw new ValidationError("editorInvalidEnv");
|
|
}
|
|
draft = { yaml: data.yaml,
|
|
env: data.env,
|
|
isAdd: data.isAdd,
|
|
revision: data.revision };
|
|
}
|
|
if (mode === "service" && (typeof service !== "string" || !serviceNamePattern.test(service))) {
|
|
throw new ValidationError("deployInvalidRequest");
|
|
}
|
|
const record = this.create(name, mode, draft);
|
|
record.service = typeof service === "string" ? service : undefined;
|
|
this.run(record, () => Stack.withOperation(this.server, name, () => this.prepareRecord(record)));
|
|
return publicRecord(record);
|
|
}
|
|
|
|
async prepareScheduled(stack: Stack, candidates: Map<string, Candidate>, delayHours: number) {
|
|
await this.initialize();
|
|
const current = this.stores.get(stack.name)?.pending;
|
|
if (current) {
|
|
return current.mode === "scheduled" ? (current.phase === "failed" ? "failed" : "approval") : "skipped";
|
|
}
|
|
const record = this.create(stack.name, "scheduled");
|
|
this.run(record, () => this.prepareRecord(record, candidates, delayHours));
|
|
await this.jobs.get(stack.name);
|
|
const pending = this.stores.get(stack.name)?.pending;
|
|
return pending ? (pending.phase === "failed" ? "failed" : "approval") : "unchanged";
|
|
}
|
|
|
|
private create(name: string, mode: Mode, draft?: Draft) {
|
|
const store = this.store(name);
|
|
if (store.pending || this.jobs.has(name) || this.shutdown.signal.aborted) {
|
|
throw new ValidationError("deployAlreadyPending");
|
|
}
|
|
const record: Deployment = {
|
|
id: randomUUID(),
|
|
name,
|
|
mode,
|
|
draft,
|
|
phase: "preparing",
|
|
startedAt: new Date().toISOString(),
|
|
changes: [],
|
|
images: [],
|
|
scans: [],
|
|
sourceHashes: {},
|
|
};
|
|
store.pending = record;
|
|
return record;
|
|
}
|
|
|
|
private run(record: Deployment, action: () => Promise<void>) {
|
|
const job = Promise.resolve().then(action).catch(async error => {
|
|
record.phase = "failed";
|
|
record.error = operationError(error, "deployOperationFailed");
|
|
record.field = error instanceof ComposeValidationError ? error.field : undefined;
|
|
record.finishedAt = new Date().toISOString();
|
|
await this.write(record.name).catch(() => {});
|
|
log.warn("deploy", `${record.name}: ${record.error}`);
|
|
}).finally(() => {
|
|
this.jobs.delete(record.name);
|
|
});
|
|
this.jobs.set(record.name, job);
|
|
}
|
|
|
|
private async command(args: string[], cwd?: string, timeout = 30000) {
|
|
const { stdout } = await exec("docker", args, {
|
|
cwd,
|
|
timeout,
|
|
encoding: "utf8",
|
|
maxBuffer: 8 * 1024 * 1024,
|
|
windowsHide: true,
|
|
signal: this.shutdown.signal,
|
|
});
|
|
return stdout.trim();
|
|
}
|
|
|
|
private async configure<T>(stack: Stack, draft: Draft | undefined, action: (compose: (args: string[], timeout?: number) => Promise<string>) => Promise<T>) {
|
|
if (!draft) {
|
|
return action(([ command, ...args ], timeout) => this.command(stack.getComposeOptions(command, ...args), stack.fullPath, timeout));
|
|
}
|
|
const temp = await fs.mkdtemp(path.join(this.directory, ".preview-"));
|
|
try {
|
|
const yaml = path.join(temp, "compose.yaml");
|
|
const env = path.join(temp, ".env");
|
|
await fs.writeFile(yaml, draft.yaml, { mode: 0o600 });
|
|
await fs.writeFile(env, draft.env, { mode: 0o600 });
|
|
const global = path.join(this.server.stacksDir, "global.env");
|
|
const args = [ "compose", "--project-directory", stack.fullPath, "--file", yaml ];
|
|
if (existsSync(global)) {
|
|
args.push("--env-file", global);
|
|
}
|
|
args.push("--env-file", env);
|
|
return await action((command, timeout) => this.command([ ...args, ...command ], undefined, timeout));
|
|
} finally {
|
|
await fs.rm(temp, { recursive: true,
|
|
force: true });
|
|
}
|
|
}
|
|
|
|
private async readConfig(compose: (args: string[]) => Promise<string>, service?: string) {
|
|
try {
|
|
const config = JSON.parse(await compose([ "config", "--format", "json", ...(service ? [ "--", service ] : []) ])) as Config;
|
|
if (!config.name || !config.services || !Object.keys(config.services).length) {
|
|
throw new Error("Empty configuration");
|
|
}
|
|
const hashes = await compose([ "config", "--hash", "*", ...(service ? [ "--", service ] : []) ]);
|
|
return { config,
|
|
hashes: Object.fromEntries(hashes.split(/\r?\n/).filter(Boolean).map(line => line.trim().split(/\s+/, 2))) };
|
|
} catch (error) {
|
|
const stderr = typeof error === "object" && error && "stderr" in error ? String(error.stderr) : "";
|
|
const field = stderr.match(/\b(?:services|networks|volumes|configs|secrets)\.[a-zA-Z0-9_.-]{1,180}\b/)?.[0];
|
|
throw new ComposeValidationError(field);
|
|
}
|
|
}
|
|
|
|
private async runtime(project: string): Promise<Runtime[]> {
|
|
const ids = (await this.command([ "container", "ls", "--all", "--quiet", "--no-trunc", "--filter",
|
|
`label=com.docker.compose.project=${project}`, "--filter", "label=com.docker.compose.oneoff=False" ])).split(/\s+/).filter(Boolean);
|
|
if (!ids.length) {
|
|
return [];
|
|
}
|
|
if (ids.length > 500 || ids.some(id => !/^[a-f0-9]{64}$/.test(id))) {
|
|
throw new ValidationError("deployTooManyContainers");
|
|
}
|
|
const format = "{\"id\":{{json .Id}},\"name\":{{json .Name}},\"service\":{{json (index .Config.Labels \"com.docker.compose.service\")}}," +
|
|
"\"image\":{{json .Image}},\"hash\":{{json (index .Config.Labels \"com.docker.compose.config-hash\")}},\"state\":{{json .State.Status}}," +
|
|
"\"health\":{{with index .State \"Health\"}}{{json .Status}}{{else}}\"\"{{end}}}";
|
|
const rows = await this.command([ "container", "inspect", "--format", format, "--", ...ids ]);
|
|
return rows.split(/\r?\n/).map(row => JSON.parse(row) as Runtime).sort((a, b) => a.id.localeCompare(b.id));
|
|
}
|
|
|
|
private runtimeDigest(rows: Runtime[]) {
|
|
return digest(rows.map(({ id, image, hash }) => [ id, image, hash ]));
|
|
}
|
|
|
|
private async inspect(reference: string, platform?: string) {
|
|
try {
|
|
const args = [ "image", "inspect", "--format", "{{.Id}}" ];
|
|
if (platform) {
|
|
args.push("--platform", platform);
|
|
}
|
|
const id = await this.command([ ...args, "--", reference ]);
|
|
return imageIdPattern.test(id) ? id : undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
withImageChanges<T>(action: () => Promise<T>) {
|
|
const operation = this.pullQueue.then(action);
|
|
this.pullQueue = operation.catch(() => {});
|
|
return operation;
|
|
}
|
|
|
|
private async prepareRecord(record: Deployment, candidates?: Map<string, Candidate>, delayHours = 0) {
|
|
await this.write(record.name);
|
|
const stack = new Stack(this.server, record.name);
|
|
if (record.draft?.isAdd ? existsSync(stack.path) : !stack.isManagedByDockge) {
|
|
throw new ValidationError("editorConflict");
|
|
}
|
|
record.revision = record.draft?.isAdd ? undefined : stack.revision;
|
|
if (record.draft?.revision && record.draft.revision !== record.revision) {
|
|
throw new ValidationError("editorConflict");
|
|
}
|
|
const current = await this.configure(stack, record.draft, async compose => {
|
|
const { config, hashes } = await this.readConfig(compose, record.service);
|
|
record.sourceHashes = hashes;
|
|
record.project = config.name;
|
|
record.fingerprint = digest(config);
|
|
const runtime = await this.runtime(config.name);
|
|
record.runtimeFingerprint = this.runtimeDigest(runtime);
|
|
const selection = record.service ? this.dependencies(config, record.service) : Object.keys(config.services);
|
|
const names = candidates ? selection.filter(name => candidates.has(name)) : selection;
|
|
if (!names.length) {
|
|
throw new ValidationError("deployInvalidRequest");
|
|
}
|
|
record.phase = "pulling";
|
|
record.changes = this.changes(record, config, runtime, names);
|
|
await this.write(record.name);
|
|
await this.withImageChanges(() => this.pull(record, compose, config, names));
|
|
if (candidates) {
|
|
record.changes = this.changes(record, config, runtime, names);
|
|
for (const change of record.changes) {
|
|
const existing = candidates.get(change.name);
|
|
if (!existing || existing.imageIds.every(id => id === change.imageId)) {
|
|
change.action = "keep";
|
|
}
|
|
}
|
|
record.changes = record.changes.filter(change => change.action !== "keep");
|
|
if (!record.changes.length) {
|
|
delete this.store(record.name).pending;
|
|
await this.write(record.name);
|
|
return null;
|
|
}
|
|
record.scale = Object.fromEntries(record.changes.map(change => [ change.name, candidates.get(change.name)!.containers.length ]));
|
|
const rejected = this.store(record.name).history.find(item => item.mode === "scheduled" && item.phase === "rejected");
|
|
if (rejected && record.changes.every(change => rejected.changes.some(old => old.name === change.name && old.imageId === change.imageId))) {
|
|
await this.withImageChanges(() => this.removePulled(record));
|
|
delete this.store(record.name).pending;
|
|
await this.write(record.name);
|
|
return null;
|
|
}
|
|
if (delayHours) {
|
|
record.notBefore = new Date(Date.now() + delayHours * 3600000).toISOString();
|
|
}
|
|
} else {
|
|
const pinned = this.pin(record, config, new Set(names));
|
|
const expected = await this.withPinnedConfig(stack, pinned, async args => {
|
|
const hashes = await this.command([ ...args, "config", "--hash", "*" ]);
|
|
return Object.fromEntries(hashes.split(/\r?\n/).filter(Boolean).map(line => line.trim().split(/\s+/, 2)));
|
|
});
|
|
record.changes = this.changes(record, config, runtime, names, expected);
|
|
}
|
|
return config;
|
|
});
|
|
if (!current) {
|
|
return;
|
|
}
|
|
record.phase = "scanning";
|
|
await this.write(record.name);
|
|
const images = new Map<string, ImageScan>();
|
|
for (const change of record.changes) {
|
|
if (!change.imageId || change.action === "remove") {
|
|
continue;
|
|
}
|
|
const candidate = record.images.find(image => image.id === change.imageId);
|
|
if (change.action === "keep" && !candidate?.fresh && !candidate?.retagged) {
|
|
continue;
|
|
}
|
|
const scan = images.get(change.imageId) ?? { id: change.imageId,
|
|
references: [],
|
|
services: [],
|
|
status: "pending" as const,
|
|
findings: [] };
|
|
scan.services.push(change.name);
|
|
if (change.reference && !scan.references.includes(change.reference)) {
|
|
scan.references.push(change.reference);
|
|
}
|
|
images.set(change.imageId, scan);
|
|
}
|
|
if (images.size) {
|
|
const scan = await this.server.imageVulnerabilityScan.scanPrepared(stack, Array.from(images.values()));
|
|
record.scans = scan.images;
|
|
record.scanReportId = scan.id;
|
|
if (scan.error || scan.images.some(image => image.status !== "scanned")) {
|
|
throw new ValidationError(scan.error || "deployScanIncomplete");
|
|
}
|
|
}
|
|
record.phase = "ready";
|
|
await this.write(record.name);
|
|
}
|
|
|
|
private dependencies(config: Config, service: string, names = new Set<string>()) {
|
|
const selected = config.services[service];
|
|
if (!selected || !Object.hasOwn(config.services, service)) {
|
|
throw new ValidationError("deployInvalidRequest");
|
|
}
|
|
if (!names.has(service)) {
|
|
names.add(service);
|
|
const dependencies = selected.depends_on || {};
|
|
for (const name of Array.isArray(dependencies) ? dependencies : Object.keys(dependencies)) {
|
|
if (Object.hasOwn(config.services, name)) {
|
|
this.dependencies(config, name, names);
|
|
}
|
|
}
|
|
}
|
|
return Array.from(names);
|
|
}
|
|
|
|
private reference(config: Config, name: string) {
|
|
return config.services[name].image || `${config.name}-${name}`;
|
|
}
|
|
|
|
private changes(record: Deployment, config: Config, runtime: Runtime[], names: string[], targetHashes?: Record<string, string>) {
|
|
const result: Change[] = names.map(name => {
|
|
const reference = this.reference(config, name);
|
|
const platform = config.services[name].platform;
|
|
const imageId = record.images.find(image => image.reference === reference && image.platform === platform)?.id;
|
|
const rows = runtime.filter(row => row.service === name);
|
|
const matches = (row: Runtime) => targetHashes ? row.hash === targetHashes[name]
|
|
: row.hash === record.sourceHashes[name] || this.matchesDeployedHash(record.name, name, record.sourceHashes[name], row.hash);
|
|
const action = !rows.length ? "create"
|
|
: rows.some(row => !matches(row) || (imageId && row.image !== imageId)) ? "recreate"
|
|
: rows.some(row => row.state !== "running") ? "start" : "keep";
|
|
return { name,
|
|
reference,
|
|
imageId,
|
|
previousImageIds: imageId ? Array.from(new Set(rows.map(row => row.image).filter(id => id !== imageId))) : undefined,
|
|
action };
|
|
});
|
|
if ([ "deploy", "start", "update" ].includes(record.mode)) {
|
|
for (const row of runtime) {
|
|
if (!Object.hasOwn(config.services, row.service)) {
|
|
result.push({ name: row.name.replace(/^\//, ""),
|
|
action: "remove" });
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
matchesDeployedHash(stack: string, service: string, sourceHash: string, containerHash: string) {
|
|
return Boolean(sourceHash && containerHash && this.stores.get(stack)?.history.some(record => record.phase === "deployed"
|
|
&& record.sourceHashes[service] === sourceHash && record.appliedHashes?.[service] === containerHash));
|
|
}
|
|
|
|
private async pull(record: Deployment, compose: (args: string[], timeout?: number) => Promise<string>, config: Config, names: string[]) {
|
|
const initial = new Set((await this.command([ "image", "ls", "--all", "--no-trunc", "--quiet" ])).split(/\s+/));
|
|
for (const name of names) {
|
|
const service = config.services[name];
|
|
const reference = this.reference(config, name);
|
|
const platform = service.platform;
|
|
const existing = record.images.find(image => image.reference === reference && image.platform === platform);
|
|
if (existing) {
|
|
continue;
|
|
}
|
|
const previous = await this.inspect(reference, platform);
|
|
try {
|
|
if (service.build && (!previous || record.mode === "deploy" || record.mode === "update")) {
|
|
await compose([ "build", "--", name ], 10 * 60 * 1000);
|
|
} else if (service.image && service.pull_policy !== "never" && (!service.build || !previous)
|
|
&& (!previous || service.pull_policy === "always" || record.mode === "update" || record.mode === "scheduled")) {
|
|
await compose([ "pull", "--policy", "always", "--ignore-buildable", "--", name ], 10 * 60 * 1000);
|
|
}
|
|
} finally {
|
|
const id = await this.inspect(reference, platform);
|
|
if (id) {
|
|
record.images.push({ reference,
|
|
platform,
|
|
id,
|
|
previous,
|
|
fresh: !initial.has(id),
|
|
retagged: previous !== id });
|
|
await this.write(record.name);
|
|
}
|
|
}
|
|
if (!record.images.some(image => image.reference === reference && image.platform === platform)) {
|
|
throw new ValidationError("deployImageMissing");
|
|
}
|
|
}
|
|
}
|
|
|
|
async decide(value: unknown, id: unknown, approve: unknown) {
|
|
await this.initialize();
|
|
const name = this.name(value);
|
|
const previous = this.stores.get(name)?.pending;
|
|
if (previous && previous.id === id && [ "ready", "failed" ].includes(previous.phase)) {
|
|
await this.jobs.get(name);
|
|
}
|
|
const record = this.stores.get(name)?.pending;
|
|
if (!record || record.id !== id || typeof approve !== "boolean" || this.jobs.has(name)
|
|
|| ![ "ready", "failed" ].includes(record.phase)) {
|
|
throw new ValidationError("deployInvalidDecision");
|
|
}
|
|
if (approve && (record.phase !== "ready" || (record.notBefore && Date.parse(record.notBefore) > Date.now()))) {
|
|
throw new ValidationError("deployInvalidDecision");
|
|
}
|
|
record.phase = "applying";
|
|
record.approved = approve;
|
|
this.run(record, () => Stack.withOperation(this.server, name, async () => {
|
|
await this.write(name);
|
|
if (approve) {
|
|
await this.apply(record);
|
|
record.phase = "deployed";
|
|
} else {
|
|
record.cleanup = await this.withImageChanges(() => this.removePulled(record));
|
|
if (record.scanReportId) {
|
|
this.server.imageVulnerabilityScan.forget(record.name, record.scanReportId);
|
|
}
|
|
record.phase = "rejected";
|
|
}
|
|
record.finishedAt = new Date().toISOString();
|
|
const store = this.store(name);
|
|
store.history.unshift(record);
|
|
store.history = store.history.slice(0, historyLimit);
|
|
delete store.pending;
|
|
await this.write(name);
|
|
void this.server.sendStackList();
|
|
}));
|
|
return publicRecord(record);
|
|
}
|
|
|
|
private async apply(record: Deployment) {
|
|
const stack = new Stack(this.server, record.name);
|
|
if (record.draft?.isAdd ? existsSync(stack.path) : !stack.isManagedByDockge || stack.revision !== record.revision) {
|
|
throw new ValidationError("editorConflict");
|
|
}
|
|
const { config } = await this.configure(stack, record.draft, compose => this.readConfig(compose, record.service));
|
|
if (digest(config) !== record.fingerprint || this.runtimeDigest(await this.runtime(config.name)) !== record.runtimeFingerprint) {
|
|
throw new ValidationError("deployPlanChanged");
|
|
}
|
|
const names = new Set(record.changes.filter(change => change.action !== "remove").map(change => change.name));
|
|
const pinned = this.pin(record, config, names);
|
|
for (const name of names) {
|
|
const service = config.services[name];
|
|
const image = record.images.find(item => item.reference === this.reference(config, name) && item.platform === service.platform);
|
|
if (!image || await this.inspect(image.id, image.platform) !== image.id) {
|
|
throw new ValidationError("deployImageMissing");
|
|
}
|
|
}
|
|
if (record.draft) {
|
|
const draft = new Stack(this.server, record.name, record.draft.yaml, record.draft.env);
|
|
await draft.save(record.draft.isAdd, record.revision);
|
|
} else {
|
|
record.draft = { yaml: stack.composeYAML,
|
|
env: stack.composeENV,
|
|
isAdd: false };
|
|
}
|
|
await this.withPinnedConfig(stack, pinned, async args => {
|
|
const selected = record.mode === "scheduled" ? [ ...names ] : record.service ? [ record.service ] : [];
|
|
const scale = Object.entries(record.scale || {}).flatMap(([ name, count ]) => [ "--scale", `${name}=${count}` ]);
|
|
const flags = record.mode === "scheduled" ? [ "--no-deps", ...scale ] : record.service ? [] : [ "--remove-orphans" ];
|
|
await this.command([ ...args, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "120",
|
|
...flags, ...(selected.length ? [ "--", ...selected ] : []) ], stack.fullPath, 180000);
|
|
const runtime = await this.runtime(config.name);
|
|
record.appliedHashes = Object.fromEntries(runtime.filter(row => names.has(row.service)).map(row => [ row.service, row.hash ]));
|
|
});
|
|
}
|
|
|
|
private pin(record: Deployment, config: Config, names: Set<string>) {
|
|
const services = Object.fromEntries(Object.entries(config.services).map(([ name, service ]) => {
|
|
if (!names.has(name)) {
|
|
return [ name, service ];
|
|
}
|
|
const image = record.images.find(item => item.reference === this.reference(config, name) && item.platform === service.platform);
|
|
if (!image) {
|
|
throw new ValidationError("deployImageMissing");
|
|
}
|
|
return [ name, { ...service,
|
|
image: image.id,
|
|
pull_policy: "never" }];
|
|
}));
|
|
return { ...config,
|
|
services };
|
|
}
|
|
|
|
private async withPinnedConfig<T>(stack: Stack, config: Config, action: (args: string[]) => Promise<T>) {
|
|
const temp = await fs.mkdtemp(path.join(this.directory, ".apply-"));
|
|
try {
|
|
const file = path.join(temp, "compose.json");
|
|
// The Compose config renderer already escapes literal dollars for re-reading.
|
|
await fs.writeFile(file, JSON.stringify(config), { mode: 0o600 });
|
|
return await action([ "compose", "--project-directory", stack.fullPath, "--file", file ]);
|
|
} finally {
|
|
await fs.rm(temp, { recursive: true,
|
|
force: true });
|
|
}
|
|
}
|
|
|
|
private async removePulled(record: Deployment) {
|
|
const shared = this.protectedImages(record.id);
|
|
const fresh = new Set<string>();
|
|
for (const image of record.images) {
|
|
if (image.fresh) {
|
|
fresh.add(image.id);
|
|
}
|
|
if (!image.retagged || !image.previous || image.reference.includes("@") || imageIdPattern.test(image.reference)
|
|
|| await this.inspect(image.reference, image.platform) !== image.id) {
|
|
continue;
|
|
}
|
|
await this.command([ "image", "tag", "--", image.previous, image.reference ]).catch(() => {});
|
|
}
|
|
let removed = 0;
|
|
for (const id of fresh) {
|
|
if (shared.has(id)) {
|
|
continue;
|
|
}
|
|
try {
|
|
// Docker performs the final reference check, including stopped containers.
|
|
await this.command([ "image", "rm", "--no-prune", "--", id ]);
|
|
removed++;
|
|
} catch {
|
|
// The image may have acquired another tag or container reference.
|
|
}
|
|
}
|
|
return { removed,
|
|
retained: fresh.size - removed };
|
|
}
|
|
|
|
protectedImages(except?: string) {
|
|
const ids = new Set<string>();
|
|
for (const store of this.stores.values()) {
|
|
const deployments = store.history.filter(item => item.phase === "deployed").slice(0, 2);
|
|
if (store.pending?.id !== except && store.pending) {
|
|
deployments.push(store.pending);
|
|
}
|
|
for (const deployment of deployments) {
|
|
for (const image of deployment.images) {
|
|
ids.add(image.id);
|
|
if (image.previous && deployment === store.pending) {
|
|
ids.add(image.previous);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return ids;
|
|
}
|
|
|
|
attention() {
|
|
return Array.from(this.stores.entries()).flatMap(([ stack, store ]) => {
|
|
if (store.pending?.phase === "ready" || store.pending?.phase === "failed") {
|
|
return [{ stack,
|
|
kind: store.pending.phase === "ready" ? "deployAttentionApproval" : "deployAttentionFailed" }];
|
|
}
|
|
return [];
|
|
});
|
|
}
|
|
}
|