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
@@ -342,6 +342,69 @@ export const workerState = sqliteTable("worker_state", {
|
||||
heartbeatAt: ts("heartbeat_at").notNull(),
|
||||
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
|
||||
scanRequestedAt: ts("scan_requested_at"),
|
||||
/** Docker connection and host facts, reported by the worker (null: no DOCKER_HOST). */
|
||||
docker: text("docker", { mode: "json" }).$type<DockerHostInfo>(),
|
||||
});
|
||||
|
||||
export type DockerHostInfo = {
|
||||
connected: boolean;
|
||||
error: string | null;
|
||||
serverVersion: string | null;
|
||||
os: string | null;
|
||||
architecture: string | null;
|
||||
cpus: number | null;
|
||||
memoryBytes: number | null;
|
||||
cpuModel: string | null;
|
||||
/** Relevant CPU features (avx2, avx512f, avx512_bf16, amx_bf16, …). */
|
||||
cpuFeatures: string[];
|
||||
/** Docker network inference containers join, so the worker can reach them. */
|
||||
network: string | null;
|
||||
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
|
||||
modelsSource: { type: "bind" | "volume"; source: string } | null;
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** How Kaname builds the command line and talks to the server. */
|
||||
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
|
||||
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
|
||||
|
||||
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
|
||||
export type ImageState = (typeof IMAGE_STATES)[number];
|
||||
|
||||
export const runtimes = sqliteTable("runtimes", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
|
||||
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
|
||||
image: text("image").notNull(),
|
||||
description: text("description"),
|
||||
/** Environment variables for the container. */
|
||||
env: text("env", { mode: "json" }).$type<Record<string, string>>().notNull().default(sql`'{}'`),
|
||||
/** Appended to the generated command line (fork-specific flags). */
|
||||
extraArgs: text("extra_args", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
|
||||
/** Host devices to pass through, e.g. "/dev/dri" (later: Intel GPUs). */
|
||||
devices: text("devices", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
|
||||
shmSizeMb: integer("shm_size_mb"),
|
||||
/** vLLM's NUMA optimizations: adds CAP_SYS_NICE and seccomp=unconfined. Off unless enabled. */
|
||||
numaTuning: integer("numa_tuning", { mode: "boolean" }).notNull().default(false),
|
||||
/** Preset this runtime was created from, if any. */
|
||||
preset: text("preset"),
|
||||
imageState: text("image_state", { enum: IMAGE_STATES }).notNull().default("unknown"),
|
||||
imageId: text("image_id"),
|
||||
imageSize: integer("image_size"),
|
||||
imageCreated: text("image_created"),
|
||||
/** Set by "Pull"; the worker pulls when this is newer than the last pull. */
|
||||
pullRequestedAt: ts("pull_requested_at"),
|
||||
pullStartedAt: ts("pull_started_at"),
|
||||
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
|
||||
pullError: text("pull_error"),
|
||||
imageCheckedAt: ts("image_checked_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,6 +22,14 @@ const coreSchema = z.object({
|
||||
),
|
||||
/** hf CLI home (token cache, Xet logs/cache). Not the model storage. */
|
||||
HF_HOME: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/**
|
||||
* Docker API for runtimes (worker only), e.g. tcp://docker-proxy:2375 or unix:///var/run/docker.sock.
|
||||
* Unset: runtimes are disabled.
|
||||
*/
|
||||
DOCKER_HOST: z.preprocess(emptyToUndefined, z.string().regex(/^(tcp|unix):\/\//, "must start with tcp:// or unix://").optional()),
|
||||
/** Override the auto-detected Docker network / models source (needed when the worker isn't a container). */
|
||||
KANAME_DOCKER_NETWORK: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
KANAME_MODELS_SOURCE: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
});
|
||||
|
||||
const authSchema = z.object({
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { parseEnvLines, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "./runtimes-shared";
|
||||
|
||||
const base = { name: "x", engine: "vllm" as const, image: "vllm/vllm-openai-cpu:v0.31.0" };
|
||||
|
||||
describe("validateRuntime", () => {
|
||||
it("accepts the presets and common image references", () => {
|
||||
for (const p of RUNTIME_PRESETS) assert.doesNotThrow(() => validateRuntime(p));
|
||||
for (const image of [
|
||||
"ghcr.io/ggml-org/llama.cpp:server",
|
||||
"git.linxweiler.xyz/me/vllm-arc:0.9-patched",
|
||||
"localhost:5000/vllm",
|
||||
`vllm/vllm-openai-xpu@sha256:${"a".repeat(64)}`,
|
||||
]) {
|
||||
assert.equal(validateRuntime({ ...base, image }).image, image);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects bad images, env names, devices and multi-line values", () => {
|
||||
const bad = (patch: object) => assert.throws(() => validateRuntime({ ...base, ...patch }), RuntimeValidationError);
|
||||
bad({ image: "Vllm/Upper:tag" });
|
||||
bad({ image: "vllm/vllm --privileged" });
|
||||
bad({ env: { "BAD-KEY": "1" } });
|
||||
bad({ env: { OK: "a\nb" } });
|
||||
bad({ devices: ["/dev/sda"] });
|
||||
bad({ devices: ["/"] });
|
||||
bad({ extraArgs: ["--a\n--b"] });
|
||||
bad({ name: " " });
|
||||
assert.deepEqual(validateRuntime({ ...base, devices: ["/dev/dri", "/dev/dri/renderD128"] }).devices, [
|
||||
"/dev/dri",
|
||||
"/dev/dri/renderD128",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseEnvLines", () => {
|
||||
it("parses KEY=value lines, skipping blanks and comments", () => {
|
||||
assert.deepEqual(parseEnvLines("A=1\n\n# note\nB = x=y \n"), { A: "1", B: "x=y" });
|
||||
assert.throws(() => parseEnvLines("novalue"), RuntimeValidationError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
// Runtime presets and validation. Pure (no DB), shared by the web app, the worker and tests.
|
||||
|
||||
import type { RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
export type RuntimeInput = {
|
||||
name: string;
|
||||
engine: RuntimeEngine;
|
||||
image: string;
|
||||
description?: string | null;
|
||||
env?: Record<string, string>;
|
||||
extraArgs?: string[];
|
||||
devices?: string[];
|
||||
shmSizeMb?: number | null;
|
||||
numaTuning?: boolean;
|
||||
};
|
||||
|
||||
export type RuntimePreset = RuntimeInput & { id: string; summary: string };
|
||||
|
||||
/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0). */
|
||||
export const RUNTIME_PRESETS: RuntimePreset[] = [
|
||||
{
|
||||
id: "llama.cpp-cpu",
|
||||
name: "llama.cpp (CPU)",
|
||||
engine: "llama.cpp",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server",
|
||||
summary: "Official llama-server image, CPU build. Serves GGUF models.",
|
||||
description: "Official llama.cpp server, CPU build. Pin a build tag (e.g. server-b11429) for reproducible tests.",
|
||||
},
|
||||
{
|
||||
id: "vllm-cpu",
|
||||
name: "vLLM (CPU)",
|
||||
engine: "vllm",
|
||||
image: "vllm/vllm-openai-cpu:v0.31.0",
|
||||
summary: "Official vLLM CPU image. Serves safetensors models (BF16 recommended on AMD Zen).",
|
||||
description: "Official vLLM CPU build. VLLM_CPU_KVCACHE_SPACE is the KV cache size in GiB.",
|
||||
env: { VLLM_CPU_KVCACHE_SPACE: "4" },
|
||||
extraArgs: ["--dtype=bfloat16"],
|
||||
shmSizeMb: 4096,
|
||||
},
|
||||
];
|
||||
|
||||
export const RUNTIME_NAME_MAX = 60;
|
||||
// [registry[:port]/]path[:tag][@sha256:digest], lowercase path components as Docker requires.
|
||||
const IMAGE_RE =
|
||||
/^(?:[a-z0-9]+(?:[.-][a-z0-9]+)*(?::\d+)?\/)?[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*(?::[\w][\w.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$/;
|
||||
const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
/** Device passthrough is limited to GPU device nodes (Intel/AMD: /dev/dri, AMD: /dev/kfd). */
|
||||
const DEVICE_RE = /^\/dev\/(dri(\/[\w.-]+)?|kfd)$/;
|
||||
|
||||
export class RuntimeValidationError extends Error {}
|
||||
|
||||
/** Normalize and validate a runtime definition; throws RuntimeValidationError with a readable message. */
|
||||
export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
|
||||
const name = input.name.trim().replace(/\s+/g, " ");
|
||||
if (!name || name.length > RUNTIME_NAME_MAX) throw new RuntimeValidationError(`Name must be 1–${RUNTIME_NAME_MAX} characters.`);
|
||||
if (input.engine !== "llama.cpp" && input.engine !== "vllm") throw new RuntimeValidationError("Unknown engine type.");
|
||||
const image = input.image.trim();
|
||||
if (!IMAGE_RE.test(image)) throw new RuntimeValidationError(`"${image}" is not a valid image reference (e.g. ghcr.io/org/image:tag).`);
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(input.env ?? {})) {
|
||||
if (!ENV_KEY_RE.test(k)) throw new RuntimeValidationError(`Invalid environment variable name "${k}".`);
|
||||
if (/[\r\n\0]/.test(v)) throw new RuntimeValidationError(`Value of ${k} must be a single line.`);
|
||||
env[k] = v;
|
||||
}
|
||||
const extraArgs = (input.extraArgs ?? []).map((a) => a.trim()).filter(Boolean);
|
||||
for (const a of extraArgs) if (/[\r\n\0]/.test(a)) throw new RuntimeValidationError("Arguments must be single lines.");
|
||||
const devices = (input.devices ?? []).map((d) => d.trim()).filter(Boolean);
|
||||
for (const d of devices) {
|
||||
if (!DEVICE_RE.test(d)) throw new RuntimeValidationError(`Device "${d}" isn't allowed (only /dev/dri… and /dev/kfd).`);
|
||||
}
|
||||
const shm = input.shmSizeMb ?? null;
|
||||
if (shm != null && (!Number.isInteger(shm) || shm < 64 || shm > 262_144)) {
|
||||
throw new RuntimeValidationError("Shared memory must be between 64 MiB and 256 GiB.");
|
||||
}
|
||||
return {
|
||||
name,
|
||||
engine: input.engine,
|
||||
image,
|
||||
description: input.description?.trim() || null,
|
||||
env,
|
||||
extraArgs,
|
||||
devices,
|
||||
shmSizeMb: shm,
|
||||
numaTuning: !!input.numaTuning,
|
||||
};
|
||||
}
|
||||
|
||||
/** "KEY=value" lines ⇄ env object (for the editor). */
|
||||
export function parseEnvLines(text: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line || line.startsWith("#")) continue;
|
||||
const eq = line.indexOf("=");
|
||||
if (eq <= 0) throw new RuntimeValidationError(`"${line}" isn't KEY=value.`);
|
||||
out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const formatEnvLines = (env: Record<string, string>) =>
|
||||
Object.entries(env)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("\n");
|
||||
@@ -0,0 +1,97 @@
|
||||
import "server-only";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type DockerHostInfo, runtimes, workerState } from "@/lib/db/schema";
|
||||
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
|
||||
|
||||
export type Runtime = typeof runtimes.$inferSelect;
|
||||
|
||||
/** Request body for creating/updating a runtime (validated further by validateRuntime). */
|
||||
export const RuntimeBody = z.object({
|
||||
name: z.string().max(200),
|
||||
engine: z.enum(["llama.cpp", "vllm"]),
|
||||
image: z.string().max(512),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
env: z.record(z.string(), z.string().max(4000)).optional(),
|
||||
extraArgs: z.array(z.string().max(4000)).max(200).optional(),
|
||||
devices: z.array(z.string().max(200)).max(20).optional(),
|
||||
shmSizeMb: z.number().int().nullable().optional(),
|
||||
numaTuning: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export class RuntimeError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function validated(input: RuntimeInput) {
|
||||
try {
|
||||
return validateRuntime(input);
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeValidationError) throw new RuntimeError("invalid", err.message, 400);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listRuntimes(): Promise<Runtime[]> {
|
||||
return db().select().from(runtimes).orderBy(asc(runtimes.createdAt));
|
||||
}
|
||||
|
||||
export async function getRuntime(id: string): Promise<Runtime> {
|
||||
const r = await db().query.runtimes.findFirst({ where: eq(runtimes.id, id) });
|
||||
if (!r) throw new RuntimeError("not_found", "Runtime not found.", 404);
|
||||
return r;
|
||||
}
|
||||
|
||||
export async function createRuntime(input: RuntimeInput & { preset?: string }): Promise<Runtime> {
|
||||
const v = validated(input);
|
||||
const preset = input.preset && RUNTIME_PRESETS.some((p) => p.id === input.preset) ? input.preset : null;
|
||||
const [row] = await db()
|
||||
.insert(runtimes)
|
||||
.values({ ...v, preset })
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateRuntime(id: string, input: RuntimeInput): Promise<Runtime> {
|
||||
const current = await getRuntime(id);
|
||||
const v = validated(input);
|
||||
const imageChanged = v.image !== current.image;
|
||||
const [row] = await db()
|
||||
.update(runtimes)
|
||||
.set({
|
||||
...v,
|
||||
// A different image has to be looked up (and maybe pulled) again.
|
||||
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, pullError: null } : {}),
|
||||
})
|
||||
.where(eq(runtimes.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function deleteRuntime(id: string): Promise<void> {
|
||||
await getRuntime(id);
|
||||
await db().delete(runtimes).where(eq(runtimes.id, id));
|
||||
}
|
||||
|
||||
/** Ask the worker to pull (or re-pull, to update a moving tag) the runtime's image. */
|
||||
export async function requestPull(id: string): Promise<void> {
|
||||
await getRuntime(id);
|
||||
await db().update(runtimes).set({ pullRequestedAt: new Date(), pullError: null }).where(eq(runtimes.id, id));
|
||||
}
|
||||
|
||||
/** Docker facts as last reported by the worker; null when DOCKER_HOST isn't configured. */
|
||||
export async function getDockerInfo(): Promise<DockerHostInfo | null> {
|
||||
try {
|
||||
const row = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
|
||||
return row?.docker ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user