1#!/usr/bin/env python3
2import json
3import contextlib
4import fcntl
5from importlib import import_module
6import os
7from pathlib import Path
8import re
9import secrets
10import shlex
11import shutil
12import signal
13import stat
14import tempfile
15import time
16import subprocess
17import sys
18import xml.etree.ElementTree as ET
19
20
21DISKS = Path("/srv/vm")
22PCI = Path("/sys/bus/pci/devices")
23AI_DISKS = Path(os.environ["SNOWGLOBE_VM_AI_DISKS_ROOT"]) if os.environ.get("SNOWGLOBE_VM_AI_DISKS_ROOT") else None
24IMAGES = Path(os.environ.get("SNOWGLOBE_VM_IMAGES_ROOT", "/srv/clover/Media/vm"))
25PRESETS = Path(os.environ.get("SNOWGLOBE_VM_PRESETS_ROOT", str(IMAGES / "Presets")))
26UPLOADS = Path(os.environ.get("SNOWGLOBE_VM_UPLOADS_ROOT", str(IMAGES / "Install Disks")))
27mac_vms = import_module("mac-vms")
28NS = "{https://paperclover.net/snowglobe}"
29NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}\Z")
30GUEST_CHANNEL = json.loads((Path(__file__).resolve().parent.parent / "guest/protocol.json").read_text())["channel"]
31PROFILES = {
32 "linux-x86-virtio": {
33 "arch": "x86_64", "machine": "q35", "platform": "linux", "firmware": None,
34 "disk": ("vda", "virtio"), "cd": ("sdb", "sata"), "seed": ("sdc", "sata"),
35 "network": "virtio", "usb": "qemu-xhci", "clock": "utc",
36 },
37 "linux-aarch64-virtio": {
38 "arch": "aarch64", "machine": "virt", "platform": "linux", "firmware": "uefi",
39 "disk": ("vda", "virtio"), "cd": ("sda", "scsi"), "seed": ("sdb", "scsi"),
40 "network": "virtio", "usb": "qemu-xhci", "clock": "utc", "emulated": True,
41 "scsi": True, "video": "virtio", "keyboard": "usb", "serial": "ttyAMA0",
42 },
43 "windows-aarch64-nvme": {
44 "arch": "aarch64", "machine": "virt-11.1", "platform": "windows", "firmware": "uefi",
45 "disk": ("nvme0n1", "nvme"), "cd": ("sda", "usb"), "network": "virtio",
46 "usb": "qemu-xhci", "clock": "utc", "emulated": True, "secure": True,
47 "video": "virtio", "keyboard": "usb", "gic": "3", "tpm": "tpm-tis",
48 },
49 "windows-q35-uefi": {
50 "arch": "x86_64", "machine": "q35", "platform": "windows", "firmware": "uefi",
51 "disk": ("sda", "sata"), "cd": ("sdb", "sata"), "network": "e1000e",
52 "usb": "qemu-xhci", "clock": "localtime", "tpm": "tpm-crb", "cpu_mode": "host-passthrough",
53 },
54 "windows-q35-secure": {
55 "arch": "x86_64", "machine": "q35", "platform": "windows", "firmware": "uefi",
56 "disk": ("sda", "sata"), "cd": ("sdb", "sata"), "network": "e1000e",
57 "usb": "qemu-xhci", "clock": "utc", "cpu_mode": "host-passthrough",
58 "tpm": "tpm-crb", "secure": True, "smm": True,
59 },
60 "windows-q35-bios": {
61 "arch": "x86_64", "machine": "pc-q35-10.2", "platform": "windows", "firmware": "bios",
62 "disk": ("sda", "sata"), "cd": ("sdb", "sata"), "network": "e1000e",
63 "usb": "qemu-xhci", "clock": "localtime", "balloon": "none",
64 },
65 "windows-legacy-ide": {
66 "arch": "x86_64", "machine": "pc-i440fx-10.2", "platform": "windows", "firmware": "bios",
67 "disk": ("hda", "ide"), "cd": ("hdc", "ide"), "network": "e1000",
68 "usb": "piix3-uhci", "clock": "localtime", "balloon": "none",
69 },
70 "macos-legacy-q35": {
71 "arch": "x86_64", "machine": "pc-q35-10.2", "platform": "macos", "firmware": "uefi",
72 "disk": ("sda", "sata"), "cd": ("sdb", "sata"), "network": "e1000-82545em",
73 "usb": "ich9-ehci1", "clock": "utc", "cpu": "Penryn", "emulated": True,
74 "keyboard": "usb", "balloon": "none",
75 },
76}
77ACTION_FIELDS = {
78 "node": None, "domains": None, "computers": None, "stats": None,
79 "create": {"name", "description", "image", "vcpus", "memory", "disk", "autostart", "start", "mode", "firmware", "platform", "owner", "username"},
80 "act": {"name", "action"}, "update": {"name", "description", "autostart"},
81 "remove": {"name", "disks"},
82 "library": None, "media": {"name", "image"},
83 "preset": {"name", "id", "os", "description"},
84 "clipboard": {"name", "text"},
85 "computer": {"name", "request"},
86 "console": {"name"}, "serial": {"name"}, "guest": {"name"}, "owner": {"name"}, "access": {"name"}, "upload": {"volume", "size"},
87}
88
89
90def profile(name):
91 try:
92 return PROFILES[name]
93 except KeyError as error:
94 raise ValueError("This VM needs a supported hardware profile.") from error
95
96
97def default_profile(platform, firmware, arch="x86_64"):
98 if platform == "macos":
99 return "macos-legacy-q35"
100 if arch == "aarch64":
101 return "windows-aarch64-nvme" if platform == "windows" else "linux-aarch64-virtio"
102 if platform == "windows":
103 return "windows-q35-uefi" if firmware == "uefi" else "windows-q35-bios"
104 return "linux-x86-virtio"
105
106
107def installer_profile(source, spec):
108 if source:
109 name = source.name.lower()
110 if "windows xp" in name or "windows vista" in name or "windows 7" in name:
111 return "windows-legacy-ide"
112 if "windows 8" in name:
113 return "windows-q35-bios"
114 if "windows 11" in name and architecture(name) == "x86_64":
115 return "windows-q35-secure"
116 arch = architecture(name)
117 else:
118 arch = "x86_64"
119 return default_profile(spec["platform"], spec["firmware"], arch)
120
121
122def inferred_profile(root):
123 stored = root.findtext(f"metadata/{NS}vm/{NS}hardwareProfile")
124 if stored:
125 return stored
126 os_element = root.find("os")
127 type_element = os_element.find("type") if os_element is not None else None
128 arch = type_element.get("arch", "x86_64") if type_element is not None else "x86_64"
129 machine = type_element.get("machine", "") if type_element is not None else ""
130 platform = root.findtext(f"metadata/{NS}vm/{NS}platform", "linux")
131 firmware = "uefi" if (os_element is not None and (os_element.find("loader") is not None or os_element.get("firmware") == "efi")) else "bios"
132 if machine.startswith("pc-i440fx"):
133 return "windows-legacy-ide"
134 return default_profile(platform, firmware, arch)
135
136
137def checked_profile(name, platform, firmware, arch):
138 result = profile(name)
139 if (result["platform"] != platform or result["arch"] != arch
140 or (result["firmware"] and result["firmware"] != firmware)):
141 raise ValueError("This preset needs to be prepared again.")
142 return result
143
144
145def node():
146 memory = next(int(line.split()[1]) * 1024 for line in Path("/proc/meminfo").read_text().splitlines() if line.startswith("MemTotal:"))
147 return {"name": os.uname().nodename, "cpus": os.cpu_count(), "memory": memory}
148
149
150def validate(action, payload):
151 if action not in ACTION_FIELDS:
152 raise ValueError("Choose a supported VM action.")
153 fields = ACTION_FIELDS[action]
154 if fields is None:
155 if payload is not None:
156 raise ValueError("This VM query doesn't take any fields.")
157 return
158 if (not isinstance(payload, dict) or not set(payload) <= fields
159 or (action != "update" and set(payload) != fields)
160 or (action == "update" and ("name" not in payload or len(payload) < 2))):
161 raise ValueError("Use only the fields required by this VM action.")
162 if action == "upload":
163 volume = payload["volume"]
164 if (not isinstance(volume, str) or not volume.lower().endswith(".iso")
165 or len(volume) > 200 or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9 ._()-]*", volume)):
166 raise ValueError("Choose an ISO with a simple filename ending in .iso.")
167 if type(payload["size"]) is not int or not 32768 <= payload["size"] <= 32 * 2**30:
168 raise ValueError("Choose an ISO between 32 KiB and 32 GiB.")
169 return
170 if "name" not in payload:
171 raise ValueError("Enter a VM name.")
172 ensure_name(payload["name"])
173 if action == "computer" and not isinstance(payload["request"], dict):
174 raise ValueError("Send a computer operation.")
175 if "description" in payload and (not isinstance(payload["description"], str) or len(payload["description"]) > 200):
176 raise ValueError("Keep the description under 200 characters.")
177 for field in ("autostart", "start", "disks"):
178 if field in payload and not isinstance(payload[field], bool):
179 raise ValueError(f"Choose whether to enable {field}.")
180 if action == "act" and (not isinstance(payload["action"], str) or payload["action"] not in {"start", "shutdown", "reboot", "reset", "destroy", "resume", "suspend"}):
181 raise ValueError("Choose a supported VM action.")
182 if action == "clipboard" and (not isinstance(payload["text"], str) or len(payload["text"].encode()) > 262144):
183 raise ValueError("Shorten the clipboard text, then send it again.")
184 if action == "preset":
185 ensure_name(payload["id"])
186 if not isinstance(payload["os"], str) or not 1 <= len(payload["os"]) <= 100:
187 raise ValueError("Enter the operating system's name.")
188 if action == "media":
189 validate_image_id(payload["image"], empty=True)
190 if action == "create":
191 if not isinstance(payload["owner"], str) or not re.fullmatch(r"[a-zA-Z0-9_-]{1,128}", payload["owner"]):
192 raise ValueError("Choose a signed-in account to own this VM.")
193 if not isinstance(payload["username"], str) or not 1 <= len(payload["username"]) <= 128:
194 raise ValueError("Choose a signed-in account to create this VM.")
195 if payload["mode"] not in {"iso", "preset"}:
196 raise ValueError("Choose an installer or a prepared preset.")
197 if payload["firmware"] not in {"bios", "uefi"} or payload["platform"] not in {"linux", "windows", "macos"}:
198 raise ValueError("Choose supported firmware and guest hardware.")
199 if payload["platform"] == "macos" and payload["mode"] != "preset":
200 raise ValueError("Use a prepared OS X preset.")
201 image = payload["image"]
202 validate_image_id(image)
203 host = node()
204 for field, minimum, maximum in [("vcpus", 1, host["cpus"]), ("memory", 2**29, host["memory"]), ("disk", 2**30, 2**63 - 1)]:
205 if type(payload[field]) is not int or not minimum <= payload[field] <= maximum:
206 raise ValueError(f"Choose {field} within the host's supported range.")
207 if action == "create" and mac_vms.owns(payload["name"]):
208 raise ValueError("A VM already has this name. Choose another name.")
209 if DISKS.is_symlink() or (DISKS / payload["name"]).is_symlink():
210 raise ValueError("The VM disk directory is a symbolic link. Remove the link before continuing.")
211
212
213@contextlib.contextmanager
214def computer_lock(name, action="computer", identity=None):
215 ensure_name(name)
216 directory = DISKS / name
217 if directory.is_symlink():
218 raise ValueError("The VM disk directory is a symbolic link.")
219 descriptor = os.open(directory / "computer.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
220 with os.fdopen(descriptor, "w") as lock:
221 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
222 operation = {"id": identity or "operation:" + secrets.token_hex(16), "action": action}
223 with computer_control(name):
224 lock.truncate(0)
225 json.dump(operation, lock)
226 lock.flush()
227 yield operation
228
229
230@contextlib.contextmanager
231def computer_control(name):
232 ensure_name(name)
233 directory = DISKS / name
234 if directory.is_symlink():
235 raise ValueError("The VM disk directory is a symbolic link.")
236 descriptor = os.open(directory / "computer-control", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
237 with os.fdopen(descriptor, "r+") as control:
238 fcntl.flock(control, fcntl.LOCK_EX)
239 yield control
240
241
242def computer_cancel(control, identity):
243 control.seek(0)
244 control.truncate()
245 control.write(identity)
246 control.flush()
247
248
249def computer_activity(name):
250 try:
251 with os.fdopen(open_regular(DISKS / name / "computer.lock")) as incoming:
252 try:
253 fcntl.flock(incoming, fcntl.LOCK_SH | fcntl.LOCK_NB)
254 except BlockingIOError:
255 try:
256 operation = json.load(incoming)
257 except ValueError:
258 return {"action": "computer"}
259 operation["age_seconds"] = round(max(0, time.time() - os.fstat(incoming.fileno()).st_mtime), 1)
260 return operation
261 except FileNotFoundError:
262 pass
263 return None
264
265
266def command(*args, pass_fds=(), timeout=None):
267 return subprocess.run(args, check=True, text=True, capture_output=True, pass_fds=pass_fds, timeout=timeout).stdout.strip()
268
269
270def virsh(*args, timeout=None):
271 return command("virsh", "-c", "qemu:///system", *args, timeout=timeout)
272
273
274def info(file):
275 return json.loads(command("qemu-img", "info", "-U", "--output=json", str(file)))
276
277
278def standalone(details):
279 return (details.get("format") in {"raw", "qcow2"} and not details.get("backing-filename")
280 and not details.get("format-specific", {}).get("data", {}).get("data-file"))
281
282
283def disk(file, target, pool):
284 details = info(file) if file.is_file() else {}
285 return {
286 "target": target,
287 "pool": pool,
288 "source": file.name if pool else str(file),
289 "capacity": details.get("virtual-size", file.stat().st_size if file.exists() else 0),
290 "allocation": details.get("actual-size", 0),
291 }
292
293
294def image(file):
295 os_name = file.stem.replace("_", " ").replace("-", " ")
296 windows = "windows" in os_name.lower()
297 return {"volume": image_id(file), "os": os_name, "arch": architecture(file.name),
298 "capacity": file.stat().st_size,
299 "recommended": {"vcpus": 4 if windows else 2, "memory": 4 * 2**30,
300 "disk": (64 if windows else 32) * 2**30}}
301
302
303def domains(*, computers=False):
304 result = []
305 for name in virsh("list", "--all", "--name").splitlines():
306 if not name:
307 continue
308 root = ET.fromstring(virsh("dumpxml", name))
309 state_line = virsh("domstate", name, "--reason").splitlines()[0].lower()
310 state = next((value for value in ("running", "blocked", "paused", "shutdown", "crashed", "pmsuspended") if state_line.startswith(value)), "shutoff")
311 reason = state_line.split("(", 1)[1].rstrip(")") if state in {"paused", "crashed"} and "(" in state_line else None
312 ai = import_module("vm-ai").lease(name)
313 entry = {
314 "name": name, "owner": root.findtext(f"metadata/{NS}vm/{NS}owner"),
315 "platform": root.findtext(f"metadata/{NS}vm/{NS}platform", "linux"),
316 "os": root.findtext(f"metadata/{NS}vm/{NS}os", root.findtext(f"metadata/{NS}os", "Other")),
317 "arch": root.find("./os/type").get("arch"), "state": state,
318 "aiOwned": ai is not None, "ownerOnly": ai is not None,
319 "expiresAt": ai["expiresAt"] if ai else None,
320 "capabilities": ["start", "shutdown", "reboot", "reset", "destroy", "resume", "suspend", "edit", "delete", "media", "preset", "computer"],
321 }
322 if computers:
323 result.append(entry)
324 continue
325 memory = int(root.findtext("memory", "0")) * 1024
326 balloon = int(root.findtext("currentMemory", str(memory // 1024))) * 1024
327 disks = []
328 media = []
329 for element in root.findall("./devices/disk"):
330 if element.findtext("serial") == "snowglobe-cloud-init":
331 continue
332 source = element.find("source")
333 target = element.find("target")
334 if target is not None and element.get("device") == "cdrom":
335 media.append({"target": target.get("dev", ""),
336 "source": Path(source.get("file")).name if source is not None and source.get("file") else None})
337 continue
338 if source is None or target is None:
339 continue
340 file = source.get("file") or source.get("dev")
341 if not file:
342 continue
343 target_name = target.get("dev", "")
344 pool = "vms" if Path(file).is_relative_to(DISKS / name) else None
345 if AI_DISKS is not None and Path(file) == AI_DISKS / (name + ".qcow2"):
346 pool = "vm-disks"
347 disks.append(disk(Path(file), target_name, pool))
348 interfaces = []
349 for element in root.findall("./devices/interface"):
350 mac = element.find("mac")
351 source = element.find("source")
352 interfaces.append({
353 "mac": mac.get("address", "") if mac is not None else "",
354 "source": source.get("network", source.get("bridge", "")) if source is not None else "",
355 "addresses": [],
356 })
357 if state == "running":
358 for line in virsh("domifaddr", name, "--source", "lease").splitlines():
359 fields = line.split()
360 if len(fields) >= 4:
361 interface = next((item for item in interfaces if item["mac"].lower() == fields[1].lower()), None)
362 if interface:
363 interface["addresses"].append(fields[3].split("/", 1)[0])
364 pid_file = Path("/run/libvirt/qemu") / f"{name}.pid"
365 started = None
366 if state == "running" and pid_file.exists():
367 pid = pid_file.read_text().strip()
368 boot = next(int(line.split()[1]) for line in Path("/proc/stat").read_text().splitlines() if line.startswith("btime "))
369 ticks = int(Path(f"/proc/{pid}/stat").read_text().rsplit(") ", 1)[1].split()[19])
370 started = boot + ticks / os.sysconf("SC_CLK_TCK")
371 agent = root.find("./devices/channel/target[@name='org.qemu.guest_agent.0']")
372 setup = root.findtext(f"metadata/{NS}vm/{NS}setup")
373 result.append({
374 **entry,
375 "host": os.uname().nodename,
376 "pendingAction": None,
377 "description": root.findtext("description", ""),
378 "reason": reason,
379 "vcpus": int(root.findtext("vcpu", "1")),
380 "pinned": None,
381 "memory": memory,
382 "balloon": balloon,
383 "autostart": re.search(r"^Autostart:\s+enable", virsh("dominfo", name), re.MULTILINE) is not None,
384 "startedAt": started,
385 "agent": agent.get("state", "disconnected") if agent is not None else None,
386 "setup": windows_setup(name) if setup in {"windows-v3", "windows-v4"} and state == "running" else None,
387 "disks": disks,
388 "media": media,
389 "firmware": "uefi" if root.find("./os/loader") is not None or root.find("os").get("firmware") == "efi" else "bios",
390 "console": root.find("./devices/graphics[@type='vnc']") is not None,
391 "serial": root.find("./devices/console[@type='pty']/target[@type='serial']") is not None,
392 "interfaces": interfaces,
393 "hostdevs": [],
394 "gpu": passes_gpu(root),
395 })
396 return result
397
398
399def passes_gpu(root):
400 """Whether the domain passes through an NVIDIA display controller."""
401 for address in root.findall("./devices/hostdev[@type='pci']/source/address"):
402 device = PCI / "{:04x}:{:02x}:{:02x}.{:x}".format(*(int(address.get(field), 16) for field in ("domain", "bus", "slot", "function")))
403 try:
404 if (device / "vendor").read_text().strip() == "0x10de" and (device / "class").read_text().startswith("0x03"):
405 return True
406 except FileNotFoundError:
407 continue
408 return False
409
410
411def gpu_guest():
412 return next((name for name in virsh("list", "--all", "--name").splitlines()
413 if name and passes_gpu(ET.fromstring(virsh("dumpxml", "--inactive", name)))), None)
414
415
416def 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
420
421
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"))):
426 spec = json.loads(nomad("job", "inspect", "-json", job))
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
451
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:
458 print(f"Stopping {job}", flush=True)
459 nomad("job", "stop", "-yes", job)
460 if not wait(lambda: not any(alloc["ClientStatus"] in {"pending", "running"}
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)
468 try:
469 virsh("start", guest)
470 except subprocess.CalledProcessError as error:
471 print(error.stderr, flush=True)
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
476
477
478def wait(ready, seconds):
479 deadline = time.monotonic() + seconds
480 while not ready():
481 if time.monotonic() > deadline:
482 return False
483 time.sleep(2)
484 return True
485
486
487def windows_setup(name):
488 for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]:
489 try:
490 handle = json.loads(virsh("qemu-agent-command", name, json.dumps({"execute": "guest-file-open", "arguments": {"path": "C:\\Snowglobe\\setup\\" + stage, "mode": "r"}}), "--timeout", "1"))["return"]
491 except (subprocess.CalledProcessError, ValueError, KeyError, TypeError):
492 continue
493 try:
494 virsh("qemu-agent-command", name, json.dumps({"execute": "guest-file-close", "arguments": {"handle": handle}}), "--timeout", "1")
495 except subprocess.CalledProcessError:
496 pass
497 return stage
498 return "starting"
499
500
501def ensure_name(name):
502 if not isinstance(name, str) or not NAME.fullmatch(name):
503 raise ValueError("invalid VM name")
504
505
506def ensure_network():
507 if re.search(r"^Active:\s+no", virsh("net-info", "default"), re.MULTILINE):
508 virsh("net-start", "default")
509 virsh("net-autostart", "default")
510
511
512def validate_image_id(value, empty=False):
513 if not isinstance(value, str) or len(value) > 512 or (not value and not empty):
514 raise ValueError("Choose an installer from the library.")
515 if value in {"", "blank"}:
516 return
517 relative = value.split(":", 1)[1] if value.startswith(("media:", "upload:")) else value
518 if relative.startswith("/") or any(part in {"", ".", ".."} for part in relative.split("/")):
519 raise ValueError("Choose an installer from the library.")
520
521
522def open_regular(file):
523 # Walk with directory FDs so replacing any parent with a symlink cannot escape.
524 parent = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
525 try:
526 for part in file.parts[1:-1]:
527 child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
528 os.close(parent)
529 parent = child
530 fd = os.open(file.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
531 if not stat.S_ISREG(os.fstat(fd).st_mode):
532 os.close(fd)
533 raise ValueError("Choose a regular image file.")
534 return fd
535 finally:
536 os.close(parent)
537
538
539def resolve_image(value):
540 validate_image_id(value)
541 if value.startswith("upload:"):
542 file = UPLOADS / value.removeprefix("upload:")
543 else:
544 file = IMAGES / value.removeprefix("media:")
545 if file.suffix.lower() != ".iso":
546 raise ValueError("Choose a supported installer or disk image.")
547 try:
548 os.close(open_regular(file))
549 except OSError as error:
550 raise ValueError("This image is unavailable. Refresh the library and choose another.") from error
551 return file
552
553
554def architecture(name):
555 text = name.lower()
556 return "aarch64" if any(word in text for word in ("arm64", "aarch64")) else "x86_64"
557
558
559def read_preset(identity):
560 ensure_name(identity)
561 directory = PRESETS / identity
562 try:
563 with os.fdopen(open_regular(directory / "preset.json")) as incoming:
564 result = json.load(incoming)
565 with os.fdopen(open_regular(directory / "disk.qcow2"), "rb") as incoming:
566 details = json.loads(command("qemu-img", "info", "-U", "--output=json", f"/proc/self/fd/{incoming.fileno()}", pass_fds=(incoming.fileno(),)))
567 if not standalone(details) or result["firmware"] not in {"bios", "uefi"} or result["platform"] not in {"linux", "windows", "macos"}:
568 raise ValueError("This preset needs to be prepared again.")
569 if "supersedes" in result:
570 ensure_name(result["supersedes"])
571 result.setdefault("arch", "x86_64")
572 result.setdefault("hardwareProfile", default_profile(result["platform"], result["firmware"], result["arch"]))
573 checked_profile(result["hardwareProfile"], result["platform"], result["firmware"], result["arch"])
574 result["capacity"] = details["virtual-size"]
575 return result
576 except (OSError, KeyError, json.JSONDecodeError) as error:
577 raise ValueError("This preset is unavailable. Refresh the library and choose another.") from error
578
579
580def image_id(file):
581 if file.is_relative_to(IMAGES):
582 return "media:" + file.relative_to(IMAGES).as_posix()
583 return "upload:" + file.relative_to(UPLOADS).as_posix()
584
585
586def library():
587 installers = []
588 roots = [IMAGES]
589 if not UPLOADS.is_relative_to(IMAGES):
590 roots.append(UPLOADS)
591 for base in roots:
592 if not base.is_dir() or base.is_symlink():
593 continue
594 for root, directories, files in os.walk(base, followlinks=False):
595 directories[:] = [name for name in directories if not (Path(root) / name).is_symlink() and not name.startswith(".") and name != "Presets"]
596 for name in files:
597 file = Path(root) / name
598 if file.is_symlink() or file.suffix.lower() != ".iso":
599 continue
600 installers.append(image(file))
601 presets = []
602 directory = PRESETS
603 if directory.is_dir() and not directory.is_symlink():
604 for file in sorted(directory.iterdir()):
605 if not file.is_dir() or file.is_symlink() or not NAME.fullmatch(file.name):
606 continue
607 try:
608 presets.append(read_preset(file.name))
609 except (ValueError, subprocess.CalledProcessError):
610 continue
611 superseded = {item.get("supersedes") for item in presets}
612 return {"installers": sorted(installers, key=lambda item: item["os"].lower()), "presets": [item for item in presets if item["id"] not in superseded], "arch": "x86_64"}
613
614
615def managed_directory(path):
616 path.mkdir(parents=True, exist_ok=True)
617 fd = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
618 try:
619 for part in path.parts[1:]:
620 child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
621 os.close(fd)
622 fd = child
623 finally:
624 os.close(fd)
625
626
627def change_media(spec):
628 name = spec["name"]
629 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))
630 drives = root.findall("./devices/disk[@device='cdrom']")
631 source = resolve_image(spec["image"]) if spec["image"] else None
632 details = profile(inferred_profile(root))
633 if source and architecture(source.name) != details["arch"]:
634 raise ValueError(f"Choose a {details['arch']} ISO for this VM.")
635 directory = DISKS / name
636 managed_directory(directory)
637 frozen = None
638 if source:
639 fd, temporary = tempfile.mkstemp(prefix=source.stem[:70] + "-", suffix=".iso", dir=directory)
640 frozen = Path(temporary)
641 try:
642 with os.fdopen(open_regular(source), "rb") as incoming, os.fdopen(fd, "wb") as outgoing:
643 shutil.copyfileobj(incoming, outgoing)
644 except BaseException:
645 frozen.unlink(missing_ok=True)
646 raise
647 cd = drives[0] if drives else ET.Element("disk", type="file", device="cdrom")
648 target = cd.find("target")
649 if target is None:
650 ET.SubElement(cd, "driver", name="qemu", type="raw")
651 ET.SubElement(cd, "target", dev=details["cd"][0], bus=details["cd"][1])
652 ET.SubElement(cd, "readonly")
653 for element in cd.findall("source"):
654 cd.remove(element)
655 if frozen:
656 ET.SubElement(cd, "source", file=str(frozen))
657 flags = ["--config"]
658 if virsh("domstate", name).strip() != "shut off":
659 if not drives:
660 if frozen:
661 frozen.unlink(missing_ok=True)
662 raise ValueError("Shut down this VM before adding its first CD drive.")
663 flags.extend(["--live", "--force"])
664 xml = directory / "media.xml"
665 xml.write_bytes(ET.tostring(cd))
666 try:
667 virsh("update-device" if drives else "attach-device", name, str(xml), *flags)
668 except BaseException:
669 # A live/config update can partially succeed. Keep media referenced by either XML.
670 if frozen and str(frozen) not in virsh("dumpxml", name) + virsh("dumpxml", name, "--inactive"):
671 frozen.unlink(missing_ok=True)
672 raise
673 # Only collect managed optical images no longer referenced by either definition.
674 references = virsh("dumpxml", name) + virsh("dumpxml", name, "--inactive")
675 for file in directory.glob("*.iso"):
676 if str(file) not in references:
677 file.unlink()
678
679
680def save_preset(spec):
681 name = spec["name"]
682 if virsh("domstate", name).strip() != "shut off":
683 raise ValueError("Shut down this VM before saving a preset.")
684 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))
685 if root.findtext(f"metadata/{NS}vm/{NS}platform") == "macos":
686 raise ValueError("Use a prepared OS X preset from the OS library.")
687 if root.findtext(f"metadata/{NS}vm/{NS}setup") in {"windows-v2", "windows-v3", "windows-v4"} and spec.get("setup") not in {"windows-v3", "windows-v4"}:
688 raise ValueError("Prepare a Windows template before publishing another preset.")
689 disks = root.findall("./devices/disk[@device='disk']")
690 if len(disks) != 1 or root.findall("./devices/hostdev"):
691 raise ValueError("Use a VM with one disk and no passed-through devices.")
692 source = disks[0].find("source")
693 if source is None or not source.get("file"):
694 raise ValueError("Use a VM with a managed disk.")
695 file = Path(source.get("file"))
696 if not file.is_relative_to(DISKS / name) and not ((DISKS / name / "ai.json").is_file() and file == disposable_disk(name)):
697 raise ValueError("Use a disk stored with this VM.")
698 base = PRESETS
699 managed_directory(base)
700 target = base / spec["id"]
701 if target.exists():
702 raise ValueError("A preset already has this name. Choose another name.")
703 temporary = Path(tempfile.mkdtemp(prefix=".preparing-", dir=base))
704 try:
705 # Copy from a verified FD; never follow a swapped symlink to a host file.
706 with os.fdopen(open_regular(file), "rb") as incoming:
707 command("cp", "--reflink=auto", "--sparse=always", f"/proc/self/fd/{incoming.fileno()}", str(temporary / "source"), pass_fds=(incoming.fileno(),))
708 details = info(temporary / "source")
709 if not standalone(details):
710 backing = Path(details.get("backing-filename", ""))
711 if (details.get("format") != "qcow2" or details.get("format-specific", {}).get("data", {}).get("data-file")
712 or backing.parent.parent != PRESETS or backing.name != "disk.qcow2"):
713 raise ValueError("Use a standalone disk or an overlay of a prepared preset.")
714 read_preset(backing.parent.name)
715 command("qemu-img", "convert", "-O", "qcow2", str(temporary / "source"), str(temporary / "disk.qcow2"))
716 (temporary / "source").unlink()
717 os_element = root.find("os")
718 firmware = "uefi" if root.find("./os/loader") is not None or os_element.get("firmware") == "efi" else "bios"
719 platform = root.findtext(f"metadata/{NS}vm/{NS}platform", "linux")
720 hardware_profile = inferred_profile(root)
721 type_element = os_element.find("type")
722 arch = type_element.get("arch", "x86_64")
723 checked_profile(hardware_profile, platform, firmware, arch)
724 # Boot entries and signed EFI variables belong to the prepared image.
725 nvram = root.findtext("./os/nvram")
726 if nvram:
727 with os.fdopen(open_regular(Path(nvram)), "rb") as incoming, (temporary / "nvram.fd").open("xb") as outgoing:
728 shutil.copyfileobj(incoming, outgoing)
729 preset = {"id": spec["id"], "os": spec["os"], "description": spec["description"],
730 "firmware": firmware, "platform": platform, "arch": arch, "hardwareProfile": hardware_profile,
731 "capacity": details["virtual-size"], "createdAt": int(time.time()),
732 "recommended": {"vcpus": int(root.findtext("vcpu", "2")),
733 "memory": int(root.findtext("memory")) * 1024, "disk": details["virtual-size"]}}
734 if spec.get("setup") in {"windows-v3", "windows-v4"} and platform == "windows":
735 preset["setup"] = spec["setup"]
736 if supersedes := spec.get("supersedes"):
737 ensure_name(supersedes)
738 preset["supersedes"] = supersedes
739 (temporary / "preset.json").write_text(json.dumps(preset))
740 # rename won't overwrite a nonempty preset, including a concurrent publication.
741 temporary.rename(target)
742 finally:
743 if temporary.exists():
744 shutil.rmtree(temporary)
745
746
747def console_target(name, *, timeout=None):
748 root = ET.fromstring(virsh("dumpxml", name, timeout=timeout))
749 graphics = root.find("./devices/graphics[@type='vnc']")
750 if virsh("domstate", name, timeout=timeout).strip() not in {"running", "paused", "blocked"} or graphics is None:
751 raise ValueError("Start this VM before opening its screen.")
752 # Only libvirt's loopback VNC listener; callers cannot provide a host or port.
753 if graphics.get("listen") != "127.0.0.1" or graphics.get("socket"):
754 raise ValueError("Configure this VM's VNC screen to listen on 127.0.0.1.")
755 port = int(graphics.get("port", "-1"))
756 if not 5900 <= port <= 65535:
757 raise ValueError("This VM's screen is not ready. Try again shortly.")
758 return {"port": port, "uuid": root.findtext("uuid")}
759
760
761def secure_firmware(arch):
762 firmware = "AAVMF" if arch == "aarch64" else "OVMF"
763 code = Path(os.environ.get(f"SNOWGLOBE_VM_SECURE_{firmware}_CODE", ""))
764 variables = Path(os.environ.get(f"SNOWGLOBE_VM_SECURE_{firmware}_VARS", ""))
765 if not code.is_absolute() or not variables.is_absolute():
766 raise ValueError("Secure UEFI firmware is unavailable on this host.")
767 try:
768 for file in [code, variables]:
769 os.close(open_regular(file))
770 except OSError as error:
771 raise ValueError("Secure UEFI firmware is unavailable on this host.") from error
772 return code, variables
773
774
775def copy_regular(source, target):
776 with os.fdopen(open_regular(source), "rb") as incoming, target.open("xb") as outgoing:
777 shutil.copyfileobj(incoming, outgoing)
778
779
780def guest_access(directory, username, hostname):
781 password = secrets.token_urlsafe(18)
782 with open(directory / "access.json", "x", opener=lambda path, flags: os.open(path, flags, 0o600)) as outgoing:
783 json.dump({"username": username, "password": password, "hostname": hostname}, outgoing)
784 return password
785
786
787def linux_seed(directory, username, os_name, serial="ttyS0"):
788 if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", username) or username == "root":
789 raise ValueError("Use an account username suitable for a Linux guest.")
790 hostname = "snowglobe-vm-" + secrets.token_hex(4)
791 password = guest_access(directory, username, hostname)
792 hashed = subprocess.run(["openssl", "passwd", "-6", "-stdin"], input=password + "\n", text=True, capture_output=True, check=True).stdout.strip()
793 fedora = "fedora" in os_name.lower()
794 nixos = "nixos" in os_name.lower()
795 account_tool = "/run/current-system/sw/bin/" if nixos else ""
796 gdm_config = "/etc/gdm/custom.conf" if fedora or nixos else "/etc/gdm3/custom.conf"
797 gdm_content = f"[daemon]\nAutomaticLoginEnable=true\nAutomaticLogin={username}\n"
798 personalize = f'''set -eu
799old=$({account_tool}getent passwd 1000 | cut -d: -f1)
800test -n "$old"
801if [ "$old" != {username} ]; then
802 ! {account_tool}getent passwd {username}
803 if [ -e /home/{username} ]; then
804 {account_tool}usermod -l {username} -c {username} "$old"
805 else
806 {account_tool}usermod -l {username} -c {username} -d /home/{username} -m "$old"
807 fi
808 if [ "$({account_tool}getent group 1000 | cut -d: -f1)" = "$old" ]; then {account_tool}groupmod -n {username} "$old"; fi
809fi
810'''
811 if fedora:
812 personalize += "printf '%s' " + shlex.quote(gdm_content) + " > " + shlex.quote(gdm_config) + "\n"
813 personalize += '''for service in accounts-daemon.service display-manager.service; do
814 if systemctl is-active --quiet "$service"; then systemctl restart "$service"; fi
815done
816'''
817 files = [] if fedora else [{"path": gdm_config, "content": gdm_content}]
818 if not nixos:
819 files.insert(0, {"path": "/etc/ssh/sshd_config.d/00-snowglobe.conf", "permissions": "0600", "content": "PasswordAuthentication yes\nPermitRootLogin yes\n"})
820 else:
821 files.append({"path": "/var/lib/snowglobe/hostname", "content": hostname + "\n"})
822 guest = Path(__file__).resolve().parent.parent / "guest"
823 files.extend([
824 {"path": "/usr/local/libexec/snowglobe-computer.py", "permissions": "0755", "content": (guest / "computer-linux.py").read_text()},
825 {"path": "/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer", "permissions": "0755", "content": (guest / "computer-linux-launch").read_text()},
826 ])
827 computer_setup = []
828 if fedora:
829 computer_setup = [["setsebool", "-P", "virt_qemu_ga_run_unconfined", "on"], ["restorecon", "-R", "/etc/qemu-ga/fsfreeze-hook.d"]]
830 if nixos:
831 files.append({"path": "/var/lib/snowglobe/computer.nix", "content": (guest / "computer-linux.nix").read_text()})
832 computer_setup = [["/run/current-system/sw/bin/bash", "-lc", "nix-env --profile /var/lib/snowglobe/computer -if /var/lib/snowglobe/computer.nix"]]
833 config = {
834 "users": [], "disable_root": False, "ssh_pwauth": True, "ssh_deletekeys": True,
835 "bootcmd": ([["rm", "-f", gdm_config]] if nixos else []) + [
836 (["cloud-init-per", "instance", "snowglobe-desktop"] if fedora else []) + ["sh", "-c", personalize]],
837 "chpasswd": {"expire": False, "users": [{"name": user, "password": hashed, "type": "hash"} for user in [username, "root"]]},
838 "write_files": files,
839 "runcmd": [["systemctl", "enable", "--now", "sshd" if fedora or nixos else "ssh"], ["systemctl", "enable", "--now", f"serial-getty@{serial}.service"]] + computer_setup,
840 }
841 if not nixos:
842 config["packages"] = ["python3", "python3-gobject", "at-spi2-core"] if fedora else ["python3", "python3-gi", "gir1.2-atspi-2.0"]
843 with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary:
844 files = Path(temporary)
845 (files / "user-data").write_text("#cloud-config\n" + json.dumps(config))
846 (files / "meta-data").write_text(json.dumps({"instance-id": secrets.token_hex(16), "local-hostname": hostname}))
847 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "cidata", "-joliet", "-rock", str(files / "user-data"), str(files / "meta-data"))
848
849
850def windows_seed(directory, username, *, rename=True):
851 if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,19}", username):
852 raise ValueError("Use an account username suitable for a Windows guest.")
853 hostname = "sgvm-" + secrets.token_hex(4) if rename else ""
854 password = guest_access(directory, username, hostname)
855 with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary:
856 marker = Path(temporary) / "SNOWGLOB.INI"
857 marker.write_text(f"[snowglobe]\nUSERNAME={username}\nPASSWORD={password}\n" + (f"HOSTNAME={hostname}\n" if rename else ""))
858 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "SNOWGLOBE", "-joliet", "-rock", str(marker))
859
860
861def macos_seed(directory, username):
862 if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", username) or username == "root":
863 raise ValueError("Use an account username suitable for an OS X guest.")
864 hostname = "snowglobe-vm-" + secrets.token_hex(4)
865 password = guest_access(directory, username, hostname)
866 command("ssh-keygen", "-q", "-t", "rsa", "-b", "3072", "-m", "PEM", "-N", "", "-f", str(directory / "ssh_key"))
867 with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary:
868 files = Path(temporary)
869 (files / "access.json").write_text(json.dumps({"username": username, "password": password, "hostname": hostname}))
870 (files / "authorized_keys").write_text('from="10.0.2.2",no-agent-forwarding,no-port-forwarding,no-X11-forwarding ' + (directory / "ssh_key.pub").read_text())
871 command("ssh-keygen", "-q", "-t", "rsa", "-b", "3072", "-m", "PEM", "-N", "", "-f", str(files / "ssh_host_rsa_key"))
872 (directory / "ssh_known_hosts").write_text(directory.name + " " + (files / "ssh_host_rsa_key.pub").read_text())
873 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "SNOWGLOBE", "-joliet", "-rock", str(files))
874 (directory / "ssh_key.pub").unlink()
875 (directory / "seed.iso").chmod(0o600)
876
877
878def disposable_disk(name):
879 if AI_DISKS is None:
880 return DISKS / name / "disk.qcow2"
881 if AI_DISKS.is_symlink() or not AI_DISKS.is_mount():
882 raise ValueError("Test VM storage is unavailable. Ask an administrator to check the SSD mount.")
883 return AI_DISKS / (name + ".qcow2")
884
885
886def create(spec, *, ai=False):
887 name = spec["name"]
888 ensure_name(name)
889 if name in virsh("list", "--all", "--name").splitlines():
890 raise ValueError("VM already exists")
891 selected = spec["image"]
892 mode = spec["mode"]
893 preset = None
894 if mode == "preset":
895 ensure_name(selected)
896 preset = read_preset(selected)
897 source = PRESETS / selected / "disk.qcow2"
898 profile_name = preset["hardwareProfile"]
899 spec = {**spec, "firmware": preset["firmware"], "platform": preset["platform"]}
900 else:
901 source = resolve_image(selected) if selected != "blank" else None
902 profile_name = installer_profile(source, spec)
903 details_profile = profile(profile_name)
904 spec = {**spec, "firmware": details_profile["firmware"] or spec["firmware"], "platform": details_profile["platform"]}
905 if spec["platform"] == "macos" and spec["vcpus"] != 1:
906 raise ValueError("Use one vCPU for this OS X preset.")
907 if not preset and source and architecture(source.name) != details_profile["arch"]:
908 raise ValueError(f"Choose a {details_profile['arch']} ISO for this hardware profile.")
909 if mode == "preset" and spec["disk"] < preset["capacity"]:
910 raise ValueError("Choose a disk at least as large as the preset.")
911 directory = DISKS / name
912 drive = disposable_disk(name) if ai else directory / "disk.qcow2"
913 pool = "vm-disks" if drive.parent != directory else "vms"
914 pool_root = drive.parent if drive.parent != directory else DISKS
915 if pool not in virsh("pool-list", "--all", "--name").splitlines():
916 pool_root.mkdir(parents=True, exist_ok=True)
917 virsh("pool-define-as", pool, "dir", "--target", str(pool_root))
918 if re.search(r"^State:\s+inactive", virsh("pool-info", pool), re.MULTILINE):
919 virsh("pool-start", pool)
920 virsh("pool-autostart", pool)
921 directory.mkdir(mode=0o700, parents=True, exist_ok=False)
922
923 def expired(_signum, _frame):
924 raise TimeoutError("VM image preparation timed out.")
925
926 previous = signal.signal(signal.SIGALRM, expired)
927 signal.alarm(840)
928 external_created = False
929 try:
930 if ai:
931 (directory / "ai.json").write_text(json.dumps({"expiresAt": int(time.time()) + import_module("vm-ai").LIMITS["idle_seconds"]}))
932 if drive.parent != directory:
933 with drive.open("xb"):
934 pass
935 external_created = True
936 os_name = "Other"
937 overlay = preset and not (spec["platform"] == "macos" and spec["disk"] > preset["capacity"])
938 if overlay:
939 os_name = preset["os"]
940 with os.fdopen(open_regular(source), "rb") as incoming:
941 details = json.loads(command("qemu-img", "info", "-U", "--output=json", f"/proc/self/fd/{incoming.fileno()}", pass_fds=(incoming.fileno(),)))
942 if not standalone(details):
943 raise ValueError("This preset needs to be prepared again.")
944 command("qemu-img", "create", "-u", "-f", "qcow2", "-F", details["format"], "-b", str(source), str(drive), str(spec["disk"]))
945 elif source:
946 source_fd = open_regular(source)
947 frozen = directory / (source.name if source.suffix.lower() == ".iso" else "source-image")
948 with os.fdopen(source_fd, "rb") as incoming:
949 if source.suffix.lower() == ".iso":
950 with frozen.open("xb") as outgoing:
951 shutil.copyfileobj(incoming, outgoing)
952 else:
953 command("cp", "--reflink=auto", "--sparse=always", f"/proc/self/fd/{incoming.fileno()}", str(frozen), pass_fds=(incoming.fileno(),))
954 details = info(frozen) if source.suffix.lower() != ".iso" else {}
955 if source.suffix.lower() != ".iso" and not standalone(details):
956 raise ValueError("Use a standalone raw or QCOW2 image without external data files.")
957 os_name = preset["os"] if preset else source.stem.replace("_", " ").replace("-", " ")
958 if details.get("virtual-size", 0) > spec["disk"]:
959 raise ValueError("Choose a disk at least as large as the OS image.")
960 source = frozen
961 if not overlay and source and source.suffix.lower() != ".iso":
962 if spec["platform"] == "macos" and spec["disk"] > details["virtual-size"]:
963 expanded = directory / "expanded.raw"
964 command("qemu-img", "convert", "-O", "raw", str(source), str(expanded))
965 command("qemu-img", "resize", "-f", "raw", str(expanded), str(spec["disk"]))
966 command("sgdisk", "--move-second-header", str(expanded))
967 command("qemu-img", "convert", "-O", "qcow2", str(expanded), str(drive))
968 expanded.unlink()
969 else:
970 command("qemu-img", "convert", "-O", "qcow2", str(source), str(drive))
971 if spec["disk"] > info(drive)["virtual-size"]:
972 command("qemu-img", "resize", str(drive), str(spec["disk"]))
973 source.unlink()
974 elif not overlay:
975 command("qemu-img", "create", "-f", "qcow2", str(drive), str(spec["disk"]))
976 virsh("pool-refresh", pool)
977 domain_type = "qemu" if details_profile.get("emulated") or os.environ.get("SNOWGLOBE_VM_ACCEL") == "qemu" else "kvm"
978 root = ET.Element("domain", type=domain_type)
979 ET.SubElement(root, "name").text = name
980 ET.SubElement(root, "description").text = spec["description"]
981 metadata = ET.SubElement(ET.SubElement(root, "metadata"), NS + "vm")
982 ET.SubElement(metadata, NS + "os").text = os_name
983 ET.SubElement(metadata, NS + "platform").text = spec["platform"]
984 ET.SubElement(metadata, NS + "hardwareProfile").text = profile_name
985 ET.SubElement(metadata, NS + "owner").text = spec["owner"]
986 if preset and preset.get("setup") in {"windows-v3", "windows-v4"}:
987 ET.SubElement(metadata, NS + "setup").text = preset["setup"]
988 ET.SubElement(root, "memory", unit="bytes").text = str(spec["memory"])
989 ET.SubElement(root, "vcpu").text = str(spec["vcpus"])
990 firmware = spec["firmware"]
991 os_element = ET.SubElement(root, "os")
992 if firmware == "uefi":
993 if details_profile.get("secure"):
994 code, variables = secure_firmware(details_profile["arch"])
995 if preset and (PRESETS / selected / "nvram.fd").exists():
996 variables = PRESETS / selected / "nvram.fd"
997 nvram = directory / "nvram.fd"
998 copy_regular(variables, nvram)
999 loader = ET.SubElement(os_element, "loader", readonly="yes", type="pflash")
1000 # Libvirt restricts the secure attribute to q35; AAVMF's enrolled variables enable it on ARM.
1001 if details_profile["arch"] == "x86_64":
1002 loader.set("secure", "yes")
1003 loader.text = str(code)
1004 ET.SubElement(os_element, "nvram", template=str(variables), templateFormat="raw", format="raw").text = str(nvram)
1005 else:
1006 os_element.set("firmware", "efi")
1007 if preset and (PRESETS / selected / "nvram.fd").exists():
1008 nvram = directory / "nvram.fd"
1009 copy_regular(PRESETS / selected / "nvram.fd", nvram)
1010 ET.SubElement(os_element, "nvram").text = str(nvram)
1011 features = ET.SubElement(os_element, "firmware")
1012 ET.SubElement(features, "feature", enabled="no", name="secure-boot")
1013 ET.SubElement(os_element, "type", arch=details_profile["arch"], machine=details_profile["machine"]).text = "hvm"
1014 ET.SubElement(os_element, "boot", dev="cdrom" if source and source.suffix.lower() == ".iso" else "hd")
1015 if source and source.suffix.lower() == ".iso":
1016 ET.SubElement(os_element, "boot", dev="hd")
1017 if not preset:
1018 ET.SubElement(os_element, "bootmenu", enable="yes", timeout="5000")
1019 features = ET.SubElement(root, "features")
1020 ET.SubElement(features, "acpi")
1021 if details_profile["arch"] == "x86_64":
1022 ET.SubElement(features, "apic")
1023 if profile_name == "windows-q35-uefi":
1024 hyperv = ET.SubElement(features, "hyperv", mode="custom")
1025 for feature in ["relaxed", "vapic", "vpindex", "synic", "stimer", "frequencies", "tlbflush", "ipi"]:
1026 ET.SubElement(hyperv, feature, state="on")
1027 ET.SubElement(hyperv, "spinlocks", state="on", retries="8191")
1028 if gic := details_profile.get("gic"):
1029 ET.SubElement(features, "gic", version=gic)
1030 if details_profile.get("smm"):
1031 ET.SubElement(features, "smm", state="on")
1032 if cpu_mode := details_profile.get("cpu_mode"):
1033 ET.SubElement(root, "cpu", mode=cpu_mode, check="none", migratable="on")
1034 elif details_profile.get("cpu"):
1035 cpu = ET.SubElement(root, "cpu", mode="custom", match="exact", check="full")
1036 ET.SubElement(cpu, "model", fallback="forbid").text = details_profile["cpu"]
1037 ET.SubElement(cpu, "feature", policy="require", name="hypervisor")
1038 elif root.get("type") == "qemu":
1039 ET.SubElement(root, "cpu", mode="maximum")
1040 if spec["platform"] == "windows":
1041 cpu = root.find("cpu")
1042 if cpu is None:
1043 cpu = ET.SubElement(root, "cpu")
1044 ET.SubElement(cpu, "topology", sockets="1", cores=str(spec["vcpus"]), threads="1")
1045 clock = ET.SubElement(root, "clock", offset=details_profile["clock"])
1046 if profile_name == "windows-q35-uefi":
1047 ET.SubElement(clock, "timer", name="hypervclock", present="yes")
1048 ET.SubElement(root, "on_poweroff").text = "destroy"
1049 ET.SubElement(root, "on_reboot").text = "restart"
1050 ET.SubElement(root, "on_crash").text = "destroy"
1051 devices = ET.SubElement(root, "devices")
1052 emulator = f"/run/current-system/sw/bin/qemu-system-{details_profile['arch']}"
1053 if profile_name == "windows-aarch64-nvme":
1054 emulator = os.environ.get("SNOWGLOBE_VM_WINDOWS_ARM_EMULATOR", "")
1055 if not Path(emulator).is_absolute():
1056 raise ValueError("Windows ARM is unavailable on this host. Choose another OS.")
1057 ET.SubElement(devices, "emulator").text = emulator
1058 if details_profile.get("scsi"):
1059 ET.SubElement(devices, "controller", type="scsi", index="0", model="virtio-scsi")
1060 primary = ET.SubElement(devices, "disk", type="file", device="disk")
1061 ET.SubElement(primary, "driver", name="qemu", type="qcow2")
1062 ET.SubElement(primary, "source", file=str(drive))
1063 ET.SubElement(primary, "target", dev=details_profile["disk"][0], bus=details_profile["disk"][1])
1064 if details_profile["disk"][1] == "nvme":
1065 ET.SubElement(primary, "serial").text = "snowglobe"
1066 cd = ET.SubElement(devices, "disk", type="file", device="cdrom")
1067 ET.SubElement(cd, "driver", name="qemu", type="raw")
1068 if source and source.suffix.lower() == ".iso":
1069 ET.SubElement(cd, "source", file=str(source))
1070 ET.SubElement(cd, "target", dev=details_profile["cd"][0], bus=details_profile["cd"][1])
1071 ET.SubElement(cd, "readonly")
1072 if preset and spec["platform"] == "linux":
1073 linux_seed(directory, spec["username"], preset["os"], details_profile.get("serial", "ttyS0"))
1074 seed = ET.SubElement(devices, "disk", type="file", device="cdrom")
1075 ET.SubElement(seed, "driver", name="qemu", type="raw")
1076 ET.SubElement(seed, "source", file=str(directory / "seed.iso"))
1077 ET.SubElement(seed, "target", dev=details_profile["seed"][0], bus=details_profile["seed"][1])
1078 ET.SubElement(seed, "serial").text = "snowglobe-cloud-init"
1079 ET.SubElement(seed, "readonly")
1080 if preset and spec["platform"] == "windows":
1081 windows_seed(directory, spec["username"], rename=preset.get("setup") != "windows-v4")
1082 ET.SubElement(cd, "source", file=str(directory / "seed.iso"))
1083 ET.SubElement(cd, "serial").text = "snowglobe-provision"
1084 if spec["platform"] == "macos":
1085 macos_seed(directory, spec["username"])
1086 ET.SubElement(cd, "source", file=str(directory / "seed.iso"))
1087 qemu_ns = "http://libvirt.org/schemas/domain/qemu/1.0"
1088 ET.register_namespace("qemu", qemu_ns)
1089 arguments = ET.SubElement(root, "{" + qemu_ns + "}commandline")
1090 for argument in [
1091 "-device", "isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc",
1092 "-smbios", "type=2", "-netdev", "user,id=osxnet,restrict=yes,hostfwd=tcp:127.0.0.1:0-:22",
1093 "-device", details_profile["network"] + ",netdev=osxnet,bus=pcie.0,addr=0x12",
1094 ]:
1095 ET.SubElement(arguments, "{" + qemu_ns + "}arg", value=argument)
1096 else:
1097 nic = ET.SubElement(devices, "interface", type="network")
1098 ET.SubElement(nic, "source", network="default")
1099 ET.SubElement(nic, "model", type=details_profile["network"])
1100 ET.SubElement(devices, "graphics", type="vnc", port="-1", autoport="yes", listen="127.0.0.1")
1101 video = {"type": details_profile.get("video", "vga"), "heads": "1", "primary": "yes"}
1102 if video["type"] == "vga":
1103 video["vram"] = "16384"
1104 ET.SubElement(ET.SubElement(devices, "video"), "model", **video)
1105 ET.SubElement(devices, "input", type="tablet", bus="usb")
1106 if keyboard := details_profile.get("keyboard"):
1107 ET.SubElement(devices, "input", type="keyboard", bus=keyboard)
1108 usb = ET.SubElement(devices, "controller", type="usb", index="0", model=details_profile["usb"])
1109 if spec["platform"] == "macos":
1110 ET.SubElement(usb, "address", type="pci", domain="0x0000", bus="0x00", slot="0x1d", function="0x7")
1111 for index in range(3):
1112 controller = ET.SubElement(devices, "controller", type="usb", index="0", model=f"ich9-uhci{index + 1}")
1113 ET.SubElement(controller, "master", startport=str(index * 2))
1114 ET.SubElement(controller, "address", type="pci", domain="0x0000", bus="0x00", slot="0x1d", function=hex(index), **({"multifunction": "on"} if index == 0 else {}))
1115 if details_profile.get("tpm"):
1116 tpm = ET.SubElement(devices, "tpm", model=details_profile["tpm"])
1117 ET.SubElement(tpm, "backend", type="emulator", version="2.0")
1118 if details_profile.get("balloon"):
1119 ET.SubElement(devices, "memballoon", model=details_profile["balloon"])
1120 if spec["platform"] != "macos":
1121 ET.SubElement(devices, "console", type="pty")
1122 ET.SubElement(devices, "channel", type="unix").append(ET.Element("target", type="virtio", name="org.qemu.guest_agent.0"))
1123 ET.SubElement(devices, "channel", type="unix").append(ET.Element("target", type="virtio", name=GUEST_CHANNEL))
1124 xml = directory / "domain.xml"
1125 xml.write_bytes(ET.tostring(root))
1126 signal.alarm(0)
1127 virsh("define", str(xml))
1128 if spec["autostart"]:
1129 virsh("autostart", name)
1130 if spec["start"]:
1131 if spec["platform"] != "macos":
1132 ensure_network()
1133 virsh("start", name)
1134 except Exception:
1135 signal.alarm(0)
1136 if name not in virsh("list", "--all", "--name").splitlines():
1137 if external_created:
1138 drive.unlink()
1139 for file in directory.iterdir():
1140 file.unlink()
1141 directory.rmdir()
1142 raise
1143 finally:
1144 signal.alarm(0)
1145 signal.signal(signal.SIGALRM, previous)
1146
1147
1148def remove(spec, *, missing_ok=False):
1149 name = spec["name"]
1150 ensure_name(name)
1151 exists = name in virsh("list", "--all", "--name").splitlines()
1152 if not exists and not missing_ok:
1153 raise ValueError("VM does not exist")
1154 directory = DISKS / name
1155 external = None
1156 if spec["disks"] and (directory / "ai.json").is_file() and AI_DISKS is not None:
1157 candidate = AI_DISKS / (name + ".qcow2")
1158 if exists:
1159 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))
1160 if any(source.get("file") == str(candidate) for source in root.findall("./devices/disk[@device='disk']/source")):
1161 external = disposable_disk(name)
1162 elif not (directory / "disk.qcow2").exists():
1163 external = disposable_disk(name)
1164 if exists:
1165 if virsh("domstate", name).strip() != "shut off":
1166 virsh("destroy", name)
1167 root = ET.fromstring(virsh("dumpxml", name))
1168 virsh("undefine", name, "--managed-save", *(["--nvram"] if root.find("./os/nvram") is not None else []), *(["--tpm"] if root.find("./devices/tpm") is not None else []))
1169 if external is not None:
1170 external.unlink(missing_ok=True)
1171 if spec["disks"] and directory.is_dir():
1172 for file in directory.iterdir():
1173 file.unlink()
1174 directory.rmdir()
1175
1176
1177def main():
1178 action = sys.argv[1]
1179 payload = json.loads(sys.argv[2]) if len(sys.argv) > 2 else None
1180 validate(action, payload)
1181 if action == "node":
1182 return node()
1183 if action in {"domains", "computers"}:
1184 return domains(computers=action == "computers") + mac_vms.domain()
1185 if action == "stats":
1186 result = {}
1187 for name in virsh("list", "--name").splitlines():
1188 pid_file = Path("/run/libvirt/qemu") / f"{name}.pid"
1189 if not pid_file.exists():
1190 continue
1191 pid = pid_file.read_text().strip()
1192 fields = Path(f"/proc/{pid}/stat").read_text().rsplit(") ", 1)[1].split()
1193 resident = int(Path(f"/proc/{pid}/statm").read_text().split()[1]) * os.sysconf("SC_PAGE_SIZE")
1194 result[name] = {"cpu": (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK"), "memory": resident,
1195 "vcpus": int(ET.fromstring(virsh("dumpxml", name)).findtext("vcpu", "1"))}
1196 return result
1197 if action == "library":
1198 return library()
1199 if isinstance(payload, dict) and mac_vms.owns(payload.get("name")):
1200 return mac_vms.handle(action, payload)
1201 if action == "console":
1202 return console_target(payload["name"])
1203 if action == "guest":
1204 root = ET.fromstring(virsh("dumpxml", payload["name"]))
1205 source = root.find(f"./devices/channel[@type='unix']/target[@name='{GUEST_CHANNEL}']/../source")
1206 expected = f"/run/libvirt/qemu/channel/{root.get('id')}-{payload['name'][:20]}/{GUEST_CHANNEL}"
1207 if virsh("domstate", payload["name"]).strip() != "running" or source is None or source.get("mode") != "bind" or source.get("path") != expected:
1208 raise ValueError("This VM has no guest display channel.")
1209 return {"path": expected}
1210 if action == "serial":
1211 if virsh("domstate", payload["name"]).strip() not in {"running", "blocked"}:
1212 raise ValueError("Start this VM before opening its console.")
1213 root = ET.fromstring(virsh("dumpxml", payload["name"]))
1214 console = root.find("./devices/console[@type='pty']")
1215 source = console.find("source") if console is not None else None
1216 target = console.find("target") if console is not None else None
1217 path = source.get("path", "") if source is not None else ""
1218 if target is None or target.get("type") != "serial" or not re.fullmatch(r"/dev/pts/[0-9]+", path):
1219 raise ValueError("This VM has no serial console. Add one in its hardware settings.")
1220 return {"path": path}
1221 if action == "owner":
1222 return {"owner": ET.fromstring(virsh("dumpxml", payload["name"])).findtext(f"metadata/{NS}vm/{NS}owner"), "ownerOnly": import_module("vm-ai").lease(payload["name"]) is not None}
1223 if action == "access":
1224 try:
1225 with os.fdopen(open_regular(DISKS / payload["name"] / "access.json")) as incoming:
1226 return json.load(incoming)
1227 except FileNotFoundError:
1228 return None
1229 if action == "media":
1230 change_media(payload)
1231 elif action == "preset":
1232 save_preset(payload)
1233 elif action == "create":
1234 create(payload)
1235 elif action == "act":
1236 name = payload["name"]
1237 ensure_name(name)
1238 forced = payload["action"] in {"reset", "destroy"}
1239 with computer_control(name) if forced else computer_lock(name) as control:
1240 if forced:
1241 active = computer_activity(name)
1242 if active is not None and active.get("id"):
1243 computer_cancel(control, active["id"])
1244 if payload["action"] == "start":
1245 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))
1246 if root.find("./devices/interface/source[@network='default']") is not None:
1247 ensure_network()
1248 ai = import_module("vm-ai")
1249 ai.lease(name, ai.LIMITS["idle_seconds"])
1250 virsh(payload["action"], name, timeout=15 if forced else None)
1251 elif action == "update":
1252 name = payload["name"]
1253 ensure_name(name)
1254 if "autostart" in payload:
1255 virsh("autostart", *([] if payload["autostart"] else ["--disable"]), name)
1256 if "description" in payload:
1257 flags = ["--config"]
1258 if virsh("domstate", name).strip() != "shut off":
1259 flags.append("--live")
1260 virsh("desc", name, *flags, "--", payload["description"])
1261 elif action == "remove":
1262 with computer_lock(payload["name"]):
1263 remove(payload)
1264 else:
1265 raise ValueError("unsupported VM action")
1266 return None
1267
1268
1269if __name__ == "__main__":
1270 try:
1271 if sys.argv[1] == "gpu" and len(sys.argv) == 3:
1272 ensure_name(sys.argv[2])
1273 switch_gpu(sys.argv[2])
1274 sys.exit(0)
1275 print(json.dumps(main()))
1276 except ValueError as failure:
1277 print(str(failure), file=sys.stderr)
1278 sys.exit(2)
1279 except (OSError, subprocess.CalledProcessError) as failure:
1280 print(str(failure), file=sys.stderr)
1281 sys.exit(1)