blob: dba99867fefc671147fba75259e3a6eb464b3f05 [file]
# Copyright 2025 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 contextlib
import hashlib
import json
import logging
import os
import shlex
import signal
import time
from collections.abc import Collection, Sequence, Set
from typing import AsyncGenerator, Callable, Literal, Protocol
import build_dir
from async_utils.command import AsyncCommand, AsyncCommandError, CommandOutput
from ffx_cmd import FfxCmd
from fx_cmd import FxCmd
_LOGGER = logging.getLogger(__name__)
_DEFAULT_SERVER_STARTUP_TIMEOUT = 30
_DEFAULT_BACKGROUND_STARTUP_TIMEOUT = 60
_CHECK_SERVER_POLLING_INTERVAL = 0.2
_DEFAULT_PROBE_TIMEOUT = 15.0
_DEFAULT_DEREGISTER_TIMEOUT = 5.0
_DEFAULT_SERVER_STOP_TIMEOUT = 10.0
_DEFAULT_ABORT_GRACE_PERIOD = 5.0
_FOREGROUND_CLEANUP_GRACE_PERIOD = 1.0
_FOREGROUND_STOP_TIMEOUT = 4.0
_PGID_EXIT_POLL_INTERVAL = 0.05
class CommandRunner(Protocol):
"""Callable that executes an `fx` subcommand asynchronously.
Args:
*args (str): Subcommand and arguments to pass to `fx`.
timeout (float | None): Optional timeout in seconds before terminating
the command.
abort_signal (asyncio.Event | None): Optional event that, when set,
requests graceful termination of the running command.
quiet_mode (bool): Whether to suppress command lifecycle output in
interactive status displays.
Returns:
CommandOutput | None: Completed command output, or None if the command
could not be started.
"""
async def __call__(
self,
*args: str,
timeout: float | None = None,
abort_signal: asyncio.Event | None = None,
quiet_mode: bool = False,
) -> CommandOutput | None:
...
def _default_command_runner(
build_directory: str | os.PathLike[str] | None = None,
) -> CommandRunner:
"""Creates a `CommandRunner` backed by `FxCmd` and `AsyncCommand`."""
resolved_build_dir = (
os.fspath(build_directory) if build_directory is not None else None
)
async def run_fx(
*args: str,
timeout: float | None = None,
abort_signal: asyncio.Event | None = None,
quiet_mode: bool = False,
) -> CommandOutput | None:
del quiet_mode
started: AsyncCommand | None = None
abort_task: asyncio.Task[None] | None = None
try:
fx_cmd = FxCmd(
build_directory=resolved_build_dir,
timeout=timeout,
)
started = await fx_cmd.start(*args)
if abort_signal is not None:
async def handle_abort() -> None:
await abort_signal.wait()
started.terminate()
await asyncio.sleep(_DEFAULT_ABORT_GRACE_PERIOD)
started.kill()
abort_task = asyncio.create_task(handle_abort())
return await started.run_to_completion()
except asyncio.CancelledError:
if started is not None:
started.kill()
raise
except AsyncCommandError:
return None
finally:
if abort_task is not None:
abort_task.cancel()
return run_fx
class PackageServingException(Exception):
"""This exception is raised on unsuccessful package serving attempts."""
class PackageServingCLIException(SystemExit, PackageServingException):
"""
Like `PackageServingException`, but does not print a stack trace when uncaught.
Used in the `run_and_stop_on_exit()` asynccontextmanager function, where concise error messages
are more helpful than noisy stack traces for CLI developer tools.
"""
def _canonical_amber_files_path(
build_directory: str | os.PathLike[str] | None = None,
) -> str:
out_dir = (
build_directory
if build_directory is not None
else build_dir.get_build_directory()
)
return os.path.realpath(os.path.join(out_dir, "amber-files"))
def _extract_ffx_machine_list(output: str) -> Sequence[object] | None:
parsed = json.loads(output)
# Expected format from ffx --machine json: {"ok": {"data": [...]}}
if isinstance(parsed, dict) and isinstance(
ok_val := parsed.get("ok"), dict
):
data = ok_val.get("data", [])
return data if isinstance(data, list) else None
if isinstance(parsed, list):
return parsed
return None
async def _run_ffx_machine_list(
runner: CommandRunner,
ffx_args: Sequence[str],
*,
timeout: float,
description: str,
) -> Sequence[object]:
output = await runner(
"ffx",
"--machine",
"json",
*ffx_args,
timeout=timeout,
quiet_mode=True,
)
if output is None:
raise PackageServingException(f"Failed to list {description}.")
# Use `is True` so bare MagicMock CommandOutput stubs in downstream tests
# (such as fxtest's main_test.py) are not treated as timed out.
if output.was_timeout is True:
raise PackageServingException(
f"Timed out listing {description} after {timeout}s."
)
if output.return_code != 0:
err_output = output.stderr.strip() or output.stdout.strip()
detail = f": {err_output}" if err_output else ""
raise PackageServingException(
f"Failed to list {description} "
f"(exit code {output.return_code}){detail}."
)
cmd_label = f"ffx {' '.join(ffx_args)}"
try:
entries = _extract_ffx_machine_list(output.stdout)
except json.JSONDecodeError as e:
raise PackageServingException(
f"Invalid JSON from {cmd_label}: {e}"
) from e
if entries is None:
raise PackageServingException(
f"Unexpected JSON envelope from {cmd_label}."
)
return entries
def _extract_running_server_name(entry: object) -> str | None:
if not isinstance(entry, dict):
return None
name = entry.get("name")
return name if isinstance(name, str) and name else None
def _parse_running_server_names(
entries: Collection[object], expected_repo_path: str
) -> Set[str]:
matching_names = []
for entry in entries:
if (
not isinstance(entry, dict)
or (name := _extract_running_server_name(entry)) is None
):
continue
repo_path = entry.get("repo_path")
if isinstance(repo_path, dict):
raw_path = repo_path.get("file")
elif isinstance(repo_path, str):
raw_path = repo_path
else:
raw_path = None
if (
isinstance(raw_path, str)
and raw_path
and os.path.realpath(raw_path) == expected_repo_path
):
matching_names.append(name)
return frozenset(matching_names)
async def get_running_server_names(
build_directory: str | os.PathLike[str] | None = None,
*,
timeout: float = _DEFAULT_PROBE_TIMEOUT,
run_command: CommandRunner | None = None,
) -> Set[str]:
"""
Returns the names of running package servers for a build directory.
Args:
build_directory (str | PathLike[str] | None): Build directory whose
`amber-files` path is matched, or None for the active build
directory.
timeout (float): Subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
Set[str]: Names of running package servers whose canonicalized
`repo_path.file` matches `<build_directory>/amber-files`.
Raises:
PackageServingException: If listing running package servers fails,
times out, or returns malformed JSON.
"""
out_dir = (
build_directory
if build_directory is not None
else build_dir.get_build_directory()
)
expected_repo_path = _canonical_amber_files_path(out_dir)
runner = run_command or _default_command_runner(build_directory=out_dir)
entries = await _run_ffx_machine_list(
runner,
("repository", "server", "list"),
timeout=timeout,
description="running package servers",
)
return _parse_running_server_names(entries, expected_repo_path)
async def is_running(
*,
timeout: float | None = None,
run_command: CommandRunner | None = None,
) -> bool:
"""
Checks whether a package server is currently running.
Args:
timeout (float | None): Subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
bool: Whether a package server is currently running.
"""
runner = run_command or _default_command_runner()
result = await runner("is-package-server-running", timeout=timeout)
return result is not None and result.return_code == 0
def _extract_registered_fuchsia_repo_names(
entries: Collection[object],
) -> Set[str]:
names = []
for entry in entries:
if not isinstance(entry, dict):
continue
raw_name = entry.get("name")
if not isinstance(raw_name, str):
continue
name = raw_name.removeprefix("fuchsia-pkg://")
if not name:
continue
aliases = entry.get("aliases")
if name == "fuchsia.com" or (
isinstance(aliases, list) and "fuchsia.com" in aliases
):
names.append(name)
return frozenset(names)
async def get_registered_fuchsia_repo_names(
*,
timeout: float = _DEFAULT_PROBE_TIMEOUT,
run_command: CommandRunner | None = None,
) -> Set[str]:
"""
Returns names of `fuchsia.com` repositories registered on the target device.
Args:
timeout (float): Subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
Set[str]: Repository names registered on the target device that match
`fuchsia.com` by name or alias.
Raises:
PackageServingException: If listing target repositories fails,
times out, or returns malformed JSON.
"""
runner = run_command or _default_command_runner()
entries = await _run_ffx_machine_list(
runner,
("target", "repository", "list"),
timeout=timeout,
description="target package repositories",
)
return _extract_registered_fuchsia_repo_names(entries)
async def is_fuchsia_repo_registered_on_device(
*,
repo_name: str | None = None,
timeout: float = _DEFAULT_PROBE_TIMEOUT,
run_command: CommandRunner | None = None,
) -> bool:
"""
Checks whether a `fuchsia.com` repository is registered on the target device.
Args:
repo_name (str | None): Optional repository name to require when
matching `fuchsia.com` registrations.
timeout (float): Subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
bool: True if a matching `fuchsia.com` repository is registered on the
target device.
"""
try:
registered_names = await get_registered_fuchsia_repo_names(
timeout=timeout,
run_command=run_command,
)
except PackageServingException:
return False
return (
bool(registered_names)
if repo_name is None
else repo_name in registered_names
)
async def is_connected_to_device(
*,
repo_name: str | None = None,
timeout: float = _DEFAULT_PROBE_TIMEOUT,
run_command: CommandRunner | None = None,
) -> bool:
"""
Checks whether a package server is running and registered on the target device.
Args:
repo_name (str | None): Optional repository name to require when
matching `fuchsia.com` registrations on the target.
timeout (float): Subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
bool: True only if a host package server is running and registered on
the target device.
"""
if not await is_running(
timeout=timeout,
run_command=run_command,
):
return False
return await is_fuchsia_repo_registered_on_device(
repo_name=repo_name,
timeout=timeout,
run_command=run_command,
)
async def wait_for_registration(
*,
repo_name: str | None = None,
retries: int = 30,
interval: float = 1.0,
timeout: float = _DEFAULT_PROBE_TIMEOUT,
run_command: CommandRunner | None = None,
) -> bool:
"""
Polls until a `fuchsia.com` repository is registered on the target device.
Args:
repo_name (str | None): Optional repository name to require when
matching `fuchsia.com` registrations. Filtering by an expected
ephemeral repository name prevents unrelated stale registrations
from causing the wait to return early.
retries (int): Maximum number of polling attempts.
interval (float): Delay in seconds between polling attempts.
timeout (float): Per-probe subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
bool: True if the repository is registered within `retries` attempts.
"""
runner = run_command or _default_command_runner()
for _ in range(retries):
if await is_fuchsia_repo_registered_on_device(
repo_name=repo_name,
timeout=timeout,
run_command=runner,
):
return True
await asyncio.sleep(interval)
return False
async def deregister(
name: str,
*,
timeout: float = _DEFAULT_DEREGISTER_TIMEOUT,
run_command: CommandRunner | None = None,
) -> CommandOutput | None:
"""
Deregisters a package repository from the target device.
Args:
name (str): Repository name to deregister from the target.
timeout (float): Subprocess timeout in seconds.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
Returns:
CommandOutput | None: Subprocess output, or None if execution failed.
"""
runner = run_command or _default_command_runner()
return await runner(
"ffx",
"target",
"repository",
"deregister",
"-r",
name,
timeout=timeout,
quiet_mode=True,
)
async def serve(
*,
name: str | None = None,
prefix: str = "tmp",
build_directory: str | os.PathLike[str] | None = None,
run_command: CommandRunner | None = None,
on_warning: Callable[[str], None] | None = None,
) -> tuple[asyncio.Task[None], asyncio.Event]:
"""
Starts a managed background package server and returns its control handles.
Deregisters any stale target registration for the repository name before
starting the server, and when the returned event is set, deregisters the
repository from the target before terminating the server process group.
Args:
name (str | None): Explicit repository name, or None to derive a
deterministic ephemeral name using `prefix` and `build_directory`.
prefix (str): Tool-specific prefix when deriving an ephemeral repository
name.
build_directory (str | PathLike[str] | None): Build directory whose
package repository is being served, or None for the active build
directory.
run_command (CommandRunner | None): Optional runner for `fx`
subcommands.
on_warning (Callable[[str], None] | None): Optional callback invoked
with a human-readable warning message if teardown deregistration or
server shutdown fails.
Returns:
tuple[Task[None], Event]: Background lifecycle task and the event that
triggers graceful deregistration and server shutdown when set.
Raises:
build_dir.GetBuildDirectoryError: If `build_directory` is None (when
deriving `name` or using the default command runner) and no active
build directory can be determined.
"""
cancel_event = asyncio.Event()
repo_name = name or ephemeral_repository_name(prefix, build_directory)
runner = run_command or _default_command_runner(
build_directory=build_directory
)
# Deregister any stale registration left on the device by an interrupted
# prior run so `wait_for_registration` waits for the newly started server
# instance to register its port.
await deregister(repo_name, run_command=runner)
started_event = asyncio.Event()
repo_deregistered_event = asyncio.Event()
# Aborting the `fx serve` task stops the repository server but does not
# remove the corresponding repository config or rewrite rule from the
# device. The repository config is explicitly deregistered from the device
# (which also removes the rewrite rule) before cancelling the server task to
# avoid the pkg-resolver's AutoClient logging that the server has gone away.
async def impl() -> None:
serve_task: asyncio.Task[CommandOutput | None] | None = None
try:
serve_task = asyncio.create_task(
runner(
"serve",
"-l",
"0",
"--name",
repo_name,
abort_signal=repo_deregistered_event,
quiet_mode=True,
)
)
started_event.set()
await cancel_event.wait()
finally:
try:
deregister_output = await deregister(
repo_name,
run_command=runner,
)
if (
deregister_output is None
or deregister_output.return_code != 0
):
raise RuntimeError(
f"exit code {deregister_output.return_code if deregister_output is not None else -1}"
)
except Exception as e:
if on_warning is not None:
on_warning(
f"Failed to deregister temporary package repository {repo_name}: {e}"
)
finally:
repo_deregistered_event.set()
if serve_task is not None:
try:
await asyncio.wait_for(
serve_task, timeout=_DEFAULT_SERVER_STOP_TIMEOUT
)
except TimeoutError:
if on_warning is not None:
on_warning(
f"Timed out waiting for temporary package server ({repo_name}) to stop."
)
serve_task.cancel()
task = asyncio.create_task(impl())
try:
await started_event.wait()
except BaseException:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
raise
return (task, cancel_event)
async def wait_for_package_server(
process: asyncio.subprocess.Process, timeout: float, interval: float
) -> bool:
"""
Waits for a package server to come online by periodically polling.
Exits early if the given package serving process terminates.
Args:
process (Process): The package serving process. If it terminates early, this function
automatically returns False.
timeout (float): The maximum amount of time (in seconds) to wait for the package server.
interval (float): The delay (in seconds) between each package server availability check.
Returns:
bool: Whether the package serving process is available within `timeout` seconds.
"""
async def poll_is_running(interval: float) -> Literal[True]:
while not await is_running():
await asyncio.sleep(interval)
return True
async def wait_for_process(
process: asyncio.subprocess.Process,
) -> Literal[False]:
await process.wait()
return False
async def wait_for_timeout(timeout: float) -> Literal[False]:
await asyncio.sleep(timeout)
return False
# This task represents the True condition: When `fx is-package-server-running` is True.
poll_task = asyncio.create_task(poll_is_running(interval))
# This task represents a False condition: When `process` terminates unexpectedly.
process_task = asyncio.create_task(wait_for_process(process))
# This task represents a False condition: When `timeout` has been reached.
timeout_task = asyncio.create_task(wait_for_timeout(timeout))
# Race the three tasks; prioritize exceptions, then process exit over polling/timeout.
all_tasks = (poll_task, process_task, timeout_task)
try:
finished_task, _ = await asyncio.wait(
all_tasks,
return_when=asyncio.FIRST_COMPLETED,
)
for task in all_tasks:
if task in finished_task and (
task.cancelled() or task.exception() is not None
):
task.result()
for task in (process_task, poll_task, timeout_task):
if task in finished_task:
return task.result()
return False
finally:
for task in all_tasks:
if not task.done():
task.cancel()
await asyncio.gather(*all_tasks, return_exceptions=True)
def is_package_repository_built() -> bool:
"""
Checks whether the in-tree package repository is built.
Returns:
bool: Whether the in-tree package repository is built.
"""
return (
build_dir.get_build_directory()
/ "amber-files"
/ "repository"
/ "9.root.json"
).is_file()
def ephemeral_repository_name(
prefix: str = "tmp",
build_directory: str | os.PathLike[str] | None = None,
) -> str:
"""
Returns deterministic ephemeral repository name for a build directory.
Args:
prefix (str): Tool-specific prefix for the repository name.
build_directory (str | PathLike[str] | None): Build directory whose
package repository is being served, or None to use the active build
directory.
Returns:
str: Deterministic repository name prefixed with `<prefix>-`.
Raises:
build_dir.GetBuildDirectoryError: If `build_directory` is None and no
active build directory can be determined.
"""
repo_path = _canonical_amber_files_path(build_directory)
path_hash = hashlib.sha256(repo_path.encode("utf-8")).hexdigest()[:16]
return f"{prefix}-{path_hash}"
async def get_arguments(
name: str | None = None,
*,
port: int = 0,
background: bool = False,
) -> Sequence[str]:
"""
Gets the ffx command line arguments for starting a package server.
Retains `async def` for compatibility with callers that await this helper.
Args:
name (str | None): Optionally specify the main repository name for this server.
port (int): TCP port to listen on; 0 selects an ephemeral port.
background (bool): Whether to pass `--background` instead of `--foreground`.
Returns:
Sequence[str]: ffx arguments for package serving.
"""
out_dir = build_dir.get_build_directory()
repo_name = name or ephemeral_repository_name(build_directory=out_dir)
mode_flag = "--background" if background else "--foreground"
# Intentionally ignore repository.server.default_port here and default to
# ephemeral port 0 so concurrent build directories do not collide on 8083;
# tools/devshell/serve retains repository.server.default_port unless -l 0 is passed.
# LINT.IfChange
return (
"repository",
"server",
"start",
mode_flag,
"--address",
f"[::]:{port}",
"--repository",
repo_name,
"--repo-path",
str(out_dir / "amber-files"),
"--trusted-root",
str(out_dir / "amber-files" / "repository" / "9.root.json"),
"--alias",
"fuchsia.com",
"--alias",
"chromium.org",
)
# LINT.ThenChange(//tools/devshell/serve)
def _is_pgid_alive(pgid: int) -> bool:
try:
os.killpg(pgid, 0)
return True
except (ProcessLookupError, PermissionError):
return False
def _resolve_isolated_pgid(
process: asyncio.subprocess.Process,
) -> int | None:
pid = getattr(process, "pid", None)
if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 1:
return None
current_pgrp = os.getpgrp()
if pid == current_pgrp:
return None
try:
pgid = os.getpgid(pid)
except ProcessLookupError:
return pid if _is_pgid_alive(pid) else None
except PermissionError:
return None
if process.returncode is not None:
return None
return pgid if pgid == pid else None
async def _wait_for_pgid_exit(pgid: int) -> None:
while _is_pgid_alive(pgid):
await asyncio.sleep(_PGID_EXIT_POLL_INTERVAL)
async def _wait_for_foreground_exit(
process: asyncio.subprocess.Process, pgid: int | None
) -> None:
if process.returncode is None:
await process.wait()
if pgid is not None:
await _wait_for_pgid_exit(pgid)
def _signal_foreground_target(
process: asyncio.subprocess.Process,
pgid: int | None,
sig: signal.Signals,
) -> None:
with contextlib.suppress(ProcessLookupError):
if pgid is not None:
os.killpg(pgid, sig)
elif process.returncode is None:
if sig == signal.SIGTERM:
process.terminate()
elif sig == signal.SIGKILL:
process.kill()
else:
raise ValueError(f"Unsupported signal: {sig}")
async def cleanup_foreground_server(
process: asyncio.subprocess.Process | None,
repo_name: str | None = None,
*,
allow_stop_by_name: bool = True,
) -> None:
"""Terminates a foreground package server process group and stops its repo.
Signals the isolated process group (falling back to `process.terminate()`
and `process.kill()` if `process` is not in its own process group) with
`SIGTERM`, escalates to `SIGKILL` after a grace period if it does not exit,
and then stops `repo_name` via `stop(repo_name)` when `repo_name` is not
None and `allow_stop_by_name` is True.
Shields cleanup against cancellation; if `asyncio.CancelledError` arrives
while the foreground process or process group is still running, sends
`SIGKILL` immediately and waits for cleanup to finish before re-raising
`asyncio.CancelledError`.
Args:
process (asyncio.subprocess.Process | None): Foreground package server
process handle (for example from `start()`), or None if no process
needs termination.
repo_name (str | None): Repository name to pass to `stop()`. When None,
`stop()` is not called.
allow_stop_by_name (bool): Whether to invoke `stop(repo_name)` after
terminating `process` when `repo_name` is not None.
"""
should_stop = allow_stop_by_name and repo_name is not None
if process is None and not should_stop:
return
pgid = _resolve_isolated_pgid(process) if process is not None else None
foreground_exited = process is None or (
pgid is None and process.returncode is not None
)
async def _cleanup() -> None:
nonlocal foreground_exited
if process is not None and (
pgid is not None or process.returncode is None
):
try:
_signal_foreground_target(process, pgid, signal.SIGTERM)
try:
async with asyncio.timeout(
_FOREGROUND_CLEANUP_GRACE_PERIOD
):
await _wait_for_foreground_exit(process, pgid)
foreground_exited = True
except TimeoutError:
_signal_foreground_target(process, pgid, signal.SIGKILL)
with contextlib.suppress(TimeoutError):
async with asyncio.timeout(
_FOREGROUND_CLEANUP_GRACE_PERIOD
):
await _wait_for_foreground_exit(process, pgid)
foreground_exited = True
except Exception as exc:
_LOGGER.warning(
"Failed to terminate foreground package server process for %s: %s",
repo_name or "<unnamed>",
exc,
)
if should_stop:
assert repo_name is not None
try:
async with asyncio.timeout(_FOREGROUND_STOP_TIMEOUT):
stop_output = await stop(repo_name)
if stop_output.return_code != 0:
detail = (
stop_output.stderr.strip() or stop_output.stdout.strip()
)
combined_output = (
f"{stop_output.stderr}\n{stop_output.stdout}".lower()
)
if "no running server" not in combined_output:
detail_suffix = f": {detail}" if detail else ""
_LOGGER.warning(
"Package server %s stop exited with code %d%s.",
repo_name,
stop_output.return_code,
detail_suffix,
)
except TimeoutError:
_LOGGER.warning(
"Timed out waiting for package server %s to stop during cleanup.",
repo_name,
)
except Exception as exc:
_LOGGER.warning(
"Failed to stop package server %s during cleanup: %s",
repo_name,
exc,
)
cleanup_task = asyncio.create_task(_cleanup())
deferred_cancel: asyncio.CancelledError | None = None
while not cleanup_task.done():
try:
await asyncio.shield(cleanup_task)
except asyncio.CancelledError as cancel_exc:
deferred_cancel = cancel_exc
if process is not None and not foreground_exited:
try:
_signal_foreground_target(process, pgid, signal.SIGKILL)
except Exception as kill_exc:
_LOGGER.warning(
"Failed to kill foreground package server process for %s: %s",
repo_name or "<unnamed>",
kill_exc,
)
if deferred_cancel is not None:
raise deferred_cancel
async def _get_all_running_server_names_or_none(
timeout: float,
) -> Set[str] | None:
try:
entries = await _run_ffx_machine_list(
_default_command_runner(),
("repository", "server", "list"),
timeout=timeout,
description="running package servers",
)
except PackageServingException:
return None
return frozenset(
name
for entry in entries
if (name := _extract_running_server_name(entry)) is not None
)
async def start(
name: str | None = None,
timeout: float = _DEFAULT_SERVER_STARTUP_TIMEOUT,
) -> asyncio.subprocess.Process:
"""
Starts a foreground package server in an isolated session.
Checks that the package repository is built, probes running servers via
`ffx repository server list` (bounded by `min(timeout, 15.0)` seconds) to
reject startup if `repo_name` is already running, and launches
`fx ffx repository server start --foreground` with `start_new_session=True`.
Running in a detached session isolates the child from the controlling
terminal (so closing the terminal does not deliver `SIGHUP` to the child)
and puts the wrapper and server in a dedicated process group for teardown.
On startup failure, timeout, or cancellation, `cleanup_foreground_server()`
terminates the child process group (`SIGTERM`, escalating to `SIGKILL` after
a grace period) and calls `stop()` only if preflight server listing
succeeded and the process had not already exited.
Callers are responsible for cleaning up the returned process on shutdown
(for example, via `cleanup_foreground_server()`).
Args:
name (str | None): Optionally specify the main repository name for this
server. Defaults to an ephemeral name derived from the active build
directory.
timeout (float): The maximum amount of time (in seconds) to wait for the
package server.
Returns:
asyncio.subprocess.Process: An asyncio Process instance for the package
server.
Raises:
PackageServingException: If the package repository is not built, the
repository name is already running, the server exits prematurely, or
startup times out after `timeout` seconds.
build_dir.GetBuildDirectoryError: If no active build directory can be
determined when resolving the repository name or command arguments.
"""
if not is_package_repository_built():
raise PackageServingException("The package repository is not built!")
start_time = time.monotonic()
repo_name = name or ephemeral_repository_name()
fx = FxCmd()
ffx = FfxCmd()
args = await get_arguments(repo_name)
timeout_error = (
f"The package server didn't start within {timeout}s."
+ f"\nCommand: {shlex.join(args)}"
)
def _remaining_budget() -> float:
return timeout - (time.monotonic() - start_time)
def _require_remaining_budget() -> float:
remaining = _remaining_budget()
if remaining <= 0:
raise PackageServingException(timeout_error)
return remaining
remaining = _require_remaining_budget()
pre_running_names = await _get_all_running_server_names_or_none(
min(remaining, _DEFAULT_PROBE_TIMEOUT)
)
if pre_running_names is not None and repo_name in pre_running_names:
raise PackageServingException(
f"Package server {repo_name} is already running."
)
_require_remaining_budget()
allow_stop_by_name = pre_running_names is not None
# Run the wrapper and child ffx server in their own session and process
# group so cleanup can signal both together and interactive terminal SIGINT
# does not prematurely terminate the server.
process = await asyncio.create_subprocess_exec(
*fx.command_line(*ffx.command_line(*args)),
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
start_new_session=True,
)
try:
remaining = _remaining_budget()
if remaining > 0 and await wait_for_package_server(
process, remaining, _CHECK_SERVER_POLLING_INTERVAL
):
return process
except BaseException:
await cleanup_foreground_server(
process,
repo_name,
allow_stop_by_name=(
allow_stop_by_name and process.returncode is None
),
)
raise
timed_out = process.returncode is None
return_code = process.returncode
await cleanup_foreground_server(
process,
repo_name,
allow_stop_by_name=allow_stop_by_name and timed_out,
)
if timed_out:
raise PackageServingException(timeout_error)
raise PackageServingException(
f"The package server exited with code {return_code}."
+ f"\nCommand: {shlex.join(args)}"
)
async def _get_running_server_names_or_empty(
runner: CommandRunner,
timeout: float,
) -> Set[str]:
try:
return await get_running_server_names(
run_command=runner,
timeout=timeout,
)
except PackageServingException:
return frozenset()
async def start_background(
name: str | None = None,
timeout: float = _DEFAULT_BACKGROUND_STARTUP_TIMEOUT,
*,
port: int = 0,
run_command: CommandRunner | None = None,
) -> bool:
"""
Starts a detached background package server via `ffx`.
Args:
name (str | None): Optionally specify the main repository name for this server.
timeout (float): Maximum time in seconds for `ffx` to start the server.
port (int): TCP port to listen on; 0 selects an ephemeral port.
run_command (CommandRunner | None): Optional runner for `fx` subcommands.
Returns:
bool: True if the server started (or was already running for this build
directory), or False if the package repository has not been built.
Raises:
PackageServingException: If starting the server fails or times out.
"""
if not is_package_repository_built():
return False
repo_name = name or ephemeral_repository_name()
runner = run_command or _default_command_runner()
pre_running_names = await get_running_server_names(
run_command=runner,
timeout=timeout,
)
if port == 0 and repo_name in pre_running_names:
return True
args = await get_arguments(repo_name, port=port, background=True)
output = await runner("ffx", *args, timeout=timeout, quiet_mode=True)
if output is None:
raise PackageServingException(
f"Failed to start package server.\nCommand: {shlex.join(args)}"
)
if output.was_timeout:
post_running_names = await _get_running_server_names_or_empty(
runner, timeout
)
# Only stop repo_name if this startup attempt created it for this build
# directory; ffx stops by name globally and would kill another build's
# or a pre-existing healthy server when target RCS probing times out.
if (
repo_name not in pre_running_names
and repo_name in post_running_names
):
await runner(
"ffx",
"repository",
"server",
"stop",
repo_name,
timeout=_DEFAULT_SERVER_STOP_TIMEOUT,
quiet_mode=True,
)
raise PackageServingException(
f"The package server didn't start within {timeout}s.\n"
f"Command: {shlex.join(args)}"
)
if output.return_code != 0:
if port == 0:
running_names = await _get_running_server_names_or_empty(
runner, timeout
)
if repo_name in running_names:
return True
stderr = output.stderr.strip()
detail = f": {stderr}" if stderr else ""
raise PackageServingException(
f"The package server exited with code {output.return_code}{detail}.\n"
f"Command: {shlex.join(args)}"
)
if repo_name not in await get_running_server_names(
run_command=runner,
timeout=timeout,
):
raise PackageServingException(
f"The package server {repo_name} is not running after startup.\n"
f"Command: {shlex.join(args)}"
)
return True
async def stop(name: str | None = None) -> CommandOutput:
"""
Stops running package servers.
Args:
name (str | None): Optionally specify the repository name of the server to terminate.
If omitted, all package servers will be stopped.
Returns:
CommandOutput: Output from `ffx repository server stop`.
"""
process = await FfxCmd().start(
"repository",
"server",
"stop",
*([name] if name else []),
)
try:
return await process.run_to_completion()
except BaseException:
process.kill()
raise
@contextlib.asynccontextmanager
async def run_and_stop_on_exit() -> AsyncGenerator[None, None]:
"""
Starts a package server for the duration of the context block, if one is not currently running,
and stops and deregisters it on exit.
"""
if await is_running():
yield
return
try:
repo_name = ephemeral_repository_name()
print(
"You do not seem to have a package server running. "
+ "A temporary one will be started for the duration of this execution."
)
server = await start(repo_name)
except PackageServingException as e:
raise PackageServingCLIException(
f"Error: {e}\nError: Failed to start the temporary package server. "
+ "You may need to manually start one via `fx serve`."
)
try:
yield
finally:
try:
await deregister(repo_name)
finally:
await cleanup_foreground_server(server, repo_name)