authoravatarclover caruso<git@paperclover.net>2026-11-28 20:40:41-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 03:08:43-08:00
log5f66b6183205a3a66af26f549340b3ed5f83f186
treef8f909e182705c9e19fe0c7aec283b8998815875
parentb70609bde48d15ac1c36df711fdce8684046a60e
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

14 files changed, 413 insertions(+), 6 deletions(-)

dashboard/src/apps.rs+65
...@@ -94,6 +94,57 @@ async fn vm_call(action: &str, payload: Option<Value>) -> Result<Value> {...@@ -94,6 +94,57 @@ async fn vm_call(action: &str, payload: Option<Value>) -> Result<Value> {
94 host::call(request).await94 host::call(request).await
95}95}
9696
97/// Who has the GPU. The guest's power state says games; the GPU services' health says AI.
98async fn gpu(app: Arc<App>, name: &str) -> Value {
99 let ai = core::scan(app).await.ok().map(|scan| {
100 let mut health = scan
101 .value
102 .as_object()
103 .into_iter()
104 .flat_map(|jobs| jobs.values())
105 .filter(|entry| {
106 array(&entry["job"]["TaskGroups"])
107 .iter()
108 .flat_map(|group| array(&group["Tasks"]))
109 .any(|task| {
110 array(&task["Config"]["devices"])
111 .iter()
112 .any(|device| string(device).starts_with("/dev/nvidia"))
113 })
114 })
115 .map(|entry| string(&entry["health"]).to_owned());
116 health
117 .find(|health| health != "stopped")
118 .unwrap_or_else(|| "stopped".into())
119 });
120 let run = host::call(json!({"operation":"deploy.last"}))
121 .await
122 .unwrap_or_default();
123 let ours = matches!(run["action"].as_str(), Some("games" | "ai")) && run["target"] == name;
124 let failed = if !ours || run["code"].is_null() || run["code"] == 0 {
125 Value::Null
126 } else if run["code"] == 2 {
127 // The switch exits 2 with a message for the person on its last line.
128 let lines = host::call(json!({"operation":"deploy.run","id":run["id"]}))
129 .await
130 .unwrap_or_default();
131 array(&lines["lines"])
132 .iter()
133 .rev()
134 .nth(1)
135 .cloned()
136 .unwrap_or(json!("Couldn't switch the GPU."))
137 } else {
138 json!("Couldn't switch the GPU.")
139 };
140 let switching = if ours && run["code"].is_null() {
141 run["action"].clone()
142 } else {
143 Value::Null
144 };
145 json!({"ai":ai,"switching":switching,"failed":failed})
146}
147
97fn vm_name(name: &str) -> Result<()> {148fn vm_name(name: &str) -> Result<()> {
98 if regex::Regex::new(r"^[a-z0-9][a-z0-9-]{0,62}$")149 if regex::Regex::new(r"^[a-z0-9][a-z0-9-]{0,62}$")
99 .unwrap()150 .unwrap()
...@@ -309,6 +360,11 @@ pub async fn route(...@@ -309,6 +360,11 @@ pub async fn route(
309 .get(string(&domain["name"]))360 .get(string(&domain["name"]))
310 .cloned()361 .cloned()
311 .unwrap_or(Value::Null);362 .unwrap_or(Value::Null);
363 domain["gpu"] = if domain["gpu"] == true {
364 gpu(app.clone(), string(&domain["name"])).await
365 } else {
366 Value::Null
367 };
312 }368 }
313 json!({"node":values[0],"domains":values[1],"library":values[2],"canPublish":array(&me["sections"]).iter().any(|section| section == "admin")})369 json!({"node":values[0],"domains":values[1],"library":values[2],"canPublish":array(&me["sections"]).iter().any(|section| section == "admin")})
314 }370 }
...@@ -369,6 +425,15 @@ pub async fn route(...@@ -369,6 +425,15 @@ pub async fn route(
369 ["media"] if method == Method::PUT => {425 ["media"] if method == Method::PUT => {
370 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;426 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;
371 }427 }
428 ["gpu"] if method == Method::POST => {
429 let mode = body["mode"]
430 .as_str()
431 .filter(|mode| ["games", "ai"].contains(mode))
432 .ok_or_else(|| Error::new(400, "Choose games or AI."))?;
433 host::call(json!({"operation":"deploy.start","action":mode,"target":name}))
434 .await?;
435 app.cache.invalidate("deploys");
436 }
372 ["preset"] if method == Method::POST => {437 ["preset"] if method == Method::POST => {
373 need(me, "admin")?;438 need(me, "admin")?;
374 vm_call("preset", Some(json!({"name":name,"id":body["id"],"os":body["os"],"description":body["description"]}))).await?;439 vm_call("preset", Some(json!({"name":name,"id":body["id"],"os":body["os"],"description":body["description"]}))).await?;
dashboard/src/deploys.rs+2
...@@ -227,6 +227,8 @@ fn display_run(run: Value, history: &Value) -> Result<Value> {...@@ -227,6 +227,8 @@ fn display_run(run: Value, history: &Value) -> Result<Value> {
227 "secret-set" => format!("set {target}/{}", string(&run["key"])),227 "secret-set" => format!("set {target}/{}", string(&run["key"])),
228 "secret-rotate" => format!("rotate {target}/{}", string(&run["key"])),228 "secret-rotate" => format!("rotate {target}/{}", string(&run["key"])),
229 action @ ("start" | "stop" | "restart") => format!("{action} {target}"),229 action @ ("start" | "stop" | "restart") => format!("{action} {target}"),
230 "games" => "switch GPU to games".to_owned(),
231 "ai" => "switch GPU to AI".to_owned(),
230 "deploy" => "deploy main".to_owned(),232 "deploy" => "deploy main".to_owned(),
231 "promote" => format!("promote {target}"),233 "promote" => format!("promote {target}"),
232 "destroy" => format!("destroy {target}"),234 "destroy" => format!("destroy {target}"),
dashboard/web/api.contract.ts+3
...@@ -333,6 +333,9 @@ export type Api = Hono<{}, {...@@ -333,6 +333,9 @@ export type Api = Hono<{}, {
333 "/vms/:name/preset": {333 "/vms/:name/preset": {
334 $post: Endpoint<null, { param: { name: string }; json: { id: string; os: string; description: string } }, 204, "body">;334 $post: Endpoint<null, { param: { name: string }; json: { id: string; os: string; description: string } }, 204, "body">;
335 };335 };
336 "/vms/:name/gpu": {
337 $post: Endpoint<null, { param: { name: string }; json: { mode: "games" | "ai" } }, 204, "body">;
338 };
336 "/vms/:name/:action": {339 "/vms/:name/:action": {
337 $post: Endpoint<null, { param: { name: string; action: "start" | "destroy" | "shutdown" | "reboot" | "resume" | "suspend"; }; }, 204, "body">;340 $post: Endpoint<null, { param: { name: string; action: "start" | "destroy" | "shutdown" | "reboot" | "resume" | "suspend"; }; }, 204, "body">;
338 };341 };
dashboard/web/components/GpuSwitch.css created+4
...@@ -0,0 +1,4 @@
1.gpu-switch { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }
2.gpu-progress { min-width: 0; font-size: 12px; }
3.gpu-progress .status-label { display: flex; min-width: 0; }
4.gpu-progress .status-label > svg { flex: none; }
dashboard/web/components/GpuSwitch.tsx created+72
...@@ -0,0 +1,72 @@
1import { parseResponse } from "hono/client";
2import { createSignal, Show } from "solid-js";
3import { api, reason } from "../api.ts";
4import type { Domain, GpuShare } from "../types/vms.ts";
5import { showConfirmDialog } from "./Dialog.tsx";
6import { type StatusKind, StatusLabel } from "./Status.tsx";
7import { TabBar } from "./TabBar.tsx";
8import { toast } from "./Toast.tsx";
9import "./GpuSwitch.css";
10
11type Side = NonNullable<GpuShare["switching"]>;
12
13const loading = (ai: GpuShare["ai"]) => ai === "starting" || ai === "deploying" || ai === "restarting";
14
15/** Gives the GPU to `vm` for games or to AI. Who has it comes from the guest's power state and AI's health. */
16export function GpuSwitch(props: { vm: Domain & { gpu: GpuShare }; refetch: () => unknown }) {
17 const [sending, setSending] = createSignal(false);
18 const off = () => props.vm.state === "shutoff" || props.vm.state === "crashed";
19 const aiOn = () => props.vm.gpu.ai !== null && props.vm.gpu.ai !== "stopped";
20 const side = (): Side | null => props.vm.gpu.switching ?? (!off() ? "games" : aiOn() ? "ai" : null);
21 const busy = () => sending() || props.vm.gpu.switching !== null;
22 const progress = (): [StatusKind, string] | null => {
23 const { switching, ai, failed } = props.vm.gpu;
24 if (switching === "games") return ["starting", aiOn() ? "stopping AI…" : `starting ${props.vm.name}…`];
25 if (switching === "ai") return ["starting", off() ? "loading AI…" : `shutting down ${props.vm.name}…`];
26 if (failed) return ["down", failed];
27 if (!off()) return null;
28 if (loading(ai)) return ["starting", "loading AI…"];
29 if (ai === "down" || ai === "degraded") return [ai, `AI is ${ai}`];
30 return ai === "stopped" ? ["stopped", "idle"] : null;
31 };
32 const send = async (mode: Side) => {
33 setSending(true);
34 try {
35 await parseResponse(api.vms[":name"].gpu.$post({ param: { name: props.vm.name }, json: { mode } }));
36 await props.refetch();
37 } finally {
38 setSending(false);
39 }
40 };
41 const choose = (mode: Side) => {
42 if (mode === "ai" && !off()) {
43 showConfirmDialog({
44 title: "Switch the GPU to AI?",
45 description: `${props.vm.name} shuts down first. Anything unsaved in it is lost.`,
46 confirmLabel: "switch to AI",
47 destructive: true,
48 onConfirm: () => send(mode),
49 });
50 } else if (mode === "games" && aiOn()) {
51 showConfirmDialog({
52 title: "Switch the GPU to games?",
53 description: "AI stops, along with replies it's writing, and takes a while to load again.",
54 confirmLabel: "switch to games",
55 onConfirm: () => send(mode),
56 });
57 } else {
58 send(mode).catch((failure) => toast(`Couldn't switch the GPU. ${reason(failure)}`));
59 }
60 };
61 return (
62 <span class="gpu-switch" aria-busy={busy()}>
63 <TabBar label="GPU for">
64 <button aria-pressed={side() === "games"} disabled={busy() || side() === "games"} onClick={() => choose("games")}>games</button>
65 <button aria-pressed={side() === "ai"} disabled={busy() || side() === "ai"} onClick={() => choose("ai")}>AI</button>
66 </TabBar>
67 <Show when={progress()}>
68 {(now) => <span class="gpu-progress" role="status" data-tip={now()[1]}><StatusLabel health={now()[0]}>{now()[1]}</StatusLabel></span>}
69 </Show>
70 </span>
71 );
72}
dashboard/web/pages/Overview.tsx+7-1
...@@ -9,11 +9,13 @@ import ShieldCheck from "lucide-solid/icons/shield-check";...@@ -9,11 +9,13 @@ import ShieldCheck from "lucide-solid/icons/shield-check";
9import Trash from "lucide-solid/icons/trash";9import Trash from "lucide-solid/icons/trash";
10import Undo2 from "lucide-solid/icons/undo-2";10import Undo2 from "lucide-solid/icons/undo-2";
11import { createMemo, createResource, createRoot, createSignal, For, type JSX, onCleanup, Show } from "solid-js";11import { createMemo, createResource, createRoot, createSignal, For, type JSX, onCleanup, Show } from "solid-js";
12import type { Domain, GpuShare } from "../types/vms.ts";
12import { type Health, type HostInfo, type Live, type Me, type Series, type ServiceSummary, trouble } from "../types/model.ts";13import { type Health, type HostInfo, type Live, type Me, type Series, type ServiceSummary, trouble } from "../types/model.ts";
13import { api, queries, reason } from "../api.ts";14import { api, queries, reason } from "../api.ts";
14import { Ago } from "../components/Ago.tsx";15import { Ago } from "../components/Ago.tsx";
15import { AppIcon } from "../components/AppIcon.tsx";16import { AppIcon } from "../components/AppIcon.tsx";
16import { Donut } from "../components/Donut.tsx";17import { Donut } from "../components/Donut.tsx";
18import { GpuSwitch } from "../components/GpuSwitch.tsx";
17import { lastGood, Loaded } from "../components/Loaded.tsx";19import { lastGood, Loaded } from "../components/Loaded.tsx";
18import { Meter } from "../components/Meter.tsx";20import { Meter } from "../components/Meter.tsx";
19import { OpenApp } from "../components/OpenApp.tsx";21import { OpenApp } from "../components/OpenApp.tsx";
...@@ -146,9 +148,12 @@ function Dashboard(props: { me: Me }) {...@@ -146,9 +148,12 @@ function Dashboard(props: { me: Me }) {
146 const [storage, { refetch: refetchStorage }] = queries.storage.use();148 const [storage, { refetch: refetchStorage }] = queries.storage.use();
147 const [services, { refetch: refetchServices }] = queries.services.use();149 const [services, { refetch: refetchServices }] = queries.services.use();
148 const [deploys, { refetch: refetchDeploys }] = queries.deploys.use(() => (admin ? undefined : false));150 const [deploys, { refetch: refetchDeploys }] = queries.deploys.use(() => (admin ? undefined : false));
151 const [vms, { refetch: refetchVms }] = queries.vms.use(() => (props.me.sections.includes("vms") ? undefined : false));
149 const timer = setInterval(() => [refetchLauncher, refetchHost, refetchStorage, refetchServices, refetchDeploys]152 const timer = setInterval(() => [refetchLauncher, refetchHost, refetchStorage, refetchServices, refetchDeploys]
150 .forEach((refetch) => refetch()), 60_000);153 .forEach((refetch) => refetch()), 60_000);
151 onCleanup(() => clearInterval(timer));154 const gpuGuest = () => lastGood(vms)()?.domains.find((vm): vm is Domain & { gpu: GpuShare } => vm.gpu !== null);
155 const gpuTimer = setInterval(() => gpuGuest() && refetchVms(), 5_000);
156 onCleanup(() => [timer, gpuTimer].forEach(clearInterval));
152 const info = lastGood(host);157 const info = lastGood(host);
153 const pool = lastGood(storage);158 const pool = lastGood(storage);
154 const apps = lastGood(launcher);159 const apps = lastGood(launcher);
...@@ -365,6 +370,7 @@ function Dashboard(props: { me: Me }) {...@@ -365,6 +370,7 @@ function Dashboard(props: { me: Me }) {
365 + (tick.host.arc === null ? "" : ` · ${bytes(tick.host.arc)} ZFS cache`),370 + (tick.host.arc === null ? "" : ` · ${bytes(tick.host.arc)} ZFS cache`),
366 }))} />371 }))} />
367 <Strip title="gpu" metric="host.gpu" range={range()} format={percent} max={100} height={80}372 <Strip title="gpu" metric="host.gpu" range={range()} format={percent} max={100} height={80}
373 tabs={<Show when={gpuGuest()}>{(vm) => <GpuSwitch vm={vm()} refetch={refetchVms} />}</Show>}
368 now={(series) => {374 now={(series) => {
369 const value = latestOf(series[0]);375 const value = latestOf(series[0]);
370 return value === undefined ? undefined : { value: percent(value) };376 return value === undefined ? undefined : { value: percent(value) };
dashboard/web/pages/VMs.tsx+2
...@@ -26,6 +26,7 @@ import { DetailedError, parseResponse } from "hono/client";...@@ -26,6 +26,7 @@ import { DetailedError, parseResponse } from "hono/client";
26import { api, queries, reason, unconnected } from "../api.ts";26import { api, queries, reason, unconnected } from "../api.ts";
27import { VMConsole } from "../components/VMConsole.tsx";27import { VMConsole } from "../components/VMConsole.tsx";
28import { Checkbox } from "../components/Checkbox.tsx";28import { Checkbox } from "../components/Checkbox.tsx";
29import { GpuSwitch } from "../components/GpuSwitch.tsx";
29import { Copy, CopyField } from "../components/Copy.tsx";30import { Copy, CopyField } from "../components/Copy.tsx";
30import { showConfirmDialog, showTextDialog } from "../components/Dialog.tsx";31import { showConfirmDialog, showTextDialog } from "../components/Dialog.tsx";
31import { ListPage } from "../components/ListPage.tsx";32import { ListPage } from "../components/ListPage.tsx";
...@@ -353,6 +354,7 @@ function Hardware(props: { vm: Domain; refetch: () => unknown; username?: string...@@ -353,6 +354,7 @@ function Hardware(props: { vm: Domain; refetch: () => unknown; username?: string
353 <Show when={props.vm.pinned}>{(pinned) => <span class="vm-resource-usage">Pinned to threads {threads(pinned())}</span>}</Show>354 <Show when={props.vm.pinned}>{(pinned) => <span class="vm-resource-usage">Pinned to threads {threads(pinned())}</span>}</Show>
354 </dd>355 </dd>
355 <dt>memory</dt><dd>{allocated(props.vm)}</dd>356 <dt>memory</dt><dd>{allocated(props.vm)}</dd>
357 <Show when={props.vm.gpu}>{(gpu) => <><dt>GPU</dt><dd><GpuSwitch vm={{ ...props.vm, gpu: gpu() }} refetch={props.refetch} /></dd></>}</Show>
356 <Show when={props.username}><dt>guest user</dt><dd>{props.username}</dd></Show>358 <Show when={props.username}><dt>guest user</dt><dd>{props.username}</dd></Show>
357 <Show when={props.hostname}>{(hostname) => <><dt>hostname</dt><dd><Copy value={hostname()} /></dd></>}</Show>359 <Show when={props.hostname}>{(hostname) => <><dt>hostname</dt><dd><Copy value={hostname()} /></dd></>}</Show>
358 <Show when={props.vm.capabilities.includes("edit")}>360 <Show when={props.vm.capabilities.includes("edit")}>
dashboard/web/styles.css+5-2
...@@ -463,9 +463,12 @@ h2 {...@@ -463,9 +463,12 @@ h2 {
463 white-space: nowrap;463 white-space: nowrap;
464 transition: background-color 200ms, color 200ms, transform 200ms var(--ease-overshoot);464 transition: background-color 200ms, color 200ms, transform 200ms var(--ease-overshoot);
465}465}
466.segmented > :is(button, a):hover { color: var(--text); background: var(--hover); }466.segmented > :is(button, a):hover:not(:disabled) { color: var(--text); background: var(--hover); }
467.segmented > :is(button, a):active { transform: scale(0.94); }467.segmented > :is(button, a):active:not(:disabled) { transform: scale(0.94); }
468.segmented > button:disabled { cursor: default; }
469.segmented > button:disabled:not([aria-pressed="true"]) { opacity: 0.5; }
468.segmented :is(.pill, .ink) { position: absolute; pointer-events: none; }470.segmented :is(.pill, .ink) { position: absolute; pointer-events: none; }
471.segmented :is(.pill, .ink)[hidden] { display: none; }
469.segmented .pill {472.segmented .pill {
470 z-index: 1;473 z-index: 1;
471 top: 2px;474 top: 2px;
dashboard/web/types/vms.ts+13
...@@ -1,3 +1,5 @@...@@ -1,3 +1,5 @@
1import type { Health } from "./model.ts";
2
1/** "shutdown" means a shutdown is under way; "unreachable" means the host did not answer. */3/** "shutdown" means a shutdown is under way; "unreachable" means the host did not answer. */
2export type DomainState = "running" | "blocked" | "paused" | "shutdown" | "shutoff" | "crashed" | "pmsuspended" | "unreachable";4export type DomainState = "running" | "blocked" | "paused" | "shutdown" | "shutoff" | "crashed" | "pmsuspended" | "unreachable";
35
...@@ -69,6 +71,17 @@ export interface Domain {...@@ -69,6 +71,17 @@ export interface Domain {
69 /** `source` is the bridge or libvirt network; addresses come from DHCP leases. */71 /** `source` is the bridge or libvirt network; addresses come from DHCP leases. */
70 interfaces: { mac: string; source: string; addresses: string[] }[];72 interfaces: { mac: string; source: string; addresses: string[] }[];
71 hostdevs: Hostdev[];73 hostdevs: Hostdev[];
74 /** Set on the guest the host's GPU passes through to, which has the GPU while it's on. */
75 gpu: GpuShare | null;
76}
77
78export interface GpuShare {
79 /** Health of the services that need the GPU; null while it's unknown. */
80 ai: Health | null;
81 /** The side a switch under way is giving the GPU to. */
82 switching: "games" | "ai" | null;
83 /** Why the latest switch failed, until another run starts. */
84 failed: string | null;
72}85}
7386
74export interface Installer {87export interface Installer {
tools/dashboard-deploy-test.py+4-1
...@@ -67,7 +67,8 @@ class DeploymentBoundary(unittest.TestCase):...@@ -67,7 +67,8 @@ class DeploymentBoundary(unittest.TestCase):
67 {"operation": "deploy.run", "id": "../../nomad.token"},67 {"operation": "deploy.run", "id": "../../nomad.token"},
68 {"operation": "deploy.history", "path": "/etc/shadow"}]68 {"operation": "deploy.history", "path": "/etc/shadow"}]
69 for action, target in [("sh", self.stage), ([], self.stage), ("destroy", "../escape"),69 for action, target in [("sh", self.stage), ([], self.stage), ("destroy", "../escape"),
70 ("destroy", "--root"), ("rollback", self.version), ("rollback", "0"), ("rollback", [])]:70 ("destroy", "--root"), ("rollback", self.version), ("rollback", "0"), ("rollback", []),
71 ("games", "--root"), ("ai", "../escape"), ("games", [])]:
71 requests.append({"operation": "deploy.start", "action": action, "target": target})72 requests.append({"operation": "deploy.start", "action": action, "target": target})
72 with patch.object(runs.subprocess, "run") as executed:73 with patch.object(runs.subprocess, "run") as executed:
73 for request in requests:74 for request in requests:
...@@ -82,6 +83,8 @@ class DeploymentBoundary(unittest.TestCase):...@@ -82,6 +83,8 @@ class DeploymentBoundary(unittest.TestCase):
82 self.assertEqual(runs.command("start", "fixture")[1:], [str(self.snapshot / "tools/snowglobe.py"), "deploy", "fixture"])83 self.assertEqual(runs.command("start", "fixture")[1:], [str(self.snapshot / "tools/snowglobe.py"), "deploy", "fixture"])
83 self.assertEqual(runs.command("stop", "fixture"), ["nomad", "job", "stop", "-yes", "fixture"])84 self.assertEqual(runs.command("stop", "fixture"), ["nomad", "job", "stop", "-yes", "fixture"])
84 self.assertEqual(runs.command("restart", "fixture"), ["nomad", "job", "restart", "-yes", "fixture"])85 self.assertEqual(runs.command("restart", "fixture"), ["nomad", "job", "restart", "-yes", "fixture"])
86 for mode in ["games", "ai"]:
87 self.assertEqual(runs.command(mode, "win11-gaming")[1:], [str(Path(runs.__file__).with_name("vms.py")), "gpu", mode, "win11-gaming"])
85 (self.snapshot / "tools/snowglobe.py").write_text("changed")88 (self.snapshot / "tools/snowglobe.py").write_text("changed")
86 for action, target in [("destroy", self.stage), ("deploy", self.version), ("rollback", "1"), ("start", "fixture")]:89 for action, target in [("destroy", self.stage), ("deploy", self.version), ("rollback", "1"), ("start", "fixture")]:
87 with self.subTest(action=action), self.assertRaisesRegex(ValueError, "contents changed"):90 with self.subTest(action=action), self.assertRaisesRegex(ValueError, "contents changed"):
tools/dashboard-run.py+5-1
...@@ -25,7 +25,7 @@ FIELDS = {...@@ -25,7 +25,7 @@ FIELDS = {
25 "deploy.secret.get": {"service", "key"}, "deploy.secret.set": {"service", "key", "value"},25 "deploy.secret.get": {"service", "key"}, "deploy.secret.set": {"service", "key", "value"},
26 "deploy.secret.rotate": {"service", "key"},26 "deploy.secret.rotate": {"service", "key"},
27}27}
28ACTIONS = {"deploy", "destroy", "rollback", "start", "stop", "restart", "secret-set", "secret-rotate"}28ACTIONS = {"deploy", "destroy", "rollback", "start", "stop", "restart", "secret-set", "secret-rotate", "games", "ai"}
29MAX_LOG = 1024 * 102429MAX_LOG = 1024 * 1024
30MAX_METADATA = 6553630MAX_METADATA = 65536
31HOST_STATE = Path(os.environ.get("SNOWGLOBE_HOST_STATE_ROOT", "/var/lib/snowglobe/host"))31HOST_STATE = Path(os.environ.get("SNOWGLOBE_HOST_STATE_ROOT", "/var/lib/snowglobe/host"))
...@@ -161,6 +161,10 @@ def command(action, target, key=None):...@@ -161,6 +161,10 @@ def command(action, target, key=None):
161 if version is None:161 if version is None:
162 raise Error(409, "No release is running. Deploy a release before starting this service.")162 raise Error(409, "No release is running. Deploy a release before starting this service.")
163 return [sys.executable, str(release.check_release(version) / "tools/snowglobe.py"), "deploy", target]163 return [sys.executable, str(release.check_release(version) / "tools/snowglobe.py"), "deploy", target]
164 if action in {"games", "ai"}:
165 if not isinstance(target, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", target):
166 raise Error(400, "Choose the VM that uses the GPU.")
167 return [sys.executable, str(Path(__file__).with_name("vms.py")), "gpu", action, target]
164 if action == "rollback":168 if action == "rollback":
165 saved = entry(target)169 saved = entry(target)
166 version = saved["release"]170 version = saved["release"]
tools/dashboard-vms-test.py+130
...@@ -1,5 +1,6 @@...@@ -1,5 +1,6 @@
1#!/usr/bin/env python31#!/usr/bin/env python3
2"""VM library and trust-boundary regressions, without a hypervisor."""2"""VM library and trust-boundary regressions, without a hypervisor."""
3import importlib
3import importlib.util4import importlib.util
4import json5import json
5import os6import os
...@@ -582,5 +583,134 @@ class DisposableStorage(unittest.TestCase):...@@ -582,5 +583,134 @@ class DisposableStorage(unittest.TestCase):
582 self.assertTrue(all(call.args[0] == 'list' for call in virsh.call_args_list))583 self.assertTrue(all(call.args[0] == 'list' for call in virsh.call_args_list))
583584
584585
586GPU_GUEST = """<domain><devices>
587 <hostdev mode="subsystem" type="pci" managed="yes"><source><address domain="0x0000" bus="0x09" slot="0x00" function="0x1"/></source></hostdev>
588 <hostdev mode="subsystem" type="pci" managed="yes"><source><address domain="0x0000" bus="0x09" slot="0x00" function="0x0"/></source></hostdev>
589</devices></domain>"""
590
591
592class GpuSwitch(unittest.TestCase):
593 """The switch against a fake libvirt, Nomad and sysfs, so the real GPU never moves."""
594
595 def setUp(self):
596 temporary = tempfile.TemporaryDirectory()
597 self.addCleanup(temporary.cleanup)
598 root = Path(temporary.name)
599 for address, vendor, kind in [('0000:09:00.0', '0x10de', '0x030000'), ('0000:09:00.1', '0x10de', '0x040300'),
600 ('0000:0a:00.0', '0x1002', '0x030000')]:
601 (root / 'pci' / address).mkdir(parents=True)
602 (root / 'pci' / address / 'vendor').write_text(vendor + '\n')
603 (root / 'pci' / address / 'class').write_text(kind + '\n')
604 (root / 'nomad.token').write_text('token\n')
605 self.domains = {'testbox': '<domain><devices/></domain>', 'win11-gaming': GPU_GUEST}
606 self.state, self.start_fails, self.shuts_down = 'shut off', False, True
607 self.jobs = {'local-ai': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'devices': ['/dev/nvidia0', '/dev/nvidiactl']}}]}]},
608 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}}
609 self.polls = {}
610 self.calls = []
611
612 def virsh(*args, timeout=None):
613 self.calls.append(('virsh', *args))
614 if args[0] == 'list':
615 return '\n'.join(self.domains) + '\n'
616 if args[0] == 'dumpxml':
617 return self.domains[args[-1]]
618 if args[0] == 'domstate':
619 return self.state
620 if args[0] == 'start':
621 if self.start_fails:
622 raise vms.subprocess.CalledProcessError(1, 'virsh', stderr='device is busy')
623 self.state = 'running'
624 if args[0] == 'shutdown' and self.shuts_down:
625 self.state = 'shut off'
626 return ''
627
628 def run(args, **kwargs):
629 self.calls.append(tuple(args))
630 output = ''
631 if args[0] == 'nomad':
632 self.assertEqual(kwargs['env']['NOMAD_TOKEN'], 'token')
633 verb, job = args[2], args[-1]
634 if verb == 'status':
635 output = json.dumps([{'Summary': {'JobID': name}} for name in self.jobs])
636 elif verb == 'inspect':
637 output = json.dumps(self.jobs[job])
638 elif verb == 'stop':
639 self.jobs[job]['Stop'] = True
640 elif verb == 'allocs':
641 # A stopped job's allocation keeps running for one more poll.
642 self.polls[job] = self.polls.get(job, 0) + 1
643 stopped = self.jobs[job]['Stop'] and self.polls[job] > 1
644 output = json.dumps([{'ClientStatus': 'complete'}, {'ClientStatus': 'complete' if stopped else 'running'}])
645 return SimpleNamespace(stdout=output, returncode=0)
646
647 release = SimpleNamespace(STATE=root, current_release=lambda: 'a' * 16, check_release=lambda version: root / version)
648 clock = iter(range(0, 10**6, 50))
649 for context in [patch.object(vms, 'PCI', root / 'pci'), patch.object(vms, 'virsh', side_effect=virsh),
650 patch.object(vms.subprocess, 'run', side_effect=run), patch.object(vms.time, 'sleep'),
651 patch.object(vms.time, 'monotonic', side_effect=lambda: next(clock)),
652 patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]:
653 context.start()
654 self.addCleanup(context.stop)
655 self.deploy = (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', '--gpu')
656
657 def test_the_gpu_guest_is_the_one_passing_through_an_nvidia_display(self):
658 self.assertTrue(vms.passes_gpu(vms.ET.fromstring(GPU_GUEST)))
659 for function, bus in [('0x1', '0x09'), ('0x0', '0x0a'), ('0x0', '0x0b')]:
660 other = GPU_GUEST.split('<hostdev', 2)[0] + f'<hostdev type="pci"><source><address domain="0x0000" bus="{bus}" slot="0x00" function="{function}"/></source></hostdev></devices></domain>'
661 with self.subTest(bus=bus, function=function):
662 self.assertFalse(vms.passes_gpu(vms.ET.fromstring(other)))
663 self.assertEqual(vms.gpu_guest(), 'win11-gaming')
664 del self.domains['win11-gaming']
665 self.assertIsNone(vms.gpu_guest())
666
667 def test_games_stops_only_gpu_jobs_and_waits_for_them_before_starting_the_guest(self):
668 vms.switch_gpu('games', 'win11-gaming')
669 self.assertEqual(self.state, 'running')
670 stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai'))
671 start = self.calls.index(('virsh', 'start', 'win11-gaming'))
672 self.assertLess(stop, start)
673 self.assertEqual(self.polls['local-ai'], 2)
674 self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'jellyfin'), self.calls)
675 self.assertNotIn(self.deploy, self.calls)
676
677 def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_ai(self):
678 self.start_fails = True
679 with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. AI has it again."):
680 vms.switch_gpu('games', 'win11-gaming')
681 self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy))
682
683 def test_ai_shuts_the_guest_down_before_deploying_the_gpu_services(self):
684 self.state = 'running'
685 vms.switch_gpu('ai', 'win11-gaming')
686 self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy))
687 self.assertFalse(any(call[0] == 'nomad' for call in self.calls))
688
689 def test_a_guest_that_wont_shut_down_keeps_the_gpu(self):
690 self.state, self.shuts_down = 'running', False
691 with self.assertRaisesRegex(ValueError, "didn't shut down"):
692 vms.switch_gpu('ai', 'win11-gaming')
693 self.assertNotIn(self.deploy, self.calls)
694
695 def test_only_the_gpu_guest_switches_and_only_toward_the_other_side(self):
696 with self.assertRaisesRegex(ValueError, "testbox doesn't use the GPU"):
697 vms.switch_gpu('games', 'testbox')
698 self.state = 'running'
699 with self.assertRaisesRegex(ValueError, 'already has the GPU'):
700 vms.switch_gpu('games', 'win11-gaming')
701 self.assertFalse(any(call[0] in {'nomad', vms.sys.executable} or call[:2] == ('virsh', 'start') for call in self.calls))
702
703 def test_deploys_leave_gpu_services_alone_while_the_guest_has_the_gpu(self):
704 import snowglobe
705 services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}]
706 self.assertEqual([snowglobe.gpu(item) for item in services], [True, False])
707 self.assertIsNone(snowglobe.gpu_holder(services))
708 self.state = 'running'
709 self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming')
710 self.calls.clear()
711 self.assertIsNone(snowglobe.gpu_holder(services[1:]))
712 self.assertEqual(self.calls, [])
713
714
585if __name__ == '__main__':715if __name__ == '__main__':
586 unittest.main()716 unittest.main()
tools/snowglobe.py+24-1
...@@ -55,6 +55,19 @@ def dependencies(data):...@@ -55,6 +55,19 @@ def dependencies(data):
55 return set(data["dependsOn"]) | {item["provider"] for item in data["inputs"].values() if item["provider"] != "snowglobe"}55 return set(data["dependsOn"]) | {item["provider"] for item in data["inputs"].values() if item["provider"] != "snowglobe"}
5656
5757
58def gpu(data):
59 return any(device.startswith("/dev/nvidia") for task in data["containers"].values() for device in task["devices"])
60
61
62def gpu_holder(data):
63 """The guest holding the GPU, which the services that need it must leave alone."""
64 if not any(gpu(item) for item in data):
65 return None
66 vms = __import__("vms")
67 guest = vms.gpu_guest()
68 return guest if guest and vms.virsh("domstate", guest) != "shut off" else None
69
70
58def ordered(data):71def ordered(data):
59 pending = {item["id"]: item for item in data}72 pending = {item["id"]: item for item in data}
60 result = []73 result = []
...@@ -980,7 +993,10 @@ def main():...@@ -980,7 +993,10 @@ def main():
980 parser.add_argument("--media-root")993 parser.add_argument("--media-root")
981 parser.add_argument("--env", action="append", default=[])994 parser.add_argument("--env", action="append", default=[])
982 parser.add_argument("--key", action="append", default=[])995 parser.add_argument("--key", action="append", default=[])
996 parser.add_argument("--gpu", action="store_true")
983 args = parser.parse_args()997 args = parser.parse_args()
998 if args.gpu and (args.mode != "deploy" or args.name):
999 parser.error("--gpu deploys every service that needs the GPU, without a service name")
984 if args.computer and (args.mode != "stage" or args.name != "dashboard"):1000 if args.computer and (args.mode != "stage" or args.name != "dashboard"):
985 parser.error("--computer requires stage dashboard")1001 parser.error("--computer requires stage dashboard")
986 if args.mode == "stage" and args.name == "dashboard":1002 if args.mode == "stage" and args.name == "dashboard":
...@@ -1262,7 +1278,7 @@ def main():...@@ -1262,7 +1278,7 @@ def main():
1262 if args.name and args.name not in definitions:1278 if args.name and args.name not in definitions:
1263 raise ValueError(f"unknown service: {args.name}")1279 raise ValueError(f"unknown service: {args.name}")
1264 if not args.name and args.mode == "deploy":1280 if not args.name and args.mode == "deploy":
1265 names = [name for name in names if definitions[name]["containers"]]1281 names = [name for name in names if definitions[name]["containers"] and (gpu(definitions[name]) or not args.gpu)]
1266 selected = set(names)1282 selected = set(names)
1267 while True:1283 while True:
1268 required = selected | set().union(*(dependencies(definitions[name]) for name in selected))1284 required = selected | set().union(*(dependencies(definitions[name]) for name in selected))
...@@ -1282,7 +1298,10 @@ def main():...@@ -1282,7 +1298,10 @@ def main():
1282 for item in data:1298 for item in data:
1283 submit(item, "validate", definitions)1299 submit(item, "validate", definitions)
1284 elif args.mode == "check":1300 elif args.mode == "check":
1301 holder = gpu_holder(data)
1285 for item in data:1302 for item in data:
1303 if holder and gpu(item):
1304 continue
1286 for task in item["containers"].values():1305 for task in item["containers"].values():
1287 if task.get("http") and task["http"].get("hostname"):1306 if task.get("http") and task["http"].get("hostname"):
1288 check_http(task["http"]["hostname"], task["http"]["checkPath"], task["http"]["tlsInternal"])1307 check_http(task["http"]["hostname"], task["http"]["checkPath"], task["http"]["tlsInternal"])
...@@ -1314,7 +1333,11 @@ def main():...@@ -1314,7 +1333,11 @@ def main():
1314 bootstrap(data)1333 bootstrap(data)
1315 elif args.mode == "deploy":1334 elif args.mode == "deploy":
1316 bootstrap(data)1335 bootstrap(data)
1336 holder = gpu_holder(data)
1317 for item in data:1337 for item in data:
1338 if holder and gpu(item):
1339 print(f"Skipping {item['id']} while {holder} has the GPU", flush=True)
1340 continue
1318 provision_inputs(item, definitions)1341 provision_inputs(item, definitions)
1319 provision(item)1342 provision(item)
1320 prepare(item)1343 prepare(item)
tools/vms.py+77
...@@ -19,6 +19,7 @@ import xml.etree.ElementTree as ET...@@ -19,6 +19,7 @@ import xml.etree.ElementTree as ET
1919
2020
21DISKS = Path("/srv/vm")21DISKS = Path("/srv/vm")
22PCI = Path("/sys/bus/pci/devices")
22AI_DISKS = Path(os.environ["SNOWGLOBE_VM_AI_DISKS_ROOT"]) if os.environ.get("SNOWGLOBE_VM_AI_DISKS_ROOT") else None23AI_DISKS = Path(os.environ["SNOWGLOBE_VM_AI_DISKS_ROOT"]) if os.environ.get("SNOWGLOBE_VM_AI_DISKS_ROOT") else None
23IMAGES = Path(os.environ.get("SNOWGLOBE_VM_IMAGES_ROOT", "/srv/clover/Media/vm"))24IMAGES = Path(os.environ.get("SNOWGLOBE_VM_IMAGES_ROOT", "/srv/clover/Media/vm"))
24PRESETS = Path(os.environ.get("SNOWGLOBE_VM_PRESETS_ROOT", str(IMAGES / "Presets")))25PRESETS = Path(os.environ.get("SNOWGLOBE_VM_PRESETS_ROOT", str(IMAGES / "Presets")))
...@@ -390,10 +391,82 @@ def domains(*, computers=False):...@@ -390,10 +391,82 @@ def domains(*, computers=False):
390 "serial": root.find("./devices/console[@type='pty']/target[@type='serial']") is not None,391 "serial": root.find("./devices/console[@type='pty']/target[@type='serial']") is not None,
391 "interfaces": interfaces,392 "interfaces": interfaces,
392 "hostdevs": [],393 "hostdevs": [],
394 "gpu": passes_gpu(root),
393 })395 })
394 return result396 return result
395397
396398
399def passes_gpu(root):
400 """Whether the domain passes through an NVIDIA display controller."""
401 for address in root.findall("./devices/hostdev[@type='pci']/source/address"):
402 device = PCI / "{:04x}:{:02x}:{:02x}.{:x}".format(*(int(address.get(field), 16) for field in ("domain", "bus", "slot", "function")))
403 try:
404 if (device / "vendor").read_text().strip() == "0x10de" and (device / "class").read_text().startswith("0x03"):
405 return True
406 except FileNotFoundError:
407 continue
408 return False
409
410
411def gpu_guest():
412 return next((name for name in virsh("list", "--all", "--name").splitlines()
413 if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None)
414
415
416def switch_gpu(mode, name):
417 """Hands the GPU to the guest (games) or to the services that need it (ai)."""
418 if gpu_guest() != name:
419 raise ValueError(f"{name} doesn't use the GPU.")
420 release = import_module("release")
421 deploy = [sys.executable, str(release.check_release(release.current_release()) / "tools/snowglobe.py"), "deploy", "--gpu"]
422 if mode == "ai":
423 if virsh("domstate", name) != "shut off":
424 print(f"Shutting down {name}", flush=True)
425 virsh("shutdown", name)
426 if not wait(lambda: virsh("domstate", name) == "shut off", 300):
427 raise ValueError(f"{name} didn't shut down. Close its apps or force it off, then switch again.")
428 try:
429 subprocess.run(deploy, check=True)
430 except subprocess.CalledProcessError:
431 raise ValueError("AI couldn't start. Open the Local AI service to see why.") from None
432 return
433 if virsh("domstate", name) != "shut off":
434 raise ValueError(f"{name} already has the GPU.")
435 environment = {**os.environ, "NOMAD_TOKEN": (release.STATE / "nomad.token").read_text().strip()}
436
437 def nomad(*args):
438 return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True, env=environment).stdout
439
440 def needs_gpu(job):
441 spec = json.loads(nomad("job", "inspect", "-json", job))
442 return not spec.get("Stop") and any(device.startswith("/dev/nvidia") for group in spec["TaskGroups"]
443 for task in group["Tasks"] for device in (task["Config"] or {}).get("devices") or [])
444
445 jobs = [job for job in (entry["Summary"]["JobID"] for entry in json.loads(nomad("job", "status", "-json"))) if needs_gpu(job)]
446 for job in jobs:
447 print(f"Stopping {job}", flush=True)
448 nomad("job", "stop", "-yes", job)
449 if not wait(lambda: not any(alloc["ClientStatus"] in {"pending", "running"}
450 for job in jobs for alloc in json.loads(nomad("job", "allocs", "-json", job))), 300):
451 raise ValueError("AI didn't stop. Open the Local AI service to see why.")
452 print(f"Starting {name}", flush=True)
453 try:
454 virsh("start", name)
455 except subprocess.CalledProcessError as error:
456 print(error.stderr, flush=True)
457 restored = subprocess.run(deploy).returncode == 0
458 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
459
460
461def wait(ready, seconds):
462 deadline = time.monotonic() + seconds
463 while not ready():
464 if time.monotonic() > deadline:
465 return False
466 time.sleep(2)
467 return True
468
469
397def windows_setup(name):470def windows_setup(name):
398 for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]:471 for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]:
399 try:472 try:
...@@ -1178,6 +1251,10 @@ def main():...@@ -1178,6 +1251,10 @@ def main():
11781251
1179if __name__ == "__main__":1252if __name__ == "__main__":
1180 try:1253 try:
1254 if sys.argv[1] == "gpu" and len(sys.argv) == 4 and sys.argv[2] in {"games", "ai"}:
1255 ensure_name(sys.argv[3])
1256 switch_gpu(sys.argv[2], sys.argv[3])
1257 sys.exit(0)
1181 print(json.dumps(main()))1258 print(json.dumps(main()))
1182 except ValueError as failure:1259 except ValueError as failure:
1183 print(str(failure), file=sys.stderr)1260 print(str(failure), file=sys.stderr)