Compare commits

..
10 Commits
Author SHA1 Message Date
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 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 03ccae82e3 Merge pull request 'chore(release): 4.44.0' (#133) from feature/pve93-2728 into main
driver / types (push) Successful in 59s
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 14s
driver / test (3.12) (push) Successful in 1m14s
driver / test (3.13) (push) Successful in 1m8s
driver / lowest (push) Successful in 40s
driver / build (push) Successful in 34s
driver / security (push) Successful in 1m9s
driver / publish (push) Successful in 28s
CI / driver (push) Successful in 3m24s
2026-11-26 17:15:12 +00:00
christianmanivong d561046802 refactor: the update history shapes live with UpdateMixin, within the quality ratchet
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m3s
driver / test (3.12) (pull_request) Successful in 1m16s
driver / test (3.13) (pull_request) Successful in 1m11s
driver / lowest (pull_request) Successful in 42s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m3s
CI / driver (pull_request) Successful in 2m33s
driver / publish (pull_request) Skipped
2026-11-26 18:11:58 +01:00
christianmanivong 53bc79098b chore(release): 4.44.0
driver / lint (pull_request) Successful in 16s
driver / standard (pull_request) Failing after 18s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m22s
driver / test (3.12) (pull_request) Successful in 1m28s
driver / lowest (pull_request) Successful in 45s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m3s
CI / driver (pull_request) Failing after 2m45s
driver / publish (pull_request) Skipped
2026-11-26 18:05:09 +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
christianmanivong 07fc7d0dd3 feat: guest uid, credential expiry and update history contracts (NetOrk/netork#2728)
VMDict.uid is an identity of the guest that survives a migration, a restore
and a changed vmid. CredentialExpiryMixin reads when the credential a driver
logs in with expires. UpdateMixin.get_update_history lists the package
manager's past transactions. resume_vm documents that the guest clock is set
after a resume where the platform can.
2026-11-26 17:26:57 +01:00
12 changed files with 825 additions and 8 deletions

No files matched your search

+38
View File
@@ -7,6 +7,44 @@ 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
- `VMDict.uid`, optional: an identity of the guest that survives a migration, a restore
and a changed `vmid` (NetOrk/netork#2728). Proxmox VE 9.3 gives every guest one, VMware's
instance UUID is one; a driver leaves it out where the platform has none, and a caller
then knows the guest by `vmid` alone.
- `CredentialExpiryMixin.get_credential_expiry()`: the credential the connection logged in
with (`kind` `"api-token"` or `"account"`, its `name`) and when it expires, `None` for
never (NetOrk/netork#2728). `PermissionError` where the platform will not tell the
credential its own expiry.
- `UpdateMixin.get_update_history(since)`: the package manager's past transactions, newest
first, each with a stable `id`, start and end, the packages it changed (`action`, old and
new version), who asked for it, the command line and the error it ended with
(`UpdateHistoryDict`, `UpdateHistoryPackageDict`, NetOrk/netork#2728).
### Changed
- `HypervisorDriver.resume_vm()`: the guest's clock is set to the host's time after it
resumes, where the platform can (NetOrk/netork#2728). A documented expectation, not a
parameter: no caller wants a guest that runs behind.
## [4.43.0] - 2026-11-26
### Added
+10
View File
@@ -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
+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` |
+32 -1
View File
@@ -41,6 +41,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.config_revisions.ConfigRevisionsMixin`
* :class:`~napalm_device_types.config_sync.ConfigSyncMixin`
* :class:`~napalm_device_types.container_engine.ContainerEngineMixin`
* :class:`~napalm_device_types.credential_expiry.CredentialExpiryMixin`
* :class:`~napalm_device_types.dhcp.DhcpServerMixin`
* :class:`~napalm_device_types.firewall_rules.FirewallRuleMixin`
* :class:`~napalm_device_types.health_metrics.HealthMetricsMixin`
@@ -60,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`
@@ -143,6 +145,11 @@ from napalm_device_types.container_engine import (
ContainerEngineMixin,
ContainerEngineUnavailable,
)
from napalm_device_types.credential_expiry import (
CredentialExpiryDict,
CredentialExpiryMixin,
CredentialKind,
)
from napalm_device_types.dhcp import DhcpApplyError, DhcpServerMixin, normalize_cidr, normalize_mac
from napalm_device_types.dns_forward import DnsForwardMixin
from napalm_device_types.firewall import FirewallDriver
@@ -300,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,
@@ -361,7 +375,13 @@ from napalm_device_types.time_sync import (
check_ntp_servers,
)
from napalm_device_types.time_sync_posix import PosixTimeSyncMixin, parse_time_sync
from napalm_device_types.updates import PackageIndexMissing, UpdateMixin
from napalm_device_types.updates import (
PackageIndexMissing,
UpdateHistoryAction,
UpdateHistoryDict,
UpdateHistoryPackageDict,
UpdateMixin,
)
from napalm_device_types.virtual_ips import (
VIRTUAL_IPS_COMMAND,
VirtualIpsMixin,
@@ -406,6 +426,12 @@ __all__ = [
"OspfInterfaceDict",
"OspfMixin",
"UpdateProgressDict",
"UpdateHistoryAction",
"UpdateHistoryDict",
"UpdateHistoryPackageDict",
"CredentialExpiryDict",
"CredentialExpiryMixin",
"CredentialKind",
"FirmwareOfferMixin",
"FirmwareUpgradeMixin",
"LicenseDict",
@@ -516,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",
+58
View File
@@ -0,0 +1,58 @@
"""When the credential a driver logs in with stops working.
An API token can be given an expiry, and a platform can require one (Proxmox VE
9.3's datacenter ``token-policy``). Once it has passed, every login fails with
an authentication error, and an application that polls the device learns of it
only then. A driver that can read its own credential's expiry says so here, so
the application can warn before, the way it warns of an expiring certificate.
Which credential is read is the driver's: the one this connection logged in
with, never another.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Literal
from typing_extensions import TypedDict
#: ``"api-token"``: a token of an account; ``"account"``: the account a password logs in to.
CredentialKind = Literal["api-token", "account"]
class CredentialExpiryDict(TypedDict):
"""The credential this connection logged in with, and when it expires."""
kind: CredentialKind
#: The credential as the platform names it, e.g. ``"netork@pve!poll"``.
name: str
#: Unix seconds; ``None`` when it never expires.
expires: int | None
class CredentialExpiryMixin:
"""Reads the expiry of the credential the driver logged in with.
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder.
"""
if TYPE_CHECKING:
def get_credential_expiry(self) -> CredentialExpiryDict:
"""
The credential this connection logged in with, and when it expires.
``expires`` is ``None`` for one that never expires. A credential
whose expiry has passed cannot log in, so a driver that returns at
all reports one that still works.
:raises PermissionError: The platform will not tell this credential
its own expiry (a token whose privileges do not reach it). Not a
fault of the connection; a caller then knows nothing either way.
:raises RuntimeError: The platform could not be read.
Example::
{"kind": "api-token", "name": "netork@pve!poll", "expires": 1767225600}
"""
...
+14 -2
View File
@@ -41,6 +41,13 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
Inherits all standard NAPALM NetworkDriver methods and adds
hypervisor-specific operations that concrete drivers must implement.
A guest is known by its ``vmid``, which a platform may give to another guest
once the first is gone, and where it has one also by its ``uid``
(``VMDict.uid``): an identity that survives a migration, a restore and a
changed ``vmid`` -- Proxmox VE 9.3's ``uid``, VMware's instance UUID. A driver
leaves it out where the platform has none or has not given the guest one yet;
a caller then knows that guest by ``vmid`` alone.
"""
#: Stable key netOrk exposes as ``device_class``. The order in which a
@@ -69,8 +76,7 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
Each entry contains:
* name (string) - VM display name
* vmid (string) - hypervisor-internal ID (Proxmox: ``"100"``,
VMware: the instance UUID)
* vmid (string) - hypervisor-internal ID (Proxmox: ``"100"``, VMware: the instance UUID)
* status (string) - ``"running"``, ``"stopped"``, ``"paused"``, ``"suspended"``.
A guest that is not executing is never ``"running"``: ``"paused"``
while its process still holds its memory (Proxmox's ``qmpstatus``
@@ -82,6 +88,7 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
* memory_usage (int) - current RAM usage in megabytes
* uptime (int) - uptime in seconds (0 if not running)
* node (string) - cluster node this VM lives on (empty string for standalone)
* uid (string, optional) - outlives the ``vmid``; absent where none (``VMDict.uid``)
Example::
@@ -272,6 +279,11 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
counterpart of :meth:`suspend_vm`. The method blocks until the
hypervisor took the request.
The guest's clock is set to the host's time after it resumes, where the
platform can do so (Proxmox VE: through the guest agent): a guest that
stood still for hours would otherwise run behind. No caller wants
otherwise, so it is the driver's to do, not a choice.
Optional, like every power action: a driver whose platform cannot
resume a guest does not implement it, and a caller then offers no
resume. A driver that can resume some guests but not others (a
+2 -2
View File
@@ -1,5 +1,4 @@
"""
TypedDicts for NAPALM device-type-specific return values.
"""TypedDicts for NAPALM device-type-specific return values.
These supplement the types defined in napalm.base.models and are used by the
abstract device-type driver classes in this package.
@@ -835,6 +834,7 @@ class VMDict(TypedDict):
memory_usage: int
uptime: int
node: str
uid: NotRequired[str] # outlives a migration, a restore, a changed vmid (get_vms)
class VMPassthroughDict(TypedDict):
+218
View File
@@ -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))
+78 -2
View File
@@ -12,9 +12,47 @@ this class in can never shadow a working implementation from a sibling base.
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Literal
from napalm_device_types.models import ApplyUpdatesResultDict, UpdateDict, UpdateProgressDict
from typing_extensions import TypedDict
from napalm_device_types.models import (
ApplyUpdatesResultDict,
UpdateDict,
UpdateProgressDict,
)
UpdateHistoryAction = Literal[
"install", "reinstall", "upgrade", "downgrade", "remove", "purge", "disappear"
]
class UpdateHistoryPackageDict(TypedDict):
"""One package a past transaction changed (``UpdateHistoryDict.packages``)."""
name: str
action: UpdateHistoryAction # "disappear": dpkg dropped it, its files taken by another
old_version: str | None # None where nothing was installed before
new_version: str | None # None where nothing is installed after
class UpdateHistoryDict(TypedDict):
"""A past run of the host's package manager (``UpdateMixin.get_update_history``).
A fact of the host's own log: what it changed, when, and who asked, also for
a run that no application of the caller started.
"""
#: Stable for the same transaction across reads, unique on the host: apt's
#: start time with its index among those starting in the same second, dnf's
#: transaction ID.
id: str
start: int # unix seconds
end: int | None # None: still running, or interrupted
packages: list[UpdateHistoryPackageDict]
requested_by: str | None # the user behind sudo, pkexec or PackageKit; None when unknown
command: str | None # the command line, where the log keeps it
error: str | None # the error the run ended with; None for none
class PackageIndexMissing(RuntimeError):
@@ -83,6 +121,44 @@ class UpdateMixin:
"""
...
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
"""
The transactions the host's package manager ran, newest first: what
each changed, when, and who asked for it -- also those no caller of
this driver started (an operator's ``apt upgrade``, unattended-upgrades).
:param since: Unix seconds; only transactions that started at or after
it. ``None`` for as far back as the host's log reaches.
**An empty list means no transaction since.** A reader that cannot
read raises, as :meth:`get_available_updates` does: a caller keeps what
it read before, and an empty list for "don't know" would read as a
host that never changed. ``NotImplementedError`` where the package
manager keeps no history.
Example::
[
{
"id": "1764158400-0",
"start": 1764158400,
"end": 1764158460,
"packages": [
{
"name": "openssh-server",
"action": "upgrade",
"old_version": "1:9.2p1-2+deb12u1",
"new_version": "1:9.2p1-2+deb12u2",
},
],
"requested_by": "admin",
"command": "apt-get -y upgrade",
"error": None,
},
]
"""
...
def refresh_available_updates(self) -> dict[str, Any]:
"""
Refreshes the host's package index, so that :meth:`get_available_updates`
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-device-types"
version = "4.43.0"
version = "4.45.0"
description = "Abstract device-type base classes for NAPALM drivers"
readme = "README.md"
requires-python = ">=3.12"
+68
View File
@@ -0,0 +1,68 @@
"""Contracts Proxmox VE 9.3 made worth having, kept neutral (NetOrk/netork#2728).
A guest identity that survives a changed ID, the expiry of the credential a
driver logs in with, and what a host's package manager did in the past: each a
shape every driver of its kind can fill, with the platform's own calls left to
the driver.
"""
from __future__ import annotations
import typing
from typing import get_type_hints
from napalm_device_types import (
CredentialExpiryDict,
CredentialExpiryMixin,
UpdateHistoryDict,
UpdateHistoryPackageDict,
UpdateMixin,
)
from napalm_device_types.models import VMDict
def test_a_vm_may_carry_an_identity_that_outlives_its_vmid():
assert "uid" in get_type_hints(VMDict)
assert "uid" in VMDict.__optional_keys__
def test_a_credential_expiry_names_the_credential_and_when_it_ends():
assert set(get_type_hints(CredentialExpiryDict)) == {"kind", "name", "expires"}
kinds = typing.get_args(get_type_hints(CredentialExpiryDict)["kind"])
assert set(kinds) == {"api-token", "account"}
def test_credential_expiry_is_a_contract_not_a_placeholder():
assert not hasattr(CredentialExpiryMixin, "get_credential_expiry")
def test_an_update_transaction_is_its_packages_and_who_asked_for_it():
assert set(get_type_hints(UpdateHistoryDict)) == {
"id",
"start",
"end",
"packages",
"requested_by",
"command",
"error",
}
assert set(get_type_hints(UpdateHistoryPackageDict)) == {
"name",
"action",
"old_version",
"new_version",
}
actions = typing.get_args(get_type_hints(UpdateHistoryPackageDict)["action"])
assert set(actions) == {
"install",
"reinstall",
"upgrade",
"downgrade",
"remove",
"purge",
"disappear",
}
def test_update_history_is_declared_next_to_pending_updates():
assert not hasattr(UpdateMixin, "get_update_history")
+305
View File
@@ -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")