Deployments: serve a model with a runtime container

- deployments + deployment_logs tables; desired/actual state reconciled by
  the worker (create/start/stop/remove via the socket proxy, /health wait,
  log follower, stats, memory guard, adopt/remove containers on restart).
- Pure command builder for llama-server and vllm serve (mmproj, MTP draft,
  KV cache types, dtype, KV cache size) with tests; file candidates per
  engine with tests.
- New main menu entry Deployments: list, new/edit form (runtime -> model
  and files -> launch options, live command preview), detail page with
  stats, log, endpoint and a streaming chat smoke test.

Not yet tested end-to-end against real containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 11:31:04 +02:00
1 parent 4f7ae1fc8c
commit 8b74fa69db
32 files changed
+3824 -3

No files matched your search

+18
View File
@@ -6,6 +6,24 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
### Added
- **Deployments** (new main menu entry): serve a downloaded model with a runtime container.
- **New deployment:** pick a runtime (only pulled images), then a model it can serve (llama.cpp:
downloaded GGUF files with the quant, optional mmproj for vision and MTP head / draft model for
speculative decoding; vLLM: safetensors repos with a config.json), then launch options: context
size, threads, parallel slots, KV cache types, flash attention, batch sizes (llama.cpp) or data
type, max sequences, KV cache GiB (vLLM), CPU and memory limits (with an estimate), an optional
published host port and extra arguments. A live preview shows the exact `docker run` command.
- The worker starts the container on Kaname's Docker network with the models mounted read-only,
waits for `/health`, follows the log, samples CPU/RAM every 5 s and refuses to start when the
memory limits of running deployments wouldn't fit. Containers keep running across worker
restarts; orphaned ones are removed.
- Deployment page: state, load time, live CPU/RAM, endpoint URLs (Docker network and published
port), live log, start/stop/edit/delete, and a "Try it" chat that streams the answer and shows
time to first token and tokens/s.
- Models and runtimes used by a deployment can't be deleted until the deployment is.
### Fixed
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
+37
View File
@@ -0,0 +1,37 @@
CREATE TABLE `deployment_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`deployment_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL,
FOREIGN KEY (`deployment_id`) REFERENCES `deployments`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `deployment_logs_idx` ON `deployment_logs` (`deployment_id`,`id`);--> statement-breakpoint
CREATE TABLE `deployments` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`runtime_id` text NOT NULL,
`model_id` text NOT NULL,
`options` text NOT NULL,
`cpus` real,
`memory_mb` integer,
`host_port` integer,
`desired_state` text DEFAULT 'stopped' NOT NULL,
`state` text DEFAULT 'stopped' NOT NULL,
`delete_requested_at` integer,
`container_id` text,
`container_name` text,
`command` text,
`image_id` text,
`started_at` integer,
`ready_at` integer,
`stopped_at` integer,
`exit_code` integer,
`error` text,
`stats` text,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`runtime_id`) REFERENCES `runtimes`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -78,6 +78,13 @@
"when": 1791242201063,
"tag": "0010_runtimes",
"breakpoints": true
},
{
"idx": 11,
"version": "6",
"when": 1791278463453,
"tag": "0011_deployments",
"breakpoints": true
}
]
}
@@ -0,0 +1,402 @@
"use client";
import { PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { ENGINE_PORT } from "@/lib/deploy-command";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
type LogLine = { id: number; ts: number; stream: string; line: string };
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold tabular-nums">{value}</span>
{children}
</div>
);
}
export function DeploymentDetail({ initial }: { initial: Deployment }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
useEffect(() => {
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
if (res?.status === 404) router.push("/deployments");
else if (res?.ok) setD(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [d.id, router]);
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
// The browser's host name (null while rendering on the server, so hydration matches).
const hostname = useSyncExternalStore(
() => () => {},
() => window.location.hostname,
() => null,
);
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{d.name}</h1>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
{d.repoId}
</Link>
{file && ` · ${file}`}
{d.options.mmproj && " · vision"}
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
</p>
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
</div>
<div className="flex flex-wrap items-center gap-2">
{active ? (
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
<SquareIcon />
Stop
</Button>
) : (
<Button onClick={() => startDeployment(d.id)}>
<PlayIcon />
Start
</Button>
)}
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
aria-disabled={active}
title={active ? "Stop it first" : undefined}
>
<PencilIcon />
Edit
</Link>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteDeployment(d.id)) router.push("/deployments");
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{d.state === "failed" && d.error && (
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
<div className="flex min-w-0 flex-col gap-4">
<Card>
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat
label="CPU"
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
>
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
</Stat>
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
{d.stats && d.state === "running" && d.memoryMb ? (
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
) : (
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
)}
</Stat>
<Stat
label={d.state === "starting" ? "Loading" : "Load time"}
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
>
<span className="text-xs text-muted-foreground">until /health answered</span>
</Stat>
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
<span className="text-xs text-muted-foreground">
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
</span>
</Stat>
</CardContent>
</Card>
<Logs id={d.id} />
</div>
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-xs">
{internal ? (
<div className="flex items-center justify-between gap-2">
<code className="font-mono break-all">{internal}</code>
<CopyButton value={internal} label="Copy URL" />
</div>
) : (
<span className="text-muted-foreground">Not started yet.</span>
)}
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
{published && (
<div className="flex items-center justify-between gap-2 border-t pt-2">
<code className="font-mono break-all">{published}</code>
<CopyButton value={published} label="Copy URL" />
</div>
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
</span>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Container</dt>
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={d.startedAt} />
</dd>
<dt className="text-muted-foreground">Stopped</dt>
<dd>
<LocalTime value={d.stoppedAt} />
</dd>
{d.command && (
<>
<dt className="text-muted-foreground">Arguments</dt>
<dd className="flex items-start gap-1">
<code className="font-mono break-all">{d.command.join(" ")}</code>
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
</dd>
</>
)}
</dl>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
/** Live container log (polls new lines every 1.5 s). */
function Logs({ id }: { id: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`/api/deployments/${id}/logs?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [id]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className="min-w-0">
<CardHeader>
<CardTitle>Log</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
const [answer, setAnswer] = useState("");
const [busy, setBusy] = useState(false);
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
const [error, setError] = useState<string | null>(null);
async function send() {
setBusy(true);
setAnswer("");
setError(null);
setStats(null);
const t0 = performance.now();
let first: number | null = null;
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
let chunks = 0;
try {
const res = await fetch(`/api/deployments/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
});
if (!res.ok || !res.body) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const j = JSON.parse(data);
if (j.usage) usage = j.usage;
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
if (delta) {
first ??= performance.now();
chunks++;
setAnswer((a) => a + delta);
}
}
}
const total = (performance.now() - t0) / 1000;
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle>Try it</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
disabled={!running}
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
/>
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
<SendIcon />
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
</Button>
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
{stats && (
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div>
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
<div className="text-muted-foreground">first token</div>
</div>
<div>
<div className="font-semibold tabular-nums">
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
</div>
<div className="text-muted-foreground">generation</div>
</div>
<div>
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,26 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentForm } from "../../deployment-form";
import { formData } from "../../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Edit deployment" };
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
const { id } = await params;
const [d, data] = await Promise.all([getDeployment(id), formData()]);
if (!d) notFound();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
{d.state !== "stopped" && d.state !== "failed" && (
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
)}
<DeploymentForm
{...data}
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
/>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
const d = await getDeployment((await params).id);
return { title: d ? d.name : "Deployment" };
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const d = await getDeployment((await params).id);
if (!d) notFound();
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} />;
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string): Promise<boolean> {
const res = await fetch(url, { method });
if (res.ok) return true;
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
@@ -0,0 +1,520 @@
"use client";
import { BoxesIcon, CheckIcon, CpuIcon, SearchIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
import { buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
export type FormRuntime = {
id: string;
name: string;
engine: RuntimeEngine;
image: string;
imageState: string;
env: Record<string, string>;
extraArgs: string[];
};
export type FormModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
export type FormHost = { cpus: number | null; memoryBytes: number | null; cpuFeatures: string[] } | null;
export type FormInitial = {
id?: string;
name: string;
runtimeId: string;
modelId: string;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
hostPort: number | null;
};
const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
const KV_TYPES = ["f16", "q8_0", "q4_0"];
const selectClass =
"h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
function Section({ step, title, description, children }: { step: number; title: string; description?: string; children: React.ReactNode }) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-primary text-xs text-primary-foreground">{step}</span>
{title}
</CardTitle>
{description && <CardDescription>{description}</CardDescription>}
</CardHeader>
<CardContent className="flex flex-col gap-4">{children}</CardContent>
</Card>
);
}
function Field({ label, hint, children, htmlFor }: { label: string; hint?: React.ReactNode; children: React.ReactNode; htmlFor?: string }) {
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={htmlFor}>{label}</Label>
{children}
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
);
}
/** Pick runtime → model and files → launch options. Used for "New deployment" and "Edit". */
export function DeploymentForm({
runtimes,
models,
host,
initial,
}: {
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
initial?: FormInitial;
}) {
const router = useRouter();
const editing = !!initial?.id;
const [runtimeId, setRuntimeId] = useState(initial?.runtimeId ?? runtimes.find((r) => r.imageState === "present")?.id ?? "");
const runtime = runtimes.find((r) => r.id === runtimeId) ?? null;
const engine = runtime?.engine ?? "llama.cpp";
const [query, setQuery] = useState("");
const [modelId, setModelId] = useState(initial?.modelId ?? "");
const servable = models.filter((m) => (engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm));
const shown = servable.filter((m) => m.repoId.toLowerCase().includes(query.trim().toLowerCase()));
const model = servable.find((m) => m.id === modelId) ?? null;
const o = initial?.options;
const [modelFile, setModelFile] = useState(o?.modelFile ?? "");
const [mmproj, setMmproj] = useState(o?.mmproj ?? "");
const [draftFile, setDraftFile] = useState(o?.draftFile ?? "");
const [name, setName] = useState(initial?.name ?? "");
const [contextSize, setContextSize] = useState(String(o?.contextSize ?? 4096));
const [threads, setThreads] = useState(o?.threads != null ? String(o.threads) : "");
const [parallel, setParallel] = useState(o?.parallel != null ? String(o.parallel) : "1");
const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? "");
const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
const [batchSize, setBatchSize] = useState(o?.batchSize != null ? String(o.batchSize) : "");
const [ubatchSize, setUbatchSize] = useState(o?.ubatchSize != null ? String(o.ubatchSize) : "");
const [dtype, setDtype] = useState(o?.dtype ?? "");
const [maxNumSeqs, setMaxNumSeqs] = useState(o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "");
const [kvCacheGb, setKvCacheGb] = useState(o?.kvCacheGb != null ? String(o.kvCacheGb) : "");
const [extraArgs, setExtraArgs] = useState((o?.extraArgs ?? []).join("\n"));
const [cpus, setCpus] = useState(initial?.cpus != null ? String(initial.cpus) : "");
const [memoryMb, setMemoryMb] = useState(initial?.memoryMb != null ? String(initial.memoryMb) : "");
const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
const [hostPort, setHostPort] = useState(initial?.hostPort != null ? String(initial.hostPort) : "");
const [saving, setSaving] = useState(false);
function pickModel(m: FormModel) {
setModelId(m.id);
const first = m.candidates.gguf[0];
setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : "");
setMmproj(m.candidates.mmproj[0]?.path ?? "");
setDraftFile("");
if (!editing) setName(`${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim());
}
const options: DeploymentOptions = {
modelFile: engine === "llama.cpp" ? modelFile : "",
mmproj: engine === "llama.cpp" && mmproj ? mmproj : null,
draftFile: engine === "llama.cpp" && draftFile ? draftFile : null,
draftType: model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
contextSize: intOrNull(contextSize) ?? 4096,
threads: intOrNull(threads),
parallel: intOrNull(parallel),
batchSize: engine === "llama.cpp" ? intOrNull(batchSize) : null,
ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null,
cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null,
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
extraArgs: extraArgs
.split("\n")
.map((a) => a.trim())
.filter(Boolean),
};
const fileBytes = model
? engine === "llama.cpp"
? (model.candidates.gguf.find((g) => g.path === modelFile)?.size ?? 0) +
(model.candidates.mmproj.find((g) => g.path === mmproj)?.size ?? 0) +
(model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0)
: (model.candidates.vllm?.size ?? 0)
: 0;
const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, options.kvCacheGb) : null;
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
runtime && model ? renderCommand(runtime.image, buildCommand({ engine, options, model, runtime: { env: runtime.env, extraArgs: runtime.extraArgs } })) : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
if (!runtime || !model) return;
setSaving(true);
try {
const body = {
name: name.trim() || model.repoId,
runtimeId: runtime.id,
modelId: model.id,
options,
cpus: numOrNull(cpus),
memoryMb: memory,
hostPort: intOrNull(hostPort),
start,
};
const res = await fetch(editing ? `/api/deployments/${initial!.id}` : "/api/deployments", {
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
return;
}
const id = editing ? initial!.id : json.id;
if (editing && start) await fetch(`/api/deployments/${id}/start`, { method: "POST" });
toast.success(start ? "Deployment starting" : "Deployment saved");
router.push(`/deployments/${id}`);
router.refresh();
} finally {
setSaving(false);
}
}
return (
<div className="flex flex-col gap-4">
<Section step={1} title="Runtime" description="The container image that serves the model.">
{runtimes.length === 0 ? (
<p className="text-sm text-muted-foreground">
No runtimes yet.{" "}
<Link href="/settings/runtimes" className="underline">
Add one in Settings
</Link>
.
</p>
) : (
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{runtimes.map((r) => {
const ready = r.imageState === "present";
return (
<button
key={r.id}
type="button"
disabled={!ready}
onClick={() => {
setRuntimeId(r.id);
if (r.engine !== engine) setModelId("");
}}
className={cn(
"flex flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50",
runtimeId === r.id ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/50",
)}
>
<span className="flex w-full items-center justify-between gap-2 text-sm font-medium">
<span className="flex items-center gap-1.5">
<BoxesIcon className="size-4 text-muted-foreground" />
{r.name}
</span>
{runtimeId === r.id && <CheckIcon className="size-4 text-primary" />}
</span>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
<span className="text-xs text-muted-foreground">
{r.engine === "vllm" ? "vLLM · safetensors" : "llama.cpp · GGUF"}
{!ready && " · image not pulled"}
</span>
</button>
);
})}
</div>
)}
{runtimes.some((r) => r.imageState !== "present") && (
<p className="text-xs text-muted-foreground">
Runtimes whose image isn&apos;t pulled yet can&apos;t be picked.{" "}
<Link href="/settings/runtimes" className="underline">
Pull them in Settings
</Link>
.
</p>
)}
</Section>
{runtime && (
<Section
step={2}
title="Model"
description={engine === "llama.cpp" ? "Downloaded GGUF models. Pick the quant and optional extras." : "Downloaded safetensors repos (with config.json)."}
>
{servable.length === 0 ? (
<p className="text-sm text-muted-foreground">
No downloaded model fits this runtime.{" "}
<Link href="/" className="underline">
Add one in the library
</Link>
{engine === "vllm" ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)." : "."}
</p>
) : (
<>
{servable.length > 6 && (
<div className="relative">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search models…" className="pl-8" />
</div>
)}
<div className="flex max-h-72 flex-col divide-y overflow-y-auto rounded-lg ring-1 ring-foreground/10">
{shown.map((m) => (
<button
key={m.id}
type="button"
onClick={() => pickModel(m)}
className={cn("flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50", modelId === m.id && "bg-primary/5")}
>
<span className="flex min-w-0 items-center gap-2">
{modelId === m.id ? <CheckIcon className="size-4 shrink-0 text-primary" /> : <span className="size-4 shrink-0" />}
<span className="truncate">{m.repoId}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{engine === "llama.cpp"
? `${m.candidates.gguf.length} GGUF${m.candidates.mmproj.length ? " · vision" : ""}${m.candidates.drafts.length ? " · MTP/draft" : ""}`
: formatBytes(m.candidates.vllm?.size ?? 0)}
</span>
</button>
))}
</div>
{model && engine === "llama.cpp" && (
<div className="grid gap-4 md:grid-cols-3">
<Field label="Model file">
<div className="flex flex-col gap-1">
{model.candidates.gguf.map((g) => (
<label key={g.path} className={cn("flex cursor-pointer items-center gap-2 rounded-md border px-2 py-1.5 text-xs", modelFile === g.path && "border-primary bg-primary/5")}>
<input type="radio" name="modelFile" checked={modelFile === g.path} onChange={() => setModelFile(g.path)} className="accent-primary" />
<span className="min-w-0 flex-1 truncate font-mono" title={g.path}>
{quantGroup(g.path) ?? g.path}
</span>
<span className="text-muted-foreground tabular-nums">{formatBytes(g.size)}</span>
</label>
))}
</div>
</Field>
<Field label="Vision (mmproj)" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<select value={mmproj} onChange={(e) => setMmproj(e.target.value)} className={selectClass} disabled={model.candidates.mmproj.length === 0}>
<option value="">None</option>
{model.candidates.mmproj.map((m) => (
<option key={m.path} value={m.path}>
{m.path} ({formatBytes(m.size)})
</option>
))}
</select>
</Field>
<Field
label="Speculative decoding"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "MTP heads use --spec-type draft-mtp."}
>
<select value={draftFile} onChange={(e) => setDraftFile(e.target.value)} className={selectClass} disabled={model.candidates.drafts.length === 0}>
<option value="">Off</option>
{model.candidates.drafts.map((d) => (
<option key={d.path} value={d.path}>
{d.type === "draft-mtp" ? "MTP: " : "Draft: "}
{d.path} ({formatBytes(d.size)})
</option>
))}
</select>
</Field>
</div>
)}
{model && (
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{[modelFile, mmproj, draftFile].filter(Boolean).map((p) => (
<span key={p} className="flex items-center gap-1">
<FileRoleBadge path={p} />
</span>
))}
<span>{formatBytes(fileBytes)} of model files</span>
</div>
)}
</>
)}
</Section>
)}
{runtime && model && (
<Section step={3} title="Launch options" description="Empty fields use the engine's defaults.">
<div className="grid gap-4 md:grid-cols-3">
<Field label="Name" htmlFor="d-name">
<Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} />
</Field>
<Field label="Context size (tokens)" htmlFor="d-ctx" hint={engine === "vllm" ? "--max-model-len" : "-c"}>
<div className="flex gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-24" />
<div className="flex flex-wrap gap-1">
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c >= 1024 ? `${c / 1024}k` : c}
</Button>
))}
</div>
</div>
</Field>
<Field
label={engine === "vllm" ? "Max concurrent sequences" : "Parallel slots"}
htmlFor="d-par"
hint={engine === "vllm" ? "--max-num-seqs" : "-np; the context is shared between slots"}
>
{engine === "vllm" ? (
<Input id="d-par" value={maxNumSeqs} onChange={(e) => setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
) : (
<Input id="d-par" value={parallel} onChange={(e) => setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
)}
</Field>
</div>
{engine === "llama.cpp" ? (
<div className="grid gap-4 md:grid-cols-4">
<Field label="Threads" htmlFor="d-thr" hint={host?.cpus ? `-t / -tb; host has ${host.cpus}` : "-t / -tb"}>
<Input id="d-thr" value={threads} onChange={(e) => setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
<Field label="KV cache K / V" hint="-ctk / -ctv; q8_0 halves the KV memory">
<div className="flex gap-1.5">
{[
[cacheTypeK, setCacheTypeK],
[cacheTypeV, setCacheTypeV],
].map(([value, set], i) => (
<select key={i} value={value as string} onChange={(e) => (set as (v: string) => void)(e.target.value)} className={selectClass}>
<option value="">default</option>
{KV_TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
))}
</div>
</Field>
<Field label="Flash attention" hint="-fa">
<select value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)} className={selectClass}>
<option value="">default (auto)</option>
<option value="on">on</option>
<option value="off">off</option>
</select>
</Field>
<Field label="Batch / micro-batch" hint="-b / -ub">
<div className="flex gap-1.5">
<Input value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" aria-label="Batch size" />
<Input value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" aria-label="Micro-batch size" />
</div>
</Field>
</div>
) : (
<div className="grid gap-4 md:grid-cols-3">
<Field
label="Data type"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster than bfloat16." : "--dtype; overrides the runtime's default"}
>
<select value={dtype} onChange={(e) => setDtype(e.target.value)} className={selectClass}>
<option value="">runtime default</option>
<option value="bfloat16">bfloat16</option>
<option value="float32">float32</option>
<option value="float16">float16</option>
<option value="auto">auto</option>
</select>
</Field>
<Field label="KV cache (GiB)" htmlFor="d-kv" hint="VLLM_CPU_KVCACHE_SPACE">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
<Field label="Threads" hint="vLLM binds OpenMP threads itself (VLLM_CPU_OMP_THREADS_BIND); limit CPUs below instead.">
<Input value="auto" disabled />
</Field>
</div>
)}
<div className="grid gap-4 md:grid-cols-3">
<Field label="CPU limit (cores)" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus})` : "Empty: no limit"}>
<Input id="d-cpus" value={cpus} onChange={(e) => setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
</Field>
<Field
label="Memory limit (MiB)"
htmlFor="d-mem"
hint={
<>
Estimate: {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
{host?.memoryBytes ? ` · host: ${formatBytes(host.memoryBytes)}` : ""}
{memoryTouched && (
<button type="button" className="ml-1 underline" onClick={() => setMemoryTouched(false)}>
use estimate
</button>
)}
</>
}
>
<Input
id="d-mem"
value={memoryTouched ? memoryMb : String(estimate ?? "")}
onChange={(e) => {
setMemoryTouched(true);
setMemoryMb(e.target.value.replace(/\D/g, ""));
}}
inputMode="numeric"
/>
</Field>
<Field label="Publish on host port" htmlFor="d-port" hint={`Optional: reach the API at http://<server>:<port>/v1 (container port ${ENGINE_PORT[engine]}).`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
</div>
<Field label="Extra arguments" htmlFor="d-args" hint="One per line, appended after the runtime's own extra arguments.">
<textarea
id="d-args"
value={extraArgs}
onChange={(e) => setExtraArgs(e.target.value)}
spellCheck={false}
className="min-h-16 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"
placeholder={engine === "vllm" ? "--enforce-eager" : "--temp\n0.7"}
/>
</Field>
{preview && (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<Label className="flex items-center gap-1.5">
<CpuIcon className="size-4 text-muted-foreground" />
Command
</Label>
<CopyButton value={preview} label="Copy command" />
</div>
<pre className="overflow-x-auto rounded-lg bg-muted/60 px-3 py-2 font-mono text-xs whitespace-pre-wrap break-all">{preview}</pre>
</div>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => router.back()}>
Cancel
</Button>
<Button type="button" variant="outline" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(false)}>
{editing ? "Save" : "Create"}
</Button>
<Button type="button" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(true)}>
{editing ? "Save & start" : "Create & start"}
</Button>
</div>
</Section>
)}
</div>
);
}
@@ -0,0 +1,97 @@
"use client";
import { PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { startDeployment, stopDeployment } from "./actions";
type Row = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
const isActive = (r: Row) => r.desiredState === "running" || r.state === "starting" || r.state === "running" || r.state === "stopping";
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
async function reload() {
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(() => null);
if (res?.ok) setRows(await res.json());
}
useEffect(() => {
const t = setInterval(reload, busy ? 2_000 : 5_000);
return () => clearInterval(t);
}, [busy]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<RocketIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">No deployments yet. Pick a runtime and a downloaded model to start one.</p>
<Link href="/deployments/new" className="text-sm underline">
New deployment
</Link>
</Card>
);
}
return (
<div className="grid gap-3 md:grid-cols-2">
{rows.map((r) => {
const file = r.options.modelFile ? (quantGroup(r.options.modelFile) ?? r.options.modelFile) : null;
const loadSecs = r.readyAt && r.startedAt ? (new Date(r.readyAt).getTime() - new Date(r.startedAt).getTime()) / 1000 : null;
return (
<Card key={r.id} className="gap-3 px-4 py-3">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-0.5">
<Link href={`/deployments/${r.id}`} className="truncate font-medium hover:underline">
{r.name}
</Link>
<span className="truncate text-xs text-muted-foreground">
{r.repoId}
{file && ` · ${file}`}
{r.options.mmproj && " · vision"}
{r.options.draftFile && " · MTP/draft"}
</span>
<span className="text-xs text-muted-foreground">{r.runtimeName}</span>
</div>
<DeploymentStateBadge state={r.state} desiredState={r.desiredState} />
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="tabular-nums">
{r.state === "running" && r.stats
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
: r.state === "failed"
? (r.error?.split("\n")[0] ?? "failed")
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
{r.state === "running" && loadSecs != null && ` · loaded in ${loadSecs.toFixed(1)} s`}
</span>
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
</div>
</Card>
);
})}
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import "server-only";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost }> {
const [runtimes, models, docker] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
};
}
+16
View File
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
export default async function NewDeploymentPage() {
const data = await formData();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { listDeployments } from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { DeploymentList } from "./deployment-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Deployments" };
export default async function DeploymentsPage() {
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Deployments</h1>
<Link href="/deployments/new" className={buttonVariants()}>
New deployment
</Link>
</div>
{!docker?.connected && (
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
<Link href="/settings/runtimes" className="underline">
Settings → Runtimes
</Link>
.
</p>
)}
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
@@ -0,0 +1,41 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
const Body = z.object({
messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100),
maxTokens: z.number().int().min(1).max(8192).default(256),
});
/**
* Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and
* streams the server-sent events back unchanged.
*/
export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (req, { params }) => {
try {
const d = await getDeployment((await params).id);
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`);
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listDeploymentLogs } from "@/lib/deployments";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/deployments/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listDeploymentLogs((await params).id, after));
});
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentBody, DeploymentError, getDeployment, requestDelete, updateDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
const d = await getDeployment((await params).id);
return d ? NextResponse.json(d) : apiError(404, "not_found", "Deployment not found.");
});
export const PUT = withAuth<RouteContext<"/api/deployments/[id]">>(async (req, { params }) => {
try {
await updateDeployment((await params).id, DeploymentBody.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Stop the container (if running) and delete the deployment. */
export const DELETE = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
try {
await requestDelete((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/start">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "running");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/stop">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "stopped");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createDeployment, DeploymentBody, DeploymentError, listDeployments } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listDeployments()));
/** Create a deployment; `start: true` starts it right away. */
export const POST = withAuth(async (req) => {
try {
const body = DeploymentBody.extend({ start: z.boolean().default(true) }).parse(await req.json());
return NextResponse.json(await createDeployment(body, body.start), { status: 201 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+9 -3
View File
@@ -1,12 +1,18 @@
"use client";
import { LibraryIcon, SettingsIcon } from "lucide-react";
import { LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
const LINKS = [
{ href: "/", label: "Library", icon: LibraryIcon, active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/jobs/") },
{
href: "/",
label: "Library",
icon: LibraryIcon,
active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/deployments"),
},
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
@@ -16,7 +22,7 @@ export function AppNav() {
return (
<nav className="flex items-center gap-1 text-sm">
{LINKS.map((l) => {
const active = l.active(pathname) || (l.href === "/" && pathname.startsWith("/jobs/"));
const active = l.active(pathname);
return (
<Link
key={l.href}
+23
View File
@@ -0,0 +1,23 @@
import { LoaderCircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const STYLE: Record<string, { label: string; className: string }> = {
stopped: { label: "stopped", className: "border-foreground/15 text-muted-foreground" },
starting: { label: "starting", className: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300" },
running: { label: "running", className: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" },
stopping: { label: "stopping", className: "border-foreground/15 text-muted-foreground" },
failed: { label: "failed", className: "border-destructive/30 bg-destructive/10 text-destructive" },
};
/** Deployment state; shows "starting" as soon as a start was requested. */
export function DeploymentStateBadge({ state, desiredState, className }: { state: string; desiredState: string; className?: string }) {
const effective = desiredState === "running" && (state === "stopped" || state === "failed") ? "starting" : desiredState === "stopped" && (state === "running" || state === "starting") ? "stopping" : state;
const s = STYLE[effective] ?? STYLE.stopped;
return (
<span className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-4xl border px-2 text-xs font-medium whitespace-nowrap", s.className, className)}>
{(effective === "starting" || effective === "stopping") && <LoaderCircleIcon className="size-3 animate-spin" />}
{effective === "running" && <span className="size-1.5 rounded-full bg-emerald-500" />}
{s.label}
</span>
);
}
+86
View File
@@ -3,6 +3,7 @@ import {
index,
integer,
primaryKey,
real,
sqliteTable,
text,
uniqueIndex,
@@ -422,3 +423,88 @@ export const localFolders = sqliteTable("local_folders", {
commit: text("commit"),
scannedAt: ts("scanned_at").notNull(),
});
// ---------------------------------------------------------------------------
// Deployments: a model served by a runtime container
// ---------------------------------------------------------------------------
/** What the worker is doing with the container. */
export const DEPLOYMENT_STATES = ["stopped", "starting", "running", "stopping", "failed"] as const;
export type DeploymentState = (typeof DEPLOYMENT_STATES)[number];
/** Launch options. Engine-specific fields are ignored by the other engine. */
export type DeploymentOptions = {
/** Model file (llama.cpp: the GGUF, first part of a split) or "" for the repo folder (vLLM). */
modelFile: string;
/** llama.cpp: multimodal projector. */
mmproj?: string | null;
/** llama.cpp: draft model (MTP head or a small draft model) for speculative decoding. */
draftFile?: string | null;
draftType?: "draft-mtp" | "draft-simple" | null;
contextSize: number;
threads?: number | null;
batchSize?: number | null;
ubatchSize?: number | null;
parallel?: number | null;
cacheTypeK?: string | null;
cacheTypeV?: string | null;
flashAttn?: "auto" | "on" | "off" | null;
/** vLLM */
dtype?: string | null;
maxNumSeqs?: number | null;
kvCacheGb?: number | null;
extraArgs: string[];
};
export type DeploymentStats = { cpuPercent: number; memoryBytes: number; memoryLimitBytes: number; at: string };
export const deployments = sqliteTable("deployments", {
id: id(),
name: text("name").notNull(),
runtimeId: text("runtime_id")
.notNull()
.references(() => runtimes.id),
modelId: text("model_id")
.notNull()
.references(() => models.id),
options: text("options", { mode: "json" }).$type<DeploymentOptions>().notNull(),
/** CPU limit in cores (fractions allowed) and memory limit; null = no limit. */
cpus: real("cpus"),
memoryMb: integer("memory_mb"),
/** Publish the API on this host port (optional; Kaname itself uses the Docker network). */
hostPort: integer("host_port"),
/** Set by the web app; the worker starts/stops the container to match. */
desiredState: text("desired_state", { enum: ["running", "stopped"] }).notNull().default("stopped"),
state: text("state", { enum: DEPLOYMENT_STATES }).notNull().default("stopped"),
/** Delete requested: the worker removes the container, then the row. */
deleteRequestedAt: ts("delete_requested_at"),
containerId: text("container_id"),
containerName: text("container_name"),
/** Command line the container was started with (for display and reproducibility). */
command: text("command", { mode: "json" }).$type<string[]>(),
imageId: text("image_id"),
startedAt: ts("started_at"),
readyAt: ts("ready_at"),
stoppedAt: ts("stopped_at"),
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
export const deploymentLogs = sqliteTable(
"deployment_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
deploymentId: text("deployment_id")
.notNull()
.references(() => deployments.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
);
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { modelCandidates, servableBy } from "./deploy-candidates";
const f = (path: string, size = 10) => ({ path, size });
describe("modelCandidates", () => {
it("lists GGUF weights (split as first part), mmproj and MTP/draft files", () => {
const c = modelCandidates([
f("Qwen3.8-27B-UD-Q4_K_XL.gguf"),
f("BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf"),
f("BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf"),
f("mmproj-F16.gguf"),
f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"),
f("imatrix_unsloth.gguf"),
f("config.json"),
]);
assert.deepEqual(
c.gguf.map((g) => [g.path, g.parts]),
[
["Qwen3.8-27B-UD-Q4_K_XL.gguf", 1],
["BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", 2],
],
);
assert.deepEqual(c.mmproj.map((m) => m.path), ["mmproj-F16.gguf"]);
assert.deepEqual(c.drafts.map((d) => [d.path, d.type]), [["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "draft-mtp"]]);
assert.equal(c.vllm, null);
assert.ok(servableBy(c, "llama.cpp") && !servableBy(c, "vllm"));
});
it("recognizes a safetensors repo for vLLM", () => {
const c = modelCandidates([f("config.json", 1), f("model.safetensors", 100), f("tokenizer.json", 5)]);
assert.deepEqual(c.vllm, { size: 106 });
assert.equal(c.gguf.length, 0);
});
});
+41
View File
@@ -0,0 +1,41 @@
// Which downloaded files a runtime can serve. Pure; shared by the server and the deployment form.
import type { RuntimeEngine } from "@/lib/db/schema";
import { groupSplitFiles } from "@/lib/file-groups";
import { fileRole } from "@/lib/file-roles";
export type LocalFile = { path: string; size: number };
export type CandidateFile = { path: string; size: number; parts: number };
export type DraftFile = CandidateFile & { type: "draft-mtp" | "draft-simple" };
export type ModelCandidates = {
/** llama.cpp: loadable GGUF weights (split files as their first part), plus optional extras. */
gguf: CandidateFile[];
mmproj: CandidateFile[];
drafts: DraftFile[];
/** vLLM: the repo folder has a config.json and safetensors weights. */
vllm: { size: number } | null;
};
const isGguf = (p: string) => p.toLowerCase().endsWith(".gguf");
/** `files`: the model's files that are on disk (present or verified). */
export function modelCandidates(files: LocalFile[]): ModelCandidates {
const entries = (pred: (p: string) => boolean) =>
groupSplitFiles(files.filter((f) => pred(f.path))).map((g) => ({ path: g.parts[0].path, size: g.size, parts: g.totalParts }));
const gguf = entries((p) => isGguf(p) && fileRole(p) === "model");
const mmproj = entries((p) => isGguf(p) && fileRole(p) === "vision");
const drafts: DraftFile[] = [
...entries((p) => isGguf(p) && fileRole(p) === "mtp").map((f) => ({ ...f, type: "draft-mtp" as const })),
...entries((p) => isGguf(p) && fileRole(p) === "draft").map((f) => ({ ...f, type: "draft-simple" as const })),
];
const hasConfig = files.some((f) => f.path === "config.json");
const safetensors = files.filter((f) => f.path.endsWith(".safetensors") && fileRole(f.path) === "model");
const vllm = hasConfig && safetensors.length > 0 ? { size: files.reduce((s, f) => s + f.size, 0) } : null;
return { gguf, mmproj, drafts, vllm };
}
export function servableBy(c: ModelCandidates, engine: RuntimeEngine): boolean {
return engine === "llama.cpp" ? c.gguf.length > 0 : c.vllm !== null;
}
+49
View File
@@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { buildCommand, renderCommand } from "./deploy-command";
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
describe("buildCommand", () => {
it("builds llama-server arguments with mmproj and MTP draft", () => {
const cmd = buildCommand({
engine: "llama.cpp",
model,
runtime: { env: {}, extraArgs: ["--jinja"] },
options: {
modelFile: "Qwen3-0.6B-Q4_K_M.gguf",
mmproj: "mmproj-F16.gguf",
draftFile: "MTP/mtp-Q4_0.gguf",
draftType: "draft-mtp",
contextSize: 4096,
threads: 8,
parallel: 1,
cacheTypeK: "q8_0",
extraArgs: ["--temp", "0.7"],
},
});
assert.equal(cmd.port, 8080);
assert.deepEqual(cmd.args.slice(0, 2), ["-m", "/models/unsloth/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q4_K_M.gguf"]);
const s = cmd.args.join(" ");
assert.match(s, /-c 4096 -t 8 -tb 8 -np 1 -ctk q8_0/);
assert.match(s, /--mmproj \/models\/unsloth\/Qwen3-0\.6B-GGUF\/mmproj-F16\.gguf/);
assert.match(s, /-md \/models\/unsloth\/Qwen3-0\.6B-GGUF\/MTP\/mtp-Q4_0\.gguf --spec-type draft-mtp/);
assert.ok(s.endsWith("--metrics --jinja --temp 0.7"));
assert.ok(!s.includes("-b "), "unset options are left out");
});
it("builds vllm serve arguments; deployment dtype and KV cache override the runtime", () => {
const cmd = buildCommand({
engine: "vllm",
model: { repoId: "HuggingFaceTB/SmolLM2-135M-Instruct", localPath: "HuggingFaceTB/SmolLM2-135M-Instruct" },
runtime: { env: { VLLM_CPU_KVCACHE_SPACE: "4" }, extraArgs: ["--dtype=bfloat16"] },
options: { modelFile: "", contextSize: 2048, maxNumSeqs: 4, dtype: "float32", kvCacheGb: 2, extraArgs: [] },
});
assert.equal(cmd.port, 8000);
assert.equal(cmd.args[0], "/models/HuggingFaceTB/SmolLM2-135M-Instruct");
assert.equal(cmd.env.VLLM_CPU_KVCACHE_SPACE, "2");
const s = cmd.args.join(" ");
assert.ok(s.indexOf("--dtype=bfloat16") < s.indexOf("--dtype float32"));
assert.match(renderCommand("vllm/vllm-openai-cpu:v0.31.0", cmd), /^docker run -e VLLM_CPU_KVCACHE_SPACE=2 /);
});
});
+93
View File
@@ -0,0 +1,93 @@
// Container command lines for deployments, per engine type. Pure: used by the worker to start
// containers and by the UI for the live preview. Flags verified against llama.cpp build 11429
// (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`).
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
/** Where the models folder is mounted inside every runtime container (read-only). */
export const CONTAINER_MODELS_DIR = "/models";
export const ENGINE_PORT: Record<RuntimeEngine, number> = { "llama.cpp": 8080, vllm: 8000 };
export type CommandInput = {
engine: RuntimeEngine;
options: DeploymentOptions;
model: { repoId: string; localPath: string };
runtime: { env: Record<string, string>; extraArgs: string[] };
};
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
const inModels = (localPath: string, file?: string | null) =>
[CONTAINER_MODELS_DIR, localPath, file].filter(Boolean).join("/").replace(/\/+/g, "/");
const num = (flag: string, v: number | null | undefined) => (v != null && Number.isFinite(v) ? [flag, String(v)] : []);
const str = (flag: string, v: string | null | undefined) => (v ? [flag, v] : []);
export function buildCommand({ engine, options: o, model, runtime }: CommandInput): ContainerCommand {
const port = ENGINE_PORT[engine];
if (engine === "llama.cpp") {
// The image's entrypoint is llama-server, so these are its arguments.
const args = [
"-m",
inModels(model.localPath, o.modelFile),
"--host",
"0.0.0.0",
"--port",
String(port),
"-a",
model.repoId,
...num("-c", o.contextSize),
...num("-t", o.threads),
...num("-tb", o.threads),
...num("-b", o.batchSize),
...num("-ub", o.ubatchSize),
...num("-np", o.parallel),
...str("-ctk", o.cacheTypeK),
...str("-ctv", o.cacheTypeV),
...str("-fa", o.flashAttn),
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
"--metrics",
...runtime.extraArgs,
...o.extraArgs,
];
return { args, env: { ...runtime.env }, port };
}
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
const env = { ...runtime.env };
if (o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
const args = [
inModels(model.localPath, o.modelFile || null),
"--host",
"0.0.0.0",
"--port",
String(port),
"--served-model-name",
model.repoId,
...num("--max-model-len", o.contextSize),
...num("--max-num-seqs", o.maxNumSeqs),
...runtime.extraArgs,
// After the runtime's defaults, so a deployment's dtype wins (argparse keeps the last value).
...str("--dtype", o.dtype),
...o.extraArgs,
];
return { args, env, port };
}
/** Shell-style rendering for display ("docker run … image args"). */
export function renderCommand(image: string, cmd: ContainerCommand): string {
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
const env = Object.entries(cmd.env).map(([k, v]) => `-e ${q(`${k}=${v}`)}`);
return ["docker run", ...env, `-v <models>:${CONTAINER_MODELS_DIR}:ro`, q(image), ...cmd.args.map(q)].join(" ");
}
/** Rough memory need: model files plus KV cache and runtime overhead. */
export function estimateMemoryMb(fileBytes: number, contextSize: number, engine: RuntimeEngine, kvCacheGb?: number | null): number {
const model = fileBytes / 2 ** 20;
if (engine === "vllm") return Math.ceil(model + (kvCacheGb ?? 4) * 1024 + 2048);
// llama.cpp: ~ctx/8 MiB of f16 KV cache per 4k tokens for small models is too model-specific to
// compute without the GGUF header; a margin that scales with context is a safe default.
return Math.ceil(model * 1.1 + 512 + contextSize / 16);
}
+237
View File
@@ -0,0 +1,237 @@
import "server-only";
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
export class DeploymentError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
message: string,
public status: number,
) {
super(message);
}
}
const int = (min: number, max: number) => z.number().int().min(min).max(max);
export const DeploymentBody = z.object({
name: z.string().trim().min(1).max(80),
runtimeId: z.string().min(1),
modelId: z.string().min(1),
options: z.object({
modelFile: z.string().max(1024),
mmproj: z.string().max(1024).nullable().optional(),
draftFile: z.string().max(1024).nullable().optional(),
draftType: z.enum(["draft-mtp", "draft-simple"]).nullable().optional(),
contextSize: int(128, 1_048_576),
threads: int(1, 1024).nullable().optional(),
batchSize: int(1, 65_536).nullable().optional(),
ubatchSize: int(1, 65_536).nullable().optional(),
parallel: int(1, 256).nullable().optional(),
cacheTypeK: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
maxNumSeqs: int(1, 1024).nullable().optional(),
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
extraArgs: z.array(z.string().max(4000).refine((a) => !/[\r\n\0]/.test(a), "single line")).max(100),
}),
cpus: z.number().min(0.1).max(1024).nullable().optional(),
memoryMb: int(256, 4_194_304).nullable().optional(),
hostPort: int(1024, 65_535).nullable().optional(),
});
export type DeploymentInput = z.infer<typeof DeploymentBody>;
/** Downloaded files of a model (selected and on disk). */
async function localFiles(modelId: string) {
return db()
.select({ path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
}
export type DeployableModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
/** Library models with something a runtime can serve. */
export async function listDeployableModels(): Promise<DeployableModel[]> {
const rows = await db().select({ id: models.id, repoId: models.repoId, localPath: models.localPath }).from(models).orderBy(asc(models.repoId));
const files = await db()
.select({ modelId: modelFiles.modelId, path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
const byModel = new Map<string, { path: string; size: number }[]>();
for (const f of files) byModel.set(f.modelId, [...(byModel.get(f.modelId) ?? []), f]);
return rows
.map((m) => ({ ...m, candidates: modelCandidates(byModel.get(m.id) ?? []) }))
.filter((m) => m.candidates.gguf.length > 0 || m.candidates.vllm);
}
/** Check that runtime, model and files fit together; returns normalized options. */
async function validate(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
const runtime = await db().query.runtimes.findFirst({ where: eq(runtimes.id, input.runtimeId) });
if (!runtime) throw new DeploymentError("invalid", "Runtime not found.", 400);
const model = await db().query.models.findFirst({ where: eq(models.id, input.modelId) });
if (!model) throw new DeploymentError("invalid", "Model not found.", 400);
const c = modelCandidates(await localFiles(model.id));
if (!servableBy(c, runtime.engine)) {
throw new DeploymentError("invalid", `${model.repoId} has no downloaded files ${runtime.name} can serve.`, 400);
}
const o = input.options;
const options: DeploymentOptions = { ...o, extraArgs: o.extraArgs.map((a) => a.trim()).filter(Boolean) };
if (runtime.engine === "llama.cpp") {
if (!c.gguf.some((g) => g.path === o.modelFile)) throw new DeploymentError("invalid", "Pick one of the model's downloaded GGUF files.", 400);
if (o.mmproj && !c.mmproj.some((m) => m.path === o.mmproj)) throw new DeploymentError("invalid", "Unknown mmproj file.", 400);
const draft = o.draftFile ? c.drafts.find((d) => d.path === o.draftFile) : null;
if (o.draftFile && !draft) throw new DeploymentError("invalid", "Unknown draft/MTP file.", 400);
options.draftType = draft?.type ?? null;
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null });
} else {
Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null });
}
if (input.hostPort) {
const clash = await db().query.deployments.findFirst({
columns: { name: true },
where: and(eq(deployments.hostPort, input.hostPort), selfId ? ne(deployments.id, selfId) : undefined, isNull(deployments.deleteRequestedAt)),
});
if (clash) throw new DeploymentError("invalid", `Port ${input.hostPort} is already used by "${clash.name}".`, 409);
}
return options;
}
export async function createDeployment(input: DeploymentInput, startNow: boolean) {
const options = await validate(input);
const [row] = await db()
.insert(deployments)
.values({
name: input.name,
runtimeId: input.runtimeId,
modelId: input.modelId,
options,
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
desiredState: startNow ? "running" : "stopped",
})
.returning({ id: deployments.id });
return row;
}
async function get(id: string) {
const d = await db().query.deployments.findFirst({ where: and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)) });
if (!d) throw new DeploymentError("not_found", "Deployment not found.", 404);
return d;
}
/** Change launch options; only while stopped (a running container keeps its command). */
export async function updateDeployment(id: string, input: DeploymentInput) {
const d = await get(id);
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment before changing it.", 409);
const options = await validate(input, id);
await db()
.update(deployments)
.set({
name: input.name,
runtimeId: input.runtimeId,
modelId: input.modelId,
options,
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
})
.where(eq(deployments.id, id));
}
export async function setDesiredState(id: string, desired: "running" | "stopped") {
const d = await get(id);
if (d.desiredState === desired) return;
await db()
.update(deployments)
.set({ desiredState: desired, ...(desired === "running" ? { error: null } : {}) })
.where(eq(deployments.id, id));
}
/** The worker stops the container and deletes the row. */
export async function requestDelete(id: string) {
await get(id);
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
}
const listColumns = {
id: deployments.id,
name: deployments.name,
state: deployments.state,
desiredState: deployments.desiredState,
options: deployments.options,
cpus: deployments.cpus,
memoryMb: deployments.memoryMb,
hostPort: deployments.hostPort,
containerName: deployments.containerName,
command: deployments.command,
startedAt: deployments.startedAt,
readyAt: deployments.readyAt,
stoppedAt: deployments.stoppedAt,
exitCode: deployments.exitCode,
error: deployments.error,
stats: deployments.stats,
createdAt: deployments.createdAt,
runtimeId: deployments.runtimeId,
runtimeName: runtimes.name,
runtimeImage: runtimes.image,
engine: runtimes.engine,
modelId: deployments.modelId,
repoId: models.repoId,
};
export type DeploymentRow = Awaited<ReturnType<typeof listDeployments>>[number];
export async function listDeployments() {
return db()
.select(listColumns)
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(isNull(deployments.deleteRequestedAt))
.orderBy(desc(deployments.createdAt));
}
export async function getDeployment(id: string) {
const [row] = await db()
.select(listColumns)
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)));
return row ?? null;
}
export async function listDeploymentLogs(id: string, afterId: number, tail = 500) {
const rows =
afterId > 0
? await db()
.select()
.from(deploymentLogs)
.where(and(eq(deploymentLogs.deploymentId, id), gt(deploymentLogs.id, afterId)))
.orderBy(asc(deploymentLogs.id))
.limit(2000)
: (
await db().select().from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(tail)
).reverse();
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
}
/** Deployments that use a model or runtime (deleting those is refused while any exist). */
export async function deploymentsUsing(by: { modelId?: string; runtimeId?: string }) {
return db()
.select({ id: deployments.id, name: deployments.name })
.from(deployments)
.where(
and(
isNull(deployments.deleteRequestedAt),
by.modelId ? eq(deployments.modelId, by.modelId) : undefined,
by.runtimeId ? eq(deployments.runtimeId, by.runtimeId) : undefined,
),
);
}
+5
View File
@@ -6,6 +6,7 @@ import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from
import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { deploymentsUsing } from "@/lib/deployments";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
@@ -102,6 +103,10 @@ export async function deleteModel(id: string, options: { deleteFiles: boolean })
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
}
const using = await deploymentsUsing({ modelId: id });
if (using.length > 0) {
throw new ModelError("busy", `Deployments use this model (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
}
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
const neverDownloaded = model.status === "pending" && n === 0;
if (!options.deleteFiles || neverDownloaded) {
+5
View File
@@ -3,6 +3,7 @@ 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 { deploymentsUsing } from "@/lib/deployments";
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
export type Runtime = typeof runtimes.$inferSelect;
@@ -77,6 +78,10 @@ export async function updateRuntime(id: string, input: RuntimeInput): Promise<Ru
export async function deleteRuntime(id: string): Promise<void> {
await getRuntime(id);
const using = await deploymentsUsing({ runtimeId: id });
if (using.length > 0) {
throw new RuntimeError("invalid", `Deployments use this runtime (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
}
await db().delete(runtimes).where(eq(runtimes.id, id));
}
+313
View File
@@ -0,0 +1,313 @@
// Deployments: the worker keeps runtime containers in line with what the web app asked for
// (desiredState), follows their logs, checks health and samples CPU/memory. Containers keep running
// across worker restarts; the worker re-attaches to them.
import { stat } from "node:fs/promises";
import { join } from "node:path";
import { and, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, renderCommand } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { docker } from "./runtimes";
import type { DockerClient } from "./docker/client";
type Deployment = typeof deployments.$inferSelect;
const LABEL = "kaname.deployment";
const STATS_MS = 5_000;
const LOG_FLUSH_MS = 1_000;
const LOG_KEEP = 5_000;
/** Give up on a container that isn't healthy after this long (big models load slowly on CPU). */
const START_TIMEOUT_MS = 30 * 60_000;
/** Leave this much of the host's memory to the system and other containers. */
const MEMORY_RESERVE_MB = 2048;
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
const slug = (s: string) =>
s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 40) || "model";
// --- logs ------------------------------------------------------------------------------------
const followers = new Map<string, AbortController>();
const pending: { deploymentId: string; stream: LogStream; line: string; ts: Date }[] = [];
function addLog(deploymentId: string, stream: LogStream, line: string) {
pending.push({ deploymentId, stream, line: sanitizeLine(line, [coreEnv().HF_TOKEN ?? ""]).slice(0, 4000), ts: new Date() });
}
export async function flushDeploymentLogs(): Promise<void> {
if (pending.length === 0) return;
const batch = pending.splice(0, pending.length);
for (let i = 0; i < batch.length; i += 500) await db().insert(deploymentLogs).values(batch.slice(i, i + 500));
// Keep the newest LOG_KEEP lines per deployment.
for (const id of new Set(batch.map((b) => b.deploymentId))) {
const [cut] = await db()
.select({ id: deploymentLogs.id })
.from(deploymentLogs)
.where(eq(deploymentLogs.deploymentId, id))
.orderBy(desc(deploymentLogs.id))
.limit(1)
.offset(LOG_KEEP);
if (cut) await db().delete(deploymentLogs).where(and(eq(deploymentLogs.deploymentId, id), lt(deploymentLogs.id, cut.id)));
}
}
function follow(c: DockerClient, d: { id: string; containerId: string }, tail = 0) {
followers.get(d.id)?.abort();
const ctl = new AbortController();
followers.set(d.id, ctl);
c.followLogs(d.containerId, (stream, line) => addLog(d.id, stream, line), { tail, signal: ctl.signal })
.catch((err) => !ctl.signal.aborted && log.warn(`logs of deployment ${d.id}: ${message(err)}`))
.finally(() => followers.get(d.id) === ctl && followers.delete(d.id));
}
function unfollow(id: string) {
followers.get(id)?.abort();
followers.delete(id);
}
// --- start / stop ------------------------------------------------------------------------------
async function update(id: string, set: Partial<Deployment>) {
await db().update(deployments).set(set).where(eq(deployments.id, id));
}
async function fail(d: Deployment, error: string, exitCode: number | null = null) {
addLog(d.id, "system", `Failed: ${error}`);
log.warn(`deployment ${d.name}: ${error}`);
// desiredState stopped, so the worker doesn't retry in a loop.
await update(d.id, { state: "failed", desiredState: "stopped", error, exitCode, stoppedAt: new Date(), stats: null });
}
async function start(c: DockerClient, d: Deployment) {
const [runtime, model, ws] = await Promise.all([
db().query.runtimes.findFirst({ where: eq(runtimes.id, d.runtimeId) }),
db().query.models.findFirst({ where: eq(models.id, d.modelId) }),
db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
]);
if (!runtime) return fail(d, "The runtime was deleted.");
if (!model) return fail(d, "The model was deleted.");
const host = ws?.docker;
if (!host?.connected) return fail(d, "Docker isn't connected.");
if (!host.network || !host.modelsSource) {
return fail(d, "The Docker network or the models source wasn't detected (see Settings → Runtimes).");
}
const image = await c.inspectImage(runtime.image);
if (!image) return fail(d, `Image ${runtime.image} isn't pulled yet (Settings → Runtimes → Pull).`);
// The files must be there (the worker sees the same models folder the container gets).
for (const f of [d.options.modelFile, d.options.mmproj, d.options.draftFile]) {
if (f == null || (f === "" && runtime.engine !== "vllm")) continue;
const path = join(coreEnv().MODELS_DIR, model.localPath, f);
if (!(await stat(path).catch(() => null))) return fail(d, `File not found: ${model.localPath}/${f}. Is the model downloaded?`);
}
// Memory: what the other running deployments reserve plus this one must fit.
if (d.memoryMb && host.memoryBytes) {
const others = await db()
.select({ memoryMb: deployments.memoryMb })
.from(deployments)
.where(and(inArray(deployments.state, ["starting", "running"])));
const used = others.reduce((s, o) => s + (o.memoryMb ?? 0), 0);
const available = host.memoryBytes / 2 ** 20 - MEMORY_RESERVE_MB - used;
if (d.memoryMb > available) {
return fail(
d,
`Not enough memory: ${formatBytes(d.memoryMb * 2 ** 20)} requested, ${formatBytes(Math.max(0, available) * 2 ** 20)} left for deployments (running ones reserve ${formatBytes(used * 2 ** 20)}).`,
);
}
}
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime });
const name = `kaname-${slug(d.name)}-${d.id.slice(-6).toLowerCase()}`;
const portKey = `${cmd.port}/tcp`;
const spec = {
Image: runtime.image,
Cmd: cmd.args,
Env: Object.entries(cmd.env).map(([k, v]) => `${k}=${v}`),
Labels: { [LABEL]: d.id, "kaname.managed": "true" },
ExposedPorts: { [portKey]: {} },
HostConfig: {
Mounts: [{ Type: host.modelsSource.type, Source: host.modelsSource.source, Target: CONTAINER_MODELS_DIR, ReadOnly: true }],
NanoCpus: d.cpus ? Math.round(d.cpus * 1e9) : 0,
Memory: d.memoryMb ? d.memoryMb * 2 ** 20 : 0,
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
Devices: runtime.devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
Privileged: false,
Init: true,
RestartPolicy: { Name: "no" },
},
NetworkingConfig: { EndpointsConfig: { [host.network]: {} } },
};
addLog(d.id, "system", `Starting ${runtime.name} (${runtime.image})`);
addLog(d.id, "system", `$ ${renderCommand(runtime.image, cmd)}`);
try {
await c.removeContainer(name); // leftover from a crash
const created = await c.createContainer(name, spec);
for (const w of created.Warnings ?? []) addLog(d.id, "system", `Docker: ${w}`);
await update(d.id, {
state: "starting",
containerId: created.Id,
containerName: name,
command: cmd.args,
imageId: image.Id,
startedAt: new Date(),
readyAt: null,
stoppedAt: null,
error: null,
exitCode: null,
stats: null,
});
follow(c, { id: d.id, containerId: created.Id });
await c.startContainer(created.Id);
log.info(`deployment ${d.name}: started ${name}`);
} catch (err) {
await c.removeContainer(name).catch(() => {});
await fail(d, `Docker: ${message(err)}`);
}
}
async function stopContainer(c: DockerClient, d: Deployment) {
if (d.containerId) {
await update(d.id, { state: "stopping" });
await c.stopContainer(d.containerId, 15);
await c.removeContainer(d.containerId);
}
unfollow(d.id);
addLog(d.id, "system", "Stopped.");
await update(d.id, { state: "stopped", stoppedAt: new Date(), stats: null, containerId: null });
}
/** Tail of the log for error messages. */
async function lastLines(id: string, n = 15): Promise<string> {
await flushDeploymentLogs();
const rows = await db()
.select({ line: deploymentLogs.line })
.from(deploymentLogs)
.where(eq(deploymentLogs.deploymentId, id))
.orderBy(desc(deploymentLogs.id))
.limit(n);
return rows
.reverse()
.map((r) => r.line)
.join("\n");
}
async function healthy(name: string, port: number): Promise<boolean> {
try {
const res = await fetch(`http://${name}:${port}/health`, { signal: AbortSignal.timeout(2_000) });
return res.ok;
} catch {
return false;
}
}
// --- reconcile -----------------------------------------------------------------------------------
const lastStats = new Map<string, number>();
async function reconcileOne(c: DockerClient, d: Deployment) {
if (d.deleteRequestedAt) {
if (d.containerId) {
await c.stopContainer(d.containerId, 15).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
}
unfollow(d.id);
pending.splice(0, pending.length, ...pending.filter((p) => p.deploymentId !== d.id));
await db().batch([db().delete(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)), db().delete(deployments).where(eq(deployments.id, d.id))]);
log.info(`deployment ${d.name} deleted`);
return;
}
if (d.desiredState === "stopped") {
if (d.state === "starting" || d.state === "running" || d.state === "stopping") await stopContainer(c, d);
return;
}
// desired: running
if (d.state === "stopped" || d.state === "failed") return start(c, d);
if (!d.containerId || !d.containerName) return fail(d, "Container is missing.");
const st = await c.containerState(d.containerId);
if (!st || !st.Running) {
const why = st?.OOMKilled ? "out of memory (raise the memory limit)" : `exit code ${st?.ExitCode ?? "?"}`;
unfollow(d.id);
const tail = await lastLines(d.id);
await c.removeContainer(d.containerId).catch(() => {});
return fail(d, `The container stopped (${why}).${tail ? `\n${tail}` : ""}`, st?.ExitCode ?? null);
}
if (!followers.has(d.id)) follow(c, { id: d.id, containerId: d.containerId });
const runtime = await db().query.runtimes.findFirst({ columns: { engine: true }, where: eq(runtimes.id, d.runtimeId) });
const port = ENGINE_PORT[runtime?.engine ?? "llama.cpp"];
if (d.state === "starting") {
if (await healthy(d.containerName, port)) {
const now = new Date();
const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?";
addLog(d.id, "system", `Ready after ${secs} s.`);
await update(d.id, { state: "running", readyAt: now });
} else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) {
await c.stopContainer(d.containerId).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
return fail(d, "Not healthy after 30 minutes.");
}
}
if (Date.now() - (lastStats.get(d.id) ?? 0) >= STATS_MS) {
lastStats.set(d.id, Date.now());
const s = await c.containerStats(d.containerId).catch(() => null);
if (s) await update(d.id, { stats: { ...s, at: new Date().toISOString() } });
}
}
let reconciling = false;
export async function reconcileDeployments(): Promise<void> {
const c = docker();
if (!c || reconciling) return;
reconciling = true;
try {
for (const d of await db().select().from(deployments)) {
await reconcileOne(c, d).catch((err) => log.error(`deployment ${d.name}`, err));
}
} finally {
reconciling = false;
}
}
/** After a worker restart: re-attach to running containers, remove ones no deployment owns. */
export async function adoptContainers(): Promise<void> {
const c = docker();
if (!c) return;
try {
const rows = await db().select({ id: deployments.id, containerId: deployments.containerId, state: deployments.state }).from(deployments);
const byId = new Map(rows.map((r) => [r.id, r]));
for (const ct of await c.listContainers(LABEL)) {
const owner = byId.get(ct.Labels[LABEL]);
if (!owner || owner.containerId !== ct.Id) {
await c.removeContainer(ct.Id);
log.info(`removed orphaned container ${ct.Names[0] ?? ct.Id}`);
} else if (ct.State === "running") {
follow(c, { id: owner.id, containerId: ct.Id });
}
}
} catch (err) {
log.warn(`adopting deployment containers failed: ${message(err)}`);
}
}
export function stopFollowingLogs() {
for (const id of [...followers.keys()]) unfollow(id);
}
export const LOG_FLUSH_INTERVAL_MS = LOG_FLUSH_MS;
+106
View File
@@ -92,6 +92,112 @@ export class DockerClient {
}
}
/** Containers with a label (e.g. "kaname.deployment"), running or not. */
listContainers(label: string) {
const filters = encodeURIComponent(JSON.stringify({ label: [label] }));
return this.json<{ Id: string; Names: string[]; State: string; Labels: Record<string, string> }[]>(
"GET",
`/containers/json?all=1&filters=${filters}`,
);
}
createContainer(name: string, spec: unknown) {
return this.json<{ Id: string; Warnings: string[] }>("POST", `/containers/create?name=${encodeURIComponent(name)}`, spec);
}
async startContainer(id: string) {
await this.json("POST", `/containers/${encodeURIComponent(id)}/start`);
}
/** Stop (SIGTERM, SIGKILL after `timeout` s); ignores "already stopped". */
async stopContainer(id: string, timeout = 10) {
try {
await this.json("POST", `/containers/${encodeURIComponent(id)}/stop?t=${timeout}`);
} catch (err) {
if (!(err instanceof DockerError && (err.status === 304 || err.status === 404))) throw err;
}
}
/** Remove a container (forced); ignores "no such container". */
async removeContainer(id: string) {
try {
await this.json("DELETE", `/containers/${encodeURIComponent(id)}?force=1`);
} catch (err) {
if (!(err instanceof DockerError && err.status === 404)) throw err;
}
}
async containerState(id: string) {
const c = await this.json<{ State: { Status: string; Running: boolean; ExitCode: number; Error: string; OOMKilled: boolean } } | null>(
"GET",
`/containers/${encodeURIComponent(id)}/json`,
).catch((err) => {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
});
return c?.State ?? null;
}
/** One stats sample: CPU % (of one core = 100) and memory. */
async containerStats(id: string): Promise<{ cpuPercent: number; memoryBytes: number; memoryLimitBytes: number }> {
const s = await this.json<{
cpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number; online_cpus: number };
precpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number };
memory_stats: { usage?: number; limit?: number; stats?: { inactive_file?: number; cache?: number } };
}>("GET", `/containers/${encodeURIComponent(id)}/stats?stream=false`);
const cpuDelta = s.cpu_stats.cpu_usage.total_usage - (s.precpu_stats.cpu_usage?.total_usage ?? 0);
const sysDelta = s.cpu_stats.system_cpu_usage - (s.precpu_stats.system_cpu_usage ?? 0);
const cpuPercent = sysDelta > 0 ? (cpuDelta / sysDelta) * (s.cpu_stats.online_cpus || 1) * 100 : 0;
// Like `docker stats`: usage minus page cache.
const cache = s.memory_stats.stats?.inactive_file ?? s.memory_stats.stats?.cache ?? 0;
return {
cpuPercent: Math.round(cpuPercent * 10) / 10,
memoryBytes: Math.max(0, (s.memory_stats.usage ?? 0) - cache),
memoryLimitBytes: s.memory_stats.limit ?? 0,
};
}
/**
* Follow a container's stdout/stderr (from now, plus the last `tail` lines). The stream uses
* Docker's multiplexed format (8-byte frame headers) for containers without a TTY. Resolves when
* the container stops or `signal` aborts.
*/
async followLogs(
id: string,
onLine: (stream: "stdout" | "stderr", line: string) => void,
options: { tail?: number; signal?: AbortSignal } = {},
): Promise<void> {
const res = await this.raw(
"GET",
`/containers/${encodeURIComponent(id)}/logs?follow=1&stdout=1&stderr=1&tail=${options.tail ?? 0}`,
undefined,
0,
);
if ((res.statusCode ?? 500) >= 400) throw new DockerError(`logs: HTTP ${res.statusCode}`, res.statusCode ?? null);
options.signal?.addEventListener("abort", () => res.destroy());
let buf = Buffer.alloc(0);
const partial = { stdout: "", stderr: "" };
const emit = (stream: "stdout" | "stderr", text: string) => {
const parts = (partial[stream] + text).split(/\r?\n|\r/);
partial[stream] = parts.pop() ?? "";
for (const p of parts) if (p.trim()) onLine(stream, p);
};
try {
for await (const chunk of res) {
buf = Buffer.concat([buf, chunk as Buffer]);
while (buf.length >= 8) {
const size = buf.readUInt32BE(4);
if (buf.length < 8 + size) break;
emit(buf[0] === 2 ? "stderr" : "stdout", buf.subarray(8, 8 + size).toString("utf8"));
buf = buf.subarray(8 + size);
}
}
} catch (err) {
if (!options.signal?.aborted) throw err;
}
for (const s of ["stdout", "stderr"] as const) if (partial[s].trim()) onLine(s, partial[s]);
}
/** Inspect a local image; null if it isn't pulled. */
async inspectImage(ref: string) {
try {
+10
View File
@@ -12,6 +12,7 @@ import { coreEnv } from "@/lib/env";
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
import { DownloadRunner } from "./download";
import { log } from "./log";
import type { Runner } from "./runner";
@@ -32,6 +33,7 @@ const FOLDER_SCAN_MS = 2 * 60_000;
const DOCKER_INFO_MS = 5 * 60_000;
const IMAGE_SYNC_MS = 60_000;
const PULL_CHECK_MS = 3_000;
const DEPLOYMENT_TICK_MS = 2_000;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
@@ -343,6 +345,9 @@ async function shutdown(reason: string, code = 0) {
stopping = true;
log.info(`shutting down (${reason})`);
timers.forEach(clearInterval);
// Deployment containers keep running; the next worker re-attaches to them.
stopFollowingLogs();
await flushDeploymentLogs().catch(() => {});
if (runners.size > 0) {
for (const r of runners.values()) r.interrupt();
const deadline = Date.now() + SHUTDOWN_GRACE_MS;
@@ -394,6 +399,11 @@ async function main() {
timers.push(setInterval(() => void dockerInfo(), DOCKER_INFO_MS));
timers.push(setInterval(() => void imageSync(), IMAGE_SYNC_MS));
timers.push(setInterval(() => void handlePullRequests().catch((err) => log.error("pull failed", err)), PULL_CHECK_MS));
// Deployments: re-attach to running containers, then keep them in line with the desired state.
await adoptContainers();
timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS));
timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS));
void scanFolders();
void tick();
setTimeout(() => void checkHubDue(), 15_000);