diff --git a/dashboard/src/apps.rs b/dashboard/src/apps.rs index 3168098b19582aef5e028e55fd25094770b3fb9d..227c4e6f820fec81e26d8673885226c5e7e1ee6c 100644 --- a/dashboard/src/apps.rs +++ b/dashboard/src/apps.rs @@ -94,16 +94,16 @@ async fn vm_call(action: &str, payload: Option) -> Result { host::call(request).await } -/// Who has the GPU. The guest's power state says games; the GPU services' health says AI. -async fn gpu(app: Arc, name: &str) -> Value { - let ai = core::scan(app).await.ok().map(|scan| { - let mut health = scan - .value +/// Who has the GPU. The guest's power state says games; the GPU services' health says which service. +async fn gpu(app: Arc) -> Value { + let found = tokio::try_join!(core::managed(), core::scan(app)).ok(); + let services = found.map(|(managed, scan)| { + scan.value .as_object() .into_iter() - .flat_map(|jobs| jobs.values()) - .filter(|entry| { - array(&entry["job"]["TaskGroups"]) + .flat_map(|jobs| jobs.iter()) + .filter(|(id, entry)| { + managed.contains(id) && array(&entry["job"]["TaskGroups"]) .iter() .flat_map(|group| array(&group["Tasks"])) .any(|task| { @@ -112,15 +112,13 @@ async fn gpu(app: Arc, name: &str) -> Value { .any(|device| string(device).starts_with("/dev/nvidia")) }) }) - .map(|entry| string(&entry["health"]).to_owned()); - health - .find(|health| health != "stopped") - .unwrap_or_else(|| "stopped".into()) + .map(|(id, entry)| json!({"id":id,"name":entry["job"]["Meta"]["snowglobe_name"].as_str().unwrap_or(id),"health":entry["health"]})) + .collect::>() }); let run = host::call(json!({"operation":"deploy.last"})) .await .unwrap_or_default(); - let ours = matches!(run["action"].as_str(), Some("games" | "ai")) && run["target"] == name; + let ours = run["action"] == "gpu"; let failed = if !ours || run["code"].is_null() || run["code"] == 0 { Value::Null } else if run["code"] == 2 { @@ -138,11 +136,11 @@ async fn gpu(app: Arc, name: &str) -> Value { json!("Couldn't switch the GPU.") }; let switching = if ours && run["code"].is_null() { - run["action"].clone() + run["target"].clone() } else { Value::Null }; - json!({"ai":ai,"switching":switching,"failed":failed}) + json!({"services":services,"switching":switching,"failed":failed}) } fn vm_name(name: &str) -> Result<()> { @@ -361,7 +359,7 @@ pub async fn route( .cloned() .unwrap_or(Value::Null); domain["gpu"] = if domain["gpu"] == true { - gpu(app.clone(), string(&domain["name"])).await + gpu(app.clone()).await } else { Value::Null }; @@ -426,11 +424,14 @@ pub async fn route( vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?; } ["gpu"] if method == Method::POST => { - let mode = body["mode"] - .as_str() - .filter(|mode| ["games", "ai"].contains(mode)) - .ok_or_else(|| Error::new(400, "Choose games or AI."))?; - host::call(json!({"operation":"deploy.start","action":mode,"target":name})) + // Access to the guest that passes the GPU through is what grants the switch. + if !array(&vm_call("domains", None).await?) + .iter() + .any(|domain| domain["name"] == *name && domain["gpu"] == true) + { + return Err(Error::new(400, format!("{name} doesn't use the GPU."))); + } + host::call(json!({"operation":"deploy.start","action":"gpu","target":body["side"]})) .await?; app.cache.invalidate("deploys"); } diff --git a/dashboard/src/deploys.rs b/dashboard/src/deploys.rs index 20d9c31a90c5a671682c6ee6c36054878c483058..77457d15d0c9c13c20a02efd3e1b74bd633004d9 100644 --- a/dashboard/src/deploys.rs +++ b/dashboard/src/deploys.rs @@ -227,8 +227,9 @@ fn display_run(run: Value, history: &Value) -> Result { "secret-set" => format!("set {target}/{}", string(&run["key"])), "secret-rotate" => format!("rotate {target}/{}", string(&run["key"])), action @ ("start" | "stop" | "restart") => format!("{action} {target}"), - "games" => "switch GPU to games".to_owned(), - "ai" => "switch GPU to AI".to_owned(), + "gpu" => format!("switch GPU to {target}"), + // Runs recorded before switches named their side as the target. + action @ ("games" | "ai") => format!("switch GPU to {action}"), "deploy" => "deploy main".to_owned(), "promote" => format!("promote {target}"), "destroy" => format!("destroy {target}"), diff --git a/dashboard/web/api.contract.ts b/dashboard/web/api.contract.ts index a785c5070714f05e6b3e55e316cfded480b7aa0a..6ed8bb4fc5c2fc004432c02274326ad9f661d8d1 100644 --- a/dashboard/web/api.contract.ts +++ b/dashboard/web/api.contract.ts @@ -334,7 +334,7 @@ export type Api = Hono<{}, { $post: Endpoint; }; "/vms/:name/gpu": { - $post: Endpoint; + $post: Endpoint; }; "/vms/:name/:action": { $post: Endpoint; diff --git a/dashboard/web/components/GpuSwitch.tsx b/dashboard/web/components/GpuSwitch.tsx index e78df4fe6b6434f047124b80beaba039ea6acbaf..c6ee071c70ee82ce0d455ec9a21d6e741db4557b 100644 --- a/dashboard/web/components/GpuSwitch.tsx +++ b/dashboard/web/components/GpuSwitch.tsx @@ -1,6 +1,7 @@ import { parseResponse } from "hono/client"; -import { createSignal, Show } from "solid-js"; +import { createSignal, For, Show } from "solid-js"; import { api, reason } from "../api.ts"; +import type { Health } from "../types/model.ts"; import type { Domain, GpuShare } from "../types/vms.ts"; import { showConfirmDialog } from "./Dialog.tsx"; import { type StatusKind, StatusLabel } from "./Status.tsx"; @@ -8,61 +9,73 @@ import { TabBar } from "./TabBar.tsx"; import { toast } from "./Toast.tsx"; import "./GpuSwitch.css"; -type Side = NonNullable; +const loading = (health: Health) => health === "starting" || health === "deploying" || health === "restarting"; -const loading = (ai: GpuShare["ai"]) => ai === "starting" || ai === "deploying" || ai === "restarting"; - -/** Gives the GPU to `vm` for games or to AI. Who has it comes from the guest's power state and AI's health. */ +/** 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. */ export function GpuSwitch(props: { vm: Domain & { gpu: GpuShare }; refetch: () => unknown }) { const [sending, setSending] = createSignal(false); const off = () => props.vm.state === "shutoff" || props.vm.state === "crashed"; - const aiOn = () => props.vm.gpu.ai !== null && props.vm.gpu.ai !== "stopped"; - const side = (): Side | null => props.vm.gpu.switching ?? (!off() ? "games" : aiOn() ? "ai" : null); + const services = () => props.vm.gpu.services ?? []; + const holder = () => services().find((service) => service.health !== "stopped"); + const name = (side: string) => services().find((service) => service.id === side)?.name ?? side; + const side = () => props.vm.gpu.switching ?? (!off() ? "games" : holder()?.id ?? null); const busy = () => sending() || props.vm.gpu.switching !== null; const progress = (): [StatusKind, string] | null => { - const { switching, ai, failed } = props.vm.gpu; - if (switching === "games") return ["starting", aiOn() ? "stopping AI…" : `starting ${props.vm.name}…`]; - if (switching === "ai") return ["starting", off() ? "loading AI…" : `shutting down ${props.vm.name}…`]; + const { switching, failed } = props.vm.gpu; + const running = holder(); + if (switching === "games") return ["starting", running ? `stopping ${running.name}…` : `starting ${props.vm.name}…`]; + if (switching) { + if (!off()) return ["starting", `shutting down ${props.vm.name}…`]; + return ["starting", running && running.id !== switching ? `stopping ${running.name}…` : `loading ${name(switching)}…`]; + } if (failed) return ["down", failed]; - if (!off()) return null; - if (loading(ai)) return ["starting", "loading AI…"]; - if (ai === "down" || ai === "degraded") return [ai, `AI is ${ai}`]; - return ai === "stopped" ? ["stopped", "idle"] : null; + if (!off() || props.vm.gpu.services === null) return null; + if (!running) return ["stopped", "idle"]; + if (loading(running.health)) return ["starting", `loading ${running.name}…`]; + if (running.health === "down" || running.health === "degraded") return [running.health, `${running.name} is ${running.health}`]; + return null; }; - const send = async (mode: Side) => { + const send = async (to: string) => { setSending(true); try { - await parseResponse(api.vms[":name"].gpu.$post({ param: { name: props.vm.name }, json: { mode } })); + await parseResponse(api.vms[":name"].gpu.$post({ param: { name: props.vm.name }, json: { side: to } })); await props.refetch(); } finally { setSending(false); } }; - const choose = (mode: Side) => { - if (mode === "ai" && !off()) { + const choose = (to: string) => { + const label = to === "games" ? "games" : name(to); + const running = holder(); + if (to !== "games" && !off()) { showConfirmDialog({ - title: "Switch the GPU to AI?", + title: `Switch the GPU to ${label}?`, description: `${props.vm.name} shuts down first. Anything unsaved in it is lost.`, - confirmLabel: "switch to AI", + confirmLabel: `switch to ${label}`, destructive: true, - onConfirm: () => send(mode), + onConfirm: () => send(to), }); - } else if (mode === "games" && aiOn()) { + } else if (running && running.id !== to) { showConfirmDialog({ - title: "Switch the GPU to games?", - description: "AI stops, along with replies it's writing, and takes a while to load again.", - confirmLabel: "switch to games", - onConfirm: () => send(mode), + title: `Switch the GPU to ${label}?`, + description: `${running.name} stops, along with anything it's working on.`, + confirmLabel: `switch to ${label}`, + onConfirm: () => send(to), }); } else { - send(mode).catch((failure) => toast(`Couldn't switch the GPU. ${reason(failure)}`)); + send(to).catch((failure) => toast(`Couldn't switch the GPU. ${reason(failure)}`)); } }; return ( - - + + {(option) => ( + + )} + {(now) => {now()[1]}} diff --git a/dashboard/web/types/vms.ts b/dashboard/web/types/vms.ts index cfcfac2bf291de00f79de356182e07b7cdb09c80..6d3898c268d90d3366f510313dadf6ec17b6db44 100644 --- a/dashboard/web/types/vms.ts +++ b/dashboard/web/types/vms.ts @@ -76,10 +76,10 @@ export interface Domain { } export interface GpuShare { - /** Health of the services that need the GPU; null while it's unknown. */ - ai: Health | null; - /** The side a switch under way is giving the GPU to. */ - switching: "games" | "ai" | null; + /** The services that need the GPU; null while they're unknown. */ + services: { id: string; name: string; health: Health }[] | null; + /** The side a switch under way is giving the GPU to: "games" or a service ID. */ + switching: string | null; /** Why the latest switch failed, until another run starts. */ failed: string | null; } diff --git a/nixos/snowglobe.nix b/nixos/snowglobe.nix index 4f3dd43be828a509ab7f2a3e7fa10d93b6937a63..f554450d60cd6a5eb3dc6f420b354d4307047d10 100644 --- a/nixos/snowglobe.nix +++ b/nixos/snowglobe.nix @@ -31,6 +31,9 @@ in networking.firewall.allowedUDPPortRanges = [{ from = xmppNetwork.relay_first; to = xmppNetwork.relay_last; }]; networking.firewall.extraCommands = lib.concatMapStrings ({ address, prefixLength, ... }: '' iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p tcp --dport 445 -j nixos-fw-accept + # Fusion Render Node + iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p tcp -m multiport --dports 1144,49152:49159 -j nixos-fw-accept + iptables -A nixos-fw -i enp4s0 -s ${address}/${toString prefixLength} -p udp -m multiport --dports 1144,49152:49159 -j nixos-fw-accept '') config.networking.interfaces.enp4s0.ipv4.addresses + '' 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 ip6tables -A nixos-fw -i enp4s0 -s fe80::/10 -p tcp --dport 445 -j nixos-fw-accept diff --git a/service/fusion/Dockerfile b/service/fusion/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afe7e4a41a51a58e49cd4dc64543f7bf80c3a5e6 --- /dev/null +++ b/service/fusion/Dockerfile @@ -0,0 +1,40 @@ +FROM docker.io/rockylinux/rockylinux@sha256:7b2eba7b6bf1c5c93f343c5f03a582e4e32ffd7c19187010c6aa2a848bce295a AS installer + +# Fusion Studio 21.1 for Linux; render nodes must match the Fusion Studio version that submits to them. +ARG DOWNLOAD=c2ad9534bf5746cd8a9db063f1cad9b1 +ARG SHA256=a19bb7c95eb0c00abf96f7d236a195da6729f07e9f3b81bbe7fc15869eba816f +ARG RUN=Blackmagic_Fusion_Render_Node_Linux_21.1_installer.run +RUN dnf -y install epel-release && dnf -y install python3 squashfs-tools && dnf clean all +# Studio downloads need no registration details beyond a country. +RUN python3 -I -c 'import hashlib, json, sys, urllib.request, zipfile; \ + agent = {"User-Agent": "Mozilla/5.0"}; \ + 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"}); \ + url = urllib.request.urlopen(request).read().decode(); \ + digest = hashlib.sha256(); \ + out = open("/tmp/fusion.zip", "wb"); \ + response = urllib.request.urlopen(urllib.request.Request(url, headers=agent)); \ + [(digest.update(chunk), out.write(chunk)) for chunk in iter(lambda: response.read(1 << 20), b"")]; \ + out.close(); \ + assert digest.hexdigest() == sys.argv[2], digest.hexdigest(); \ + zipfile.ZipFile("/tmp/fusion.zip").extract(sys.argv[3], "/tmp")' "$DOWNLOAD" "$SHA256" "$RUN" \ + && rm /tmp/fusion.zip +# The installer is an AppImage; its squashfs payload starts where the ELF runtime's section headers end. +RUN offset=$(python3 -I -c 'import struct, sys; header = open(sys.argv[1], "rb").read(64); \ + print(struct.unpack_from("', 'win11-gaming': GPU_GUEST} self.state, self.start_fails, self.shuts_down = 'shut off', False, True - self.jobs = {'local-ai': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'devices': ['/dev/nvidia0', '/dev/nvidiactl']}}]}]}, + gpu_job = lambda stopped: {'Stop': stopped, 'TaskGroups': [{'Tasks': [{'Config': {'devices': ['/dev/nvidia0', '/dev/nvidiactl']}}]}]} + self.jobs = {'local-ai': gpu_job(False), 'fusion': gpu_job(True), 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}} self.polls = {} self.calls = [] @@ -652,7 +653,7 @@ class GpuSwitch(unittest.TestCase): patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]: context.start() self.addCleanup(context.stop) - self.deploy = (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', '--gpu') + self.deploy = lambda job: (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', job) def test_the_gpu_guest_is_the_one_passing_through_an_nvidia_display(self): self.assertTrue(vms.passes_gpu(vms.ET.fromstring(GPU_GUEST))) @@ -665,45 +666,63 @@ class GpuSwitch(unittest.TestCase): self.assertIsNone(vms.gpu_guest()) def test_games_stops_only_gpu_jobs_and_waits_for_them_before_starting_the_guest(self): - vms.switch_gpu('games', 'win11-gaming') + vms.switch_gpu('games') self.assertEqual(self.state, 'running') stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai')) start = self.calls.index(('virsh', 'start', 'win11-gaming')) self.assertLess(stop, start) self.assertEqual(self.polls['local-ai'], 2) self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'jellyfin'), self.calls) - self.assertNotIn(self.deploy, self.calls) + self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'fusion'), self.calls) + self.assertFalse(any(call[0] == vms.sys.executable for call in self.calls)) - def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_ai(self): + def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_the_service_that_had_it(self): self.start_fails = True - with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. AI has it again."): - vms.switch_gpu('games', 'win11-gaming') - self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy)) + with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. local-ai has it again."): + vms.switch_gpu('games') + self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy('local-ai'))) + self.assertNotIn(self.deploy('fusion'), self.calls) - def test_ai_shuts_the_guest_down_before_deploying_the_gpu_services(self): + def test_a_service_takes_the_gpu_from_another_service(self): + vms.switch_gpu('fusion') + self.assertLess(self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai')), self.calls.index(self.deploy('fusion'))) + self.assertEqual(self.polls['local-ai'], 2) + self.assertNotIn(('virsh', 'shutdown', 'win11-gaming'), self.calls) + + def test_a_service_shuts_the_guest_down_before_deploying(self): self.state = 'running' - vms.switch_gpu('ai', 'win11-gaming') - self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy)) - self.assertFalse(any(call[0] == 'nomad' for call in self.calls)) + self.jobs['local-ai']['Stop'] = True + vms.switch_gpu('local-ai') + self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy('local-ai'))) + self.assertFalse(any(call[:3] == ('nomad', 'job', 'stop') for call in self.calls)) def test_a_guest_that_wont_shut_down_keeps_the_gpu(self): self.state, self.shuts_down = 'running', False + self.jobs['local-ai']['Stop'] = True with self.assertRaisesRegex(ValueError, "didn't shut down"): - vms.switch_gpu('ai', 'win11-gaming') - self.assertNotIn(self.deploy, self.calls) + vms.switch_gpu('fusion') + self.assertFalse(any(call[0] == vms.sys.executable for call in self.calls)) - def test_only_the_gpu_guest_switches_and_only_toward_the_other_side(self): - with self.assertRaisesRegex(ValueError, "testbox doesn't use the GPU"): - vms.switch_gpu('games', 'testbox') + def test_only_gpu_sides_switch_and_only_away_from_the_holder(self): + for side, message in [('jellyfin', "jellyfin doesn't use the GPU"), ('local-ai', 'local-ai already has the GPU')]: + with self.subTest(side=side), self.assertRaisesRegex(ValueError, message): + vms.switch_gpu(side) self.state = 'running' - with self.assertRaisesRegex(ValueError, 'already has the GPU'): - vms.switch_gpu('games', 'win11-gaming') - self.assertFalse(any(call[0] in {'nomad', vms.sys.executable} or call[:2] == ('virsh', 'start') for call in self.calls)) + self.jobs['local-ai']['Stop'] = True + with self.assertRaisesRegex(ValueError, 'win11-gaming already has the GPU'): + vms.switch_gpu('games') + del self.domains['win11-gaming'] + with self.assertRaisesRegex(ValueError, 'No VM uses the GPU'): + vms.switch_gpu('games') + self.assertFalse(any(call[0] in {vms.sys.executable} or call[:3] == ('nomad', 'job', 'stop') or call[:2] == ('virsh', 'start') + for call in self.calls)) - def test_deploys_leave_gpu_services_alone_while_the_guest_has_the_gpu(self): + def test_the_holder_is_the_running_guest_else_the_running_gpu_job(self): import snowglobe services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}] self.assertEqual([snowglobe.gpu(item) for item in services], [True, False]) + self.assertEqual(snowglobe.gpu_holder(services), 'local-ai') + self.jobs['local-ai']['Stop'] = True self.assertIsNone(snowglobe.gpu_holder(services)) self.state = 'running' self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming') @@ -711,6 +730,19 @@ class GpuSwitch(unittest.TestCase): self.assertIsNone(snowglobe.gpu_holder(services[1:])) self.assertEqual(self.calls, []) + def test_a_stopped_registration_parses_the_job_and_submits_it_stopped(self): + import snowglobe + submitted = [] + + def command(*args, capture=False): + if '-output' in args: + return SimpleNamespace(stdout=json.dumps({'Job': {'ID': 'fusion'}})) + submitted.append((args, json.loads(Path(args[-1]).read_text()))) + + with patch.object(snowglobe, 'render', return_value='job "fusion" {}'), patch.object(snowglobe, 'command', side_effect=command): + snowglobe.submit({'containers': {'app': {}}}, 'run', {}, stopped=True) + self.assertEqual([(args[:5], job) for args, job in submitted], + [(('nomad', 'job', 'run', '-detach', '-json'), {'Job': {'ID': 'fusion', 'Stop': True}})]) if __name__ == '__main__': unittest.main() diff --git a/tools/fusion.md b/tools/fusion.md new file mode 100644 index 0000000000000000000000000000000000000000..177e3a3f3f6fddf703605cb8b5c4fb1212353e91 --- /dev/null +++ b/tools/fusion.md @@ -0,0 +1,13 @@ +# Fusion Render Node + +`service/fusion` runs Blackmagic's Fusion Render Node under Xvfb. It holds the 3090 only when the dashboard's GPU +switch gives it Fusion; otherwise its job stays registered and stopped. + +- **Version:** a render node only takes jobs from the same Fusion Studio version. The Dockerfile pins the Linux + download ID and SHA-256 from `https://www.blackmagicdesign.com/api/support/us/downloads.json`; bump both when + the Mac's Fusion Studio updates. +- **License:** the node borrows the license from a Fusion Studio found on the LAN, so the Mac's dongle covers it. +- **Paths:** `/srv/clover` mounts at `/Volumes/clover`, the Mac's SMB mount point, so comps render without path + maps. Fonts, OFX plugins and Reactor fuses must be installed in the image too. +- **Network:** host networking; Fusion uses TCP/UDP 1144 and 49152-49159, which the firewall opens to the LAN only. +- **State:** preferences live in the service's `/home/fusion`. diff --git a/tools/snowglobe.py b/tools/snowglobe.py index fa57fabc9668b197118fbebeaca4b919af8f2712..9eb9eb3213f13a6a57718f79df6561e809172dbb 100644 --- a/tools/snowglobe.py +++ b/tools/snowglobe.py @@ -60,12 +60,14 @@ def gpu(data): def gpu_holder(data): - """The guest holding the GPU, which the services that need it must leave alone.""" + """The guest passing the GPU through while it's on, else the running job that needs the GPU.""" if not any(gpu(item) for item in data): return None vms = __import__("vms") guest = vms.gpu_guest() - return guest if guest and vms.virsh("domstate", guest) != "shut off" else None + if guest and vms.virsh("domstate", guest) != "shut off": + return guest + return next((job for job, stopped in vms.gpu_jobs().items() if not stopped), None) def ordered(data): @@ -657,14 +659,21 @@ def provision(data): })) -def submit(data, mode, definitions): +def submit(data, mode, definitions, stopped=False): + """`stopped` registers the job with no allocations, as `nomad job stop` leaves it.""" if not data["containers"]: return with tempfile.NamedTemporaryFile("w", suffix=".nomad.hcl", delete=False) as file: file.write(render(data, definitions)) path = file.name try: - command("nomad", "job", mode, path) + if stopped: + job = json.loads(command("nomad", "job", "run", "-output", path, capture=True).stdout) + job["Job"]["Stop"] = True + Path(path).write_text(json.dumps(job)) + command("nomad", "job", "run", "-detach", "-json", path) + else: + command("nomad", "job", mode, path) finally: Path(path).unlink() @@ -993,10 +1002,7 @@ def main(): parser.add_argument("--media-root") parser.add_argument("--env", action="append", default=[]) parser.add_argument("--key", action="append", default=[]) - parser.add_argument("--gpu", action="store_true") args = parser.parse_args() - if args.gpu and (args.mode != "deploy" or args.name): - parser.error("--gpu deploys every service that needs the GPU, without a service name") if args.computer and (args.mode != "stage" or args.name != "dashboard"): parser.error("--computer requires stage dashboard") if args.mode == "stage" and args.name == "dashboard": @@ -1278,7 +1284,7 @@ def main(): if args.name and args.name not in definitions: raise ValueError(f"unknown service: {args.name}") if not args.name and args.mode == "deploy": - names = [name for name in names if definitions[name]["containers"] and (gpu(definitions[name]) or not args.gpu)] + names = [name for name in names if definitions[name]["containers"]] selected = set(names) while True: required = selected | set().union(*(dependencies(definitions[name]) for name in selected)) @@ -1300,7 +1306,7 @@ def main(): elif args.mode == "check": holder = gpu_holder(data) for item in data: - if holder and gpu(item): + if gpu(item) and item["id"] != holder: continue for task in item["containers"].values(): if task.get("http") and task["http"].get("hostname"): @@ -1334,13 +1340,18 @@ def main(): elif args.mode == "deploy": bootstrap(data) holder = gpu_holder(data) + if args.name and gpu(definitions[args.name]) and holder not in {None, args.name}: + raise ValueError(f"{holder} has the GPU. Switch the GPU to {args.name} from the dashboard.") for item in data: - if holder and gpu(item): - print(f"Skipping {item['id']} while {holder} has the GPU", flush=True) - continue + # Deploys never move the GPU: only its holder runs, or the named service while nothing has it. + stopped = gpu(item) and item["id"] != (holder or args.name) provision_inputs(item, definitions) provision(item) prepare(item) + if stopped: + print(f"Registering {item['id']} stopped while {holder or 'nothing'} has the GPU", flush=True) + submit(item, "run", definitions, stopped=True) + continue build_images(item) submit(item, "run", definitions) configure(item) diff --git a/tools/vms.py b/tools/vms.py index 8714afd4f4954b7f62fe44a37aeb1ad64af4952e..a45b7aa7da02dc27bd7671124899d9d2e9f2822f 100644 --- a/tools/vms.py +++ b/tools/vms.py @@ -413,49 +413,66 @@ def gpu_guest(): if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None) -def switch_gpu(mode, name): - """Hands the GPU to the guest (games) or to the services that need it (ai).""" - if gpu_guest() != name: - raise ValueError(f"{name} doesn't use the GPU.") - release = import_module("release") - deploy = [sys.executable, str(release.check_release(release.current_release()) / "tools/snowglobe.py"), "deploy", "--gpu"] - if mode == "ai": - if virsh("domstate", name) != "shut off": - print(f"Shutting down {name}", flush=True) - virsh("shutdown", name) - if not wait(lambda: virsh("domstate", name) == "shut off", 300): - raise ValueError(f"{name} didn't shut down. Close its apps or force it off, then switch again.") - try: - subprocess.run(deploy, check=True) - except subprocess.CalledProcessError: - raise ValueError("AI couldn't start. Open the Local AI service to see why.") from None - return - if virsh("domstate", name) != "shut off": - raise ValueError(f"{name} already has the GPU.") - environment = {**os.environ, "NOMAD_TOKEN": (release.STATE / "nomad.token").read_text().strip()} +def nomad(*args): + token = (import_module("release").STATE / "nomad.token").read_text().strip() + return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True, + env={**os.environ, "NOMAD_TOKEN": token}).stdout - def nomad(*args): - return subprocess.run(["nomad", *args], check=True, text=True, capture_output=True, env=environment).stdout - def needs_gpu(job): +def gpu_jobs(): + """Nomad jobs that need the GPU, mapped to whether they're stopped.""" + jobs = {} + for job in (entry["Summary"]["JobID"] for entry in json.loads(nomad("job", "status", "-json"))): spec = json.loads(nomad("job", "inspect", "-json", job)) - return not spec.get("Stop") and any(device.startswith("/dev/nvidia") for group in spec["TaskGroups"] - for task in group["Tasks"] for device in (task["Config"] or {}).get("devices") or []) + if any(device.startswith("/dev/nvidia") for group in spec["TaskGroups"] + for task in group["Tasks"] for device in (task["Config"] or {}).get("devices") or []): + jobs[job] = bool(spec.get("Stop")) + return jobs - jobs = [job for job in (entry["Summary"]["JobID"] for entry in json.loads(nomad("job", "status", "-json"))) if needs_gpu(job)] - for job in jobs: + +def switch_gpu(side): + """Hands the GPU to the guest passing it through (games) or to one service that needs it.""" + guest, jobs = gpu_guest(), gpu_jobs() + if side == "games" and not guest: + raise ValueError("No VM uses the GPU.") + if side != "games" and side not in jobs: + raise ValueError(f"{side} doesn't use the GPU.") + on = bool(guest) and virsh("domstate", guest) != "shut off" + holders = [job for job, stopped in jobs.items() if not stopped and job != side] + if side == "games" and on: + raise ValueError(f"{guest} already has the GPU.") + if side != "games" and not on and not holders and not jobs[side]: + raise ValueError(f"{side} already has the GPU.") + release = import_module("release") + script = str(release.check_release(release.current_release()) / "tools/snowglobe.py") + + def deploy(job): + return subprocess.run([sys.executable, script, "deploy", job]).returncode == 0 + + if on: + print(f"Shutting down {guest}", flush=True) + virsh("shutdown", guest) + if not wait(lambda: virsh("domstate", guest) == "shut off", 300): + raise ValueError(f"{guest} didn't shut down. Close its apps or force it off, then switch again.") + for job in holders: print(f"Stopping {job}", flush=True) nomad("job", "stop", "-yes", job) if not wait(lambda: not any(alloc["ClientStatus"] in {"pending", "running"} - for job in jobs for alloc in json.loads(nomad("job", "allocs", "-json", job))), 300): - raise ValueError("AI didn't stop. Open the Local AI service to see why.") - print(f"Starting {name}", flush=True) + for job in holders for alloc in json.loads(nomad("job", "allocs", "-json", job))), 300): + raise ValueError(f"{', '.join(holders)} didn't stop. Open its service page to see why.") + if side != "games": + if not deploy(side): + raise ValueError(f"{side} couldn't start. Open its service page to see why.") + return + print(f"Starting {guest}", flush=True) try: - virsh("start", name) + virsh("start", guest) except subprocess.CalledProcessError as error: print(error.stderr, flush=True) - restored = subprocess.run(deploy).returncode == 0 - raise ValueError(f"{name} couldn't take the GPU. " + ("AI has it again." if restored else "AI couldn't start either. Open the Local AI service to see why.")) from None + restored = all([deploy(job) for job in holders]) # A list, so one failure doesn't skip the rest. + raise ValueError(f"{guest} couldn't take the GPU. " + ( + f"{', '.join(holders)} has it again." if holders and restored + else "Nothing else had it." if restored else "Open the service pages to see why.")) from None def wait(ready, seconds): @@ -1251,9 +1268,9 @@ def main(): if __name__ == "__main__": try: - if sys.argv[1] == "gpu" and len(sys.argv) == 4 and sys.argv[2] in {"games", "ai"}: - ensure_name(sys.argv[3]) - switch_gpu(sys.argv[2], sys.argv[3]) + if sys.argv[1] == "gpu" and len(sys.argv) == 3: + ensure_name(sys.argv[2]) + switch_gpu(sys.argv[2]) sys.exit(0) print(json.dumps(main())) except ValueError as failure: diff --git a/tools/win11-gaming.md b/tools/win11-gaming.md index 480b7bdfdc30b1f755b9d76941d30e9aa333f86f..b5086c1e8f0b7e57990f0a74cabcecc955aaeb52 100644 --- a/tools/win11-gaming.md +++ b/tools/win11-gaming.md @@ -13,7 +13,8 @@ dashboard console / Computer MCP ─── libvirt VNC + guest agent (owner Clov guest ── virbr-ext (forward mode='open') ── MASQUERADE ── internet only ``` -- **GPU:** the 3090 serves either this guest or local AI, chosen with the dashboard's Games/AI switch. The +- **GPU:** the 3090 serves this guest or one GPU service (Local AI, Fusion), chosen with the dashboard's GPU switch. + Deploys never move it: GPU services other than the holder are registered stopped. The domain's `managed='yes'` hostdevs make libvirt move both functions to vfio-pci at start and back to nvidia at shut off; `nvidia-persistenced` stays off so nothing holds the device. Windows Update is barred from driver updates (`ExcludeWUDriversInQualityUpdate`); install GeForce drivers with `-s -n`.