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.
This commit is contained in:
christianmanivong committed 2026-11-26 17:39:04 +01:00
1 parent 818016b717
commit 9c889f3715
7 files changed
+558

No files matched your search

+9
View File
@@ -60,6 +60,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`
@@ -300,6 +301,11 @@ 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,
ServicesRestartMixin,
parse_services_restart,
)
from napalm_device_types.snmp_health_profile import (
SnmpHealthProfile,
SnmpInterfacesSpec,
@@ -516,6 +522,9 @@ __all__ = [
"KERNEL_FACTS_COMMAND",
"parse_kernel_facts",
"SERVICE_PACKAGES_COMMAND",
"SERVICES_RESTART_COMMAND",
"ServicesRestartMixin",
"parse_services_restart",
"ServicePackagesMixin",
"parse_service_packages",
"LISTENING_SOCKETS_COMMAND",
+21
View File
@@ -406,6 +406,27 @@ class ListeningSocketsDict(TypedDict):
sockets: list[ListeningSocketDict]
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 ``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]
class NetfilterMatchDict(TypedDict):
"""One condition of a netfilter rule.
+197
View File
@@ -0,0 +1,197 @@
"""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 is
left out (the container runs its image's libraries, which no host update
replaces), 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
from napalm_device_types.listening import _cgroup_paths, _container, _unit
from napalm_device_types.models import RestartProcessDict, ServicesRestartDict
from napalm_device_types.terminal import strip_terminal_codes
_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(?=/|$)")
_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):
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))