diff --git a/src/hhstream_live/__main__.py b/src/hhstream_live/__main__.py index b0b3dd9..3c0bb80 100644 --- a/src/hhstream_live/__main__.py +++ b/src/hhstream_live/__main__.py @@ -17,12 +17,16 @@ from __future__ import annotations import argparse import logging +import signal import sys +import threading from . import phrase as phrase_mod from .publisher import DEFAULT_FPS, FPS_CAP, StreamRegistry, StreamSpec from .server import DEFAULT_HOST, DEFAULT_PORT, LiveServer +log = logging.getLogger("hhstream.live") + #: The session's own capture command, JPEG for the same reason the host config #: spells it out: a 1280x720 JPEG q80 is ~46 ms and the point is a video, not a #: slideshow. `-c` asks grim to include the cursor. @@ -53,13 +57,27 @@ def parse_stream(arg: str) -> tuple[str, str]: raise argparse.ArgumentTypeError(str(exc)) from exc +def _add_log_level(parser: argparse.ArgumentParser, default: str) -> None: + """Put `--log-level` on a parser. + + It is a global option, but it has to exist on the subparsers too: with no + subcommand the whole line is parsed as `serve ...`, and `serve` is then the + parser that sees it. `SUPPRESS` as the subparser default is what stops + `hhstream-live --log-level debug serve` from being reset to `info` -- a + subparser argument that defaults to `SUPPRESS` and is not supplied leaves + the namespace alone. + """ + parser.add_argument("--log-level", default=default, + choices=["debug", "info", "warning", "error"]) + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="hhstream-live", description=__doc__) - parser.add_argument("--log-level", default="info", - choices=["debug", "info", "warning", "error"]) + _add_log_level(parser, "info") subs = parser.add_subparsers(dest="command") serve = subs.add_parser("serve", help="run the web app (default)") + _add_log_level(serve, argparse.SUPPRESS) serve.add_argument("--port", type=int, default=DEFAULT_PORT, help=f"the one port every stream shares (default {DEFAULT_PORT})") serve.add_argument("--bind", default=DEFAULT_HOST, @@ -76,11 +94,36 @@ def build_parser() -> argparse.ArgumentParser: "only shape that survives words starting with '-')") gen = subs.add_parser("phrase", help="print a fresh phrase and exit") + _add_log_level(gen, argparse.SUPPRESS) gen.add_argument("--count", type=int, default=1) return parser +#: The subcommands, named here because the default one is chosen before the +#: parser runs. See `parse_args`. +COMMANDS = ("serve", "phrase") + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + """Parse the command line, defaulting to `serve`. + + `serve` is the default, and its options live on its own subparser, so the + word has to be *inserted* rather than filled in afterwards: a namespace from + the top-level parser has no `capture_command`, no `port` and no `stream`, and + `cmd_serve` would die on the first attribute it read. Inserting it has to + happen before parsing, too -- `hhstream-live --port 9999` would otherwise be + rejected for an unknown `--port` before anything could be defaulted. + + `--help` is left alone so that a bare `hhstream-live --help` still shows the + program's own help rather than `serve`'s. + """ + raw = list(sys.argv[1:] if argv is None else argv) + if not any(word in COMMANDS or word in ("-h", "--help") for word in raw): + raw = ["serve", *raw] + return build_parser().parse_args(raw) + + def make_registry(streams: list[tuple[str, str]], capture_base: list[str], fps: int) -> StreamRegistry: from hhstream.capture import CommandCapture @@ -97,42 +140,58 @@ def cmd_serve(args: argparse.Namespace) -> int: registry = make_registry(args.stream, capture_base, args.fps) server = LiveServer(registry, host=args.bind, port=args.port) - print(f"landing page: http://{server.address}:{args.port}/", file=sys.stderr) - if not args.stream: - print("no --stream given; only the landing page will answer", file=sys.stderr) - server.start() # raises OSError loudly if the port is taken - for phrase in registry.phrases(): - print(server.url_for(phrase)) - sys.stdout.flush() + # A service is stopped with SIGTERM, not with Ctrl-C: without a handler the + # default action kills the process outright and `server.stop` never runs, so + # the listener and the capture threads go down with no ordering at all. + # Installed *before* the listener exists, so there is no window in which a + # supervisor's very first signal is the fatal one. + stopping = threading.Event() + previous = None + + def _request_stop(signum, frame) -> None: # noqa: ARG001 - handler signature + stopping.set() try: - import time + previous = signal.signal(signal.SIGTERM, _request_stop) + except ValueError: + # Not the main thread: an embedder's problem to solve, not ours. + log.debug("SIGTERM handler not installed (not the main thread)") - while True: - time.sleep(3600) + try: + server.start() # raises OSError loudly if the port is taken + # Printed after `start`, because a requested port of 0 only has an answer + # once it is bound. `describe_bind` names the real bind, so `0.0.0.0` is + # not reported as loopback just because that is the address you click. + print(server.describe_bind(), file=sys.stderr) + print(f"landing page: http://{server.address}:{server.port}/", file=sys.stderr) + if not args.stream: + print("no --stream given; only the landing page will answer", + file=sys.stderr) + for phrase in registry.phrases(): + print(server.url_for(phrase)) + sys.stdout.flush() + stopping.wait() + print("stopping", file=sys.stderr) except KeyboardInterrupt: print("stopping", file=sys.stderr) finally: + if previous is not None: + signal.signal(signal.SIGTERM, previous) server.stop() return 0 def main(argv: list[str] | None = None) -> int: - parser = build_parser() - args = parser.parse_args(argv) + args = parse_args(argv) logging.basicConfig( - level=getattr(logging, (args.log_level or "info").upper()), + level=getattr(logging, (getattr(args, "log_level", None) or "info").upper()), format="%(asctime)s %(levelname)s %(name)s: %(message)s", ) - command = args.command or "serve" - if command == "phrase": + if args.command == "phrase": for _ in range(args.count): print(phrase_mod.generate()) return 0 - if command == "serve": - return cmd_serve(args) - parser.error(f"unknown command {command!r}") # pragma: no cover - return 2 + return cmd_serve(args) if __name__ == "__main__": diff --git a/tests/live/test_live_cli.py b/tests/live/test_live_cli.py index a4ce249..f4ad0b6 100644 --- a/tests/live/test_live_cli.py +++ b/tests/live/test_live_cli.py @@ -3,10 +3,22 @@ from __future__ import annotations import io +import os +import pathlib +import re +import signal +import subprocess +import sys +import time from contextlib import redirect_stdout import pytest -from hhstream_live.__main__ import DEFAULT_CAPTURE, capture_argv, main, parse_stream +from hhstream_live.__main__ import (DEFAULT_CAPTURE, capture_argv, main, parse_args, + parse_stream) + +#: What `hhstream-live phrase` must print: four alphabetic words and a tail. +PHRASE_SHAPE = re.compile(r"^[a-z]+(?:-[a-z]+){3}-[a-z0-9]{5}$") +_SRC = pathlib.Path(__file__).resolve().parents[2] / "src" def test_capture_command_is_aimed_by_inserting_the_output_before_stdout(): @@ -40,7 +52,9 @@ def test_the_phrase_subcommand_prints_a_phrase(): with redirect_stdout(out): assert main(["phrase"]) == 0 printed = out.getvalue().strip() - assert printed.count("-") == 4 # four words + tail + # Not just `count("-") == 4`: a hyphenated word on the list would satisfy + # the count with five words and four hyphens in the wrong places. + assert PHRASE_SHAPE.match(printed), printed def test_the_phrase_subcommand_can_print_several(): @@ -48,3 +62,64 @@ def test_the_phrase_subcommand_can_print_several(): with redirect_stdout(out): main(["phrase", "--count", "3"]) assert len(out.getvalue().split()) == 3 + + +# ---- the default subcommand, and shutdown ---------------------------------- + +def test_a_bare_command_line_means_serve(): + """`hhstream-live` with no subcommand is `hhstream-live serve`. + + The serve options live on the `serve` subparser, so the namespace has to be + the subparser's; reading `capture_command` off the top-level one is the + `AttributeError` this guards. + """ + args = parse_args([]) + assert args.command == "serve" + assert args.capture_command is None + assert args.port and args.bind and args.stream == [] + assert args.log_level == "info" + + +def test_serve_options_work_without_naming_the_subcommand(): + args = parse_args(["--port", "0", "--bind", "0.0.0.0"]) + assert (args.command, args.port, args.bind) == ("serve", 0, "0.0.0.0") + + +def test_a_global_option_survives_the_subcommand(): + """`--log-level` is on both parsers; the subparser must not reset it.""" + assert parse_args(["--log-level", "debug"]).log_level == "debug" + assert parse_args(["--log-level", "debug", "serve"]).log_level == "debug" + assert parse_args(["--log-level", "debug", "phrase"]).log_level == "debug" + + +def test_a_bare_run_serves_and_sigterm_stops_it_cleanly(): + """The whole path: no subcommand, then the signal a service is stopped with. + + `SIGTERM`'s default action kills the process outright, so without a handler + `server.stop()` never runs and the exit status is a signal, not a 0. + """ + env = dict(os.environ, PYTHONPATH=os.pathsep.join( + [str(_SRC), os.environ.get("PYTHONPATH", "")]).rstrip(os.pathsep)) + proc = subprocess.Popen( + [sys.executable, "-m", "hhstream_live", "--port", "0"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, + ) + try: + deadline = time.monotonic() + 20 + banner = "" + while "landing page:" not in banner and time.monotonic() < deadline: + line = proc.stderr.readline() + if not line: + break + banner += line + assert "landing page:" in banner, banner + assert "bound to 127.0.0.1:" in banner, banner + + proc.send_signal(signal.SIGTERM) + out, err = proc.communicate(timeout=20) + except BaseException: + proc.kill() + proc.communicate() + raise + assert proc.returncode == 0, (proc.returncode, banner, err) + assert "Traceback" not in err, err