blob: 806f2eab4a39ae7d472fd1c2886073d853aeb96b [file] [edit]
#!/usr/bin/env fuchsia-vendored-python
# 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.
"""Runs a command with a Python forkserver.
Starts server.py in its own process group, tells the command where to find it
through $FX_PYTHON_FORKSERVER_SOCKET, runs the command, and stops the server
afterwards (process-group SIGTERM, then SIGKILL after 5 s). Python scripts that
the command starts use the server by going through client.py.
top_build_wrap.py adds this layer to builds when //.fx/config/python_forkserver
turns the forkserver on (see setting.py).
"""
import argparse
import contextlib
import os
import signal
import subprocess
import sys
import uuid
from collections.abc import Iterator, Mapping, Sequence
from pathlib import Path
from typing import NamedTuple
from build.scripts import signal_utils
from build.scripts.python_forkserver import client
_SCRIPT_PATH = Path(__file__).resolve()
_SCRIPT_NAME = _SCRIPT_PATH.name
_SERVER = _SCRIPT_PATH.parent / "server.py"
LOGS_SUBDIR: str = "python_forkserver"
_LOG_NAME: str = "python_forkserver.log"
_STATS_JSON_NAME: str = "python_forkserver.stats.json"
# Tells client.py where to find the server.
ENV_SOCKET = client.SOCKET_ENV.decode()
class ServerError(Exception):
"""server.py couldn't start."""
class ServerInfo(NamedTuple):
"""A running server.py and the abstract socket name it listens on."""
process: subprocess.Popen[bytes]
socket_name: str
def msg(text: str) -> None:
"""Prints a message to stderr, prefixed with the script's name."""
print(f"[{_SCRIPT_NAME}] {text}", file=sys.stderr)
def forkserver_artifacts(log_dir: Path) -> dict[str, Path]:
"""Returns the paths of the files the server writes to `log_dir`."""
return {
"log": log_dir / _LOG_NAME,
"stats": log_dir / _STATS_JSON_NAME,
}
def start_server(
build_dir: Path, log_dir: Path, env: Mapping[str, str]
) -> ServerInfo:
"""Starts server.py in its own process group and waits until it's bound.
The server runs scripts with its own interpreter flags, so it starts with
the flags that build actions use (common_python_args in BUILDCONFIG.gn).
It warms up in, and serves actions from, `build_dir`, so it starts there.
Returns:
The server process and the abstract socket name it listens on.
Raises:
ServerError: The server exited before it was ready.
"""
socket_name = f"fx-python-forkserver-{os.getuid()}-{os.getpid()}-{uuid.uuid4().hex[:8]}"
ready_r, ready_w = os.pipe()
try:
with open(log_dir / _LOG_NAME, "wb") as log:
server = subprocess.Popen(
[
sys.executable,
"-S",
"-W",
"error::SyntaxWarning",
str(_SERVER),
"--socket-name",
socket_name,
"--stats",
str((log_dir / _STATS_JSON_NAME).absolute()),
"--ready-fd",
str(ready_w),
],
cwd=build_dir,
env=dict(env),
stdin=subprocess.DEVNULL,
stdout=log,
stderr=subprocess.STDOUT,
pass_fds=(ready_w,),
process_group=0,
)
finally:
os.close(ready_w)
# Wait for the server's ready byte, which it sends once it has bound the
# socket and warmed up (server.py --ready-fd). If the server exits first,
# the read returns b"" instead: the server held the only other copy of
# the write end, which we closed above.
try:
ready = os.read(ready_r, 1)
finally:
os.close(ready_r)
if not ready:
# The pipe closed without the ready byte: the server exited first.
raise ServerError(
f"server.py exited with status {server.wait()} before it was "
f"ready; see {log_dir / _LOG_NAME}"
)
return ServerInfo(server, socket_name)
def stop_server(server: subprocess.Popen[bytes]) -> None:
"""Stops server.py and its forkers: SIGTERM, then SIGKILL after 5 s."""
with contextlib.suppress(ProcessLookupError):
os.killpg(server.pid, signal.SIGTERM)
try:
if server.wait(timeout=5) == 0:
return
except subprocess.TimeoutExpired:
pass
# The server is stuck or died early, and may have left forkers behind.
with contextlib.suppress(ProcessLookupError):
os.killpg(server.pid, signal.SIGKILL)
server.wait()
@contextlib.contextmanager
def running_server(
build_dir: Path, log_dir: Path, env: Mapping[str, str]
) -> Iterator[ServerInfo]:
"""Runs server.py for the duration of the `with` block.
Raises:
ServerError: The server exited before it was ready.
"""
server = start_server(build_dir, log_dir, env)
try:
yield server
finally:
stop_server(server.process)
def _parse_args(
argv: Sequence[str],
) -> tuple[argparse.Namespace, list[str]]:
parser = argparse.ArgumentParser(
description=(__doc__ or "").splitlines()[0],
usage="%(prog)s [options] -- command [args...]",
)
parser.add_argument(
"--build-dir",
type=Path,
required=True,
help="The build directory, where the server runs actions.",
)
parser.add_argument(
"--logdir",
type=Path,
required=True,
help="Directory for the server's log and stats.",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Print verbose execution details.",
)
args_list = list(argv)
wrapped_command: list[str]
if "--" in args_list:
sep_idx = args_list.index("--")
opt_args = args_list[:sep_idx]
wrapped_command = args_list[sep_idx + 1 :]
else:
opt_args = args_list
wrapped_command = []
return parser.parse_args(opt_args), wrapped_command
def main(argv: Sequence[str], env: Mapping[str, str]) -> int:
args, command = _parse_args(argv)
if not command:
msg("error: A command must be specified after '--'.")
return 2
args.logdir.mkdir(parents=True, exist_ok=True)
# Re-arm client.py's warning about running without a server, so that an
# action in this build that can't find the server warns again.
(args.build_dir / client.SLOW_PATH_MARKER).unlink(missing_ok=True)
try:
with running_server(args.build_dir, args.logdir, env) as server:
return signal_utils.run_command(
command,
env={**env, ENV_SOCKET: server.socket_name},
separate_pgrp=True,
verbose=args.verbose,
)
except ServerError as err:
msg(f"error: {err}")
return 1
except signal_utils.BuildInterruptedError as err:
return err.return_code
if __name__ == "__main__":
sys.exit(main(sys.argv[1:], os.environ))