Runtimes: Docker connection via socket proxy, runtime images, host info
- docker-proxy service (tecnativa/docker-socket-proxy) in both compose files; worker uses it via DOCKER_HOST with a dependency-free client. - runtimes table with presets (llama.cpp CPU, vLLM CPU) and custom images; validation of image refs, env, args, devices (/dev/dri, /dev/kfd). - Worker reports Docker/CPU/memory facts and detects its network and models mount; pulls images with progress; image state per runtime. - Settings -> Runtimes page with host card, list, editor, pull/update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
76683ffd7b
commit
b68b4a2b23
23 files changed
+2622
-2
No files matched your search
@@ -0,0 +1,203 @@
|
||||
// Worker side of runtimes: Docker host facts, image state per runtime, pulling images.
|
||||
// The web app never talks to Docker; it reads what the worker reports in the DB.
|
||||
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { hostname } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
import { and, eq, isNotNull, ne } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type DockerHostInfo, runtimes, settings, workerState } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { RUNTIME_PRESETS } from "@/lib/runtimes-shared";
|
||||
import { DockerClient, DockerError } from "./docker/client";
|
||||
import { log } from "./log";
|
||||
|
||||
const PROGRESS_MS = 1_000;
|
||||
/** CPU flags that matter for inference engines. */
|
||||
const CPU_FEATURES = ["avx2", "avx512f", "avx512_bf16", "avx512_vnni", "avx512bw", "amx_bf16", "amx_int8", "f16c", "fma"];
|
||||
|
||||
let client: DockerClient | null | undefined;
|
||||
export function docker(): DockerClient | null {
|
||||
if (client === undefined) {
|
||||
const host = coreEnv().DOCKER_HOST;
|
||||
client = host ? new DockerClient(host) : null;
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
/** CPU model and features from /proc/cpuinfo (the host's, also inside a container). */
|
||||
async function cpuFacts(): Promise<{ model: string | null; features: string[] }> {
|
||||
try {
|
||||
const text = await readFile("/proc/cpuinfo", "utf8");
|
||||
const model = text.match(/^model name\s*:\s*(.+)$/m)?.[1]?.trim() ?? null;
|
||||
const flags = new Set(text.match(/^flags\s*:\s*(.+)$/m)?.[1]?.split(/\s+/) ?? []);
|
||||
return { model, features: CPU_FEATURES.filter((f) => flags.has(f)) };
|
||||
} catch {
|
||||
return { model: null, features: [] }; // not Linux (dev on Windows/macOS)
|
||||
}
|
||||
}
|
||||
|
||||
/** Find our own container to learn the network and where MODELS_DIR comes from on the host. */
|
||||
async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "network" | "modelsSource">> {
|
||||
const env = coreEnv();
|
||||
let network: string | null = env.KANAME_DOCKER_NETWORK ?? null;
|
||||
let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE
|
||||
? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE }
|
||||
: null;
|
||||
if (network && modelsSource) return { network, modelsSource };
|
||||
|
||||
const self = await c.inspectContainer(hostname()).catch(() => null);
|
||||
if (self) {
|
||||
network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null;
|
||||
const mount = self.Mounts.find((m) => resolve(m.Destination) === resolve(env.MODELS_DIR));
|
||||
if (!modelsSource && mount) {
|
||||
modelsSource = mount.Type === "volume" ? { type: "volume", source: mount.Name ?? mount.Source } : { type: "bind", source: mount.Source };
|
||||
}
|
||||
}
|
||||
return { network, modelsSource };
|
||||
}
|
||||
|
||||
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
|
||||
export async function refreshDockerInfo(instanceId: string): Promise<void> {
|
||||
const c = docker();
|
||||
let info: DockerHostInfo | null = null;
|
||||
if (c) {
|
||||
const cpu = await cpuFacts();
|
||||
const base = {
|
||||
cpuModel: cpu.model,
|
||||
cpuFeatures: cpu.features,
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
const [v, i] = await Promise.all([c.version(), c.info()]);
|
||||
info = {
|
||||
connected: true,
|
||||
error: null,
|
||||
serverVersion: v.Version,
|
||||
os: i.OperatingSystem,
|
||||
architecture: i.Architecture,
|
||||
cpus: i.NCPU,
|
||||
memoryBytes: i.MemTotal,
|
||||
...base,
|
||||
...(await selfDetect(c)),
|
||||
};
|
||||
} catch (err) {
|
||||
info = {
|
||||
connected: false,
|
||||
error: message(err),
|
||||
serverVersion: null,
|
||||
os: null,
|
||||
architecture: null,
|
||||
cpus: null,
|
||||
memoryBytes: null,
|
||||
network: null,
|
||||
modelsSource: null,
|
||||
...base,
|
||||
};
|
||||
}
|
||||
}
|
||||
await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
|
||||
}
|
||||
|
||||
const SEEDED_KEY = "runtimes.presetsSeeded";
|
||||
|
||||
/** Create the preset runtimes once (deleted presets don't come back). */
|
||||
export async function seedRuntimePresets(): Promise<void> {
|
||||
const d = db();
|
||||
const seeded = await d.query.settings.findFirst({ where: eq(settings.key, SEEDED_KEY) });
|
||||
if (seeded) return;
|
||||
const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1);
|
||||
if (existing.length === 0) {
|
||||
await d.insert(runtimes).values(
|
||||
RUNTIME_PRESETS.map((p) => ({
|
||||
name: p.name,
|
||||
engine: p.engine,
|
||||
image: p.image,
|
||||
description: p.description ?? null,
|
||||
env: p.env ?? {},
|
||||
extraArgs: p.extraArgs ?? [],
|
||||
devices: p.devices ?? [],
|
||||
shmSizeMb: p.shmSizeMb ?? null,
|
||||
numaTuning: p.numaTuning ?? false,
|
||||
preset: p.id,
|
||||
})),
|
||||
);
|
||||
log.info(`created ${RUNTIME_PRESETS.length} preset runtime(s)`);
|
||||
}
|
||||
await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing();
|
||||
}
|
||||
|
||||
/** Look up every runtime's image locally (present / missing), except ones being pulled. */
|
||||
export async function syncImageStates(): Promise<void> {
|
||||
const c = docker();
|
||||
if (!c) return;
|
||||
const rows = await db().select().from(runtimes).where(ne(runtimes.imageState, "pulling"));
|
||||
for (const r of rows) {
|
||||
try {
|
||||
const img = await c.inspectImage(r.image);
|
||||
await db()
|
||||
.update(runtimes)
|
||||
.set(
|
||||
img
|
||||
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageCheckedAt: new Date() }
|
||||
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageCheckedAt: new Date() },
|
||||
)
|
||||
.where(eq(runtimes.id, r.id));
|
||||
} catch (err) {
|
||||
log.warn(`image check for ${r.image} failed: ${message(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pulls interrupted by a worker restart can't still be running. */
|
||||
export async function resetStalePulls(): Promise<void> {
|
||||
await db().update(runtimes).set({ imageState: "unknown", pullProgress: null }).where(eq(runtimes.imageState, "pulling"));
|
||||
}
|
||||
|
||||
let pulling = false;
|
||||
/** Pull images whose "Pull" was requested after the last pull started. One at a time. */
|
||||
export async function handlePullRequests(): Promise<void> {
|
||||
const c = docker();
|
||||
if (!c || pulling) return;
|
||||
const rows = await db().select().from(runtimes).where(isNotNull(runtimes.pullRequestedAt));
|
||||
const next = rows.find((r) => r.imageState !== "pulling" && (!r.pullStartedAt || r.pullRequestedAt! > r.pullStartedAt));
|
||||
if (!next) return;
|
||||
|
||||
pulling = true;
|
||||
const d = db();
|
||||
await d
|
||||
.update(runtimes)
|
||||
.set({ imageState: "pulling", pullStartedAt: new Date(), pullError: null, pullProgress: { doneBytes: 0, totalBytes: 0, status: "Starting" } })
|
||||
.where(eq(runtimes.id, next.id));
|
||||
log.info(`pulling ${next.image}`);
|
||||
let lastWrite = 0;
|
||||
try {
|
||||
await c.pullImage(next.image, (p) => {
|
||||
if (Date.now() - lastWrite < PROGRESS_MS) return;
|
||||
lastWrite = Date.now();
|
||||
void d.update(runtimes).set({ pullProgress: p }).where(eq(runtimes.id, next.id));
|
||||
});
|
||||
const img = await c.inspectImage(next.image);
|
||||
await d
|
||||
.update(runtimes)
|
||||
.set({
|
||||
imageState: img ? "present" : "failed",
|
||||
imageId: img?.Id ?? null,
|
||||
imageSize: img?.Size ?? null,
|
||||
imageCreated: img?.Created ?? null,
|
||||
pullProgress: null,
|
||||
pullError: img ? null : "Pull finished but the image isn't there.",
|
||||
imageCheckedAt: new Date(),
|
||||
})
|
||||
.where(eq(runtimes.id, next.id));
|
||||
log.info(`pulled ${next.image}`);
|
||||
} catch (err) {
|
||||
const msg = err instanceof DockerError ? err.message : message(err);
|
||||
await d.update(runtimes).set({ imageState: "failed", pullProgress: null, pullError: msg }).where(eq(runtimes.id, next.id));
|
||||
log.warn(`pulling ${next.image} failed: ${msg}`);
|
||||
} finally {
|
||||
pulling = false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user