feat(services-restart): the services that still run replaced code (NetOrk/netork#2700) #132
No files matched your search
@@ -7,6 +7,23 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
@@ -208,6 +208,16 @@ 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 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
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""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, 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(?=/|$)")
|
||||
_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))
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "4.44.0"
|
||||
version = "4.45.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
"""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": []}
|
||||
|
||||
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")
|
||||
Reference in new issue
Block a user