From 5ddbfd6cfbf3f0bd6e896ec68f51aebbb529b1ec Mon Sep 17 00:00:00 2001 From: Tim-Oliver Husser Date: Wed, 25 Nov 2026 21:21:23 +0100 Subject: [PATCH] Module side of the systemd mode: READY=1, no duplicate journal lines, pyobsd exec - Application sends READY=1 once the module is open (no-op without $NOTIFY_SOCKET). - With --syslog, no stderr handler if stderr is the journal ($JOURNAL_STREAM compared with stderr's device and inode, since children inherit it). - pyobsd exec (hidden): finds .yaml or _.yaml and execs pyobs in the foreground with the options from the pyobsd config, without --pid-file. Argument building is shared with the PID-file mode. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + pyobs/application.py | 33 +++- pyobs/cli/pyobsd.py | 70 ++++++--- specs/plans/2026-11-25-pyobsd-systemd-mode.md | 6 +- tests/cli/test_pyobsd_exec.py | 128 +++++++++++++++ tests/test_application_systemd.py | 148 ++++++++++++++++++ 6 files changed, 366 insertions(+), 26 deletions(-) create mode 100644 tests/cli/test_pyobsd_exec.py create mode 100644 tests/test_application_systemd.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4470d7f2b..c71e4ec09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,11 +17,18 @@ Entries for 2.6.0 to 2.14.0 were generated from commit subjects. Older entries w - `pyobs --pid-file` refuses to start if the config file sets `pyobsd.mode: systemd`, so that a module can't run twice on a host whose modules run under systemd. `PYOBSD_MODE=pid` overrides it. pyobsd in PID-file mode sets it for the modules it starts. +- A module sends `READY=1` to systemd once it is open (only if `$NOTIFY_SOCKET` is set), for units with + `Type=notify`. +- `pyobsd exec ` (internal, not in the help) replaces pyobsd with `pyobs` running the module in the + foreground, with the options from the pyobsd config and without a PID file. It finds `.yaml` or + `_.yaml`. The systemd unit will run this. ### Changed - pyobsd's PID-file code moved into `PidFileDaemon`, with the parts shared by both modes in `PyobsDaemonBase`. `PyobsDaemon` stays as an alias. +- With `--syslog`, a module no longer logs to stderr if stderr is the systemd journal (`$JOURNAL_STREAM` + matches stderr), so lines don't show up twice in the journal. - The warm-up progress line on close shows the sensor temperature and power the last step was planned with, instead of reading them again after the step. The done line says why the warm-up ended (setpoint reached, or cooler idle, with the readings). `RampStep` has a new field `idle`. diff --git a/pyobs/application.py b/pyobs/application.py index bc4b4d55f..6ad829fe5 100644 --- a/pyobs/application.py +++ b/pyobs/application.py @@ -4,6 +4,7 @@ import os import platform import signal +import sys import warnings from collections.abc import Awaitable, Callable from io import StringIO @@ -99,6 +100,23 @@ class InfluxLogConfig(TypedDict): bucket: str +def _stderr_is_journal() -> bool: + """Whether stderr is connected to the systemd journal. + + systemd sets $JOURNAL_STREAM to ":" of that stream. Child processes inherit the variable even if + their stderr goes elsewhere, so it is compared with stderr's own device and inode (see systemd.exec(5), + $JOURNAL_STREAM).""" + value = os.environ.get("JOURNAL_STREAM") + if not value: + return False + try: + device, inode = (int(v) for v in value.split(":")) + st = os.fstat(sys.stderr.fileno()) + except (ValueError, OSError, AttributeError): + return False + return (st.st_dev, st.st_ino) == (device, inode) + + class Application: """Class for initializing and shutting down a pyobs process.""" @@ -179,11 +197,13 @@ def __init__( handlers: list[logging.Handler] = [] - # create stdout logging handler - stream_handler = logging.StreamHandler() - stream_handler.setFormatter(formatter) - stream_handler.addFilter(module_name_filter) - handlers.append(stream_handler) + # create stderr logging handler, unless stderr goes to the journal anyway (under systemd), where the + # journal handler below already writes every line, with PYOBS_MODULE + if not (syslog and _stderr_is_journal()): + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + stream_handler.addFilter(module_name_filter) + handlers.append(stream_handler) # create file logging handler, if log file is given if log_file is not None: @@ -444,6 +464,9 @@ async def _main(self) -> None: await self._module.startup() log.info("Started successfully.") + # under systemd (Type=notify), the start only counts as done once the module is open. No-op otherwise + shutdown.notify("READY=1") + # run module await self._module.main() diff --git a/pyobs/cli/pyobsd.py b/pyobs/cli/pyobsd.py index f94a0cc69..02f0c8a17 100755 --- a/pyobs/cli/pyobsd.py +++ b/pyobs/cli/pyobsd.py @@ -95,7 +95,8 @@ def init_cli(self) -> None: self._parser.add_argument("-v", "--verbose", action="store_true") # commands - sp = self._parser.add_subparsers(dest="command") + # metavar lists the commands for users, without the internal "exec" + sp = self._parser.add_subparsers(dest="command", metavar="{start,stop,restart,status,list,logs}") sp.add_parser("start", help="start modules").add_argument("modules", type=str, nargs="*") stop_parser = sp.add_parser("stop", help="stop modules") stop_parser.add_argument("modules", type=str, nargs="*") @@ -126,9 +127,12 @@ def init_cli(self) -> None: sp.add_parser("logs", help="show/follow module logs via journalctl").add_argument( "args", nargs=argparse.REMAINDER, help="[module] [journalctl arguments...]" ) + # internal: what the systemd unit runs, replaces pyobsd with "pyobs" for the module, in the foreground + sp.add_parser("exec").add_argument("module", type=str) def run(self) -> None: - if self._config["mode"] == "systemd": + # "exec" is the same in both modes + if self._config["mode"] == "systemd" and self._config["command"] != "exec": print("The systemd mode is not implemented in this version of pyobsd yet.") sys.exit(1) @@ -162,6 +166,8 @@ def run(self) -> None: daemon.list_modules() case "logs": daemon.logs(self._config["args"]) + case "exec": + daemon.exec_module(self._config["module"]) class PyobsDaemonBase(abc.ABC): @@ -318,6 +324,49 @@ def restart(self, modules: list[str] | None = None, kill: bool = False) -> None: def status(self, print_json: bool = False, cpu_interval: float | None = None) -> None: """Prints the status of all modules.""" + def _pyobs_args(self, module: str) -> list[str]: + """Options and config file for running a module with pyobs, the same in both modes.""" + args = [ + "--log-level", + self._log_level, + # the module ends itself if its shutdown takes longer than this (or what it asked for) + "--stop-timeout", + str(self._stop_timeout), + self._config_file(module), + ] + if self._file_log: + os.makedirs(self._log_path, exist_ok=True) + args += ["--log-file", self._log_file(module)] + if self._syslog: + args.append("--syslog") + return args + + def _find_config(self, name: str) -> str | None: + """The config of a module by its active name: "", or else the disabled "_". A leading + underscore in name is ignored. None if neither exists.""" + active = self._strip_disabled(name) + configs = self._list_configs() + for module in (active, "_" + active): + if module in configs: + return module + return None + + def exec_module(self, name: str) -> None: + """Replaces this process with pyobs running the module in the foreground, without a PID file. + + This is what the systemd unit runs ("pyobsd exec %i", with the active name). The process keeps its PID, + so pyobs is the unit's main process and can notify systemd. Runs as the calling user, chuid is not used. + """ + module = self._find_config(name) + if module is None: + self._error(f"Module {name!r} does not exist.") + return + cmd = [self._pyobs_exec, *self._pyobs_args(module)] + if self._verbose: + print(f"[DEBUG] Executing: {' '.join(cmd)}") + sys.stdout.flush() + os.execv(self._pyobs_exec, cmd) + def list_modules(self) -> None: print("\n".join(self._list_configs())) @@ -552,22 +601,7 @@ def _start_service(self, module: str) -> None: except FileNotFoundError: pass - cmd = [ - self._pyobs_exec, - "--pid-file", - self._pid_file(module), - "--log-level", - self._log_level, - # the module ends itself if its shutdown takes longer than this (or what it asked for) - "--stop-timeout", - str(self._stop_timeout), - self._config_file(module), - ] - if self._file_log: - os.makedirs(self._log_path, exist_ok=True) - cmd += ["--log-file", self._log_file(module)] - if self._syslog: - cmd.append("--syslog") + cmd = [self._pyobs_exec, "--pid-file", self._pid_file(module), *self._pyobs_args(module)] if self._verbose: print(f"[DEBUG] Executing: {' '.join(cmd)}") diff --git a/specs/plans/2026-11-25-pyobsd-systemd-mode.md b/specs/plans/2026-11-25-pyobsd-systemd-mode.md index 0063ddda5..1d83ffb0e 100644 --- a/specs/plans/2026-11-25-pyobsd-systemd-mode.md +++ b/specs/plans/2026-11-25-pyobsd-systemd-mode.md @@ -265,11 +265,11 @@ repo for the PID-file mode. If a host has it installed, it has to be disabled wh (current code moves into the PID-file backend without behavior changes). - [x] pyobs-core: guard in `PyobsCLI.run()` against `--pid-file` in systemd mode, sharing the mode lookup with pyobsd. -- [ ] pyobs-core: `pyobsd exec ` (config lookup by active name, options from the pyobsd config). +- [x] pyobs-core: `pyobsd exec ` (config lookup by active name, options from the pyobsd config). - [ ] pyobs-core: unit rendering, unit file sync, enable sync, linger check, user manager selection. - [ ] pyobs-core: systemd backend for start/stop/restart/status, extended `status --json`. -- [ ] pyobs-core: skip the stderr `StreamHandler` when `syslog` and `JOURNAL_STREAM` are set. -- [ ] pyobs-core: send `READY=1` after the module is open (systemd mode only). +- [x] pyobs-core: skip the stderr `StreamHandler` when `syslog` and `JOURNAL_STREAM` are set. +- [x] pyobs-core: send `READY=1` after the module is open (systemd mode only). - [ ] pyobs-core tests: unit rendering, sync (tmp dirs, mocked `systemctl`), status JSON parsing, guard, `exec` lookup. - [ ] pyobs-core docs: `cli.rst`, `installing.rst` (linger, where to put `mode`, reboot drop-in, switching a diff --git a/tests/cli/test_pyobsd_exec.py b/tests/cli/test_pyobsd_exec.py new file mode 100644 index 000000000..f302956d9 --- /dev/null +++ b/tests/cli/test_pyobsd_exec.py @@ -0,0 +1,128 @@ +"""Tests for "pyobsd exec ", which the systemd unit runs (see specs/plans/2026-11-25-pyobsd-systemd-mode.md).""" + +from __future__ import annotations + +import sys +from pathlib import Path +from typing import Any + +import pytest + +from pyobs.cli import _cli, pyobsd +from pyobs.cli.pyobsd import PidFileDaemon + + +@pytest.fixture(autouse=True) +def no_host_config(monkeypatch) -> None: + """Keep the config file and $PYOBSD_MODE of the machine running the tests out of them.""" + monkeypatch.delenv("PYOBSD_MODE", raising=False) + monkeypatch.setattr(_cli, "find_config_file", lambda: None) + + +@pytest.fixture +def execv(mocker): + return mocker.patch.object(pyobsd.os, "execv") + + +def make_daemon(tmp_path: Path, configs: list[str], **kwargs: Any) -> PidFileDaemon: + config = tmp_path / "config" + config.mkdir() + for name in configs: + (config / name).write_text("class: pyobs.modules.test.StandAlone\n") + daemon = PidFileDaemon(str(config), str(tmp_path / "run"), str(tmp_path / "log"), **kwargs) + daemon._pyobs_exec = "/usr/bin/pyobs" + return daemon + + +def test_exec(tmp_path, execv) -> None: + daemon = make_daemon(tmp_path, ["camera.yaml"]) + + daemon.exec_module("camera") + + execv.assert_called_once_with( + "/usr/bin/pyobs", + ["/usr/bin/pyobs", "--log-level", "info", "--stop-timeout", "30.0", str(tmp_path / "config" / "camera.yaml")], + ) + + +def test_exec_options(tmp_path, execv) -> None: + """Same options as in PID-file mode, but no --pid-file, so pyobs stays in the foreground.""" + daemon = make_daemon(tmp_path, ["camera.yaml"], log_level="debug", syslog=True, file_log=True, stop_timeout=60) + + daemon.exec_module("camera") + + cmd = execv.call_args.args[1] + assert "--pid-file" not in cmd + assert cmd[1:] == [ + "--log-level", + "debug", + "--stop-timeout", + "60", + str(tmp_path / "config" / "camera.yaml"), + "--log-file", + str(tmp_path / "log" / "camera.log"), + "--syslog", + ] + assert (tmp_path / "log").is_dir() + + +@pytest.mark.parametrize("name", ["camera", "_camera"]) +def test_exec_disabled(tmp_path, execv, name) -> None: + """The unit runs with the active name, also for a disabled config (started without enabling it). The log + file keeps the active name.""" + daemon = make_daemon(tmp_path, ["_camera.yaml"], file_log=True) + + daemon.exec_module(name) + + cmd = execv.call_args.args[1] + assert str(tmp_path / "config" / "_camera.yaml") in cmd + assert str(tmp_path / "log" / "camera.log") in cmd + + +def test_exec_prefers_enabled(tmp_path, execv) -> None: + daemon = make_daemon(tmp_path, ["camera.yaml", "_camera.yaml"]) + + daemon.exec_module("camera") + + assert str(tmp_path / "config" / "camera.yaml") in execv.call_args.args[1] + + +def test_exec_ignores_shared(tmp_path, execv) -> None: + daemon = make_daemon(tmp_path, ["camera.shared.yaml"]) + + with pytest.raises(SystemExit): + daemon.exec_module("camera.shared") + execv.assert_not_called() + + +def test_exec_unknown(tmp_path, execv, capsys) -> None: + daemon = make_daemon(tmp_path, ["camera.yaml"]) + + with pytest.raises(SystemExit) as exc: + daemon.exec_module("dome") + + assert exc.value.code == 1 + assert "Module 'dome' does not exist." in capsys.readouterr().out + execv.assert_not_called() + + +def test_cli_exec_in_systemd_mode(tmp_path, execv, monkeypatch) -> None: + """exec works in systemd mode, the other commands don't yet.""" + (tmp_path / "config").mkdir() + (tmp_path / "config" / "camera.yaml").write_text("class: pyobs.modules.test.StandAlone\n") + monkeypatch.setenv("PYOBSD_MODE", "systemd") + monkeypatch.setattr(sys, "argv", ["pyobsd", "-p", str(tmp_path), "exec", "camera"]) + + pyobsd.main() + + execv.assert_called_once() + assert str(tmp_path / "config" / "camera.yaml") in execv.call_args.args[1] + + +def test_exec_not_in_help(monkeypatch, capsys) -> None: + monkeypatch.setattr(sys, "argv", ["pyobsd", "--help"]) + with pytest.raises(SystemExit): + pyobsd.main() + out = capsys.readouterr().out + assert "{start,stop,restart,status,list,logs}" in out + assert "exec" not in out diff --git a/tests/test_application_systemd.py b/tests/test_application_systemd.py new file mode 100644 index 000000000..48813fa86 --- /dev/null +++ b/tests/test_application_systemd.py @@ -0,0 +1,148 @@ +"""Tests for running a module under systemd: READY=1 once the module is open, and no stderr log handler when +stderr goes to the journal anyway (see specs/plans/2026-11-25-pyobsd-systemd-mode.md).""" + +from __future__ import annotations + +import logging +import os +import sys +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import logging_journald +import pytest + +from pyobs import application +from pyobs.application import Application, _stderr_is_journal +from pyobs.modules import Module + +# ── READY=1 ────────────────────────────────────────────────────────────────── + + +def make_module(**kwargs: Any) -> MagicMock: + module = MagicMock(spec=Module) + module.startup = AsyncMock(**kwargs) + module.main = AsyncMock() + module.close = AsyncMock() + return module + + +def make_app(module: MagicMock) -> Application: + app = Application.__new__(Application) + app._module = module + app._module_factory = None + return app + + +@pytest.mark.asyncio +async def test_ready_after_startup(mocker) -> None: + notify = mocker.patch.object(application.shutdown, "notify") + module = make_module() + # READY=1 must come after startup() and before main() + module.main.side_effect = lambda: notify.assert_called_once_with("READY=1") + + await make_app(module)._main() + + module.startup.assert_awaited_once() + module.main.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_no_ready_if_startup_fails(mocker) -> None: + notify = mocker.patch.object(application.shutdown, "notify") + module = make_module(side_effect=RuntimeError("no camera")) + + await make_app(module)._main() + + notify.assert_not_called() + module.main.assert_not_awaited() + + +# ── stderr and the journal ─────────────────────────────────────────────────── + + +@pytest.fixture +def stderr_file(tmp_path: Path, monkeypatch): + """Returns a function that makes a file stderr and returns the JOURNAL_STREAM value systemd would set for it. + It has to be called in the test itself, pytest's output capturing replaces sys.stderr after the fixtures.""" + with open(tmp_path / "stderr", "w") as f: + + def use() -> str: + monkeypatch.setattr(sys, "stderr", f) + st = os.fstat(f.fileno()) + return f"{st.st_dev}:{st.st_ino}" + + yield use + + +def test_stderr_is_journal(stderr_file, monkeypatch) -> None: + monkeypatch.setenv("JOURNAL_STREAM", stderr_file()) + assert _stderr_is_journal() + + +def test_stderr_is_journal_not_set(stderr_file, monkeypatch) -> None: + stderr_file() + monkeypatch.delenv("JOURNAL_STREAM", raising=False) + assert not _stderr_is_journal() + + +def test_stderr_is_journal_inherited(stderr_file, monkeypatch) -> None: + """A child process inherits JOURNAL_STREAM, but its stderr may go elsewhere.""" + device, inode = stderr_file().split(":") + monkeypatch.setenv("JOURNAL_STREAM", f"{device}:{int(inode) + 1}") + assert not _stderr_is_journal() + + +@pytest.mark.parametrize("value", ["", "garbage", "1:2:3", "a:b"]) +def test_stderr_is_journal_invalid(stderr_file, monkeypatch, value) -> None: + stderr_file() + monkeypatch.setenv("JOURNAL_STREAM", value) + assert not _stderr_is_journal() + + +def test_stderr_is_journal_no_stderr(monkeypatch) -> None: + monkeypatch.setenv("JOURNAL_STREAM", "1:2") + monkeypatch.setattr(sys, "stderr", None) + assert not _stderr_is_journal() + + +class FakeJournaldLogHandler(logging.Handler): + """Stands in for logging_journald's handler, so the tests don't need a journal.""" + + LEVELS: dict[int, int] = {} + + def __init__(self, identifier: str = "", **kwargs: Any) -> None: + super().__init__() + + +def handler_types(monkeypatch, mocker, tmp_path: Path, syslog: bool) -> list[str]: + monkeypatch.setattr(logging_journald, "JournaldLogHandler", FakeJournaldLogHandler) + basic_config = mocker.patch.object(application.logging, "basicConfig") + config = tmp_path / "test_module.yaml" + config.write_text("class: pyobs.modules.Module\n") + + app = Application(config=str(config), syslog=syslog) + app._loop.close() + + return [type(h).__name__ for h in basic_config.call_args.kwargs["handlers"]] + + +@pytest.mark.asyncio +async def test_no_stream_handler_under_journal(stderr_file, monkeypatch, mocker, tmp_path) -> None: + monkeypatch.setenv("JOURNAL_STREAM", stderr_file()) + assert handler_types(monkeypatch, mocker, tmp_path, syslog=True) == ["PyobsJournaldLogHandler"] + + +@pytest.mark.asyncio +async def test_stream_handler_without_syslog(stderr_file, monkeypatch, mocker, tmp_path) -> None: + """Without --syslog, stderr is the only way into the journal, so it stays.""" + monkeypatch.setenv("JOURNAL_STREAM", stderr_file()) + assert handler_types(monkeypatch, mocker, tmp_path, syslog=False) == ["StreamHandler"] + + +@pytest.mark.asyncio +async def test_stream_handler_outside_journal(stderr_file, monkeypatch, mocker, tmp_path) -> None: + stderr_file() + monkeypatch.delenv("JOURNAL_STREAM", raising=False) + assert handler_types(monkeypatch, mocker, tmp_path, syslog=True) == ["StreamHandler", "PyobsJournaldLogHandler"]