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:
1 parent
818016b717
commit
9c889f3715
7 files changed
+558
No files matched your search
@@ -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