""" Where the maintainer's commands run. The daemon lives on the core stack host and normally runs everything there (a `local` host). The other kinds let it work on a machine it is not on. A Host runs a shell script on one of them and reads or writes a file there, so the daemon's probes, its git bookkeeping and the agent's tools all go through one place. Kinds, from config.json -> hosts: local bash on this machine ssh bash on a remote machine, over one multiplexed SSH connection powershell Windows PowerShell through WSL interop (shell only, no file tools) Stdlib only: maintainer.py imports this for its health checks. """ import base64 import os import shlex import signal import subprocess import threading # Enough for `docker ps` and a page of logs; the agent is told to narrow a # query rather than page through the rest. OUTPUT_LIMIT = 24000 class Host: def __init__(self, name, spec, state_dir): self.name = name self.spec = spec self.about = spec.get("about", "") if spec.get("ssh"): self.kind = "ssh" elif spec.get("shell") == "powershell": self.kind = "powershell" else: self.kind = "local" self.target = spec.get("ssh", "") self.powershell = spec.get("powershell_bin", "powershell.exe") # Exported before every command, e.g. the bot's git identity on core. self.env = dict(spec.get("env") or {}) self.state_dir = state_dir def __repr__(self): return f"Host({self.name}, {self.kind}{', ' + self.target if self.target else ''})" # -- running commands --------------------------------------------------- # def argv(self, script, cwd=None, env=None): """The local argv that runs `script` on this host. `env` is exported on an ssh host; locally the caller puts it in the process environment.""" if self.kind == "powershell": if cwd: script = f"Set-Location -LiteralPath '{cwd}'\n{script}" encoded = base64.b64encode(script.encode("utf-16-le")).decode() return [self.powershell, "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded] prefix = f"cd {shlex.quote(cwd)} && " if cwd else "" if self.kind == "local": return ["bash", "-lc", prefix + script] exports = "".join(f"export {k}={shlex.quote(str(v))}; " for k, v in {**self.env, **(env or {})}.items()) return ["ssh", *self.ssh_options(), self.target, "bash -lc " + shlex.quote(exports + prefix + script)] def ssh_options(self): opts = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=20", "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=4"] if os.name != "nt" and self.spec.get("multiplex", True): # One TCP connection for the many short commands of an agent run. os.makedirs(self.state_dir, exist_ok=True) opts += ["-o", "ControlMaster=auto", "-o", f"ControlPath={self.state_dir}/ssh-%C", "-o", "ControlPersist=600"] return opts + list(self.spec.get("ssh_options") or []) def run(self, script, timeout=300, input=None, cwd=None, procs=None, env=None): """Run a script; returns a CompletedProcess. A timeout kills the whole process group and returns code 124. `procs` (a ProcessSet) lets another thread kill the command, as `cancel` does.""" popen = dict(stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if os.name == "nt": popen["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP else: popen["start_new_session"] = True if self.kind == "local": popen["env"] = {**os.environ, **self.env, **(env or {})} argv = self.argv(script, cwd, env) try: proc = subprocess.Popen(argv, **popen) except OSError as e: return subprocess.CompletedProcess(argv, 127, "", f"cannot start {argv[0]}: {e}") if procs is not None: procs.add(proc) try: out, err = proc.communicate( input=input.encode() if isinstance(input, str) else input, timeout=timeout) code = proc.returncode except subprocess.TimeoutExpired: kill_tree(proc) out, err = proc.communicate() code = 124 err = (err or b"") + f"\n(timed out after {timeout}s and was killed)".encode() finally: if procs is not None: procs.discard(proc) return subprocess.CompletedProcess(argv, code, decode(out), decode(err)) def check(self, script, timeout=120, **kw): """Run and return stdout; raise RuntimeError on a non-zero exit.""" res = self.run(script, timeout=timeout, **kw) if res.returncode != 0: raise RuntimeError(f"{self.name}: exit {res.returncode}: " f"{(res.stderr or res.stdout).strip()[:400]}") return res.stdout # -- files -------------------------------------------------------------- # # Written in place (truncate and write), never replaced by a rename: core's # configs are bind-mounted single files, and a container keeps the old # inode of a file that was renamed over. def read_text(self, path, timeout=60): if self.kind == "local": with open(path, encoding="utf-8", errors="replace") as fh: return fh.read() if self.kind == "powershell": raise RuntimeError("file tools do not work on a powershell host; " "read Windows files from `local` under /mnt/c") return self.check(f"cat -- {shlex.quote(path)}", timeout=timeout) def write_text(self, path, content, timeout=60): if self.kind == "local": os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, "w", encoding="utf-8") as fh: fh.write(content) return if self.kind == "powershell": raise RuntimeError("file tools do not work on a powershell host") q = shlex.quote(path) self.check(f"mkdir -p -- \"$(dirname -- {q})\" && cat > {q}", timeout=timeout, input=content) def exists(self, path): if self.kind == "local": return os.path.exists(path) return self.run(f"test -e {shlex.quote(path)}", timeout=60).returncode == 0 class ProcessSet: """The processes a run has in flight, so `cancel` can stop them.""" def __init__(self): self._procs = set() self._lock = threading.Lock() def add(self, proc): with self._lock: self._procs.add(proc) def discard(self, proc): with self._lock: self._procs.discard(proc) def kill_all(self): with self._lock: procs = list(self._procs) for proc in procs: kill_tree(proc) def kill_tree(proc, grace=10): """Stop a command and everything it started. For an ssh host this kills the local ssh client; the remote command gets SIGHUP when it goes.""" if proc.poll() is not None: return try: if os.name == "nt": subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True) return os.killpg(proc.pid, signal.SIGTERM) except (ProcessLookupError, PermissionError): return try: proc.wait(timeout=grace) except subprocess.TimeoutExpired: try: os.killpg(proc.pid, signal.SIGKILL) except ProcessLookupError: pass def decode(data): return (data or b"").decode("utf-8", errors="replace") def clip(text, limit=OUTPUT_LIMIT): """Head and tail of a long output: errors are usually at the end.""" if len(text) <= limit: return text head = limit // 3 tail = limit - head return (f"{text[:head]}\n\n… [{len(text) - limit} characters cut; narrow the " f"command to see them] …\n\n{text[-tail:]}") def windows_host_ip(): """The Windows side of WSL's NAT network: the default gateway.""" try: with open("/proc/net/route") as fh: for line in fh.readlines()[1:]: parts = line.split() if len(parts) > 2 and parts[1] == "00000000": raw = bytes.fromhex(parts[2]) return ".".join(str(b) for b in reversed(raw)) except OSError: pass return "localhost" def load_hosts(cfg): state_dir = os.path.dirname(cfg["state_file"]) return {name: Host(name, spec, state_dir) for name, spec in cfg["hosts"].items()}