// PEP-244: an agent's container does not outlive its session. `docker run` is started from tmux, // but the container does not depend on it: when the tmux server goes (the watchdog's container // is recreated by a deploy) the sessions become `failed` and their containers keep running. // Once a minute the watchdog removes `peppa-s` containers whose session is over or gone. import { FINISHED_SESSION_STATUSES, getProject, getSession, listHosts, logEvent, logSessionEvent, parseDockerPs, platformProjectKey, type SessionView } from "@peppa/core"; import type { Db } from "@peppa/db"; import { runOn, type Target } from "./exec.ts"; import { dockerBin, removeContainer } from "./sandbox.ts"; const NAME_RE = /^peppa-s(\d+)$/; /** A container must be an orphan at two checks this far apart — a resume reuses the same name. */ export const ORPHAN_GRACE_MS = 60_000; /** Where an orphan was first seen: `/` → ms. Lives in the watchdog's process. */ export type OrphanMemory = Map; const memory: OrphanMemory = new Map(); export interface OrphanRemoved { container: string; host: string | null; sessionId: number; status: string | null; } async function listAgentContainers(target: Target): Promise { const { stdout } = await runOn(target, [dockerBin(target), "ps", "--no-trunc", "--format", "{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}"], { timeoutMs: 20_000 }); return parseDockerPs(stdout).map((c) => c.name).filter((n) => NAME_RE.test(n)); } /** Removes containers of finished or missing sessions on this machine and the online runner hosts. */ export async function orphanContainersTick(db: Db, o: { now?: Date; log?: (m: string) => void; seen?: OrphanMemory } = {}): Promise { if (process.env.PEPPA_ORPHAN_CONTAINERS === "off") return []; const log = o.log ?? (() => {}); const now = (o.now ?? new Date()).getTime(); const seen = o.seen ?? memory; const hosts = (await listHosts(db, { enabled: true })).filter((h) => h.status === "online"); const machines: { key: string; target: Target; name: string | null }[] = [{ key: "local", target: null, name: null }, ...hosts.map((h) => ({ key: `h${h.id}`, target: h, name: h.name }))]; const removed: OrphanRemoved[] = []; const stillSeen = new Set(); for (const mc of machines) { let names: string[]; try { names = await listAgentContainers(mc.target); } catch (e) { log(`orphan containers${mc.name ? ` (${mc.name})` : ""}: docker ps: ${(e as Error).message.split("\n")[0]}`); // Unknown state: keep the marks of this machine as they are. for (const k of seen.keys()) if (k.startsWith(`${mc.key}/`)) stillSeen.add(k); continue; } for (const name of names) { const sessionId = Number(NAME_RE.exec(name)![1]); const s: SessionView | null = await getSession(db, sessionId).catch(() => null); if (s && !FINISHED_SESSION_STATUSES.includes(s.status)) continue; const key = `${mc.key}/${name}`; stillSeen.add(key); const first = seen.get(key); if (first == null) { seen.set(key, now); continue; } if (now - first < ORPHAN_GRACE_MS) continue; await removeContainer(mc.target, name); seen.delete(key); stillSeen.delete(key); const r: OrphanRemoved = { container: name, host: mc.name, sessionId, status: s?.status ?? null }; removed.push(r); log(`orphan containers: removed ${name}${mc.name ? ` on ${mc.name}` : ""} (session ${s ? s.status : "missing"})`); const payload = { container: name, host: mc.name, status: r.status }; if (s) await logSessionEvent(db, s, "container_orphan_removed", payload); else { const p = await getProject(db, platformProjectKey()).catch(() => null); if (p) await logEvent(db, { projectId: p.id, type: "container_orphan_removed", payload: { ...payload, sessionId } }); } } } // A container that is gone or got a live session again is not an orphan any more. for (const k of [...seen.keys()]) if (!stillSeen.has(k)) seen.delete(k); return removed; }