From 5f66b6183205a3a66af26f549340b3ed5f83f186 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Sat, 28 Nov 2026 20:40:41 -0800 Subject: [PATCH] dashboard: switch the 3090 between games and local AI The switch derives its mode from whether the GPU guest is running. Games stops the services that need /dev/nvidia* and starts the guest; AI shuts the guest down and deploys those services from the active release. snowglobe.py deploy and check skip GPU services while the guest holds the card, without dropping them from the managed job set. Assisted-by: claude-opus-5.5 --- dashboard/src/apps.rs | 65 +++++++++++++ dashboard/src/deploys.rs | 2 + dashboard/web/api.contract.ts | 3 + dashboard/web/components/GpuSwitch.css | 4 + dashboard/web/components/GpuSwitch.tsx | 72 ++++++++++++++ dashboard/web/pages/Overview.tsx | 8 +- dashboard/web/pages/VMs.tsx | 2 + dashboard/web/styles.css | 7 +- dashboard/web/types/vms.ts | 13 +++ tools/dashboard-deploy-test.py | 5 +- tools/dashboard-run.py | 6 +- tools/dashboard-vms-test.py | 130 +++++++++++++++++++++++++ tools/snowglobe.py | 25 ++++- tools/vms.py | 77 +++++++++++++++ 14 files changed, 413 insertions(+), 6 deletions(-) create mode 100644 dashboard/web/components/GpuSwitch.css create mode 100644 dashboard/web/components/GpuSwitch.tsx diff --git a/dashboard/src/apps.rs b/dashboard/src/apps.rs index 61fc62a4f04ec6aba7ed86649059a99fc4080736..3168098b19582aef5e028e55fd25094770b3fb9d 100644 --- a/dashboard/src/apps.rs +++ b/dashboard/src/apps.rs @@ -94,6 +94,57 @@ async fn vm_call(action: &str, payload: Option) -> Result { host::call(request).await } +/// Who has the GPU. The guest's power state says games; the GPU services' health says AI. +async fn gpu(app: Arc, name: &str) -> Value { + let ai = core::scan(app).await.ok().map(|scan| { + let mut health = scan + .value + .as_object() + .into_iter() + .flat_map(|jobs| jobs.values()) + .filter(|entry| { + array(&entry["job"]["TaskGroups"]) + .iter() + .flat_map(|group| array(&group["Tasks"])) + .any(|task| { + array(&task["Config"]["devices"]) + .iter() + .any(|device| string(device).starts_with("/dev/nvidia")) + }) + }) + .map(|entry| string(&entry["health"]).to_owned()); + health + .find(|health| health != "stopped") + .unwrap_or_else(|| "stopped".into()) + }); + let run = host::call(json!({"operation":"deploy.last"})) + .await + .unwrap_or_default(); + let ours = matches!(run["action"].as_str(), Some("games" | "ai")) && run["target"] == name; + let failed = if !ours || run["code"].is_null() || run["code"] == 0 { + Value::Null + } else if run["code"] == 2 { + // The switch exits 2 with a message for the person on its last line. + let lines = host::call(json!({"operation":"deploy.run","id":run["id"]})) + .await + .unwrap_or_default(); + array(&lines["lines"]) + .iter() + .rev() + .nth(1) + .cloned() + .unwrap_or(json!("Couldn't switch the GPU.")) + } else { + json!("Couldn't switch the GPU.") + }; + let switching = if ours && run["code"].is_null() { + run["action"].clone() + } else { + Value::Null + }; + json!({"ai":ai,"switching":switching,"failed":failed}) +} + fn vm_name(name: &str) -> Result<()> { if regex::Regex::new(r"^[a-z0-9][a-z0-9-]{0,62}$") .unwrap() @@ -309,6 +360,11 @@ pub async fn route( .get(string(&domain["name"])) .cloned() .unwrap_or(Value::Null); + domain["gpu"] = if domain["gpu"] == true { + gpu(app.clone(), string(&domain["name"])).await + } else { + Value::Null + }; } json!({"node":values[0],"domains":values[1],"library":values[2],"canPublish":array(&me["sections"]).iter().any(|section| section == "admin")}) } @@ -369,6 +425,15 @@ pub async fn route( ["media"] if method == Method::PUT => { vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?; } + ["gpu"] if method == Method::POST => { + let mode = body["mode"] + .as_str() + .filter(|mode| ["games", "ai"].contains(mode)) + .ok_or_else(|| Error::new(400, "Choose games or AI."))?; + host::call(json!({"operation":"deploy.start","action":mode,"target":name})) + .await?; + app.cache.invalidate("deploys"); + } ["preset"] if method == Method::POST => { need(me, "admin")?; vm_call("preset", Some(json!({"name":name,"id":body["id"],"os":body["os"],"description":body["description"]}))).await?; diff --git a/dashboard/src/deploys.rs b/dashboard/src/deploys.rs index bdc1dfcc42de5207cf117957f1368d48ab1ef6f6..20d9c31a90c5a671682c6ee6c36054878c483058 100644 --- a/dashboard/src/deploys.rs +++ b/dashboard/src/deploys.rs @@ -227,6 +227,8 @@ fn display_run(run: Value, history: &Value) -> Result { "secret-set" => format!("set {target}/{}", string(&run["key"])), "secret-rotate" => format!("rotate {target}/{}", string(&run["key"])), action @ ("start" | "stop" | "restart") => format!("{action} {target}"), + "games" => "switch GPU to games".to_owned(), + "ai" => "switch GPU to AI".to_owned(), "deploy" => "deploy main".to_owned(), "promote" => format!("promote {target}"), "destroy" => format!("destroy {target}"), diff --git a/dashboard/web/api.contract.ts b/dashboard/web/api.contract.ts index 2ca74c48eebeb5d115b2af373f823de4768dc4b2..a785c5070714f05e6b3e55e316cfded480b7aa0a 100644 --- a/dashboard/web/api.contract.ts +++ b/dashboard/web/api.contract.ts @@ -333,6 +333,9 @@ export type Api = Hono<{}, { "/vms/:name/preset": { $post: Endpoint; }; + "/vms/:name/gpu": { + $post: Endpoint; + }; "/vms/:name/:action": { $post: Endpoint; }; diff --git a/dashboard/web/components/GpuSwitch.css b/dashboard/web/components/GpuSwitch.css new file mode 100644 index 0000000000000000000000000000000000000000..1698daa3d6cb34c4eb06fb646813bfeaae44142b --- /dev/null +++ b/dashboard/web/components/GpuSwitch.css @@ -0,0 +1,4 @@ +.gpu-switch { display: inline-flex; align-items: center; gap: 8px; min-width: 0; } +.gpu-progress { min-width: 0; font-size: 12px; } +.gpu-progress .status-label { display: flex; min-width: 0; } +.gpu-progress .status-label > svg { flex: none; } diff --git a/dashboard/web/components/GpuSwitch.tsx b/dashboard/web/components/GpuSwitch.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e78df4fe6b6434f047124b80beaba039ea6acbaf --- /dev/null +++ b/dashboard/web/components/GpuSwitch.tsx @@ -0,0 +1,72 @@ +import { parseResponse } from "hono/client"; +import { createSignal, Show } from "solid-js"; +import { api, reason } from "../api.ts"; +import type { Domain, GpuShare } from "../types/vms.ts"; +import { showConfirmDialog } from "./Dialog.tsx"; +import { type StatusKind, StatusLabel } from "./Status.tsx"; +import { TabBar } from "./TabBar.tsx"; +import { toast } from "./Toast.tsx"; +import "./GpuSwitch.css"; + +type Side = NonNullable; + +const loading = (ai: GpuShare["ai"]) => ai === "starting" || ai === "deploying" || ai === "restarting"; + +/** Gives the GPU to `vm` for games or to AI. Who has it comes from the guest's power state and AI's health. */ +export function GpuSwitch(props: { vm: Domain & { gpu: GpuShare }; refetch: () => unknown }) { + const [sending, setSending] = createSignal(false); + const off = () => props.vm.state === "shutoff" || props.vm.state === "crashed"; + const aiOn = () => props.vm.gpu.ai !== null && props.vm.gpu.ai !== "stopped"; + const side = (): Side | null => props.vm.gpu.switching ?? (!off() ? "games" : aiOn() ? "ai" : null); + const busy = () => sending() || props.vm.gpu.switching !== null; + const progress = (): [StatusKind, string] | null => { + const { switching, ai, failed } = props.vm.gpu; + if (switching === "games") return ["starting", aiOn() ? "stopping AI…" : `starting ${props.vm.name}…`]; + if (switching === "ai") return ["starting", off() ? "loading AI…" : `shutting down ${props.vm.name}…`]; + if (failed) return ["down", failed]; + if (!off()) return null; + if (loading(ai)) return ["starting", "loading AI…"]; + if (ai === "down" || ai === "degraded") return [ai, `AI is ${ai}`]; + return ai === "stopped" ? ["stopped", "idle"] : null; + }; + const send = async (mode: Side) => { + setSending(true); + try { + await parseResponse(api.vms[":name"].gpu.$post({ param: { name: props.vm.name }, json: { mode } })); + await props.refetch(); + } finally { + setSending(false); + } + }; + const choose = (mode: Side) => { + if (mode === "ai" && !off()) { + showConfirmDialog({ + title: "Switch the GPU to AI?", + description: `${props.vm.name} shuts down first. Anything unsaved in it is lost.`, + confirmLabel: "switch to AI", + destructive: true, + onConfirm: () => send(mode), + }); + } else if (mode === "games" && aiOn()) { + showConfirmDialog({ + title: "Switch the GPU to games?", + description: "AI stops, along with replies it's writing, and takes a while to load again.", + confirmLabel: "switch to games", + onConfirm: () => send(mode), + }); + } else { + send(mode).catch((failure) => toast(`Couldn't switch the GPU. ${reason(failure)}`)); + } + }; + return ( + + + + + + + {(now) => {now()[1]}} + + + ); +} diff --git a/dashboard/web/pages/Overview.tsx b/dashboard/web/pages/Overview.tsx index e4510bb5004256620ecbe545accda4925edc97dc..49ed21a28d45d88ba56be3bd805dbb49a5c78480 100644 --- a/dashboard/web/pages/Overview.tsx +++ b/dashboard/web/pages/Overview.tsx @@ -9,11 +9,13 @@ import ShieldCheck from "lucide-solid/icons/shield-check"; import Trash from "lucide-solid/icons/trash"; import Undo2 from "lucide-solid/icons/undo-2"; import { createMemo, createResource, createRoot, createSignal, For, type JSX, onCleanup, Show } from "solid-js"; +import type { Domain, GpuShare } from "../types/vms.ts"; import { type Health, type HostInfo, type Live, type Me, type Series, type ServiceSummary, trouble } from "../types/model.ts"; import { api, queries, reason } from "../api.ts"; import { Ago } from "../components/Ago.tsx"; import { AppIcon } from "../components/AppIcon.tsx"; import { Donut } from "../components/Donut.tsx"; +import { GpuSwitch } from "../components/GpuSwitch.tsx"; import { lastGood, Loaded } from "../components/Loaded.tsx"; import { Meter } from "../components/Meter.tsx"; import { OpenApp } from "../components/OpenApp.tsx"; @@ -146,9 +148,12 @@ function Dashboard(props: { me: Me }) { const [storage, { refetch: refetchStorage }] = queries.storage.use(); const [services, { refetch: refetchServices }] = queries.services.use(); const [deploys, { refetch: refetchDeploys }] = queries.deploys.use(() => (admin ? undefined : false)); + const [vms, { refetch: refetchVms }] = queries.vms.use(() => (props.me.sections.includes("vms") ? undefined : false)); const timer = setInterval(() => [refetchLauncher, refetchHost, refetchStorage, refetchServices, refetchDeploys] .forEach((refetch) => refetch()), 60_000); - onCleanup(() => clearInterval(timer)); + const gpuGuest = () => lastGood(vms)()?.domains.find((vm): vm is Domain & { gpu: GpuShare } => vm.gpu !== null); + const gpuTimer = setInterval(() => gpuGuest() && refetchVms(), 5_000); + onCleanup(() => [timer, gpuTimer].forEach(clearInterval)); const info = lastGood(host); const pool = lastGood(storage); const apps = lastGood(launcher); @@ -365,6 +370,7 @@ function Dashboard(props: { me: Me }) { + (tick.host.arc === null ? "" : ` · ${bytes(tick.host.arc)} ZFS cache`), }))} /> {(vm) => }} now={(series) => { const value = latestOf(series[0]); return value === undefined ? undefined : { value: percent(value) }; diff --git a/dashboard/web/pages/VMs.tsx b/dashboard/web/pages/VMs.tsx index 2e8efaacaf471d8787248e679e3a51211eb0ed8f..fa5c391f822286fda345803594d205ca77f7d3fa 100644 --- a/dashboard/web/pages/VMs.tsx +++ b/dashboard/web/pages/VMs.tsx @@ -26,6 +26,7 @@ import { DetailedError, parseResponse } from "hono/client"; import { api, queries, reason, unconnected } from "../api.ts"; import { VMConsole } from "../components/VMConsole.tsx"; import { Checkbox } from "../components/Checkbox.tsx"; +import { GpuSwitch } from "../components/GpuSwitch.tsx"; import { Copy, CopyField } from "../components/Copy.tsx"; import { showConfirmDialog, showTextDialog } from "../components/Dialog.tsx"; import { ListPage } from "../components/ListPage.tsx"; @@ -353,6 +354,7 @@ function Hardware(props: { vm: Domain; refetch: () => unknown; username?: string {(pinned) => Pinned to threads {threads(pinned())}}
memory
{allocated(props.vm)}
+ {(gpu) => <>
GPU
}
guest user
{props.username}
{(hostname) => <>
hostname
}
diff --git a/dashboard/web/styles.css b/dashboard/web/styles.css index 4c52aad6d07c632becebd8f089590be802728d28..f5b11050f3a5db723381fa02e66b18593a259f5c 100644 --- a/dashboard/web/styles.css +++ b/dashboard/web/styles.css @@ -463,9 +463,12 @@ h2 { white-space: nowrap; transition: background-color 200ms, color 200ms, transform 200ms var(--ease-overshoot); } -.segmented > :is(button, a):hover { color: var(--text); background: var(--hover); } -.segmented > :is(button, a):active { transform: scale(0.94); } +.segmented > :is(button, a):hover:not(:disabled) { color: var(--text); background: var(--hover); } +.segmented > :is(button, a):active:not(:disabled) { transform: scale(0.94); } +.segmented > button:disabled { cursor: default; } +.segmented > button:disabled:not([aria-pressed="true"]) { opacity: 0.5; } .segmented :is(.pill, .ink) { position: absolute; pointer-events: none; } +.segmented :is(.pill, .ink)[hidden] { display: none; } .segmented .pill { z-index: 1; top: 2px; diff --git a/dashboard/web/types/vms.ts b/dashboard/web/types/vms.ts index 14d77e871014bea9cb73498d549170ec95ce5018..cfcfac2bf291de00f79de356182e07b7cdb09c80 100644 --- a/dashboard/web/types/vms.ts +++ b/dashboard/web/types/vms.ts @@ -1,3 +1,5 @@ +import type { Health } from "./model.ts"; + /** "shutdown" means a shutdown is under way; "unreachable" means the host did not answer. */ export type DomainState = "running" | "blocked" | "paused" | "shutdown" | "shutoff" | "crashed" | "pmsuspended" | "unreachable"; @@ -69,6 +71,17 @@ export interface Domain { /** `source` is the bridge or libvirt network; addresses come from DHCP leases. */ interfaces: { mac: string; source: string; addresses: string[] }[]; hostdevs: Hostdev[]; + /** Set on the guest the host's GPU passes through to, which has the GPU while it's on. */ + gpu: GpuShare | null; +} + +export interface GpuShare { + /** Health of the services that need the GPU; null while it's unknown. */ + ai: Health | null; + /** The side a switch under way is giving the GPU to. */ + switching: "games" | "ai" | null; + /** Why the latest switch failed, until another run starts. */ + failed: string | null; } export interface Installer { diff --git a/tools/dashboard-deploy-test.py b/tools/dashboard-deploy-test.py index 1b1623da0368805568bcd60cfd5e02e2dc31d363..b053a4772b759c5272dcd9eb58b375f247c48715 100644 --- a/tools/dashboard-deploy-test.py +++ b/tools/dashboard-deploy-test.py @@ -67,7 +67,8 @@ class DeploymentBoundary(unittest.TestCase): {"operation": "deploy.run", "id": "../../nomad.token"}, {"operation": "deploy.history", "path": "/etc/shadow"}] for action, target in [("sh", self.stage), ([], self.stage), ("destroy", "../escape"), - ("destroy", "--root"), ("rollback", self.version), ("rollback", "0"), ("rollback", [])]: + ("destroy", "--root"), ("rollback", self.version), ("rollback", "0"), ("rollback", []), + ("games", "--root"), ("ai", "../escape"), ("games", [])]: requests.append({"operation": "deploy.start", "action": action, "target": target}) with patch.object(runs.subprocess, "run") as executed: for request in requests: @@ -82,6 +83,8 @@ class DeploymentBoundary(unittest.TestCase): self.assertEqual(runs.command("start", "fixture")[1:], [str(self.snapshot / "tools/snowglobe.py"), "deploy", "fixture"]) self.assertEqual(runs.command("stop", "fixture"), ["nomad", "job", "stop", "-yes", "fixture"]) self.assertEqual(runs.command("restart", "fixture"), ["nomad", "job", "restart", "-yes", "fixture"]) + for mode in ["games", "ai"]: + self.assertEqual(runs.command(mode, "win11-gaming")[1:], [str(Path(runs.__file__).with_name("vms.py")), "gpu", mode, "win11-gaming"]) (self.snapshot / "tools/snowglobe.py").write_text("changed") for action, target in [("destroy", self.stage), ("deploy", self.version), ("rollback", "1"), ("start", "fixture")]: with self.subTest(action=action), self.assertRaisesRegex(ValueError, "contents changed"): diff --git a/tools/dashboard-run.py b/tools/dashboard-run.py index 7225235dfd5a535d3b6d3f88833aa56398863207..3ea36d29b032f81eacfbe279483da1c4ffab8443 100644 --- a/tools/dashboard-run.py +++ b/tools/dashboard-run.py @@ -25,7 +25,7 @@ FIELDS = { "deploy.secret.get": {"service", "key"}, "deploy.secret.set": {"service", "key", "value"}, "deploy.secret.rotate": {"service", "key"}, } -ACTIONS = {"deploy", "destroy", "rollback", "start", "stop", "restart", "secret-set", "secret-rotate"} +ACTIONS = {"deploy", "destroy", "rollback", "start", "stop", "restart", "secret-set", "secret-rotate", "games", "ai"} MAX_LOG = 1024 * 1024 MAX_METADATA = 65536 HOST_STATE = Path(os.environ.get("SNOWGLOBE_HOST_STATE_ROOT", "/var/lib/snowglobe/host")) @@ -161,6 +161,10 @@ def command(action, target, key=None): if version is None: raise Error(409, "No release is running. Deploy a release before starting this service.") return [sys.executable, str(release.check_release(version) / "tools/snowglobe.py"), "deploy", target] + if action in {"games", "ai"}: + if not isinstance(target, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", target): + raise Error(400, "Choose the VM that uses the GPU.") + return [sys.executable, str(Path(__file__).with_name("vms.py")), "gpu", action, target] if action == "rollback": saved = entry(target) version = saved["release"] diff --git a/tools/dashboard-vms-test.py b/tools/dashboard-vms-test.py index 5bb7771d5763464379c4e502677ad4e03c3442ec..4278bd0d838031d6ecbd98d33634814eb3dccaeb 100644 --- a/tools/dashboard-vms-test.py +++ b/tools/dashboard-vms-test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 """VM library and trust-boundary regressions, without a hypervisor.""" +import importlib import importlib.util import json import os @@ -582,5 +583,134 @@ class DisposableStorage(unittest.TestCase): self.assertTrue(all(call.args[0] == 'list' for call in virsh.call_args_list)) +GPU_GUEST = """ +
+
+""" + + +class GpuSwitch(unittest.TestCase): + """The switch against a fake libvirt, Nomad and sysfs, so the real GPU never moves.""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + root = Path(temporary.name) + for address, vendor, kind in [('0000:09:00.0', '0x10de', '0x030000'), ('0000:09:00.1', '0x10de', '0x040300'), + ('0000:0a:00.0', '0x1002', '0x030000')]: + (root / 'pci' / address).mkdir(parents=True) + (root / 'pci' / address / 'vendor').write_text(vendor + '\n') + (root / 'pci' / address / 'class').write_text(kind + '\n') + (root / 'nomad.token').write_text('token\n') + self.domains = {'testbox': '', 'win11-gaming': GPU_GUEST} + self.state, self.start_fails, self.shuts_down = 'shut off', False, True + self.jobs = {'local-ai': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'devices': ['/dev/nvidia0', '/dev/nvidiactl']}}]}]}, + 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}} + self.polls = {} + self.calls = [] + + def virsh(*args, timeout=None): + self.calls.append(('virsh', *args)) + if args[0] == 'list': + return '\n'.join(self.domains) + '\n' + if args[0] == 'dumpxml': + return self.domains[args[-1]] + if args[0] == 'domstate': + return self.state + if args[0] == 'start': + if self.start_fails: + raise vms.subprocess.CalledProcessError(1, 'virsh', stderr='device is busy') + self.state = 'running' + if args[0] == 'shutdown' and self.shuts_down: + self.state = 'shut off' + return '' + + def run(args, **kwargs): + self.calls.append(tuple(args)) + output = '' + if args[0] == 'nomad': + self.assertEqual(kwargs['env']['NOMAD_TOKEN'], 'token') + verb, job = args[2], args[-1] + if verb == 'status': + output = json.dumps([{'Summary': {'JobID': name}} for name in self.jobs]) + elif verb == 'inspect': + output = json.dumps(self.jobs[job]) + elif verb == 'stop': + self.jobs[job]['Stop'] = True + elif verb == 'allocs': + # A stopped job's allocation keeps running for one more poll. + self.polls[job] = self.polls.get(job, 0) + 1 + stopped = self.jobs[job]['Stop'] and self.polls[job] > 1 + output = json.dumps([{'ClientStatus': 'complete'}, {'ClientStatus': 'complete' if stopped else 'running'}]) + return SimpleNamespace(stdout=output, returncode=0) + + release = SimpleNamespace(STATE=root, current_release=lambda: 'a' * 16, check_release=lambda version: root / version) + clock = iter(range(0, 10**6, 50)) + for context in [patch.object(vms, 'PCI', root / 'pci'), patch.object(vms, 'virsh', side_effect=virsh), + patch.object(vms.subprocess, 'run', side_effect=run), patch.object(vms.time, 'sleep'), + patch.object(vms.time, 'monotonic', side_effect=lambda: next(clock)), + patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]: + context.start() + self.addCleanup(context.stop) + self.deploy = (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', '--gpu') + + def test_the_gpu_guest_is_the_one_passing_through_an_nvidia_display(self): + self.assertTrue(vms.passes_gpu(vms.ET.fromstring(GPU_GUEST))) + for function, bus in [('0x1', '0x09'), ('0x0', '0x0a'), ('0x0', '0x0b')]: + other = GPU_GUEST.split('
' + with self.subTest(bus=bus, function=function): + self.assertFalse(vms.passes_gpu(vms.ET.fromstring(other))) + self.assertEqual(vms.gpu_guest(), 'win11-gaming') + del self.domains['win11-gaming'] + self.assertIsNone(vms.gpu_guest()) + + def test_games_stops_only_gpu_jobs_and_waits_for_them_before_starting_the_guest(self): + vms.switch_gpu('games', 'win11-gaming') + self.assertEqual(self.state, 'running') + stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai')) + start = self.calls.index(('virsh', 'start', 'win11-gaming')) + self.assertLess(stop, start) + self.assertEqual(self.polls['local-ai'], 2) + self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'jellyfin'), self.calls) + self.assertNotIn(self.deploy, self.calls) + + def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_ai(self): + self.start_fails = True + with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. AI has it again."): + vms.switch_gpu('games', 'win11-gaming') + self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy)) + + def test_ai_shuts_the_guest_down_before_deploying_the_gpu_services(self): + self.state = 'running' + vms.switch_gpu('ai', 'win11-gaming') + self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy)) + self.assertFalse(any(call[0] == 'nomad' for call in self.calls)) + + def test_a_guest_that_wont_shut_down_keeps_the_gpu(self): + self.state, self.shuts_down = 'running', False + with self.assertRaisesRegex(ValueError, "didn't shut down"): + vms.switch_gpu('ai', 'win11-gaming') + self.assertNotIn(self.deploy, self.calls) + + def test_only_the_gpu_guest_switches_and_only_toward_the_other_side(self): + with self.assertRaisesRegex(ValueError, "testbox doesn't use the GPU"): + vms.switch_gpu('games', 'testbox') + self.state = 'running' + with self.assertRaisesRegex(ValueError, 'already has the GPU'): + vms.switch_gpu('games', 'win11-gaming') + self.assertFalse(any(call[0] in {'nomad', vms.sys.executable} or call[:2] == ('virsh', 'start') for call in self.calls)) + + def test_deploys_leave_gpu_services_alone_while_the_guest_has_the_gpu(self): + import snowglobe + services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}] + self.assertEqual([snowglobe.gpu(item) for item in services], [True, False]) + self.assertIsNone(snowglobe.gpu_holder(services)) + self.state = 'running' + self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming') + self.calls.clear() + self.assertIsNone(snowglobe.gpu_holder(services[1:])) + self.assertEqual(self.calls, []) + + if __name__ == '__main__': unittest.main() diff --git a/tools/snowglobe.py b/tools/snowglobe.py index 8ff991ca07b33711da2fd0a750c5685ff26e5a43..fa57fabc9668b197118fbebeaca4b919af8f2712 100644 --- a/tools/snowglobe.py +++ b/tools/snowglobe.py @@ -55,6 +55,19 @@ def dependencies(data): return set(data["dependsOn"]) | {item["provider"] for item in data["inputs"].values() if item["provider"] != "snowglobe"} +def gpu(data): + return any(device.startswith("/dev/nvidia") for task in data["containers"].values() for device in task["devices"]) + + +def gpu_holder(data): + """The guest holding the GPU, which the services that need it must leave alone.""" + if not any(gpu(item) for item in data): + return None + vms = __import__("vms") + guest = vms.gpu_guest() + return guest if guest and vms.virsh("domstate", guest) != "shut off" else None + + def ordered(data): pending = {item["id"]: item for item in data} result = [] @@ -980,7 +993,10 @@ def main(): parser.add_argument("--media-root") parser.add_argument("--env", action="append", default=[]) parser.add_argument("--key", action="append", default=[]) + parser.add_argument("--gpu", action="store_true") args = parser.parse_args() + if args.gpu and (args.mode != "deploy" or args.name): + parser.error("--gpu deploys every service that needs the GPU, without a service name") if args.computer and (args.mode != "stage" or args.name != "dashboard"): parser.error("--computer requires stage dashboard") if args.mode == "stage" and args.name == "dashboard": @@ -1262,7 +1278,7 @@ def main(): if args.name and args.name not in definitions: raise ValueError(f"unknown service: {args.name}") if not args.name and args.mode == "deploy": - names = [name for name in names if definitions[name]["containers"]] + names = [name for name in names if definitions[name]["containers"] and (gpu(definitions[name]) or not args.gpu)] selected = set(names) while True: required = selected | set().union(*(dependencies(definitions[name]) for name in selected)) @@ -1282,7 +1298,10 @@ def main(): for item in data: submit(item, "validate", definitions) elif args.mode == "check": + holder = gpu_holder(data) for item in data: + if holder and gpu(item): + continue for task in item["containers"].values(): if task.get("http") and task["http"].get("hostname"): check_http(task["http"]["hostname"], task["http"]["checkPath"], task["http"]["tlsInternal"]) @@ -1314,7 +1333,11 @@ def main(): bootstrap(data) elif args.mode == "deploy": bootstrap(data) + holder = gpu_holder(data) for item in data: + if holder and gpu(item): + print(f"Skipping {item['id']} while {holder} has the GPU", flush=True) + continue provision_inputs(item, definitions) provision(item) prepare(item) diff --git a/tools/vms.py b/tools/vms.py index fd4d3d4a34f3a06613335d4acb7ccda78a06ad57..8714afd4f4954b7f62fe44a37aeb1ad64af4952e 100644 --- a/tools/vms.py +++ b/tools/vms.py @@ -19,6 +19,7 @@ import xml.etree.ElementTree as ET DISKS = Path("/srv/vm") +PCI = Path("/sys/bus/pci/devices") AI_DISKS = Path(os.environ["SNOWGLOBE_VM_AI_DISKS_ROOT"]) if os.environ.get("SNOWGLOBE_VM_AI_DISKS_ROOT") else None IMAGES = Path(os.environ.get("SNOWGLOBE_VM_IMAGES_ROOT", "/srv/clover/Media/vm")) PRESETS = Path(os.environ.get("SNOWGLOBE_VM_PRESETS_ROOT", str(IMAGES / "Presets"))) @@ -390,10 +391,82 @@ def domains(*, computers=False): "serial": root.find("./devices/console[@type='pty']/target[@type='serial']") is not None, "interfaces": interfaces, "hostdevs": [], + "gpu": passes_gpu(root), }) return result +def passes_gpu(root): + """Whether the domain passes through an NVIDIA display controller.""" + for address in root.findall("./devices/hostdev[@type='pci']/source/address"): + device = PCI / "{:04x}:{:02x}:{:02x}.{:x}".format(*(int(address.get(field), 16) for field in ("domain", "bus", "slot", "function"))) + try: + if (device / "vendor").read_text().strip() == "0x10de" and (device / "class").read_text().startswith("0x03"): + return True + except FileNotFoundError: + continue + return False + + +def gpu_guest(): + return next((name for name in virsh("list", "--all", "--name").splitlines() + if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None) + + +def switch_gpu(mode, name): + """Hands the GPU to the guest (games) or to the services that need it (ai).""" + if gpu_guest() != name: + raise ValueError(f"{name} doesn't use the GPU.") + release = import_module("release") + deploy = [sys.executable, str(release.check_release(release.current_release()) / "tools/snowglobe.py"), "deploy", "--gpu"] + if mode == "ai": + if virsh("domstate", name) != "shut off": + print(f"Shutting down {name}", flush=True) + virsh("shutdown", name) + if not wait(lambda: virsh("domstate", name) == "shut off", 300): + raise ValueError(f"{name} didn't shut down. Close its apps or force it off, then switch again.") + try: + subprocess.run(deploy, check=True) + except subprocess.CalledProcessError: + raise ValueError("AI couldn't start. Open the Local AI service to see why.") from None + return + if virsh("domstate", name) != "shut off": + raise ValueError(f"{name} already has the GPU.") + environment = {**os.environ, "NOMAD_TOKEN": (release.STATE / "nomad.token").read_text().strip()} + + def nomad(*args): + return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True, env=environment).stdout + + def needs_gpu(job): + spec = json.loads(nomad("job", "inspect", "-json", job)) + return not spec.get("Stop") and any(device.startswith("/dev/nvidia") for group in spec["TaskGroups"] + for task in group["Tasks"] for device in (task["Config"] or {}).get("devices") or []) + + jobs = [job for job in (entry["Summary"]["JobID"] for entry in json.loads(nomad("job", "status", "-json"))) if needs_gpu(job)] + for job in jobs: + print(f"Stopping {job}", flush=True) + nomad("job", "stop", "-yes", job) + if not wait(lambda: not any(alloc["ClientStatus"] in {"pending", "running"} + for job in jobs for alloc in json.loads(nomad("job", "allocs", "-json", job))), 300): + raise ValueError("AI didn't stop. Open the Local AI service to see why.") + print(f"Starting {name}", flush=True) + try: + virsh("start", name) + except subprocess.CalledProcessError as error: + print(error.stderr, flush=True) + restored = subprocess.run(deploy).returncode == 0 + raise ValueError(f"{name} couldn't take the GPU. " + ("AI has it again." if restored else "AI couldn't start either. Open the Local AI service to see why.")) from None + + +def wait(ready, seconds): + deadline = time.monotonic() + seconds + while not ready(): + if time.monotonic() > deadline: + return False + time.sleep(2) + return True + + def windows_setup(name): for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]: try: @@ -1178,6 +1251,10 @@ def main(): if __name__ == "__main__": try: + if sys.argv[1] == "gpu" and len(sys.argv) == 4 and sys.argv[2] in {"games", "ai"}: + ensure_name(sys.argv[3]) + switch_gpu(sys.argv[2], sys.argv[3]) + sys.exit(0) print(json.dumps(main())) except ValueError as failure: print(str(failure), file=sys.stderr) -- 2.54.1