|
| 1 | +"""Cross-platform process helpers for provider CLIs.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import contextlib |
| 7 | +import os |
| 8 | +import shutil |
| 9 | +import signal |
| 10 | +import subprocess |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +IS_WINDOWS = os.name == "nt" |
| 14 | + |
| 15 | + |
| 16 | +def path_for_provider(path: str | Path) -> str: |
| 17 | + """Serialize a filesystem path for provider APIs with stable separators.""" |
| 18 | + return Path(path).as_posix() |
| 19 | + |
| 20 | + |
| 21 | +def resolve_executable(command: str) -> str | None: |
| 22 | + """Resolve a command name to an executable path on the current platform. |
| 23 | +
|
| 24 | + On Windows this finds npm ``.CMD``/``.BAT`` shims that |
| 25 | + ``asyncio.create_subprocess_exec("codex", ...)`` cannot launch by bare |
| 26 | + name. |
| 27 | +
|
| 28 | + A bare name always goes through ``PATH``. Only a command written as a path |
| 29 | + is read from the filesystem, so a file named ``codex`` in the working |
| 30 | + directory cannot shadow the real executable. |
| 31 | + """ |
| 32 | + if _is_path_like(command): |
| 33 | + # Returned verbatim: normalising through Path would strip a leading |
| 34 | + # ``./``, turning an explicit relative path back into a bare name that |
| 35 | + # the exec call would then look up on PATH. |
| 36 | + return command if Path(command).is_file() else None |
| 37 | + return shutil.which(command) |
| 38 | + |
| 39 | + |
| 40 | +def _is_path_like(command: str) -> bool: |
| 41 | + """Return whether a command names a filesystem path rather than a bare name.""" |
| 42 | + separators = (os.sep, os.altsep) if os.altsep else (os.sep,) |
| 43 | + return any(separator in command for separator in separators) |
| 44 | + |
| 45 | + |
| 46 | +def popen_start_new_session() -> bool: |
| 47 | + """Return whether new process groups are safe for this platform.""" |
| 48 | + # Windows process groups do not match POSIX killpg semantics and can leave |
| 49 | + # npm shim trees behind when only the wrapper pid is terminated. |
| 50 | + return not IS_WINDOWS |
| 51 | + |
| 52 | + |
| 53 | +def process_is_alive(pid: int) -> bool: |
| 54 | + """Return whether a PID currently refers to a live process.""" |
| 55 | + if pid <= 0: |
| 56 | + return False |
| 57 | + if pid == os.getpid(): |
| 58 | + return True |
| 59 | + if IS_WINDOWS: |
| 60 | + return _windows_process_is_alive(pid) |
| 61 | + try: |
| 62 | + os.kill(pid, 0) |
| 63 | + except ProcessLookupError: |
| 64 | + return False |
| 65 | + except PermissionError: |
| 66 | + return True |
| 67 | + return True |
| 68 | + |
| 69 | + |
| 70 | +def _windows_process_is_alive(pid: int) -> bool: |
| 71 | + import ctypes |
| 72 | + from ctypes import wintypes |
| 73 | + |
| 74 | + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) |
| 75 | + process_query_limited_information = 0x1000 |
| 76 | + still_active = 259 |
| 77 | + handle = kernel32.OpenProcess(process_query_limited_information, 0, pid) |
| 78 | + if not handle: |
| 79 | + return False |
| 80 | + try: |
| 81 | + exit_code = wintypes.DWORD() |
| 82 | + if kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)) == 0: |
| 83 | + return False |
| 84 | + return int(exit_code.value) == still_active |
| 85 | + finally: |
| 86 | + kernel32.CloseHandle(handle) |
| 87 | + |
| 88 | + |
| 89 | +def kill_process_tree(pid: int) -> None: |
| 90 | + """Force-terminate a process and its descendants.""" |
| 91 | + if pid <= 0: |
| 92 | + return |
| 93 | + if IS_WINDOWS: |
| 94 | + creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) |
| 95 | + subprocess.run( |
| 96 | + ["taskkill", "/PID", str(pid), "/T", "/F"], |
| 97 | + check=False, |
| 98 | + capture_output=True, |
| 99 | + creationflags=creationflags, |
| 100 | + ) |
| 101 | + return |
| 102 | + if _kill_process_group(pid): |
| 103 | + return |
| 104 | + with contextlib.suppress(ProcessLookupError, PermissionError): |
| 105 | + os.kill(pid, signal.SIGKILL) |
| 106 | + |
| 107 | + |
| 108 | +def _kill_process_group(pid: int) -> bool: |
| 109 | + """Kill the process group led by ``pid``, if it is safe to do so. |
| 110 | +
|
| 111 | + Children started with ``start_new_session=True`` lead their own group, so |
| 112 | + signalling the group reaches descendants that a bare ``os.kill`` would |
| 113 | + orphan. A child sharing this process's group is skipped: signalling that |
| 114 | + group would kill the caller too. |
| 115 | + """ |
| 116 | + try: |
| 117 | + group = os.getpgid(pid) |
| 118 | + except (ProcessLookupError, PermissionError, OSError): |
| 119 | + return False |
| 120 | + if group in (os.getpgid(0), 0): |
| 121 | + return False |
| 122 | + try: |
| 123 | + os.killpg(group, signal.SIGKILL) |
| 124 | + except (ProcessLookupError, PermissionError, OSError): |
| 125 | + return False |
| 126 | + return True |
| 127 | + |
| 128 | + |
| 129 | +async def terminate_asyncio_process(process: asyncio.subprocess.Process) -> None: |
| 130 | + """Terminate an asyncio subprocess, including Windows npm shim trees.""" |
| 131 | + if process.returncode is not None or process.pid is None: |
| 132 | + return |
| 133 | + if IS_WINDOWS: |
| 134 | + await asyncio.to_thread(kill_process_tree, process.pid) |
| 135 | + try: |
| 136 | + await asyncio.wait_for(process.wait(), timeout=2) |
| 137 | + except TimeoutError: |
| 138 | + process.kill() |
| 139 | + await process.wait() |
| 140 | + return |
| 141 | + process.kill() |
| 142 | + await process.wait() |
| 143 | + |
| 144 | + |
| 145 | +def terminate_popen(process: subprocess.Popen[str]) -> None: |
| 146 | + """Terminate a ``subprocess.Popen`` process tree.""" |
| 147 | + if process.poll() is not None or process.pid is None: |
| 148 | + return |
| 149 | + kill_process_tree(process.pid) |
| 150 | + try: |
| 151 | + process.wait(timeout=2) |
| 152 | + except subprocess.TimeoutExpired: |
| 153 | + process.kill() |
| 154 | + with contextlib.suppress(subprocess.TimeoutExpired): |
| 155 | + process.wait(timeout=0.5) |
0 commit comments