authoravatarclover caruso<git@paperclover.net>2026-11-29 19:41:18-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 03:08:43-08:00
log5854c1a79d82d57034a5fc32a2b96c4cc24a904e
tree891e7ef47f359c52d55ac167f11c408a2a5d328d
parent5f66b6183205a3a66af26f549340b3ed5f83f186
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fusion: add Fusion Studio Render Node and generalize the GPU switch

Adds service/fusion running Blackmagic Fusion Render Node 21.1 headless under Xvfb with host networking, LAN-only firewall rules (1144 and 49152-49159), and /srv/clover mounted at /Volumes/clover so comps resolve without path maps. Generalizes the 3090 GPU switch from Games/AI to Games plus any managed GPU service (Fusion, Local AI). Deploys never move the GPU: GPU services other than the current holder are registered stopped in Nomad. Assisted-by: claude-opus-5.5 Assisted-by: gemini-4-neon

15 files changed, 308 insertions(+), 134 deletions(-)

dashboard/src/apps.rs+22-21
...@@ -94,16 +94,16 @@ async fn vm_call(action: &str, payload: Option<Value>) -> Result<Value> {...@@ -94,16 +94,16 @@ 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.97/// Who has the GPU. The guest's power state says games; the GPU services' health says which service.
98async fn gpu(app: Arc<App>, name: &str) -> Value {98async fn gpu(app: Arc<App>) -> Value {
99 let ai = core::scan(app).await.ok().map(|scan| {99 let found = tokio::try_join!(core::managed(), core::scan(app)).ok();
100 let mut health = scan100 let services = found.map(|(managed, scan)| {
101 .value101 scan.value
102 .as_object()102 .as_object()
103 .into_iter()103 .into_iter()
104 .flat_map(|jobs| jobs.values())104 .flat_map(|jobs| jobs.iter())
105 .filter(|entry| {105 .filter(|(id, entry)| {
106 array(&entry["job"]["TaskGroups"])106 managed.contains(id) && array(&entry["job"]["TaskGroups"])
107 .iter()107 .iter()
108 .flat_map(|group| array(&group["Tasks"]))108 .flat_map(|group| array(&group["Tasks"]))
109 .any(|task| {109 .any(|task| {
...@@ -112,15 +112,13 @@ async fn gpu(app: Arc<App>, name: &str) -> Value {...@@ -112,15 +112,13 @@ async fn gpu(app: Arc<App>, name: &str) -> Value {
112 .any(|device| string(device).starts_with("/dev/nvidia"))112 .any(|device| string(device).starts_with("/dev/nvidia"))
113 })113 })
114 })114 })
115 .map(|entry| string(&entry["health"]).to_owned());115 .map(|(id, entry)| json!({"id":id,"name":entry["job"]["Meta"]["snowglobe_name"].as_str().unwrap_or(id),"health":entry["health"]}))
116 health116 .collect::<Vec<_>>()
117 .find(|health| health != "stopped")
118 .unwrap_or_else(|| "stopped".into())
119 });117 });
120 let run = host::call(json!({"operation":"deploy.last"}))118 let run = host::call(json!({"operation":"deploy.last"}))
121 .await119 .await
122 .unwrap_or_default();120 .unwrap_or_default();
123 let ours = matches!(run["action"].as_str(), Some("games" | "ai")) && run["target"] == name;121 let ours = run["action"] == "gpu";
124 let failed = if !ours || run["code"].is_null() || run["code"] == 0 {122 let failed = if !ours || run["code"].is_null() || run["code"] == 0 {
125 Value::Null123 Value::Null
126 } else if run["code"] == 2 {124 } else if run["code"] == 2 {
...@@ -138,11 +136,11 @@ async fn gpu(app: Arc<App>, name: &str) -> Value {...@@ -138,11 +136,11 @@ async fn gpu(app: Arc<App>, name: &str) -> Value {
138 json!("Couldn't switch the GPU.")136 json!("Couldn't switch the GPU.")
139 };137 };
140 let switching = if ours && run["code"].is_null() {138 let switching = if ours && run["code"].is_null() {
141 run["action"].clone()139 run["target"].clone()
142 } else {140 } else {
143 Value::Null141 Value::Null
144 };142 };
145 json!({"ai":ai,"switching":switching,"failed":failed})143 json!({"services":services,"switching":switching,"failed":failed})
146}144}
147145
148fn vm_name(name: &str) -> Result<()> {146fn vm_name(name: &str) -> Result<()> {
...@@ -361,7 +359,7 @@ pub async fn route(...@@ -361,7 +359,7 @@ pub async fn route(
361 .cloned()359 .cloned()
362 .unwrap_or(Value::Null);360 .unwrap_or(Value::Null);
363 domain["gpu"] = if domain["gpu"] == true {361 domain["gpu"] = if domain["gpu"] == true {
364 gpu(app.clone(), string(&domain["name"])).await362 gpu(app.clone()).await
365 } else {363 } else {
366 Value::Null364 Value::Null
367 };365 };
...@@ -426,11 +424,14 @@ pub async fn route(...@@ -426,11 +424,14 @@ pub async fn route(
426 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;424 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;
427 }425 }
428 ["gpu"] if method == Method::POST => {426 ["gpu"] if method == Method::POST => {
429 let mode = body["mode"]427 // Access to the guest that passes the GPU through is what grants the switch.
430 .as_str()428 if !array(&vm_call("domains", None).await?)
431 .filter(|mode| ["games", "ai"].contains(mode))429 .iter()
432 .ok_or_else(|| Error::new(400, "Choose games or AI."))?;430 .any(|domain| domain["name"] == *name && domain["gpu"] == true)
433 host::call(json!({"operation":"deploy.start","action":mode,"target":name}))431 {
432 return Err(Error::new(400, format!("{name} doesn't use the GPU.")));
433 }
434 host::call(json!({"operation":"deploy.start","action":"gpu","target":body["side"]}))
434 .await?;435 .await?;
435 app.cache.invalidate("deploys");436 app.cache.invalidate("deploys");
436 }437 }
dashboard/src/deploys.rs+3-2
...@@ -227,8 +227,9 @@ fn display_run(run: Value, history: &Value) -> Result<Value> {...@@ -227,8 +227,9 @@ 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(),230 "gpu" => format!("switch GPU to {target}"),
231 "ai" => "switch GPU to AI".to_owned(),231 // Runs recorded before switches named their side as the target.
232 action @ ("games" | "ai") => format!("switch GPU to {action}"),
232 "deploy" => "deploy main".to_owned(),233 "deploy" => "deploy main".to_owned(),
233 "promote" => format!("promote {target}"),234 "promote" => format!("promote {target}"),
234 "destroy" => format!("destroy {target}"),235 "destroy" => format!("destroy {target}"),
dashboard/web/api.contract.ts+1-1
...@@ -334,7 +334,7 @@ export type Api = Hono<{}, {...@@ -334,7 +334,7 @@ export type Api = Hono<{}, {
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": {336 "/vms/:name/gpu": {
337 $post: Endpoint<null, { param: { name: string }; json: { mode: "games" | "ai" } }, 204, "body">;337 $post: Endpoint<null, { param: { name: string }; json: { side: string } }, 204, "body">;
338 };338 };
339 "/vms/:name/:action": {339 "/vms/:name/:action": {
340 $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">;
dashboard/web/components/GpuSwitch.tsx+42-29
...@@ -1,6 +1,7 @@...@@ -1,6 +1,7 @@
1import { parseResponse } from "hono/client";1import { parseResponse } from "hono/client";
2import { createSignal, Show } from "solid-js";2import { createSignal, For, Show } from "solid-js";
3import { api, reason } from "../api.ts";3import { api, reason } from "../api.ts";
4import type { Health } from "../types/model.ts";
4import type { Domain, GpuShare } from "../types/vms.ts";5import type { Domain, GpuShare } from "../types/vms.ts";
5import { showConfirmDialog } from "./Dialog.tsx";6import { showConfirmDialog } from "./Dialog.tsx";
6import { type StatusKind, StatusLabel } from "./Status.tsx";7import { type StatusKind, StatusLabel } from "./Status.tsx";
...@@ -8,61 +9,73 @@ import { TabBar } from "./TabBar.tsx";...@@ -8,61 +9,73 @@ import { TabBar } from "./TabBar.tsx";
8import { toast } from "./Toast.tsx";9import { toast } from "./Toast.tsx";
9import "./GpuSwitch.css";10import "./GpuSwitch.css";
1011
11type Side = NonNullable<GpuShare["switching"]>;12const loading = (health: Health) => health === "starting" || health === "deploying" || health === "restarting";
1213
13const loading = (ai: GpuShare["ai"]) => ai === "starting" || ai === "deploying" || ai === "restarting";14/** Gives the GPU to `vm` for games or to one service. Who has it comes from the guest's power state and the services' health. */
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 }) {15export function GpuSwitch(props: { vm: Domain & { gpu: GpuShare }; refetch: () => unknown }) {
17 const [sending, setSending] = createSignal(false);16 const [sending, setSending] = createSignal(false);
18 const off = () => props.vm.state === "shutoff" || props.vm.state === "crashed";17 const off = () => props.vm.state === "shutoff" || props.vm.state === "crashed";
19 const aiOn = () => props.vm.gpu.ai !== null && props.vm.gpu.ai !== "stopped";18 const services = () => props.vm.gpu.services ?? [];
20 const side = (): Side | null => props.vm.gpu.switching ?? (!off() ? "games" : aiOn() ? "ai" : null);19 const holder = () => services().find((service) => service.health !== "stopped");
20 const name = (side: string) => services().find((service) => service.id === side)?.name ?? side;
21 const side = () => props.vm.gpu.switching ?? (!off() ? "games" : holder()?.id ?? null);
21 const busy = () => sending() || props.vm.gpu.switching !== null;22 const busy = () => sending() || props.vm.gpu.switching !== null;
22 const progress = (): [StatusKind, string] | null => {23 const progress = (): [StatusKind, string] | null => {
23 const { switching, ai, failed } = props.vm.gpu;24 const { switching, failed } = props.vm.gpu;
24 if (switching === "games") return ["starting", aiOn() ? "stopping AI…" : `starting ${props.vm.name}…`];25 const running = holder();
25 if (switching === "ai") return ["starting", off() ? "loading AI…" : `shutting down ${props.vm.name}…`];26 if (switching === "games") return ["starting", running ? `stopping ${running.name}…` : `starting ${props.vm.name}…`];
27 if (switching) {
28 if (!off()) return ["starting", `shutting down ${props.vm.name}…`];
29 return ["starting", running && running.id !== switching ? `stopping ${running.name}…` : `loading ${name(switching)}…`];
30 }
26 if (failed) return ["down", failed];31 if (failed) return ["down", failed];
27 if (!off()) return null;32 if (!off() || props.vm.gpu.services === null) return null;
28 if (loading(ai)) return ["starting", "loading AI…"];33 if (!running) return ["stopped", "idle"];
29 if (ai === "down" || ai === "degraded") return [ai, `AI is ${ai}`];34 if (loading(running.health)) return ["starting", `loading ${running.name}…`];
30 return ai === "stopped" ? ["stopped", "idle"] : null;35 if (running.health === "down" || running.health === "degraded") return [running.health, `${running.name} is ${running.health}`];
36 return null;
31 };37 };
32 const send = async (mode: Side) => {38 const send = async (to: string) => {
33 setSending(true);39 setSending(true);
34 try {40 try {
35 await parseResponse(api.vms[":name"].gpu.$post({ param: { name: props.vm.name }, json: { mode } }));41 await parseResponse(api.vms[":name"].gpu.$post({ param: { name: props.vm.name }, json: { side: to } }));
36 await props.refetch();42 await props.refetch();
37 } finally {43 } finally {
38 setSending(false);44 setSending(false);
39 }45 }
40 };46 };
41 const choose = (mode: Side) => {47 const choose = (to: string) => {
42 if (mode === "ai" && !off()) {48 const label = to === "games" ? "games" : name(to);
49 const running = holder();
50 if (to !== "games" && !off()) {
43 showConfirmDialog({51 showConfirmDialog({
44 title: "Switch the GPU to AI?",52 title: `Switch the GPU to ${label}?`,
45 description: `${props.vm.name} shuts down first. Anything unsaved in it is lost.`,53 description: `${props.vm.name} shuts down first. Anything unsaved in it is lost.`,
46 confirmLabel: "switch to AI",54 confirmLabel: `switch to ${label}`,
47 destructive: true,55 destructive: true,
48 onConfirm: () => send(mode),56 onConfirm: () => send(to),
49 });57 });
50 } else if (mode === "games" && aiOn()) {58 } else if (running && running.id !== to) {
51 showConfirmDialog({59 showConfirmDialog({
52 title: "Switch the GPU to games?",60 title: `Switch the GPU to ${label}?`,
53 description: "AI stops, along with replies it's writing, and takes a while to load again.",61 description: `${running.name} stops, along with anything it's working on.`,
54 confirmLabel: "switch to games",62 confirmLabel: `switch to ${label}`,
55 onConfirm: () => send(mode),63 onConfirm: () => send(to),
56 });64 });
57 } else {65 } else {
58 send(mode).catch((failure) => toast(`Couldn't switch the GPU. ${reason(failure)}`));66 send(to).catch((failure) => toast(`Couldn't switch the GPU. ${reason(failure)}`));
59 }67 }
60 };68 };
61 return (69 return (
62 <span class="gpu-switch" aria-busy={busy()}>70 <span class="gpu-switch" aria-busy={busy()}>
63 <TabBar label="GPU for">71 <TabBar label="GPU for">
64 <button aria-pressed={side() === "games"} disabled={busy() || side() === "games"} onClick={() => choose("games")}>games</button>72 <For each={[{ id: "games", name: "games" }, ...services()]}>
65 <button aria-pressed={side() === "ai"} disabled={busy() || side() === "ai"} onClick={() => choose("ai")}>AI</button>73 {(option) => (
74 <button aria-pressed={side() === option.id} disabled={busy() || side() === option.id} onClick={() => choose(option.id)}>
75 {option.name}
76 </button>
77 )}
78 </For>
66 </TabBar>79 </TabBar>
67 <Show when={progress()}>80 <Show when={progress()}>
68 {(now) => <span class="gpu-progress" role="status" data-tip={now()[1]}><StatusLabel health={now()[0]}>{now()[1]}</StatusLabel></span>}81 {(now) => <span class="gpu-progress" role="status" data-tip={now()[1]}><StatusLabel health={now()[0]}>{now()[1]}</StatusLabel></span>}
dashboard/web/types/vms.ts+4-4
...@@ -76,10 +76,10 @@ export interface Domain {...@@ -76,10 +76,10 @@ export interface Domain {
76}76}
7777
78export interface GpuShare {78export interface GpuShare {
79 /** Health of the services that need the GPU; null while it's unknown. */79 /** The services that need the GPU; null while they're unknown. */
80 ai: Health | null;80 services: { id: string; name: string; health: Health }[] | null;
81 /** The side a switch under way is giving the GPU to. */81 /** The side a switch under way is giving the GPU to: "games" or a service ID. */
82 switching: "games" | "ai" | null;82 switching: string | null;
83 /** Why the latest switch failed, until another run starts. */83 /** Why the latest switch failed, until another run starts. */
84 failed: string | null;84 failed: string | null;
85}85}
nixos/snowglobe.nix+3
...@@ -31,6 +31,9 @@ in...@@ -31,6 +31,9 @@ in
31 networking.firewall.allowedUDPPortRanges = [{ from = xmppNetwork.relay_first; to = xmppNetwork.relay_last; }];31 networking.firewall.allowedUDPPortRanges = [{ from = xmppNetwork.relay_first; to = xmppNetwork.relay_last; }];
32 networking.firewall.extraCommands = lib.concatMapStrings ({ address, prefixLength, ... }: ''32 networking.firewall.extraCommands = lib.concatMapStrings ({ address, prefixLength, ... }: ''
33 iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p tcp --dport 445 -j nixos-fw-accept33 iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p tcp --dport 445 -j nixos-fw-accept
34 # Fusion Render Node
35 iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p tcp -m multiport --dports 1144,49152:49159 -j nixos-fw-accept
36 iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p udp -m multiport --dports 1144,49152:49159 -j nixos-fw-accept
34 '') config.networking.interfaces.enp4s0.ipv4.addresses + ''37 '') config.networking.interfaces.enp4s0.ipv4.addresses + ''
35 iptables -A nixos-fw -i enp4s0 -s ${(builtins.fromJSON (builtins.readFile ../config/mac-studio-sandbox.json)).guestAddress}/32 -p tcp --dport 2049 -j nixos-fw-accept38 iptables -A nixos-fw -i enp4s0 -s ${(builtins.fromJSON (builtins.readFile ../config/mac-studio-sandbox.json)).guestAddress}/32 -p tcp --dport 2049 -j nixos-fw-accept
36 ip6tables -A nixos-fw -i enp4s0 -s fe80::/10 -p tcp --dport 445 -j nixos-fw-accept39 ip6tables -A nixos-fw -i enp4s0 -s fe80::/10 -p tcp --dport 445 -j nixos-fw-accept
service/fusion/Dockerfile created+40
...@@ -0,0 +1,40 @@
1FROM docker.io/rockylinux/rockylinux@sha256:7b2eba7b6bf1c5c93f343c5f03a582e4e32ffd7c19187010c6aa2a848bce295a AS installer
2
3# Fusion Studio 21.1 for Linux; render nodes must match the Fusion Studio version that submits to them.
4ARG DOWNLOAD=c2ad9534bf5746cd8a9db063f1cad9b1
5ARG SHA256=a19bb7c95eb0c00abf96f7d236a195da6729f07e9f3b81bbe7fc15869eba816f
6ARG RUN=Blackmagic_Fusion_Render_Node_Linux_21.1_installer.run
7RUN dnf -y install epel-release && dnf -y install python3 squashfs-tools && dnf clean all
8# Studio downloads need no registration details beyond a country.
9RUN python3 -I -c 'import hashlib, json, sys, urllib.request, zipfile; \
10 agent = {"User-Agent": "Mozilla/5.0"}; \
11 request = urllib.request.Request("https://www.blackmagicdesign.com/api/register/us/download/" + sys.argv[1], json.dumps({"country": "us", "downloadOnly": True}).encode(), {**agent, "Content-Type": "application/json"}); \
12 url = urllib.request.urlopen(request).read().decode(); \
13 digest = hashlib.sha256(); \
14 out = open("/tmp/fusion.zip", "wb"); \
15 response = urllib.request.urlopen(urllib.request.Request(url, headers=agent)); \
16 [(digest.update(chunk), out.write(chunk)) for chunk in iter(lambda: response.read(1 << 20), b"")]; \
17 out.close(); \
18 assert digest.hexdigest() == sys.argv[2], digest.hexdigest(); \
19 zipfile.ZipFile("/tmp/fusion.zip").extract(sys.argv[3], "/tmp")' "$DOWNLOAD" "$SHA256" "$RUN" \
20 && rm /tmp/fusion.zip
21# The installer is an AppImage; its squashfs payload starts where the ELF runtime's section headers end.
22RUN offset=$(python3 -I -c 'import struct, sys; header = open(sys.argv[1], "rb").read(64); \
23 print(struct.unpack_from("<Q", header, 0x28)[0] + struct.unpack_from("<H", header, 0x3A)[0] * struct.unpack_from("<H", header, 0x3C)[0])' "/tmp/$RUN") \
24 && mkdir -p /opt/BlackmagicDesign && unsquashfs -o "$offset" -d /opt/BlackmagicDesign/FusionRenderNode21 "/tmp/$RUN" \
25 && rm "/tmp/$RUN" \
26 && cd /opt/BlackmagicDesign/FusionRenderNode21 \
27 && rm -f AppRun FusionInstaller FusionInstaller.desktop filelist.txt \
28 && chmod -R a+rX,go-w .
29
30FROM docker.io/rockylinux/rockylinux@sha256:7b2eba7b6bf1c5c93f343c5f03a582e4e32ffd7c19187010c6aa2a848bce295a
31# The installer's own Rocky/RHEL dependency list, plus Xvfb for its Qt GUI thread and an OpenCL loader.
32RUN dnf -y install epel-release && dnf -y install --setopt=install_weak_deps=False \
33 alsa-lib apr apr-util bzip2-libs dbus-libs expat fontconfig freetype glib2 libgomp libICE libSM libuuid \
34 libX11 libXau libxcb libXcursor libXext libXfixes libXi libXinerama libxkbcommon libxkbcommon-x11 \
35 libXrandr libXrender libXtst libXxf86vm libglvnd-egl libglvnd-glx libglvnd-opengl mesa-libGLU \
36 mesa-dri-drivers systemd-libs xcb-util xcb-util-image xcb-util-keysyms xcb-util-renderutil xcb-util-wm \
37 ocl-icd xorg-x11-server-Xvfb dejavu-sans-fonts liberation-sans-fonts \
38 && dnf clean all
39COPY --from=installer /opt/BlackmagicDesign /opt/BlackmagicDesign
40WORKDIR /opt/BlackmagicDesign/FusionRenderNode21
service/fusion/service.pkl created+42
...@@ -0,0 +1,42 @@
1amends "../../config/Service.pkl"
2
3import "../../config/site.pkl" as site
4
5name = "Fusion"
6tagline = "Render node for Fusion Studio"
7launcher = false
8access = "admin"
9stageIsolation = "fresh"
10snapshots = false
11
12container {
13 build = "."
14 // Fusion Studio finds render nodes by UDP broadcast and connects back on 1144 and 49152-49159.
15 hostNetwork = !site.preview
16 cpu = 8000
17 memory = 16384
18 entrypoint = "/bin/sh"
19 args {
20 "-c"
21 """
22 Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp -nolisten local &
23 while [ ! -S /tmp/.X11-unix/X99 ]; do sleep 0.1; done
24 DISPLAY=:99 exec ./FusionRenderNode
25 """
26 }
27 volumes {
28 // The Mac's SMB mount point, so comps resolve without path maps.
29 ["/Volumes/clover"] { src = if (site.preview) null else site.cloverRoot; readOnly = site.cloverReadOnly }
30 ["/Volumes/clover/Media"] { src = if (site.preview) null else site.mediaRoot; readOnly = site.mediaReadOnly }
31 // Preferences, including path maps and the license server.
32 ["/home/fusion"] {}
33 ["/nvidia/lib"] { src = "/run/opengl-driver/lib"; readOnly = true }
34 ["/etc/OpenCL/vendors"] { src = "/run/opengl-driver/etc/OpenCL/vendors"; readOnly = true }
35 ["/nix/store"] { src = "/nix/store"; readOnly = true }
36 }
37 devices { "/dev/nvidia0"; "/dev/nvidiactl"; "/dev/nvidia-uvm" }
38 env {
39 ["HOME"] = "/home/fusion"
40 ["LD_LIBRARY_PATH"] = "/nvidia/lib"
41 }
42}
tools/dashboard-deploy-test.py+3-3
...@@ -68,7 +68,7 @@ class DeploymentBoundary(unittest.TestCase):...@@ -68,7 +68,7 @@ class DeploymentBoundary(unittest.TestCase):
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 ("gpu", "--root"), ("gpu", "../escape"), ("gpu", []), ("ai", "local-ai")]:
72 requests.append({"operation": "deploy.start", "action": action, "target": target})72 requests.append({"operation": "deploy.start", "action": action, "target": target})
73 with patch.object(runs.subprocess, "run") as executed:73 with patch.object(runs.subprocess, "run") as executed:
74 for request in requests:74 for request in requests:
...@@ -83,8 +83,8 @@ class DeploymentBoundary(unittest.TestCase):...@@ -83,8 +83,8 @@ class DeploymentBoundary(unittest.TestCase):
83 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"])
84 self.assertEqual(runs.command("stop", "fixture"), ["nomad", "job", "stop", "-yes", "fixture"])84 self.assertEqual(runs.command("stop", "fixture"), ["nomad", "job", "stop", "-yes", "fixture"])
85 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"]:86 for side in ["games", "fusion"]:
87 self.assertEqual(runs.command(mode, "win11-gaming")[1:], [str(Path(runs.__file__).with_name("vms.py")), "gpu", mode, "win11-gaming"])87 self.assertEqual(runs.command("gpu", side)[1:], [str(Path(runs.__file__).with_name("vms.py")), "gpu", side])
88 (self.snapshot / "tools/snowglobe.py").write_text("changed")88 (self.snapshot / "tools/snowglobe.py").write_text("changed")
89 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")]:
90 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+4-4
...@@ -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", "games", "ai"}28ACTIONS = {"deploy", "destroy", "rollback", "start", "stop", "restart", "secret-set", "secret-rotate", "gpu"}
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,10 +161,10 @@ def command(action, target, key=None):...@@ -161,10 +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"}:164 if action == "gpu":
165 if not isinstance(target, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", target):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.")166 raise Error(400, "Choose games or a service that uses the GPU.")
167 return [sys.executable, str(Path(__file__).with_name("vms.py")), "gpu", action, target]167 return [sys.executable, str(Path(__file__).with_name("vms.py")), "gpu", target]
168 if action == "rollback":168 if action == "rollback":
169 saved = entry(target)169 saved = entry(target)
170 version = saved["release"]170 version = saved["release"]
tools/dashboard-vms-test.py+53-21
...@@ -604,7 +604,8 @@ class GpuSwitch(unittest.TestCase):...@@ -604,7 +604,8 @@ class GpuSwitch(unittest.TestCase):
604 (root / 'nomad.token').write_text('token\n')604 (root / 'nomad.token').write_text('token\n')
605 self.domains = {'testbox': '<domain><devices/></domain>', 'win11-gaming': GPU_GUEST}605 self.domains = {'testbox': '<domain><devices/></domain>', 'win11-gaming': GPU_GUEST}
606 self.state, self.start_fails, self.shuts_down = 'shut off', False, True606 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']}}]}]},607 gpu_job = lambda stopped: {'Stop': stopped, 'TaskGroups': [{'Tasks': [{'Config': {'devices': ['/dev/nvidia0', '/dev/nvidiactl']}}]}]}
608 self.jobs = {'local-ai': gpu_job(False), 'fusion': gpu_job(True),
608 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}}609 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}}
609 self.polls = {}610 self.polls = {}
610 self.calls = []611 self.calls = []
...@@ -652,7 +653,7 @@ class GpuSwitch(unittest.TestCase):...@@ -652,7 +653,7 @@ class GpuSwitch(unittest.TestCase):
652 patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]:653 patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]:
653 context.start()654 context.start()
654 self.addCleanup(context.stop)655 self.addCleanup(context.stop)
655 self.deploy = (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', '--gpu')656 self.deploy = lambda job: (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', job)
656657
657 def test_the_gpu_guest_is_the_one_passing_through_an_nvidia_display(self):658 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 self.assertTrue(vms.passes_gpu(vms.ET.fromstring(GPU_GUEST)))
...@@ -665,45 +666,63 @@ class GpuSwitch(unittest.TestCase):...@@ -665,45 +666,63 @@ class GpuSwitch(unittest.TestCase):
665 self.assertIsNone(vms.gpu_guest())666 self.assertIsNone(vms.gpu_guest())
666667
667 def test_games_stops_only_gpu_jobs_and_waits_for_them_before_starting_the_guest(self):668 def test_games_stops_only_gpu_jobs_and_waits_for_them_before_starting_the_guest(self):
668 vms.switch_gpu('games', 'win11-gaming')669 vms.switch_gpu('games')
669 self.assertEqual(self.state, 'running')670 self.assertEqual(self.state, 'running')
670 stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai'))671 stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai'))
671 start = self.calls.index(('virsh', 'start', 'win11-gaming'))672 start = self.calls.index(('virsh', 'start', 'win11-gaming'))
672 self.assertLess(stop, start)673 self.assertLess(stop, start)
673 self.assertEqual(self.polls['local-ai'], 2)674 self.assertEqual(self.polls['local-ai'], 2)
674 self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'jellyfin'), self.calls)675 self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'jellyfin'), self.calls)
675 self.assertNotIn(self.deploy, self.calls)676 self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'fusion'), self.calls)
677 self.assertFalse(any(call[0] == vms.sys.executable for call in self.calls))
676678
677 def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_ai(self):679 def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_the_service_that_had_it(self):
678 self.start_fails = True680 self.start_fails = True
679 with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. AI has it again."):681 with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. local-ai has it again."):
680 vms.switch_gpu('games', 'win11-gaming')682 vms.switch_gpu('games')
681 self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy))683 self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy('local-ai')))
684 self.assertNotIn(self.deploy('fusion'), self.calls)
685
686 def test_a_service_takes_the_gpu_from_another_service(self):
687 vms.switch_gpu('fusion')
688 self.assertLess(self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai')), self.calls.index(self.deploy('fusion')))
689 self.assertEqual(self.polls['local-ai'], 2)
690 self.assertNotIn(('virsh', 'shutdown', 'win11-gaming'), self.calls)
682691
683 def test_ai_shuts_the_guest_down_before_deploying_the_gpu_services(self):692 def test_a_service_shuts_the_guest_down_before_deploying(self):
684 self.state = 'running'693 self.state = 'running'
685 vms.switch_gpu('ai', 'win11-gaming')694 self.jobs['local-ai']['Stop'] = True
686 self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy))695 vms.switch_gpu('local-ai')
687 self.assertFalse(any(call[0] == 'nomad' for call in self.calls))696 self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy('local-ai')))
697 self.assertFalse(any(call[:3] == ('nomad', 'job', 'stop') for call in self.calls))
688698
689 def test_a_guest_that_wont_shut_down_keeps_the_gpu(self):699 def test_a_guest_that_wont_shut_down_keeps_the_gpu(self):
690 self.state, self.shuts_down = 'running', False700 self.state, self.shuts_down = 'running', False
701 self.jobs['local-ai']['Stop'] = True
691 with self.assertRaisesRegex(ValueError, "didn't shut down"):702 with self.assertRaisesRegex(ValueError, "didn't shut down"):
692 vms.switch_gpu('ai', 'win11-gaming')703 vms.switch_gpu('fusion')
693 self.assertNotIn(self.deploy, self.calls)704 self.assertFalse(any(call[0] == vms.sys.executable for call in self.calls))
694705
695 def test_only_the_gpu_guest_switches_and_only_toward_the_other_side(self):706 def test_only_gpu_sides_switch_and_only_away_from_the_holder(self):
696 with self.assertRaisesRegex(ValueError, "testbox doesn't use the GPU"):707 for side, message in [('jellyfin', "jellyfin doesn't use the GPU"), ('local-ai', 'local-ai already has the GPU')]:
697 vms.switch_gpu('games', 'testbox')708 with self.subTest(side=side), self.assertRaisesRegex(ValueError, message):
709 vms.switch_gpu(side)
698 self.state = 'running'710 self.state = 'running'
699 with self.assertRaisesRegex(ValueError, 'already has the GPU'):711 self.jobs['local-ai']['Stop'] = True
700 vms.switch_gpu('games', 'win11-gaming')712 with self.assertRaisesRegex(ValueError, 'win11-gaming already has the GPU'):
701 self.assertFalse(any(call[0] in {'nomad', vms.sys.executable} or call[:2] == ('virsh', 'start') for call in self.calls))713 vms.switch_gpu('games')
714 del self.domains['win11-gaming']
715 with self.assertRaisesRegex(ValueError, 'No VM uses the GPU'):
716 vms.switch_gpu('games')
717 self.assertFalse(any(call[0] in {vms.sys.executable} or call[:3] == ('nomad', 'job', 'stop') or call[:2] == ('virsh', 'start')
718 for call in self.calls))
702719
703 def test_deploys_leave_gpu_services_alone_while_the_guest_has_the_gpu(self):720 def test_the_holder_is_the_running_guest_else_the_running_gpu_job(self):
704 import snowglobe721 import snowglobe
705 services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}]722 services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}]
706 self.assertEqual([snowglobe.gpu(item) for item in services], [True, False])723 self.assertEqual([snowglobe.gpu(item) for item in services], [True, False])
724 self.assertEqual(snowglobe.gpu_holder(services), 'local-ai')
725 self.jobs['local-ai']['Stop'] = True
707 self.assertIsNone(snowglobe.gpu_holder(services))726 self.assertIsNone(snowglobe.gpu_holder(services))
708 self.state = 'running'727 self.state = 'running'
709 self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming')728 self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming')
...@@ -711,6 +730,19 @@ class GpuSwitch(unittest.TestCase):...@@ -711,6 +730,19 @@ class GpuSwitch(unittest.TestCase):
711 self.assertIsNone(snowglobe.gpu_holder(services[1:]))730 self.assertIsNone(snowglobe.gpu_holder(services[1:]))
712 self.assertEqual(self.calls, [])731 self.assertEqual(self.calls, [])
713732
733 def test_a_stopped_registration_parses_the_job_and_submits_it_stopped(self):
734 import snowglobe
735 submitted = []
736
737 def command(*args, capture=False):
738 if '-output' in args:
739 return SimpleNamespace(stdout=json.dumps({'Job': {'ID': 'fusion'}}))
740 submitted.append((args, json.loads(Path(args[-1]).read_text())))
741
742 with patch.object(snowglobe, 'render', return_value='job "fusion" {}'), patch.object(snowglobe, 'command', side_effect=command):
743 snowglobe.submit({'containers': {'app': {}}}, 'run', {}, stopped=True)
744 self.assertEqual([(args[:5], job) for args, job in submitted],
745 [(('nomad', 'job', 'run', '-detach', '-json'), {'Job': {'ID': 'fusion', 'Stop': True}})])
714746
715if __name__ == '__main__':747if __name__ == '__main__':
716 unittest.main()748 unittest.main()
tools/fusion.md created+13
...@@ -0,0 +1,13 @@
1# Fusion Render Node
2
3`service/fusion` runs Blackmagic's Fusion Render Node under Xvfb. It holds the 3090 only when the dashboard's GPU
4switch gives it Fusion; otherwise its job stays registered and stopped.
5
6- **Version:** a render node only takes jobs from the same Fusion Studio version. The Dockerfile pins the Linux
7 download ID and SHA-256 from `https://www.blackmagicdesign.com/api/support/us/downloads.json`; bump both when
8 the Mac's Fusion Studio updates.
9- **License:** the node borrows the license from a Fusion Studio found on the LAN, so the Mac's dongle covers it.
10- **Paths:** `/srv/clover` mounts at `/Volumes/clover`, the Mac's SMB mount point, so comps render without path
11 maps. Fonts, OFX plugins and Reactor fuses must be installed in the image too.
12- **Network:** host networking; Fusion uses TCP/UDP 1144 and 49152-49159, which the firewall opens to the LAN only.
13- **State:** preferences live in the service's `/home/fusion`.
tools/snowglobe.py+23-12
...@@ -60,12 +60,14 @@ def gpu(data):...@@ -60,12 +60,14 @@ def gpu(data):
6060
6161
62def gpu_holder(data):62def gpu_holder(data):
63 """The guest holding the GPU, which the services that need it must leave alone."""63 """The guest passing the GPU through while it's on, else the running job that needs the GPU."""
64 if not any(gpu(item) for item in data):64 if not any(gpu(item) for item in data):
65 return None65 return None
66 vms = __import__("vms")66 vms = __import__("vms")
67 guest = vms.gpu_guest()67 guest = vms.gpu_guest()
68 return guest if guest and vms.virsh("domstate", guest) != "shut off" else None68 if guest and vms.virsh("domstate", guest) != "shut off":
69 return guest
70 return next((job for job, stopped in vms.gpu_jobs().items() if not stopped), None)
6971
7072
71def ordered(data):73def ordered(data):
...@@ -657,14 +659,21 @@ def provision(data):...@@ -657,14 +659,21 @@ def provision(data):
657 }))659 }))
658660
659661
660def submit(data, mode, definitions):662def submit(data, mode, definitions, stopped=False):
663 """`stopped` registers the job with no allocations, as `nomad job stop` leaves it."""
661 if not data["containers"]:664 if not data["containers"]:
662 return665 return
663 with tempfile.NamedTemporaryFile("w", suffix=".nomad.hcl", delete=False) as file:666 with tempfile.NamedTemporaryFile("w", suffix=".nomad.hcl", delete=False) as file:
664 file.write(render(data, definitions))667 file.write(render(data, definitions))
665 path = file.name668 path = file.name
666 try:669 try:
667 command("nomad", "job", mode, path)670 if stopped:
671 job = json.loads(command("nomad", "job", "run", "-output", path, capture=True).stdout)
672 job["Job"]["Stop"] = True
673 Path(path).write_text(json.dumps(job))
674 command("nomad", "job", "run", "-detach", "-json", path)
675 else:
676 command("nomad", "job", mode, path)
668 finally:677 finally:
669 Path(path).unlink()678 Path(path).unlink()
670679
...@@ -993,10 +1002,7 @@ def main():...@@ -993,10 +1002,7 @@ def main():
993 parser.add_argument("--media-root")1002 parser.add_argument("--media-root")
994 parser.add_argument("--env", action="append", default=[])1003 parser.add_argument("--env", action="append", default=[])
995 parser.add_argument("--key", action="append", default=[])1004 parser.add_argument("--key", action="append", default=[])
996 parser.add_argument("--gpu", action="store_true")
997 args = parser.parse_args()1005 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")
1000 if args.computer and (args.mode != "stage" or args.name != "dashboard"):1006 if args.computer and (args.mode != "stage" or args.name != "dashboard"):
1001 parser.error("--computer requires stage dashboard")1007 parser.error("--computer requires stage dashboard")
1002 if args.mode == "stage" and args.name == "dashboard":1008 if args.mode == "stage" and args.name == "dashboard":
...@@ -1278,7 +1284,7 @@ def main():...@@ -1278,7 +1284,7 @@ def main():
1278 if args.name and args.name not in definitions:1284 if args.name and args.name not in definitions:
1279 raise ValueError(f"unknown service: {args.name}")1285 raise ValueError(f"unknown service: {args.name}")
1280 if not args.name and args.mode == "deploy":1286 if not args.name and args.mode == "deploy":
1281 names = [name for name in names if definitions[name]["containers"] and (gpu(definitions[name]) or not args.gpu)]1287 names = [name for name in names if definitions[name]["containers"]]
1282 selected = set(names)1288 selected = set(names)
1283 while True:1289 while True:
1284 required = selected | set().union(*(dependencies(definitions[name]) for name in selected))1290 required = selected | set().union(*(dependencies(definitions[name]) for name in selected))
...@@ -1300,7 +1306,7 @@ def main():...@@ -1300,7 +1306,7 @@ def main():
1300 elif args.mode == "check":1306 elif args.mode == "check":
1301 holder = gpu_holder(data)1307 holder = gpu_holder(data)
1302 for item in data:1308 for item in data:
1303 if holder and gpu(item):1309 if gpu(item) and item["id"] != holder:
1304 continue1310 continue
1305 for task in item["containers"].values():1311 for task in item["containers"].values():
1306 if task.get("http") and task["http"].get("hostname"):1312 if task.get("http") and task["http"].get("hostname"):
...@@ -1334,13 +1340,18 @@ def main():...@@ -1334,13 +1340,18 @@ def main():
1334 elif args.mode == "deploy":1340 elif args.mode == "deploy":
1335 bootstrap(data)1341 bootstrap(data)
1336 holder = gpu_holder(data)1342 holder = gpu_holder(data)
1343 if args.name and gpu(definitions[args.name]) and holder not in {None, args.name}:
1344 raise ValueError(f"{holder} has the GPU. Switch the GPU to {args.name} from the dashboard.")
1337 for item in data:1345 for item in data:
1338 if holder and gpu(item):1346 # Deploys never move the GPU: only its holder runs, or the named service while nothing has it.
1339 print(f"Skipping {item['id']} while {holder} has the GPU", flush=True)1347 stopped = gpu(item) and item["id"] != (holder or args.name)
1340 continue
1341 provision_inputs(item, definitions)1348 provision_inputs(item, definitions)
1342 provision(item)1349 provision(item)
1343 prepare(item)1350 prepare(item)
1351 if stopped:
1352 print(f"Registering {item['id']} stopped while {holder or 'nothing'} has the GPU", flush=True)
1353 submit(item, "run", definitions, stopped=True)
1354 continue
1344 build_images(item)1355 build_images(item)
1345 submit(item, "run", definitions)1356 submit(item, "run", definitions)
1346 configure(item)1357 configure(item)
tools/vms.py+53-36
...@@ -413,49 +413,66 @@ def gpu_guest():...@@ -413,49 +413,66 @@ def gpu_guest():
413 if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None)413 if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None)
414414
415415
416def switch_gpu(mode, name):416def nomad(*args):
417 """Hands the GPU to the guest (games) or to the services that need it (ai)."""417 token = (import_module("release").STATE / "nomad.token").read_text().strip()
418 if gpu_guest() != name:418 return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True,
419 raise ValueError(f"{name} doesn't use the GPU.")419 env={**os.environ, "NOMAD_TOKEN": token}).stdout
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()}
436420
437 def nomad(*args):
438 return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True, env=environment).stdout
439421
440 def needs_gpu(job):422def gpu_jobs():
423 """Nomad jobs that need the GPU, mapped to whether they're stopped."""
424 jobs = {}
425 for job in (entry["Summary"]["JobID"] for entry in json.loads(nomad("job", "status", "-json"))):
441 spec = json.loads(nomad("job", "inspect", "-json", job))426 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"]427 if 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 [])428 for task in group["Tasks"] for device in (task["Config"] or {}).get("devices") or []):
429 jobs[job] = bool(spec.get("Stop"))
430 return jobs
431
432
433def switch_gpu(side):
434 """Hands the GPU to the guest passing it through (games) or to one service that needs it."""
435 guest, jobs = gpu_guest(), gpu_jobs()
436 if side == "games" and not guest:
437 raise ValueError("No VM uses the GPU.")
438 if side != "games" and side not in jobs:
439 raise ValueError(f"{side} doesn't use the GPU.")
440 on = bool(guest) and virsh("domstate", guest) != "shut off"
441 holders = [job for job, stopped in jobs.items() if not stopped and job != side]
442 if side == "games" and on:
443 raise ValueError(f"{guest} already has the GPU.")
444 if side != "games" and not on and not holders and not jobs[side]:
445 raise ValueError(f"{side} already has the GPU.")
446 release = import_module("release")
447 script = str(release.check_release(release.current_release()) / "tools/snowglobe.py")
448
449 def deploy(job):
450 return subprocess.run([sys.executable, script, "deploy", job]).returncode == 0
444451
445 jobs = [job for job in (entry["Summary"]["JobID"] for entry in json.loads(nomad("job", "status", "-json"))) if needs_gpu(job)]452 if on:
446 for job in jobs:453 print(f"Shutting down {guest}", flush=True)
454 virsh("shutdown", guest)
455 if not wait(lambda: virsh("domstate", guest) == "shut off", 300):
456 raise ValueError(f"{guest} didn't shut down. Close its apps or force it off, then switch again.")
457 for job in holders:
447 print(f"Stopping {job}", flush=True)458 print(f"Stopping {job}", flush=True)
448 nomad("job", "stop", "-yes", job)459 nomad("job", "stop", "-yes", job)
449 if not wait(lambda: not any(alloc["ClientStatus"] in {"pending", "running"}460 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):461 for job in holders 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.")462 raise ValueError(f"{', '.join(holders)} didn't stop. Open its service page to see why.")
452 print(f"Starting {name}", flush=True)463 if side != "games":
464 if not deploy(side):
465 raise ValueError(f"{side} couldn't start. Open its service page to see why.")
466 return
467 print(f"Starting {guest}", flush=True)
453 try:468 try:
454 virsh("start", name)469 virsh("start", guest)
455 except subprocess.CalledProcessError as error:470 except subprocess.CalledProcessError as error:
456 print(error.stderr, flush=True)471 print(error.stderr, flush=True)
457 restored = subprocess.run(deploy).returncode == 0472 restored = all([deploy(job) for job in holders]) # A list, so one failure doesn't skip the rest.
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 None473 raise ValueError(f"{guest} couldn't take the GPU. " + (
474 f"{', '.join(holders)} has it again." if holders and restored
475 else "Nothing else had it." if restored else "Open the service pages to see why.")) from None
459476
460477
461def wait(ready, seconds):478def wait(ready, seconds):
...@@ -1251,9 +1268,9 @@ def main():...@@ -1251,9 +1268,9 @@ def main():
12511268
1252if __name__ == "__main__":1269if __name__ == "__main__":
1253 try:1270 try:
1254 if sys.argv[1] == "gpu" and len(sys.argv) == 4 and sys.argv[2] in {"games", "ai"}:1271 if sys.argv[1] == "gpu" and len(sys.argv) == 3:
1255 ensure_name(sys.argv[3])1272 ensure_name(sys.argv[2])
1256 switch_gpu(sys.argv[2], sys.argv[3])1273 switch_gpu(sys.argv[2])
1257 sys.exit(0)1274 sys.exit(0)
1258 print(json.dumps(main()))1275 print(json.dumps(main()))
1259 except ValueError as failure:1276 except ValueError as failure:
tools/win11-gaming.md+2-1
...@@ -13,7 +13,8 @@ dashboard console / Computer MCP ─── libvirt VNC + guest agent (owner Clov...@@ -13,7 +13,8 @@ dashboard console / Computer MCP ─── libvirt VNC + guest agent (owner Clov
13guest ── virbr-ext (forward mode='open') ── MASQUERADE ── internet only13guest ── virbr-ext (forward mode='open') ── MASQUERADE ── internet only
14```14```
1515
16- **GPU:** the 3090 serves either this guest or local AI, chosen with the dashboard's Games/AI switch. The16- **GPU:** the 3090 serves this guest or one GPU service (Local AI, Fusion), chosen with the dashboard's GPU switch.
17 Deploys never move it: GPU services other than the holder are registered stopped. The
17 domain's `managed='yes'` hostdevs make libvirt move both functions to vfio-pci at start and back to nvidia at18 domain's `managed='yes'` hostdevs make libvirt move both functions to vfio-pci at start and back to nvidia at
18 shut off; `nvidia-persistenced` stays off so nothing holds the device. Windows Update is barred from driver19 shut off; `nvidia-persistenced` stays off so nothing holds the device. Windows Update is barred from driver
19 updates (`ExcludeWUDriversInQualityUpdate`); install GeForce drivers with `-s -n`.20 updates (`ExcludeWUDriversInQualityUpdate`); install GeForce drivers with `-s -n`.