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> {
9494 host::call(request).await
9595}
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
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>) -> Value {
99 let found = tokio::try_join!(core::managed(), core::scan(app)).ok();
100 let services = found.map(|(managed, scan)| {
101 scan.value
102102 .as_object()
103103 .into_iter()
104 .flat_map(|jobs| jobs.values())
105 .filter(|entry| {
106 array(&entry["job"]["TaskGroups"])
104 .flat_map(|jobs| jobs.iter())
105 .filter(|(id, entry)| {
106 managed.contains(id) && array(&entry["job"]["TaskGroups"])
107107 .iter()
108108 .flat_map(|group| array(&group["Tasks"]))
109109 .any(|task| {
......@@ -112,15 +112,13 @@ async fn gpu(app: Arc<App>, name: &str) -> Value {
112112 .any(|device| string(device).starts_with("/dev/nvidia"))
113113 })
114114 })
115 .map(|entry| string(&entry["health"]).to_owned());
116 health
117 .find(|health| health != "stopped")
118 .unwrap_or_else(|| "stopped".into())
115 .map(|(id, entry)| json!({"id":id,"name":entry["job"]["Meta"]["snowglobe_name"].as_str().unwrap_or(id),"health":entry["health"]}))
116 .collect::<Vec<_>>()
119117 });
120118 let run = host::call(json!({"operation":"deploy.last"}))
121119 .await
122120 .unwrap_or_default();
123 let ours = matches!(run["action"].as_str(), Some("games" | "ai")) && run["target"] == name;
121 let ours = run["action"] == "gpu";
124122 let failed = if !ours || run["code"].is_null() || run["code"] == 0 {
125123 Value::Null
126124 } else if run["code"] == 2 {
......@@ -138,11 +136,11 @@ async fn gpu(app: Arc<App>, name: &str) -> Value {
138136 json!("Couldn't switch the GPU.")
139137 };
140138 let switching = if ours && run["code"].is_null() {
141 run["action"].clone()
139 run["target"].clone()
142140 } else {
143141 Value::Null
144142 };
145 json!({"ai":ai,"switching":switching,"failed":failed})
143 json!({"services":services,"switching":switching,"failed":failed})
146144}
147145
148146fn vm_name(name: &str) -> Result<()> {
......@@ -361,7 +359,7 @@ pub async fn route(
361359 .cloned()
362360 .unwrap_or(Value::Null);
363361 domain["gpu"] = if domain["gpu"] == true {
364 gpu(app.clone(), string(&domain["name"])).await
362 gpu(app.clone()).await
365363 } else {
366364 Value::Null
367365 };
......@@ -426,11 +424,14 @@ pub async fn route(
426424 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;
427425 }
428426 ["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}))
427 // Access to the guest that passes the GPU through is what grants the switch.
428 if !array(&vm_call("domains", None).await?)
429 .iter()
430 .any(|domain| domain["name"] == *name && domain["gpu"] == true)
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"]}))
434435 .await?;
435436 app.cache.invalidate("deploys");
436437 }
dashboard/src/deploys.rs+3-2
......@@ -227,8 +227,9 @@ fn display_run(run: Value, history: &Value) -> Result<Value> {
227227 "secret-set" => format!("set {target}/{}", string(&run["key"])),
228228 "secret-rotate" => format!("rotate {target}/{}", string(&run["key"])),
229229 action @ ("start" | "stop" | "restart") => format!("{action} {target}"),
230 "games" => "switch GPU to games".to_owned(),
231 "ai" => "switch GPU to AI".to_owned(),
230 "gpu" => format!("switch GPU to {target}"),
231 // Runs recorded before switches named their side as the target.
232 action @ ("games" | "ai") => format!("switch GPU to {action}"),
232233 "deploy" => "deploy main".to_owned(),
233234 "promote" => format!("promote {target}"),
234235 "destroy" => format!("destroy {target}"),
dashboard/web/api.contract.ts+1-1
......@@ -334,7 +334,7 @@ export type Api = Hono<{}, {
334334 $post: Endpoint<null, { param: { name: string }; json: { id: string; os: string; description: string } }, 204, "body">;
335335 };
336336 "/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">;
338338 };
339339 "/vms/:name/:action": {
340340 $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 @@
11import { parseResponse } from "hono/client";
2import { createSignal, Show } from "solid-js";
2import { createSignal, For, Show } from "solid-js";
33import { api, reason } from "../api.ts";
4import type { Health } from "../types/model.ts";
45import type { Domain, GpuShare } from "../types/vms.ts";
56import { showConfirmDialog } from "./Dialog.tsx";
67import { type StatusKind, StatusLabel } from "./Status.tsx";
......@@ -8,61 +9,73 @@ import { TabBar } from "./TabBar.tsx";
89import { toast } from "./Toast.tsx";
910import "./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
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. */
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. */
1615export function GpuSwitch(props: { vm: Domain & { gpu: GpuShare }; refetch: () => unknown }) {
1716 const [sending, setSending] = createSignal(false);
1817 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);
18 const services = () => props.vm.gpu.services ?? [];
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);
2122 const busy = () => sending() || props.vm.gpu.switching !== null;
2223 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}…`];
24 const { switching, failed } = props.vm.gpu;
25 const running = holder();
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 }
2631 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;
32 if (!off() || props.vm.gpu.services === null) return null;
33 if (!running) return ["stopped", "idle"];
34 if (loading(running.health)) return ["starting", `loading ${running.name}…`];
35 if (running.health === "down" || running.health === "degraded") return [running.health, `${running.name} is ${running.health}`];
36 return null;
3137 };
32 const send = async (mode: Side) => {
38 const send = async (to: string) => {
3339 setSending(true);
3440 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 } }));
3642 await props.refetch();
3743 } finally {
3844 setSending(false);
3945 }
4046 };
41 const choose = (mode: Side) => {
42 if (mode === "ai" && !off()) {
47 const choose = (to: string) => {
48 const label = to === "games" ? "games" : name(to);
49 const running = holder();
50 if (to !== "games" && !off()) {
4351 showConfirmDialog({
44 title: "Switch the GPU to AI?",
52 title: `Switch the GPU to ${label}?`,
4553 description: `${props.vm.name} shuts down first. Anything unsaved in it is lost.`,
46 confirmLabel: "switch to AI",
54 confirmLabel: `switch to ${label}`,
4755 destructive: true,
48 onConfirm: () => send(mode),
56 onConfirm: () => send(to),
4957 });
50 } else if (mode === "games" && aiOn()) {
58 } else if (running && running.id !== to) {
5159 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),
60 title: `Switch the GPU to ${label}?`,
61 description: `${running.name} stops, along with anything it's working on.`,
62 confirmLabel: `switch to ${label}`,
63 onConfirm: () => send(to),
5664 });
5765 } 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)}`));
5967 }
6068 };
6169 return (
6270 <span class="gpu-switch" aria-busy={busy()}>
6371 <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>
72 <For each={[{ id: "games", name: "games" }, ...services()]}>
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>
6679 </TabBar>
6780 <Show when={progress()}>
6881 {(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 {
7676}
7777
7878export 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;
79 /** The services that need the GPU; null while they're unknown. */
80 services: { id: string; name: string; health: Health }[] | null;
81 /** The side a switch under way is giving the GPU to: "games" or a service ID. */
82 switching: string | null;
8383 /** Why the latest switch failed, until another run starts. */
8484 failed: string | null;
8585}
nixos/snowglobe.nix+3
......@@ -31,6 +31,9 @@ in
3131 networking.firewall.allowedUDPPortRanges = [{ from = xmppNetwork.relay_first; to = xmppNetwork.relay_last; }];
3232 networking.firewall.extraCommands = lib.concatMapStrings ({ address, prefixLength, ... }: ''
3333 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
3437 '') config.networking.interfaces.enp4s0.ipv4.addresses + ''
3538 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
3639 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):
6868 {"operation": "deploy.history", "path": "/etc/shadow"}]
6969 for action, target in [("sh", self.stage), ([], self.stage), ("destroy", "../escape"),
7070 ("destroy", "--root"), ("rollback", self.version), ("rollback", "0"), ("rollback", []),
71 ("games", "--root"), ("ai", "../escape"), ("games", [])]:
71 ("gpu", "--root"), ("gpu", "../escape"), ("gpu", []), ("ai", "local-ai")]:
7272 requests.append({"operation": "deploy.start", "action": action, "target": target})
7373 with patch.object(runs.subprocess, "run") as executed:
7474 for request in requests:
......@@ -83,8 +83,8 @@ class DeploymentBoundary(unittest.TestCase):
8383 self.assertEqual(runs.command("start", "fixture")[1:], [str(self.snapshot / "tools/snowglobe.py"), "deploy", "fixture"])
8484 self.assertEqual(runs.command("stop", "fixture"), ["nomad", "job", "stop", "-yes", "fixture"])
8585 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"])
86 for side in ["games", "fusion"]:
87 self.assertEqual(runs.command("gpu", side)[1:], [str(Path(runs.__file__).with_name("vms.py")), "gpu", side])
8888 (self.snapshot / "tools/snowglobe.py").write_text("changed")
8989 for action, target in [("destroy", self.stage), ("deploy", self.version), ("rollback", "1"), ("start", "fixture")]:
9090 with self.subTest(action=action), self.assertRaisesRegex(ValueError, "contents changed"):
tools/dashboard-run.py+4-4
......@@ -25,7 +25,7 @@ FIELDS = {
2525 "deploy.secret.get": {"service", "key"}, "deploy.secret.set": {"service", "key", "value"},
2626 "deploy.secret.rotate": {"service", "key"},
2727}
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"}
2929MAX_LOG = 1024 * 1024
3030MAX_METADATA = 65536
3131HOST_STATE = Path(os.environ.get("SNOWGLOBE_HOST_STATE_ROOT", "/var/lib/snowglobe/host"))
......@@ -161,10 +161,10 @@ def command(action, target, key=None):
161161 if version is None:
162162 raise Error(409, "No release is running. Deploy a release before starting this service.")
163163 return [sys.executable, str(release.check_release(version) / "tools/snowglobe.py"), "deploy", target]
164 if action in {"games", "ai"}:
164 if action == "gpu":
165165 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]
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", target]
168168 if action == "rollback":
169169 saved = entry(target)
170170 version = saved["release"]
tools/dashboard-vms-test.py+53-21
......@@ -604,7 +604,8 @@ class GpuSwitch(unittest.TestCase):
604604 (root / 'nomad.token').write_text('token\n')
605605 self.domains = {'testbox': '<domain><devices/></domain>', 'win11-gaming': GPU_GUEST}
606606 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),
608609 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}}
609610 self.polls = {}
610611 self.calls = []
......@@ -652,7 +653,7 @@ class GpuSwitch(unittest.TestCase):
652653 patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]:
653654 context.start()
654655 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
657658 def test_the_gpu_guest_is_the_one_passing_through_an_nvidia_display(self):
658659 self.assertTrue(vms.passes_gpu(vms.ET.fromstring(GPU_GUEST)))
......@@ -665,45 +666,63 @@ class GpuSwitch(unittest.TestCase):
665666 self.assertIsNone(vms.gpu_guest())
666667
667668 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')
669670 self.assertEqual(self.state, 'running')
670671 stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai'))
671672 start = self.calls.index(('virsh', 'start', 'win11-gaming'))
672673 self.assertLess(stop, start)
673674 self.assertEqual(self.polls['local-ai'], 2)
674675 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):
678680 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))
681 with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. local-ai has it again."):
682 vms.switch_gpu('games')
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):
684693 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))
694 self.jobs['local-ai']['Stop'] = True
695 vms.switch_gpu('local-ai')
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
689699 def test_a_guest_that_wont_shut_down_keeps_the_gpu(self):
690700 self.state, self.shuts_down = 'running', False
701 self.jobs['local-ai']['Stop'] = True
691702 with self.assertRaisesRegex(ValueError, "didn't shut down"):
692 vms.switch_gpu('ai', 'win11-gaming')
693 self.assertNotIn(self.deploy, self.calls)
703 vms.switch_gpu('fusion')
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):
696 with self.assertRaisesRegex(ValueError, "testbox doesn't use the GPU"):
697 vms.switch_gpu('games', 'testbox')
706 def test_only_gpu_sides_switch_and_only_away_from_the_holder(self):
707 for side, message in [('jellyfin', "jellyfin doesn't use the GPU"), ('local-ai', 'local-ai already has the GPU')]:
708 with self.subTest(side=side), self.assertRaisesRegex(ValueError, message):
709 vms.switch_gpu(side)
698710 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))
711 self.jobs['local-ai']['Stop'] = True
712 with self.assertRaisesRegex(ValueError, 'win11-gaming already has the GPU'):
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):
704721 import snowglobe
705722 services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}]
706723 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
707726 self.assertIsNone(snowglobe.gpu_holder(services))
708727 self.state = 'running'
709728 self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming')
......@@ -711,6 +730,19 @@ class GpuSwitch(unittest.TestCase):
711730 self.assertIsNone(snowglobe.gpu_holder(services[1:]))
712731 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
715747if __name__ == '__main__':
716748 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):
6060
6161
6262def 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."""
6464 if not any(gpu(item) for item in data):
6565 return None
6666 vms = __import__("vms")
6767 guest = vms.gpu_guest()
68 return guest if guest and vms.virsh("domstate", guest) != "shut off" else None
68 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
7173def ordered(data):
......@@ -657,14 +659,21 @@ def provision(data):
657659 }))
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."""
661664 if not data["containers"]:
662665 return
663666 with tempfile.NamedTemporaryFile("w", suffix=".nomad.hcl", delete=False) as file:
664667 file.write(render(data, definitions))
665668 path = file.name
666669 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)
668677 finally:
669678 Path(path).unlink()
670679
......@@ -993,10 +1002,7 @@ def main():
9931002 parser.add_argument("--media-root")
9941003 parser.add_argument("--env", action="append", default=[])
9951004 parser.add_argument("--key", action="append", default=[])
996 parser.add_argument("--gpu", action="store_true")
9971005 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")
10001006 if args.computer and (args.mode != "stage" or args.name != "dashboard"):
10011007 parser.error("--computer requires stage dashboard")
10021008 if args.mode == "stage" and args.name == "dashboard":
......@@ -1278,7 +1284,7 @@ def main():
12781284 if args.name and args.name not in definitions:
12791285 raise ValueError(f"unknown service: {args.name}")
12801286 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"]]
12821288 selected = set(names)
12831289 while True:
12841290 required = selected | set().union(*(dependencies(definitions[name]) for name in selected))
......@@ -1300,7 +1306,7 @@ def main():
13001306 elif args.mode == "check":
13011307 holder = gpu_holder(data)
13021308 for item in data:
1303 if holder and gpu(item):
1309 if gpu(item) and item["id"] != holder:
13041310 continue
13051311 for task in item["containers"].values():
13061312 if task.get("http") and task["http"].get("hostname"):
......@@ -1334,13 +1340,18 @@ def main():
13341340 elif args.mode == "deploy":
13351341 bootstrap(data)
13361342 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.")
13371345 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
1346 # Deploys never move the GPU: only its holder runs, or the named service while nothing has it.
1347 stopped = gpu(item) and item["id"] != (holder or args.name)
13411348 provision_inputs(item, definitions)
13421349 provision(item)
13431350 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
13441355 build_images(item)
13451356 submit(item, "run", definitions)
13461357 configure(item)
tools/vms.py+53-36
......@@ -413,49 +413,66 @@ def gpu_guest():
413413 if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None)
414414
415415
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()}
416def nomad(*args):
417 token = (import_module("release").STATE / "nomad.token").read_text().strip()
418 return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True,
419 env={**os.environ, "NOMAD_TOKEN": token}).stdout
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"))):
441426 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 [])
427 if any(device.startswith("/dev/nvidia") for group in spec["TaskGroups"]
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)]
446 for job in jobs:
452 if on:
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:
447458 print(f"Stopping {job}", flush=True)
448459 nomad("job", "stop", "-yes", job)
449460 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)
461 for job in holders for alloc in json.loads(nomad("job", "allocs", "-json", job))), 300):
462 raise ValueError(f"{', '.join(holders)} didn't stop. Open its service page to see why.")
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)
453468 try:
454 virsh("start", name)
469 virsh("start", guest)
455470 except subprocess.CalledProcessError as error:
456471 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
472 restored = all([deploy(job) for job in holders]) # A list, so one failure doesn't skip the rest.
473 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
461478def wait(ready, seconds):
......@@ -1251,9 +1268,9 @@ def main():
12511268
12521269if __name__ == "__main__":
12531270 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])
1271 if sys.argv[1] == "gpu" and len(sys.argv) == 3:
1272 ensure_name(sys.argv[2])
1273 switch_gpu(sys.argv[2])
12571274 sys.exit(0)
12581275 print(json.dumps(main()))
12591276 except ValueError as failure:
tools/win11-gaming.md+2-1
......@@ -13,7 +13,8 @@ dashboard console / Computer MCP ─── libvirt VNC + guest agent (owner Clov
1313guest ── virbr-ext (forward mode='open') ── MASQUERADE ── internet only
1414```
1515
16- **GPU:** the 3090 serves either this guest or local AI, chosen with the dashboard's Games/AI switch. The
16- **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
1718 domain's `managed='yes'` hostdevs make libvirt move both functions to vfio-pci at start and back to nvidia at
1819 shut off; `nvidia-persistenced` stays off so nothing holds the device. Windows Update is barred from driver
1920 updates (`ExcludeWUDriversInQualityUpdate`); install GeForce drivers with `-s -n`.