Compare commits

...
11 Commits
Author SHA1 Message Date
christianmanivong 5985c87cc8 Merge pull request 'fix(services-restart): an LXC container's processes are left out, 4.46.0 (NetOrk/netork#2750)' (#134) from feature/services-need-restart-lxc into main
driver / types (push) Successful in 1m3s
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m27s
driver / test (3.13) (push) Successful in 1m22s
driver / lowest (push) Successful in 50s
driver / build (push) Successful in 35s
driver / security (push) Successful in 1m8s
driver / publish (push) Successful in 33s
CI / driver (push) Successful in 11m9s
2026-11-26 18:56:35 +00:00
christianmanivong 6c90373c80 Merge remote-tracking branch 'origin/main' into feature/services-need-restart-lxc
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m20s
driver / lowest (pull_request) Successful in 42s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Successful in 2m42s
driver / publish (pull_request) Skipped
2026-11-26 19:46:33 +01:00
christianmanivong ddc9316fb5 Merge pull request 'feat(services-restart): the services that still run replaced code (NetOrk/netork#2700)' (#132) from feature/services-need-restart into main
driver / types (push) Successful in 1m6s
driver / standard (push) Successful in 21s
driver / lint (push) Successful in 17s
driver / test (3.12) (push) Successful in 1m31s
driver / test (3.13) (push) Successful in 1m19s
driver / lowest (push) Successful in 51s
driver / build (push) Successful in 33s
driver / security (push) Successful in 1m6s
driver / publish (push) Successful in 32s
CI / driver (push) Successful in 3m44s
2026-11-26 18:31:38 +00:00
christianmanivong f8c456d784 chore(release): 4.46.0
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m22s
driver / test (3.13) (pull_request) Successful in 1m17s
driver / lowest (pull_request) Successful in 55s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m58s
driver / publish (pull_request) Skipped
2026-11-26 19:25:55 +01:00
christianmanivong a5275d4c4d Merge NAPALM/napalm-device-types#132 (4.45.0) into feature/services-need-restart-lxc 2026-11-26 19:25:55 +01:00
christianmanivong a38f07513f chore(release): 4.45.0
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 1m16s
driver / test (3.12) (pull_request) Successful in 1m20s
driver / lowest (pull_request) Successful in 41s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 2m44s
driver / publish (pull_request) Skipped
2026-11-26 19:24:36 +01:00
christianmanivong ddcd9ebc0a Merge remote-tracking branch 'origin/main' into feature/services-need-restart
# Conflicts:
#	CHANGELOG.md
2026-11-26 19:24:17 +01:00
christianmanivong 494b9ed046 refactor(services-restart): its shapes live in its own module, within the quality ratchet
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 1m26s
driver / test (3.12) (pull_request) Successful in 1m30s
driver / lowest (pull_request) Successful in 46s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m7s
CI / driver (pull_request) Successful in 2m56s
driver / publish (pull_request) Skipped
models.py had grown past its recorded size; ServicesRestartDict and
RestartProcessDict move to services_restart, exported from the package.
2026-11-26 19:06:23 +01:00
christianmanivong 67ffee4e9e fix(services-restart): an LXC container's processes are left out (NetOrk/netork#2750)
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m23s
driver / test (3.13) (pull_request) Successful in 1m22s
driver / lowest (pull_request) Successful in 44s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Failing after 3m0s
driver / publish (pull_request) Skipped
On a Proxmox node the /proc scan sees every container's processes: an LXC
container updates itself, and its own systemd's units (lxc/<vmid>/ns/...
.service) would read as the host's services needing a restart. They are
left out like Docker's and Podman's: /lxc/<name>/ (Proxmox VE, cgroup v1)
and /lxc.payload.<name>/ (LXC 4 and later). The monitor, lxc.monitor/<name>,
runs the host's lxc-start and still counts.
2026-11-26 18:53:07 +01:00
christianmanivong 5517464e1f chore(release): 4.44.0
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Failing after 20s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m14s
driver / test (3.12) (pull_request) Successful in 1m23s
driver / lowest (pull_request) Successful in 37s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Failing after 2m36s
driver / publish (pull_request) Skipped
2026-11-26 17:39:04 +01:00
christianmanivong 9c889f3715 feat(services-restart): the services that still run replaced code (NetOrk/netork#2700)
ServicesRestartMixin.get_services_need_restart reads, as root and in one
fixed read-only command, which systemd services still run code an update
replaced on disk: needs-restarting -s on the dnf family, else needrestart
in batch list-only mode (-r l and NEEDRESTART_MODE=l, whatever its config
says), else the processes whose /proc/<pid>/maps maps deleted code, each
named by its cgroup's service as the listening sockets are. A refused root
raises instead of reading clean.
2026-11-26 17:39:04 +01:00
7 changed files with 610 additions and 1 deletions

No files matched your search

+27
View File
@@ -7,6 +7,33 @@ recorded here; their history is the git log.
## [Unreleased]
## [4.46.0] - 2026-11-26
### Fixed
- `get_services_need_restart()` leaves an LXC container's processes out of the `/proc` scan,
as it does Docker's and Podman's (NetOrk/netork#2750). On a Proxmox VE node a container
updates itself, and its own systemd's units (`/lxc/<vmid>/ns/system.slice/nginx.service`)
read as host services that need a restart. Left out: `/lxc/<name>/` (Proxmox VE, cgroup v1)
and `/lxc.payload.<name>/` (LXC 4 and later); `/lxc.monitor/<name>` still counts, since
`lxc-start` runs the host's binary.
## [4.45.0] - 2026-11-26
### Added
- `ServicesRestartMixin.get_services_need_restart()`: the systemd services that still run
code an update replaced on disk, so they keep the old library until they restart
(NetOrk/netork#2700). One fixed, read-only command as root: `needs-restarting -s` (the dnf
family), else `needrestart -b -r l` (Debian, Ubuntu; list only, by option and by
`NEEDRESTART_MODE=l`, whatever `needrestart.conf` says), else a scan of
`/proc/<pid>/maps` for executable mappings of deleted files under `/usr`, `/lib*`, `/bin`,
`/sbin` or `/opt`, each process mapped to its service through `/proc/<pid>/cgroup` as the
listening sockets do. A user's own systemd counts as `user@<uid>`, a container's process is
left out, and a process in no service is listed under `processes`. A refused root gives
no report and raises, never a clean reading. A driver supplies
`_run_services_restart_command(command)`.
- `parse_services_restart`, `SERVICES_RESTART_COMMAND`, `DELETED_CODE_PATTERN`, and the
`ServicesRestartDict` and `RestartProcessDict` shapes (in `services_restart`).
## [4.44.0] - 2026-11-26
### Added
+11
View File
@@ -208,6 +208,17 @@ without `ss` is read with `netstat -lntup` (OpenWrt's busybox, old net-tools); o
cgroup names the procd service (`/services/<name>/<instance>`). A host with neither raises
`ListeningSocketsUnavailable`.
`ServicesRestartMixin` (`get_services_need_restart`) is mixed in the same way: the systemd
services that still run code an update replaced on disk -- an openssl or glibc update is not
finished until they restart. One fixed, read-only command, as root: `needs-restarting -s`
where dnf-utils has it, else `needrestart -b -r l` (list only, whatever `needrestart.conf`
says), else the processes whose `/proc/<pid>/maps` maps deleted code
(`DELETED_CODE_PATTERN`), each named by the service its cgroup gives, as for the listening
sockets. A container's processes are left out, an LXC container's as well (a Proxmox node's
containers update themselves). A driver supplies `_run_services_restart_command(command)`; the command arrives as
one `sh -c` argument and reads no stdin. Without root there is no reading: one that saw only
the login user's processes would read as clean.
`LogSourcesMixin` (`get_log_sources`) is mixed in the same way: every log the host writes, in
one round trip. The units journald holds entries for (`journalctl -F _SYSTEMD_UNIT`, services
only), the log files running processes hold open (`/proc/<pid>/fd`: `*.log`, `*.log.N` and
+1
View File
@@ -156,6 +156,7 @@ the driver.
| `package_managers` | rpm, dnf and yum history, apk's and opkg's databases, `/proc/<pid>/comm` |
| `kernel` | `/proc`, `/lib/modules`, gzip, base64 |
| `listening` | `ss`, `netstat`, `/proc/<pid>/cgroup` |
| `services_restart` | `needs-restarting`, `needrestart`, `/proc/<pid>/maps` and `cgroup` |
| `systemd` | `systemctl` |
| `virtual_ips` | vip-manager, keepalived, awk |
| `system_identity` | SMBIOS via sysfs and `dmidecode` |
+13
View File
@@ -61,6 +61,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.running_backups.RunningBackupsMixin`
* :class:`~napalm_device_types.service_clusters.ServiceClustersMixin`
* :class:`~napalm_device_types.service_packages.ServicePackagesMixin`
* :class:`~napalm_device_types.services_restart.ServicesRestartMixin`
* :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin`
* :class:`~napalm_device_types.sudo_history.SudoHistoryMixin`
* :class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin`
@@ -306,6 +307,13 @@ from napalm_device_types.service_packages import (
parse_service_packages,
)
from napalm_device_types.services import ServiceControlMixin
from napalm_device_types.services_restart import (
SERVICES_RESTART_COMMAND,
RestartProcessDict,
ServicesRestartDict,
ServicesRestartMixin,
parse_services_restart,
)
from napalm_device_types.snmp_health_profile import (
SnmpHealthProfile,
SnmpInterfacesSpec,
@@ -534,6 +542,11 @@ __all__ = [
"KERNEL_FACTS_COMMAND",
"parse_kernel_facts",
"SERVICE_PACKAGES_COMMAND",
"SERVICES_RESTART_COMMAND",
"ServicesRestartMixin",
"ServicesRestartDict",
"RestartProcessDict",
"parse_services_restart",
"ServicePackagesMixin",
"parse_service_packages",
"LISTENING_SOCKETS_COMMAND",
+223
View File
@@ -0,0 +1,223 @@
"""Services that still run replaced code: what an update did not finish without a restart.
An upgrade of openssl or glibc replaces the files on disk. Every daemon that had
them loaded keeps running the old code, vulnerable or not, until it restarts
(NetOrk/netork#2700). Whether the *host* needs a reboot is
:mod:`napalm_device_types.host_status`'s; this asks which *services* need a restart.
It is read the same way on every Linux host, so the command and its parse live
here once, and a driver only carries the command across.
**Three sources, in this order:**
- ``needs-restarting -s`` (dnf-utils, the dnf family): the services it names.
- ``needrestart -b -r l`` (Debian, Ubuntu): batch mode, list only. ``-r l`` and
``NEEDRESTART_MODE=l`` both say so, so whatever the host's ``needrestart.conf``
asks for, this never restarts anything.
- Neither there, or both failed: every process whose ``/proc/<pid>/maps`` maps
deleted code (:data:`DELETED_CODE_PATTERN`) -- an executable mapping of a file
under ``/usr``, ``/lib*``, ``/bin``, ``/sbin`` or ``/opt`` that is gone from
disk. Shared memory, memfd and temporary files are deleted on purpose and do not
count, nor data such as the locale archive.
**Units from cgroups.** For the ``/proc`` scan, ``/proc/<pid>/cgroup`` names the
systemd service a process runs in, as for the listening sockets: a process of a
user's own systemd is that user's manager (``user@1000``), one of a container --
Docker, Podman, or LXC as on a Proxmox node -- is left out (the container runs its
own libraries, which no host update replaces, and its own systemd's units are none
of the host's services), and one in no service -- a login session, systemd itself --
is listed as a process. The host's tools name services only, so ``processes`` stays empty
for them.
**Root, or nothing.** Only root sees every process's memory. The script goes to
the host as one ``sh -c`` argument, so a ``sudo`` prefix covers all of it. A
reading without root would miss every other user's process and read as clean, so
there is none: when root is refused, no report comes back and the parse raises.
It is one fixed command, read-only, so it fits a sudoers allowlist.
"""
from __future__ import annotations
import re
from shlex import quote
from typing import TYPE_CHECKING, TypedDict
from napalm_device_types.listening import _cgroup_paths, _container, _unit
from napalm_device_types.terminal import strip_terminal_codes
class RestartProcessDict(TypedDict):
"""A process that runs replaced code and belongs to no systemd service."""
pid: int
name: str # /proc/<pid>/comm
class ServicesRestartDict(TypedDict):
"""What :meth:`ServicesRestartMixin.get_services_need_restart` read.
``units`` are the systemd services, without ".service", that still run code
an update replaced on disk; empty when none does. ``processes`` are the ones
that belong to no service (a login session, systemd itself), read only by the
``/proc`` scan; the host's own tools name services only.
"""
source: str # "needs-restarting", "needrestart" or "maps"
units: list[str]
processes: list[RestartProcessDict]
_BEGIN = "RST_BEGIN"
_END = "RST_END"
NEEDS_RESTARTING = "needs-restarting"
NEEDRESTART = "needrestart"
MAPS = "maps"
_SOURCES = (NEEDS_RESTARTING, NEEDRESTART, MAPS)
#: A line of ``/proc/<pid>/maps`` that maps deleted code: executable, from a
#: directory packages install into, and gone from disk. POSIX ERE, for ``grep -E``.
DELETED_CODE_PATTERN = (
r"^[0-9a-f]+-[0-9a-f]+ ..x. .* /(usr|lib|lib32|lib64|bin|sbin|opt)/.* \(deleted\)$"
)
#: One line, POSIX ``sh``, read-only. The frame markers are printed in two halves
#: so that a transport which echoes the command does not show them early. The
#: tools are in ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
SERVICES_RESTART_COMMAND = (
"PATH=$PATH:/usr/sbin:/sbin; "
"printf '%s%s\\n' RST_ BEGIN; s=; "
"if command -v needs-restarting >/dev/null 2>&1 "
"&& o=$(needs-restarting -s 2>/dev/null); then s=needs-restarting; "
"elif command -v needrestart >/dev/null 2>&1 "
"&& o=$(NEEDRESTART_MODE=l needrestart -b -r l 2>/dev/null); then s=needrestart; fi; "
'if [ -n "$s" ]; then echo "[$s]"; printf \'%s\\n\' "$o"; else p=; '
"for d in /proc/[0-9]*; do "
f'grep -qE \'{DELETED_CODE_PATTERN}\' "$d/maps" 2>/dev/null && p="$p ${{d#/proc/}}"; '
"done; "
"echo '[maps]'; for i in $p; do "
'printf \'%s %s\\n\' "$i" "$(cat /proc/$i/comm 2>/dev/null)"; done; '
"echo '[cgroups]'; for i in $p; do "
'sed "s|^|$i |" /proc/$i/cgroup 2>/dev/null; done; fi; '
"printf '%s%s\\n' RST_ END"
)
#: A service as ``needs-restarting -s`` names it; anything else it prints is noise
#: ("Updating Subscription Management repositories.").
_SERVICE_LINE = re.compile(r"^([\w:.@\\-]+)\.service$")
_NEEDRESTART_SVC = re.compile(r"^NEEDRESTART-SVC:\s*(.+?)\s*$")
#: A process of a user's own systemd: that user's manager is what restarts it.
_USER_MANAGER = re.compile(r"/(user@\d+)\.service(?=/|$)")
#: A process inside an LXC container: ``/lxc/<name>/`` (Proxmox VE, which nests the
#: container's own cgroups under ``ns``; cgroup v1) or ``/lxc.payload.<name>/`` (LXC 4
#: and later). Not ``/lxc.monitor/<name>``: ``lxc-start`` runs the host's binary.
_LXC = re.compile(r"^/lxc(?:/|\.payload\.)[^/]+(?:/|$)")
_SERVICE_SUFFIX = ".service"
def _sections(output: str) -> dict[str, list[str]]:
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
try:
start = lines.index(_BEGIN)
end = lines.index(_END, start)
except ValueError:
raise ValueError("no intact services restart report in the output") from None
sections: dict[str, list[str]] = {}
current: list[str] = []
for line in lines[start + 1 : end]:
if line.startswith("[") and line.endswith("]") and " " not in line:
current = sections.setdefault(line[1:-1], [])
elif line:
current.append(line)
return sections
def _without_suffix(unit: str) -> str:
return unit[: -len(_SERVICE_SUFFIX)] if unit.endswith(_SERVICE_SUFFIX) else unit
def _needs_restarting(lines: list[str]) -> list[str]:
return [m.group(1) for m in map(_SERVICE_LINE.match, lines) if m]
def _needrestart(lines: list[str]) -> list[str]:
return [_without_suffix(m.group(1)) for m in map(_NEEDRESTART_SVC.match, lines) if m]
def _process_unit(path: str | None) -> str | None:
manager = _USER_MANAGER.search(path or "")
return manager.group(1) if manager else _unit(path)
def _maps(sections: dict[str, list[str]]) -> tuple[list[str], list[RestartProcessDict]]:
paths = _cgroup_paths(sections.get("cgroups", []))
units: list[str] = []
processes: list[RestartProcessDict] = []
for line in sections.get(MAPS, []):
pid, _, name = line.partition(" ")
if not pid.isdigit():
continue
path = paths.get(int(pid))
if _container(path) or _LXC.match(path or ""):
continue
unit = _process_unit(path)
if unit:
units.append(unit)
else:
processes.append({"pid": int(pid), "name": name.strip()})
return units, sorted(processes, key=lambda p: p["pid"])
def parse_services_restart(output: str) -> ServicesRestartDict:
"""Parse what :data:`SERVICES_RESTART_COMMAND` printed.
:raises ValueError: when the output carries no intact report, or one without a source.
"""
sections = _sections(output)
source = next((s for s in _SOURCES if s in sections), None)
if source is None:
raise ValueError("the services restart report names no source")
processes: list[RestartProcessDict] = []
if source == NEEDS_RESTARTING:
units = _needs_restarting(sections[source])
elif source == NEEDRESTART:
units = _needrestart(sections[source])
else:
units, processes = _maps(sections)
return {"source": source, "units": sorted(set(units)), "processes": processes}
class ServicesRestartMixin:
"""Adds :meth:`get_services_need_restart` to a driver that can run a command on a
Linux host as root.
The template form (README, "Function classes"): the command and its parse are
the same everywhere, and a driver supplies only
:meth:`_run_services_restart_command` -- how a command reaches its host as
root. Mixed in by the drivers that can, so
``hasattr(driver, "get_services_need_restart")`` stays a truthful answer.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_services_restart_command(self, command: str) -> str:
"""Run *command* on the host as root and return what it printed. The
command is a single ``sh -c`` invocation; it reads nothing from stdin."""
...
def get_services_need_restart(self) -> ServicesRestartDict:
"""
Returns the systemd services that still run code an update replaced.
* source (string) - ``needs-restarting``, ``needrestart`` or ``maps``
* units (list of strings) - the services, without ``.service``; empty when none
* processes (list of {pid, name}) - replaced code outside any service
(``maps`` only)
Example::
{"source": "needrestart", "units": ["nginx", "ssh"], "processes": []}
:raises ValueError: if the host's output carried no intact report -- root
refused, or the command cut short.
"""
command = f"sh -c {quote(SERVICES_RESTART_COMMAND)}"
return parse_services_restart(self._run_services_restart_command(command))
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-device-types"
version = "4.44.0"
version = "4.46.0"
description = "Abstract device-type base classes for NAPALM drivers"
readme = "README.md"
requires-python = ">=3.12"
+334
View File
@@ -0,0 +1,334 @@
"""get_services_need_restart: which services still run the code an update replaced.
An upgrade of openssl or glibc replaces the files on disk; every daemon that had
them loaded keeps running the old code until it restarts (NetOrk/netork#2700).
The host's own tools say which: ``needs-restarting -s`` on the dnf family,
``needrestart -b`` on Debian and Ubuntu, and on a host with neither the
processes that map a deleted library (``/proc/<pid>/maps``). Each process is
then the systemd unit its cgroup names, as for the listening sockets.
"""
from __future__ import annotations
import shutil
import subprocess
import pytest
from napalm_device_types import OSDriver
from napalm_device_types.services_restart import (
DELETED_CODE_PATTERN,
SERVICES_RESTART_COMMAND,
ServicesRestartMixin,
parse_services_restart,
)
CID = "4f1c" + "0" * 60
#: One host after an openssl update: sshd, nginx (two workers), postgres and a
#: user's systemd manager still map the old library.
NEEDS_RESTARTING = """Updating Subscription Management repositories.
sshd.service
nginx.service
postgresql@16-main.service
user@1000.service
"""
NEEDRESTART = """NEEDRESTART-VER: 3.6
NEEDRESTART-KCUR: 6.8.0-87-generic
NEEDRESTART-KEXP: 6.8.0-87-generic
NEEDRESTART-KSTA: 1
NEEDRESTART-SVC: sshd.service
NEEDRESTART-SVC: nginx.service
NEEDRESTART-SVC: postgresql@16-main.service
NEEDRESTART-SVC: user@1000.service
NEEDRESTART-SESS: alice @ session #3
"""
MAPS = """700 sshd
900 nginx
901 nginx
812 postgres
1500 systemd
1501 tmux: server
1300 node_exporter
"""
CGROUPS = f"""700 0::/system.slice/sshd.service
900 0::/system.slice/nginx.service
901 0::/system.slice/nginx.service
812 0::/system.slice/system-postgresql.slice/postgresql@16-main.service
1500 0::/user.slice/user-1000.slice/user@1000.service/init.scope
1501 0::/user.slice/user-1000.slice/session-3.scope
1300 0::/system.slice/docker-{CID}.scope
"""
UNITS = ["nginx", "postgresql@16-main", "sshd", "user@1000"]
def _wire(*sections: tuple[str, str], noise: str = "") -> str:
"""The report as the command prints it, framed."""
body = "".join(f"[{name}]\n{text}" for name, text in sections)
return f"{noise}RST_BEGIN\n{body}RST_END\n"
class TestTheThreeSourcesAgree:
def test_needs_restarting(self):
reading = parse_services_restart(_wire(("needs-restarting", NEEDS_RESTARTING)))
assert reading == {"source": "needs-restarting", "units": UNITS, "processes": []}
def test_needrestart(self):
reading = parse_services_restart(_wire(("needrestart", NEEDRESTART)))
assert reading == {"source": "needrestart", "units": UNITS, "processes": []}
def test_the_maps_scan(self):
reading = parse_services_restart(_wire(("maps", MAPS), ("cgroups", CGROUPS)))
assert reading["source"] == "maps"
assert reading["units"] == UNITS
def test_the_maps_scan_names_the_processes_without_a_unit(self):
reading = parse_services_restart(_wire(("maps", MAPS), ("cgroups", CGROUPS)))
assert reading["processes"] == [{"pid": 1501, "name": "tmux: server"}]
class TestNothingToRestart:
@pytest.mark.parametrize(
"sections",
[
(("needs-restarting", ""),),
(("needrestart", "NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n"),),
(("maps", ""), ("cgroups", "")),
],
)
def test_a_clean_reading_is_an_empty_list(self, sections):
reading = parse_services_restart(_wire(*sections))
assert reading["units"] == [] and reading["processes"] == []
class TestTheMapsScan:
def test_a_container_is_left_out(self):
"""A container runs its image's libraries, which no host update replaces."""
reading = parse_services_restart(
_wire(("maps", "1300 node_exporter\n"), ("cgroups", CGROUPS))
)
assert reading == {"source": "maps", "units": [], "processes": []}
@pytest.mark.parametrize(
"cgroup",
[
# Proxmox VE: the container's own systemd, under lxc/<vmid>/ns.
"0::/lxc/101/ns/system.slice/nginx.service",
"0::/lxc/101/ns/init.scope",
# LXC 4 and later by default.
"0::/lxc.payload.web/system.slice/nginx.service",
# cgroup v1, systemd's hierarchy.
"12:name=systemd:/lxc/web/system.slice/nginx.service",
],
)
def test_an_lxc_container_is_left_out(self, cgroup):
"""A Proxmox node's containers update themselves: the host sees their processes'
mappings, and their own systemd's units, which are no services of the host's."""
cgroups = f"2100 {cgroup}\n"
reading = parse_services_restart(_wire(("maps", "2100 nginx\n"), ("cgroups", cgroups)))
assert reading == {"source": "maps", "units": [], "processes": []}
def test_an_lxc_monitor_is_the_hosts(self):
"""``lxc-start`` runs the host's own binary, outside the container."""
reading = parse_services_restart(
_wire(("maps", "2090 lxc-start\n"), ("cgroups", "2090 0::/lxc.monitor/101\n"))
)
assert reading["processes"] == [{"pid": 2090, "name": "lxc-start"}]
def test_a_process_gone_before_its_cgroup_was_read_has_no_unit(self):
reading = parse_services_restart(_wire(("maps", "4242 cron\n"), ("cgroups", "")))
assert reading["processes"] == [{"pid": 4242, "name": "cron"}]
def test_cgroup_v1_reads_the_systemd_hierarchy(self):
cgroups = "700 12:name=systemd:/system.slice/sshd.service\n700 3:cpu:/\n"
reading = parse_services_restart(_wire(("maps", "700 sshd\n"), ("cgroups", cgroups)))
assert reading["units"] == ["sshd"]
def test_pid_1_is_a_process_without_a_unit(self):
"""systemd itself needs ``daemon-reexec``, not a unit restart."""
reading = parse_services_restart(
_wire(("maps", "1 systemd\n"), ("cgroups", "1 0::/init.scope\n"))
)
assert reading["processes"] == [{"pid": 1, "name": "systemd"}]
@pytest.mark.parametrize(
"line",
[
"7f2a1c000000-7f2a1c1a0000 r-xp 00028000 fd:00 131 /usr/lib/x86_64-linux-gnu/libc.so.6 (deleted)",
"55d0c0000000-55d0c0100000 r-xp 00000000 fd:00 99 /usr/sbin/sshd (deleted)",
"7f00-7f10 r-xp 00000000 fd:00 7 /lib64/libssl.so.3 (deleted)",
"7f00-7f10 r-xp 00000000 fd:00 7 /opt/app/lib/libfoo.so (deleted)",
],
)
def test_replaced_code_counts(self, line):
assert (
subprocess.run(["grep", "-qE", DELETED_CODE_PATTERN], input=line, text=True).returncode
== 0
)
@pytest.mark.parametrize(
"line",
[
# Code still on disk.
"7f2a1c000000-7f2a1c1a0000 r-xp 00028000 fd:00 131 /usr/lib/x86_64-linux-gnu/libc.so.6",
# Data, not code: the locale archive an update replaced.
"7f00-7f10 r--p 00000000 fd:00 7 /usr/lib/locale/locale-archive (deleted)",
# Deleted on purpose: shared memory, memfd, a temporary file.
"7f00-7f10 rw-s 00000000 00:01 7 /SYSV00000000 (deleted)",
"7f00-7f10 r-xp 00000000 00:01 7 /memfd:jit (deleted)",
"7f00-7f10 r-xp 00000000 00:01 7 /tmp/ffiXyz (deleted)",
"7f00-7f10 r-xp 00000000 00:01 7 /dev/shm/pulse-shm-1 (deleted)",
],
)
def test_what_is_not_replaced_code(self, line):
assert (
subprocess.run(["grep", "-qE", DELETED_CODE_PATTERN], input=line, text=True).returncode
== 1
)
class TestFailures:
def test_whatever_surrounds_the_frame_is_ignored(self):
reading = parse_services_restart(
_wire(("needs-restarting", "sshd.service\n"), noise="[sudo] password for netork:\n")
)
assert reading["units"] == ["sshd"]
def test_output_without_the_frame_raises(self):
"""sudo refused: the script never ran, and that is no clean reading."""
with pytest.raises(ValueError):
parse_services_restart("sudo: a password is required\n")
def test_a_report_cut_short_raises(self):
with pytest.raises(ValueError):
parse_services_restart("RST_BEGIN\n[needs-restarting]\nsshd.service\n")
def test_a_report_without_a_source_raises(self):
with pytest.raises(ValueError):
parse_services_restart("RST_BEGIN\nRST_END\n")
def _stub(tmp_path, name: str, script: str) -> None:
stub = tmp_path / name
stub.write_text(f"#!/bin/sh\n{script}\n")
stub.chmod(0o755)
def _run(tmp_path) -> str:
for tool in ("cat", "grep", "sed", "printf"):
if shutil.which(tool):
(tmp_path / tool).symlink_to(shutil.which(tool))
return subprocess.run(
["/bin/sh", "-c", SERVICES_RESTART_COMMAND],
capture_output=True,
text=True,
env={"PATH": str(tmp_path)},
timeout=60,
).stdout
class TestTheOrderOfPreference:
def test_needs_restarting_first(self, tmp_path):
_stub(tmp_path, "needs-restarting", f"cat <<'EOF'\n{NEEDS_RESTARTING}EOF")
_stub(tmp_path, "needrestart", "echo NEEDRESTART-SVC: other.service")
assert parse_services_restart(_run(tmp_path))["source"] == "needs-restarting"
def test_needrestart_when_needs_restarting_fails(self, tmp_path):
_stub(tmp_path, "needs-restarting", "exit 1")
_stub(tmp_path, "needrestart", f"cat <<'EOF'\n{NEEDRESTART}EOF")
reading = parse_services_restart(_run(tmp_path))
assert reading == {"source": "needrestart", "units": UNITS, "processes": []}
def test_needrestart_only_lists(self, tmp_path):
"""Batch mode, list only, by its option and by its environment: whatever the
host's needrestart.conf says, it restarts nothing."""
_stub(tmp_path, "needrestart", 'echo "NEEDRESTART-SVC: $NEEDRESTART_MODE $*.service"')
reading = parse_services_restart(_run(tmp_path))
assert reading["units"] == ["l -b -r l"]
def test_the_maps_scan_when_both_fail(self, tmp_path):
"""Stubs that fail stand in for the host's own tools, which ``/usr/sbin``
on this host may hold."""
_stub(tmp_path, "needs-restarting", "exit 1")
_stub(tmp_path, "needrestart", "exit 1")
assert parse_services_restart(_run(tmp_path))["source"] == "maps"
class TestTheCommand:
def test_the_frame_is_not_in_the_command_itself(self):
assert "RST_BEGIN" not in SERVICES_RESTART_COMMAND
assert "RST_END" not in SERVICES_RESTART_COMMAND
def test_it_writes_and_changes_nothing(self):
for verb in ("sudo", " > ", ">>", "kill", "rm ", "systemctl ", "-r a", "-r i"):
assert verb not in SERVICES_RESTART_COMMAND
def test_it_is_posix_sh(self):
result = subprocess.run(
["sh", "-n", "-c", SERVICES_RESTART_COMMAND], capture_output=True, text=True
)
assert result.returncode == 0, result.stderr
def test_it_runs_and_parses_on_this_host(self):
out = subprocess.run(
["sh", "-c", SERVICES_RESTART_COMMAND], capture_output=True, text=True, timeout=120
).stdout
reading = parse_services_restart(out)
assert reading["source"] in ("needs-restarting", "needrestart", "maps")
class _Driver(ServicesRestartMixin):
def __init__(self, output: str):
self.output = output
self.commands: list[str] = []
def _run_services_restart_command(self, command: str) -> str:
self.commands.append(command)
return self.output
class TestTheTemplate:
def test_a_driver_supplies_only_the_transport(self):
driver = _Driver(_wire(("needs-restarting", "sshd.service\n")))
assert driver.get_services_need_restart()["units"] == ["sshd"]
def test_the_command_reaches_root_as_one_shell(self):
driver = _Driver(_wire(("needs-restarting", "")))
driver.get_services_need_restart()
(command,) = driver.commands
assert command.startswith("sh -c '")
assert subprocess.run(["sh", "-n", "-c", command]).returncode == 0
def test_a_refused_root_raises_rather_than_reads_clean(self):
driver = _Driver("sudo: a password is required\n")
with pytest.raises(ValueError):
driver.get_services_need_restart()
def test_not_every_os_driver_has_it(self):
assert not hasattr(OSDriver, "get_services_need_restart")