from __future__ import annotations
import contextlib
import os
import shlex
import shutil
import signal
import subprocess
import sys
import time
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
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"
@contextlib.contextmanager
def stage_lock(stage: Path) -> Iterator[None]:
lock_path = stage.parent / f"{stage.name}.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT)
try:
try:
if sys.platform == "win32":
import msvcrt
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (BlockingIOError, PermissionError): print(
f"error: another devvm command is using {stage}; wait for it to finish and run this again",
file=sys.stderr,
)
sys.exit(1)
try:
yield
finally:
if sys.platform == "win32":
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
finally:
os.close(fd)
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)
with _started_in_kill_tree_scope(
["vagrant", "winrm", "-c", powershell_cmd],
cwd=guest_dir(guest),
env=vagrant_env(guest),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
) as (proc, kill_tree):
try:
stdout, stderr = proc.communicate(timeout=remaining)
except subprocess.TimeoutExpired:
kill_tree()
stdout, stderr = proc.communicate()
return BoundedWinrmResult(1, stdout, stderr, timed_out=True)
return BoundedWinrmResult(proc.returncode, stdout, stderr, timed_out=False)
@contextlib.contextmanager
def _started_in_kill_tree_scope(argv: list[str], **popen_kwargs: Any) -> Iterator[tuple[Any, Callable[[], None]]]:
if sys.platform == "win32":
from devvm_winjob import KillOnCloseJob
with KillOnCloseJob() as job, job.popen(argv, **popen_kwargs) as proc:
yield proc, job.terminate
else:
proc = subprocess.Popen(argv, start_new_session=True, **popen_kwargs)
yield proc, lambda: os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
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}"
)