Deployments: serve a model with a runtime container
- deployments + deployment_logs tables; desired/actual state reconciled by the worker (create/start/stop/remove via the socket proxy, /health wait, log follower, stats, memory guard, adopt/remove containers on restart). - Pure command builder for llama-server and vllm serve (mmproj, MTP draft, KV cache types, dtype, KV cache size) with tests; file candidates per engine with tests. - New main menu entry Deployments: list, new/edit form (runtime -> model and files -> launch options, live command preview), detail page with stats, log, endpoint and a streaming chat smoke test. Not yet tested end-to-end against real containers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4f7ae1fc8c
commit
8b74fa69db
32 files changed
+3824
-3
No files matched your search
@@ -0,0 +1,313 @@
|
||||
// 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<string, AbortController>();
|
||||
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<void> {
|
||||
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<Deployment>) {
|
||||
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<string> {
|
||||
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<boolean> {
|
||||
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<string, number>();
|
||||
|
||||
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<void> {
|
||||
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<void> {
|
||||
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;
|
||||
@@ -92,6 +92,112 @@ export class DockerClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Containers with a label (e.g. "kaname.deployment"), running or not. */
|
||||
listContainers(label: string) {
|
||||
const filters = encodeURIComponent(JSON.stringify({ label: [label] }));
|
||||
return this.json<{ Id: string; Names: string[]; State: string; Labels: Record<string, string> }[]>(
|
||||
"GET",
|
||||
`/containers/json?all=1&filters=${filters}`,
|
||||
);
|
||||
}
|
||||
|
||||
createContainer(name: string, spec: unknown) {
|
||||
return this.json<{ Id: string; Warnings: string[] }>("POST", `/containers/create?name=${encodeURIComponent(name)}`, spec);
|
||||
}
|
||||
|
||||
async startContainer(id: string) {
|
||||
await this.json("POST", `/containers/${encodeURIComponent(id)}/start`);
|
||||
}
|
||||
|
||||
/** Stop (SIGTERM, SIGKILL after `timeout` s); ignores "already stopped". */
|
||||
async stopContainer(id: string, timeout = 10) {
|
||||
try {
|
||||
await this.json("POST", `/containers/${encodeURIComponent(id)}/stop?t=${timeout}`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof DockerError && (err.status === 304 || err.status === 404))) throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a container (forced); ignores "no such container". */
|
||||
async removeContainer(id: string) {
|
||||
try {
|
||||
await this.json("DELETE", `/containers/${encodeURIComponent(id)}?force=1`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof DockerError && err.status === 404)) throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async containerState(id: string) {
|
||||
const c = await this.json<{ State: { Status: string; Running: boolean; ExitCode: number; Error: string; OOMKilled: boolean } } | null>(
|
||||
"GET",
|
||||
`/containers/${encodeURIComponent(id)}/json`,
|
||||
).catch((err) => {
|
||||
if (err instanceof DockerError && err.status === 404) return null;
|
||||
throw err;
|
||||
});
|
||||
return c?.State ?? null;
|
||||
}
|
||||
|
||||
/** One stats sample: CPU % (of one core = 100) and memory. */
|
||||
async containerStats(id: string): Promise<{ cpuPercent: number; memoryBytes: number; memoryLimitBytes: number }> {
|
||||
const s = await this.json<{
|
||||
cpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number; online_cpus: number };
|
||||
precpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number };
|
||||
memory_stats: { usage?: number; limit?: number; stats?: { inactive_file?: number; cache?: number } };
|
||||
}>("GET", `/containers/${encodeURIComponent(id)}/stats?stream=false`);
|
||||
const cpuDelta = s.cpu_stats.cpu_usage.total_usage - (s.precpu_stats.cpu_usage?.total_usage ?? 0);
|
||||
const sysDelta = s.cpu_stats.system_cpu_usage - (s.precpu_stats.system_cpu_usage ?? 0);
|
||||
const cpuPercent = sysDelta > 0 ? (cpuDelta / sysDelta) * (s.cpu_stats.online_cpus || 1) * 100 : 0;
|
||||
// Like `docker stats`: usage minus page cache.
|
||||
const cache = s.memory_stats.stats?.inactive_file ?? s.memory_stats.stats?.cache ?? 0;
|
||||
return {
|
||||
cpuPercent: Math.round(cpuPercent * 10) / 10,
|
||||
memoryBytes: Math.max(0, (s.memory_stats.usage ?? 0) - cache),
|
||||
memoryLimitBytes: s.memory_stats.limit ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow a container's stdout/stderr (from now, plus the last `tail` lines). The stream uses
|
||||
* Docker's multiplexed format (8-byte frame headers) for containers without a TTY. Resolves when
|
||||
* the container stops or `signal` aborts.
|
||||
*/
|
||||
async followLogs(
|
||||
id: string,
|
||||
onLine: (stream: "stdout" | "stderr", line: string) => void,
|
||||
options: { tail?: number; signal?: AbortSignal } = {},
|
||||
): Promise<void> {
|
||||
const res = await this.raw(
|
||||
"GET",
|
||||
`/containers/${encodeURIComponent(id)}/logs?follow=1&stdout=1&stderr=1&tail=${options.tail ?? 0}`,
|
||||
undefined,
|
||||
0,
|
||||
);
|
||||
if ((res.statusCode ?? 500) >= 400) throw new DockerError(`logs: HTTP ${res.statusCode}`, res.statusCode ?? null);
|
||||
options.signal?.addEventListener("abort", () => res.destroy());
|
||||
let buf = Buffer.alloc(0);
|
||||
const partial = { stdout: "", stderr: "" };
|
||||
const emit = (stream: "stdout" | "stderr", text: string) => {
|
||||
const parts = (partial[stream] + text).split(/\r?\n|\r/);
|
||||
partial[stream] = parts.pop() ?? "";
|
||||
for (const p of parts) if (p.trim()) onLine(stream, p);
|
||||
};
|
||||
try {
|
||||
for await (const chunk of res) {
|
||||
buf = Buffer.concat([buf, chunk as Buffer]);
|
||||
while (buf.length >= 8) {
|
||||
const size = buf.readUInt32BE(4);
|
||||
if (buf.length < 8 + size) break;
|
||||
emit(buf[0] === 2 ? "stderr" : "stdout", buf.subarray(8, 8 + size).toString("utf8"));
|
||||
buf = buf.subarray(8 + size);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (!options.signal?.aborted) throw err;
|
||||
}
|
||||
for (const s of ["stdout", "stderr"] as const) if (partial[s].trim()) onLine(s, partial[s]);
|
||||
}
|
||||
|
||||
/** Inspect a local image; null if it isn't pulled. */
|
||||
async inspectImage(ref: string) {
|
||||
try {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { coreEnv } from "@/lib/env";
|
||||
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DeleteRunner } from "./delete";
|
||||
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import type { Runner } from "./runner";
|
||||
@@ -32,6 +33,7 @@ const FOLDER_SCAN_MS = 2 * 60_000;
|
||||
const DOCKER_INFO_MS = 5 * 60_000;
|
||||
const IMAGE_SYNC_MS = 60_000;
|
||||
const PULL_CHECK_MS = 3_000;
|
||||
const DEPLOYMENT_TICK_MS = 2_000;
|
||||
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
|
||||
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
@@ -343,6 +345,9 @@ async function shutdown(reason: string, code = 0) {
|
||||
stopping = true;
|
||||
log.info(`shutting down (${reason})`);
|
||||
timers.forEach(clearInterval);
|
||||
// Deployment containers keep running; the next worker re-attaches to them.
|
||||
stopFollowingLogs();
|
||||
await flushDeploymentLogs().catch(() => {});
|
||||
if (runners.size > 0) {
|
||||
for (const r of runners.values()) r.interrupt();
|
||||
const deadline = Date.now() + SHUTDOWN_GRACE_MS;
|
||||
@@ -394,6 +399,11 @@ async function main() {
|
||||
timers.push(setInterval(() => void dockerInfo(), DOCKER_INFO_MS));
|
||||
timers.push(setInterval(() => void imageSync(), IMAGE_SYNC_MS));
|
||||
timers.push(setInterval(() => void handlePullRequests().catch((err) => log.error("pull failed", err)), PULL_CHECK_MS));
|
||||
|
||||
// Deployments: re-attach to running containers, then keep them in line with the desired state.
|
||||
await adoptContainers();
|
||||
timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS));
|
||||
timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS));
|
||||
void scanFolders();
|
||||
void tick();
|
||||
setTimeout(() => void checkHubDue(), 15_000);
|
||||
|
||||
Reference in new issue
Block a user