Compare commits

...
2 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 930126c5eb Release 0.7.0: runtimes and Docker connection
Release / release (push) Successful in 11m56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:27:18 +02:00
Pascal LinxweilerandClaude Opus 5.5 b68b4a2b23 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>
2026-10-06 01:24:59 +02:00
25 changed files with 2631 additions and 5 deletions

No files matched your search

+23
View File
@@ -6,6 +6,29 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.7.0] - 2026-10-06
First part of model testing: runtimes (llama.cpp, vLLM and your own images) and the Docker
connection through a socket proxy. Starting containers with a model comes next.
**Upgrade note:** `compose.yaml` has a new `docker-proxy` service and `DOCKER_HOST` on the worker;
copy them from `deploy/compose.yaml`.
### Added
- **Runtimes** (Settings → Runtimes): container images that serve models. Presets for the official
llama.cpp CPU server (`ghcr.io/ggml-org/llama.cpp:server`) and vLLM CPU
(`vllm/vllm-openai-cpu:v0.31.0`), plus your own images from any registry (e.g. patched forks) with
an engine type (llama.cpp- or vLLM-compatible), environment, extra arguments, shared memory,
device passthrough (only `/dev/dri…`, `/dev/kfd`) and an opt-in "NUMA tuning" switch (the
`CAP_SYS_NICE` + `seccomp=unconfined` that vLLM recommends on CPU; off by default).
- Pull and update runtime images from the UI, with progress and readable errors.
- Docker host card: Docker version, CPU model and features (AVX2, AVX-512, AMX, …), memory, and the
network and models source the worker detected from its own container.
- `docker-proxy` service (`tecnativa/docker-socket-proxy:v0.5.0`) in both compose files; the worker
reaches Docker only through it (`DOCKER_HOST`). New settings `DOCKER_HOST`,
`KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` (see the wiki).
## [0.6.0] - 2026-10-06
Delete models (with their files), verify and deep verify, one-click repair, and update checks
+3
View File
@@ -82,6 +82,9 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
model is flagged and your local copy is kept.
- **Delete:** removes the model and, if you want, its files from disk.
- **Runtimes:** register llama.cpp, vLLM or your own fork images and pull them from Settings → Runtimes
(groundwork for testing model configs). See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
## How it works
+22
View File
@@ -16,6 +16,11 @@ services:
worker:
<<: *app
command: worker
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
DOCKER_HOST: tcp://docker-proxy:2375
volumes: [data:/data, models:/models]
web:
@@ -23,6 +28,23 @@ services:
ports: ["${WEB_PORT:-3000}:3000"]
volumes: [data:/data]
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
volumes:
data:
models:
+19
View File
@@ -8,6 +8,8 @@ services:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
DOCKER_HOST: tcp://docker-proxy:2375
volumes:
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
@@ -20,3 +22,20 @@ services:
volumes:
- ${KANAME_DATA_DIR:-./data}:/data
restart: unless-stopped
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
+26
View File
@@ -0,0 +1,26 @@
CREATE TABLE `runtimes` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`engine` text NOT NULL,
`image` text NOT NULL,
`description` text,
`env` text DEFAULT '{}' NOT NULL,
`extra_args` text DEFAULT '[]' NOT NULL,
`devices` text DEFAULT '[]' NOT NULL,
`shm_size_mb` integer,
`numa_tuning` integer DEFAULT false NOT NULL,
`preset` text,
`image_state` text DEFAULT 'unknown' NOT NULL,
`image_id` text,
`image_size` integer,
`image_created` text,
`pull_requested_at` integer,
`pull_started_at` integer,
`pull_progress` text,
`pull_error` text,
`image_checked_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `worker_state` ADD `docker` text;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -71,6 +71,13 @@
"when": 1791238659338,
"tag": "0009_verify_update",
"breakpoints": true
},
{
"idx": 10,
"version": "6",
"when": 1791242201063,
"tag": "0010_runtimes",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.6.0",
"version": "0.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.6.0",
"version": "0.7.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.6.0",
"version": "0.7.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
+2 -1
View File
@@ -1,10 +1,11 @@
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
+12
View File
@@ -0,0 +1,12 @@
import type { Metadata } from "next";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import { getWorkerStatus } from "@/lib/worker-status";
import { RuntimesView } from "./runtimes-view";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Runtimes · Settings" };
export default async function RuntimesPage() {
const [runtimes, docker, worker] = await Promise.all([listRuntimes(), getDockerInfo(), getWorkerStatus()]);
return <RuntimesView runtimes={runtimes} docker={docker} workerOnline={worker.online} />;
}
@@ -0,0 +1,187 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
{ id: "llama.cpp", label: "llama.cpp-compatible", hint: "llama-server command line, GGUF models" },
{ id: "vllm", label: "vLLM-compatible", hint: "vllm serve command line, safetensors models" },
];
const textareaClass =
"min-h-20 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
/** Create/edit a runtime. Validates locally with the same rules as the server. */
export function RuntimeForm({
initial,
submitLabel,
onSubmit,
onCancel,
}: {
initial: RuntimeInput;
submitLabel: string;
onSubmit: (value: RuntimeInput) => Promise<boolean>;
onCancel: () => void;
}) {
const [name, setName] = useState(initial.name);
const [engine, setEngine] = useState<RuntimeEngine>(initial.engine);
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argsText, setArgsText] = useState((initial.extraArgs ?? []).join("\n"));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
const [numa, setNuma] = useState(!!initial.numaTuning);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
async function submit(e: React.FormEvent) {
e.preventDefault();
let value: RuntimeInput;
try {
value = validateRuntime({
name,
engine,
image,
description,
env: parseEnvLines(envText),
extraArgs: argsText.split("\n"),
devices: devicesText.split(/[,\s]+/),
shmSizeMb: shm.trim() ? Number(shm) : null,
numaTuning: numa,
});
} catch (err) {
setError(err instanceof RuntimeValidationError ? err.message : String(err));
return;
}
setError(null);
setSaving(true);
try {
await onSubmit(value);
} finally {
setSaving(false);
}
}
return (
<form onSubmit={submit} className="flex flex-col gap-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-name">Name</Label>
<Input id="rt-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="vLLM XPU (Arc patches)" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-image">Image</Label>
<Input
id="rt-image"
value={image}
onChange={(e) => setImage(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="registry.example.com/org/image:tag"
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label>Engine type</Label>
<div className="grid gap-2 sm:grid-cols-2">
{ENGINES.map((e) => (
<button
key={e.id}
type="button"
onClick={() => setEngine(e.id)}
className={cn(
"flex flex-col items-start rounded-lg border px-3 py-2 text-left text-sm transition-colors",
engine === e.id ? "border-primary bg-primary/5" : "hover:bg-muted/50",
)}
>
<span className="font-medium">{e.label}</span>
<span className="text-xs text-muted-foreground">{e.hint}</span>
</button>
))}
</div>
<p className="text-xs text-muted-foreground">
Decides how Kaname builds the command line. Forks with the same CLI (e.g. patched vLLM builds) use the same type.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-desc">Description</Label>
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-args">Extra arguments</Label>
<textarea
id="rt-args"
value={argsText}
onChange={(e) => setArgsText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"--dtype=bfloat16"}
/>
<p className="text-xs text-muted-foreground">One per line, appended to the generated command.</p>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-shm">Shared memory (MiB)</Label>
<Input id="rt-shm" value={shm} onChange={(e) => setShm(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric" placeholder="Docker default (64)" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-devices">Devices</Label>
<Input
id="rt-devices"
value={devicesText}
onChange={(e) => setDevicesText(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="/dev/dri (Intel/AMD GPUs, later)"
/>
</div>
</div>
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg bg-muted/50 px-3 py-2.5 text-sm">
<Checkbox checked={numa} onCheckedChange={(v) => setNuma(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>NUMA tuning</span>
<span className="text-xs text-muted-foreground">
Adds <code>CAP_SYS_NICE</code> and <code>seccomp=unconfined</code>, as vLLM recommends for its CPU build. This relaxes
the container&apos;s isolation; leave it off unless you need the extra speed.
</span>
</span>
</label>
{error && <p className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</p>}
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button type="submit" disabled={saving}>
{saving ? "Saving…" : submitLabel}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,352 @@
"use client";
import { ChevronDownIcon, CopyIcon, DownloadCloudIcon, PencilIcon, PlusIcon, ServerIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Progress } from "@/components/ui/progress";
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
import { formatBytes, percent } from "@/lib/format";
import { RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
import { RuntimeForm } from "./runtime-form";
type Runtime = typeof runtimes.$inferSelect;
const FEATURE_LABEL: Record<string, string> = {
avx2: "AVX2",
avx512f: "AVX-512",
avx512_bf16: "AVX-512 BF16",
avx512_vnni: "AVX-512 VNNI",
avx512bw: "AVX-512 BW",
amx_bf16: "AMX BF16",
amx_int8: "AMX INT8",
f16c: "F16C",
fma: "FMA",
};
async function send(url: string, method: string, body?: unknown): Promise<boolean> {
const res = await fetch(url, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
if (res.ok) return true;
const json = await res.json().catch(() => ({}));
toast.error(json.error?.message ?? `Request failed (${res.status})`);
return false;
}
const toInput = (r: Runtime): RuntimeInput => ({
name: r.name,
engine: r.engine,
image: r.image,
description: r.description,
env: r.env,
extraArgs: r.extraArgs,
devices: r.devices,
shmSizeMb: r.shmSizeMb,
numaTuning: r.numaTuning,
});
export function RuntimesView({ runtimes, docker, workerOnline }: { runtimes: Runtime[]; docker: DockerHostInfo | null; workerOnline: boolean }) {
const router = useRouter();
const [creating, setCreating] = useState<(RuntimeInput & { preset?: string }) | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const anyPulling = runtimes.some((r) => r.imageState === "pulling" || (r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt)));
// While a pull runs, refresh the server data every 2 s for its progress.
useEffect(() => {
if (!anyPulling) return;
const t = setInterval(() => router.refresh(), 2_000);
return () => clearInterval(t);
}, [anyPulling, router]);
return (
<div className="flex flex-col gap-4">
<HostCard docker={docker} workerOnline={workerOnline} />
<Card>
<CardHeader>
<CardTitle>Runtimes</CardTitle>
<CardDescription>
Container images that serve models: official llama.cpp and vLLM builds, or your own forks from any registry. Kaname
only starts images registered here, with the models mounted read-only.
</CardDescription>
<CardAction>
<DropdownMenu>
<DropdownMenuTrigger render={<Button size="sm" />}>
<PlusIcon />
Add runtime
<ChevronDownIcon className="opacity-70" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-72">
<DropdownMenuGroup>
<DropdownMenuLabel>From a preset</DropdownMenuLabel>
{RUNTIME_PRESETS.map((p) => (
<DropdownMenuItem key={p.id} onClick={() => setCreating({ ...p, name: p.name, preset: p.id })} className="flex-col items-start gap-0">
<span>{p.name}</span>
<span className="text-xs text-muted-foreground">{p.summary}</span>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setCreating({ name: "", engine: "vllm", image: "" })}>Custom image (fork)…</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardAction>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{creating && (
<div className="rounded-lg p-4 ring-1 ring-primary/40">
<RuntimeForm
initial={creating}
submitLabel="Add runtime"
onCancel={() => setCreating(null)}
onSubmit={async (value) => {
const ok = await send("/api/runtimes", "POST", { ...value, preset: creating.preset });
if (ok) {
toast.success(`Runtime "${value.name}" added`);
setCreating(null);
router.refresh();
}
return ok;
}}
/>
</div>
)}
{runtimes.length === 0 && !creating && <p className="text-sm text-muted-foreground">No runtimes yet. Add one from a preset.</p>}
{runtimes.map((r) =>
editing === r.id ? (
<div key={r.id} className="rounded-lg p-4 ring-1 ring-primary/40">
<RuntimeForm
initial={toInput(r)}
submitLabel="Save"
onCancel={() => setEditing(null)}
onSubmit={async (value) => {
const ok = await send(`/api/runtimes/${r.id}`, "PUT", value);
if (ok) {
setEditing(null);
router.refresh();
}
return ok;
}}
/>
</div>
) : (
<RuntimeRow
key={r.id}
runtime={r}
dockerReady={!!docker?.connected}
onEdit={() => setEditing(r.id)}
onDuplicate={() => setCreating({ ...toInput(r), name: `${r.name} (copy)` })}
/>
),
)}
</CardContent>
</Card>
</div>
);
}
function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; workerOnline: boolean }) {
return (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ServerIcon className="size-4 text-muted-foreground" />
Docker host
</CardTitle>
<CardDescription>
{!workerOnline
? "The worker is offline; these facts may be outdated."
: !docker
? "Not connected. Runtimes need the worker to reach Docker through the socket proxy (DOCKER_HOST)."
: docker.connected
? `Docker ${docker.serverVersion} on ${docker.os} (${docker.architecture})`
: `Can't reach Docker: ${docker.error}`}
</CardDescription>
</CardHeader>
{docker && (
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">CPU</dt>
<dd>
{docker.cpuModel ?? "unknown"}
{docker.cpus != null && <span className="text-muted-foreground"> · {docker.cpus} threads</span>}
</dd>
<dt className="text-muted-foreground">Features</dt>
<dd className="flex flex-wrap gap-1">
{docker.cpuFeatures.length === 0 ? (
<span className="text-muted-foreground">unknown</span>
) : (
docker.cpuFeatures.map((f) => (
<span
key={f}
className={cn(
"rounded border px-1.5 text-xs",
f.startsWith("avx512") || f.startsWith("amx") ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground",
)}
>
{FEATURE_LABEL[f] ?? f}
</span>
))
)}
</dd>
<dt className="text-muted-foreground">Memory</dt>
<dd>{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}</dd>
<dt className="text-muted-foreground">Network</dt>
<dd className={cn("font-mono text-xs", !docker.network && "text-amber-700 dark:text-amber-300")}>
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
</dd>
<dt className="text-muted-foreground">Models</dt>
<dd className={cn("font-mono text-xs break-all", !docker.modelsSource && "text-amber-700 dark:text-amber-300")}>
{docker.modelsSource ? `${docker.modelsSource.source} (${docker.modelsSource.type}, mounted read-only)` : "not detected (set KANAME_MODELS_SOURCE)"}
</dd>
<dt className="text-muted-foreground">Checked</dt>
<dd>
<LocalTime value={docker.checkedAt} />
</dd>
</dl>
</CardContent>
)}
</Card>
);
}
function ImageState({ r }: { r: Runtime }) {
const requested = !!r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt);
if (r.imageState === "pulling" || requested) {
const p = r.pullProgress;
return (
<div className="flex min-w-48 flex-col gap-1">
<span className="text-xs text-muted-foreground">
{p ? `${p.status} · ${formatBytes(p.doneBytes)}${p.totalBytes ? ` / ${formatBytes(p.totalBytes)}` : ""}` : "Pull queued…"}
</span>
<Progress value={p && p.totalBytes ? percent(p.doneBytes, p.totalBytes) : 0} />
</div>
);
}
if (r.imageState === "present") {
return (
<span className="text-xs text-emerald-700 dark:text-emerald-400">
Pulled · {r.imageSize != null ? formatBytes(r.imageSize) : "?"}
{r.imageCreated && (
<span className="text-muted-foreground">
{" "}
· built <LocalTime value={r.imageCreated} />
</span>
)}
</span>
);
}
if (r.imageState === "failed") return <span className="text-xs break-all text-destructive">Pull failed: {r.pullError}</span>;
if (r.imageState === "missing") return <span className="text-xs text-muted-foreground">Not pulled yet</span>;
return <span className="text-xs text-muted-foreground">Not checked yet</span>;
}
function RuntimeRow({
runtime: r,
dockerReady,
onEdit,
onDuplicate,
}: {
runtime: Runtime;
dockerReady: boolean;
onEdit: () => void;
onDuplicate: () => void;
}) {
const router = useRouter();
const pulling = r.imageState === "pulling";
const envCount = Object.keys(r.env).length;
return (
<div className="flex flex-col gap-3 rounded-lg px-4 py-3 ring-1 ring-foreground/10">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{r.name}</span>
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">{r.engine === "vllm" ? "vLLM" : "llama.cpp"}</span>
{r.numaTuning && <span className="rounded-md border border-amber-500/30 px-1.5 text-xs text-amber-700 dark:text-amber-300">NUMA tuning</span>}
</div>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
{r.description && <p className="text-xs text-muted-foreground">{r.description}</p>}
</div>
<div className="flex items-center gap-1">
<Button
size="sm"
variant={r.imageState === "present" ? "ghost" : "outline"}
disabled={!dockerReady || pulling}
title={!dockerReady ? "Docker isn't connected" : r.imageState === "present" ? "Pull again to update the tag" : undefined}
onClick={async () => {
if (await send(`/api/runtimes/${r.id}/pull`, "POST")) router.refresh();
}}
>
<DownloadCloudIcon />
{r.imageState === "present" ? "Update" : "Pull"}
</Button>
<Button size="icon-sm" variant="ghost" onClick={onEdit} aria-label={`Edit ${r.name}`}>
<PencilIcon />
</Button>
<Button size="icon-sm" variant="ghost" onClick={onDuplicate} aria-label={`Duplicate ${r.name}`}>
<CopyIcon />
</Button>
<AlertDialog>
<AlertDialogTrigger render={<Button size="icon-sm" variant="ghost" aria-label={`Delete ${r.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete runtime &ldquo;{r.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>The pulled image stays in Docker; remove it there if you need the space.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1 text-xs text-muted-foreground">
<ImageState r={r} />
<span>
{envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
{r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
{r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
{r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
</span>
</div>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { requestPull, RuntimeError } from "@/lib/runtimes";
/** Ask the worker to pull the image (again; updates moving tags like :server). */
export const POST = withAuth<RouteContext<"/api/runtimes/[id]/pull">>(async (_req, { params }) => {
const { id } = await params;
try {
await requestPull(id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteRuntime, RuntimeBody, RuntimeError, updateRuntime } from "@/lib/runtimes";
export const PUT = withAuth<RouteContext<"/api/runtimes/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await updateRuntime(id, RuntimeBody.parse(await req.json())));
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
export const DELETE = withAuth<RouteContext<"/api/runtimes/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteRuntime(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createRuntime, getDockerInfo, listRuntimes, RuntimeBody, RuntimeError } from "@/lib/runtimes";
export const dynamic = "force-dynamic";
/** Runtimes plus the Docker facts the worker reported. */
export const GET = withAuth(async () => NextResponse.json({ runtimes: await listRuntimes(), docker: await getDockerInfo() }));
export const POST = withAuth(async (req) => {
try {
const body = RuntimeBody.extend({ preset: z.string().optional() }).parse(await req.json());
return NextResponse.json(await createRuntime(body), { status: 201 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+5 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -67,6 +67,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<TagsIcon />
Tags
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/runtimes" />}>
<BoxesIcon />
Runtimes
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
+63
View File
@@ -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(),
});
/**
+8
View File
@@ -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({
+42
View File
@@ -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);
});
});
+105
View File
@@ -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");
+97
View File
@@ -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;
}
}
+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;
}
}