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