Description: Supervise receive-wal processes through systemd When systemd is the running init (/run/systemd/system exists) and the per-server unit can be managed, "barman cron" starts each streaming server's WAL receiver via the dedicated template unit "barman-receive-wal@.service" instead of forking and detaching it with os.setsid(); the same applies to Server.restart_processes() (config-switch/config-update). If the unit cannot be started (systemd is absent, or the unprivileged barman user is not authorised because polkit is not installed) it falls back to forking the receiver as before. The choice has no configuration knob; it is detected at run time. . Under systemd the receiver runs in its own cgroup, supervised and restarted by systemd. The forked fallback, when used, is still a child of the cron oneshot, so barman.service keeps KillMode=process (Debian #1138696) to let it outlive the cron run. . Stopping is detected, never configured: ProcessManager.kill() reads the process cgroup (/proc//cgroup) and, if the PID is supervised by a barman-receive-wal@ unit, runs "systemctl stop " instead of signalling the PID (which systemd would just revive). When no live receiver is found (e.g. the unit is in a Restart= backoff window, where the lock is released and the process is briefly gone) the unit is stopped by its deterministic name as a fallback. This makes "barman receive-wal --stop" and cron's own disable path stop the receiver reliably, with no extra flag and no stored state. ("barman receive-wal --reset" is unchanged: as before, it still requires the receiver to be stopped first.) Author: Marco Nenciarini Forwarded: not-needed Last-Update: 2026-06-04 --- --- a/src/barman/process.py +++ b/src/barman/process.py @@ -19,7 +19,9 @@ import errno import logging import os +import re import signal +import subprocess import time from glob import glob @@ -36,6 +38,128 @@ _logger = logging.getLogger(__name__) +# Per-server template unit; full name is "barman-receive-wal@.service". +SYSTEMD_RECEIVE_WAL_UNIT_PREFIX = "barman-receive-wal@" + + +def systemd_is_running(): + """ + Return whether systemd is the running init system. + + Detected from the presence of ``/run/systemd/system``, the standard way to + tell a systemd boot from a non-systemd one. + + :rtype: bool + """ + return os.path.isdir("/run/systemd/system") + + +def systemd_receive_wal_unit(server_name): + """ + Build the ``barman-receive-wal@.service`` unit name for a server. + + The server name is used verbatim as the instance: it round-trips only + because ExecStart reads it back with %i, not %I, so escaping it here would + break the round-trip. Callers must gate on :func:`server_name_is_unit_safe`. + + :param str server_name: the barman server name (must be unit-safe) + :rtype: str + """ + return "%s%s.service" % (SYSTEMD_RECEIVE_WAL_UNIT_PREFIX, server_name) + + +# Names safe to use verbatim as the %i instance, i.e. needing no systemd-escape +# (%i does not undo escaping). Others are forked rather than run under a unit. +_UNIT_SAFE_SERVER_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") + + +def server_name_is_unit_safe(server_name): + """ + Return whether the server name is safe to use verbatim as the %i instance + of its ``barman-receive-wal@`` unit (see :data:`_UNIT_SAFE_SERVER_NAME`). + + :param str server_name: the barman server name + :rtype: bool + """ + return bool(_UNIT_SAFE_SERVER_NAME.match(server_name)) + + +def _systemd_unit_from_cgroup(cgroup_content): + """ + Parse the content of a ``/proc//cgroup`` file and return the + ``barman-receive-wal@`` systemd unit the process belongs to, or ``None``. + + :param str cgroup_content: the content of a cgroup file + :rtype: str|None + """ + unit_re = re.compile( + r"/(%s[^/\s]+\.service)" % re.escape(SYSTEMD_RECEIVE_WAL_UNIT_PREFIX) + ) + for line in cgroup_content.splitlines(): + # cgroup v2: "0::/system.slice/barman-receive-wal@main.service" + # cgroup v1: ":name=systemd:/.../barman-receive-wal@x.service" + match = unit_re.search(line) + if match: + return match.group(1) + return None + + +def systemd_unit_for_pid(pid): + """ + Return the name of the ``barman-receive-wal@`` systemd unit a process + belongs to, or ``None`` if the process is not supervised by such a unit. + + Read from ``/proc//cgroup``, so barman stores no state: a process is + under the unit cgroup exactly as long as systemd supervises it. + + :param int pid: the process id to inspect + :rtype: str|None + """ + try: + with open("/proc/%d/cgroup" % pid) as cgroup: + return _systemd_unit_from_cgroup(cgroup.read()) + except (OSError, ValueError): + # No such process, or an unreadable/badly-formed cgroup file: treat + # the process as not supervised by systemd. + return None + + +def systemctl(action, unit): + """ + Run ``systemctl `` and report whether it succeeded. + + Failures are logged, not raised: a failing call is expected (e.g. the + barman user cannot manage the unit because polkit is absent) and the + caller falls back to forking. Raising would make a successful ``barman + cron`` run exit non-zero. + + :param str action: the systemctl verb (e.g. "start" or "stop") + :param str unit: the systemd unit to act upon + :rtype: bool + """ + try: + # --no-ask-password: fail fast rather than block on an interactive + # polkit agent when the barman user is not authorised, so the caller + # can fall back to forking. + result = subprocess.run( + ["systemctl", "--no-ask-password", action, unit], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + except OSError as e: + _logger.warning("Unable to run 'systemctl %s %s': %s", action, unit, e) + return False + if result.returncode != 0: + _logger.warning( + "'systemctl %s %s' failed (exit %s): %s", + action, + unit, + result.returncode, + result.stdout.decode("utf-8", "replace").strip(), + ) + return False + return True + class ProcessInfo(object): """ @@ -144,6 +268,18 @@ if the process is still alive :rtype: bool """ + # If the process is supervised by a dedicated systemd unit, stop the + # unit rather than signalling the PID: an externally signalled receiver + # can exit non-zero, which Restart=on-failure would then revive. The + # unit is discovered from the process cgroup, so this works whatever + # requested the stop (a barman cron run disabling streaming, or an + # interactive `barman receive-wal --stop`). + unit = systemd_unit_for_pid(process_info.pid) + if unit: + _logger.debug( + "PID %s is supervised by systemd unit %s", process_info.pid, unit + ) + return systemctl("stop", unit) # Try to kill the process try: _logger.debug("Sending SIGINT to PID %s", process_info.pid) --- a/src/barman/server.py +++ b/src/barman/server.py @@ -99,7 +99,13 @@ StandbyPostgreSQLConnection, StreamingConnection, ) -from barman.process import ProcessManager +from barman.process import ( + ProcessManager, + server_name_is_unit_safe, + systemctl, + systemd_is_running, + systemd_receive_wal_unit, +) from barman.remote_status import RemoteStatusMixin from barman.retention_policies import RetentionPolicy, RetentionPolicyFactory from barman.utils import ( @@ -3529,10 +3535,16 @@ # Execute the archive-wal sub-process self.cron_archive_wal(keep_descriptors) if self.config.streaming_archiver: - # Spawn the receive-wal sub-process - self.background_receive_wal(keep_descriptors) + # Skip if a receiver (systemd unit or forked) is already + # running: this avoids re-attempting "systemctl start" + # every run (noisy when the unit cannot be managed, e.g. + # no polkit) and a forked receiver racing a freshly + # started unit for the lock. + if not self.process_manager.list("receive-wal"): + self.start_receive_wal(keep_descriptors) else: - # Terminate the receive-wal sub-process if present + # Terminate the receiver; Server.kill() stops the + # systemd unit when one supervises it, else signals it. self.kill("receive-wal", fail_if_not_present=False) # Verify backup @@ -3668,6 +3680,48 @@ "server %s" % self.config.name ) + def start_receive_wal(self, keep_descriptors): + """ + Start the receive-wal process, preferring systemd supervision. + + Start the ``barman-receive-wal@.service`` unit, or fall back to + forking via :meth:`background_receive_wal` when the unit cannot be used + (no systemd, non-unit-safe server name, or polkit not authorising the + barman user). The forked fallback relies on ``KillMode=process`` in + barman.service to outlive the cron oneshot. + + :param bool keep_descriptors: whether to keep subprocess descriptors, + passed through to the forked fallback + """ + if ( + systemd_is_running() + and server_name_is_unit_safe(self.config.name) + and self.systemd_receive_wal() + ): + return + self.background_receive_wal(keep_descriptors) + + def systemd_receive_wal(self): + """ + Start the receive-wal process under its dedicated systemd unit + (``barman-receive-wal@.service``). + + ``systemctl start`` is a no-op when the unit is already running, so + this is safe to call repeatedly. + + :return: whether the unit was started (False if systemctl failed, e.g. + the barman user is not authorised to manage it) + :rtype: bool + """ + unit = systemd_receive_wal_unit(self.config.name) + output.info( + "Starting streaming archiver for server %s via systemd unit %s", + self.config.name, + unit, + log=False, + ) + return systemctl("start", unit) + def cron_check_backup(self, keep_descriptors): """ Method that handles the start of a 'check-backup' sub process @@ -4337,6 +4391,17 @@ "Cannot terminate process %s(%s)", process.task, process.pid ) return + # No live process found via the lock, but a systemd-supervised receiver + # can be momentarily gone in a Restart= backoff window (the lock is + # released the instant it exits). Stop the unit by its deterministic + # name so systemd does not revive it (systemctl stop is idempotent). + if ( + task == "receive-wal" + and systemd_is_running() + and server_name_is_unit_safe(self.config.name) + ): + systemctl("stop", systemd_receive_wal_unit(self.config.name)) + return if fail_if_not_present: output.error( "Termination of %s failed: no such process for server %s", @@ -5494,11 +5559,9 @@ """ Restart server subprocesses. """ - # Terminate the receive-wal sub-process if present self.kill("receive-wal", fail_if_not_present=False) if self.config.streaming_archiver: - # Spawn the receive-wal sub-process - self.background_receive_wal(keep_descriptors=False) + self.start_receive_wal(keep_descriptors=False) def get_errors_dst(self, file_name, suffix): """