import { execFile } from "node:child_process"; import { randomUUID } from "node:crypto"; import { promises as fs } from "node:fs"; import { hostname } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { Cron } from "croner"; import type { DockgeServer } from "./dockge-server"; import { log } from "./log"; import { Stack } from "./stack"; import { ValidationError } from "./util-server"; const exec = promisify(execFile); const policyFile = ".dockge-auto-update.json"; const dockgeImage = /(?:^|\/)louislam\/dockge(?:[:@]|$)/i; const stackName = /^[a-z0-9_-]+$/; type Outcome = "updated" | "unchanged" | "skipped" | "failed"; const outcomes: Outcome[] = [ "updated", "unchanged", "skipped", "failed" ]; interface Policy { enabled: boolean; lastRun?: { at: string; result: Outcome; }; } interface ContainerSummary { ID: string; Service: string; State: string; } interface ContainerDetails { image: string; hash: string; directory: string; oneOff: string; } interface Candidate { image: string; hash: string; containers: string[]; imageIds: string[]; } interface ComposeConfig { name: string; services: Record; } const inspectFields = [ "\"image\":{{json .Image}}", "\"hash\":{{json (index .Config.Labels \"com.docker.compose.config-hash\")}}", "\"directory\":{{json (index .Config.Labels \"com.docker.compose.project.working_dir\")}}", "\"oneOff\":{{json (index .Config.Labels \"com.docker.compose.oneoff\")}}", ]; const inspectFormat = `{${inspectFields.join(",")}}`; export class StackAutoUpdate { private schedule?: Cron; private runInProgress = false; private readonly shutdown = new AbortController(); constructor(private readonly server: DockgeServer) {} /** Run daily on this host, including when no browser is connected. */ start() { this.schedule = new Cron("0 4 * * *", { timezone: "UTC", protect: true, }, () => this.run()); } /** Stop scheduling and terminate commands during application shutdown. */ stop() { this.schedule?.stop(); this.shutdown.abort(); } /** Return an absent policy for stacks that cannot be scheduled. */ async getPolicy(stack: Stack): Promise { if (!stackName.test(stack.name) || stack.name === "dockge") { return; } const dir = await fs.lstat(stack.path).catch(() => undefined); if (!dir?.isDirectory() || !await Stack.composeFileExists(this.server.stacksDir, stack.name)) { return; } try { const file = path.join(stack.path, policyFile); if (!(await fs.lstat(file)).isFile()) { throw new Error("The policy is not a regular file"); } const policy = JSON.parse(await fs.readFile(file, "utf8")); const lastRun = policy?.lastRun; const validPolicy: Policy = { enabled: policy?.enabled === true }; if (typeof lastRun?.at === "string" && Number.isFinite(Date.parse(lastRun.at)) && outcomes.includes(lastRun.result)) { validPolicy.lastRun = { at: lastRun.at, result: lastRun.result, }; } return validPolicy; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") { log.warn("auto-update", `Could not read policy for ${stack.name}`); } return { enabled: false }; } } /** Persist the administrator's explicit choice for this stack. */ async setEnabled(stack: Stack, enabled: boolean): Promise { const current = await this.getPolicy(stack); if (!current) { throw new ValidationError("Automatic updates are unavailable for this stack."); } const policy = { ...current, enabled, }; await this.writePolicy(stack, policy); return policy; } /** Check each opted-in stack once per scheduled run. */ async run(): Promise { if (this.runInProgress || this.shutdown.signal.aborted) { return; } this.runInProgress = true; try { const dirs = await fs.readdir(this.server.stacksDir, { withFileTypes: true }); for (const dir of dirs) { if (this.shutdown.signal.aborted) { break; } if (!dir.isDirectory() || !stackName.test(dir.name) || dir.name === "dockge") { continue; } const stack = new Stack(this.server, dir.name); if (!(await this.getPolicy(stack))?.enabled) { continue; } try { await Stack.withOperation(this.server, dir.name, async () => { const policy = await this.getPolicy(stack); if (!policy?.enabled) { return; } let result: Outcome; try { result = await this.update(stack); } catch (error) { result = "failed"; log.warn("auto-update", `${stack.name}: ${String(error)}`); } const current = await this.getPolicy(stack); if (!current?.enabled) { return; } await this.writePolicy(stack, { ...current, lastRun: { at: new Date().toISOString(), result, }, }); log.info("auto-update", `${stack.name}: ${result}`); }); } catch (error) { log.warn("auto-update", `${stack.name}: ${String(error)}`); } } } catch (error) { log.warn("auto-update", String(error)); } finally { this.runInProgress = false; } } /** Replace the policy atomically without exposing a partially written file. */ private async writePolicy(stack: Stack, policy: Policy): Promise { const file = path.join(stack.path, policyFile); const temp = `${file}.${randomUUID()}.tmp`; try { await fs.writeFile(temp, JSON.stringify(policy) + "\n", { flag: "wx", mode: 0o600, }); await fs.rename(temp, file); } finally { await fs.rm(temp, { force: true }); } } /** Pull and recreate only running services whose image actually changed. */ private async update(stack: Stack): Promise { const before = await this.getCandidates(stack); if (before.size === 0) { return "skipped"; } await this.docker(stack, stack.getComposeOptions("pull", "--policy", "always", "--ignore-buildable", "--", ...before.keys())); const after = await this.getCandidates(stack); const changed = new Map(); let skipped = false; for (const [ name, original ] of before) { const current = after.get(name); if (!current || original.hash !== current.hash || original.image !== current.image || original.containers.join() !== current.containers.join()) { skipped = true; continue; } const imageId = await this.docker(stack, [ "image", "inspect", "--format", "{{.Id}}", "--", current.image ]); if (!/^sha256:[a-f0-9]{64}$/.test(imageId)) { throw new Error("Docker image inspect returned an invalid image ID"); } if (current.imageIds.some(id => id !== imageId)) { changed.set(name, current); } } if (!changed.size) { return skipped ? "skipped" : "unchanged"; } if (!(await this.getPolicy(stack))?.enabled) { return "skipped"; } const scale = Array.from(changed, ([ name, service ]) => [ "--scale", `${name}=${service.containers.length}` ]).flat(); await this.docker(stack, stack.getComposeOptions("up", "-d", "--no-deps", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "120", ...scale, "--", ...changed.keys())); return "updated"; } /** Restrict candidates to unchanged, running services owned by this stack directory. */ private async getCandidates(stack: Stack): Promise> { const result = new Map(); const ps = await this.docker(stack, stack.getComposeOptions("ps", "--all", "--orphans=false", "--format", "json")); if (!ps) { return result; } const containers: ContainerSummary[] = ps.startsWith("[") ? JSON.parse(ps) : ps.split(/\r?\n/).map(line => JSON.parse(line)); if (!containers.length || !containers.every(container => /^[a-f0-9]{12,64}$/.test(container.ID))) { return result; } const localHostname = hostname(); if (/^[a-f0-9]{12,64}$/.test(localHostname) && containers.some(container => container.ID.startsWith(localHostname))) { return result; } const configJson = await this.docker(stack, stack.getComposeOptions("config", "--format", "json")); let config: ComposeConfig; try { config = JSON.parse(configJson); } catch { throw new Error("Docker Compose did not return valid configuration JSON"); } if (config.name === "dockge" || Object.values(config.services).some(service => dockgeImage.test(service.image || ""))) { return result; } const configHashes = await this.docker(stack, stack.getComposeOptions("config", "--hash", "*")); const hashes = new Map(configHashes.split(/\r?\n/).map(line => { const [ name, hash ] = line.trim().split(/\s+/); return [ name, hash ]; })); const info = await this.docker(stack, [ "container", "inspect", "--format", inspectFormat, "--", ...containers.map(container => container.ID) ]); const details: ContainerDetails[] = info.split(/\r?\n/).map(line => JSON.parse(line)); if (details.length !== containers.length) { throw new Error("Docker container inspect did not return all requested containers"); } const services = new Map>(); containers.forEach((container, index) => { if (details[index].oneOff?.toLowerCase() !== "false") { return; } const entries = services.get(container.Service) ?? []; entries.push({ ...container, ...details[index], }); services.set(container.Service, entries); }); for (const [ name, entries ] of services) { const service = config.services[name]; const hash = hashes.get(name); if (!service?.image || service.build || service.platform || service.pull_policy === "never" || !hash || !/^[a-f0-9]{64}$/.test(hash)) { continue; } const directory = path.resolve(stack.path); if (!entries.every(container => container.State === "running" && container.hash === hash && container.directory && path.resolve(container.directory) === directory)) { continue; } result.set(name, { image: service.image, hash, containers: entries.map(container => container.ID).sort(), imageIds: entries.map(container => container.image), }); } return result; } /** Run Docker without a shell and keep raw Compose configuration out of logs. */ private async docker(stack: Stack, args: string[]): Promise { try { const { stdout } = await exec("docker", args, { cwd: stack.path, env: { ...process.env, COMPOSE_REMOVE_ORPHANS: "false", }, encoding: "utf8", timeout: 15 * 60 * 1000, maxBuffer: 16 * 1024 * 1024, signal: this.shutdown.signal, windowsHide: true, }); return stdout.trim(); } catch (error) { const code = (error as NodeJS.ErrnoException).code ?? "interrupted"; throw new Error(`Docker ${args[0]} command failed (${code})`); } } }