from __future__ import annotations
import argparse
import base64
import contextlib
import math
import ntpath
import os
import shlex
import shutil
import stat
import subprocess
import sys
import time
from collections.abc import Iterator
from pathlib import Path
_SCRIPT_DIR = Path(__file__).resolve().parent
if str(_SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPT_DIR))
from devvm_common import ( REPO_ROOT,
STATE_DIR,
Guest,
auto_consent_state_path,
dotfile_dir,
get_vagrant_machine_state,
powershell_quote,
require_tool,
run_vagrant,
stage_dir,
stage_lock,
)
from devvm_windows import ( InteractiveLookupFailure,
get_windows_interactive_username,
provision_windows_guest,
)
if sys.platform != "win32":
import devvm_macos
WINDOWS_RUN_UNELEVATED_MAX_TIMEOUT_SECONDS = (2**31 - 1) // 1000
WINDOWS_VERBATIM_PREFIX = "\\\\?\\"
WINDOWS_VERBATIM_UNC_PREFIX = "\\\\?\\UNC\\"
WINDOWS_DEVICE_PREFIX = "\\\\.\\"
def _fs_path(path: Path) -> str:
absolute = os.path.abspath(path)
if sys.platform != "win32":
return absolute
return _windows_verbatim(absolute)
def _windows_verbatim(absolute: str) -> str:
if absolute.startswith(WINDOWS_VERBATIM_PREFIX):
return absolute
if absolute.startswith(WINDOWS_DEVICE_PREFIX):
return WINDOWS_VERBATIM_PREFIX + absolute[len(WINDOWS_DEVICE_PREFIX) :]
if ntpath.splitdrive(absolute)[0].startswith("\\\\"):
return WINDOWS_VERBATIM_UNC_PREFIX + absolute[2:]
return WINDOWS_VERBATIM_PREFIX + absolute
def _clear_readonly_and_retry(func, path, _exc) -> None:
os.chmod(path, stat.S_IWRITE)
func(path)
def _rmtree(path: str) -> None:
if sys.platform != "win32":
shutil.rmtree(path)
elif sys.version_info >= (3, 12):
shutil.rmtree(path, onexc=_clear_readonly_and_retry)
else:
shutil.rmtree(path, onerror=lambda func, p, _info: _clear_readonly_and_retry(func, p, None))
MACOS_BOX_NOTE = "Tart, Cirrus base image - not GitHub's runner image"
GUESTS: dict[str, Guest] = {
"linux-x64": Guest(
name="linux-x64",
communicator="ssh",
box="cloud-image/ubuntu-24.04 (qemu/amd64)",
tree_path_posix="/home/vagrant/cosca",
),
"linux-arm64": Guest(
name="linux-arm64",
communicator="ssh",
box="perk/ubuntu-24.04-arm64 (qemu/arm64)",
tree_path_posix="/home/vagrant/cosca",
),
"macos-arm64": Guest(
name="macos-arm64",
communicator="tart",
box=MACOS_BOX_NOTE if sys.platform == "win32" else f"{devvm_macos.BASE_IMAGE} ({MACOS_BOX_NOTE})",
available=sys.platform != "win32",
unavailable_reason="needs an Apple Silicon Mac (Tart)" if sys.platform == "win32" else None,
tree_path_posix="~/cosca",
),
"windows-x64": Guest(
name="windows-x64",
communicator="winrm",
box="stromweld/windows-10 (qemu/amd64)",
tree_path_posix="C:/cosca",
),
"windows-arm64": Guest(
name="windows-arm64",
communicator="winrm",
box="(none)",
available=False,
unavailable_reason=(
"no publicly available Vagrant box for Windows on arm64 targets the qemu or "
"libvirt provider this tool uses. Build your own box from a Windows-on-ARM "
"evaluation VHDX and pass its path via `qe.image_path` in a custom Vagrantfile "
"if you need this lane; see scripts/README.md#windows-arm64 for details."
),
),
}
def read_persisted_auto_consent(guest: Guest) -> bool:
path = auto_consent_state_path(guest)
if not path.exists():
return False
return path.read_text().strip() == "1"
def write_persisted_auto_consent(guest: Guest, value: bool) -> None:
path = auto_consent_state_path(guest)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("1" if value else "0")
def require_available(guest: Guest) -> None:
if not guest.available:
print(f"error: guest '{guest.name}' is not available: {guest.unavailable_reason}", file=sys.stderr)
sys.exit(1)
def _diag_write(direct: bool, message_expr: str) -> str:
if direct:
return f"Write-Host {message_expr}"
return f"[Console]::Error.WriteLine({message_expr})"
def build_run_inner(guest: Guest, cmd_args: list[str], *, direct: bool) -> str:
quoted_path = powershell_quote(guest.tree_path_posix)
quoted_cmd = " ".join(powershell_quote(part) for part in cmd_args)
trap_write = _diag_write(direct, '"devvm: $_"')
exit_write = _diag_write(direct, '"devvm: command exited $__devvmExit"')
return (
"$ProgressPreference = 'SilentlyContinue'; "
f"trap {{ {trap_write}; exit 1 }}; "
f"Set-Location -Path {quoted_path} -ErrorAction Stop; "
f'$env:CARGO_TARGET_DIR = "$HOME\\cargo-target"; '
"$global:LASTEXITCODE = $null; "
f"& {quoted_cmd}; "
"if ($null -ne $LASTEXITCODE) { $__devvmExit = $LASTEXITCODE } else { $__devvmExit = [int](-not $?) }; "
f"if ($__devvmExit -ne 0) {{ {exit_write} }}; "
"exit $__devvmExit"
)
@contextlib.contextmanager
def staged_tree(guest: Guest, *, repo_root: Path = REPO_ROOT, dest: Path | None = None) -> Iterator[None]:
if dest is None:
dest = stage_dir(guest)
with stage_lock(dest):
_copy_tracked(repo_root, dest)
yield
def stage_tree(guest: Guest, *, repo_root: Path = REPO_ROOT, dest: Path | None = None) -> None:
with staged_tree(guest, repo_root=repo_root, dest=dest):
pass
def _copy_tracked(repo_root: Path, dest: Path) -> None:
require_tool("git")
if sys.platform != "win32":
require_tool("rsync")
ls_files = subprocess.run(
["git", "-C", str(repo_root), "ls-files", "-z"],
check=True,
capture_output=True,
)
tracked = [p for p in ls_files.stdout.split(b"\0") if p]
src_root = _fs_path(repo_root)
dst_root = _fs_path(dest)
def native(rel: bytes) -> str:
name = rel.decode()
return name.replace("/", "\\") if sys.platform == "win32" else name
existing = [p for p in tracked if os.path.isfile(os.path.join(src_root, native(p)))]
existing_set = set(existing)
skipped = [p for p in tracked if p not in existing_set]
assert not any(os.path.lexists(os.path.join(src_root, native(p))) for p in skipped), (
"a tracked entry that is not a regular file exists on disk (a directory, a submodule, a dangling symlink)"
)
assert not any(os.path.islink(os.path.join(src_root, native(p))) for p in existing), (
"a tracked symlink: the stage copies regular files only"
)
os.makedirs(os.path.dirname(dst_root), exist_ok=True)
try:
_rmtree(dst_root)
except FileNotFoundError:
pass
os.makedirs(dst_root)
if sys.platform == "win32":
for rel in existing:
target = os.path.join(dst_root, native(rel))
os.makedirs(os.path.dirname(target), exist_ok=True)
shutil.copy2(os.path.join(src_root, native(rel)), target)
return
files_list = dest.parent / "tracked-files.list"
files_list.write_bytes(b"\0".join(existing) + (b"\0" if existing else b""))
cmd = [
"rsync",
"--archive",
"--from0",
f"--files-from={files_list}",
f"{repo_root}/",
f"{dest}/",
]
print(f"+ {shlex.join(cmd)}", file=sys.stderr)
subprocess.run(cmd, check=True)
def parse_run_argv(rest: list[str]) -> tuple[list[str], bool, int | None, list[str]]:
if "--" in rest:
idx = rest.index("--")
before, cmd_tail = rest[:idx], rest[idx + 1 :]
else:
before, cmd_tail = rest, []
def parse_timeout(raw: str) -> int:
try:
return int(raw)
except ValueError:
print(f"devvm.py run: argument --timeout: invalid int value: {raw!r}", file=sys.stderr)
sys.exit(2)
head: list[str] = []
unelevated = False
timeout: int | None = None
i = 0
while i < len(before):
tok = before[i]
if tok == "--unelevated":
unelevated = True
i += 1
elif tok == "--timeout":
if i + 1 >= len(before):
print("devvm.py run: argument --timeout: expected one argument", file=sys.stderr)
sys.exit(2)
timeout = parse_timeout(before[i + 1])
i += 2
elif tok.startswith("--timeout="):
timeout = parse_timeout(tok[len("--timeout=") :])
i += 1
else:
head.append(tok)
i += 1
return head, unelevated, timeout, cmd_tail
def _vagrant_status(guest: Guest) -> str:
require_tool("vagrant")
if not dotfile_dir(guest).exists():
return "not created"
try:
return get_vagrant_machine_state(guest)
except RuntimeError:
return "unknown"
def cmd_list(_args: argparse.Namespace) -> None:
for guest in GUESTS.values():
if not guest.available:
print(f"{guest.name:14s} UNAVAILABLE {guest.unavailable_reason}")
continue
state = backend_for(guest).status()
print(f"{guest.name:14s} {state:14s} {guest.box} (communicator: {guest.communicator})")
def _vagrant_up(args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
display = bool(getattr(args, "display", False))
if args.allow_elevation and guest.communicator != "winrm":
print("error: --allow-elevation only applies to Windows guests", file=sys.stderr)
sys.exit(1)
if display and guest.communicator != "winrm":
print("error: --display only applies to Windows guests", file=sys.stderr)
sys.exit(1)
if getattr(args, "rosetta", False):
print("error: --rosetta only applies to macOS guests", file=sys.stderr)
sys.exit(1)
if getattr(args, "rev", None) is not None:
print("error: --rev only applies to macOS guests (the others stage the working tree)", file=sys.stderr)
sys.exit(1)
dotfile_dir(guest).mkdir(parents=True, exist_ok=True)
if guest.communicator == "winrm":
if args.allow_elevation is None:
auto_consent = read_persisted_auto_consent(guest)
else:
auto_consent = args.allow_elevation
write_persisted_auto_consent(guest, auto_consent)
else:
auto_consent = False
if auto_consent:
print(
"note: auto-approve-consent is ON for this guest — ShellExecuteExW(\"runas\") will "
"elevate without a UAC prompt. This is an opt-in probe-only mode; see "
"scripts/README.md#windows-guests.",
file=sys.stderr,
)
if display:
print(
"note: --display is ON for this guest — QEMU will open a local window on this Mac "
"(-display cocoa -vga std) instead of running headless. This is a local window "
"only, not VNC or any other network-exposed display; the loopback-only port "
"forwarding guarantee is unaffected.",
file=sys.stderr,
)
with staged_tree(guest):
if guest.communicator == "winrm":
provision_windows_guest(guest, auto_consent=auto_consent, display=display, create=True)
else:
run_vagrant(guest, ["up", "--provider", "qemu", "--provision"])
if guest.communicator == "ssh":
print(f"note: the read-only working tree is synced to {guest.tree_path_posix} — run `devvm.py sync {guest.name}` after local changes.")
else:
print(f"note: the read-only working tree is copied to {guest.tree_path_posix} — run `devvm.py sync {guest.name}` after local changes.")
def _vagrant_sync(args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
if getattr(args, "rev", None) is not None:
print("error: --rev only applies to macOS guests (the others stage the working tree)", file=sys.stderr)
sys.exit(1)
if not dotfile_dir(guest).exists():
print(f"error: guest '{guest.name}' has not been brought up yet; run `devvm.py up {guest.name}` first", file=sys.stderr)
sys.exit(1)
with staged_tree(guest):
if guest.communicator == "ssh":
run_vagrant(guest, ["rsync"])
else:
auto_consent = read_persisted_auto_consent(guest)
provision_windows_guest(guest, auto_consent=auto_consent, create=False)
def _vagrant_ssh(args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
if guest.communicator == "ssh":
run_vagrant(guest, ["ssh"])
return
if not sys.platform.startswith("win"):
print(
f"error: `devvm.py ssh {guest.name}` runs `vagrant powershell`, which only works "
"on a Windows host — Vagrant 2.4.9 raises HostUnsupported immediately on any other "
"host (plugins/commands/powershell/command.rb:74), before ever touching the guest. "
f"Use `devvm.py run {guest.name} -- <cmd>` for a one-off command, or RDP into the "
"guest for an interactive session (127.0.0.1:3389 by default — see the 'rdp' "
f"forwarded_port in scripts/devvm/guests/{guest.name}/Vagrantfile).",
file=sys.stderr,
)
sys.exit(1)
run_vagrant(guest, ["powershell"])
def _vagrant_run(args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
cmd_args = list(args.cmd)
if cmd_args and cmd_args[0] == "--":
cmd_args = cmd_args[1:]
if not cmd_args:
print("error: no command given; usage: devvm.py run <guest> -- <cmd...>", file=sys.stderr)
sys.exit(1)
if args.unelevated and guest.communicator != "winrm":
print("error: --unelevated only applies to Windows guests", file=sys.stderr)
sys.exit(1)
if args.timeout is not None and not args.unelevated:
print("error: --timeout only applies to --unelevated", file=sys.stderr)
sys.exit(1)
timeout = args.timeout if args.timeout is not None else 3600
if timeout <= 0:
print(f"error: --timeout must be positive, got {timeout}", file=sys.stderr)
sys.exit(1)
if timeout > WINDOWS_RUN_UNELEVATED_MAX_TIMEOUT_SECONDS:
print(
f"error: --timeout must be at most {WINDOWS_RUN_UNELEVATED_MAX_TIMEOUT_SECONDS} "
f"(seconds*1000 must fit in a 32-bit millisecond count on the guest side), got "
f"{timeout}",
file=sys.stderr,
)
sys.exit(1)
if guest.communicator == "ssh":
inner = (
f'export PATH="$HOME/.cargo/bin:$PATH"; '
f"cd {guest.tree_path_posix} && CARGO_TARGET_DIR=$HOME/cargo-target {shlex.join(cmd_args)}"
)
run_vagrant(guest, ["ssh", "-c", inner])
return
if not args.unelevated:
inner = build_run_inner(guest, cmd_args, direct=True)
run_vagrant(guest, ["winrm", "-c", inner])
return
deadline = time.monotonic() + timeout
interactive_user, failure, interactive_output = get_windows_interactive_username(guest, deadline)
if interactive_user is None:
if failure is InteractiveLookupFailure.TIMED_OUT:
print(
f"error: timed out after {timeout}s waiting for WinRM to report whether "
"'vagrant' has an interactive (session 1, console or RDP-redirected) logon. "
"Try a longer --timeout.",
file=sys.stderr,
)
elif failure is InteractiveLookupFailure.WINRM_FAILED:
print(
"error: the WinRM query for an interactive logon on 'vagrant' failed (see "
"output below) — this is a real failure WinRM reported, not a timeout or an "
"absence of any session.",
file=sys.stderr,
)
else:
print(
"error: no interactive (session 1, console or RDP-redirected) logon for 'vagrant' "
"was found, so there is no logon for --unelevated's scheduled task to borrow. See "
"windows-account-and-uac.ps1's autologon setup.",
file=sys.stderr,
)
if interactive_output.strip():
print(f"Last WinRM output:\n{interactive_output}", file=sys.stderr)
sys.exit(1)
remaining = deadline - time.monotonic()
if remaining <= 0:
print(
f"error: timed out after {timeout}s — the interactive-logon lookup above used up "
"the whole --timeout budget, leaving none for the probe itself. Try a longer "
"--timeout.",
file=sys.stderr,
)
sys.exit(1)
remaining_timeout_seconds = math.ceil(remaining)
inner = build_run_inner(guest, cmd_args, direct=False)
encoded = base64.b64encode(inner.encode("utf-16-le")).decode("ascii")
runner_path = f"{guest.tree_path_posix}/scripts/devvm/provision/windows-run-unelevated.ps1"
outer = (
'trap { Write-Host "devvm: $_"; exit 1 }; '
"$global:LASTEXITCODE = $null; "
f"& {powershell_quote(runner_path)} -EncodedCommand {powershell_quote(encoded)} "
f"-InteractiveUser {powershell_quote(interactive_user)} "
f"-TimeoutSeconds {remaining_timeout_seconds}; "
"if ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }; "
"exit [int](-not $?)"
)
run_vagrant(guest, ["winrm", "-c", outer])
def _vagrant_halt(args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
run_vagrant(guest, ["halt"])
def _vagrant_destroy(args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
returncode = run_vagrant(guest, ["destroy", "-f"], check=False)
if returncode != 0:
print(
f"error: `vagrant destroy` failed (exit {returncode}) for guest '{guest.name}' — "
"leaving .tmp/devvm state in place rather than deleting it out from under a VM "
"that may still be running. Investigate (e.g. `vagrant status`, a stuck lock) "
"and re-run `destroy` once it's actually gone.",
file=sys.stderr,
)
sys.exit(returncode)
guest_state = STATE_DIR / guest.name
if guest_state.exists():
shutil.rmtree(guest_state)
class VagrantBackend:
def __init__(self, guest: Guest):
self.guest = guest
def status(self) -> str:
return _vagrant_status(self.guest)
def up(self, args: argparse.Namespace) -> None:
_vagrant_up(args)
def sync(self, args: argparse.Namespace) -> None:
_vagrant_sync(args)
def ssh(self, args: argparse.Namespace) -> None:
_vagrant_ssh(args)
def run(self, args: argparse.Namespace) -> None:
_vagrant_run(args)
def halt(self, args: argparse.Namespace) -> None:
_vagrant_halt(args)
def destroy(self, args: argparse.Namespace) -> None:
_vagrant_destroy(args)
def fetch(self, _args: argparse.Namespace) -> None:
print("error: fetch only applies to macOS guests", file=sys.stderr)
sys.exit(1)
def backend_for(guest: Guest):
if guest.communicator == "tart":
assert sys.platform != "win32", "the macOS guest is unavailable on a Windows host"
return devvm_macos.MacosBackend(None, REPO_ROOT, STATE_DIR)
return VagrantBackend(guest)
def _dispatch(verb: str, args: argparse.Namespace) -> None:
guest = GUESTS[args.guest]
require_available(guest)
getattr(backend_for(guest), verb)(args)
def cmd_up(args: argparse.Namespace) -> None:
_dispatch("up", args)
def cmd_sync(args: argparse.Namespace) -> None:
_dispatch("sync", args)
def cmd_ssh(args: argparse.Namespace) -> None:
_dispatch("ssh", args)
def cmd_run(args: argparse.Namespace) -> None:
_dispatch("run", args)
def cmd_halt(args: argparse.Namespace) -> None:
_dispatch("halt", args)
def cmd_destroy(args: argparse.Namespace) -> None:
_dispatch("destroy", args)
def cmd_fetch(args: argparse.Namespace) -> None:
_dispatch("fetch", args)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="devvm.py",
description="Provision throwaway VMs for cosca's system-affecting tests. Dev tooling only — never a CI replacement.",
)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("list", help="list known guests and their state").set_defaults(func=cmd_list)
p = sub.add_parser("up", help="create/start a guest and provision it")
p.add_argument("guest", choices=GUESTS.keys())
p.add_argument(
"--allow-elevation",
action=argparse.BooleanOptionalAction,
default=None,
help="(Windows only) auto-approve UAC consent prompts, for unattended probe runs. Off "
"by default. Persisted per guest — omit the flag on a later `up`/`sync` to keep "
"reusing whatever was last set; pass --no-allow-elevation to explicitly turn it "
"back off.",
)
p.add_argument(
"--display",
action="store_true",
help="(Windows only) open a local QEMU window on this Mac (-display cocoa -vga std) "
"instead of running headless, e.g. so a human can watch the guest's console live. "
"Headless remains the default; this is a local window only, never VNC or any other "
"network-exposed display. Not persisted — pass it again on every `up` that needs it.",
)
p.add_argument(
"--rev",
default=None,
help="(macOS only) git rev to `git archive` into the guest (default HEAD; committed state only).",
)
p.add_argument(
"--rosetta",
action="store_true",
help="(macOS only) install Rosetta and the x86_64-apple-darwin target, to run x86_64 test "
"binaries in the guest. An approximation of the Intel lane, not a replacement.",
)
p.set_defaults(func=cmd_up)
p = sub.add_parser("sync", help="push the working tree into a running guest (macOS guests get the committed `git archive <rev>` instead)")
p.add_argument("guest", choices=GUESTS.keys())
p.add_argument("--rev", default=None, help="(macOS only) git rev to `git archive` into the guest.")
p.set_defaults(func=cmd_sync)
p = sub.add_parser("ssh", help="open an interactive shell in a guest")
p.add_argument("guest", choices=GUESTS.keys())
p.set_defaults(func=cmd_ssh)
p = sub.add_parser("run", help="run one command in a guest, e.g.: devvm.py run linux-x64 -- cargo test")
p.add_argument("guest", choices=GUESTS.keys())
p.add_argument(
"--unelevated",
action="store_true",
help="(Windows only) run via a scheduled task borrowing the current interactive "
"logon's real filtered (non-elevated) token, instead of WinRM's own full-rights "
"network-logon token — needed to measure the actual UAC/runas consent path.",
)
p.add_argument(
"--timeout",
type=int,
help="Seconds to wait for an --unelevated command to finish (default 3600).",
)
p.add_argument("cmd", nargs=argparse.REMAINDER, help="command to run, prefixed with --")
p.set_defaults(func=cmd_run)
p = sub.add_parser("fetch", help="(macOS only) copy a file or directory out of the guest")
p.add_argument("guest", choices=GUESTS.keys())
p.add_argument("guest_path")
p.add_argument("host_dest")
p.set_defaults(func=cmd_fetch)
p = sub.add_parser("halt", help="shut down a guest, keeping its disk")
p.add_argument("guest", choices=GUESTS.keys())
p.set_defaults(func=cmd_halt)
p = sub.add_parser("destroy", help="delete a guest and its state entirely")
p.add_argument("guest", choices=GUESTS.keys())
p.set_defaults(func=cmd_destroy)
return parser
def main(argv: list[str] | None = None) -> None:
argv = list(argv if argv is not None else sys.argv[1:])
unelevated = False
timeout: int | None = None
if argv[:1] == ["run"]:
head, unelevated, timeout, cmd_tail = parse_run_argv(argv[1:])
argv = ["run", *head]
else:
cmd_tail = None
parser = build_parser()
args = parser.parse_args(argv)
if args.command == "run":
args.unelevated = unelevated
args.timeout = timeout
args.cmd = cmd_tail if cmd_tail is not None else []
args.func(args)
if __name__ == "__main__":
main()