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|dockge:local)(?:[:@]|$)/i; const stackName = /^[a-z0-9_-]+$/; type Outcome = "updated" | "unchanged" | "waiting" | "skipped" | "failed" | "approval"; const outcomes: Outcome[] = [ "updated", "unchanged", "waiting", "skipped", "failed", "approval" ]; interface Schedule { enabled: boolean; time: string; timezone: string; delayHours: number; } interface PendingImage { service: string; image: string; id: string; since: string; } interface Policy extends Schedule { lastScheduledDay?: string; lastRun?: { at: string; result: Outcome; }; pending: PendingImage[]; } const defaults: Schedule = { enabled: false, time: "04:00", timezone: "UTC", delayHours: 0, }; const clockTime = /^([01][0-9]|2[0-3]):[0-5][0-9]$/; const hourMs = 60 * 60 * 1000; function validTimezone(timezone: unknown): timezone is string { if (typeof timezone !== "string" || timezone.length > 100 || !/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(timezone)) { return false; } try { new Intl.DateTimeFormat("en-CA", { timeZone: timezone }); return true; } catch { return false; } } function validDelay(value: unknown): value is number { return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2160; } function validDate(value: unknown): value is string { return typeof value === "string" && Number.isFinite(Date.parse(value)); } function localDay(timezone: string, date: Date): string { return new Intl.DateTimeFormat("en-CA", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", }).format(date); } function nextRun(policy: Schedule, after: Date) { const [ hours, minutes ] = policy.time.split(":").map(Number); const cron = new Cron(`${minutes} ${hours} * * *`, { timezone: policy.timezone, paused: true }); try { return cron.nextRun(after); } finally { cron.stop(); } } 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 due = new Map(); 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 * * * * *", { timezone: "UTC", protect: true, }, () => this.collectDue()); } /** Stop scheduling and terminate commands during application shutdown. */ stop() { this.schedule?.stop(); this.due.clear(); this.shutdown.abort(); } /** Return an absent policy for stacks that cannot be scheduled. */ private async readPolicy(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, time: typeof policy?.time === "string" && clockTime.test(policy.time) ? policy.time : defaults.time, timezone: validTimezone(policy?.timezone) ? policy.timezone : defaults.timezone, delayHours: validDelay(policy?.delayHours) ? policy.delayHours : defaults.delayHours, pending: Array.isArray(policy?.pending) ? policy.pending.filter((entry: PendingImage) => typeof entry?.service === "string" && typeof entry.image === "string" && typeof entry.id === "string" && /^sha256:[a-f0-9]{64}$/.test(entry.id) && validDate(entry.since)) : [], }; if (typeof policy?.lastScheduledDay === "string" && /^\d{4}-\d{2}-\d{2}$/.test(policy.lastScheduledDay)) { validPolicy.lastScheduledDay = policy.lastScheduledDay; } 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 { ...defaults, pending: [] }; } } async getPolicy(stack: Stack) { const policy = await this.readPolicy(stack); return policy && this.publicPolicy(policy); } private publicPolicy(policy: Policy) { let next = policy.enabled ? nextRun(policy, new Date()) : null; if (next && localDay(policy.timezone, next) === policy.lastScheduledDay) { next = nextRun(policy, next); } return { enabled: policy.enabled, time: policy.time, timezone: policy.timezone, delayHours: policy.delayHours, lastRun: policy.lastRun, nextRun: next?.toISOString(), pending: policy.pending.map(entry => ({ service: entry.service, eligibleAt: new Date(Date.parse(entry.since) + policy.delayHours * hourMs).toISOString(), })), }; } /** Save the schedule on the host running the stack. Boolean requests are used by older clients. */ async setPolicy(stack: Stack, settings: unknown) { const current = await this.readPolicy(stack); if (!current) { throw new ValidationError("autoUpdateUnavailable"); } if (typeof settings === "boolean") { current.enabled = settings; } else { const schedule = settings as Partial | null; if (typeof schedule?.enabled !== "boolean" || typeof schedule.time !== "string" || !clockTime.test(schedule.time) || !validTimezone(schedule.timezone) || !validDelay(schedule.delayHours)) { throw new ValidationError("autoUpdateInvalidSchedule"); } current.enabled = schedule.enabled; current.time = schedule.time; current.timezone = schedule.timezone; current.delayHours = schedule.delayHours; } await this.writePolicy(stack, current); return this.publicPolicy(current); } private isDue(policy: Policy, minute: Date) { return policy.enabled && policy.lastScheduledDay !== localDay(policy.timezone, minute) && nextRun(policy, new Date(minute.getTime() - 1000))?.getTime() === minute.getTime(); } /** Collect each minute separately so long pulls do not block other scheduled starts. */ private async collectDue() { const minute = new Date(Math.floor(Date.now() / 60000) * 60000); try { const dirs = await fs.readdir(this.server.stacksDir, { withFileTypes: true }); for (const dir of dirs) { if (!dir.isDirectory() || !stackName.test(dir.name) || dir.name === "dockge") { continue; } const policy = await this.readPolicy(new Stack(this.server, dir.name)); if (policy && this.isDue(policy, minute)) { this.due.set(dir.name, minute); } } void this.runDue(); } catch (error) { log.warn("auto-update", String(error)); } } private async runDue() { if (this.runInProgress || this.shutdown.signal.aborted) { return; } this.runInProgress = true; try { for (const [ name, minute ] of this.due) { if (this.shutdown.signal.aborted) { break; } this.due.delete(name); const stack = new Stack(this.server, name); try { await Stack.withOperation(this.server, name, async () => { const policy = await this.readPolicy(stack); if (!policy || !this.isDue(policy, minute)) { return; } policy.lastScheduledDay = localDay(policy.timezone, minute); await this.writePolicy(stack, policy); let result: Outcome; try { result = await this.update(stack, policy); } catch (error) { result = "failed"; log.warn("auto-update", `${stack.name}: ${String(error)}`); } policy.lastRun = { at: new Date().toISOString(), result, }; await this.writePolicy(stack, policy); log.info("auto-update", `${stack.name}: ${result}`); }); } catch (error) { log.warn("auto-update", `${stack.name}: ${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 }); } } /** Prepare changed images for review while leaving the running containers in place. */ private async update(stack: Stack, policy: Policy): Promise { const candidates = await this.getCandidates(stack); if (!candidates.size) { return "skipped"; } policy.pending = []; return this.server.stackDeployments.prepareScheduled(stack, candidates, policy.delayHours); } /** 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 || this.server.stackDeployments.matchesDeployedHash(stack.name, name, hash, container.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})`); } } }