Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5985c87cc8 | ||
|
|
6c90373c80 | ||
|
|
ddc9316fb5 | ||
|
|
f8c456d784 | ||
|
|
a5275d4c4d | ||
|
|
a38f07513f | ||
|
|
ddcd9ebc0a | ||
|
|
494b9ed046 | ||
|
|
67ffee4e9e | ||
|
|
03ccae82e3 | ||
|
|
d561046802 | ||
|
|
53bc79098b | ||
|
|
5517464e1f | ||
|
|
9c889f3715 | ||
|
|
07fc7d0dd3 | ||
|
|
818016b717 | ||
|
|
66f26c3d8e | ||
|
|
507e9a8728 | ||
|
|
4df932e0ca | ||
|
|
cbd1cd3d11 | ||
|
|
ebd3255e5a | ||
|
|
fb927e7255 | ||
|
|
ae21c7fba7 | ||
|
|
784f7ac686 | ||
|
|
2412a99eeb | ||
|
|
cd47587e80 | ||
|
|
b1ea364674 | ||
|
|
e729b935a4 | ||
|
|
f654076560 | ||
|
|
2dea517e89 | ||
|
|
1a7885d22e | ||
|
|
71588613fb | ||
|
|
93ba335798 |
No files matched your search
+112
@@ -7,6 +7,118 @@ 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
|
||||
- `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
|
||||
- `opened_ports`: the record of the firewall rules netOrk opened on a host
|
||||
(NetOrk/netork#2693). ufw, iptables and firewalld do not say who wrote a rule, so a
|
||||
driver that opens a port in one of them appends the rule to `/var/lib/netork/opened-ports`
|
||||
(root's, mode 644) -- only when the firewall did not have it before, so an identical rule
|
||||
the operator wrote is never recorded. `parse_opened_ports_record` reads it strictly: not at
|
||||
all where the directory or the file is not root's alone or is a symbolic link, and a line
|
||||
that is not exactly a rule is reported, never acted on. `ufw_allow_recorded_command` and
|
||||
`ufw_delete_command` are ufw's commands, which napalm-linux and napalm-proxmox share,
|
||||
`revoke_recorded_rules` removes the rules recorded under a purpose with the driver's own
|
||||
command and keeps every other line;
|
||||
`revoked_output` says what closing removed and what it left for the port.
|
||||
- `ZabbixAgentMixin._revoke_zabbix_agent_sources(settings)`, optional: for an `active_only`
|
||||
agent, `configure_zabbix_agent`'s firewall step has the driver close what netOrk opened
|
||||
for the agent on an earlier passive run, and nothing else (NetOrk/netork#2693). A driver
|
||||
without it changes nothing and says that it cannot tell netOrk's rule from the
|
||||
operator's.
|
||||
|
||||
## [4.42.0] - 2026-11-25
|
||||
|
||||
### Added
|
||||
- `AptReleaseMixin.get_apt_source_releases()`: the host's release from `/etc/os-release`
|
||||
(`ID`, `ID_LIKE`, `VERSION_CODENAME`, `UBUNTU_CODENAME`) and every enabled source apt
|
||||
reads, one-line and deb822, with its file, line, types, URI, suites and components
|
||||
(NetOrk/netork#2614). `AptProxyMixin` brings it, so every apt driver has it.
|
||||
- `AptReleaseMixin.set_apt_source_release(path, release, codename)`: every suite of
|
||||
*release* in one of apt's source files moved to *codename* (`focal-security` →
|
||||
`noble-security`), once each new suite's `InRelease` or `Release` is fetched with apt's
|
||||
downloader; nothing is written where the vendor has none.
|
||||
- `parse_apt_releases`, `rewrite_release`, `suite_release`, `APT_RELEASES_COMMAND`.
|
||||
- `ZabbixAgentSettingsDict.active_only`: an agent that only connects out
|
||||
(NetOrk/netork#2683). `zabbix_agent_config` writes `StartAgents=0` -- no passive
|
||||
checks, no listening port -- and comments `Server` out, which Zabbix requires only
|
||||
while `StartAgents` is not 0; `check_zabbix_agent_settings` then requires
|
||||
`server_active` instead of `server`. `configure_zabbix_agent`'s firewall step opens
|
||||
nothing for it and does not call the driver's `_allow_zabbix_agent_sources`, so no
|
||||
driver changes.
|
||||
- `HypervisorDriver.resume_vm(name)`: bring a paused or suspended VM back where it stopped,
|
||||
the counterpart of `suspend_vm` (NetOrk/netork#2658). Optional like every power action;
|
||||
a driver that can resume some guests but not others refuses the others with
|
||||
`RuntimeError`.
|
||||
|
||||
### Changed
|
||||
- `zabbix_agent_config` comments a `StartAgents=0` line out for an agent that is not
|
||||
active only, since it would keep the agent from listening; another count stays.
|
||||
- `HypervisorDriver.get_vms()`: a guest that is not executing is never `"running"`. It is
|
||||
`"paused"` while its process still holds its memory and `"suspended"` once its state was
|
||||
saved away (NetOrk/netork#2658). `suspend_vm` names `resume_vm`, not `start_vm`, as the
|
||||
way back.
|
||||
|
||||
## [4.41.0] - 2026-11-17
|
||||
|
||||
### Added
|
||||
- `FirmwareUpgradeMixin.start_firmware_upgrade(version)`: start installing the firmware a
|
||||
driver offers; the device runs it by itself and restarts at its end, and
|
||||
`UpdateMixin.get_update_progress` follows it until then (NetOrk/netork#2615, OpenWrt's
|
||||
sysupgrade through owut).
|
||||
- `FirmwareOfferDict.installable`: whether the driver can install `latest_version` itself
|
||||
now, False while the device lacks what that takes; and
|
||||
`FirmwareOfferDict.latest_major_version`, the newest of a later release line, shown and
|
||||
never crossed to by the driver.
|
||||
|
||||
## [4.40.0] - 2026-11-17
|
||||
|
||||
### Added
|
||||
|
||||
@@ -126,7 +126,8 @@ firewall, start), `LldpAgentMixin.configure_lldp_agent(interfaces)` (install, wr
|
||||
interfaces, enable and restart; the driver writes only the interfaces),
|
||||
`ZabbixAgentMixin.configure_zabbix_agent(settings)` (install from the host's packages or
|
||||
else Zabbix's repository, configure, firewall, enable and restart; the driver writes the
|
||||
configuration and opens the firewall), `EnsurePackageMixin.ensure_package(name)`,
|
||||
configuration and opens the firewall; an `active_only` agent gets `StartAgents=0` and no
|
||||
firewall opening), `EnsurePackageMixin.ensure_package(name)`,
|
||||
`PackageProxyMixin.configure_package_proxy(url)`,
|
||||
`TimeSyncMixin.configure_time_sync(ntp_servers, timezone)` and
|
||||
`ContainerEngineMixin.grant_container_engine_access(user)`. A driver whose device takes the
|
||||
@@ -175,6 +176,15 @@ wins (`get_package_proxy`, `get_package_proxy_report` with every line that sets
|
||||
different proxy, reads the result back and fetches one http source's `InRelease` through it.
|
||||
A driver supplies `_run_apt_command`, `_run_apt_root_command` and `_write_apt_file`.
|
||||
|
||||
`AptReleaseMixin` (`napalm_device_types.apt_releases`) comes with it: every source apt reads,
|
||||
with its file, line, URI and suites, and the host's release from `/etc/os-release`
|
||||
(`get_apt_source_releases`). A release upgrade leaves third-party sources on the old release,
|
||||
where they stop getting updates once the vendor stops building for it; whether a suite names
|
||||
another release than the host's is the caller's to judge (`suite_release` gives the word).
|
||||
`set_apt_source_release(path, release, codename)` moves every suite of *release* in one
|
||||
source file to *codename*, after fetching each new suite's `InRelease` with apt's downloader:
|
||||
where the vendor has none, the file stays as it is.
|
||||
|
||||
`HostStatusMixin` (`get_host_status`) is mixed in the same way: whether a Linux host needs
|
||||
a reboot to finish an update (`/var/run/reboot-required`, `needs-restarting -r`, or a newer
|
||||
kernel of the running flavour installed), whether it patches itself (unattended-upgrades,
|
||||
@@ -198,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
|
||||
|
||||
@@ -78,6 +78,7 @@ The same shape replaces every action in today's `run_device_action`:
|
||||
|---|---|
|
||||
| `fix_snmp` | `configure_snmp_agent(settings)` |
|
||||
| `fix_apt_proxy` | `configure_package_proxy(url)` |
|
||||
| an apt source on another release than the host (NetOrk/netork#2614) | `set_apt_source_release(path, release, codename)` |
|
||||
| `fix_docker_permissions` | `grant_container_engine_access(user)` |
|
||||
| `install_lldpd`, `install_auc` | `ensure_package(name)` |
|
||||
| the Zabbix agent where no container engine runs (NetOrk/netork#2571) | `configure_zabbix_agent(settings)` |
|
||||
@@ -155,10 +156,12 @@ 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` |
|
||||
| `package_updates` | apt and dnf output |
|
||||
| `apt_releases` | apt's source files (one-line and deb822), `/etc/os-release`, `apt-helper` |
|
||||
| `ssh_server` | OpenSSH (`sshd -T`, `sshd -t`, `sshd_config`); which algorithms to drop stays the caller's |
|
||||
| `terminal` | ANSI escape codes in shell output |
|
||||
| `channel`: `run_on_transport`, `open_stream_on_transport`, `ParamikoExecStream` | paramiko exec channels |
|
||||
|
||||
@@ -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`
|
||||
@@ -86,6 +88,15 @@ from napalm_device_types.apt_proxy import (
|
||||
parse_apt_proxy,
|
||||
same_proxy_url,
|
||||
)
|
||||
from napalm_device_types.apt_releases import (
|
||||
APT_RELEASES_COMMAND,
|
||||
AptReleaseFixDict,
|
||||
AptReleaseMixin,
|
||||
AptReleasesDict,
|
||||
AptSourceDict,
|
||||
parse_apt_releases,
|
||||
suite_release,
|
||||
)
|
||||
from napalm_device_types.arp import ARP_AGE_UNKNOWN
|
||||
from napalm_device_types.backup_server import BackupServerDriver
|
||||
from napalm_device_types.backups import (
|
||||
@@ -134,11 +145,16 @@ 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
|
||||
from napalm_device_types.firewall_rules import FirewallRuleMixin
|
||||
from napalm_device_types.firmware import FirmwareOfferMixin
|
||||
from napalm_device_types.firmware import FirmwareOfferDict, FirmwareOfferMixin, FirmwareUpgradeMixin
|
||||
from napalm_device_types.fixes import (
|
||||
EnsurePackageMixin,
|
||||
LldpAgentMixin,
|
||||
@@ -205,7 +221,6 @@ from napalm_device_types.models import (
|
||||
DnsForwardDict,
|
||||
EventLogEntryDict,
|
||||
FirmwareDict,
|
||||
FirmwareOfferDict,
|
||||
FixResultDict,
|
||||
FixStepDict,
|
||||
FixStepOutcomeDict,
|
||||
@@ -221,6 +236,23 @@ from napalm_device_types.models import (
|
||||
UpdateProgressDict,
|
||||
)
|
||||
from napalm_device_types.nat_vpn import NatVpnMixin
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
SNMP_PURPOSE,
|
||||
ZABBIX_AGENT_PURPOSE,
|
||||
OpenedPortsRecordDict,
|
||||
OpenedRuleDict,
|
||||
RevokedRulesDict,
|
||||
opened_rule_line,
|
||||
opened_rules_text,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
record_opened_rule_command,
|
||||
revoke_recorded_rules,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
from napalm_device_types.os import OSDriver
|
||||
from napalm_device_types.ospf import OspfMixin
|
||||
from napalm_device_types.package_updates import (
|
||||
@@ -275,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,
|
||||
@@ -336,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,
|
||||
@@ -381,7 +426,14 @@ __all__ = [
|
||||
"OspfInterfaceDict",
|
||||
"OspfMixin",
|
||||
"UpdateProgressDict",
|
||||
"UpdateHistoryAction",
|
||||
"UpdateHistoryDict",
|
||||
"UpdateHistoryPackageDict",
|
||||
"CredentialExpiryDict",
|
||||
"CredentialExpiryMixin",
|
||||
"CredentialKind",
|
||||
"FirmwareOfferMixin",
|
||||
"FirmwareUpgradeMixin",
|
||||
"LicenseDict",
|
||||
"LicenseMixin",
|
||||
"EnsurePackageMixin",
|
||||
@@ -396,6 +448,13 @@ __all__ = [
|
||||
"parse_apt_fetch",
|
||||
"parse_apt_proxy",
|
||||
"same_proxy_url",
|
||||
"APT_RELEASES_COMMAND",
|
||||
"AptReleaseFixDict",
|
||||
"AptReleaseMixin",
|
||||
"AptReleasesDict",
|
||||
"AptSourceDict",
|
||||
"parse_apt_releases",
|
||||
"suite_release",
|
||||
"SnmpAgentMixin",
|
||||
"SnmpAgentSettingsDict",
|
||||
"run_fix_steps",
|
||||
@@ -404,6 +463,21 @@ __all__ = [
|
||||
"check_zabbix_agent_settings",
|
||||
"zabbix_agent_config",
|
||||
"zabbix_repository_command",
|
||||
"OPENED_PORTS_RECORD",
|
||||
"SNMP_PURPOSE",
|
||||
"ZABBIX_AGENT_PURPOSE",
|
||||
"OpenedPortsRecordDict",
|
||||
"OpenedRuleDict",
|
||||
"opened_rule_line",
|
||||
"opened_rules_text",
|
||||
"parse_opened_ports_record",
|
||||
"read_opened_ports_command",
|
||||
"record_opened_rule_command",
|
||||
"RevokedRulesDict",
|
||||
"revoke_recorded_rules",
|
||||
"revoked_output",
|
||||
"ufw_allow_recorded_command",
|
||||
"ufw_delete_command",
|
||||
"SnmpHealthProfile",
|
||||
"SnmpInterfacesSpec",
|
||||
"SnmpMemorySpec",
|
||||
@@ -468,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",
|
||||
|
||||
@@ -53,6 +53,7 @@ from urllib.parse import urlsplit
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.apt_releases import AptReleaseMixin
|
||||
from napalm_device_types.apt_sources import (
|
||||
NOT_CACHED_KEY,
|
||||
VIA_CACHE,
|
||||
@@ -427,7 +428,7 @@ def _described(s: AptProxySettingDict) -> str:
|
||||
return f"{s['file']}:{s['line']} ({s['value']}) {what}"
|
||||
|
||||
|
||||
class AptProxyMixin(PackageProxyMixin):
|
||||
class AptProxyMixin(AptReleaseMixin, PackageProxyMixin):
|
||||
""":class:`~napalm_device_types.fixes.PackageProxyMixin` for a Debian-family host.
|
||||
|
||||
The template form, like :class:`~napalm_device_types.host_status.HostStatusMixin`:
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
"""apt's sources and the release each names, and moving one file's sources to the host's.
|
||||
|
||||
A release upgrade moves the distribution's own sources to the new release and
|
||||
leaves the third-party ones where they were -- or turns them off, and the person
|
||||
who turns them back on keeps the old name. A source on the old release still
|
||||
answers, so apt says nothing; its packages simply stop getting updates once the
|
||||
vendor stops building for that release. Docker's last build for Ubuntu 20.04
|
||||
(``focal``) is 28.1.1, and a noble host on ``focal`` never sees a newer one
|
||||
(NetOrk/netork#2614).
|
||||
|
||||
**What is read** (:meth:`AptReleaseMixin.get_apt_source_releases`): the host's
|
||||
``/etc/os-release`` (``ID``, ``ID_LIKE``, ``VERSION_CODENAME``,
|
||||
``UBUNTU_CODENAME``) and every source apt reads -- ``sources.list`` and the
|
||||
``*.list`` and ``*.sources`` files of ``sources.list.d``, wherever ``apt-config``
|
||||
says they are -- with its file, line, types, URI, suites and components.
|
||||
Commented-out lines and deb822 paragraphs with ``Enabled: no`` are not sources.
|
||||
Whether a suite names another release than the host's is not said here: which
|
||||
words are releases of which distribution is the caller's to know
|
||||
(:func:`suite_release` gives the word).
|
||||
|
||||
**Moving a file** (:meth:`AptReleaseMixin.set_apt_source_release`): every suite of
|
||||
*release* in one of apt's source files becomes the same suite of *codename*
|
||||
(``focal-security`` → ``noble-security``), on enabled lines only. Before anything is
|
||||
written, each new suite's ``InRelease`` (or ``Release``) is fetched from its URI with
|
||||
apt's own downloader and the proxy apt is set to; when one of them is not there,
|
||||
the vendor does not build for *codename* and the file stays as it is. The file is
|
||||
written whole, as root, mode 644. Loading the package index afterwards is the
|
||||
caller's (``refresh_available_updates``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
import shlex
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.fixes import run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "ARELEASE_BEGIN"
|
||||
_END = "ARELEASE_END"
|
||||
|
||||
#: A release's codename: one lower-case word (``noble``, ``bookworm``).
|
||||
_CODENAME = re.compile(r"^[a-z][a-z0-9]*$")
|
||||
#: A suite that names a release: its codename, then perhaps a suffix (``-security``).
|
||||
_SUITE = re.compile(r"^([a-z][a-z0-9]*)(-[a-z0-9-]+)?$")
|
||||
#: One source line of a ``.list`` file, its comment cut off: types, options, URI, suite.
|
||||
_LIST_LINE = re.compile(r"^(\s*(deb|deb-src)\s+(?:\[[^\]]*\]\s+)?(\S+)\s+)(\S+)(.*)$")
|
||||
#: A deb822 field's first line.
|
||||
_FIELD = re.compile(r"^([A-Za-z][A-Za-z0-9-]*):(.*)$")
|
||||
_DISABLED = frozenset({"no", "false", "0"})
|
||||
|
||||
|
||||
class AptSourceDict(TypedDict):
|
||||
"""One source apt reads (``get_apt_source_releases``)."""
|
||||
|
||||
#: The file it is in.
|
||||
file: str
|
||||
#: The line of a ``.list`` file's entry; of a deb822 paragraph's ``Suites:`` field.
|
||||
line: int
|
||||
#: ``deb``, ``deb-src``; a deb822 paragraph may name both.
|
||||
types: list[str]
|
||||
#: Its URI, as written; a deb822 paragraph with several URIs is one source per URI.
|
||||
uri: str
|
||||
#: Its suites; a flat repository's path (``./``) is one too.
|
||||
suites: list[str]
|
||||
components: list[str]
|
||||
|
||||
|
||||
class AptReleasesDict(TypedDict):
|
||||
"""The host's release and its sources (``get_apt_source_releases``)."""
|
||||
|
||||
#: ``ID`` and ``ID_LIKE`` of ``/etc/os-release``; "" and [] when it says none.
|
||||
os_id: str
|
||||
os_like: list[str]
|
||||
#: ``VERSION_CODENAME``; a derivative's own (Linux Mint's ``virginia``).
|
||||
codename: str
|
||||
#: ``UBUNTU_CODENAME``: the Ubuntu release Ubuntu and its derivatives are built on.
|
||||
ubuntu_codename: str
|
||||
sources: list[AptSourceDict]
|
||||
|
||||
|
||||
class AptReleaseFixDict(FixResultDict):
|
||||
"""The result of ``set_apt_source_release``: the fix, and how many suites moved."""
|
||||
|
||||
rewritten: int
|
||||
|
||||
|
||||
def apt_releases_command(
|
||||
apt_config: str = "apt-config", os_release: str = "/etc/os-release"
|
||||
) -> str:
|
||||
"""The read-only command that prints the host's release and apt's source files.
|
||||
|
||||
One line, POSIX ``sh``, no privileges. Every line of a file is printed behind a
|
||||
``|``, so an empty line -- which ends a deb822 paragraph -- comes through.
|
||||
*apt_config* and *os_release* let a test point it elsewhere.
|
||||
"""
|
||||
return (
|
||||
f"( export LC_ALL=C; printf '%s%s\\n' ARELEASE_ BEGIN; echo '@@os'; "
|
||||
f'o={shlex.quote(os_release)}; [ -r "$o" ] || o=/usr/lib/os-release; '
|
||||
'[ -r "$o" ] && sed \'s/^/|/\' "$o"; '
|
||||
f'eval "$({apt_config} shell sl Dir::Etc::sourcelist/f sp Dir::Etc::sourceparts/d '
|
||||
'2>/dev/null)"; sl="${sl:-/etc/apt/sources.list}"; sp="${sp:-/etc/apt/sources.list.d/}"; '
|
||||
'for f in "$sl" "$sp"*.list "$sp"*.sources; do [ -f "$f" ] || continue; '
|
||||
'if [ -r "$f" ]; then printf \'@@file %s\\n\' "$f"; sed \'s/^/|/\' "$f"; '
|
||||
"else printf '@@unreadable %s\\n' \"$f\"; fi; done; "
|
||||
"printf '%s%s\\n' ARELEASE_ END ) 2>/dev/null | cat"
|
||||
)
|
||||
|
||||
|
||||
#: The command as a driver runs it.
|
||||
APT_RELEASES_COMMAND = apt_releases_command()
|
||||
|
||||
|
||||
def suite_release(suite: str) -> str | None:
|
||||
"""The word a suite starts with, ``noble`` of ``noble-security``; None for a path.
|
||||
|
||||
Whether that word is a release, and of which distribution, the caller knows:
|
||||
``stable`` and ``nodistro`` have the form too.
|
||||
"""
|
||||
found = _SUITE.match(suite)
|
||||
return found.group(1) if found else None
|
||||
|
||||
|
||||
def _codename(name: str) -> str:
|
||||
if not _CODENAME.match(name):
|
||||
raise ValueError(f"not a release's codename: {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
# ── Reading ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _blocks(output: str) -> list[tuple[str, list[str]]]:
|
||||
"""``(header, lines)`` of each block between the frame markers, in order."""
|
||||
lines = strip_terminal_codes(output).splitlines()
|
||||
stripped = [line.strip() for line in lines]
|
||||
try:
|
||||
start = stripped.index(_BEGIN)
|
||||
end = stripped.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact apt release report in the output") from None
|
||||
blocks: list[tuple[str, list[str]]] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
if line.startswith("@@"):
|
||||
blocks.append((line[2:].strip(), []))
|
||||
elif line.startswith("|") and blocks:
|
||||
blocks[-1][1].append(line[1:].rstrip("\r"))
|
||||
return blocks
|
||||
|
||||
|
||||
def _os_release(lines: list[str]) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
for line in lines:
|
||||
key, sep, value = line.strip().partition("=")
|
||||
if sep and key:
|
||||
values[key] = value.strip().strip("'\"")
|
||||
return values
|
||||
|
||||
|
||||
def _code(line: str) -> str:
|
||||
"""*line* without its comment."""
|
||||
return line.split("#", 1)[0]
|
||||
|
||||
|
||||
def _list_sources(path: str, lines: list[str]) -> list[AptSourceDict]:
|
||||
found: list[AptSourceDict] = []
|
||||
for number, line in enumerate(lines, start=1):
|
||||
entry = _LIST_LINE.match(_code(line))
|
||||
if entry:
|
||||
_, kind, uri, suite, rest = entry.groups()
|
||||
found.append(
|
||||
{
|
||||
"file": path,
|
||||
"line": number,
|
||||
"types": [kind],
|
||||
"uri": uri,
|
||||
"suites": [suite],
|
||||
"components": rest.split(),
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Field:
|
||||
first: int # index of its first line
|
||||
lines: list[int] = field(default_factory=list) # indices of every line it spans
|
||||
value: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Paragraph:
|
||||
fields: dict[str, _Field] = field(default_factory=dict)
|
||||
|
||||
def value(self, name: str) -> str:
|
||||
found = self.fields.get(name)
|
||||
return found.value if found else ""
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self.value("enabled").strip().lower() not in _DISABLED
|
||||
|
||||
|
||||
def _paragraphs(lines: list[str]) -> list[_Paragraph]:
|
||||
"""The deb822 paragraphs of *lines*; comments are skipped, an empty line ends one."""
|
||||
paragraphs: list[_Paragraph] = []
|
||||
current: _Paragraph | None = None
|
||||
last: _Field | None = None
|
||||
for index, line in enumerate(lines):
|
||||
if not line.strip():
|
||||
current, last = None, None
|
||||
continue
|
||||
if line.lstrip().startswith("#"):
|
||||
continue
|
||||
if line[0] in " \t":
|
||||
if last is not None:
|
||||
last.lines.append(index)
|
||||
last.value += " " + line.strip()
|
||||
continue
|
||||
found = _FIELD.match(line)
|
||||
if not found:
|
||||
continue
|
||||
if current is None:
|
||||
current = _Paragraph()
|
||||
paragraphs.append(current)
|
||||
last = _Field(first=index, lines=[index], value=found.group(2).strip())
|
||||
current.fields[found.group(1).lower()] = last
|
||||
return paragraphs
|
||||
|
||||
|
||||
def _deb822_sources(path: str, lines: list[str]) -> list[AptSourceDict]:
|
||||
found: list[AptSourceDict] = []
|
||||
for paragraph in _paragraphs(lines):
|
||||
suites = paragraph.fields.get("suites")
|
||||
if not paragraph.enabled or suites is None:
|
||||
continue
|
||||
for uri in paragraph.value("uris").split():
|
||||
found.append(
|
||||
{
|
||||
"file": path,
|
||||
"line": suites.first + 1,
|
||||
"types": paragraph.value("types").split(),
|
||||
"uri": uri,
|
||||
"suites": suites.value.split(),
|
||||
"components": paragraph.value("components").split(),
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def _is_deb822(path: str) -> bool:
|
||||
return path.endswith(".sources")
|
||||
|
||||
|
||||
def parse_apt_releases(output: str) -> AptReleasesDict:
|
||||
"""What :func:`apt_releases_command` printed, as :class:`AptReleasesDict`.
|
||||
|
||||
:raises ValueError: if the output carried no intact report.
|
||||
"""
|
||||
os_values: dict[str, str] = {}
|
||||
sources: list[AptSourceDict] = []
|
||||
for header, lines in _blocks(output):
|
||||
kind, _, path = header.partition(" ")
|
||||
if kind == "os":
|
||||
os_values = _os_release(lines)
|
||||
elif kind == "file" and path:
|
||||
read = _deb822_sources if _is_deb822(path) else _list_sources
|
||||
sources.extend(read(path, lines))
|
||||
return {
|
||||
"os_id": os_values.get("ID", "").lower(),
|
||||
"os_like": os_values.get("ID_LIKE", "").lower().split(),
|
||||
"codename": os_values.get("VERSION_CODENAME", "").lower(),
|
||||
"ubuntu_codename": os_values.get("UBUNTU_CODENAME", "").lower(),
|
||||
"sources": sources,
|
||||
}
|
||||
|
||||
|
||||
# ── Rewriting ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _moved(suite: str, release: str, codename: str) -> str:
|
||||
return codename + suite[len(release) :] if suite_release(suite) == release else suite
|
||||
|
||||
|
||||
def _rewrite_list_line(line: str, release: str, codename: str) -> tuple[str, int]:
|
||||
code = _code(line)
|
||||
entry = _LIST_LINE.match(code)
|
||||
if not entry:
|
||||
return line, 0
|
||||
suite = entry.group(4)
|
||||
new = _moved(suite, release, codename)
|
||||
if new == suite:
|
||||
return line, 0
|
||||
head = entry.group(1)
|
||||
return head + new + line[len(head) + len(suite) :], 1
|
||||
|
||||
|
||||
def _rewrite_tokens(text: str, release: str, codename: str) -> tuple[str, int]:
|
||||
changed = 0
|
||||
|
||||
def one(token: re.Match[str]) -> str:
|
||||
nonlocal changed
|
||||
new = _moved(token.group(), release, codename)
|
||||
changed += new != token.group()
|
||||
return new
|
||||
|
||||
return re.sub(r"\S+", one, text), changed
|
||||
|
||||
|
||||
def _rewrite_deb822(lines: list[str], release: str, codename: str) -> int:
|
||||
changed = 0
|
||||
for paragraph in _paragraphs(lines):
|
||||
suites = paragraph.fields.get("suites")
|
||||
if not paragraph.enabled or suites is None:
|
||||
continue
|
||||
for index in suites.lines:
|
||||
line = lines[index]
|
||||
cut = line.index(":") + 1 if index == suites.first else 0
|
||||
tail, count = _rewrite_tokens(line[cut:], release, codename)
|
||||
lines[index] = line[:cut] + tail
|
||||
changed += count
|
||||
return changed
|
||||
|
||||
|
||||
def rewrite_release(text: str, release: str, codename: str, *, deb822: bool) -> tuple[str, int]:
|
||||
"""*text*, a source file, with every suite of *release* on *codename*; and how many.
|
||||
|
||||
Only enabled sources: not a commented-out line, not a paragraph with
|
||||
``Enabled: no``. A URI or comment that names *release* stays as it is.
|
||||
|
||||
:raises ValueError: if *release* or *codename* is not a codename.
|
||||
"""
|
||||
release, codename = _codename(release), _codename(codename)
|
||||
lines = text.split("\n")
|
||||
if deb822:
|
||||
changed = _rewrite_deb822(lines, release, codename)
|
||||
else:
|
||||
changed = 0
|
||||
for index, line in enumerate(lines):
|
||||
lines[index], count = _rewrite_list_line(line, release, codename)
|
||||
changed += count
|
||||
return "\n".join(lines), changed
|
||||
|
||||
|
||||
# ── The mixin ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _release_urls(uri: str, suite: str) -> list[str]:
|
||||
base = f"{uri.rstrip('/')}/dists/{suite}/"
|
||||
return [base + "InRelease", base + "Release"]
|
||||
|
||||
|
||||
class AptReleaseMixin:
|
||||
"""Reads the release each apt source names; moves one file's sources to another.
|
||||
|
||||
The template form, like :class:`~napalm_device_types.apt_proxy.AptProxyMixin`,
|
||||
which brings it to every driver that has it: a driver supplies
|
||||
``_run_apt_command`` and ``_write_apt_file``, and ``_is_apt_host`` where it
|
||||
can be something else.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_apt_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh``, without privileges; what it printed."""
|
||||
...
|
||||
|
||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
"""Replace *path* with *content*, as a new file owned by root, mode 644."""
|
||||
...
|
||||
|
||||
def _is_apt_host(self) -> bool:
|
||||
"""Whether apt is the host's package manager; a driver that can tell overrides it."""
|
||||
return True
|
||||
|
||||
def get_apt_source_releases(self) -> AptReleasesDict | None:
|
||||
"""The host's release and every source apt reads; None on a host without apt.
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
if not self._is_apt_host():
|
||||
return None
|
||||
return parse_apt_releases(self._run_apt_command(APT_RELEASES_COMMAND))
|
||||
|
||||
def set_apt_source_release(self, path: str, release: str, codename: str) -> AptReleaseFixDict:
|
||||
"""Every suite of *release* in *path* on *codename*, where the vendor serves it.
|
||||
|
||||
Three steps: ``read`` (*path* is one of apt's source files, and which of its
|
||||
sources name *release*), ``check`` (each new suite's ``InRelease`` or
|
||||
``Release`` is there) and ``rewrite``. Nothing is written when a step fails;
|
||||
nothing is fetched or written when no source of *path* names *release*.
|
||||
"""
|
||||
moving: list[AptSourceDict] = []
|
||||
rewritten = [0]
|
||||
result = run_fix_steps(
|
||||
[
|
||||
("read", lambda: self._sources_on(path, release, codename, moving)),
|
||||
("check", lambda: self._served(moving, release, codename)),
|
||||
("rewrite", lambda: self._rewrite(path, release, codename, moving, rewritten)),
|
||||
]
|
||||
)
|
||||
return {**result, "rewritten": rewritten[0]}
|
||||
|
||||
def _sources_on(
|
||||
self, path: str, release: str, codename: str, moving: list[AptSourceDict]
|
||||
) -> FixStepOutcomeDict:
|
||||
_codename(release)
|
||||
_codename(codename)
|
||||
found = self.get_apt_source_releases()
|
||||
if found is None:
|
||||
return {"ok": False, "output": "not an apt host"}
|
||||
in_file = [s for s in found["sources"] if s["file"] == path]
|
||||
if not in_file:
|
||||
return {"ok": False, "output": f"{path} is none of apt's source files"}
|
||||
moving.extend(s for s in in_file if any(suite_release(x) == release for x in s["suites"]))
|
||||
if not moving:
|
||||
return {"ok": True, "output": f"no source in {path} is on {release} any more"}
|
||||
named = "; ".join(f"{s['uri']} {' '.join(s['suites'])}" for s in moving)
|
||||
return {"ok": True, "output": f"on {release} in {path}: {named}"}
|
||||
|
||||
def _served(
|
||||
self, moving: list[AptSourceDict], release: str, codename: str
|
||||
) -> FixStepOutcomeDict:
|
||||
from napalm_device_types.apt_proxy import apt_fetch_command, parse_apt_fetch
|
||||
|
||||
wanted = sorted(
|
||||
{
|
||||
(s["uri"], _moved(suite, release, codename))
|
||||
for s in moving
|
||||
for suite in s["suites"]
|
||||
if suite_release(suite) == release
|
||||
}
|
||||
)
|
||||
said: list[str] = []
|
||||
for uri, suite in wanted:
|
||||
error = ""
|
||||
for url in _release_urls(uri, suite):
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(url)))
|
||||
error = fetched["error"]
|
||||
if not error:
|
||||
said.append(f"{uri} serves {suite}")
|
||||
break
|
||||
else:
|
||||
return {"ok": False, "output": f"{uri} has no {suite}: {error}; nothing changed"}
|
||||
return {"ok": True, "output": "; ".join(said) or "nothing to check"}
|
||||
|
||||
def _rewrite(
|
||||
self,
|
||||
path: str,
|
||||
release: str,
|
||||
codename: str,
|
||||
moving: list[AptSourceDict],
|
||||
rewritten: list[int],
|
||||
) -> FixStepOutcomeDict:
|
||||
if not moving:
|
||||
return {"ok": True, "output": "nothing to rewrite"}
|
||||
encoded = "".join(self._run_apt_command(f"base64 {shlex.quote(path)}").split())
|
||||
text = base64.b64decode(encoded).decode()
|
||||
new, count = rewrite_release(text, release, codename, deb822=_is_deb822(path))
|
||||
if not count:
|
||||
return {"ok": True, "output": f"no source in {path} is on {release} any more"}
|
||||
written = self._write_apt_file(path, new)
|
||||
if not written["ok"]:
|
||||
return written
|
||||
rewritten[0] = count
|
||||
suites = "1 suite" if count == 1 else f"{count} suites"
|
||||
return {"ok": True, "output": f"{path}: {suites} moved from {release} to {codename}"}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"APT_RELEASES_COMMAND",
|
||||
"AptReleaseFixDict",
|
||||
"AptReleaseMixin",
|
||||
"AptReleasesDict",
|
||||
"AptSourceDict",
|
||||
"apt_releases_command",
|
||||
"parse_apt_releases",
|
||||
"rewrite_release",
|
||||
"suite_release",
|
||||
]
|
||||
@@ -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}
|
||||
"""
|
||||
...
|
||||
@@ -1,23 +1,39 @@
|
||||
"""The firmware a vendor offers for a device.
|
||||
"""The firmware a vendor offers for a device, and installing it.
|
||||
|
||||
A fact for the caller (docs/STRUCTURE.md): a driver may know the newer firmware
|
||||
from the vendor's download catalogue or the device's own update check; whether
|
||||
running an older one is a problem is decided above the driver. Comparing the
|
||||
vendor's version strings is vendor knowledge, so the driver says itself whether
|
||||
the offer is newer. Declared only; a driver that can tell implements it.
|
||||
|
||||
Installing it is a capability of its own (``FirmwareUpgradeMixin``): when and
|
||||
whether is the caller's call, as with package updates; how is the driver's.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING, NotRequired, TypedDict
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import FirmwareOfferDict
|
||||
class FirmwareOfferDict(TypedDict):
|
||||
"""The firmware a device runs and the newest its vendor offers
|
||||
(``FirmwareOfferMixin.get_firmware_offer``). A fact, not a judgement."""
|
||||
|
||||
current_version: str
|
||||
latest_version: str
|
||||
newer: bool # the offer is newer than what runs, by the vendor's versioning
|
||||
download_url: NotRequired[str]
|
||||
# The driver can install latest_version itself (FirmwareUpgradeMixin) now; False
|
||||
# while the device lacks what that takes (OpenWrt without owut). Left out where
|
||||
# the driver never installs firmware on this device.
|
||||
installable: NotRequired[bool]
|
||||
# The newest of a later release line (OpenWrt 25.12 on a 24.10 device), which
|
||||
# latest_version does not cross to: shown, never installed by the driver.
|
||||
latest_major_version: NotRequired[str]
|
||||
|
||||
|
||||
class FirmwareOfferMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_firmware_offer(self) -> FirmwareOfferDict | None:
|
||||
def get_firmware_offer(self) -> "FirmwareOfferDict | None":
|
||||
"""The firmware running and the newest the vendor offers.
|
||||
|
||||
None when the driver cannot tell for this device (an unknown model,
|
||||
@@ -29,3 +45,23 @@ class FirmwareOfferMixin:
|
||||
"newer": True, "download_url": "https://.../GS308E_1.0.2.12.zip"}
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class FirmwareUpgradeMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def start_firmware_upgrade(self, version: str) -> None:
|
||||
"""Starts installing *version*, an offer's ``latest_version`` that
|
||||
:meth:`FirmwareOfferMixin.get_firmware_offer` called ``installable``.
|
||||
|
||||
The device runs the upgrade by itself and restarts at its end, which
|
||||
ends the session; the configuration is kept. Returns once it has
|
||||
started. ``UpdateMixin.get_update_progress`` follows it until then:
|
||||
``"failed"`` when it stopped before the device restarted, which leaves
|
||||
the running firmware as it was.
|
||||
|
||||
:raises ValueError: *version* is not a version string the driver takes.
|
||||
:raises RuntimeError: the device cannot start it (what it takes is
|
||||
missing, an upgrade is already running).
|
||||
"""
|
||||
...
|
||||
@@ -23,7 +23,7 @@ They replace ``run_device_action`` (docs/STRUCTURE.md):
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
|
||||
from napalm_device_types.models import (
|
||||
FixResultDict,
|
||||
@@ -215,7 +215,9 @@ class ZabbixAgentMixin:
|
||||
where those have none, from Zabbix's repository for ``settings["release"]``
|
||||
(:func:`~napalm_device_types.zabbix_agent.zabbix_repository_command`) --, write
|
||||
its configuration (:func:`~napalm_device_types.zabbix_agent.zabbix_agent_config`),
|
||||
let the allowed sources through the host's firewall, enable and restart it.
|
||||
let the allowed sources through the host's firewall -- for an agent that is
|
||||
``active_only``, which listens on no port, close what netOrk opened for it
|
||||
earlier instead --, enable and restart it.
|
||||
Installing and starting are generic, over ``ensure_package`` and
|
||||
``manage_service`` with ``ZABBIX_AGENT_PACKAGE`` and ``ZABBIX_AGENT_SERVICE``.
|
||||
Whether Zabbix reaches it is the caller's to ask Zabbix.
|
||||
@@ -242,7 +244,7 @@ class ZabbixAgentMixin:
|
||||
[
|
||||
("install", lambda: self._install_zabbix_agent(settings)),
|
||||
("configure", lambda: self._write_zabbix_agent_config(settings)),
|
||||
("firewall", lambda: self._allow_zabbix_agent_sources(settings)),
|
||||
("firewall", lambda: self._open_zabbix_agent_port(settings)),
|
||||
("start", self._start_zabbix_agent),
|
||||
]
|
||||
)
|
||||
@@ -276,6 +278,22 @@ class ZabbixAgentMixin:
|
||||
return ""
|
||||
return f"package index not loaded: {str(loaded.get('output', '')).strip()}"
|
||||
|
||||
def _open_zabbix_agent_port(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
"""The driver's firewall step. An agent that only connects out listens on no
|
||||
port (NetOrk/netork#2683): nothing is opened, and the driver closes what netOrk
|
||||
opened for the agent earlier (``_revoke_zabbix_agent_sources``,
|
||||
NetOrk/netork#2693). A driver without it changes nothing and says why."""
|
||||
if not settings.get("active_only"):
|
||||
return self._allow_zabbix_agent_sources(settings)
|
||||
revoke = getattr(self, "_revoke_zabbix_agent_sources", None)
|
||||
if callable(revoke):
|
||||
return cast(FixStepOutcomeDict, revoke(settings))
|
||||
return {
|
||||
"ok": True,
|
||||
"output": "active only: the agent listens on no port; this driver cannot tell"
|
||||
" a rule netOrk opened for it from the operator's, so the firewall is unchanged",
|
||||
}
|
||||
|
||||
def _start_zabbix_agent(self) -> FixStepOutcomeDict:
|
||||
return enable_and_restart(self.manage_service, self.ZABBIX_AGENT_SERVICE)
|
||||
|
||||
@@ -306,7 +324,20 @@ class ZabbixAgentMixin:
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Let ``settings["allowed_sources"]`` reach tcp/``listen_port``; ``ok`` with
|
||||
nothing to do where the host has no firewall of its own, or for []."""
|
||||
nothing to do where the host has no firewall of its own, or for []. Not
|
||||
called for an ``active_only`` agent."""
|
||||
...
|
||||
|
||||
# Optional: a driver that can tell its own rules from the operator's.
|
||||
|
||||
def _revoke_zabbix_agent_sources(
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Close what ``_allow_zabbix_agent_sources`` opened for the agent on an
|
||||
earlier run, for an ``active_only`` agent, and nothing else: a rule the
|
||||
operator wrote stays, however alike (NetOrk/netork#2693). ``ok`` where
|
||||
nothing was opened. Where the firewall itself does not say who wrote a
|
||||
rule, the driver keeps :mod:`~napalm_device_types.opened_ports`' record."""
|
||||
...
|
||||
|
||||
|
||||
|
||||
@@ -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,15 +76,19 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - VM display name
|
||||
* vmid (string) - hypervisor-internal ID (Proxmox: ``"100"``,
|
||||
VMware: the instance UUID)
|
||||
* status (string) - ``"running"``, ``"stopped"``, ``"paused"``, ``"suspended"``
|
||||
* 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``
|
||||
``paused``), ``"suspended"`` once its state was saved away (VMware's
|
||||
``suspended``). :meth:`resume_vm` brings either back.
|
||||
* vcpus (int) - number of virtual CPUs assigned
|
||||
* memory (int) - configured RAM in megabytes
|
||||
* cpu_usage (float) - current CPU utilisation 0.0–1.0
|
||||
* 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::
|
||||
|
||||
@@ -248,7 +259,9 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
def suspend_vm(self, name: str) -> None:
|
||||
"""
|
||||
Suspends (pauses) a running virtual machine, preserving its in-memory
|
||||
state. The VM can be resumed with :meth:`start_vm`.
|
||||
state. :meth:`get_vms` then reports it ``"paused"`` (its process
|
||||
still holds the memory) or ``"suspended"`` (its state was saved
|
||||
away), and :meth:`resume_vm` brings it back.
|
||||
|
||||
:param name: VM name or its ``vmid``.
|
||||
:raises ValueError: If no VM with the given name/ID exists.
|
||||
@@ -260,6 +273,33 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
"""
|
||||
...
|
||||
|
||||
def resume_vm(self, name: str) -> None:
|
||||
"""
|
||||
Resumes a paused or suspended virtual machine where it stopped, the
|
||||
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
|
||||
Proxmox container) refuses the others with ``RuntimeError``.
|
||||
|
||||
:param name: VM name or its ``vmid``.
|
||||
:raises ValueError: If no VM with the given name/ID exists.
|
||||
:raises RuntimeError: If the VM is neither paused nor suspended, or
|
||||
the platform cannot resume this kind of guest.
|
||||
|
||||
Example::
|
||||
|
||||
driver.resume_vm("web01")
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Snapshots
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -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):
|
||||
@@ -1172,16 +1172,6 @@ class OspfDict(TypedDict):
|
||||
interfaces: dict[str, OspfInterfaceDict] # by interface name
|
||||
|
||||
|
||||
class FirmwareOfferDict(TypedDict):
|
||||
"""The firmware a device runs and the newest its vendor offers
|
||||
(``FirmwareOfferMixin.get_firmware_offer``). A fact, not a judgement."""
|
||||
|
||||
current_version: str
|
||||
latest_version: str
|
||||
newer: bool # the offer is newer than what runs, by the vendor's versioning
|
||||
download_url: NotRequired[str]
|
||||
|
||||
|
||||
class HypervisorHostDict(TypedDict):
|
||||
"""One host of a hypervisor or cluster (``HypervisorDriver.get_hypervisor_hosts``)."""
|
||||
|
||||
@@ -1440,3 +1430,7 @@ class ManagementProtocolsDict(TypedDict):
|
||||
snmp: ProtocolStateDict
|
||||
kvm: ProtocolStateDict
|
||||
virtual_media: ProtocolStateDict
|
||||
|
||||
|
||||
# Importable from here as before 4.41; it lives with its contract now.
|
||||
from napalm_device_types.firmware import FirmwareOfferDict as FirmwareOfferDict # noqa: E402
|
||||
@@ -0,0 +1,341 @@
|
||||
"""The record of the firewall rules netOrk opened on a host (NetOrk/netork#2693).
|
||||
|
||||
ufw, iptables and firewalld do not say who wrote a rule: a rule netOrk added to let an
|
||||
agent's server through looks exactly like one the operator wrote. To close it again --
|
||||
when a Zabbix agent becomes active only, say, and listens on no port any more -- a
|
||||
driver needs to know which rules are netOrk's. So a driver that opens a port in one of
|
||||
them records the rule in :data:`OPENED_PORTS_RECORD`, a file only root may write, and
|
||||
**only when the firewall did not have the rule before**: an identical rule the operator
|
||||
wrote earlier is never recorded, and so never removed. Closing removes exactly the
|
||||
recorded rules and leaves every other one in place; what it left for the same port is
|
||||
reported (:func:`revoked_output`). Rules opened before a driver recorded them have no
|
||||
line here and stay, reported.
|
||||
|
||||
**The line.** One rule per line, whitespace-separated, read strictly::
|
||||
|
||||
v1 <purpose> <backend> <proto> <port> <source> # ufw, iptables
|
||||
v1 <purpose> firewalld <proto> <port> <source> <zone> <runtime|permanent>
|
||||
|
||||
``purpose`` says which agent opened it (``zabbix-agent``, ``snmp``), ``source`` is a
|
||||
network in its normal form (``10.0.0.1/32``). A line that is not exactly that is
|
||||
reported and never acted on; it stays in the file.
|
||||
|
||||
**The file.** It is read only when the directory and the file are root's, are not
|
||||
writable by anyone else and are what they claim to be (no symbolic link): a record
|
||||
someone else could have written could name the operator's rules.
|
||||
|
||||
What is the same on every host and needs no I/O lives here: the line, reading it,
|
||||
the shell that records a rule, and ufw's commands, which napalm-linux and
|
||||
napalm-proxmox share. A driver runs them as root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from typing import Literal, TypedDict, cast
|
||||
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
#: Where a host keeps the rules netOrk opened, root's and outside every account's home.
|
||||
OPENED_PORTS_DIRECTORY = "/var/lib/netork"
|
||||
OPENED_PORTS_RECORD = f"{OPENED_PORTS_DIRECTORY}/opened-ports"
|
||||
|
||||
#: The purposes the drivers record their rules under.
|
||||
ZABBIX_AGENT_PURPOSE = "zabbix-agent"
|
||||
SNMP_PURPOSE = "snmp"
|
||||
|
||||
Backend = Literal["ufw", "iptables", "firewalld"]
|
||||
_BACKENDS = ("ufw", "iptables", "firewalld")
|
||||
|
||||
_PURPOSE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
|
||||
_ZONE = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
|
||||
#: What :func:`record_opened_rule_command` puts between double quotes: the line's own
|
||||
#: characters, and ``$z`` for a zone the shell loops over.
|
||||
_RECORDABLE = re.compile(r"^v1( (\$z|[A-Za-z0-9./:_-]+))+$")
|
||||
|
||||
|
||||
class OpenedRuleDict(TypedDict):
|
||||
"""One rule netOrk opened, as its record line says."""
|
||||
|
||||
purpose: str
|
||||
backend: Backend
|
||||
proto: Literal["tcp", "udp"]
|
||||
port: int
|
||||
#: The network in its normal form, ``10.0.0.1/32``.
|
||||
source: str
|
||||
#: firewalld's zone; "" for ufw and iptables.
|
||||
zone: str
|
||||
#: firewalld: the permanent configuration, not the runtime one. True for the others.
|
||||
permanent: bool
|
||||
|
||||
|
||||
class OpenedPortsRecordDict(TypedDict):
|
||||
"""What :func:`parse_opened_ports_record` read."""
|
||||
|
||||
rules: list[OpenedRuleDict]
|
||||
#: Lines that are not exactly a rule: reported, never acted on.
|
||||
unknown: list[str]
|
||||
#: Why the record was not read at all; "" when it was, or when there is none.
|
||||
problem: str
|
||||
|
||||
|
||||
def opened_rule_line(rule: OpenedRuleDict) -> str:
|
||||
"""The record's line for *rule*."""
|
||||
fields = ["v1", rule["purpose"], rule["backend"], rule["proto"], str(rule["port"])]
|
||||
fields.append(rule["source"])
|
||||
if rule["backend"] == "firewalld":
|
||||
fields += [rule["zone"], "permanent" if rule["permanent"] else "runtime"]
|
||||
return " ".join(fields)
|
||||
|
||||
|
||||
def _network(value: str) -> bool:
|
||||
"""Whether *value* is a network in its normal form, with its prefix."""
|
||||
try:
|
||||
return "/" in value and str(ipaddress.ip_network(value)) == value
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _port(value: str) -> bool:
|
||||
return value.isdigit() and value == str(int(value)) and 0 < int(value) < 65536
|
||||
|
||||
|
||||
def _firewalld_place(fields: list[str]) -> tuple[str, bool] | None:
|
||||
"""firewalld's zone and whether the configuration is the permanent one, or None."""
|
||||
zone, scope = fields
|
||||
if not _ZONE.match(zone) or scope not in ("runtime", "permanent"):
|
||||
return None
|
||||
return zone, scope == "permanent"
|
||||
|
||||
|
||||
def _well_formed(fields: list[str]) -> bool:
|
||||
"""Whether *fields* are a rule line's: version, backend and as many as it takes,
|
||||
a purpose, a protocol, a port and a network."""
|
||||
backend = fields[2] if len(fields) > 2 else ""
|
||||
if fields[0] != "v1" or backend not in _BACKENDS:
|
||||
return False
|
||||
if len(fields) != (8 if backend == "firewalld" else 6):
|
||||
return False
|
||||
purpose, proto, port, source = fields[1], fields[3], fields[4], fields[5]
|
||||
return (
|
||||
bool(_PURPOSE.match(purpose))
|
||||
and proto in ("tcp", "udp")
|
||||
and _port(port)
|
||||
and _network(source)
|
||||
)
|
||||
|
||||
|
||||
def _rule(line: str) -> OpenedRuleDict | None:
|
||||
"""The rule *line* says, or None where it is not exactly one."""
|
||||
fields = line.split(" ")
|
||||
if not _well_formed(fields):
|
||||
return None
|
||||
purpose, backend, proto, port, source = fields[1:6]
|
||||
place = _firewalld_place(fields[6:]) if backend == "firewalld" else ("", True)
|
||||
if place is None:
|
||||
return None
|
||||
return {
|
||||
"purpose": purpose,
|
||||
"backend": cast(Backend, backend),
|
||||
"proto": cast(Literal["tcp", "udp"], proto),
|
||||
"port": int(port),
|
||||
"source": source,
|
||||
"zone": place[0],
|
||||
"permanent": place[1],
|
||||
}
|
||||
|
||||
|
||||
def read_opened_ports_command() -> str:
|
||||
"""The shell, as root, that prints owner, mode and kind of the directory and the
|
||||
record, then the record; nothing where there is no record."""
|
||||
return (
|
||||
f"if [ -e {OPENED_PORTS_RECORD} ] || [ -L {OPENED_PORTS_RECORD} ]; then"
|
||||
f" stat -c '%u %a %F' {OPENED_PORTS_DIRECTORY} {OPENED_PORTS_RECORD}"
|
||||
f" && cat {OPENED_PORTS_RECORD}; fi"
|
||||
)
|
||||
|
||||
|
||||
def _untrusted(stat_line: str, kind: str) -> str:
|
||||
"""Why the path *stat_line* describes may not be trusted; "" where it may."""
|
||||
parts = stat_line.split(" ", 2)
|
||||
if len(parts) != 3 or not parts[1].isdigit():
|
||||
return "owner and mode unknown"
|
||||
owner, mode, actual = parts
|
||||
if actual != kind:
|
||||
return f"not a {kind}"
|
||||
if owner != "0":
|
||||
return "not root's"
|
||||
if int(mode, 8) & 0o022:
|
||||
return "writable by others than root"
|
||||
return ""
|
||||
|
||||
|
||||
def parse_opened_ports_record(output: str) -> OpenedPortsRecordDict:
|
||||
"""The rules the output of :func:`read_opened_ports_command` names.
|
||||
|
||||
Nothing at all where the directory or the record is not root's alone; lines that
|
||||
are not exactly a rule go to ``unknown``.
|
||||
"""
|
||||
if not output.strip():
|
||||
return {"rules": [], "unknown": [], "problem": ""}
|
||||
lines = output.split("\n")
|
||||
for path, stat_line, kind in (
|
||||
(OPENED_PORTS_DIRECTORY, lines[0], "directory"),
|
||||
(OPENED_PORTS_RECORD, lines[1] if len(lines) > 1 else "", "regular file"),
|
||||
):
|
||||
why = _untrusted(stat_line.strip(), kind)
|
||||
if why:
|
||||
return {"rules": [], "unknown": [], "problem": f"{path}: {why}; not read"}
|
||||
rules: list[OpenedRuleDict] = []
|
||||
unknown: list[str] = []
|
||||
for line in lines[2:]:
|
||||
if not line.strip():
|
||||
continue
|
||||
rule = _rule(line)
|
||||
if rule is None:
|
||||
unknown.append(line)
|
||||
else:
|
||||
rules.append(rule)
|
||||
return {"rules": rules, "unknown": unknown, "problem": ""}
|
||||
|
||||
|
||||
class RevokedRulesDict(TypedDict):
|
||||
"""What :func:`revoke_recorded_rules` did."""
|
||||
|
||||
removed: list[OpenedRuleDict]
|
||||
#: The record after it: every other line, in order, as the driver writes it back.
|
||||
record: str
|
||||
#: A rule it could not remove, with why; it stays in ``record``.
|
||||
failed: list[str]
|
||||
|
||||
|
||||
def revoke_recorded_rules(
|
||||
record: OpenedPortsRecordDict,
|
||||
purpose: str,
|
||||
remove: Callable[[OpenedRuleDict], FixStepOutcomeDict],
|
||||
) -> RevokedRulesDict:
|
||||
"""Remove each rule of *record* recorded under *purpose*, whatever port it opened,
|
||||
with the driver's *remove*; keep every other line, the unknown ones too."""
|
||||
removed: list[OpenedRuleDict] = []
|
||||
kept: list[str] = []
|
||||
failed: list[str] = []
|
||||
for rule in record["rules"]:
|
||||
if rule["purpose"] == purpose:
|
||||
outcome = remove(rule)
|
||||
if outcome["ok"]:
|
||||
removed.append(rule)
|
||||
continue
|
||||
failed.append(f"{opened_rule_line(rule)}: {outcome.get('output', '')}")
|
||||
kept.append(opened_rule_line(rule))
|
||||
return {
|
||||
"removed": removed,
|
||||
"record": opened_rules_text(kept + record["unknown"]),
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
|
||||
def opened_rules_text(lines: list[str]) -> str:
|
||||
"""The record holding *lines*, as a driver writes it back after closing rules."""
|
||||
return "".join(f"{line}\n" for line in lines)
|
||||
|
||||
|
||||
def record_opened_rule_command(line: str) -> str:
|
||||
"""The shell, as root, that appends *line* to the record, creating root's
|
||||
directory and file where they are missing.
|
||||
|
||||
*line* is :func:`opened_rule_line`'s, where firewalld's zone may be ``$z``, the
|
||||
variable of a shell loop over the zones.
|
||||
|
||||
:raises ValueError: for anything else.
|
||||
"""
|
||||
if not _RECORDABLE.match(line):
|
||||
raise ValueError(f"not a record line: {line!r}")
|
||||
return (
|
||||
f"install -d -m 755 -o root -g root {OPENED_PORTS_DIRECTORY}"
|
||||
f" && printf '%s\\n' \"{line}\" >> {OPENED_PORTS_RECORD}"
|
||||
f" && chmod 644 {OPENED_PORTS_RECORD}"
|
||||
)
|
||||
|
||||
|
||||
def _ufw_rule(source: str, port: int, proto: str) -> str:
|
||||
return f"from {source} to any port {port} proto {proto}"
|
||||
|
||||
|
||||
def ufw_allow_recorded_command(source: str, port: int, proto: str, purpose: str) -> str:
|
||||
"""The shell, as root, that lets *source* reach *proto*/*port* in ufw and records
|
||||
the rule when ufw added it.
|
||||
|
||||
ufw answers "Skipping adding existing rule" for a rule it had -- someone else's,
|
||||
which is not recorded -- and "Rule added" (active) or "Rules updated" (inactive)
|
||||
for a new one. ``LC_ALL=C`` keeps those words English.
|
||||
"""
|
||||
line = opened_rule_line(
|
||||
{
|
||||
"purpose": purpose,
|
||||
"backend": "ufw",
|
||||
"proto": cast(Literal["tcp", "udp"], proto),
|
||||
"port": port,
|
||||
"source": source,
|
||||
"zone": "",
|
||||
"permanent": True,
|
||||
}
|
||||
)
|
||||
return (
|
||||
f"{{ o=$(LC_ALL=C ufw allow {_ufw_rule(source, port, proto)} 2>&1);"
|
||||
f' s=$?; echo "$o"; [ "$s" -eq 0 ] && case "$o" in *Skipping*) ;;'
|
||||
f" *'Rule added'*|*'Rules updated'*) {record_opened_rule_command(line)};; esac; }}"
|
||||
)
|
||||
|
||||
|
||||
def ufw_delete_command(rule: OpenedRuleDict) -> str:
|
||||
"""The shell, as root, that deletes *rule* from ufw; done too where ufw no longer
|
||||
has it ("Could not delete non-existent rule")."""
|
||||
return (
|
||||
"{ o=$(LC_ALL=C ufw delete allow"
|
||||
f" {_ufw_rule(rule['source'], rule['port'], rule['proto'])} 2>&1)"
|
||||
' || case "$o" in *non-existent*) ;; *) echo "$o"; false ;; esac; }'
|
||||
)
|
||||
|
||||
|
||||
def revoked_output(
|
||||
removed: list[OpenedRuleDict], *, unknown: list[str], left: int, proto: str, port: int
|
||||
) -> str:
|
||||
"""What closing said: the rules it *removed*, the record lines it could not read,
|
||||
and the *left* rules for *proto*/*port* that netOrk did not record."""
|
||||
parts = []
|
||||
if removed:
|
||||
sources = ", ".join(sorted({r["source"] for r in removed}))
|
||||
ports = ", ".join(sorted({f"{r['proto']}/{r['port']}" for r in removed}))
|
||||
parts.append(f"removed the rules netOrk opened for {ports} from {sources}")
|
||||
else:
|
||||
parts.append("netOrk recorded no rule it opened; nothing removed")
|
||||
if unknown:
|
||||
parts.append(f"record lines not understood, left alone: {'; '.join(unknown)}")
|
||||
if left:
|
||||
parts.append(
|
||||
f"{left} rule(s) for {proto}/{port} that netOrk did not record are left in place"
|
||||
" -- the operator's, or opened before netOrk recorded its rules"
|
||||
)
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OPENED_PORTS_DIRECTORY",
|
||||
"OPENED_PORTS_RECORD",
|
||||
"SNMP_PURPOSE",
|
||||
"ZABBIX_AGENT_PURPOSE",
|
||||
"OpenedPortsRecordDict",
|
||||
"OpenedRuleDict",
|
||||
"opened_rule_line",
|
||||
"opened_rules_text",
|
||||
"parse_opened_ports_record",
|
||||
"read_opened_ports_command",
|
||||
"record_opened_rule_command",
|
||||
"RevokedRulesDict",
|
||||
"revoke_recorded_rules",
|
||||
"revoked_output",
|
||||
"ufw_allow_recorded_command",
|
||||
"ufw_delete_command",
|
||||
]
|
||||
@@ -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))
|
||||
@@ -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`
|
||||
@@ -97,7 +173,8 @@ class UpdateMixin:
|
||||
"""
|
||||
Where an update the device runs by itself stands, for a caller that
|
||||
follows it: a firewall's firmware upgrade, which :meth:`apply_updates`
|
||||
only starts. ``state`` is ``"running"`` until it ends in ``"done"``
|
||||
only starts, or one that ``FirmwareUpgradeMixin.start_firmware_upgrade``
|
||||
started. ``state`` is ``"running"`` until it ends in ``"done"``
|
||||
or ``"failed"``; ``log`` is the device's whole log of it.
|
||||
|
||||
Declared only: a driver whose :meth:`apply_updates` returns when the
|
||||
|
||||
@@ -12,6 +12,13 @@ reads and writes the file and runs the command.
|
||||
``Hostname`` -- the host's technical name in Zabbix, which an active agent sends.
|
||||
Every other line stays as it was; a key the file does not set is added at its end.
|
||||
|
||||
**Active only** (NetOrk/netork#2683). An agent whose site only lets it connect out
|
||||
gets ``StartAgents=0``: Zabbix's agent then runs no passive checks and listens on no
|
||||
port. ``Server`` is mandatory only while ``StartAgents`` is not 0, so it is commented
|
||||
out -- nobody may ask -- and ``ServerActive`` is required instead. An agent that is not
|
||||
active only gets a ``StartAgents=0`` line commented out, since it would keep the agent
|
||||
from listening; another count of listeners stays.
|
||||
|
||||
**The repository.** Zabbix publishes a ``zabbix-release`` package per release line
|
||||
and distribution that adds its repository and key. Since 7.2 it lives under
|
||||
``<release>/release/<distribution>/``; up to 7.0 under ``<release>/<distribution>/``,
|
||||
@@ -39,6 +46,9 @@ class ZabbixAgentSettingsDict(TypedDict):
|
||||
# the server's release line ("7.4"): Zabbix's repository to fall back to where the
|
||||
# host's own packages have no agent; absent: no fallback
|
||||
release: NotRequired[str]
|
||||
# the agent only connects out: StartAgents=0, Server commented out (``server`` may be
|
||||
# ""), ServerActive required, and the firewall step opens nothing; absent: False
|
||||
active_only: NotRequired[bool]
|
||||
|
||||
|
||||
#: Addresses, comma-separated, as ``Server`` and ``ServerActive`` take them: names,
|
||||
@@ -49,7 +59,7 @@ _HOSTNAME = re.compile(r"^[A-Za-z0-9._ -]+$")
|
||||
#: A release line, as Zabbix's repository names it.
|
||||
_RELEASE = re.compile(r"^(\d+)\.(\d+)$")
|
||||
|
||||
_KEYS = ("Server", "ServerActive", "ListenPort", "Hostname")
|
||||
_KEYS = ("Server", "ServerActive", "ListenPort", "Hostname", "StartAgents")
|
||||
_LINE = re.compile(r"^(\s*)(" + "|".join(_KEYS) + r")\s*=\s*(.*?)\s*$")
|
||||
|
||||
REPOSITORY = "https://repo.zabbix.com/zabbix"
|
||||
@@ -72,8 +82,11 @@ def check_zabbix_agent_settings(settings: ZabbixAgentSettingsDict) -> None:
|
||||
|
||||
:raises ValueError: naming the setting.
|
||||
"""
|
||||
_check_addresses("Server", str(settings.get("server", "")), required=True)
|
||||
_check_addresses("ServerActive", str(settings.get("server_active", "")), required=False)
|
||||
active_only = settings.get("active_only", False)
|
||||
if not isinstance(active_only, bool):
|
||||
raise ValueError(f"active_only is True or False, not {active_only!r}")
|
||||
_check_addresses("Server", str(settings.get("server", "")), required=not active_only)
|
||||
_check_addresses("ServerActive", str(settings.get("server_active", "")), required=active_only)
|
||||
hostname = settings.get("hostname")
|
||||
if hostname is not None and not _HOSTNAME.match(hostname):
|
||||
raise ValueError(f"not a Zabbix host name: {hostname!r}")
|
||||
@@ -91,34 +104,49 @@ def _check_addresses(key: str, value: str, *, required: bool) -> None:
|
||||
|
||||
|
||||
def _wanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]:
|
||||
"""The value of each key the caller sets; "" comments the key out."""
|
||||
active_only = bool(settings.get("active_only"))
|
||||
wanted = {
|
||||
"Server": settings["server"],
|
||||
"Server": "" if active_only else settings["server"],
|
||||
"ServerActive": settings.get("server_active", ""),
|
||||
"ListenPort": str(settings["listen_port"]),
|
||||
}
|
||||
if settings.get("hostname"):
|
||||
wanted["Hostname"] = str(settings["hostname"])
|
||||
if active_only:
|
||||
wanted["StartAgents"] = "0"
|
||||
return wanted
|
||||
|
||||
|
||||
def _unwanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]:
|
||||
"""Lines commented out where they hold this value, though the caller sets no value
|
||||
for their key: ``StartAgents=0`` would keep an agent that is not active only from
|
||||
listening."""
|
||||
return {} if settings.get("active_only") else {"StartAgents": "0"}
|
||||
|
||||
|
||||
def zabbix_agent_config(text: str, settings: ZabbixAgentSettingsDict) -> tuple[str, list[str]]:
|
||||
"""*text*, an agent's configuration file, with *settings*; and what changed, one
|
||||
``"Key: old → new"`` each.
|
||||
|
||||
An empty ``server_active`` comments ``ServerActive`` out: the agent then runs
|
||||
passive checks only.
|
||||
passive checks only. ``active_only`` is the other way round: ``StartAgents=0``
|
||||
and ``Server`` commented out.
|
||||
"""
|
||||
wanted = _wanted(settings)
|
||||
wanted, unwanted = _wanted(settings), _unwanted(settings)
|
||||
lines: list[str] = []
|
||||
changes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for line in text.splitlines(keepends=True):
|
||||
match = _LINE.match(line.rstrip("\r\n"))
|
||||
if not match or match.group(2) not in wanted:
|
||||
key = match.group(2) if match else ""
|
||||
if match and key in wanted:
|
||||
seen.add(key)
|
||||
lines.append(_set_line(line, match, wanted, changes))
|
||||
elif match and unwanted.get(key) == match.group(3):
|
||||
lines.append(_set_line(line, match, {key: ""}, changes))
|
||||
else:
|
||||
lines.append(line)
|
||||
continue
|
||||
seen.add(match.group(2))
|
||||
lines.append(_set_line(line, match, wanted, changes))
|
||||
_add_missing(
|
||||
lines, [key for key in _KEYS if wanted.get(key) and key not in seen], wanted, changes
|
||||
)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "4.40.0"
|
||||
version = "4.46.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"mypy_relaxed": [],
|
||||
"python_file_lines": {
|
||||
"napalm_device_types/models.py": 1442
|
||||
"napalm_device_types/models.py": 1436
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
"""apt's sources and the release they name, and moving one file's sources to the host's.
|
||||
|
||||
A release upgrade keeps third-party sources on the old release: z2m-house, Ubuntu
|
||||
24.04 (noble), kept Docker's source on ``focal`` and never saw a Docker newer than
|
||||
the last focal build (NetOrk/netork#2614). The read command runs here for real, on
|
||||
files in a temporary directory that ``apt-config -o`` points apt's settings at.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.apt_proxy import AptProxyMixin
|
||||
from napalm_device_types.apt_releases import (
|
||||
AptReleaseMixin,
|
||||
apt_releases_command,
|
||||
parse_apt_releases,
|
||||
rewrite_release,
|
||||
suite_release,
|
||||
)
|
||||
|
||||
_APT_CONFIG = shutil.which("apt-config")
|
||||
needs_apt = pytest.mark.skipif(_APT_CONFIG is None, reason="apt-config is not on this host")
|
||||
|
||||
_NOBLE = (
|
||||
'PRETTY_NAME="Ubuntu 24.04.3 LTS"\nNAME="Ubuntu"\nVERSION_ID="24.04"\n'
|
||||
"VERSION_CODENAME=noble\nID=ubuntu\nID_LIKE=debian\nUBUNTU_CODENAME=noble\n"
|
||||
)
|
||||
_TRIXIE = 'PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nVERSION_CODENAME=trixie\nID=debian\n'
|
||||
_MINT = (
|
||||
'NAME="Linux Mint"\nVERSION_CODENAME=virginia\nID=linuxmint\nID_LIKE="ubuntu debian"\n'
|
||||
"UBUNTU_CODENAME=jammy\n"
|
||||
)
|
||||
|
||||
#: z2m-house's Docker source, as found: through the cache, on focal (#2614).
|
||||
_Z2M_DOCKER = "deb http://HTTPS///download.docker.com/linux/ubuntu focal stable\n"
|
||||
_Z2M_DOCKER_FILE = "archive_uri-https_download_docker_com_linux_ubuntu-noble.list"
|
||||
_UBUNTU_SOURCES = (
|
||||
"Types: deb\n"
|
||||
"URIs: http://archive.ubuntu.com/ubuntu/\n"
|
||||
"Suites: noble noble-updates noble-backports\n"
|
||||
"Components: main restricted universe multiverse\n"
|
||||
"Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n"
|
||||
"\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://security.ubuntu.com/ubuntu/\n"
|
||||
"Suites: noble-security\n"
|
||||
"Components: main restricted universe multiverse\n"
|
||||
)
|
||||
|
||||
|
||||
def _framed(os_release: str, files: dict[str, str]) -> str:
|
||||
"""What :func:`apt_releases_command` prints for *os_release* and *files*."""
|
||||
lines = ["ARELEASE_BEGIN", "@@os"]
|
||||
lines += [f"|{line}" for line in os_release.splitlines()]
|
||||
for path, text in files.items():
|
||||
lines.append(f"@@file {path}")
|
||||
lines += [f"|{line}" for line in text.splitlines()]
|
||||
lines.append("ARELEASE_END")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
class TestSuiteRelease:
|
||||
@pytest.mark.parametrize(
|
||||
("suite", "release"),
|
||||
[
|
||||
("noble", "noble"),
|
||||
("noble-security", "noble"),
|
||||
("noble-updates", "noble"),
|
||||
("focal-backports", "focal"),
|
||||
("bookworm-proposed-updates", "bookworm"),
|
||||
("trixie-security", "trixie"),
|
||||
],
|
||||
)
|
||||
def test_the_release_a_suite_names(self, suite, release):
|
||||
assert suite_release(suite) == release
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("suite", "word"),
|
||||
[("stable", "stable"), ("nodistro", "nodistro"), ("pve-no-subscription", "pve")],
|
||||
)
|
||||
def test_a_word_the_caller_judges(self, suite, word):
|
||||
# Which words are releases is the caller's to know: "stable" has the form too.
|
||||
assert suite_release(suite) == word
|
||||
|
||||
@pytest.mark.parametrize("suite", ["/", "./", "focal/", "Focal", "$(ARCH)", ""])
|
||||
def test_a_suite_of_another_form(self, suite):
|
||||
# A flat repository's path, or anything not a lower-case word, names none.
|
||||
assert suite_release(suite) is None
|
||||
|
||||
|
||||
class TestParse:
|
||||
def test_the_host_and_a_list_source(self):
|
||||
found = parse_apt_releases(
|
||||
_framed(_NOBLE, {f"/etc/apt/sources.list.d/{_Z2M_DOCKER_FILE}": _Z2M_DOCKER})
|
||||
)
|
||||
assert found["os_id"] == "ubuntu"
|
||||
assert found["os_like"] == ["debian"]
|
||||
assert found["codename"] == "noble"
|
||||
assert found["ubuntu_codename"] == "noble"
|
||||
assert found["sources"] == [
|
||||
{
|
||||
"file": f"/etc/apt/sources.list.d/{_Z2M_DOCKER_FILE}",
|
||||
"line": 1,
|
||||
"types": ["deb"],
|
||||
"uri": "http://HTTPS///download.docker.com/linux/ubuntu",
|
||||
"suites": ["focal"],
|
||||
"components": ["stable"],
|
||||
}
|
||||
]
|
||||
|
||||
def test_options_comments_and_disabled_lines(self):
|
||||
text = (
|
||||
"# deb http://old.example/ubuntu bionic main\n"
|
||||
"\n"
|
||||
"deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] "
|
||||
"https://download.docker.com/linux/ubuntu jammy stable # moved by hand\n"
|
||||
"deb-src [ arch=amd64 ] http://archive.ubuntu.com/ubuntu noble main\n"
|
||||
"deb https://repo.example/flat ./\n"
|
||||
)
|
||||
found = parse_apt_releases(_framed(_NOBLE, {"/etc/apt/sources.list": text}))
|
||||
assert [
|
||||
(s["line"], s["types"], s["uri"], s["suites"], s["components"])
|
||||
for s in found["sources"]
|
||||
] == [
|
||||
(3, ["deb"], "https://download.docker.com/linux/ubuntu", ["jammy"], ["stable"]),
|
||||
(4, ["deb-src"], "http://archive.ubuntu.com/ubuntu", ["noble"], ["main"]),
|
||||
(5, ["deb"], "https://repo.example/flat", ["./"], []),
|
||||
]
|
||||
|
||||
def test_deb822_paragraphs_one_per_uri(self):
|
||||
text = (
|
||||
"Types: deb deb-src\n"
|
||||
"URIs: http://a.example/ubuntu http://b.example/ubuntu\n"
|
||||
"Suites: focal\n"
|
||||
" focal-updates\n"
|
||||
"Components: main\n"
|
||||
"\n"
|
||||
"# a comment between paragraphs\n"
|
||||
"Enabled: no\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://c.example/ubuntu\n"
|
||||
"Suites: bionic\n"
|
||||
"Components: main\n"
|
||||
)
|
||||
found = parse_apt_releases(_framed(_NOBLE, {"/etc/apt/sources.list.d/x.sources": text}))
|
||||
assert [(s["line"], s["types"], s["uri"], s["suites"]) for s in found["sources"]] == [
|
||||
(3, ["deb", "deb-src"], "http://a.example/ubuntu", ["focal", "focal-updates"]),
|
||||
(3, ["deb", "deb-src"], "http://b.example/ubuntu", ["focal", "focal-updates"]),
|
||||
]
|
||||
|
||||
def test_debian_and_a_derivative(self):
|
||||
assert parse_apt_releases(_framed(_TRIXIE, {}))["codename"] == "trixie"
|
||||
mint = parse_apt_releases(_framed(_MINT, {}))
|
||||
assert (mint["os_id"], mint["os_like"], mint["codename"], mint["ubuntu_codename"]) == (
|
||||
"linuxmint",
|
||||
["ubuntu", "debian"],
|
||||
"virginia",
|
||||
"jammy",
|
||||
)
|
||||
|
||||
def test_without_os_release(self):
|
||||
found = parse_apt_releases("ARELEASE_BEGIN\n@@os\nARELEASE_END\n")
|
||||
assert (found["os_id"], found["codename"], found["ubuntu_codename"]) == ("", "", "")
|
||||
|
||||
def test_an_unreadable_file_is_left_out(self):
|
||||
out = _framed(_NOBLE, {}).replace(
|
||||
"ARELEASE_END", "@@unreadable /etc/apt/sources.list\nARELEASE_END"
|
||||
)
|
||||
assert parse_apt_releases(out)["sources"] == []
|
||||
|
||||
def test_no_intact_report(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_apt_releases("ARELEASE_BEGIN\n@@os\n")
|
||||
|
||||
|
||||
@needs_apt
|
||||
class TestTheCommand:
|
||||
def test_reads_list_and_sources_files_as_apt_names_them(self, tmp_path):
|
||||
(tmp_path / "sources.list.d").mkdir()
|
||||
(tmp_path / "sources.list").write_text("")
|
||||
(tmp_path / "sources.list.d" / _Z2M_DOCKER_FILE).write_text(_Z2M_DOCKER)
|
||||
(tmp_path / "sources.list.d" / "ubuntu.sources").write_text(_UBUNTU_SOURCES)
|
||||
(tmp_path / "sources.list.d" / "old.list.distUpgrade").write_text(_Z2M_DOCKER)
|
||||
(tmp_path / "os-release").write_text(_NOBLE)
|
||||
command = apt_releases_command(
|
||||
apt_config=(
|
||||
f"apt-config -o Dir::Etc::sourcelist={tmp_path}/sources.list "
|
||||
f"-o Dir::Etc::sourceparts={tmp_path}/sources.list.d/"
|
||||
),
|
||||
os_release=str(tmp_path / "os-release"),
|
||||
)
|
||||
done = subprocess.run(["sh", "-c", command], capture_output=True, text=True, check=False)
|
||||
found = parse_apt_releases(done.stdout)
|
||||
assert found["codename"] == "noble"
|
||||
assert [(s["file"].rsplit("/", 1)[-1], s["suites"]) for s in found["sources"]] == [
|
||||
(_Z2M_DOCKER_FILE, ["focal"]),
|
||||
("ubuntu.sources", ["noble", "noble-updates", "noble-backports"]),
|
||||
("ubuntu.sources", ["noble-security"]),
|
||||
]
|
||||
|
||||
|
||||
class TestRewriteRelease:
|
||||
def test_a_list_line(self):
|
||||
assert rewrite_release(_Z2M_DOCKER, "focal", "noble", deb822=False) == (
|
||||
"deb http://HTTPS///download.docker.com/linux/ubuntu noble stable\n",
|
||||
1,
|
||||
)
|
||||
|
||||
def test_suffixes_options_and_a_uri_that_names_the_release(self):
|
||||
text = (
|
||||
"deb [signed-by=/k.asc] http://repo.example/focal/ focal-security main # focal\n"
|
||||
"# deb http://repo.example/focal/ focal main\n"
|
||||
"deb http://repo.example/other noble main\n"
|
||||
"deb http://repo.example/flat ./\n"
|
||||
)
|
||||
assert rewrite_release(text, "focal", "noble", deb822=False) == (
|
||||
"deb [signed-by=/k.asc] http://repo.example/focal/ noble-security main # focal\n"
|
||||
"# deb http://repo.example/focal/ focal main\n"
|
||||
"deb http://repo.example/other noble main\n"
|
||||
"deb http://repo.example/flat ./\n",
|
||||
1,
|
||||
)
|
||||
|
||||
def test_a_release_that_is_only_a_prefix_is_not_it(self):
|
||||
text = "deb http://repo.example/x focalfossa main\n"
|
||||
assert rewrite_release(text, "focal", "noble", deb822=False) == (text, 0)
|
||||
|
||||
def test_deb822_suites_and_continuations_of_enabled_paragraphs(self):
|
||||
text = (
|
||||
"Types: deb\n"
|
||||
"URIs: http://a.example/focal\n"
|
||||
"Suites: focal focal-updates\n"
|
||||
" focal-backports\n"
|
||||
"Components: main\n"
|
||||
"\n"
|
||||
"Enabled: no\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://b.example/ubuntu\n"
|
||||
"Suites: focal\n"
|
||||
"Components: main\n"
|
||||
)
|
||||
new, changed = rewrite_release(text, "focal", "noble", deb822=True)
|
||||
assert changed == 3
|
||||
assert new == (
|
||||
"Types: deb\n"
|
||||
"URIs: http://a.example/focal\n"
|
||||
"Suites: noble noble-updates\n"
|
||||
" noble-backports\n"
|
||||
"Components: main\n"
|
||||
"\n"
|
||||
"Enabled: no\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://b.example/ubuntu\n"
|
||||
"Suites: focal\n"
|
||||
"Components: main\n"
|
||||
)
|
||||
|
||||
def test_the_text_without_a_final_newline_stays_so(self):
|
||||
assert rewrite_release("deb http://a/ focal main", "focal", "noble", deb822=False) == (
|
||||
"deb http://a/ noble main",
|
||||
1,
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("bad", ["", "Noble", "no ble", "noble;", "../x"])
|
||||
def test_a_name_that_is_no_codename(self, bad):
|
||||
with pytest.raises(ValueError):
|
||||
rewrite_release(_Z2M_DOCKER, bad, "noble", deb822=False)
|
||||
with pytest.raises(ValueError):
|
||||
rewrite_release(_Z2M_DOCKER, "focal", bad, deb822=False)
|
||||
|
||||
|
||||
_OK = "[fetch]\nGet:1 x\n[rc]\n0\n"
|
||||
_NOT_FOUND = "[fetch]\nE: Failed to fetch {url} 404 Not Found [IP: 1.2.3.4 80]\n[rc]\n100\n"
|
||||
|
||||
|
||||
class _Host(AptReleaseMixin):
|
||||
"""An apt host whose files are a dict and whose fetches answer from a set."""
|
||||
|
||||
def __init__(self, files, os_release=_NOBLE, served=(), apt=True):
|
||||
self.files = dict(files)
|
||||
self.os_release = os_release
|
||||
self.served = set(served)
|
||||
self.apt = apt
|
||||
self.fetched: list[str] = []
|
||||
self.written: list[str] = []
|
||||
|
||||
def _is_apt_host(self):
|
||||
return self.apt
|
||||
|
||||
def _run_apt_command(self, command):
|
||||
if "ARELEASE_" in command:
|
||||
return _framed(self.os_release, self.files)
|
||||
if command.startswith("base64 "):
|
||||
path = command.split(" ", 1)[1].strip("'")
|
||||
return base64.b64encode(self.files[path].encode()).decode() + "\n"
|
||||
url = command.split("download-file ", 1)[1].split()[0].strip("'")
|
||||
self.fetched.append(url)
|
||||
body = _OK if url in self.served else _NOT_FOUND.format(url=url)
|
||||
return f"APROXY_BEGIN\n{body}APROXY_END\n"
|
||||
|
||||
def _write_apt_file(self, path, content):
|
||||
self.written.append(path)
|
||||
self.files[path] = content
|
||||
return {"ok": True, "output": f"wrote {path}"}
|
||||
|
||||
|
||||
_DOCKER_PATH = f"/etc/apt/sources.list.d/{_Z2M_DOCKER_FILE}"
|
||||
_DOCKER_NOBLE = "http://HTTPS///download.docker.com/linux/ubuntu/dists/noble/InRelease"
|
||||
|
||||
|
||||
class TestTheMixin:
|
||||
def test_reads_the_host(self):
|
||||
found = _Host({_DOCKER_PATH: _Z2M_DOCKER}).get_apt_source_releases()
|
||||
assert found is not None
|
||||
assert found["codename"] == "noble"
|
||||
assert found["sources"][0]["suites"] == ["focal"]
|
||||
|
||||
def test_none_without_apt(self):
|
||||
assert _Host({}, apt=False).get_apt_source_releases() is None
|
||||
|
||||
def test_moves_the_file_once_the_vendor_serves_the_release(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={_DOCKER_NOBLE})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert result["success"], result["output"]
|
||||
assert host.files[_DOCKER_PATH] == (
|
||||
"deb http://HTTPS///download.docker.com/linux/ubuntu noble stable\n"
|
||||
)
|
||||
assert host.fetched == [_DOCKER_NOBLE]
|
||||
assert result["rewritten"] == 1
|
||||
assert [s["step"] for s in result["steps"]] == ["read", "check", "rewrite"]
|
||||
|
||||
def test_the_release_file_when_there_is_no_inrelease(self):
|
||||
release = _DOCKER_NOBLE.replace("InRelease", "Release")
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={release})
|
||||
assert host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")["success"]
|
||||
assert host.fetched == [_DOCKER_NOBLE, release]
|
||||
|
||||
def test_refuses_where_the_vendor_has_no_such_release(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert not result["success"]
|
||||
assert host.written == []
|
||||
assert "noble" in result["output"] and "404" in result["output"]
|
||||
assert result["rewritten"] == 0
|
||||
|
||||
def test_one_suite_missing_leaves_the_whole_file(self):
|
||||
text = "deb http://a.example/u focal main\ndeb http://a.example/u focal-security main\n"
|
||||
served = {"http://a.example/u/dists/noble/InRelease"}
|
||||
host = _Host({"/etc/apt/sources.list": text}, served=served)
|
||||
result = host.set_apt_source_release("/etc/apt/sources.list", "focal", "noble")
|
||||
assert not result["success"]
|
||||
assert host.files["/etc/apt/sources.list"] == text
|
||||
|
||||
def test_a_file_apt_does_not_read_is_never_written(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={_DOCKER_NOBLE})
|
||||
result = host.set_apt_source_release("/etc/shadow", "focal", "noble")
|
||||
assert not result["success"]
|
||||
assert host.written == []
|
||||
|
||||
def test_nothing_left_on_that_release(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER.replace("focal", "noble")})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert result["success"]
|
||||
assert result["rewritten"] == 0
|
||||
assert host.written == [] and host.fetched == []
|
||||
|
||||
def test_a_deb822_file(self):
|
||||
path = "/etc/apt/sources.list.d/docker.sources"
|
||||
text = "Types: deb\nURIs: https://download.docker.com/linux/ubuntu\nSuites: focal\nComponents: stable\n"
|
||||
served = {"https://download.docker.com/linux/ubuntu/dists/noble/InRelease"}
|
||||
host = _Host({path: text}, served=served)
|
||||
assert host.set_apt_source_release(path, "focal", "noble")["success"]
|
||||
assert "Suites: noble\n" in host.files[path]
|
||||
|
||||
def test_not_an_apt_host(self):
|
||||
result = _Host({}, apt=False).set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert not result["success"]
|
||||
|
||||
def test_a_name_that_is_no_codename_changes_nothing(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={_DOCKER_NOBLE})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble; rm -rf /")
|
||||
assert not result["success"]
|
||||
assert host.written == [] and host.fetched == []
|
||||
|
||||
|
||||
def test_every_apt_proxy_host_reads_its_releases():
|
||||
# Every driver with apt's proxy is an apt host: it reads its sources' releases too.
|
||||
assert issubclass(AptProxyMixin, AptReleaseMixin)
|
||||
@@ -56,8 +56,26 @@ def test_a_firmware_offer_says_what_runs_and_what_is_offered():
|
||||
from napalm_device_types import FirmwareOfferDict, FirmwareOfferMixin
|
||||
|
||||
hints = get_type_hints(FirmwareOfferDict)
|
||||
assert set(hints) == {"current_version", "latest_version", "newer", "download_url"}
|
||||
assert set(hints) == {
|
||||
"current_version",
|
||||
"latest_version",
|
||||
"newer",
|
||||
"download_url",
|
||||
"installable",
|
||||
"latest_major_version",
|
||||
}
|
||||
assert FirmwareOfferDict.__required_keys__ == frozenset(
|
||||
{"current_version", "latest_version", "newer"}
|
||||
)
|
||||
assert not hasattr(FirmwareOfferMixin, "get_firmware_offer")
|
||||
|
||||
|
||||
def test_a_firmware_upgrade_is_started_and_followed_like_a_device_run_update():
|
||||
"""A driver that can install the firmware it offers starts it and the device
|
||||
runs it by itself, restarting at its end (OpenWrt's sysupgrade, NetOrk/netork#2615);
|
||||
the caller follows it through ``get_update_progress``. Declared only, so
|
||||
``hasattr`` tells a caller whether the driver offers it."""
|
||||
from napalm_device_types import FirmwareUpgradeMixin, UpdateMixin
|
||||
|
||||
assert not hasattr(FirmwareUpgradeMixin, "start_firmware_upgrade")
|
||||
assert not hasattr(UpdateMixin, "get_update_progress")
|
||||
@@ -0,0 +1,286 @@
|
||||
"""The record of the firewall rules netOrk opened on a host (NetOrk/netork#2693)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
OpenedRuleDict,
|
||||
opened_rule_line,
|
||||
opened_rules_text,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
record_opened_rule_command,
|
||||
revoke_recorded_rules,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
|
||||
UFW: OpenedRuleDict = {
|
||||
"purpose": "zabbix-agent",
|
||||
"backend": "ufw",
|
||||
"proto": "tcp",
|
||||
"port": 10050,
|
||||
"source": "10.40.100.254/32",
|
||||
"zone": "",
|
||||
"permanent": True,
|
||||
}
|
||||
FIREWALLD: OpenedRuleDict = {**UFW, "backend": "firewalld", "zone": "public", "permanent": False}
|
||||
|
||||
ROOT_DIR = "0 755 directory"
|
||||
ROOT_FILE = "0 644 regular file"
|
||||
|
||||
|
||||
def _read(*lines: str, directory: str = ROOT_DIR, record: str = ROOT_FILE) -> str:
|
||||
return "\n".join([directory, record, *lines]) + "\n"
|
||||
|
||||
|
||||
class TestTheLine:
|
||||
def test_ufw(self):
|
||||
assert opened_rule_line(UFW) == "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
|
||||
|
||||
def test_firewalld_names_zone_and_configuration(self):
|
||||
assert opened_rule_line(FIREWALLD) == (
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.40.100.254/32 public runtime"
|
||||
)
|
||||
|
||||
def test_a_line_reads_back_as_the_rule(self):
|
||||
for rule in (UFW, FIREWALLD, {**UFW, "backend": "iptables", "source": "2001:db8::/64"}):
|
||||
record = parse_opened_ports_record(_read(opened_rule_line(rule)))
|
||||
assert record["rules"] == [rule]
|
||||
assert record["unknown"] == []
|
||||
assert record["problem"] == ""
|
||||
|
||||
|
||||
class TestStrictReading:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
"v2 zabbix-agent ufw tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent nft tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw icmp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 0 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 70000 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.0/8;reboot",
|
||||
"v1 zabbix-agent ufw tcp 10050 any",
|
||||
"v1 Zabbix_Agent ufw tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1/32 public runtime",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32 $(id) runtime",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32 public sometimes",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1/32",
|
||||
],
|
||||
)
|
||||
def test_a_line_that_is_not_exactly_a_rule_is_not_acted_on(self, line):
|
||||
record = parse_opened_ports_record(_read(line))
|
||||
|
||||
assert record["rules"] == []
|
||||
assert record["unknown"] == [line]
|
||||
|
||||
def test_blank_lines_are_neither(self):
|
||||
record = parse_opened_ports_record(_read("", opened_rule_line(UFW), " "))
|
||||
|
||||
assert record["rules"] == [UFW]
|
||||
assert record["unknown"] == []
|
||||
|
||||
def test_no_record_is_no_rules(self):
|
||||
record = parse_opened_ports_record("")
|
||||
|
||||
assert record == {"rules": [], "unknown": [], "problem": ""}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("directory", "record", "why"),
|
||||
[
|
||||
("1000 755 directory", ROOT_FILE, "not root's"),
|
||||
("0 775 directory", ROOT_FILE, "writable"),
|
||||
(ROOT_DIR, "1000 644 regular file", "not root's"),
|
||||
(ROOT_DIR, "0 666 regular file", "writable"),
|
||||
(ROOT_DIR, "0 777 symbolic link", "not a regular file"),
|
||||
("0 755 symbolic link", ROOT_FILE, "not a directory"),
|
||||
],
|
||||
)
|
||||
def test_a_record_others_could_have_written_is_not_read(self, directory, record, why):
|
||||
read = parse_opened_ports_record(
|
||||
_read(opened_rule_line(UFW), directory=directory, record=record)
|
||||
)
|
||||
|
||||
assert read["rules"] == []
|
||||
assert why in read["problem"]
|
||||
|
||||
def test_a_read_that_says_nothing_about_owner_and_mode_is_not_trusted(self):
|
||||
read = parse_opened_ports_record("v1 zabbix-agent ufw tcp 10050 10.0.0.1/32\n")
|
||||
|
||||
assert read["rules"] == []
|
||||
assert read["problem"]
|
||||
|
||||
|
||||
class TestCommands:
|
||||
def test_reading_says_owner_mode_and_kind_of_the_directory_and_the_file(self):
|
||||
command = read_opened_ports_command()
|
||||
|
||||
assert "stat -c '%u %a %F' /var/lib/netork " + OPENED_PORTS_RECORD in command
|
||||
assert f"cat {OPENED_PORTS_RECORD}" in command
|
||||
assert "exit" not in command
|
||||
|
||||
def test_recording_creates_root_s_directory_and_appends_the_line(self):
|
||||
command = record_opened_rule_command(opened_rule_line(UFW))
|
||||
|
||||
assert command.startswith("install -d -m 755 -o root -g root /var/lib/netork")
|
||||
assert f"printf '%s\\n' \"{opened_rule_line(UFW)}\" >> {OPENED_PORTS_RECORD}" in command
|
||||
assert f"chmod 644 {OPENED_PORTS_RECORD}" in command
|
||||
|
||||
def test_recording_takes_a_firewalld_zone_from_the_shell(self):
|
||||
line = opened_rule_line({**FIREWALLD, "zone": "$z"})
|
||||
|
||||
assert '"v1 zabbix-agent firewalld tcp 10050 10.40.100.254/32 $z runtime"' in (
|
||||
record_opened_rule_command(line)
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("line", ['v1 "; rm -rf /', "v1 `id`", "v1 a\nb", "v1 $(id)"])
|
||||
def test_recording_refuses_what_is_not_a_line(self, line):
|
||||
with pytest.raises(ValueError):
|
||||
record_opened_rule_command(line)
|
||||
|
||||
def test_ufw_records_a_rule_only_when_ufw_added_it(self):
|
||||
command = ufw_allow_recorded_command("10.40.100.254/32", 10050, "tcp", "zabbix-agent")
|
||||
|
||||
assert "LC_ALL=C ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in command
|
||||
# ufw says "Skipping adding existing rule" for a rule it had: someone else's.
|
||||
assert "*Skipping*) ;;" in command
|
||||
assert "*'Rule added'*|*'Rules updated'*)" in command
|
||||
assert opened_rule_line(UFW) in command
|
||||
assert "exit" not in command
|
||||
|
||||
def test_ufw_delete(self):
|
||||
assert (
|
||||
"LC_ALL=C ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp"
|
||||
in ufw_delete_command(UFW)
|
||||
)
|
||||
assert "exit" not in ufw_delete_command(UFW)
|
||||
|
||||
|
||||
def _shell(tmp_path, command: str, ufw_says: str, ufw_status: int = 0):
|
||||
"""Run *command* with a fake ufw that answers *ufw_says*, the record under *tmp_path*."""
|
||||
fake = tmp_path / "bin" / "ufw"
|
||||
fake.parent.mkdir(exist_ok=True)
|
||||
fake.write_text(f"#!/bin/sh\necho '{ufw_says}'\nexit {ufw_status}\n")
|
||||
fake.chmod(0o755)
|
||||
record = tmp_path / "netork" / "opened-ports"
|
||||
command = command.replace(
|
||||
"install -d -m 755 -o root -g root /var/lib/netork", f"mkdir -p {record.parent}"
|
||||
).replace(OPENED_PORTS_RECORD, str(record))
|
||||
done = subprocess.run(
|
||||
["sh", "-c", command],
|
||||
env={**os.environ, "PATH": f"{fake.parent}:{os.environ['PATH']}"},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
return done, (record.read_text() if record.exists() else "")
|
||||
|
||||
|
||||
class TestUfwOnAShell:
|
||||
COMMAND = ufw_allow_recorded_command("10.40.100.254/32", 10050, "tcp", "zabbix-agent")
|
||||
|
||||
@pytest.mark.parametrize("says", ["Rule added", "Rules updated"])
|
||||
def test_a_rule_ufw_added_is_recorded(self, tmp_path, says):
|
||||
done, record = _shell(tmp_path, self.COMMAND, says)
|
||||
|
||||
assert done.returncode == 0, done.stderr
|
||||
assert record == opened_rule_line(UFW) + "\n"
|
||||
|
||||
def test_a_rule_ufw_had_is_not_recorded(self, tmp_path):
|
||||
done, record = _shell(tmp_path, self.COMMAND, "Skipping adding existing rule")
|
||||
|
||||
assert done.returncode == 0, done.stderr
|
||||
assert record == ""
|
||||
|
||||
def test_a_refused_rule_fails_and_is_not_recorded(self, tmp_path):
|
||||
done, record = _shell(tmp_path, self.COMMAND, "ERROR: Bad port", ufw_status=1)
|
||||
|
||||
assert done.returncode != 0
|
||||
assert "Bad port" in done.stdout
|
||||
assert record == ""
|
||||
|
||||
def test_deleting_a_rule_ufw_no_longer_has_is_done(self, tmp_path):
|
||||
done, _ = _shell(
|
||||
tmp_path, ufw_delete_command(UFW), "Could not delete non-existent rule", ufw_status=1
|
||||
)
|
||||
|
||||
assert done.returncode == 0
|
||||
|
||||
def test_a_delete_ufw_refuses_fails(self, tmp_path):
|
||||
done, _ = _shell(tmp_path, ufw_delete_command(UFW), "ERROR: problem", ufw_status=1)
|
||||
|
||||
assert done.returncode != 0
|
||||
assert "problem" in done.stdout
|
||||
|
||||
def test_rules_text_keeps_what_it_is_given_one_per_line(self):
|
||||
assert opened_rules_text([]) == ""
|
||||
assert opened_rules_text(["a", "b"]) == "a\nb\n"
|
||||
|
||||
|
||||
class TestReport:
|
||||
def test_removed_rules_are_named(self):
|
||||
output = revoked_output([UFW], unknown=[], left=0, proto="tcp", port=10050)
|
||||
|
||||
assert "removed" in output
|
||||
assert "10.40.100.254/32" in output
|
||||
|
||||
def test_without_a_recorded_rule_it_says_so(self):
|
||||
assert "netOrk recorded no rule" in revoked_output(
|
||||
[], unknown=[], left=0, proto="tcp", port=10050
|
||||
)
|
||||
|
||||
def test_rules_netork_did_not_record_are_reported_not_removed(self):
|
||||
output = revoked_output([], unknown=[], left=2, proto="tcp", port=10050)
|
||||
|
||||
assert "2 rule(s) for tcp/10050" in output
|
||||
assert "left in place" in output
|
||||
|
||||
def test_lines_it_could_not_read_are_reported(self):
|
||||
output = revoked_output([], unknown=["v9 x"], left=0, proto="tcp", port=10050)
|
||||
|
||||
assert "v9 x" in output
|
||||
|
||||
|
||||
class TestRevoking:
|
||||
SNMP: OpenedRuleDict = {**UFW, "purpose": "snmp", "proto": "udp", "port": 161}
|
||||
EARLIER_PORT: OpenedRuleDict = {**UFW, "port": 10051}
|
||||
|
||||
def _record(self, *lines):
|
||||
return parse_opened_ports_record(_read(*lines))
|
||||
|
||||
def test_only_the_purpose_s_rules_go_whatever_their_port(self):
|
||||
record = self._record(
|
||||
opened_rule_line(UFW),
|
||||
opened_rule_line(self.SNMP),
|
||||
"v9 not a rule",
|
||||
opened_rule_line(self.EARLIER_PORT),
|
||||
)
|
||||
asked: list[OpenedRuleDict] = []
|
||||
|
||||
done = revoke_recorded_rules(
|
||||
record, "zabbix-agent", lambda r: asked.append(r) or {"ok": True, "output": ""}
|
||||
)
|
||||
|
||||
assert asked == [UFW, self.EARLIER_PORT]
|
||||
assert done["removed"] == [UFW, self.EARLIER_PORT]
|
||||
assert done["record"] == f"{opened_rule_line(self.SNMP)}\nv9 not a rule\n"
|
||||
assert done["failed"] == []
|
||||
|
||||
def test_a_rule_that_will_not_go_stays_and_says_why(self):
|
||||
record = self._record(opened_rule_line(UFW))
|
||||
|
||||
done = revoke_recorded_rules(
|
||||
record, "zabbix-agent", lambda r: {"ok": False, "output": "ufw: locked"}
|
||||
)
|
||||
|
||||
assert done["removed"] == []
|
||||
assert done["record"] == f"{opened_rule_line(UFW)}\n"
|
||||
assert done["failed"] == [f"{opened_rule_line(UFW)}: ufw: locked"]
|
||||
@@ -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")
|
||||
@@ -12,6 +12,7 @@ These tests pin the property that prevents a fourth.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
@@ -82,6 +83,7 @@ class TestDeclaredMethodsDoNotExistAtRuntime:
|
||||
(StorageDriver, "get_disks"),
|
||||
(StorageDriver, "get_volumes"),
|
||||
(HypervisorDriver, "get_vms"),
|
||||
(HypervisorDriver, "resume_vm"),
|
||||
(FirewallDriver, "send_wake_on_lan"),
|
||||
(SwitchDriver, "set_vlan"),
|
||||
(AccessPointDriver, "get_wireless_config"),
|
||||
@@ -101,6 +103,27 @@ class TestDeclaredMethodsDoNotExistAtRuntime:
|
||||
assert not hasattr(base, method)
|
||||
|
||||
|
||||
class TestHypervisorPowerContract:
|
||||
"""The power actions a hypervisor driver may implement, as declared."""
|
||||
|
||||
@staticmethod
|
||||
def _declared(module) -> dict[str, list[str]]:
|
||||
tree = ast.parse(inspect.getsource(module))
|
||||
methods: dict[str, list[str]] = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
methods[node.name] = [a.arg for a in node.args.args]
|
||||
return methods
|
||||
|
||||
def test_resume_vm_is_declared_beside_suspend_vm(self):
|
||||
"""A VM netOrk paused must be one it can bring back (NetOrk/netork#2658)."""
|
||||
from napalm_device_types import hypervisor
|
||||
|
||||
declared = self._declared(hypervisor)
|
||||
assert declared.get("suspend_vm") == ["self", "name"]
|
||||
assert declared.get("resume_vm") == ["self", "name"]
|
||||
|
||||
|
||||
class TestNoShadowingAcrossRoles:
|
||||
"""The regression test for the bug class."""
|
||||
|
||||
|
||||
@@ -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")
|
||||
@@ -97,6 +97,75 @@ class TestConfig:
|
||||
assert text.count("Server=zabbix.example.com\n") == 2
|
||||
|
||||
|
||||
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
|
||||
|
||||
|
||||
class TestActiveOnly:
|
||||
"""A site whose agents only connect out (NetOrk/netork#2683): no passive listener.
|
||||
|
||||
Zabbix's ``StartAgents=0`` disables passive checks and the agent listens on no
|
||||
port; ``Server`` is mandatory only while ``StartAgents`` is not 0, so nothing is
|
||||
left that may ask.
|
||||
"""
|
||||
|
||||
def test_it_starts_no_listener_and_lets_nobody_ask(self):
|
||||
text, changes = zabbix_agent_config(SAMPLE, ACTIVE_ONLY)
|
||||
|
||||
assert text.endswith("StartAgents=0\n")
|
||||
assert "\n# Server=127.0.0.1\n" in text
|
||||
assert "\nServer=" not in text
|
||||
assert "\nServerActive=zabbix.example.com\n" in text
|
||||
assert "\nHostname=ap-1og\n" in text
|
||||
assert "StartAgents: (not set) → 0" in changes
|
||||
assert "Server: 127.0.0.1 → (not set)" in changes
|
||||
|
||||
def test_a_listener_count_of_its_own_becomes_none(self):
|
||||
text, changes = zabbix_agent_config("StartAgents=5\n", ACTIVE_ONLY)
|
||||
|
||||
assert text.startswith("StartAgents=0\n")
|
||||
assert "StartAgents: 5 → 0" in changes
|
||||
|
||||
def test_a_file_that_already_says_it_changes_nothing(self):
|
||||
text, _ = zabbix_agent_config(SAMPLE, ACTIVE_ONLY)
|
||||
|
||||
again, changes = zabbix_agent_config(text, ACTIVE_ONLY)
|
||||
|
||||
assert again == text
|
||||
assert changes == []
|
||||
|
||||
def test_a_passive_agent_listens_again(self):
|
||||
"""An agent that was active only before: ``StartAgents=0`` would keep it deaf."""
|
||||
text, _ = zabbix_agent_config(SAMPLE, ACTIVE_ONLY)
|
||||
|
||||
again, changes = zabbix_agent_config(text, SETTINGS)
|
||||
|
||||
assert "\n# StartAgents=0\n" in again
|
||||
assert "\nServer=zabbix.example.com\n" in again
|
||||
assert "StartAgents: 0 → (not set)" in changes
|
||||
|
||||
def test_a_passive_agent_keeps_its_own_listener_count(self):
|
||||
text, changes = zabbix_agent_config("StartAgents=5\n", SETTINGS)
|
||||
|
||||
assert text.startswith("StartAgents=5\n")
|
||||
assert not any(c.startswith("StartAgents") for c in changes)
|
||||
|
||||
def test_it_needs_somewhere_to_send_its_checks(self):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**ACTIVE_ONLY, "server_active": ""})
|
||||
|
||||
def test_it_needs_no_server_that_may_ask(self):
|
||||
check_zabbix_agent_settings({**ACTIVE_ONLY, "server": ""})
|
||||
|
||||
def test_a_server_that_is_not_addresses_is_still_refused(self):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**ACTIVE_ONLY, "server": "a\nb"})
|
||||
|
||||
@pytest.mark.parametrize("value", ["yes", 1, None])
|
||||
def test_active_only_is_a_bool(self, value):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**SETTINGS, "active_only": value})
|
||||
|
||||
|
||||
class TestSettings:
|
||||
@pytest.mark.parametrize(
|
||||
"server",
|
||||
@@ -327,6 +396,52 @@ class TestZabbixAgentMixin:
|
||||
assert result["success"] is True
|
||||
assert agent.calls[0] == ("ensure_package", "zabbix-agent")
|
||||
|
||||
def test_an_active_only_agent_opens_no_port(self):
|
||||
"""NetOrk/netork#2683: nothing listens, so nothing is let through."""
|
||||
agent = _Agent()
|
||||
|
||||
result = agent.configure_zabbix_agent({**ACTIVE_ONLY, "allowed_sources": ["10.0.0.1"]})
|
||||
|
||||
assert result["success"] is True
|
||||
assert not [c for c in agent.calls if c[0] == "firewall"]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
assert "active only" in result["steps"][2]["output"]
|
||||
|
||||
def test_an_active_only_agent_has_the_driver_revoke_what_netork_opened(self):
|
||||
"""NetOrk/netork#2693: a rule an earlier passive install opened is closed."""
|
||||
agent = _Agent()
|
||||
agent._revoke_zabbix_agent_sources = lambda settings: ( # type: ignore[attr-defined]
|
||||
agent.calls.append(("revoke", settings["listen_port"]))
|
||||
or {"ok": True, "output": "removed tcp/10050"}
|
||||
)
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert ("revoke", ACTIVE_ONLY["listen_port"]) in agent.calls
|
||||
assert not [c for c in agent.calls if c[0] == "firewall"]
|
||||
assert result["steps"][2]["output"] == "removed tcp/10050"
|
||||
|
||||
def test_a_driver_that_cannot_tell_its_rules_apart_changes_nothing_and_says_so(self):
|
||||
agent = _Agent()
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "cannot tell" in result["steps"][2]["output"]
|
||||
|
||||
def test_a_revoke_that_fails_starts_nothing(self):
|
||||
agent = _Agent()
|
||||
agent._revoke_zabbix_agent_sources = lambda settings: { # type: ignore[attr-defined]
|
||||
"ok": False,
|
||||
"output": "ufw: permission denied",
|
||||
}
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is False
|
||||
assert ("restart", "zabbix-agent") not in agent.calls
|
||||
|
||||
def test_a_closed_firewall_starts_nothing(self):
|
||||
agent = _Agent(refuse=frozenset({"firewall"}))
|
||||
|
||||
|
||||
Reference in new issue
Block a user