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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
64 changes: 52 additions & 12 deletions pyobs/cli/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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."""
Expand Down
19 changes: 18 additions & 1 deletion pyobs/cli/pyobs.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from __future__ import annotations

import os
import sys
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from pyobs.application import Application

from pyobs import version

from ._cli import CLI
from ._cli import CLI, PYOBSD_MODE_ENV, pyobsd_mode


class PyobsCLI(CLI):
Expand Down Expand Up @@ -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"])

Expand All @@ -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 <module>, 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.

Expand Down
Loading
Loading