from __future__ import annotations
import os
import shlex
import shutil
import signal
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
GUESTS_DIR = SCRIPT_DIR / "devvm" / "guests"
WINDOWS_PROVISION_DIR = SCRIPT_DIR / "devvm" / "provision"
STATE_DIR = REPO_ROOT / ".tmp" / "devvm"
@dataclass(frozen=True)
class Guest:
name: str
communicator: str box: str
available: bool = True
unavailable_reason: str | None = None
tree_path_posix: str | None = None
def guest_dir(guest: Guest) -> Path:
return GUESTS_DIR / guest.name
def dotfile_dir(guest: Guest) -> Path:
return STATE_DIR / guest.name / ".vagrant"
def stage_dir(guest: Guest) -> Path:
return STATE_DIR / guest.name / "tree"
def auto_consent_state_path(guest: Guest) -> Path:
return STATE_DIR / guest.name / "auto_consent"
def require_tool(name: str) -> None:
if shutil.which(name) is None:
print(
f"error: '{name}' not found on PATH. See scripts/README.md#prerequisites for what to install.",
file=sys.stderr,
)
sys.exit(1)
def vagrant_env(guest: Guest, *, display: bool = False) -> dict[str, str]:
env = dict(os.environ)
env["VAGRANT_DOTFILE_PATH"] = str(dotfile_dir(guest))
env["DEVVM_STAGE_DIR"] = str(stage_dir(guest))
env["DEVVM_WINDOWS_DISPLAY"] = "1" if display else "0"
return env
def run_vagrant(guest: Guest, args: list[str], *, display: bool = False, check: bool = True) -> int:
require_tool("vagrant")
cwd = guest_dir(guest)
cmd = ["vagrant", *args]
print(f"+ (cd {cwd} && {shlex.join(cmd)})", file=sys.stderr)
result = subprocess.run(cmd, cwd=cwd, env=vagrant_env(guest, display=display))
if check and result.returncode != 0:
sys.exit(result.returncode)
return result.returncode
def run_vagrant_streaming(
guest: Guest,
args: list[str],
*,
display: bool = False,
check: bool = True,
) -> tuple[int, str]:
require_tool("vagrant")
cwd = guest_dir(guest)
cmd = ["vagrant", *args]
print(f"+ (cd {cwd} && {shlex.join(cmd)})", file=sys.stderr)
proc = subprocess.Popen(
cmd,
cwd=cwd,
env=vagrant_env(guest, display=display),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
assert proc.stdout is not None
lines = []
for line in proc.stdout:
sys.stdout.write(line)
lines.append(line)
returncode = proc.wait()
if check and returncode != 0:
sys.exit(returncode)
return returncode, "".join(lines)
@dataclass(frozen=True)
class BoundedWinrmResult:
returncode: int
stdout: str
stderr: str
timed_out: bool
def run_vagrant_winrm_bounded(guest: Guest, powershell_cmd: str, deadline: float) -> BoundedWinrmResult:
remaining = max(deadline - time.monotonic(), 0.001)
proc = subprocess.Popen(
["vagrant", "winrm", "-c", powershell_cmd],
cwd=guest_dir(guest),
env=vagrant_env(guest),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
start_new_session=True,
)
try:
stdout, stderr = proc.communicate(timeout=remaining)
except subprocess.TimeoutExpired:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
stdout, stderr = proc.communicate()
return BoundedWinrmResult(1, stdout, stderr, timed_out=True)
return BoundedWinrmResult(proc.returncode, stdout, stderr, timed_out=False)
def powershell_quote(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def get_vagrant_machine_state(guest: Guest) -> str:
require_tool("vagrant")
result = subprocess.run(
["vagrant", "status", "--machine-readable"],
cwd=guest_dir(guest),
env=vagrant_env(guest),
capture_output=True,
text=True,
)
for line in result.stdout.splitlines():
fields = line.split(",", 3)
if len(fields) >= 4 and fields[2] == "state":
return fields[3]
raise RuntimeError(
f"devvm: could not find a 'state' line in `vagrant status --machine-readable` for "
f"guest '{guest.name}' (exit {result.returncode}) — output:\n{result.stdout}"
)