From 9337042a0fd7774b354256117338007f80496434 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 19:33:26 -0700 Subject: [PATCH] feat(e2e): drive a Windows guest under QEMU with the neutral Platform guest.py starts QEMU and swtpm on an overlay of the golden image, with saved-state restore (state.py), qmp.py sends keys and the pointer, agent.py talks to the guest agent, windows_platform.py implements the Platform protocol and run.py runs the scenarios, one guest each. --- e2e/platforms/qemu_windows/__init__.py | 0 e2e/platforms/qemu_windows/agent.py | 102 +++++ e2e/platforms/qemu_windows/guest.py | 226 +++++++++++ e2e/platforms/qemu_windows/qmp.py | 84 +++++ e2e/platforms/qemu_windows/run.py | 351 ++++++++++++++++++ e2e/platforms/qemu_windows/state.py | 76 ++++ .../qemu_windows/windows_platform.py | 345 +++++++++++++++++ 7 files changed, 1184 insertions(+) create mode 100644 e2e/platforms/qemu_windows/__init__.py create mode 100644 e2e/platforms/qemu_windows/agent.py create mode 100644 e2e/platforms/qemu_windows/guest.py create mode 100644 e2e/platforms/qemu_windows/qmp.py create mode 100644 e2e/platforms/qemu_windows/run.py create mode 100644 e2e/platforms/qemu_windows/state.py create mode 100644 e2e/platforms/qemu_windows/windows_platform.py diff --git a/e2e/platforms/qemu_windows/__init__.py b/e2e/platforms/qemu_windows/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/e2e/platforms/qemu_windows/agent.py b/e2e/platforms/qemu_windows/agent.py new file mode 100644 index 00000000..e9e6517d --- /dev/null +++ b/e2e/platforms/qemu_windows/agent.py @@ -0,0 +1,102 @@ +"""The host side of `komorebi-e2e-agent`: JSON lines over a forwarded port.""" + +import json +import socket +import time +from itertools import count +from pathlib import Path +from typing import Any + + +class AgentError(Exception): + pass + + +class AgentLost(AgentError): + """The connection dropped during a call: the call is not repeated, as it + may have run, and the caller names it, so that a dead agent is not taken + for the command having broken what it was testing.""" + + +class Agent: + def __init__(self, host: str = "127.0.0.1", port: int = 7878) -> None: + self._addr = (host, port) + self._ids = count(1) + self._sock: socket.socket | None = None + self._file: Any = None + + def connect(self, timeout: float = 120) -> None: + """Waits for the guest to boot and the agent to listen.""" + deadline = time.monotonic() + timeout + while True: + try: + self._sock = socket.create_connection(self._addr, timeout=5) + self._sock.settimeout(60) + self._file = self._sock.makefile("rwb") + if self.call("ping") == "pong": + return + except (OSError, ValueError, AgentLost): + # QEMU accepts the forwarded connection before the guest + # listens, then closes it: an empty answer + if self._sock: + self._sock.close() + if time.monotonic() > deadline: + raise AgentError(f"no agent at {self._addr} after {timeout}s") + time.sleep(1) + + def call(self, verb: str, **fields: Any) -> Any: + request_id = next(self._ids) + line = json.dumps({"id": request_id, "verb": verb, **fields}) + "\n" + try: + self._file.write(line.encode()) + self._file.flush() + return self._read_reply(request_id) + except (OSError, ValueError) as e: + what = " ".join([verb, *map(str, fields.get("args", []))]) + raise AgentLost(f"agent connection lost during {what}: {e}") from e + + def _read_reply(self, request_id: int) -> Any: + reply = json.loads(self._file.readline()) + if reply.get("id") != request_id: + got = reply.get("id") + raise AgentError(f"answer to {got}, expected {request_id}") + if "error" in reply: + raise AgentError(reply["error"]) + return reply["ok"] + + def exec(self, *args: str) -> dict[str, Any]: + return self.call("exec", args=list(args)) + + def spawn(self, *args: str) -> int: + return self.call("spawn", args=list(args))["pid"] + + def os_windows(self) -> list[dict[str, Any]]: + return self.call("os_windows") + + def displays(self) -> list[dict[str, Any]]: + return self.call("displays") + + def put_file(self, local: Path, remote: str) -> None: + data = local.read_bytes() + request_id = next(self._ids) + header = { + "id": request_id, + "verb": "put_file", + "path": remote, + "size": len(data), + } + self._file.write((json.dumps(header) + "\n").encode() + data) + self._file.flush() + self._read_reply(request_id) + + def get_file(self, remote: str) -> bytes: + request_id = next(self._ids) + header = {"id": request_id, "verb": "get_file", "path": remote} + self._file.write((json.dumps(header) + "\n").encode()) + self._file.flush() + size = self._read_reply(request_id)["size"] + return self._file.read(size) + + def close(self) -> None: + if self._sock: + self._sock.close() diff --git a/e2e/platforms/qemu_windows/guest.py b/e2e/platforms/qemu_windows/guest.py new file mode 100644 index 00000000..913ff41c --- /dev/null +++ b/e2e/platforms/qemu_windows/guest.py @@ -0,0 +1,226 @@ +"""One throwaway Windows guest: an overlay on the golden image, run by QEMU. + +The golden image is never written: every run has its own +overlay, its own copy of the firmware variables and of the TPM state, and +all of them are deleted with the run directory. +""" + +import os +import shutil +import socket +import subprocess +import time +from pathlib import Path +from types import TracebackType + +from .agent import Agent +from .qmp import Qmp + +# the guest clock: an evaluation build reads as expired at the host's date +RTC_BASE = "2024-10-01T00:00:00" + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +# a second monitor: a QXL device, which gets the signed qxldod driver from the +# image. Windows' basic display driver ignores a second VGA device. +SECOND_DISPLAY = [ + "-device", "qxl,id=qxl2,ram_size_mb=64,vram_size_mb=64,vgamem_mb=16", +] + + +# how many displays can be added at runtime +HOTPLUG_PORTS = 6 + + +class Guest: + """Boots the golden image and gives a `Qmp` and a connected `Agent`. + + Needs `qemu-system-x86_64`, `qemu-img` and `swtpm` on PATH and `OVMF_FD` + (an OVMF build with TPM support and without SMM) in the environment. + """ + + def __init__( + self, + golden: Path, + run: Path, + vcpus: int = 4, + mem: str = "6G", + extra: list[str] | None = None, + state: Path | None = None, + ahci: bool = False, + rtc_base: str | None = RTC_BASE, + keep: bool = False, + ) -> None: + self._ahci = ahci + self._rtc_base = rtc_base + self._keep = keep + # a saved state is restored instead of booting; it can only be saved + # from a disk on an AHCI controller (QEMU does not migrate NVMe), so + # a guest that takes part in saving or restoring uses one + self._state = state + self._golden = golden + self._run = run + self._vcpus = vcpus + self._mem = mem + self._extra = extra or [] + self._procs: list[subprocess.Popen[bytes]] = [] + self.agent_port = _free_port() + self.qmp: Qmp + self.agent: Agent + + def __enter__(self) -> "Guest": + self._run.mkdir(parents=True, exist_ok=True) + run, golden = self._run, self._golden + # the sockets of the guest are in `run`, and a unix socket path is + # limited to 108 bytes: say so, instead of a guest that never answers + longest = str(run / "tpm.sock") + if len(longest.encode()) > 100: + raise RuntimeError( + f"the run directory path is too long for a socket: {longest}" + ) + overlay = run / "overlay.qcow2" + # the base is the golden disk, or the disk as it was when the state + # was saved: the saved memory belongs to exactly that disk + base = self._state / "overlay.qcow2" if self._state \ + else golden / "disk.qcow2" + origin = self._state or golden + subprocess.run( + ["qemu-img", "create", "-q", "-f", "qcow2", "-b", + str(base), "-F", "qcow2", str(overlay)], + check=True, + ) + shutil.copy(origin / "vars.fd", run / "vars.fd") + shutil.copytree(origin / "tpm", run / "tpm", dirs_exist_ok=True) + + self._start( + ["swtpm", "socket", "--tpm2", "--tpmstate", f"dir={run / 'tpm'}", + "--ctrl", f"type=unixio,path={run / 'tpm.sock'}"] + ) + ovmf = Path(os.environ["OVMF_FD"]) / "FV" + self._start( + ["qemu-system-x86_64", "-name", "e2e-windows", "-accel", "kvm", + "-machine", "q35,smm=off", "-cpu", "host", + "-smp", str(self._vcpus), "-m", self._mem, + *(["-rtc", f"base={self._rtc_base}"] if self._rtc_base else []), + "-drive", f"if=pflash,format=raw,readonly=on,unit=0," + f"file={ovmf / 'OVMF_CODE.fd'}", + "-drive", f"if=pflash,format=raw,unit=1,file={run / 'vars.fd'}", + "-chardev", f"socket,id=chrtpm,path={run / 'tpm.sock'}", + "-tpmdev", "emulator,id=tpm0,chardev=chrtpm", + "-device", "tpm-crb,tpmdev=tpm0", + "-drive", f"if=none,id=disk,file={overlay},format=qcow2", + *self._disk_device(), + "-netdev", f"user,id=net0,hostfwd=tcp:127.0.0.1:" + f"{self.agent_port}-:7878", + "-device", "e1000e,netdev=net0", + "-device", "qemu-xhci", "-device", "usb-tablet", + "-device", "usb-kbd", "-device", "VGA,vgamem_mb=64", + # hotplug slots for extra displays (see `WindowsPlatform`) + *[arg for n in range(1, HOTPLUG_PORTS + 1) for arg in + ("-device", f"pcie-root-port,id=rp{n},chassis={n},slot={n}")], + *self._extra, + # a QXL device wants a SPICE server behind it; without one QEMU + # aborts in handle_dev_oom when the device runs short of memory + "-spice", f"unix=on,addr={run / 'spice.sock'}," + "disable-ticketing=on", + "-display", "none", + "-qmp", f"unix:{run / 'qmp.sock'},server=on,wait=off", + *(["-incoming", "defer"] if self._state else [])] + ) + self.qmp = Qmp(run / "qmp.sock") + if self._state: + self._restore() + self.agent = Agent(port=self.agent_port) + self.agent.connect(timeout=180) + return self + + def _disk_device(self) -> list[str]: + if self._state is None and not self._ahci: + return ["-device", "nvme,drive=disk,serial=e2e0,bootindex=1"] + return ["-device", "ich9-ahci,id=ahci", + "-device", "ide-hd,drive=disk,bus=ahci.0,bootindex=1"] + + def _restore(self) -> None: + self.qmp.execute( + "migrate-incoming", uri=f"exec:cat {self._state / 'state.mig'}" + ) + deadline = time.monotonic() + 300 + while self.qmp.status() == "inmigrate": + if time.monotonic() > deadline: + raise RuntimeError("the saved state did not load") + time.sleep(0.05) + self.qmp.execute("cont") + + def save(self, dest: Path) -> None: + """Saves the running guest to `dest` and stops it: its memory + (state.mig), the disk as it is now (overlay.qcow2, to be a read-only + base), the firmware variables and the TPM state.""" + dest.mkdir(parents=True, exist_ok=True) + self.agent.close() + self.qmp.execute("stop") + self.qmp.execute( + "migrate", uri=f"exec:cat > {dest / 'state.mig'}" + ) + while True: + status = self.qmp.execute("query-migrate")["status"] + if status == "completed": + break + if status in ("failed", "cancelled"): + raise RuntimeError(f"saving the state: migration {status}") + time.sleep(0.05) + self.qmp.close() + self._terminate() + shutil.move(self._run / "overlay.qcow2", dest / "overlay.qcow2") + shutil.copy(self._run / "vars.fd", dest / "vars.fd") + shutil.copytree(self._run / "tpm", dest / "tpm", dirs_exist_ok=True) + + def _start(self, argv: list[str]) -> None: + self._procs.append(subprocess.Popen(argv)) + + def upload(self, local_dir: Path, names: list[str]) -> None: + """Puts binaries under test in the guest's `C:\\e2e\\bin`.""" + self.agent.exec("cmd", "/c", "mkdir C:\\e2e\\bin 2>nul") + for name in names: + self.agent.put_file(local_dir / name, f"C:\\e2e\\bin\\{name}") + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + try: + self.agent.close() + self.qmp.close() + except Exception: + pass + self._terminate() + # the overlay, the firmware variables and the TPM state of a run are + # several hundred megabytes each; the artifacts that matter are in + # the output directory, outside this one + if not self._keep and not os.environ.get("KOMOREBI_E2E_KEEP_GUEST"): + shutil.rmtree(self._run, ignore_errors=True) + + def wait_exit(self, timeout: float) -> bool: + """Waits for QEMU to exit, as it does when the guest shuts itself + down; True if it did.""" + try: + self._procs[-1].wait(timeout=timeout) + except subprocess.TimeoutExpired: + return False + return True + + def _terminate(self) -> None: + # our own children only, by handle: never by name + for proc in reversed(self._procs): + proc.terminate() + for proc in self._procs: + try: + proc.wait(timeout=20) + except subprocess.TimeoutExpired: + proc.kill() diff --git a/e2e/platforms/qemu_windows/qmp.py b/e2e/platforms/qemu_windows/qmp.py new file mode 100644 index 00000000..54cd586b --- /dev/null +++ b/e2e/platforms/qemu_windows/qmp.py @@ -0,0 +1,84 @@ +"""A QMP client: the host-side hands and eyes of a QEMU guest. + +Keys, pointer and screenshots go through QEMU, not through the guest, so they +need no permission in it and work at the lock screen. +""" + +import json +import socket +import time +from pathlib import Path +from typing import Any + +# the absolute pointer axes of QEMU's `usb-tablet` run from 0 to this +POINTER_MAX = 0x7FFF + + +class QmpError(Exception): + pass + + +class Qmp: + def __init__(self, path: str | Path, timeout: float = 30) -> None: + self._sock = socket.socket(socket.AF_UNIX) + self._sock.settimeout(timeout) + deadline = time.monotonic() + timeout + while True: + try: + self._sock.connect(str(path)) + break + except (FileNotFoundError, ConnectionRefusedError): + if time.monotonic() > deadline: + raise + time.sleep(0.2) + self._file = self._sock.makefile("rw", encoding="utf-8") + self._file.readline() # the greeting + self.execute("qmp_capabilities") + + def execute(self, command: str, **arguments: Any) -> Any: + request: dict[str, Any] = {"execute": command} + if arguments: + request["arguments"] = arguments + self._file.write(json.dumps(request) + "\n") + self._file.flush() + while True: + reply = json.loads(self._file.readline()) + if "event" in reply: + continue + if "error" in reply: + raise QmpError(f"{command}: {reply['error']['desc']}") + return reply["return"] + + def status(self) -> str: + return self.execute("query-status")["status"] + + def screendump(self, path: str | Path, device: str | None = None) -> None: + """Writes the display as a PNG, from the head `device` if given.""" + extra = {"device": device} if device else {} + self.execute("screendump", filename=str(path), format="png", **extra) + + def key(self, *qcodes: str, hold_ms: int = 50) -> None: + """Presses the keys together, then releases them. + + `key("ctrl", "alt", "delete")` is the chord. + """ + keys = [{"type": "qcode", "data": q} for q in qcodes] + self.execute("send-key", keys=keys, **{"hold-time": hold_ms}) + + def pointer_move(self, x: int, y: int, width: int, height: int) -> None: + """Moves the pointer to a pixel of a `width` x `height` display.""" + + def axis(name: str, value: int, extent: int) -> dict[str, Any]: + scaled = value * POINTER_MAX // max(extent - 1, 1) + return {"type": "abs", "data": {"axis": name, "value": scaled}} + + events = [axis("x", x, width), axis("y", y, height)] + self.execute("input-send-event", events=events) + + def pointer_button(self, down: bool, button: str = "left") -> None: + events = [{"type": "btn", "data": {"button": button, "down": down}}] + self.execute("input-send-event", events=events) + + def close(self) -> None: + self._file.close() + self._sock.close() diff --git a/e2e/platforms/qemu_windows/run.py b/e2e/platforms/qemu_windows/run.py new file mode 100644 index 00000000..36ebf320 --- /dev/null +++ b/e2e/platforms/qemu_windows/run.py @@ -0,0 +1,351 @@ +"""Runs neutral scenarios against a fresh Windows guest. + +usage: python -m platforms.qemu_windows.run GOLDEN BIN_DIR OUT SCENARIO... + +GOLDEN is the golden image directory, BIN_DIR holds komorebi.exe, +komorebic.exe and komorebi-testwin.exe, OUT gets the run's artifacts. +Every scenario gets its own guest. Those that take clients start from the +windows that `tiling` opens. + +With `KOMOREBI_E2E_RECORDER=DIR` (the folder of komorebi-recorder.exe) the +daemon runs at trace level and komorebi-recorder records the scenario in the +guest, with window tracking; the session comes back as OUT/recording.zip. Every +run also writes OUT/result.json, naming the scenario, the port, the kfw commit +and each check, so that a session can be matched with its run. + +With `KOMOREBI_E2E_SCALE=1.5` every wait of a scenario is 1.5 times as long, for a +busy host (the daemon is slow to answer, and kfw is slow to drop a monitor). + +With `KOMOREBI_E2E_STATE=DIR` every guest is restored from a state saved there +(made on the first run, and again when the golden image, QEMU or guest.py +changed) instead of booting: about 3 s instead of 50 to 90. + +With `KOMOREBI_E2E_CAPTURE=DIR` the raw `komorebic state` is saved to DIR +after `tiling` (state-kfw-tiled.json) and after one window is stacked onto +another (state-kfw-stack.json) and after the focused one is floated +(state-kfw-float.json), to be used as fixtures. +""" + +import importlib +import json +import os +import subprocess +import sys +import time +import traceback +import zipfile +from pathlib import Path + +from komorebi_vm.core.checks import Checks + +from .agent import AgentError, AgentLost +from .guest import Guest +from .state import ensure +from .windows_platform import WindowsPlatform + +# `move_container_to_monitor` takes the focused container off its monitor +# before it looks the target monitor up, so a monitor that is not there loses +# the window; the window stays on screen, unmanaged +UNKNOWN_MONITOR_BUG = ( + "kfw drops the focused window from management when the target monitor " + "does not exist" +) + + +# `PlacementTarget` deserializes with `String::deserialize`, so the number 2 +# is rejected ("data did not match any variant of untagged enum +# InitialWindowPlacementRules") although the type's docs allow an integer; +# the string "2" works +PLACEMENT_INTEGER_CASE = "by the number of the place, counted from 1" +PLACEMENT_INTEGER_BUG = ( + "kfw rejects a number as initial_window_placement_rules and exits at " + "start, a string is accepted" +) + + +class RecordedChecks(Checks): + """`Checks` that also keeps each check, for the result file.""" + + def __init__(self) -> None: + super().__init__() + self.results: list[dict[str, object]] = [] + + def ok(self, description: str) -> None: + super().ok(description) + self.results.append({"check": description, "passed": True}) + + def bad(self, description: str) -> None: + super().bad(description) + self.results.append({"check": description, "passed": False}) + + def skip(self, description: str, reason: str) -> None: + super().skip(description, reason) + self.results.append( + {"check": description, "skipped": True, "reason": reason} + ) + + def known_failure( + self, description: str, condition: bool, reason: str + ) -> bool: + holds = super().known_failure(description, condition, reason) + if not holds: + self.results.append( + {"check": description, "known_failure": True, + "reason": reason} + ) + return holds + + +def _commit() -> str: + """The kfw commit under test: set `KOMOREBI_E2E_COMMIT` to the commit the + binaries were built from; otherwise this tree's HEAD, which may not be it.""" + if os.environ.get("KOMOREBI_E2E_COMMIT"): + return os.environ["KOMOREBI_E2E_COMMIT"] + here = Path(__file__).resolve().parent + try: + git = subprocess.run( + ["git", "-C", str(here), "rev-parse", "HEAD"], + capture_output=True, text=True, + ) + except FileNotFoundError: + return "unknown" + return git.stdout.strip() or "unknown" + + +BINARIES = ["komorebi.exe", "komorebic.exe", "komorebi-testwin.exe"] +WITH_CLIENTS = { + "focus", "moving", "stacks", "workspaces", "resize", "monocle", "closing", + "commands", "hotplug", "unknown_monitor", "lifecycle", + "focus_follows_mouse", +} + +# a small configuration for the sweep's `replace-configuration` +SWEEP_CONFIG = '{"monitors":[{"workspaces":[{"name":"again","layout":"BSP"}]}]}' +SWEEP_CONFIG_PATH = "C:\\e2e\\sweep.json" + + +def _capture(platform: WindowsPlatform, directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + (directory / "state-kfw-tiled.json").write_text( + platform.komorebic("state") + ) + # the last window opened has the focus: stack it onto its neighbor + platform.komorebic("stack", "left") + platform.wait_for(lambda: len(platform.state().containers()) == 2) + time.sleep(1) + (directory / "state-kfw-stack.json").write_text(platform.komorebic("state")) + # then float the focused window, which leaves the stack + platform.komorebic("toggle-float") + time.sleep(1) + (directory / "state-kfw-float.json").write_text(platform.komorebic("state")) + + +RECORD_SECONDS = 100 + + +def _start_recorder( + platform: WindowsPlatform, recorder_dir: Path, guest: Guest, out: Path +) -> None: + """Starts komorebi-recorder in the guest for a fixed time.""" + guest.upload(recorder_dir, ["komorebi-recorder.exe"]) + doctor = platform.agent_exec("C:\\e2e\\bin\\komorebi-recorder.exe", "doctor") + (out / "recorder-doctor.txt").write_text( + f"status {doctor['status']}\n{doctor['stdout']}{doctor['stderr']}" + ) + args = ["record", "--duration", str(RECORD_SECONDS), "--window-track", + "--out", "C:\\e2e\\rec"] + if os.environ.get("RECORD_NO_VIDEO"): + args.append("--no-video") + platform.agent_spawn("C:\\e2e\\bin\\komorebi-recorder.exe", *args) + + +def _collect_recording(platform: WindowsPlatform, out: Path) -> None: + """Waits for the recorder to finish, then brings the session home.""" + def gone() -> bool: + listing = platform.agent_exec("tasklist")["stdout"] + return "komorebi-recorder.exe" not in listing + + platform.wait_for(gone, timeout=RECORD_SECONDS + 60) + platform.agent_exec( + "powershell", "-NoProfile", "-Command", + "Compress-Archive -Force C:\\e2e\\rec C:\\e2e\\rec.zip", + ) + archive = out / "recording.zip" + archive.write_bytes(platform.agent_get_file("C:\\e2e\\rec.zip")) + # Windows PowerShell 5 writes entry names with backslashes + with zipfile.ZipFile(archive) as z: + for entry in z.infolist(): + target = out / "session" / entry.filename.replace("\\", "/") + if entry.is_dir() or entry.filename.endswith("\\"): + target.mkdir(parents=True, exist_ok=True) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(z.read(entry)) + + +def _fetch_logs(guest: Guest, out: Path) -> None: + """After a failure: bring home the agent's log and the daemon's.""" + try: + guest.agent.connect(timeout=20) + guest.agent.exec( + "powershell", "-NoProfile", "-Command", + "Copy-Item $env:TEMP\\komorebi_plaintext.log.* C:\\e2e\\" + "komorebi.log -ErrorAction SilentlyContinue", + ) + for name, remote in (("agent.log", "C:\\e2e\\agent.log"), + ("komorebi.log", "C:\\e2e\\komorebi.log")): + try: + (out / name).write_bytes(guest.agent.get_file(remote)) + except AgentError as e: + print(f" no {name}: {e}") + except (AgentError, OSError, ValueError) as e: + print(f" no logs: {e}") + + +def _diagnose_start( + platform: WindowsPlatform, guest: Guest, out: Path +) -> None: + """After a daemon that did not answer: the processes, the daemon's log, + the agent's log and a screenshot, into `out`.""" + try: + processes = guest.agent.exec( + "cmd", "/c", "tasklist /v /fo csv" + )["stdout"] + (out / "tasklist.csv").write_text(processes) + platform.screenshot("start-failed") + except Exception as e: + print(f" no diagnosis of the start: {e}") + _fetch_logs(guest, out) + + +def run_one( + golden: Path, bin_dir: Path, out: Path, name: str, + state: Path | None = None, +) -> RecordedChecks: + out.mkdir(parents=True, exist_ok=True) + module = "commands" if name == "unknown_monitor" else name + scenario = importlib.import_module( + f"komorebi_vm.core.scenarios.{module}" + ) + tiling = importlib.import_module("komorebi_vm.core.scenarios.tiling") + capture = os.environ.get("KOMOREBI_E2E_CAPTURE") + + checks = RecordedChecks() + print(f"== {name}") + with Guest(golden, out / "guest", state=state) as guest: + guest.upload(bin_dir, BINARIES) + platform = WindowsPlatform( + guest.qmp, guest.agent, out, + scale=float(os.environ.get("KOMOREBI_E2E_SCALE", "1")), + ) + recorder = os.environ.get("KOMOREBI_E2E_RECORDER") + try: + platform.start_komorebi( + log_level="trace" if recorder + else os.environ.get("KOMOREBI_E2E_LOG_LEVEL") + ) + except Exception: + # what the guest was doing when the daemon did not answer + _diagnose_start(platform, guest, out) + raise + if recorder: + _start_recorder(platform, Path(recorder), guest, out) + try: + if name in WITH_CLIENTS: + clients = tiling.run(platform, checks) + if capture and name == "stacks": + _capture(platform, Path(capture)) + return checks + kwargs = {} + if name == "resize" and os.environ.get("RESIZE_DX"): + kwargs["dx"] = int(os.environ["RESIZE_DX"]) + if name == "commands": + config = out / "sweep.json" + config.write_text(SWEEP_CONFIG) + guest.agent.put_file(config, SWEEP_CONFIG_PATH) + if os.environ.get("SWEEP_TWO_DISPLAYS"): + platform.add_display() + time.sleep(5) + scenario.layouts(platform, checks, clients) + scenario.sweep( + platform, checks, clients, SWEEP_CONFIG_PATH + ) + scenario.prints(platform, checks) + return checks + if name == "unknown_monitor": + commands = importlib.import_module( + "komorebi_vm.core.scenarios.commands" + ) + commands.unknown_monitor( + platform, checks, clients, + known_failure=UNKNOWN_MONITOR_BUG, + ) + return checks + if name == "closing": + # the window that was opened last + kwargs["closing"] = clients[-1] + if name == "focus_follows_mouse": + # two tiles that are in view and do not overlap + scenario.run(platform, checks, *clients[:2]) + return checks + scenario.run(platform, checks, clients, **kwargs) + elif name == "placement": + scenario.run( + platform, checks, + known_failures={PLACEMENT_INTEGER_CASE: PLACEMENT_INTEGER_BUG}, + ) + else: + scenario.run(platform, checks) + except AgentLost as e: + print(f" AGENT LOST: {e}") + checks.bad(str(e)) + _fetch_logs(guest, out) + except Exception: + _fetch_logs(guest, out) + raise + finally: + platform.screenshot(f"final-{name}") + if recorder: + _collect_recording(platform, out) + # matches a recorder session directory with the run that made it + (out / "result.json").write_text(json.dumps({ + "scenario": name, + "port": "kfw", + "commit": _commit(), + "passed": checks.passed, + "failed": checks.failed, + "skipped": len(checks.skipped), + "known_failures": len(checks.known), + "start_retries": platform.start_notes, + "checks": checks.results, + }, indent=2)) + return checks + + +def main(argv: list[str]) -> int: + golden, bin_dir, out, *names = argv + failed = 0 + state = None + if os.environ.get("KOMOREBI_E2E_STATE"): + state = ensure(Path(golden), Path(os.environ["KOMOREBI_E2E_STATE"])) + for name in names: + try: + checks = run_one( + Path(golden), Path(bin_dir), Path(out) / name, name, state + ) + except Exception: + # a scenario that cannot run is a failure of its own, and the + # others still run + traceback.print_exc() + print(f"{name}: did not run, counted as 1 failed") + failed += 1 + continue + print(f"{name}: passed {checks.passed} failed {checks.failed}") + if checks.known: + print(f"{name}: known failures {len(checks.known)}") + failed += checks.failed + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/e2e/platforms/qemu_windows/state.py b/e2e/platforms/qemu_windows/state.py new file mode 100644 index 00000000..6bb485ee --- /dev/null +++ b/e2e/platforms/qemu_windows/state.py @@ -0,0 +1,76 @@ +"""A saved running guest, to restore instead of booting for every scenario. + +Booting the golden image takes 50 to 90 seconds; restoring a state saved +after the boot takes about 3 (see W1.md). The state is the guest's memory, +the disk as it was then, the firmware variables and the TPM state, and it +only fits the golden image, the QEMU and the command line it was saved with, +so `ensure` makes a new one when any of them changed. +""" + +import hashlib +import json +import os +import shutil +import subprocess +import tempfile +import time +from pathlib import Path + +from .guest import Guest + +# the guest sits idle this long after the agent answers, before it is saved +SETTLE_SECONDS = 20 + + +def _chain(disk: Path) -> list[str]: + """The size and modification time of a disk and of every image it is + backed by: a golden layer on a base changes when either does.""" + parts = [] + while True: + stat = disk.stat() + parts.append(f"{disk.name} {stat.st_size} {stat.st_mtime_ns}") + info = json.loads(subprocess.run( + ["qemu-img", "info", "--output=json", str(disk)], + capture_output=True, text=True, check=True, + ).stdout) + backing = info.get("backing-filename") + if not backing: + return parts + disk = (disk.parent / backing).resolve() + + +def _key(golden: Path) -> str: + qemu = subprocess.run( + ["qemu-system-x86_64", "--version"], capture_output=True, text=True, + check=True, + ).stdout + # guest.py holds the command line: a change to it makes a new state + source = (Path(__file__).parent / "guest.py").read_bytes() + parts = [ + *_chain(golden / "disk.qcow2"), qemu, + os.environ.get("OVMF_FD", ""), hashlib.sha256(source).hexdigest(), + ] + return hashlib.sha256("\n".join(parts).encode()).hexdigest() + + +def ensure(golden: Path, state: Path) -> Path: + """Returns `state`, saved from `golden` if it is not there or is stale. + + One process at a time: nothing guards against two making it together. + """ + key = _key(golden) + marker = state / "key" + if marker.exists() and marker.read_text() == key: + return state + shutil.rmtree(state, ignore_errors=True) + print(f"== saving a state of the guest to {state}", flush=True) + started = time.monotonic() + # next to the state, not in $TMPDIR: the sockets of the guest are in it, + # and a socket path is limited to about 100 characters + with tempfile.TemporaryDirectory(dir=state.parent, prefix=".build-") as run: + with Guest(golden, Path(run), ahci=True) as guest: + time.sleep(SETTLE_SECONDS) + guest.save(state) + marker.write_text(key) + print(f" saved after {time.monotonic() - started:.0f} s", flush=True) + return state diff --git a/e2e/platforms/qemu_windows/windows_platform.py b/e2e/platforms/qemu_windows/windows_platform.py new file mode 100644 index 00000000..f7a9e9a8 --- /dev/null +++ b/e2e/platforms/qemu_windows/windows_platform.py @@ -0,0 +1,345 @@ +"""The Windows guest as a `Platform` for the shared scenarios. + +Draft: written against the `Platform` protocol of kfde's `komorebi_vm.core` +and not run yet, because the guest agent is not built. The import path moves +with `core/` into this tree. + +Hands and eyes split the way the plan has them: keys, pointer and screenshots +go through QMP, on the host; windows, processes and files go through the agent +in the guest's interactive session. +""" + +import json +import re +import time +from pathlib import Path +from typing import Any + +from PIL import Image + +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Client, OsWindow, Predicate +from komorebi_vm.core.snapshot import Snapshot, parse + +from .agent import Agent, AgentError +from .guest import HOTPLUG_PORTS +from .qmp import Qmp + +# where the host driver puts the binaries under test, in the guest +GUEST_BIN = "C:\\e2e\\bin" +# komorebi.exe's stdout and stderr, kept for a launch that fails +DAEMON_OUTPUT = "C:\\e2e\\komorebi.out" +# what the wrapper writes after the daemon, with its exit code +EXIT_LINE = "komorebi exit code" +# colour codes in the daemon's output +ANSI = re.compile(r"\x1b\[[0-9;]*m") +# a daemon that exited at start is launched again, this many times in all +LAUNCHES = 3 +# the static configuration `restart_with` writes +CONFIG_PATH = "C:\\e2e\\komorebi.json" + + +class WindowsPointer: + """The pointer, driven through QMP's absolute tablet on the host. + + The tablet spans the first display, so a pixel of it is a pixel of the + first monitor. + """ + + def __init__(self, qmp: Qmp, agent: Agent) -> None: + self._qmp = qmp + self._agent = agent + + def _size(self) -> tuple[int, int]: + monitor = self._agent.displays()[0]["monitor"] + return monitor["right"], monitor["bottom"] + + def move(self, x: int, y: int) -> None: + self._qmp.pointer_move(x, y, *self._size()) + + def down(self) -> None: + self._qmp.pointer_button(True) + + def up(self) -> None: + self._qmp.pointer_button(False) + + def drag( + self, + start: tuple[int, int], + end: tuple[int, int], + steps: int = 25, + ms: int = 30, + ) -> None: + width, height = self._size() + self._qmp.pointer_move(*start, width, height) + time.sleep(0.2) + self._qmp.pointer_button(True) + for i in range(1, steps + 1): + x = start[0] + (end[0] - start[0]) * i // steps + y = start[1] + (end[1] - start[1]) * i // steps + self._qmp.pointer_move(x, y, width, height) + time.sleep(ms / 1000) + self._qmp.pointer_button(False) + + +class WindowsPlatform: + """One Windows guest: a QEMU instance, its agent, and the daemon in it.""" + + # the DWM frame is the visible frame, so this is only for rounding + tolerance = 2 + + def __init__( + self, qmp: Qmp, agent: Agent, out: Path, scale: float = 1.0 + ) -> None: + self._qmp = qmp + self._agent = agent + self._out = out + self._scale = scale + self._daemon_pid: int | None = None + self.start_notes: list[str] = [] + self._pointer = WindowsPointer(qmp, agent) + self._added: list[str] = [] + self._ports_used = 0 + + def has(self, feature: str) -> bool: + return feature == "pointer" + + @property + def pointer(self) -> WindowsPointer: + return self._pointer + + def wait_for(self, predicate: Predicate, timeout: float = 10) -> bool: + deadline = time.monotonic() + timeout * self._scale + while time.monotonic() < deadline: + try: + if predicate(): + return True + except RuntimeError: + # `komorebic` failed or timed out while the host is busy: + # not yet, and the last call below says if it still fails + pass + time.sleep(0.1) + return predicate() + + def start_komorebi( + self, log_level: str | None = None, config: str | None = None + ) -> None: + """Starts the daemon and waits until it answers. + + komorebi can fail to launch (`AllowSetForegroundWindow` failing five + times at once, for one), and launching it again works, so a daemon + that has exited without answering is started again, up to + `LAUNCHES` times in all. Every launch that failed is kept, with what + the daemon wrote to stderr, in `start_notes`. + """ + # kfw applies the last state file at start unless told not to, so + # every scenario starts clean + args = ["--clean-state"] + if config: + args += ["--config", config] + if log_level: + args += ["--log-level", log_level] + command = " ".join([f"{GUEST_BIN}\\komorebi.exe", *args]) + for launch in range(1, LAUNCHES + 1): + # through cmd, to keep what the daemon prints if it dies + # `!errorlevel!` is the daemon's exit code, said when it ends + self._daemon_pid = self._agent.spawn( + "cmd", "/v:on", "/c", + f"{command} > {DAEMON_OUTPUT} 2>&1 & " + f"echo {EXIT_LINE} !errorlevel! >> {DAEMON_OUTPUT}", + ) + outcome = self._wait_launched() + if outcome is None: + return + self.start_notes.append(f"launch {launch}: {outcome}") + print(f" komorebi: launch {launch} failed: {outcome}") + raise RuntimeError( + "komorebi did not answer `komorebic state` after " + f"{LAUNCHES} launches: {'; '.join(self.start_notes[-LAUNCHES:])}" + ) + + def _wait_launched(self) -> str | None: + """None once the daemon answers; otherwise why this launch failed: + it ended (with its exit code and what it printed), or it ran on and + never answered. + + That it ended is known from the exit code the wrapper in + `start_komorebi` writes after it; a process list read right after + the launch races the process coming into being. + """ + deadline = time.monotonic() + 60 * self._scale + while time.monotonic() < deadline: + try: + self.komorebic("state") + return None + except Exception: + pass + try: + text = self._agent.get_file(DAEMON_OUTPUT).decode( + errors="replace" + ) + except AgentError: + text = "" + text = ANSI.sub("", text) + lines = [line for line in text.splitlines() if line.strip()] + if any(line.startswith(EXIT_LINE) for line in lines): + # an eyre report starts at "Error:", and the backtrace after + # it is noise; otherwise the end of the output counts + start = next( + (i for i, line in enumerate(lines) + if line.startswith("Error")), None + ) + shown = lines[start:start + 3] if start is not None \ + else lines[-4:] + return "ended without answering; it printed: " + " | ".join( + line.strip() for line in shown + ) + time.sleep(0.5) + return "ran for 60 s and did not answer" + + def restart_with(self, config: dict[str, Any]) -> None: + """Stops the daemon if it runs and starts it from a clean state with + `config` as its static configuration; open windows are taken up.""" + if self.komorebic_status("state")[0] == 0: + self.komorebic("stop") + if not self.wait_for( + lambda: self.komorebic_status("state")[0] != 0, timeout=20 + ): + raise RuntimeError("komorebi did not stop") + local = self._out / "komorebi.json" + local.write_text(json.dumps(config, indent=2)) + self._agent.put_file(local, CONFIG_PATH) + self.start_komorebi(config=CONFIG_PATH) + + def _wait_answering(self) -> None: + def answers() -> bool: + try: + self.komorebic("state") + except Exception: + return False + return True + + if not self.wait_for(answers, timeout=60): + raise RuntimeError("komorebi did not answer `komorebic state`") + + def komorebic(self, *args: str) -> str: + result = self._agent.exec(f"{GUEST_BIN}\\komorebic.exe", *args) + if result["status"] != 0: + raise RuntimeError( + f"komorebic {' '.join(args)}: {result['stderr'] or result}" + ) + return result["stdout"] + + def state(self) -> Snapshot: + return parse(json.loads(self.komorebic("state"))) + + def spawn(self, title: str) -> Client: + self._agent.spawn( + f"{GUEST_BIN}\\komorebi-testwin.exe", "--title", title + ) + if not self.wait_for(lambda: self._find(title) is not None): + raise RuntimeError(f"no window titled {title!r} appeared") + return Client(title) + + def _find(self, title: str) -> dict | None: + for window in self._agent.os_windows(): + if window["title"] == title: + return window + return None + + def os_window_by_title(self, title: str) -> dict | None: + return self._find(title) + + def os_window(self, client: Client) -> OsWindow | None: + window = self._find(client.title) + if window is None: + return None + f = window["frame"] + return OsWindow( + title=window["title"], + frame=Rect(f["left"], f["top"], f["right"], f["bottom"]), + focused=window["focused"], + ) + + def hidden(self, client: Client) -> bool: + # komorebi hides a window of another workspace by cloaking it + window = self._find(client.title) + return window is not None and window["cloaked"] + + def close(self, client: Client) -> None: + window = self._find(client.title) + if window is None: + raise RuntimeError(f"no window titled {client.title!r}") + self._agent.call("close", hwnd=window["hwnd"]) + + def komorebic_status(self, *args: str) -> tuple[int, str]: + result = self._agent.exec(f"{GUEST_BIN}\\komorebic.exe", *args) + return result["status"], result["stdout"] + result["stderr"] + + def _displays(self) -> list[dict]: + # the agent may drop the connection while the display topology + # changes; one reconnect is enough + try: + return self._agent.displays() + except (OSError, ValueError, AgentError): + self._agent.connect(timeout=10) + return self._agent.displays() + + def displays(self) -> list[Rect]: + monitors = [d["monitor"] for d in self._displays()] + rects = [ + Rect(m["left"], m["top"], m["right"], m["bottom"]) + for m in monitors + ] + return sorted(rects, key=lambda r: r.x) + + def _wait_displays(self, count: int) -> None: + if not self.wait_for(lambda: len(self.displays()) == count, 60): + raise RuntimeError(f"the OS did not reach {count} displays") + + def add_display(self) -> None: + # a port is never reused: QEMU aborts when a QXL device is added at a + # path whose RAM blocks the one before it has not given back yet + self._ports_used += 1 + n = self._ports_used + if n > HOTPLUG_PORTS: + raise RuntimeError("no hotplug port left for another display") + before = len(self.displays()) + self._qmp.execute( + "device_add", driver="qxl", id=f"qxl{n}", bus=f"rp{n}", + ram_size_mb=64, vram_size_mb=64, vgamem_mb=16, + ) + self._added.append(f"qxl{n}") + self._wait_displays(before + 1) + + def remove_display(self) -> None: + if not self._added: + raise RuntimeError("no display was added by add_display") + before = len(self.displays()) + self._qmp.execute("device_del", id=self._added.pop()) + self._wait_displays(before - 1) + + def work_area(self) -> Rect: + area = self._agent.displays()[0]["work_area"] + return Rect(area["left"], area["top"], area["right"], area["bottom"]) + + def activate(self, client: Client) -> None: + window = self._find(client.title) + if window is None: + raise RuntimeError(f"no window titled {client.title!r}") + self._agent.call("activate", hwnd=window["hwnd"]) + + def screenshot(self, name: str) -> Image.Image: + path = self._out / f"{name}.png" + self._qmp.screendump(path) + return Image.open(path) + + def agent_exec(self, *args: str) -> dict: + """Runs a program in the guest, for the recorder step of the runner.""" + return self._agent.exec(*args) + + def agent_spawn(self, *args: str) -> int: + return self._agent.spawn(*args) + + def agent_get_file(self, remote: str) -> bytes: + return self._agent.get_file(remote)