Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <module>` (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 `<module>.yaml` or
`_<module>.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`.
Expand Down
33 changes: 28 additions & 5 deletions pyobs/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import platform
import signal
import sys
import warnings
from collections.abc import Awaitable, Callable
from io import StringIO
Expand Down Expand Up @@ -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 "<device>:<inode>" 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."""

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()

Expand Down
70 changes: 52 additions & 18 deletions pyobs/cli/pyobsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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="*")
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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: "<name>", or else the disabled "_<name>". 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()))

Expand Down Expand Up @@ -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)}")
Expand Down
6 changes: 3 additions & 3 deletions specs/plans/2026-11-25-pyobsd-systemd-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <module>` (config lookup by active name, options from the pyobsd config).
- [x] pyobs-core: `pyobsd exec <module>` (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
Expand Down
128 changes: 128 additions & 0 deletions tests/cli/test_pyobsd_exec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""Tests for "pyobsd exec <module>", 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
Loading
Loading