diff --git a/CHANGELOG.md b/CHANGELOG.md index 892a094e9..4470d7f2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,19 @@ Entries for 2.6.0 to 2.14.0 were generated from commit subjects. Older entries w ## [Unreleased] +### Added + +- Preparation for a systemd mode of pyobsd: a `mode` key in the `pyobsd` section of the config file, a + `--mode` option and `$PYOBSD_MODE` (`pid` or `systemd`, default `pid`). The systemd mode itself is not + implemented yet, pyobsd exits with an error in it. +- `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. + ### Changed +- pyobsd's PID-file code moved into `PidFileDaemon`, with the parts shared by both modes in + `PyobsDaemonBase`. `PyobsDaemon` stays as an alias. - 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/cli/_cli.py b/pyobs/cli/_cli.py index 074a32c7a..e33c1bcf4 100644 --- a/pyobs/cli/_cli.py +++ b/pyobs/cli/_cli.py @@ -7,6 +7,47 @@ log = logging.getLogger("pyobs") +# how pyobsd runs modules: as daemons with PID files, or as systemd user units +PYOBSD_MODES = ("pid", "systemd") +PYOBSD_MODE_ENV = "PYOBSD_MODE" + + +def find_config_file() -> str | None: + """The shared pyobs config file, or None. The first one found wins.""" + candidates = [ + os.path.expanduser(os.path.join("~", ".config", "pyobs.yaml")), + os.path.join("/", "etc", "pyobs.yaml"), + os.path.join("/", "opt", "pyobs", "storage", "pyobs.yaml"), + ] + for config_file in candidates: + if os.path.exists(config_file): + return config_file + return None + + +def pyobsd_mode(file_config: dict[str, Any]) -> str: + """The pyobsd mode, from $PYOBSD_MODE or else from the "pyobsd" section of the config file, "pid" by default. + + pyobs needs this too (to refuse --pid-file in systemd mode), so it does not use the CLI's own key handling. + + Args: + file_config: Content of the config file, see CLI.file_config. + + Raises: + ValueError: If the mode is unknown. + """ + mode = os.environ.get(PYOBSD_MODE_ENV) + source = "$" + PYOBSD_MODE_ENV + if mode is None: + section = file_config.get("pyobsd") + mode = section.get("mode") if isinstance(section, dict) else None + source = "pyobsd.mode in the config file" + if mode is None: + return "pid" + if mode not in PYOBSD_MODES: + raise ValueError(f"Unknown pyobsd mode {mode!r} in {source}, must be one of: {', '.join(PYOBSD_MODES)}.") + return str(mode) + class CLI: # name of section in configuration file @@ -18,6 +59,8 @@ class CLI: def __init__(self) -> None: """Initializes a new instance of the CLI class.""" self._config: dict[str, Any] = {} + # whole content of the config file, all sections + self.file_config: dict[str, Any] = {} self._parser = argparse.ArgumentParser() def __call__(self) -> None: @@ -45,22 +88,19 @@ def run(self) -> None: def _load_config(self) -> None: """Load config from config file""" - candidates = [ - os.path.expanduser(os.path.join("~", ".config", "pyobs.yaml")), - os.path.join("/", "etc", "pyobs.yaml"), - os.path.join("/", "opt", "pyobs", "storage", "pyobs.yaml"), - ] - for config_file in candidates: - if os.path.exists(config_file): - break - else: + config_file = find_config_file() + if config_file is None: return log.info("Using config file %s.", config_file) with open(config_file) as f: cfg = yaml.safe_load(f) - if cfg is None or self.CONFIG_SECTION not in cfg: - return - self._config.update(**{k: v for k, v in cfg[self.CONFIG_SECTION].items() if k in self.GLOBAL_CONFIG_KEYS}) + if not isinstance(cfg, dict): + return + self.file_config = cfg + section = cfg.get(self.CONFIG_SECTION) + if not isinstance(section, dict): + return + self._config.update(**{k: v for k, v in section.items() if k in self.GLOBAL_CONFIG_KEYS}) def _load_env(self) -> None: """Load config from environment variables.""" diff --git a/pyobs/cli/pyobs.py b/pyobs/cli/pyobs.py index 803cb1bda..c8818c439 100755 --- a/pyobs/cli/pyobs.py +++ b/pyobs/cli/pyobs.py @@ -1,6 +1,7 @@ from __future__ import annotations import os +import sys from typing import TYPE_CHECKING, Any if TYPE_CHECKING: @@ -8,7 +9,7 @@ from pyobs import version -from ._cli import CLI +from ._cli import CLI, PYOBSD_MODE_ENV, pyobsd_mode class PyobsCLI(CLI): @@ -92,6 +93,10 @@ def application(self, **kwargs: Any) -> Application: def run(self) -> None: from pyobs.utils.time import Time + # on a host whose modules run under systemd, a module started with a PID file would run next to its unit + if self._config["pid_file"] is not None: + self._check_pid_mode() + # get full path of config self._config["config"] = os.path.abspath(self._config["config"]) @@ -113,6 +118,18 @@ def run(self) -> None: else: self.application(**self._config).run() + def _check_pid_mode(self) -> None: + """Exits if pyobsd runs the modules on this host under systemd, see pyobsd_mode.""" + try: + mode = pyobsd_mode(self.file_config) + except ValueError as e: + sys.exit(str(e)) + if mode == "systemd": + sys.exit( + "This host runs pyobs modules under systemd (pyobsd mode: systemd), so --pid-file is refused. " + f"Use pyobsd start , or set {PYOBSD_MODE_ENV}=pid to start it with a PID file anyway." + ) + def _start_daemon(self, pid_file: str, **kwargs: Any) -> None: """Start process as a daemon. diff --git a/pyobs/cli/pyobsd.py b/pyobs/cli/pyobsd.py index 0ea10e1e9..f94a0cc69 100755 --- a/pyobs/cli/pyobsd.py +++ b/pyobs/cli/pyobsd.py @@ -1,5 +1,6 @@ from __future__ import annotations +import abc import argparse import glob import json @@ -16,7 +17,7 @@ from pyobs.utils.shutdown import read_stop_deadline, stop_file_for -from ._cli import CLI +from ._cli import CLI, PYOBSD_MODE_ENV, PYOBSD_MODES, pyobsd_mode log = logging.getLogger("pyobs") @@ -42,8 +43,24 @@ class PyobsDaemonCLI(CLI): "chuid", "stop_timeout", ] + # "mode" is not in GLOBAL_CONFIG_KEYS: pyobs reads it too, so it has its own lookup with $PYOBSD_MODE (see + # pyobsd_mode), instead of the generic $PYOBS_ def init_cli(self) -> None: + # mode + try: + mode = pyobsd_mode(self.file_config) + except ValueError as e: + self._parser.error(str(e)) + self._parser.add_argument( + "--mode", + type=str, + choices=PYOBSD_MODES, + default=mode, + help=f"run modules as daemons with PID files, or as systemd user units (default from ${PYOBSD_MODE_ENV} " + "or pyobsd.mode in the config file, else pid)", + ) + # init parser self._parser.add_argument("-p", "--path", type=str, default=self._config.get("path", "/opt/pyobs")) self._parser.add_argument("-c", "--config-path", type=str, default=self._config.get("config_path", "config")) @@ -111,8 +128,12 @@ def init_cli(self) -> None: ) def run(self) -> None: + if self._config["mode"] == "systemd": + print("The systemd mode is not implemented in this version of pyobsd yet.") + sys.exit(1) + # init daemon - daemon = PyobsDaemon( + daemon: PyobsDaemonBase = PidFileDaemon( str(os.path.join(self._config["path"], self._config["config_path"])), str(os.path.join(self._config["path"], self._config["run_path"])), str(os.path.join(self._config["path"], self._config["log_path"])), @@ -143,7 +164,9 @@ def run(self) -> None: daemon.logs(self._config["args"]) -class PyobsDaemon: +class PyobsDaemonBase(abc.ABC): + """What both modes of pyobsd share: module names, config files, process info, logs.""" + def __init__( self, config_path: str, @@ -211,54 +234,14 @@ def _strip_disabled(module: str) -> str: def _config_file(self, module: str) -> str: return os.path.join(self._config_path, module + ".yaml") - def _pid_file(self, module: str) -> str: - return os.path.join(self._run_path, self._strip_disabled(module) + ".pid") - def _log_file(self, module: str) -> str: return os.path.join(self._log_path, self._strip_disabled(module) + ".log") - def _stop_file(self, module: str) -> str: - """Where a stopping module writes its shutdown deadline (see pyobs.utils.shutdown).""" - return stop_file_for(self._pid_file(module)) - def _list_configs(self) -> list[str]: """Return sorted module names from *.yaml files, excluding *.shared.yaml.""" paths = sorted(glob.glob(os.path.join(self._config_path, "*.yaml"))) return [self._module(p) for p in paths if not p.endswith(".shared.yaml")] - def _read_pid(self, module: str) -> int | None: - """Read and return the PID from the module's PID file, or None.""" - pid_file = self._pid_file(module) - if not os.path.exists(pid_file): - return None - try: - with open(pid_file) as f: - return int(f.read().strip()) - except (ValueError, OSError): - return None - - def _is_alive(self, pid: int) -> bool: - try: - os.kill(pid, 0) - return True - except OSError: - return False - - def _running_pid(self, module: str) -> int | None: - """Return the live PID for a module, or None. Cleans up stale PID files.""" - pid = self._read_pid(module) - if pid is None: - return None - if self._is_alive(pid): - return pid - # stale PID file — remove it, together with a stop file the process may have left behind - self._remove_run_files(module) - return None - - def _stop_deadline(self, module: str) -> float | None: - """The deadline a running module wrote into its stop file, or None if it is not stopping.""" - return read_stop_deadline(self._stop_file(module)) - def _process_info(self, pid: int) -> dict[str, Any]: """Return uptime (seconds) and rss_mb for a running PID. No CPU -- that needs a shared sampling window across all processes, see _sample_cpu_percent.""" @@ -306,6 +289,99 @@ def _fmt_uptime(seconds: float) -> str: return f"{d}d {h:02d}:{m:02d}:{s:02d}" return f"{h:02d}:{m:02d}:{s:02d}" + @staticmethod + def _fmt_wait(seconds: float) -> str: + seconds = max(0, int(seconds)) + if seconds < 120: + return f"{seconds} s" + return f"{round(seconds / 60)} min" + + # ── public commands ─────────────────────────────────────────────────────── + + @abc.abstractmethod + def start(self, modules: list[str] | None = None) -> None: + """Starts the given modules, or all enabled ones.""" + + @abc.abstractmethod + def stop(self, modules: list[str] | None = None, wait: bool = True) -> None: + """Stops the given modules, or all running ones. With wait=False, does not wait for them to exit.""" + + @abc.abstractmethod + def kill(self, modules: list[str] | None = None) -> None: + """Kills the given modules, or all running ones, without a shutdown.""" + + @abc.abstractmethod + def restart(self, modules: list[str] | None = None, kill: bool = False) -> None: + """Restarts the given modules. With kill=True, kills them instead of a normal stop.""" + + @abc.abstractmethod + def status(self, print_json: bool = False, cpu_interval: float | None = None) -> None: + """Prints the status of all modules.""" + + def list_modules(self) -> None: + print("\n".join(self._list_configs())) + + def logs(self, args: list[str]) -> None: + """Show/follow module logs by exec'ing into journalctl.""" + match_args = ["SYSLOG_IDENTIFIER=pyobs"] + remainder = list(args) + # "--" may have been auto-inserted by main() to work around argparse.REMAINDER + # refusing to swallow a leading flag (e.g. "pyobsd logs -f") — drop it here. + if remainder and remainder[0] == "--": + remainder.pop(0) + if remainder and remainder[0] in self._list_configs(): + match_args.append(f"PYOBS_MODULE={remainder.pop(0)}") + cmd = ["journalctl", *match_args, *remainder] + if self._verbose: + print(f"[DEBUG] Executing: {' '.join(cmd)}") + os.execvp("journalctl", cmd) + + +class PidFileDaemon(PyobsDaemonBase): + """PID-file mode: runs modules as daemons (pyobs --pid-file) and tracks them by their PID files.""" + + # ── helpers ─────────────────────────────────────────────────────────────── + + def _pid_file(self, module: str) -> str: + return os.path.join(self._run_path, self._strip_disabled(module) + ".pid") + + def _stop_file(self, module: str) -> str: + """Where a stopping module writes its shutdown deadline (see pyobs.utils.shutdown).""" + return stop_file_for(self._pid_file(module)) + + def _read_pid(self, module: str) -> int | None: + """Read and return the PID from the module's PID file, or None.""" + pid_file = self._pid_file(module) + if not os.path.exists(pid_file): + return None + try: + with open(pid_file) as f: + return int(f.read().strip()) + except (ValueError, OSError): + return None + + def _is_alive(self, pid: int) -> bool: + try: + os.kill(pid, 0) + return True + except OSError: + return False + + def _running_pid(self, module: str) -> int | None: + """Return the live PID for a module, or None. Cleans up stale PID files.""" + pid = self._read_pid(module) + if pid is None: + return None + if self._is_alive(pid): + return pid + # stale PID file — remove it, together with a stop file the process may have left behind + self._remove_run_files(module) + return None + + def _stop_deadline(self, module: str) -> float | None: + """The deadline a running module wrote into its stop file, or None if it is not stopping.""" + return read_stop_deadline(self._stop_file(module)) + # ── public commands ─────────────────────────────────────────────────────── def start(self, modules: list[str] | None = None) -> None: @@ -465,24 +541,6 @@ def status(self, print_json: bool = False, cpu_interval: float | None = None) -> else: print(f"{module:<30} {'stopped':<8}") - def list_modules(self) -> None: - print("\n".join(self._list_configs())) - - def logs(self, args: list[str]) -> None: - """Show/follow module logs by exec'ing into journalctl.""" - match_args = ["SYSLOG_IDENTIFIER=pyobs"] - remainder = list(args) - # "--" may have been auto-inserted by main() to work around argparse.REMAINDER - # refusing to swallow a leading flag (e.g. "pyobsd logs -f") — drop it here. - if remainder and remainder[0] == "--": - remainder.pop(0) - if remainder and remainder[0] in self._list_configs(): - match_args.append(f"PYOBS_MODULE={remainder.pop(0)}") - cmd = ["journalctl", *match_args, *remainder] - if self._verbose: - print(f"[DEBUG] Executing: {' '.join(cmd)}") - os.execvp("journalctl", cmd) - # ── process management ──────────────────────────────────────────────────── def _start_service(self, module: str) -> None: @@ -514,10 +572,15 @@ def _start_service(self, module: str) -> None: if self._verbose: print(f"[DEBUG] Executing: {' '.join(cmd)}") + # pyobs refuses --pid-file if the config says systemd mode, but this pyobsd runs in PID-file mode (e.g. with + # --mode pid), so pass that on + env = os.environ.copy() + env[PYOBSD_MODE_ENV] = "pid" kwargs: dict[str, Any] = dict( stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, # detach from pyobsd's process group + env=env, ) if self._user: kwargs["user"] = self._user @@ -527,11 +590,9 @@ def _start_service(self, module: str) -> None: # Mimic `su`/`sudo -u` and set HOME/USER/LOGNAME for the target user. try: pw = pwd.getpwnam(self._user) - env = os.environ.copy() env["HOME"] = pw.pw_dir env["USER"] = self._user env["LOGNAME"] = self._user - kwargs["env"] = env except KeyError: self._error(f"User {self._user!r} not found.") if self._group: @@ -635,12 +696,9 @@ def _remove_run_files(self, module: str) -> None: except OSError: pass - @staticmethod - def _fmt_wait(seconds: float) -> str: - seconds = max(0, int(seconds)) - if seconds < 120: - return f"{seconds} s" - return f"{round(seconds / 60)} min" + +# old name, from before there were two modes +PyobsDaemon = PidFileDaemon def main() -> None: diff --git a/specs/plans/2026-11-25-pyobsd-systemd-mode.md b/specs/plans/2026-11-25-pyobsd-systemd-mode.md index 24ff9e9e9..0063ddda5 100644 --- a/specs/plans/2026-11-25-pyobsd-systemd-mode.md +++ b/specs/plans/2026-11-25-pyobsd-systemd-mode.md @@ -261,9 +261,9 @@ repo for the PID-file mode. If a host has it installed, it has to be disabled wh - [x] pyobs-core tests for the PID-file mode before refactoring (`tests/cli/test_pyobsd_pidmode.py`, e9a0084a). - [x] pyobs-web-admin, old mode: non-blocking stop, `stopping` state, kill, restart as a background job (2.4.0). -- [ ] pyobs-core: `mode` config key, `--mode` option and `PYOBSD_MODE`, mode-specific backends in `pyobsd.py` +- [x] pyobs-core: `mode` config key, `--mode` option and `PYOBSD_MODE`, mode-specific backends in `pyobsd.py` (current code moves into the PID-file backend without behavior changes). -- [ ] pyobs-core: guard in `PyobsCLI.run()` against `--pid-file` in systemd mode, sharing the mode lookup with +- [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). - [ ] pyobs-core: unit rendering, unit file sync, enable sync, linger check, user manager selection. diff --git a/tests/cli/test_mode.py b/tests/cli/test_mode.py new file mode 100644 index 000000000..8bc7b8ff4 --- /dev/null +++ b/tests/cli/test_mode.py @@ -0,0 +1,182 @@ +"""Tests for the pyobsd mode switch (pyobsd.mode, --mode, $PYOBSD_MODE) and for pyobs refusing --pid-file in +systemd mode, 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._cli import pyobsd_mode +from pyobs.cli.pyobs import PyobsCLI +from pyobs.cli.pyobsd import PidFileDaemon, PyobsDaemon + + +@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) + + +def use_config(monkeypatch, tmp_path: Path, text: str) -> None: + config_file = tmp_path / "pyobs.yaml" + config_file.write_text(text) + monkeypatch.setattr(_cli, "find_config_file", lambda: str(config_file)) + + +# ── pyobsd_mode ────────────────────────────────────────────────────────────── + + +def test_mode_default() -> None: + assert pyobsd_mode({}) == "pid" + assert pyobsd_mode({"pyobsd": {"path": "/opt/pyobs"}}) == "pid" + assert pyobsd_mode({"pyobsd": None}) == "pid" + + +def test_mode_from_config() -> None: + assert pyobsd_mode({"pyobsd": {"mode": "systemd"}}) == "systemd" + assert pyobsd_mode({"pyobsd": {"mode": "pid"}}) == "pid" + + +def test_mode_env_overrides_config(monkeypatch) -> None: + monkeypatch.setenv("PYOBSD_MODE", "pid") + assert pyobsd_mode({"pyobsd": {"mode": "systemd"}}) == "pid" + monkeypatch.setenv("PYOBSD_MODE", "systemd") + assert pyobsd_mode({}) == "systemd" + + +def test_mode_unknown(monkeypatch) -> None: + with pytest.raises(ValueError, match="pyobsd.mode in the config file"): + pyobsd_mode({"pyobsd": {"mode": "docker"}}) + monkeypatch.setenv("PYOBSD_MODE", "docker") + with pytest.raises(ValueError, match=r"\$PYOBSD_MODE"): + pyobsd_mode({}) + + +# ── config file ────────────────────────────────────────────────────────────── + + +def test_load_config_keeps_whole_file(monkeypatch, tmp_path) -> None: + """Each CLI takes only its own keys from its section, but file_config has all of it.""" + use_config(monkeypatch, tmp_path, "pyobs:\n log_level: debug\n unknown: 1\npyobsd:\n mode: systemd\n") + cli = PyobsCLI() + cli._load_config() + assert cli._config == {"log_level": "debug"} + assert cli.file_config["pyobsd"] == {"mode": "systemd"} + + +def test_load_config_empty_file(monkeypatch, tmp_path) -> None: + use_config(monkeypatch, tmp_path, "") + cli = PyobsCLI() + cli._load_config() + assert cli._config == {} + assert cli.file_config == {} + + +# ── pyobs: guard against --pid-file ────────────────────────────────────────── + + +def run_pyobs(monkeypatch, mocker, *args: str) -> tuple[Any, Any]: + start_daemon = mocker.patch.object(PyobsCLI, "_start_daemon") + application = mocker.patch.object(PyobsCLI, "application") + monkeypatch.setattr(sys, "argv", ["pyobs", *args, "module.yaml"]) + PyobsCLI()() + return start_daemon, application + + +def test_pyobs_pid_file_in_pid_mode(monkeypatch, mocker) -> None: + start_daemon, _ = run_pyobs(monkeypatch, mocker, "--pid-file", "run/module.pid") + start_daemon.assert_called_once() + + +def test_pyobs_pid_file_refused_in_systemd_mode(monkeypatch, mocker, tmp_path) -> None: + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: systemd\n") + with pytest.raises(SystemExit) as exc: + run_pyobs(monkeypatch, mocker, "--pid-file", "run/module.pid") + assert "pyobsd mode: systemd" in str(exc.value.code) + assert "PYOBSD_MODE=pid" in str(exc.value.code) + + +def test_pyobs_pid_file_allowed_with_env_override(monkeypatch, mocker, tmp_path) -> None: + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: systemd\n") + monkeypatch.setenv("PYOBSD_MODE", "pid") + start_daemon, _ = run_pyobs(monkeypatch, mocker, "--pid-file", "run/module.pid") + start_daemon.assert_called_once() + + +def test_pyobs_foreground_in_systemd_mode(monkeypatch, mocker, tmp_path) -> None: + """Without --pid-file (as the unit starts it), pyobs runs in systemd mode.""" + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: systemd\n") + start_daemon, application = run_pyobs(monkeypatch, mocker) + start_daemon.assert_not_called() + application.return_value.run.assert_called_once() + + +def test_pyobs_pid_file_with_unknown_mode(monkeypatch, mocker, tmp_path) -> None: + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: docker\n") + with pytest.raises(SystemExit) as exc: + run_pyobs(monkeypatch, mocker, "--pid-file", "run/module.pid") + assert "Unknown pyobsd mode 'docker'" in str(exc.value.code) + + +# ── pyobsd: --mode ─────────────────────────────────────────────────────────── + + +def run_pyobsd(monkeypatch, tmp_path, *args: str) -> None: + monkeypatch.setattr( + sys, "argv", ["pyobsd", "-p", str(tmp_path), "-c", "config", "-r", "run", "-l", "log", *args, "list"] + ) + pyobsd.main() + + +def test_pyobsd_old_name() -> None: + assert PyobsDaemon is PidFileDaemon + + +def test_pyobsd_pid_mode_by_default(monkeypatch, mocker, tmp_path) -> None: + list_modules = mocker.patch.object(PidFileDaemon, "list_modules") + run_pyobsd(monkeypatch, tmp_path) + list_modules.assert_called_once() + + +def test_pyobsd_systemd_mode_not_implemented(monkeypatch, mocker, tmp_path, capsys) -> None: + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: systemd\n") + list_modules = mocker.patch.object(PidFileDaemon, "list_modules") + with pytest.raises(SystemExit) as exc: + run_pyobsd(monkeypatch, tmp_path) + assert exc.value.code == 1 + assert "systemd mode is not implemented" in capsys.readouterr().out + list_modules.assert_not_called() + + +def test_pyobsd_mode_option_overrides_config(monkeypatch, mocker, tmp_path) -> None: + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: systemd\n") + list_modules = mocker.patch.object(PidFileDaemon, "list_modules") + run_pyobsd(monkeypatch, tmp_path, "--mode", "pid") + list_modules.assert_called_once() + + +def test_pyobsd_unknown_mode_in_config(monkeypatch, tmp_path, capsys) -> None: + use_config(monkeypatch, tmp_path, "pyobsd:\n mode: docker\n") + with pytest.raises(SystemExit) as exc: + run_pyobsd(monkeypatch, tmp_path) + assert exc.value.code == 2 + assert "Unknown pyobsd mode 'docker'" in capsys.readouterr().err + + +def test_pid_mode_passes_mode_to_pyobs(mocker, tmp_path) -> None: + """pyobsd in PID-file mode (e.g. --mode pid on a systemd host) sets $PYOBSD_MODE=pid for the module, so the + guard in pyobs lets it start.""" + popen = mocker.patch("subprocess.Popen") + mocker.patch.object(PidFileDaemon, "_read_pid", return_value=12345) + mocker.patch.object(PidFileDaemon, "_is_alive", return_value=True) + daemon = PidFileDaemon(str(tmp_path / "config"), str(tmp_path / "run"), str(tmp_path / "log")) + daemon._pyobs_exec = "pyobs" + + daemon._start_service("camera") + + assert popen.call_args.kwargs["env"]["PYOBSD_MODE"] == "pid"