| # Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| import asyncio | |
| import enum | |
| import logging | |
| import os | |
| import signal | |
| import socket | |
| import subprocess | |
| import time | |
| from collections.abc import Callable | |
| from pathlib import Path | |
| from typing import Final | |
| from fx_cmd.lib import FxCmd | |
| from pydantic import ValidationError | |
| from shared import cleanup | |
| from shared.protocol import PROTOCOL_VERSION, Response, serialize | |
| from shared.protocol.hello import HelloRequest | |
| from shared.protocol.start import StartRequest | |
| from shared.protocol.stop import StopRequest | |
| _LOGGER = logging.getLogger(__name__) | |
| UDS_PATH: Final[Path] = Path("/tmp/fx-debug-daemon.sock") | |
| # Stay above worst-case startup (10s handshake + | |
| # TargetRepoManager.ensure_serving() [13s prior stop + 20s host list (15s + | |
| # 5s kill grace) + 10s target list (5s + 5s kill grace) + 6s stale stop + | |
| # 20s post-stop list (15s + 5s kill grace) + 3s exit poll + 10s stale | |
| # deregister (5s + 5s kill grace) + 105s start_background (3x30s + 3x5s kill | |
| # grace) + 30s wait_for_registration = 217s] + 30s _DAP_READY_TIMEOUT_SECS + | |
| # ~30s _connect_to_dap() + 14s failure cleanup_session_resources() [1s writer | |
| # close + 13s repo teardown], ~301s max even if every step nearly times out | |
| # sequentially) so daemon-side error diagnostics return over UDS before | |
| # DaemonManager times out. | |
| _DEFAULT_STARTUP_TIMEOUT_SECS = 320.0 | |
| # Aligned above worst-case daemon teardown (1s active handlers + 1s detach + | |
| # 1s writer close + 2s deregister + 5s AsyncCommand kill grace + 6s stop = ~16s) | |
| # so cooperative shutdown finishes before SIGTERM/SIGKILL fallback or early | |
| # socket unlink. | |
| _STOP_GRACE_PERIOD_SECS = 20.0 | |
| _SIGTERM_GRACE_PERIOD_SECS = _STOP_GRACE_PERIOD_SECS | |
| _SIGTERM_FALLBACK_GRACE_SECS = 3.0 | |
| _HANDSHAKE_TIMEOUT_SECS = 10.0 | |
| class DaemonManagerError(Exception): | |
| """Base class for all DaemonManager errors.""" | |
| class DaemonAlreadyRunningError(DaemonManagerError): | |
| """Raised when the daemon socket exists and responds to handshake, but we didn't request connecting to it.""" | |
| class DaemonHandshakeError(DaemonManagerError): | |
| """Raised when handshake with the daemon fails (e.g. version mismatch or protocol error).""" | |
| class DaemonStartupTimeoutError(DaemonManagerError): | |
| """Raised when waiting for the daemon to signal readiness times out.""" | |
| class DaemonCrashError(DaemonManagerError): | |
| """Raised when the daemon process exits prematurely before signaling readiness.""" | |
| class DaemonConnectionError(DaemonManagerError): | |
| """Raised when connecting to the daemon socket fails.""" | |
| def _resolve_isolated_pgid(proc: subprocess.Popen[bytes]) -> int | None: | |
| if getattr(proc, "returncode", None) is not None: | |
| return None | |
| pid = getattr(proc, "pid", None) | |
| if isinstance(pid, int) and not isinstance(pid, bool) and pid > 1: | |
| try: | |
| pgid = os.getpgid(pid) | |
| except (ProcessLookupError, PermissionError): | |
| return None | |
| if pgid > 1 and pgid == pid and pgid != os.getpgrp(): | |
| return pgid | |
| return None | |
| def _send_signal_and_wait( | |
| proc: subprocess.Popen[bytes], | |
| sig: int, | |
| fallback_fn: Callable[[], None], | |
| timeout: float, | |
| pgid: int | None, | |
| ) -> bool: | |
| """Sends a terminating signal to an isolated PGID or falls back to proc, waiting for exit.""" | |
| if pgid is None: | |
| try: | |
| fallback_fn() | |
| except ProcessLookupError: | |
| return True | |
| except PermissionError: | |
| return False | |
| try: | |
| proc.wait(timeout=timeout) | |
| return True | |
| except subprocess.TimeoutExpired: | |
| return False | |
| deadline = time.monotonic() + max(timeout, 0.0) | |
| try: | |
| os.killpg(pgid, sig) | |
| except ProcessLookupError: | |
| return True | |
| except PermissionError: | |
| return _send_signal_and_wait(proc, sig, fallback_fn, timeout, pgid=None) | |
| try: | |
| proc.wait(timeout=max(deadline - time.monotonic(), 0.0)) | |
| except subprocess.TimeoutExpired: | |
| pass | |
| while True: | |
| try: | |
| os.killpg(pgid, 0) | |
| except ProcessLookupError: | |
| return True | |
| except PermissionError: | |
| return proc.poll() is not None | |
| if (rem := deadline - time.monotonic()) <= 0.0: | |
| return False | |
| time.sleep(min(0.02, rem)) | |
| @enum.unique | |
| class _Unset(enum.Enum): | |
| TOKEN = enum.auto() | |
| _UNSET = _Unset.TOKEN | |
| def _cleanup_process( | |
| proc: subprocess.Popen[bytes], | |
| sigterm_timeout: float = _SIGTERM_GRACE_PERIOD_SECS, | |
| pgid: int | None | _Unset = _UNSET, | |
| ) -> None: | |
| """Cleans up the process by terminating it and killing it if it doesn't exit.""" | |
| resolved_pgid = _resolve_isolated_pgid(proc) if pgid is _UNSET else pgid | |
| if proc.poll() is not None: | |
| if resolved_pgid is None: | |
| return | |
| try: | |
| os.killpg(resolved_pgid, 0) | |
| except (ProcessLookupError, PermissionError): | |
| return | |
| try: | |
| terminated = _send_signal_and_wait( | |
| proc, | |
| signal.SIGTERM, | |
| proc.terminate, | |
| sigterm_timeout, | |
| pgid=resolved_pgid, | |
| ) | |
| except Exception: | |
| terminated = False | |
| if not terminated: | |
| try: | |
| _send_signal_and_wait( | |
| proc, signal.SIGKILL, proc.kill, 2.0, pgid=resolved_pgid | |
| ) | |
| except Exception: | |
| pass | |
| async def _await_process_cleanup(proc: subprocess.Popen[bytes]) -> None: | |
| cleanup_task = asyncio.create_task( | |
| asyncio.to_thread(_cleanup_process, proc) | |
| ) | |
| await cleanup.await_shielded_cleanup( | |
| cleanup_task, | |
| _LOGGER, | |
| "Daemon startup process cleanup failed", | |
| ) | |
| def _remaining_budget(deadline: float, cap: float | None = None) -> float: | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0.0: | |
| raise DaemonStartupTimeoutError("Timed out starting daemon.") | |
| return min(remaining, cap) if cap is not None else remaining | |
| def _send_stop_ipc(target_socket: Path, deadline: float) -> bool: | |
| """Attempts cooperative StopRequest IPC within deadline. | |
| Returns: | |
| True if graceful IPC succeeded, False if the socket is stale | |
| (ConnectionRefusedError or FileNotFoundError). | |
| Raises: | |
| TimeoutError: If deadline expires before or during stop IPC. | |
| OSError: If socket creation, connect, send, or recv fails unexpectedly. | |
| """ | |
| remaining = max(deadline - time.monotonic(), 0.0) | |
| if remaining <= 0.0: | |
| raise TimeoutError("Timed out before daemon stop IPC") | |
| with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: | |
| s.settimeout(remaining) | |
| try: | |
| s.connect(str(target_socket)) | |
| stop_req = StopRequest() | |
| s.sendall(serialize(stop_req).encode("utf-8")) | |
| # Read until EOF. | |
| while True: | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0.0: | |
| raise TimeoutError("Timed out waiting for daemon stop EOF") | |
| s.settimeout(remaining) | |
| data = s.recv(4096) | |
| if not data: | |
| break | |
| return True | |
| except (ConnectionRefusedError, FileNotFoundError): | |
| return False | |
| def _wait_and_cleanup_proc( | |
| proc: subprocess.Popen[bytes], | |
| *, | |
| timeout: float, | |
| deadline: float, | |
| graceful_ipc_succeeded: bool, | |
| ipc_error: Exception | None, | |
| pgid: int | None, | |
| ) -> None: | |
| """Waits for proc after graceful IPC if applicable, then terminates its group.""" | |
| wait_timed_out = False | |
| try: | |
| if graceful_ipc_succeeded: | |
| try: | |
| proc.wait(timeout=max(deadline - time.monotonic(), 0.0)) | |
| except subprocess.TimeoutExpired: | |
| wait_timed_out = True | |
| except Exception: | |
| pass | |
| finally: | |
| remaining = max(deadline - time.monotonic(), 0.0) | |
| if not graceful_ipc_succeeded or wait_timed_out: | |
| if ipc_error is not None: | |
| _LOGGER.debug( | |
| "Daemon stop IPC failed (%s); falling back to process cleanup", | |
| ipc_error, | |
| ) | |
| fallback_grace = min( | |
| max(timeout, 0.0), _SIGTERM_FALLBACK_GRACE_SECS | |
| ) | |
| sigterm_timeout = min( | |
| max(remaining, fallback_grace), | |
| _SIGTERM_GRACE_PERIOD_SECS, | |
| ) | |
| else: | |
| sigterm_timeout = min(remaining, _SIGTERM_GRACE_PERIOD_SECS) | |
| _cleanup_process( | |
| proc, | |
| sigterm_timeout=sigterm_timeout, | |
| pgid=pgid, | |
| ) | |
| class DaemonManager: | |
| def __init__( | |
| self, | |
| socket_path: Path = UDS_PATH, | |
| port: int | None = None, | |
| connect_to_existing: bool = False, | |
| startup_timeout: float = _DEFAULT_STARTUP_TIMEOUT_SECS, | |
| spawn_fn: Callable[[int], subprocess.Popen[bytes]] | None = None, | |
| ) -> None: | |
| self.socket_path = socket_path | |
| self.port = port | |
| self.connect_to_existing = connect_to_existing | |
| self.startup_timeout = startup_timeout | |
| self.spawn_fn = spawn_fn | |
| self._proc: subprocess.Popen[bytes] | None = None | |
| async def do_handshake_and_connect( | |
| self, timeout: float | None = None | |
| ) -> bool | None: | |
| """Attempts to connect to the UDS and perform handshake. | |
| Args: | |
| timeout: Optional timeout in seconds for the connection and | |
| handshake. Defaults to `self.startup_timeout`, and is capped at | |
| `_HANDSHAKE_TIMEOUT_SECS` (`10.0s`). | |
| Returns: | |
| True if handshake succeeded. | |
| None if connection failed because the socket is not ready/refused. | |
| Raises: | |
| DaemonConnectionError: If connection to the socket fails unexpectedly. | |
| DaemonHandshakeError: If the handshake protocol or version check fails. | |
| """ | |
| handshake_timeout = min( | |
| _HANDSHAKE_TIMEOUT_SECS, | |
| self.startup_timeout if timeout is None else timeout, | |
| ) | |
| writer: asyncio.StreamWriter | None = None | |
| try: | |
| async with asyncio.timeout(handshake_timeout): | |
| try: | |
| reader, writer = await asyncio.open_unix_connection( | |
| self.socket_path | |
| ) | |
| except (ConnectionRefusedError, FileNotFoundError): | |
| return None | |
| except TimeoutError: | |
| raise | |
| except Exception as e: | |
| raise DaemonConnectionError( | |
| f"Error connecting to daemon: {e}" | |
| ) | |
| req = HelloRequest(version=PROTOCOL_VERSION) | |
| writer.write(serialize(req).encode("utf-8")) | |
| await writer.drain() | |
| response_line = await reader.readline() | |
| if not response_line: | |
| raise DaemonHandshakeError( | |
| "No response received during handshake" | |
| ) | |
| try: | |
| resp = Response.model_validate_json( | |
| response_line.decode("utf-8") | |
| ) | |
| except ValidationError as e: | |
| raise DaemonHandshakeError(f"Malformed handshake response: {e}") | |
| if not resp.success: | |
| raise DaemonHandshakeError(f"Handshake failed: {resp.message}") | |
| if not isinstance(resp.body, dict): | |
| raise DaemonHandshakeError("Malformed handshake response body") | |
| daemon_version = resp.body.get("protocol_version") | |
| if daemon_version != PROTOCOL_VERSION: | |
| raise DaemonHandshakeError( | |
| f"Protocol version mismatch. CLI: {PROTOCOL_VERSION}, Daemon: {daemon_version}" | |
| ) | |
| return True | |
| except TimeoutError: | |
| raise DaemonHandshakeError("Handshake timeout") | |
| except (DaemonConnectionError, DaemonHandshakeError): | |
| raise | |
| except Exception as e: | |
| raise DaemonHandshakeError(f"Error during handshake: {e}") | |
| finally: | |
| if writer is not None: | |
| writer.close() | |
| try: | |
| await writer.wait_closed() | |
| except Exception: | |
| pass | |
| async def is_running(self) -> bool: | |
| """Checks if the daemon is currently running and responding to handshakes.""" | |
| try: | |
| return (await self.do_handshake_and_connect()) is True | |
| except (DaemonConnectionError, DaemonHandshakeError): | |
| return False | |
| async def connect_to_running_daemon( | |
| self, timeout: float | None = None | |
| ) -> None: | |
| """Sends a StartRequest to the already running daemon to connect it to DAP.""" | |
| if not self.socket_path.exists(): | |
| raise DaemonConnectionError( | |
| f"Daemon socket not found at {self.socket_path}. Is it running?" | |
| ) | |
| await self._send_start_request(connect=True, timeout=timeout) | |
| def _spawn_daemon_process(self, write_fd: int) -> subprocess.Popen[bytes]: | |
| """Spawns the zxdb-daemon process in the background using FxCmd.""" | |
| fx_cmd = FxCmd() | |
| args = ["zxdb-daemon"] | |
| if self.port is not None: | |
| args.extend(["--port", str(self.port)]) | |
| os.set_inheritable(write_fd, True) | |
| args.append(f"--ready-fd={write_fd}") | |
| command_line = fx_cmd.command_line(*args) | |
| return subprocess.Popen( | |
| command_line, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| start_new_session=True, | |
| pass_fds=[write_fd], | |
| ) | |
| async def _wait_for_ready_signal( | |
| self, read_fd: int, timeout: float | None = None | |
| ) -> None: | |
| """Waits for the ready signal byte on the non-blocking pipe read end.""" | |
| loop = asyncio.get_running_loop() | |
| future = loop.create_future() | |
| os.set_blocking(read_fd, False) | |
| def on_read() -> None: | |
| try: | |
| data = os.read(read_fd, 1) | |
| if not future.done(): | |
| if data == b"": | |
| future.set_exception( | |
| DaemonCrashError( | |
| "Daemon exited prematurely and closed the sync pipe." | |
| ) | |
| ) | |
| else: | |
| future.set_result(data) | |
| except BlockingIOError: | |
| pass | |
| except Exception as e: | |
| if not future.done(): | |
| future.set_exception(e) | |
| loop.add_reader(read_fd, on_read) | |
| try: | |
| effective_timeout = ( | |
| self.startup_timeout if timeout is None else timeout | |
| ) | |
| await asyncio.wait_for(future, timeout=effective_timeout) | |
| except asyncio.TimeoutError: | |
| raise DaemonStartupTimeoutError( | |
| "Timed out waiting for daemon to signal readiness." | |
| ) | |
| finally: | |
| loop.remove_reader(read_fd) | |
| async def _send_start_request( | |
| self, | |
| *, | |
| timeout: float | None, | |
| connect: bool | None = None, | |
| socket_path: Path | None = None, | |
| ) -> Response[object]: | |
| """Sends a StartRequest to the daemon and returns the validated Response.""" | |
| connect_flag = self.connect_to_existing if connect is None else connect | |
| target_socket = ( | |
| socket_path if socket_path is not None else self.socket_path | |
| ) | |
| request_timeout = self.startup_timeout if timeout is None else timeout | |
| writer: asyncio.StreamWriter | None = None | |
| try: | |
| async with asyncio.timeout(request_timeout): | |
| try: | |
| reader, writer = await asyncio.open_unix_connection( | |
| target_socket | |
| ) | |
| except TimeoutError: | |
| raise | |
| except Exception as e: | |
| raise DaemonConnectionError( | |
| f"Error connecting to daemon: {e}" | |
| ) | |
| start_req = StartRequest(port=self.port, connect=connect_flag) | |
| writer.write(serialize(start_req).encode("utf-8")) | |
| await writer.drain() | |
| response_line = await reader.readline() | |
| if not response_line: | |
| raise DaemonConnectionError( | |
| "No response received from daemon on start request." | |
| ) | |
| try: | |
| resp = Response.model_validate_json( | |
| response_line.decode("utf-8") | |
| ) | |
| except ValidationError as e: | |
| raise DaemonConnectionError( | |
| f"Malformed response on start request: {e}" | |
| ) | |
| if not resp.success: | |
| raise DaemonConnectionError( | |
| resp.message or "Failed to initialize session" | |
| ) | |
| return resp | |
| except TimeoutError: | |
| raise DaemonConnectionError( | |
| "Timed out waiting for response from daemon." | |
| ) | |
| except DaemonConnectionError: | |
| raise | |
| except Exception as e: | |
| raise DaemonConnectionError(f"Error communicating with daemon: {e}") | |
| finally: | |
| if writer is not None: | |
| writer.close() | |
| try: | |
| await writer.wait_closed() | |
| except Exception: | |
| pass | |
| async def start(self) -> subprocess.Popen[bytes] | None: | |
| """Starts the daemon process or connects to an existing one. | |
| Returns: | |
| The spawned subprocess.Popen object, or None if successfully connected | |
| to an already running daemon. | |
| """ | |
| deadline = time.monotonic() + max(self.startup_timeout, 0.0) | |
| read_fd = -1 | |
| write_fd = -1 | |
| proc = None | |
| startup_success = False | |
| try: | |
| # 1. Handle existing socket | |
| if self.socket_path.exists(): | |
| handshake_result = await self.do_handshake_and_connect( | |
| timeout=_remaining_budget(deadline, _HANDSHAKE_TIMEOUT_SECS) | |
| ) | |
| if handshake_result is True: | |
| if self.connect_to_existing: | |
| await self.connect_to_running_daemon( | |
| timeout=_remaining_budget(deadline) | |
| ) | |
| return None | |
| raise DaemonAlreadyRunningError( | |
| f"Daemon socket already exists at {self.socket_path}" | |
| ) | |
| else: | |
| # handshake_result is None: socket exists but is stale | |
| self.socket_path.unlink(missing_ok=True) | |
| # 2. Start a new daemon process | |
| _remaining_budget(deadline) | |
| read_fd, write_fd = os.pipe() | |
| if self.spawn_fn: | |
| proc = self.spawn_fn(write_fd) | |
| else: | |
| proc = self._spawn_daemon_process(write_fd) | |
| os.close(write_fd) | |
| write_fd = -1 | |
| # Wait for daemon to signal readiness | |
| await self._wait_for_ready_signal( | |
| read_fd, timeout=_remaining_budget(deadline) | |
| ) | |
| # Verify handshake | |
| handshake_result = await self.do_handshake_and_connect( | |
| timeout=_remaining_budget(deadline, _HANDSHAKE_TIMEOUT_SECS) | |
| ) | |
| if handshake_result is not True: | |
| raise DaemonHandshakeError( | |
| "Daemon started but failed to respond to handshake in time." | |
| ) | |
| # Send StartRequest to establish the session | |
| await self._send_start_request(timeout=_remaining_budget(deadline)) | |
| startup_success = True | |
| self._proc = proc | |
| return proc | |
| finally: | |
| if write_fd != -1: | |
| try: | |
| os.close(write_fd) | |
| except OSError: | |
| pass | |
| if read_fd != -1: | |
| try: | |
| os.close(read_fd) | |
| except OSError: | |
| pass | |
| if not startup_success and proc is not None: | |
| try: | |
| await _await_process_cleanup(proc) | |
| finally: | |
| try: | |
| self.socket_path.unlink(missing_ok=True) | |
| except OSError as e: | |
| _LOGGER.warning( | |
| "Failed to unlink daemon socket %s: %s", | |
| self.socket_path, | |
| e, | |
| ) | |
| def stop_sync(self, timeout: float = _STOP_GRACE_PERIOD_SECS) -> None: | |
| """Stops the daemon cooperatively over UDS, escalating to SIGTERM/SIGKILL if needed. | |
| `timeout` bounds the cooperative UDS `StopRequest` IPC drain and | |
| post-IPC `proc.wait()` budget. If cooperative shutdown fails, times out, | |
| or is skipped while a child process is tracked (or post-IPC `wait()` | |
| times out), `_cleanup_process()` is guaranteed a bounded SIGTERM | |
| fallback grace window of at least | |
| `min(max(timeout, 0.0), _SIGTERM_FALLBACK_GRACE_SECS)` (3.0s when | |
| `timeout >= 3.0`, bounded for tiny or zero timeouts, and capped at | |
| `_SIGTERM_GRACE_PERIOD_SECS`) so the daemon can complete handler and | |
| socket teardown before SIGKILL escalation. | |
| If no child process is tracked and cooperative IPC raises an error | |
| (other than `ConnectionRefusedError` or `FileNotFoundError`) while | |
| `socket_path` still exists, the IPC exception is raised without | |
| unlinking `socket_path`. If the socket file does not exist or the daemon | |
| is already stopped, this method returns cleanly. | |
| """ | |
| deadline = time.monotonic() + max(timeout, 0.0) | |
| had_proc = self._proc is not None | |
| # Resolve the isolated PGID before wait() reaps self._proc.pid so | |
| # lingering process-group children can still be probed/signaled and a | |
| # recycled PID is never queried afterward. | |
| pgid = ( | |
| _resolve_isolated_pgid(self._proc) | |
| if self._proc is not None | |
| else None | |
| ) | |
| graceful_ipc_succeeded = False | |
| stale_socket = False | |
| ipc_error: Exception | None = None | |
| try: | |
| if self.socket_path.exists(): | |
| try: | |
| graceful_ipc_succeeded = _send_stop_ipc( | |
| self.socket_path, deadline | |
| ) | |
| stale_socket = not graceful_ipc_succeeded | |
| except Exception as exc: | |
| ipc_error = exc | |
| finally: | |
| if self._proc is not None: | |
| try: | |
| _wait_and_cleanup_proc( | |
| self._proc, | |
| timeout=timeout, | |
| deadline=deadline, | |
| graceful_ipc_succeeded=graceful_ipc_succeeded, | |
| ipc_error=ipc_error, | |
| pgid=pgid, | |
| ) | |
| finally: | |
| self._proc = None | |
| if had_proc or graceful_ipc_succeeded or stale_socket: | |
| try: | |
| self.socket_path.unlink(missing_ok=True) | |
| except OSError as exc: | |
| _LOGGER.warning( | |
| "Failed to unlink daemon socket %s: %s", | |
| self.socket_path, | |
| exc, | |
| ) | |
| elif ipc_error is not None and self.socket_path.exists(): | |
| raise ipc_error | |
| async def stop(self, timeout: float = _STOP_GRACE_PERIOD_SECS) -> None: | |
| """Asynchronously delegates daemon shutdown to `stop_sync(timeout)`. | |
| Stops the daemon cooperatively via UDS `StopRequest` within `timeout`, | |
| escalating to SIGTERM/SIGKILL if a child process is tracked. If no | |
| child process is tracked and cooperative IPC times out or raises an | |
| error other than `ConnectionRefusedError` or `FileNotFoundError` while | |
| `socket_path` still exists, the IPC exception is raised without | |
| unlinking `socket_path`. Returns cleanly if `socket_path` does not | |
| exist or the daemon is already stopped. | |
| """ | |
| await asyncio.to_thread(self.stop_sync, timeout) |