// Worker side of runtimes: Docker host facts, image state per runtime, pulling images. // The web app never talks to Docker; it reads what the worker reports in the DB. import { readFile } from "node:fs/promises"; import { hostname } from "node:os"; import { resolve } from "node:path"; import { and, eq, isNotNull, ne } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { type DockerHostInfo, type HostGpu, type HostHardware, type PcieLink, runtimes, settings, workerState } from "@/lib/db/schema"; import { coreEnv } from "@/lib/env"; import { RUNTIME_PRESETS } from "@/lib/runtimes-shared"; import { DockerClient, DockerError } from "./docker/client"; import { detectHardware, normalizePciAddress, parseP2p } from "./hardware"; import { log } from "./log"; const PROGRESS_MS = 1_000; /** CPU flags that matter for inference engines. */ const CPU_FEATURES = ["avx2", "avx512f", "avx512_bf16", "avx512_vnni", "avx512bw", "amx_bf16", "amx_int8", "f16c", "fma"]; let client: DockerClient | null | undefined; export function docker(): DockerClient | null { if (client === undefined) { const host = coreEnv().DOCKER_HOST; client = host ? new DockerClient(host) : null; } return client; } const message = (err: unknown) => (err instanceof Error ? err.message : String(err)); /** CPU model and features from /proc/cpuinfo (the host's, also inside a container). */ async function cpuFacts(): Promise<{ model: string | null; features: string[] }> { try { const text = await readFile("/proc/cpuinfo", "utf8"); const model = text.match(/^model name\s*:\s*(.+)$/m)?.[1]?.trim() ?? null; const flags = new Set(text.match(/^flags\s*:\s*(.+)$/m)?.[1]?.split(/\s+/) ?? []); return { model, features: CPU_FEATURES.filter((f) => flags.has(f)) }; } catch { return { model: null, features: [] }; // not Linux (dev on Windows/macOS) } } /** Find our own container to learn the network and where MODELS_DIR comes from on the host. */ async function selfDetect(c: DockerClient): Promise & { image: string | null }> { const env = coreEnv(); let network: string | null = env.KANAME_DOCKER_NETWORK ?? null; let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE ? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE } : null; // Always inspected: the worker's own image also serves as the GPU probe image. const self = await c.inspectContainer(hostname()).catch(() => null); if (self) { network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null; const mount = self.Mounts.find((m) => resolve(m.Destination) === resolve(env.MODELS_DIR)); if (!modelsSource && mount) { modelsSource = mount.Type === "volume" ? { type: "volume", source: mount.Name ?? mount.Source } : { type: "bind", source: mount.Source }; } } return { network, modelsSource, image: self?.Image ?? null }; } // --- GPUs --------------------------------------------------------------------- const GPU_PROBE_MS = 60 * 60_000; let ownImage: string | null = null; /** The worker's own image (from the last host check); probe containers run from it. */ export const workerImage = () => ownImage; let gpuCache: { at: number; gpus: HostGpu[]; p2p: HostHardware["p2p"]; error: string | null } | null = null; /** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */ export function parseNvidiaSmi(csv: string): HostGpu[] { return csv .split(/\r?\n/) .map((l) => l.split(",").map((p) => p.trim())) .filter((p) => p.length >= 5 && /^\d+$/.test(p[0])) .map(([index, uuid, name, mem, driver, bus, genCur, genMax, widthCur, widthMax]) => ({ vendor: "nvidia" as const, index: Number(index), uuid, name, memoryMb: Number(mem) || 0, driver, pciAddress: bus ? normalizePciAddress(bus) : null, linkCurrent: nvLink(genCur, widthCur), linkMax: nvLink(genMax, widthMax), })); } const nvNum = (s: string | undefined) => (s && /^\d+$/.test(s) ? Number(s) : null); function nvLink(gen: string | undefined, width: string | undefined): PcieLink | null { const l = { gen: nvNum(gen), width: nvNum(width) }; return l.gen == null && l.width == null ? null : l; } /** * Lists the GPUs containers get from Docker (nvidia-smi, which the NVIDIA Container Toolkit injects) * and, with two or more, whether they can talk peer-to-peer. */ async function probeNvidia(c: DockerClient, image: string): Promise<{ gpus: HostGpu[]; p2p: HostHardware["p2p"] }> { const gpus = parseNvidiaSmi((await nvidiaSmi(c, image, ["--query-gpu=index,uuid,name,memory.total,driver_version,pci.bus_id,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,pcie.link.width.max", "--format=csv,noheader,nounits"])).join("\n")); let p2p: HostHardware["p2p"] = null; if (gpus.length >= 2) p2p = parseP2p((await nvidiaSmi(c, image, ["topo", "-p2p", "r"]).catch(() => [])).join("\n")); return { gpus, p2p }; } /** Runs `nvidia-smi ` in a short-lived container (our own image) that gets every GPU; its output lines. */ function nvidiaSmi(c: DockerClient, image: string, args: string[]): Promise { return runProbe(c, { Image: image, Entrypoint: ["nvidia-smi"], Cmd: args, Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"], HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false }, }); } /** * Group IDs of the host's /dev/dri nodes (render, video), as a short-lived container with /dev/dri * sees them (Docker copies the host's owner and mode). Runtime containers get them as extra groups, * so images that don't run as root can open the GPU. */ async function probeDriGroups(c: DockerClient, image: string): Promise { const lines = await runProbe(c, { Image: image, Entrypoint: ["sh", "-c", "stat -c '%n %g' /dev/dri/*"], Cmd: [], HostConfig: { Devices: [{ PathOnHost: "/dev/dri", PathInContainer: "/dev/dri", CgroupPermissions: "r" }], NetworkMode: "none", Privileged: false, ReadonlyRootfs: true }, }); return parseDriGroups(lines); } /** "`/dev/dri/renderD128 993`" lines → the distinct non-root group IDs. */ export function parseDriGroups(lines: string[]): number[] { const gids = lines.map((l) => l.trim().match(/^\/dev\/dri\/\S+\s+(\d+)$/)?.[1]).filter((g): g is string => !!g).map(Number); return [...new Set(gids.filter((g) => g > 0))].sort((a, b) => a - b); } /** Runs a short-lived probe container from our own image and returns its output lines. */ async function runProbe(c: DockerClient, spec: { Image: string; Entrypoint: string[]; Cmd: string[]; Env?: string[]; HostConfig: Record }): Promise { const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, { ...spec, Labels: { "kaname.managed": "true", "kaname.probe": "gpu" } }); try { const lines: string[] = []; await c.startContainer(created.Id); await c.followLogs(created.Id, (_s, line) => lines.push(line), { tail: "all", signal: AbortSignal.timeout(30_000) }); const st = await c.containerState(created.Id); if (st && st.ExitCode !== 0) throw new Error(`${spec.Entrypoint[0]} exited with ${st.ExitCode}: ${lines.slice(-3).join(" ")}`); return lines; } finally { await c.removeContainer(created.Id).catch(() => {}); } } async function gpuFacts(c: DockerClient, info: Awaited>, selfImage: string | null) { const nvidia = !!info.Runtimes?.nvidia || !!info.DiscoveredDevices?.some((d) => d.ID.startsWith("nvidia.com/gpu")); if (!nvidia) return { nvidia, gpus: [], p2p: null, gpuError: null, gpuCheckedAt: null }; if (!gpuCache || Date.now() - gpuCache.at > GPU_PROBE_MS) { try { if (!selfImage) throw new Error("Kaname's own image is unknown (the worker isn't running in a container), so GPUs can't be probed."); const { gpus, p2p } = await probeNvidia(c, selfImage); gpuCache = { at: Date.now(), gpus, p2p, error: null }; if (gpus.length) { log.info(`GPUs: ${gpus.map((g) => `${g.index}: ${g.name} (${Math.round(g.memoryMb / 1024)} GiB)`).join(", ")}`); await seedGpuPresets(); } } catch (err) { gpuCache = { at: Date.now(), gpus: [], p2p: null, error: message(err) }; log.warn(`GPU probe failed: ${message(err)}`); } } return { nvidia, gpus: gpuCache.gpus, p2p: gpuCache.p2p, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() }; } const CUDA_SEEDED_KEY = "runtimes.cudaPresetSeeded"; /** The first time NVIDIA GPUs show up, add the llama.cpp CUDA runtime (once). */ async function seedGpuPresets() { const d = db(); if (await d.query.settings.findFirst({ where: eq(settings.key, CUDA_SEEDED_KEY) })) return; const p = RUNTIME_PRESETS.find((x) => x.id === "llama.cpp-cuda"); if (p) { await d.insert(runtimes).values({ name: p.name, engine: p.engine, accelerator: "nvidia", image: p.image, description: p.description ?? null, preset: p.id }); log.info(`NVIDIA GPU found: added the "${p.name}" runtime`); } await d.insert(settings).values({ key: CUDA_SEEDED_KEY, value: true }).onConflictDoNothing(); } const INTEL_SEEDED_KEY = "runtimes.intelPresetSeeded"; /** The first time an Intel GPU shows up, add the llama.cpp runtimes for it (SYCL and Vulkan, once). */ async function seedIntelPresets() { const d = db(); if (await d.query.settings.findFirst({ where: eq(settings.key, INTEL_SEEDED_KEY) })) return; for (const p of RUNTIME_PRESETS.filter((x) => x.id === "llama.cpp-intel" || x.id === "llama.cpp-vulkan")) { await d.insert(runtimes).values({ name: p.name, engine: p.engine, accelerator: p.accelerator ?? "dri", image: p.image, description: p.description ?? null, env: p.env ?? {}, devices: p.devices ?? [], preset: p.id, }); log.info(`Intel GPU found: added the "${p.name}" runtime`); } await d.insert(settings).values({ key: INTEL_SEEDED_KEY, value: true }).onConflictDoNothing(); } let driCache: { at: number; gids: number[] } | null = null; /** Render/video group IDs of /dev/dri, re-checked hourly while there are Intel or AMD GPUs. */ async function driGroups(c: DockerClient, image: string | null, hardware: HostHardware | null): Promise { if (!image || !hardware?.gpus.some((g) => g.vendor !== "nvidia")) return undefined; if (!driCache || Date.now() - driCache.at > GPU_PROBE_MS) { try { driCache = { at: Date.now(), gids: await probeDriGroups(c, image) }; log.info(`/dev/dri groups: ${driCache.gids.join(", ") || "none besides root"}`); } catch (err) { driCache = { at: Date.now(), gids: [] }; log.warn(`/dev/dri group check failed: ${message(err)}`); } } return driCache.gids; } /** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */ export async function refreshDockerInfo(instanceId: string): Promise { const c = docker(); let info: DockerHostInfo | null = null; if (c) { const cpu = await cpuFacts(); const base = { cpuModel: cpu.model, cpuFeatures: cpu.features, checkedAt: new Date().toISOString(), }; try { const [v, i] = await Promise.all([c.version(), c.info()]); const self = await selfDetect(c); ownImage = self.image; const { p2p, ...gpu } = await gpuFacts(c, i, self.image); const hardware = await detectHardware({ modelsDir: coreEnv().MODELS_DIR, nvidia: gpu.gpus, p2p }).catch((err) => { log.warn(`hardware detection failed: ${message(err)}`); return null; }); if (hardware?.gpus.some((g) => g.vendor === "intel")) await seedIntelPresets(); const driGids = await driGroups(c, self.image, hardware); info = { connected: true, error: null, serverVersion: v.Version, os: i.OperatingSystem, architecture: i.Architecture, cpus: i.NCPU, memoryBytes: i.MemTotal, ...base, network: self.network, modelsSource: self.modelsSource, ...gpu, hardware, ...(driGids ? { driGroups: driGids } : {}), }; } catch (err) { info = { connected: false, error: message(err), serverVersion: null, os: null, architecture: null, cpus: null, memoryBytes: null, network: null, modelsSource: null, ...base, }; } } await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId))); } /** The registry digest ("sha256:…") of an image reference, from Docker's RepoDigests ("repo@sha256:…"). */ export function repoDigest(ref: string, repoDigests: string[] | null | undefined): string | null { const repo = ref.split("@")[0].replace(/:[^/:]+$/, ""); const all = repoDigests ?? []; const hit = all.find((d) => d.split("@")[0] === repo) ?? all[0]; return hit?.split("@")[1] ?? null; } const SEEDED_KEY = "runtimes.presetsSeeded"; /** Create the preset runtimes once (deleted presets don't come back). */ export async function seedRuntimePresets(): Promise { const d = db(); const seeded = await d.query.settings.findFirst({ where: eq(settings.key, SEEDED_KEY) }); if (seeded) return; const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1); if (existing.length === 0) { // CPU presets only; GPU ones are added from Settings (or automatically when an NVIDIA GPU shows up). const presets = RUNTIME_PRESETS.filter((p) => (p.accelerator ?? "cpu") === "cpu"); await d.insert(runtimes).values( presets.map((p) => ({ name: p.name, engine: p.engine, accelerator: p.accelerator ?? "cpu", image: p.image, description: p.description ?? null, env: p.env ?? {}, extraArgs: p.extraArgs ?? [], devices: p.devices ?? [], shmSizeMb: p.shmSizeMb ?? null, numaTuning: p.numaTuning ?? false, preset: p.id, })), ); log.info(`created ${presets.length} preset runtime(s)`); } await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing(); } /** Look up every runtime's image locally (present / missing), except ones being pulled. */ export async function syncImageStates(): Promise { const c = docker(); if (!c) return; const rows = await db().select().from(runtimes).where(ne(runtimes.imageState, "pulling")); for (const r of rows) { try { const img = await c.inspectImage(r.image); await db() .update(runtimes) .set( img ? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageDigest: repoDigest(r.image, img.RepoDigests), imageCheckedAt: new Date() } : { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, imageCheckedAt: new Date() }, ) .where(eq(runtimes.id, r.id)); } catch (err) { log.warn(`image check for ${r.image} failed: ${message(err)}`); } } } /** Pulls interrupted by a worker restart can't still be running. */ export async function resetStalePulls(): Promise { await db().update(runtimes).set({ imageState: "unknown", pullProgress: null }).where(eq(runtimes.imageState, "pulling")); } let pulling = false; /** Pull images whose "Pull" was requested after the last pull started. One at a time. */ export async function handlePullRequests(): Promise { const c = docker(); if (!c || pulling) return; const rows = await db().select().from(runtimes).where(isNotNull(runtimes.pullRequestedAt)); const next = rows.find((r) => r.imageState !== "pulling" && (!r.pullStartedAt || r.pullRequestedAt! > r.pullStartedAt)); if (!next) return; pulling = true; const d = db(); await d .update(runtimes) .set({ imageState: "pulling", pullStartedAt: new Date(), pullError: null, pullProgress: { doneBytes: 0, totalBytes: 0, status: "Starting" } }) .where(eq(runtimes.id, next.id)); log.info(`pulling ${next.image}`); let lastWrite = 0; try { await c.pullImage(next.image, (p) => { if (Date.now() - lastWrite < PROGRESS_MS) return; lastWrite = Date.now(); // Drizzle queries only run when awaited/then'd; `void query` would never execute. d.update(runtimes) .set({ pullProgress: p }) .where(eq(runtimes.id, next.id)) .then( () => {}, (err) => log.warn(`pull progress update failed: ${message(err)}`), ); }); const img = await c.inspectImage(next.image); await d .update(runtimes) .set({ imageState: img ? "present" : "failed", imageId: img?.Id ?? null, imageSize: img?.Size ?? null, imageCreated: img?.Created ?? null, imageDigest: img ? repoDigest(next.image, img.RepoDigests) : null, pullProgress: null, pullError: img ? null : "Pull finished but the image isn't there.", imageCheckedAt: new Date(), }) .where(eq(runtimes.id, next.id)); log.info(`pulled ${next.image}`); } catch (err) { const msg = err instanceof DockerError ? err.message : message(err); await d.update(runtimes).set({ imageState: "failed", pullProgress: null, pullError: msg }).where(eq(runtimes.id, next.id)); log.warn(`pulling ${next.image} failed: ${msg}`); } finally { pulling = false; } }