829 lines
29 KiB
Python
829 lines
29 KiB
Python
"""Warm pre-forked Python zygote worker pool for plugin script execution.
|
|
|
|
Every plugin action normally runs ``subprocess.run([sys.executable, script], ...)``,
|
|
paying ~40-80 ms of Python interpreter startup and stdlib import overhead per call.
|
|
When enabled on POSIX, this module lazily maintains a single strictly stripped-env
|
|
zygote helper that pre-imports common stdlib modules, listens on a ``0600`` Unix
|
|
domain socket inside a ``0700`` temp dir, and handles concurrent calls in a
|
|
single-threaded ``selectors`` loop that ``os.fork()``s a clean child per request.
|
|
|
|
Security invariants:
|
|
* Host secrets (``ANTHROPIC_API_KEY``, ``SIDECAR_TOKEN``, etc.) NEVER enter the
|
|
zygote environment or memory; it spawns with ``-I`` and ``_SAFE_ENV_KEYS`` only.
|
|
* Each forked child calls ``os.setsid()``, closes all zygote/peer fds, replaces
|
|
``os.environ`` with the request's stripped ``env``, ``chdir``s to ``cwd``, puts
|
|
``cwd`` at ``sys.path[0]`` (with zero hub backend dirs on ``sys.path``), and
|
|
runs ``runpy.run_path``.
|
|
* On Linux, the zygote arms ``PR_SET_PDEATHSIG(SIGTERM)`` so it cannot orphan if
|
|
the hub process dies unexpectedly.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import atexit
|
|
import base64
|
|
import ctypes
|
|
from dataclasses import dataclass
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import runpy
|
|
import selectors
|
|
import shutil
|
|
import signal
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import traceback
|
|
from typing import Any
|
|
|
|
MAX_OUTPUT_BYTES = 16 * 1024 * 1024
|
|
MAX_FRAME_BYTES = 32 * 1024 * 1024
|
|
_SAFE_ENV_KEYS = ("PATH", "LANG", "LC_ALL", "TZ", "HOME", "TMPDIR", "PYTHONUNBUFFERED")
|
|
_HEADER = struct.Struct("!I")
|
|
_PREIMPORTS = (
|
|
"json", "os", "sys", "re", "pathlib", "urllib.request", "urllib.error",
|
|
"urllib.parse", "datetime", "sqlite3", "hashlib", "time", "math",
|
|
"collections", "shutil", "subprocess", "tempfile", "base64", "hmac",
|
|
"http.client", "runpy", "ssl", "io", "functools", "itertools",
|
|
"traceback", "ipaddress", "csv",
|
|
)
|
|
|
|
_THIS_FILE = os.path.abspath(__file__)
|
|
_THIS_DIR = os.path.dirname(_THIS_FILE)
|
|
_BACKEND_DIR = os.path.dirname(_THIS_DIR)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ZygoteResult:
|
|
"""Result mirroring ``subprocess.CompletedProcess`` attributes."""
|
|
|
|
returncode: int
|
|
stdout: bytes
|
|
stderr: bytes
|
|
|
|
|
|
@dataclass
|
|
class _ZygoteState:
|
|
proc: subprocess.Popen[bytes] | None = None
|
|
sock_dir: str | None = None
|
|
sock_path: str | None = None
|
|
owner_pid: int | None = None
|
|
atexit_registered: bool = False
|
|
zygote_calls: int = 0
|
|
fallback_calls: int = 0
|
|
restarts: int = 0
|
|
|
|
|
|
_lock = threading.Lock()
|
|
_state = _ZygoteState()
|
|
|
|
|
|
def is_enabled() -> bool:
|
|
"""Return True when the zygote pool can and should be used."""
|
|
return (
|
|
os.name == "posix"
|
|
and hasattr(os, "fork")
|
|
and os.environ.get("AIA_PLUGIN_ZYGOTE") != "0"
|
|
)
|
|
|
|
|
|
def _make_sock_dir() -> tuple[str, str]:
|
|
sock_dir = tempfile.mkdtemp(prefix="aia-zygote-")
|
|
sock_path = os.path.join(sock_dir, "z.sock")
|
|
# AF_UNIX sun_path is capped at 108 bytes on Linux; fall back to /tmp if TMPDIR is deep.
|
|
if len(sock_path.encode("utf-8")) > 100:
|
|
shutil.rmtree(sock_dir, ignore_errors=True)
|
|
sock_dir = tempfile.mkdtemp(prefix="aiaz-", dir="/tmp")
|
|
sock_path = os.path.join(sock_dir, "z.sock")
|
|
os.chmod(sock_dir, 0o700)
|
|
return sock_dir, sock_path
|
|
|
|
|
|
def _cleanup_proc_and_dir(proc: subprocess.Popen[bytes] | None, sock_dir: str | None) -> None:
|
|
if proc is not None and proc.poll() is None:
|
|
for fn in (proc.terminate, proc.kill):
|
|
try:
|
|
fn()
|
|
proc.wait(timeout=1.0)
|
|
break
|
|
except Exception:
|
|
pass
|
|
elif proc is not None:
|
|
try:
|
|
proc.wait(timeout=0.1)
|
|
except Exception:
|
|
pass
|
|
if sock_dir:
|
|
shutil.rmtree(sock_dir, ignore_errors=True)
|
|
|
|
|
|
def _send_frame(sock: socket.socket, payload: dict[str, Any]) -> None:
|
|
data = json.dumps(payload).encode("utf-8")
|
|
sock.sendall(_HEADER.pack(len(data)) + data)
|
|
|
|
|
|
def _recv_exact(sock: socket.socket, size: int) -> bytes:
|
|
buf = bytearray()
|
|
while len(buf) < size:
|
|
chunk = sock.recv(size - len(buf))
|
|
if not chunk:
|
|
raise EOFError("zygote socket closed")
|
|
buf.extend(chunk)
|
|
return bytes(buf)
|
|
|
|
|
|
def _recv_frame(sock: socket.socket) -> dict[str, Any]:
|
|
(length,) = _HEADER.unpack(_recv_exact(sock, _HEADER.size))
|
|
if length > MAX_FRAME_BYTES:
|
|
raise ValueError(f"zygote response frame too large: {length}")
|
|
obj = json.loads(_recv_exact(sock, length).decode("utf-8"))
|
|
if not isinstance(obj, dict):
|
|
raise ValueError("invalid zygote response payload")
|
|
return obj
|
|
|
|
|
|
def _spawn_zygote() -> tuple[subprocess.Popen[bytes], str, str] | None:
|
|
safe_env = {k: os.environ[k] for k in _SAFE_ENV_KEYS if k in os.environ}
|
|
sock_dir, sock_path = _make_sock_dir()
|
|
ready_r, ready_w = os.pipe()
|
|
proc: subprocess.Popen[bytes] | None = None
|
|
try:
|
|
cmd = [sys.executable, "-I", _THIS_FILE, sock_path,
|
|
"--parent-pid", str(os.getpid()), "--ready-fd", str(ready_w)]
|
|
proc = subprocess.Popen(
|
|
cmd, env=safe_env, cwd=sock_dir, stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, pass_fds=(ready_w,),
|
|
)
|
|
os.close(ready_w)
|
|
ready_w = -1
|
|
sel = selectors.DefaultSelector()
|
|
try:
|
|
sel.register(ready_r, selectors.EVENT_READ)
|
|
events = sel.select(timeout=10.0)
|
|
finally:
|
|
sel.close()
|
|
if not events or os.read(ready_r, 1) != b"1" or proc.poll() is not None:
|
|
_cleanup_proc_and_dir(proc, sock_dir)
|
|
return None
|
|
return proc, sock_dir, sock_path
|
|
except Exception:
|
|
_cleanup_proc_and_dir(proc, sock_dir)
|
|
return None
|
|
finally:
|
|
for fd in (ready_w, ready_r):
|
|
if fd >= 0:
|
|
try:
|
|
os.close(fd)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _ensure_started() -> tuple[subprocess.Popen[bytes], str] | None:
|
|
with _lock:
|
|
pid = os.getpid()
|
|
if _state.owner_pid is not None and _state.owner_pid != pid:
|
|
# Forked child of hub: drop inherited handle without touching parent's zygote.
|
|
_state.proc = _state.sock_dir = _state.sock_path = _state.owner_pid = None
|
|
if _state.proc is not None and _state.proc.poll() is None and _state.sock_path:
|
|
return _state.proc, _state.sock_path
|
|
if _state.proc is not None or _state.sock_dir is not None:
|
|
_cleanup_proc_and_dir(_state.proc, _state.sock_dir)
|
|
_state.proc = _state.sock_dir = _state.sock_path = None
|
|
_state.restarts += 1
|
|
started = _spawn_zygote()
|
|
if started is None:
|
|
return None
|
|
_state.proc, _state.sock_dir, _state.sock_path = started
|
|
_state.owner_pid = pid
|
|
if not _state.atexit_registered:
|
|
atexit.register(shutdown)
|
|
_state.atexit_registered = True
|
|
return _state.proc, _state.sock_path
|
|
|
|
|
|
def _reset_broken(expected_proc: subprocess.Popen[bytes]) -> None:
|
|
with _lock:
|
|
if _state.proc is not expected_proc:
|
|
return
|
|
proc, sock_dir = _state.proc, _state.sock_dir
|
|
_state.proc = _state.sock_dir = _state.sock_path = None
|
|
_cleanup_proc_and_dir(proc, sock_dir)
|
|
|
|
|
|
def _rpc_run(
|
|
sock_path: str, *, script: str, stdin_bytes: bytes, env: dict[str, str],
|
|
cwd: str, timeout_sec: float,
|
|
) -> dict[str, Any]:
|
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
try:
|
|
sock.settimeout(max(timeout_sec + 5.0, 5.0))
|
|
sock.connect(sock_path)
|
|
_send_frame(sock, {
|
|
"cmd": "run", "script": script, "cwd": cwd, "env": env,
|
|
"stdin_b64": base64.b64encode(stdin_bytes).decode("ascii"),
|
|
"timeout_sec": timeout_sec,
|
|
})
|
|
return _recv_frame(sock)
|
|
finally:
|
|
sock.close()
|
|
|
|
|
|
def run_python(
|
|
script_path: pathlib.Path,
|
|
*,
|
|
stdin_bytes: bytes,
|
|
env: dict[str, str],
|
|
cwd: str,
|
|
timeout_sec: int | float,
|
|
) -> ZygoteResult | None:
|
|
"""Run ``script_path`` in a forked zygote child.
|
|
|
|
Returns ``None`` when disabled or unavailable so callers can transparently
|
|
fall back to ``subprocess.run``. Raises ``subprocess.TimeoutExpired`` on timeout.
|
|
"""
|
|
if not is_enabled():
|
|
with _lock:
|
|
_state.fallback_calls += 1
|
|
return None
|
|
|
|
script_str = os.path.abspath(os.fspath(script_path))
|
|
cwd_str = os.path.abspath(os.fspath(cwd))
|
|
timeout_val = max(float(timeout_sec), 0.001)
|
|
deadline = time.monotonic() + timeout_val
|
|
|
|
for attempt in range(2):
|
|
started = _ensure_started()
|
|
if started is None:
|
|
with _lock:
|
|
_state.fallback_calls += 1
|
|
return None
|
|
proc, sock_path = started
|
|
call_timeout = timeout_val if attempt == 0 else max(
|
|
min(timeout_val, 0.1), deadline - time.monotonic(),
|
|
)
|
|
try:
|
|
resp = _rpc_run(
|
|
sock_path, script=script_str, stdin_bytes=stdin_bytes,
|
|
env=env, cwd=cwd_str, timeout_sec=call_timeout,
|
|
)
|
|
except (OSError, ValueError, EOFError):
|
|
_reset_broken(proc)
|
|
continue
|
|
|
|
stdout = base64.b64decode(resp.get("stdout_b64") or "")
|
|
stderr = base64.b64decode(resp.get("stderr_b64") or "")
|
|
with _lock:
|
|
_state.zygote_calls += 1
|
|
if resp.get("timed_out"):
|
|
raise subprocess.TimeoutExpired(
|
|
cmd=[sys.executable, script_str], timeout=timeout_sec,
|
|
output=stdout, stderr=stderr,
|
|
)
|
|
return ZygoteResult(returncode=int(resp.get("returncode", 1)), stdout=stdout, stderr=stderr)
|
|
|
|
with _lock:
|
|
_state.fallback_calls += 1
|
|
return None
|
|
|
|
|
|
def shutdown() -> None:
|
|
"""Cleanly stop the zygote helper and remove its socket directory."""
|
|
with _lock:
|
|
if _state.owner_pid is not None and _state.owner_pid != os.getpid():
|
|
return
|
|
proc, sock_dir, sock_path = _state.proc, _state.sock_dir, _state.sock_path
|
|
_state.proc = _state.sock_dir = _state.sock_path = None
|
|
|
|
if proc is not None and proc.poll() is None and sock_path:
|
|
try:
|
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
try:
|
|
sock.settimeout(0.5)
|
|
sock.connect(sock_path)
|
|
_send_frame(sock, {"cmd": "shutdown"})
|
|
_recv_frame(sock)
|
|
finally:
|
|
sock.close()
|
|
except OSError:
|
|
pass
|
|
_cleanup_proc_and_dir(proc, sock_dir)
|
|
|
|
|
|
def stats() -> dict[str, Any]:
|
|
"""Return observability metrics for the zygote worker pool."""
|
|
with _lock:
|
|
proc = _state.proc
|
|
alive = _state.owner_pid == os.getpid() and proc is not None and proc.poll() is None
|
|
return {
|
|
"alive": alive,
|
|
"pid": proc.pid if alive and proc is not None else None,
|
|
"zygote_calls": _state.zygote_calls,
|
|
"fallback_calls": _state.fallback_calls,
|
|
"restarts": _state.restarts,
|
|
}
|
|
|
|
|
|
# ── Zygote worker process ────────────────────────────────────────────────────
|
|
|
|
@dataclass
|
|
class _ClientConn:
|
|
conn: socket.socket
|
|
in_buf: bytearray
|
|
req_len: int | None = None
|
|
out_buf: bytearray | None = None
|
|
out_pos: int = 0
|
|
job: _ChildJob | None = None
|
|
|
|
|
|
@dataclass
|
|
class _ChildJob:
|
|
client: _ClientConn
|
|
pid: int
|
|
deadline: float
|
|
stdin_data: bytes
|
|
stdin_pos: int
|
|
stdin_w: int | None
|
|
stdout_r: int | None
|
|
stderr_r: int | None
|
|
pidfd: int | None
|
|
stdout_buf: bytearray
|
|
stderr_buf: bytearray
|
|
exited: bool = False
|
|
returncode: int | None = None
|
|
|
|
|
|
def _arm_pdeathsig(parent_pid: int) -> None:
|
|
if not sys.platform.startswith("linux"):
|
|
return
|
|
try:
|
|
libc = ctypes.CDLL(None, use_errno=True)
|
|
prctl = libc.prctl
|
|
prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]
|
|
prctl.restype = ctypes.c_int
|
|
prctl(1, signal.SIGTERM, 0, 0, 0) # PR_SET_PDEATHSIG = 1
|
|
except (OSError, AttributeError):
|
|
return
|
|
if os.getppid() != parent_pid:
|
|
os._exit(0)
|
|
|
|
|
|
def _scrub_sys_path() -> None:
|
|
blocked = {_THIS_DIR, _BACKEND_DIR}
|
|
sys.path[:] = [p for p in sys.path if p not in ("", ".") and os.path.abspath(p) not in blocked]
|
|
|
|
|
|
def _close_fd_watched(sel: selectors.BaseSelector, fd: int | None) -> None:
|
|
if fd is None:
|
|
return
|
|
try:
|
|
sel.unregister(fd)
|
|
except (KeyError, ValueError, OSError):
|
|
pass
|
|
try:
|
|
os.close(fd)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _open_pidfd(pid: int) -> int | None:
|
|
if not hasattr(os, "pidfd_open"):
|
|
return None
|
|
try:
|
|
return os.pidfd_open(pid)
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def _run_child_script(
|
|
*, script_path: str, cwd: str, req_env: dict[str, str],
|
|
stdin_r: int, stdout_w: int, stderr_w: int, close_fds: set[int],
|
|
) -> None:
|
|
signal.set_wakeup_fd(-1)
|
|
signal.signal(signal.SIGTERM, signal.SIG_DFL)
|
|
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
|
os.setsid()
|
|
|
|
for src, target in ((stdin_r, 0), (stdout_w, 1), (stderr_w, 2)):
|
|
if src != target:
|
|
os.dup2(src, target)
|
|
for fd in close_fds:
|
|
if fd > 2:
|
|
try:
|
|
os.close(fd)
|
|
except OSError:
|
|
pass
|
|
|
|
os.environ.clear()
|
|
os.environ.update(req_env)
|
|
tempfile.tempdir = None
|
|
if hasattr(time, "tzset") and "TZ" in req_env:
|
|
try:
|
|
time.tzset()
|
|
except Exception:
|
|
pass
|
|
if req_env.get("PYTHONUNBUFFERED"):
|
|
for stream in (sys.stdout, sys.stderr):
|
|
if hasattr(stream, "reconfigure"):
|
|
try:
|
|
stream.reconfigure(write_through=True)
|
|
except Exception:
|
|
pass
|
|
|
|
rc = 1
|
|
try:
|
|
script_abs = os.path.abspath(script_path)
|
|
cwd_abs = os.path.abspath(cwd)
|
|
os.chdir(cwd_abs)
|
|
script_dir = os.path.dirname(script_abs)
|
|
_scrub_sys_path()
|
|
if script_dir and script_dir != cwd_abs and script_dir not in sys.path:
|
|
sys.path.insert(0, script_dir)
|
|
if cwd_abs in sys.path:
|
|
sys.path.remove(cwd_abs)
|
|
sys.path.insert(0, cwd_abs)
|
|
sys.argv = [script_abs]
|
|
runpy.run_path(script_abs, run_name="__main__")
|
|
rc = 0
|
|
except SystemExit as exc:
|
|
code = exc.code
|
|
if code is None:
|
|
rc = 0
|
|
elif isinstance(code, int):
|
|
rc = code
|
|
else:
|
|
try:
|
|
print(code, file=sys.stderr)
|
|
except Exception:
|
|
pass
|
|
rc = 1
|
|
except BaseException:
|
|
try:
|
|
traceback.print_exc(file=sys.stderr)
|
|
except Exception:
|
|
pass
|
|
rc = 1
|
|
finally:
|
|
for stream in (sys.stdout, sys.stderr):
|
|
try:
|
|
stream.flush()
|
|
except Exception:
|
|
pass
|
|
os._exit(rc)
|
|
|
|
|
|
def _drain_pipe(fd: int, buf: bytearray) -> bool:
|
|
"""Read up to 16 chunks from non-blocking ``fd``; return True on EOF."""
|
|
for _ in range(16):
|
|
try:
|
|
data = os.read(fd, 65536)
|
|
except BlockingIOError:
|
|
return False
|
|
except OSError:
|
|
return True
|
|
if not data:
|
|
return True
|
|
room = MAX_OUTPUT_BYTES - len(buf)
|
|
if room > 0:
|
|
buf.extend(data[:room])
|
|
return False
|
|
|
|
|
|
def _reap_nonblocking(job: _ChildJob) -> None:
|
|
if job.exited:
|
|
return
|
|
try:
|
|
wpid, status = os.waitpid(job.pid, os.WNOHANG)
|
|
if wpid == job.pid:
|
|
job.exited = True
|
|
job.returncode = os.waitstatus_to_exitcode(status)
|
|
except ChildProcessError:
|
|
job.exited = True
|
|
job.returncode = 0
|
|
|
|
|
|
class _ZygoteServer:
|
|
"""Single-threaded selector loop multiplexing Unix socket RPCs and forked jobs."""
|
|
|
|
def __init__(self, sock_path: str, ready_fd: int) -> None:
|
|
self.sock_path = sock_path
|
|
if os.path.exists(sock_path):
|
|
os.unlink(sock_path)
|
|
self.server_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
self.server_sock.bind(sock_path)
|
|
os.chmod(sock_path, 0o600)
|
|
self.server_sock.setblocking(False)
|
|
self.server_sock.listen(128)
|
|
|
|
self.sig_r, self.sig_w = os.pipe()
|
|
os.set_blocking(self.sig_r, False)
|
|
os.set_blocking(self.sig_w, False)
|
|
signal.set_wakeup_fd(self.sig_w, warn_on_full_buffer=False)
|
|
signal.signal(signal.SIGTERM, lambda _s, _f: None)
|
|
signal.signal(signal.SIGINT, lambda _s, _f: None)
|
|
os.write(ready_fd, b"1")
|
|
os.close(ready_fd)
|
|
|
|
self.sel = selectors.DefaultSelector()
|
|
self.sel.register(self.server_sock, selectors.EVENT_READ, ("accept", None))
|
|
self.sel.register(self.sig_r, selectors.EVENT_READ, ("signal", None))
|
|
self.clients: dict[int, _ClientConn] = {}
|
|
self.jobs: dict[int, _ChildJob] = {}
|
|
self.stopping = False
|
|
self.shutdown_client: _ClientConn | None = None
|
|
|
|
def _collect_open_fds(self) -> set[int]:
|
|
fds = {self.server_sock.fileno(), self.sel.fileno(), self.sig_r, self.sig_w}
|
|
fds.update(c.conn.fileno() for c in self.clients.values())
|
|
for j in self.jobs.values():
|
|
fds.update(fd for fd in (j.stdin_w, j.stdout_r, j.stderr_r, j.pidfd) if fd is not None)
|
|
return fds
|
|
|
|
def _drop_client(self, client: _ClientConn) -> None:
|
|
self.clients.pop(client.conn.fileno(), None)
|
|
try:
|
|
self.sel.unregister(client.conn)
|
|
except (KeyError, ValueError, OSError):
|
|
pass
|
|
try:
|
|
client.conn.close()
|
|
except OSError:
|
|
pass
|
|
|
|
def _kill_and_reap(self, job: _ChildJob) -> None:
|
|
for fn in (os.killpg, os.kill):
|
|
try:
|
|
fn(job.pid, signal.SIGKILL)
|
|
except ProcessLookupError:
|
|
pass
|
|
for fd in (job.stdin_w, job.stdout_r, job.stderr_r, job.pidfd):
|
|
_close_fd_watched(self.sel, fd)
|
|
job.stdin_w = job.stdout_r = job.stderr_r = job.pidfd = None
|
|
if not job.exited:
|
|
try:
|
|
_, status = os.waitpid(job.pid, 0)
|
|
job.exited = True
|
|
job.returncode = os.waitstatus_to_exitcode(status)
|
|
except ChildProcessError:
|
|
job.exited = True
|
|
job.returncode = -signal.SIGKILL
|
|
self.jobs.pop(job.pid, None)
|
|
|
|
def _enqueue(self, client: _ClientConn, resp: dict[str, Any]) -> None:
|
|
data = json.dumps(resp).encode("utf-8")
|
|
client.out_buf = bytearray(_HEADER.pack(len(data)) + data)
|
|
client.out_pos = 0
|
|
try:
|
|
self.sel.modify(client.conn, selectors.EVENT_WRITE, ("client_write", client))
|
|
except (KeyError, ValueError, OSError):
|
|
self._drop_client(client)
|
|
|
|
def _spawn_job(self, client: _ClientConn, req: dict[str, Any]) -> None:
|
|
stdin_r, stdin_w = os.pipe()
|
|
stdout_r, stdout_w = os.pipe()
|
|
stderr_r, stderr_w = os.pipe()
|
|
close_in_child = self._collect_open_fds() | {stdin_r, stdin_w, stdout_r, stdout_w, stderr_r, stderr_w}
|
|
try:
|
|
pid = os.fork()
|
|
except OSError:
|
|
for fd in (stdin_r, stdin_w, stdout_r, stdout_w, stderr_r, stderr_w):
|
|
try:
|
|
os.close(fd)
|
|
except OSError:
|
|
pass
|
|
self._drop_client(client)
|
|
return
|
|
if pid == 0:
|
|
_run_child_script(
|
|
script_path=str(req["script"]), cwd=str(req["cwd"]),
|
|
req_env={str(k): str(v) for k, v in (req.get("env") or {}).items()},
|
|
stdin_r=stdin_r, stdout_w=stdout_w, stderr_w=stderr_w, close_fds=close_in_child,
|
|
)
|
|
return
|
|
|
|
os.close(stdin_r); os.close(stdout_w); os.close(stderr_w)
|
|
os.set_blocking(stdout_r, False); os.set_blocking(stderr_r, False)
|
|
stdin_data = base64.b64decode(req.get("stdin_b64") or "")
|
|
if stdin_data:
|
|
os.set_blocking(stdin_w, False)
|
|
watched_stdin: int | None = stdin_w
|
|
else:
|
|
os.close(stdin_w)
|
|
watched_stdin = None
|
|
|
|
pidfd = _open_pidfd(pid)
|
|
job = _ChildJob(
|
|
client=client, pid=pid,
|
|
deadline=time.monotonic() + max(float(req.get("timeout_sec") or 30), 0.001),
|
|
stdin_data=stdin_data, stdin_pos=0, stdin_w=watched_stdin,
|
|
stdout_r=stdout_r, stderr_r=stderr_r, pidfd=pidfd,
|
|
stdout_buf=bytearray(), stderr_buf=bytearray(),
|
|
)
|
|
client.job = job
|
|
self.jobs[pid] = job
|
|
if watched_stdin is not None:
|
|
self.sel.register(watched_stdin, selectors.EVENT_WRITE, ("stdin", job))
|
|
self.sel.register(stdout_r, selectors.EVENT_READ, ("stdout", job))
|
|
self.sel.register(stderr_r, selectors.EVENT_READ, ("stderr", job))
|
|
if pidfd is not None:
|
|
self.sel.register(pidfd, selectors.EVENT_READ, ("pidfd", job))
|
|
|
|
def _on_accept(self) -> None:
|
|
while True:
|
|
try:
|
|
conn, _ = self.server_sock.accept()
|
|
except BlockingIOError:
|
|
break
|
|
conn.setblocking(False)
|
|
c = _ClientConn(conn=conn, in_buf=bytearray())
|
|
self.clients[conn.fileno()] = c
|
|
self.sel.register(conn, selectors.EVENT_READ, ("client_read", c))
|
|
|
|
def _on_client_read(self, client: _ClientConn) -> None:
|
|
if client.job is not None:
|
|
try:
|
|
chunk = client.conn.recv(64)
|
|
except OSError:
|
|
chunk = b""
|
|
if not chunk:
|
|
self._kill_and_reap(client.job)
|
|
self._drop_client(client)
|
|
return
|
|
try:
|
|
chunk = client.conn.recv(65536)
|
|
except BlockingIOError:
|
|
return
|
|
except OSError:
|
|
chunk = b""
|
|
if not chunk:
|
|
self._drop_client(client)
|
|
return
|
|
client.in_buf.extend(chunk)
|
|
if len(client.in_buf) > MAX_FRAME_BYTES:
|
|
self._drop_client(client)
|
|
return
|
|
if client.req_len is None and len(client.in_buf) >= _HEADER.size:
|
|
(client.req_len,) = _HEADER.unpack_from(client.in_buf, 0)
|
|
if client.req_len > MAX_FRAME_BYTES:
|
|
self._drop_client(client)
|
|
return
|
|
if client.req_len is not None and len(client.in_buf) >= _HEADER.size + client.req_len:
|
|
raw = bytes(client.in_buf[_HEADER.size : _HEADER.size + client.req_len])
|
|
client.in_buf.clear()
|
|
client.req_len = None
|
|
try:
|
|
req = json.loads(raw.decode("utf-8"))
|
|
except (ValueError, UnicodeDecodeError):
|
|
self._drop_client(client)
|
|
return
|
|
cmd = req.get("cmd")
|
|
if cmd == "ping":
|
|
self._enqueue(client, {"ok": True, "pid": os.getpid()})
|
|
elif cmd == "shutdown":
|
|
self.shutdown_client = client
|
|
self._enqueue(client, {"ok": True})
|
|
elif cmd == "run":
|
|
self._spawn_job(client, req)
|
|
else:
|
|
self._drop_client(client)
|
|
|
|
def _on_client_write(self, client: _ClientConn) -> None:
|
|
assert client.out_buf is not None
|
|
try:
|
|
client.out_pos += client.conn.send(memoryview(client.out_buf)[client.out_pos :])
|
|
except BlockingIOError:
|
|
return
|
|
except OSError:
|
|
self._drop_client(client)
|
|
if self.shutdown_client is client:
|
|
self.stopping = True
|
|
return
|
|
if client.out_pos >= len(client.out_buf):
|
|
self._drop_client(client)
|
|
if self.shutdown_client is client:
|
|
self.stopping = True
|
|
|
|
def _on_stdin(self, job: _ChildJob) -> None:
|
|
if job.stdin_w is None:
|
|
return
|
|
try:
|
|
job.stdin_pos += os.write(job.stdin_w, memoryview(job.stdin_data)[job.stdin_pos :])
|
|
except BlockingIOError:
|
|
return
|
|
except OSError:
|
|
_close_fd_watched(self.sel, job.stdin_w)
|
|
job.stdin_w = None
|
|
return
|
|
if job.stdin_pos >= len(job.stdin_data):
|
|
_close_fd_watched(self.sel, job.stdin_w)
|
|
job.stdin_w = None
|
|
|
|
def _sweep_jobs(self) -> None:
|
|
now = time.monotonic()
|
|
for job in list(self.jobs.values()):
|
|
if not job.exited and job.stdout_r is None and job.stderr_r is None:
|
|
_reap_nonblocking(job)
|
|
if job.stdout_r is None and job.stderr_r is None and job.exited:
|
|
_close_fd_watched(self.sel, job.stdin_w)
|
|
_close_fd_watched(self.sel, job.pidfd)
|
|
job.stdin_w = job.pidfd = None
|
|
self.jobs.pop(job.pid, None)
|
|
job.client.job = None
|
|
self._enqueue(job.client, {
|
|
"timed_out": False,
|
|
"returncode": job.returncode if job.returncode is not None else 0,
|
|
"stdout_b64": base64.b64encode(bytes(job.stdout_buf)).decode("ascii"),
|
|
"stderr_b64": base64.b64encode(bytes(job.stderr_buf)).decode("ascii"),
|
|
})
|
|
elif now >= job.deadline:
|
|
self._kill_and_reap(job)
|
|
job.client.job = None
|
|
self._enqueue(job.client, {
|
|
"timed_out": True,
|
|
"stdout_b64": base64.b64encode(bytes(job.stdout_buf)).decode("ascii"),
|
|
"stderr_b64": base64.b64encode(bytes(job.stderr_buf)).decode("ascii"),
|
|
})
|
|
|
|
def run(self) -> None:
|
|
try:
|
|
while not self.stopping:
|
|
now = time.monotonic()
|
|
timeout: float | None = None
|
|
for job in self.jobs.values():
|
|
rem = max(0.0, job.deadline - now)
|
|
if job.pidfd is None and job.stdout_r is None and job.stderr_r is None and not job.exited:
|
|
rem = min(rem, 0.005)
|
|
timeout = rem if timeout is None else min(timeout, rem)
|
|
|
|
for key, _ in self.sel.select(timeout=timeout):
|
|
kind, obj = key.data
|
|
if kind == "signal":
|
|
try:
|
|
os.read(self.sig_r, 64)
|
|
except OSError:
|
|
pass
|
|
self.stopping = True
|
|
elif kind == "accept":
|
|
self._on_accept()
|
|
elif kind == "client_read":
|
|
self._on_client_read(obj)
|
|
elif kind == "client_write":
|
|
self._on_client_write(obj)
|
|
elif kind == "stdin":
|
|
self._on_stdin(obj)
|
|
elif kind in ("stdout", "stderr"):
|
|
fd = obj.stdout_r if kind == "stdout" else obj.stderr_r
|
|
buf = obj.stdout_buf if kind == "stdout" else obj.stderr_buf
|
|
if fd is not None and _drain_pipe(fd, buf):
|
|
_close_fd_watched(self.sel, fd)
|
|
if kind == "stdout":
|
|
obj.stdout_r = None
|
|
else:
|
|
obj.stderr_r = None
|
|
elif kind == "pidfd":
|
|
_close_fd_watched(self.sel, obj.pidfd)
|
|
obj.pidfd = None
|
|
_reap_nonblocking(obj)
|
|
self._sweep_jobs()
|
|
finally:
|
|
for job in list(self.jobs.values()):
|
|
self._kill_and_reap(job)
|
|
for client in list(self.clients.values()):
|
|
self._drop_client(client)
|
|
_close_fd_watched(self.sel, self.server_sock.fileno())
|
|
_close_fd_watched(self.sel, self.sig_r)
|
|
try:
|
|
os.close(self.sig_w)
|
|
except OSError:
|
|
pass
|
|
self.sel.close()
|
|
try:
|
|
os.unlink(self.sock_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _serve_zygote(sock_path: str, parent_pid: int, ready_fd: int) -> None:
|
|
_arm_pdeathsig(parent_pid)
|
|
_scrub_sys_path()
|
|
for mod in _PREIMPORTS:
|
|
__import__(mod)
|
|
_ZygoteServer(sock_path, ready_fd).run()
|
|
|
|
|
|
def _main(argv: list[str]) -> int:
|
|
_serve_zygote(
|
|
argv[1],
|
|
int(argv[argv.index("--parent-pid") + 1]),
|
|
int(argv[argv.index("--ready-fd") + 1]),
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(_main(sys.argv))
|