// Host hardware from sysfs and procfs, which a container sees unprivileged: GPUs on the PCI bus with // their PCIe link and BAR size (for Resizable BAR), CPU, RAM, kernel, virtualization and the disk // holding the models folder. Root-only sources (lspci's extended capabilities, DMI serials) and host // tools (systemd-detect-virt) aren't available in the worker, so this reads the same facts from files. // Everything reads through a SysFs, so tests run against an in-memory tree. import { readdir, readFile, realpath } from "node:fs/promises"; import { release } from "node:os"; import { posix } from "node:path"; import type { GpuVendor, HardwareGpu, HostGpu, HostHardware, PcieLink } from "@/lib/db/schema"; import { linkGen, rebarFrom } from "@/lib/hardware"; const VENDORS: Record = { "0x10de": "nvidia", "0x8086": "intel", "0x1002": "amd" }; const VENDOR_LABEL: Record = { nvidia: "NVIDIA", intel: "Intel", amd: "AMD" }; const PCI_ADDR = /^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i; const PCI_IDS = ["/usr/share/misc/pci.ids", "/usr/share/hwdata/pci.ids"]; /** Where drivers report total VRAM, if they do (amdgpu; xe/i915 vary by kernel). */ const VRAM_FILES = ["mem_info_vram_total", "tile0/physical_vram_size_bytes", "lmem_total_bytes"]; const IORESOURCE_MEM = BigInt(0x200); const ZERO = BigInt(0); const MIB = BigInt(2 ** 20); const { basename, dirname, join } = posix; /** The few file operations detection needs (absolute POSIX paths). */ export type SysFs = { /** Trimmed file content, or null when it can't be read. */ read(path: string): Promise; list(dir: string): Promise; /** Symlinks resolved (sysfs device links); the path itself when it isn't one. */ resolve(path: string): Promise; }; export const nodeFs: SysFs = { read: (p) => readFile(p, "utf8").then((t) => t.trim(), () => null), list: (d) => readdir(d).catch(() => []), resolve: (p) => realpath(p).catch(() => p), }; const num = (s: string | null) => (s != null && /^\d+$/.test(s) ? Number(s) : null); /** nvidia-smi's "00000000:01:00.0" → sysfs "0000:01:00.0". */ export function normalizePciAddress(id: string): string { const [domain, ...rest] = id.trim().toLowerCase().split(":"); return [domain.slice(-4).padStart(4, "0"), ...rest].join(":"); } /** Largest memory BAR in MiB, from a device's `resource` file ("start end flags" per line). */ export function largestBarMb(resource: string | null): number | null { if (!resource) return null; let max = ZERO; for (const line of resource.split("\n")) { const [start, end, flags] = line.trim().split(/\s+/).map((x) => { try { return BigInt(x); } catch { return ZERO; } }); if (!end || !(flags & IORESOURCE_MEM)) continue; const size = end - start + BigInt(1); if (size > max) max = size; } return max > ZERO ? Number(max / MIB) : null; } /** * The card's own upstream link: cards like Intel's Arc B-series sit behind an on-card PCIe switch, * whose internal link is what the GPU function reports. Walk up while the parent belongs to the same * vendor and isn't the root port. */ async function cardUpstream(fs: SysFs, dev: string, vendor: string): Promise { let cur = dev; for (;;) { const parent = dirname(cur); if (!PCI_ADDR.test(basename(parent)) || !PCI_ADDR.test(basename(dirname(parent)))) return cur; if ((await fs.read(join(parent, "vendor"))) !== vendor) return cur; cur = parent; } } async function link(fs: SysFs, dir: string, kind: "current" | "max") { const gen = linkGen(await fs.read(join(dir, `${kind}_link_speed`))); const width = num(await fs.read(join(dir, `${kind}_link_width`))); return gen == null && width == null ? null : { gen, width }; } const pciIds = new WeakMap>(); async function pciIdsText(fs: SysFs): Promise { if (!pciIds.has(fs)) { pciIds.set( fs, (async () => { for (const p of PCI_IDS) { const text = await fs.read(p); if (text) return text; } return null; })(), ); } return pciIds.get(fs)!; } /** Name from pci.ids: the subsystem's (board) name if listed, else the chip's; "[Arc B580]" preferred. */ export function pciName(ids: string, vendor: string, device: string, subVendor?: string | null, subDevice?: string | null): string | null { const v = vendor.replace(/^0x/, "").toLowerCase(); const d = device.replace(/^0x/, "").toLowerCase(); const sub = subVendor && subDevice ? `${subVendor.replace(/^0x/, "")} ${subDevice.replace(/^0x/, "")}`.toLowerCase() : null; const lines = ids.split("\n"); let i = lines.findIndex((l) => l.startsWith(`${v} `)); if (i < 0) return null; let chip: string | null = null; for (i++; i < lines.length && (lines[i].startsWith("\t") || lines[i].startsWith("#") || !lines[i].trim()); i++) { const l = lines[i]; if (!l.startsWith("\t\t") && l.startsWith("\t")) { if (chip) break; if (l.slice(1, 5).toLowerCase() === d) chip = l.slice(7).trim(); } else if (chip && sub && l.startsWith("\t\t") && l.slice(2, 11).toLowerCase() === sub) { return l.slice(13).trim(); } } return chip; } /** "AD102 [GeForce RTX 4090]" → "NVIDIA GeForce RTX 4090". */ export function gpuDisplayName(vendor: GpuVendor, pciIdsName: string | null): string | null { if (!pciIdsName) return null; const bracket = pciIdsName.match(/\[([^\]]+)\]/)?.[1]; const name = bracket ?? pciIdsName; const label = VENDOR_LABEL[vendor]; return name.toLowerCase().startsWith(label.toLowerCase()) ? name : `${label} ${name}`; } function uevent(text: string | null): Record { return Object.fromEntries((text ?? "").split("\n").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)])); } /** Display controllers (class 0x03…) from NVIDIA, Intel and AMD. NVIDIA names/VRAM come from nvidia-smi. */ export async function detectGpus(fs: SysFs, nvidia: HostGpu[], kernel: string | null): Promise { const base = "/sys/bus/pci/devices"; const addrs = (await fs.list(base)).filter((a) => PCI_ADDR.test(a)).sort(); const out: HardwareGpu[] = []; for (const addr of addrs) { const dev = await fs.resolve(join(base, addr)); const [cls, vendorId] = await Promise.all([fs.read(join(dev, "class")), fs.read(join(dev, "vendor"))]); const vendor = vendorId ? VENDORS[vendorId.toLowerCase()] : undefined; if (!cls?.startsWith("0x03") || !vendor) continue; const ev = uevent(await fs.read(join(dev, "uevent"))); const driver = ev.DRIVER || null; const up = await cardUpstream(fs, dev, vendorId!.toLowerCase()); const nv = nvidia.find((g) => g.pciAddress && normalizePciAddress(g.pciAddress) === addr.toLowerCase()); let vramMb: number | null = nv?.memoryMb ?? null; for (const f of VRAM_FILES) { if (vramMb) break; const bytes = num(await fs.read(join(dev, f))); if (bytes) vramMb = Math.round(bytes / 2 ** 20); } const ids = await pciIdsText(fs); const [device, subVendor, subDevice] = await Promise.all(["device", "subsystem_vendor", "subsystem_device"].map((f) => fs.read(join(dev, f)))); const barMb = largestBarMb(await fs.read(join(dev, "resource"))); const moduleVersion = driver ? await fs.read(join("/sys/module", driver, "version")) : null; out.push({ vendor, pciAddress: addr.toLowerCase(), name: nv?.name ?? (ids && device ? gpuDisplayName(vendor, pciName(ids, vendorId!, device, subVendor, subDevice)) : null), vramMb, driver, driverVersion: nv?.driver ?? moduleVersion ?? (driver && kernel ? `kernel ${kernel}` : null), linkCurrent: (await link(fs, up, "current")) ?? nv?.linkCurrent ?? null, linkMax: (await link(fs, up, "max")) ?? nv?.linkMax ?? null, barMb, rebar: rebarFrom(barMb, vramMb), }); } // NVIDIA GPUs that aren't on the visible PCI bus (WSL2 passes them through its own driver). for (const g of nvidia) { const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`; if (out.some((o) => o.pciAddress === addr)) continue; out.push({ vendor: "nvidia", pciAddress: addr, name: g.name, vramMb: g.memoryMb || null, driver: "nvidia", driverVersion: g.driver || null, linkCurrent: g.linkCurrent ?? null, linkMax: g.linkMax ?? null, barMb: null, rebar: null, }); } return out; } /** The current link of each GPU's card (upstream port), for sampling during a run; skips unknown ones. */ export async function currentLinks(fs: SysFs, pciAddresses: string[]): Promise> { const out: Record = {}; for (const addr of pciAddresses) { const dev = await fs.resolve(join("/sys/bus/pci/devices", addr)); const vendor = await fs.read(join(dev, "vendor")); if (!vendor) continue; const l = await link(fs, await cardUpstream(fs, dev, vendor.toLowerCase()), "current"); if (l) out[addr] = l; } return out; } /** `nvidia-smi topo -p2p r`: "OK" between every pair → on, none → off. */ export function parseP2p(text: string): "on" | "off" | "partial" | null { const cells = text .split("\n") .filter((l) => /^\s*GPU\d+\s/.test(l)) .flatMap((l) => l.trim().split(/\s+/).slice(1)) .filter((c) => c !== "X" && !/^GPU\d+$/.test(c)); if (cells.length === 0) return null; const ok = cells.filter((c) => c === "OK").length; return ok === cells.length ? "on" : ok === 0 ? "off" : "partial"; } export function parseCpu(cpuinfo: string | null): HostHardware["cpu"] & { hypervisor: boolean } { if (!cpuinfo) return { model: null, cores: null, threads: null, hypervisor: false }; const blocks = cpuinfo.split(/\n\s*\n/).filter((b) => /^processor\s*:/m.test(b)); const field = (b: string, k: string) => b.match(new RegExp(`^${k}\\s*:\\s*(.*)$`, "m"))?.[1]?.trim() ?? null; const cores = new Set(blocks.map((b) => `${field(b, "physical id") ?? 0}:${field(b, "core id") ?? field(b, "processor")}`)); return { model: blocks[0] ? field(blocks[0], "model name") : null, cores: blocks.length ? cores.size : null, threads: blocks.length || null, hypervisor: blocks[0] ? /\bhypervisor\b/.test(field(blocks[0], "flags") ?? "") : false, }; } const HYPERVISORS: [RegExp, string][] = [ [/^QEMU|KVM/i, "KVM/QEMU"], [/Microsoft/i, "Hyper-V"], [/VMware/i, "VMware"], [/Xen/i, "Xen"], [/innotek|VirtualBox/i, "VirtualBox"], [/Amazon/i, "AWS"], [/Google/i, "Google Cloud"], ]; /** VM or bare metal, from the CPU's hypervisor flag and the DMI vendor (both readable unprivileged). */ export async function detectVirtualization(fs: SysFs, hypervisorFlag: boolean, kernel: string | null): Promise { const dmi = [await fs.read("/sys/class/dmi/id/sys_vendor"), await fs.read("/sys/class/dmi/id/product_name")].filter(Boolean).join(" "); if (kernel && /microsoft.*wsl/i.test(kernel)) return { vm: true, hypervisor: "WSL2 (Hyper-V)" }; const known = HYPERVISORS.find(([re]) => re.test(dmi))?.[1] ?? null; if (hypervisorFlag || known) return { vm: true, hypervisor: known }; return { vm: dmi ? false : null, hypervisor: null }; } /** The mount holding `dir` (longest mount point that is a prefix), as "major:minor". */ export function mountDevice(mountinfo: string, dir: string): string | null { const target = posix.normalize(dir.replace(/\\/g, "/")).replace(/(.)\/$/, "$1"); let best: { point: string; dev: string } | null = null; for (const line of mountinfo.split("\n")) { const f = line.split(" "); if (f.length < 5) continue; const point = f[4].replace(/\\040/g, " "); const inside = target === point || target.startsWith(point.endsWith("/") ? point : `${point}/`); if (inside && (!best || point.length > best.point.length)) best = { point, dev: f[2] }; } return best?.dev ?? null; } /** The disk behind a block device: partitions → their disk, device-mapper (LVM, LUKS) → first slave. */ async function diskOf(fs: SysFs, devDir: string, depth = 0): Promise { if (depth > 4) return null; if (await fs.read(join(devDir, "partition"))) return dirname(devDir); if (basename(devDir).startsWith("dm-") || basename(devDir).startsWith("md")) { const slaves = await fs.list(join(devDir, "slaves")); if (!slaves[0]) return devDir; return diskOf(fs, await fs.resolve(join("/sys/class/block", slaves[0])), depth + 1); } return devDir; } export async function detectStorage(fs: SysFs, modelsDir: string): Promise { const mountinfo = await fs.read("/proc/self/mountinfo"); const dev = mountinfo ? mountDevice(mountinfo, modelsDir) : null; if (!dev || dev.startsWith("0:")) return null; // ZFS, overlay, network filesystems: no block device const blockDir = join("/sys/dev/block", dev); if ((await fs.list(blockDir)).length === 0) return null; const disk = await diskOf(fs, await fs.resolve(blockDir)); if (!disk) return null; const name = basename(disk); const model = (await fs.read(join(disk, "device/model")))?.replace(/\s+/g, " ") || null; const vendor = (await fs.read(join(disk, "device/vendor")))?.trim() ?? ""; const rotational = await fs.read(join(disk, "queue/rotational")); const sectors = num(await fs.read(join(disk, "size"))); const virtual = /^vd|^xvd/.test(name) || vendor === "0x1af4" || /QEMU|Virtual Disk|VBOX|VMware/i.test(`${vendor} ${model ?? ""}`); return { model: model ?? (virtual ? "virtio disk" : null), kind: virtual ? "virtual" : name.startsWith("nvme") ? "nvme" : rotational === "1" ? "hdd" : rotational === "0" ? "ssd" : null, sizeBytes: sectors != null ? sectors * 512 : null, }; } export async function detectHardware(o: { fs?: SysFs; modelsDir: string; nvidia?: HostGpu[]; p2p?: HostHardware["p2p"]; kernel?: string | null }): Promise { const fs = o.fs ?? nodeFs; const kernel = o.kernel !== undefined ? o.kernel : release(); const cpu = parseCpu(await fs.read("/proc/cpuinfo")); const memKb = Number((await fs.read("/proc/meminfo"))?.match(/^MemTotal:\s+(\d+)\s*kB/m)?.[1]); const gpus = await detectGpus(fs, o.nvidia ?? [], kernel); return { gpus, p2p: gpus.length >= 2 ? (o.p2p ?? null) : null, cpu: { model: cpu.model, cores: cpu.cores, threads: cpu.threads }, memoryBytes: Number.isFinite(memKb) && memKb > 0 ? memKb * 1024 : null, kernel, virtualization: await detectVirtualization(fs, cpu.hypervisor, kernel), storage: await detectStorage(fs, o.modelsDir).catch(() => null), checkedAt: new Date().toISOString(), }; }