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:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 01:24:59 +02:00
1 parent 76683ffd7b
commit b68b4a2b23
23 files changed
+2622 -2

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
// Minimal Docker Engine API client (no dependencies): HTTP over TCP (socket proxy) or a unix socket.
// Only the endpoints Kaname needs. Paths are unversioned, so the daemon's own API version is used.
import http from "node:http";
export class DockerError extends Error {
constructor(
message: string,
public status: number | null,
) {
super(message);
this.name = "DockerError";
}
}
type Target = { socketPath: string } | { host: string; port: number };
function parseHost(dockerHost: string): Target {
if (dockerHost.startsWith("unix://")) return { socketPath: dockerHost.slice("unix://".length) };
const url = new URL(dockerHost.replace(/^tcp:/, "http:"));
return { host: url.hostname, port: Number(url.port || 2375) };
}
export class DockerClient {
private target: Target;
constructor(dockerHost: string) {
this.target = parseHost(dockerHost);
}
private raw(method: string, path: string, body?: unknown, timeoutMs = 30_000): Promise<http.IncomingMessage> {
return new Promise((resolve, reject) => {
const payload = body === undefined ? undefined : JSON.stringify(body);
const req = http.request(
{
...this.target,
method,
path,
headers: { Host: "docker", ...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}) },
timeout: timeoutMs,
},
resolve,
);
req.on("timeout", () => req.destroy(new DockerError(`Docker API ${method} ${path} timed out`, null)));
req.on("error", (err) =>
reject(err instanceof DockerError ? err : new DockerError(`Can't reach Docker (${err.message})`, null)),
);
if (payload) req.write(payload);
req.end();
});
}
private async json<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await this.raw(method, path, body);
const chunks: Buffer[] = [];
for await (const c of res) chunks.push(c as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
if ((res.statusCode ?? 500) >= 400) {
let message = text;
try {
message = JSON.parse(text).message ?? text;
} catch {}
if (res.statusCode === 403) message = `Docker API refused ${method} ${path} (socket proxy permissions?): ${message}`;
throw new DockerError(message.trim() || `HTTP ${res.statusCode}`, res.statusCode ?? null);
}
return (text ? JSON.parse(text) : null) as T;
}
version() {
return this.json<{ Version: string; ApiVersion: string; Os: string; Arch: string }>("GET", "/version");
}
info() {
return this.json<{ NCPU: number; MemTotal: number; OperatingSystem: string; Architecture: string; ServerVersion: string }>(
"GET",
"/info",
);
}
/** Inspect a container; null if it doesn't exist. */
async inspectContainer(id: string) {
try {
return await this.json<{
Id: string;
Name: string;
Mounts: { Type: string; Source: string; Destination: string; Name?: string }[];
NetworkSettings: { Networks: Record<string, unknown> };
}>("GET", `/containers/${encodeURIComponent(id)}/json`);
} catch (err) {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
}
}
/** Inspect a local image; null if it isn't pulled. */
async inspectImage(ref: string) {
try {
return await this.json<{ Id: string; Size: number; Created: string; RepoDigests: string[] }>(
"GET",
`/images/${encodeURIComponent(ref)}/json`,
);
} catch (err) {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
}
}
/**
* Pull an image. The daemon streams JSON lines per layer; `onProgress` gets the summed bytes of
* all layers seen so far. Resolves when the pull finished, rejects on an error line.
*/
async pullImage(ref: string, onProgress: (p: { doneBytes: number; totalBytes: number; status: string }) => void): Promise<void> {
const at = ref.lastIndexOf("@") > 0 ? ref.lastIndexOf("@") : -1;
const colon = ref.lastIndexOf(":");
const hasTag = at === -1 && colon > ref.lastIndexOf("/");
const fromImage = at !== -1 ? ref : hasTag ? ref.slice(0, colon) : ref;
const tag = at !== -1 ? "" : hasTag ? ref.slice(colon + 1) : "latest";
const query = new URLSearchParams({ fromImage, ...(tag ? { tag } : {}) });
const res = await this.raw("POST", `/images/create?${query}`, undefined, 60 * 60_000);
if ((res.statusCode ?? 500) >= 400) {
const chunks: Buffer[] = [];
for await (const c of res) chunks.push(c as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
let message = text;
try {
message = JSON.parse(text).message ?? text;
} catch {}
throw new DockerError(message.trim(), res.statusCode ?? null);
}
const layers = new Map<string, { current: number; total: number }>();
let buffer = "";
let status = "Pulling";
for await (const chunk of res) {
buffer += (chunk as Buffer).toString("utf8");
let nl: number;
while ((nl = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (!line) continue;
const msg = JSON.parse(line) as {
id?: string;
status?: string;
error?: string;
progressDetail?: { current?: number; total?: number };
};
if (msg.error) throw new DockerError(msg.error, null);
if (msg.status) status = msg.status;
if (msg.id && msg.status === "Downloading" && msg.progressDetail?.total) {
layers.set(msg.id, { current: msg.progressDetail.current ?? 0, total: msg.progressDetail.total });
} else if (msg.id && (msg.status === "Download complete" || msg.status === "Pull complete" || msg.status === "Already exists")) {
const l = layers.get(msg.id);
if (l) l.current = l.total;
}
let done = 0;
let total = 0;
for (const l of layers.values()) {
done += l.current;
total += l.total;
}
onProgress({ doneBytes: done, totalBytes: total, status });
}
}
}
}
+17
View File
@@ -15,6 +15,7 @@ import { DeleteRunner } from "./delete";
import { DownloadRunner } from "./download";
import { log } from "./log";
import type { Runner } from "./runner";
import { docker, handlePullRequests, refreshDockerInfo, resetStalePulls, seedRuntimePresets, syncImageStates } from "./runtimes";
import { scanModelsDir } from "./scan";
import { VerifyRunner } from "./verify";
import { settleModelStatus } from "./model-status";
@@ -28,6 +29,9 @@ const SHUTDOWN_GRACE_MS = 8_000;
const HUB_CHECK_SCAN_MS = 10 * 60_000;
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
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;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
@@ -377,6 +381,19 @@ async function main() {
timers.push(setInterval(() => void tick(), TICK_MS));
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
// Runtimes (Docker): presets, host facts, image states, pulls.
await resetStalePulls();
await seedRuntimePresets().catch((err) => log.error("seeding runtime presets failed", err));
if (docker()) log.info(`Docker API: ${coreEnv().DOCKER_HOST}`);
else log.info("DOCKER_HOST not set; runtimes are disabled");
const dockerInfo = () => refreshDockerInfo(instanceId).catch((err) => log.error("Docker info failed", err));
const imageSync = () => syncImageStates().catch((err) => log.error("image sync failed", err));
await dockerInfo();
void imageSync();
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));
void scanFolders();
void tick();
setTimeout(() => void checkHubDue(), 15_000);
+203
View File
@@ -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;
}
}