"""File and command execution: either on this machine or on the Proxmox host over SSH.""" from __future__ import annotations import os import shlex import subprocess import tempfile import time from dataclasses import dataclass from pathlib import Path from typing import Protocol, Sequence from .errors import ProxdomainError @dataclass(frozen=True) class CommandResult: argv: tuple[str, ...] returncode: int stdout: str = "" stderr: str = "" @property def ok(self) -> bool: return self.returncode == 0 def output(self, limit: int = 1200) -> str: text = "\n".join(part.strip() for part in (self.stdout, self.stderr) if part.strip()) return text[-limit:] class Runner(Protocol): def run( self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0 ) -> CommandResult: ... def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: ... def read_text(self, path: str) -> str | None: ... def remove(self, path: str) -> bool: ... def exists(self, path: str) -> bool: ... def mkdir(self, path: str) -> None: ... def describe(self) -> str: ... class LocalRunner: """Writes files and runs commands directly (used when proxdomain runs on the PVE host).""" def __init__(self, *, sleep=time.sleep) -> None: self._sleep = sleep def run( self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0 ) -> CommandResult: argv = tuple(argv) if not argv: raise ProxdomainError("refusing to run an empty command") try: completed = subprocess.run( list(argv), input=input_text, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, check=False, ) except FileNotFoundError as exc: raise ProxdomainError(f"command not found: {argv[0]}") from exc except subprocess.TimeoutExpired as exc: raise ProxdomainError(f"command timed out after {timeout}s: {' '.join(argv)}") from exc return CommandResult( argv=argv, returncode=completed.returncode, stdout=completed.stdout or "", stderr=completed.stderr or "", ) def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: target = Path(path) current = self.read_text(path) if current is not None and current == content: return False target.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent)) try: with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: handle.write(content) handle.flush() os.fsync(handle.fileno()) if os.name != "nt": os.chmod(tmp, mode) os.replace(tmp, target) except BaseException: with _suppress_errors(): os.unlink(tmp) raise return True def read_text(self, path: str) -> str | None: try: return Path(path).read_text(encoding="utf-8") except FileNotFoundError: return None except IsADirectoryError: return None except OSError as exc: raise ProxdomainError(f"cannot read {path}: {exc}") from exc def remove(self, path: str) -> bool: try: os.unlink(path) return True except FileNotFoundError: return False except OSError as exc: raise ProxdomainError(f"cannot remove {path}: {exc}") from exc def exists(self, path: str) -> bool: return Path(path).exists() def mkdir(self, path: str) -> None: Path(path).mkdir(parents=True, exist_ok=True) def describe(self) -> str: return "local" class SSHRunner: """Runs commands and manages files on the Proxmox host through `ssh`. Uses non-interactive sudo (`sudo -n` by default) so a missing sudo grant fails fast instead of hanging a cron job or systemd unit. """ def __init__( self, host: str, *, port: int = 22, identity_file: str = "", ssh_options: Sequence[str] = (), sudo: str = "sudo -n", timeout: float = 120.0, sleep=time.sleep, ) -> None: if not host: raise ProxdomainError("webserver.ssh_host must not be empty") self.host = host self.port = port self.identity_file = identity_file self.ssh_options = tuple(ssh_options) self.sudo = sudo.strip() self.timeout = timeout self._sleep = sleep # -- commands ------------------------------------------------------- def run( self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0 ) -> CommandResult: argv = tuple(argv) if not argv: raise ProxdomainError("refusing to run an empty command") remote = " ".join(shlex.quote(str(part)) for part in argv) return self._ssh(remote, input_text=input_text, timeout=timeout) def _ssh( self, remote_command: str, *, input_text: str | None = None, timeout: float = 120.0 ) -> CommandResult: argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10"] if self.port != 22: argv += ["-p", str(self.port)] if self.identity_file: argv += ["-i", self.identity_file] for option in self.ssh_options: argv += ["-o", option] argv += [self.host, remote_command] try: completed = subprocess.run( argv, input=input_text, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, check=False, ) except FileNotFoundError as exc: raise ProxdomainError("ssh client not found on PATH") from exc except subprocess.TimeoutExpired as exc: raise ProxdomainError( f"ssh to {self.host} timed out after {timeout}s: {remote_command[:200]}" ) from exc return CommandResult( argv=tuple(argv), returncode=completed.returncode, stdout=completed.stdout or "", stderr=completed.stderr or "", ) # -- files ---------------------------------------------------------- def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: if self.read_text(path) == content: return False directory = _posix_dirname(path) tmp = f"{path}.proxdomain.tmp" script = " && ".join( [ self._sudo(f"mkdir -p {shlex.quote(directory)}"), self._sudo(f"tee {shlex.quote(tmp)} > /dev/null"), self._sudo(f"chmod {mode:o} {shlex.quote(tmp)}"), self._sudo(f"mv -f {shlex.quote(tmp)} {shlex.quote(path)}"), ] ) result = self._ssh(script, input_text=content) if not result.ok: raise ProxdomainError( f"cannot write {path} on {self.host}: {result.output()}" ) return True def read_text(self, path: str) -> str | None: result = self._ssh(self._sudo(f"cat {shlex.quote(path)}")) if not result.ok: if "No such file" in result.stderr or "cannot open" in result.stderr: return None raise ProxdomainError(f"cannot read {path} on {self.host}: {result.output()}") return result.stdout def remove(self, path: str) -> bool: if not self.exists(path): return False result = self._ssh(self._sudo(f"rm -f {shlex.quote(path)}")) if not result.ok: raise ProxdomainError(f"cannot remove {path} on {self.host}: {result.output()}") return True def exists(self, path: str) -> bool: result = self._ssh(self._sudo(f"test -e {shlex.quote(path)}")) return result.ok def mkdir(self, path: str) -> None: result = self._ssh(self._sudo(f"mkdir -p {shlex.quote(path)}")) if not result.ok: raise ProxdomainError( f"cannot create directory {path} on {self.host}: {result.output()}" ) def describe(self) -> str: return f"ssh://{self.host}" def _sudo(self, command: str) -> str: return f"{self.sudo} {command}" if self.sudo else command def build_runner(config) -> Runner: # config: WebServerConfig if config.mode == "ssh": return SSHRunner( config.ssh_host, port=config.ssh_port, identity_file=config.ssh_identity_file, ssh_options=config.ssh_options, sudo=config.sudo, ) return LocalRunner() def _posix_dirname(path: str) -> str: trimmed = path.rstrip("/") if "/" not in trimmed: return "." return trimmed.rsplit("/", 1)[0] or "/" class _suppress_errors: def __enter__(self) -> None: return None def __exit__(self, *exc_info: object) -> bool: return True