// Deployments: the worker keeps runtime containers in line with what the web app asked for // (desiredState), follows their logs, checks health and samples CPU/memory. Containers keep running // across worker restarts; the worker re-attaches to them. import { stat } from "node:fs/promises"; import { join } from "node:path"; import { and, desc, eq, inArray, lt } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema"; import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, renderCommand } from "@/lib/deploy-command"; import { coreEnv } from "@/lib/env"; import { formatBytes } from "@/lib/format"; import { sanitizeLine } from "./job-log"; import { log } from "./log"; import { docker } from "./runtimes"; import type { DockerClient } from "./docker/client"; type Deployment = typeof deployments.$inferSelect; const LABEL = "kaname.deployment"; const STATS_MS = 5_000; const LOG_FLUSH_MS = 1_000; const LOG_KEEP = 5_000; /** Give up on a container that isn't healthy after this long (big models load slowly on CPU). */ const START_TIMEOUT_MS = 30 * 60_000; /** Leave this much of the host's memory to the system and other containers. */ const MEMORY_RESERVE_MB = 2048; const message = (err: unknown) => (err instanceof Error ? err.message : String(err)); const slug = (s: string) => s .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-|-$/g, "") .slice(0, 40) || "model"; // --- logs ------------------------------------------------------------------------------------ const followers = new Map(); const pending: { deploymentId: string; stream: LogStream; line: string; ts: Date }[] = []; function addLog(deploymentId: string, stream: LogStream, line: string) { pending.push({ deploymentId, stream, line: sanitizeLine(line, [coreEnv().HF_TOKEN ?? ""]).slice(0, 4000), ts: new Date() }); } export async function flushDeploymentLogs(): Promise { if (pending.length === 0) return; const batch = pending.splice(0, pending.length); for (let i = 0; i < batch.length; i += 500) await db().insert(deploymentLogs).values(batch.slice(i, i + 500)); // Keep the newest LOG_KEEP lines per deployment. for (const id of new Set(batch.map((b) => b.deploymentId))) { const [cut] = await db() .select({ id: deploymentLogs.id }) .from(deploymentLogs) .where(eq(deploymentLogs.deploymentId, id)) .orderBy(desc(deploymentLogs.id)) .limit(1) .offset(LOG_KEEP); if (cut) await db().delete(deploymentLogs).where(and(eq(deploymentLogs.deploymentId, id), lt(deploymentLogs.id, cut.id))); } } function follow(c: DockerClient, d: { id: string; containerId: string }, tail = 0) { followers.get(d.id)?.abort(); const ctl = new AbortController(); followers.set(d.id, ctl); c.followLogs(d.containerId, (stream, line) => addLog(d.id, stream, line), { tail, signal: ctl.signal }) .catch((err) => !ctl.signal.aborted && log.warn(`logs of deployment ${d.id}: ${message(err)}`)) .finally(() => followers.get(d.id) === ctl && followers.delete(d.id)); } function unfollow(id: string) { followers.get(id)?.abort(); followers.delete(id); } // --- start / stop ------------------------------------------------------------------------------ async function update(id: string, set: Partial) { await db().update(deployments).set(set).where(eq(deployments.id, id)); } async function fail(d: Deployment, error: string, exitCode: number | null = null) { addLog(d.id, "system", `Failed: ${error}`); log.warn(`deployment ${d.name}: ${error}`); // desiredState stopped, so the worker doesn't retry in a loop. await update(d.id, { state: "failed", desiredState: "stopped", error, exitCode, stoppedAt: new Date(), stats: null }); } async function start(c: DockerClient, d: Deployment) { const [runtime, model, ws] = await Promise.all([ db().query.runtimes.findFirst({ where: eq(runtimes.id, d.runtimeId) }), db().query.models.findFirst({ where: eq(models.id, d.modelId) }), db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }), ]); if (!runtime) return fail(d, "The runtime was deleted."); if (!model) return fail(d, "The model was deleted."); const host = ws?.docker; if (!host?.connected) return fail(d, "Docker isn't connected."); if (!host.network || !host.modelsSource) { return fail(d, "The Docker network or the models source wasn't detected (see Settings → Runtimes)."); } const image = await c.inspectImage(runtime.image); if (!image) return fail(d, `Image ${runtime.image} isn't pulled yet (Settings → Runtimes → Pull).`); // The files must be there (the worker sees the same models folder the container gets). for (const f of [d.options.modelFile, d.options.mmproj, d.options.draftFile]) { if (f == null || (f === "" && runtime.engine !== "vllm")) continue; const path = join(coreEnv().MODELS_DIR, model.localPath, f); if (!(await stat(path).catch(() => null))) return fail(d, `File not found: ${model.localPath}/${f}. Is the model downloaded?`); } // Memory: what the other running deployments reserve plus this one must fit. if (d.memoryMb && host.memoryBytes) { const others = await db() .select({ memoryMb: deployments.memoryMb }) .from(deployments) .where(and(inArray(deployments.state, ["starting", "running"]))); const used = others.reduce((s, o) => s + (o.memoryMb ?? 0), 0); const available = host.memoryBytes / 2 ** 20 - MEMORY_RESERVE_MB - used; if (d.memoryMb > available) { return fail( d, `Not enough memory: ${formatBytes(d.memoryMb * 2 ** 20)} requested, ${formatBytes(Math.max(0, available) * 2 ** 20)} left for deployments (running ones reserve ${formatBytes(used * 2 ** 20)}).`, ); } } const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime }); const name = `kaname-${slug(d.name)}-${d.id.slice(-6).toLowerCase()}`; const portKey = `${cmd.port}/tcp`; const spec = { Image: runtime.image, Cmd: cmd.args, Env: Object.entries(cmd.env).map(([k, v]) => `${k}=${v}`), Labels: { [LABEL]: d.id, "kaname.managed": "true" }, ExposedPorts: { [portKey]: {} }, HostConfig: { Mounts: [{ Type: host.modelsSource.type, Source: host.modelsSource.source, Target: CONTAINER_MODELS_DIR, ReadOnly: true }], NanoCpus: d.cpus ? Math.round(d.cpus * 1e9) : 0, Memory: d.memoryMb ? d.memoryMb * 2 ** 20 : 0, ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined, Devices: runtime.devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })), CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [], SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [], PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {}, Privileged: false, Init: true, RestartPolicy: { Name: "no" }, }, NetworkingConfig: { EndpointsConfig: { [host.network]: {} } }, }; addLog(d.id, "system", `Starting ${runtime.name} (${runtime.image})`); addLog(d.id, "system", `$ ${renderCommand(runtime.image, cmd)}`); try { await c.removeContainer(name); // leftover from a crash const created = await c.createContainer(name, spec); for (const w of created.Warnings ?? []) addLog(d.id, "system", `Docker: ${w}`); await update(d.id, { state: "starting", containerId: created.Id, containerName: name, command: cmd.args, imageId: image.Id, startedAt: new Date(), readyAt: null, stoppedAt: null, error: null, exitCode: null, stats: null, }); follow(c, { id: d.id, containerId: created.Id }); await c.startContainer(created.Id); log.info(`deployment ${d.name}: started ${name}`); } catch (err) { await c.removeContainer(name).catch(() => {}); await fail(d, `Docker: ${message(err)}`); } } async function stopContainer(c: DockerClient, d: Deployment) { if (d.containerId) { await update(d.id, { state: "stopping" }); await c.stopContainer(d.containerId, 15); await c.removeContainer(d.containerId); } unfollow(d.id); addLog(d.id, "system", "Stopped."); await update(d.id, { state: "stopped", stoppedAt: new Date(), stats: null, containerId: null }); } /** Tail of the log for error messages. */ async function lastLines(id: string, n = 15): Promise { await flushDeploymentLogs(); const rows = await db() .select({ line: deploymentLogs.line }) .from(deploymentLogs) .where(eq(deploymentLogs.deploymentId, id)) .orderBy(desc(deploymentLogs.id)) .limit(n); return rows .reverse() .map((r) => r.line) .join("\n"); } async function healthy(name: string, port: number): Promise { try { const res = await fetch(`http://${name}:${port}/health`, { signal: AbortSignal.timeout(2_000) }); return res.ok; } catch { return false; } } // --- reconcile ----------------------------------------------------------------------------------- const lastStats = new Map(); async function reconcileOne(c: DockerClient, d: Deployment) { if (d.deleteRequestedAt) { if (d.containerId) { await c.stopContainer(d.containerId, 15).catch(() => {}); await c.removeContainer(d.containerId).catch(() => {}); } unfollow(d.id); pending.splice(0, pending.length, ...pending.filter((p) => p.deploymentId !== d.id)); await db().batch([db().delete(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)), db().delete(deployments).where(eq(deployments.id, d.id))]); log.info(`deployment ${d.name} deleted`); return; } if (d.desiredState === "stopped") { if (d.state === "starting" || d.state === "running" || d.state === "stopping") await stopContainer(c, d); return; } // desired: running if (d.state === "stopped" || d.state === "failed") return start(c, d); if (!d.containerId || !d.containerName) return fail(d, "Container is missing."); const st = await c.containerState(d.containerId); if (!st || !st.Running) { const why = st?.OOMKilled ? "out of memory (raise the memory limit)" : `exit code ${st?.ExitCode ?? "?"}`; unfollow(d.id); const tail = await lastLines(d.id); await c.removeContainer(d.containerId).catch(() => {}); return fail(d, `The container stopped (${why}).${tail ? `\n${tail}` : ""}`, st?.ExitCode ?? null); } if (!followers.has(d.id)) follow(c, { id: d.id, containerId: d.containerId }); const runtime = await db().query.runtimes.findFirst({ columns: { engine: true }, where: eq(runtimes.id, d.runtimeId) }); const port = ENGINE_PORT[runtime?.engine ?? "llama.cpp"]; if (d.state === "starting") { if (await healthy(d.containerName, port)) { const now = new Date(); const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?"; addLog(d.id, "system", `Ready after ${secs} s.`); await update(d.id, { state: "running", readyAt: now }); } else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) { await c.stopContainer(d.containerId).catch(() => {}); await c.removeContainer(d.containerId).catch(() => {}); return fail(d, "Not healthy after 30 minutes."); } } if (Date.now() - (lastStats.get(d.id) ?? 0) >= STATS_MS) { lastStats.set(d.id, Date.now()); const s = await c.containerStats(d.containerId).catch(() => null); if (s) await update(d.id, { stats: { ...s, at: new Date().toISOString() } }); } } let reconciling = false; export async function reconcileDeployments(): Promise { const c = docker(); if (!c || reconciling) return; reconciling = true; try { for (const d of await db().select().from(deployments)) { await reconcileOne(c, d).catch((err) => log.error(`deployment ${d.name}`, err)); } } finally { reconciling = false; } } /** After a worker restart: re-attach to running containers, remove ones no deployment owns. */ export async function adoptContainers(): Promise { const c = docker(); if (!c) return; try { const rows = await db().select({ id: deployments.id, containerId: deployments.containerId, state: deployments.state }).from(deployments); const byId = new Map(rows.map((r) => [r.id, r])); for (const ct of await c.listContainers(LABEL)) { const owner = byId.get(ct.Labels[LABEL]); if (!owner || owner.containerId !== ct.Id) { await c.removeContainer(ct.Id); log.info(`removed orphaned container ${ct.Names[0] ?? ct.Id}`); } else if (ct.State === "running") { follow(c, { id: owner.id, containerId: ct.Id }); } } } catch (err) { log.warn(`adopting deployment containers failed: ${message(err)}`); } } export function stopFollowingLogs() { for (const id of [...followers.keys()]) unfollow(id); } export const LOG_FLUSH_INTERVAL_MS = LOG_FLUSH_MS;