| 1 |
Description: Supervise receive-wal processes through systemd |
| 2 |
When systemd is the running init (/run/systemd/system exists) and the per-server |
| 3 |
unit can be managed, "barman cron" starts each streaming server's WAL receiver |
| 4 |
via the dedicated template unit "barman-receive-wal@<server>.service" instead of |
| 5 |
forking and detaching it with os.setsid(); the same applies to |
| 6 |
Server.restart_processes() (config-switch/config-update). If the unit cannot be |
| 7 |
started (systemd is absent, or the unprivileged barman user is not authorised |
| 8 |
because polkit is not installed) it falls back to forking the receiver as |
| 9 |
before. The choice has no configuration knob; it is detected at run time. |
| 10 |
. |
| 11 |
Under systemd the receiver runs in its own cgroup, supervised and restarted by |
| 12 |
systemd. The forked fallback, when used, is still a child of the cron oneshot, |
| 13 |
so barman.service keeps KillMode=process (Debian #1138696) to let it outlive the |
| 14 |
cron run. |
| 15 |
. |
| 16 |
Stopping is detected, never configured: ProcessManager.kill() reads the |
| 17 |
process cgroup (/proc/<pid>/cgroup) and, if the PID is supervised by a |
| 18 |
barman-receive-wal@ unit, runs "systemctl stop <unit>" instead of signalling |
| 19 |
the PID (which systemd would just revive). When no live receiver is |
| 20 |
found (e.g. the unit is in a Restart= backoff window, where the lock is |
| 21 |
released and the process is briefly gone) the unit is stopped by its |
| 22 |
deterministic name as a fallback. This makes "barman receive-wal --stop" and |
| 23 |
cron's own disable path stop the receiver reliably, with no extra flag and no |
| 24 |
stored state. ("barman receive-wal --reset" is unchanged: as before, it still |
| 25 |
requires the receiver to be stopped first.) |
| 26 |
Author: Marco Nenciarini <[email protected]> |
| 27 |
Forwarded: not-needed |
| 28 |
Last-Update: 2026-06-04 |
| 29 |
--- |
| 30 |
--- a/src/barman/process.py |
| 31 |
+++ b/src/barman/process.py |
| 32 |
@@ -19,7 +19,9 @@ |
| 33 |
import errno |
| 34 |
import logging |
| 35 |
import os |
| 36 |
+import re |
| 37 |
import signal |
| 38 |
+import subprocess |
| 39 |
import time |
| 40 |
from glob import glob |
| 41 |
|
| 42 |
@@ -36,6 +38,128 @@ |
| 43 |
|
| 44 |
_logger = logging.getLogger(__name__) |
| 45 |
|
| 46 |
+# Per-server template unit; full name is "barman-receive-wal@<server>.service". |
| 47 |
+SYSTEMD_RECEIVE_WAL_UNIT_PREFIX = "barman-receive-wal@" |
| 48 |
+ |
| 49 |
+ |
| 50 |
+def systemd_is_running(): |
| 51 |
+ """ |
| 52 |
+ Return whether systemd is the running init system. |
| 53 |
+ |
| 54 |
+ Detected from the presence of ``/run/systemd/system``, the standard way to |
| 55 |
+ tell a systemd boot from a non-systemd one. |
| 56 |
+ |
| 57 |
+ :rtype: bool |
| 58 |
+ """ |
| 59 |
+ return os.path.isdir("/run/systemd/system") |
| 60 |
+ |
| 61 |
+ |
| 62 |
+def systemd_receive_wal_unit(server_name): |
| 63 |
+ """ |
| 64 |
+ Build the ``barman-receive-wal@<server>.service`` unit name for a server. |
| 65 |
+ |
| 66 |
+ The server name is used verbatim as the instance: it round-trips only |
| 67 |
+ because ExecStart reads it back with %i, not %I, so escaping it here would |
| 68 |
+ break the round-trip. Callers must gate on :func:`server_name_is_unit_safe`. |
| 69 |
+ |
| 70 |
+ :param str server_name: the barman server name (must be unit-safe) |
| 71 |
+ :rtype: str |
| 72 |
+ """ |
| 73 |
+ return "%s%s.service" % (SYSTEMD_RECEIVE_WAL_UNIT_PREFIX, server_name) |
| 74 |
+ |
| 75 |
+ |
| 76 |
+# Names safe to use verbatim as the %i instance, i.e. needing no systemd-escape |
| 77 |
+# (%i does not undo escaping). Others are forked rather than run under a unit. |
| 78 |
+_UNIT_SAFE_SERVER_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") |
| 79 |
+ |
| 80 |
+ |
| 81 |
+def server_name_is_unit_safe(server_name): |
| 82 |
+ """ |
| 83 |
+ Return whether the server name is safe to use verbatim as the %i instance |
| 84 |
+ of its ``barman-receive-wal@`` unit (see :data:`_UNIT_SAFE_SERVER_NAME`). |
| 85 |
+ |
| 86 |
+ :param str server_name: the barman server name |
| 87 |
+ :rtype: bool |
| 88 |
+ """ |
| 89 |
+ return bool(_UNIT_SAFE_SERVER_NAME.match(server_name)) |
| 90 |
+ |
| 91 |
+ |
| 92 |
+def _systemd_unit_from_cgroup(cgroup_content): |
| 93 |
+ """ |
| 94 |
+ Parse the content of a ``/proc/<pid>/cgroup`` file and return the |
| 95 |
+ ``barman-receive-wal@`` systemd unit the process belongs to, or ``None``. |
| 96 |
+ |
| 97 |
+ :param str cgroup_content: the content of a cgroup file |
| 98 |
+ :rtype: str|None |
| 99 |
+ """ |
| 100 |
+ unit_re = re.compile( |
| 101 |
+ r"/(%s[^/\s]+\.service)" % re.escape(SYSTEMD_RECEIVE_WAL_UNIT_PREFIX) |
| 102 |
+ ) |
| 103 |
+ for line in cgroup_content.splitlines(): |
| 104 |
+ # cgroup v2: "0::/system.slice/[email protected]" |
| 105 |
+ # cgroup v1: "<n>:name=systemd:/.../[email protected]" |
| 106 |
+ match = unit_re.search(line) |
| 107 |
+ if match: |
| 108 |
+ return match.group(1) |
| 109 |
+ return None |
| 110 |
+ |
| 111 |
+ |
| 112 |
+def systemd_unit_for_pid(pid): |
| 113 |
+ """ |
| 114 |
+ Return the name of the ``barman-receive-wal@`` systemd unit a process |
| 115 |
+ belongs to, or ``None`` if the process is not supervised by such a unit. |
| 116 |
+ |
| 117 |
+ Read from ``/proc/<pid>/cgroup``, so barman stores no state: a process is |
| 118 |
+ under the unit cgroup exactly as long as systemd supervises it. |
| 119 |
+ |
| 120 |
+ :param int pid: the process id to inspect |
| 121 |
+ :rtype: str|None |
| 122 |
+ """ |
| 123 |
+ try: |
| 124 |
+ with open("/proc/%d/cgroup" % pid) as cgroup: |
| 125 |
+ return _systemd_unit_from_cgroup(cgroup.read()) |
| 126 |
+ except (OSError, ValueError): |
| 127 |
+ # No such process, or an unreadable/badly-formed cgroup file: treat |
| 128 |
+ # the process as not supervised by systemd. |
| 129 |
+ return None |
| 130 |
+ |
| 131 |
+ |
| 132 |
+def systemctl(action, unit): |
| 133 |
+ """ |
| 134 |
+ Run ``systemctl <action> <unit>`` and report whether it succeeded. |
| 135 |
+ |
| 136 |
+ Failures are logged, not raised: a failing call is expected (e.g. the |
| 137 |
+ barman user cannot manage the unit because polkit is absent) and the |
| 138 |
+ caller falls back to forking. Raising would make a successful ``barman |
| 139 |
+ cron`` run exit non-zero. |
| 140 |
+ |
| 141 |
+ :param str action: the systemctl verb (e.g. "start" or "stop") |
| 142 |
+ :param str unit: the systemd unit to act upon |
| 143 |
+ :rtype: bool |
| 144 |
+ """ |
| 145 |
+ try: |
| 146 |
+ # --no-ask-password: fail fast rather than block on an interactive |
| 147 |
+ # polkit agent when the barman user is not authorised, so the caller |
| 148 |
+ # can fall back to forking. |
| 149 |
+ result = subprocess.run( |
| 150 |
+ ["systemctl", "--no-ask-password", action, unit], |
| 151 |
+ stdout=subprocess.PIPE, |
| 152 |
+ stderr=subprocess.STDOUT, |
| 153 |
+ ) |
| 154 |
+ except OSError as e: |
| 155 |
+ _logger.warning("Unable to run 'systemctl %s %s': %s", action, unit, e) |
| 156 |
+ return False |
| 157 |
+ if result.returncode != 0: |
| 158 |
+ _logger.warning( |
| 159 |
+ "'systemctl %s %s' failed (exit %s): %s", |
| 160 |
+ action, |
| 161 |
+ unit, |
| 162 |
+ result.returncode, |
| 163 |
+ result.stdout.decode("utf-8", "replace").strip(), |
| 164 |
+ ) |
| 165 |
+ return False |
| 166 |
+ return True |
| 167 |
+ |
| 168 |
|
| 169 |
class ProcessInfo(object): |
| 170 |
""" |
| 171 |
@@ -144,6 +268,18 @@ |
| 172 |
if the process is still alive |
| 173 |
:rtype: bool |
| 174 |
""" |
| 175 |
+ # If the process is supervised by a dedicated systemd unit, stop the |
| 176 |
+ # unit rather than signalling the PID: an externally signalled receiver |
| 177 |
+ # can exit non-zero, which Restart=on-failure would then revive. The |
| 178 |
+ # unit is discovered from the process cgroup, so this works whatever |
| 179 |
+ # requested the stop (a barman cron run disabling streaming, or an |
| 180 |
+ # interactive `barman receive-wal --stop`). |
| 181 |
+ unit = systemd_unit_for_pid(process_info.pid) |
| 182 |
+ if unit: |
| 183 |
+ _logger.debug( |
| 184 |
+ "PID %s is supervised by systemd unit %s", process_info.pid, unit |
| 185 |
+ ) |
| 186 |
+ return systemctl("stop", unit) |
| 187 |
# Try to kill the process |
| 188 |
try: |
| 189 |
_logger.debug("Sending SIGINT to PID %s", process_info.pid) |
| 190 |
--- a/src/barman/server.py |
| 191 |
+++ b/src/barman/server.py |
| 192 |
@@ -99,7 +99,13 @@ |
| 193 |
StandbyPostgreSQLConnection, |
| 194 |
StreamingConnection, |
| 195 |
) |
| 196 |
-from barman.process import ProcessManager |
| 197 |
+from barman.process import ( |
| 198 |
+ ProcessManager, |
| 199 |
+ server_name_is_unit_safe, |
| 200 |
+ systemctl, |
| 201 |
+ systemd_is_running, |
| 202 |
+ systemd_receive_wal_unit, |
| 203 |
+) |
| 204 |
from barman.remote_status import RemoteStatusMixin |
| 205 |
from barman.retention_policies import RetentionPolicy, RetentionPolicyFactory |
| 206 |
from barman.utils import ( |
| 207 |
@@ -3529,10 +3535,16 @@ |
| 208 |
# Execute the archive-wal sub-process |
| 209 |
self.cron_archive_wal(keep_descriptors) |
| 210 |
if self.config.streaming_archiver: |
| 211 |
- # Spawn the receive-wal sub-process |
| 212 |
- self.background_receive_wal(keep_descriptors) |
| 213 |
+ # Skip if a receiver (systemd unit or forked) is already |
| 214 |
+ # running: this avoids re-attempting "systemctl start" |
| 215 |
+ # every run (noisy when the unit cannot be managed, e.g. |
| 216 |
+ # no polkit) and a forked receiver racing a freshly |
| 217 |
+ # started unit for the lock. |
| 218 |
+ if not self.process_manager.list("receive-wal"): |
| 219 |
+ self.start_receive_wal(keep_descriptors) |
| 220 |
else: |
| 221 |
- # Terminate the receive-wal sub-process if present |
| 222 |
+ # Terminate the receiver; Server.kill() stops the |
| 223 |
+ # systemd unit when one supervises it, else signals it. |
| 224 |
self.kill("receive-wal", fail_if_not_present=False) |
| 225 |
|
| 226 |
# Verify backup |
| 227 |
@@ -3668,6 +3680,48 @@ |
| 228 |
"server %s" % self.config.name |
| 229 |
) |
| 230 |
|
| 231 |
+ def start_receive_wal(self, keep_descriptors): |
| 232 |
+ """ |
| 233 |
+ Start the receive-wal process, preferring systemd supervision. |
| 234 |
+ |
| 235 |
+ Start the ``barman-receive-wal@<server>.service`` unit, or fall back to |
| 236 |
+ forking via :meth:`background_receive_wal` when the unit cannot be used |
| 237 |
+ (no systemd, non-unit-safe server name, or polkit not authorising the |
| 238 |
+ barman user). The forked fallback relies on ``KillMode=process`` in |
| 239 |
+ barman.service to outlive the cron oneshot. |
| 240 |
+ |
| 241 |
+ :param bool keep_descriptors: whether to keep subprocess descriptors, |
| 242 |
+ passed through to the forked fallback |
| 243 |
+ """ |
| 244 |
+ if ( |
| 245 |
+ systemd_is_running() |
| 246 |
+ and server_name_is_unit_safe(self.config.name) |
| 247 |
+ and self.systemd_receive_wal() |
| 248 |
+ ): |
| 249 |
+ return |
| 250 |
+ self.background_receive_wal(keep_descriptors) |
| 251 |
+ |
| 252 |
+ def systemd_receive_wal(self): |
| 253 |
+ """ |
| 254 |
+ Start the receive-wal process under its dedicated systemd unit |
| 255 |
+ (``barman-receive-wal@<server>.service``). |
| 256 |
+ |
| 257 |
+ ``systemctl start`` is a no-op when the unit is already running, so |
| 258 |
+ this is safe to call repeatedly. |
| 259 |
+ |
| 260 |
+ :return: whether the unit was started (False if systemctl failed, e.g. |
| 261 |
+ the barman user is not authorised to manage it) |
| 262 |
+ :rtype: bool |
| 263 |
+ """ |
| 264 |
+ unit = systemd_receive_wal_unit(self.config.name) |
| 265 |
+ output.info( |
| 266 |
+ "Starting streaming archiver for server %s via systemd unit %s", |
| 267 |
+ self.config.name, |
| 268 |
+ unit, |
| 269 |
+ log=False, |
| 270 |
+ ) |
| 271 |
+ return systemctl("start", unit) |
| 272 |
+ |
| 273 |
def cron_check_backup(self, keep_descriptors): |
| 274 |
""" |
| 275 |
Method that handles the start of a 'check-backup' sub process |
| 276 |
@@ -4337,6 +4391,17 @@ |
| 277 |
"Cannot terminate process %s(%s)", process.task, process.pid |
| 278 |
) |
| 279 |
return |
| 280 |
+ # No live process found via the lock, but a systemd-supervised receiver |
| 281 |
+ # can be momentarily gone in a Restart= backoff window (the lock is |
| 282 |
+ # released the instant it exits). Stop the unit by its deterministic |
| 283 |
+ # name so systemd does not revive it (systemctl stop is idempotent). |
| 284 |
+ if ( |
| 285 |
+ task == "receive-wal" |
| 286 |
+ and systemd_is_running() |
| 287 |
+ and server_name_is_unit_safe(self.config.name) |
| 288 |
+ ): |
| 289 |
+ systemctl("stop", systemd_receive_wal_unit(self.config.name)) |
| 290 |
+ return |
| 291 |
if fail_if_not_present: |
| 292 |
output.error( |
| 293 |
"Termination of %s failed: no such process for server %s", |
| 294 |
@@ -5494,11 +5559,9 @@ |
| 295 |
""" |
| 296 |
Restart server subprocesses. |
| 297 |
""" |
| 298 |
- # Terminate the receive-wal sub-process if present |
| 299 |
self.kill("receive-wal", fail_if_not_present=False) |
| 300 |
if self.config.streaming_archiver: |
| 301 |
- # Spawn the receive-wal sub-process |
| 302 |
- self.background_receive_wal(keep_descriptors=False) |
| 303 |
+ self.start_receive_wal(keep_descriptors=False) |
| 304 |
|
| 305 |
def get_errors_dst(self, file_name, suffix): |
| 306 |
""" |