"""Bounded binary stdout/stderr journal for one launchd-owned child process. The parent drains a pipe and owns rotation; no copy/truncate race with a writer. It does not change the child's arguments, environment, credentials or network. """ from __future__ import annotations import argparse import fcntl import os import selectors import signal import stat import subprocess import time from pathlib import Path MAX_BYTES = 8 * 1024**2 BACKUPS = 4 class Journal: def __init__(self, path: Path, *, max_bytes=MAX_BYTES, backups=BACKUPS): if max_bytes < 1 or not 1 <= backups <= 20: raise ValueError("Invalid journal limits") self.path = path.absolute() self.max_bytes, self.backups = max_bytes, backups self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) if self.path.parent.resolve() != self.path.parent: raise ValueError("Journal parent is not canonical") self.lock = self._open(self.path.with_name(self.path.name + ".lock")) try: fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) self.fd = self._open(self.path) except BaseException: os.close(self.lock) raise @staticmethod def _open(path): fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW, 0o600) info = os.fstat(fd) if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid(): os.close(fd) raise ValueError("Journal must be an owned, unlinked regular file") os.fchmod(fd, 0o600) return fd def _rotate(self): # Validate every managed destination before changing the rotation set. paths = [self.path] + [Path(f"{self.path}.{i}") for i in range(1, self.backups + 1)] for p in paths: if p.exists() or p.is_symlink(): s = p.lstat() if not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_uid != os.getuid(): raise ValueError("Unsafe journal rotation target") named = self.path.stat() opened = os.fstat(self.fd) if (named.st_dev, named.st_ino) != (opened.st_dev, opened.st_ino): raise ValueError("Journal identity changed") os.close(self.fd) self.fd = -1 try: paths[-1].unlink(missing_ok=True) for index in range(self.backups - 1, -1, -1): if paths[index].exists(): os.replace(paths[index], paths[index + 1]) finally: self.fd = self._open(self.path) def write(self, payload: bytes): view = memoryview(payload) while view: space = self.max_bytes - os.fstat(self.fd).st_size if space <= 0: self._rotate() space = self.max_bytes written = os.write(self.fd, view[:space]) if written <= 0: raise OSError("Journal write made no progress") view = view[written:] def close(self): if self.fd >= 0: os.close(self.fd) self.fd = -1 if self.lock >= 0: os.close(self.lock) self.lock = -1 def supervise(command, path: Path, *, max_bytes=MAX_BYTES, backups=BACKUPS): journal = Journal(path, max_bytes=max_bytes, backups=backups) child = None previous = {} deadline = None dropped = 0 try: child = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) assert child.stdout is not None def stop(signum, _frame): nonlocal deadline if child.poll() is None: child.send_signal(signum) deadline = time.monotonic() + 12 for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): previous[signum] = signal.signal(signum, stop) with selectors.DefaultSelector() as selector: selector.register(child.stdout, selectors.EVENT_READ) exited = None eof = False while True: if deadline is not None and time.monotonic() >= deadline and child.poll() is None: child.kill() ready = selector.select(0.25) if ready: chunk = os.read(child.stdout.fileno(), 65536) if not chunk: selector.unregister(child.stdout) eof = True try: if dropped: journal.write( f"\n[journal recovered; dropped {dropped} bytes]\n".encode() ) dropped = 0 journal.write(chunk) except (OSError, ValueError): # A full/unavailable disk must not deadlock the operator service. # The loss counter is bounded state, not an in-memory log backlog. dropped = min(2**63 - 1, dropped + len(chunk)) if child.poll() is not None: if eof: break exited = exited or time.monotonic() if time.monotonic() - exited >= 2: break # A descendant must not keep a dead service's pipe alive forever. child.stdout.close() code = child.wait() return code if code >= 0 else 128 - code finally: if child is not None and child.poll() is None: child.terminate() try: child.wait(timeout=12) except subprocess.TimeoutExpired: child.kill() child.wait() for signum, handler in previous.items(): signal.signal(signum, handler) journal.close() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--log", type=Path, required=True) parser.add_argument("command", nargs=argparse.REMAINDER) args = parser.parse_args() command = args.command[1:] if args.command[:1] == ["--"] else args.command if not command: parser.error("child command is required") return supervise(command, args.log) if __name__ == "__main__": raise SystemExit(main())