"""Own helper commands until their groups are stopped and their leaders reaped. The control byte after the request, or stdin EOF, cancels the helper. Command creation and cancellation share a lock. Leaders remain unreaped until group cleanup so their process group IDs cannot be reused while we signal them. """ from __future__ import annotations import ctypes import errno import os import signal import struct import subprocess import sys import threading import time from typing import IO import albedo_proc _DARWIN_P_PID = 1 _DARWIN_WNOHANG = 0x1 _DARWIN_WEXITED = 0x4 _DARWIN_WNOWAIT = 0x20 _DARWIN_SIGINFO_BYTES = 104 _DARWIN_SI_PID_OFFSET = 12 def _darwin_libc() -> ctypes.CDLL | None: if sys.platform != "darwin": return None libc = ctypes.CDLL(None, use_errno=True) libc.waitid.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.c_void_p, ctypes.c_int] libc.waitid.restype = ctypes.c_int return libc _DARWIN_LIBC = _darwin_libc() def _exited_unreaped(pid: int) -> bool: waitid = getattr(os, "waitid", None) if waitid is not None: try: return ( waitid( getattr(os, "P_PID"), pid, getattr(os, "WEXITED") | getattr(os, "WNOWAIT") | getattr(os, "WNOHANG"), ) is not None ) except ChildProcessError: return True if _DARWIN_LIBC is None: raise RuntimeError("os.waitid is unavailable on this platform") info = ctypes.create_string_buffer(_DARWIN_SIGINFO_BYTES) ctypes.set_errno(0) if ( _DARWIN_LIBC.waitid( _DARWIN_P_PID, pid, info, _DARWIN_WEXITED | _DARWIN_WNOWAIT | _DARWIN_WNOHANG, ) == -1 ): err = ctypes.get_errno() if err == errno.ECHILD: return True if err == errno.EINTR: return False raise OSError(err, os.strerror(err)) return struct.unpack_from("=i", info.raw, _DARWIN_SI_PID_OFFSET)[0] == pid def read_request() -> bytes: """Read exactly one line without buffering the subsequent control byte.""" data = bytearray() while byte := os.read(sys.stdin.fileno(), 1): if byte == b"\n": break data.extend(byte) return bytes(data) class Commands: def __init__(self) -> None: self._lock = threading.Lock() self._processes: set[subprocess.Popen[bytes]] = set() self._cancelled = False threading.Thread(target=self._watch, daemon=True).start() def _watch(self) -> None: os.read(sys.stdin.fileno(), 1) try: self.close() except OSError as error: print(f"helper cleanup failed: {error}", flush=True) os._exit(125) os._exit(124) def start( self, command: str, *, cwd: str | None, stdin: IO[bytes], stdout: IO[bytes], stderr: IO[bytes] | int, ) -> subprocess.Popen[bytes]: with self._lock: if self._cancelled: raise RuntimeError("helper cancelled") process = subprocess.Popen( command, shell=True, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr, start_new_session=True, ) self._processes.add(process) return process def wait(self, process: subprocess.Popen[bytes], timeout: float) -> None: deadline = time.monotonic() + timeout while True: # WNOWAIT pins the leader even after it exits, including while # descendants remain in its group. Popen.wait would reap it. if _exited_unreaped(process.pid): return if time.monotonic() >= deadline: raise subprocess.TimeoutExpired(process.args, timeout) time.sleep(0.01) def finish(self, process: subprocess.Popen[bytes]) -> None: with self._lock: if process not in self._processes: return stop(process.pid) self._settle(process) self._processes.remove(process) def close(self) -> None: with self._lock: self._cancelled = True for process in self._processes: stop(process.pid) for process in self._processes: self._settle(process) self._processes.clear() @staticmethod def _settle(process: subprocess.Popen[bytes]) -> None: await_stopped(process.pid) process.wait(timeout=2) def stop(group: int) -> None: """Kill a command's group. A group that is already gone needs nothing.""" try: os.killpg(group, signal.SIGKILL) except ProcessLookupError: pass except PermissionError: # Darwin returns EPERM when only the un-reaped zombie leader remains. if sys.platform != "darwin" or albedo_proc.live_members(group) != []: raise def await_stopped(group: int) -> None: """Wait until a killed group has no live member. Where the process table cannot be read there is nothing to wait on, and the kill already sent is all this can do. """ deadline = time.monotonic() + 2 while albedo_proc.live_members(group): if time.monotonic() >= deadline: raise OSError(f"command group {group} did not stop") time.sleep(0.01)