File
Blob: dev/vm/vm.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Persistent native test guests, using the host's existing libvirt installation.""" |
| 3 | |
| 4 | import argparse |
| 5 | import contextlib |
| 6 | import fcntl |
| 7 | import hashlib |
| 8 | import importlib |
| 9 | import ipaddress |
| 10 | import json |
| 11 | import os |
| 12 | from pathlib import Path |
| 13 | import re |
| 14 | import shlex |
| 15 | import shutil |
| 16 | import subprocess |
| 17 | import sys |
| 18 | import tarfile |
| 19 | import tempfile |
| 20 | import time |
| 21 | import urllib.request |
| 22 | import uuid |
| 23 | import xml.etree.ElementTree as ET |
| 24 | |
| 25 | |
| 26 | PREFIX = "SPECTER_VM_" |
| 27 | OPTIONS = {"URI", "DISK_POOL", "MEDIA_POOL", "NETWORK", "DNS", "CPUS", "MEMORY_MIB", "DISK_GIB"} |
| 28 | DEFAULTS = {"cpus": 2, "memory_mib": 4096, "disk_gib": 20} |
| 29 | |
| 30 | |
| 31 | def run(args, *, check=True, capture=True, **kwargs): |
| 32 | result = subprocess.run([str(arg) for arg in args], text=True, |
| 33 | stdout=subprocess.PIPE if capture else None, |
| 34 | stderr=subprocess.PIPE if capture else None, **kwargs) |
| 35 | if check and result.returncode: |
| 36 | detail = (result.stderr or result.stdout or "").strip() |
| 37 | raise RuntimeError(f"{shlex.join(map(str, args))} failed: {detail}") |
| 38 | return result |
| 39 | |
| 40 | |
| 41 | def local_config(): |
| 42 | path = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "specter/vm.env" |
| 43 | values = {} |
| 44 | if path.exists(): |
| 45 | for line in path.read_text().splitlines(): |
| 46 | tokens = shlex.split(line, comments=True) |
| 47 | if not tokens: |
| 48 | continue |
| 49 | if len(tokens) != 1 or "=" not in tokens[0]: |
| 50 | raise RuntimeError(f"{path}: expected NAME=value, with quoted values if needed") |
| 51 | key, value = tokens[0].split("=", 1) |
| 52 | if key.removeprefix(PREFIX) not in OPTIONS or not key.startswith(PREFIX): |
| 53 | raise RuntimeError(f"{path}: unknown setting {key}") |
| 54 | values[key] = value |
| 55 | values.update({key: value for key, value in os.environ.items() if key.startswith(PREFIX)}) |
| 56 | return values |
| 57 | |
| 58 | |
| 59 | def parse_json_stream(text): |
| 60 | decoder = json.JSONDecoder() |
| 61 | while text.strip(): |
| 62 | value, end = decoder.raw_decode(text.lstrip()) |
| 63 | yield value |
| 64 | text = text.lstrip()[end:] |
| 65 | |
| 66 | |
| 67 | def owned_volume(name, fixture_uuid): |
| 68 | return name.startswith(f"specter-{fixture_uuid}-") |
| 69 | |
| 70 | |
| 71 | class Guest: |
| 72 | def __init__(self, os_name, config): |
| 73 | self.os_name = os_name |
| 74 | self.backend = importlib.import_module(os_name) |
| 75 | self.config = config |
| 76 | data = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) |
| 77 | cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) |
| 78 | self.state_dir = data / "specter/vms" / os_name |
| 79 | self.cache_dir = cache / "specter/vm-images" |
| 80 | self.state_dir.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 81 | self.state_file = self.state_dir / "guest.json" |
| 82 | self.state = json.loads(self.state_file.read_text()) if self.state_file.exists() else {} |
| 83 | configured_uri = config.get(PREFIX + "URI") |
| 84 | if self.state and configured_uri and configured_uri != self.state["uri"]: |
| 85 | raise RuntimeError(f"fixture belongs to {self.state['uri']}; refusing URI override {configured_uri}") |
| 86 | self.uri = self.state.get("uri", configured_uri or "qemu:///system") |
| 87 | if self.uri not in ("qemu:///system", "qemu:///session"): |
| 88 | raise RuntimeError("this runner requires a local qemu:///system or qemu:///session connection") |
| 89 | self.name = f"specter-dev-{os_name}" |
| 90 | self.ip = None |
| 91 | |
| 92 | @property |
| 93 | def uuid(self): |
| 94 | return self.state["uuid"] |
| 95 | |
| 96 | @property |
| 97 | def settings(self): |
| 98 | return self.state["settings"] |
| 99 | |
| 100 | @property |
| 101 | def mac(self): |
| 102 | return "52:54:00:" + ":".join(self.uuid.replace("-", "")[i:i + 2] for i in (0, 2, 4)) |
| 103 | |
| 104 | @property |
| 105 | def public_key(self): |
| 106 | return (self.state_dir / "id_ed25519.pub").read_text().strip() |
| 107 | |
| 108 | @property |
| 109 | def network(self): |
| 110 | root = ET.fromstring(self.virsh("net-dumpxml", self.settings["network"]).stdout) |
| 111 | ip = root.find("ip[@address]") |
| 112 | if ip is None: |
| 113 | raise RuntimeError("the selected network needs IPv4 addressing and DHCP") |
| 114 | gateway = ip.attrib["address"] |
| 115 | mask = ip.attrib.get("netmask") or str(ipaddress.ip_network(f"{gateway}/{ip.attrib['prefix']}", strict=False).netmask) |
| 116 | return {"gateway": gateway, "dns": gateway, "netmask": mask} |
| 117 | |
| 118 | def save_state(self): |
| 119 | temporary = self.state_file.with_suffix(".tmp") |
| 120 | temporary.write_text(json.dumps(self.state, indent=2) + "\n") |
| 121 | temporary.chmod(0o600) |
| 122 | temporary.replace(self.state_file) |
| 123 | |
| 124 | def virsh(self, *args, **kwargs): |
| 125 | return run(["virsh", "--connect", self.uri, *args], **kwargs) |
| 126 | |
| 127 | def xml_command(self, command, xml): |
| 128 | with tempfile.NamedTemporaryFile(mode="w", suffix=".xml") as stream: |
| 129 | stream.write(ET.tostring(xml, encoding="unicode")) |
| 130 | stream.flush() |
| 131 | return self.virsh(command, stream.name) |
| 132 | |
| 133 | def domain(self): |
| 134 | if self.state and self.uuid in self.virsh("list", "--all", "--uuid").stdout.split(): |
| 135 | return ET.fromstring(self.virsh("dumpxml", self.uuid).stdout) |
| 136 | if self.name in self.virsh("list", "--all", "--name").stdout.splitlines(): |
| 137 | raise RuntimeError(f"{self.name} already exists and is not owned by this fixture") |
| 138 | return None |
| 139 | |
| 140 | def initialize(self): |
| 141 | # Check the name before persisting an identity or creating any libvirt object. |
| 142 | if self.domain() is not None: |
| 143 | return |
| 144 | if self.state: |
| 145 | return |
| 146 | settings = dict(DEFAULTS) |
| 147 | for key in ("cpus", "memory_mib", "disk_gib"): |
| 148 | value = self.config.get(PREFIX + key.upper()) |
| 149 | if value is not None: |
| 150 | settings[key] = int(value) |
| 151 | if settings[key] <= 0: |
| 152 | raise RuntimeError(f"{key} must be positive") |
| 153 | disk_pool = self.config.get(PREFIX + "DISK_POOL") |
| 154 | if not disk_pool: |
| 155 | raise RuntimeError("set SPECTER_VM_DISK_POOL for first creation (see dev/vm/README.md)") |
| 156 | disk_xml = ET.fromstring(self.virsh("pool-dumpxml", disk_pool).stdout) |
| 157 | media_pool = self.config.get(PREFIX + "MEDIA_POOL") |
| 158 | if not media_pool and disk_xml.attrib["type"] == "dir": |
| 159 | media_pool = disk_pool |
| 160 | if not media_pool: |
| 161 | raise RuntimeError("set SPECTER_VM_MEDIA_POOL to an active directory pool") |
| 162 | media_xml = ET.fromstring(self.virsh("pool-dumpxml", media_pool).stdout) |
| 163 | if media_xml.attrib["type"] != "dir": |
| 164 | raise RuntimeError("SPECTER_VM_MEDIA_POOL must be a directory pool") |
| 165 | active_pools = self.virsh("pool-list", "--name").stdout.split() |
| 166 | if disk_pool not in active_pools or media_pool not in active_pools: |
| 167 | raise RuntimeError("selected storage pools must already be active") |
| 168 | settings.update(disk_pool=disk_pool, media_pool=media_pool, |
| 169 | network=self.config.get(PREFIX + "NETWORK") or self.name, |
| 170 | own_network=not bool(self.config.get(PREFIX + "NETWORK"))) |
| 171 | self.state = {"uri": self.uri, "uuid": str(uuid.uuid4()), "settings": settings, "backend": {}} |
| 172 | self.save_state() |
| 173 | |
| 174 | def ensure_key(self): |
| 175 | key = self.state_dir / "id_ed25519" |
| 176 | if not key.exists(): |
| 177 | run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key]) |
| 178 | |
| 179 | def ensure_network(self): |
| 180 | name = self.settings["network"] |
| 181 | result = self.virsh("net-dumpxml", name, check=False) |
| 182 | if not self.settings["own_network"]: |
| 183 | if result.returncode or name not in self.virsh("net-list", "--name").stdout.splitlines(): |
| 184 | raise RuntimeError(f"selected network {name} must already exist and be active") |
| 185 | root = ET.fromstring(result.stdout) |
| 186 | if root.find("ip/dhcp") is None: |
| 187 | raise RuntimeError("selected network must provide IPv4 DHCP for SSH discovery") |
| 188 | return |
| 189 | if not result.returncode: |
| 190 | root = ET.fromstring(result.stdout) |
| 191 | if root.findtext("uuid") != self.uuid: |
| 192 | raise RuntimeError(f"network {name} is not owned by this fixture") |
| 193 | else: |
| 194 | used = [] |
| 195 | for network in self.virsh("net-list", "--all", "--name").stdout.splitlines(): |
| 196 | if not network: |
| 197 | continue |
| 198 | root = ET.fromstring(self.virsh("net-dumpxml", network).stdout) |
| 199 | for item in root.findall("ip"): |
| 200 | if ":" not in item.attrib.get("address", ""): |
| 201 | used.append(ipaddress.ip_network(f"{item.attrib['address']}/{item.attrib.get('prefix', item.attrib.get('netmask', '24'))}", strict=False)) |
| 202 | for route in json.loads(run(["ip", "-j", "route", "show", "table", "all"]).stdout): |
| 203 | if route.get("dst", "default") != "default": |
| 204 | used.append(ipaddress.ip_network(route["dst"], strict=False)) |
| 205 | subnet = next((ipaddress.ip_network(f"192.168.{n}.0/24") for n in range(200, 255) |
| 206 | if not any(ipaddress.ip_network(f"192.168.{n}.0/24").overlaps(item) for item in used)), None) |
| 207 | if subnet is None: |
| 208 | raise RuntimeError("no unused fixture subnet found; select SPECTER_VM_NETWORK") |
| 209 | root = ET.Element("network") |
| 210 | ET.SubElement(root, "name").text = name |
| 211 | ET.SubElement(root, "uuid").text = self.uuid |
| 212 | ET.SubElement(root, "description").text = "Specter native development fixture" |
| 213 | ip = ET.SubElement(root, "ip", address=str(subnet[1]), netmask=str(subnet.netmask)) |
| 214 | dhcp = ET.SubElement(ip, "dhcp") |
| 215 | ET.SubElement(dhcp, "range", start=str(subnet[10]), end=str(subnet[100])) |
| 216 | ET.SubElement(dhcp, "host", mac=self.mac, name=self.name, ip=str(subnet[10])) |
| 217 | dns = self.settings.get("dns", "libvirt") |
| 218 | if dns not in ("libvirt", "host"): |
| 219 | raise RuntimeError("SPECTER_VM_DNS must be libvirt or host") |
| 220 | if dns == "host" and root.find("dns[@enable='no']") is None: |
| 221 | if name in self.virsh("net-list", "--name").stdout.splitlines(): |
| 222 | raise RuntimeError("cannot change DNS of a running fixture network") |
| 223 | ET.SubElement(root, "dns", enable="no") |
| 224 | self.xml_command("net-define", root) |
| 225 | if name not in self.virsh("net-list", "--name").stdout.splitlines(): |
| 226 | self.virsh("net-start", name) |
| 227 | |
| 228 | def fetch(self, url, checksum, algorithm="sha256"): |
| 229 | self.cache_dir.mkdir(parents=True, exist_ok=True) |
| 230 | path = self.cache_dir / (checksum[:16] + "-" + url.rsplit("/", 1)[-1]) |
| 231 | with path.with_suffix(path.suffix + ".lock").open("w") as lock: |
| 232 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 233 | if path.exists(): |
| 234 | with path.open("rb") as stream: |
| 235 | if hashlib.file_digest(stream, algorithm).hexdigest() == checksum: |
| 236 | return path |
| 237 | raise RuntimeError(f"cached image checksum mismatch: {path}") |
| 238 | print(f"Downloading {url}", flush=True) |
| 239 | temporary = path.with_suffix(path.suffix + ".part") |
| 240 | offset = temporary.stat().st_size if temporary.exists() else 0 |
| 241 | request = urllib.request.Request(url, headers={"Range": f"bytes={offset}-"} if offset else {}) |
| 242 | with urllib.request.urlopen(request, timeout=60) as response: |
| 243 | mode = "ab" if offset and response.status == 206 else "wb" |
| 244 | with temporary.open(mode) as stream: |
| 245 | shutil.copyfileobj(response, stream) |
| 246 | with temporary.open("rb") as stream: |
| 247 | if hashlib.file_digest(stream, algorithm).hexdigest() != checksum: |
| 248 | raise RuntimeError(f"download checksum mismatch: {temporary}") |
| 249 | temporary.replace(path) |
| 250 | return path |
| 251 | |
| 252 | def create_volume(self, role, pool, size, source=None): |
| 253 | name = f"specter-{self.uuid}-{role}" |
| 254 | if self.virsh("vol-info", name, "--pool", pool, check=False).returncode: |
| 255 | self.virsh("vol-create-as", pool, name, str(size), "--format", "raw") |
| 256 | if source is not None: |
| 257 | print(f"Uploading {role} to pool {pool}", flush=True) |
| 258 | self.virsh("vol-upload", name, source, "--pool", pool, "--sparse") |
| 259 | return name |
| 260 | |
| 261 | def define(self, disks): |
| 262 | root = ET.Element("domain", type="kvm") |
| 263 | ET.SubElement(root, "name").text = self.name |
| 264 | ET.SubElement(root, "uuid").text = self.uuid |
| 265 | ET.SubElement(root, "description").text = "Specter native development fixture; managed by dev/vm/vm.py" |
| 266 | ET.SubElement(root, "memory", unit="MiB").text = str(self.settings["memory_mib"]) |
| 267 | ET.SubElement(root, "vcpu").text = str(self.settings["cpus"]) |
| 268 | os_xml = ET.SubElement(root, "os") |
| 269 | ET.SubElement(os_xml, "type", arch="x86_64", machine="pc").text = "hvm" |
| 270 | features = ET.SubElement(root, "features") |
| 271 | ET.SubElement(features, "acpi") |
| 272 | ET.SubElement(features, "apic") |
| 273 | ET.SubElement(root, "cpu", mode="host-passthrough") |
| 274 | ET.SubElement(root, "clock", offset="utc") |
| 275 | for event, policy in (("poweroff", "destroy"), ("reboot", "restart"), ("crash", "preserve")): |
| 276 | ET.SubElement(root, "on_" + event).text = policy |
| 277 | devices = ET.SubElement(root, "devices") |
| 278 | disk_index = 0 |
| 279 | for spec in disks: |
| 280 | media = spec.get("media", False) |
| 281 | source = spec.get("source") |
| 282 | size = spec.get("size_gib", self.settings["disk_gib"]) * 1024 ** 3 if not media else Path(source).stat().st_size |
| 283 | pool = self.settings["media_pool" if media else "disk_pool"] |
| 284 | volume = self.create_volume(spec["role"], pool, size, source) |
| 285 | volume_xml = ET.fromstring(self.virsh("vol-dumpxml", volume, "--pool", pool).stdout) |
| 286 | disk_type = volume_xml.attrib["type"] |
| 287 | if disk_type not in ("file", "block"): |
| 288 | raise RuntimeError(f"unsupported volume type {disk_type}") |
| 289 | # Resolve the managed volume so libvirt's AppArmor/DAC rules include |
| 290 | # its actual device. Older libvirt omits LVM devices for type=volume. |
| 291 | disk = ET.SubElement(devices, "disk", type=disk_type, device="cdrom" if media else "disk") |
| 292 | driver = ET.SubElement(disk, "driver", name="qemu", type="raw") |
| 293 | if not media: |
| 294 | driver.set("cache", "none") |
| 295 | ET.SubElement(disk, "source", **{"dev" if disk_type == "block" else "file": volume_xml.findtext("target/path")}) |
| 296 | ET.SubElement(disk, "target", dev="hdc" if media else "vd" + chr(97 + disk_index), bus="ide" if media else "virtio") |
| 297 | if media: |
| 298 | ET.SubElement(disk, "readonly") |
| 299 | else: |
| 300 | disk_index += 1 |
| 301 | if "boot" in spec: |
| 302 | ET.SubElement(disk, "boot", order=str(spec["boot"])) |
| 303 | interface = ET.SubElement(devices, "interface", type="network") |
| 304 | ET.SubElement(interface, "source", network=self.settings["network"]) |
| 305 | ET.SubElement(interface, "mac", address=self.mac) |
| 306 | ET.SubElement(interface, "model", type=getattr(self.backend, "NIC_MODEL", "e1000")) |
| 307 | serial_volume = self.create_volume("serial.log", self.settings["media_pool"], 0) |
| 308 | serial_path = self.virsh("vol-path", serial_volume, "--pool", self.settings["media_pool"]).stdout.strip() |
| 309 | serial = ET.SubElement(devices, "serial", type="pty") |
| 310 | ET.SubElement(serial, "log", file=serial_path, append="on") |
| 311 | ET.SubElement(serial, "target", port="0") |
| 312 | console = ET.SubElement(devices, "console", type="pty") |
| 313 | ET.SubElement(console, "target", type="serial", port="0") |
| 314 | self.xml_command("define", root) |
| 315 | |
| 316 | def running(self): |
| 317 | return self.virsh("domstate", self.uuid).stdout.strip() in ("running", "blocked", "paused", "in shutdown") |
| 318 | |
| 319 | def address(self): |
| 320 | result = self.virsh("net-dhcp-leases", self.settings["network"], "--mac", self.mac) |
| 321 | for line in result.stdout.splitlines(): |
| 322 | for word in line.split(): |
| 323 | if re.fullmatch(r"\d+\.\d+\.\d+\.\d+/\d+", word): |
| 324 | return str(ipaddress.ip_interface(word).ip) |
| 325 | return None |
| 326 | |
| 327 | def ssh_options(self, user=None, password=None): |
| 328 | if self.ip is None: |
| 329 | self.ip = self.address() |
| 330 | if self.ip is None: |
| 331 | raise RuntimeError("guest has no DHCP lease yet") |
| 332 | options = ["-i", self.state_dir / "id_ed25519", "-o", "IdentitiesOnly=yes", |
| 333 | "-o", "ConnectTimeout=5", "-o", "ConnectionAttempts=1", |
| 334 | "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=3", |
| 335 | "-o", "StrictHostKeyChecking=accept-new", "-o", f"HostKeyAlias={self.uuid}", |
| 336 | "-o", f"UserKnownHostsFile={self.state_dir / 'known_hosts'}"] |
| 337 | env = os.environ.copy() |
| 338 | if password is None: |
| 339 | options += ["-o", "BatchMode=yes"] |
| 340 | else: |
| 341 | askpass = self.state_dir / "askpass" |
| 342 | askpass.write_text('#!/bin/sh\nprintf "%s\\n" "$SPECTER_VM_BOOTSTRAP_PASSWORD"\n') |
| 343 | askpass.chmod(0o700) |
| 344 | env.update(SSH_ASKPASS=str(askpass), SSH_ASKPASS_REQUIRE="force", DISPLAY="specter-vm", |
| 345 | SPECTER_VM_BOOTSTRAP_PASSWORD=password) |
| 346 | options += ["-o", "PreferredAuthentications=publickey,password", |
| 347 | "-o", "NumberOfPasswordPrompts=1"] |
| 348 | return options, env, f"{user or self.backend.SSH_USER}@{self.ip}" |
| 349 | |
| 350 | def ssh(self, script, user=None, password=None, timeout=30, check=True, input=None, capture=True, stdin=None): |
| 351 | options, env, destination = self.ssh_options(user, password) |
| 352 | return run(["ssh", *options, destination, script], env=env, timeout=timeout, check=check, |
| 353 | input=input, stdin=stdin, capture=capture) |
| 354 | |
| 355 | def upload(self, local, remote, user=None, password=None): |
| 356 | options, env, destination = self.ssh_options(user, password) |
| 357 | return run(["scp", "-O", *options, local, f"{destination}:{remote}"], env=env, timeout=600) |
| 358 | |
| 359 | def wait_ssh(self, user=None, password=None, timeout=600): |
| 360 | deadline = time.monotonic() + timeout |
| 361 | last_error = "no DHCP lease" |
| 362 | while time.monotonic() < deadline: |
| 363 | self.ip = self.address() |
| 364 | if self.ip: |
| 365 | try: |
| 366 | result = self.ssh("true", user=user, password=password, timeout=10, check=False) |
| 367 | if not result.returncode: |
| 368 | return |
| 369 | last_error = result.stderr.strip() |
| 370 | except subprocess.TimeoutExpired: |
| 371 | last_error = "SSH attempt timed out" |
| 372 | if not self.running(): |
| 373 | raise RuntimeError("guest stopped before SSH became available") |
| 374 | time.sleep(2) |
| 375 | raise RuntimeError(f"SSH did not become ready within {timeout}s: {last_error}") |
| 376 | |
| 377 | def start(self): |
| 378 | self.initialize() |
| 379 | self.ensure_key() |
| 380 | if self.domain() is None: |
| 381 | self.settings["dns"] = self.config.get(PREFIX + "DNS", self.settings.get("dns", "libvirt")) |
| 382 | self.save_state() |
| 383 | self.ensure_network() |
| 384 | if self.domain() is None: |
| 385 | self.define(self.backend.prepare(self)) |
| 386 | if not self.running(): |
| 387 | print(f"Starting {self.name}", flush=True) |
| 388 | self.virsh("start", self.uuid) |
| 389 | deadline = time.monotonic() + 600 |
| 390 | while self.address() is None: |
| 391 | if not self.running() or time.monotonic() >= deadline: |
| 392 | raise RuntimeError("guest did not obtain an IPv4 DHCP lease within 600s") |
| 393 | time.sleep(2) |
| 394 | self.ip = self.address() |
| 395 | self.backend.provision(self) |
| 396 | print(f"{self.name} ready at {self.ip}; state: {self.state_dir}", flush=True) |
| 397 | |
| 398 | def serial_log(self): |
| 399 | if not self.state: |
| 400 | return |
| 401 | name = f"specter-{self.uuid}-serial.log" |
| 402 | path = self.state_dir / "serial.log" |
| 403 | result = self.virsh("vol-download", name, path, "--pool", self.settings["media_pool"], check=False) |
| 404 | if not result.returncode: |
| 405 | print(f"Serial log: {path}", file=sys.stderr) |
| 406 | |
| 407 | def stop(self): |
| 408 | if self.domain() is None: |
| 409 | raise RuntimeError("fixture has not been created") |
| 410 | if self.running(): |
| 411 | self.virsh("shutdown", self.uuid, "--mode", "acpi") |
| 412 | deadline = time.monotonic() + 120 |
| 413 | while self.running() and time.monotonic() < deadline: |
| 414 | time.sleep(2) |
| 415 | if self.running(): |
| 416 | raise RuntimeError("guest did not shut down within 120s; retained for inspection") |
| 417 | self.serial_log() |
| 418 | print(f"Stopped {self.name}; disks retained") |
| 419 | |
| 420 | def destroy(self): |
| 421 | if not self.state: |
| 422 | raise RuntimeError("no fixture identity found; nothing will be removed") |
| 423 | domain = self.domain() |
| 424 | if domain is not None: |
| 425 | if self.running(): |
| 426 | self.virsh("destroy", self.uuid) |
| 427 | self.virsh("undefine", self.uuid) |
| 428 | for pool in set((self.settings["disk_pool"], self.settings["media_pool"])): |
| 429 | for volume in self.virsh("vol-list", pool, "--name").stdout.splitlines(): |
| 430 | volume = volume.strip() |
| 431 | if owned_volume(volume, self.uuid): |
| 432 | self.virsh("vol-delete", volume, "--pool", pool) |
| 433 | if self.settings["own_network"]: |
| 434 | name = self.settings["network"] |
| 435 | result = self.virsh("net-dumpxml", name, check=False) |
| 436 | if not result.returncode: |
| 437 | if ET.fromstring(result.stdout).findtext("uuid") != self.uuid: |
| 438 | raise RuntimeError("network identity changed; refusing to remove it") |
| 439 | for other in self.virsh("list", "--all", "--uuid").stdout.splitlines(): |
| 440 | if other and any(item.attrib.get("network") == name for item in ET.fromstring(self.virsh("dumpxml", other).stdout).findall("devices/interface/source")): |
| 441 | raise RuntimeError(f"network {name} is used by another domain; retained") |
| 442 | if name in self.virsh("net-list", "--name").stdout.splitlines(): |
| 443 | self.virsh("net-destroy", name) |
| 444 | self.virsh("net-undefine", name) |
| 445 | for path in self.state_dir.iterdir(): |
| 446 | if path.is_dir() and not path.is_symlink(): |
| 447 | shutil.rmtree(path) |
| 448 | elif path.name != ".lock": |
| 449 | path.unlink() |
| 450 | print(f"Destroyed {self.name}; downloaded image cache retained") |
| 451 | |
| 452 | def test(self, patterns, flags): |
| 453 | self.start() |
| 454 | repo = Path(run(["git", "rev-parse", "--show-toplevel"]).stdout.strip()) |
| 455 | env = dict(os.environ, GOOS=self.backend.GOOS, GOARCH="amd64", CGO_ENABLED="0") |
| 456 | packages = list(parse_json_stream(run(["go", "list", "-json", *patterns], cwd=repo, env=env).stdout)) |
| 457 | upload_root, guest_root = self.backend.workspace(self) |
| 458 | with tempfile.TemporaryDirectory(prefix="specter-native-") as directory: |
| 459 | stage = Path(directory) |
| 460 | selected = [] |
| 461 | for package in packages: |
| 462 | if not package.get("TestGoFiles") and not package.get("XTestGoFiles"): |
| 463 | continue |
| 464 | relative = Path(package["Dir"]).relative_to(repo) |
| 465 | destination = stage / relative |
| 466 | destination.mkdir(parents=True, exist_ok=True) |
| 467 | print(f"Building {package['ImportPath']} for {self.backend.GOOS}", flush=True) |
| 468 | run(["go", "test", "-c", "-o", destination / "package.test", package["ImportPath"]], cwd=repo, env=env, capture=False) |
| 469 | if (Path(package["Dir"]) / "testdata").exists(): |
| 470 | shutil.copytree(Path(package["Dir"]) / "testdata", destination / "testdata") |
| 471 | selected.append(relative) |
| 472 | if not selected: |
| 473 | raise RuntimeError("no test packages selected") |
| 474 | for fixture in ("packaging/templates", "certs", "dev/pebble"): |
| 475 | if (repo / fixture).is_dir(): |
| 476 | shutil.copytree(repo / fixture, stage / fixture, dirs_exist_ok=True) |
| 477 | archive = stage / "tests.tar" |
| 478 | with tarfile.open(archive, "w", format=tarfile.USTAR_FORMAT) as stream: |
| 479 | for path in stage.iterdir(): |
| 480 | if path != archive: |
| 481 | stream.add(path, arcname=path.name) |
| 482 | self.ssh(f"mkdir -p {shlex.quote(upload_root + '/.tmp')}") |
| 483 | with archive.open("rb") as stream: |
| 484 | self.ssh(f"cd {shlex.quote(upload_root)} && tar -xf -", stdin=stream, timeout=600) |
| 485 | if hasattr(self.backend, "prepare_workspace"): |
| 486 | self.backend.prepare_workspace(self) |
| 487 | failed = [] |
| 488 | test_env = {key: os.environ[key] for key in ("GO_INTEGRATION_TUNNEL", "GO_INTEGRATION_ACME", "SPECTER_TEST_ACME_URL") if key in os.environ} |
| 489 | for relative in selected: |
| 490 | command = f"cd {shlex.quote(str(Path(guest_root) / relative))} && " + shlex.join([ |
| 491 | "env", f"TMPDIR={guest_root}/.tmp", *[f"{key}={value}" for key, value in test_env.items()], |
| 492 | "./package.test", "-test.v", "-test.short", "-test.count=1", "-test.timeout=300s", *flags]) |
| 493 | print(f"Testing {relative} on {self.os_name}", flush=True) |
| 494 | result = self.ssh(self.backend.command(self, command), timeout=900, check=False, capture=False) |
| 495 | if result.returncode: |
| 496 | failed.append(str(relative)) |
| 497 | if failed: |
| 498 | raise RuntimeError("native tests failed: " + ", ".join(failed)) |
| 499 | |
| 500 | |
| 501 | def main(): |
| 502 | parser = argparse.ArgumentParser(description=__doc__) |
| 503 | parser.add_argument("action", choices=("start", "test", "stop", "destroy")) |
| 504 | parser.add_argument("os", choices=("freebsd", "smartos")) |
| 505 | parser.add_argument("packages", nargs="*", help="go package patterns for test; defaults to ./...") |
| 506 | argv = sys.argv[1:] |
| 507 | flags = [] |
| 508 | if "--" in argv: |
| 509 | index = argv.index("--") |
| 510 | argv, flags = argv[:index], argv[index + 1:] |
| 511 | args = parser.parse_args(argv) |
| 512 | if args.action != "test" and (args.packages or flags): |
| 513 | parser.error("package patterns and test flags apply only to test") |
| 514 | guest = None |
| 515 | try: |
| 516 | guest = Guest(args.os, local_config()) |
| 517 | with (guest.state_dir / ".lock").open("w") as lock: |
| 518 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 519 | # A different invocation may have finished provisioning while we waited. |
| 520 | guest = Guest(args.os, local_config()) |
| 521 | if args.action == "test": |
| 522 | guest.test(args.packages or ["./..."], flags) |
| 523 | else: |
| 524 | getattr(guest, args.action)() |
| 525 | except (RuntimeError, ValueError, OSError, subprocess.SubprocessError) as error: |
| 526 | print(f"vm: {error}", file=sys.stderr) |
| 527 | if guest is not None and guest.state: |
| 528 | with contextlib.suppress(Exception): |
| 529 | guest.serial_log() |
| 530 | return 1 |
| 531 | except KeyboardInterrupt: |
| 532 | print("vm: interrupted; fixture and partial downloads retained for the next start", file=sys.stderr) |
| 533 | return 130 |
| 534 | return 0 |
| 535 | |
| 536 | |
| 537 | if __name__ == "__main__": |
| 538 | sys.exit(main()) |