Compare commits
314
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07920941c8 | ||
|
|
92b1b6402b | ||
|
|
e4fde2283a | ||
|
|
419d3ee0e0 | ||
|
|
c93ceeb320 | ||
|
|
d77a8982a8 | ||
|
|
594cc5e486 | ||
|
|
e440bee9e1 | ||
|
|
3cd0e3621a | ||
|
|
3813aee3a8 | ||
|
|
e3420269b7 | ||
|
|
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 | ||
|
|
eb1964c4b3 | ||
|
|
3622d0f825 | ||
|
|
caf7ef4cc8 | ||
|
|
3422b7d030 | ||
|
|
f1940aa918 | ||
|
|
5217c6e333 | ||
|
|
7051199589 | ||
|
|
7c0e4fffc5 | ||
|
|
cb0f1cc05c | ||
|
|
b4929990f1 | ||
|
|
3db6c6385c | ||
|
|
c5154d954b | ||
|
|
211d0c02eb | ||
|
|
74d2f42b0e | ||
|
|
c25f39768f | ||
|
|
9ecc6823c8 | ||
|
|
2080ccbfd7 | ||
|
|
ce1fe18405 | ||
|
|
e43926f1d5 | ||
|
|
43e0210ff6 | ||
|
|
241acef6c1 | ||
|
|
4c0ba5b2c0 | ||
|
|
e9da399568 | ||
|
|
8673d1eda1 | ||
|
|
46d7125aa6 | ||
|
|
8e43fe2ed9 | ||
|
|
679584766f | ||
|
|
1b04818982 | ||
|
|
65991d0930 | ||
|
|
9dfb5596bc | ||
|
|
b4cdcfd347 | ||
|
|
5258a43dc9 | ||
|
|
f3cb3601a8 | ||
|
|
a8fedf299a | ||
|
|
c736fb30d0 | ||
|
|
cf555d006d | ||
|
|
4e79cd1fc8 | ||
|
|
304f404567 | ||
|
|
aaa9f0504a | ||
|
|
bc47220318 | ||
|
|
08a62838f7 | ||
|
|
ac38c68feb | ||
|
|
8516f2a1ee | ||
|
|
c74173523a | ||
|
|
6c7f164004 | ||
|
|
073087da69 | ||
|
|
278a707157 | ||
|
|
56e5e82a59 | ||
|
|
e6f145d4a3 | ||
|
|
66037e878e | ||
|
|
afffd0915c | ||
|
|
92891473be | ||
|
|
658f1c8ab2 | ||
|
|
aacde6be3f | ||
|
|
58c7616401 | ||
|
|
b7e31205d5 | ||
|
|
1d71ff8f91 | ||
|
|
58ed0f0a94 | ||
|
|
c1a05d6dba | ||
|
|
fccf902c07 | ||
|
|
f5a2811333 | ||
|
|
98d1dbef4c | ||
|
|
252ea3b81c | ||
|
|
b685b200cc | ||
|
|
8557710724 | ||
|
|
1b600416f0 | ||
|
|
e622b26d42 | ||
|
|
5daba5d37c | ||
|
|
dacd10fcce | ||
|
|
8a54674e40 | ||
|
|
d45455adf1 | ||
|
|
ac49e2b5d4 | ||
|
|
c967635cba | ||
|
|
c470686305 | ||
|
|
1edf458feb | ||
|
|
00452d0d37 | ||
|
|
4e40f95bc1 | ||
|
|
70e1c9b218 | ||
|
|
a70501ff60 | ||
|
|
c6d119eb83 | ||
|
|
8e9d21c368 | ||
|
|
25f28297e4 | ||
|
|
847c902193 | ||
|
|
ffbb194300 | ||
|
|
edef6cf07c | ||
|
|
df476a12f2 | ||
|
|
834cb2e0ea | ||
|
|
f573fa53d2 | ||
|
|
fdf2f89115 | ||
|
|
d63abff467 | ||
|
|
9d6a1a65ed | ||
|
|
95e3aa1e26 | ||
|
|
a0901e3277 | ||
|
|
060e210130 | ||
|
|
31973d2d5f | ||
|
|
abda0973e7 | ||
|
|
4eeaaef236 | ||
|
|
3490d8b62a | ||
|
|
2542081c6f | ||
|
|
4427be35cc | ||
|
|
ad9ec0fb4d | ||
|
|
8dd7e8ab9a | ||
|
|
935fad2a2d | ||
|
|
f337ae7fb8 | ||
|
|
e2aebeadeb | ||
|
|
36cf117b95 | ||
|
|
02d461036b | ||
|
|
63039ce758 | ||
|
|
516fb18c0e | ||
|
|
8d32e70cd7 | ||
|
|
51e8c849bb | ||
|
|
6aadcc3d91 | ||
|
|
e98d4763f3 | ||
|
|
24f4be3b7e | ||
|
|
f4354f498e | ||
|
|
73771aba00 | ||
|
|
c9571d59f1 | ||
|
|
cf862af026 | ||
|
|
83ea13f88e | ||
|
|
4938056d20 | ||
|
|
9c3be46d8a | ||
|
|
a6289cb24a | ||
|
|
46c1c9dc4e | ||
|
|
bc17862a44 | ||
|
|
9f6ffa8a25 | ||
|
|
4150570a94 | ||
|
|
a809e6c02f | ||
|
|
5b894913e1 | ||
|
|
00aa5efef0 | ||
|
|
97cb8779c5 | ||
|
|
47751d12d6 | ||
|
|
3f59023f46 | ||
|
|
666be091e3 | ||
|
|
25cc264306 | ||
|
|
86959b7599 | ||
|
|
8664accbc4 | ||
|
|
449a6b13ca | ||
|
|
c71ddd7fe6 | ||
|
|
3b6c5f9585 | ||
|
|
1c71fe6896 | ||
|
|
9159106837 | ||
|
|
28ff14589b | ||
|
|
5fffb3b886 | ||
|
|
2846824a21 | ||
|
|
0545d1d814 | ||
|
|
49c65cbd5d | ||
|
|
888a7229dc | ||
|
|
0f0064c2d7 | ||
|
|
cb90fa9835 | ||
|
|
551ed0a29d | ||
|
|
0dc1a598e2 | ||
|
|
131346c228 | ||
|
|
a5b7b540c6 | ||
|
|
874c6c5a92 | ||
|
|
145c2c668b | ||
|
|
1cef3385e8 | ||
|
|
fbd3cf0129 | ||
|
|
e400c4359c | ||
|
|
4d3574cd60 | ||
|
|
87dbdfac66 | ||
|
|
a07ced2df6 | ||
|
|
22e4377c2b | ||
|
|
49830671c9 | ||
|
|
d7ec558933 | ||
|
|
0475184684 | ||
|
|
b7350a9b2c | ||
|
|
08296d0d2e | ||
|
|
ac8e7c4c11 | ||
|
|
f77091c489 | ||
|
|
be3958e561 | ||
|
|
a21e365c4e | ||
|
|
cce26eff44 | ||
|
|
888a11ca6a | ||
|
|
94bf399d34 | ||
|
|
bb2229fd9e | ||
|
|
680500dd2e | ||
|
|
a0e70d1686 | ||
|
|
2bd7bcc77c | ||
|
|
83cd7db761 | ||
|
|
1dd448e1d3 | ||
|
|
753ddc5eda | ||
|
|
59fb1273e8 | ||
|
|
4641063db6 | ||
|
|
634c142477 | ||
|
|
2d1c40c87d | ||
|
|
87c9b06bf3 | ||
|
|
2805f911c4 | ||
|
|
6551008ad3 | ||
|
|
321537ff0a | ||
|
|
9324a5b8f1 | ||
|
|
b4c4ec0b0b | ||
|
|
07b50f6a48 | ||
|
|
90367c1370 | ||
|
|
2739f10ecd | ||
|
|
0330f17a67 | ||
|
|
d3034bc8ea | ||
|
|
4f3b88db0e | ||
|
|
c7ea15dbb4 | ||
|
|
01fe680456 | ||
|
|
fde6d717a8 | ||
|
|
a1da0337e2 | ||
|
|
7afa590c0c | ||
|
|
155b5bbbe4 | ||
|
|
e509445572 | ||
|
|
dd8977750d | ||
|
|
e58b65a3db | ||
|
|
7ec427c743 | ||
|
|
d43e15e8db | ||
|
|
23c352aa8a | ||
|
|
a710a85de6 | ||
|
|
c947250179 | ||
|
|
ff6dbe0206 | ||
|
|
7aa731ad34 | ||
|
|
72679ff4f8 | ||
|
|
7b44f689bc | ||
|
|
ba2f18ea7d | ||
|
|
37c09d0fa0 | ||
|
|
8111c4cde3 | ||
|
|
e1ce72cc5c | ||
|
|
7ba84acad3 | ||
|
|
8eb7dcd871 | ||
|
|
95d9031c8d | ||
|
|
885c7e1f53 | ||
|
|
eb80d5cb0d | ||
|
|
e50e497939 | ||
|
|
3aed0b48d7 | ||
|
|
735b683028 | ||
|
|
08ec32e93a | ||
|
|
bd43bd75fa | ||
|
|
1112191aec | ||
|
|
b8b89acee1 | ||
|
|
f833e23422 | ||
|
|
b97ec654a0 | ||
|
|
c2d8d4a0d2 | ||
|
|
18676a573f | ||
|
|
4071f35050 | ||
|
|
17d8dabb4d | ||
|
|
d55b036a8e | ||
|
|
536ffcf6e1 | ||
|
|
97e7ede131 | ||
|
|
b5c40019af | ||
|
|
36b7852bce | ||
|
|
31949eca0a | ||
|
|
7b491164a2 | ||
|
|
f3fa75bbca | ||
|
|
34b8f10ffa | ||
|
|
1ce0a0b6f2 | ||
|
|
70841feaa1 | ||
|
|
d8dbc7a442 | ||
|
|
ec0612b300 | ||
|
|
b53cf4d1f4 | ||
|
|
b8977cdaa5 | ||
|
|
a211629875 | ||
|
|
90b8e08789 | ||
|
|
b3d67d1517 | ||
|
|
6ea862e65d | ||
|
|
478c7b434a | ||
|
|
841881018c | ||
|
|
f5c286a713 | ||
|
|
6c4ff65710 | ||
|
|
f9b8a54673 | ||
|
|
d9a23e08f2 | ||
|
|
5059df6b25 | ||
|
|
a37dc8d632 | ||
|
|
cb274156a4 | ||
|
|
a16ca77156 | ||
|
|
fcf72b6dad | ||
|
|
2cc93885b4 | ||
|
|
97cab9754b | ||
|
|
7d18c12579 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
driver:
|
||||
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
|
||||
with:
|
||||
standard-ref: main
|
||||
secrets:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
+692
@@ -0,0 +1,692 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to napalm-device-types. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/), versions follow
|
||||
[Semantic Versioning](https://semver.org/). Versions up to 4.21.0 were not
|
||||
recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.49.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `RadioStatusDict` carries a radio's runtime state beside its configuration
|
||||
(NetOrk/netork#31): `up` (the radio runs), `pending` (the device is still bringing it
|
||||
up or down) and `setup_failed` (the device gave up bringing it up after its retries).
|
||||
All three are optional: a driver that cannot read the state leaves them out. A radio
|
||||
can be `enabled` and not run, as on 2026-07-16, when a rejected value kept every radio
|
||||
of a fleet in a restart loop the configuration never showed.
|
||||
|
||||
## [4.48.0] - 2026-11-27
|
||||
|
||||
### Added
|
||||
- `HardeningMixin.get_hardening()`: how a Linux host is hardened, read with one fixed,
|
||||
read-only command (NetOrk/netork#2706). The active security modules
|
||||
(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`, else
|
||||
`/sys/fs/selinux/enforce`) and its configured mode (`SELINUX=` in `/etc/selinux/config`),
|
||||
AppArmor's switch and, as root, its profiles per mode (`aa-status --json`), the crypto
|
||||
policy (`update-crypto-policies --show`) and FIPS mode (`/proc/sys/crypto/fips_enabled`),
|
||||
the kernel's text for each file under `/sys/devices/system/cpu/vulnerabilities`, the
|
||||
kernel command line with `mitigations=` (`auto` when not given) and `nosmt`, and
|
||||
`ID`/`ID_LIKE` from `/etc/os-release`. Read as root first; where root is refused, as the
|
||||
login user, without the profile counts. Anything not read is `None`, never "off". A
|
||||
driver supplies `_run_hardening_command(command, *, privileged)`.
|
||||
- `parse_hardening`, `HARDENING_COMMAND`, `cpu_vulnerability_state` (`not_affected`,
|
||||
`mitigated`, `vulnerable` or `unknown`, from the kernel's words), and the
|
||||
`HardeningDict`, `SelinuxDict` and `AppArmorDict` shapes (in `hardening`).
|
||||
|
||||
## [4.47.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- `AptHistoryMixin.get_update_history(since)`: apt's own history log as past transactions
|
||||
(NetOrk/netork#2728), for every driver of a Debian-family host that has `run_command`.
|
||||
`APT_HISTORY_COMMAND` prints `/var/log/apt/history.log` and its rotations
|
||||
(`history.log.<n>.gz` through `zcat`) in one round trip, as the login user (the files
|
||||
are 0644), with the host's time zone (`/etc/localtime`'s link, `/etc/timezone`) and
|
||||
`date +%z` for a zone without a name; only a file that user may not read makes the
|
||||
mixin read it again as root. `parse_apt_history(text, since)` reads apt's dates in that
|
||||
zone and names each transaction as Proxmox VE 9.3's `GET /nodes/{node}/apt/history`
|
||||
does: start time and the number of earlier transactions with that start in the same
|
||||
file, so a node that moves to 9.3 keeps its ids. Strict: a block whose package lines
|
||||
do not read as apt writes them is left out (and still counted), one without
|
||||
`End-Date` has `end` None, a report cut short or a file that could not be read raises.
|
||||
- `apt_history_command(log_dir)`, `host_zone(name, offset)` and `AptHistoryUnreadable`
|
||||
(a `PermissionError`), in `apt_history`.
|
||||
|
||||
## [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
|
||||
- `ZabbixAgentMixin.configure_zabbix_agent(settings)`: a native Zabbix agent, for a host
|
||||
without a container engine (NetOrk/netork#2571). Install (`ensure_package` with
|
||||
`ZABBIX_AGENT_PACKAGE`, and where the host's own packages have none and
|
||||
`settings["release"]` names the server's release line, the driver's
|
||||
`_add_zabbix_repository(release)` and a second try), configure (the driver's
|
||||
`_write_zabbix_agent_config`), firewall (the driver's `_allow_zabbix_agent_sources`),
|
||||
start (`manage_service` enable and restart of `ZABBIX_AGENT_SERVICE`). Settings that do
|
||||
not hold raise `ValueError` before anything changes.
|
||||
- `ZabbixAgentSettingsDict`; `zabbix_agent_config(text, settings)`, the agent's
|
||||
configuration with `Server`, `ServerActive`, `ListenPort` and `Hostname` set and the rest
|
||||
kept; `zabbix_repository_command(os_release, release)`, the root command that adds
|
||||
Zabbix's repository for Debian, Ubuntu, Raspberry Pi OS, RHEL, CentOS, Oracle Linux,
|
||||
AlmaLinux and Rocky Linux, in the layout before and since 7.2;
|
||||
`check_zabbix_agent_settings(settings)`.
|
||||
- `fixes.enable_and_restart(manage_service, service)`, the start step `LldpAgentMixin` and
|
||||
`ZabbixAgentMixin` share.
|
||||
- Podman as a container engine (NetOrk/netork#818): `container_engines()` lists it with the
|
||||
API `podman-libpod`, and `open_container_engine("podman")` reaches it with `podman system
|
||||
dial-stdio` (Podman 4.0 and later). It is the host's rootful Podman, so the connection
|
||||
runs every call as root (`ContainerEngineConnection.privileged`, `ROOT_ENGINES`).
|
||||
- `apt_sources`: apt's https sources through the package cache, in the form apt-cacher-ng
|
||||
fetches over https itself and stores (`http://HTTPS///<host>/…`, with `AllowUserPorts=80
|
||||
443` on the cache). `cacheable_https_hosts(report)` names the hosts this applies to, and
|
||||
`rewrite_sources_command` / `revert_sources_command` are the root commands, for `.list`
|
||||
and deb822 `.sources` files. A host apt keeps credentials for in `auth.conf` stays on
|
||||
https, because apt finds them by the host's name and the cache is shared. The rewrite
|
||||
names such a host in the proxy file as `Package-Proxy::Not-Cached` (NetOrk/netork#2555).
|
||||
- `get_package_proxy_report()` reports those hosts as `not_cached`.
|
||||
|
||||
### Changed
|
||||
- `container_engines()` lists an engine only when its CLI names itself on `--version`:
|
||||
podman-docker's `docker` is podman, and is no longer listed as Docker.
|
||||
- `configure_package_proxy(url)` has a step `cache` before `https`. It rewrites the https
|
||||
sources it can, fetches one of them through *url*, and turns them all back to https
|
||||
where *url* cannot. The `fetch` step proves the proxy with a plain http source only.
|
||||
- `configure_package_proxy("")` turns the sources back to https (step `sources`) before it
|
||||
removes the proxy file. Without the cache, apt would look for a host called `HTTPS`.
|
||||
|
||||
## [4.39.0] - 2026-11-14
|
||||
|
||||
### Added
|
||||
- `PackageIndexMissing` (a `RuntimeError`): what `get_available_updates()` raises when
|
||||
the host holds no package index to read from -- OpenWrt's, which lives in RAM, after
|
||||
every reboot. `refresh_available_updates()` loads it again, so a caller can tell this
|
||||
from a failed read and refresh instead of reporting an error (NetOrk/netork#2527).
|
||||
|
||||
## [4.38.0] - 2026-11-13
|
||||
|
||||
### Added
|
||||
- `get_system_identity()` also reads the host's system firmware (BIOS or UEFI) from the
|
||||
same SMBIOS tables in the same round trip: `bios_vendor`, `bios_version` and
|
||||
`bios_date` (ISO 8601, from sysfs's `MM/DD/YYYY`; anything else reads as empty). Only
|
||||
the vendors' text defaults (`To be filled by O.E.M.`, `Default string`) are
|
||||
placeholders there -- a version of `1` is a version. Output of the three identity
|
||||
fields alone still parses, with the firmware empty (NetOrk/netork#2518).
|
||||
- `ConfigRevisionsMixin`: a device's own configuration history (NetOrk/netork#2511).
|
||||
`get_config_revisions()` (newest first, the first in place now, as
|
||||
`ConfigRevisionDict`: id, UTC time, description, user, size) and
|
||||
`get_config_revision(revision_id)` are declared. `revert_config_revision(revision_id)`
|
||||
is a template over the driver's `_revert_to_config_revision`: it refuses an id that is
|
||||
not in the history (`UnknownConfigRevision`), and after the revert checks that the
|
||||
newest revision holds the revision's configuration, else `ConfigRevertFailed`; it
|
||||
returns that revision. `config_revision_content(text)` leaves out what a device stamps
|
||||
into every save, so an application can compare revisions with a configuration it has.
|
||||
- `add_service_account(..., replaces=[...])`: netOrk's keys the new one takes the place of
|
||||
go from its account once the new key is in it (step `old keys`), never the new key
|
||||
itself; while the new key could not be added they stay, so netOrk keeps its way in.
|
||||
netOrk calls it through a login with the new key, after trying that login, to move a
|
||||
host from its installation-wide key to its site's (NetOrk/netork#2462).
|
||||
- Each forwarding rule of `LogForwardingDict` names its `template`: the one the rule
|
||||
gives (`@host;RSYSLOG_SyslogProtocol23Format`, `action(… template="…")`), else the
|
||||
default set before it (`$ActionForwardDefaultTemplate`, or
|
||||
`module(load="builtin:omfwd" template="…")` for omfwd actions), else None -- rsyslog's
|
||||
own default, RFC 3164, which sends the host's local time without a time zone. A
|
||||
reader can tell a rule whose timestamps a collector files shifted (NetOrk/netork#493).
|
||||
|
||||
### Fixed
|
||||
- `apply_dhcp_reservationset` writes its changes so an address is released before it is
|
||||
taken: an update that moves a reservation off its address goes before the change that
|
||||
takes that address (along a chain, from its free end), and adds come after every
|
||||
update. A server that keeps addresses unique at each write, such as Kea, no longer
|
||||
refuses the second reservation as a duplicate when an address moves from one to
|
||||
another. A swap -- reservations trading addresses, or a longer rotation -- has no such
|
||||
order: its changes are still tried, and where the server refuses them the `[failed]`
|
||||
line says it was a swap and with which reservations. Everything else is still written
|
||||
and committed, and `DhcpApplyError` follows (#106).
|
||||
- `apply_dhcp_subnetset` no longer stops at the first subnet the device refuses. As
|
||||
`apply_dhcp_reservationset` has since 4.35.1, a refused subnet gets a `[failed]` line,
|
||||
the others are still written, any non-empty diff is committed -- even one whose every
|
||||
write was refused -- and `DhcpApplyError` follows. Before, the subnets written ahead of
|
||||
the refused one stayed saved but inactive, and since the device reports them as
|
||||
configured, no later apply committed them. `DhcpApplyError` takes an optional `kind`
|
||||
(`"reservation"` by default, `"subnet"` here) that its message names (#113).
|
||||
|
||||
## [4.37.0] - 2026-11-12
|
||||
|
||||
### Added
|
||||
- `UpdateMixin.get_installed_advisory_cves()` (declared): the CVEs a host's installed
|
||||
security advisories close, per package. With `DNF_INSTALLED_CVES_COMMAND` (dnf 4,
|
||||
read from the cache) and `parse_dnf_installed_cves()`, the parser every dnf driver
|
||||
shares. netOrk reads it where its knowledge base holds no records of the host's
|
||||
release, as the distribution's word that a backport is in (netOrk #2394).
|
||||
|
||||
## [4.36.2] - 2026-11-12
|
||||
|
||||
### Fixed
|
||||
- `kernel_reboot_pending` compares kernel releases the way rpm does (`rpmvercmp`). A
|
||||
number is newer than letters in the same place, so an Oracle Linux host running
|
||||
`6.12.0-208.112.5.1.el9uek` no longer asks to reboot into the older
|
||||
`6.12.0-208.112.5.el9uek`. A `~` (release candidate) comes before its release (#109).
|
||||
|
||||
## [4.36.1] - 2026-11-12
|
||||
|
||||
### Fixed
|
||||
- The host status no longer reports an Oracle Linux host's UEK kernels as an interrupted
|
||||
dnf transaction. The installonly packages are now also the ones the host's libdnf was
|
||||
built with, read from its Python binding: Oracle adds `kernel-uek` and its parts there,
|
||||
and their packages provide nothing of upstream's defaults (#107).
|
||||
|
||||
## [4.36.0] - 2026-11-11
|
||||
|
||||
### Added
|
||||
- `TimeSyncDict.dhcp_ntp_servers` (not required): the NTP servers a device got by DHCP
|
||||
(option 42) and uses, in its order; `[]` for none, absent or None where the driver cannot
|
||||
tell. `ntp_servers` stays the servers configured on the device and no longer holds
|
||||
DHCP's. A device that gets the site's time giver by DHCP is aligned, so an application
|
||||
has to tell the two apart (NetOrk/netork#2380).
|
||||
- `PosixTimeSyncMixin` reads them: chrony's sources from the DHCP client's `sourcedir`
|
||||
(`CHRONY_DHCP_DIRS`, `/run/chrony-dhcp` by default), systemd-timesyncd's
|
||||
`LinkNTPServers`. Where ntpd or OpenNTPD runs they are unknown (None).
|
||||
`timesyncd_link_servers` is public.
|
||||
|
||||
### Changed
|
||||
- `configure_time_sync` leaves DHCP-provided NTP servers alone. chrony: only `server`,
|
||||
`pool` and `peer` lines are commented out; no `sourcedir` line is any more, and the DHCP
|
||||
client's files are left alone. systemd-timesyncd: a link's servers stay and no longer
|
||||
fail the `verify` step.
|
||||
- A write gives back a DHCP client's `sourcedir` that 4.35.0 commented out
|
||||
(`#napalm-time-sync: sourcedir /run/chrony-dhcp`), so a host aligned by 4.35.0 hears DHCP
|
||||
again; chronyd restarts for it. Another `sourcedir` 4.35.0 took out stays out.
|
||||
- `timesyncd_servers` returns the configured servers (runtime, then system) without a
|
||||
link's; the fallback only while there is no server at all.
|
||||
|
||||
## [4.35.1] - 2026-11-11
|
||||
|
||||
### Fixed
|
||||
- `apply_dhcp_reservationset()` no longer stops at the first reservation the device refuses.
|
||||
One refused write (on OPNsense, an address in a subnet Kea does not manage) ended the run
|
||||
before the commit: every later reservation went unwritten, and the earlier ones stayed
|
||||
saved but inactive, where the next diff found them configured and never committed them. A
|
||||
refused change now gets a `[failed] <mac> -> <ip>: <reason>` line, the others are written,
|
||||
any non-empty diff commits, and `DhcpApplyError` (a `RuntimeError`, exported) is raised
|
||||
after the commit with how many of how many were refused (NetOrk/netork#2381).
|
||||
|
||||
## [4.35.0] - 2026-11-11
|
||||
|
||||
### Added
|
||||
- `TimeSyncMixin`: a device's time sources and time zone. `get_time_sync()` (declared only)
|
||||
returns `TimeSyncDict` -- the configured NTP servers in the device's order, the zone as an
|
||||
IANA name (None where the device keeps no name), whether the clock is synchronised now,
|
||||
and the client (`chrony`, `systemd-timesyncd`, `ntpd`, `openntpd`; None for the device's
|
||||
own). `configure_time_sync(ntp_servers=None, timezone=None)` is a fix template: None
|
||||
leaves a value alone, the device ends up with exactly the servers given, in order, and a
|
||||
`verify` step reads it back. An unknown zone, a malformed server, an empty list or a value
|
||||
outside the driver's `time_sync_writes` is refused before anything is written.
|
||||
`TIME_SYNC_VALUES` and `check_ntp_servers` are public (NetOrk/netork#2361).
|
||||
- `PosixTimeSyncMixin` implements it over `run_command`: read in one round trip as the login
|
||||
user (`timedatectl`, chrony's configuration and `chronyc -n sources`, `timedatectl
|
||||
show-timesync`, ntpd's and OpenNTPD's configuration); the zone by `timedatectl
|
||||
set-timezone`; chrony's servers in a file of their own (`sources.d`, else a `confdir` or
|
||||
an included file) with every other source commented out, then `chronyc reload sources` or
|
||||
a restart; systemd-timesyncd's in a drop-in that resets `NTP=` and empties `FallbackNTP=`.
|
||||
ntpd and OpenNTPD are read, not written. `parse_time_sync` is public.
|
||||
- `napalm_device_types.posix_tz` (from netOrk): `posix_tz`, `is_iana_zone`, `is_posix_tz` and
|
||||
`UnknownTimezone`, and `parse_posix_tz`, which takes a POSIX rule apart into the UTC
|
||||
offset and the summer-time transitions a switch wants (`PosixTzDict`,
|
||||
`DstTransitionDict`).
|
||||
|
||||
### Changed
|
||||
- Needs `tzdata` (2024.1 or later): the zones' rules come from its TZif files.
|
||||
|
||||
## [4.34.0] - 2026-11-10
|
||||
|
||||
### Added
|
||||
- `RunningBackupsMixin.get_running_backups()`: the backups running on a device right now --
|
||||
a hypervisor's backup of its guests (with the guests it is taking now), a backup server's
|
||||
backup, sync, verify, garbage collection, prune or tape run, a host's own file-level backup.
|
||||
Declared only; a driver mixes it in when it can tell, and a driver without it cannot tell.
|
||||
`RunningBackupDict`, `RunningBackupKind` and `RUNNING_BACKUP_KINDS` are public. An
|
||||
application asks right before it restarts a device (NetOrk/netork#2318).
|
||||
|
||||
## [4.33.0] - 2026-11-07
|
||||
|
||||
### Added
|
||||
- `get_host_status()` tells an interrupted package manager on hosts without dpkg too, and
|
||||
says which one it read in the new `package_manager` field (`dpkg`, `dnf`, `yum`, `apk`,
|
||||
`opkg`, or None). dnf and yum: a package installed in two versions (not the kernels and
|
||||
other packages dnf keeps side by side) as state `duplicate`, or a transaction that never
|
||||
ended (dnf 4's history, yum's `transaction-all` journal). apk: a package apk marked with
|
||||
broken files or a broken script (`broken-files`, `broken-script`), the ones `apk fix` would
|
||||
take. opkg: a package left `unpacked`, `half-configured` or `half-installed`, or flagged for
|
||||
reinstallation. All read without root; while one of them runs the answer is unknown
|
||||
(NetOrk/netork#851).
|
||||
|
||||
## [4.32.0] - 2026-11-07
|
||||
|
||||
### Added
|
||||
- `SshServerAuthMixin.get_ssh_server_auth()`: how an OpenSSH server lets people log in --
|
||||
password, keyboard-interactive, public key, host-based and GSSAPI authentication,
|
||||
`AuthenticationMethods` as lists of methods, `PermitRootLogin` and `UsePAM`, from `sshd -T`
|
||||
as root, and sshd's PAM `auth` stack (each module with its control and arguments, includes
|
||||
followed), from `/etc/pam.d` as the login user. `OpenSshServerMixin` carries it, so every
|
||||
driver that can harden sshd has it. `parse_sshd_auth`, `parse_pam_auth`, `parse_pam_files`,
|
||||
`pam_auth_stack` and `SSHD_EFFECTIVE_COMMAND` are public (NetOrk/netork#662).
|
||||
|
||||
## [4.31.1] - 2026-11-06
|
||||
|
||||
### Fixed
|
||||
- `get_log_sources()` names as a file's writer only a process that holds it open for writing.
|
||||
A log reader -- CrowdSec, Promtail, rsyslog's `imfile`, a `tail -F` -- was given the file
|
||||
it reads as if it wrote it. A file only readers hold is now listed without a producer
|
||||
(`unit` and `process` None); one only a reader inside a container holds is left out, as its
|
||||
path is that container's view of a mount. The access mode comes from
|
||||
`/proc/<pid>/fdinfo/<fd>`, read in the same command (NetOrk/netork#2092).
|
||||
|
||||
## [4.31.0] - 2026-11-06
|
||||
|
||||
### Added
|
||||
- `get_log_sources()` also says where the logs go beyond the host: `forwarding` holds whether
|
||||
rsyslog runs, its forwarding rules (legacy `@`/`@@`/`:omrelp:` and RainerScript
|
||||
`omfwd`/`omrelp`, with selector, ruleset and whether they take every message), its `imfile`
|
||||
inputs, and whether the journal reaches it (`imjournal`, or `imuxsock` with journald's
|
||||
`ForwardToSyslog`). Read in the same command; `parse_log_forwarding` and `parse_rsyslog` are
|
||||
public (NetOrk/netork#2053).
|
||||
|
||||
## [4.30.0] - 2026-11-04
|
||||
|
||||
### Added
|
||||
- `LogSourcesMixin.get_log_sources()`: every log a Linux host writes. Sources are the units
|
||||
journald holds entries for, the log files running processes hold open (with size, last write
|
||||
and the service or container writing them), and the engine's file of each container's output.
|
||||
A file a container writes is named by the container's own path. `LOG_SOURCES_COMMAND` and
|
||||
`parse_log_sources` are public, and a host whose `find` cannot list open files (busybox)
|
||||
raises `LogSourcesUnavailable`. A driver supplies `_run_log_sources_command(command,
|
||||
privileged=)`, as for listening sockets (NetOrk/netork#2049).
|
||||
|
||||
## [4.29.0] - 2026-11-04
|
||||
|
||||
### Added
|
||||
- `remove_local_account_keys(name, keys, *, clear_password=False)`: with `clear_password`
|
||||
the account's password goes along with the keys, and so do its sudo rule and admin
|
||||
groups, as sudo asks for that password. For a person who deleted their key and whose
|
||||
password went with it. The account stays open; the steps are `keys`, `password` and
|
||||
`sudo`, each run when another failed (NetOrk/netork#2033).
|
||||
|
||||
## [4.28.0] - 2026-11-04
|
||||
|
||||
### Added
|
||||
- `LocalAccountsMixin.add_local_account(..., replaces=[...])`: the keys the new one takes
|
||||
the place of go from the account, matched by their base64 whatever a line's options or
|
||||
comment. Keys the person added on the host stay. The step is `old keys`; it runs even
|
||||
when the new key could not be added (NetOrk/netork#2013).
|
||||
- `add_local_account(..., clear_password=True)`: the account's password goes, and it logs
|
||||
in with a key only. Step `password`. It cannot be combined with a `password_hash` or
|
||||
with `admin=True`, as the sudo rule asks for that password. A driver supplies
|
||||
`_account_clear_password`; one that does not fails the step and says so.
|
||||
- `LocalAccountsMixin.remove_local_account_keys(name, keys)`: takes the named keys off an
|
||||
account and leaves it open, its password and sudo as they are -- for a person who
|
||||
deleted a key and has no new one. Step `keys`.
|
||||
- A driver whose host keeps keys elsewhere overrides `_account_drop_keys` next to
|
||||
`_account_add_key` and `_account_remove_keys`.
|
||||
|
||||
## [4.27.0] - 2026-11-03
|
||||
|
||||
### Added
|
||||
- `ScheduledJobsMixin`: what a host runs on its own schedule as one shape,
|
||||
`ScheduledJobDict` — cron lines, run-parts scripts, anacron, systemd timers, `periodic`,
|
||||
a platform's own jobs, Windows tasks — with who owns each definition (`managed_by`) and
|
||||
what the driver can do to it (`actions`). `get_scheduled_jobs` reads them with the host's
|
||||
time zone; `manage_scheduled_job` enables, disables or runs one now; `put_scheduled_job`
|
||||
and `delete_scheduled_job` create, change and delete a job an application writes. Every
|
||||
write names the `digest` the caller saw (`job_digest`) and raises `ScheduledJobChanged`
|
||||
when the host's definition differs; `ScheduledJobRefused` for a job that cannot take a
|
||||
verb (NetOrk/netork#1933, #86).
|
||||
- `PosixScheduledJobsMixin`: the implementation over the command channel. One framed report
|
||||
as root reads `/etc/crontab`, `/etc/cron.d`, the user crontabs, the run-parts directories,
|
||||
`/etc/anacrontab` and every systemd timer with the unit it starts, and which package owns
|
||||
each definition. A cron line is switched off behind `#napalm-disabled: `; an
|
||||
application's job is a timer where systemd runs, else a file in `/etc/cron.d` or marked
|
||||
lines in the user's crontab.
|
||||
- `napalm_device_types.cron`: cron expressions as Vixie cron reads them, their next runs in
|
||||
a time zone, and as systemd `OnCalendar` lines that fire on exactly the same minutes.
|
||||
|
||||
### Removed
|
||||
- `OSDriver.get_cron_jobs` and `CronJobDict`. No application called them; the readers in
|
||||
napalm-linux and napalm-bsd go with them. `get_scheduled_jobs` replaces them.
|
||||
|
||||
## [4.26.0] - 2026-11-03
|
||||
|
||||
### Added
|
||||
- `OpenSshServerMixin.SSHD_CONFIG_GENERATED`: a driver whose platform writes sshd_config
|
||||
from its own database, but includes `/etc/ssh/sshd_config.d` (OpenMediaVault), sets it
|
||||
and keeps `harden_ssh_server`. The hardening then goes only into the drop-in; a
|
||||
sshd_config without that include is left alone and the result says why, since the
|
||||
platform would write over a change to it on its next apply (#88, NetOrk/netork#1950).
|
||||
|
||||
## [4.25.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
- `BackupServerDriver` (`ROLE = "backup_server"`), a role base for backup servers such as
|
||||
Proxmox Backup Server (#82). It declares `get_backup_datastores`, `get_backup_groups`
|
||||
(each group with its newest snapshot), `get_backup_snapshots`, `get_backup_jobs`
|
||||
(garbage collection, verify, prune, sync and tape in one list) and `get_backup_remotes`,
|
||||
and the actions `start_garbage_collection`, `run_backup_job`, `verify_backup_snapshot`,
|
||||
`set_backup_snapshot_protected` and `delete_backup_snapshot`, which return a task to
|
||||
follow with `get_backup_task`. The shapes live in `napalm_device_types.backups`. A
|
||||
server that manages its own disks lists `StorageDriver` as its second role.
|
||||
- `ClusterStorageDict.backup_server` (optional): which backup server, datastore and
|
||||
namespace a hypervisor's backup storage writes to, with the certificate fingerprint it
|
||||
pins, so an application can tie a server's backup groups to a cluster's guests.
|
||||
|
||||
## [4.24.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
- `parse_lldpctl_keyvalue(output)` and `LLDPCTL_KEYVALUE_COMMAND`: lldpd's neighbours
|
||||
(`lldpctl -f keyvalue`) as one `LldpNeighborRow` per neighbour, for every driver of a
|
||||
host that runs lldpd. Several neighbours on one port (a phone and the PC behind it, an
|
||||
unmanaged switch) stay apart, an interface name with dots (`eth0.1`) stays whole, the
|
||||
chassis and port ids are read whatever their type (MAC, address, interface name, local
|
||||
id), with management addresses and capabilities. A failed lldpctl (lldpd not running,
|
||||
lldpctl missing) raises instead of reading as no neighbours.
|
||||
- `lldp_neighbors(rows)` and `lldp_neighbors_detail(rows, interface="")`: NAPALM's
|
||||
`get_lldp_neighbors` and `get_lldp_neighbors_detail` from those rows, so a driver no
|
||||
longer builds the two shapes itself. A neighbour that names its chassis by a MAC
|
||||
address carries it in `get_lldp_neighbors` as `mac`, in lower case
|
||||
(`LldpNeighborDict`), so an application can match it by MAC.
|
||||
|
||||
### Fixed
|
||||
- `DNF_SECURITY_COMMAND` reads the cached metadata only (`dnf --cacheonly`), as
|
||||
`APT_UPGRADABLE_COMMAND` reads apt's local index (#76). With an expired cache dnf
|
||||
downloaded the repositories' metadata first, and on an Oracle Linux host on OCI that
|
||||
outlasted netOrk's whole poll budget. Refreshing the index stays a step of its own
|
||||
(`dnf makecache`). Without a cache dnf fails at once, which already reads as
|
||||
"security unknown".
|
||||
|
||||
## [4.23.0] - 2026-11-02
|
||||
|
||||
### Changed
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||
3.12 venv no longer has.
|
||||
- `requests` is a declared dependency (floor 2.25.0), for `tls_certificates`; it came
|
||||
with napalm before.
|
||||
- The SNMP health profile shapes (`SnmpHealthProfile`, `SnmpValueSpec`,
|
||||
`SnmpMemorySpec`, `SnmpInterfacesSpec`) are defined in
|
||||
`napalm_device_types.snmp_health_profile`. The package and `models` still export
|
||||
them, so an existing import keeps working.
|
||||
|
||||
### Added
|
||||
- `HypervisorDriver.get_vm_migration_preflight(name)`, `migrate_vm(name, target_node,
|
||||
online=True, target_storage=None, timeout=3600)` and `set_node_maintenance(node,
|
||||
enabled)`: which nodes of its cluster a guest could move to and what blocks it
|
||||
(`MigrationPreflightDict`: `allowed_nodes`, `refused_nodes` with the platform's
|
||||
reason, `local_disks` the migration copies, `local_resources` that block it), the
|
||||
move itself, blocking until the platform's task ended and raising with the
|
||||
platform's own cause, and a node's HA maintenance mode. Declared only; netOrk
|
||||
probes each with `hasattr`.
|
||||
- `get_clusters()` may report HA, backups and quorum votes: `ClusterDict.ha_resources`
|
||||
(`HAResourceDict`: requested and current state, node, PVE 8 group, PVE 9 rules),
|
||||
`backup_jobs` (`BackupJobDict`: schedule, storage, mode, the guests a job covers)
|
||||
and `backups` (`BackupDict`: per guest and storage the newest backup, its size
|
||||
and how many there are), and `ClusterNodeDict.votes`. All `NotRequired`, so
|
||||
drivers written before stay valid; None means could not be read, `[]` read and
|
||||
empty.
|
||||
- `napalm_device_types.tls_certificates`: TLS certificates by trust on first use, the
|
||||
counterpart of `ssh_host_keys` for a driver's HTTPS API. A driver takes the
|
||||
fingerprint to expect from `optional_args["tls_fingerprints"]` (by port, the SHA-256
|
||||
of the DER certificate, `SHA256:AB:CD:…`) and refuses any other certificate with
|
||||
`TlsCertificateMismatch` (a `ConnectionException` naming both fingerprints) before a
|
||||
password is sent; no CA is consulted, so a self-signed certificate verifies. Without
|
||||
a fingerprint the first certificate is accepted. Every certificate seen goes to
|
||||
`optional_args["tls_certificate_observer"]`. `CertificateCheck.verify_server()`
|
||||
checks the certificate in a handshake of its own, `pin(session)` makes every later
|
||||
connection of a `requests` session present the same one, `refusing()` turns a refusal
|
||||
there into the mismatch, `observe()` reports it once the login stands
|
||||
(NAPALM/napalm-hpe-aruba-procurve#17).
|
||||
- `LldpAgentMixin.configure_lldp_agent(interfaces)` (`napalm_device_types.fixes`): run
|
||||
an LLDP agent on the interfaces the caller names. The template installs the agent
|
||||
(`ensure_package(LLDP_AGENT_PACKAGE)`), has the driver write the interface list
|
||||
(`_write_lldp_agent_config`), then enables and restarts the service
|
||||
(`manage_service(LLDP_AGENT_SERVICE, …)`); both names default to `lldpd`. No
|
||||
interface is a ValueError before anything changes. It is the action for what LLDP
|
||||
getters used to do on their own (NAPALM/napalm-openwrt#8).
|
||||
- `SnmpValueSpec.unknown`: a driver whose device's agent answers a value wrongly says
|
||||
so in its `SNMP_HEALTH_PROFILE` (`"cpu": {"unknown": True}`), and the application
|
||||
reports no value for it -- not the standard reading, not 0. OpenBSD's net-snmp,
|
||||
which reports the CPU as never idle, is the case (NAPALM/napalm-bsd#7).
|
||||
- `VMProvisionIncomplete` (`napalm_device_types.provisioning`): what
|
||||
`create_vm_from_cloud_init` raises when it fails after the VM was created. A
|
||||
`RuntimeError` with the failure as its cause and the half-built VM's `vmid` and
|
||||
`node`, so the caller can remove it with `destroy_vm` (NAPALM/napalm-proxmox#28).
|
||||
- `HypervisorDriver.get_clusters()` and its shapes `ClusterDict`, `ClusterNodeDict`,
|
||||
`ClusterStorageDict`, `ClusterNetworkDict`: every cluster the connection can see,
|
||||
with its nodes (offline ones included, `local` on the node the connection is),
|
||||
their CPU and memory, and the storages and networks with the nodes that see each.
|
||||
A standalone host is a cluster of one with no name; a manager reports each cluster
|
||||
and standalone host it runs. Declared only (NetOrk/netork#484, #1821).
|
||||
- `create_vm_from_cloud_init(node=…)`: the cluster node to create the VM on. None
|
||||
leaves it to the driver; a driver that can only create on its own node raises
|
||||
ValueError for another (NetOrk/netork#1822).
|
||||
- `LocalAccountsMixin.add_service_account(name, public_key)`: netOrk's own account,
|
||||
created through the account the driver logs in with today. It takes a key and no
|
||||
password, and a rule of its own in `85-service-<name>` lets it run everything as
|
||||
root without a password (`NOPASSWD: ALL`, checked with `visudo` and `sudo -l`). An
|
||||
account that is there is opened again and keeps its other keys; root is refused
|
||||
(NetOrk/netork#1817). With `uid=`, a new account gets that uid once no other account
|
||||
has it; one that is there keeps its own. A driver supplies
|
||||
`_account_create_with_uid`. An account that is there and cannot log in (`nologin`,
|
||||
`false`) is another service's, such as a netOrk satellite's `netork`, and is refused
|
||||
before anything changes.
|
||||
- `LocalAccountsMixin` (`napalm_device_types.local_accounts`): personal login accounts
|
||||
on a host. `get_local_accounts(names)` reads them back (groups, lock, sudo, key
|
||||
files), `add_local_account(name, public_key, password_hash=, admin=)` creates or
|
||||
reopens one, `lock_local_account(name)` takes its keys and sudo away and refuses
|
||||
every login while keeping its home. Every command root runs is one fixed command,
|
||||
the key files are read and written as the account itself, and the sudo rule is a
|
||||
drop-in of its own, checked with `visudo` and `sudo -l`. A driver supplies the
|
||||
commands that create, open and lock an account and take it out of a group, and may
|
||||
replace where the keys are kept (`_account_key_files`, `_account_read_keys`,
|
||||
`_account_add_key`, `_account_remove_keys`; default `~/.ssh/authorized_keys`)
|
||||
(NetOrk/netork#1793).
|
||||
- `OpenSshServerMixin.exempt_from_ssh_penalties`: puts the address the host sees
|
||||
the managing client at (`$SSH_CONNECTION`) into `PerSourcePenaltyExemptList`,
|
||||
in `/etc/ssh/sshd_config.d/00-netork-penalty-exempt.conf`, next to the host's
|
||||
own exemptions. Only where sshd has per-source penalties (OpenSSH 9.8+; an older
|
||||
one refuses the directive) and sshd_config includes the drop-in directory;
|
||||
checked with `sshd -t` and `sshd -T`, then a new session, and taken back on any
|
||||
failure. Helpers: `parse_penalty_exemptions`, `client_address`, `is_exempt`
|
||||
(NetOrk/netork#1800).
|
||||
- `retry_refused` and `refused_before_banner` (`napalm_device_types.ssh_host_keys`):
|
||||
a connection sshd closes before its banner -- what OpenSSH 9.8+ does to a source
|
||||
it has just penalised -- is tried again after 1, 3, 7 and 15 s.
|
||||
`HostKeyCheck.connect` does so itself (NetOrk/netork#1800).
|
||||
- `ARP_AGE_UNKNOWN` (`napalm_device_types.arp`, `-1.0`): the `age` a driver reports
|
||||
in `get_arp_table` and `get_ipv6_neighbors_table` when the device does not say how
|
||||
old an entry is. `0.0` means "confirmed just now" and is no stand-in for it
|
||||
(NetOrk/netork#1327).
|
||||
- `NetworkTargetDict.uplinks` (optional): the physical NICs a bridge leaves the
|
||||
host through, one group per way out -- a bond's slaves together, a single NIC
|
||||
alone (`[["eno1", "eno2"]]`). A missing key means unknown, an empty list a
|
||||
bridge without uplink. NetOrk follows their LLDP neighbours to the switch port
|
||||
and its untagged VLAN; one slave's neighbour speaks for its bond
|
||||
(NetOrk/netork#1325).
|
||||
- `HostShutdownMixin.shutdown_host()`, on `DeviceTypeDriver`: shut the device itself
|
||||
down cleanly through its own means; declared, so `hasattr` says whether a driver
|
||||
can. No forced variant (NetOrk/netork#1636).
|
||||
- `VmStopRequestMixin.begin_stop_vm(name)`: ask for a VM's clean shutdown and return
|
||||
at once, for callers that wait on a timer instead of in `stop_vm`. No role demands
|
||||
it (NetOrk/netork#1636).
|
||||
- `SudoHistoryMixin` (`napalm_device_types.sudo_history`): the sudo password an earlier
|
||||
driver typed into an interactive shell (`echo '<password>' | sudo -S -p "" …`) and
|
||||
left in the login user's shell history, for a driver to mix in (NetOrk/netork#1090).
|
||||
The driver says what its lines carry (`SUDO_HISTORY_MARKER`) and which files its
|
||||
partial sudo left to the login user (`SUDO_ROOT_FILES`), and supplies `run_command`.
|
||||
- `get_history_sudo_lines()` counts the lines per history file (`~/.bash_history`,
|
||||
`~/.zsh_history`, `~/.ash_history`, `~/.sh_history`) with `grep -c` as the login
|
||||
user. No line is read back; a file it cannot read raises.
|
||||
- `remove_history_sudo_lines()` deletes exactly those lines as the login user (`sed
|
||||
-i`, its backup overwritten with `shred -u`), and as root gives each of
|
||||
`SUDO_ROOT_FILES` back to `root:root` where it is a regular file, not a symbolic
|
||||
link, owned by the login user. It reports every file's lines before and after,
|
||||
how many were removed and which files are root's again. Nothing goes to stdin.
|
||||
|
||||
### Fixed
|
||||
- `AptProxyMixin` knows that apt's https sources take the http proxy too: apt's https
|
||||
method asks `Acquire::https::Proxy` and then `Acquire::http::Proxy`, for the host and
|
||||
then for all. An `00proxy` with the http line alone sent download.docker.com and
|
||||
every other https source to apt-cacher-ng, which answers `403 CONNECT denied` without
|
||||
a `PassThroughPattern`, and the whole upgrade failed (NetOrk/netork#1811).
|
||||
- The report carries `https_proxy`, `https_per_host` and `https_settings`;
|
||||
`https_proxy_for(report, host)` is the proxy apt takes for one https host.
|
||||
- `check_https_source()` fetches one https source's `InRelease` the way apt does;
|
||||
None where no https source goes through a proxy.
|
||||
- `configure_package_proxy` gains an `https` step: one https source through the new
|
||||
proxy. Where the proxy refuses it, `00proxy` also says `Acquire::https::Proxy
|
||||
"DIRECT";`, later https lines to the same proxy are commented out, and the source
|
||||
is fetched direct. An HTTP error from the mirror counts as let through.
|
||||
- `apt_fetch_command` takes https URLs; `direct` sets the host's https setting too.
|
||||
- `comment_out_command(..., scheme="https")`.
|
||||
|
||||
## [4.22.0] - 2026-10-23
|
||||
|
||||
### Added
|
||||
- `AptProxyMixin` (`napalm_device_types.apt_proxy`): apt's proxy on a
|
||||
Debian-family host, for a driver to mix in (NetOrk/netork#1397).
|
||||
- `get_package_proxy()` is the proxy apt really fetches through, as
|
||||
`apt-config dump` says, and no longer the content of one file. A proxy the
|
||||
Debian or Ubuntu installer set elsewhere wins over `00proxy`, and was missed.
|
||||
- `get_package_proxy_report()` adds where it is set: every line of apt's
|
||||
configuration that sets it, in the order apt reads them, the per-host
|
||||
proxies, and the sources fetched over http and over https.
|
||||
- `check_package_proxy(url, expect)` fetches a page from the host with apt's
|
||||
own downloader, past any proxy, and says whether the host reached it and
|
||||
whether the page says what you expected.
|
||||
- `configure_package_proxy(url)` writes the proxy, comments out every other
|
||||
line that sets a different one, reads the result back and fetches one
|
||||
source through the proxy. It fails when apt still fetches elsewhere.
|
||||
- `same_proxy_url()` compares two proxy URLs by scheme, host and port.
|
||||
|
||||
## [4.21.1] - 2026-10-22
|
||||
|
||||
The first release on PyPI since 0.1.0.
|
||||
|
||||
### Changed
|
||||
- The package follows the NAPALM driver standard
|
||||
(https://git.netork.io/NAPALM/driver-standard): CI on Gitea runs ruff, strict
|
||||
mypy, the tests on Python 3.10–3.13 and at the lowest declared versions,
|
||||
bandit, pip-audit and a build check, and a release tag publishes to PyPI.
|
||||
- Type annotations use builtin generics (`list[str]`, `X | None`) instead of
|
||||
`typing.List` and `Optional`. They mean the same to a type checker.
|
||||
- The project links point at git.netork.io instead of GitHub.
|
||||
@@ -6,14 +6,14 @@ Instead of inheriting directly from `napalm.base.NetworkDriver`, a driver can in
|
||||
|
||||
```python
|
||||
# without napalm-device-types
|
||||
class OpenWrtDriver(NetworkDriver):
|
||||
...
|
||||
class OpenWrtDriver(NetworkDriver): ...
|
||||
|
||||
|
||||
# with napalm-device-types
|
||||
from napalm_device_types import AccessPointDriver
|
||||
|
||||
class OpenWrtDriver(AccessPointDriver):
|
||||
...
|
||||
|
||||
class OpenWrtDriver(AccessPointDriver): ...
|
||||
```
|
||||
|
||||
## Why?
|
||||
@@ -22,13 +22,581 @@ NAPALM's `NetworkDriver` defines a common interface for all network devices. In
|
||||
|
||||
`napalm-device-types` sits in between: it adds one well-typed layer of abstract methods per device category, so every driver for the same category exposes the same interface.
|
||||
|
||||
## Roles: what a device *is*
|
||||
|
||||
A device is often several things at once. A QNAP NAS runs VMs on a Linux userland; an
|
||||
OpenMediaVault box is a NAS built on Debian. So a driver inherits **one role base per
|
||||
role its device fills**, and **the order it lists them in is the ranking**:
|
||||
|
||||
```python
|
||||
class QnapQtsDriver(
|
||||
StorageDriver, HypervisorDriver, LinuxDriver
|
||||
): ... # primary_role_of(...) == "storage"
|
||||
```
|
||||
|
||||
`roles_of(cls)`, `role_keys_of(cls)` and `primary_role_of(cls)` read that back. Nothing
|
||||
restates the ranking: there is no precedence table and no attribute to override.
|
||||
|
||||
A server's baseboard management controller (Supermicro BMC, Dell iDRAC, HPE iLO,
|
||||
Lenovo XCC) is a role of its own, `ManagementControllerDriver` (`management_controller`),
|
||||
reached over Redfish or IPMI (`USES_SSH = False`). It is not the server it manages:
|
||||
`reboot_host` restarts the BMC (Redfish `Manager.Reset`), while `set_power_state`
|
||||
(`On`, `GracefulShutdown`, `ForceOff`, `GracefulRestart`, `ForceRestart`, `PowerCycle`)
|
||||
acts on the server. `get_hardware_inventory` carries the server's serial number, system
|
||||
UUID and NIC MACs -- what ties the BMC to the host it manages. Its sensors come through
|
||||
NAPALM's `get_environment`, with `cpu` and `memory` empty, since a BMC does not know the
|
||||
host OS's load; it has no `HealthMetricsMixin` (SNMP) and no command channel.
|
||||
|
||||
A backup server (Proxmox Backup Server) is a role of its own too, `BackupServerDriver`
|
||||
(`backup_server`). Its datastores, the backup groups in them (each with its newest
|
||||
snapshot), its jobs (garbage collection, verify, prune, sync, tape) and its remotes have
|
||||
no counterpart in `StorageDriver`, so they are not bent into pools, volumes and
|
||||
replication jobs. A server that also manages its own disks and pools lists
|
||||
`StorageDriver` second: `class ProxmoxBackupDriver(BackupServerDriver, StorageDriver, ...)`.
|
||||
Its actions (garbage collection, running a job, verifying, protecting or deleting a
|
||||
snapshot) start a task and return its id at once; `get_backup_task` follows it. On the
|
||||
hypervisor side, a cluster storage that writes to a backup server says which one
|
||||
(`ClusterStorageDict.backup_server`: server, port, datastore, namespace, fingerprint), so
|
||||
an application can tie the server's groups to the cluster's guests.
|
||||
|
||||
### Role bases declare; they never implement
|
||||
|
||||
**A role base must not contain a single runtime method — not even a
|
||||
`NotImplementedError` placeholder.** Its methods are declared under `if TYPE_CHECKING`:
|
||||
|
||||
```python
|
||||
class StorageDriver(DeviceTypeDriver):
|
||||
"""Contract, not code."""
|
||||
|
||||
ROLE: str = "storage"
|
||||
TYPE_LABEL: str = "Storage"
|
||||
|
||||
if TYPE_CHECKING: # nothing exists at runtime
|
||||
|
||||
def get_disks(self) -> List[PhysicalDiskDict]: ...
|
||||
```
|
||||
|
||||
This is not a style preference. A placeholder on a base class is not neutral under
|
||||
multiple inheritance: it wins the MRO against a sibling base's *working* implementation
|
||||
and silently replaces it. Adding one stub to a base is therefore a breaking change for
|
||||
every driver that mixes that base with another. It happened three times here before the
|
||||
rule existed, and each time the fix was hand-written forwarding methods in the driver.
|
||||
|
||||
Two things follow, and both are improvements:
|
||||
|
||||
- **`hasattr` is truthful again.** A method exists on a driver class exactly when that
|
||||
driver implemented it, which is how netOrk asks "can this driver list disks".
|
||||
- **A method that was never implemented raises `AttributeError`, not
|
||||
`NotImplementedError`.** Ask before calling.
|
||||
|
||||
The rule covers this package's methods, not NAPALM's. `NetworkDriver` still carries
|
||||
a runtime `NotImplementedError` stub for each of its getters (`get_interfaces`,
|
||||
`get_environment`, `get_users`, …), and every role base inherits it. So a NAPALM getter
|
||||
must come from the driver class itself or from a mixin listed **before** the first role
|
||||
base; a mixin listed after it loses the MRO to NAPALM's stub. For the same reason
|
||||
`hasattr` says nothing about NAPALM's getters, and the OS role's account listing is
|
||||
`get_os_users`, not `get_users` -- NAPALM's `get_users` has a different shape.
|
||||
|
||||
### NAPALM's getters: an unknown ARP age is `-1.0`
|
||||
|
||||
NAPALM requires an `age` on every entry of `get_arp_table` and
|
||||
`get_ipv6_neighbors_table`: seconds since the device last confirmed that neighbour.
|
||||
Many devices do not report one (`ip neigh`, `/proc/net/arp`, a router's host list).
|
||||
A driver that cannot read the age reports `ARP_AGE_UNKNOWN` (`-1.0`, as NAPALM's IOS
|
||||
driver does), never `0.0`: `0.0` means "confirmed just now", and an application that
|
||||
ranks sightings by freshness takes it at its word (NetOrk/netork#1327). An expiry
|
||||
countdown (FreeBSD's `expires in 1180 seconds`) is not an age either. A driver whose
|
||||
device does report the age keeps reporting it.
|
||||
|
||||
## Function classes: what a device *can do*
|
||||
|
||||
Behaviour shared across roles lives in a function class, exactly once, and a role base
|
||||
is a thin bundle over them — `PackageManagementMixin`, `HealthMetricsMixin`,
|
||||
`ServiceControlMixin`, `UpdateMixin`, `NatVpnMixin`, `MacAclMixin`, `FirewallRuleMixin`,
|
||||
`DhcpServerMixin`, `PingSweepMixin`, `ConfigLifecycleMixin`, `InterfaceFilterMixin`.
|
||||
`HostRebootMixin` (`reboot_host`) and `HostShutdownMixin` (`shutdown_host`) are mixed
|
||||
into `DeviceTypeDriver` itself, since any device may be restartable or able to shut itself
|
||||
down; like the others they only declare. `VmStopRequestMixin` (`begin_stop_vm`) asks for a
|
||||
VM's clean shutdown without waiting for it — a hypervisor driver mixes it in when it can.
|
||||
|
||||
**Fixes are templates** (`napalm_device_types.fixes`, since 4.13). A change the
|
||||
application wants made on a device runs as fixed steps the driver implements, with values
|
||||
the caller supplies: `SnmpAgentMixin.configure_snmp_agent(settings)` (install, configure,
|
||||
firewall, start), `LldpAgentMixin.configure_lldp_agent(interfaces)` (install, write the
|
||||
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; 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
|
||||
change in one call overrides the template method. A driver mixes in the fixes its device
|
||||
can take; none is on a role base. They replace `run_device_action`, which is deprecated.
|
||||
|
||||
**SNMP is the application's** (`docs/STRUCTURE.md`). `HealthMetricsMixin` is deprecated
|
||||
since 4.12 and goes in 5.0. A driver does not collect over SNMP; a driver whose device
|
||||
publishes its health values under OIDs of its own declares them as data:
|
||||
|
||||
```python
|
||||
class MySwitchDriver(SwitchDriver):
|
||||
SNMP_HEALTH_PROFILE: ClassVar[SnmpHealthProfile] = {
|
||||
"uptime": {"oids": ["1.3.6.1.2.1.1.3.0"]},
|
||||
"cpu": {"oids": ["<vendor cpu oid>", "<older firmware's>"]},
|
||||
"memory": {"total": {"oids": ["<oid>"]}, "free": {"oids": ["<oid>"]}, "unit": "KiB"},
|
||||
}
|
||||
```
|
||||
|
||||
A value is `oids` (the first that answers wins) or a `table` folded by `first`, `average`
|
||||
or `max`, with an optional `pattern` for an agent that answers with text. What the profile
|
||||
does not name, the application reads from the standard UCD-MIB and IF-MIB.
|
||||
A value the agent gets wrong is `{"unknown": True}`: the application then reports no value
|
||||
for it, rather than the standard reading or a default (OpenBSD's net-snmp reports its CPU
|
||||
as never idle).
|
||||
|
||||
`KernelFactsMixin` (`get_kernel_facts`) is the exception that is mixed in by a driver
|
||||
rather than by a role base: what a Linux kernel has built and loaded is read the same way
|
||||
everywhere, so the command and its parse are concrete here and a driver supplies only
|
||||
`_run_kernel_facts_command`. `OSDriver` does not carry it — a Windows host is an OS driver
|
||||
too, and `hasattr(driver, "get_kernel_facts")` has to stay truthful.
|
||||
|
||||
`HardeningMixin` (`get_hardening`) is mixed in the same way: how the host is hardened, as
|
||||
its kernel and its own tools say it, in one read-only command. The active security modules
|
||||
(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`) and the mode it boots in
|
||||
(`/etc/selinux/config`), AppArmor's switch and its profiles per mode (`aa-status --json`,
|
||||
the one part that needs root), the crypto policy (`update-crypto-policies --show`) and FIPS
|
||||
mode, the kernel's answer for each CPU vulnerability (`/sys/devices/system/cpu/vulnerabilities`,
|
||||
put in one word by `cpu_vulnerability_state`), `mitigations=` and `nosmt` from the kernel
|
||||
command line, and `ID`/`ID_LIKE` from `/etc/os-release`. Read as root first and, where root
|
||||
is refused, as the login user without the profile counts. A driver supplies
|
||||
`_run_hardening_command(command, privileged=)`; what was not read is `None`, never "off".
|
||||
|
||||
`ServicePackagesMixin` (`get_service_packages`) is mixed in the same way: which installed
|
||||
packages each systemd service is made of — the one shipping its unit file and the one
|
||||
shipping the binary its `ExecStart` runs, by `dpkg -S` or `rpm -qf`, not the libraries
|
||||
that binary links against. An application needs it to let a statement about a service
|
||||
(the postgresql unit) reach the findings on its packages. A driver supplies
|
||||
`_run_service_packages_command`.
|
||||
|
||||
`AptProxyMixin` (`napalm_device_types.apt_proxy`, since 4.22) is `PackageProxyMixin` for a
|
||||
Debian-family host, mixed in the same way. What apt fetches through is what `apt-config dump`
|
||||
says, not one file: apt reads `apt.conf.d` in order and `apt.conf` last, and the last value
|
||||
wins (`get_package_proxy`, `get_package_proxy_report` with every line that sets it).
|
||||
`check_package_proxy(url, expect)` fetches a page with apt's own downloader, past any proxy.
|
||||
`configure_package_proxy(url)` writes `00proxy`, comments out every other line that sets a
|
||||
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.
|
||||
|
||||
`AptHistoryMixin` (`napalm_device_types.apt_history`) implements
|
||||
`UpdateMixin.get_update_history` from apt's own log over the driver's `run_command`: every
|
||||
transaction in `/var/log/apt/history.log` and its rotations, newest first, with the same
|
||||
ids Proxmox VE 9.3's `GET /nodes/{node}/apt/history` gives (start time and the index among
|
||||
those that started in the same second of the same file). A driver whose host may run
|
||||
another package manager gates it, as napalm-linux does.
|
||||
|
||||
`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,
|
||||
dnf-automatic) and when that last succeeded (apt's `upgrade-stamp`), and whether its package
|
||||
manager was left halfway (unknown while one is running): dpkg (a journal in
|
||||
`/var/lib/dpkg/updates` or a half-configured package), dnf or yum (two versions of a package
|
||||
in the rpm database, a transaction that never ended), apk (a package marked with broken files
|
||||
or a broken script) or opkg (a package left `unpacked`), with `package_manager` naming which,
|
||||
and how full `/`, `/boot` and `/var` are (`df -Pk`,
|
||||
each filesystem once, in bytes; how full is too full is the caller's decision). `package_updates` holds the shared apt and dnf parsers: apt's suites become
|
||||
an update's `origin`, a `-security` suite makes it a security update, and dnf's security
|
||||
advisories do the same.
|
||||
|
||||
`ListeningSocketsMixin` (`get_listening_sockets`) is mixed in the same way: every listening
|
||||
TCP and bound UDP socket from `ss -lntup`, with the systemd service or container behind it
|
||||
from `/proc/<pid>/cgroup`, in one round trip. A driver supplies
|
||||
`_run_listening_sockets_command(command, privileged=)`; the command arrives as one `sh -c`
|
||||
argument, so a `sudo -n` prefix covers all of it. Without root `ss` names only the login
|
||||
user's processes, and the reading says so (`attributed: false`) instead of failing. A host
|
||||
without `ss` is read with `netstat -lntup` (OpenWrt's busybox, old net-tools); on OpenWrt the
|
||||
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
|
||||
anything under `/var/log`) with size and last write from `stat -L` on the descriptor, and the
|
||||
engine's own file of a container's output (`/var/lib/docker/containers/<id>/…`) as that
|
||||
container's stream. Each file names the service or container of its first writer from
|
||||
`/proc/<pid>/cgroup`; a file a container writes carries the container's own path. journald's
|
||||
store, deleted files and a database's write-ahead log (LevelDB's `000004.log`) are left out; a
|
||||
host whose `find` cannot list open files (busybox) raises `LogSourcesUnavailable`. A
|
||||
driver supplies `_run_log_sources_command(command, privileged=)`; without root only the login
|
||||
user's processes show their files, and the reading says so (`attributed: false`).
|
||||
The same round trip reads where the logs go beyond the host (`forwarding`,
|
||||
`napalm_device_types.log_forwarding`): whether rsyslog runs, its forwarding rules (`@`, `@@`,
|
||||
`:omrelp:`, `action(type="omfwd"|"omrelp")`, each *complete* only for `*.*` with no condition
|
||||
around it), the files it reads in (`imfile`), and whether the journal reaches it (`imjournal`,
|
||||
or `imuxsock` with journald's `ForwardToSyslog`, the distribution's commented default counting).
|
||||
|
||||
LLDP neighbours are rows: `LldpNeighborRow` is one neighbour as its local port heard it
|
||||
(chassis and port id with their type, name, description, management addresses,
|
||||
capabilities in NAPALM's names), and `lldp_neighbors(rows)` / `lldp_neighbors_detail(rows,
|
||||
interface)` are NAPALM's two getters projected from them, a port with two neighbours
|
||||
keeping both; a neighbour named by its chassis MAC carries it as `mac` (lower case). A driver for a host that runs lldpd sends `LLDPCTL_KEYVALUE_COMMAND` and
|
||||
hands its output to `parse_lldpctl_keyvalue`: one row per neighbour block, an interface
|
||||
name with dots (`eth0.1`) kept whole, ids read under the type lldpd prints them with
|
||||
(`chassis.mac`, `port.local`, ...). When lldpctl fails (lldpd not running, no `lldpctl`)
|
||||
the parse raises instead of reading as no neighbours.
|
||||
|
||||
`HostFirewallMixin` (`get_host_firewall`) reads a Linux host's own netfilter rules the same
|
||||
way: `nft -j list ruleset`, with the tables iptables-nft manages taken from `iptables-save`
|
||||
instead, because nft shows their extensions (`-m conntrack`, `-m set`) only as an opaque `xt`.
|
||||
A legacy iptables is a ruleset of its own and is kept beside nft's. Every chain says its family,
|
||||
table, hook, priority and policy; every rule is a list of matches (`iifname`, `saddr`, `dport`,
|
||||
`ct_state`, ...) and a verdict. A condition it does not model is an `unknown` match with its
|
||||
text, never left out. A driver supplies `_run_host_firewall_command(command, privileged=)`; both
|
||||
tools need root, so a host where neither could be read raises `HostFirewallUnavailable` rather
|
||||
than reading as one without rules. Whether the rules keep a service unreachable is the
|
||||
consumer's call.
|
||||
|
||||
`VirtualIpsMixin` (`get_virtual_ips`) reads the addresses a host's HA configuration lets
|
||||
float between machines: vip-manager (5.x's `--config` YAML, 1.x's `-ip=${VIP_IP}` resolved
|
||||
through the unit's environment) and keepalived (`virtual_ipaddress` of every
|
||||
`vrrp_instance`, `include` followed four levels deep). It reports what is *declared*, not
|
||||
what the host holds right now -- that is in its interface addresses. The same files hold
|
||||
the etcd password and `auth_pass`, so an awk program filters **on the host** and prints
|
||||
allowlisted fields only; a secret never reaches the caller. Root first, then without it.
|
||||
A mechanism it could not read completely is `None` ("did not look"), a host without it
|
||||
`[]`. The command is about 4 kB, so a driver sends it on an exec channel
|
||||
(`_run_virtual_ips_command(command, privileged=)`), not typed into a shell.
|
||||
|
||||
`ServiceClustersMixin` (`get_service_clusters`) reads the configuration that proves two
|
||||
hosts run one service together -- not merely that they answer at one address: Patroni
|
||||
(`scope`, `name` and `restapi.connect_address` from its YAML, then the members and roles
|
||||
its REST API's `/cluster` lists from the DCS), adguardhome-sync (`ORIGIN_URL` and
|
||||
`REPLICA*_URL` of its container: the origin pushes to each replica) and BunkerWeb (a
|
||||
worker's `API_WHITELIST_IP` names the manager it takes its configuration from, a manager's
|
||||
`BUNKERWEB_INSTANCES` its workers). Each member carries its role as the mechanism words it
|
||||
and the index of the member it takes its configuration from (`config_from`). The same
|
||||
configuration holds the superuser password, the sync's logins and BunkerWeb's database URI,
|
||||
so awk programs filter **on the host**: allowlisted fields only, a URL without its
|
||||
`user:password@`, and the DCS endpoints stay on the host. Root first (Patroni's YAML is the
|
||||
postgres user's), then without it. `None` per mechanism is "did not look", `[]` "has none".
|
||||
The container engine is asked through `_container_engine_binary` where the driver has one.
|
||||
A driver sends the command on an exec channel (`_run_service_clusters_command(command,
|
||||
privileged=)`).
|
||||
|
||||
`get_dhcp_ha` (declared on `DhcpServerMixin`, optional) is what a DHCP server's own HA
|
||||
configuration says: whether HA is on, which peer this server is, each peer's name, role --
|
||||
as the server words it, not a shared vocabulary -- and, where the server has one, the URL
|
||||
its HA listener answers on. It is configuration, not state: whether the pair is in hot
|
||||
standby right now is not in it. `ConfigSyncMixin` (`get_config_sync`) is where a host
|
||||
pushes its configuration (`peer`, None for no one) and for which services, by the names
|
||||
`get_services` reports; sync items the driver has no service name for stay visible under
|
||||
`unmapped`. A driver mixes it in -- no role promises it. Both getters raise when they could
|
||||
not read; neither answers "off" for "could not ask". What the facts mean for a pair (hot
|
||||
standby, which side to write to) is the caller's to work out.
|
||||
|
||||
A firewall's CARP addresses are a third mechanism, `carp`: a firewall driver reads them from
|
||||
its own API and reports them under the reading's `carp` key (`vip_manager` and `keepalived`
|
||||
then None). What a CARP state means is protocol knowledge and stays in that driver. The
|
||||
contract only carries the result: unlike the other two, a CARP entry says who holds the
|
||||
address (`holds`), because a firewall's interface list need not show it. `holds` None
|
||||
leaves the holder to the interfaces.
|
||||
|
||||
`SystemIdentityMixin` (`get_system_identity`) reads a host's SMBIOS identity -- system UUID,
|
||||
product serial and board serial from `/sys/class/dmi/id` -- which is what ties a server to
|
||||
its BMC (`ManagementControllerDriver.get_hardware_inventory` reports the same values from
|
||||
the other side). Vendor placeholders (`0123456789` on Supermicro boards, `To be filled by
|
||||
O.E.M.`, `Default string`, all-zero or the common `03000200-…-000700080009` UUID) read as
|
||||
empty: matching on them would join unrelated machines. `is_placeholder_identity` is the
|
||||
same filter for a BMC driver's side. `product_uuid` and `product_serial` are root's, so a
|
||||
driver supplies `_run_system_identity_command(command, privileged=)`.
|
||||
The same round trip reads the host's system firmware (BIOS or UEFI): `bios_vendor`,
|
||||
`bios_version` and `bios_date` (`YYYY-MM-DD`, from sysfs's `MM/DD/YYYY`). Only the vendors'
|
||||
text defaults read as empty there; a short version such as `1` is a version.
|
||||
|
||||
`OpenSshServerMixin` (`harden_ssh_server`, `get_ssh_server_algorithms`) takes algorithms
|
||||
out of what an OpenSSH server offers -- the ones ssh-audit flags. It reads the lists sshd
|
||||
really uses (`sshd -T`), takes out what was asked and writes the rest to
|
||||
`/etc/ssh/sshd_config.d/00-netork-ssh-hardening.conf`; only where sshd_config has no such
|
||||
`Include` is sshd_config itself rewritten, after a copy. It never removes the last algorithm
|
||||
of a class, nor -- given the managing client's lists -- the last one that client speaks.
|
||||
`sshd -t` must accept the result and `sshd -T` must show it; after the reload the caller's
|
||||
`verify` opens a new session, and if that fails the still-open one puts the old state back.
|
||||
A driver mixes it in and supplies `run_command`; a platform that regenerates sshd_config
|
||||
itself (an appliance with its own database) must not, or opts out with
|
||||
`harden_ssh_server = None`.
|
||||
|
||||
`SshServerAuthMixin` (`get_ssh_server_auth`) says how an OpenSSH server lets people log in:
|
||||
password, keyboard-interactive, public key, host-based and GSSAPI authentication on or off,
|
||||
`AuthenticationMethods` as lists of methods (empty for `any`), `PermitRootLogin` and
|
||||
`UsePAM` (None where sshd has no PAM), from `sshd -T` as root -- the same fixed command the
|
||||
hardening reads. With PAM on, it also names the modules of sshd's PAM `auth` stack
|
||||
with each control and its arguments, read from `/etc/pam.d` in one listing as the
|
||||
login user and followed through `@include`, `include` and `substack`. Which of them is a
|
||||
second factor is the consumer's call. `Match` blocks are not read. `OpenSshServerMixin`
|
||||
carries it; a driver can also mix it in alone and supply `run_command`.
|
||||
|
||||
`SudoHistoryMixin` (`get_history_sudo_lines`, `remove_history_sudo_lines`) deals with what
|
||||
a driver left behind when it typed `echo '<password>' | sudo -S -p "" …` into an interactive
|
||||
shell: that line, password and all, in the login user's shell history, and files its partial
|
||||
sudo wrote as the login user. The driver names the marker its lines carry
|
||||
(`SUDO_HISTORY_MARKER`) and those files (`SUDO_ROOT_FILES`). The getter counts the lines per
|
||||
history file with `grep -c`, as the login user; the fix deletes them with `sed -i` and
|
||||
overwrites the backup with `shred -u`, then gives the files back to root (regular files the
|
||||
login user owns, never a symbolic link). The password is never read, sent or written. A
|
||||
driver mixes it in and supplies `run_command`.
|
||||
|
||||
**Update readers raise when they cannot read.** `get_available_updates` returns an empty
|
||||
list only when nothing is pending; netOrk keeps "pending since" per package, and an empty
|
||||
list for "don't know" would reset it.
|
||||
|
||||
`SystemdServicesMixin` (`get_services`, `manage_service`) is mixed in the same way, by
|
||||
the drivers whose host runs systemd. Listing the services, checking a unit name and
|
||||
reading an action's exit status are the same on every such host, so they are concrete
|
||||
here, and a driver supplies only `_run_service_command(command, *, privileged, timeout)`
|
||||
— how a command reaches its host and how it gains root there. The listing is one round
|
||||
trip (`list-unit-files` plus one `systemctl show` over every loaded unit) instead of an
|
||||
`is-enabled` and a `show` per unit. A host without systemd raises `SystemdUnavailable`,
|
||||
a `NotImplementedError`, so a driver can fall back to another init system.
|
||||
|
||||
`ScheduledJobsMixin` (`get_scheduled_jobs`, `manage_scheduled_job`, `put_scheduled_job`,
|
||||
`delete_scheduled_job`) is what a host runs on its own schedule — cron lines, run-parts
|
||||
scripts, anacron, systemd timers, `periodic`, a platform's own jobs, Windows tasks — as one
|
||||
shape, `ScheduledJobDict`. Every job says who owns its definition (`managed_by`: package,
|
||||
admin, platform, application) and what the driver can do to it (`actions`): every job a
|
||||
driver can switch takes `enable`, `disable` and `run`; only a job an application wrote
|
||||
through `put_scheduled_job` takes `edit` and `delete`. Every write names the `digest` the
|
||||
caller saw and raises `ScheduledJobChanged` when the host's definition is no longer that.
|
||||
`PosixScheduledJobsMixin` implements it over `run_command`: one framed report as root,
|
||||
a cron line switched off behind `#napalm-disabled: `, a timer by `systemctl`, an
|
||||
application's job as a timer where systemd runs, else in `/etc/cron.d` or the user's
|
||||
crontab. A driver sets the paths its host keeps jobs in. `napalm_device_types.cron` parses
|
||||
cron expressions, gives their next runs and writes them as `OnCalendar` lines.
|
||||
|
||||
`TimeSyncMixin` (`get_time_sync`, `configure_time_sync`) is how a device keeps its clock:
|
||||
the NTP servers it is configured with, in its order, its time zone as an IANA name, whether
|
||||
it is synchronised now and which client does it (`TimeSyncDict`). The servers it got by
|
||||
DHCP (option 42) and uses are apart, in `dhcp_ntp_servers` (`[]` for none, left out where
|
||||
the driver cannot tell): DHCP counts, a device that gets the site's time giver that way is
|
||||
aligned. `get_time_sync` is declared only; `configure_time_sync(ntp_servers=None,
|
||||
timezone=None)` is a fix template -- `None` leaves a value alone, the device ends up
|
||||
configured with exactly the servers given, in that order, its DHCP-provided servers left
|
||||
alone, and a `verify` step reads it back. A zone that is not in the IANA database, a
|
||||
malformed server, an empty list or a value outside the driver's `time_sync_writes` is
|
||||
refused before anything is written. A driver states in `time_sync_writes` which of
|
||||
`ntp_servers` and `timezone` it can write (a BMC that runs on UTC only: `ntp_servers`).
|
||||
`napalm_device_types.posix_tz` turns an IANA name into the POSIX rule libc wants in `TZ`
|
||||
(OpenWrt) and that rule into a UTC offset and summer-time transitions (a switch), from the
|
||||
`tzdata` package. `PosixTimeSyncMixin` implements it over `run_command`: one reading as the
|
||||
login user (`timedatectl show`, the active client: chrony's configuration and `chronyc -n
|
||||
sources`, `timedatectl show-timesync`, `ntp.conf`, OpenNTPD's `ntpd.conf`); the zone by
|
||||
`timedatectl set-timezone`; chrony's servers in a file of their own --
|
||||
`/etc/chrony/sources.d/netork.sources` where chrony reads that directory, else a `confdir`
|
||||
or an included `/etc/chrony.d/netork.conf` -- with every other `server`, `pool` and `peer`
|
||||
line commented out behind `#napalm-time-sync: `, then `chronyc reload sources` or a
|
||||
restart; systemd-timesyncd's in `/etc/systemd/timesyncd.conf.d/netork.conf` (`NTP=` reset,
|
||||
`FallbackNTP=` emptied), then a restart. What DHCP brings is read apart and kept: chrony's
|
||||
DHCP `sourcedir` (`CHRONY_DHCP_DIRS`, `/run/chrony-dhcp`) is never commented out -- one
|
||||
that 4.35.0 commented out comes back on the next write -- and systemd-timesyncd's
|
||||
`LinkNTPServers` stay. ntpd and OpenNTPD are read, not written; what DHCP gives them is
|
||||
unknown.
|
||||
|
||||
`ConfigRevisionsMixin` (`get_config_revisions`, `get_config_revision`,
|
||||
`revert_config_revision`) is a device's own configuration history: a copy of the
|
||||
configuration for every save, which the device can go back to. An application restores a
|
||||
configuration there by reverting to the revision that holds it -- on OPNsense the only way,
|
||||
since its API takes no uploaded config.xml (NetOrk/netork#2511). Listing (newest first, the
|
||||
first in place now: id, UTC time, description, user, size as `ConfigRevisionDict`) and
|
||||
reading one revision are declared only. `revert_config_revision(revision_id)` is a
|
||||
template: it refuses an id that is not in the history (`UnknownConfigRevision`, a
|
||||
`ValueError`) before anything changes, reads the revision -- before the revert, which may
|
||||
rotate it out -- lets the driver revert (`_revert_to_config_revision`), and checks that the
|
||||
newest revision afterwards holds the revision's configuration (`ConfigRevertFailed`
|
||||
otherwise: a device may say it reverted when it did not). It returns that newest revision.
|
||||
`config_revision_content(text)` is what of a revision is its configuration; a driver whose
|
||||
device stamps every save (who, when) strips the stamp there, and an application that looks
|
||||
for the revision holding a configuration compares through it too. A driver that can list
|
||||
but not revert sets `revert_config_revision = None`.
|
||||
|
||||
### Access channels: why there is no container model here
|
||||
|
||||
`CommandChannelMixin` declares a driver's public channel to its host:
|
||||
- `run_command(command, *, privileged=False, timeout=60, stdin=None)` returns a `CommandResult(stdout, stderr, exit_code)`;
|
||||
- `open_stream(command, *, privileged=False)` returns a `ByteStream` to the command's stdin and stdout.
|
||||
|
||||
The mixin sits in `DeviceTypeDriver` and only declares, so `hasattr(driver, "run_command")` is true exactly where a driver implements it. For SSH drivers, `channel.run_on_transport` and `channel.open_stream_on_transport` are the implementation over a paramiko exec channel: no PTY, stderr kept apart, a real exit code. How a command gains root stays with the driver.
|
||||
|
||||
**`ContainerEngineMixin` is deliberately different from `SystemdServicesMixin`.** The systemd mixin owns its command and its parse; this one owns neither.
|
||||
- `container_engines()` says which engines the host offers (`[{"engine": "docker", "api": "docker-engine"}, {"engine": "podman", "api": "podman-libpod"}]`). An engine is listed when its CLI answers `--version` with its own name; podman-docker's `docker` says it is podman and is left out.
|
||||
- `open_container_engine(engine)` returns a `ContainerEngineConnection`:
|
||||
- `open_api()` is a stream to the engine's API (`docker system dial-stdio`, `podman system dial-stdio`);
|
||||
- `run_cli(args)` and `stream_cli(args)` run the engine's CLI with arguments the caller chooses. With `privileged=True` the driver runs it the way `run_command` gains root, for an engine that refuses the login user.
|
||||
- **Podman is reached as root** (`ROOT_ENGINES`, `connection.privileged`): the host's rootful Podman, the engine of the system's containers and of Quadlet's units, whose API `podman.socket` serves. A login user's rootless containers are that user's own and invisible to others. `podman system dial-stdio` exists from Podman 4.0 on and needs the socket listening (`systemctl enable --now podman.socket`) (NetOrk/netork#818).
|
||||
- The driver decides only *how* the engine is reached. Its hook `_container_engine_binary(engine)` returns, for QNAP, the Container Station path, and the caller never sees it.
|
||||
|
||||
**What runs on the engine, and what to do with it, is netOrk's** (NetOrk/netork#765): the container model, the Engine API requests, compose, updates. Above the connection everything is specific to the service, so this package abstracts the connection and nothing more.
|
||||
|
||||
A driver mixes `ContainerEngineMixin` in itself; `OSDriver` does not carry it. A Windows host is an OS driver too, and has no `dial-stdio` to offer over WinRM.
|
||||
|
||||
**Never half-close early.** `ByteStream.write` does not close anything; only `close_write` does. `dial-stdio` hands the daemon a half-close as "client gone", and the daemon then answers an unfinished request with HTTP 499.
|
||||
|
||||
A function class may use the **template form** — public method concrete, the
|
||||
device-specific part a `_hook` declared under `if TYPE_CHECKING` — *when the base
|
||||
genuinely does work* on the result: normalising, sorting, validating, or orchestrating
|
||||
several hooks. `ConfigLifecycleMixin.compare_config` over `_get_running_config` is the
|
||||
model. Where the base would only pass the call through, declare the method directly;
|
||||
two names for one pass-through is ceremony, not design.
|
||||
|
||||
NAPALM's own getters (`get_facts`, `get_interfaces`, `ping`, `get_config`) are never
|
||||
wrapped in a template — they belong to NAPALM, and code outside this repo relies on
|
||||
their contract.
|
||||
|
||||
### SSH host keys: trust on first use
|
||||
|
||||
A driver that accepts any host key logs in with the device's credentials at whatever
|
||||
answers on the device's address (NetOrk/netork#1167). The store of trusted keys is the
|
||||
caller's; `ssh_host_keys.HostKeyCheck` is how every SSH driver verifies against it:
|
||||
|
||||
- **In:** `optional_args["ssh_host_keys"]` = `{"22": {"key_type": "ssh-ed25519", "key": "<base64>"}}`,
|
||||
by port. The driver takes the key for the port it connects to. With one, any other key is
|
||||
refused *before* authentication and the connection raises `SshHostKeyMismatch` (a
|
||||
`ConnectionException`). Without one, the first key is accepted.
|
||||
- **Out:** `optional_args["ssh_host_key_observer"]`, a callable, gets one dict per
|
||||
connection: `{"host", "port", "seen": {"key_type", "key", "fingerprint"}, "expected", "accepted"}`.
|
||||
`accepted` is False only for a refused key. A failing observer is logged, never raised.
|
||||
- **paramiko:** `HostKeyCheck(optional_args, host, port).connect(client, **connect_kwargs)`.
|
||||
- **netmiko:** `with check.netmiko(self.netmiko_optional_args) as kwargs: ConnectHandler(..., **kwargs)`,
|
||||
then `check.observe(conn.remote_conn_pre.get_transport())`. The known key reaches netmiko as a
|
||||
`known_hosts` file that exists only inside the block, with `ssh_strict=True`.
|
||||
|
||||
A caller that passes neither key gets first use on every connection, as before; a driver
|
||||
that ignores both still connects. Old and new versions on either side keep working.
|
||||
|
||||
### TLS certificates: trust on first use
|
||||
|
||||
The same for a driver's HTTPS API. Devices ship self-signed certificates, so a CA check
|
||||
fails on all of them and turning verification off trusts whatever answers;
|
||||
`tls_certificates.CertificateCheck` pins the certificate by its fingerprint instead
|
||||
(NAPALM/napalm-hpe-aruba-procurve#17). No CA is consulted.
|
||||
|
||||
- **In:** `optional_args["tls_fingerprints"]` = `{"443": "SHA256:AB:CD:…"}`, by port: the
|
||||
SHA-256 of the DER certificate as `openssl x509 -fingerprint -sha256` prints it (prefix,
|
||||
colons and case optional). With one, any other certificate is refused *before* a request
|
||||
carries credentials and the connection raises `TlsCertificateMismatch` (a
|
||||
`ConnectionException` naming both fingerprints). Without one, the first certificate is
|
||||
accepted. A driver does not fall back to another transport on a mismatch.
|
||||
- **Out:** `optional_args["tls_certificate_observer"]`, a callable, gets one dict per
|
||||
connection: `{"host", "port", "seen": {"fingerprint"}, "expected", "accepted"}`.
|
||||
- **requests:** `check = CertificateCheck(optional_args, host, port)`;
|
||||
`check.verify_server(timeout)` before the login, `check.pin(session)` so every later
|
||||
connection of the session must present that certificate, the login inside
|
||||
`with check.refusing():`, then `check.observe()`.
|
||||
|
||||
## Design principle: generic vs. device-specific logic
|
||||
|
||||
When adding behavior to a device-type base class, split it along one line: **would
|
||||
this exact logic work unchanged for a different vendor's driver of the same
|
||||
device-type, if that driver only implemented the same abstract methods?**
|
||||
|
||||
- If yes, it's generic — implement it once as a **concrete** method on the
|
||||
device-type base class (here, in this repo).
|
||||
- If no — it talks to the device itself (a specific REST endpoint, a CLI command,
|
||||
a vendor-specific payload format) — it belongs in the concrete driver as the
|
||||
implementation of an **abstract** method the base class declares.
|
||||
|
||||
Concretely: matching/comparison/reconciliation algorithms, orchestration flows, and
|
||||
generic data shapes belong here. Only the actual device communication belongs in
|
||||
`vendor/napalm-<name>`.
|
||||
|
||||
**Worked example — firewall rule diff/apply** (`FirewallRuleMixin`, in `FirewallDriver`):
|
||||
|
||||
```python
|
||||
class FirewallRuleMixin: # mixed into FirewallDriver
|
||||
# Declared only — every driver implements its own device communication.
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_firewall_rules(self) -> List[FirewallRuleDict]: ...
|
||||
def apply_firewall_rule(
|
||||
self, rule: FirewallRuleDict, *, uuid: Optional[str] = None
|
||||
) -> Dict[str, Any]: ...
|
||||
def commit_firewall_rules(self) -> Dict[str, Any]: ...
|
||||
|
||||
# Concrete — the matching/comparison/orchestration algorithm is identical
|
||||
# for every firewall vendor, so it lives here once.
|
||||
def diff_firewall_rules(
|
||||
self, desired: List[FirewallRuleDict]
|
||||
) -> (
|
||||
FirewallRuleDiffDict
|
||||
): ... # matches self.get_firewall_rules() against `desired` by description
|
||||
|
||||
def apply_firewall_ruleset(
|
||||
self, desired: List[FirewallRuleDict]
|
||||
): ... # computes the diff, calls apply_firewall_rule() per change, commits
|
||||
```
|
||||
|
||||
The same split applies to `DhcpServerMixin`: `get_dhcp_reservations`/
|
||||
`apply_dhcp_reservation`/`commit_dhcp_reservations` are abstract (Kea REST on
|
||||
OPNsense, dnsmasq/odhcpd UCI on OpenWrt), while `diff_dhcp_reservations` and
|
||||
`apply_dhcp_reservationset` are concrete — matching by normalised MAC and the
|
||||
apply-then-commit orchestration are identical for every DHCP server. The apply writes
|
||||
its changes so an address is released before another reservation takes it (an update
|
||||
that frees an address first, adds last); a swap of addresses has no such order and is
|
||||
reported as one where the server refuses it.
|
||||
|
||||
A new driver (FortiGate, pfSense, …) gets `diff_firewall_rules`/
|
||||
`apply_firewall_ruleset` for free the moment it implements the three abstract
|
||||
methods — it never needs to reimplement the reconciliation logic itself.
|
||||
|
||||
**Second worked example — ping sweeps** (`PingSweepMixin`, mixed into
|
||||
`DeviceTypeDriver`, so *every* device-type driver has it):
|
||||
|
||||
```python
|
||||
class PingSweepMixin:
|
||||
# Concrete — the loop, the reply parsing, the target cap and the progress
|
||||
# reporting are the same for every device that can ping at all.
|
||||
def ping_sweep(self, destinations, *, count=1, timeout=1, …) -> PingSweepResultDict:
|
||||
... # calls NAPALM's standard ping() once per destination
|
||||
```
|
||||
|
||||
A driver becomes a usable sweep source the moment it implements NAPALM's
|
||||
`ping()` — nothing else is required, and `driver_supports_ping(cls)` reports
|
||||
whether it did (introspection, not a hand-maintained list). A driver whose
|
||||
device offers something genuinely faster overrides `ping_sweep` and keeps the
|
||||
return shape: `napalm-opnsense` starts a batch of ping jobs over the
|
||||
diagnostics API, waits once for all of them, and reads every result with a
|
||||
single request — a per-host loop would be unusable there.
|
||||
|
||||
This mirrors a similar split already documented on the consumer side, in NetOrk's
|
||||
`docs/ARCHITECTURE.md` ("Device Warnings — Trennung von Erkennung und
|
||||
Präsentation"): drivers return raw signals, the higher layer gives them meaning.
|
||||
Same shape of separation, different axis — device-specific vs. generic here,
|
||||
detection vs. presentation there.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install napalm-device-types
|
||||
```
|
||||
|
||||
Requires Python ≥ 3.9 and NAPALM ≥ 4.0.
|
||||
Requires Python ≥ 3.12 (tested up to 3.13) and NAPALM ≥ 4.0.
|
||||
|
||||
## Available base classes
|
||||
|
||||
@@ -40,6 +608,39 @@ Requires Python ≥ 3.9 and NAPALM ≥ 4.0.
|
||||
| `HypervisorDriver` | Hypervisors & virtualisation platforms | Proxmox VE, VMware ESXi, KVM/libvirt |
|
||||
| `OSDriver` | General-purpose operating systems | Linux, BSD, macOS |
|
||||
| `StorageDriver` | Storage appliances & NAS/SAN | TrueNAS, Synology DSM, QNAP QTS |
|
||||
| `ResidentialGatewayDriver` | Router + firewall + AP in one box | OpenWrt, FritzBox |
|
||||
| `PhoneDriver` | IP telephony endpoints | Yealink |
|
||||
| `MediaDriver` | Speakers, streamers, media renderers | Sonos, Chromecast |
|
||||
| `ManagementControllerDriver` | Server baseboard management controllers | Supermicro BMC, Dell iDRAC, HPE iLO, Lenovo XCC |
|
||||
| `BackupServerDriver` | Backup servers: datastores, backup groups, GC/verify/prune/sync/tape jobs | Proxmox Backup Server |
|
||||
|
||||
Mixins that come with the classes above: `PingSweepMixin` (subnet sweeps, in
|
||||
every driver through `DeviceTypeDriver`) and `DhcpServerMixin` (static DHCP
|
||||
reservations — mixed into `FirewallDriver` and `ResidentialGatewayDriver`,
|
||||
since both commonly run the DHCP server for their networks).
|
||||
`ConfigLifecycleMixin` (config load/compare/commit/rollback) is mixed in by a
|
||||
driver itself.
|
||||
|
||||
### Fingerprints
|
||||
|
||||
`DeviceTypeDriver` carries what discovery matches a device against: `PORT_SPECS`,
|
||||
`SNMP_OBJECT_ID_PREFIX`, `SNMP_FINGERPRINT`, `SSH_FINGERPRINT`, `HTTP_FINGERPRINT` and
|
||||
`OUI_PREFIXES`. A `FingerprintRule` is a lowercase substring with a weight; `mandatory`
|
||||
disqualifies the driver when it is missing, `negative` subtracts.
|
||||
|
||||
Discovery compares drivers by score divided by the most a driver could score. Rules that
|
||||
can never match together, such as one vendor's landing page or another's, share a
|
||||
`group`: only the strongest rule of a group counts towards that maximum
|
||||
(`rules_max_weight`). Without it, a driver that recognises three vendors' pages would
|
||||
score a third as well as one that recognises a single page:
|
||||
|
||||
```python
|
||||
HTTP_FINGERPRINT = [
|
||||
FingerprintRule("aten international", 6.0, group="landing_page"), # Supermicro
|
||||
FingerprintRule("idrac", 6.0, group="landing_page"),
|
||||
FingerprintRule("integrated lights-out", 6.0, group="landing_page"), # HPE iLO
|
||||
]
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -48,8 +649,8 @@ Requires Python ≥ 3.9 and NAPALM ≥ 4.0.
|
||||
```python
|
||||
from napalm_device_types import AccessPointDriver
|
||||
|
||||
class OpenWrtDriver(AccessPointDriver):
|
||||
|
||||
class OpenWrtDriver(AccessPointDriver):
|
||||
def get_wireless_clients(self):
|
||||
# return List[WirelessClientDict]
|
||||
...
|
||||
@@ -64,8 +665,8 @@ class OpenWrtDriver(AccessPointDriver):
|
||||
```python
|
||||
from napalm_device_types import SwitchDriver
|
||||
|
||||
class CiscoIOSDriver(SwitchDriver):
|
||||
|
||||
class CiscoIOSDriver(SwitchDriver):
|
||||
def get_spanning_tree(self):
|
||||
# return Dict[str, SpanningTreeDict]
|
||||
...
|
||||
@@ -80,8 +681,8 @@ class CiscoIOSDriver(SwitchDriver):
|
||||
```python
|
||||
from napalm_device_types import FirewallDriver
|
||||
|
||||
class PfSenseDriver(FirewallDriver):
|
||||
|
||||
class PfSenseDriver(FirewallDriver):
|
||||
def get_nat_translations(self):
|
||||
# return List[NATTranslationDict]
|
||||
...
|
||||
@@ -89,6 +690,11 @@ class PfSenseDriver(FirewallDriver):
|
||||
def get_vpn_tunnels(self):
|
||||
# return Dict[str, VPNTunnelDict]
|
||||
...
|
||||
|
||||
def get_port_forwards(self):
|
||||
# return List[PortForwardDict] — forwards from the WAN only, never a
|
||||
# redirect between internal networks (shared with home gateways)
|
||||
...
|
||||
```
|
||||
|
||||
### Hypervisor
|
||||
@@ -96,23 +702,49 @@ class PfSenseDriver(FirewallDriver):
|
||||
```python
|
||||
from napalm_device_types import HypervisorDriver
|
||||
|
||||
class ProxmoxDriver(HypervisorDriver):
|
||||
|
||||
class ProxmoxDriver(HypervisorDriver):
|
||||
def get_vms(self):
|
||||
# return List[VMDict]
|
||||
...
|
||||
|
||||
def snapshot_create(self, name, snapshot, description="", include_memory=False):
|
||||
def create_vm_snapshot(self, name, snapshot, description="", include_memory=False): ...
|
||||
|
||||
def get_network_targets(self):
|
||||
# return List[NetworkTargetDict]: bridges and vnets a new VM's NIC may
|
||||
# attach to; a bridge may name its physical NICs in `uplinks`, one group
|
||||
# per way out: [["eno1", "eno2"]] for a bond, [["eno1"]] for a single NIC,
|
||||
# no internal or VLAN ports -- leave the key out when they cannot be
|
||||
# determined
|
||||
...
|
||||
|
||||
def get_vm_cpu_types(self):
|
||||
# optional — return List[VMCpuTypeDict]: the CPU models a new VM may get
|
||||
# on this node, each with its cpuinfo flags and whether the node can run
|
||||
# it; the name goes to create_vm_from_cloud_init(cpu_type=...)
|
||||
...
|
||||
```
|
||||
|
||||
A hypervisor that provisions VMs from cloud images declares, per guest OS,
|
||||
the agent cloud-init installs so the hypervisor can read the new VM's IP:
|
||||
`GUEST_AGENTS = {guest_os: (packages, runcmd)}`. Its keys are the guests the
|
||||
driver can provision, and `create_vm_from_cloud_init(guest_os=...)` refuses
|
||||
any other. A QEMU-based driver takes `provisioning.QEMU_GUEST_AGENTS`
|
||||
(Linux, FreeBSD, OpenBSD). `provisioning.network_config()` writes the
|
||||
network-config v2 every cloud-init flavour reads (FreeBSD's nuageinit reads
|
||||
no other), and `provisioning.split_compression()` says how a packed image is
|
||||
unpacked; both are the same for every hypervisor. A creation that fails once
|
||||
the VM exists raises `VMProvisionIncomplete`, a `RuntimeError` that names the
|
||||
half-built VM (`vmid`, `node`) for the caller to `destroy_vm`, with the failure
|
||||
as its cause.
|
||||
|
||||
### OS / Linux
|
||||
|
||||
```python
|
||||
from napalm_device_types import OSDriver
|
||||
|
||||
class LinuxDriver(OSDriver):
|
||||
|
||||
class LinuxDriver(OSDriver):
|
||||
def get_packages(self):
|
||||
# return List[PackageDict]
|
||||
...
|
||||
@@ -121,17 +753,13 @@ class LinuxDriver(OSDriver):
|
||||
# return List[ServiceDict]
|
||||
...
|
||||
|
||||
def get_users(self):
|
||||
# return List[UserDict]
|
||||
def get_os_users(self):
|
||||
# return List[UserDict] -- not NAPALM's get_users, whose shape differs
|
||||
...
|
||||
|
||||
def get_processes(self):
|
||||
# return List[ProcessDict]
|
||||
...
|
||||
|
||||
def get_cron_jobs(self):
|
||||
# return List[CronJobDict]
|
||||
...
|
||||
```
|
||||
|
||||
### Storage / NAS
|
||||
@@ -139,8 +767,8 @@ class LinuxDriver(OSDriver):
|
||||
```python
|
||||
from napalm_device_types import StorageDriver
|
||||
|
||||
class TrueNASDriver(StorageDriver):
|
||||
|
||||
class TrueNASDriver(StorageDriver):
|
||||
def get_disks(self):
|
||||
# return List[PhysicalDiskDict]
|
||||
...
|
||||
@@ -166,7 +794,7 @@ from napalm_device_types.models import (
|
||||
## Development
|
||||
|
||||
```bash
|
||||
git clone https://github.com/chrismanivong/napalm-device-types.git
|
||||
git clone https://git.netork.io/NAPALM/napalm-device-types.git
|
||||
cd napalm-device-types
|
||||
pip install -e ".[dev]"
|
||||
```
|
||||
@@ -179,10 +807,15 @@ mypy napalm_device_types
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch (`git checkout -b feature/router-driver`)
|
||||
3. Implement your changes
|
||||
4. Open a Pull Request
|
||||
This package follows the
|
||||
[NAPALM driver standard](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md):
|
||||
test first, ruff and strict mypy, Conventional Commits, one pull request per change
|
||||
against `main`. CI checks what a tool can check:
|
||||
|
||||
```bash
|
||||
pip install "napalm-standard @ git+https://git.netork.io/NAPALM/driver-standard.git"
|
||||
napalm-standard check && napalm-standard ratchet
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
# Structure
|
||||
|
||||
Status: agreed plan. Nothing here is implemented yet; the migration at the end says in
|
||||
which order it will be.
|
||||
|
||||
## Principle
|
||||
|
||||
**napalm-device-types is vendor-, OS-, protocol- and product-agnostic.** It holds the
|
||||
contracts every driver implements and the generic logic that works unchanged for every
|
||||
driver of a role. It knows no shell, no paramiko, no package manager, no container CLI,
|
||||
no SNMP OID, no cloud-init and no application that uses the drivers.
|
||||
|
||||
That rules out three kinds of code that are here today:
|
||||
|
||||
- **How a kind of host is read.** Shell commands and their parsers for POSIX hosts move to
|
||||
a new package, **napalm-unix**, which napalm-linux and napalm-bsd depend on.
|
||||
- **What an application does with a device.** Polling a device over SNMP, sweeping a range
|
||||
with pings, scoring discovery evidence, choosing what a provisioned guest installs, and
|
||||
deciding what counts as a problem belong to the application, not to the drivers.
|
||||
- **Product naming.** Files, markers and messages a driver leaves on a device carry the
|
||||
driver's name or none, never the name of the application that called it.
|
||||
|
||||
```
|
||||
napalm-device-types roles, capabilities, templates, models, reconcilers <- every driver
|
||||
^
|
||||
napalm-unix POSIX host readers, SSH exec transport, privilege <- napalm-linux, napalm-bsd
|
||||
^
|
||||
napalm-linux, napalm-bsd connection, platform getters, platform steps
|
||||
|
||||
application SNMP polling, ping sweeps, discovery scoring, guest
|
||||
profiles, warnings, and the values every fix is given
|
||||
```
|
||||
|
||||
## What stays in napalm-device-types
|
||||
|
||||
| Kind | Rule | Modules |
|
||||
|---|---|---|
|
||||
| **Role** | Declares only, under `TYPE_CHECKING`. No runtime method. | `access_point`, `switch`, `firewall`, `hypervisor`, `os`, `storage`, `phone`, `media`, `residential_gateway`, `management_controller`, `backup_server` |
|
||||
| **Capability** | Declares only. | `packages`, `services`, `updates`, `nat_vpn`, `mac_acl`, `config_lifecycle`, `interface_filter`, `host_reboot` |
|
||||
| **Template** | A concrete method that runs a fixed sequence of abstract steps. A driver implements the steps, or overrides the whole method when its device does it in one go. All values come from the caller. | the fix routines below |
|
||||
| **Contract types** | Interfaces and data shapes other packages implement or fill. | `CommandChannelMixin`, `CommandResult`, `ByteStream`; the declaration of `ContainerEngineMixin`; the reader mixins' public method declarations; the SNMP profile type; `models` |
|
||||
| **Reconciler** | Concrete and vendor-neutral, without I/O of its own. | `firewall_rules` and `dhcp` diff/apply, `_matching`, `_dhcp_order`, `lag` |
|
||||
| **Introspection** | Concrete, without I/O. | `roles`; `base` (`FingerprintRule`, `PortSpec`, the fingerprint attributes) |
|
||||
| **Driver facts** | Class attributes that describe the device or how it is reached, not what an application does with it. | `USES_SSH`, `FULL_UPGRADE`, `platform`, `SNMP_HEALTH_PROFILE` |
|
||||
|
||||
### Fix routines are templates
|
||||
|
||||
A change the application wants made on a device, for example "run an SNMP agent that
|
||||
answers us", is one template per purpose. The template fixes the order of the steps; the
|
||||
driver knows how each step is done on its device; the caller supplies every value.
|
||||
|
||||
```python
|
||||
class SnmpAgentMixin:
|
||||
def configure_snmp_agent(self, settings: SnmpAgentSettingsDict) -> FixResultDict:
|
||||
steps = [
|
||||
self._install_snmp_agent,
|
||||
self._write_snmp_agent_config,
|
||||
self._enable_snmp_agent,
|
||||
self._verify_snmp_agent,
|
||||
]
|
||||
... # runs them in order, stops at the first failure
|
||||
|
||||
# declared only; napalm-unix implements them for net-snmp
|
||||
def _install_snmp_agent(self) -> FixStepDict: ...
|
||||
def _write_snmp_agent_config(self, settings: SnmpAgentSettingsDict) -> FixStepDict: ...
|
||||
def _enable_snmp_agent(self) -> FixStepDict: ...
|
||||
def _verify_snmp_agent(self, settings: SnmpAgentSettingsDict) -> FixStepDict: ...
|
||||
```
|
||||
|
||||
napalm-unix implements the four steps for net-snmp, for Linux and the BSDs alike. A REST
|
||||
driver such as OPNsense overrides `configure_snmp_agent` as a whole, because its device
|
||||
takes the whole configuration in one call. The community, the allowed sources, contact
|
||||
and location are the caller's.
|
||||
|
||||
The same shape replaces every action in today's `run_device_action`:
|
||||
|
||||
| Today | Template |
|
||||
|---|---|
|
||||
| `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)` |
|
||||
|
||||
The mixin is mixed in by the driver, or by the platform package, not by a role base. A
|
||||
driver that inherits a template it cannot run on its device, as a NAS driver built on the
|
||||
Linux driver inherits the package proxy, opts out by setting the method to `None`. So a
|
||||
caller asks `callable(getattr(driver, "configure_snmp_agent", None))`, never `hasattr`.
|
||||
|
||||
The caller verifies the result from its own side where it can; the SNMP agent is asked
|
||||
by the application's SNMP client, not by a probe the driver hand-builds.
|
||||
|
||||
### SNMP: drivers declare data, the application polls
|
||||
|
||||
The drivers do not collect over SNMP. A driver whose device answers the standard UCD-MIB
|
||||
and IF-MIB declares nothing. A driver whose device publishes the same values under
|
||||
proprietary OIDs declares them as data, in a class attribute of a type defined here:
|
||||
|
||||
```python
|
||||
class ProcurveDriver(SwitchDriver):
|
||||
SNMP_HEALTH_PROFILE: ClassVar[SnmpHealthProfile] = {
|
||||
"uptime": {"oids": ["1.3.6.1.4.1.11.2.14.11.1.2.4.1.5.1"], "format": "ticks"},
|
||||
"cpu": {"oids": ["1.3.6.1.4.1.11.2.14.11.5.1.9.6.1.0", "1.3.6.1.4.1.11.2.3.7.8.6.1.0"]},
|
||||
"memory": {"total": "...", "free": "...", "unit": "bytes"},
|
||||
}
|
||||
```
|
||||
|
||||
One OID per value is not enough for the drivers there are. The profile type has to say:
|
||||
|
||||
- **Fallbacks:** an ordered list of OIDs; the first that answers wins (ProCurve's CPU).
|
||||
- **Tables:** an OID to walk and how to fold its rows: first, average or maximum (TP-Link
|
||||
reports CPU and memory per stack unit).
|
||||
- **Text values:** a pattern that takes the number out of a string (Netgear reports CPU
|
||||
as `"5 Secs ( 3.2%)"`).
|
||||
- **Memory:** total with used or free, or a percentage only, and the unit.
|
||||
- **Uptime:** which OID, standard ones included (`sysUpTime` where a device has no
|
||||
`hrSystemUptime`), and its format.
|
||||
- **Interfaces:** a pattern of names to skip, and whether the TX-error counter counts
|
||||
drops. Today the second is `True` on every firewall, because OPNsense counts drops
|
||||
there; it becomes OPNsense's profile entry.
|
||||
|
||||
Polling, the standard OIDs, the counter arithmetic (64-bit counters first, 32-bit as the
|
||||
fallback) and the defaults are the application's.
|
||||
|
||||
### Warnings are facts
|
||||
|
||||
A driver reports facts: the proxy a host is configured with, a DSL line's SNR, the
|
||||
firmware version it runs and the one it is offered. It does not compare them with a
|
||||
setting of the application or with a threshold, and it does not name a warning.
|
||||
|
||||
The same goes for lookups a device does not make itself: what firmware a vendor
|
||||
currently publishes is the application's catalogue, not a getter.
|
||||
|
||||
### Getters read, and say when they cannot
|
||||
|
||||
- A getter changes nothing on the device. It does not start a daemon, rewrite its
|
||||
configuration or install a package on the way to an answer.
|
||||
- A read that fails raises. An empty list means "there is none", never "could not ask";
|
||||
a sync that deletes and re-adds on top of an empty answer would otherwise duplicate
|
||||
everything.
|
||||
- A write reports failure from the device's answer or exit status, never `success: True`
|
||||
by default.
|
||||
|
||||
### The application uses public methods only
|
||||
|
||||
The application never calls a driver's private methods (`_get`, `_post`,
|
||||
`_send_command`, `_action_*`). What it needs from a device becomes a declared method of
|
||||
the driver.
|
||||
|
||||
## What moves to napalm-unix
|
||||
|
||||
| Module | Knows |
|
||||
|---|---|
|
||||
| `host_status` | apt, dnf, dpkg, systemd timers, `df` |
|
||||
| `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_history` | apt's history log, `zcat`, `/etc/localtime` |
|
||||
| `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 |
|
||||
| `container_engine`: `ContainerEngineConnection`, engine probing | the Docker CLI, `system dial-stdio` |
|
||||
|
||||
It also takes what napalm-linux and napalm-bsd each carry today:
|
||||
|
||||
- **Privilege:** one `sudo -S` / `sudo -n` / root layer, including the rule that a
|
||||
privileged command never gets stdin while a sudo password is set, and one way to write a
|
||||
file as root (stage with `mktemp`, then `install`). Two copies of this have already
|
||||
drifted apart.
|
||||
- **Parsers:** `/etc/passwd` with `/etc/group`, crontab lines, `ps` with `lstart`.
|
||||
- **Fix steps:** net-snmp, the package proxy, container engine group membership.
|
||||
|
||||
The FreeBSD part of `host_status` (`freebsd-version -k` against `-r`) moves to napalm-bsd.
|
||||
|
||||
In napalm-unix every reader follows one pattern:
|
||||
|
||||
- **Shape:** `FOO_COMMAND`, `parse_foo(output)`, and `FooMixin.get_foo()`.
|
||||
- **Reaching the host:** the mixin uses `run_command(command, privileged=...)` from
|
||||
`CommandChannelMixin`. The six per-reader `_run_*` hooks, with four different signatures,
|
||||
go away.
|
||||
- **Framing:** one frame helper writes and parses the `BEGIN`/`END` markers for every reader.
|
||||
- **Errors:** one exception for "cannot read" and one for "not on this host". A read that
|
||||
fails or is cut short raises; it never reads as "nothing there".
|
||||
- **Names on the host:** temporary files, markers and drop-ins carry `napalm` or the
|
||||
driver's name. A drop-in written under an older name is still recognised and replaced.
|
||||
|
||||
Layout: `napalm_unix/{posix,linux,freebsd,openssh,transport}/`.
|
||||
|
||||
## What moves to the application
|
||||
|
||||
| Today | Why it is not a driver's |
|
||||
|---|---|
|
||||
| `health_metrics`, `_ucd_metrics` | Polling over SNMP is something the application does to a device; the driver is not even connected while it runs. |
|
||||
| `ping_sweep` | Looping over addresses, capping the targets and reporting progress is a scan. A device with a faster batch keeps it as a capability of its own. |
|
||||
| `rules_max_weight` | Scoring is how one application ranks drivers. The rules themselves stay with the driver. |
|
||||
| `provisioning` (`QEMU_GUEST_AGENTS`, cloud-init network-config, decompressors) | Which agent a guest gets and how its network is configured is a guest profile. The hypervisor driver is handed the packages and commands. |
|
||||
| `TYPE_LABEL`, `REBOOT_SETTLE_SECONDS` | A display name and a polling delay. |
|
||||
| firmware catalogues (napalm-netgear's `netgear_plus`) | What a vendor publishes is not something the device reports. |
|
||||
| `run_device_action` | Replaced by the templates above. |
|
||||
|
||||
`OSDriver.ROLE` stops defaulting to `"linux"`. Each OS driver states its own role.
|
||||
|
||||
## Rules, enforced by tests in this package
|
||||
|
||||
1. Roles and capabilities own no runtime method; a template runs only declared steps.
|
||||
2. No module imports `paramiko`, `socket`, `subprocess` or `asyncio`, and none defines a
|
||||
`*_COMMAND`.
|
||||
3. No module, string or default names an application.
|
||||
4. Role methods return TypedDicts, not `Any`.
|
||||
|
||||
Each rule is added with the step that makes it pass.
|
||||
|
||||
## Migration
|
||||
|
||||
This package cannot keep re-exports pointing at napalm-unix: the contract package would
|
||||
then depend on its implementation. So a moved name is first deprecated here and then
|
||||
removed, and nothing breaks in between.
|
||||
|
||||
| Step | Change |
|
||||
|---|---|
|
||||
| 1 | The application moves to 4.9 and the drivers that need it; napalm-bsd stops passing stdin to a privileged command while a sudo password is set. |
|
||||
| 2 | This document; the application's architecture docs and this README follow it. |
|
||||
| 3 | `SnmpHealthProfile`. The application polls on its own; the four switch and phone drivers declare their OIDs as data. `HealthMetricsMixin` is deprecated. |
|
||||
| 4 | The fix templates. napalm-linux and napalm-bsd implement the steps; the application calls the templates with its values. `run_device_action` is deprecated. The other drivers follow, one issue each. |
|
||||
| 5 | Ping sweep, scoring, provisioning, `TYPE_LABEL` and `REBOOT_SETTLE_SECONDS` move to the application and are deprecated here. Drivers report facts instead of warnings. |
|
||||
| 6 | napalm-unix, with the moved code and its tests, the unified hooks and the frame helper. napalm-linux and napalm-bsd import from it; the moved names are deprecated here. |
|
||||
| 7 | 5.0 removes everything deprecated. It also splits `models.py` by area, types the remaining `Dict[str, Any]` role returns, declares what drivers already offer undeclared (`get_networks`, `search_packages`, `first_boot_pending`, the base-system update entry), and makes `install_package` declare the result drivers return. |
|
||||
| 8 | The README shrinks to the concepts; the reader details move with the readers. |
|
||||
|
||||
## Proposals this replaces
|
||||
|
||||
Several open issues proposed adding shared driver code here. Under this structure:
|
||||
|
||||
| Issue | Goes to |
|
||||
|---|---|
|
||||
| #8 netmiko session | not here: a CLI-driver helper package, or left in the drivers |
|
||||
| #9 config mode for CLI switches | not here: a CLI-driver helper package, or left in the drivers |
|
||||
| #10 LLDP rows | the projection of rows into NAPALM's two shapes stays here; the `lldpctl` parser goes to napalm-unix |
|
||||
| #11 CLI text helpers | not here; the natural port sort, which `lag` already has, may become public |
|
||||
| #12 ping | the reply builder stays here; the BusyBox and iputils parser goes to napalm-unix |
|
||||
| #13 Linux userland | napalm-unix; the snmpd part becomes the SNMP template's steps |
|
||||
| #14 `run_device_action` | replaced by the fix templates |
|
||||
| #22 hooks onto `run_command` | step 6 |
|
||||
+644
-12
@@ -4,52 +4,684 @@ napalm-device-types
|
||||
|
||||
Abstract device-type base classes for NAPALM drivers.
|
||||
|
||||
Instead of inheriting directly from ``napalm.base.NetworkDriver``, a driver
|
||||
can inherit from one of the device-type classes defined here to gain
|
||||
type-specific abstract methods and a clearer contract::
|
||||
A driver inherits one base per role its device fills, and **the order of those
|
||||
bases is the ranking** -- the first one is what netOrk shows as the device's
|
||||
class::
|
||||
|
||||
from napalm_device_types import AccessPointDriver
|
||||
from napalm_device_types import StorageDriver, HypervisorDriver
|
||||
|
||||
class OpenWrtDriver(AccessPointDriver):
|
||||
...
|
||||
class QnapQtsDriver(StorageDriver, HypervisorDriver, LinuxDriver):
|
||||
... # a NAS that also runs VMs on a Linux userland
|
||||
|
||||
Available base classes:
|
||||
That works because a role base *declares* its methods (under ``if
|
||||
TYPE_CHECKING``) and implements none of them. Nothing exists at runtime until a
|
||||
concrete driver provides it, so no base can shadow a working implementation
|
||||
inherited from a sibling, and ``hasattr`` is a truthful answer to "can this
|
||||
driver do X".
|
||||
|
||||
Role bases -- what a device *is*:
|
||||
|
||||
* :class:`~napalm_device_types.access_point.AccessPointDriver`
|
||||
* :class:`~napalm_device_types.backup_server.BackupServerDriver`
|
||||
* :class:`~napalm_device_types.switch.SwitchDriver`
|
||||
* :class:`~napalm_device_types.firewall.FirewallDriver`
|
||||
* :class:`~napalm_device_types.hypervisor.HypervisorDriver`
|
||||
* :class:`~napalm_device_types.os.OSDriver`
|
||||
* :class:`~napalm_device_types.storage.StorageDriver`
|
||||
* :class:`~napalm_device_types.phone.PhoneDriver`
|
||||
* :class:`~napalm_device_types.media.MediaDriver`
|
||||
* :class:`~napalm_device_types.management_controller.ManagementControllerDriver`
|
||||
* :class:`~napalm_device_types.residential_gateway.ResidentialGatewayDriver`
|
||||
|
||||
Also provided:
|
||||
Function classes -- what a device *can do*. Shared behaviour lives here once
|
||||
instead of being restated on every role that happens to need it:
|
||||
|
||||
* :class:`~napalm_device_types.config_lifecycle.ConfigLifecycleMixin` --
|
||||
stand-alone mixin to reduce duplication of config lifecycle methods across
|
||||
drivers.
|
||||
* :class:`~napalm_device_types.channel.CommandChannelMixin`
|
||||
* :class:`~napalm_device_types.apt_history.AptHistoryMixin`
|
||||
* :class:`~napalm_device_types.config_lifecycle.ConfigLifecycleMixin`
|
||||
* :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.hardening.HardeningMixin`
|
||||
* :class:`~napalm_device_types.health_metrics.HealthMetricsMixin`
|
||||
* :class:`~napalm_device_types.host_status.HostStatusMixin`
|
||||
* :class:`~napalm_device_types.host_reboot.HostRebootMixin`
|
||||
* :class:`~napalm_device_types.host_shutdown.HostShutdownMixin`
|
||||
* :class:`~napalm_device_types.interface_filter.InterfaceFilterMixin`
|
||||
* :class:`~napalm_device_types.kernel.KernelFactsMixin`
|
||||
* :class:`~napalm_device_types.listening.ListeningSocketsMixin`
|
||||
* :class:`~napalm_device_types.local_accounts.LocalAccountsMixin`
|
||||
* :class:`~napalm_device_types.log_sources.LogSourcesMixin`
|
||||
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
|
||||
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
|
||||
* :class:`~napalm_device_types.nat_vpn.NatVpnMixin`
|
||||
* :class:`~napalm_device_types.packages.PackageManagementMixin`
|
||||
* :class:`~napalm_device_types.ping_sweep.PingSweepMixin`
|
||||
* :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`
|
||||
* :class:`~napalm_device_types.scheduled_jobs_posix.PosixScheduledJobsMixin`
|
||||
* :class:`~napalm_device_types.services.ServiceControlMixin`
|
||||
* :class:`~napalm_device_types.systemd.SystemdServicesMixin`
|
||||
* :class:`~napalm_device_types.time_sync.TimeSyncMixin`
|
||||
* :class:`~napalm_device_types.time_sync_posix.PosixTimeSyncMixin`
|
||||
* :class:`~napalm_device_types.updates.UpdateMixin`
|
||||
* :class:`~napalm_device_types.virtual_ips.VirtualIpsMixin`
|
||||
* :class:`~napalm_device_types.vm_stop_request.VmStopRequestMixin`
|
||||
|
||||
Introspection -- :func:`~napalm_device_types.roles.roles_of`,
|
||||
:func:`~napalm_device_types.roles.role_keys_of` and
|
||||
:func:`~napalm_device_types.roles.primary_role_of`.
|
||||
"""
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver, FingerprintRule, PortSpec
|
||||
from napalm_device_types.access_point import AccessPointDriver
|
||||
from napalm_device_types.apt_history import (
|
||||
APT_HISTORY_COMMAND,
|
||||
AptHistoryMixin,
|
||||
AptHistoryUnreadable,
|
||||
apt_history_command,
|
||||
host_zone,
|
||||
parse_apt_history,
|
||||
)
|
||||
from napalm_device_types.apt_proxy import (
|
||||
APT_PROXY_COMMAND,
|
||||
AptProxyMixin,
|
||||
https_proxy_for,
|
||||
parse_apt_fetch,
|
||||
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 (
|
||||
BACKUP_JOB_KINDS,
|
||||
BackupDatastoreDict,
|
||||
BackupGroupDict,
|
||||
BackupJobKind,
|
||||
BackupRemoteDict,
|
||||
BackupRunState,
|
||||
BackupServerJobDict,
|
||||
BackupServerRefDict,
|
||||
BackupSnapshotDict,
|
||||
BackupSnapshotRefDict,
|
||||
BackupTaskDict,
|
||||
BackupTaskStatusDict,
|
||||
BackupVerifyState,
|
||||
)
|
||||
from napalm_device_types.base import DeviceTypeDriver, FingerprintRule, PortSpec, rules_max_weight
|
||||
from napalm_device_types.channel import (
|
||||
ByteStream,
|
||||
CommandChannelMixin,
|
||||
CommandResult,
|
||||
ParamikoExecStream,
|
||||
open_stream_on_transport,
|
||||
run_on_transport,
|
||||
)
|
||||
from napalm_device_types.clusters import (
|
||||
BackupDict,
|
||||
BackupJobDict,
|
||||
ClusterDict,
|
||||
ClusterNetworkDict,
|
||||
ClusterNodeDict,
|
||||
ClusterStorageDict,
|
||||
HAResourceDict,
|
||||
)
|
||||
from napalm_device_types.config_lifecycle import ConfigLifecycleMixin
|
||||
from napalm_device_types.config_revisions import (
|
||||
ConfigRevertFailed,
|
||||
ConfigRevisionDict,
|
||||
ConfigRevisionsMixin,
|
||||
UnknownConfigRevision,
|
||||
)
|
||||
from napalm_device_types.config_sync import ConfigSyncMixin
|
||||
from napalm_device_types.container_engine import (
|
||||
ContainerEngineConnection,
|
||||
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 FirmwareOfferDict, FirmwareOfferMixin, FirmwareUpgradeMixin
|
||||
from napalm_device_types.fixes import (
|
||||
EnsurePackageMixin,
|
||||
LldpAgentMixin,
|
||||
PackageProxyMixin,
|
||||
SnmpAgentMixin,
|
||||
ZabbixAgentMixin,
|
||||
run_fix_steps,
|
||||
)
|
||||
from napalm_device_types.hardening import (
|
||||
HARDENING_COMMAND,
|
||||
HardeningDict,
|
||||
HardeningMixin,
|
||||
cpu_vulnerability_state,
|
||||
parse_hardening,
|
||||
)
|
||||
from napalm_device_types.health_metrics import HealthMetricsMixin
|
||||
from napalm_device_types.host_firewall import (
|
||||
HostFirewallMixin,
|
||||
HostFirewallUnavailable,
|
||||
parse_host_firewall,
|
||||
)
|
||||
from napalm_device_types.host_reboot import HostRebootMixin
|
||||
from napalm_device_types.host_shutdown import HostShutdownMixin
|
||||
from napalm_device_types.host_status import HOST_STATUS_COMMAND, HostStatusMixin, parse_host_status
|
||||
from napalm_device_types.hypervisor import HypervisorDriver
|
||||
from napalm_device_types.interface_filter import InterfaceFilterMixin
|
||||
from napalm_device_types.kernel import KERNEL_FACTS_COMMAND, KernelFactsMixin, parse_kernel_facts
|
||||
from napalm_device_types.lag import add_lag_interfaces
|
||||
from napalm_device_types.licenses import LicenseMixin
|
||||
from napalm_device_types.listening import (
|
||||
LISTENING_SOCKETS_COMMAND,
|
||||
ListeningSocketsMixin,
|
||||
ListeningSocketsUnavailable,
|
||||
parse_listening_sockets,
|
||||
)
|
||||
from napalm_device_types.lldp import (
|
||||
LldpNeighborDict,
|
||||
LldpNeighborRow,
|
||||
lldp_neighbors,
|
||||
lldp_neighbors_detail,
|
||||
)
|
||||
from napalm_device_types.lldpctl import LLDPCTL_KEYVALUE_COMMAND, parse_lldpctl_keyvalue
|
||||
from napalm_device_types.local_accounts import (
|
||||
LocalAccountChangeDict,
|
||||
LocalAccountDict,
|
||||
LocalAccountsMixin,
|
||||
)
|
||||
from napalm_device_types.log_forwarding import (
|
||||
FileInputDict,
|
||||
ForwardRuleDict,
|
||||
LogForwardingDict,
|
||||
parse_rsyslog,
|
||||
)
|
||||
from napalm_device_types.log_sources import (
|
||||
LOG_SOURCES_COMMAND,
|
||||
LogSourceDict,
|
||||
LogSourcesDict,
|
||||
LogSourcesMixin,
|
||||
LogSourcesUnavailable,
|
||||
parse_log_forwarding,
|
||||
parse_log_sources,
|
||||
)
|
||||
from napalm_device_types.mac_acl import MacAclMixin
|
||||
from napalm_device_types.management_controller import ManagementControllerDriver
|
||||
from napalm_device_types.media import MediaDriver
|
||||
from napalm_device_types.models import (
|
||||
POWER_ACTIONS,
|
||||
ConfigSyncDict,
|
||||
DhcpHaDict,
|
||||
DhcpHaPeerDict,
|
||||
DnsForwardDict,
|
||||
EventLogEntryDict,
|
||||
FirmwareDict,
|
||||
FixResultDict,
|
||||
FixStepDict,
|
||||
FixStepOutcomeDict,
|
||||
HardwareInventoryDict,
|
||||
HypervisorHostDict,
|
||||
LicenseDict,
|
||||
ManagementProtocolsDict,
|
||||
OspfDict,
|
||||
OspfInterfaceDict,
|
||||
PowerAction,
|
||||
PowerStateDict,
|
||||
SnmpAgentSettingsDict,
|
||||
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 (
|
||||
APT_UPGRADABLE_COMMAND,
|
||||
DNF_INSTALLED_CVES_COMMAND,
|
||||
DNF_SECURITY_COMMAND,
|
||||
parse_apt_upgradable,
|
||||
parse_dnf_installed_cves,
|
||||
parse_dnf_security,
|
||||
)
|
||||
from napalm_device_types.packages import PackageManagementMixin
|
||||
from napalm_device_types.phone import PhoneDriver
|
||||
from napalm_device_types.ping_sweep import PingSweepMixin, driver_supports_ping
|
||||
from napalm_device_types.posix_tz import (
|
||||
DstTransitionDict,
|
||||
PosixTzDict,
|
||||
UnknownTimezone,
|
||||
is_iana_zone,
|
||||
is_posix_tz,
|
||||
parse_posix_tz,
|
||||
posix_tz,
|
||||
)
|
||||
from napalm_device_types.provisioning import VMProvisionIncomplete
|
||||
from napalm_device_types.residential_gateway import ResidentialGatewayDriver
|
||||
from napalm_device_types.roles import primary_role_of, role_keys_of, roles_of
|
||||
from napalm_device_types.running_backups import (
|
||||
RUNNING_BACKUP_KINDS,
|
||||
RunningBackupDict,
|
||||
RunningBackupKind,
|
||||
RunningBackupsMixin,
|
||||
)
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobDict,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobResultDict,
|
||||
ScheduledJobsMixin,
|
||||
ScheduledJobSpecDict,
|
||||
ScheduledJobsReadingDict,
|
||||
job_digest,
|
||||
)
|
||||
from napalm_device_types.scheduled_jobs_posix import PosixScheduledJobsMixin
|
||||
from napalm_device_types.service_clusters import (
|
||||
SERVICE_CLUSTERS_COMMAND,
|
||||
ServiceClustersMixin,
|
||||
parse_service_clusters,
|
||||
service_clusters_command,
|
||||
)
|
||||
from napalm_device_types.service_packages import (
|
||||
SERVICE_PACKAGES_COMMAND,
|
||||
ServicePackagesMixin,
|
||||
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,
|
||||
SnmpMemorySpec,
|
||||
SnmpValueSpec,
|
||||
)
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
KNOWN_KEYS_ARG as SSH_HOST_KEYS_ARG,
|
||||
)
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
OBSERVER_ARG as SSH_HOST_KEY_OBSERVER_ARG,
|
||||
)
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
HostKeyCheck,
|
||||
HostKeyObservation,
|
||||
SshHostKey,
|
||||
SshHostKeyMismatch,
|
||||
)
|
||||
from napalm_device_types.ssh_server import (
|
||||
SSH_ALGORITHM_CLASSES,
|
||||
OpenSshServerMixin,
|
||||
SshHardeningPlan,
|
||||
SshHardeningResult,
|
||||
plan_ssh_hardening,
|
||||
)
|
||||
from napalm_device_types.ssh_server_auth import (
|
||||
SSHD_EFFECTIVE_COMMAND,
|
||||
PamAuthEntryDict,
|
||||
SshServerAuthDict,
|
||||
SshServerAuthMixin,
|
||||
pam_auth_stack,
|
||||
parse_sshd_auth,
|
||||
)
|
||||
from napalm_device_types.storage import StorageDriver
|
||||
from napalm_device_types.sudo_history import (
|
||||
HistoryCleanupDict,
|
||||
HistorySudoLinesDict,
|
||||
SudoHistoryCleanupDict,
|
||||
SudoHistoryMixin,
|
||||
)
|
||||
from napalm_device_types.switch import SwitchDriver
|
||||
from napalm_device_types.system_identity import (
|
||||
SYSTEM_IDENTITY_COMMAND,
|
||||
SystemIdentityMixin,
|
||||
is_placeholder_identity,
|
||||
parse_system_identity,
|
||||
)
|
||||
from napalm_device_types.systemd import (
|
||||
SYSTEMD_SERVICES_COMMAND,
|
||||
SystemdServicesMixin,
|
||||
SystemdUnavailable,
|
||||
parse_systemd_services,
|
||||
)
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
from napalm_device_types.time_sync import (
|
||||
TIME_SYNC_VALUES,
|
||||
TimeSyncDict,
|
||||
TimeSyncMixin,
|
||||
check_ntp_servers,
|
||||
)
|
||||
from napalm_device_types.time_sync_posix import PosixTimeSyncMixin, parse_time_sync
|
||||
from napalm_device_types.updates import (
|
||||
PackageIndexMissing,
|
||||
UpdateHistoryAction,
|
||||
UpdateHistoryDict,
|
||||
UpdateHistoryPackageDict,
|
||||
UpdateMixin,
|
||||
)
|
||||
from napalm_device_types.virtual_ips import (
|
||||
VIRTUAL_IPS_COMMAND,
|
||||
VirtualIpsMixin,
|
||||
parse_virtual_ips,
|
||||
)
|
||||
from napalm_device_types.vm_migration import MigrationPreflightDict
|
||||
from napalm_device_types.vm_stop_request import VmStopRequestMixin
|
||||
from napalm_device_types.zabbix_agent import (
|
||||
ZabbixAgentSettingsDict,
|
||||
check_zabbix_agent_settings,
|
||||
zabbix_agent_config,
|
||||
zabbix_repository_command,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BACKUP_JOB_KINDS",
|
||||
"BackupDatastoreDict",
|
||||
"BackupGroupDict",
|
||||
"BackupJobKind",
|
||||
"BackupRemoteDict",
|
||||
"BackupRunState",
|
||||
"BackupServerJobDict",
|
||||
"BackupServerRefDict",
|
||||
"BackupSnapshotDict",
|
||||
"BackupSnapshotRefDict",
|
||||
"BackupTaskDict",
|
||||
"BackupTaskStatusDict",
|
||||
"BackupVerifyState",
|
||||
"BackupDict",
|
||||
"BackupJobDict",
|
||||
"ClusterDict",
|
||||
"ClusterNetworkDict",
|
||||
"ClusterNodeDict",
|
||||
"ClusterStorageDict",
|
||||
"HAResourceDict",
|
||||
"MigrationPreflightDict",
|
||||
"HypervisorHostDict",
|
||||
"DnsForwardDict",
|
||||
"DnsForwardMixin",
|
||||
"FirmwareOfferDict",
|
||||
"OspfDict",
|
||||
"OspfInterfaceDict",
|
||||
"OspfMixin",
|
||||
"UpdateProgressDict",
|
||||
"UpdateHistoryAction",
|
||||
"UpdateHistoryDict",
|
||||
"UpdateHistoryPackageDict",
|
||||
"CredentialExpiryDict",
|
||||
"CredentialExpiryMixin",
|
||||
"CredentialKind",
|
||||
"FirmwareOfferMixin",
|
||||
"FirmwareUpgradeMixin",
|
||||
"LicenseDict",
|
||||
"LicenseMixin",
|
||||
"EnsurePackageMixin",
|
||||
"FixResultDict",
|
||||
"FixStepDict",
|
||||
"FixStepOutcomeDict",
|
||||
"LldpAgentMixin",
|
||||
"PackageProxyMixin",
|
||||
"APT_HISTORY_COMMAND",
|
||||
"AptHistoryMixin",
|
||||
"AptHistoryUnreadable",
|
||||
"apt_history_command",
|
||||
"host_zone",
|
||||
"parse_apt_history",
|
||||
"APT_PROXY_COMMAND",
|
||||
"AptProxyMixin",
|
||||
"https_proxy_for",
|
||||
"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",
|
||||
"ZabbixAgentMixin",
|
||||
"ZabbixAgentSettingsDict",
|
||||
"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",
|
||||
"SnmpValueSpec",
|
||||
"AccessPointDriver",
|
||||
"BackupServerDriver",
|
||||
"ByteStream",
|
||||
"CommandChannelMixin",
|
||||
"CommandResult",
|
||||
"ContainerEngineConnection",
|
||||
"ContainerEngineMixin",
|
||||
"ContainerEngineUnavailable",
|
||||
"ParamikoExecStream",
|
||||
"open_stream_on_transport",
|
||||
"run_on_transport",
|
||||
"ConfigLifecycleMixin",
|
||||
"ConfigRevisionsMixin",
|
||||
"ConfigRevisionDict",
|
||||
"ConfigRevertFailed",
|
||||
"UnknownConfigRevision",
|
||||
"ConfigSyncDict",
|
||||
"ConfigSyncMixin",
|
||||
"DhcpHaDict",
|
||||
"DhcpHaPeerDict",
|
||||
"DeviceTypeDriver",
|
||||
"DhcpApplyError",
|
||||
"DhcpServerMixin",
|
||||
"FingerprintRule",
|
||||
"rules_max_weight",
|
||||
"FirewallDriver",
|
||||
"FirewallRuleMixin",
|
||||
"HealthMetricsMixin",
|
||||
"HOST_STATUS_COMMAND",
|
||||
"HostStatusMixin",
|
||||
"HostRebootMixin",
|
||||
"HostShutdownMixin",
|
||||
"HypervisorDriver",
|
||||
"InterfaceFilterMixin",
|
||||
"MacAclMixin",
|
||||
"ManagementControllerDriver",
|
||||
"ARP_AGE_UNKNOWN",
|
||||
"POWER_ACTIONS",
|
||||
"PowerAction",
|
||||
"PowerStateDict",
|
||||
"HardwareInventoryDict",
|
||||
"EventLogEntryDict",
|
||||
"FirmwareDict",
|
||||
"ManagementProtocolsDict",
|
||||
"MediaDriver",
|
||||
"NatVpnMixin",
|
||||
"OSDriver",
|
||||
"PackageManagementMixin",
|
||||
"APT_UPGRADABLE_COMMAND",
|
||||
"DNF_INSTALLED_CVES_COMMAND",
|
||||
"DNF_SECURITY_COMMAND",
|
||||
"parse_apt_upgradable",
|
||||
"parse_dnf_installed_cves",
|
||||
"parse_dnf_security",
|
||||
"parse_host_status",
|
||||
"strip_terminal_codes",
|
||||
"KernelFactsMixin",
|
||||
"KERNEL_FACTS_COMMAND",
|
||||
"parse_kernel_facts",
|
||||
"HARDENING_COMMAND",
|
||||
"HardeningMixin",
|
||||
"HardeningDict",
|
||||
"cpu_vulnerability_state",
|
||||
"parse_hardening",
|
||||
"SERVICE_PACKAGES_COMMAND",
|
||||
"SERVICES_RESTART_COMMAND",
|
||||
"ServicesRestartMixin",
|
||||
"ServicesRestartDict",
|
||||
"RestartProcessDict",
|
||||
"parse_services_restart",
|
||||
"ServicePackagesMixin",
|
||||
"parse_service_packages",
|
||||
"LISTENING_SOCKETS_COMMAND",
|
||||
"HostFirewallMixin",
|
||||
"HostFirewallUnavailable",
|
||||
"parse_host_firewall",
|
||||
"ListeningSocketsMixin",
|
||||
"ListeningSocketsUnavailable",
|
||||
"LOG_SOURCES_COMMAND",
|
||||
"FileInputDict",
|
||||
"ForwardRuleDict",
|
||||
"LogForwardingDict",
|
||||
"parse_log_forwarding",
|
||||
"parse_rsyslog",
|
||||
"LogSourceDict",
|
||||
"LogSourcesDict",
|
||||
"LogSourcesMixin",
|
||||
"LogSourcesUnavailable",
|
||||
"parse_log_sources",
|
||||
"parse_listening_sockets",
|
||||
"LLDPCTL_KEYVALUE_COMMAND",
|
||||
"LldpNeighborDict",
|
||||
"LldpNeighborRow",
|
||||
"lldp_neighbors",
|
||||
"lldp_neighbors_detail",
|
||||
"parse_lldpctl_keyvalue",
|
||||
"LocalAccountsMixin",
|
||||
"LocalAccountDict",
|
||||
"LocalAccountChangeDict",
|
||||
"PhoneDriver",
|
||||
"PingSweepMixin",
|
||||
"PortSpec",
|
||||
"ResidentialGatewayDriver",
|
||||
"ServiceControlMixin",
|
||||
"PosixScheduledJobsMixin",
|
||||
"ScheduledJobChanged",
|
||||
"ScheduledJobDict",
|
||||
"ScheduledJobRefused",
|
||||
"ScheduledJobResultDict",
|
||||
"ScheduledJobSpecDict",
|
||||
"ScheduledJobsMixin",
|
||||
"ScheduledJobsReadingDict",
|
||||
"job_digest",
|
||||
"StorageDriver",
|
||||
"SwitchDriver",
|
||||
"SYSTEMD_SERVICES_COMMAND",
|
||||
"SystemdServicesMixin",
|
||||
"SystemdUnavailable",
|
||||
"parse_systemd_services",
|
||||
"PackageIndexMissing",
|
||||
"UpdateMixin",
|
||||
"VIRTUAL_IPS_COMMAND",
|
||||
"VirtualIpsMixin",
|
||||
"VmStopRequestMixin",
|
||||
"RUNNING_BACKUP_KINDS",
|
||||
"RunningBackupDict",
|
||||
"RunningBackupKind",
|
||||
"RunningBackupsMixin",
|
||||
"TIME_SYNC_VALUES",
|
||||
"TimeSyncDict",
|
||||
"TimeSyncMixin",
|
||||
"check_ntp_servers",
|
||||
"PosixTimeSyncMixin",
|
||||
"parse_time_sync",
|
||||
"DstTransitionDict",
|
||||
"PosixTzDict",
|
||||
"UnknownTimezone",
|
||||
"is_iana_zone",
|
||||
"is_posix_tz",
|
||||
"parse_posix_tz",
|
||||
"posix_tz",
|
||||
"VMProvisionIncomplete",
|
||||
"SERVICE_CLUSTERS_COMMAND",
|
||||
"ServiceClustersMixin",
|
||||
"parse_service_clusters",
|
||||
"service_clusters_command",
|
||||
"SystemIdentityMixin",
|
||||
"SYSTEM_IDENTITY_COMMAND",
|
||||
"is_placeholder_identity",
|
||||
"parse_system_identity",
|
||||
"OpenSshServerMixin",
|
||||
"PamAuthEntryDict",
|
||||
"SshServerAuthDict",
|
||||
"SshServerAuthMixin",
|
||||
"SSHD_EFFECTIVE_COMMAND",
|
||||
"pam_auth_stack",
|
||||
"parse_sshd_auth",
|
||||
"SSH_ALGORITHM_CLASSES",
|
||||
"SshHardeningPlan",
|
||||
"SshHardeningResult",
|
||||
"plan_ssh_hardening",
|
||||
"SudoHistoryMixin",
|
||||
"HistorySudoLinesDict",
|
||||
"HistoryCleanupDict",
|
||||
"SudoHistoryCleanupDict",
|
||||
"SSH_HOST_KEYS_ARG",
|
||||
"SSH_HOST_KEY_OBSERVER_ARG",
|
||||
"HostKeyCheck",
|
||||
"HostKeyObservation",
|
||||
"SshHostKey",
|
||||
"SshHostKeyMismatch",
|
||||
"parse_virtual_ips",
|
||||
"add_lag_interfaces",
|
||||
"driver_supports_ping",
|
||||
"normalize_cidr",
|
||||
"normalize_mac",
|
||||
"primary_role_of",
|
||||
"role_keys_of",
|
||||
"roles_of",
|
||||
]
|
||||
@@ -0,0 +1,189 @@
|
||||
"""How chrony is given exactly the time sources a caller names.
|
||||
|
||||
The sources go to one file of their own (:func:`plan_chrony` picks it):
|
||||
|
||||
1. the sources file in a ``sourcedir`` the main configuration reads (Debian's
|
||||
``/etc/chrony/sources.d``): ``chronyc reload sources`` takes it without a restart;
|
||||
2. else ``netork.conf`` -- the include file's name -- in the first ``confdir``;
|
||||
3. else the include file, where an ``include`` pattern already takes it (SUSE's
|
||||
``/etc/chrony.d/*.conf``);
|
||||
4. else the include file, with an ``include`` line appended to the main configuration
|
||||
(RHEL's ``/etc/chrony.conf``).
|
||||
|
||||
Every other configured source stops counting: a ``server``, ``pool`` or ``peer``
|
||||
line in any other file chrony reads is commented out behind :data:`COMMENT_MARK`.
|
||||
``sourcedir`` lines stay. The DHCP client's directory (``/run/chrony-dhcp``) and its
|
||||
files are left alone: DHCP option 42 counts (NetOrk/netork#2380), and the client
|
||||
rewrites those files on every lease anyway.
|
||||
|
||||
4.35.0 commented out every ``sourcedir`` other than the sources file's, the DHCP
|
||||
client's among them, which left a host deaf to DHCP. A write gives a DHCP client's
|
||||
``sourcedir`` back where it finds one behind :data:`COMMENT_MARK`; any other one it
|
||||
took out stays out, its sources would be commented out now anyway.
|
||||
|
||||
chronyd reads its main configuration only when it starts: a change there means a
|
||||
restart.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
import shlex
|
||||
from dataclasses import dataclass, field
|
||||
from fnmatch import fnmatchcase
|
||||
|
||||
from napalm_device_types._time_sync_reading import (
|
||||
CHRONY_DHCP_DIRS,
|
||||
SOURCE_LINE,
|
||||
ConfigFile,
|
||||
in_dhcp_dir,
|
||||
)
|
||||
|
||||
#: What a source line taken out of chrony's configuration starts with.
|
||||
COMMENT_MARK = "#napalm-time-sync: "
|
||||
#: The comment above an ``include`` line appended to the main configuration.
|
||||
INCLUDE_COMMENT = "# napalm-time-sync: the time sources"
|
||||
|
||||
_DIRECTORY_LINE = re.compile(r"\s*(sourcedir|confdir|include)\s+(.+?)\s*$")
|
||||
#: A ``sourcedir`` line 4.35.0 commented out.
|
||||
_MARKED_SOURCEDIR = re.compile(rf"{re.escape(COMMENT_MARK)}sourcedir\s+(.+?)\s*$")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChronyPlan:
|
||||
"""What :func:`plan_chrony` decided."""
|
||||
|
||||
target: str # the file the sources go to
|
||||
content: str
|
||||
comment_out: dict[str, list[int]] = field(default_factory=dict) # path: line numbers
|
||||
restore: dict[str, list[int]] = field(default_factory=dict) # path: marked sourcedir lines
|
||||
include_in: str | None = None # the main configuration an include of target is appended to
|
||||
reload: bool = False # True: ``chronyc reload sources`` takes the change
|
||||
|
||||
|
||||
def source_line(server: str) -> str:
|
||||
"""The line a server is written as: a pool's name as a ``pool``, anything else a ``server``."""
|
||||
directive = "pool" if ".pool." in f".{server.lower()}." else "server"
|
||||
return f"{directive} {server} iburst"
|
||||
|
||||
|
||||
def _directives(main: ConfigFile) -> list[tuple[int, str, list[str]]]:
|
||||
found = []
|
||||
for number, line in enumerate(main.lines, start=1):
|
||||
match = _DIRECTORY_LINE.match(line)
|
||||
if match:
|
||||
found.append((number, match[1], match[2].split()))
|
||||
return found
|
||||
|
||||
|
||||
def _arguments(directives: list[tuple[int, str, list[str]]], kind: str) -> list[str]:
|
||||
return [arg for _, k, args in directives if k == kind for arg in args]
|
||||
|
||||
|
||||
def _target(main: ConfigFile, sources_file: str, include_file: str) -> tuple[str, str | None, bool]:
|
||||
"""The file the sources go to, the main configuration to include it from, and
|
||||
whether it is a sources file."""
|
||||
directives = _directives(main)
|
||||
if posixpath.dirname(sources_file) in _arguments(directives, "sourcedir"):
|
||||
return sources_file, None, True
|
||||
confdirs = _arguments(directives, "confdir")
|
||||
if confdirs:
|
||||
return posixpath.join(confdirs[0], posixpath.basename(include_file)), None, False
|
||||
if any(fnmatchcase(include_file, p) for p in _arguments(directives, "include")):
|
||||
return include_file, None, False
|
||||
return include_file, main.path, False
|
||||
|
||||
|
||||
def _dhcp_sourcedirs_to_restore(main: ConfigFile, dhcp_dirs: tuple[str, ...]) -> list[int]:
|
||||
"""The lines of *main* where 4.35.0 commented out a DHCP client's ``sourcedir``."""
|
||||
dhcp = {posixpath.normpath(d) for d in dhcp_dirs}
|
||||
return [
|
||||
number
|
||||
for number, line in enumerate(main.lines, start=1)
|
||||
if (marked := _MARKED_SOURCEDIR.match(line))
|
||||
and all(posixpath.normpath(arg) in dhcp for arg in marked[1].split())
|
||||
]
|
||||
|
||||
|
||||
def plan_chrony(
|
||||
files: list[ConfigFile],
|
||||
servers: list[str],
|
||||
*,
|
||||
sources_file: str,
|
||||
include_file: str,
|
||||
dhcp_dirs: tuple[str, ...] = CHRONY_DHCP_DIRS,
|
||||
) -> ChronyPlan:
|
||||
"""Where *servers* go, what else is commented out, and which DHCP ``sourcedir``
|
||||
(one of *dhcp_dirs*) comes back.
|
||||
|
||||
:raises RuntimeError: when the reading found no chrony configuration.
|
||||
"""
|
||||
main = next((f for f in files if f.kind == "main"), None)
|
||||
if main is None:
|
||||
raise RuntimeError("chrony runs, but no chrony configuration was found to write to")
|
||||
target, include_in, is_sources = _target(main, sources_file, include_file)
|
||||
comment_out = _comment_out(files, target, dhcp_dirs)
|
||||
restore = _dhcp_sourcedirs_to_restore(main, dhcp_dirs)
|
||||
return ChronyPlan(
|
||||
target=target,
|
||||
content="".join(f"{source_line(s)}\n" for s in servers),
|
||||
comment_out=comment_out,
|
||||
restore={main.path: restore} if restore else {},
|
||||
include_in=include_in,
|
||||
reload=(
|
||||
is_sources
|
||||
and include_in is None
|
||||
and not restore
|
||||
and _only_sources_files(files, comment_out)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _only_sources_files(files: list[ConfigFile], changed: dict[str, list[int]]) -> bool:
|
||||
"""Whether every file that changes is one ``chronyc reload sources`` reads again."""
|
||||
return all(f.kind == "sourcedir" for f in files if f.path in changed)
|
||||
|
||||
|
||||
def _comment_out(
|
||||
files: list[ConfigFile], target: str, dhcp_dirs: tuple[str, ...]
|
||||
) -> dict[str, list[int]]:
|
||||
"""Per file, the lines that take a source; the DHCP client's files are left alone."""
|
||||
found: dict[str, list[int]] = {}
|
||||
for f in files:
|
||||
if f.path == target or in_dhcp_dir(f, dhcp_dirs):
|
||||
continue
|
||||
numbers = [n for n, line in enumerate(f.lines, start=1) if SOURCE_LINE.match(line)]
|
||||
if numbers:
|
||||
found[f.path] = numbers
|
||||
return found
|
||||
|
||||
|
||||
def comment_out_command(path: str, numbers: list[int]) -> str:
|
||||
"""``sed`` that comments out those lines of *path* that still hold a source."""
|
||||
edits = " ".join(
|
||||
"-e "
|
||||
+ shlex.quote(f"{n}{{/^[[:space:]]*(server|pool|peer)[[:space:]]/s/^/{COMMENT_MARK}/;}}")
|
||||
for n in numbers
|
||||
)
|
||||
return f"sed -i -E {edits} {shlex.quote(path)}"
|
||||
|
||||
|
||||
def restore_command(path: str, numbers: list[int]) -> str:
|
||||
"""``sed`` that takes :data:`COMMENT_MARK` off those lines of *path* that are still a
|
||||
``sourcedir`` behind it. The mark holds nothing a regular expression or ``sed``'s
|
||||
``s///`` would read as special."""
|
||||
edits = " ".join(
|
||||
"-e " + shlex.quote(f"{n}{{s/^{COMMENT_MARK}(sourcedir[[:space:]])/\\1/;}}")
|
||||
for n in numbers
|
||||
)
|
||||
return f"sed -i -E {edits} {shlex.quote(path)}"
|
||||
|
||||
|
||||
def include_command(main: str, target: str) -> str:
|
||||
"""Append an ``include`` of *target* to *main*, on a line of its own."""
|
||||
lines = " ".join(shlex.quote(line) for line in (INCLUDE_COMMENT, f"include {target}"))
|
||||
return (
|
||||
f'{{ [ -z "$(tail -c 1 -- {shlex.quote(main)})" ] || echo; '
|
||||
f"printf '%s\\n' {lines}; }} >> {shlex.quote(main)}"
|
||||
)
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Crontabs and anacrontabs as text: the jobs in them, and changing one line of them.
|
||||
|
||||
Pure: no I/O. :mod:`napalm_device_types.scheduled_jobs_posix` reads the files and
|
||||
writes them back; this module says what is in them and what the new text is.
|
||||
|
||||
**A line's key survives switching it off.** A job switched off is the same line
|
||||
behind the marker :data:`DISABLED_MARKER`; the key is built from the line without
|
||||
it, so the job keeps its key and the marker is all that changes. Two equal lines
|
||||
in one file get ``:2``, ``:3`` after the first.
|
||||
|
||||
**A job an application wrote** is the line after ``# napalm-scheduled-job: <name>``
|
||||
and is keyed ``job:<name>``, whatever its schedule.
|
||||
|
||||
**Everything else is left as it was**: comments, blank lines, variables, lines
|
||||
cron would not take.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from shlex import quote
|
||||
|
||||
DISABLED_MARKER = "#napalm-disabled: "
|
||||
JOB_MARKER = "# napalm-scheduled-job: "
|
||||
|
||||
_VARIABLE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$")
|
||||
_ANACRON_PERIOD = re.compile(r"^(\d+|@(daily|weekly|monthly|yearly|annually))$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CronLine:
|
||||
"""One job in a crontab: where it is, what it says, and what was set before it."""
|
||||
|
||||
index: int # the line's number in the text, from 0
|
||||
key: str
|
||||
schedule: str
|
||||
run_as: str
|
||||
command: str
|
||||
enabled: bool
|
||||
env: dict[str, str] = field(default_factory=dict)
|
||||
name: str = "" # the name an application gave it
|
||||
description: str = ""
|
||||
|
||||
|
||||
def _unquote(value: str) -> str:
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def _digest(text: str) -> str:
|
||||
return hashlib.sha256(" ".join(text.split()).encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
def _split(content: str, *, system: bool, user: str) -> tuple[str, str, str] | None:
|
||||
"""(schedule, run_as, command) of a cron line; None for one cron would not take."""
|
||||
fields = 1 if content.startswith("@") else 5
|
||||
owner = 1 if system else 0
|
||||
parts = content.split(None, fields + owner)
|
||||
if len(parts) < fields + owner + 1:
|
||||
return None
|
||||
schedule = " ".join(parts[:fields])
|
||||
run_as = parts[fields] if system else user
|
||||
return schedule, run_as, parts[-1]
|
||||
|
||||
|
||||
def _anacron_split(content: str) -> tuple[str, str, str] | None:
|
||||
"""(period, job identifier, command) of an anacrontab line."""
|
||||
parts = content.split(None, 3)
|
||||
if len(parts) < 4 or not _ANACRON_PERIOD.match(parts[0]) or not parts[1].isdigit():
|
||||
return None
|
||||
return parts[0], parts[2], parts[3]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Scan:
|
||||
"""What is set while a text is read line by line."""
|
||||
|
||||
env: dict[str, str] = field(default_factory=dict)
|
||||
seen: dict[str, int] = field(default_factory=dict)
|
||||
name: str = ""
|
||||
description: str = ""
|
||||
|
||||
def key(self, base: str) -> str:
|
||||
n = self.seen.get(base, 0) + 1
|
||||
self.seen[base] = n
|
||||
return base if n == 1 else f"{base}:{n}"
|
||||
|
||||
def take_name(self) -> tuple[str, str]:
|
||||
named = self.name, self.description
|
||||
self.name, self.description = "", ""
|
||||
return named
|
||||
|
||||
|
||||
def _content(raw: str) -> tuple[str, bool] | None:
|
||||
"""The job text of *raw* and whether it is on; None for a comment or a blank."""
|
||||
line = raw.strip()
|
||||
if line.startswith(DISABLED_MARKER.strip()):
|
||||
return line[len(DISABLED_MARKER.strip()) :].strip(), False
|
||||
if not line or line.startswith("#"):
|
||||
return None
|
||||
return line, True
|
||||
|
||||
|
||||
def _remember(scan: _Scan, raw: str) -> bool:
|
||||
"""Take a variable or an application's marker from *raw*; whether it was one."""
|
||||
line = raw.strip()
|
||||
if line.startswith(JOB_MARKER.strip()):
|
||||
name, _, description = line[len(JOB_MARKER.strip()) :].strip().partition(" ")
|
||||
scan.name, scan.description = name, description.strip()
|
||||
return True
|
||||
variable = _VARIABLE.match(line)
|
||||
if variable:
|
||||
scan.env[variable[1]] = _unquote(variable[2])
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def parse_crontab(path: str, text: str, *, system: bool, user: str = "") -> list[CronLine]:
|
||||
"""The jobs of the crontab *text* at *path*.
|
||||
|
||||
*system*: a sixth field names the user (``/etc/crontab``, ``/etc/cron.d``);
|
||||
otherwise every job runs as *user*.
|
||||
"""
|
||||
scan, jobs = _Scan(), []
|
||||
for index, raw in enumerate(text.splitlines()):
|
||||
if _remember(scan, raw):
|
||||
continue
|
||||
found = _content(raw)
|
||||
split = _split(found[0], system=system, user=user) if found else None
|
||||
if found is None or split is None:
|
||||
continue
|
||||
content, enabled = found
|
||||
name, description = scan.take_name()
|
||||
key = f"job:{name}" if name else scan.key(f"cron:{path}:{_digest(content)}")
|
||||
schedule, run_as, command = split
|
||||
jobs.append(
|
||||
CronLine(
|
||||
index, key, schedule, run_as, command, enabled, dict(scan.env), name, description
|
||||
)
|
||||
)
|
||||
return jobs
|
||||
|
||||
|
||||
def parse_anacrontab(text: str) -> list[CronLine]:
|
||||
"""The jobs of an anacrontab: period, delay, identifier, command; all run as root."""
|
||||
scan, jobs = _Scan(), []
|
||||
for index, raw in enumerate(text.splitlines()):
|
||||
if _remember(scan, raw):
|
||||
continue
|
||||
found = _content(raw)
|
||||
split = _anacron_split(found[0]) if found else None
|
||||
if found is None or split is None:
|
||||
continue
|
||||
period, identifier, command = split
|
||||
key = scan.key(f"anacron:{identifier}")
|
||||
jobs.append(CronLine(index, key, period, "root", command, found[1], dict(scan.env)))
|
||||
return jobs
|
||||
|
||||
|
||||
def _replace(text: str, index: int, lines: list[str]) -> str:
|
||||
rows = text.splitlines()
|
||||
rows[index : index + 1] = lines
|
||||
return "\n".join(rows) + "\n"
|
||||
|
||||
|
||||
def switched(text: str, line: CronLine, *, enabled: bool) -> str:
|
||||
"""*text* with *line* switched on or off: the marker added or taken away, nothing else."""
|
||||
raw = text.splitlines()[line.index]
|
||||
found = _content(raw)
|
||||
if found is None: # pragma: no cover - a CronLine always points at a job
|
||||
raise ValueError(f"line {line.index} is no job")
|
||||
content = found[0]
|
||||
return _replace(text, line.index, [content if enabled else DISABLED_MARKER + content])
|
||||
|
||||
|
||||
def marked_lines(name: str, description: str, line: str, *, enabled: bool) -> list[str]:
|
||||
"""An application's job as crontab lines: its marker, then the job, maybe switched off."""
|
||||
marker = f"{JOB_MARKER}{name} {description}".rstrip()
|
||||
return [marker, line if enabled else DISABLED_MARKER + line]
|
||||
|
||||
|
||||
def with_job(text: str, jobs: list[CronLine], name: str, lines: list[str]) -> str:
|
||||
"""*text* with the application's job *name* as *lines*: replaced, or added at the end."""
|
||||
current = next((j for j in jobs if j.name == name), None)
|
||||
if current is None:
|
||||
body = text if not text or text.endswith("\n") else text + "\n"
|
||||
return body + "\n".join(lines) + "\n"
|
||||
rows = text.splitlines()
|
||||
rows[current.index - 1 : current.index + 1] = lines
|
||||
return "\n".join(rows) + "\n"
|
||||
|
||||
|
||||
def without_job(text: str, jobs: list[CronLine], name: str) -> str:
|
||||
"""*text* without the application's job *name* and its marker."""
|
||||
current = next(j for j in jobs if j.name == name)
|
||||
rows = text.splitlines()
|
||||
del rows[current.index - 1 : current.index + 1]
|
||||
return "\n".join(rows) + ("\n" if rows else "")
|
||||
|
||||
|
||||
def _unescape(part: str) -> str:
|
||||
return part.replace("\\%", "%")
|
||||
|
||||
|
||||
def run_script(command: str, env: dict[str, str]) -> str:
|
||||
"""*command* as ``sh -c`` takes it, the way cron would run it.
|
||||
|
||||
The crontab's variables are exported first. The first ``%`` that is not
|
||||
escaped ends the command; what follows is its stdin, with every further
|
||||
``%`` a newline, and ``\\%`` is a ``%``.
|
||||
"""
|
||||
parts = re.split(r"(?<!\\)%", command)
|
||||
exports = "".join(f"export {k}={quote(v)}; " for k, v in env.items() if k != "MAILTO")
|
||||
head = _unescape(parts[0])
|
||||
if len(parts) == 1:
|
||||
return exports + head
|
||||
stdin = "\n".join(_unescape(p) for p in parts[1:])
|
||||
return f"{exports}printf '%s\\n' {quote(stdin)} | {{ {head}\n}}"
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The order an applied reservation set is written in (#106).
|
||||
|
||||
A DHCP server such as Kea keeps every address unique at each write, not only at the
|
||||
commit: a reservation that takes an address another one still holds is refused as a
|
||||
duplicate. So the changes are ordered for an address to be released before it is taken:
|
||||
|
||||
* An update that moves a reservation off its address goes before the change that takes
|
||||
that address -- along a chain, from its free end.
|
||||
* Adds come after every update: they release nothing, and an update may free their
|
||||
address.
|
||||
|
||||
A *swap* -- two reservations trading addresses, or a longer rotation -- has no such
|
||||
order. Its changes are still tried, in the order of the desired set: a server that checks
|
||||
only at the commit takes them. A server that refuses them refuses each with its own
|
||||
message, and the progress line says it was a swap. Nothing is moved to a temporary
|
||||
address: the contract knows no free one (pools, leases and reservations nobody manages
|
||||
all hold addresses), and a second write that failed would leave the reservation on it.
|
||||
|
||||
Without I/O: a reconciler's part, see ``docs/STRUCTURE.md``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from dataclasses import dataclass
|
||||
|
||||
from napalm_device_types.models import DhcpReservationDict, DhcpReservationDiffDict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReservationChange:
|
||||
"""One write of an applied set, in the order it is made."""
|
||||
|
||||
reservation: DhcpReservationDict
|
||||
#: The live reservation's id for an update, None for an add.
|
||||
uuid: str | None
|
||||
#: The changed fields of an update (``"ip, hostname"``), empty for an add.
|
||||
fields: str = ""
|
||||
#: The other reservations' MACs of the swap this change is part of, if any.
|
||||
swap: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _address(ip: str | None) -> str:
|
||||
"""*ip* in one spelling, so ``192.0.2.010``-style differences cannot hide a match."""
|
||||
text = (ip or "").strip()
|
||||
try:
|
||||
return str(ipaddress.ip_address(text))
|
||||
except ValueError:
|
||||
return text.lower()
|
||||
|
||||
|
||||
def _waits_on(updates: list[tuple[str, str]]) -> list[int | None]:
|
||||
"""For each ``(old, new)`` address pair, the update whose release it waits for."""
|
||||
released = {old: i for i, (old, new) in enumerate(updates) if old and old != new}
|
||||
return [released.get(new) if new != old else None for old, new in updates]
|
||||
|
||||
|
||||
def _cycles(waits_on: list[int | None]) -> dict[int, list[int]]:
|
||||
"""Each update that is part of a cycle, with the cycle's members in order."""
|
||||
members: dict[int, list[int]] = {}
|
||||
for start in range(len(waits_on)):
|
||||
path: list[int] = []
|
||||
node: int | None = start
|
||||
while node is not None and node not in path and node not in members:
|
||||
path.append(node)
|
||||
node = waits_on[node]
|
||||
if node is not None and node in path:
|
||||
cycle = sorted(path[path.index(node) :])
|
||||
members.update(dict.fromkeys(cycle, cycle))
|
||||
return members
|
||||
|
||||
|
||||
def _update_order(waits_on: list[int | None], cycles: dict[int, list[int]]) -> list[int]:
|
||||
"""Every update after the one it waits on; stable otherwise. Where only cycles are
|
||||
left, the first of them goes as it is, and so on."""
|
||||
order: list[int] = []
|
||||
done: set[int] = set()
|
||||
pending = list(range(len(waits_on)))
|
||||
while pending:
|
||||
ready = [i for i in pending if waits_on[i] is None or waits_on[i] in done]
|
||||
if not ready:
|
||||
ready = [next(i for i in pending if i in cycles)]
|
||||
order += ready
|
||||
done.update(ready)
|
||||
pending = [i for i in pending if i not in done]
|
||||
return order
|
||||
|
||||
|
||||
def order_reservation_changes(
|
||||
diff: DhcpReservationDiffDict, live: list[DhcpReservationDict]
|
||||
) -> list[ReservationChange]:
|
||||
"""The changes of *diff* in the order they are written; see the module.
|
||||
|
||||
:param diff: What ``diff_dhcp_reservations`` found.
|
||||
:param live: The reservations it compared against, for the addresses updates release.
|
||||
"""
|
||||
held = {r.get("uuid"): _address(r.get("ip")) for r in live if r.get("uuid")}
|
||||
updates = diff["update"]
|
||||
waits_on = _waits_on(
|
||||
[(held.get(e["uuid"], ""), _address(e["reservation"].get("ip"))) for e in updates]
|
||||
)
|
||||
cycles = _cycles(waits_on)
|
||||
|
||||
def swap(i: int) -> tuple[str, ...]:
|
||||
return tuple(updates[j]["reservation"]["mac"] for j in cycles.get(i, []) if j != i)
|
||||
|
||||
ordered = [
|
||||
ReservationChange(
|
||||
updates[i]["reservation"],
|
||||
updates[i]["uuid"],
|
||||
", ".join(updates[i]["changed_fields"]),
|
||||
swap(i),
|
||||
)
|
||||
for i in _update_order(waits_on, cycles)
|
||||
]
|
||||
return ordered + [ReservationChange(r, None) for r in diff["add"]]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Keying live and desired entries for a diff, refusing what cannot be matched.
|
||||
|
||||
A diff matches a desired entry to a live one by a key (a rule's description, a
|
||||
reservation's MAC, a subnet's CIDR). An empty key or one held twice cannot
|
||||
name a single entry, and guessing would overwrite one the caller never meant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
|
||||
def index_live[T](entries: Iterable[T], key: Callable[[T], str]) -> tuple[dict[str, T], set[str]]:
|
||||
"""Live entries by key, and the keys more than one of them holds.
|
||||
|
||||
Entries without a key are left out: they are not the caller's to match.
|
||||
"""
|
||||
by_key: dict[str, T] = {}
|
||||
shared: set[str] = set()
|
||||
for entry in entries:
|
||||
k = key(entry)
|
||||
if not k:
|
||||
continue
|
||||
if k in by_key:
|
||||
shared.add(k)
|
||||
by_key[k] = entry
|
||||
for k in shared:
|
||||
del by_key[k]
|
||||
return by_key, shared
|
||||
|
||||
|
||||
def check_desired[T](
|
||||
entries: list[T], key: Callable[[T], str], shared: set[str], what: str
|
||||
) -> None:
|
||||
"""``ValueError`` for a desired entry with no key, a key given twice, or a
|
||||
key that names more than one live entry."""
|
||||
seen: set[str] = set()
|
||||
for entry in entries:
|
||||
k = key(entry)
|
||||
if not k:
|
||||
raise ValueError(f"a desired entry has no {what}")
|
||||
if k in seen:
|
||||
raise ValueError(f"{what} {k!r} is given twice")
|
||||
if k in shared:
|
||||
raise ValueError(f"{what} {k!r} names more than one entry on the device")
|
||||
seen.add(k)
|
||||
@@ -0,0 +1,417 @@
|
||||
"""The scheduled-jobs report of a POSIX host: the command that prints it, and its parse.
|
||||
|
||||
:mod:`napalm_device_types.scheduled_jobs_posix` sends :func:`reading_command` and
|
||||
hands what came back to :func:`parse_reading`. Pure: no I/O.
|
||||
|
||||
**One framed report, as root.** Every crontab, cron.d file, anacrontab and job
|
||||
script is printed behind a header line and with ``|`` before each of its lines,
|
||||
so no line of a file can pass for a header; run-parts scripts by their execute
|
||||
bit and checksum; systemd's timers and the units they start by ``systemctl show``;
|
||||
then the time zone and which package owns each definition file. A report whose
|
||||
end marker is missing raises: a list cut short must never read as jobs that went
|
||||
away.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from shlex import quote
|
||||
|
||||
from napalm_device_types._crontab import JOB_MARKER, CronLine, parse_anacrontab, parse_crontab
|
||||
from napalm_device_types.scheduled_jobs import DELETE, EDIT, job_digest
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "SJ_BEGIN"
|
||||
_END = "SJ_END"
|
||||
SCHEDULE_HEADER = "# schedule: "
|
||||
|
||||
TIMER_PROPERTIES = (
|
||||
"Id,Unit,Description,TimersCalendar,TimersMonotonic,NextElapseUSecRealtime,"
|
||||
"LastTriggerUSec,UnitFileState,ActiveState,FragmentPath"
|
||||
)
|
||||
UNIT_PROPERTIES = "Id,ExecStart,User,Result,FragmentPath"
|
||||
|
||||
#: The names run-parts runs (Debian's ``--lsbsysinit``-less default).
|
||||
_RUN_PARTS_NAME = re.compile(r"^[A-Za-z0-9_-]+$")
|
||||
_SECTION = re.compile(r"^\[([a-z-]+)(?: (.*))?\]$")
|
||||
|
||||
#: Reads definition paths on stdin, prints ``<package>: <path>`` for each a package owns.
|
||||
OWNERS_SH = (
|
||||
"if command -v dpkg >/dev/null 2>&1; then xargs dpkg -S 2>/dev/null; "
|
||||
"elif command -v rpm >/dev/null 2>&1; then while read -r p; do "
|
||||
'o=$(rpm -qf --qf \'%{NAME}\' -- "$p" 2>/dev/null) && printf \'%s: %s\\n\' "$o" "$p"; done; '
|
||||
"elif command -v apk >/dev/null 2>&1; then while read -r p; do "
|
||||
'o=$(apk info -qW -- "$p" 2>/dev/null) && [ -n "$o" ] && printf \'%s: %s\\n\' "$o" "$p"; done; '
|
||||
"else cat >/dev/null; fi"
|
||||
)
|
||||
|
||||
|
||||
#: Prints the host's time zone: an IANA name, or a path ending in ``zoneinfo/<name>``.
|
||||
TIME_ZONE_SH = "cat /etc/timezone 2>/dev/null || readlink /etc/localtime 2>/dev/null"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paths:
|
||||
"""Where a host keeps its scheduled jobs."""
|
||||
|
||||
system_files: tuple[str, ...]
|
||||
cron_d_dirs: tuple[str, ...]
|
||||
spool_dirs: tuple[str, ...]
|
||||
run_parts: tuple[tuple[str, str], ...] # (period, directory)
|
||||
anacrontab: str
|
||||
script_dir: str
|
||||
systemd_marker: str = "/run/systemd/system"
|
||||
owners_sh: str = OWNERS_SH
|
||||
time_zone_sh: str = TIME_ZONE_SH
|
||||
|
||||
|
||||
@dataclass
|
||||
class Reading:
|
||||
"""What one report said, beyond the jobs: what writes need to know."""
|
||||
|
||||
jobs: list[dict[str, object]] = field(default_factory=list)
|
||||
time_zone: str | None = None
|
||||
systemd: bool = False
|
||||
#: per key: the unit a timer starts, the crontab line a cron job is
|
||||
units: dict[str, str] = field(default_factory=dict)
|
||||
lines: dict[str, CronLine] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _q(path: str) -> str:
|
||||
return quote(path)
|
||||
|
||||
|
||||
def _files(section: str, pattern: str) -> str:
|
||||
return (
|
||||
f'for f in {pattern}; do [ -f "$f" ] || continue; printf \'[%s %s]\\n\' {section} "$f"; '
|
||||
# GNU sed keeps a missing last newline; without one of its own the next
|
||||
# header would run on into the file's last line.
|
||||
'sed \'s/^/|/\' "$f"; [ -n "$(tail -c 1 "$f")" ] && echo; P="$P\n$f"; done; '
|
||||
)
|
||||
|
||||
|
||||
def _run_parts(period: str, directory: str) -> str:
|
||||
return (
|
||||
f'for f in {_q(directory)}/*; do [ -f "$f" ] || continue; '
|
||||
'[ -x "$f" ] && x=1 || x=0; c=$(cksum < "$f" | cut -d" " -f1); '
|
||||
f'printf \'[run-parts %s %s %s %s]\\n\' {period} "$x" "$c" "$f"; P="$P\n$f"; done; '
|
||||
)
|
||||
|
||||
|
||||
def _timers(paths: Paths) -> str:
|
||||
show = f"systemctl show --no-pager -p {TIMER_PROPERTIES}"
|
||||
units = f"systemctl show --no-pager -p {UNIT_PROPERTIES}"
|
||||
return (
|
||||
f"if [ -d {_q(paths.systemd_marker)} ]; then echo '[systemd]'; "
|
||||
"t=$(systemctl list-unit-files --type=timer --no-legend --no-pager 2>/dev/null "
|
||||
"| awk '$1 !~ /@\\./ {print $1}'); "
|
||||
'if [ -n "$t" ]; then '
|
||||
f"s=$({show} --timestamp=unix $t 2>/dev/null || {show} $t 2>/dev/null); "
|
||||
"echo '[timers]'; printf '%s\\n' \"$s\" | sed 's/^/|/'; "
|
||||
"u=$(printf '%s\\n' \"$s\" | sed -n 's/^Unit=//p'); "
|
||||
f"echo '[units]'; {units} $u 2>/dev/null | sed 's/^/|/'; "
|
||||
"P=\"$P\n$(printf '%s\\n' \"$s\" | sed -n 's/^FragmentPath=//p')\"; fi; fi; "
|
||||
)
|
||||
|
||||
|
||||
def reading_command(paths: Paths) -> str:
|
||||
"""One POSIX ``sh`` script that prints every scheduled job of the host; run it as root."""
|
||||
parts = ["printf '%s%s\\n' SJ_ BEGIN; P=''; "]
|
||||
parts += [_files("system", _q(f)) for f in paths.system_files]
|
||||
parts += [_files("system", f"{_q(d)}/*") for d in paths.cron_d_dirs]
|
||||
parts += [_files("user", f"{_q(d)}/*") for d in paths.spool_dirs]
|
||||
parts.append(_files("anacron", _q(paths.anacrontab)))
|
||||
parts += [_run_parts(period, d) for period, d in paths.run_parts]
|
||||
parts.append(_files("script", f"{_q(paths.script_dir)}/*"))
|
||||
parts.append(_timers(paths))
|
||||
parts.append(
|
||||
f"echo '[tz]'; {{ {paths.time_zone_sh}; }}; "
|
||||
f"echo '[owners]'; printf '%s\\n' \"$P\" | sed '/^$/d' | {{ {paths.owners_sh}; }}; "
|
||||
"printf '%s%s\\n' SJ_ END"
|
||||
)
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
# -- parse ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Section:
|
||||
name: str
|
||||
args: str
|
||||
lines: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _sections(output: str) -> list[_Section]:
|
||||
text = strip_terminal_codes(output)
|
||||
begin, end = text.rfind(_BEGIN), text.rfind(_END)
|
||||
if begin < 0 or end < begin:
|
||||
raise ValueError("the scheduled-jobs report is cut short (no end marker)")
|
||||
sections: list[_Section] = []
|
||||
for line in text[begin + len(_BEGIN) : end].splitlines():
|
||||
header = _SECTION.match(line)
|
||||
if header:
|
||||
sections.append(_Section(header[1], header[2] or ""))
|
||||
elif sections:
|
||||
sections[-1].lines.append(line[1:] if line.startswith("|") else line)
|
||||
return sections
|
||||
|
||||
|
||||
def _owned(lines: list[str]) -> set[str]:
|
||||
owned: set[str] = set()
|
||||
for line in lines:
|
||||
package, sep, path = line.partition(": ")
|
||||
if sep and path.startswith("/") and not package.startswith("diversion"):
|
||||
owned.add(path.strip())
|
||||
return owned
|
||||
|
||||
|
||||
def _time_zone(lines: list[str]) -> str | None:
|
||||
value = next((ln.strip() for ln in lines if ln.strip()), "")
|
||||
if "zoneinfo/" in value:
|
||||
value = value.split("zoneinfo/", 1)[1]
|
||||
return value or None
|
||||
|
||||
|
||||
def _blocks(lines: list[str]) -> list[dict[str, list[str]]]:
|
||||
blocks: list[dict[str, list[str]]] = [{}]
|
||||
for line in lines:
|
||||
if not line.strip():
|
||||
blocks.append({})
|
||||
continue
|
||||
key, sep, value = line.partition("=")
|
||||
if sep:
|
||||
blocks[-1].setdefault(key, []).append(value)
|
||||
return [b for b in blocks if b.get("Id")]
|
||||
|
||||
|
||||
def _one(block: dict[str, list[str]], key: str) -> str:
|
||||
return (block.get(key) or [""])[0].strip()
|
||||
|
||||
|
||||
def _timestamp(value: str) -> str | None:
|
||||
"""systemd's ``@<seconds>`` (or a UTC time) as ISO 8601; None when it never was."""
|
||||
value = value.strip()
|
||||
if value.startswith("@") and value[1:].isdigit() and int(value[1:]) > 0:
|
||||
return datetime.fromtimestamp(int(value[1:]), UTC).isoformat()
|
||||
match = re.search(r"(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d) UTC$", value)
|
||||
if match:
|
||||
return datetime.strptime(match[1], "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC).isoformat()
|
||||
return None
|
||||
|
||||
|
||||
def _timer_entries(block: dict[str, list[str]], key: str) -> list[str]:
|
||||
"""``{ OnCalendar=daily ; next_elapse=… }`` → ``OnCalendar=daily``, one per entry.
|
||||
|
||||
``systemctl show`` names a monotonic setting by its property (``OnUnitActiveUSec``);
|
||||
it is given as the unit file says it (``OnUnitActiveSec``).
|
||||
"""
|
||||
entries = (v.strip(" {}").split(" ; ")[0].strip() for v in block.get(key, []) if v.strip())
|
||||
return [re.sub(r"^(On\w+)USec=", r"\1Sec=", e) for e in entries]
|
||||
|
||||
|
||||
def _argv(exec_start: list[str]) -> str:
|
||||
commands = []
|
||||
for value in exec_start:
|
||||
match = re.search(r"argv\[\]=(.*?) ; ", value)
|
||||
if match:
|
||||
commands.append(match[1].strip())
|
||||
return "; ".join(commands)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Script:
|
||||
name: str
|
||||
description: str
|
||||
schedule: str
|
||||
command: str
|
||||
|
||||
|
||||
def _script(path: str, lines: list[str]) -> _Script | None:
|
||||
"""An application's job script: its marker, schedule and command; None for any other file."""
|
||||
marker = next((ln for ln in lines if ln.startswith(JOB_MARKER)), None)
|
||||
schedule = next((ln for ln in lines if ln.startswith(SCHEDULE_HEADER)), None)
|
||||
if marker is None or schedule is None:
|
||||
return None
|
||||
name, _, description = marker[len(JOB_MARKER) :].partition(" ")
|
||||
body = [ln for ln in lines if ln not in (marker, schedule) and not ln.startswith("#!")]
|
||||
return _Script(
|
||||
name, description.strip(), schedule[len(SCHEDULE_HEADER) :], "\n".join(body).strip()
|
||||
)
|
||||
|
||||
|
||||
def _job(
|
||||
*,
|
||||
key: str,
|
||||
kind: str,
|
||||
source: str,
|
||||
run_as: str,
|
||||
schedule: str,
|
||||
schedule_kind: str,
|
||||
command: str,
|
||||
enabled: bool,
|
||||
managed_by: str,
|
||||
actions: list[str],
|
||||
content: str = "",
|
||||
**extra: object,
|
||||
) -> dict[str, object]:
|
||||
job: dict[str, object] = {
|
||||
"key": key,
|
||||
"kind": kind,
|
||||
"source": source,
|
||||
"run_as": run_as,
|
||||
"schedule": schedule,
|
||||
"schedule_kind": schedule_kind,
|
||||
"command": command,
|
||||
"enabled": enabled,
|
||||
"managed_by": managed_by,
|
||||
"actions": actions,
|
||||
}
|
||||
job["digest"] = job_digest(job, content=content)
|
||||
job.update({k: v for k, v in extra.items() if v not in (None, "")})
|
||||
return job
|
||||
|
||||
|
||||
_SWITCH = ["enable", "disable", "run"]
|
||||
_OWN = [*_SWITCH, EDIT, DELETE]
|
||||
|
||||
|
||||
def _cron_jobs(section: _Section, owned: set[str], reading: Reading) -> None:
|
||||
path = section.args
|
||||
text = "\n".join(section.lines)
|
||||
if section.name == "anacron":
|
||||
found = parse_anacrontab(text)
|
||||
else:
|
||||
user = path.rsplit("/", 1)[-1]
|
||||
found = parse_crontab(path, text, system=section.name == "system", user=user)
|
||||
kind = "anacron" if section.name == "anacron" else "cron"
|
||||
for line in found:
|
||||
own = bool(line.name)
|
||||
reading.lines[line.key] = line
|
||||
reading.jobs.append(
|
||||
_job(
|
||||
key=line.key,
|
||||
kind=kind,
|
||||
source=path,
|
||||
run_as=line.run_as,
|
||||
schedule=line.schedule,
|
||||
schedule_kind="period" if kind == "anacron" else "cron",
|
||||
command=line.command,
|
||||
enabled=line.enabled,
|
||||
managed_by="application" if own else ("package" if path in owned else "admin"),
|
||||
actions=_OWN if own else _SWITCH,
|
||||
name=line.name,
|
||||
description=line.description,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _run_parts_job(section: _Section, owned: set[str], reading: Reading) -> None:
|
||||
period, executable, checksum, path = section.args.split(" ", 3)
|
||||
if not _RUN_PARTS_NAME.match(path.rsplit("/", 1)[-1]):
|
||||
return
|
||||
reading.jobs.append(
|
||||
_job(
|
||||
key=f"run-parts:{path}",
|
||||
kind="run_parts",
|
||||
source=path,
|
||||
run_as="root",
|
||||
schedule=period,
|
||||
schedule_kind="period",
|
||||
command=path,
|
||||
enabled=executable == "1",
|
||||
managed_by="package" if path in owned else "admin",
|
||||
actions=_SWITCH,
|
||||
content=checksum,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _timer_job(
|
||||
timer: dict[str, list[str]],
|
||||
unit: dict[str, list[str]],
|
||||
scripts: dict[str, _Script],
|
||||
owned: set[str],
|
||||
) -> dict[str, object]:
|
||||
fragment = _one(timer, "FragmentPath")
|
||||
calendar = _timer_entries(timer, "TimersCalendar")
|
||||
schedule = "; ".join(calendar + _timer_entries(timer, "TimersMonotonic"))
|
||||
command = _argv(unit.get("ExecStart", []))
|
||||
script = scripts.get(command.split(" ", 1)[0])
|
||||
last_run = _timestamp(_one(timer, "LastTriggerUSec"))
|
||||
switchable = _one(timer, "UnitFileState") not in ("static", "generated", "transient")
|
||||
common = {
|
||||
"kind": "systemd_timer",
|
||||
"source": fragment,
|
||||
"run_as": _one(unit, "User") or "root",
|
||||
"enabled": _one(timer, "ActiveState") == "active",
|
||||
"last_run": last_run,
|
||||
"last_result": _one(unit, "Result") or None if last_run else None,
|
||||
"next_run": _timestamp(_one(timer, "NextElapseUSecRealtime")),
|
||||
}
|
||||
if script is not None:
|
||||
return _job(
|
||||
key=f"job:{script.name}",
|
||||
schedule=script.schedule,
|
||||
schedule_kind="cron",
|
||||
command=script.command,
|
||||
managed_by="application",
|
||||
actions=_OWN,
|
||||
name=script.name,
|
||||
description=script.description,
|
||||
**common, # type: ignore[arg-type]
|
||||
)
|
||||
packaged = fragment in owned or fragment.startswith(("/usr/lib/", "/lib/"))
|
||||
return _job(
|
||||
key=f"timer:{_one(timer, 'Id')}",
|
||||
schedule=schedule,
|
||||
schedule_kind="calendar" if calendar else "monotonic",
|
||||
command=command,
|
||||
managed_by="package" if packaged else "admin",
|
||||
actions=_SWITCH if switchable else ["run"],
|
||||
description=_one(timer, "Description"),
|
||||
**common, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
|
||||
def _timer_jobs(
|
||||
sections: dict[str, _Section], scripts: dict[str, _Script], owned: set[str], reading: Reading
|
||||
) -> None:
|
||||
timers = _blocks(sections["timers"].lines) if "timers" in sections else []
|
||||
units = (
|
||||
{_one(b, "Id"): b for b in _blocks(sections["units"].lines)} if "units" in sections else {}
|
||||
)
|
||||
for timer in timers:
|
||||
unit = units.get(_one(timer, "Unit"), {})
|
||||
job = _timer_job(timer, unit, scripts, owned)
|
||||
reading.units[str(job["key"])] = _one(timer, "Unit")
|
||||
reading.jobs.append(job)
|
||||
|
||||
|
||||
def parse_reading(output: str) -> Reading:
|
||||
"""The jobs, time zone and write context of a report from :func:`reading_command`.
|
||||
|
||||
:raises ValueError: when the report is cut short.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
named = {s.name: s for s in sections if s.name in ("timers", "units", "tz", "owners")}
|
||||
owned = _owned(named["owners"].lines) if "owners" in named else set()
|
||||
reading = Reading(
|
||||
time_zone=_time_zone(named["tz"].lines) if "tz" in named else None,
|
||||
systemd=any(s.name == "systemd" for s in sections),
|
||||
)
|
||||
for section in sections:
|
||||
if section.name in ("system", "user", "anacron"):
|
||||
_cron_jobs(section, owned, reading)
|
||||
elif section.name == "run-parts":
|
||||
_run_parts_job(section, owned, reading)
|
||||
_timer_jobs(named, _scripts(sections), owned, reading)
|
||||
return reading
|
||||
|
||||
|
||||
def _scripts(sections: list[_Section]) -> dict[str, _Script]:
|
||||
"""An application's job scripts, by path."""
|
||||
scripts = ((s.args, _script(s.args, s.lines)) for s in sections if s.name == "script")
|
||||
return {path: script for path, script in scripts if script is not None}
|
||||
@@ -0,0 +1,369 @@
|
||||
"""The reading behind :class:`~napalm_device_types.time_sync_posix.PosixTimeSyncMixin`.
|
||||
|
||||
One command, as the login user, prints framed sections (``@@ts <name> ...``):
|
||||
|
||||
* ``timedatectl`` -- ``timedatectl show``: the zone, and whether the kernel clock is
|
||||
synchronised;
|
||||
* ``zone`` -- ``/etc/timezone`` or the target of ``/etc/localtime``, for a host
|
||||
without timedatectl;
|
||||
* ``active`` -- one ``<unit> <daemon> <state>`` line per time sync service;
|
||||
* ``timesync`` -- ``timedatectl show-timesync``: systemd-timesyncd's servers;
|
||||
* ``chronyc`` -- ``chronyc -n sources``: whether chronyd has selected a source;
|
||||
* ``chrony <line> <kind> <path>`` -- chrony's main configuration (line 0, kind
|
||||
``main``), then each file an ``include``, ``confdir`` or ``sourcedir`` on that
|
||||
line of it reads;
|
||||
* ``ntpd <path>``, ``openntpd <path>`` -- their configuration;
|
||||
* ``end`` -- the reading is complete.
|
||||
|
||||
What DHCP brought is read apart from the configured servers: chrony's files in a
|
||||
DHCP client's ``sourcedir`` (:data:`CHRONY_DHCP_DIRS`), systemd-timesyncd's
|
||||
``LinkNTPServers``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
import shlex
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from napalm_device_types.time_sync import TimeSyncDict
|
||||
|
||||
_MARK = "@@ts "
|
||||
|
||||
#: ``<unit> <daemon>``: the services that keep a host's clock; the first active one counts.
|
||||
TIME_SYNC_UNITS: tuple[tuple[str, str], ...] = (
|
||||
("chrony", "chrony"),
|
||||
("chronyd", "chrony"),
|
||||
("systemd-timesyncd", "systemd-timesyncd"),
|
||||
("ntpsec", "ntpd"),
|
||||
("ntp", "ntpd"),
|
||||
("ntpd", "ntpd"),
|
||||
("openntpd", "openntpd"),
|
||||
)
|
||||
|
||||
#: The ``sourcedir`` a DHCP client writes chrony's sources to, one file per interface
|
||||
#: and lease: the NetworkManager dispatcher and dhclient hook of Debian, Ubuntu and
|
||||
#: Red Hat. What chrony reads from there is DHCP's (option 42), not configuration.
|
||||
CHRONY_DHCP_DIRS: tuple[str, ...] = ("/run/chrony-dhcp", "/var/run/chrony-dhcp")
|
||||
|
||||
#: A source line of chrony's or ntpd's configuration: the directive and what follows.
|
||||
SOURCE_LINE = re.compile(r"\s*(server|pool|peer)\s+(.*)")
|
||||
_OPENNTPD_SOURCE = re.compile(r"\s*(servers?)\s+(\S+)")
|
||||
_ZONE_NAME = re.compile(r"[A-Za-z0-9_+-]+(?:/[A-Za-z0-9_+-]+)*")
|
||||
#: ntpd's reference clocks are addresses in 127.127.0.0/16, not servers.
|
||||
_REFCLOCK = "127.127."
|
||||
|
||||
# The files a chrony configuration reads, each after a marker with the line that names it.
|
||||
_CHRONY_FOLLOW = """\
|
||||
awk '$1=="include"||$1=="confdir"||$1=="sourcedir"{for(i=2;i<=NF;i++)print NR, $1, $i}' "$c" |
|
||||
while read -r n k p; do
|
||||
case $k in include) set -- $p ;; confdir) set -- "$p"/*.conf ;; *) set -- "$p"/*.sources ;; esac
|
||||
for f in "$@"; do
|
||||
[ -f "$f" ] && { printf '@@ts chrony %s %s %s\\n' "$n" "$k" "$f"; cat -- "$f"; echo; }
|
||||
done
|
||||
done"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReadPaths:
|
||||
"""Where a host keeps what the reading reads."""
|
||||
|
||||
units: tuple[tuple[str, str], ...]
|
||||
chrony_configs: tuple[str, ...]
|
||||
ntpd_configs: tuple[str, ...]
|
||||
openntpd_configs: tuple[str, ...]
|
||||
time_zone_sh: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConfigFile:
|
||||
"""One configuration file as the reading printed it."""
|
||||
|
||||
path: str
|
||||
kind: str # "main", "include", "confdir", "sourcedir"; "ntpd", "openntpd"
|
||||
at: int # the line of the main configuration that names it; 0 for that file itself
|
||||
lines: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Reading:
|
||||
"""Everything one reading said."""
|
||||
|
||||
timedatectl: dict[str, str] = field(default_factory=dict)
|
||||
zone_files: list[str] = field(default_factory=list)
|
||||
active: list[tuple[str, str]] = field(default_factory=list) # (unit, daemon), active ones
|
||||
timesync: dict[str, str] = field(default_factory=dict)
|
||||
chronyc: str = ""
|
||||
chrony: list[ConfigFile] = field(default_factory=list)
|
||||
ntpd: ConfigFile | None = None
|
||||
openntpd: ConfigFile | None = None
|
||||
|
||||
@property
|
||||
def daemon(self) -> str | None:
|
||||
return self.active[0][1] if self.active else None
|
||||
|
||||
@property
|
||||
def unit(self) -> str | None:
|
||||
return self.active[0][0] if self.active else None
|
||||
|
||||
|
||||
def _first_file(kind: str, paths: tuple[str, ...]) -> str:
|
||||
candidates = " ".join(shlex.quote(p) for p in paths)
|
||||
return (
|
||||
f'for c in {candidates}; do [ -f "$c" ] && '
|
||||
f'{{ printf \'@@ts {kind} %s\\n\' "$c"; cat -- "$c"; echo; break; }}; done'
|
||||
)
|
||||
|
||||
|
||||
def reading_command(paths: ReadPaths) -> str:
|
||||
"""The command that prints the reading; ``sh`` runs it, whatever the login shell."""
|
||||
active = "\n".join(
|
||||
f"printf '%s %s %s\\n' {shlex.quote(unit)} {shlex.quote(daemon)} "
|
||||
f'"$(systemctl is-active {shlex.quote(unit + ".service")} 2>/dev/null)"'
|
||||
for unit, daemon in paths.units
|
||||
)
|
||||
chrony = " ".join(shlex.quote(p) for p in paths.chrony_configs)
|
||||
script = "\n".join(
|
||||
[
|
||||
"echo '@@ts timedatectl'",
|
||||
"timedatectl show 2>/dev/null",
|
||||
"echo '@@ts zone'",
|
||||
f"{{ {paths.time_zone_sh}; }}",
|
||||
"echo '@@ts active'",
|
||||
active,
|
||||
"echo '@@ts timesync'",
|
||||
"timedatectl show-timesync 2>/dev/null",
|
||||
"echo '@@ts chronyc'",
|
||||
"chronyc -n sources 2>/dev/null",
|
||||
f'for c in {chrony}; do [ -f "$c" ] || continue',
|
||||
'printf \'@@ts chrony 0 main %s\\n\' "$c"; cat -- "$c"; echo',
|
||||
_CHRONY_FOLLOW,
|
||||
"break; done",
|
||||
_first_file("ntpd", paths.ntpd_configs),
|
||||
_first_file("openntpd", paths.openntpd_configs),
|
||||
"echo '@@ts end'",
|
||||
]
|
||||
)
|
||||
return f"sh -c {shlex.quote(script)}"
|
||||
|
||||
|
||||
def parse_key_values(text: str) -> dict[str, str]:
|
||||
"""``Key=value`` lines (``timedatectl show``, ``show-timesync``)."""
|
||||
values: dict[str, str] = {}
|
||||
for line in text.splitlines():
|
||||
key, sep, value = line.partition("=")
|
||||
if sep and key.strip():
|
||||
values[key.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
def _sections(text: str) -> list[tuple[list[str], list[str]]]:
|
||||
sections: list[tuple[list[str], list[str]]] = []
|
||||
for line in text.splitlines():
|
||||
if line.startswith(_MARK):
|
||||
sections.append((line[len(_MARK) :].split(maxsplit=3), []))
|
||||
elif sections:
|
||||
sections[-1][1].append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _active(lines: list[str]) -> list[tuple[str, str]]:
|
||||
rows = [line.split() for line in lines]
|
||||
return [(r[0], r[1]) for r in rows if len(r) == 3 and r[2] == "active"]
|
||||
|
||||
|
||||
def _take(reading: Reading, header: list[str], lines: list[str]) -> None:
|
||||
name, text = header[0], "\n".join(lines)
|
||||
if name == "chrony" and len(header) == 4:
|
||||
reading.chrony.append(ConfigFile(header[3], header[2], int(header[1]), lines))
|
||||
elif name in ("ntpd", "openntpd") and len(header) == 2:
|
||||
setattr(reading, name, ConfigFile(header[1], name, 0, lines))
|
||||
else:
|
||||
simple = {
|
||||
"timedatectl": ("timedatectl", parse_key_values(text)),
|
||||
"zone": ("zone_files", lines),
|
||||
"active": ("active", _active(lines)),
|
||||
"timesync": ("timesync", parse_key_values(text)),
|
||||
"chronyc": ("chronyc", text),
|
||||
}
|
||||
if name in simple:
|
||||
setattr(reading, *simple[name])
|
||||
|
||||
|
||||
def parse_reading(text: str) -> Reading:
|
||||
"""The reading's sections. :raises ValueError: for a reading cut short."""
|
||||
sections = _sections(text)
|
||||
if not sections or sections[-1][0] != ["end"]:
|
||||
raise ValueError("the time sync reading was cut short")
|
||||
reading = Reading()
|
||||
for header, lines in sections:
|
||||
_take(reading, header, lines)
|
||||
return reading
|
||||
|
||||
|
||||
def _source_name(rest: str) -> str | None:
|
||||
"""The server in what follows ``server``/``pool``/``peer``: ntpd puts ``-4`` first."""
|
||||
return next((word for word in rest.split() if not word.startswith("-")), None)
|
||||
|
||||
|
||||
def in_dhcp_dir(f: ConfigFile, dhcp_dirs: tuple[str, ...]) -> bool:
|
||||
"""Whether *f* is a sources file a DHCP client wrote to one of *dhcp_dirs*."""
|
||||
if f.kind != "sourcedir":
|
||||
return False
|
||||
directory = posixpath.normpath(posixpath.dirname(f.path))
|
||||
return directory in {posixpath.normpath(d) for d in dhcp_dirs}
|
||||
|
||||
|
||||
def _named_on(files: list[ConfigFile], number: int) -> list[ConfigFile]:
|
||||
"""The files the main configuration's line *number* reads."""
|
||||
return [f for f in files if f.at == number and f.kind != "main"]
|
||||
|
||||
|
||||
def _read_order(files: list[ConfigFile], dhcp_dirs: tuple[str, ...]) -> list[tuple[bool, str]]:
|
||||
"""Every line chrony reads, in its order -- each file in place of the line naming
|
||||
it -- and whether a DHCP client wrote it."""
|
||||
main = next((f for f in files if f.kind == "main"), None)
|
||||
if main is None:
|
||||
return []
|
||||
found: list[tuple[bool, str]] = []
|
||||
for number, line in enumerate(main.lines, start=1):
|
||||
found.append((False, line))
|
||||
for included in _named_on(files, number):
|
||||
dhcp = in_dhcp_dir(included, dhcp_dirs)
|
||||
found.extend((dhcp, text) for text in included.lines)
|
||||
return found
|
||||
|
||||
|
||||
def chrony_servers(files: list[ConfigFile], dhcp_dirs: tuple[str, ...] = ()) -> list[str]:
|
||||
"""chrony's configured sources in the order it reads them; not those in *dhcp_dirs*."""
|
||||
return _sources([line for dhcp, line in _read_order(files, dhcp_dirs) if not dhcp])
|
||||
|
||||
|
||||
def chrony_dhcp_servers(files: list[ConfigFile], dhcp_dirs: tuple[str, ...]) -> list[str]:
|
||||
"""The sources chrony reads from the DHCP client's files in *dhcp_dirs*, in its order.
|
||||
|
||||
A ``sourcedir`` chrony does not read (commented out) prints no files: nothing then.
|
||||
"""
|
||||
return _sources([line for dhcp, line in _read_order(files, dhcp_dirs) if dhcp])
|
||||
|
||||
|
||||
def _sources(lines: list[str]) -> list[str]:
|
||||
names = []
|
||||
for line in lines:
|
||||
match = SOURCE_LINE.match(line)
|
||||
if match and (name := _source_name(match[2])):
|
||||
names.append(name)
|
||||
return names
|
||||
|
||||
|
||||
def ntpd_servers(lines: list[str]) -> list[str]:
|
||||
"""ntpd's servers, pools and peers; reference clocks are not servers."""
|
||||
return [name for name in _sources(lines) if not name.startswith(_REFCLOCK)]
|
||||
|
||||
|
||||
def openntpd_servers(lines: list[str]) -> list[str]:
|
||||
"""OpenNTPD's ``server`` and ``servers``; ``constraint`` and ``sensor`` are no sources."""
|
||||
return [m[2] for line in lines if (m := _OPENNTPD_SOURCE.match(line))]
|
||||
|
||||
|
||||
def _listed(values: dict[str, str], *keys: str) -> list[str]:
|
||||
found: list[str] = []
|
||||
for key in keys:
|
||||
for server in values.get(key, "").split():
|
||||
if server not in found:
|
||||
found.append(server)
|
||||
return found
|
||||
|
||||
|
||||
def timesyncd_servers(values: dict[str, str]) -> list[str]:
|
||||
"""systemd-timesyncd's configured servers, runtime then system; the fallback only
|
||||
while it has no other server, a link's included. A link's servers are not among
|
||||
them: :func:`timesyncd_link_servers`."""
|
||||
configured = _listed(values, "RuntimeNTPServers", "SystemNTPServers")
|
||||
if configured or timesyncd_link_servers(values):
|
||||
return configured
|
||||
return _listed(values, "FallbackNTPServers")
|
||||
|
||||
|
||||
def timesyncd_link_servers(values: dict[str, str]) -> list[str]:
|
||||
"""The servers network links gave systemd-timesyncd: systemd-networkd's, from a DHCP
|
||||
lease (option 42) or a ``.network`` file's ``NTP=`` -- the reading cannot tell those
|
||||
apart and counts them as DHCP's."""
|
||||
return _listed(values, "LinkNTPServers")
|
||||
|
||||
|
||||
def chrony_synchronized(sources: str) -> bool | None:
|
||||
"""Whether chronyd has selected a source (``^*``); None for no answer from chronyc."""
|
||||
rows = [line for line in sources.splitlines() if line[:1] in ("^", "=", "#")]
|
||||
if not rows:
|
||||
return None
|
||||
return any(line[1:2] == "*" for line in rows)
|
||||
|
||||
|
||||
def _zone_name(value: str) -> str | None:
|
||||
value = value.strip()
|
||||
if "zoneinfo/" in value:
|
||||
value = value.split("zoneinfo/", 1)[1]
|
||||
for prefix in ("posix/", "right/"):
|
||||
value = value.removeprefix(prefix)
|
||||
return value if _ZONE_NAME.fullmatch(value) else None
|
||||
|
||||
|
||||
def _time_zone(reading: Reading) -> str | None:
|
||||
named = reading.timedatectl.get("Timezone", "")
|
||||
if named and named != "n/a":
|
||||
return _zone_name(named)
|
||||
return next((z for line in reading.zone_files if (z := _zone_name(line))), None)
|
||||
|
||||
|
||||
def _servers(reading: Reading, dhcp_dirs: tuple[str, ...]) -> list[str]:
|
||||
if reading.daemon == "chrony":
|
||||
return chrony_servers(reading.chrony, dhcp_dirs)
|
||||
if reading.daemon == "systemd-timesyncd":
|
||||
return timesyncd_servers(reading.timesync)
|
||||
if reading.daemon == "ntpd" and reading.ntpd is not None:
|
||||
return ntpd_servers(reading.ntpd.lines)
|
||||
if reading.daemon == "openntpd" and reading.openntpd is not None:
|
||||
return openntpd_servers(reading.openntpd.lines)
|
||||
return []
|
||||
|
||||
|
||||
def _dhcp_servers(reading: Reading, dhcp_dirs: tuple[str, ...]) -> list[str] | None:
|
||||
"""What DHCP brought: chrony's and timesyncd's; None where ntpd or OpenNTPD runs,
|
||||
whose DHCP hooks keep a configuration of their own that is not read."""
|
||||
if reading.daemon == "chrony":
|
||||
return chrony_dhcp_servers(reading.chrony, dhcp_dirs)
|
||||
if reading.daemon == "systemd-timesyncd":
|
||||
return timesyncd_link_servers(reading.timesync)
|
||||
if reading.daemon is None:
|
||||
return []
|
||||
return None
|
||||
|
||||
|
||||
def _synchronized(reading: Reading) -> bool | None:
|
||||
if reading.daemon == "chrony":
|
||||
chrony = chrony_synchronized(reading.chronyc)
|
||||
if chrony is not None:
|
||||
return chrony
|
||||
return {"yes": True, "no": False}.get(reading.timedatectl.get("NTPSynchronized", ""))
|
||||
|
||||
|
||||
def time_sync_of(reading: Reading, dhcp_dirs: tuple[str, ...] = CHRONY_DHCP_DIRS) -> TimeSyncDict:
|
||||
"""What a reading says, as ``get_time_sync`` returns it; *dhcp_dirs* are the DHCP
|
||||
client's ``sourcedir`` of chrony."""
|
||||
return {
|
||||
"ntp_servers": _servers(reading, dhcp_dirs),
|
||||
"timezone": _time_zone(reading),
|
||||
"synchronized": _synchronized(reading),
|
||||
"daemon": reading.daemon,
|
||||
"dhcp_ntp_servers": _dhcp_servers(reading, dhcp_dirs),
|
||||
}
|
||||
|
||||
|
||||
def parse_time_sync(text: str, dhcp_dirs: tuple[str, ...] = CHRONY_DHCP_DIRS) -> TimeSyncDict:
|
||||
"""The reading's output as ``get_time_sync`` returns it.
|
||||
|
||||
:raises ValueError: for a reading cut short.
|
||||
"""
|
||||
return time_sync_of(parse_reading(text), dhcp_dirs)
|
||||
@@ -1,35 +1,43 @@
|
||||
"""Shared SNMP metric collection helpers for UCD-MIB and IF-MIB."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from typing import Awaitable, Callable, Dict, Optional
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
# ── UCD-MIB OIDs ──────────────────────────────────────────────────────────────
|
||||
OID_SYS_UPTIME = "1.3.6.1.2.1.25.1.1.0" # hrSystemUptime (centiseconds)
|
||||
OID_CPU_IDLE = "1.3.6.1.4.1.2021.11.11.0" # UCD ssCpuIdle (%)
|
||||
OID_MEM_TOTAL = "1.3.6.1.4.1.2021.4.5.0" # memTotalReal (kB)
|
||||
OID_MEM_FREE = "1.3.6.1.4.1.2021.4.6.0" # memAvailReal (kB)
|
||||
OID_MEM_BUFFER = "1.3.6.1.4.1.2021.4.14.0" # memBuffer (kB)
|
||||
OID_MEM_CACHED = "1.3.6.1.4.1.2021.4.15.0" # memCached (kB)
|
||||
OID_SWAP_TOTAL = "1.3.6.1.4.1.2021.4.3.0" # memTotalSwap (kB)
|
||||
OID_SWAP_AVAIL = "1.3.6.1.4.1.2021.4.4.0" # memAvailSwap (kB)
|
||||
OID_LOAD_1 = "1.3.6.1.4.1.2021.10.1.3.1" # laLoad 1-min
|
||||
OID_LOAD_5 = "1.3.6.1.4.1.2021.10.1.3.2" # laLoad 5-min
|
||||
OID_LOAD_15 = "1.3.6.1.4.1.2021.10.1.3.3" # laLoad 15-min
|
||||
OID_SYS_UPTIME = "1.3.6.1.2.1.25.1.1.0" # hrSystemUptime (centiseconds)
|
||||
OID_CPU_IDLE = "1.3.6.1.4.1.2021.11.11.0" # UCD ssCpuIdle (%)
|
||||
OID_MEM_TOTAL = "1.3.6.1.4.1.2021.4.5.0" # memTotalReal (kB)
|
||||
OID_MEM_FREE = "1.3.6.1.4.1.2021.4.6.0" # memAvailReal (kB)
|
||||
OID_MEM_BUFFER = "1.3.6.1.4.1.2021.4.14.0" # memBuffer (kB)
|
||||
OID_MEM_CACHED = "1.3.6.1.4.1.2021.4.15.0" # memCached (kB)
|
||||
OID_SWAP_TOTAL = "1.3.6.1.4.1.2021.4.3.0" # memTotalSwap (kB)
|
||||
OID_SWAP_AVAIL = "1.3.6.1.4.1.2021.4.4.0" # memAvailSwap (kB)
|
||||
OID_LOAD_1 = "1.3.6.1.4.1.2021.10.1.3.1" # laLoad 1-min
|
||||
OID_LOAD_5 = "1.3.6.1.4.1.2021.10.1.3.2" # laLoad 5-min
|
||||
OID_LOAD_15 = "1.3.6.1.4.1.2021.10.1.3.3" # laLoad 15-min
|
||||
|
||||
# ── IF-MIB OIDs ───────────────────────────────────────────────────────────────
|
||||
OID_IF_DESCR = "1.3.6.1.2.1.2.2.1.2"
|
||||
OID_IF_SPEED = "1.3.6.1.2.1.2.2.1.5"
|
||||
OID_IF_IN_OCT = "1.3.6.1.2.1.2.2.1.10"
|
||||
OID_IF_DESCR = "1.3.6.1.2.1.2.2.1.2"
|
||||
OID_IF_SPEED = "1.3.6.1.2.1.2.2.1.5"
|
||||
OID_IF_IN_OCT = "1.3.6.1.2.1.2.2.1.10"
|
||||
OID_IF_OUT_OCT = "1.3.6.1.2.1.2.2.1.16"
|
||||
OID_IF_IN_ERR = "1.3.6.1.2.1.2.2.1.14"
|
||||
OID_IF_IN_ERR = "1.3.6.1.2.1.2.2.1.14"
|
||||
OID_IF_OUT_ERR = "1.3.6.1.2.1.2.2.1.20"
|
||||
# ifXTable: 64-bit octets and Mbps. The 32-bit counters wrap every ~34 s at
|
||||
# 1 Gbit/s and ifSpeed stops at 4294 Mbps; an agent without ifXTable (SNMPv1)
|
||||
# falls back to them.
|
||||
OID_IF_HC_IN_OCT = "1.3.6.1.2.1.31.1.1.1.6"
|
||||
OID_IF_HC_OUT_OCT = "1.3.6.1.2.1.31.1.1.1.10"
|
||||
OID_IF_HIGH_SPEED = "1.3.6.1.2.1.31.1.1.1.15"
|
||||
|
||||
IF_SKIP_DEFAULT = re.compile(r'^(lo|sit\d|tun\d|docker|veth|br-|virbr)', re.IGNORECASE)
|
||||
IF_SKIP_DEFAULT = re.compile(r"^(lo|sit\d|tun\d|docker|veth|br-|virbr)", re.IGNORECASE)
|
||||
|
||||
SnmpGetFn = Callable[[str], Awaitable[Optional[str]]]
|
||||
SnmpWalkFn = Callable[[str], Awaitable[Dict[str, str]]]
|
||||
SnmpGetFn = Callable[[str], Awaitable[str | None]]
|
||||
SnmpWalkFn = Callable[[str], Awaitable[dict[str, str]]]
|
||||
|
||||
|
||||
def ticks_to_seconds(raw: str | None) -> int | None:
|
||||
@@ -42,36 +50,43 @@ def ticks_to_seconds(raw: str | None) -> int | None:
|
||||
|
||||
|
||||
def build_if_metrics(
|
||||
metrics: dict,
|
||||
descr: Dict[str, str],
|
||||
speed: Dict[str, str],
|
||||
in_oct: Dict[str, str],
|
||||
out_oct: Dict[str, str],
|
||||
in_err: Dict[str, str],
|
||||
out_err: Dict[str, str],
|
||||
metrics: dict[str, Any],
|
||||
descr: dict[str, str],
|
||||
speed: dict[str, str],
|
||||
in_oct: dict[str, str],
|
||||
out_oct: dict[str, str],
|
||||
in_err: dict[str, str],
|
||||
out_err: dict[str, str],
|
||||
*,
|
||||
if_skip: re.Pattern | None = None,
|
||||
if_skip: re.Pattern[str] | None = None,
|
||||
tx_err_is_drop: bool = False,
|
||||
hc_in_oct: dict[str, str] | None = None,
|
||||
hc_out_oct: dict[str, str] | None = None,
|
||||
high_speed: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
if if_skip is None:
|
||||
if_skip = IF_SKIP_DEFAULT
|
||||
interfaces: dict = {}
|
||||
interfaces: dict[str, Any] = {}
|
||||
for idx, name in descr.items():
|
||||
if if_skip.match(name):
|
||||
continue
|
||||
iface: dict = {"name": name}
|
||||
iface: dict[str, Any] = {"name": name}
|
||||
try:
|
||||
iface["rx_bytes"] = int(in_oct.get(idx, 0) or 0)
|
||||
iface["tx_bytes"] = int(out_oct.get(idx, 0) or 0)
|
||||
iface["rx_errors"] = int(in_err.get(idx, 0) or 0)
|
||||
iface["rx_bytes"] = int((hc_in_oct or {}).get(idx) or in_oct.get(idx) or 0)
|
||||
iface["tx_bytes"] = int((hc_out_oct or {}).get(idx) or out_oct.get(idx) or 0)
|
||||
iface["rx_errors"] = int(in_err.get(idx, 0) or 0)
|
||||
tx_val = int(out_err.get(idx, 0) or 0)
|
||||
if tx_err_is_drop:
|
||||
iface["tx_errors"] = 0
|
||||
iface["tx_drops"] = tx_val
|
||||
iface["tx_drops"] = tx_val
|
||||
else:
|
||||
iface["tx_errors"] = tx_val
|
||||
high = (high_speed or {}).get(idx)
|
||||
spd = speed.get(idx)
|
||||
iface["speed_mbps"] = int(spd) // 1_000_000 if spd and int(spd) > 0 else 0
|
||||
if high and int(high) > 0:
|
||||
iface["speed_mbps"] = int(high)
|
||||
else:
|
||||
iface["speed_mbps"] = int(spd) // 1_000_000 if spd and int(spd) > 0 else 0
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
interfaces[name] = iface
|
||||
@@ -84,15 +99,35 @@ async def collect_ucd_metrics(
|
||||
snmp_walk: SnmpWalkFn,
|
||||
*,
|
||||
tx_err_is_drop: bool = False,
|
||||
if_skip: re.Pattern | None = None,
|
||||
) -> dict:
|
||||
if_skip: re.Pattern[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Collect UCD-MIB system metrics + IF-MIB interface counters in parallel."""
|
||||
(
|
||||
uptime_raw, cpu_idle_raw,
|
||||
mem_total_raw, mem_free_raw, mem_buf_raw, mem_cache_raw,
|
||||
swap_total_raw, swap_avail_raw,
|
||||
load1_raw, load5_raw, load15_raw,
|
||||
), (descr, speed, in_oct, out_oct, in_err, out_err) = await asyncio.gather(
|
||||
(
|
||||
uptime_raw,
|
||||
cpu_idle_raw,
|
||||
mem_total_raw,
|
||||
mem_free_raw,
|
||||
mem_buf_raw,
|
||||
mem_cache_raw,
|
||||
swap_total_raw,
|
||||
swap_avail_raw,
|
||||
load1_raw,
|
||||
load5_raw,
|
||||
load15_raw,
|
||||
),
|
||||
(
|
||||
descr,
|
||||
speed,
|
||||
in_oct,
|
||||
out_oct,
|
||||
in_err,
|
||||
out_err,
|
||||
hc_in_oct,
|
||||
hc_out_oct,
|
||||
high_speed,
|
||||
),
|
||||
) = await asyncio.gather(
|
||||
asyncio.gather(
|
||||
snmp_get(OID_SYS_UPTIME),
|
||||
snmp_get(OID_CPU_IDLE),
|
||||
@@ -113,10 +148,13 @@ async def collect_ucd_metrics(
|
||||
snmp_walk(OID_IF_OUT_OCT),
|
||||
snmp_walk(OID_IF_IN_ERR),
|
||||
snmp_walk(OID_IF_OUT_ERR),
|
||||
snmp_walk(OID_IF_HC_IN_OCT),
|
||||
snmp_walk(OID_IF_HC_OUT_OCT),
|
||||
snmp_walk(OID_IF_HIGH_SPEED),
|
||||
),
|
||||
)
|
||||
|
||||
metrics: dict = {}
|
||||
metrics: dict[str, Any] = {}
|
||||
|
||||
secs = ticks_to_seconds(uptime_raw)
|
||||
if secs is not None:
|
||||
@@ -131,14 +169,14 @@ async def collect_ucd_metrics(
|
||||
if mem_total_raw and mem_free_raw:
|
||||
try:
|
||||
total_kb = int(mem_total_raw)
|
||||
free_kb = int(mem_free_raw)
|
||||
buf_kb = int(mem_buf_raw) if mem_buf_raw else 0
|
||||
free_kb = int(mem_free_raw)
|
||||
buf_kb = int(mem_buf_raw) if mem_buf_raw else 0
|
||||
cache_kb = int(mem_cache_raw) if mem_cache_raw else 0
|
||||
used_kb = max(0, total_kb - free_kb - buf_kb - cache_kb)
|
||||
used_kb = max(0, total_kb - free_kb - buf_kb - cache_kb)
|
||||
metrics["memory_total_bytes"] = total_kb * 1024
|
||||
metrics["memory_used_bytes"] = used_kb * 1024
|
||||
metrics["memory_percent"] = round(used_kb / total_kb * 100, 1) if total_kb else 0.0
|
||||
metrics["memory_free_bytes"] = free_kb * 1024
|
||||
metrics["memory_used_bytes"] = used_kb * 1024
|
||||
metrics["memory_percent"] = round(used_kb / total_kb * 100, 1) if total_kb else 0.0
|
||||
metrics["memory_free_bytes"] = free_kb * 1024
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
@@ -146,10 +184,10 @@ async def collect_ucd_metrics(
|
||||
try:
|
||||
stotal = int(swap_total_raw)
|
||||
savail = int(swap_avail_raw)
|
||||
sused = stotal - savail
|
||||
sused = stotal - savail
|
||||
metrics["swap_total_bytes"] = stotal * 1024
|
||||
metrics["swap_used_bytes"] = sused * 1024
|
||||
metrics["swap_percent"] = round(sused / stotal * 100, 1) if stotal else 0.0
|
||||
metrics["swap_used_bytes"] = sused * 1024
|
||||
metrics["swap_percent"] = round(sused / stotal * 100, 1) if stotal else 0.0
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
@@ -160,6 +198,18 @@ async def collect_ucd_metrics(
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
build_if_metrics(metrics, descr, speed, in_oct, out_oct, in_err, out_err,
|
||||
if_skip=if_skip, tx_err_is_drop=tx_err_is_drop)
|
||||
build_if_metrics(
|
||||
metrics,
|
||||
descr,
|
||||
speed,
|
||||
in_oct,
|
||||
out_oct,
|
||||
in_err,
|
||||
out_err,
|
||||
if_skip=if_skip,
|
||||
tx_err_is_drop=tx_err_is_drop,
|
||||
hc_in_oct=hc_in_oct,
|
||||
hc_out_oct=hc_out_oct,
|
||||
high_speed=high_speed,
|
||||
)
|
||||
return metrics
|
||||
+199
-453
@@ -10,30 +10,34 @@ Usage::
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
from napalm_device_types._ucd_metrics import IF_SKIP_DEFAULT, collect_ucd_metrics
|
||||
from napalm_device_types.health_metrics import HealthMetricsMixin
|
||||
from napalm_device_types.interface_filter import InterfaceFilterMixin
|
||||
from napalm_device_types.mac_acl import MacAclMixin
|
||||
from napalm_device_types.models import (
|
||||
ChannelScanEntryDict,
|
||||
Dot1XConfigDict,
|
||||
FastTransitionConfigDict,
|
||||
HealthMetricsDict,
|
||||
MACACLDict,
|
||||
MeshConfigDict,
|
||||
MeshPeerDict,
|
||||
PackageDict,
|
||||
RadioStatusDict,
|
||||
ServiceDict,
|
||||
SSIDBridgeDict,
|
||||
SSIDDict,
|
||||
UpdateDict,
|
||||
WirelessClientDict,
|
||||
WirelessConfigDict,
|
||||
)
|
||||
from napalm_device_types.packages import PackageManagementMixin
|
||||
from napalm_device_types.services import ServiceControlMixin
|
||||
from napalm_device_types.updates import UpdateMixin
|
||||
|
||||
|
||||
class AccessPointDriver(DeviceTypeDriver):
|
||||
TYPE_LABEL: str = "Access Point"
|
||||
class AccessPointDriver(
|
||||
MacAclMixin,
|
||||
UpdateMixin,
|
||||
ServiceControlMixin,
|
||||
PackageManagementMixin,
|
||||
HealthMetricsMixin,
|
||||
InterfaceFilterMixin,
|
||||
DeviceTypeDriver,
|
||||
):
|
||||
"""
|
||||
Abstract intermediate driver for wireless access points.
|
||||
|
||||
@@ -41,33 +45,11 @@ class AccessPointDriver(DeviceTypeDriver):
|
||||
access-point-specific operations that concrete drivers must implement.
|
||||
"""
|
||||
|
||||
# Interfaces that carry no operational meaning on an access point and
|
||||
# should be excluded from get_interfaces() / get_facts() interface_list.
|
||||
_EXCLUDED_INTERFACES: frozenset = frozenset({"lo"})
|
||||
|
||||
# Interface name *prefixes* to exclude (e.g. Linux phy* are raw radio
|
||||
# devices and have no IP/Ethernet significance at the AP level).
|
||||
_EXCLUDED_INTERFACE_PREFIXES: tuple = ("phy",)
|
||||
|
||||
_SNMP_SKIP_IF = IF_SKIP_DEFAULT
|
||||
_SNMP_TX_ERR_IS_DROP: bool = False
|
||||
|
||||
@classmethod
|
||||
async def get_health_metrics(cls, snmp_get, snmp_walk) -> HealthMetricsDict:
|
||||
return await collect_ucd_metrics(
|
||||
snmp_get, snmp_walk,
|
||||
tx_err_is_drop=cls._SNMP_TX_ERR_IS_DROP,
|
||||
if_skip=cls._SNMP_SKIP_IF,
|
||||
)
|
||||
|
||||
def _filter_interfaces(self, interfaces: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Remove loopback and radio-device (phy*) interfaces from an interface dict."""
|
||||
return {
|
||||
name: data
|
||||
for name, data in interfaces.items()
|
||||
if name not in self._EXCLUDED_INTERFACES
|
||||
and not name.startswith(self._EXCLUDED_INTERFACE_PREFIXES)
|
||||
}
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "access_point"
|
||||
TYPE_LABEL: str = "Access Point"
|
||||
|
||||
# AP-specific methods (get_wireless_clients, get_ssids, get_radio_status,
|
||||
# get_interfaces, get_vlans, …) are intentionally NOT defined here.
|
||||
@@ -77,451 +59,215 @@ class AccessPointDriver(DeviceTypeDriver):
|
||||
# all standard NAPALM methods, so AccessPointDriver must come LAST to avoid
|
||||
# shadowing the mixin implementations.
|
||||
|
||||
def get_wireless_config(self) -> WirelessConfigDict:
|
||||
"""
|
||||
Returns global wireless configuration parameters that apply across
|
||||
all radios and SSIDs.
|
||||
if TYPE_CHECKING:
|
||||
|
||||
* country_code (string) - ISO 3166-1 alpha-2 country code (e.g. ``"DE"``)
|
||||
* regulatory_domain (string) - regulatory domain string (e.g. ``"ETSI"``)
|
||||
* beacon_interval (int) - beacon interval in TUs (default 100)
|
||||
* dtim_period (int) - DTIM period (default 2)
|
||||
* rts_threshold (int) - RTS/CTS threshold in bytes (2347 = disabled)
|
||||
* fragmentation_threshold (int) - fragmentation threshold in bytes
|
||||
* short_preamble (bool) - whether short preamble is enabled
|
||||
* wmm_enabled (bool) - whether WMM/QoS is enabled
|
||||
def get_wireless_config(self) -> WirelessConfigDict:
|
||||
"""
|
||||
Returns global wireless configuration parameters that apply across
|
||||
all radios and SSIDs.
|
||||
|
||||
Example::
|
||||
* country_code (string) - ISO 3166-1 alpha-2 country code (e.g. ``"DE"``)
|
||||
* regulatory_domain (string) - regulatory domain string (e.g. ``"ETSI"``)
|
||||
* beacon_interval (int) - beacon interval in TUs (default 100)
|
||||
* dtim_period (int) - DTIM period (default 2)
|
||||
* rts_threshold (int) - RTS/CTS threshold in bytes (2347 = disabled)
|
||||
* fragmentation_threshold (int) - fragmentation threshold in bytes
|
||||
* short_preamble (bool) - whether short preamble is enabled
|
||||
* wmm_enabled (bool) - whether WMM/QoS is enabled
|
||||
|
||||
{
|
||||
"country_code": "DE",
|
||||
"regulatory_domain": "ETSI",
|
||||
"beacon_interval": 100,
|
||||
"dtim_period": 2,
|
||||
"rts_threshold": 2347,
|
||||
"fragmentation_threshold": 2346,
|
||||
"short_preamble": True,
|
||||
"wmm_enabled": True,
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
Example::
|
||||
|
||||
def get_fast_transition_config(self) -> Dict[str, FastTransitionConfigDict]:
|
||||
"""
|
||||
Returns the 802.11r Fast BSS Transition (FT) configuration per SSID.
|
||||
|
||||
Keys are SSID names. Each value contains:
|
||||
|
||||
* enabled (bool) - whether FT is active on this SSID
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* mobility_domain (string) - 4-hex-digit Mobility Domain ID (MDID)
|
||||
* reassociation_deadline (int) - FT reassociation deadline in TUs
|
||||
* r0_key_lifetime (int) - PMK-R0 key lifetime in minutes
|
||||
* r1_key_holder (string) - R1 Key Holder identifier (MAC-like string)
|
||||
* pmk_r1_push (bool) - whether PMK-R1 is proactively pushed to neighbours
|
||||
* over_ds (bool) - whether FT over DS (instead of FT over air) is used
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"enabled": True,
|
||||
"ssid": "CorpWiFi",
|
||||
"mobility_domain": "a1b2",
|
||||
"reassociation_deadline": 1000,
|
||||
"r0_key_lifetime": 10000,
|
||||
"r1_key_holder": "00:11:22:33:44:55",
|
||||
"pmk_r1_push": True,
|
||||
"over_ds": False,
|
||||
}
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_mesh_config(self) -> Dict[str, MeshConfigDict]:
|
||||
"""
|
||||
Returns the 802.11s mesh configuration per mesh interface.
|
||||
|
||||
Keys are mesh interface names (e.g. ``"mesh0"``). Each value contains:
|
||||
|
||||
* enabled (bool) - whether the mesh interface is active
|
||||
* radio (string) - underlying radio (e.g. ``"radio0"``)
|
||||
* mesh_id (string) - 802.11s Mesh ID (analogous to SSID)
|
||||
* path_metric (string) - path selection metric, e.g. ``"airtime"`` or ``"hopcount"``
|
||||
* gate_announcements (bool) - whether gate announcements (GANN) are sent
|
||||
* is_gate (bool) - whether this node acts as a mesh gate to the DS
|
||||
* encryption (string) - e.g. ``"SAE"``, ``"open"``
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"mesh0": {
|
||||
"enabled": True,
|
||||
"radio": "radio1",
|
||||
"mesh_id": "office-mesh",
|
||||
"path_metric": "airtime",
|
||||
"gate_announcements": True,
|
||||
"is_gate": True,
|
||||
"encryption": "SAE",
|
||||
}
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_mesh_peers(self) -> List[MeshPeerDict]:
|
||||
"""
|
||||
Returns a list of currently active 802.11s mesh peers.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* mac (string) - peer MAC address
|
||||
* radio (string) - radio on which the peering was established
|
||||
* signal (int) - received signal strength in dBm
|
||||
* tx_rate (float) - TX bitrate to peer in Mbit/s
|
||||
* rx_rate (float) - RX bitrate from peer in Mbit/s
|
||||
* uptime (int) - peering duration in seconds
|
||||
* hop_count (int) - number of hops to the mesh gate (0 = this node is the gate)
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"mac": "AA:BB:CC:DD:EE:01",
|
||||
"radio": "radio1",
|
||||
"signal": -58,
|
||||
"tx_rate": 300.0,
|
||||
"rx_rate": 270.0,
|
||||
"uptime": 7200,
|
||||
"hop_count": 1,
|
||||
"country_code": "DE",
|
||||
"regulatory_domain": "ETSI",
|
||||
"beacon_interval": 100,
|
||||
"dtim_period": 2,
|
||||
"rts_threshold": 2347,
|
||||
"fragmentation_threshold": 2346,
|
||||
"short_preamble": True,
|
||||
"wmm_enabled": True,
|
||||
}
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"""
|
||||
...
|
||||
|
||||
def get_ssid_bridge_config(self) -> Dict[str, SSIDBridgeDict]:
|
||||
"""
|
||||
Returns the Layer-2 bridging configuration for each SSID, i.e. which
|
||||
bridge interface and VLAN each SSID is mapped to.
|
||||
def get_fast_transition_config(self) -> dict[str, FastTransitionConfigDict]:
|
||||
"""
|
||||
Returns the 802.11r Fast BSS Transition (FT) configuration per SSID.
|
||||
|
||||
Keys are SSID names. Each value contains:
|
||||
Keys are SSID names. Each value contains:
|
||||
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* bridge (string) - bridge interface the VAP is attached to (e.g. ``"br-lan"``, ``"br-guest"``)
|
||||
* vlan_id (int) - 802.1Q VLAN ID (0 = untagged / no VLAN separation)
|
||||
* tagged (bool) - whether traffic is 802.1Q-tagged on the uplink port
|
||||
* client_isolation (bool) - whether clients on this SSID are isolated from each other
|
||||
* enabled (bool) - whether FT is active on this SSID
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* mobility_domain (string) - 4-hex-digit Mobility Domain ID (MDID)
|
||||
* reassociation_deadline (int) - FT reassociation deadline in TUs
|
||||
* r0_key_lifetime (int) - PMK-R0 key lifetime in minutes
|
||||
* r1_key_holder (string) - R1 Key Holder identifier (MAC-like string)
|
||||
* pmk_r1_push (bool) - whether PMK-R1 is proactively pushed to neighbours
|
||||
* over_ds (bool) - whether FT over DS (instead of FT over air) is used
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"ssid": "CorpWiFi",
|
||||
"bridge": "br-corp",
|
||||
"vlan_id": 10,
|
||||
"tagged": True,
|
||||
"client_isolation": False,
|
||||
},
|
||||
"GuestNet": {
|
||||
"ssid": "GuestNet",
|
||||
"bridge": "br-guest",
|
||||
"vlan_id": 20,
|
||||
"tagged": True,
|
||||
"client_isolation": True,
|
||||
},
|
||||
"IoT": {
|
||||
"ssid": "IoT",
|
||||
"bridge": "br-iot",
|
||||
"vlan_id": 30,
|
||||
"tagged": True,
|
||||
"client_isolation": True,
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"enabled": True,
|
||||
"ssid": "CorpWiFi",
|
||||
"mobility_domain": "a1b2",
|
||||
"reassociation_deadline": 1000,
|
||||
"r0_key_lifetime": 10000,
|
||||
"r1_key_holder": "00:11:22:33:44:55",
|
||||
"pmk_r1_push": True,
|
||||
"over_ds": False,
|
||||
}
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
def get_mac_acl(self) -> Dict[str, MACACLDict]:
|
||||
"""
|
||||
Returns the MAC-address-based access control lists configured per SSID.
|
||||
def get_mesh_config(self) -> dict[str, MeshConfigDict]:
|
||||
"""
|
||||
Returns the 802.11s mesh configuration per mesh interface.
|
||||
|
||||
Keys are SSID names. Each value contains:
|
||||
Keys are mesh interface names (e.g. ``"mesh0"``). Each value contains:
|
||||
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* policy (string) - ACL mode:
|
||||
* enabled (bool) - whether the mesh interface is active
|
||||
* radio (string) - underlying radio (e.g. ``"radio0"``)
|
||||
* mesh_id (string) - 802.11s Mesh ID (analogous to SSID)
|
||||
* path_metric (string) - path selection metric, e.g. ``"airtime"`` or ``"hopcount"``
|
||||
* gate_announcements (bool) - whether gate announcements (GANN) are sent
|
||||
* is_gate (bool) - whether this node acts as a mesh gate to the DS
|
||||
* encryption (string) - e.g. ``"SAE"``, ``"open"``
|
||||
|
||||
* ``"allow"`` – whitelist: only listed MACs may associate
|
||||
* ``"deny"`` – blacklist: listed MACs are blocked
|
||||
* ``"disabled"`` – no MAC filtering active
|
||||
Example::
|
||||
|
||||
* entries (list) - ACL entries, each with:
|
||||
{
|
||||
"mesh0": {
|
||||
"enabled": True,
|
||||
"radio": "radio1",
|
||||
"mesh_id": "office-mesh",
|
||||
"path_metric": "airtime",
|
||||
"gate_announcements": True,
|
||||
"is_gate": True,
|
||||
"encryption": "SAE",
|
||||
}
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
* mac (string) - MAC address (normalised, colon-separated)
|
||||
* action (string) - ``"allow"`` or ``"deny"``
|
||||
* description (string) - optional human-readable label
|
||||
def get_mesh_peers(self) -> list[MeshPeerDict]:
|
||||
"""
|
||||
Returns a list of currently active 802.11s mesh peers.
|
||||
|
||||
Example::
|
||||
Each entry contains:
|
||||
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"name": "CorpWiFi",
|
||||
"policy": "allow",
|
||||
"entries": [
|
||||
{"mac": "AA:BB:CC:DD:EE:01", "action": "allow", "description": "CEO-Laptop"},
|
||||
{"mac": "AA:BB:CC:DD:EE:02", "action": "allow", "description": "CFO-Laptop"},
|
||||
],
|
||||
},
|
||||
"GuestNet": {
|
||||
"name": "GuestNet",
|
||||
"policy": "deny",
|
||||
"entries": [
|
||||
{"mac": "DE:AD:BE:EF:00:01", "action": "deny", "description": "blocked device"},
|
||||
],
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
* mac (string) - peer MAC address
|
||||
* radio (string) - radio on which the peering was established
|
||||
* signal (int) - received signal strength in dBm
|
||||
* tx_rate (float) - TX bitrate to peer in Mbit/s
|
||||
* rx_rate (float) - RX bitrate from peer in Mbit/s
|
||||
* uptime (int) - peering duration in seconds
|
||||
* hop_count (int) - number of hops to the mesh gate (0 = this node is the gate)
|
||||
|
||||
def get_dot1x_config(self) -> Dict[str, Dot1XConfigDict]:
|
||||
"""
|
||||
Returns the 802.1X / WPA-Enterprise (RADIUS) configuration per SSID.
|
||||
Example::
|
||||
|
||||
Keys are SSID names. Each value contains:
|
||||
[
|
||||
{
|
||||
"mac": "AA:BB:CC:DD:EE:01",
|
||||
"radio": "radio1",
|
||||
"signal": -58,
|
||||
"tx_rate": 300.0,
|
||||
"rx_rate": 270.0,
|
||||
"uptime": 7200,
|
||||
"hop_count": 1,
|
||||
}
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
* enabled (bool) - whether 802.1X authentication is active on this SSID
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* auth_server (dict) - RADIUS authentication server:
|
||||
def get_ssid_bridge_config(self) -> dict[str, SSIDBridgeDict]:
|
||||
"""
|
||||
Returns the Layer-2 bridging configuration for each SSID, i.e. which
|
||||
bridge interface and VLAN each SSID is mapped to.
|
||||
|
||||
* host (string) - IP or FQDN of the RADIUS server
|
||||
* port (int) - UDP port (default 1812)
|
||||
* timeout (int) - request timeout in seconds
|
||||
* retries (int) - number of retransmissions
|
||||
Keys are SSID names. Each value contains:
|
||||
|
||||
* acct_server (dict or None) - RADIUS accounting server (same keys as auth_server,
|
||||
``None`` if accounting is not configured)
|
||||
* reauth_interval (int) - re-authentication interval in seconds (0 = disabled)
|
||||
* pmksa_caching (bool) - whether PMKSA caching (opportunistic key caching) is enabled
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* bridge (string) - bridge interface the VAP is attached to
|
||||
(e.g. ``"br-lan"``, ``"br-guest"``)
|
||||
* vlan_id (int) - 802.1Q VLAN ID (0 = untagged / no VLAN separation)
|
||||
* tagged (bool) - whether traffic is 802.1Q-tagged on the uplink port
|
||||
* client_isolation (bool) - whether clients on this SSID are isolated from each other
|
||||
|
||||
Note: The RADIUS shared secret is intentionally omitted from the return
|
||||
value for security reasons.
|
||||
Example::
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"enabled": True,
|
||||
"ssid": "CorpWiFi",
|
||||
"auth_server": {
|
||||
"host": "radius.corp.example",
|
||||
"port": 1812,
|
||||
"timeout": 5,
|
||||
"retries": 3,
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"ssid": "CorpWiFi",
|
||||
"bridge": "br-corp",
|
||||
"vlan_id": 10,
|
||||
"tagged": True,
|
||||
"client_isolation": False,
|
||||
},
|
||||
"acct_server": {
|
||||
"host": "radius.corp.example",
|
||||
"port": 1813,
|
||||
"timeout": 5,
|
||||
"retries": 3,
|
||||
"GuestNet": {
|
||||
"ssid": "GuestNet",
|
||||
"bridge": "br-guest",
|
||||
"vlan_id": 20,
|
||||
"tagged": True,
|
||||
"client_isolation": True,
|
||||
},
|
||||
"IoT": {
|
||||
"ssid": "IoT",
|
||||
"bridge": "br-iot",
|
||||
"vlan_id": 30,
|
||||
"tagged": True,
|
||||
"client_isolation": True,
|
||||
},
|
||||
"reauth_interval": 3600,
|
||||
"pmksa_caching": True,
|
||||
}
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"""
|
||||
...
|
||||
|
||||
def get_packages(self) -> List[PackageDict]:
|
||||
"""
|
||||
Returns all packages currently known to the device's package manager
|
||||
(e.g. ``opkg`` on OpenWrt, ``apk`` on Alpine-based APs).
|
||||
def get_dot1x_config(self) -> dict[str, Dot1XConfigDict]:
|
||||
"""
|
||||
Returns the 802.1X / WPA-Enterprise (RADIUS) configuration per SSID.
|
||||
|
||||
Each entry contains:
|
||||
Keys are SSID names. Each value contains:
|
||||
|
||||
* name (string) - package name
|
||||
* version (string) - installed or available version string
|
||||
* installed (bool) - ``True`` if the package is currently installed
|
||||
* description (string) - short package description
|
||||
* size (int) - package size in bytes (0 if unknown)
|
||||
* source (string) - repository / feed the package comes from
|
||||
* enabled (bool) - whether 802.1X authentication is active on this SSID
|
||||
* ssid (string) - SSID name (repeated for convenience)
|
||||
* auth_server (dict) - RADIUS authentication server:
|
||||
|
||||
Example::
|
||||
* host (string) - IP or FQDN of the RADIUS server
|
||||
* port (int) - UDP port (default 1812)
|
||||
* timeout (int) - request timeout in seconds
|
||||
* retries (int) - number of retransmissions
|
||||
|
||||
* acct_server (dict or None) - RADIUS accounting server (same keys as auth_server,
|
||||
``None`` if accounting is not configured)
|
||||
* reauth_interval (int) - re-authentication interval in seconds (0 = disabled)
|
||||
* pmksa_caching (bool) - whether PMKSA caching (opportunistic key caching) is enabled
|
||||
|
||||
Note: The RADIUS shared secret is intentionally omitted from the return
|
||||
value for security reasons.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "luci-app-statistics",
|
||||
"version": "git-24.001.00000-1",
|
||||
"installed": True,
|
||||
"description": "LuCI Statistics application",
|
||||
"size": 20480,
|
||||
"source": "openwrt/packages",
|
||||
},
|
||||
{
|
||||
"name": "collectd-mod-wireless",
|
||||
"version": "5.12.0-24",
|
||||
"installed": False,
|
||||
"description": "Wireless statistics plugin for collectd",
|
||||
"size": 8192,
|
||||
"source": "openwrt/packages",
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def install_package(self, name: str, version: str = "") -> None:
|
||||
"""
|
||||
Installs a package on the device.
|
||||
|
||||
The method blocks until the installation is complete. After it returns
|
||||
successfully the package is available for use without a reboot
|
||||
(where the underlying package manager supports this).
|
||||
|
||||
:param name: Package name as known to the package manager.
|
||||
:param version: Exact version to install. An empty string (default)
|
||||
installs the latest available version.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package name is unknown or the version does
|
||||
not exist in any configured feed.
|
||||
:raises RuntimeError: If the installation fails on the device side
|
||||
(e.g. dependency conflict, disk full).
|
||||
|
||||
Example::
|
||||
|
||||
driver.install_package("luci-app-statistics")
|
||||
driver.install_package("collectd", version="5.12.0-24")
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def remove_package(self, name: str) -> None:
|
||||
"""
|
||||
Removes an installed package from the device.
|
||||
|
||||
The method blocks until the removal is complete.
|
||||
|
||||
:param name: Package name to remove.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package is not currently installed.
|
||||
:raises RuntimeError: If the removal fails on the device side
|
||||
(e.g. other packages depend on it).
|
||||
|
||||
Example::
|
||||
|
||||
driver.remove_package("luci-app-statistics")
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_package_config(self, name: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Returns the current configuration of an installed package as a
|
||||
dictionary. The structure is package-specific.
|
||||
|
||||
:param name: Package name.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package is not installed.
|
||||
|
||||
Example::
|
||||
|
||||
driver.get_package_config("luci-app-statistics")
|
||||
# →
|
||||
{
|
||||
"collectd": {
|
||||
"enabled": True,
|
||||
"interval": 30,
|
||||
},
|
||||
"rrdtool": {
|
||||
"datadir": "/tmp/rrd",
|
||||
"stepsize": 30,
|
||||
"heartbeat": 60,
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_services(self) -> List[ServiceDict]:
|
||||
"""
|
||||
Returns the list of system services known to the device's init system.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - service name as registered with the init system
|
||||
* running (bool) - ``True`` if the service process is currently running
|
||||
* enabled (bool) - ``True`` if the service starts automatically at boot
|
||||
* pid (int) - process ID of the main service process; 0 if not running
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{"name": "lldpd", "running": True, "enabled": True, "pid": 2341},
|
||||
{"name": "sshd", "running": True, "enabled": True, "pid": 1198},
|
||||
{"name": "cron", "running": False, "enabled": False, "pid": 0},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def manage_service(self, name: str, action: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute a lifecycle action on a named service.
|
||||
|
||||
:param name: Service name as returned by :meth:`get_services`.
|
||||
:param action: One of ``start``, ``stop``, ``restart``, ``enable``, ``disable``.
|
||||
:returns: ``{"success": bool, "output": str}``
|
||||
:raises ValueError: If ``name`` or ``action`` is invalid.
|
||||
:raises NotImplementedError: If the driver does not support service management.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_available_updates(self) -> List[UpdateDict]:
|
||||
"""
|
||||
Returns the list of installed packages that have a newer version available.
|
||||
|
||||
Uses the local package manager cache — does not run ``opkg update`` / ``apk update``.
|
||||
|
||||
:returns: List of :class:`~napalm_device_types.models.UpdateDict`.
|
||||
:raises NotImplementedError: If the driver does not support update listing.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{"name": "busybox", "current_version": "1.36.1-1", "new_version": "1.37.0-1"},
|
||||
{"name": "dropbear", "current_version": "2022.83-2", "new_version": "2024.86-1"},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def apply_updates(self, packages: List[str]) -> Dict[str, Any]:
|
||||
"""
|
||||
Upgrade one or more packages to their newest available version.
|
||||
|
||||
:param packages: List of package names to upgrade.
|
||||
:returns: ``{"success": bool, "output": str}``
|
||||
:raises NotImplementedError: If the driver does not support package upgrades.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def set_package_config(self, name: str, config: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Writes a new configuration for an installed package.
|
||||
|
||||
The ``config`` dict must match the structure returned by
|
||||
:meth:`get_package_config`. Unknown keys are ignored or raise a
|
||||
``ValueError`` depending on the driver implementation.
|
||||
|
||||
Changes take effect immediately where the package supports live
|
||||
reload; otherwise a package restart or device reboot may be
|
||||
required – behaviour is driver-specific.
|
||||
|
||||
:param name: Package name.
|
||||
:param config: New configuration as a nested dictionary.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package is not installed or the configuration
|
||||
contains invalid values.
|
||||
:raises RuntimeError: If the device rejects the configuration.
|
||||
|
||||
Example::
|
||||
|
||||
driver.set_package_config(
|
||||
"luci-app-statistics",
|
||||
{
|
||||
"collectd": {"enabled": True, "interval": 60},
|
||||
"rrdtool": {"datadir": "/tmp/rrd", "stepsize": 60, "heartbeat": 120},
|
||||
},
|
||||
)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"CorpWiFi": {
|
||||
"enabled": True,
|
||||
"ssid": "CorpWiFi",
|
||||
"auth_server": {
|
||||
"host": "radius.corp.example",
|
||||
"port": 1812,
|
||||
"timeout": 5,
|
||||
"retries": 3,
|
||||
},
|
||||
"acct_server": {
|
||||
"host": "radius.corp.example",
|
||||
"port": 1813,
|
||||
"timeout": 5,
|
||||
"retries": 3,
|
||||
},
|
||||
"reauth_interval": 3600,
|
||||
"pmksa_caching": True,
|
||||
}
|
||||
}
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,115 @@
|
||||
"""The shapes an access point's getters return (models.py's Access Point part).
|
||||
|
||||
Apart from ``models.py`` for its size; ``models`` re-exports each, so
|
||||
``napalm_device_types.models.RadioStatusDict`` stays where callers import it.
|
||||
"""
|
||||
|
||||
from typing import NotRequired
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
|
||||
class WirelessClientDict(TypedDict):
|
||||
mac: str
|
||||
ssid: str
|
||||
radio: str
|
||||
signal: int
|
||||
noise: int
|
||||
tx_rate: float
|
||||
rx_rate: float
|
||||
uptime: int
|
||||
# Optional fields populated by DHCP cross-reference (e.g. from firewall)
|
||||
ip: NotRequired[str]
|
||||
hostname: NotRequired[str]
|
||||
lease_end: NotRequired[int] # Unix timestamp when DHCP lease expires
|
||||
|
||||
|
||||
class SSIDDict(TypedDict):
|
||||
enabled: bool
|
||||
radio: str
|
||||
bssid: str
|
||||
encryption: str
|
||||
hidden: bool
|
||||
clients: int
|
||||
|
||||
|
||||
class RadioStatusDict(TypedDict):
|
||||
"""One radio: ``enabled`` is the configuration, the rest what the radio does.
|
||||
|
||||
The runtime state is left out where the driver cannot read it, never guessed
|
||||
(NetOrk/netork#31): ``up`` whether the radio runs, ``pending`` whether the
|
||||
device is still bringing it up or down, ``setup_failed`` whether the device
|
||||
gave up bringing it up after its retries.
|
||||
"""
|
||||
|
||||
enabled: bool
|
||||
band: str
|
||||
channel: int
|
||||
channel_width: int
|
||||
tx_power: int
|
||||
frequency: float
|
||||
up: NotRequired[bool]
|
||||
pending: NotRequired[bool]
|
||||
setup_failed: NotRequired[bool]
|
||||
|
||||
|
||||
class ChannelScanEntryDict(TypedDict):
|
||||
"""One neighboring AP entry as returned by get_channel_scan()."""
|
||||
|
||||
bssid: str
|
||||
ssid: str
|
||||
frequency: int # centre frequency in MHz, e.g. 2437
|
||||
channel: int # channel number, e.g. 6
|
||||
signal_dbm: int # RSSI in dBm, e.g. -72
|
||||
channel_width: int # MHz: 20 / 40 / 80 / 160; 0 if unknown
|
||||
band: str # "2.4GHz" | "5GHz" | "6GHz"
|
||||
|
||||
|
||||
class WirelessConfigDict(TypedDict):
|
||||
country_code: str
|
||||
regulatory_domain: str
|
||||
beacon_interval: int
|
||||
dtim_period: int
|
||||
rts_threshold: int
|
||||
fragmentation_threshold: int
|
||||
short_preamble: bool
|
||||
wmm_enabled: bool
|
||||
|
||||
|
||||
class FastTransitionConfigDict(TypedDict):
|
||||
enabled: bool
|
||||
ssid: str
|
||||
mobility_domain: str
|
||||
reassociation_deadline: int
|
||||
r0_key_lifetime: int
|
||||
r1_key_holder: str
|
||||
pmk_r1_push: bool
|
||||
over_ds: bool
|
||||
|
||||
|
||||
class MeshPeerDict(TypedDict):
|
||||
mac: str
|
||||
radio: str
|
||||
signal: int
|
||||
tx_rate: float
|
||||
rx_rate: float
|
||||
uptime: int
|
||||
hop_count: int
|
||||
|
||||
|
||||
class MeshConfigDict(TypedDict):
|
||||
enabled: bool
|
||||
radio: str
|
||||
mesh_id: str
|
||||
path_metric: str
|
||||
gate_announcements: bool
|
||||
is_gate: bool
|
||||
encryption: str
|
||||
|
||||
|
||||
class SSIDBridgeDict(TypedDict):
|
||||
ssid: str
|
||||
bridge: str
|
||||
vlan_id: int
|
||||
tagged: bool
|
||||
client_isolation: bool
|
||||
@@ -0,0 +1,402 @@
|
||||
"""apt's history log as past transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||
|
||||
apt appends a block to ``/var/log/apt/history.log`` for every run that changed a
|
||||
package, also those no caller started (an operator's ``apt``, unattended-upgrades,
|
||||
PackageKit)::
|
||||
|
||||
Start-Date: 2026-11-26 10:00:00
|
||||
Commandline: apt-get -y upgrade
|
||||
Requested-By: admin (1000)
|
||||
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic)
|
||||
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1)
|
||||
Remove: ifupdown:amd64 (0.8.44)
|
||||
Error: Sub-process /usr/bin/dpkg returned an error code (1)
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
logrotate moves it to ``history.log.1.gz`` and on, monthly, twelve deep by default.
|
||||
The file is 0644 on Debian and Ubuntu, so :data:`APT_HISTORY_COMMAND` reads it
|
||||
as the login user; :class:`AptHistoryMixin` asks for root only where a file is
|
||||
not readable that way. One round trip prints every file behind a marker line,
|
||||
the host's time zone (``/etc/localtime``'s link, ``/etc/timezone``) and its UTC
|
||||
offset (``date +%z``), which stands in where the zone has no name.
|
||||
|
||||
The dates are the host's local time. A transaction is named like Proxmox VE 9.3's
|
||||
``GET /nodes/{node}/apt/history`` names it: its start in unix seconds and the
|
||||
number of earlier transactions with the same start **in the same log file**, so
|
||||
a Proxmox VE node that moves to 9.3 keeps the ids it had. The count takes every
|
||||
block with a readable start, also one skipped below; it never depends on *since*.
|
||||
|
||||
Strict: a block whose package lines or end do not read as apt writes them is left
|
||||
out, never guessed at; a block without ``End-Date`` is one that is running or was
|
||||
interrupted (``end`` None). A report cut short, or a file that could not be read,
|
||||
raises: an empty list means no transaction, never "could not read".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta, timezone, tzinfo
|
||||
from typing import TYPE_CHECKING
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from napalm_device_types._time_sync_reading import _zone_name
|
||||
from napalm_device_types.updates import (
|
||||
UpdateHistoryAction,
|
||||
UpdateHistoryDict,
|
||||
UpdateHistoryPackageDict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: Where apt keeps its history log.
|
||||
APT_HISTORY_DIR = "/var/log/apt"
|
||||
|
||||
_MARK = "### apt-history"
|
||||
|
||||
#: Seconds the read may take: twelve rotated months of a busy host.
|
||||
_READ_TIMEOUT = 120
|
||||
|
||||
|
||||
def apt_history_command(log_dir: str = APT_HISTORY_DIR) -> str:
|
||||
"""``sh`` that prints the time zone, the UTC offset and every history file in *log_dir*.
|
||||
|
||||
Each file follows a ``### apt-history file <path>`` line and ends with a
|
||||
``### apt-history status <exit code>`` line; one the login user may not read
|
||||
is only named (``unreadable``). ``### apt-history end`` closes the report.
|
||||
"""
|
||||
return (
|
||||
f"m='{_MARK}'; "
|
||||
"z=$( { readlink /etc/localtime || cat /etc/timezone; } 2>/dev/null | head -n 1); "
|
||||
'printf "%s zone %s\\n" "$m" "$z"; '
|
||||
'printf "%s offset %s\\n" "$m" "$(date +%z)"; '
|
||||
f"for f in {log_dir}/history.log {log_dir}/history.log.*; do "
|
||||
'[ -f "$f" ] || continue; '
|
||||
'if [ ! -r "$f" ]; then printf "%s unreadable %s\\n" "$m" "$f"; continue; fi; '
|
||||
'printf "%s file %s\\n" "$m" "$f"; '
|
||||
'case "$f" in *.gz) zcat -- "$f";; *) cat -- "$f";; esac 2>/dev/null; '
|
||||
'printf "\\n%s status %s\\n" "$m" "$?"; '
|
||||
"done; "
|
||||
'printf "%s end\\n" "$m"'
|
||||
)
|
||||
|
||||
|
||||
#: Prints apt's history log, rotated files too, with the host's time zone.
|
||||
APT_HISTORY_COMMAND = apt_history_command()
|
||||
|
||||
|
||||
class AptHistoryUnreadable(PermissionError):
|
||||
"""A history file the user that read the log may not read."""
|
||||
|
||||
|
||||
#: The package lines apt writes, and the action each stands for.
|
||||
_ACTIONS: dict[str, UpdateHistoryAction] = {
|
||||
"Install": "install",
|
||||
"Reinstall": "reinstall",
|
||||
"Upgrade": "upgrade",
|
||||
"Downgrade": "downgrade",
|
||||
"Remove": "remove",
|
||||
"Purge": "purge",
|
||||
"Disappeared": "disappear",
|
||||
}
|
||||
#: ``name[:arch] (versions)``; neither a name nor a Debian version holds ``,``, ``(`` or ``)``.
|
||||
_ENTRY = re.compile(r"([^\s,()]+) \(([^()]*)\)")
|
||||
#: ``Disappeared`` names a package without a version where apt no longer knows it.
|
||||
_DISAPPEARED = re.compile(r"([^\s,()]+)(?: \(([^\s,()]+)\))?")
|
||||
_REQUESTED_BY = re.compile(r"(.+) \(\d+\)")
|
||||
_DATE = "%Y-%m-%d %H:%M:%S"
|
||||
_OFFSET = re.compile(r"([+-])(\d\d)(\d\d)")
|
||||
#: ``history.log``, ``history.log.<n>`` and ``history.log.<n>.gz``.
|
||||
_ROTATED = re.compile(r"history\.log(?:\.(\d+)(?:\.gz)?)?")
|
||||
|
||||
|
||||
def host_zone(name: str, offset: str) -> tzinfo:
|
||||
"""The host's zone from its name, else the fixed UTC offset ``date +%z`` printed.
|
||||
|
||||
:raises ValueError: when neither says.
|
||||
"""
|
||||
zone = _zone_name(name)
|
||||
if zone:
|
||||
try:
|
||||
return ZoneInfo(zone)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
pass
|
||||
match = _OFFSET.fullmatch(offset.strip())
|
||||
if match is None:
|
||||
raise ValueError(f"the host named no time zone ({name!r}) and no UTC offset ({offset!r})")
|
||||
sign = -1 if match.group(1) == "-" else 1
|
||||
return timezone(sign * timedelta(hours=int(match.group(2)), minutes=int(match.group(3))))
|
||||
|
||||
|
||||
def _local(value: str, zone: tzinfo) -> int | None:
|
||||
"""apt's ``YYYY-MM-DD HH:MM:SS`` in *zone* as unix seconds; None for anything else."""
|
||||
try:
|
||||
when = datetime.strptime(" ".join(value.split()), _DATE)
|
||||
except ValueError:
|
||||
return None
|
||||
return int(when.replace(tzinfo=zone).timestamp())
|
||||
|
||||
|
||||
_Versions = tuple[str | None, str | None] | None
|
||||
|
||||
|
||||
def _installed(v: list[str]) -> _Versions:
|
||||
return (None, v[0]) if v[1:] in ([], ["automatic"]) else None
|
||||
|
||||
|
||||
def _changed(v: list[str]) -> _Versions:
|
||||
return (v[0], v[1]) if len(v) == 2 else None
|
||||
|
||||
|
||||
def _same(v: list[str]) -> _Versions:
|
||||
return (v[0], v[0]) if len(v) == 1 else None
|
||||
|
||||
|
||||
def _removed(v: list[str]) -> _Versions:
|
||||
# A package removed earlier and purged now has no installed version: ``Purge: name ()``.
|
||||
return (v[0] or None, None) if len(v) == 1 else None
|
||||
|
||||
|
||||
def _gone(v: list[str]) -> _Versions:
|
||||
return ((v[0] if v else None), None) if len(v) <= 1 else None
|
||||
|
||||
|
||||
#: Per action: ``(old, new)`` from the versions apt wrote in a package's brackets.
|
||||
_VERSIONS: dict[UpdateHistoryAction, Callable[[list[str]], _Versions]] = {
|
||||
"install": _installed,
|
||||
"reinstall": _same,
|
||||
"upgrade": _changed,
|
||||
"downgrade": _changed,
|
||||
"remove": _removed,
|
||||
"purge": _removed,
|
||||
"disappear": _gone,
|
||||
}
|
||||
|
||||
|
||||
def _versions(action: UpdateHistoryAction, versions: list[str]) -> _Versions:
|
||||
"""``(old, new)`` of one package; None where what apt wrote does not fit *action*."""
|
||||
if action not in ("remove", "purge") and not all(versions):
|
||||
return None
|
||||
return _VERSIONS[action](versions)
|
||||
|
||||
|
||||
def _disappeared(value: str) -> list[tuple[str, list[str]]] | None:
|
||||
found = [_DISAPPEARED.fullmatch(item) for item in value.split(", ")]
|
||||
if not all(found):
|
||||
return None
|
||||
return [(m.group(1), [m.group(2)] if m.group(2) else []) for m in found if m]
|
||||
|
||||
|
||||
def _entries(action: UpdateHistoryAction, value: str) -> list[tuple[str, list[str]]] | None:
|
||||
"""``(name[:arch], versions)`` per package of a line; None unless all of it reads."""
|
||||
if action == "disappear":
|
||||
return _disappeared(value)
|
||||
matches = list(_ENTRY.finditer(value))
|
||||
if not matches or ", ".join(m.group(0) for m in matches) != value:
|
||||
return None
|
||||
return [(m.group(1), [v.strip() for v in m.group(2).split(",")]) for m in matches]
|
||||
|
||||
|
||||
def _packages(action: UpdateHistoryAction, value: str) -> list[UpdateHistoryPackageDict] | None:
|
||||
"""The packages of one ``Install:``-style line; None unless every one reads."""
|
||||
entries = _entries(action, value.strip())
|
||||
if entries is None:
|
||||
return None
|
||||
packages: list[UpdateHistoryPackageDict] = []
|
||||
for name, versions in entries:
|
||||
pair = _versions(action, versions)
|
||||
if pair is None:
|
||||
return None
|
||||
packages.append(
|
||||
{
|
||||
"name": name.split(":", 1)[0],
|
||||
"action": action,
|
||||
"old_version": pair[0],
|
||||
"new_version": pair[1],
|
||||
}
|
||||
)
|
||||
return packages
|
||||
|
||||
|
||||
def _transaction(start: int, lines: list[str], zone: tzinfo) -> UpdateHistoryDict | None:
|
||||
"""One block after its ``Start-Date``; None where a line does not read."""
|
||||
found: UpdateHistoryDict = {
|
||||
"id": "",
|
||||
"start": start,
|
||||
"end": None,
|
||||
"packages": [],
|
||||
"requested_by": None,
|
||||
"command": None,
|
||||
"error": None,
|
||||
}
|
||||
for line in lines:
|
||||
key, sep, value = line.partition(": ")
|
||||
if not sep:
|
||||
return None
|
||||
if key in _ACTIONS:
|
||||
packages = _packages(_ACTIONS[key], value)
|
||||
if packages is None:
|
||||
return None
|
||||
found["packages"].extend(packages)
|
||||
elif key == "End-Date":
|
||||
found["end"] = _local(value, zone)
|
||||
if found["end"] is None:
|
||||
return None
|
||||
elif key in ("Commandline", "Requested-By", "Error"):
|
||||
_text(found, key, value.strip())
|
||||
return found
|
||||
|
||||
|
||||
def _text(found: UpdateHistoryDict, key: str, value: str) -> None:
|
||||
if key == "Commandline":
|
||||
found["command"] = value or None
|
||||
elif key == "Requested-By":
|
||||
match = _REQUESTED_BY.fullmatch(value)
|
||||
found["requested_by"] = (match.group(1) if match else value) or None
|
||||
else:
|
||||
found["error"] = value or None
|
||||
|
||||
|
||||
def _blocks(lines: list[str]) -> list[tuple[str, list[str]]]:
|
||||
"""``(Start-Date value, the lines after it)`` per block of one file."""
|
||||
blocks: list[tuple[str, list[str]]] = []
|
||||
for line in lines:
|
||||
line = line.rstrip("\r")
|
||||
if line.startswith("Start-Date:"):
|
||||
blocks.append((line.partition(":")[2], []))
|
||||
elif blocks and line.strip():
|
||||
blocks[-1][1].append(line)
|
||||
return blocks
|
||||
|
||||
|
||||
def _file_transactions(lines: list[str], zone: tzinfo) -> list[UpdateHistoryDict]:
|
||||
"""One file's transactions in the order it holds them, each with its id."""
|
||||
seen: dict[int, int] = {}
|
||||
found: list[UpdateHistoryDict] = []
|
||||
for date, body in _blocks(lines):
|
||||
start = _local(date, zone)
|
||||
if start is None:
|
||||
continue
|
||||
index = seen.get(start, 0)
|
||||
seen[start] = index + 1
|
||||
transaction = _transaction(start, body, zone)
|
||||
if transaction is not None:
|
||||
transaction["id"] = f"{start}-{index}"
|
||||
found.append(transaction)
|
||||
return found
|
||||
|
||||
|
||||
def _rotation(path: str) -> int | None:
|
||||
"""0 for ``history.log``, *n* for its *n*-th rotation; None for another file."""
|
||||
match = _ROTATED.fullmatch(path.rpartition("/")[2])
|
||||
if match is None:
|
||||
return None
|
||||
return int(match.group(1) or 0)
|
||||
|
||||
|
||||
def _marker(
|
||||
kind: str, rest: str, values: dict[str, str], files: dict[int, list[str]]
|
||||
) -> list[str] | None:
|
||||
"""Take one marker line; the lines of the history file it opens, if it opens one.
|
||||
|
||||
:raises AptHistoryUnreadable: for a history file the user may not read.
|
||||
"""
|
||||
rotation = _rotation(rest.strip())
|
||||
if kind == "unreadable" and rotation is not None:
|
||||
raise AptHistoryUnreadable(f"{rest.strip()} is not readable")
|
||||
if kind == "file" and rotation is not None:
|
||||
return files.setdefault(rotation, [])
|
||||
if kind in ("zone", "offset"):
|
||||
values[kind] = rest
|
||||
return None
|
||||
|
||||
|
||||
def _report(text: str) -> tuple[dict[str, str], dict[int, list[str]]]:
|
||||
"""The report's ``zone`` and ``offset``, and each history file's lines by rotation.
|
||||
|
||||
:raises ValueError: for a report cut short or a file that could not be read.
|
||||
:raises AptHistoryUnreadable: for a file the user may not read.
|
||||
"""
|
||||
values: dict[str, str] = {}
|
||||
files: dict[int, list[str]] = {}
|
||||
current: list[str] | None = None
|
||||
for line in text.splitlines():
|
||||
if not line.startswith(_MARK + " "):
|
||||
if current is not None:
|
||||
current.append(line)
|
||||
continue
|
||||
kind, _, rest = line[len(_MARK) + 1 :].partition(" ")
|
||||
if kind == "end":
|
||||
return values, files
|
||||
if kind == "status" and current is not None and rest.strip() != "0":
|
||||
raise ValueError(f"apt's history log could not be read (exit {rest.strip()})")
|
||||
current = _marker(kind, rest, values, files)
|
||||
raise ValueError("apt's history log came back cut short")
|
||||
|
||||
|
||||
def parse_apt_history(text: str, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
""":data:`APT_HISTORY_COMMAND`'s report as transactions, newest first.
|
||||
|
||||
:param since: Unix seconds; only transactions that started at or after it.
|
||||
:raises ValueError: for a report cut short, a file that could not be read, or
|
||||
a host that named neither its time zone nor its UTC offset.
|
||||
:raises AptHistoryUnreadable: for a file the user may not read.
|
||||
"""
|
||||
values, files = _report(text)
|
||||
zone = host_zone(values.get("zone", ""), values.get("offset", ""))
|
||||
oldest_first: list[UpdateHistoryDict] = []
|
||||
for rotation in sorted(files, reverse=True):
|
||||
oldest_first.extend(_file_transactions(files[rotation], zone))
|
||||
newest = sorted(reversed(oldest_first), key=lambda t: t["start"], reverse=True)
|
||||
return [t for t in newest if since is None or t["start"] >= since]
|
||||
|
||||
|
||||
class AptHistoryMixin:
|
||||
"""Adds :meth:`get_update_history` from apt's log, over the driver's ``run_command``.
|
||||
|
||||
Mixed in by the drivers of Debian-family hosts, so
|
||||
``hasattr(driver, "get_update_history")`` stays a truthful answer. The log is
|
||||
read as the login user; only a file that user may not read makes it read as root.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
"""apt's transactions on the host, newest first, from *since* (unix seconds) on.
|
||||
|
||||
:raises RuntimeError: when the log could not be read.
|
||||
:raises ValueError: when the report came back cut short.
|
||||
:raises AptHistoryUnreadable: when even root could not read a file.
|
||||
"""
|
||||
try:
|
||||
return parse_apt_history(self._read_apt_history(privileged=False), since)
|
||||
except AptHistoryUnreadable:
|
||||
return parse_apt_history(self._read_apt_history(privileged=True), since)
|
||||
|
||||
def _read_apt_history(self, *, privileged: bool) -> str:
|
||||
result = self.run_command(APT_HISTORY_COMMAND, privileged=privileged, timeout=_READ_TIMEOUT)
|
||||
if result.exit_code != 0:
|
||||
said = (result.stderr or result.stdout).strip()[-300:]
|
||||
raise RuntimeError(f"cannot read apt's history log: {said or result.exit_code}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
__all__ = [
|
||||
"APT_HISTORY_COMMAND",
|
||||
"APT_HISTORY_DIR",
|
||||
"AptHistoryMixin",
|
||||
"AptHistoryUnreadable",
|
||||
"apt_history_command",
|
||||
"host_zone",
|
||||
"parse_apt_history",
|
||||
]
|
||||
@@ -0,0 +1,755 @@
|
||||
"""apt's proxy: what apt fetches through, whether a proxy answers, and pointing apt at one.
|
||||
|
||||
Read the same way on every Debian-family host, so the commands and their parse
|
||||
live here once, like :mod:`~napalm_device_types.host_status`; a driver only
|
||||
carries a command across and runs one as root.
|
||||
|
||||
**What apt fetches through** is what ``apt-config dump`` says, not one file. apt
|
||||
reads every file in ``Dir::Etc::parts`` (``apt.conf.d``) in byte order, then
|
||||
``Dir::Etc::main`` (``apt.conf``); for a single value the last one read wins. The
|
||||
Debian installer writes its proxy into ``apt.conf``, Ubuntu's into
|
||||
``apt.conf.d/90curtin-aptproxy``: both win over an ``00proxy``
|
||||
(NetOrk/netork#1397). ``DIRECT`` for the proxy, or for one host
|
||||
(``Acquire::http::Proxy::<host>``), means no proxy there.
|
||||
|
||||
**https** goes through the http proxy too. apt's https method asks
|
||||
``Acquire::https::Proxy`` first and ``Acquire::http::Proxy`` after it, for one
|
||||
host and then for all (NetOrk/netork#1811). An http proxy alone therefore takes
|
||||
every https source as well, and a cache that does not tunnel them answers 403.
|
||||
|
||||
**Where it is set** is every line of apt's files that sets the http proxy, in the
|
||||
order apt reads them; the https proxy's lines are named apart. A line of the form
|
||||
``Acquire::http::Proxy "…";`` can be commented out; a setting inside a block
|
||||
(``Acquire::http { Proxy "…"; };``) is named but left alone. apt skips a file in
|
||||
``apt.conf.d`` whose name has other characters than letters, digits, ``_``, ``-``
|
||||
and ``.``, or an extension other than ``.conf`` (``00proxy.bak``, ``*.dpkg-old``);
|
||||
so is it here.
|
||||
|
||||
**Whether a proxy answers** is a fetch with apt's own downloader,
|
||||
``apt-helper download-file``, which is on every apt host and needs no root:
|
||||
straight to a page the caller names (past any proxy), or through the proxy apt is
|
||||
set to. An HTTP error is an answer too: the other end was reached. Whether the
|
||||
page is the right one, the caller says (``expect``).
|
||||
|
||||
**Pointing apt at a proxy** writes :attr:`AptProxyMixin.APT_PROXY_FILE`, comments
|
||||
out every other line that sets a different one, reads the result back from
|
||||
``apt-config``, and fetches the ``InRelease`` of one http source through it. The
|
||||
last step is what proves it: apt reached a mirror through the proxy it is now set
|
||||
to. The source chosen is one apt does not fetch ``DIRECT``. Then the https sources
|
||||
go through the proxy in the form it stores (:mod:`~napalm_device_types.apt_sources`),
|
||||
and one of them is fetched; where the proxy cannot, they go back to https. Last it
|
||||
fetches one https source left the same way; where the proxy refuses it, https goes
|
||||
``DIRECT``. Removing the proxy turns the sources back to https first: without the
|
||||
proxy apt cannot fetch the stored form.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Callable
|
||||
from typing import TYPE_CHECKING
|
||||
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,
|
||||
cacheable_https_hosts,
|
||||
is_host_name,
|
||||
revert_sources_command,
|
||||
rewrite_sources_command,
|
||||
)
|
||||
from napalm_device_types.fixes import PackageProxyMixin, run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
|
||||
class AptProxySettingDict(TypedDict):
|
||||
"""One line of apt's configuration that sets a proxy (``AptProxyMixin``)."""
|
||||
|
||||
file: str
|
||||
line: int # 1-based
|
||||
value: str
|
||||
#: True for ``Acquire::http::Proxy "…";`` on a line of its own, which can be
|
||||
#: commented out; False for a setting inside a block.
|
||||
editable: bool
|
||||
|
||||
|
||||
class AptProxyReportDict(TypedDict):
|
||||
"""What apt fetches through, and where that is set (``get_package_proxy_report``)."""
|
||||
|
||||
#: The http proxy apt fetches through; None for none or ``DIRECT``.
|
||||
proxy: str | None
|
||||
#: ``Acquire::http::Proxy::<host>``: a proxy, or ``DIRECT``, for one host.
|
||||
per_host: dict[str, str]
|
||||
#: ``Acquire::http::Proxy-Auto-Detect``: a program that names the proxy.
|
||||
auto_detect: str | None
|
||||
#: Every line that sets it, in the order apt reads them; the last one wins.
|
||||
settings: list[AptProxySettingDict]
|
||||
#: The proxy apt takes for https: ``Acquire::https::Proxy``, else the http one;
|
||||
#: None for none or ``DIRECT``.
|
||||
https_proxy: str | None
|
||||
#: The per-host proxies https takes: ``Acquire::https::Proxy::<host>``, else
|
||||
#: ``Acquire::http::Proxy::<host>``.
|
||||
https_per_host: dict[str, str]
|
||||
#: Every line that sets ``Acquire::https::Proxy``, in the order apt reads them.
|
||||
https_settings: list[AptProxySettingDict]
|
||||
#: The base URIs of the host's sources over http and over https.
|
||||
http_sources: list[str]
|
||||
https_sources: list[str]
|
||||
#: The hosts the cache rewrite left on https, for their credentials
|
||||
#: (:data:`~napalm_device_types.apt_sources.NOT_CACHED_KEY`).
|
||||
not_cached: list[str]
|
||||
|
||||
|
||||
class ProxyFetchDict(TypedDict):
|
||||
"""A fetch from the host with apt's downloader (``check_package_proxy``)."""
|
||||
|
||||
#: Whether the other end answered at all; an HTTP error is an answer.
|
||||
reachable: bool
|
||||
#: Whether the page contained what the caller expected; None when it named nothing
|
||||
#: or nothing came back.
|
||||
expected: bool | None
|
||||
#: apt's reason when the fetch failed, else "".
|
||||
error: str
|
||||
|
||||
|
||||
class HttpsSourceFetchDict(ProxyFetchDict):
|
||||
"""One https source fetched the way apt fetches it (``check_https_source``)."""
|
||||
|
||||
#: What was fetched: the source's ``InRelease``.
|
||||
url: str
|
||||
#: The proxy apt took for it.
|
||||
proxy: str
|
||||
|
||||
|
||||
_BEGIN = "APROXY_BEGIN"
|
||||
_END = "APROXY_END"
|
||||
_APT_HELPER = "/usr/lib/apt/apt-helper"
|
||||
|
||||
#: A proxy URL apt's file and a shell word can both carry.
|
||||
PROXY_URL = re.compile(r"^https?://[A-Za-z0-9.\-\[\]:@%_~/]+$")
|
||||
|
||||
#: One line, POSIX ``sh``, read-only, no privileges. In a subshell, so neither the
|
||||
#: locale nor its variables stay behind in an interactive session; the frame
|
||||
#: markers are printed in two halves so that an echoing transport does not show
|
||||
#: them early.
|
||||
APT_PROXY_COMMAND = (
|
||||
"( export LC_ALL=C; printf '%s%s\\n' APROXY_ BEGIN; "
|
||||
"echo '[dump]'; apt-config dump 2>/dev/null "
|
||||
"| grep -i -E '^(Acquire::https?::Proxy|Package-Proxy::)'; "
|
||||
'eval "$(apt-config shell ap_parts Dir::Etc::parts/d ap_main Dir::Etc::main/f 2>/dev/null)"; '
|
||||
"echo '[parts]'; for f in \"${ap_parts:-/etc/apt/apt.conf.d/}\"*; do "
|
||||
'[ -f "$f" ] && grep -Hin proxy "$f"; done; '
|
||||
'echo \'[main]\'; f="${ap_main:-/etc/apt/apt.conf}"; [ -f "$f" ] && grep -Hin proxy "$f"; '
|
||||
"echo '[sources]'; apt-get indextargets --no-release-info --format '$(BASE_URI)' "
|
||||
"2>/dev/null | sort -u; "
|
||||
"printf '%s%s\\n' APROXY_ END ) 2>/dev/null | cat"
|
||||
)
|
||||
|
||||
_NOT_CACHED = re.compile(rf'^{re.escape(NOT_CACHED_KEY)}::\s+"([^"]+)"', re.I)
|
||||
_DUMP = re.compile(r'^Acquire::(https?)::Proxy(::\S+|-Auto-Detect)?\s+"([^"]*)"', re.I)
|
||||
_GREP = re.compile(r"^(/[^:]+):(\d+):(.*)$")
|
||||
_FLAT = re.compile(r'^\s*Acquire::http::Proxy\s+"([^"]*)"\s*;', re.I)
|
||||
_NOT_HTTP_PROXY = re.compile(
|
||||
r"^\s*(//|#)|Acquire::(https|ftp|socks)\b|::Proxy::|Proxy-Auto-Detect", re.I
|
||||
)
|
||||
_FLAT_HTTPS = re.compile(r'^\s*Acquire::https::Proxy\s+"([^"]*)"\s*;', re.I)
|
||||
#: A line that sets the https proxy inside a block, all on the line itself.
|
||||
_HTTPS_BLOCK = re.compile(r'^\s*Acquire::https\s*\{[^}]*\bProxy\s+"([^"]*)"', re.I)
|
||||
_IN_BLOCK = re.compile(r'\bProxy\s+"([^"]*)"', re.I)
|
||||
#: The names apt reads in ``apt.conf.d``: no extension, or ``.conf``.
|
||||
_PART_NAME = re.compile(r"^(?:[A-Za-z0-9_\-]+|[A-Za-z0-9_.\-]+\.conf)$")
|
||||
_NO_PROXY = frozenset({"", "direct"})
|
||||
|
||||
|
||||
def _sections(output: str) -> dict[str, list[str]]:
|
||||
lines = [line.rstrip() for line in 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 proxy report in the output") from None
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] = []
|
||||
for line, bare in zip(lines[start + 1 : end], stripped[start + 1 : end], strict=True):
|
||||
if bare.startswith("[") and bare.endswith("]") and " " not in bare:
|
||||
current = sections.setdefault(bare[1:-1], [])
|
||||
elif bare:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _grep_line(line: str, main: bool) -> tuple[str, int, str] | None:
|
||||
"""File, line number and text of one line grep printed; None for a file apt skips."""
|
||||
found = _GREP.match(line)
|
||||
if not found:
|
||||
return None
|
||||
path, number, text = found.groups()
|
||||
if not main and not _PART_NAME.match(path.rsplit("/", 1)[-1]):
|
||||
return None
|
||||
return path, int(number), text
|
||||
|
||||
|
||||
def _setting(line: str, main: bool) -> AptProxySettingDict | None:
|
||||
found = _grep_line(line, main)
|
||||
if not found:
|
||||
return None
|
||||
path, number, text = found
|
||||
flat = _FLAT.match(text)
|
||||
if flat:
|
||||
return {"file": path, "line": int(number), "value": flat.group(1), "editable": True}
|
||||
if _NOT_HTTP_PROXY.search(text):
|
||||
return None
|
||||
nested = _IN_BLOCK.search(text)
|
||||
if not nested:
|
||||
return None
|
||||
return {"file": path, "line": int(number), "value": nested.group(1), "editable": False}
|
||||
|
||||
|
||||
def _https_setting(line: str, main: bool) -> AptProxySettingDict | None:
|
||||
found = _grep_line(line, main)
|
||||
if not found:
|
||||
return None
|
||||
path, number, text = found
|
||||
flat = _FLAT_HTTPS.match(text)
|
||||
if flat:
|
||||
return {"file": path, "line": number, "value": flat.group(1), "editable": True}
|
||||
block = _HTTPS_BLOCK.match(text)
|
||||
if block:
|
||||
return {"file": path, "line": number, "value": block.group(1), "editable": False}
|
||||
return None
|
||||
|
||||
|
||||
class _Dump(TypedDict):
|
||||
proxy: str | None
|
||||
per_host: dict[str, str]
|
||||
auto_detect: str | None
|
||||
#: ``Acquire::https::Proxy`` as written; None when unset or empty.
|
||||
https: str | None
|
||||
https_per_host: dict[str, str]
|
||||
|
||||
|
||||
def _dump(lines: list[str]) -> _Dump:
|
||||
"""The proxies, the per-host proxies and the auto-detect program in ``apt-config dump``."""
|
||||
dump: _Dump = {
|
||||
"proxy": None,
|
||||
"per_host": {},
|
||||
"auto_detect": None,
|
||||
"https": None,
|
||||
"https_per_host": {},
|
||||
}
|
||||
for found in (_DUMP.match(line.strip()) for line in lines):
|
||||
if found:
|
||||
_take(dump, *found.groups())
|
||||
return dump
|
||||
|
||||
|
||||
def _take(dump: _Dump, scheme: str, suffix: str | None, value: str) -> None:
|
||||
"""One line of the dump into *dump*; a later one of the same key wins, as in apt."""
|
||||
https = scheme.lower() == "https"
|
||||
if not suffix:
|
||||
_take_for_all(dump, https, value)
|
||||
elif suffix.lower() == "-auto-detect":
|
||||
if not https:
|
||||
dump["auto_detect"] = value or None
|
||||
elif value:
|
||||
dump["https_per_host" if https else "per_host"][suffix[2:]] = value
|
||||
|
||||
|
||||
def _take_for_all(dump: _Dump, https: bool, value: str) -> None:
|
||||
"""The proxy for every host: https keeps an empty value as unset, apt's fallback."""
|
||||
if https:
|
||||
dump["https"] = value or None
|
||||
else:
|
||||
dump["proxy"] = None if value.lower() in _NO_PROXY else value
|
||||
|
||||
|
||||
def _https_proxy(dump: _Dump) -> str | None:
|
||||
"""apt's https method takes its own setting and falls back to the http one."""
|
||||
if dump["https"] is None:
|
||||
return dump["proxy"]
|
||||
return None if dump["https"].lower() in _NO_PROXY else dump["https"]
|
||||
|
||||
|
||||
def https_proxy_for(report: AptProxyReportDict, host: str) -> str | None:
|
||||
"""The proxy apt takes for an https source on *host*; None for ``DIRECT`` or none.
|
||||
|
||||
The host's own setting first, https before http, then the one for all hosts.
|
||||
"""
|
||||
for per_host in (report["https_per_host"], report["per_host"]):
|
||||
value = next((v for h, v in per_host.items() if h.lower() == host.lower()), None)
|
||||
if value:
|
||||
return None if value.lower() in _NO_PROXY else value
|
||||
return report["https_proxy"]
|
||||
|
||||
|
||||
def parse_apt_proxy(output: str) -> AptProxyReportDict:
|
||||
"""The report :data:`APT_PROXY_COMMAND` prints, as :class:`AptProxyReportDict`.
|
||||
|
||||
:raises ValueError: if the output carried no intact report.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
dump = _dump(sections.get("dump", []))
|
||||
lines = [
|
||||
(main, line)
|
||||
for main, key in ((False, "parts"), (True, "main"))
|
||||
for line in sections.get(key, [])
|
||||
]
|
||||
sources = [line.strip() for line in sections.get("sources", [])]
|
||||
return {
|
||||
"proxy": dump["proxy"],
|
||||
"per_host": dump["per_host"],
|
||||
"auto_detect": dump["auto_detect"],
|
||||
"settings": _settings(lines, _setting),
|
||||
"https_proxy": _https_proxy(dump),
|
||||
"https_per_host": {**dump["per_host"], **dump["https_per_host"]},
|
||||
"https_settings": _settings(lines, _https_setting),
|
||||
"http_sources": _of_scheme(sources, "http"),
|
||||
"https_sources": _of_scheme(sources, "https"),
|
||||
"not_cached": [m.group(1) for m in map(_NOT_CACHED.match, sections.get("dump", [])) if m],
|
||||
}
|
||||
|
||||
|
||||
def _settings(
|
||||
lines: list[tuple[bool, str]], parse: Callable[[str, bool], AptProxySettingDict | None]
|
||||
) -> list[AptProxySettingDict]:
|
||||
return [s for s in (parse(line, main) for main, line in lines) if s]
|
||||
|
||||
|
||||
def _of_scheme(sources: list[str], scheme: str) -> list[str]:
|
||||
return [s for s in sources if s.startswith(f"{scheme}://")]
|
||||
|
||||
|
||||
_DEFAULT_PORT = {"http": 80, "https": 443}
|
||||
|
||||
|
||||
def _endpoint(url: str | None) -> tuple[str, str, int | None, str] | None:
|
||||
"""Scheme, host, port (the scheme's own when none is given) and path; None for no URL."""
|
||||
if not url:
|
||||
return None
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
port = parts.port or _DEFAULT_PORT.get(parts.scheme)
|
||||
except ValueError:
|
||||
return None
|
||||
return parts.scheme, parts.hostname or "", port, parts.path.rstrip("/")
|
||||
|
||||
|
||||
def same_proxy_url(a: str | None, b: str | None) -> bool:
|
||||
"""Whether *a* and *b* name the same proxy: scheme, host and port, a trailing ``/`` aside."""
|
||||
first = _endpoint(a)
|
||||
return first is not None and first == _endpoint(b)
|
||||
|
||||
|
||||
def apt_fetch_command(url: str, *, direct: bool = False, expect: str = "") -> str:
|
||||
"""The command that fetches *url* with apt's downloader into a temporary file.
|
||||
|
||||
*direct* goes past any proxy apt is set to, to *url*'s host itself; without it
|
||||
the fetch takes apt's own way. *expect* is text the page should contain.
|
||||
|
||||
:raises ValueError: if *url* is not an http(s) URL a shell word can carry.
|
||||
"""
|
||||
if not PROXY_URL.match(url):
|
||||
raise ValueError(f"not an http URL: {url!r}")
|
||||
options = ["-o Acquire::Retries=0", "-o Acquire::http::Timeout=10"]
|
||||
host = urlsplit(url).hostname or ""
|
||||
if direct and host and ":" not in host:
|
||||
# *host* comes from a URL PROXY_URL let through: no quote in it. For https
|
||||
# the host's https setting comes first, so both are set.
|
||||
if url.startswith("https://"):
|
||||
options.append(f"-o 'Acquire::https::Proxy::{host}=DIRECT'")
|
||||
options.append(f"-o 'Acquire::http::Proxy::{host}=DIRECT'")
|
||||
match = f"echo '[match]'; grep -c -F -- {shlex.quote(expect)} \"$t\"; " if expect else ""
|
||||
return (
|
||||
"( export LC_ALL=C; t=$(mktemp) || exit 1; printf '%s%s\\n' APROXY_ BEGIN; "
|
||||
f"echo '[fetch]'; {_APT_HELPER} {' '.join(options)} download-file "
|
||||
f'{shlex.quote(url)} "$t" 2>&1; rc=$?; echo \'[rc]\'; echo "$rc"; '
|
||||
f"{match}rm -f \"$t\"; printf '%s%s\\n' APROXY_ END ) | cat"
|
||||
)
|
||||
|
||||
|
||||
_FAILED = re.compile(r"^E: Failed to fetch \S+\s+(.*)$")
|
||||
_HTTP_STATUS = re.compile(r"^\d{3}\s")
|
||||
|
||||
|
||||
def parse_apt_fetch(output: str) -> ProxyFetchDict:
|
||||
"""What :func:`apt_fetch_command` printed, as :class:`ProxyFetchDict`.
|
||||
|
||||
:raises ValueError: if the output carried no intact report, or apt-helper is
|
||||
missing -- then nothing could be tried.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
try:
|
||||
rc = int(sections["rc"][0])
|
||||
except (KeyError, IndexError, ValueError):
|
||||
raise ValueError("no exit status in the apt fetch report") from None
|
||||
if rc in (126, 127):
|
||||
raise ValueError(f"{_APT_HELPER} cannot run on this host")
|
||||
match = sections.get("match")
|
||||
if rc == 0:
|
||||
expected = (match[0].strip() not in ("", "0")) if match else None
|
||||
return {"reachable": True, "expected": expected, "error": ""}
|
||||
error = next(
|
||||
(m.group(1).strip() for m in map(_FAILED.match, sections.get("fetch", [])) if m),
|
||||
"the download failed",
|
||||
)
|
||||
answered = bool(_HTTP_STATUS.match(error))
|
||||
return {"reachable": answered, "expected": False if answered else None, "error": error}
|
||||
|
||||
|
||||
#: sed's edit of one line: comment it out, if it still sets the proxy of *scheme*.
|
||||
_COMMENT_OUT = "-e '{line}{{/^[[:space:]]*Acquire::{scheme}::Proxy[[:space:]]/Is|^|// |}}'"
|
||||
_SCHEMES = ("http", "https")
|
||||
|
||||
|
||||
def comment_out_command(path: str, lines: list[int], scheme: str = "http") -> str:
|
||||
"""The root command that comments out *lines* of *path* where they set *scheme*'s proxy."""
|
||||
if scheme not in _SCHEMES:
|
||||
raise ValueError(f"not a scheme apt proxies: {scheme!r}")
|
||||
edits = " ".join(_COMMENT_OUT.format(line=int(n), scheme=scheme) for n in lines)
|
||||
return f"sed -i {edits} {shlex.quote(path)}"
|
||||
|
||||
|
||||
def _editable_lines(settings: list[AptProxySettingDict]) -> dict[str, list[int]]:
|
||||
by_file: dict[str, list[int]] = {}
|
||||
for s in settings:
|
||||
if s["editable"]:
|
||||
by_file.setdefault(s["file"], []).append(s["line"])
|
||||
return by_file
|
||||
|
||||
|
||||
def _described(s: AptProxySettingDict) -> str:
|
||||
what = "commented out" if s["editable"] else "left alone (inside a block)"
|
||||
return f"{s['file']}:{s['line']} ({s['value']}) {what}"
|
||||
|
||||
|
||||
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`:
|
||||
the reading, the parse and the order of the fix are the same everywhere; a
|
||||
driver supplies the transports below. Mixed in by the drivers that can, so
|
||||
``callable(getattr(driver, "configure_package_proxy", None))`` stays a truthful
|
||||
answer.
|
||||
"""
|
||||
|
||||
#: The file the proxy is written to. Its name carries no application's.
|
||||
APT_PROXY_FILE = "/etc/apt/apt.conf.d/00proxy"
|
||||
|
||||
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 _run_apt_root_command(self, command: str, done: str) -> FixStepOutcomeDict:
|
||||
"""Run *command* as root; ``ok`` with *done* when it exited 0."""
|
||||
...
|
||||
|
||||
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_package_proxy_report(self) -> AptProxyReportDict | None:
|
||||
"""What apt fetches through and where that is set; None on a host without apt.
|
||||
|
||||
* proxy (string or None): the http proxy apt fetches through
|
||||
* per_host ({host: proxy or "DIRECT"})
|
||||
* auto_detect (string or None): ``Acquire::http::Proxy-Auto-Detect``
|
||||
* settings (list of {file, line, value, editable}), in apt's reading order
|
||||
* https_proxy (string or None): the proxy https takes, the http one if unset
|
||||
* https_per_host ({host: proxy or "DIRECT"}), https_settings (as settings)
|
||||
* http_sources, https_sources (lists of the sources' base URIs)
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
if not self._is_apt_host():
|
||||
return None
|
||||
return parse_apt_proxy(self._run_apt_command(APT_PROXY_COMMAND))
|
||||
|
||||
def get_package_proxy(self) -> str | None:
|
||||
"""The proxy apt fetches through now; None for none, or a host without apt."""
|
||||
report = self.get_package_proxy_report()
|
||||
return report["proxy"] if report else None
|
||||
|
||||
def check_package_proxy(self, url: str, expect: str = "") -> ProxyFetchDict:
|
||||
"""Fetch *url* from the host, past any proxy apt is set to.
|
||||
|
||||
Whether the host reaches it, and whether the page contains *expect*.
|
||||
|
||||
:raises ValueError: if *url* is no http URL, or the host cannot fetch at all.
|
||||
:raises NotImplementedError: on a host without apt.
|
||||
"""
|
||||
if not self._is_apt_host():
|
||||
raise NotImplementedError("not an apt host")
|
||||
return parse_apt_fetch(
|
||||
self._run_apt_command(apt_fetch_command(url, direct=True, expect=expect))
|
||||
)
|
||||
|
||||
def check_https_source(self) -> HttpsSourceFetchDict | None:
|
||||
"""Fetch one https source's ``InRelease`` the way apt does, through its proxy.
|
||||
|
||||
None when no https source goes through a proxy: there are none, or https
|
||||
goes ``DIRECT``.
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
:raises NotImplementedError: on a host without apt.
|
||||
"""
|
||||
if not self._is_apt_host():
|
||||
raise NotImplementedError("not an apt host")
|
||||
report = self._report()
|
||||
found = _https_source(report, lambda proxy: proxy is not None)
|
||||
if found is None:
|
||||
return None
|
||||
target, proxy = found
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(target)))
|
||||
return {**fetched, "url": target, "proxy": proxy}
|
||||
|
||||
def configure_package_proxy(self, url: str) -> FixResultDict:
|
||||
"""apt fetches through *url*, and is shown to; ``""`` removes :attr:`APT_PROXY_FILE`.
|
||||
|
||||
The https sources go through *url* in the form it stores, where it can; the
|
||||
rest goes through *url* too, unless *url* refuses it: then ``DIRECT``.
|
||||
"""
|
||||
if not url:
|
||||
return run_fix_steps(
|
||||
[("sources", self._revert_sources), ("configure", self._remove_package_proxy)]
|
||||
)
|
||||
return run_fix_steps(
|
||||
[
|
||||
("configure", lambda: self._write_package_proxy(url)),
|
||||
("conflicts", lambda: self._comment_out_other_proxies(url)),
|
||||
("verify", lambda: self._verify_package_proxy(url)),
|
||||
("fetch", lambda: self._fetch_through_package_proxy(url)),
|
||||
("cache", lambda: self._cache_https_sources(url)),
|
||||
("https", lambda: self._https_through_package_proxy(url)),
|
||||
]
|
||||
)
|
||||
|
||||
def _not_apt(self) -> FixStepOutcomeDict:
|
||||
return {"ok": False, "output": "not an apt host"}
|
||||
|
||||
def _revert_sources(self) -> FixStepOutcomeDict:
|
||||
if not self._is_apt_host():
|
||||
return self._not_apt()
|
||||
return self._run_apt_root_command(revert_sources_command(), "sources back on https")
|
||||
|
||||
def _remove_package_proxy(self) -> FixStepOutcomeDict:
|
||||
if not self._is_apt_host():
|
||||
return self._not_apt()
|
||||
return self._run_apt_root_command(
|
||||
f"rm -f {shlex.quote(self.APT_PROXY_FILE)}", "proxy removed"
|
||||
)
|
||||
|
||||
def _write_package_proxy(
|
||||
self, url: str, https_direct: bool = False, not_cached: list[str] | None = None
|
||||
) -> FixStepOutcomeDict:
|
||||
if not self._is_apt_host():
|
||||
return self._not_apt()
|
||||
if not PROXY_URL.match(url):
|
||||
raise ValueError(f"not a proxy URL: {url!r}")
|
||||
content = f'Acquire::http::Proxy "{url}";\n'
|
||||
if https_direct:
|
||||
content += 'Acquire::https::Proxy "DIRECT";\n'
|
||||
# Host names the report read from this file; one a line could not carry is left out.
|
||||
content += "".join(
|
||||
f'{NOT_CACHED_KEY}:: "{host}";\n' for host in not_cached or [] if is_host_name(host)
|
||||
)
|
||||
return self._write_apt_file(self.APT_PROXY_FILE, content)
|
||||
|
||||
def _report(self) -> AptProxyReportDict:
|
||||
# The steps after "configure" run only once it passed, on an apt host.
|
||||
return parse_apt_proxy(self._run_apt_command(APT_PROXY_COMMAND))
|
||||
|
||||
def _comment_out_other_proxies(self, url: str) -> FixStepOutcomeDict:
|
||||
others = [
|
||||
s
|
||||
for s in self._report()["settings"]
|
||||
if s["file"] != self.APT_PROXY_FILE and not same_proxy_url(s["value"], url)
|
||||
]
|
||||
for path, numbers in _editable_lines(others).items():
|
||||
outcome = self._run_apt_root_command(
|
||||
comment_out_command(path, numbers), f"commented out in {path}"
|
||||
)
|
||||
if not outcome["ok"]:
|
||||
return outcome
|
||||
return {"ok": True, "output": "; ".join(map(_described, others)) or "no other proxy set"}
|
||||
|
||||
def _verify_package_proxy(self, url: str) -> FixStepOutcomeDict:
|
||||
report = self._report()
|
||||
if same_proxy_url(report["proxy"], url):
|
||||
return {"ok": True, "output": f"apt fetches through {url}"}
|
||||
where = [
|
||||
f"{s['file']}:{s['line']}"
|
||||
for s in report["settings"]
|
||||
if s["value"] == report["proxy"] and s["file"] != self.APT_PROXY_FILE
|
||||
]
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"apt still fetches through {report['proxy'] or 'no proxy'}"
|
||||
+ (f", set in {', '.join(where)}" if where else ""),
|
||||
}
|
||||
|
||||
def _fetch_through_package_proxy(self, url: str) -> FixStepOutcomeDict:
|
||||
source = _plain_http_source(self._report())
|
||||
if source is None:
|
||||
return {"ok": True, "output": "no http source to fetch through the proxy; not tried"}
|
||||
target = source.rstrip("/") + "/InRelease"
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(target)))
|
||||
if fetched["reachable"] and not fetched["error"]:
|
||||
return {"ok": True, "output": f"fetched {target} through {url}"}
|
||||
return {"ok": False, "output": f"{target}: {fetched['error']}"}
|
||||
|
||||
def _cache_https_sources(self, url: str) -> FixStepOutcomeDict:
|
||||
"""The https sources through *url* in the form it stores; back to https where it cannot."""
|
||||
hosts = cacheable_https_hosts(self._report())
|
||||
if not hosts:
|
||||
return {"ok": True, "output": "no https source to cache"}
|
||||
rewritten = self._run_apt_root_command(
|
||||
rewrite_sources_command(hosts, self.APT_PROXY_FILE), "sources rewritten"
|
||||
)
|
||||
if not rewritten["ok"]:
|
||||
return rewritten
|
||||
return self._fetch_cached(url, hosts, self._report())
|
||||
|
||||
def _fetch_cached(
|
||||
self, url: str, hosts: list[str], report: AptProxyReportDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""One rewritten source through *url*: it stays where *url* fetched it."""
|
||||
left = sorted(set(hosts) & set(report["not_cached"]))
|
||||
named = f"; left on https, apt has credentials for them: {', '.join(left)}" if left else ""
|
||||
target = next(
|
||||
(s.rstrip("/") + "/InRelease" for s in report["http_sources"] if _cached(s)), None
|
||||
)
|
||||
if target is None:
|
||||
return {"ok": True, "output": f"no https source to cache{named}"}
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(target)))
|
||||
if fetched["reachable"] and not fetched["error"]:
|
||||
cached = ", ".join(h for h in hosts if h not in left)
|
||||
return {"ok": True, "output": f"https sources cached through {url}: {cached}{named}"}
|
||||
return self._back_to_https(url, f"{target}: {fetched['error']}", named)
|
||||
|
||||
def _back_to_https(self, url: str, why: str, named: str) -> FixStepOutcomeDict:
|
||||
"""*url* did not fetch the stored form: every source goes back to https."""
|
||||
back = self._run_apt_root_command(revert_sources_command(), "sources back on https")
|
||||
if not back["ok"]:
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"{why}; turning the sources back to https failed: {back['output']}",
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"output": f"{url} does not fetch https sources itself ({why}); "
|
||||
f"they stay on https, not cached{named}",
|
||||
}
|
||||
|
||||
def _https_through_package_proxy(self, url: str) -> FixStepOutcomeDict:
|
||||
"""An https source through *url*; where *url* refuses it, https goes ``DIRECT``."""
|
||||
found = _https_source(self._report(), lambda proxy: same_proxy_url(proxy, url))
|
||||
if found is None:
|
||||
return {"ok": True, "output": f"no https source goes through {url}; not tried"}
|
||||
target = found[0]
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(target)))
|
||||
# An HTTP error came from the mirror, through the tunnel: the cache let it by.
|
||||
if fetched["reachable"]:
|
||||
return {"ok": True, "output": f"fetched {target} through {url}"}
|
||||
refused = f"{url} refused https ({fetched['error']})"
|
||||
outcome = self._https_direct(url)
|
||||
if not outcome["ok"]:
|
||||
return {"ok": False, "output": f"{refused}; {outcome['output']}"}
|
||||
direct = parse_apt_fetch(self._run_apt_command(apt_fetch_command(target)))
|
||||
if not direct["reachable"]:
|
||||
return {"ok": False, "output": f"{refused}; direct too: {target}: {direct['error']}"}
|
||||
named = f"; {outcome['output']}" if outcome["output"] else ""
|
||||
return {
|
||||
"ok": True,
|
||||
"output": f"{refused}{named}; https sources go direct now: fetched {target}",
|
||||
}
|
||||
|
||||
def _https_direct(self, url: str) -> FixStepOutcomeDict:
|
||||
"""Write https ``DIRECT`` beside *url*, and comment out the later lines to *url*."""
|
||||
written = self._write_package_proxy(
|
||||
url, https_direct=True, not_cached=self._report()["not_cached"]
|
||||
)
|
||||
if not written["ok"]:
|
||||
return written
|
||||
later = self._later_https_lines(self._report(), url)
|
||||
for path, numbers in _editable_lines(later).items():
|
||||
outcome = self._run_apt_root_command(
|
||||
comment_out_command(path, numbers, scheme="https"), f"commented out in {path}"
|
||||
)
|
||||
if not outcome["ok"]:
|
||||
return outcome
|
||||
report = self._report()
|
||||
if same_proxy_url(report["https_proxy"], url):
|
||||
still = [f"{s['file']}:{s['line']}" for s in self._later_https_lines(report, url)]
|
||||
where = f", set in {', '.join(still)}" if still else ""
|
||||
return {"ok": False, "output": f"https still goes through {url}{where}"}
|
||||
return {"ok": True, "output": "; ".join(map(_described, later))}
|
||||
|
||||
def _later_https_lines(self, report: AptProxyReportDict, url: str) -> list[AptProxySettingDict]:
|
||||
"""The lines outside :attr:`APT_PROXY_FILE` that send https to *url*."""
|
||||
return [
|
||||
s
|
||||
for s in report["https_settings"]
|
||||
if s["file"] != self.APT_PROXY_FILE and same_proxy_url(s["value"], url)
|
||||
]
|
||||
|
||||
|
||||
def _plain_http_source(report: AptProxyReportDict) -> str | None:
|
||||
"""A suite's http source the proxy takes, not in the cache's https form: its proof."""
|
||||
direct = {h.lower() for h, v in report["per_host"].items() if v.lower() == "direct"}
|
||||
return next(
|
||||
(
|
||||
s
|
||||
for s in report["http_sources"]
|
||||
if "/dists/" in s
|
||||
and not s.startswith(VIA_CACHE)
|
||||
and (urlsplit(s).hostname or "").lower() not in direct
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _cached(source: str) -> bool:
|
||||
"""A source of a suite in the form the cache stores."""
|
||||
return source.startswith(VIA_CACHE) and "/dists/" in source
|
||||
|
||||
|
||||
def _https_source(
|
||||
report: AptProxyReportDict, through: Callable[[str | None], bool]
|
||||
) -> tuple[str, str] | None:
|
||||
"""The ``InRelease`` of the first https source whose proxy *through* accepts, and that proxy."""
|
||||
for source in report["https_sources"]:
|
||||
if "/dists/" not in source:
|
||||
continue
|
||||
proxy = https_proxy_for(report, urlsplit(source).hostname or "")
|
||||
if through(proxy):
|
||||
return source.rstrip("/") + "/InRelease", proxy or ""
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"APT_PROXY_COMMAND",
|
||||
"AptProxyMixin",
|
||||
"AptProxyReportDict",
|
||||
"AptProxySettingDict",
|
||||
"HttpsSourceFetchDict",
|
||||
"ProxyFetchDict",
|
||||
"PROXY_URL",
|
||||
"apt_fetch_command",
|
||||
"comment_out_command",
|
||||
"https_proxy_for",
|
||||
"parse_apt_fetch",
|
||||
"parse_apt_proxy",
|
||||
"same_proxy_url",
|
||||
]
|
||||
@@ -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,172 @@
|
||||
"""apt's https sources through the package cache, so that the cache stores them.
|
||||
|
||||
A source fetched over https goes through apt-cacher-ng's tunnel, if at all: the
|
||||
TLS runs end to end and nothing of it is stored. The cache fetches
|
||||
``http://HTTPS///<host>/<path>`` from ``https://<host>/<path>`` itself, with the
|
||||
certificate verified, and stores it -- where it allows port 443
|
||||
(``AllowUserPorts=80 443``) (NetOrk/netork#2555). apt fetches that form through
|
||||
its http proxy, so it works only while the cache is that proxy: without one apt
|
||||
looks for a host called ``HTTPS``.
|
||||
|
||||
**Which hosts** (:func:`cacheable_https_hosts`): the hosts of the https sources,
|
||||
on port 443, while apt has an http proxy for every host and none of its own for
|
||||
that one. Not a host with a login in the URL, nor one whose credentials apt keeps
|
||||
in ``auth.conf``: apt finds those by the host's name, which the rewrite changes,
|
||||
and paid content does not belong in a cache other hosts share. Only root reads
|
||||
``auth.conf``, so the rewrite judges that, leaves such a host on https and names
|
||||
it in the proxy file as ``Package-Proxy::Not-Cached``, which apt ignores and
|
||||
``apt-config dump`` shows to the report.
|
||||
|
||||
**The rewrite** (:func:`rewrite_sources_command`) turns ``https://<host>`` into
|
||||
the cache form on the lines that name sources: ``deb`` and ``deb-src`` in a
|
||||
``.list`` file, ``URIs:`` in a deb822 ``.sources`` file. A file without the host
|
||||
is not touched. :func:`revert_sources_command` turns every source back.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the report's type, without an import cycle
|
||||
from napalm_device_types.apt_proxy import AptProxyReportDict
|
||||
|
||||
#: The prefix apt-cacher-ng fetches over https.
|
||||
VIA_CACHE = "http://HTTPS///"
|
||||
|
||||
#: The key in the proxy file that names the hosts left on https for their credentials.
|
||||
NOT_CACHED_KEY = "Package-Proxy::Not-Cached"
|
||||
|
||||
_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
|
||||
_HOST = re.compile(rf"^{_LABEL}(?:\.{_LABEL})*$")
|
||||
_NO_PROXY = frozenset({"", "direct"})
|
||||
|
||||
#: Where apt's sources and credentials are, as shell variables; apt's defaults
|
||||
#: when apt-config cannot say.
|
||||
_LOCATE = (
|
||||
'eval "$({apt_config} shell sl Dir::Etc::sourcelist/f sp Dir::Etc::sourceparts/d '
|
||||
'nr Dir::Etc::netrc/f np Dir::Etc::netrcparts/d 2>/dev/null)"; '
|
||||
'sl="${{sl:-/etc/apt/sources.list}}"; sp="${{sp:-/etc/apt/sources.list.d/}}"; '
|
||||
'nr="${{nr:-/etc/apt/auth.conf}}"; np="${{np:-/etc/apt/auth.conf.d/}}"; '
|
||||
)
|
||||
|
||||
#: The lines that name sources: ``deb``/``deb-src`` and deb822's ``URIs:``.
|
||||
_SOURCE_LINES = "/^[[:space:]]*(deb|deb-src|[Uu][Rr][Ii][Ss]:)/"
|
||||
|
||||
#: The hosts apt has credentials for: each word after ``machine``, without its
|
||||
#: scheme, port and path, in lower case.
|
||||
_CREDENTIAL_HOSTS = (
|
||||
'creds=$(cat "$nr" "$np"* 2>/dev/null | tr -s " \\t\\r" "\\n" '
|
||||
"| awk 'p {{ print; p = 0; next }} $0 == \"machine\" {{ p = 1 }}' "
|
||||
"| sed -e 's|^[A-Za-z+]*://||' -e 's|[:/].*||' | tr A-Z a-z); "
|
||||
)
|
||||
|
||||
_REWRITE = (
|
||||
"( " + _LOCATE + _CREDENTIAL_HOSTS + "for h in {hosts}; do "
|
||||
'l=$(printf "%s" "$h" | tr A-Z a-z); '
|
||||
'if printf "%s\\n" "$creds" | grep -qxF -- "$l"; then '
|
||||
'grep -qF -- "\\"$h\\"" {proxy_file} 2>/dev/null || '
|
||||
'printf \'{key}:: "%s";\\n\' "$h" >> {proxy_file} || exit 1; continue; fi; '
|
||||
"e=$(printf '%s' \"$h\" | sed 's/[.]/[.]/g'); "
|
||||
'for f in "$sl" "$sp"*.list "$sp"*.sources; do '
|
||||
'[ -f "$f" ] && grep -qF -- "https://$h" "$f" || continue; '
|
||||
'sed -i -E "{lines} s#([[:space:]:])https://$e([/[:space:]]|\\$)#\\1{via}$h\\2#g" "$f" '
|
||||
"|| exit 1; done; done )"
|
||||
)
|
||||
|
||||
_REVERT = (
|
||||
"( " + _LOCATE + 'for f in "$sl" "$sp"*.list "$sp"*.sources; do '
|
||||
'[ -f "$f" ] && grep -qF -- "{via}" "$f" || continue; '
|
||||
"sed -i -E '{lines} s#([[:space:]:]){via}#\\1https://#g' \"$f\" || exit 1; done )"
|
||||
)
|
||||
|
||||
|
||||
def cache_form(url: str) -> str:
|
||||
"""*url*, an https URL, in the form apt-cacher-ng fetches over https and stores.
|
||||
|
||||
:raises ValueError: if *url* is not an https URL.
|
||||
"""
|
||||
if not url.startswith("https://"):
|
||||
raise ValueError(f"not an https URL: {url!r}")
|
||||
return VIA_CACHE + url[len("https://") :]
|
||||
|
||||
|
||||
def _per_host_direct(report: AptProxyReportDict) -> set[str]:
|
||||
hosts = {**report["per_host"], **report["https_per_host"]}
|
||||
return {h.lower() for h, v in hosts.items() if v.lower() in _NO_PROXY}
|
||||
|
||||
|
||||
def _host_of(source: str) -> str | None:
|
||||
"""The host of an https source the cache can fetch: port 443, no login in the URL."""
|
||||
try:
|
||||
parts = urlsplit(source)
|
||||
port = parts.port
|
||||
except ValueError:
|
||||
return None
|
||||
if parts.username is not None or port not in (None, 443) or not parts.hostname:
|
||||
return None
|
||||
return parts.hostname
|
||||
|
||||
|
||||
def cacheable_https_hosts(report: AptProxyReportDict) -> list[str]:
|
||||
"""The hosts of the https sources the rewrite would send through the cache, sorted.
|
||||
|
||||
None while apt has no http proxy for every host: the cache form goes through it.
|
||||
Not a host apt fetches ``DIRECT``, nor one the rewrite left on https for its
|
||||
credentials (``not_cached``), nor one on another port or with a login in the URL.
|
||||
"""
|
||||
if not report["proxy"]:
|
||||
return []
|
||||
skip = _per_host_direct(report) | {h.lower() for h in report.get("not_cached", [])}
|
||||
hosts = {_host_of(s) for s in report["https_sources"]}
|
||||
return sorted(h for h in hosts if h and h.lower() not in skip)
|
||||
|
||||
|
||||
def is_host_name(host: str) -> bool:
|
||||
"""Whether *host* is a DNS name: letters, digits and hyphens between dots."""
|
||||
return bool(_HOST.match(host))
|
||||
|
||||
|
||||
def _checked(hosts: list[str]) -> str:
|
||||
for host in hosts:
|
||||
if not is_host_name(host):
|
||||
raise ValueError(f"not a host name: {host!r}")
|
||||
return " ".join(hosts)
|
||||
|
||||
|
||||
def rewrite_sources_command(
|
||||
hosts: list[str], proxy_file: str, apt_config: str = "apt-config"
|
||||
) -> str:
|
||||
"""The root command that sends the https sources of *hosts* through the cache.
|
||||
|
||||
A host apt has credentials for stays on https and is named in *proxy_file*.
|
||||
*apt_config* is how apt-config is called; a test points apt's paths elsewhere.
|
||||
|
||||
:raises ValueError: if one of *hosts* is not a host name.
|
||||
"""
|
||||
return _REWRITE.format(
|
||||
apt_config=apt_config,
|
||||
hosts=_checked(hosts),
|
||||
proxy_file=shlex.quote(proxy_file),
|
||||
key=NOT_CACHED_KEY,
|
||||
lines=_SOURCE_LINES,
|
||||
via=VIA_CACHE,
|
||||
)
|
||||
|
||||
|
||||
def revert_sources_command(apt_config: str = "apt-config") -> str:
|
||||
"""The root command that turns every source in the cache form back to https."""
|
||||
return _REVERT.format(apt_config=apt_config, lines=_SOURCE_LINES, via=VIA_CACHE)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"NOT_CACHED_KEY",
|
||||
"VIA_CACHE",
|
||||
"cache_form",
|
||||
"cacheable_https_hosts",
|
||||
"is_host_name",
|
||||
"revert_sources_command",
|
||||
"rewrite_sources_command",
|
||||
]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""The ``age`` of an entry in NAPALM's neighbour tables when the device does not say.
|
||||
|
||||
NAPALM requires an ``age`` on every entry of ``get_arp_table`` and
|
||||
``get_ipv6_neighbors_table``: seconds since the device last confirmed that
|
||||
neighbour. Many devices do not report one. ``0.0`` means "confirmed just now"
|
||||
and must never stand in for "not reported": a caller ranking sightings by
|
||||
freshness takes it at its word (NetOrk/netork#1327). An expiry countdown is not
|
||||
an age either. The value is NAPALM's own; its IOS driver reports ``-1.0``.
|
||||
"""
|
||||
|
||||
from typing import Final
|
||||
|
||||
ARP_AGE_UNKNOWN: Final[float] = -1.0
|
||||
@@ -0,0 +1,238 @@
|
||||
"""
|
||||
Abstract base class for backup server drivers.
|
||||
|
||||
Usage::
|
||||
|
||||
from napalm_device_types import BackupServerDriver, StorageDriver
|
||||
|
||||
class ProxmoxBackupDriver(BackupServerDriver, StorageDriver):
|
||||
def get_backup_datastores(self):
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.backups import (
|
||||
BackupDatastoreDict,
|
||||
BackupGroupDict,
|
||||
BackupJobKind,
|
||||
BackupRemoteDict,
|
||||
BackupServerJobDict,
|
||||
BackupSnapshotDict,
|
||||
BackupSnapshotRefDict,
|
||||
BackupTaskDict,
|
||||
BackupTaskStatusDict,
|
||||
)
|
||||
|
||||
|
||||
class BackupServerDriver(DeviceTypeDriver):
|
||||
"""
|
||||
Abstract intermediate driver for backup servers (e.g. Proxmox Backup
|
||||
Server): the device hypervisors and hosts write their backups to.
|
||||
|
||||
A backup server keeps its backups in datastores, one group per source (a
|
||||
VM, a container, a host) and one snapshot per backup run, and keeps them
|
||||
healthy with scheduled jobs: garbage collection, verify, prune, sync with
|
||||
other servers and tape. None of that is a storage pool, a volume or a
|
||||
replication job, so it is not modelled through ``StorageDriver``. A server
|
||||
that also manages its own disks and pools lists ``StorageDriver`` as a
|
||||
second role, after this one.
|
||||
|
||||
The actions start a task on the server and return at once with its id;
|
||||
:meth:`get_backup_task` follows it.
|
||||
"""
|
||||
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "backup_server"
|
||||
TYPE_LABEL: str = "Backup Server"
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# ------------------------------------------------------------------
|
||||
# Read
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_backup_datastores(self) -> list[BackupDatastoreDict]:
|
||||
"""
|
||||
Returns the server's datastores with their usage.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "store1",
|
||||
"path": "/mnt/datastore/store1",
|
||||
"backend": "local",
|
||||
"total": 4000787030016,
|
||||
"used": 1529008357376,
|
||||
"available": 2471778672640,
|
||||
"estimated_full": 1798761600,
|
||||
"maintenance": None,
|
||||
"comment": None,
|
||||
},
|
||||
]
|
||||
|
||||
:raises Exception: when the server could not be read; never an
|
||||
empty list for a failed read.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_backup_groups(self, datastore: str = "") -> list[BackupGroupDict]:
|
||||
"""
|
||||
Returns the backup groups of every namespace of *datastore*, or of
|
||||
every datastore when it is empty, each with its newest snapshot
|
||||
only. :meth:`get_backup_snapshots` lists all of a group's.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"datastore": "store1",
|
||||
"namespace": "",
|
||||
"type": "vm",
|
||||
"id": "101",
|
||||
"owner": "backup@pbs",
|
||||
"count": 14,
|
||||
"newest": {
|
||||
"time": 1793660400,
|
||||
"size": 34359738368,
|
||||
"verify": "ok",
|
||||
"protected": False,
|
||||
"comment": "web-01",
|
||||
},
|
||||
"oldest_time": 1792537200,
|
||||
"comment": None,
|
||||
},
|
||||
]
|
||||
|
||||
:raises Exception: when the server could not be read.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_backup_snapshots(
|
||||
self, datastore: str, namespace: str, group_type: str, group_id: str
|
||||
) -> list[BackupSnapshotDict]:
|
||||
"""
|
||||
Returns every snapshot of one group, newest first.
|
||||
|
||||
:param namespace: ``""`` for the datastore's root.
|
||||
:raises ValueError: when the datastore or the group does not exist.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_backup_jobs(self) -> list[BackupServerJobDict]:
|
||||
"""
|
||||
Returns the server's scheduled jobs of every kind, garbage
|
||||
collection included (one per datastore, ``id`` = the datastore).
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"id": "store1",
|
||||
"kind": "gc",
|
||||
"datastore": "store1",
|
||||
"namespace": None,
|
||||
"schedule": "daily",
|
||||
"enabled": True,
|
||||
"last_run": 1793664000,
|
||||
"last_state": "ok",
|
||||
"last_error": None,
|
||||
"next_run": 1793750400,
|
||||
"remote": None,
|
||||
"direction": None,
|
||||
"comment": None,
|
||||
},
|
||||
{
|
||||
"id": "offsite",
|
||||
"kind": "sync",
|
||||
"datastore": "store1",
|
||||
"namespace": "",
|
||||
"schedule": "sat 03:00",
|
||||
"enabled": True,
|
||||
"last_run": 1793502000,
|
||||
"last_state": "error",
|
||||
"last_error": "connection refused",
|
||||
"next_run": 1794106800,
|
||||
"remote": "pbs-offsite",
|
||||
"direction": "push",
|
||||
"comment": None,
|
||||
},
|
||||
]
|
||||
|
||||
:raises Exception: when the server could not be read.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_backup_remotes(self) -> list[BackupRemoteDict]:
|
||||
"""
|
||||
Returns the other backup servers this one syncs with, without their
|
||||
secrets.
|
||||
|
||||
:raises Exception: when the server could not be read.
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Actions
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def start_garbage_collection(self, datastore: str) -> BackupTaskDict:
|
||||
"""
|
||||
Starts garbage collection on *datastore*.
|
||||
|
||||
:raises ValueError: when the datastore does not exist.
|
||||
:raises RuntimeError: when the server refuses (e.g. one is running).
|
||||
"""
|
||||
...
|
||||
|
||||
def run_backup_job(self, kind: BackupJobKind, job_id: str) -> BackupTaskDict:
|
||||
"""
|
||||
Runs a scheduled job now, outside its schedule.
|
||||
|
||||
:param kind: a :data:`~napalm_device_types.backups.BackupJobKind`;
|
||||
``"gc"`` runs the datastore named *job_id*'s garbage collection.
|
||||
:raises ValueError: when there is no such job.
|
||||
:raises RuntimeError: when the server refuses.
|
||||
"""
|
||||
...
|
||||
|
||||
def verify_backup_snapshot(self, snapshot: BackupSnapshotRefDict) -> BackupTaskDict:
|
||||
"""
|
||||
Verifies one snapshot now.
|
||||
|
||||
:raises ValueError: when the snapshot does not exist.
|
||||
"""
|
||||
...
|
||||
|
||||
def set_backup_snapshot_protected(
|
||||
self, snapshot: BackupSnapshotRefDict, protected: bool
|
||||
) -> None:
|
||||
"""
|
||||
Protects a snapshot from pruning and deletion, or lifts that.
|
||||
|
||||
:raises ValueError: when the snapshot does not exist.
|
||||
"""
|
||||
...
|
||||
|
||||
def delete_backup_snapshot(self, snapshot: BackupSnapshotRefDict) -> None:
|
||||
"""
|
||||
Deletes one snapshot. The data is gone once garbage collection has
|
||||
run; there is no undo.
|
||||
|
||||
:raises ValueError: when the snapshot does not exist.
|
||||
:raises RuntimeError: when it is protected.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_backup_task(self, task: str) -> BackupTaskStatusDict:
|
||||
"""
|
||||
Returns the state and the log so far of a task an action started.
|
||||
|
||||
:raises ValueError: when the server does not know the task.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,119 @@
|
||||
"""The shapes of a backup server (``BackupServerDriver``).
|
||||
|
||||
Apart from ``models.py``, which is over the file size limit. A value the
|
||||
platform does not report is None; it is never guessed.
|
||||
"""
|
||||
|
||||
from typing import Literal, TypedDict, get_args
|
||||
|
||||
#: What a backup server's jobs do. Garbage collection is one of them: it has a
|
||||
#: schedule and a last run like the others.
|
||||
BackupJobKind = Literal["gc", "verify", "prune", "sync", "tape"]
|
||||
BACKUP_JOB_KINDS: tuple[str, ...] = get_args(BackupJobKind)
|
||||
|
||||
#: How a job's or a task's run ended; "running" while it has not.
|
||||
BackupRunState = Literal["ok", "warning", "error", "running"]
|
||||
|
||||
#: The outcome of the last verification of a snapshot.
|
||||
BackupVerifyState = Literal["ok", "failed"]
|
||||
|
||||
|
||||
class BackupDatastoreDict(TypedDict):
|
||||
"""A datastore: where a backup server keeps its backups."""
|
||||
|
||||
name: str
|
||||
path: str | None # local path; for an object-store backend the local cache, if any
|
||||
backend: str # "local", "s3", "removable", ... as the platform names it
|
||||
total: int | None # bytes
|
||||
used: int | None # bytes
|
||||
available: int | None # bytes
|
||||
estimated_full: int | None # unix seconds the platform expects it to be full
|
||||
maintenance: str | None # "read-only", "offline", ...; None when in service
|
||||
comment: str | None
|
||||
|
||||
|
||||
class BackupSnapshotDict(TypedDict):
|
||||
"""One backup of a group: the state of its source at one time."""
|
||||
|
||||
time: int # unix seconds the backup was taken
|
||||
size: int | None # bytes
|
||||
verify: BackupVerifyState | None # None: never verified
|
||||
protected: bool # exempt from pruning and deletion
|
||||
comment: str | None
|
||||
|
||||
|
||||
class BackupGroupDict(TypedDict):
|
||||
"""The backups of one source (a VM, a container, a host) in one namespace."""
|
||||
|
||||
datastore: str
|
||||
namespace: str # "" for the datastore's root
|
||||
type: str # "vm", "ct", "host"
|
||||
id: str # the guest's id ("101") or the host's name
|
||||
owner: str | None # the account that writes the group's backups
|
||||
count: int # snapshots in the group
|
||||
newest: BackupSnapshotDict | None # None for a group without a snapshot
|
||||
oldest_time: int | None # unix seconds of the oldest snapshot
|
||||
comment: str | None
|
||||
|
||||
|
||||
class BackupSnapshotRefDict(TypedDict):
|
||||
"""Names one snapshot, for an action on it."""
|
||||
|
||||
datastore: str
|
||||
namespace: str # "" for the datastore's root
|
||||
group_type: str # BackupGroupDict.type
|
||||
group_id: str # BackupGroupDict.id
|
||||
time: int # BackupSnapshotDict.time
|
||||
|
||||
|
||||
class BackupServerJobDict(TypedDict):
|
||||
"""A scheduled job of a backup server."""
|
||||
|
||||
id: str # for "gc", the datastore's name
|
||||
kind: BackupJobKind
|
||||
datastore: str | None
|
||||
namespace: str | None
|
||||
schedule: str | None # as the platform writes it: "daily", "sat 02:00", "*:0/30"
|
||||
enabled: bool
|
||||
last_run: int | None # unix seconds the last run ended (or started, while running)
|
||||
last_state: BackupRunState | None # None: never ran
|
||||
last_error: str | None
|
||||
next_run: int | None # unix seconds
|
||||
remote: str | None # a sync job's BackupRemoteDict.name
|
||||
direction: Literal["pull", "push"] | None # a sync job's
|
||||
comment: str | None
|
||||
|
||||
|
||||
class BackupRemoteDict(TypedDict):
|
||||
"""Another backup server this one syncs with. Never its secret."""
|
||||
|
||||
name: str
|
||||
host: str
|
||||
port: int | None
|
||||
fingerprint: str | None # of the remote's TLS certificate
|
||||
auth_id: str | None # the account the sync logs in as
|
||||
comment: str | None
|
||||
|
||||
|
||||
class BackupTaskDict(TypedDict):
|
||||
"""A task an action started on the server, to follow with ``get_backup_task``."""
|
||||
|
||||
task: str # the platform's task id
|
||||
|
||||
|
||||
class BackupTaskStatusDict(TypedDict):
|
||||
task: str
|
||||
running: bool
|
||||
state: BackupRunState | None # "running" while it runs
|
||||
error: str | None
|
||||
log: list[str] # the task's log lines so far
|
||||
|
||||
|
||||
class BackupServerRefDict(TypedDict):
|
||||
"""Which backup server and datastore a hypervisor's backup storage writes to."""
|
||||
|
||||
server: str # host name or address, as the hypervisor has it configured
|
||||
port: int | None
|
||||
datastore: str
|
||||
namespace: str | None
|
||||
fingerprint: str | None # of the server's TLS certificate, as the hypervisor pins it
|
||||
@@ -8,10 +8,16 @@ live connection.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import NamedTuple
|
||||
|
||||
from napalm.base import NetworkDriver
|
||||
|
||||
from napalm_device_types.channel import CommandChannelMixin
|
||||
from napalm_device_types.host_reboot import HostRebootMixin
|
||||
from napalm_device_types.host_shutdown import HostShutdownMixin
|
||||
from napalm_device_types.ping_sweep import PingSweepMixin
|
||||
|
||||
|
||||
class FingerprintRule(NamedTuple):
|
||||
"""Single pattern-matching rule for device fingerprinting.
|
||||
@@ -20,12 +26,36 @@ class FingerprintRule(NamedTuple):
|
||||
weight — evidence added to the driver's score on match
|
||||
mandatory — pattern absent → driver immediately disqualified
|
||||
negative — pattern present → weight subtracted instead of added
|
||||
group — rules sharing a group are alternatives that never match
|
||||
together (one vendor's landing page *or* another's); only the
|
||||
strongest of them counts towards the most a driver can score
|
||||
"""
|
||||
|
||||
pattern: str
|
||||
weight: float = 1.0
|
||||
mandatory: bool = False
|
||||
negative: bool = False
|
||||
group: str | None = None
|
||||
|
||||
|
||||
def rules_max_weight(rules: Iterable[FingerprintRule]) -> float:
|
||||
"""The most evidence *rules* can add together.
|
||||
|
||||
Every positive rule counts, except that a group of alternatives counts once,
|
||||
with its strongest rule. Discovery divides a driver's score by its maximum to
|
||||
compare drivers; summing alternatives would make a driver that recognises
|
||||
three vendors' pages lose to one that recognises none.
|
||||
"""
|
||||
total = 0.0
|
||||
group_best: dict[str, float] = {}
|
||||
for rule in rules:
|
||||
if rule.negative or rule.weight <= 0:
|
||||
continue
|
||||
if rule.group is None:
|
||||
total += rule.weight
|
||||
else:
|
||||
group_best[rule.group] = max(group_best.get(rule.group, 0.0), rule.weight)
|
||||
return total + sum(group_best.values())
|
||||
|
||||
|
||||
class PortSpec(NamedTuple):
|
||||
@@ -45,13 +75,21 @@ class PortSpec(NamedTuple):
|
||||
mandatory: bool = False
|
||||
|
||||
|
||||
class DeviceTypeDriver(NetworkDriver):
|
||||
class DeviceTypeDriver(
|
||||
PingSweepMixin,
|
||||
HostRebootMixin,
|
||||
HostShutdownMixin,
|
||||
CommandChannelMixin,
|
||||
NetworkDriver, # type: ignore[misc]
|
||||
):
|
||||
"""Common base for all netOrk device-type drivers.
|
||||
|
||||
Sits between napalm.base.NetworkDriver and the type-specific abstract
|
||||
classes (FirewallDriver, SwitchDriver, …). Adds the fingerprinting
|
||||
interface consumed by the discovery subsystem; does not implement any
|
||||
NAPALM abstract methods.
|
||||
interface consumed by the discovery subsystem plus the generic
|
||||
``ping_sweep()`` from :class:`~napalm_device_types.ping_sweep.PingSweepMixin`
|
||||
(usable by every driver that implements NAPALM's ``ping()``); does not
|
||||
implement any NAPALM abstract methods.
|
||||
|
||||
Override these class attributes in each concrete driver:
|
||||
|
||||
@@ -76,5 +114,15 @@ class DeviceTypeDriver(NetworkDriver):
|
||||
SSH_FINGERPRINT: list[FingerprintRule] = []
|
||||
HTTP_FINGERPRINT: list[FingerprintRule] = []
|
||||
OUI_PREFIXES: list[str] = []
|
||||
|
||||
#: Whether netOrk reaches this device over SSH. False for drivers that talk
|
||||
#: to a REST API instead -- which decides whether an SSH credential is worth
|
||||
#: asking for, and whether an SSH-shaped error message would even make sense.
|
||||
USES_SSH: bool = True
|
||||
|
||||
#: How long a reboot takes before the device is worth polling again, in
|
||||
#: seconds. Hypervisors and general-purpose OS hosts run through a full
|
||||
#: init sequence; a switch or an access point is back in half the time.
|
||||
REBOOT_SETTLE_SECONDS: int = 45
|
||||
# Format: "AA:BB:CC" — first 3 octets of MAC, uppercase, colon-separated.
|
||||
# A match contributes fixed weight 6.0 to the fingerprint score.
|
||||
@@ -0,0 +1,196 @@
|
||||
"""The command channel: a public way to run a command on a host, or open a stream.
|
||||
|
||||
A driver already reaches its host, over SSH, a REST API or WinRM. What it did
|
||||
not offer was a *public* way for the layer above to use that reach: netOrk sent
|
||||
shell strings through napalm-linux's private ``_send``, an interactive PTY that
|
||||
merges stdout and stderr and has no exit code.
|
||||
|
||||
:class:`CommandChannelMixin` declares two methods, and a driver that can
|
||||
implements them:
|
||||
|
||||
* :meth:`run_command` runs a command and returns stdout, stderr and the exit code.
|
||||
* :meth:`open_stream` starts a command and returns a :class:`ByteStream` to its
|
||||
stdin and stdout. That is how netOrk speaks the Docker Engine API, over
|
||||
``docker system dial-stdio`` (see :mod:`napalm_device_types.container_engine`).
|
||||
|
||||
Like the role bases, the mixin only declares (under ``TYPE_CHECKING``), so
|
||||
``hasattr(driver, "run_command")`` stays a truthful answer.
|
||||
|
||||
:func:`run_on_transport` and :func:`open_stream_on_transport` are the SSH
|
||||
implementation over a paramiko ``Transport``, for any SSH driver: an exec
|
||||
channel, so no PTY, separate stderr and a real exit status. How a command gains
|
||||
root (``sudo -S`` with the password on stdin, ``sudo -n``, or nothing as root)
|
||||
stays with the driver.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple, Protocol, cast
|
||||
|
||||
#: How much of a stream's stderr is kept. Enough to tell "permission denied"
|
||||
#: from "no such command"; a stream that writes megabytes there keeps its tail.
|
||||
STDERR_TAIL = 64 * 1024
|
||||
|
||||
_READ = 32 * 1024
|
||||
_POLL = 0.01
|
||||
|
||||
|
||||
class CommandResult(NamedTuple):
|
||||
"""What a command printed, and how it ended."""
|
||||
|
||||
stdout: str
|
||||
stderr: str
|
||||
exit_code: int
|
||||
|
||||
|
||||
class ByteStream(Protocol):
|
||||
"""A running command's stdin and stdout, as bytes.
|
||||
|
||||
``read`` returns ``b""`` at end of stream and raises :class:`TimeoutError`
|
||||
when nothing arrives in time. ``write`` never closes anything:
|
||||
``dial-stdio`` hands the daemon a half-close as "client gone", and the
|
||||
daemon then answers an unfinished request with HTTP 499 (netork#771). Only
|
||||
``close_write`` closes the writing side.
|
||||
"""
|
||||
|
||||
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: ...
|
||||
|
||||
def write(self, data: bytes) -> None: ...
|
||||
|
||||
def close_write(self) -> None: ...
|
||||
|
||||
def close(self) -> None: ...
|
||||
|
||||
@property
|
||||
def exit_status(self) -> int | None: ...
|
||||
|
||||
@property
|
||||
def stderr(self) -> str: ...
|
||||
|
||||
|
||||
class CommandChannelMixin:
|
||||
"""Declares the channel; a driver that can reach a shell on its host implements it."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
"""Run *command* with the host's shell; *stdin*, if given, is written first."""
|
||||
...
|
||||
|
||||
def open_stream(self, command: str, *, privileged: bool = False) -> ByteStream:
|
||||
"""Start *command* and return a stream to its stdin and stdout."""
|
||||
...
|
||||
|
||||
|
||||
class ParamikoExecStream:
|
||||
"""A :class:`ByteStream` over a paramiko exec channel.
|
||||
|
||||
stderr is drained on every read: stdout and stderr share one window, and an
|
||||
unread stderr would stall the stream.
|
||||
"""
|
||||
|
||||
def __init__(self, channel: Any, *, stderr_limit: int = STDERR_TAIL) -> None:
|
||||
self._channel = channel
|
||||
self._stderr = b""
|
||||
self._limit = stderr_limit
|
||||
|
||||
def _drain_stderr(self) -> None:
|
||||
while self._channel.recv_stderr_ready():
|
||||
self._stderr = (self._stderr + self._channel.recv_stderr(_READ))[-self._limit :]
|
||||
|
||||
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
||||
self._channel.settimeout(timeout)
|
||||
try:
|
||||
return cast(bytes, self._channel.recv(max_bytes))
|
||||
except TimeoutError:
|
||||
raise TimeoutError(f"no data within {timeout}s") from None
|
||||
finally:
|
||||
self._drain_stderr()
|
||||
|
||||
def write(self, data: bytes) -> None:
|
||||
self._channel.sendall(data)
|
||||
|
||||
def close_write(self) -> None:
|
||||
self._channel.shutdown_write()
|
||||
|
||||
def close(self) -> None:
|
||||
self._channel.close()
|
||||
|
||||
@property
|
||||
def exit_status(self) -> int | None:
|
||||
if not self._channel.exit_status_ready():
|
||||
return None
|
||||
return cast(int, self._channel.recv_exit_status())
|
||||
|
||||
@property
|
||||
def stderr(self) -> str:
|
||||
self._drain_stderr()
|
||||
return self._stderr.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _collect(channel: Any, command: str, timeout: float) -> tuple[bytes, bytes]:
|
||||
out, err = b"", b""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
if channel.recv_ready():
|
||||
out += channel.recv(_READ)
|
||||
elif channel.recv_stderr_ready():
|
||||
err += channel.recv_stderr(_READ)
|
||||
elif channel.exit_status_ready():
|
||||
# sshd may send the exit status before the last output: read both to EOF.
|
||||
try:
|
||||
while chunk := channel.recv(_READ):
|
||||
out += chunk
|
||||
while chunk := channel.recv_stderr(_READ):
|
||||
err += chunk
|
||||
except TimeoutError:
|
||||
raise TimeoutError(f"{command!r} did not finish within {timeout}s") from None
|
||||
return out, err
|
||||
elif time.monotonic() > deadline:
|
||||
raise TimeoutError(f"{command!r} did not finish within {timeout}s")
|
||||
else:
|
||||
time.sleep(_POLL)
|
||||
|
||||
|
||||
def run_on_transport(
|
||||
transport: Any, command: str, *, stdin: bytes | None = None, timeout: float = 60
|
||||
) -> CommandResult:
|
||||
"""Run *command* on an exec channel of the paramiko *transport*."""
|
||||
channel = transport.open_session()
|
||||
try:
|
||||
channel.settimeout(timeout)
|
||||
channel.exec_command(command)
|
||||
if stdin is not None:
|
||||
channel.sendall(stdin)
|
||||
channel.shutdown_write()
|
||||
out, err = _collect(channel, command, timeout)
|
||||
return CommandResult(
|
||||
out.decode("utf-8", "replace"),
|
||||
err.decode("utf-8", "replace"),
|
||||
channel.recv_exit_status(),
|
||||
)
|
||||
finally:
|
||||
channel.close()
|
||||
|
||||
|
||||
def open_stream_on_transport(
|
||||
transport: Any, command: str, *, stdin_prefix: bytes | None = None
|
||||
) -> ParamikoExecStream:
|
||||
"""Start *command* on an exec channel and return its stream.
|
||||
|
||||
*stdin_prefix* is written before anything else, which is how a sudo password
|
||||
reaches ``sudo -S`` ahead of the stream's own bytes.
|
||||
"""
|
||||
channel = transport.open_session()
|
||||
channel.exec_command(command)
|
||||
if stdin_prefix:
|
||||
channel.sendall(stdin_prefix)
|
||||
return ParamikoExecStream(channel)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""The shapes of a hypervisor's clusters (``HypervisorDriver.get_clusters()``).
|
||||
|
||||
Apart from ``models.py``, which is over the file size limit.
|
||||
"""
|
||||
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
from napalm_device_types.backups import BackupServerRefDict
|
||||
|
||||
|
||||
class ClusterNodeDict(TypedDict):
|
||||
"""One host of a cluster, as its cluster sees it. A value the platform does not
|
||||
report is None; it is never guessed."""
|
||||
|
||||
name: str # the node's name in its cluster, as get_vms() reports it in ``node``
|
||||
status: str # "online", "offline" or "unknown"
|
||||
local: bool # the node this connection talks to; False on a manager (vCenter)
|
||||
maintenance: bool | None # in maintenance mode
|
||||
cpu_threads: int | None # logical CPUs
|
||||
cpu_cores: int | None # physical cores
|
||||
cpu_model: str | None
|
||||
cpu_flags: list[str] | None # cpuinfo flags; None where the platform does not say
|
||||
cpu_usage: float | None # 0.0–1.0
|
||||
memory_total: int | None # bytes
|
||||
memory_used: int | None # bytes
|
||||
votes: NotRequired[int | None] # quorum votes of this node; None standalone/unreadable
|
||||
|
||||
|
||||
class ClusterStorageDict(TypedDict):
|
||||
"""A storage of a cluster and the nodes that see it."""
|
||||
|
||||
name: str # usable as create_vm_from_cloud_init(storage=...) on each of ``nodes``
|
||||
type: str # backend type: "dir", "lvmthin", "zfspool", "nfs", "rbd", "vmfs", ...
|
||||
shared: bool # the same storage on every node in ``nodes``, so a VM on it can move
|
||||
content: list[str] # what it holds: "images", "iso", "snippets", ...
|
||||
nodes: list[str] # the nodes it is available on
|
||||
total: int | None # bytes; None where the platform does not report it
|
||||
used: int | None # bytes
|
||||
# A backup storage that writes to a backup server: which one. Left out for every
|
||||
# other storage; None where the platform does not say.
|
||||
backup_server: NotRequired[BackupServerRefDict | None]
|
||||
|
||||
|
||||
class ClusterNetworkDict(TypedDict):
|
||||
"""A network a VM's NIC may attach to, and the nodes that carry it."""
|
||||
|
||||
name: str # usable as NICConfigDict.bridge on each of ``nodes``
|
||||
kind: str # "bridge", "vnet" or "portgroup", as in NetworkTargetDict
|
||||
vlan_aware: bool # True if a NICConfigDict.vlan_tag may be set on top of it
|
||||
fixed_vlan_tag: NotRequired[int | None] # vnet/portgroup: the VLAN baked into it
|
||||
nodes: list[str]
|
||||
|
||||
|
||||
class HAResourceDict(TypedDict):
|
||||
"""A guest the cluster's HA manager looks after."""
|
||||
|
||||
vmid: int
|
||||
kind: str # "qemu" or "lxc"
|
||||
requested: str # state HA is asked to keep: "started", "stopped", "disabled", "ignored"
|
||||
status: str | None # what the HA manager reports now: "started", "fence", "migrate", ...
|
||||
node: str | None # the node the HA manager places it on now
|
||||
group: NotRequired[str | None] # HA group (Proxmox VE 8)
|
||||
rules: list[str] # ids of the HA rules that name it (Proxmox VE 9); [] where there are none
|
||||
|
||||
|
||||
class BackupJobDict(TypedDict):
|
||||
"""A scheduled backup job of the cluster."""
|
||||
|
||||
id: str
|
||||
enabled: bool
|
||||
schedule: str | None # as the platform writes it: "sat 02:00", "daily", "mon..fri 21:00"
|
||||
storage: str | None
|
||||
mode: str | None # "snapshot", "suspend", "stop"
|
||||
all: bool # every guest, minus ``exclude``
|
||||
vmids: list[int] # the guests it names; a pool job: the pool's members now; [] with all
|
||||
exclude: list[int]
|
||||
pool: str | None
|
||||
node: str | None # the one node it runs on; None for every node
|
||||
|
||||
|
||||
class BackupDict(TypedDict):
|
||||
"""The backups of one guest on one storage."""
|
||||
|
||||
vmid: int
|
||||
storage: str
|
||||
time: int # unix seconds of the newest backup of this guest on this storage
|
||||
size: int | None # bytes of that newest backup
|
||||
count: int # backups of this guest on this storage
|
||||
|
||||
|
||||
class ClusterDict(TypedDict):
|
||||
"""A cluster the connection can see. A standalone host is a cluster of one,
|
||||
with no name."""
|
||||
|
||||
id: str | None # stable across connections where the platform has one; None otherwise
|
||||
name: str | None # the cluster's name; None for a standalone host
|
||||
quorate: bool | None # None where the platform has no quorum (standalone, vSphere)
|
||||
nodes: list[ClusterNodeDict]
|
||||
storages: list[ClusterStorageDict]
|
||||
networks: list[ClusterNetworkDict]
|
||||
# None: could not be read; []: read, nothing there.
|
||||
ha_resources: NotRequired[list[HAResourceDict] | None]
|
||||
backup_jobs: NotRequired[list[BackupJobDict] | None]
|
||||
backups: NotRequired[list[BackupDict] | None]
|
||||
@@ -1,8 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
from typing import ClassVar
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from napalm.base.exceptions import (
|
||||
CommandErrorException,
|
||||
@@ -39,15 +38,13 @@ class ConfigLifecycleMixin:
|
||||
|
||||
_comment_chars: ClassVar[tuple[str, ...]] = ("!", "#")
|
||||
|
||||
def _get_running_config(self) -> str:
|
||||
raise NotImplementedError
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def commit_config(self, message: str = "", revert_in: int | None = None) -> None:
|
||||
raise NotImplementedError
|
||||
def _get_running_config(self) -> str: ...
|
||||
|
||||
def load_merge_candidate(
|
||||
self, filename: str | None = None, config: str | None = None
|
||||
) -> None:
|
||||
def commit_config(self, message: str = "", revert_in: int | None = None) -> None: ...
|
||||
|
||||
def load_merge_candidate(self, filename: str | None = None, config: str | None = None) -> None:
|
||||
if filename is not None:
|
||||
try:
|
||||
with open(filename) as fh:
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""A device's own configuration history: list it, read a revision, revert to one.
|
||||
|
||||
Some devices keep their earlier configurations themselves: a copy of the
|
||||
configuration for every save, which the device can go back to. An application
|
||||
restores a configuration there by reverting to the revision that holds it -- on a
|
||||
device whose API takes no uploaded configuration (OPNsense), the only way
|
||||
(NetOrk/netork#2511). :class:`ConfigRevisionsMixin` is the contract:
|
||||
|
||||
* ``get_config_revisions()`` and ``get_config_revision(revision_id)`` -- declared
|
||||
only, so ``callable(getattr(driver, "get_config_revisions", None))`` is the
|
||||
truthful answer to "does this device keep a history";
|
||||
* ``revert_config_revision(revision_id)`` -- a template: it refuses an id that is not
|
||||
in the history, reads the revision, lets the driver revert
|
||||
(``_revert_to_config_revision``), and reads the configuration in place afterwards
|
||||
to check that it holds the revision's. A device may answer that it reverted when it
|
||||
did not; the check does not take its word;
|
||||
* ``config_revision_content(text)`` -- what of a revision is its configuration. Every
|
||||
save may stamp a revision anew (OPNsense writes who saved it and when into
|
||||
config.xml), so two revisions with the same configuration differ as text. A driver
|
||||
whose device does that strips the stamp here; by default the whole text counts. An
|
||||
application that looks for the revision holding a configuration compares through
|
||||
it too.
|
||||
|
||||
A driver mixes it in when its device keeps a history; no role base carries it. One
|
||||
that can list the history but not revert to it sets ``revert_config_revision`` to
|
||||
``None``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
|
||||
class ConfigRevisionDict(TypedDict):
|
||||
"""One revision of the device's configuration (``get_config_revisions``)."""
|
||||
|
||||
id: str # what get_config_revision and revert_config_revision take, as the device names it
|
||||
time: str | None # when it was saved, UTC ISO 8601; None when the device does not say
|
||||
description: str | None # what made the change, as the device records it; None: none
|
||||
user: str | None # who saved it, as the device names them; None when it names nobody
|
||||
size: int | None # its size in bytes; None when not given
|
||||
|
||||
|
||||
class UnknownConfigRevision(ValueError):
|
||||
"""The device's configuration history has no revision of that id."""
|
||||
|
||||
def __init__(self, revision_id: object) -> None:
|
||||
super().__init__(f"no configuration revision {revision_id!r} in the device's history")
|
||||
|
||||
|
||||
class ConfigRevertFailed(RuntimeError):
|
||||
"""The device refused the revert, or its configuration afterwards is not the revision's."""
|
||||
|
||||
|
||||
class ConfigRevisionsMixin:
|
||||
"""List, read and revert to the device's configuration revisions; see the module."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_config_revisions(self) -> list[ConfigRevisionDict]:
|
||||
"""The device's configuration history, newest first.
|
||||
|
||||
The first revision is the configuration in place now.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"id": "config-1794603885.1239.xml",
|
||||
"time": "2026-11-13T21:04:45+00:00",
|
||||
"description": "/api/firewall/filter/apply made changes",
|
||||
"user": "apiuser@192.0.2.10",
|
||||
"size": 58213,
|
||||
},
|
||||
]
|
||||
|
||||
:raises Exception: when the history could not be read; never an empty
|
||||
list for a failed read.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_config_revision(self, revision_id: str) -> str:
|
||||
"""The configuration of revision *revision_id*, as the device keeps it.
|
||||
|
||||
:raises UnknownConfigRevision: for an id that is not in the history.
|
||||
:raises Exception: when the device could not be read.
|
||||
"""
|
||||
...
|
||||
|
||||
# The step a driver implements:
|
||||
|
||||
def _revert_to_config_revision(self, revision_id: str) -> None:
|
||||
"""Make revision *revision_id* the device's configuration; return once it is
|
||||
in place, as the newest revision of the history.
|
||||
|
||||
:raises UnknownConfigRevision: when the device no longer has it.
|
||||
:raises ConfigRevertFailed: when the device refuses.
|
||||
"""
|
||||
...
|
||||
|
||||
def config_revision_content(self, text: str) -> str:
|
||||
"""What of a revision's *text* is its configuration: the whole text by default.
|
||||
|
||||
A driver whose device stamps every save into the configuration (who, when)
|
||||
returns the text without that stamp, so that two revisions with the same
|
||||
configuration compare equal.
|
||||
"""
|
||||
return text
|
||||
|
||||
def revert_config_revision(self, revision_id: str) -> ConfigRevisionDict:
|
||||
"""Make revision *revision_id* the device's configuration again.
|
||||
|
||||
Returns the revision in place afterwards: the newest of the history, which
|
||||
holds the configuration of *revision_id* (on most devices a new revision the
|
||||
revert saved). What the device does beyond that -- reload its services,
|
||||
restart, nothing -- is the driver's to document.
|
||||
|
||||
:raises UnknownConfigRevision: for an id that is not in the history now;
|
||||
nothing has changed then.
|
||||
:raises ConfigRevertFailed: when the device refuses, or when the configuration
|
||||
in place afterwards is not the revision's.
|
||||
:raises Exception: when the device could not be reached.
|
||||
"""
|
||||
if revision_id not in {r["id"] for r in self.get_config_revisions()}:
|
||||
raise UnknownConfigRevision(revision_id)
|
||||
# Read before the revert: saving it may rotate the revision out of the history.
|
||||
wanted = self.config_revision_content(self.get_config_revision(revision_id))
|
||||
self._revert_to_config_revision(revision_id)
|
||||
revisions = self.get_config_revisions()
|
||||
if not revisions:
|
||||
raise ConfigRevertFailed(
|
||||
f"the device has no configuration after reverting to {revision_id!r}"
|
||||
)
|
||||
now = revisions[0]
|
||||
if self.config_revision_content(self.get_config_revision(now["id"])) != wanted:
|
||||
raise ConfigRevertFailed(
|
||||
f"the configuration in place ({now['id']!r}) is not revision {revision_id!r}"
|
||||
" after the revert"
|
||||
)
|
||||
return now
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Configuration sync between the two hosts of an HA pair.
|
||||
|
||||
A host that pushes its configuration to a peer (OPNsense's XMLRPC sync, say)
|
||||
makes the peer's configuration of the synced services a copy of its own: a
|
||||
change written on the receiving side lasts only until the next push. Who pushes
|
||||
what is therefore a fact a caller needs before it writes to either host.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder. A driver
|
||||
mixes it in; no role promises it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import ConfigSyncDict
|
||||
|
||||
|
||||
class ConfigSyncMixin:
|
||||
"""Where a host pushes its configuration, and for which of its services."""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_config_sync(self) -> ConfigSyncDict:
|
||||
"""
|
||||
Returns the peer this host pushes its configuration to (None when it
|
||||
pushes to no one) and the services whose configuration it pushes, by
|
||||
the name ``get_services`` reports. Sync items the driver has no
|
||||
service name for are listed under ``unmapped`` as the host names them.
|
||||
|
||||
:raises Exception: When the setting could not be read -- never
|
||||
``peer=None`` for "could not ask".
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Access to a host's container engine, and nothing more.
|
||||
|
||||
This package abstracts the connection, the driver builds it, and netOrk does
|
||||
the talking (NetOrk/netork#765). So there is no container model here and no
|
||||
parsing:
|
||||
|
||||
* :meth:`ContainerEngineMixin.container_engines` says which engines the host
|
||||
offers, and which API each speaks.
|
||||
* :meth:`ContainerEngineMixin.open_container_engine` returns a
|
||||
:class:`ContainerEngineConnection`. It opens a stream to the engine's API
|
||||
(``docker system dial-stdio``), and it runs the engine's CLI with arguments
|
||||
the caller chooses. The CLI is there for what the API cannot do: compose,
|
||||
pulls that need the host user's registry login, and private registry digests.
|
||||
|
||||
The driver decides *how* the engine is reached. The hook is
|
||||
:meth:`ContainerEngineMixin._container_engine_binary`. QNAP returns its
|
||||
Container Station path, so callers never see where the binary lives. The
|
||||
command runs through the driver's own :class:`~napalm_device_types.channel.CommandChannelMixin`,
|
||||
whose privilege handling applies unchanged; Docker normally needs none, because
|
||||
the login user is in the ``docker`` group.
|
||||
|
||||
Mixed in by a driver, not by a role base: a Windows host is an
|
||||
:class:`~napalm_device_types.os.OSDriver` too, and without a shell channel it
|
||||
has no ``dial-stdio`` to offer. ``hasattr(driver, "open_container_engine")``
|
||||
stays truthful.
|
||||
|
||||
**Which engine a CLI is.** An engine is listed when its CLI answers
|
||||
``--version`` with its own name: ``Docker version 29.0.1, build …``, ``podman
|
||||
version 5.2.2``. podman-docker installs a ``docker`` that is podman; listed as
|
||||
Docker it would be read twice, the second time as the login user's rootless
|
||||
Podman (NetOrk/netork#818).
|
||||
|
||||
**Podman as root.** The Podman this reaches is the host's *rootful* one: the
|
||||
engine of the system's containers, whose units Quadlet generates from
|
||||
``/etc/containers/systemd`` and whose API ``podman.socket`` serves at
|
||||
``/run/podman/podman.sock``. Rootless containers belong to the user who runs
|
||||
them, in that user's own storage, and no other login sees them. So the
|
||||
connection to Podman runs every call as root (``privileged``), the way the
|
||||
driver gains root for any command: root itself, or sudo. ``podman system
|
||||
dial-stdio`` exists from Podman 4.0 on; it reaches the API socket, which has
|
||||
to be listening (``systemctl enable --now podman.socket``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from napalm_device_types.channel import ByteStream, CommandResult
|
||||
from napalm_device_types.models import ContainerEngineDict, FixResultDict
|
||||
|
||||
#: Engines this package knows how to reach, and the API each speaks. Podman's
|
||||
#: is its own service, which serves Docker's API next to libpod's.
|
||||
ENGINES: dict[str, str] = {"docker": "docker-engine", "podman": "podman-libpod"}
|
||||
#: Engines reached as root: rootful Podman's socket is root's (see above).
|
||||
ROOT_ENGINES: frozenset[str] = frozenset({"podman"})
|
||||
|
||||
_PROBE_TIMEOUT = 15
|
||||
_CLI_TIMEOUT = 120
|
||||
|
||||
|
||||
class ContainerEngineUnavailable(NotImplementedError):
|
||||
"""The host offers no such engine, or this package does not know how to reach it."""
|
||||
|
||||
|
||||
class ContainerEngineConnection:
|
||||
"""The way to one container engine on one host.
|
||||
|
||||
Built by :meth:`ContainerEngineMixin.open_container_engine`. Callers pass
|
||||
arguments; binary, quoting and the channel are the driver's.
|
||||
"""
|
||||
|
||||
def __init__(self, driver: Any, engine: str, binary: str, *, privileged: bool = False) -> None:
|
||||
self._driver = driver
|
||||
self._binary = binary
|
||||
self.engine = engine
|
||||
#: Every call runs as root: the engine is root's (rootful Podman).
|
||||
self.privileged = privileged
|
||||
|
||||
def _command(self, args: Sequence[str]) -> str:
|
||||
return shlex.join([self._binary, *args])
|
||||
|
||||
def open_api(self) -> ByteStream:
|
||||
"""A stream to the engine's API: HTTP/1.1 over ``system dial-stdio``."""
|
||||
return cast(
|
||||
ByteStream,
|
||||
self._driver.open_stream(
|
||||
self._command(["system", "dial-stdio"]), privileged=self.privileged
|
||||
),
|
||||
)
|
||||
|
||||
def run_cli(
|
||||
self,
|
||||
args: Sequence[str],
|
||||
*,
|
||||
stdin: bytes | None = None,
|
||||
timeout: float = _CLI_TIMEOUT,
|
||||
privileged: bool = False,
|
||||
) -> CommandResult:
|
||||
"""Run the engine's CLI with *args* and wait for it.
|
||||
|
||||
*privileged* runs it as root, the way the driver gains root for any
|
||||
command: for a call the engine refused to the login user.
|
||||
"""
|
||||
return cast(
|
||||
CommandResult,
|
||||
self._driver.run_command(
|
||||
self._command(args),
|
||||
privileged=privileged or self.privileged,
|
||||
timeout=timeout,
|
||||
stdin=stdin,
|
||||
),
|
||||
)
|
||||
|
||||
def stream_cli(
|
||||
self, args: Sequence[str], *, merge_stderr: bool = False, privileged: bool = False
|
||||
) -> ByteStream:
|
||||
"""Start the engine's CLI with *args* and stream its output.
|
||||
|
||||
*merge_stderr* folds stderr into the stream, for tools that report
|
||||
progress there (``compose up``); *privileged* as for :meth:`run_cli`.
|
||||
"""
|
||||
command = self._command(args)
|
||||
return cast(
|
||||
ByteStream,
|
||||
self._driver.open_stream(
|
||||
f"{command} 2>&1" if merge_stderr else command,
|
||||
privileged=privileged or self.privileged,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class ContainerEngineMixin:
|
||||
"""Adds container engine access to a driver that implements the channel."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def open_stream(self, command: str, *, privileged: bool = False) -> ByteStream: ...
|
||||
|
||||
def grant_container_engine_access(self, user: str) -> FixResultDict:
|
||||
"""Let *user* reach the container engine without privilege (the
|
||||
``docker`` group on most hosts). A fix template: see
|
||||
:mod:`napalm_device_types.fixes`. Declared only; a driver implements it."""
|
||||
...
|
||||
|
||||
def _container_engine_binary(self, engine: str) -> str:
|
||||
"""The host command that is *engine*'s CLI. Override where it is not on PATH."""
|
||||
return engine
|
||||
|
||||
def container_engines(self) -> list[ContainerEngineDict]:
|
||||
"""
|
||||
Returns the container engines the host offers:
|
||||
|
||||
* engine (string) - e.g. "docker"
|
||||
* api (string) - what its API is, e.g. "docker-engine"
|
||||
|
||||
An engine is listed when its CLI exists on the host and names itself
|
||||
when asked for its version: podman-docker's ``docker`` says it is podman,
|
||||
and is left out. Whether the login user may use the engine is decided by
|
||||
the first API call, which says "permission denied" in the stream's stderr.
|
||||
"""
|
||||
return [
|
||||
{"engine": engine, "api": api}
|
||||
for engine, api in ENGINES.items()
|
||||
if self._answers_as(engine)
|
||||
]
|
||||
|
||||
def _answers_as(self, engine: str) -> bool:
|
||||
"""Whether *engine*'s CLI is on the host and says it is *engine*."""
|
||||
binary = shlex.quote(self._container_engine_binary(engine))
|
||||
probe = f"command -v {binary} >/dev/null 2>&1 && {binary} --version"
|
||||
result = self.run_command(probe, timeout=_PROBE_TIMEOUT)
|
||||
words = result.stdout.split()
|
||||
return result.exit_code == 0 and bool(words) and words[0].lower() == engine
|
||||
|
||||
def open_container_engine(self, engine: str) -> ContainerEngineConnection:
|
||||
"""The connection to *engine*; :class:`ContainerEngineUnavailable` if unknown."""
|
||||
if engine not in ENGINES:
|
||||
raise ContainerEngineUnavailable(f"no way to reach container engine {engine!r}")
|
||||
return ContainerEngineConnection(
|
||||
self,
|
||||
engine,
|
||||
self._container_engine_binary(engine),
|
||||
privileged=engine in ROOT_ENGINES,
|
||||
)
|
||||
@@ -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}
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Cron expressions: what they mean, when they fire next, and as systemd ``OnCalendar``.
|
||||
|
||||
A scheduled job is given as a cron expression on every host, and a host with
|
||||
systemd runs it as a timer. So the expression has to mean the same in three
|
||||
places -- on the host's cron, in a preview of the next runs, and in the
|
||||
``OnCalendar`` lines a timer is written with -- and the meaning lives here once.
|
||||
|
||||
**What cron means is Vixie cron's.** Five fields (minute, hour, day of month,
|
||||
month, day of week), each ``*``, a value, a range ``a-b``, a step ``*/n`` or
|
||||
``a-b/n``, or a list of those; month and weekday names in any case; ``7`` is
|
||||
Sunday as well as ``0``; the ``@hourly`` … ``@yearly`` aliases. When both day
|
||||
fields are restricted -- neither starts with ``*`` -- a day matches if *either*
|
||||
does; otherwise both must (``*/2`` counts as starting with ``*``).
|
||||
|
||||
**``OnCalendar`` by expansion.** Every field is written as its values, so a range
|
||||
with a step needs no systemd syntax of its own, and a timer fires on exactly the
|
||||
minutes cron would. The *either* rule is two ``OnCalendar`` lines, which systemd
|
||||
ORs. ``@reboot`` has no calendar; a timer takes it as ``OnBootSec``.
|
||||
|
||||
**Next runs are in the host's time zone.** A local time the clock skips when
|
||||
summer time starts is left out; cron implementations disagree on it, and a
|
||||
preview that promised it would promise too much.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import NamedTuple
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
REBOOT = "@reboot"
|
||||
|
||||
ALIASES = {
|
||||
"@yearly": "0 0 1 1 *",
|
||||
"@annually": "0 0 1 1 *",
|
||||
"@monthly": "0 0 1 * *",
|
||||
"@weekly": "0 0 * * 0",
|
||||
"@daily": "0 0 * * *",
|
||||
"@midnight": "0 0 * * *",
|
||||
"@hourly": "0 * * * *",
|
||||
}
|
||||
|
||||
_MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")
|
||||
_WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
|
||||
_SYSTEMD_WEEKDAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
|
||||
|
||||
#: (lowest, highest, names) per field; a name stands for its index plus the lowest.
|
||||
_FIELDS = (
|
||||
(0, 59, ()),
|
||||
(0, 23, ()),
|
||||
(1, 31, ()),
|
||||
(1, 12, _MONTHS),
|
||||
(0, 7, _WEEKDAYS),
|
||||
)
|
||||
|
||||
#: How far ahead a next run is looked for: a 29 February comes within eight years.
|
||||
_HORIZON_DAYS = 8 * 366
|
||||
|
||||
|
||||
class CronSchedule(NamedTuple):
|
||||
"""An expression's values per field, and whether a day matches on either day field."""
|
||||
|
||||
minutes: frozenset[int]
|
||||
hours: frozenset[int]
|
||||
days: frozenset[int]
|
||||
months: frozenset[int]
|
||||
weekdays: frozenset[int] # 0 = Sunday
|
||||
either_day: bool
|
||||
|
||||
|
||||
def is_reboot(expr: str) -> bool:
|
||||
"""Whether *expr* is ``@reboot``: once at boot, no calendar."""
|
||||
return expr.strip().lower() == REBOOT
|
||||
|
||||
|
||||
def _value(token: str, low: int, names: tuple[str, ...]) -> int:
|
||||
if token.isdigit():
|
||||
return int(token)
|
||||
if token.lower() in names:
|
||||
return names.index(token.lower()) + low
|
||||
raise ValueError(f"not a value: {token!r}")
|
||||
|
||||
|
||||
def _part(part: str, low: int, high: int, names: tuple[str, ...]) -> set[int]:
|
||||
span, _, step_text = part.partition("/")
|
||||
step = 1
|
||||
if step_text:
|
||||
if not step_text.isdigit() or int(step_text) == 0:
|
||||
raise ValueError(f"not a step: {part!r}")
|
||||
step = int(step_text)
|
||||
if span == "*":
|
||||
first, last = low, high
|
||||
elif "-" in span:
|
||||
a, _, b = span.partition("-")
|
||||
first, last = _value(a, low, names), _value(b, low, names)
|
||||
else:
|
||||
first = _value(span, low, names)
|
||||
last = high if step_text else first
|
||||
if not low <= first <= last <= high:
|
||||
raise ValueError(f"out of range {low}-{high}: {part!r}")
|
||||
return set(range(first, last + 1, step))
|
||||
|
||||
|
||||
def _field(text: str, low: int, high: int, names: tuple[str, ...]) -> frozenset[int]:
|
||||
values: set[int] = set()
|
||||
for part in text.split(","):
|
||||
if not part:
|
||||
raise ValueError(f"empty list item in {text!r}")
|
||||
values |= _part(part, low, high, names)
|
||||
return frozenset(values)
|
||||
|
||||
|
||||
def parse_cron(expr: str) -> CronSchedule:
|
||||
"""The values *expr* stands for.
|
||||
|
||||
:raises ValueError: for anything Vixie cron would not take, and for
|
||||
``@reboot``, which names no time.
|
||||
"""
|
||||
text = expr.strip()
|
||||
if is_reboot(text):
|
||||
raise ValueError("@reboot names no time; it runs once at boot")
|
||||
if text.startswith("@"):
|
||||
if text.lower() not in ALIASES:
|
||||
raise ValueError(f"unknown alias {text!r}")
|
||||
text = ALIASES[text.lower()]
|
||||
fields = text.split()
|
||||
if len(fields) != len(_FIELDS):
|
||||
raise ValueError(f"a cron expression has five fields, not {len(fields)}: {expr!r}")
|
||||
minutes, hours, days, months, weekdays = (
|
||||
_field(f, low, high, names) for f, (low, high, names) in zip(fields, _FIELDS, strict=True)
|
||||
)
|
||||
if 7 in weekdays:
|
||||
weekdays = (weekdays - {7}) | {0}
|
||||
either = not fields[2].startswith("*") and not fields[4].startswith("*")
|
||||
return CronSchedule(minutes, hours, days, months, frozenset(weekdays), either)
|
||||
|
||||
|
||||
def _day_matches(s: CronSchedule, day: date) -> bool:
|
||||
if day.month not in s.months:
|
||||
return False
|
||||
on_day = day.day in s.days
|
||||
on_weekday = (day.isoweekday() % 7) in s.weekdays
|
||||
return (on_day or on_weekday) if s.either_day else (on_day and on_weekday)
|
||||
|
||||
|
||||
def _local(day: date, hour: int, minute: int, tz: ZoneInfo) -> datetime | None:
|
||||
"""*day* at *hour*:*minute* in *tz*; None when the clock skips that time."""
|
||||
naive = datetime(day.year, day.month, day.day, hour, minute)
|
||||
aware = naive.replace(tzinfo=tz)
|
||||
if aware.astimezone(ZoneInfo("UTC")).astimezone(tz).replace(tzinfo=None) != naive:
|
||||
return None
|
||||
return aware
|
||||
|
||||
|
||||
def next_runs(expr: str, after: datetime, tz: ZoneInfo, count: int = 5) -> list[datetime]:
|
||||
"""The next *count* times *expr* fires after *after*, in *tz*.
|
||||
|
||||
``@reboot`` and a day that never comes (31 February) give none.
|
||||
|
||||
:raises ValueError: for an expression :func:`parse_cron` refuses.
|
||||
"""
|
||||
if is_reboot(expr):
|
||||
return []
|
||||
s = parse_cron(expr)
|
||||
start = after.astimezone(tz)
|
||||
runs: list[datetime] = []
|
||||
for offset in range(_HORIZON_DAYS):
|
||||
day = start.date() + timedelta(days=offset)
|
||||
if not _day_matches(s, day):
|
||||
continue
|
||||
for hour in sorted(s.hours):
|
||||
for minute in sorted(s.minutes):
|
||||
at = _local(day, hour, minute, tz)
|
||||
if at is None or at <= after:
|
||||
continue
|
||||
runs.append(at)
|
||||
if len(runs) == count:
|
||||
return runs
|
||||
return runs
|
||||
|
||||
|
||||
def _values(values: frozenset[int], low: int, high: int) -> str:
|
||||
if values == frozenset(range(low, high + 1)):
|
||||
return "*"
|
||||
return ",".join(f"{v:02d}" for v in sorted(values))
|
||||
|
||||
|
||||
def to_on_calendar(expr: str) -> list[str]:
|
||||
"""``OnCalendar`` lines that fire exactly when *expr* does.
|
||||
|
||||
:raises ValueError: for an expression :func:`parse_cron` refuses, ``@reboot``
|
||||
among them -- a timer takes that as ``OnBootSec``.
|
||||
"""
|
||||
s = parse_cron(expr)
|
||||
time = f"{_values(s.hours, 0, 23)}:{_values(s.minutes, 0, 59)}:00"
|
||||
months = _values(s.months, 1, 12)
|
||||
days = _values(s.days, 1, 31)
|
||||
weekdays = ",".join(_SYSTEMD_WEEKDAYS[d] for d in (1, 2, 3, 4, 5, 6, 0) if d in s.weekdays)
|
||||
every_weekday = s.weekdays == frozenset(range(7))
|
||||
if s.either_day:
|
||||
return [f"*-{months}-{days} {time}", f"{weekdays} *-{months}-* {time}"]
|
||||
prefix = "" if every_weekday else f"{weekdays} "
|
||||
return [f"{prefix}*-{months}-{days} {time}"]
|
||||
@@ -0,0 +1,509 @@
|
||||
"""DHCP desired-state management, shared by firewalls and gateways.
|
||||
|
||||
Covers two independent desired-state sets:
|
||||
|
||||
* **reservations** -- static MAC -> IP bindings, matched on the MAC;
|
||||
* **subnets** -- the served ranges and their per-subnet DHCP options,
|
||||
matched on the CIDR.
|
||||
|
||||
Both :class:`~napalm_device_types.firewall.FirewallDriver` and
|
||||
:class:`~napalm_device_types.residential_gateway.ResidentialGatewayDriver`
|
||||
mix this in, because both device types commonly run the DHCP server for
|
||||
their networks.
|
||||
|
||||
Only the six get/apply/commit methods are device-specific and must be
|
||||
implemented by a concrete driver; the diffs and the apply loops are
|
||||
vendor-neutral algorithms and live here -- see README.md "Design principle:
|
||||
generic vs. device-specific logic".
|
||||
|
||||
Neither diff ever deletes. For subnets that is not just caution: removing one
|
||||
takes DHCP down for an entire VLAN.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types._dhcp_order import ReservationChange, order_reservation_changes
|
||||
from napalm_device_types._matching import check_desired, index_live
|
||||
from napalm_device_types.models import (
|
||||
DhcpHaDict,
|
||||
DhcpReservationDict,
|
||||
DhcpReservationDiffDict,
|
||||
DhcpReservationUpdateDict,
|
||||
DhcpSubnetDict,
|
||||
DhcpSubnetDiffDict,
|
||||
DhcpSubnetUpdateDict,
|
||||
)
|
||||
|
||||
# `mac` is the identity, so it is matched rather than compared. `uuid` is
|
||||
# assigned by the device and never part of the desired state.
|
||||
_DHCP_RESERVATION_COMPARE_FIELDS = (
|
||||
"ip",
|
||||
"hostname",
|
||||
"description",
|
||||
"subnet",
|
||||
)
|
||||
|
||||
# `subnet` (the CIDR) is the identity, so it is matched rather than compared.
|
||||
# `uuid` is assigned by the device and never part of the desired state.
|
||||
_DHCP_SUBNET_COMPARE_FIELDS = (
|
||||
"description",
|
||||
"pools",
|
||||
"option_data",
|
||||
"match_client_id",
|
||||
)
|
||||
|
||||
_HEX_ONLY = re.compile(r"[^0-9a-f]")
|
||||
|
||||
#: Added to a refused change that is part of an address swap (#106).
|
||||
_SWAP_NOTE = (
|
||||
"an address swap with {}: no order frees an address first; "
|
||||
"move one of them to a free address in a run of its own"
|
||||
)
|
||||
|
||||
|
||||
class DhcpApplyError(RuntimeError):
|
||||
"""Some changes of an applied reservation or subnet set were refused by the device.
|
||||
|
||||
Raised after the rest were written and committed: ``failed`` of ``attempted``
|
||||
changes did not go through, and each was named in a ``[failed]`` progress line.
|
||||
``kind`` is what was applied: ``"reservation"`` or ``"subnet"``.
|
||||
"""
|
||||
|
||||
def __init__(self, failed: int, attempted: int, kind: str = "reservation") -> None:
|
||||
self.failed = failed
|
||||
self.attempted = attempted
|
||||
self.kind = kind
|
||||
super().__init__(f"{failed} of {attempted} DHCP {kind} change(s) were refused")
|
||||
|
||||
|
||||
def normalize_mac(mac: str | None) -> str:
|
||||
"""Reduces a MAC address to lowercase colon-separated form.
|
||||
|
||||
Devices report MACs in whatever form their config store happens to use --
|
||||
``AA-BB-CC-DD-EE-01``, ``aabb.ccdd.ee01``, ``AABBCCDDEE01``. Reservations
|
||||
are matched on this value, so it has to be canonical before comparison.
|
||||
|
||||
A value that is not 12 hex digits is returned lowercased and stripped
|
||||
instead of raising: a malformed device response should degrade to "this
|
||||
entry never matches" rather than abort the whole diff.
|
||||
"""
|
||||
if not mac:
|
||||
return ""
|
||||
|
||||
lowered = mac.strip().lower()
|
||||
hex_digits = _HEX_ONLY.sub("", lowered)
|
||||
if len(hex_digits) != 12:
|
||||
return lowered
|
||||
|
||||
return ":".join(hex_digits[i : i + 2] for i in range(0, 12, 2))
|
||||
|
||||
|
||||
def normalize_cidr(cidr: str | None) -> str:
|
||||
"""Reduces a subnet CIDR to a canonical string for matching.
|
||||
|
||||
Only whitespace and case are normalised -- deliberately not the network
|
||||
address itself. Rewriting ``10.10.20.5/24`` to ``10.10.20.0/24`` would
|
||||
make a caller's typo silently match a real subnet and then apply that
|
||||
caller's pools and options to it.
|
||||
"""
|
||||
return (cidr or "").strip().lower()
|
||||
|
||||
|
||||
def _subnet_field_differs(field: str, live: DhcpSubnetDict, desired: DhcpSubnetDict) -> bool:
|
||||
"""Compares one subnet field, with `option_data` handled specially.
|
||||
|
||||
For `option_data` only the options `desired` actually names are compared;
|
||||
see ``diff_dhcp_subnets`` for why an unmentioned option must not count as
|
||||
a difference.
|
||||
"""
|
||||
if field != "option_data":
|
||||
return live.get(field) != desired.get(field)
|
||||
|
||||
desired_options = desired.get("option_data") or {}
|
||||
live_options = live.get("option_data") or {}
|
||||
return any(live_options.get(option) != value for option, value in desired_options.items())
|
||||
|
||||
|
||||
def _reservation_key(reservation: DhcpReservationDict) -> str:
|
||||
return normalize_mac(reservation.get("mac"))
|
||||
|
||||
|
||||
def _diff_reservations(
|
||||
live: list[DhcpReservationDict], desired: list[DhcpReservationDict]
|
||||
) -> DhcpReservationDiffDict:
|
||||
"""``diff_dhcp_reservations`` against reservations already read."""
|
||||
live_by_mac, shared = index_live(live, _reservation_key)
|
||||
check_desired(desired, _reservation_key, shared, "MAC")
|
||||
|
||||
add: list[DhcpReservationDict] = []
|
||||
update: list[DhcpReservationUpdateDict] = []
|
||||
|
||||
for desired_reservation in desired:
|
||||
current = live_by_mac.get(_reservation_key(desired_reservation))
|
||||
if current is None:
|
||||
add.append(desired_reservation)
|
||||
continue
|
||||
|
||||
changed_fields = [
|
||||
field
|
||||
for field in _DHCP_RESERVATION_COMPARE_FIELDS
|
||||
if current.get(field) != desired_reservation.get(field)
|
||||
]
|
||||
if changed_fields:
|
||||
update.append(
|
||||
{
|
||||
"uuid": current["uuid"],
|
||||
"reservation": desired_reservation,
|
||||
"changed_fields": changed_fields,
|
||||
}
|
||||
)
|
||||
|
||||
return {"add": add, "update": update}
|
||||
|
||||
|
||||
class DhcpServerMixin:
|
||||
"""Mixin providing DHCP reservation and subnet read/diff/apply.
|
||||
|
||||
Concrete drivers **must** provide ``get_dhcp_reservations()``,
|
||||
``apply_dhcp_reservation()`` and ``commit_dhcp_reservations()``; drivers
|
||||
that also manage subnets provide ``get_dhcp_subnets()``,
|
||||
``apply_dhcp_subnet()`` and ``commit_dhcp_subnets()``.
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Device-specific -- must be implemented by the concrete driver.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_dhcp_reservations(self) -> list[DhcpReservationDict]:
|
||||
"""
|
||||
Returns all static DHCP reservations currently configured on the
|
||||
device, across all subnets.
|
||||
|
||||
This is the *configured* state, not the observed leases -- see
|
||||
``get_dhcp_leases()`` for the latter.
|
||||
|
||||
:raises NotImplementedError: If the driver does not support reading
|
||||
DHCP reservations.
|
||||
"""
|
||||
...
|
||||
|
||||
def apply_dhcp_reservation(
|
||||
self, reservation: DhcpReservationDict, *, uuid: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Creates or updates a single static DHCP reservation on the device.
|
||||
|
||||
:param reservation: The desired reservation state, vendor-neutral.
|
||||
:param uuid: If given, update the existing reservation with this ID
|
||||
in-place. If ``None``, create a new one.
|
||||
:raises NotImplementedError: If the driver does not support writing
|
||||
DHCP reservations.
|
||||
:raises ValueError: If `reservation` names a subnet the device does
|
||||
not serve.
|
||||
:raises RuntimeError: If the device rejects the write.
|
||||
|
||||
:returns: A dict with at least ``{"success": bool}``.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_dhcp_subnets(self) -> list[DhcpSubnetDict]:
|
||||
"""
|
||||
Returns every DHCPv4 subnet the device serves, with its pools and
|
||||
per-subnet options.
|
||||
|
||||
:raises NotImplementedError: If the driver does not support reading
|
||||
DHCP subnets.
|
||||
"""
|
||||
...
|
||||
|
||||
def apply_dhcp_subnet(
|
||||
self, subnet: DhcpSubnetDict, *, uuid: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Creates or updates a single DHCPv4 subnet on the device.
|
||||
|
||||
Implementations must treat ``subnet["option_data"]`` as a partial
|
||||
update: an option the caller did not name is left as the device has
|
||||
it. Managing `domain_search` alone is the common case, and it must
|
||||
not silently drop the `routers` the server autocollected.
|
||||
|
||||
:param subnet: The desired subnet state, vendor-neutral.
|
||||
:param uuid: If given, update the existing subnet with this ID
|
||||
in-place. If ``None``, create a new one.
|
||||
:raises NotImplementedError: If the driver does not support writing
|
||||
DHCP subnets.
|
||||
:raises RuntimeError: If the device rejects the write.
|
||||
|
||||
:returns: A dict with at least ``{"success": bool}``.
|
||||
"""
|
||||
...
|
||||
|
||||
def commit_dhcp_subnets(self) -> dict[str, Any]:
|
||||
"""
|
||||
Applies pending subnet changes (e.g. Kea's ``service/reconfigure``).
|
||||
|
||||
Separate from ``commit_dhcp_reservations`` even where a driver
|
||||
implements both with the same call: the two desired-state sets are
|
||||
applied independently, and a caller that changed only subnets should
|
||||
not have to know which reload the vendor happens to share.
|
||||
|
||||
:raises NotImplementedError: If the driver does not support this.
|
||||
|
||||
:returns: A dict with at least ``{"success": bool}``.
|
||||
"""
|
||||
...
|
||||
|
||||
def commit_dhcp_reservations(self) -> dict[str, Any]:
|
||||
"""
|
||||
Applies pending reservation changes (e.g. Kea's ``service/reconfigure``,
|
||||
or a dnsmasq reload).
|
||||
|
||||
Call once after one or more `apply_dhcp_reservation()` calls -- not
|
||||
after every single reservation, and not at all when nothing changed:
|
||||
on most implementations this reloads the DHCP daemon.
|
||||
|
||||
:raises NotImplementedError: If the driver does not support this
|
||||
(e.g. reservations take effect immediately on write).
|
||||
|
||||
:returns: A dict with at least ``{"success": bool}``.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_dhcp_ha(self) -> DhcpHaDict:
|
||||
"""
|
||||
Returns what the server's own HA configuration declares: whether HA
|
||||
is switched on, which peer this server is, and each peer with its
|
||||
role as the server words it.
|
||||
|
||||
Optional: a driver without it has no ``get_dhcp_ha`` at all, and a
|
||||
caller asks ``callable(getattr(driver, "get_dhcp_ha", None))``.
|
||||
|
||||
:raises Exception: When the configuration could not be read -- never
|
||||
``enabled=False`` for "could not ask".
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Generic, vendor-neutral algorithms.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def diff_dhcp_reservations(self, desired: list[DhcpReservationDict]) -> DhcpReservationDiffDict:
|
||||
"""
|
||||
Compares `desired` against the device's current reservations and
|
||||
returns what would need to change to reach that state.
|
||||
|
||||
Matches on the normalised MAC address. A desired reservation with no
|
||||
live counterpart becomes an "add"; a live one whose MAC matches but
|
||||
whose other fields differ becomes an "update". Live reservations with
|
||||
no matching desired entry are **not** reported for deletion -- a DHCP
|
||||
server routinely carries hand-created reservations that a caller's
|
||||
`desired` set was never meant to describe, and this method cannot tell
|
||||
those apart from ones simply no longer wanted. Callers wanting
|
||||
delete/cleanup semantics must implement that themselves, deliberately.
|
||||
|
||||
Live reservations without a MAC are never matched. A desired one
|
||||
without a MAC, a MAC given twice, or one more than one live
|
||||
reservation holds raise ``ValueError``.
|
||||
|
||||
:param desired: The complete desired reservation set.
|
||||
:returns: ``{"add": [...], "update": [{"uuid", "reservation",
|
||||
"changed_fields"}, ...]}``.
|
||||
:raises ValueError: When a desired reservation cannot name a single live one.
|
||||
"""
|
||||
|
||||
return _diff_reservations(self.get_dhcp_reservations(), desired)
|
||||
|
||||
def apply_dhcp_reservationset(self, desired: list[DhcpReservationDict]) -> Iterator[str]:
|
||||
"""
|
||||
Computes the diff against `desired` and applies it, yielding one
|
||||
human-readable progress line per change, then commits.
|
||||
|
||||
Unlike ``apply_firewall_ruleset``, an empty diff does **not** commit:
|
||||
committing reloads the DHCP daemon and drops in-flight requests, which
|
||||
is too high a price for a no-op run.
|
||||
|
||||
The changes are written so an address is released before it is taken; a
|
||||
swap of addresses has no such order and is reported as one (``_dhcp_order``).
|
||||
|
||||
A change the device refuses (say, an address in a subnet its DHCP server
|
||||
does not manage) does not stop the others: it gets a ``[failed]`` line,
|
||||
the rest are written and committed, and ``DhcpApplyError`` is raised at
|
||||
the end. Any non-empty diff commits, even one whose every write was
|
||||
refused, so that writes an earlier, interrupted run saved take effect.
|
||||
|
||||
:param desired: The complete desired reservation set.
|
||||
:yields: Progress lines, one per applied, updated or refused change,
|
||||
plus a final commit line.
|
||||
:raises DhcpApplyError: after the commit, when a change was refused.
|
||||
"""
|
||||
live = self.get_dhcp_reservations()
|
||||
diff = _diff_reservations(live, desired)
|
||||
attempted = len(diff["add"]) + len(diff["update"])
|
||||
if not attempted:
|
||||
yield "[commit] no changes"
|
||||
return
|
||||
|
||||
added = updated = refused = 0
|
||||
|
||||
for change in order_reservation_changes(diff, live):
|
||||
line, ok = self._write_change(change)
|
||||
refused += not ok
|
||||
added += ok and change.uuid is None
|
||||
updated += ok and change.uuid is not None
|
||||
yield line
|
||||
|
||||
# Committed even when every write was refused: a run that stopped before its
|
||||
# commit left saved writes behind, which the device reports as configured, so
|
||||
# no later diff would ever commit them.
|
||||
self.commit_dhcp_reservations()
|
||||
yield f"[commit] applied {added} add(s), {updated} update(s)"
|
||||
|
||||
if refused:
|
||||
raise DhcpApplyError(refused, attempted)
|
||||
|
||||
def _write_change(self, change: ReservationChange) -> tuple[str, bool]:
|
||||
"""Write one change of an ordered set; its progress line, and whether it went in."""
|
||||
tag = "[add]" if change.uuid is None else "[update]"
|
||||
line, ok = self._write_reservation(change.reservation, change.uuid, tag)
|
||||
if ok and change.fields:
|
||||
line = f"{line} ({change.fields})"
|
||||
elif not ok and change.swap:
|
||||
line = f"{line} -- {_SWAP_NOTE.format(', '.join(change.swap))}"
|
||||
return line, ok
|
||||
|
||||
def _write_reservation(
|
||||
self, reservation: DhcpReservationDict, uuid: str | None, tag: str
|
||||
) -> tuple[str, bool]:
|
||||
"""Write one reservation; its progress line, and whether the device took it."""
|
||||
target = f"{reservation['mac']} -> {reservation['ip']}"
|
||||
try:
|
||||
self.apply_dhcp_reservation(reservation, uuid=uuid)
|
||||
except Exception as exc:
|
||||
return f"[failed] {target}: {exc}", False
|
||||
return f"{tag} {target}", True
|
||||
|
||||
def diff_dhcp_subnets(self, desired: list[DhcpSubnetDict]) -> DhcpSubnetDiffDict:
|
||||
"""
|
||||
Compares `desired` against the device's current subnets and returns
|
||||
what would need to change to reach that state.
|
||||
|
||||
Matches on the CIDR. A desired subnet with no live counterpart becomes
|
||||
an "add"; a live one whose CIDR matches but whose other fields differ
|
||||
becomes an "update".
|
||||
|
||||
`option_data` is compared **per option**, and only over the options
|
||||
the caller named. An option the device carries but `desired` does not
|
||||
mention is left out of the comparison entirely, because absent means
|
||||
"not managed" rather than "should be empty". Without that rule a
|
||||
caller managing only `domain_search` would diff against every option
|
||||
Kea autocollects (`routers`, `domain_name_servers`, `ntp_servers`) and
|
||||
reconfigure the DHCP daemon on every single run.
|
||||
|
||||
Live subnets with no matching desired entry are **not** reported for
|
||||
deletion, and more emphatically than for reservations: removing a
|
||||
subnet takes DHCP down for a whole VLAN, and this method cannot tell
|
||||
"no longer wanted" from "was never netOrk's to describe".
|
||||
|
||||
An empty or repeated subnet raises ``ValueError``, as for reservations.
|
||||
|
||||
:param desired: The complete desired subnet set.
|
||||
:returns: ``{"add": [...], "update": [{"uuid", "subnet",
|
||||
"changed_fields"}, ...]}``.
|
||||
:raises ValueError: When a desired subnet cannot name a single live one.
|
||||
"""
|
||||
|
||||
def key(subnet: DhcpSubnetDict) -> str:
|
||||
return normalize_cidr(subnet.get("subnet"))
|
||||
|
||||
live_by_cidr, shared = index_live(self.get_dhcp_subnets(), key)
|
||||
check_desired(desired, key, shared, "subnet")
|
||||
|
||||
add: list[DhcpSubnetDict] = []
|
||||
update: list[DhcpSubnetUpdateDict] = []
|
||||
|
||||
for desired_subnet in desired:
|
||||
live = live_by_cidr.get(key(desired_subnet))
|
||||
if live is None:
|
||||
add.append(desired_subnet)
|
||||
continue
|
||||
|
||||
changed_fields = [
|
||||
field
|
||||
for field in _DHCP_SUBNET_COMPARE_FIELDS
|
||||
if _subnet_field_differs(field, live, desired_subnet)
|
||||
]
|
||||
if changed_fields:
|
||||
update.append(
|
||||
{
|
||||
"uuid": live["uuid"],
|
||||
"subnet": desired_subnet,
|
||||
"changed_fields": changed_fields,
|
||||
}
|
||||
)
|
||||
|
||||
return {"add": add, "update": update}
|
||||
|
||||
def apply_dhcp_subnetset(self, desired: list[DhcpSubnetDict]) -> Iterator[str]:
|
||||
"""
|
||||
Computes the diff against `desired` and applies it, yielding one
|
||||
human-readable progress line per change, then commits.
|
||||
|
||||
As with ``apply_dhcp_reservationset``, an empty diff does **not**
|
||||
commit: reconfiguring the DHCP daemon is too expensive for a no-op.
|
||||
|
||||
A subnet the device refuses (say, one that overlaps a subnet it serves)
|
||||
does not stop the others: it gets a ``[failed]`` line, the rest are
|
||||
written and committed, and ``DhcpApplyError`` is raised at the end. Any
|
||||
non-empty diff commits, even one whose every write was refused, so that
|
||||
writes an earlier, interrupted run saved take effect (#113).
|
||||
|
||||
:param desired: The complete desired subnet set.
|
||||
:yields: Progress lines, one per applied, updated or refused change,
|
||||
plus a final commit line.
|
||||
:raises DhcpApplyError: after the commit, when a change was refused.
|
||||
"""
|
||||
diff = self.diff_dhcp_subnets(desired)
|
||||
attempted = len(diff["add"]) + len(diff["update"])
|
||||
if not attempted:
|
||||
yield "[commit] no changes"
|
||||
return
|
||||
|
||||
changes: list[tuple[DhcpSubnetDict, str | None, str]] = [
|
||||
(subnet, None, "") for subnet in diff["add"]
|
||||
]
|
||||
changes += [
|
||||
(e["subnet"], e["uuid"], ", ".join(e["changed_fields"])) for e in diff["update"]
|
||||
]
|
||||
added = updated = refused = 0
|
||||
|
||||
for subnet, uuid, fields in changes:
|
||||
line, ok = self._write_subnet(subnet, uuid, fields)
|
||||
refused += not ok
|
||||
added += ok and uuid is None
|
||||
updated += ok and uuid is not None
|
||||
yield line
|
||||
|
||||
# Committed even when every write was refused; see apply_dhcp_reservationset.
|
||||
self.commit_dhcp_subnets()
|
||||
yield f"[commit] applied {added} add(s), {updated} update(s)"
|
||||
|
||||
if refused:
|
||||
raise DhcpApplyError(refused, attempted, "subnet")
|
||||
|
||||
def _write_subnet(
|
||||
self, subnet: DhcpSubnetDict, uuid: str | None, fields: str
|
||||
) -> tuple[str, bool]:
|
||||
"""Write one subnet; its progress line, and whether the device took it."""
|
||||
try:
|
||||
self.apply_dhcp_subnet(subnet, uuid=uuid)
|
||||
except Exception as exc:
|
||||
return f"[failed] {subnet['subnet']}: {exc}", False
|
||||
if uuid is None:
|
||||
return f"[add] {subnet['subnet']}", True
|
||||
return f"[update] {subnet['subnet']} ({fields})", True
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Domains a device's DNS resolver forwards to another server.
|
||||
|
||||
An application that makes the device's resolver ask another server for a zone
|
||||
-- the authority for an internal domain -- edits these. The driver writes them
|
||||
in its device's terms and applies them; the forwards are the caller's.
|
||||
Declared only; a driver whose device resolves DNS implements it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import DnsForwardDict
|
||||
|
||||
|
||||
class DnsForwardMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_dns_forwards(self) -> list[DnsForwardDict]:
|
||||
"""Every domain the resolver forwards, enabled or not."""
|
||||
...
|
||||
|
||||
def set_dns_forward(self, domain: str, server: str, port: int = 53) -> None:
|
||||
"""Forward *domain* to *server*: added, or the existing forward of
|
||||
*domain* changed. Applied before it returns.
|
||||
|
||||
:raises RuntimeError: when the device refuses it.
|
||||
"""
|
||||
...
|
||||
|
||||
def remove_dns_forward(self, domain: str) -> None:
|
||||
"""Stop forwarding *domain*; nothing to do when it is not forwarded.
|
||||
Applied before it returns."""
|
||||
...
|
||||
+104
-250
@@ -10,21 +10,28 @@ Usage::
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
from napalm_device_types._ucd_metrics import IF_SKIP_DEFAULT, collect_ucd_metrics
|
||||
from napalm_device_types.dhcp import DhcpServerMixin
|
||||
from napalm_device_types.firewall_rules import FirewallRuleMixin
|
||||
from napalm_device_types.health_metrics import HealthMetricsMixin
|
||||
from napalm_device_types.models import (
|
||||
HealthMetricsDict,
|
||||
NATTranslationDict,
|
||||
PackageDict,
|
||||
SecurityZoneDict,
|
||||
SessionDict,
|
||||
VPNTunnelDict,
|
||||
)
|
||||
from napalm_device_types.nat_vpn import NatVpnMixin
|
||||
from napalm_device_types.packages import PackageManagementMixin
|
||||
|
||||
|
||||
class FirewallDriver(DeviceTypeDriver):
|
||||
TYPE_LABEL: str = "Firewall"
|
||||
class FirewallDriver(
|
||||
NatVpnMixin,
|
||||
PackageManagementMixin,
|
||||
HealthMetricsMixin,
|
||||
FirewallRuleMixin,
|
||||
DhcpServerMixin,
|
||||
DeviceTypeDriver,
|
||||
):
|
||||
"""
|
||||
Abstract intermediate driver for firewall/security devices.
|
||||
|
||||
@@ -33,268 +40,115 @@ class FirewallDriver(DeviceTypeDriver):
|
||||
that concrete drivers must implement.
|
||||
"""
|
||||
|
||||
_SNMP_SKIP_IF = IF_SKIP_DEFAULT
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "firewall"
|
||||
TYPE_LABEL: str = "Firewall"
|
||||
|
||||
# OPNsense reports drops in the out-error counter.
|
||||
_SNMP_TX_ERR_IS_DROP: bool = True
|
||||
_SNMP_TX_ERR_IS_DROP: ClassVar[bool] = True
|
||||
|
||||
@classmethod
|
||||
async def get_health_metrics(cls, snmp_get, snmp_walk) -> HealthMetricsDict:
|
||||
return await collect_ucd_metrics(
|
||||
snmp_get, snmp_walk,
|
||||
tx_err_is_drop=cls._SNMP_TX_ERR_IS_DROP,
|
||||
if_skip=cls._SNMP_SKIP_IF,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_nat_translations(self) -> List[NATTranslationDict]:
|
||||
"""
|
||||
Returns a list of active NAT translation entries.
|
||||
def get_security_zones(self) -> dict[str, SecurityZoneDict]:
|
||||
"""
|
||||
Returns the security zone configuration.
|
||||
|
||||
Each entry contains:
|
||||
Keys are zone names. Each value contains:
|
||||
|
||||
* protocol (string) - ``"tcp"``, ``"udp"``, ``"icmp"``
|
||||
* inside_local (string) - original source address (IP or IP:port)
|
||||
* inside_global (string) - translated source address (IP or IP:port)
|
||||
* outside_local (string) - destination as seen from inside
|
||||
* outside_global (string) - actual destination address
|
||||
* age (float) - translation entry age in seconds
|
||||
* interfaces (list of strings) - interfaces assigned to this zone
|
||||
* policy (string) - name of the security policy applied to this zone
|
||||
* description (string) - zone description
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"protocol": "tcp",
|
||||
"inside_local": "192.168.1.10:54321",
|
||||
"inside_global": "203.0.113.1:54321",
|
||||
"outside_local": "1.1.1.1:443",
|
||||
"outside_global": "1.1.1.1:443",
|
||||
"age": 120.5,
|
||||
"LAN": {
|
||||
"interfaces": ["eth0", "eth1"],
|
||||
"policy": "LAN-policy",
|
||||
"description": "Internal LAN zone",
|
||||
},
|
||||
"WAN": {
|
||||
"interfaces": ["eth2"],
|
||||
"policy": "WAN-policy",
|
||||
"description": "Uplink to internet",
|
||||
},
|
||||
}
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"""
|
||||
...
|
||||
|
||||
def get_security_zones(self) -> Dict[str, SecurityZoneDict]:
|
||||
"""
|
||||
Returns the security zone configuration.
|
||||
def get_sessions(self) -> list[SessionDict]:
|
||||
"""
|
||||
Returns a list of active connection sessions (stateful flows).
|
||||
|
||||
Keys are zone names. Each value contains:
|
||||
Each entry contains:
|
||||
|
||||
* interfaces (list of strings) - interfaces assigned to this zone
|
||||
* policy (string) - name of the security policy applied to this zone
|
||||
* description (string) - zone description
|
||||
* protocol (string) - ``"tcp"``, ``"udp"``, ``"icmp"``
|
||||
* src_ip (string) - source IP address
|
||||
* src_port (int) - source port (0 for ICMP)
|
||||
* dst_ip (string) - destination IP address
|
||||
* dst_port (int) - destination port (0 for ICMP)
|
||||
* state (string) - session state, e.g. ``"established"``, ``"syn_sent"``
|
||||
* age (float) - session age in seconds
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
{
|
||||
"LAN": {
|
||||
"interfaces": ["eth0", "eth1"],
|
||||
"policy": "LAN-policy",
|
||||
"description": "Internal LAN zone",
|
||||
},
|
||||
"WAN": {
|
||||
"interfaces": ["eth2"],
|
||||
"policy": "WAN-policy",
|
||||
"description": "Uplink to internet",
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
[
|
||||
{
|
||||
"protocol": "tcp",
|
||||
"src_ip": "192.168.1.10",
|
||||
"src_port": 54321,
|
||||
"dst_ip": "1.1.1.1",
|
||||
"dst_port": 443,
|
||||
"state": "established",
|
||||
"age": 30.2,
|
||||
}
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_sessions(self) -> List[SessionDict]:
|
||||
"""
|
||||
Returns a list of active connection sessions (stateful flows).
|
||||
def send_wake_on_lan(self, mac_address: str, interface: str = "") -> dict[str, Any]:
|
||||
"""
|
||||
Sends a Wake-on-LAN "magic packet" to wake a host on the network.
|
||||
|
||||
Each entry contains:
|
||||
:param mac_address: Target host's MAC address (colon-separated,
|
||||
case-insensitive, e.g. ``"AA:BB:CC:DD:EE:FF"``).
|
||||
:param interface: Driver-specific interface identifier to broadcast the
|
||||
magic packet from. Required by drivers that scope WOL per interface
|
||||
(e.g. OPNsense); an empty string means "use the driver's default/
|
||||
only broadcast domain." Consult the concrete driver's docstring for
|
||||
the exact expected format.
|
||||
:raises NotImplementedError: If the driver does not support Wake-on-LAN.
|
||||
:raises ValueError: If ``mac_address`` is malformed, or ``interface`` is
|
||||
required by this driver but was not provided.
|
||||
|
||||
* protocol (string) - ``"tcp"``, ``"udp"``, ``"icmp"``
|
||||
* src_ip (string) - source IP address
|
||||
* src_port (int) - source port (0 for ICMP)
|
||||
* dst_ip (string) - destination IP address
|
||||
* dst_port (int) - destination port (0 for ICMP)
|
||||
* state (string) - session state, e.g. ``"established"``, ``"syn_sent"``
|
||||
* age (float) - session age in seconds
|
||||
:returns: A dict with:
|
||||
|
||||
Example::
|
||||
* success (bool) - ``True`` if the magic packet was sent without error
|
||||
* output (string) - human-readable status message
|
||||
|
||||
[
|
||||
{
|
||||
"protocol": "tcp",
|
||||
"src_ip": "192.168.1.10",
|
||||
"src_port": 54321,
|
||||
"dst_ip": "1.1.1.1",
|
||||
"dst_port": 443,
|
||||
"state": "established",
|
||||
"age": 30.2,
|
||||
}
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
Example::
|
||||
|
||||
def get_vpn_tunnels(self) -> Dict[str, VPNTunnelDict]:
|
||||
"""
|
||||
Returns the status of VPN tunnels.
|
||||
driver.send_wake_on_lan("AA:BB:CC:DD:EE:FF", interface="lan")
|
||||
# → {"success": True, "output": "Magic packet sent to AA:BB:CC:DD:EE:FF via lan"}
|
||||
|
||||
Keys are tunnel names or identifiers. Each value contains:
|
||||
.. note::
|
||||
|
||||
* type (string) - tunnel type: ``"IPsec"``, ``"SSL"``, ``"GRE"``, ``"WireGuard"``
|
||||
* local_endpoint (string) - local tunnel endpoint IP
|
||||
* remote_endpoint (string) - remote tunnel endpoint IP
|
||||
* is_up (bool) - whether the tunnel is operationally up
|
||||
* uptime (int) - tunnel uptime in seconds (0 if down)
|
||||
* bytes_in (int) - total bytes received through the tunnel
|
||||
* bytes_out (int) - total bytes sent through the tunnel
|
||||
A driver whose ``interface`` is *not* the name :meth:`get_interfaces`
|
||||
is keyed by must expose the name it does expect as an ``identifier``
|
||||
key on each ``get_interfaces()`` entry. Without it a caller has no
|
||||
way to offer a valid choice: OPNsense, for instance, keys interfaces
|
||||
by the physical device ("em0") but wakes by the assigned name
|
||||
("lan"), and rejects the former. ``identifier`` is a non-standard
|
||||
NAPALM key, so it reaches consumers through the usual passthrough
|
||||
for extra interface data.
|
||||
"""
|
||||
...
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"vpn-to-branch": {
|
||||
"type": "IPsec",
|
||||
"local_endpoint": "203.0.113.1",
|
||||
"remote_endpoint": "198.51.100.1",
|
||||
"is_up": True,
|
||||
"uptime": 86400,
|
||||
"bytes_in": 104857600,
|
||||
"bytes_out": 52428800,
|
||||
}
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_packages(self) -> List[PackageDict]:
|
||||
"""
|
||||
Returns all packages / plugins currently known to the firewall's
|
||||
package manager (e.g. ``pkg`` on pfSense/OPNsense, ``FortiGate
|
||||
License`` add-ons, ``apt`` on Debian-based firewalls).
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - package name
|
||||
* version (string) - installed or available version string
|
||||
* installed (bool) - ``True`` if the package is currently installed
|
||||
* description (string) - short package description
|
||||
* size (int) - package size in bytes (0 if unknown)
|
||||
* source (string) - repository / channel the package comes from
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "pfBlockerNG",
|
||||
"version": "3.2.0_4",
|
||||
"installed": True,
|
||||
"description": "IP and DNS blocking for pfSense",
|
||||
"size": 2097152,
|
||||
"source": "pfSense-pkg",
|
||||
},
|
||||
{
|
||||
"name": "suricata",
|
||||
"version": "7.0.3_1",
|
||||
"installed": False,
|
||||
"description": "High-performance Network IDS/IPS",
|
||||
"size": 51380224,
|
||||
"source": "pfSense-pkg",
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def install_package(self, name: str, version: str = "") -> None:
|
||||
"""
|
||||
Installs a package or plugin on the firewall.
|
||||
|
||||
The method blocks until the installation is complete. Whether a
|
||||
reboot is required afterwards depends on the device; check the vendor
|
||||
documentation.
|
||||
|
||||
:param name: Package name as known to the package manager.
|
||||
:param version: Exact version to install. An empty string (default)
|
||||
installs the latest available version.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package name is unknown or the requested
|
||||
version is not available.
|
||||
:raises RuntimeError: If the installation fails on the device side
|
||||
(e.g. license missing, dependency conflict, disk full).
|
||||
|
||||
Example::
|
||||
|
||||
driver.install_package("pfBlockerNG")
|
||||
driver.install_package("suricata", version="7.0.3_1")
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def remove_package(self, name: str) -> None:
|
||||
"""
|
||||
Removes an installed package or plugin from the firewall.
|
||||
|
||||
The method blocks until the removal is complete.
|
||||
|
||||
:param name: Package name to remove.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package is not currently installed.
|
||||
:raises RuntimeError: If the removal fails on the device side
|
||||
(e.g. the package is a system dependency).
|
||||
|
||||
Example::
|
||||
|
||||
driver.remove_package("pfBlockerNG")
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_package_config(self, name: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Returns the current configuration of an installed package or plugin
|
||||
as a dictionary. The structure is package-specific.
|
||||
|
||||
:param name: Package name.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package is not installed.
|
||||
|
||||
Example::
|
||||
|
||||
driver.get_package_config("pfBlockerNG")
|
||||
# →
|
||||
{
|
||||
"enable": True,
|
||||
"maxmind_key": "",
|
||||
"blocklists": [
|
||||
{"name": "PRI1", "action": "Deny_Both", "enabled": True},
|
||||
{"name": "DNSBL_ADs", "action": "Unbound", "enabled": True},
|
||||
],
|
||||
"update_interval": "Once a day",
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def set_package_config(self, name: str, config: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Writes a new configuration for an installed package or plugin.
|
||||
|
||||
The ``config`` dict must match the structure returned by
|
||||
:meth:`get_package_config`. Unknown keys are ignored or raise a
|
||||
``ValueError`` depending on the driver implementation.
|
||||
|
||||
Changes take effect immediately where the package supports live
|
||||
reload; otherwise a package restart or device reboot may be
|
||||
required – behaviour is driver-specific.
|
||||
|
||||
:param name: Package name.
|
||||
:param config: New configuration as a nested dictionary.
|
||||
:raises NotImplementedError: If the driver does not support package management.
|
||||
:raises ValueError: If the package is not installed or the configuration
|
||||
contains invalid values.
|
||||
:raises RuntimeError: If the device rejects the configuration.
|
||||
|
||||
Example::
|
||||
|
||||
driver.set_package_config(
|
||||
"pfBlockerNG",
|
||||
{
|
||||
"enable": True,
|
||||
"blocklists": [
|
||||
{"name": "PRI1", "action": "Deny_Both", "enabled": True},
|
||||
],
|
||||
"update_interval": "Twice a day",
|
||||
},
|
||||
)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
# ------------------------------------------------------------------
|
||||
# Firewall rule diff/apply. get_firewall_rules/apply_firewall_rule/
|
||||
# commit_firewall_rules are abstract (device communication); everything
|
||||
# else here is a concrete, vendor-neutral algorithm -- see README.md
|
||||
# "Design principle: generic vs. device-specific logic".
|
||||
# ------------------------------------------------------------------
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Firewall rule reconciliation: generic here, device communication in the driver.
|
||||
|
||||
The split follows the rule in this package's README: matching, diffing and the
|
||||
apply-then-commit sequence would be identical for any vendor's firewall, so they
|
||||
live here as concrete methods. Only the three hooks below touch the device, and
|
||||
a concrete driver supplies those.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``, the hooks do not exist at runtime until a
|
||||
driver implements them -- so ``hasattr`` stays an honest answer to "can this
|
||||
driver manage firewall rules", and mixing this class in can never shadow a
|
||||
working implementation inherited from elsewhere.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types._matching import check_desired, index_live
|
||||
from napalm_device_types.models import (
|
||||
FirewallRuleDict,
|
||||
FirewallRuleDiffDict,
|
||||
FirewallRuleUpdateDict,
|
||||
)
|
||||
|
||||
_FIREWALL_RULE_COMPARE_FIELDS = (
|
||||
"action",
|
||||
"interface",
|
||||
"direction",
|
||||
"protocol",
|
||||
"source_net",
|
||||
"source_port",
|
||||
"destination_net",
|
||||
"destination_port",
|
||||
"log",
|
||||
"quick",
|
||||
"enabled",
|
||||
)
|
||||
|
||||
|
||||
class FirewallRuleMixin:
|
||||
"""Adds generic firewall-rule diff and apply on top of three device hooks."""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_firewall_rules(self) -> list[FirewallRuleDict]:
|
||||
"""
|
||||
Returns all firewall filter rules currently configured on the device.
|
||||
|
||||
`description` must be a stable, human-assigned identifier -- it is
|
||||
the key used to match rules across calls (most firewall vendors
|
||||
don't expose an ID a caller can pre-assign).
|
||||
|
||||
:raises NotImplementedError: If the driver does not support reading
|
||||
firewall rules.
|
||||
"""
|
||||
...
|
||||
|
||||
def apply_firewall_rule(
|
||||
self, rule: FirewallRuleDict, *, uuid: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Creates or updates a single firewall filter rule on the device.
|
||||
|
||||
:param rule: The desired rule state, in vendor-neutral form.
|
||||
:param uuid: If given, update the existing rule with this ID
|
||||
in-place. If ``None``, create a new rule.
|
||||
:raises NotImplementedError: If the driver does not support writing
|
||||
firewall rules.
|
||||
:raises ValueError: If `rule` references an alias/interface the
|
||||
device doesn't know about.
|
||||
:raises RuntimeError: If the device rejects the write.
|
||||
|
||||
:returns: A dict with at least ``{"success": bool}``.
|
||||
"""
|
||||
...
|
||||
|
||||
def commit_firewall_rules(self) -> dict[str, Any]:
|
||||
"""
|
||||
Applies pending firewall filter rule changes (e.g. reloads pf/pfctl,
|
||||
or whatever the device's equivalent of "Apply Changes" is).
|
||||
|
||||
Call once after one or more `apply_firewall_rule()` calls -- not
|
||||
after every single rule.
|
||||
|
||||
:raises NotImplementedError: If the driver does not support this
|
||||
(e.g. rules take effect immediately on write).
|
||||
|
||||
:returns: A dict with at least ``{"success": bool}``.
|
||||
"""
|
||||
...
|
||||
|
||||
def diff_firewall_rules(self, desired: list[FirewallRuleDict]) -> FirewallRuleDiffDict:
|
||||
"""
|
||||
Compares `desired` against the device's current rules and returns
|
||||
what would need to change to reach that state.
|
||||
|
||||
Matches rules by `description`. A desired rule with no live
|
||||
counterpart becomes an "add"; a live rule whose description matches
|
||||
but whose other fields differ becomes an "update". Live rules with
|
||||
no matching desired entry are **not** reported for deletion -- this
|
||||
is intentionally conservative: a firewall may carry manually-created
|
||||
or otherwise unmanaged rules that a caller's `desired` set was never
|
||||
meant to describe, and this method has no way to distinguish those
|
||||
from ones simply no longer wanted. Callers wanting delete/cleanup
|
||||
semantics must implement that themselves, deliberately.
|
||||
|
||||
Live rules without a description are never matched. A desired rule
|
||||
without one, two desired rules with the same one, or one whose
|
||||
description more than one live rule holds raise ``ValueError``: any
|
||||
guess would overwrite a rule the caller did not mean.
|
||||
|
||||
:param desired: The complete desired rule set.
|
||||
:returns: ``{"add": [...], "update": [{"uuid", "rule",
|
||||
"changed_fields"}, ...]}``.
|
||||
:raises ValueError: When a desired rule cannot name a single live one.
|
||||
"""
|
||||
|
||||
def key(rule: FirewallRuleDict) -> str:
|
||||
return (rule.get("description") or "").strip()
|
||||
|
||||
live_by_description, shared = index_live(self.get_firewall_rules(), key)
|
||||
check_desired(desired, key, shared, "description")
|
||||
|
||||
add: list[FirewallRuleDict] = []
|
||||
update: list[FirewallRuleUpdateDict] = []
|
||||
|
||||
for desired_rule in desired:
|
||||
live_rule = live_by_description.get(key(desired_rule))
|
||||
if live_rule is None:
|
||||
add.append(desired_rule)
|
||||
continue
|
||||
|
||||
changed_fields = [
|
||||
field
|
||||
for field in _FIREWALL_RULE_COMPARE_FIELDS
|
||||
if live_rule.get(field) != desired_rule.get(field)
|
||||
]
|
||||
if changed_fields:
|
||||
update.append(
|
||||
{
|
||||
"uuid": live_rule["uuid"],
|
||||
"rule": desired_rule,
|
||||
"changed_fields": changed_fields,
|
||||
}
|
||||
)
|
||||
|
||||
return {"add": add, "update": update}
|
||||
|
||||
def apply_firewall_ruleset(self, desired: list[FirewallRuleDict]) -> Iterator[str]:
|
||||
"""
|
||||
Computes the diff against `desired` and applies it, yielding one
|
||||
human-readable progress line per change, then commits.
|
||||
|
||||
Intended for streaming to a caller (e.g. an SSE endpoint) that wants
|
||||
live progress while writing to a real device.
|
||||
|
||||
:param desired: The complete desired rule set.
|
||||
:yields: Progress lines, one per applied add/update, plus a final
|
||||
commit line.
|
||||
"""
|
||||
diff = self.diff_firewall_rules(desired)
|
||||
|
||||
for rule in diff["add"]:
|
||||
self.apply_firewall_rule(rule)
|
||||
yield f"[add] {rule['description']}"
|
||||
|
||||
for entry in diff["update"]:
|
||||
self.apply_firewall_rule(entry["rule"], uuid=entry["uuid"])
|
||||
fields = ", ".join(entry["changed_fields"])
|
||||
yield f"[update] {entry['rule']['description']} ({fields})"
|
||||
|
||||
self.commit_firewall_rules()
|
||||
yield f"[commit] applied {len(diff['add'])} add(s), {len(diff['update'])} update(s)"
|
||||
@@ -0,0 +1,67 @@
|
||||
"""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 typing import TYPE_CHECKING, NotRequired, TypedDict
|
||||
|
||||
|
||||
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":
|
||||
"""The firmware running and the newest the vendor offers.
|
||||
|
||||
None when the driver cannot tell for this device (an unknown model,
|
||||
a catalogue that did not answer).
|
||||
|
||||
Example::
|
||||
|
||||
{"current_version": "1.0.2.10", "latest_version": "1.0.2.12",
|
||||
"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).
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,369 @@
|
||||
"""Fix routines: changes an application wants made on a device, as templates.
|
||||
|
||||
A template fixes the order of the steps; the driver knows how each step is done on
|
||||
its device; the caller supplies every value -- the community, the allowed sources,
|
||||
the proxy URL, the user. A driver whose device takes the whole change in one call
|
||||
(a REST API) overrides the template method instead of its steps.
|
||||
|
||||
None of these is mixed into a role base. A driver mixes in the fixes its device can
|
||||
take, so ``callable(getattr(driver, "configure_snmp_agent", None))`` stays a truthful
|
||||
answer; a driver that inherits one it cannot run sets it to ``None``.
|
||||
|
||||
They replace ``run_device_action`` (docs/STRUCTURE.md):
|
||||
|
||||
========================== ===================================================
|
||||
``fix_snmp`` :meth:`SnmpAgentMixin.configure_snmp_agent`
|
||||
``fix_apt_proxy`` :meth:`PackageProxyMixin.configure_package_proxy`
|
||||
``fix_docker_permissions`` ``ContainerEngineMixin.grant_container_engine_access``
|
||||
``install_lldpd`` and co. :meth:`EnsurePackageMixin.ensure_package`
|
||||
(new) :meth:`ZabbixAgentMixin.configure_zabbix_agent`
|
||||
========================== ===================================================
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
|
||||
from napalm_device_types.models import (
|
||||
FixResultDict,
|
||||
FixStepDict,
|
||||
FixStepOutcomeDict,
|
||||
PackageDict,
|
||||
SnmpAgentSettingsDict,
|
||||
)
|
||||
from napalm_device_types.zabbix_agent import ZabbixAgentSettingsDict, check_zabbix_agent_settings
|
||||
|
||||
#: One step of a fix: its name and the call that does it.
|
||||
FixStep = tuple[str, Callable[[], FixStepOutcomeDict]]
|
||||
|
||||
|
||||
def run_fix_steps(steps: Sequence[FixStep]) -> FixResultDict:
|
||||
"""Run *steps* in order and stop at the first that fails.
|
||||
|
||||
A step that raises has failed, with the exception's message as its output.
|
||||
"""
|
||||
done: list[FixStepDict] = []
|
||||
for name, step in steps:
|
||||
try:
|
||||
outcome = step()
|
||||
ok, output = bool(outcome["ok"]), str(outcome.get("output", ""))
|
||||
except Exception as exc: # noqa: BLE001 - any failure of a step ends the fix
|
||||
ok, output = False, str(exc)
|
||||
done.append({"step": name, "ok": ok, "output": output})
|
||||
if not ok:
|
||||
break
|
||||
return {
|
||||
"success": bool(done) and all(s["ok"] for s in done) and len(done) == len(steps),
|
||||
"steps": done,
|
||||
"output": "\n".join(f"[{s['step']}] {s['output']}".rstrip() for s in done),
|
||||
}
|
||||
|
||||
|
||||
def enable_and_restart(
|
||||
manage_service: Callable[[str, str], dict[str, Any]], service: str
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Enable *service* at boot, then restart it so it reads its configuration; not
|
||||
restarted when it cannot be enabled."""
|
||||
for action in ("enable", "restart"):
|
||||
result = manage_service(service, action)
|
||||
if not result.get("success"):
|
||||
output = str(result.get("output", "")).strip()
|
||||
return {"ok": False, "output": f"{action} {service}: {output}".rstrip(": ")}
|
||||
return {"ok": True, "output": f"{service} enabled and restarted"}
|
||||
|
||||
|
||||
def _joined(*parts: object) -> str:
|
||||
return "\n".join(str(p).strip() for p in parts if p and str(p).strip())
|
||||
|
||||
|
||||
class SnmpAgentMixin:
|
||||
"""Run an SNMP agent on the device that answers the caller.
|
||||
|
||||
The steps: install the agent, write its configuration, let the allowed sources
|
||||
through the host's firewall, start it. Whether it answers is the caller's to ask,
|
||||
with its own SNMP client.
|
||||
"""
|
||||
|
||||
def configure_snmp_agent(self, settings: SnmpAgentSettingsDict) -> FixResultDict:
|
||||
"""Install, configure, open and start the agent with *settings*."""
|
||||
return run_fix_steps(
|
||||
[
|
||||
("install", self._install_snmp_agent),
|
||||
("configure", lambda: self._write_snmp_agent_config(settings)),
|
||||
("firewall", lambda: self._allow_snmp_sources(settings)),
|
||||
("start", self._start_snmp_agent),
|
||||
]
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_management_peer(self) -> str | None:
|
||||
"""The address the device sees this management connection come from
|
||||
(for SSH, the client side of ``SSH_CONNECTION``), or None when it cannot
|
||||
tell. A fact for the caller choosing ``allowed_sources``; optional --
|
||||
a driver that cannot tell does not implement it."""
|
||||
...
|
||||
|
||||
# The steps a driver implements:
|
||||
|
||||
def _install_snmp_agent(self) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _write_snmp_agent_config(
|
||||
self, settings: SnmpAgentSettingsDict
|
||||
) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
"""Let ``settings["allowed_sources"]`` reach the agent; ``ok`` with nothing
|
||||
to do where the host has no firewall of its own."""
|
||||
...
|
||||
|
||||
def _start_snmp_agent(self) -> FixStepOutcomeDict:
|
||||
"""(Re)start the agent so it reads the new configuration, and enable it at boot."""
|
||||
...
|
||||
|
||||
|
||||
class EnsurePackageMixin:
|
||||
"""Make sure a package is installed, installing it only where it is missing.
|
||||
|
||||
Works over :class:`~napalm_device_types.packages.PackageManagementMixin`'s
|
||||
``get_packages`` and ``install_package``, which the driver implements.
|
||||
"""
|
||||
|
||||
def ensure_package(self, name: str) -> FixResultDict:
|
||||
"""Install *name* unless it is installed already."""
|
||||
|
||||
def install() -> FixStepOutcomeDict:
|
||||
if any(p.get("name") == name and p.get("installed") for p in self.get_packages()):
|
||||
return {"ok": True, "output": f"{name} is already installed"}
|
||||
result: Any = self.install_package(name) # type: ignore[func-returns-value]
|
||||
# The contract says None (and raise on failure); some drivers still
|
||||
# return {"success", "output"}.
|
||||
if isinstance(result, dict):
|
||||
return {"ok": bool(result.get("success")), "output": str(result.get("output", ""))}
|
||||
return {"ok": True, "output": f"installed {name}"}
|
||||
|
||||
return run_fix_steps([("install", install)])
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
|
||||
def get_packages(self) -> list[PackageDict]: ...
|
||||
|
||||
def install_package(self, name: str, version: str = "") -> None: ...
|
||||
|
||||
|
||||
class LldpAgentMixin:
|
||||
"""Run an LLDP agent on the device, on the interfaces the caller names.
|
||||
|
||||
The steps: install the agent, write the interfaces it runs on, enable it at boot
|
||||
and restart it so it reads them. Installing and starting are generic, over
|
||||
``ensure_package`` and ``manage_service`` with ``LLDP_AGENT_PACKAGE`` and
|
||||
``LLDP_AGENT_SERVICE``; the driver writes the configuration. Which interfaces is
|
||||
the caller's choice -- an agent on every interface also talks to the uplink of a
|
||||
WAN port. Whether neighbours appear is the caller's to read with
|
||||
``get_lldp_neighbors``, after the agent's first advertisement interval.
|
||||
"""
|
||||
|
||||
#: The package that brings the agent, as ``ensure_package`` takes it.
|
||||
LLDP_AGENT_PACKAGE: ClassVar[str] = "lldpd"
|
||||
#: The agent's service, as ``manage_service`` takes it.
|
||||
LLDP_AGENT_SERVICE: ClassVar[str] = "lldpd"
|
||||
|
||||
def configure_lldp_agent(self, interfaces: Sequence[str]) -> FixResultDict:
|
||||
"""Install, configure for *interfaces*, enable and restart the agent.
|
||||
|
||||
:raises ValueError: for no interface, before anything changes.
|
||||
"""
|
||||
names = [str(name) for name in interfaces]
|
||||
if not names:
|
||||
raise ValueError("name at least one interface for the LLDP agent")
|
||||
return run_fix_steps(
|
||||
[
|
||||
("install", self._install_lldp_agent),
|
||||
("configure", lambda: self._write_lldp_agent_config(names)),
|
||||
("start", self._start_lldp_agent),
|
||||
]
|
||||
)
|
||||
|
||||
def _install_lldp_agent(self) -> FixStepOutcomeDict:
|
||||
result = self.ensure_package(self.LLDP_AGENT_PACKAGE)
|
||||
return {"ok": bool(result["success"]), "output": str(result.get("output", ""))}
|
||||
|
||||
def _start_lldp_agent(self) -> FixStepOutcomeDict:
|
||||
return enable_and_restart(self.manage_service, self.LLDP_AGENT_SERVICE)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def ensure_package(self, name: str) -> FixResultDict: ...
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]: ...
|
||||
|
||||
# The step a driver implements:
|
||||
|
||||
def _write_lldp_agent_config(self, interfaces: list[str]) -> FixStepOutcomeDict:
|
||||
"""Have the agent send and listen on exactly *interfaces* (names as the
|
||||
device's interface getters report them), replacing the list it had."""
|
||||
...
|
||||
|
||||
|
||||
class ZabbixAgentMixin:
|
||||
"""Run a native Zabbix agent that answers the caller's server.
|
||||
|
||||
For a host without a container engine, where the agent cannot run as a
|
||||
container. The steps: load the package index where the driver can
|
||||
(``refresh_available_updates``), install the agent from the host's own packages -- and
|
||||
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 -- 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.
|
||||
|
||||
The settings are checked before anything changes; ``ValueError`` names the one
|
||||
that does not hold. A driver that cannot add a repository sets
|
||||
``_add_zabbix_repository`` to ``None``: its hosts then take the distribution's
|
||||
package or none.
|
||||
"""
|
||||
|
||||
#: The package that brings the agent, as ``ensure_package`` takes it.
|
||||
ZABBIX_AGENT_PACKAGE: ClassVar[str] = "zabbix-agent"
|
||||
#: The agent's service, as ``manage_service`` takes it.
|
||||
ZABBIX_AGENT_SERVICE: ClassVar[str] = "zabbix-agent"
|
||||
|
||||
def configure_zabbix_agent(self, settings: ZabbixAgentSettingsDict) -> FixResultDict:
|
||||
"""Install, configure, open, enable and restart the agent with *settings*.
|
||||
|
||||
:raises ValueError: for settings the agent's configuration cannot take,
|
||||
before anything changes.
|
||||
"""
|
||||
check_zabbix_agent_settings(settings)
|
||||
return run_fix_steps(
|
||||
[
|
||||
("install", lambda: self._install_zabbix_agent(settings)),
|
||||
("configure", lambda: self._write_zabbix_agent_config(settings)),
|
||||
("firewall", lambda: self._open_zabbix_agent_port(settings)),
|
||||
("start", self._start_zabbix_agent),
|
||||
]
|
||||
)
|
||||
|
||||
def _install_zabbix_agent(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
index = self._load_package_index()
|
||||
first = self.ensure_package(self.ZABBIX_AGENT_PACKAGE)
|
||||
if first["success"]:
|
||||
return {"ok": True, "output": _joined(index, first.get("output"))}
|
||||
release = settings.get("release")
|
||||
add = getattr(self, "_add_zabbix_repository", None)
|
||||
if not release or not callable(add):
|
||||
return {"ok": False, "output": _joined(index, first.get("output"))}
|
||||
added = add(release)
|
||||
if not added["ok"]:
|
||||
return {"ok": False, "output": _joined(index, added.get("output"))}
|
||||
second = self.ensure_package(self.ZABBIX_AGENT_PACKAGE)
|
||||
return {
|
||||
"ok": bool(second["success"]),
|
||||
"output": _joined(index, added.get("output"), second.get("output")),
|
||||
}
|
||||
|
||||
def _load_package_index(self) -> str:
|
||||
"""Load the package index where the driver can (OpenWrt keeps it in RAM, gone
|
||||
after a restart); what went wrong, or "". The install tries either way."""
|
||||
refresh = getattr(self, "refresh_available_updates", None)
|
||||
if not callable(refresh):
|
||||
return ""
|
||||
loaded = refresh()
|
||||
if loaded.get("success"):
|
||||
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)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def ensure_package(self, name: str) -> FixResultDict: ...
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]: ...
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]: ...
|
||||
|
||||
# The steps a driver implements:
|
||||
|
||||
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
|
||||
"""Add Zabbix's repository for *release* and refresh the package index
|
||||
(``zabbix_repository_command`` builds the command for most hosts)."""
|
||||
...
|
||||
|
||||
def _write_zabbix_agent_config(
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Write *settings* into the agent's configuration file, keeping the rest of
|
||||
it (``zabbix_agent_config``), and whatever else the device needs before the
|
||||
agent may start."""
|
||||
...
|
||||
|
||||
def _allow_zabbix_agent_sources(
|
||||
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 []. 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."""
|
||||
...
|
||||
|
||||
|
||||
class PackageProxyMixin:
|
||||
"""Point the device's package manager at a caching proxy."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
|
||||
def configure_package_proxy(self, url: str) -> FixResultDict:
|
||||
"""Have the package manager fetch through *url*; an empty *url* removes it."""
|
||||
...
|
||||
|
||||
def get_package_proxy(self) -> str | None:
|
||||
"""The proxy the package manager fetches through now; None for none.
|
||||
|
||||
A fact: whether it is the right one is the caller's to judge."""
|
||||
...
|
||||
|
||||
|
||||
__all__ = [
|
||||
"EnsurePackageMixin",
|
||||
"FixStep",
|
||||
"LldpAgentMixin",
|
||||
"PackageProxyMixin",
|
||||
"SnmpAgentMixin",
|
||||
"ZabbixAgentMixin",
|
||||
"enable_and_restart",
|
||||
"run_fix_steps",
|
||||
]
|
||||
@@ -0,0 +1,341 @@
|
||||
"""How a Linux host is hardened, as its kernel and its own tools say it (NetOrk/netork#2706).
|
||||
|
||||
Five things, each read where the host itself keeps it:
|
||||
|
||||
- **The security modules in force:** ``/sys/kernel/security/lsm`` lists the active
|
||||
LSMs. SELinux's mode comes from ``getenforce`` (or ``/sys/fs/selinux/enforce``), the
|
||||
mode it boots in from ``SELINUX=`` in ``/etc/selinux/config``. AppArmor's switch is
|
||||
``/sys/module/apparmor/parameters/enabled``, its profiles per mode come from
|
||||
``aa-status --json`` -- the one part that needs root.
|
||||
- **The crypto policy:** ``update-crypto-policies --show`` (the dnf family; Debian and
|
||||
Ubuntu have none) and FIPS mode from ``/proc/sys/crypto/fips_enabled``.
|
||||
- **The CPU vulnerabilities:** each file under ``/sys/devices/system/cpu/vulnerabilities``
|
||||
holds the kernel's own answer for one of them: ``Not affected``, ``Mitigation: ...``,
|
||||
``Vulnerable...``, or ``Unknown: ...`` (:func:`cpu_vulnerability_state`).
|
||||
- **The kernel command line:** ``mitigations=`` (``auto`` when not given, as in the
|
||||
kernel) and ``nosmt``.
|
||||
- **The distribution's IDs** (``ID`` and ``ID_LIKE`` from ``/etc/os-release``), so a
|
||||
consumer can tell an Enterprise Linux host, where SELinux is the distribution's own
|
||||
module, from one that merely has it installed.
|
||||
|
||||
One fixed command, read-only, the same on every Linux host, so it and its parse live
|
||||
here once and a driver only carries the command across. **Not read is None, never
|
||||
empty or off:** a section the command did not print -- a file missing, a tool not
|
||||
installed, root refused -- comes back ``None``, so a consumer never reads "not looked"
|
||||
as "clean".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, Literal, TypedDict
|
||||
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "HARDENING_BEGIN"
|
||||
_END = "HARDENING_END"
|
||||
_VULNERABILITIES = "/sys/devices/system/cpu/vulnerabilities"
|
||||
|
||||
#: 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``. ``r`` prints a file
|
||||
#: under a section header and ends it with a newline: ``/sys/kernel/security/lsm`` has
|
||||
#: none of its own.
|
||||
HARDENING_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
'r() { if [ -r "$2" ]; then echo "[$1]"; cat "$2" 2>/dev/null; echo; fi; }; '
|
||||
"printf '%s%s\\n' HARDENING_ BEGIN; "
|
||||
"r lsm /sys/kernel/security/lsm; "
|
||||
"r cmdline /proc/cmdline; "
|
||||
"r fips /proc/sys/crypto/fips_enabled; "
|
||||
"r apparmor_enabled /sys/module/apparmor/parameters/enabled; "
|
||||
"if [ -r /etc/os-release ]; then echo '[os]'; grep -E '^(ID|ID_LIKE)=' /etc/os-release; fi; "
|
||||
"if command -v getenforce >/dev/null 2>&1; then echo '[selinux]'; getenforce 2>/dev/null; "
|
||||
"else r selinux_enforce /sys/fs/selinux/enforce; fi; "
|
||||
"if [ -r /etc/selinux/config ]; then echo '[selinux_config]'; "
|
||||
"grep -E '^SELINUX=' /etc/selinux/config; fi; "
|
||||
"if command -v update-crypto-policies >/dev/null 2>&1; then echo '[crypto_policy]'; "
|
||||
"update-crypto-policies --show 2>/dev/null; fi; "
|
||||
f"if [ -d {_VULNERABILITIES} ]; then echo '[cpu_vulnerabilities]'; "
|
||||
f"grep -H . {_VULNERABILITIES}/* 2>/dev/null; fi; "
|
||||
"if command -v aa-status >/dev/null 2>&1; then echo '[aa_status]'; "
|
||||
"aa-status --json 2>/dev/null; echo; fi; "
|
||||
"printf '%s%s\\n' HARDENING_ END"
|
||||
)
|
||||
|
||||
CpuVulnerabilityState = Literal["not_affected", "mitigated", "vulnerable", "unknown"]
|
||||
|
||||
_SELINUX_MODES = frozenset({"enforcing", "permissive", "disabled"})
|
||||
_ENFORCE_FILE = {"1": "enforcing", "0": "permissive"}
|
||||
_SECTION = re.compile(r"^\[([a-z_]+)\]$")
|
||||
|
||||
|
||||
class SelinuxDict(TypedDict):
|
||||
"""SELinux on the host. ``None`` in a field: could not be read."""
|
||||
|
||||
mode: str | None # "enforcing", "permissive" or "disabled"
|
||||
configured: str | None # SELINUX= in /etc/selinux/config: the mode it boots in
|
||||
|
||||
|
||||
class AppArmorDict(TypedDict):
|
||||
"""AppArmor on the host. ``None`` in a field: could not be read."""
|
||||
|
||||
enabled: bool | None # /sys/module/apparmor/parameters/enabled, else the LSM list
|
||||
#: Loaded profiles per mode ("enforce", "complain", ...), from ``aa-status --json``;
|
||||
#: None without root, which it needs.
|
||||
profiles: dict[str, int] | None
|
||||
|
||||
|
||||
class HardeningDict(TypedDict):
|
||||
"""What :meth:`HardeningMixin.get_hardening` read. ``None``: not read, never "off"."""
|
||||
|
||||
lsm: list[str] | None # /sys/kernel/security/lsm, in the kernel's order
|
||||
selinux: SelinuxDict | None # None: no sign of SELinux on the host
|
||||
apparmor: AppArmorDict | None # None: no sign of AppArmor on the host
|
||||
crypto_policy: str | None # update-crypto-policies --show, e.g. "DEFAULT:SHA1"
|
||||
fips: bool | None # /proc/sys/crypto/fips_enabled
|
||||
#: File name under /sys/devices/system/cpu/vulnerabilities -> the kernel's text.
|
||||
cpu_vulnerabilities: dict[str, str] | None
|
||||
cmdline: str | None # /proc/cmdline
|
||||
mitigations: str | None # mitigations= on the command line; "auto" when not given
|
||||
nosmt: bool | None # SMT switched off by the command line
|
||||
os_ids: list[str] | None # ID, then ID_LIKE, from /etc/os-release, lowercased
|
||||
|
||||
|
||||
def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState:
|
||||
"""What the kernel's text for one CPU vulnerability says, in one word.
|
||||
|
||||
The kernel writes ``Not affected``, ``Mitigation: ...`` (also behind a prefix, as
|
||||
``KVM: Mitigation: VMX disabled``), ``Vulnerable...`` or ``Processor vulnerable``,
|
||||
and ``Unknown: ...`` where it cannot tell (a guest that cannot see its host's
|
||||
microcode). A mitigation that leaves SMT exposed is still the kernel's
|
||||
``Mitigation``: the text keeps the rest.
|
||||
"""
|
||||
lowered = text.strip().lower()
|
||||
if lowered.startswith("not affected"):
|
||||
return "not_affected"
|
||||
if lowered.startswith(("vulnerable", "processor vulnerable")):
|
||||
return "vulnerable"
|
||||
if lowered.startswith("mitigation") or ": mitigation" in lowered:
|
||||
return "mitigated"
|
||||
return "unknown"
|
||||
|
||||
|
||||
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 hardening report in the output") from None
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
header = _SECTION.match(line)
|
||||
if header:
|
||||
current = sections.setdefault(header.group(1), [])
|
||||
elif line:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _first(sections: dict[str, list[str]], key: str) -> str | None:
|
||||
lines = sections.get(key)
|
||||
return lines[0] if lines else None
|
||||
|
||||
|
||||
def _unquote(value: str) -> str:
|
||||
value = value.strip()
|
||||
return value[1:-1] if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'" else value
|
||||
|
||||
|
||||
def _lsm(sections: dict[str, list[str]]) -> list[str] | None:
|
||||
line = _first(sections, "lsm")
|
||||
if line is None:
|
||||
return None
|
||||
return [name.strip() for name in line.split(",") if name.strip()]
|
||||
|
||||
|
||||
def _selinux_configured(sections: dict[str, list[str]]) -> str | None:
|
||||
"""The mode it boots in: ``SELINUX=`` in ``/etc/selinux/config``, the last one."""
|
||||
configured = None
|
||||
for line in sections.get("selinux_config", []):
|
||||
key, _, value = line.partition("=")
|
||||
if key.strip() == "SELINUX":
|
||||
configured = _unquote(value).lower() or None
|
||||
return configured
|
||||
|
||||
|
||||
def _selinux_running(sections: dict[str, list[str]]) -> str | None:
|
||||
"""The mode it runs in: ``getenforce``'s word, else ``/sys/fs/selinux/enforce``."""
|
||||
said = (_first(sections, "selinux") or "").lower()
|
||||
if said in _SELINUX_MODES:
|
||||
return said
|
||||
return _ENFORCE_FILE.get(_first(sections, "selinux_enforce") or "")
|
||||
|
||||
|
||||
def _selinux_seen(sections: dict[str, list[str]], lsm: list[str] | None, mode: str | None) -> bool:
|
||||
"""Whether the host shows any sign of SELinux: a mode, its configuration, the LSM list."""
|
||||
return mode is not None or "selinux_config" in sections or "selinux" in (lsm or [])
|
||||
|
||||
|
||||
def _selinux(sections: dict[str, list[str]], lsm: list[str] | None) -> SelinuxDict | None:
|
||||
mode = _selinux_running(sections)
|
||||
if not _selinux_seen(sections, lsm, mode):
|
||||
return None
|
||||
if mode is None and "selinux_config" in sections and lsm is not None:
|
||||
# Installed, but not among the modules the kernel runs: switched off at boot.
|
||||
mode = None if "selinux" in lsm else "disabled"
|
||||
return {"mode": mode, "configured": _selinux_configured(sections)}
|
||||
|
||||
|
||||
def _profiles(sections: dict[str, list[str]]) -> dict[str, int] | None:
|
||||
text = "".join(sections.get("aa_status", []))
|
||||
try:
|
||||
profiles = json.loads(text).get("profiles")
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
if not isinstance(profiles, dict):
|
||||
return None
|
||||
counts: dict[str, int] = {}
|
||||
for mode in profiles.values():
|
||||
counts[str(mode)] = counts.get(str(mode), 0) + 1
|
||||
return dict(sorted(counts.items()))
|
||||
|
||||
|
||||
def _apparmor(sections: dict[str, list[str]], lsm: list[str] | None) -> AppArmorDict | None:
|
||||
switch = _first(sections, "apparmor_enabled")
|
||||
profiles = _profiles(sections)
|
||||
in_lsm = "apparmor" in (lsm or [])
|
||||
if switch is None and profiles is None and not in_lsm:
|
||||
return None
|
||||
if switch is not None:
|
||||
enabled: bool | None = switch.upper().startswith("Y")
|
||||
else:
|
||||
enabled = True if in_lsm else None
|
||||
return {"enabled": enabled, "profiles": profiles}
|
||||
|
||||
|
||||
def _cpu_vulnerabilities(sections: dict[str, list[str]]) -> dict[str, str] | None:
|
||||
if "cpu_vulnerabilities" not in sections:
|
||||
return None
|
||||
found: dict[str, str] = {}
|
||||
for line in sections["cpu_vulnerabilities"]:
|
||||
path, sep, text = line.partition(":")
|
||||
if sep:
|
||||
found[path.rsplit("/", 1)[-1]] = text.strip()
|
||||
return dict(sorted(found.items()))
|
||||
|
||||
|
||||
def _command_line(cmdline: str | None) -> tuple[str | None, bool | None]:
|
||||
"""``mitigations=`` (the last one wins, as in the kernel) and whether SMT is off."""
|
||||
if cmdline is None:
|
||||
return None, None
|
||||
mitigations = "auto"
|
||||
nosmt = False
|
||||
for word in cmdline.split():
|
||||
key, _, value = word.partition("=")
|
||||
if key == "mitigations":
|
||||
mitigations = value
|
||||
elif key == "nosmt":
|
||||
nosmt = True
|
||||
return mitigations, nosmt or "nosmt" in mitigations.split(",")
|
||||
|
||||
|
||||
def _os_ids(sections: dict[str, list[str]]) -> list[str] | None:
|
||||
if "os" not in sections:
|
||||
return None
|
||||
values = {}
|
||||
for line in sections["os"]:
|
||||
key, _, value = line.partition("=")
|
||||
values[key.strip()] = _unquote(value)
|
||||
ids: list[str] = []
|
||||
for word in f"{values.get('ID', '')} {values.get('ID_LIKE', '')}".lower().split():
|
||||
if word not in ids:
|
||||
ids.append(word)
|
||||
return ids
|
||||
|
||||
|
||||
def parse_hardening(output: str) -> HardeningDict:
|
||||
"""Parse what :data:`HARDENING_COMMAND` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
lsm = _lsm(sections)
|
||||
cmdline = _first(sections, "cmdline")
|
||||
mitigations, nosmt = _command_line(cmdline)
|
||||
fips = _first(sections, "fips")
|
||||
return {
|
||||
"lsm": lsm,
|
||||
"selinux": _selinux(sections, lsm),
|
||||
"apparmor": _apparmor(sections, lsm),
|
||||
"crypto_policy": _first(sections, "crypto_policy"),
|
||||
"fips": None if fips is None else fips == "1",
|
||||
"cpu_vulnerabilities": _cpu_vulnerabilities(sections),
|
||||
"cmdline": cmdline,
|
||||
"mitigations": mitigations,
|
||||
"nosmt": nosmt,
|
||||
"os_ids": _os_ids(sections),
|
||||
}
|
||||
|
||||
|
||||
class HardeningMixin:
|
||||
"""Adds :meth:`get_hardening` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are the
|
||||
same everywhere, and a driver supplies only :meth:`_run_hardening_command` -- how a
|
||||
command reaches its host, and how it gains root there. Mixed in by the drivers that
|
||||
can, so ``hasattr(driver, "get_hardening")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root when
|
||||
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
|
||||
...
|
||||
|
||||
def get_hardening(self) -> HardeningDict:
|
||||
"""
|
||||
Returns how the host is hardened: its security modules, crypto policy, CPU
|
||||
vulnerabilities and kernel command line.
|
||||
|
||||
* lsm (list or None) - the active security modules, in the kernel's order
|
||||
* selinux ({mode, configured} or None) - None without any sign of SELinux
|
||||
* apparmor ({enabled, profiles} or None) - profiles per mode need root
|
||||
* crypto_policy (str or None) - ``update-crypto-policies --show``
|
||||
* fips (bool or None) - FIPS mode
|
||||
* cpu_vulnerabilities (dict or None) - name -> the kernel's text
|
||||
* cmdline (str or None), mitigations (str or None), nosmt (bool or None)
|
||||
* os_ids (list or None) - ``ID`` and ``ID_LIKE`` from ``/etc/os-release``
|
||||
|
||||
``None`` means not read. Read as root first, for AppArmor's profiles; where root
|
||||
is refused, as the login user, without them.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"lsm": ["lockdown", "capability", "yama", "selinux", "bpf"],
|
||||
"selinux": {"mode": "enforcing", "configured": "enforcing"},
|
||||
"apparmor": None,
|
||||
"crypto_policy": "DEFAULT",
|
||||
"fips": False,
|
||||
"cpu_vulnerabilities": {"meltdown": "Not affected",
|
||||
"spectre_v2": "Mitigation: Retpolines; ..."},
|
||||
"cmdline": "BOOT_IMAGE=... ro",
|
||||
"mitigations": "auto",
|
||||
"nosmt": False,
|
||||
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(HARDENING_COMMAND)}"
|
||||
try:
|
||||
return parse_hardening(self._run_hardening_command(command, privileged=True))
|
||||
except ValueError:
|
||||
pass
|
||||
return parse_hardening(self._run_hardening_command(command, privileged=False))
|
||||
@@ -0,0 +1,69 @@
|
||||
"""SNMP health collection, shared by every device type that speaks UCD-MIB.
|
||||
|
||||
**Deprecated** (docs/STRUCTURE.md): drivers do not collect over SNMP. The
|
||||
application polls; a driver whose device publishes values under its own OIDs
|
||||
declares them as ``SNMP_HEALTH_PROFILE``
|
||||
(:class:`~napalm_device_types.snmp_health_profile.SnmpHealthProfile`). This mixin goes in 5.0.
|
||||
|
||||
The collection itself is generic: CPU, memory, uptime, load and per-interface
|
||||
counters come from the same standard OIDs on any UCD-MIB/IF-MIB capable device.
|
||||
Only two details vary by device type, and both are class attributes rather than
|
||||
code -- which is why this was five byte-identical copies of the same method
|
||||
before it moved here.
|
||||
|
||||
A device type whose vendor publishes the same data under proprietary OIDs does
|
||||
**not** mix this in; ``SwitchDriver`` is the example, and its concrete drivers
|
||||
implement ``get_health_metrics`` themselves.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import warnings
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any, ClassVar, cast
|
||||
|
||||
from napalm_device_types._ucd_metrics import IF_SKIP_DEFAULT, collect_ucd_metrics
|
||||
from napalm_device_types.models import HealthMetricsDict
|
||||
|
||||
|
||||
class HealthMetricsMixin:
|
||||
"""Adds the standard UCD-MIB/IF-MIB ``get_health_metrics`` collector."""
|
||||
|
||||
#: Interfaces whose counters are noise rather than signal. Loopback,
|
||||
#: tunnels and container bridges inflate error rates without meaning.
|
||||
_SNMP_SKIP_IF: ClassVar[re.Pattern[str]] = IF_SKIP_DEFAULT
|
||||
|
||||
#: Whether the device reports discards in the TX-error counter. Firewalls
|
||||
#: do -- a dropped packet is the point, not a fault -- so counting those as
|
||||
#: errors would make a healthy firewall look broken.
|
||||
_SNMP_TX_ERR_IS_DROP: ClassVar[bool] = False
|
||||
|
||||
@classmethod
|
||||
async def get_health_metrics(
|
||||
cls,
|
||||
snmp_get: Callable[..., Awaitable[Any]],
|
||||
snmp_walk: Callable[..., Awaitable[dict[str, Any]]],
|
||||
) -> HealthMetricsDict:
|
||||
"""Collect SNMP health metrics (CPU, memory, uptime, load, interfaces).
|
||||
|
||||
Deprecated: the application polls; see the module docstring.
|
||||
"""
|
||||
warnings.warn(
|
||||
"HealthMetricsMixin.get_health_metrics is deprecated and goes in 5.0: "
|
||||
"the application polls over SNMP; a driver declares only its OIDs, "
|
||||
"as SNMP_HEALTH_PROFILE",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
# collect_ucd_metrics is untyped shared plumbing; the shape it returns is
|
||||
# the contract HealthMetricsDict describes.
|
||||
return cast(
|
||||
HealthMetricsDict,
|
||||
await collect_ucd_metrics(
|
||||
snmp_get,
|
||||
snmp_walk,
|
||||
tx_err_is_drop=cls._SNMP_TX_ERR_IS_DROP,
|
||||
if_skip=cls._SNMP_SKIP_IF,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,770 @@
|
||||
"""A Linux host's own firewall: its netfilter rules, read once, in one shape.
|
||||
|
||||
Whether a service is reachable from outside its host is decided twice: by the
|
||||
address it listens on (:mod:`napalm_device_types.listening`), and by the host's
|
||||
own firewall, which may drop the packets first. Reading the firewall is the
|
||||
same on every Linux host, so the command and its parse live here, and a driver
|
||||
only carries the command across.
|
||||
|
||||
**What is read.** ``nft -j list ruleset`` is the primary reading: every table,
|
||||
the host's own ``nftables.service`` ones included. Rules that iptables-nft wrote
|
||||
are in it too, but their extensions show only as an opaque ``xt`` -- a
|
||||
``-m conntrack --ctstate`` or ``-m set`` says nothing there. ``iptables-save``
|
||||
spells them out, so the tables iptables manages are taken from it, and the
|
||||
others from nft. A *legacy* iptables is a second ruleset beside nft, and both
|
||||
apply to every packet, so then both are kept whole.
|
||||
|
||||
**One shape.** Each chain says its family, table, hook, priority and policy;
|
||||
each rule a list of matches and a verdict. A match is ``field``, ``op``
|
||||
(``==``/``!=``) and ``values``. The fields are the few that decide reachability
|
||||
from outside: ``iifname``, ``oifname``, ``saddr``, ``daddr``, ``l4proto``,
|
||||
``dport``, ``sport``, ``ct_state``, ``ct_orig_dport`` and ``nfproto``.
|
||||
Everything else -- an ipset, ``addrtype``, a rate limit, a ``fib`` lookup -- is
|
||||
``unknown`` with its text, never dropped: a rule that matches on something this
|
||||
does not model must not read as one that matches everything.
|
||||
|
||||
**Root, and only root.** Both tools need ``CAP_NET_ADMIN``; without it they
|
||||
print an error, not an empty ruleset. So there is no reading without root:
|
||||
:class:`HostFirewallUnavailable` is raised rather than a host without rules.
|
||||
|
||||
Whether a rule set makes a service unreachable is the consumer's call.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Iterator
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import (
|
||||
HostFirewallDict,
|
||||
NetfilterChainDict,
|
||||
NetfilterMatchDict,
|
||||
NetfilterRuleDict,
|
||||
)
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "FW_BEGIN"
|
||||
_END = "FW_END"
|
||||
_RC_RE = re.compile(r"^__FW_RC=(\d+)$")
|
||||
|
||||
#: 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.
|
||||
#: Both tools live in ``/usr/sbin`` on most systems, outside a login user's ``PATH``.
|
||||
HOST_FIREWALL_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' FW_ BEGIN; "
|
||||
"if command -v nft >/dev/null 2>&1; then "
|
||||
"echo '[nft]'; nft -j list ruleset 2>&1; echo \"__FW_RC=$?\"; fi; "
|
||||
"for t in iptables-save ip6tables-save; do "
|
||||
"if command -v $t >/dev/null 2>&1; then "
|
||||
'echo "[$t]"; $t 2>&1; echo "__FW_RC=$?"; fi; done; '
|
||||
"printf '%s%s\\n' FW_ END"
|
||||
)
|
||||
|
||||
#: ``iptables-save`` reads the IPv4 tables, ``ip6tables-save`` the IPv6 ones.
|
||||
_IPTABLES_FAMILY = {"iptables-save": "ip", "ip6tables-save": "ip6"}
|
||||
|
||||
#: The built-in chains of iptables' tables: ``(type, hook, priority)``, as
|
||||
#: iptables-nft registers them (and as the legacy tables run in the kernel).
|
||||
_BUILT_IN: dict[str, dict[str, tuple[str, str, int]]] = {
|
||||
"raw": {"PREROUTING": ("filter", "prerouting", -300), "OUTPUT": ("filter", "output", -300)},
|
||||
"mangle": {
|
||||
"PREROUTING": ("filter", "prerouting", -150),
|
||||
"INPUT": ("filter", "input", -150),
|
||||
"FORWARD": ("filter", "forward", -150),
|
||||
"OUTPUT": ("route", "output", -150),
|
||||
"POSTROUTING": ("filter", "postrouting", -150),
|
||||
},
|
||||
"nat": {
|
||||
"PREROUTING": ("nat", "prerouting", -100),
|
||||
"INPUT": ("nat", "input", 100),
|
||||
"OUTPUT": ("nat", "output", -100),
|
||||
"POSTROUTING": ("nat", "postrouting", 100),
|
||||
},
|
||||
"filter": {
|
||||
"INPUT": ("filter", "input", 0),
|
||||
"FORWARD": ("filter", "forward", 0),
|
||||
"OUTPUT": ("filter", "output", 0),
|
||||
},
|
||||
"security": {
|
||||
"INPUT": ("filter", "input", 50),
|
||||
"FORWARD": ("filter", "forward", 50),
|
||||
"OUTPUT": ("filter", "output", 50),
|
||||
},
|
||||
}
|
||||
|
||||
_TERMINAL = {"ACCEPT": "accept", "DROP": "drop", "REJECT": "reject", "RETURN": "return"}
|
||||
#: Targets that look at a packet, mark it or log it, and let it go on.
|
||||
_NON_TERMINAL = frozenset(
|
||||
{
|
||||
"LOG",
|
||||
"NFLOG",
|
||||
"ULOG",
|
||||
"TRACE",
|
||||
"MARK",
|
||||
"CONNMARK",
|
||||
"CT",
|
||||
"NOTRACK",
|
||||
"TCPMSS",
|
||||
"CHECKSUM",
|
||||
"AUDIT",
|
||||
"SET",
|
||||
"DSCP",
|
||||
"TOS",
|
||||
"TTL",
|
||||
"HL",
|
||||
"CLASSIFY",
|
||||
"CONNSECMARK",
|
||||
"SECMARK",
|
||||
"IDLETIMER",
|
||||
"LED",
|
||||
"RATEEST",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class HostFirewallUnavailable(NotImplementedError):
|
||||
"""Nothing on the host could be read: no ``nft``, no ``iptables-save``, or no root."""
|
||||
|
||||
|
||||
def _frame(output: str) -> list[str]:
|
||||
lines = [line.rstrip() for line in 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 host firewall report in the output") from None
|
||||
return lines[start + 1 : end]
|
||||
|
||||
|
||||
def _sections(lines: list[str]) -> dict[str, tuple[list[str], int | None]]:
|
||||
"""Each tool's output and exit status."""
|
||||
sections: dict[str, tuple[list[str], int | None]] = {}
|
||||
name: str | None = None
|
||||
body: list[str] = []
|
||||
for line in lines:
|
||||
text = line.strip()
|
||||
if text in ("[nft]", "[iptables-save]", "[ip6tables-save]"):
|
||||
name, body = text[1:-1], []
|
||||
sections[name] = (body, None)
|
||||
continue
|
||||
rc = _RC_RE.match(text)
|
||||
if rc and name is not None:
|
||||
sections[name] = (body, int(rc.group(1)))
|
||||
name = None
|
||||
continue
|
||||
if name is not None:
|
||||
body.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
# ── iptables-save ────────────────────────────────────────────────────────────
|
||||
|
||||
#: The token that negates the option after it (``! -s 10.0.0.0/8``).
|
||||
_NEGATION = "!"
|
||||
|
||||
#: Options that start a new part of a rule, outside any ``-m`` module.
|
||||
_TOP_LEVEL = frozenset(
|
||||
{
|
||||
"-m",
|
||||
"--match",
|
||||
"-j",
|
||||
"--jump",
|
||||
"-g",
|
||||
"--goto",
|
||||
"-p",
|
||||
"--protocol",
|
||||
"-s",
|
||||
"--source",
|
||||
"-d",
|
||||
"--destination",
|
||||
"-i",
|
||||
"--in-interface",
|
||||
"-o",
|
||||
"--out-interface",
|
||||
"-f",
|
||||
"--fragment",
|
||||
"-c",
|
||||
"--set-counters",
|
||||
}
|
||||
)
|
||||
#: Modules whose options this reads; any other module is an ``unknown`` match.
|
||||
_KNOWN_MODULES = frozenset(
|
||||
{"tcp", "udp", "sctp", "udplite", "multiport", "state", "conntrack", "comment"}
|
||||
)
|
||||
|
||||
|
||||
def _match(field: str, negated: bool, values: list[str]) -> NetfilterMatchDict:
|
||||
return {"field": field, "op": "!=" if negated else "==", "values": values}
|
||||
|
||||
|
||||
def _unknown(text: str) -> NetfilterMatchDict:
|
||||
return {"field": "unknown", "op": "==", "values": [text]}
|
||||
|
||||
|
||||
def _iface(name: str) -> str:
|
||||
"""iptables writes a wildcard interface as ``eth+``; nft as ``eth*``."""
|
||||
return name[:-1] + "*" if name.endswith("+") else name
|
||||
|
||||
|
||||
def _ports(spec: str) -> list[str]:
|
||||
return [p.replace(":", "-") for p in spec.split(",") if p]
|
||||
|
||||
|
||||
def _states(spec: str) -> list[str]:
|
||||
return [s.lower() for s in spec.split(",") if s]
|
||||
|
||||
|
||||
class _RuleTokens:
|
||||
"""The tokens of one ``-A`` line, read front to back."""
|
||||
|
||||
def __init__(self, tokens: list[str]):
|
||||
self.tokens = tokens
|
||||
self.i = 0
|
||||
|
||||
def more(self) -> bool:
|
||||
return self.i < len(self.tokens)
|
||||
|
||||
def peek(self, ahead: int = 0) -> str | None:
|
||||
j = self.i + ahead
|
||||
return self.tokens[j] if j < len(self.tokens) else None
|
||||
|
||||
def take(self) -> str:
|
||||
token = self.tokens[self.i]
|
||||
self.i += 1
|
||||
return token
|
||||
|
||||
|
||||
def _module_options(module: str, rt: _RuleTokens, matches: list[NetfilterMatchDict]) -> None:
|
||||
"""Read *module*'s options from *rt* into *matches*; stop at the next top-level option."""
|
||||
text = ["-m", module]
|
||||
unknown = module not in _KNOWN_MODULES
|
||||
while rt.more():
|
||||
token = rt.peek()
|
||||
if token in _TOP_LEVEL or (token == _NEGATION and rt.peek(1) in _TOP_LEVEL):
|
||||
break
|
||||
negated = False
|
||||
if token == _NEGATION:
|
||||
rt.take()
|
||||
negated = True
|
||||
text.append(_NEGATION)
|
||||
option = rt.take()
|
||||
value = rt.take() if rt.more() and not str(rt.peek()).startswith("-") else ""
|
||||
text += [option] + ([value] if value else [])
|
||||
if unknown:
|
||||
continue
|
||||
mapped = _module_match(module, option, value, negated)
|
||||
if mapped is None:
|
||||
unknown = True
|
||||
elif mapped is not False:
|
||||
matches.append(mapped)
|
||||
if unknown and module != "comment":
|
||||
matches.append(_unknown(" ".join(text)))
|
||||
|
||||
|
||||
def _module_match(module: str, option: str, value: str, negated: bool) -> Any:
|
||||
"""The match one module option makes.
|
||||
|
||||
False for one that matches nothing new; None if not read.
|
||||
"""
|
||||
if module == "comment":
|
||||
return False
|
||||
if module in ("tcp", "udp", "sctp", "udplite"):
|
||||
if option in ("--dport", "--destination-port"):
|
||||
return _match("dport", negated, _ports(value))
|
||||
if option in ("--sport", "--source-port"):
|
||||
return _match("sport", negated, _ports(value))
|
||||
return None
|
||||
if module == "multiport":
|
||||
if option in ("--dports", "--destination-ports"):
|
||||
return _match("dport", negated, _ports(value))
|
||||
if option in ("--sports", "--source-ports"):
|
||||
return _match("sport", negated, _ports(value))
|
||||
return None
|
||||
if module == "state" and option == "--state":
|
||||
return _match("ct_state", negated, _states(value))
|
||||
if module == "conntrack":
|
||||
if option == "--ctstate":
|
||||
return _match("ct_state", negated, _states(value))
|
||||
if option == "--ctorigdstport":
|
||||
return _match("ct_orig_dport", negated, _ports(value))
|
||||
return None
|
||||
|
||||
|
||||
def _target(name: str, chains: set[str]) -> tuple[str, str | None]:
|
||||
if name in _TERMINAL:
|
||||
return _TERMINAL[name], None
|
||||
if name in chains:
|
||||
return "jump", name
|
||||
if name in _NON_TERMINAL:
|
||||
return "continue", name
|
||||
return "other", name
|
||||
|
||||
|
||||
def _iptables_rule(line: str, chains: set[str]) -> tuple[str, NetfilterRuleDict]:
|
||||
"""``-A CHAIN ...`` as ``(chain, rule)``."""
|
||||
tokens = shlex.split(line)
|
||||
chain = tokens[1]
|
||||
rt = _RuleTokens(tokens[2:])
|
||||
matches: list[NetfilterMatchDict] = []
|
||||
verdict, target = "continue", None
|
||||
negated = False
|
||||
simple = {
|
||||
"-i": "iifname",
|
||||
"--in-interface": "iifname",
|
||||
"-o": "oifname",
|
||||
"--out-interface": "oifname",
|
||||
"-s": "saddr",
|
||||
"--source": "saddr",
|
||||
"-d": "daddr",
|
||||
"--destination": "daddr",
|
||||
"-p": "l4proto",
|
||||
"--protocol": "l4proto",
|
||||
}
|
||||
while rt.more():
|
||||
token = rt.take()
|
||||
if token == _NEGATION:
|
||||
negated = True
|
||||
continue
|
||||
if token in simple:
|
||||
field, value = simple[token], rt.take()
|
||||
if field in ("iifname", "oifname"):
|
||||
matches.append(_match(field, negated, [_iface(value)]))
|
||||
elif field == "l4proto":
|
||||
if value.lower() != "all":
|
||||
matches.append(_match(field, negated, [value.lower()]))
|
||||
else:
|
||||
matches.append(_match(field, negated, value.split(",")))
|
||||
elif token in ("-m", "--match"):
|
||||
_module_options(rt.take(), rt, matches)
|
||||
elif token in ("-j", "--jump"):
|
||||
verdict, target = _target(rt.take(), chains)
|
||||
break # the target's own options follow and match nothing
|
||||
elif token in ("-g", "--goto"):
|
||||
verdict, target = "goto", rt.take()
|
||||
break
|
||||
elif token in ("-c", "--set-counters"):
|
||||
rt.take(), rt.take()
|
||||
else:
|
||||
matches.append(_unknown(token))
|
||||
negated = False
|
||||
return chain, {"matches": matches, "verdict": verdict, "target": target, "text": line}
|
||||
|
||||
|
||||
def _iptables_variant(lines: list[str]) -> str | None:
|
||||
"""``iptables-nft`` or ``iptables-legacy`` from the header; None if nothing was saved."""
|
||||
for line in lines:
|
||||
if line.startswith("# Generated by"):
|
||||
return "iptables-nft" if "(nf_tables)" in line else "iptables-legacy"
|
||||
return None
|
||||
|
||||
|
||||
def _parse_iptables_save(lines: list[str], family: str) -> list[NetfilterChainDict]:
|
||||
chains: list[NetfilterChainDict] = []
|
||||
table: str | None = None
|
||||
by_name: dict[str, NetfilterChainDict] = {}
|
||||
for raw in lines:
|
||||
line = raw.strip()
|
||||
if line.startswith("*"):
|
||||
table, by_name = line[1:], {}
|
||||
elif line.startswith(":") and table is not None:
|
||||
name, policy = line[1:].split()[:2]
|
||||
kind, hook, prio = _BUILT_IN.get(table, {}).get(name, (None, None, None))
|
||||
chain: NetfilterChainDict = {
|
||||
"family": family,
|
||||
"table": table,
|
||||
"name": name,
|
||||
"type": kind,
|
||||
"hook": hook,
|
||||
"priority": prio,
|
||||
"policy": None if policy == "-" else policy.lower(),
|
||||
"rules": [],
|
||||
}
|
||||
by_name[name] = chain
|
||||
chains.append(chain)
|
||||
elif line.startswith("-A ") and table is not None:
|
||||
name, rule = _iptables_rule(line, set(by_name))
|
||||
if name in by_name:
|
||||
by_name[name]["rules"].append(rule)
|
||||
return chains
|
||||
|
||||
|
||||
# ── nft -j ───────────────────────────────────────────────────────────────────
|
||||
|
||||
_VERDICTS = {
|
||||
"accept": "accept",
|
||||
"drop": "drop",
|
||||
"reject": "reject",
|
||||
"return": "return",
|
||||
"continue": "continue",
|
||||
}
|
||||
#: Statements that act on a packet without deciding its fate.
|
||||
_NO_OPS = frozenset(
|
||||
{
|
||||
"counter",
|
||||
"log",
|
||||
"mangle",
|
||||
"notrack",
|
||||
"set",
|
||||
"flow",
|
||||
"ct helper",
|
||||
"synproxy",
|
||||
"tcp option",
|
||||
"dup",
|
||||
"fwd",
|
||||
}
|
||||
)
|
||||
#: Statements that pass only some packets on: what follows is not about every packet.
|
||||
_PARTIAL = frozenset({"limit", "quota", "numgen", "hash", "ct count"})
|
||||
#: Verdicts that hand the packet elsewhere, or that this does not model.
|
||||
_OTHER = frozenset({"queue", "dnat", "snat", "masquerade", "redirect", "tproxy", "vmap"})
|
||||
_TRANSPORTS = frozenset({"tcp", "udp", "sctp", "udplite", "dccp"})
|
||||
|
||||
|
||||
def _nft_scalar(value: Any) -> list[str] | None:
|
||||
"""A right-hand side as values; None for one this does not model."""
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, str)):
|
||||
return [str(value)]
|
||||
if isinstance(value, dict):
|
||||
if "prefix" in value:
|
||||
return [f"{value['prefix']['addr']}/{value['prefix']['len']}"]
|
||||
if "range" in value:
|
||||
low, high = value["range"]
|
||||
return [f"{low}-{high}"]
|
||||
if "elem" in value:
|
||||
return _nft_scalar(value["elem"].get("val"))
|
||||
if "set" in value:
|
||||
return _nft_values(value["set"])
|
||||
if isinstance(value, list):
|
||||
return _nft_values(value)
|
||||
return None
|
||||
|
||||
|
||||
def _nft_values(items: Any) -> list[str] | None:
|
||||
items = items if isinstance(items, list) else [items]
|
||||
out: list[str] = []
|
||||
for item in items:
|
||||
values = _nft_scalar(item)
|
||||
if values is None:
|
||||
return None
|
||||
out += values
|
||||
return out
|
||||
|
||||
|
||||
def _left_text(left: Any) -> str:
|
||||
if isinstance(left, dict):
|
||||
if "payload" in left:
|
||||
return (
|
||||
f"{left['payload'].get('protocol', '')} {left['payload'].get('field', '')}".strip()
|
||||
)
|
||||
if "meta" in left:
|
||||
return f"meta {left['meta'].get('key', '')}"
|
||||
if "ct" in left:
|
||||
ct = left["ct"]
|
||||
return f"ct {ct.get('dir', '')} {ct.get('key', '')}".replace(" ", " ")
|
||||
key = next(iter(left), "")
|
||||
return str(key)
|
||||
return str(left)
|
||||
|
||||
|
||||
def _right_text(right: Any) -> str:
|
||||
values = _nft_scalar(right)
|
||||
if values is None:
|
||||
return json.dumps(right, sort_keys=True)
|
||||
return values[0] if len(values) == 1 else "{" + ", ".join(values) + "}"
|
||||
|
||||
|
||||
def _nft_field(left: Any) -> tuple[str | None, str | None]:
|
||||
"""``(field, implied l4proto)`` of a left-hand side; ``(None, None)`` if not modelled."""
|
||||
if not isinstance(left, dict):
|
||||
return None, None
|
||||
if "meta" in left:
|
||||
key = left["meta"].get("key")
|
||||
return {
|
||||
"iifname": "iifname",
|
||||
"iif": "iifname",
|
||||
"oifname": "oifname",
|
||||
"oif": "oifname",
|
||||
"l4proto": "l4proto",
|
||||
"nfproto": "nfproto",
|
||||
}.get(key), None
|
||||
if "payload" in left:
|
||||
proto, field = left["payload"].get("protocol"), left["payload"].get("field")
|
||||
if proto in ("ip", "ip6") and field in ("saddr", "daddr"):
|
||||
return field, None
|
||||
if (proto, field) in (("ip", "protocol"), ("ip6", "nexthdr")):
|
||||
return "l4proto", None
|
||||
if field in ("dport", "sport") and (proto in _TRANSPORTS or proto == "th"):
|
||||
return field, proto if proto in _TRANSPORTS else None
|
||||
return None, None
|
||||
if "ct" in left:
|
||||
key, direction = left["ct"].get("key"), left["ct"].get("dir")
|
||||
if key == "state":
|
||||
return "ct_state", None
|
||||
if key == "proto-dst" and direction == "original":
|
||||
return "ct_orig_dport", None
|
||||
return None, None
|
||||
|
||||
|
||||
def _nft_match(
|
||||
match: dict[str, Any], sets: dict[tuple[str, str, str], list[str]], where: tuple[str, str]
|
||||
) -> list[NetfilterMatchDict]:
|
||||
left, op, right = match.get("left"), match.get("op"), match.get("right")
|
||||
field, implied = _nft_field(left)
|
||||
raw_text = (
|
||||
f"{_left_text(left)} {'' if op in ('==', 'in') else str(op) + ' '}{_right_text(right)}"
|
||||
)
|
||||
if field is None or op not in ("==", "in", "!="):
|
||||
return [_unknown(raw_text)]
|
||||
if isinstance(right, str) and right.startswith("@"):
|
||||
values = sets.get((where[0], where[1], right[1:]))
|
||||
else:
|
||||
values = _nft_scalar(right)
|
||||
if values is None:
|
||||
return [_unknown(raw_text)]
|
||||
out: list[NetfilterMatchDict] = []
|
||||
if implied:
|
||||
out.append(_match("l4proto", False, [implied]))
|
||||
if field in ("iifname", "oifname", "l4proto", "ct_state", "nfproto"):
|
||||
values = [
|
||||
str(v).lower() if field != "iifname" and field != "oifname" else str(v) for v in values
|
||||
]
|
||||
out.append(_match(field, op == "!=", values))
|
||||
return out
|
||||
|
||||
|
||||
def _nft_rule(
|
||||
rule: dict[str, Any], sets: dict[tuple[str, str, str], list[str]]
|
||||
) -> NetfilterRuleDict:
|
||||
where = (rule.get("family", ""), rule.get("table", ""))
|
||||
matches: list[NetfilterMatchDict] = []
|
||||
verdict, target = "continue", None
|
||||
for statement in rule.get("expr") or []:
|
||||
if not isinstance(statement, dict) or not statement:
|
||||
continue
|
||||
key = next(iter(statement))
|
||||
body = statement[key]
|
||||
if key == "match":
|
||||
matches += _nft_match(body, sets, where)
|
||||
elif key in _VERDICTS:
|
||||
verdict = _VERDICTS[key]
|
||||
break
|
||||
elif key in ("jump", "goto"):
|
||||
verdict, target = key, str((body or {}).get("target"))
|
||||
break
|
||||
elif key == "xt":
|
||||
if (body or {}).get("type") == "target":
|
||||
verdict, target = "other", str(body.get("name"))
|
||||
break
|
||||
matches.append(_unknown(f"xt match {(body or {}).get('name')}"))
|
||||
elif key in _PARTIAL:
|
||||
matches.append(_unknown(key))
|
||||
elif key in _OTHER:
|
||||
verdict, target = "other", key
|
||||
break
|
||||
elif key not in _NO_OPS:
|
||||
matches.append(_unknown(key))
|
||||
entry: NetfilterRuleDict = {
|
||||
"matches": matches,
|
||||
"verdict": verdict,
|
||||
"target": target,
|
||||
"text": "",
|
||||
}
|
||||
entry["text"] = rule_text(entry)
|
||||
return entry
|
||||
|
||||
|
||||
def _parse_nft(text: str, skip: set[tuple[str, str]]) -> list[NetfilterChainDict]:
|
||||
start = text.find("{")
|
||||
if start < 0:
|
||||
raise ValueError("nft printed no JSON")
|
||||
objects = json.loads(text[start:]).get("nftables") or []
|
||||
sets: dict[tuple[str, str, str], list[str]] = {}
|
||||
for obj in objects:
|
||||
if "set" in obj and "elem" in obj["set"]:
|
||||
values = _nft_values(obj["set"]["elem"])
|
||||
if values is not None:
|
||||
s = obj["set"]
|
||||
sets[(s.get("family", ""), s.get("table", ""), s.get("name", ""))] = values
|
||||
chains: dict[tuple[str, str, str], NetfilterChainDict] = {}
|
||||
for obj in objects:
|
||||
if "chain" not in obj:
|
||||
continue
|
||||
c = obj["chain"]
|
||||
if (c.get("family"), c.get("table")) in skip:
|
||||
continue
|
||||
chains[(c["family"], c["table"], c["name"])] = {
|
||||
"family": c["family"],
|
||||
"table": c["table"],
|
||||
"name": c["name"],
|
||||
"type": c.get("type"),
|
||||
"hook": c.get("hook"),
|
||||
"priority": c.get("prio"),
|
||||
"policy": c.get("policy") if c.get("hook") else None,
|
||||
"rules": [],
|
||||
}
|
||||
for obj in objects:
|
||||
if "rule" not in obj:
|
||||
continue
|
||||
r = obj["rule"]
|
||||
chain = chains.get((r.get("family"), r.get("table"), r.get("chain")))
|
||||
if chain is not None:
|
||||
chain["rules"].append(_nft_rule(r, sets))
|
||||
return list(chains.values())
|
||||
|
||||
|
||||
# ── text ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _family_of(values: list[str]) -> str:
|
||||
try:
|
||||
return (
|
||||
"ip6"
|
||||
if all(ipaddress.ip_network(v, strict=False).version == 6 for v in values)
|
||||
else "ip"
|
||||
)
|
||||
except ValueError:
|
||||
return "ip"
|
||||
|
||||
|
||||
def _values_text(values: list[str]) -> str:
|
||||
return values[0] if len(values) == 1 else "{" + ", ".join(values) + "}"
|
||||
|
||||
|
||||
def rule_text(rule: NetfilterRuleDict) -> str:
|
||||
"""A rule as one nft-style line, from its normalized matches and verdict."""
|
||||
protos = [
|
||||
v
|
||||
for m in rule["matches"]
|
||||
if m["field"] == "l4proto" and m["op"] == "=="
|
||||
for v in m["values"]
|
||||
]
|
||||
parts: list[str] = []
|
||||
for m in rule["matches"]:
|
||||
neg = "!= " if m["op"] == "!=" else ""
|
||||
field, values = m["field"], m["values"]
|
||||
if field == "unknown":
|
||||
parts.append(" ".join(values))
|
||||
continue
|
||||
keyword = {
|
||||
"saddr": f"{_family_of(values)} saddr",
|
||||
"daddr": f"{_family_of(values)} daddr",
|
||||
"l4proto": "meta l4proto",
|
||||
"nfproto": "meta nfproto",
|
||||
"ct_state": "ct state",
|
||||
"ct_orig_dport": "ct original proto-dst",
|
||||
"dport": f"{protos[0] if len(protos) == 1 else 'th'} dport",
|
||||
"sport": f"{protos[0] if len(protos) == 1 else 'th'} sport",
|
||||
}.get(field, field)
|
||||
parts.append(f"{keyword} {neg}{_values_text(values)}")
|
||||
verdict = rule["verdict"]
|
||||
if verdict in ("jump", "goto"):
|
||||
parts.append(f"{verdict} {rule['target']}")
|
||||
elif verdict == "other":
|
||||
parts.append(str(rule["target"] or "other"))
|
||||
elif verdict != "continue":
|
||||
parts.append(verdict)
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
# ── the reading ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _iptables_sections(
|
||||
sections: dict[str, tuple[list[str], int | None]],
|
||||
) -> Iterator[tuple[str, str, list[str]]]:
|
||||
"""``(variant, family, lines)`` for each iptables tool that saved something."""
|
||||
for tool, family in _IPTABLES_FAMILY.items():
|
||||
lines, rc = sections.get(tool, ([], None))
|
||||
if rc != 0:
|
||||
continue
|
||||
variant = _iptables_variant(lines)
|
||||
if variant is not None:
|
||||
yield variant, family, lines
|
||||
|
||||
|
||||
def parse_host_firewall(output: str) -> HostFirewallDict:
|
||||
"""The framed report of :data:`HOST_FIREWALL_COMMAND` as one ruleset.
|
||||
|
||||
:raises ValueError: if the report's frame is not intact.
|
||||
:raises HostFirewallUnavailable: if neither tool could be read.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
sources: list[str] = []
|
||||
chains: list[NetfilterChainDict] = []
|
||||
covered: set[tuple[str, str]] = set()
|
||||
for variant, family, lines in _iptables_sections(sections):
|
||||
saved = _parse_iptables_save(lines, family)
|
||||
chains += saved
|
||||
if variant not in sources:
|
||||
sources.append(variant)
|
||||
if variant == "iptables-nft":
|
||||
covered |= {(c["family"], c["table"]) for c in saved}
|
||||
nft_lines, nft_rc = sections.get("nft", ([], None))
|
||||
if nft_rc == 0:
|
||||
try:
|
||||
nft_chains = _parse_nft("\n".join(nft_lines), covered)
|
||||
except ValueError:
|
||||
nft_chains = None
|
||||
if nft_chains is not None:
|
||||
sources.insert(0, "nftables")
|
||||
chains = nft_chains + chains
|
||||
if not sources:
|
||||
raise HostFirewallUnavailable("neither nft nor iptables-save could be read (root needed)")
|
||||
return {"sources": sources, "chains": chains}
|
||||
|
||||
|
||||
class HostFirewallMixin:
|
||||
"""Adds :meth:`get_host_firewall` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse
|
||||
are the same everywhere, so they are concrete here, and a driver supplies
|
||||
only :meth:`_run_host_firewall_command` -- how a command reaches its host,
|
||||
and how it gains root there. Mixed in by the drivers that can, so
|
||||
``hasattr(driver, "get_host_firewall")`` stays truthful.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_host_firewall_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root
|
||||
when *privileged*. The command is a single ``sh -c`` invocation."""
|
||||
...
|
||||
|
||||
def get_host_firewall(self) -> HostFirewallDict:
|
||||
"""
|
||||
Returns the host's netfilter rules: every chain with its hook, priority
|
||||
and policy, and every rule as matches and a verdict.
|
||||
|
||||
* sources (list) - ``nftables``, ``iptables-nft``, ``iptables-legacy``: what was read
|
||||
* chains (list) - see :class:`~napalm_device_types.models.NetfilterChainDict`
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"sources": ["nftables", "iptables-nft"],
|
||||
"chains": [
|
||||
{"family": "ip", "table": "filter", "name": "INPUT", "type": "filter",
|
||||
"hook": "input", "priority": 0, "policy": "accept",
|
||||
"rules": [
|
||||
{"matches": [{"field": "iifname", "op": "==", "values": ["ens6"]}],
|
||||
"verdict": "drop", "target": None,
|
||||
"text": "-A INPUT -i ens6 -j DROP"},
|
||||
]},
|
||||
],
|
||||
}
|
||||
|
||||
:raises HostFirewallUnavailable: if neither tool could be read -- no
|
||||
``nft``, no ``iptables-save``, or no root to run them.
|
||||
:raises ValueError: if the report came back cut short.
|
||||
"""
|
||||
command = f"sh -c {quote(HOST_FIREWALL_COMMAND)}"
|
||||
return parse_host_firewall(self._run_host_firewall_command(command, privileged=True))
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Restarting the device itself.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder. Only a
|
||||
driver that can actually restart its device defines ``reboot_host``, so
|
||||
``hasattr(driver, "reboot_host")`` tells a caller whether to offer it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
|
||||
class HostRebootMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def reboot_host(self) -> None:
|
||||
"""
|
||||
Restarts the device this driver is connected to.
|
||||
|
||||
Returns once the device has accepted the request; the session is
|
||||
usually gone right after. Waiting for the device to come back is
|
||||
the caller's business (see ``REBOOT_SETTLE_SECONDS``).
|
||||
|
||||
A driver that manages other machines restarts its *own* host, never
|
||||
one of them: a hypervisor restarts the hypervisor, not a VM.
|
||||
|
||||
:raises RuntimeError: If the device refuses, e.g. an ESXi host that
|
||||
is not in maintenance mode while VMs are running.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Shutting the device itself down cleanly.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder. Only a
|
||||
driver that can shut its device down through the device's own means defines
|
||||
``shutdown_host``, so ``hasattr(driver, "shutdown_host")`` tells a caller
|
||||
whether to offer it. There is no forced variant here, by design: cutting the
|
||||
power is the BMC's business, not a driver's.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
|
||||
class HostShutdownMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def shutdown_host(self) -> None:
|
||||
"""
|
||||
Shuts down the device this driver is connected to, cleanly.
|
||||
|
||||
Returns once the device has accepted the request; the session is
|
||||
usually gone right after. Whether the device really went off is
|
||||
the caller's business, e.g. through its BMC.
|
||||
|
||||
A driver that manages other machines shuts down its *own* host,
|
||||
never one of them: a hypervisor node shuts down itself, and its
|
||||
guests are stopped the way the node stops them on shutdown.
|
||||
|
||||
:raises RuntimeError: If the device refuses the request.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,419 @@
|
||||
"""Host status: does the host need a reboot, and does it patch itself?
|
||||
|
||||
A patch run that installed a new kernel or libc has not closed anything until
|
||||
the host restarts, so "reboot required" is part of being patched. Whether the
|
||||
host installs updates on its own (unattended-upgrades, dnf-automatic) decides
|
||||
how far netOrk's maintenance window reaches. Both are 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.
|
||||
|
||||
**Reboot required** is any of:
|
||||
|
||||
- ``/var/run/reboot-required`` exists. Ubuntu always writes it; Debian does when
|
||||
update-notifier or unattended-upgrades is installed.
|
||||
- ``needs-restarting -r`` exits 1 (dnf-utils).
|
||||
- A kernel newer than the running one is installed, of the same flavour. A
|
||||
Raspberry Pi carries ``rpi-v8`` and ``rpi-2712`` builds side by side, and only
|
||||
the running one's counts.
|
||||
- On FreeBSD, ``freebsd-version -k`` (the installed kernel) differs from
|
||||
``freebsd-version -r`` (the running one): a patch replaced the kernel.
|
||||
|
||||
It is ``None`` when none of these could be read, for example in a container
|
||||
without a ``/lib/modules`` of its own.
|
||||
|
||||
**Auto updates** is apt's ``APT::Periodic::Unattended-Upgrade`` (set, not "0",
|
||||
``apt-daily-upgrade.timer`` not disabled, and unattended-upgrades installed: a
|
||||
package removed but not purged leaves its "1" behind) or an enabled
|
||||
``dnf-automatic-install.timer``. ``dnf-automatic.timer`` installs only with
|
||||
``apply_updates = yes`` in ``automatic.conf`` (dnf5's in ``dnf5-plugins/``
|
||||
wins); by default it only downloads. It is ``None`` on a host with neither apt
|
||||
nor dnf-automatic. When they last ran
|
||||
successfully is ``/var/lib/apt/periodic/upgrade-stamp``, which
|
||||
``apt.systemd.daily`` touches only after unattended-upgrade succeeded.
|
||||
``update-success-stamp`` would say nothing: every ``apt-get update`` touches it,
|
||||
whoever runs it. How often they are meant to run is the same setting, in apt's
|
||||
units (a bare number is days).
|
||||
|
||||
**An interrupted package manager** is dpkg left halfway, the way apt checks it:
|
||||
numbered files left in ``/var/lib/dpkg/updates``, or a package in a state only
|
||||
a run cut off leaves behind (half-installed, unpacked, half-configured, waiting
|
||||
for triggers, or flagged for reinstallation). apt then refuses to install
|
||||
anything until ``dpkg --configure -a`` has run, while ``apt.systemd.daily``
|
||||
exits quietly every day (NetOrk/netork#738). While dpkg, apt, aptitude or
|
||||
unattended-upgrade is running, packages are halfway on purpose -- also between
|
||||
two of apt's dpkg calls -- so the answer is then ``None``, as on a host without
|
||||
dpkg. unattended-upgrade is told from Ubuntu's idle shutdown helper by its
|
||||
command line (:data:`BUSY_CHECK`). On a host without dpkg, dnf or yum, apk and opkg
|
||||
are read the same way (:mod:`napalm_device_types.package_managers`,
|
||||
NetOrk/netork#851), and ``package_manager`` names the one the answer is about.
|
||||
|
||||
**Filesystems** are how full ``/``, ``/boot`` and ``/var`` are, from POSIX
|
||||
``df -Pk``: where an upgrade unpacks a kernel, builds its initrd and keeps the
|
||||
package files. A kernel upgrade that ran out of room there left dpkg halfway on
|
||||
a Proxmox host whose root had been 94 % full for a week (NetOrk/netork#862). A
|
||||
directory that is not a mount of its own is reported as the filesystem it lives
|
||||
on, so each filesystem appears once. ``available`` is what df says an ordinary
|
||||
user can still write, which on ext4 is less than total minus used. How full is
|
||||
too full is not decided here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from functools import cmp_to_key
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import (
|
||||
FilesystemUsageDict,
|
||||
HostStatusDict,
|
||||
InterruptedPackageDict,
|
||||
)
|
||||
from napalm_device_types.package_managers import (
|
||||
PACKAGE_MANAGERS_COMMAND,
|
||||
PackageManagerReading,
|
||||
parse_package_managers,
|
||||
)
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "HSTAT_BEGIN"
|
||||
_END = "HSTAT_END"
|
||||
_REBOOT_FILE = "/var/run/reboot-required"
|
||||
_APT_TIMER = "apt-daily-upgrade.timer"
|
||||
_DNF_TIMER = "dnf-automatic.timer"
|
||||
_DNF_INSTALL_TIMER = "dnf-automatic-install.timer"
|
||||
_DNF_TIMERS = (_DNF_TIMER, _DNF_INSTALL_TIMER)
|
||||
#: dnf4's, then dnf5's: the last ``apply_updates`` printed is the one that holds.
|
||||
_DNF_AUTOMATIC_CONF = "/etc/dnf/automatic.conf /etc/dnf/dnf5-plugins/automatic.conf"
|
||||
_UPGRADE_STAMP = "/var/lib/apt/periodic/upgrade-stamp"
|
||||
_DPKG_JOURNAL = "/var/lib/dpkg/updates"
|
||||
#: Where an upgrade writes: the kernel's modules, its initrd, the package files.
|
||||
_FILESYSTEMS = "/ /boot /var"
|
||||
#: Prints ``[dpkg-busy]`` while a process that leaves packages halfway is working:
|
||||
#: dpkg, apt, apt-get or aptitude by name, unattended-upgrade by its command line.
|
||||
#: Its name is cut to 15 characters, ``unattended-upgr``, the same as that of
|
||||
#: ``unattended-upgrade-shutdown --wait-for-signal``, which Ubuntu keeps running all
|
||||
#: the time and which installs nothing.
|
||||
BUSY_CHECK = (
|
||||
"{ ps -e -o comm= 2>/dev/null | grep -qxE 'dpkg|apt|apt-get|aptitude' || "
|
||||
"ps -e -o args= 2>/dev/null | grep -qE '(^|[ /])unattended-upgrade( |$)'; } "
|
||||
"&& echo '[dpkg-busy]'; "
|
||||
)
|
||||
|
||||
#: One line, POSIX ``sh``, read-only, no privileges. The frame markers are
|
||||
#: printed in two halves so that an echoing transport does not show them early.
|
||||
#: Each timer is asked on its own: older systemd prints nothing for an unknown
|
||||
#: unit, which would shift a combined answer. Run through a pipe, so nothing in
|
||||
#: it sees a terminal and colours its output.
|
||||
HOST_STATUS_COMMAND = (
|
||||
"{ printf '%s%s\\n' HSTAT_ BEGIN; "
|
||||
f"[ -f {_REBOOT_FILE} ] && echo '[reboot-required]'; "
|
||||
"if command -v needs-restarting >/dev/null 2>&1; then echo '[needs-restarting]'; "
|
||||
"needs-restarting -r >/dev/null 2>&1; echo $?; fi; "
|
||||
"echo '[kernel]'; uname -r; echo '[modules]'; ls -1 /lib/modules 2>/dev/null; "
|
||||
"if command -v freebsd-version >/dev/null 2>&1; then "
|
||||
"echo '[freebsd-kernel]'; freebsd-version -k; "
|
||||
"echo '[freebsd-running]'; freebsd-version -r; fi; "
|
||||
"if command -v apt-config >/dev/null 2>&1; then echo '[apt-config]'; "
|
||||
"apt-config dump 2>/dev/null | grep '^APT::Periodic::Unattended-Upgrade '; "
|
||||
# Named through a variable: spelt out, the program name would match BUSY_CHECK
|
||||
# in this very command line.
|
||||
'uu=unattended-upgrade; { command -v "$uu" || [ -x "/usr/bin/$uu" ]; } >/dev/null 2>&1 '
|
||||
"&& echo '[unattended-upgrade]'; "
|
||||
f"echo '[upgrade-stamp]'; stat -c %Y {_UPGRADE_STAMP} 2>/dev/null; fi; "
|
||||
"if command -v dpkg-query >/dev/null 2>&1; then "
|
||||
f"{BUSY_CHECK}"
|
||||
f"echo '[dpkg-journal]'; ls -1 {_DPKG_JOURNAL} 2>/dev/null | head -n 20; "
|
||||
"echo '[dpkg-audit]'; dpkg-query -W -f='${db:Status-Abbrev} ${Package}\\n' 2>/dev/null "
|
||||
"| awk 'substr($0, 2, 1) ~ /[HUFWt]/ || substr($0, 3, 1) == \"R\"' | head -n 50; fi; "
|
||||
f"{PACKAGE_MANAGERS_COMMAND}"
|
||||
f"echo '[filesystems]'; df -Pk {_FILESYSTEMS}; "
|
||||
f"echo '[timers]'; for u in {_APT_TIMER} {' '.join(_DNF_TIMERS)}; do "
|
||||
'printf \'%s %s\\n\' "$u" "$(systemctl is-enabled "$u" 2>/dev/null)"; done; '
|
||||
"echo '[dnf-automatic]'; grep -h '^[[:space:]]*apply_updates[[:space:]]*=' "
|
||||
f"{_DNF_AUTOMATIC_CONF} 2>/dev/null; "
|
||||
"printf '%s%s\\n' HSTAT_ END; } 2>/dev/null | cat"
|
||||
)
|
||||
|
||||
_PERIODIC = re.compile(r'^APT::Periodic::Unattended-Upgrade\s+"([^"]*)"')
|
||||
_APPLY_UPDATES = re.compile(r"^apply_updates\s*=\s*(\S*)")
|
||||
#: What libdnf takes for a true boolean.
|
||||
_TRUE = frozenset({"1", "yes", "true", "on"})
|
||||
_OFF_STATES = frozenset({"disabled", "masked"})
|
||||
_INTERVAL = re.compile(r"(\d+)([smhd]?)")
|
||||
_UNIT_SECONDS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "": 86400}
|
||||
_JOURNAL_ENTRY = re.compile(r"\d+")
|
||||
#: One line of ``df -P``: device, 1024-blocks, used, available, capacity, mountpoint.
|
||||
#: The device and the mountpoint may hold blanks; the four numbers between them do not.
|
||||
_DF_LINE = re.compile(r"^.+?\s+(\d+)\s+(\d+)\s+(\d+)\s+(?:\d+%|-)\s+(/.*)$")
|
||||
#: dpkg's second status letter -> its word, for the states a cut-off run leaves.
|
||||
_HALFWAY = {
|
||||
"H": "half-installed",
|
||||
"U": "unpacked",
|
||||
"F": "half-configured",
|
||||
"W": "triggers-awaited",
|
||||
"t": "triggers-pending",
|
||||
}
|
||||
|
||||
|
||||
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 host status 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("]"):
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
elif line:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
#: A version's segments as rpm compares them: runs of digits, runs of letters, and
|
||||
#: ``~``; whatever else stands between them only separates.
|
||||
_VERSION_SEGMENT = re.compile(r"~|\d+|[A-Za-z]+")
|
||||
|
||||
|
||||
def _segment_cmp(x: str, y: str) -> int:
|
||||
"""One segment against another, as :func:`_version_cmp` takes them; 0 when equal."""
|
||||
if "~" in (x, y):
|
||||
return (y == "~") - (x == "~")
|
||||
if x.isdigit() and y.isdigit():
|
||||
return (int(x) > int(y)) - (int(x) < int(y))
|
||||
if x.isdigit() or y.isdigit():
|
||||
return 1 if x.isdigit() else -1
|
||||
return (x > y) - (x < y)
|
||||
|
||||
|
||||
def _version_cmp(a: str, b: str) -> int:
|
||||
"""rpm's ``rpmvercmp``: below 0 when ``a`` is older, above when newer.
|
||||
|
||||
Numbers compare as numbers (6.8.0-142 after 6.8.0-87), letters as text, and a
|
||||
number is newer than letters in its place: ``112.5.1.el9uek`` after
|
||||
``112.5.el9uek`` (#109). A version that has more segments where the other
|
||||
ends is the newer one, unless its next is ``~``, which comes before anything:
|
||||
``6.13~rc5`` before ``6.13``, as dpkg sorts it too.
|
||||
"""
|
||||
left, right = _VERSION_SEGMENT.findall(a), _VERSION_SEGMENT.findall(b)
|
||||
for x, y in zip(left, right, strict=False):
|
||||
if order := _segment_cmp(x, y):
|
||||
return order
|
||||
if len(left) == len(right):
|
||||
return 0
|
||||
longer, sign = (left, 1) if len(left) > len(right) else (right, -1)
|
||||
return -sign if longer[min(len(left), len(right))] == "~" else sign
|
||||
|
||||
|
||||
def kernel_reboot_pending(running: str, installed: list[str]) -> str | None:
|
||||
"""The newest installed kernel of the running flavour, if it is newer than the
|
||||
running one; otherwise None.
|
||||
|
||||
The flavour is what follows the last ``-`` (``generic``, ``amd64``, ``pve``,
|
||||
``v8``), or on an RPM kernel (``5.14.0-427.13.1.el9_4.x86_64``) the arch
|
||||
after the release; a kernel of another flavour is never a reason to reboot.
|
||||
"""
|
||||
version, flavour = _kernel_flavour(running)
|
||||
same = [k for k in installed if _kernel_flavour(k)[1] == flavour]
|
||||
if not same:
|
||||
return None
|
||||
order = cmp_to_key(_version_cmp)
|
||||
newest = max(same, key=lambda k: order(_kernel_flavour(k)[0]))
|
||||
if order(_kernel_flavour(newest)[0]) > order(version):
|
||||
return newest
|
||||
return None
|
||||
|
||||
|
||||
def _kernel_flavour(release: str) -> tuple[str, str]:
|
||||
"""``6.8.0-87-generic`` -> ``("6.8.0-87", "generic")``,
|
||||
``5.14.0-427.13.1.el9_4.x86_64`` -> ``("5.14.0-427.13.1.el9_4", "x86_64")``."""
|
||||
base, sep, tail = release.rpartition("-")
|
||||
if not sep:
|
||||
return release, ""
|
||||
if tail[:1].isdigit() and "." in tail:
|
||||
rel, _, arch = tail.rpartition(".")
|
||||
return f"{base}-{rel}", arch
|
||||
return base, tail
|
||||
|
||||
|
||||
def _freebsd_reboot(sections: dict[str, list[str]]) -> tuple[bool, str | None] | None:
|
||||
"""FreeBSD's answer from freebsd-version, or None on any other system."""
|
||||
installed = (sections.get("freebsd-kernel") or [""])[0]
|
||||
running = (sections.get("freebsd-running") or [""])[0]
|
||||
if not (installed and running):
|
||||
return None
|
||||
if installed != running:
|
||||
return True, f"kernel {installed} installed, {running} running"
|
||||
return False, None
|
||||
|
||||
|
||||
def _reboot(sections: dict[str, list[str]]) -> tuple[bool | None, str | None]:
|
||||
if "reboot-required" in sections:
|
||||
return True, f"{_REBOOT_FILE} is present"
|
||||
needs = sections.get("needs-restarting")
|
||||
if needs and needs[0] == "1":
|
||||
return True, "needs-restarting -r reports a reboot"
|
||||
freebsd = _freebsd_reboot(sections)
|
||||
if freebsd is not None:
|
||||
return freebsd
|
||||
running = (sections.get("kernel") or [""])[0]
|
||||
modules = sections.get("modules") or []
|
||||
newer = kernel_reboot_pending(running, modules) if running and modules else None
|
||||
if newer:
|
||||
return True, f"kernel {newer} installed, {running} running"
|
||||
if needs or modules:
|
||||
return False, None
|
||||
return None, None
|
||||
|
||||
|
||||
def _timer_states(sections: dict[str, list[str]]) -> dict[str, str]:
|
||||
states: dict[str, str] = {}
|
||||
for line in sections.get("timers") or []:
|
||||
unit, _, state = line.partition(" ")
|
||||
states[unit] = state.strip()
|
||||
return states
|
||||
|
||||
|
||||
def _periodic(sections: dict[str, list[str]]) -> str | None:
|
||||
"""The value of ``APT::Periodic::Unattended-Upgrade``, or None when it is not set."""
|
||||
lines = sections.get("apt-config") or []
|
||||
match = next(filter(None, (_PERIODIC.match(line) for line in lines)), None)
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def _dnf_applies(sections: dict[str, list[str]]) -> bool:
|
||||
"""Whether dnf-automatic.timer installs what it downloads; dnf's default is no."""
|
||||
lines = sections.get("dnf-automatic") or []
|
||||
values = [m.group(1) for m in map(_APPLY_UPDATES.match, lines) if m]
|
||||
return bool(values) and values[-1].lower() in _TRUE
|
||||
|
||||
|
||||
def _auto_updates(sections: dict[str, list[str]]) -> bool | None:
|
||||
timers = _timer_states(sections)
|
||||
if timers.get(_DNF_INSTALL_TIMER) == "enabled":
|
||||
return True
|
||||
downloads_only = timers.get(_DNF_TIMER) == "enabled"
|
||||
if downloads_only and _dnf_applies(sections):
|
||||
return True
|
||||
if "apt-config" not in sections:
|
||||
return False if downloads_only else None
|
||||
switched_on = _periodic(sections) not in (None, "", "0")
|
||||
installed = "unattended-upgrade" in sections
|
||||
return switched_on and installed and timers.get(_APT_TIMER) not in _OFF_STATES
|
||||
|
||||
|
||||
def _interval(sections: dict[str, list[str]]) -> int | None:
|
||||
"""apt's interval in seconds, the way ``apt.systemd.daily`` reads it; 0 for "always"."""
|
||||
value = _periodic(sections)
|
||||
if value == "always":
|
||||
return 0
|
||||
match = _INTERVAL.fullmatch(value or "")
|
||||
if not match or int(match.group(1)) == 0:
|
||||
return None
|
||||
return int(match.group(1)) * _UNIT_SECONDS[match.group(2)]
|
||||
|
||||
|
||||
def _last_success(sections: dict[str, list[str]]) -> int | None:
|
||||
stamp = (sections.get("upgrade-stamp") or [""])[0]
|
||||
return int(stamp) if stamp.isdigit() else None
|
||||
|
||||
|
||||
def _halfway(line: str) -> InterruptedPackageDict | None:
|
||||
status, _, name = line.partition(" ")
|
||||
name = name.strip()
|
||||
state = "reinstall-required" if status[2:3] == "R" else _HALFWAY.get(status[1:2])
|
||||
return {"name": name, "state": state} if name and state else None
|
||||
|
||||
|
||||
def _dpkg(sections: dict[str, list[str]]) -> PackageManagerReading | None:
|
||||
if "dpkg-audit" not in sections:
|
||||
return None
|
||||
if "dpkg-busy" in sections:
|
||||
return PackageManagerReading("dpkg", None, [])
|
||||
packages = [p for p in map(_halfway, sections["dpkg-audit"]) if p is not None]
|
||||
journal = any(_JOURNAL_ENTRY.fullmatch(f) for f in sections.get("dpkg-journal") or [])
|
||||
return PackageManagerReading("dpkg", bool(packages) or journal, packages)
|
||||
|
||||
|
||||
def _package_manager(sections: dict[str, list[str]]) -> PackageManagerReading:
|
||||
"""The reading that says most: one left halfway, then one that is not, then a busy one."""
|
||||
readings = [r for r in (_dpkg(sections), *parse_package_managers(sections)) if r is not None]
|
||||
for interrupted in (True, False):
|
||||
found = next((r for r in readings if r.interrupted is interrupted), None)
|
||||
if found is not None:
|
||||
return found
|
||||
return readings[0] if readings else PackageManagerReading(None, None, [])
|
||||
|
||||
|
||||
def _filesystems(sections: dict[str, list[str]]) -> list[FilesystemUsageDict] | None:
|
||||
"""Each filesystem df named, once and in its order; None when it named none."""
|
||||
found: dict[str, FilesystemUsageDict] = {}
|
||||
for line in sections.get("filesystems") or []:
|
||||
match = _DF_LINE.match(line)
|
||||
if not match or int(match.group(1)) == 0:
|
||||
continue
|
||||
total, used, available = (int(match.group(i)) * 1024 for i in (1, 2, 3))
|
||||
mountpoint = match.group(4)
|
||||
found.setdefault(
|
||||
mountpoint,
|
||||
{"mountpoint": mountpoint, "total": total, "used": used, "available": available},
|
||||
)
|
||||
return list(found.values()) or None
|
||||
|
||||
|
||||
def parse_host_status(output: str) -> HostStatusDict:
|
||||
"""Parse what :data:`HOST_STATUS_COMMAND` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
required, reason = _reboot(sections)
|
||||
manager = _package_manager(sections)
|
||||
return {
|
||||
"reboot_required": required,
|
||||
"reboot_reason": reason,
|
||||
"auto_updates": _auto_updates(sections),
|
||||
"auto_updates_last_success": _last_success(sections),
|
||||
"auto_updates_interval": _interval(sections),
|
||||
"package_manager": manager.manager,
|
||||
"package_manager_interrupted": manager.interrupted,
|
||||
"interrupted_packages": manager.packages,
|
||||
"filesystems": _filesystems(sections),
|
||||
}
|
||||
|
||||
|
||||
class HostStatusMixin:
|
||||
"""Adds :meth:`get_host_status` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form, like :class:`~napalm_device_types.kernel.KernelFactsMixin`:
|
||||
the reading and its parse are the same everywhere, and a driver supplies only
|
||||
:meth:`_run_host_status_command`. Mixed in by the drivers that can, so
|
||||
``hasattr(driver, "get_host_status")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_host_status_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
def get_host_status(self) -> HostStatusDict:
|
||||
"""
|
||||
Returns whether the host needs a reboot, whether it patches itself, and
|
||||
whether its package manager was left halfway.
|
||||
|
||||
* reboot_required (bool or None)
|
||||
* reboot_reason (string or None)
|
||||
* auto_updates (bool or None)
|
||||
* auto_updates_last_success (Unix time or None)
|
||||
* auto_updates_interval (seconds or None)
|
||||
* package_manager (dpkg, dnf, yum, apk, opkg, or None)
|
||||
* package_manager_interrupted (bool or None)
|
||||
* interrupted_packages (list of {name, state})
|
||||
* filesystems (list of {mountpoint, total, used, available} in bytes, or None)
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
return parse_host_status(self._run_host_status_command(HOST_STATUS_COMMAND))
|
||||
+709
-602
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
"""Dropping interfaces that are noise rather than signal.
|
||||
|
||||
An access point exposes radio PHYs and a loopback alongside its real
|
||||
interfaces. Reporting them inflates every interface count and every error rate,
|
||||
so drivers filter them out -- identically, whatever the vendor. The two class
|
||||
attributes are the customisation point.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, ClassVar
|
||||
|
||||
|
||||
class InterfaceFilterMixin:
|
||||
"""Adds :meth:`_filter_interfaces` for drivers that report raw interface dicts."""
|
||||
|
||||
#: Interface names dropped outright.
|
||||
_EXCLUDED_INTERFACES: ClassVar[frozenset[str]] = frozenset({"lo"})
|
||||
|
||||
#: Name prefixes dropped -- ``phy*`` are radio devices, not links.
|
||||
_EXCLUDED_INTERFACE_PREFIXES: ClassVar[tuple[str, ...]] = ("phy",)
|
||||
|
||||
def _filter_interfaces(self, interfaces: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Remove loopback and radio-device (phy*) interfaces from an interface dict."""
|
||||
return {
|
||||
name: data
|
||||
for name, data in interfaces.items()
|
||||
if name not in self._EXCLUDED_INTERFACES
|
||||
and not name.startswith(self._EXCLUDED_INTERFACE_PREFIXES)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
"""What the running kernel has built and loaded.
|
||||
|
||||
A kernel CVE's exploitability often hangs on code that is simply not there --
|
||||
a module that is neither loaded nor shipped, a subsystem the kernel was built
|
||||
without. Reading that is identical on every Linux host, so the command and its
|
||||
parse live here once and a driver only carries the command across: SSH,
|
||||
an API's exec endpoint, whatever it has.
|
||||
|
||||
The command is read-only and needs no privileges. It frames its report and
|
||||
sends it gzipped and base64-encoded, for two reasons: nothing in the payload can
|
||||
then look like a shell prompt to a screen-scraping transport, and a kernel's
|
||||
build configuration (~300 kB on a distribution kernel) crosses as a fifth of
|
||||
that.
|
||||
|
||||
What the four lists mean for a module, and why "not loaded" alone is never
|
||||
"absent": a module that is not loaded can still be loaded on demand -- by an
|
||||
attacker too, where autoloading reaches it. Only a module that is neither
|
||||
loaded, nor compiled in, nor shipped for this kernel is one it cannot have.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import gzip
|
||||
import zlib
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import KernelFactsDict
|
||||
|
||||
_BEGIN = "KFACTS_BEGIN"
|
||||
_END = "KFACTS_END"
|
||||
|
||||
#: 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.
|
||||
KERNEL_FACTS_COMMAND = (
|
||||
"r=$(uname -r); m=/lib/modules/$r; "
|
||||
"printf '%s%s\\n' KFACTS_ BEGIN; "
|
||||
"{ echo '[release]'; echo \"$r\"; "
|
||||
"if [ -r /proc/modules ]; then echo '[loaded]'; cut -d' ' -f1 /proc/modules; fi; "
|
||||
"if [ -r $m/modules.builtin ]; then echo '[builtin]'; cat $m/modules.builtin; fi; "
|
||||
"if [ -r $m/modules.dep ]; then echo '[available]'; cut -d: -f1 $m/modules.dep; fi; "
|
||||
"if [ -r /boot/config-$r ]; then echo '[config]'; grep '^CONFIG_' /boot/config-$r; "
|
||||
"elif [ -r /proc/config.gz ]; then echo '[config]'; "
|
||||
"zcat /proc/config.gz | grep '^CONFIG_'; fi; "
|
||||
"} 2>/dev/null | gzip -c | base64; "
|
||||
"printf '%s%s\\n' KFACTS_ END"
|
||||
)
|
||||
|
||||
|
||||
def module_name(raw: str) -> str:
|
||||
"""A module as the kernel names it: no path, no ``.ko`` suffix, ``_`` for ``-``.
|
||||
|
||||
``kernel/net/can/can-raw.ko.zst`` and ``can_raw`` are the same module; the
|
||||
kernel itself treats dash and underscore alike.
|
||||
"""
|
||||
base = raw.strip().rsplit("/", 1)[-1]
|
||||
suffix = base.find(".ko")
|
||||
if suffix != -1:
|
||||
base = base[:suffix]
|
||||
return base.replace("-", "_").lower()
|
||||
|
||||
|
||||
def _report(output: str) -> str:
|
||||
lines = [line.strip() for line in output.splitlines()]
|
||||
try:
|
||||
start = lines.index(_BEGIN)
|
||||
end = lines.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no kernel facts in the output") from None
|
||||
try:
|
||||
packed = base64.b64decode("".join(lines[start + 1 : end]), validate=True)
|
||||
report = gzip.decompress(packed).decode()
|
||||
except (binascii.Error, OSError, EOFError, zlib.error, UnicodeDecodeError) as exc:
|
||||
raise ValueError(f"the kernel facts could not be decoded: {exc}") from exc
|
||||
if "[release]" not in report.splitlines():
|
||||
raise ValueError("the kernel facts are empty: gzip or base64 is missing on the host")
|
||||
return report
|
||||
|
||||
|
||||
def _sections(report: str) -> dict[str, list[str]]:
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] | None = None
|
||||
for line in report.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
elif line and current is not None:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _config(lines: list[str]) -> dict[str, str]:
|
||||
config: dict[str, str] = {}
|
||||
for line in lines:
|
||||
option, sep, value = line.partition("=")
|
||||
if not sep:
|
||||
continue
|
||||
if len(value) >= 2 and value[0] == value[-1] == '"':
|
||||
value = value[1:-1]
|
||||
config[option] = value
|
||||
return config
|
||||
|
||||
|
||||
def parse_kernel_facts(output: str) -> KernelFactsDict:
|
||||
"""Parse what :data:`KERNEL_FACTS_COMMAND` printed.
|
||||
|
||||
A section the command did not print -- the file was missing or unreadable --
|
||||
comes back ``None``, never empty.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(_report(output))
|
||||
|
||||
def names(key: str) -> list[str] | None:
|
||||
if key not in sections:
|
||||
return None
|
||||
return sorted({module_name(line) for line in sections[key]})
|
||||
|
||||
release = sections.get("release") or [""]
|
||||
return {
|
||||
"release": release[0],
|
||||
"loaded": names("loaded"),
|
||||
"builtin": names("builtin"),
|
||||
"available": names("available"),
|
||||
"config": _config(sections["config"]) if "config" in sections else None,
|
||||
}
|
||||
|
||||
|
||||
class KernelFactsMixin:
|
||||
"""Adds :meth:`get_kernel_facts` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the reading and its parse are
|
||||
the same everywhere, so they are concrete here, and a driver supplies only
|
||||
:meth:`_run_kernel_facts_command` -- how a command reaches its host. Mixed in
|
||||
by the drivers that can, not by :class:`~napalm_device_types.os.OSDriver`:
|
||||
a Windows host is an OS driver too and has no Linux kernel to read, and
|
||||
``hasattr(driver, "get_kernel_facts")`` has to stay a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_kernel_facts_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
def get_kernel_facts(self) -> KernelFactsDict:
|
||||
"""
|
||||
Returns what the running kernel has built and loaded.
|
||||
|
||||
* release (string) - ``uname -r``
|
||||
* loaded (list or None) - loaded modules, from ``/proc/modules``
|
||||
* builtin (list or None) - modules compiled into the kernel image
|
||||
* available (list or None) - modules shipped for this kernel
|
||||
* config (dict or None) - the build configuration's set options
|
||||
|
||||
``None`` means the source could not be read.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"release": "6.1.0-25-amd64",
|
||||
"loaded": ["nf_tables", "tipc"],
|
||||
"builtin": ["tcp_cubic"],
|
||||
"available": ["can_raw", "nf_tables", "tipc"],
|
||||
"config": {"CONFIG_TIPC": "m", "CONFIG_HZ": "250"},
|
||||
}
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
return parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND))
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Logical LAG entries for ``get_interfaces()``, built from their member ports.
|
||||
|
||||
Some switches list only physical ports, each tagged with the trunk it belongs
|
||||
to, and never the trunk itself. Turning those tags into one row per trunk is
|
||||
the same for every vendor, so it lives here once; a driver only has to set
|
||||
``trunk_group`` on member ports and, where the device says so, pass the mode.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _port_order(name: str) -> list[Any]:
|
||||
return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", name)]
|
||||
|
||||
|
||||
def add_lag_interfaces(
|
||||
interfaces: dict[str, dict[str, Any]],
|
||||
lag_modes: dict[str, str] | None = None,
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
"""Return *interfaces* plus one logical entry per ``trunk_group``.
|
||||
|
||||
The LAG entry is up/enabled if any member is, its speed is the members'
|
||||
sum, and ``lag_members`` lists them in port order. A LAG the driver
|
||||
already reported is left as it is. *interfaces* itself is not modified.
|
||||
|
||||
:param lag_modes: ``{lag_name: "lacp" | "trunk"}``. A LAG without a known
|
||||
mode gets no ``lag_mode`` key rather than a guessed one.
|
||||
"""
|
||||
result = dict(interfaces)
|
||||
groups: dict[str, list[str]] = {}
|
||||
for name, iface in interfaces.items():
|
||||
group = iface.get("trunk_group")
|
||||
if group:
|
||||
groups.setdefault(group, []).append(name)
|
||||
|
||||
for group, members in groups.items():
|
||||
if group in result:
|
||||
continue
|
||||
members = sorted(members, key=_port_order)
|
||||
lag: dict[str, Any] = {
|
||||
"is_up": any(interfaces[m].get("is_up") for m in members),
|
||||
"is_enabled": any(interfaces[m].get("is_enabled") for m in members),
|
||||
"description": f"LAG ({', '.join(members)})",
|
||||
"last_flapped": -1.0,
|
||||
"speed": sum(max(float(interfaces[m].get("speed") or 0), 0.0) for m in members),
|
||||
"mtu": -1,
|
||||
"mac_address": "",
|
||||
"lag_members": members,
|
||||
}
|
||||
if lag_modes and group in lag_modes:
|
||||
lag["lag_mode"] = lag_modes[group]
|
||||
result[group] = lag
|
||||
return result
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Licenses and subscriptions a device reports.
|
||||
|
||||
A fact for the caller (docs/STRUCTURE.md): whether a free edition, a missing
|
||||
subscription or a license a feature needs is a problem is decided above the
|
||||
driver. Declared only; a driver that can read licenses implements it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import LicenseDict
|
||||
|
||||
|
||||
class LicenseMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_licenses(self) -> list[LicenseDict]:
|
||||
"""Every license or subscription the device knows of, with its status.
|
||||
|
||||
Example::
|
||||
|
||||
[{"name": "pve-subscription", "status": "none"},
|
||||
{"name": "vSphere", "status": "active", "edition": "Free"},
|
||||
{"name": "DCMS", "status": "missing",
|
||||
"withholds": ["drives", "firmware inventory"]}]
|
||||
|
||||
``withholds`` names what a device keeps back for want of a license while
|
||||
the rest of it answers; a missing license without it may keep back all.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Listening sockets: what listens on which address, and which service it is.
|
||||
|
||||
Whether a service is reachable from outside its host is decided by what it
|
||||
listens on -- ``0.0.0.0:5432`` is, ``127.0.0.1:5432`` is not -- and that 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.
|
||||
|
||||
**One round trip.** ``ss -lntup`` lists every listening TCP and bound UDP
|
||||
socket with the processes holding it; for each of those processes,
|
||||
``/proc/<pid>/cgroup`` says which systemd service or container it runs in. The
|
||||
report is framed, and a report whose end is missing raises: a list cut short
|
||||
must never read as sockets that closed.
|
||||
|
||||
**Root, and without it.** Only root sees every process behind a socket.
|
||||
The whole script therefore goes to the host as one ``sh -c`` argument -- a
|
||||
driver that prefixes ``sudo -n`` would otherwise run only its first command as
|
||||
root. When that call brings no report back (no sudo, a wrong password), the
|
||||
command runs again without privilege: the sockets are still worth having, and
|
||||
the reading says it is not ``attributed``.
|
||||
|
||||
**No ``-H``.** iproute2 before 4.10 has no option to leave out the header and
|
||||
fails on it, which would read as nothing listening. The parse skips the header
|
||||
instead.
|
||||
|
||||
**Without ``ss``, ``netstat``.** OpenWrt's busybox and old net-tools hosts have
|
||||
no ``ss``; ``netstat -lntup`` lists the same sockets with ``PID/Program``, and
|
||||
the cgroups are read for its PIDs alike. On OpenWrt the cgroup names the procd
|
||||
service (``/services/<name>/<instance>``), a jailed one too, whose PID is not the
|
||||
one procd reports. A host with neither raises :class:`ListeningSocketsUnavailable`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "SOCK_BEGIN"
|
||||
_END = "SOCK_END"
|
||||
_NO_SS = "no-ss"
|
||||
_RC_RE = re.compile(r"^__SS_RC=(\d+)$")
|
||||
|
||||
#: 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.
|
||||
#: ``ss`` is in ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
|
||||
#: ``netstat`` names a socket's process as ``PID/Program``, ``ss`` as ``pid=PID``.
|
||||
LISTENING_SOCKETS_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' SOCK_ BEGIN; "
|
||||
"if command -v ss >/dev/null 2>&1; then "
|
||||
"t=ss; s=$(ss -lntup 2>&1); r=$?; "
|
||||
"pids=$(printf '%s\\n' \"$s\" | grep -o 'pid=[0-9]*' | cut -d= -f2); "
|
||||
"elif command -v netstat >/dev/null 2>&1; then "
|
||||
"t=netstat; s=$(netstat -lntup 2>&1); r=$?; "
|
||||
"pids=$(printf '%s\\n' \"$s\" | grep -o ' [0-9][0-9]*/' | tr -d ' /'); "
|
||||
"else t=; fi; "
|
||||
'if [ -n "$t" ]; then '
|
||||
'echo "[$t]"; printf \'%s\\n\' "$s"; echo "__SS_RC=$r"; '
|
||||
"echo '[cgroups]'; "
|
||||
"for p in $(printf '%s\\n' \"$pids\" | sort -u); do "
|
||||
'sed "s|^|$p |" /proc/$p/cgroup 2>/dev/null; done; '
|
||||
"else echo '[no-ss]'; fi; "
|
||||
"printf '%s%s\\n' SOCK_ END"
|
||||
)
|
||||
|
||||
_PROTOCOLS = frozenset({"tcp", "udp"})
|
||||
#: netstat names the IPv6 sockets of net-tools ``tcp6``/``udp6``; busybox does not.
|
||||
_NETSTAT_PROTOCOLS = {"tcp": "tcp", "tcp6": "tcp", "udp": "udp", "udp6": "udp"}
|
||||
#: ``1604/dropbear``; net-tools prints ``700/sshd: /usr/sbin``.
|
||||
_PROGRAM_RE = re.compile(r"^(\d+)/(\S*)")
|
||||
#: ``users:(("nginx",pid=901,fd=6),("nginx",pid=900,fd=6))``
|
||||
_USER_RE = re.compile(r'\("((?:[^"\\]|\\.)*)",pid=(\d+),fd=\d+\)')
|
||||
#: The service a cgroup path runs in: its deepest ``*.service`` component.
|
||||
_SERVICE_RE = re.compile(r"/([^/]+)\.service(?=/|$)")
|
||||
#: OpenWrt's procd: ``/services/<name>/<instance>``.
|
||||
_PROCD_RE = re.compile(r"^/services/([^/]+)(?:/|$)")
|
||||
#: A container's cgroup: ``docker-<id>.scope`` (systemd driver), ``/docker/<id>`` (cgroupfs).
|
||||
_CONTAINER_RE = re.compile(
|
||||
r"(?:docker|libpod)-([0-9a-f]{64})\.scope|/(?:docker|libpod)/([0-9a-f]{64})(?=/|$)"
|
||||
)
|
||||
|
||||
|
||||
class ListeningSocketsUnavailable(NotImplementedError):
|
||||
"""The host has neither ``ss`` nor ``netstat``; nothing to read, nothing to retry."""
|
||||
|
||||
|
||||
def _frame(output: 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 listening socket report in the output") from None
|
||||
return lines[start + 1 : end]
|
||||
|
||||
|
||||
def _sections(lines: list[str]) -> dict[str, list[str]]:
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] = []
|
||||
for line in lines:
|
||||
if line.startswith("[") and line.endswith("]") and " " not in line:
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
else:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _split_local(local: str) -> tuple[str, str | None, int] | None:
|
||||
"""``[fe80::1]%eth0:546`` (or ``[fe80::1%eth0]:546``) -> ``("fe80::1", "eth0", 546)``;
|
||||
None if no port."""
|
||||
host, sep, port = local.rpartition(":")
|
||||
if not sep or not port.isdigit():
|
||||
return None
|
||||
address, _, zone = host.partition("%")
|
||||
zone = zone.rstrip("]")
|
||||
if address.startswith("["):
|
||||
address = address[1:].rstrip("]")
|
||||
return address or "*", zone or None, int(port)
|
||||
|
||||
|
||||
def _cgroup_paths(lines: list[str]) -> dict[int, str]:
|
||||
"""Each process's cgroup path: the unified hierarchy, or systemd's under v1."""
|
||||
paths: dict[int, str] = {}
|
||||
for line in lines:
|
||||
pid, _, entry = line.partition(" ")
|
||||
parts = entry.split(":", 2)
|
||||
if not pid.isdigit() or len(parts) != 3:
|
||||
continue
|
||||
hierarchy, controllers, path = parts
|
||||
if (hierarchy == "0" and controllers == "") or controllers == "name=systemd":
|
||||
paths[int(pid)] = path
|
||||
return paths
|
||||
|
||||
|
||||
def _unit(path: str | None) -> str | None:
|
||||
services = _SERVICE_RE.findall(path or "")
|
||||
if services:
|
||||
return str(services[-1])
|
||||
procd = _PROCD_RE.match(path or "")
|
||||
return str(procd.group(1)) if procd else None
|
||||
|
||||
|
||||
def _container(path: str | None) -> str | None:
|
||||
match = _CONTAINER_RE.search(path or "")
|
||||
return (match.group(1) or match.group(2)) if match else None
|
||||
|
||||
|
||||
def _entry(
|
||||
proto: str,
|
||||
local: tuple[str, str | None, int],
|
||||
process: str | None,
|
||||
pid: int | None,
|
||||
paths: dict[int, str],
|
||||
) -> ListeningSocketDict:
|
||||
address, interface, port = local
|
||||
path = paths.get(pid) if pid is not None else None
|
||||
return {
|
||||
"proto": proto,
|
||||
"address": address,
|
||||
"port": port,
|
||||
"interface": interface,
|
||||
"process": process,
|
||||
"pid": pid,
|
||||
"unit": _unit(path),
|
||||
"container_id": _container(path),
|
||||
}
|
||||
|
||||
|
||||
def _ss_socket(line: str, paths: dict[int, str]) -> ListeningSocketDict | None:
|
||||
parts = line.split()
|
||||
if len(parts) < 5 or parts[0] not in _PROTOCOLS:
|
||||
return None
|
||||
local = _split_local(parts[4])
|
||||
if local is None:
|
||||
return None
|
||||
users = _USER_RE.findall(line)
|
||||
process, pid = (users[0][0], int(users[0][1])) if users else (None, None)
|
||||
return _entry(parts[0], local, process, pid, paths)
|
||||
|
||||
|
||||
def _netstat_socket(line: str, paths: dict[int, str]) -> ListeningSocketDict | None:
|
||||
"""``Proto Recv-Q Send-Q Local Foreign [State] PID/Program`` -- a UDP line
|
||||
has no state, and ``-`` is a socket without a process."""
|
||||
parts = line.split()
|
||||
proto = _NETSTAT_PROTOCOLS.get(parts[0]) if parts else None
|
||||
if proto is None or len(parts) < 6:
|
||||
return None
|
||||
local = _split_local(parts[3])
|
||||
if local is None:
|
||||
return None
|
||||
process, pid = None, None
|
||||
for token in parts[5:7]:
|
||||
program = _PROGRAM_RE.match(token)
|
||||
if program:
|
||||
pid, process = int(program.group(1)), program.group(2).rstrip(":") or None
|
||||
break
|
||||
return _entry(proto, local, process, pid, paths)
|
||||
|
||||
|
||||
_PARSERS = {"ss": _ss_socket, "netstat": _netstat_socket}
|
||||
|
||||
|
||||
def parse_listening_sockets(output: str) -> list[ListeningSocketDict]:
|
||||
"""Parse what :data:`LISTENING_SOCKETS_COMMAND` printed, sorted by protocol,
|
||||
port and address.
|
||||
|
||||
:raises ListeningSocketsUnavailable: when the host has neither ``ss`` nor ``netstat``.
|
||||
:raises ValueError: when the output carries no intact report, or the tool failed.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
if _NO_SS in sections:
|
||||
raise ListeningSocketsUnavailable("the host has neither ss nor netstat")
|
||||
tool = "netstat" if "netstat" in sections else "ss"
|
||||
lines = sections.get(tool, [])
|
||||
statuses = [m.group(1) for m in map(_RC_RE.match, lines) if m]
|
||||
if not statuses or statuses[-1] != "0":
|
||||
detail = " ".join(line for line in lines if not _RC_RE.match(line))[:200]
|
||||
raise ValueError(f"{tool} did not list the sockets: {detail or 'no exit status'}")
|
||||
paths = _cgroup_paths(sections.get("cgroups", []))
|
||||
parse = _PARSERS[tool]
|
||||
sockets = [s for s in (parse(line, paths) for line in lines) if s is not None]
|
||||
return sorted(
|
||||
sockets, key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or "")
|
||||
)
|
||||
|
||||
|
||||
class ListeningSocketsMixin:
|
||||
"""Adds :meth:`get_listening_sockets` to a driver that can run a command on a Linux host.
|
||||
|
||||
With ``ss``, or ``netstat`` where there is none (OpenWrt's busybox).
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse
|
||||
are the same everywhere, so they are concrete here, and a driver supplies
|
||||
only :meth:`_run_listening_sockets_command` -- how a command reaches its
|
||||
host, and how it gains root there. Mixed in by the drivers that can, not by
|
||||
:class:`~napalm_device_types.os.OSDriver`: a Windows host is an OS driver
|
||||
too, and ``hasattr(driver, "get_listening_sockets")`` has to stay truthful.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root
|
||||
when *privileged*. The command is a single ``sh -c`` invocation."""
|
||||
...
|
||||
|
||||
def get_listening_sockets(self) -> ListeningSocketsDict:
|
||||
"""
|
||||
Returns every listening TCP and bound UDP socket, with the process,
|
||||
systemd service and container behind it.
|
||||
|
||||
* attributed (bool) - read as root, so every process is named
|
||||
* sockets (list) - see :class:`~napalm_device_types.models.ListeningSocketDict`
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"attributed": True,
|
||||
"sockets": [
|
||||
{"proto": "tcp", "address": "0.0.0.0", "port": 5432,
|
||||
"interface": None, "process": "postgres", "pid": 812,
|
||||
"unit": "postgresql@16-main", "container_id": None},
|
||||
],
|
||||
}
|
||||
|
||||
:raises ListeningSocketsUnavailable: if the host has neither ``ss`` nor ``netstat``.
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(LISTENING_SOCKETS_COMMAND)}"
|
||||
try:
|
||||
output = self._run_listening_sockets_command(command, privileged=True)
|
||||
return {"attributed": True, "sockets": parse_listening_sockets(output)}
|
||||
except ValueError:
|
||||
pass
|
||||
output = self._run_listening_sockets_command(command, privileged=False)
|
||||
return {"attributed": False, "sockets": parse_listening_sockets(output)}
|
||||
@@ -0,0 +1,97 @@
|
||||
"""LLDP neighbours as rows, and the two shapes NAPALM asks for.
|
||||
|
||||
A driver reads its neighbours one row per neighbour -- from ``lldpctl``
|
||||
(:func:`~napalm_device_types.lldpctl.parse_lldpctl_keyvalue`), an API or a CLI
|
||||
-- and ``get_lldp_neighbors`` and ``get_lldp_neighbors_detail`` are the same
|
||||
projection of those rows for every driver. A port with several neighbours (a
|
||||
phone and the PC behind it, an unmanaged switch) is several rows, and stays
|
||||
several entries in both shapes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
from napalm.base.models import LLDPNeighborDetailDict
|
||||
|
||||
#: A chassis id of type ``mac`` that really is a MAC address.
|
||||
_MAC_RE = re.compile(r"^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$")
|
||||
|
||||
|
||||
class LldpNeighborRow(TypedDict):
|
||||
"""One LLDP neighbour, as the local port heard it.
|
||||
|
||||
``chassis_id_type`` and ``port_id_type`` name what the id is: ``mac``,
|
||||
``ip``, ``ifname``, ``ifalias``, ``local`` or ``unhandled`` (an id type
|
||||
lldpd does not decode), ``""`` when the neighbour sent no id.
|
||||
``capabilities`` and ``enabled_capabilities`` use NAPALM's names
|
||||
(``bridge``, ``router``, ``wlan-access-point``, ``telephone``, ...).
|
||||
"""
|
||||
|
||||
local_port: str
|
||||
chassis_id: str
|
||||
chassis_id_type: str
|
||||
port_id: str
|
||||
port_id_type: str
|
||||
port_description: str
|
||||
system_name: str
|
||||
system_description: str
|
||||
management_addresses: list[str]
|
||||
capabilities: list[str]
|
||||
enabled_capabilities: list[str]
|
||||
|
||||
|
||||
class LldpNeighborDict(TypedDict):
|
||||
"""NAPALM's ``get_lldp_neighbors`` entry (``hostname``, ``port``), plus the chassis MAC.
|
||||
|
||||
``mac`` (lower case) is there only when the neighbour names its chassis by a
|
||||
MAC address; an application can match the neighbour by it, where a name
|
||||
may be ambiguous.
|
||||
"""
|
||||
|
||||
hostname: str
|
||||
port: str
|
||||
mac: NotRequired[str]
|
||||
|
||||
|
||||
def lldp_neighbors(rows: Iterable[LldpNeighborRow]) -> dict[str, list[LldpNeighborDict]]:
|
||||
"""``get_lldp_neighbors``: per local port, every neighbour's name, port and chassis MAC."""
|
||||
neighbors: dict[str, list[LldpNeighborDict]] = {}
|
||||
for row in rows:
|
||||
entry: LldpNeighborDict = {"hostname": row["system_name"], "port": row["port_id"]}
|
||||
if row["chassis_id_type"] == "mac" and _MAC_RE.match(row["chassis_id"]):
|
||||
entry["mac"] = row["chassis_id"].lower()
|
||||
neighbors.setdefault(row["local_port"], []).append(entry)
|
||||
return neighbors
|
||||
|
||||
|
||||
def lldp_neighbors_detail(
|
||||
rows: Iterable[LldpNeighborRow], interface: str = ""
|
||||
) -> dict[str, list[LLDPNeighborDetailDict]]:
|
||||
"""``get_lldp_neighbors_detail``: per local port, every neighbour in full.
|
||||
|
||||
With ``interface``, that port only. ``parent_interface`` stays empty: a row
|
||||
does not know which aggregate its port belongs to.
|
||||
"""
|
||||
details: dict[str, list[LLDPNeighborDetailDict]] = {}
|
||||
for row in rows:
|
||||
if interface and row["local_port"] != interface:
|
||||
continue
|
||||
details.setdefault(row["local_port"], []).append(
|
||||
{
|
||||
"parent_interface": "",
|
||||
"remote_port": row["port_id"],
|
||||
"remote_port_description": row["port_description"],
|
||||
"remote_chassis_id": row["chassis_id"],
|
||||
"remote_system_name": row["system_name"],
|
||||
"remote_system_description": row["system_description"],
|
||||
"remote_system_capab": list(row["capabilities"]),
|
||||
"remote_system_enable_capab": list(row["enabled_capabilities"]),
|
||||
}
|
||||
)
|
||||
return details
|
||||
|
||||
|
||||
__all__ = ["LldpNeighborDict", "LldpNeighborRow", "lldp_neighbors", "lldp_neighbors_detail"]
|
||||
@@ -0,0 +1,204 @@
|
||||
"""``lldpctl -f keyvalue``: lldpd's neighbours, one row each.
|
||||
|
||||
Every driver for a host that runs lldpd reads its neighbours the same way, so
|
||||
the command and its parse live here once and a driver only carries the command
|
||||
across. lldpd's keyvalue writer (``src/client/kv_writer.c``) prints one
|
||||
``key=value`` line per field, the key being the field's path joined by dots
|
||||
(a newline inside a value becomes a space)::
|
||||
|
||||
lldp.eth0.1.via=LLDP
|
||||
lldp.eth0.1.chassis.mac=00:11:22:33:44:01
|
||||
lldp.eth0.1.chassis.Tel.enabled=on
|
||||
lldp.eth0.1.port.local=gi1/0/7
|
||||
|
||||
**A neighbour is a block, not a port.** Every neighbour on a port prints the
|
||||
same keys, so grouping the lines by interface merges them. A neighbour opens
|
||||
with ``via`` (after the local interface's ``alias``, when it has one); the next
|
||||
``via`` on the same port is the next neighbour.
|
||||
|
||||
**An interface name may hold dots** (``eth0.1``, ``br-lan.10``). It is
|
||||
everything between ``lldp.`` and the neighbour's first field, never the second
|
||||
dotted part of the key.
|
||||
|
||||
**An id is printed under its type**, ``chassis.<type>=`` and ``port.<type>=``,
|
||||
with lldpd's names for the type (``mac``, ``ip``, ``ifname``, ``ifalias``,
|
||||
``local``, ``unhandled``); there is no ``chassis.id`` key.
|
||||
|
||||
**A failed read raises.** lldpctl exits non-zero when it cannot reach lldpd;
|
||||
:data:`LLDPCTL_KEYVALUE_COMMAND` brings that status and lldpctl's message back,
|
||||
and the parse raises on it instead of reading it as no neighbours. Output that
|
||||
carries no exit status (a driver that runs plain ``lldpctl -f keyvalue``) raises
|
||||
when it holds text but not a single neighbour line, as a shell's ``lldpctl: not
|
||||
found`` does.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from napalm_device_types.lldp import LldpNeighborRow
|
||||
|
||||
_RC = "__LLDPCTL_RC"
|
||||
|
||||
#: One line, POSIX ``sh``, read-only. Without arguments lldpctl shows the
|
||||
#: neighbours in detail; its error text and exit status come back with them.
|
||||
LLDPCTL_KEYVALUE_COMMAND = f"lldpctl -f keyvalue 2>&1; echo {_RC}=$?"
|
||||
|
||||
_RC_RE = re.compile(rf"^{_RC}=(\d+)$")
|
||||
_PREFIX = "lldp."
|
||||
#: The fields a neighbour opens with: the local interface's alias, then ``via``.
|
||||
_OPENERS = frozenset({"alias", "via"})
|
||||
#: The first part after the interface name of every key lldpd prints for a
|
||||
#: neighbour (``src/client/display.c``, ``display_interface``).
|
||||
_CATEGORIES = _OPENERS | {
|
||||
"rid",
|
||||
"age",
|
||||
"status",
|
||||
"chassis",
|
||||
"port",
|
||||
"ttl",
|
||||
"vlan",
|
||||
"ppvid",
|
||||
"pi",
|
||||
"lldp-med",
|
||||
"unknown-tlvs",
|
||||
}
|
||||
#: lldpd's id types (``src/lib/atoms/chassis.c``, ``port.c``), in the order read.
|
||||
_CHASSIS_ID_TYPES = ("mac", "local", "ip", "ifname", "ifalias", "unhandled")
|
||||
_PORT_ID_TYPES = ("ifname", "mac", "local", "ip", "ifalias", "unhandled")
|
||||
#: lldpd's capability symbols in NAPALM's names; one NAPALM lacks is lowercased.
|
||||
_CAPABILITIES = {
|
||||
"Other": "other",
|
||||
"Repeater": "repeater",
|
||||
"Bridge": "bridge",
|
||||
"Router": "router",
|
||||
"Wlan": "wlan-access-point",
|
||||
"Tel": "telephone",
|
||||
"Docsis": "docsis-cable-device",
|
||||
"Station": "station",
|
||||
}
|
||||
_SWITCH = {"on": True, "off": False}
|
||||
|
||||
_Fields = dict[str, list[str]]
|
||||
|
||||
|
||||
def parse_lldpctl_keyvalue(output: str) -> list[LldpNeighborRow]:
|
||||
"""One row per neighbour, in the order lldpctl listed them.
|
||||
|
||||
:raises ValueError: when lldpctl failed -- a non-zero exit status, or text
|
||||
without a single neighbour line and no status at all.
|
||||
"""
|
||||
return [_row(port, fields) for port, fields in _neighbours(_pairs(output))]
|
||||
|
||||
|
||||
def _pairs(output: str) -> list[tuple[str, str]]:
|
||||
"""``(key without "lldp.", value)`` of every neighbour line; raises on a failed run."""
|
||||
pairs: list[tuple[str, str]] = []
|
||||
other: list[str] = []
|
||||
status: int | None = None
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
key, sep, value = line.partition("=")
|
||||
if _RC_RE.match(line):
|
||||
status = int(value)
|
||||
elif sep and key.startswith(_PREFIX):
|
||||
pairs.append((key[len(_PREFIX) :], value))
|
||||
elif line:
|
||||
other.append(line)
|
||||
_raise_on_failure(status, other, bool(pairs))
|
||||
return pairs
|
||||
|
||||
|
||||
def _raise_on_failure(status: int | None, other: list[str], listed: bool) -> None:
|
||||
"""A non-zero status, or text without a status and without a neighbour line."""
|
||||
if status or (status is None and other and not listed):
|
||||
said = " ".join(other)[:200] or f"exit status {status}"
|
||||
raise ValueError(f"lldpctl did not list the neighbours: {said}")
|
||||
|
||||
|
||||
def _neighbours(pairs: list[tuple[str, str]]) -> list[tuple[str, _Fields]]:
|
||||
"""Split the lines into neighbours: ``(local interface, {field: [values]})``."""
|
||||
neighbours: list[tuple[str, _Fields]] = []
|
||||
port: str | None = None
|
||||
fields: _Fields = {}
|
||||
for key, value in pairs:
|
||||
split = _split(key, port)
|
||||
if split is None:
|
||||
continue
|
||||
name, field = split
|
||||
if name != port or field == "alias" or (field == "via" and "via" in fields):
|
||||
port, fields = name, {}
|
||||
neighbours.append((port, fields))
|
||||
fields.setdefault(field, []).append(value)
|
||||
return neighbours
|
||||
|
||||
|
||||
def _split(key: str, port: str | None) -> tuple[str, str] | None:
|
||||
"""``(interface, field)`` of a key, or None when it is no neighbour field.
|
||||
|
||||
``via`` and ``alias`` end their key, so they name the interface exactly;
|
||||
the keys after them continue that interface. Only a key that does neither
|
||||
ends its interface name at the first known field.
|
||||
"""
|
||||
head, _, last = key.rpartition(".")
|
||||
if head and last in _OPENERS:
|
||||
return head, last
|
||||
if port is not None and key.startswith(port + "."):
|
||||
field = key[len(port) + 1 :]
|
||||
if field.split(".", 1)[0] in _CATEGORIES:
|
||||
return port, field
|
||||
parts = key.split(".")
|
||||
for i in range(1, len(parts)):
|
||||
if parts[i] in _CATEGORIES:
|
||||
return ".".join(parts[:i]), ".".join(parts[i:])
|
||||
return None
|
||||
|
||||
|
||||
def _row(port: str, fields: _Fields) -> LldpNeighborRow:
|
||||
chassis_type, chassis_id = _id(fields, "chassis", _CHASSIS_ID_TYPES)
|
||||
port_type, port_id = _id(fields, "port", _PORT_ID_TYPES)
|
||||
capabilities, enabled = _capabilities(fields)
|
||||
return {
|
||||
"local_port": port,
|
||||
"chassis_id": chassis_id,
|
||||
"chassis_id_type": chassis_type,
|
||||
"port_id": port_id,
|
||||
"port_id_type": port_type,
|
||||
"port_description": _first(fields, "port.descr"),
|
||||
"system_name": _first(fields, "chassis.name"),
|
||||
"system_description": _first(fields, "chassis.descr"),
|
||||
"management_addresses": list(fields.get("chassis.mgmt-ip", [])),
|
||||
"capabilities": capabilities,
|
||||
"enabled_capabilities": enabled,
|
||||
}
|
||||
|
||||
|
||||
def _first(fields: _Fields, field: str) -> str:
|
||||
return fields.get(field, [""])[0]
|
||||
|
||||
|
||||
def _id(fields: _Fields, category: str, types: tuple[str, ...]) -> tuple[str, str]:
|
||||
"""``(type, id)`` of the chassis or the port; ``("", "")`` when none was sent."""
|
||||
for kind in types:
|
||||
if f"{category}.{kind}" in fields:
|
||||
return kind, _first(fields, f"{category}.{kind}")
|
||||
return "", ""
|
||||
|
||||
|
||||
def _capabilities(fields: _Fields) -> tuple[list[str], list[str]]:
|
||||
"""``chassis.<Symbol>.enabled=on|off``: the capabilities offered, and those enabled."""
|
||||
offered: list[str] = []
|
||||
enabled: list[str] = []
|
||||
for field, values in fields.items():
|
||||
parts = field.split(".")
|
||||
switch = _SWITCH.get(values[0])
|
||||
if len(parts) != 3 or parts[0] != "chassis" or parts[2] != "enabled" or switch is None:
|
||||
continue
|
||||
name = _CAPABILITIES.get(parts[1], parts[1].lower())
|
||||
offered.append(name)
|
||||
if switch:
|
||||
enabled.append(name)
|
||||
return offered, enabled
|
||||
|
||||
|
||||
__all__ = ["LLDPCTL_KEYVALUE_COMMAND", "parse_lldpctl_keyvalue"]
|
||||
@@ -0,0 +1,943 @@
|
||||
"""Personal login accounts on a host: reading them, adding one, locking one again.
|
||||
|
||||
A person who is to work on a host gets an account of their own: they log in
|
||||
with their public key and, where they are to administer the host, may use
|
||||
sudo with their own password. When they leave, the account is locked, not
|
||||
deleted: their key goes, sudo goes, the login is refused, and the home stays.
|
||||
|
||||
**What the person changes follows them** (NetOrk/netork#2013). A key they
|
||||
replace goes from the account as the new one comes in (``replaces``); a key
|
||||
they delete goes without a new one (``remove_local_account_keys``). Either way
|
||||
only the keys named go: one the person added on the host stays, and the
|
||||
account stays open. A password they remove goes from the account too
|
||||
(``clear_password``): it logs in with a key only and has no sudo, as the sudo
|
||||
rule asks for that password.
|
||||
|
||||
:class:`LocalAccountsMixin` holds what is the same on every POSIX host -- the
|
||||
checks, reading an account back, the order of the steps, the key file and the
|
||||
sudo rule. A driver supplies the commands that differ between operating
|
||||
systems: creating, opening and locking an account, reading its lock, and
|
||||
taking it out of a group.
|
||||
|
||||
**Every command root runs is one fixed command**, with no shell syntax of its
|
||||
own -- ``useradd ...``, ``install -m 440 ...``, ``rm -f -- <path>`` -- so a
|
||||
sudoers allowlist of commands can name each one. What goes into a file is
|
||||
staged first, without privilege; root never reads stdin, where a sudo that
|
||||
does not prompt would leave the password.
|
||||
|
||||
**Nothing root runs follows the person's files.** The key files live in a home
|
||||
the person owns, where a symbolic link may point anywhere, so they are read and
|
||||
written as that person (``sudo -n -u <name>``). Only the existence of a key
|
||||
file is asked as root.
|
||||
|
||||
**The sudo rule is a file of its own** in the drop-in directory sudo includes,
|
||||
``<name> ALL=(ALL) ALL``: the person's own password, as on a new VM. A group
|
||||
alone is not enough, as some distributions grant ``%wheel`` and others
|
||||
``%sudo``. ``visudo`` checks the rule before it is installed, and ``sudo -l``
|
||||
afterwards shows whether it took effect. A rule elsewhere -- cloud-init's
|
||||
``90-cloud-init-users`` -- is not edited; it is reported.
|
||||
|
||||
**The login user's own account and system accounts are never touched**:
|
||||
locking the first would lock the caller out.
|
||||
|
||||
**netOrk's own account** (``add_service_account``) is made the same way,
|
||||
through the account it logs in with today: a key and no password, and a rule
|
||||
of its own -- ``<name> ALL=(ALL) NOPASSWD: ALL`` in ``85-service-<name>`` --
|
||||
so it gains root without a password that could end up anywhere. Once netOrk
|
||||
logs in with it, the person's account it used before is one like any other.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Iterable, Sequence
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.fixes import FixStep, run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepDict, FixStepOutcomeDict
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: A login name every POSIX host takes as it is: lowercase, a letter or an
|
||||
#: underscore first, at most 32 characters. It is also safe in a root command.
|
||||
ACCOUNT_NAME_RE = re.compile(r"[a-z_][a-z0-9_.-]{0,31}")
|
||||
|
||||
#: The crypt(3) prefixes of each password scheme a driver may take.
|
||||
PASSWORD_SCHEMES: dict[str, tuple[str, ...]] = {
|
||||
"sha512": ("$6$",),
|
||||
"bcrypt": ("$2b$", "$2a$", "$2y$"),
|
||||
}
|
||||
_CRYPT_RE = re.compile(r"\$[0-9a-z]+\$[./0-9A-Za-z$]+")
|
||||
|
||||
#: The public key types OpenSSH takes in a key file.
|
||||
_KEY_TYPE_RE = re.compile(
|
||||
r"(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)"
|
||||
r"|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)"
|
||||
)
|
||||
_KEY_BLOB_RE = re.compile(r"[A-Za-z0-9+/]+={0,3}")
|
||||
|
||||
#: Before the rule's file name; after cloud-init's ``90-`` it would win, so before it.
|
||||
SUDOERS_FILE_PREFIX = "80-account-"
|
||||
#: Before the file name of netOrk's own account's rule; after a person's, before cloud-init's.
|
||||
SERVICE_SUDOERS_FILE_PREFIX = "85-service-"
|
||||
|
||||
#: A line of ``sudo -l`` that lets the account run every command as root.
|
||||
_RUN_ALL_RE = re.compile(r"^\s*\(ALL(\s*:\s*ALL)?\)\s+([A-Z_]+:\s*)*ALL\s*$", re.MULTILINE)
|
||||
#: The same, without a password.
|
||||
_RUN_ALL_NOPASSWD_RE = re.compile(
|
||||
r"^\s*\(ALL(\s*:\s*ALL)?\)\s+([A-Z_]+:\s*)*NOPASSWD:\s*([A-Z_]+:\s*)*ALL\s*$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
#: Login shells that refuse every login: an account with one belongs to a service.
|
||||
_NO_LOGIN_SHELLS = frozenset({"nologin", "false"})
|
||||
|
||||
#: Stages stdin as a file anyone may read -- the person reads the key file
|
||||
#: from it -- and prints its path. The content is a public key or a sudo rule.
|
||||
_STAGE = 't=$(mktemp) && chmod 644 "$t" && cat > "$t" && printf %s "$t"'
|
||||
|
||||
|
||||
class LocalAccountDict(TypedDict):
|
||||
"""A person's account as the host has it (``get_local_accounts``)."""
|
||||
|
||||
name: str
|
||||
uid: int
|
||||
home: str
|
||||
shell: str
|
||||
#: Primary group first.
|
||||
groups: list[str]
|
||||
#: No login, with a key or a password.
|
||||
locked: bool
|
||||
#: ``sudo -l`` lets it run every command as root.
|
||||
admin: bool
|
||||
#: The lines of its key files; None when they could not be read (a locked
|
||||
#: account cannot run a command any more).
|
||||
authorized_keys: list[str] | None
|
||||
|
||||
|
||||
class LocalAccountChangeDict(FixResultDict):
|
||||
"""The result of ``add_local_account`` and ``lock_local_account``."""
|
||||
|
||||
#: The account read back after the change; None when it is not there or
|
||||
#: could not be read.
|
||||
account: LocalAccountDict | None
|
||||
|
||||
|
||||
def sudoers_rule(name: str) -> str:
|
||||
"""The rule that lets *name* run everything as root, with its own password."""
|
||||
return f"{name} ALL=(ALL) ALL\n"
|
||||
|
||||
|
||||
def sudoers_rule_path(directory: str, name: str) -> str:
|
||||
"""Where *name*'s rule lives in *directory*.
|
||||
|
||||
sudo skips a file whose name holds a dot, so a dot becomes ``_2e``, and an
|
||||
underscore ``__``: no two names share a file.
|
||||
"""
|
||||
return f"{directory}/{SUDOERS_FILE_PREFIX}{_rule_file_name(name)}"
|
||||
|
||||
|
||||
def service_sudoers_rule(name: str) -> str:
|
||||
"""The rule that lets netOrk's own account *name* run everything as root, no password."""
|
||||
return f"{name} ALL=(ALL) NOPASSWD: ALL\n"
|
||||
|
||||
|
||||
def service_sudoers_rule_path(directory: str, name: str) -> str:
|
||||
"""Where the rule of netOrk's own account *name* lives in *directory*."""
|
||||
return f"{directory}/{SERVICE_SUDOERS_FILE_PREFIX}{_rule_file_name(name)}"
|
||||
|
||||
|
||||
def _rule_file_name(name: str) -> str:
|
||||
return name.replace("_", "__").replace(".", "_2e")
|
||||
|
||||
|
||||
def authorized_keys_paths(home: str) -> tuple[str, str]:
|
||||
"""The key files sshd reads in *home* unless configured otherwise."""
|
||||
return f"{home}/.ssh/authorized_keys", f"{home}/.ssh/authorized_keys2"
|
||||
|
||||
|
||||
def check_account_name(name: str) -> None:
|
||||
""":raises ValueError: when *name* is no login name every host takes."""
|
||||
if not ACCOUNT_NAME_RE.fullmatch(name):
|
||||
raise ValueError(f"not an account name: {name!r}")
|
||||
|
||||
|
||||
def _key_blob(line: str) -> str | None:
|
||||
"""The base64 part of a key file line, options and comment aside."""
|
||||
words = line.split()
|
||||
for i, word in enumerate(words[:-1]):
|
||||
if _KEY_TYPE_RE.fullmatch(word):
|
||||
return words[i + 1]
|
||||
return None
|
||||
|
||||
|
||||
def check_public_key(key: str) -> None:
|
||||
""":raises ValueError: when *key* is not one OpenSSH public key on one line."""
|
||||
words = key.split()
|
||||
if (
|
||||
"\n" in key.strip()
|
||||
or len(words) < 2
|
||||
or not _KEY_TYPE_RE.fullmatch(words[0])
|
||||
or not _KEY_BLOB_RE.fullmatch(words[1])
|
||||
):
|
||||
raise ValueError("not a public key: expected '<type> <base64> [comment]' on one line")
|
||||
|
||||
|
||||
def _checked_keys(keys: Sequence[str]) -> list[str]:
|
||||
"""*keys*, each one stripped.
|
||||
|
||||
:raises ValueError: when *keys* is one string, or one of them no public key.
|
||||
"""
|
||||
if isinstance(keys, str):
|
||||
raise ValueError("expected a list of public keys, not one string")
|
||||
for key in keys:
|
||||
check_public_key(key)
|
||||
return [key.strip() for key in keys]
|
||||
|
||||
|
||||
def _command(argv: Sequence[str]) -> str:
|
||||
return shlex.join(argv)
|
||||
|
||||
|
||||
def _as(name: str, *argv: str) -> str:
|
||||
"""*argv* run as *name*, from root: nothing it does reaches beyond that account."""
|
||||
return _command(["sudo", "-n", "-u", name, *argv])
|
||||
|
||||
|
||||
def _said(result: CommandResult) -> str:
|
||||
return (result.stderr or result.stdout).strip() or f"exit {result.exit_code}"
|
||||
|
||||
|
||||
class LocalAccountsMixin:
|
||||
"""Reads, adds and locks personal accounts; a driver supplies the OS's commands.
|
||||
|
||||
Mixed in by the drivers that can, so ``callable(getattr(driver,
|
||||
"add_local_account", None))`` says whether a driver can.
|
||||
"""
|
||||
|
||||
#: The login shell of a new account.
|
||||
ACCOUNT_SHELL: ClassVar[str] = "/bin/sh"
|
||||
#: The password scheme the host's accounts take, a key of :data:`PASSWORD_SCHEMES`.
|
||||
ACCOUNT_PASSWORD_SCHEME: ClassVar[str] = "sha512"
|
||||
#: Groups that make an account an administrator; a person without sudo leaves them.
|
||||
ACCOUNT_ADMIN_GROUPS: ClassVar[tuple[str, ...]] = ("wheel",)
|
||||
#: The lowest uid of a person's account; below are the system's.
|
||||
ACCOUNT_MIN_UID: ClassVar[int] = 1000
|
||||
#: The drop-in directory sudo includes.
|
||||
SUDOERS_DIR: ClassVar[str] = "/etc/sudoers.d"
|
||||
#: The group of root's files.
|
||||
ROOT_GROUP: ClassVar[str] = "root"
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# -- what a driver supplies ------------------------------------------------------
|
||||
#
|
||||
# ``_account_*`` are the driver's: the five below it must supply, the two after
|
||||
# them (``_account_create_with_uid``, ``_account_clear_password``) it may, and
|
||||
# the key store (``_account_key_files``, ``_account_read_keys``,
|
||||
# ``_account_add_key``, ``_account_drop_keys``, ``_account_remove_keys``) it may
|
||||
# replace. ``_accounts_*`` are this mixin's own.
|
||||
|
||||
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||
"""The commands that create *name* with a home and :attr:`ACCOUNT_SHELL`.
|
||||
|
||||
Without *password_hash* the account takes no password, only a key.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_open(
|
||||
self, name: str, password_hash: str | None, *, locked: bool
|
||||
) -> list[list[str]]:
|
||||
"""The commands that let *name* log in again, with *password_hash* if given."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]:
|
||||
"""The commands that refuse *name* every login, a key's too; none when *locked*."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_locked(self, name: str, passwd: list[str]) -> bool:
|
||||
"""Whether *name* is locked; *passwd* is its ``getent passwd`` line, split.
|
||||
|
||||
:raises RuntimeError: when that cannot be read.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
|
||||
"""The command that takes *name* out of *group*; *groups* are all of its own."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
|
||||
"""The commands that create *name* as :meth:`_account_create` does, without a
|
||||
password, and with the uid *uid*.
|
||||
|
||||
Only netOrk's own account asks for one (``add_service_account(uid=)``).
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_clear_password(self, name: str) -> list[list[str]]:
|
||||
"""The commands that take *name*'s password away; its key login stays as it is.
|
||||
|
||||
Not an empty password -- PAM's ``nullok`` lets anyone in without one --
|
||||
and not a lock or an expiry, which sshd or PAM apply to a key too.
|
||||
Only ``add_local_account(clear_password=True)`` and
|
||||
``remove_local_account_keys(clear_password=True)`` ask for it.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# -- reading ---------------------------------------------------------------------
|
||||
|
||||
def get_local_accounts(self, names: Iterable[str]) -> list[LocalAccountDict]:
|
||||
"""The accounts of *names* the host has, in that order; a missing one is left out.
|
||||
|
||||
:raises ValueError: for a name that is no account name.
|
||||
:raises RuntimeError: when an account cannot be read.
|
||||
"""
|
||||
wanted = list(names)
|
||||
for name in wanted:
|
||||
check_account_name(name)
|
||||
found = (self._accounts_read(name) for name in wanted)
|
||||
return [account for account in found if account is not None]
|
||||
|
||||
def _accounts_passwd(self, name: str) -> list[str] | None:
|
||||
result = self.run_command(_command(["getent", "passwd", name]), timeout=30)
|
||||
if result.exit_code == 2:
|
||||
return None
|
||||
fields = result.stdout.strip().split(":")
|
||||
if result.exit_code != 0 or len(fields) < 7 or fields[0] != name:
|
||||
raise RuntimeError(f"cannot read the account {name}: {_said(result)}")
|
||||
return fields
|
||||
|
||||
def _accounts_read(self, name: str) -> LocalAccountDict | None:
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is None:
|
||||
return None
|
||||
groups = self.run_command(_command(["id", "-Gn", name]), timeout=30)
|
||||
if groups.exit_code != 0:
|
||||
raise RuntimeError(f"cannot read the groups of {name}: {_said(groups)}")
|
||||
home = passwd[5]
|
||||
return {
|
||||
"name": name,
|
||||
"uid": int(passwd[2]),
|
||||
"home": home,
|
||||
"shell": passwd[6],
|
||||
"groups": groups.stdout.split(),
|
||||
"locked": self._account_locked(name, passwd),
|
||||
"admin": self._accounts_admin(name),
|
||||
"authorized_keys": self._account_read_keys(name, home),
|
||||
}
|
||||
|
||||
def _accounts_admin(self, name: str) -> bool:
|
||||
result = self.run_command(_command(["sudo", "-l", "-U", name]), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"cannot ask sudo about {name}: {_said(result)}")
|
||||
return bool(_RUN_ALL_RE.search(result.stdout))
|
||||
|
||||
def _account_key_files(self, name: str, home: str) -> tuple[str, ...]:
|
||||
"""Every file sshd reads *name*'s keys from; a host that adds one of its own says so."""
|
||||
return authorized_keys_paths(home)
|
||||
|
||||
def _account_read_keys(self, name: str, home: str) -> list[str] | None:
|
||||
"""The lines of :meth:`_account_key_files`, read as *name*; None when it cannot."""
|
||||
lines: list[str] = []
|
||||
for path in self._account_key_files(name, home):
|
||||
there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30)
|
||||
if there.exit_code != 0:
|
||||
continue
|
||||
result = self.run_command(_as(name, "cat", "--", path), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
return None
|
||||
lines += [ln for ln in result.stdout.splitlines() if ln.strip()]
|
||||
return lines
|
||||
|
||||
# -- changing ----------------------------------------------------------------------
|
||||
|
||||
def add_local_account(
|
||||
self,
|
||||
name: str,
|
||||
public_key: str,
|
||||
*,
|
||||
password_hash: str | None = None,
|
||||
admin: bool = False,
|
||||
clear_password: bool = False,
|
||||
replaces: Sequence[str] = (),
|
||||
) -> LocalAccountChangeDict:
|
||||
"""Give *name* an account that logs in with *public_key*, or open it again.
|
||||
|
||||
An account that is there is opened again and keeps its other keys; a
|
||||
new one gets a home. *password_hash* (crypt(3), in
|
||||
:attr:`ACCOUNT_PASSWORD_SCHEME`) becomes its password; *admin* gives it
|
||||
the sudo rule, which asks for that password -- so an administrator
|
||||
needs one. Without *admin*, the rule and :attr:`ACCOUNT_ADMIN_GROUPS`
|
||||
are taken away. Without *password_hash* the account keeps the password
|
||||
it has, unless *clear_password* takes it away: the account then logs
|
||||
in with a key only, and can have no sudo.
|
||||
|
||||
*replaces* are keys *public_key* takes the place of -- the person's
|
||||
old ones. They go from the account, matched by their base64 whatever
|
||||
a line's options or comment; every other key stays.
|
||||
|
||||
Steps: ``account``, then ``sudo``, ``password`` (with
|
||||
*clear_password*), ``keys`` and ``old keys`` (with *replaces*), each of
|
||||
which runs when another failed: an old key goes even when the new one
|
||||
could not be added.
|
||||
|
||||
:raises ValueError: for a name, key or hash no host takes, a replaced
|
||||
key that is none, *clear_password* with a *password_hash* or with
|
||||
*admin*, the login user's own account, or a system account.
|
||||
"""
|
||||
check_account_name(name)
|
||||
check_public_key(public_key)
|
||||
new = _key_blob(public_key)
|
||||
old = [key for key in _checked_keys(replaces) if _key_blob(key) != new]
|
||||
self._accounts_check_password(password_hash, admin=admin, clear=clear_password)
|
||||
existing = self._accounts_changeable(name)
|
||||
first = run_fix_steps(
|
||||
[("account", lambda: self._accounts_open_or_create(name, existing, password_hash))]
|
||||
)
|
||||
parts = [first]
|
||||
if first["success"]:
|
||||
steps = self._accounts_after_open(name, public_key, admin, clear_password, old)
|
||||
parts += [run_fix_steps([step]) for step in steps]
|
||||
return self._accounts_result(name, parts)
|
||||
|
||||
def _accounts_after_open(
|
||||
self, name: str, public_key: str, admin: bool, clear_password: bool, old: list[str]
|
||||
) -> list[FixStep]:
|
||||
"""The steps of ``add_local_account`` once the account is there, each on its own."""
|
||||
steps: list[FixStep] = [("sudo", lambda: self._accounts_set_sudo(name, admin=admin))]
|
||||
if clear_password:
|
||||
steps.append(("password", lambda: self._accounts_clear_password(name)))
|
||||
steps.append(("keys", lambda: self._accounts_add_key(name, public_key)))
|
||||
if old:
|
||||
steps.append(("old keys", lambda: self._accounts_drop_keys(name, old)))
|
||||
return steps
|
||||
|
||||
def remove_local_account_keys(
|
||||
self, name: str, keys: Sequence[str], *, clear_password: bool = False
|
||||
) -> LocalAccountChangeDict:
|
||||
"""Take *keys* off *name*'s account, for a person who deleted them.
|
||||
|
||||
Only those keys go, matched by their base64 whatever a line's options
|
||||
or comment; the other keys stay, and the account stays open -- to get
|
||||
a new key once there is one. A locked account has none left to
|
||||
remove: the lock took them all. Without *clear_password* the password
|
||||
and sudo stay too; with it the password goes, and so do the sudo rule
|
||||
and :attr:`ACCOUNT_ADMIN_GROUPS`, as sudo asks for that password -- for
|
||||
a person whose password went with their key.
|
||||
|
||||
Steps: ``keys``, then ``password`` and ``sudo`` (with *clear_password*),
|
||||
each of which runs when another failed.
|
||||
|
||||
:raises ValueError: for a name no host takes, no keys or one that is
|
||||
none, the login user's own account, or a system account.
|
||||
"""
|
||||
check_account_name(name)
|
||||
wanted = _checked_keys(keys)
|
||||
if not wanted:
|
||||
raise ValueError("no public key to remove")
|
||||
if self._accounts_changeable(name) is None:
|
||||
step: FixStepDict = {"step": "keys", "ok": False, "output": f"no account {name}"}
|
||||
return {**_joined([step]), "account": None}
|
||||
steps: list[FixStep] = [("keys", lambda: self._accounts_drop_keys(name, wanted))]
|
||||
if clear_password:
|
||||
steps.append(("password", lambda: self._accounts_clear_password(name)))
|
||||
steps.append(("sudo", lambda: self._accounts_set_sudo(name, admin=False)))
|
||||
return self._accounts_result(name, [run_fix_steps([step]) for step in steps])
|
||||
|
||||
def lock_local_account(self, name: str) -> LocalAccountChangeDict:
|
||||
"""Lock *name*: its keys go, every login is refused, sudo goes; its home stays.
|
||||
|
||||
Steps ``keys``, ``lock`` and ``sudo``, each run when one before failed:
|
||||
the lock matters most. A sudo rule outside the drop-in directory is
|
||||
reported, not edited -- with the account locked it can no longer be used.
|
||||
|
||||
:raises ValueError: for a name no host takes, the login user's own
|
||||
account, or a system account.
|
||||
"""
|
||||
check_account_name(name)
|
||||
if self._accounts_changeable(name) is None:
|
||||
step: FixStepDict = {"step": "account", "ok": False, "output": f"no account {name}"}
|
||||
return {**_joined([step]), "account": None}
|
||||
parts = [
|
||||
run_fix_steps([("keys", lambda: self._accounts_remove_keys(name))]),
|
||||
run_fix_steps([("lock", lambda: self._accounts_lock(name))]),
|
||||
run_fix_steps(
|
||||
[("sudo", lambda: self._accounts_set_sudo(name, admin=False, locked=True))]
|
||||
),
|
||||
]
|
||||
return self._accounts_result(name, parts)
|
||||
|
||||
def add_service_account(
|
||||
self,
|
||||
name: str,
|
||||
public_key: str,
|
||||
*,
|
||||
uid: int | None = None,
|
||||
replaces: Sequence[str] = (),
|
||||
) -> LocalAccountChangeDict:
|
||||
"""Make *name* netOrk's own account: it logs in with *public_key*, and gains
|
||||
root without a password.
|
||||
|
||||
Created through the account the driver logs in with now, or opened
|
||||
again when it is there; its other keys stay. It takes no password. Run
|
||||
again with the account the driver already logs in with, it only adds
|
||||
what is missing.
|
||||
|
||||
A new account gets *uid* when one is given -- the same on every host --
|
||||
once no other account has it; an account that is there keeps its own,
|
||||
as a uid is never changed under files that carry it.
|
||||
|
||||
*replaces* are netOrk's keys *public_key* takes the place of: they go
|
||||
from the account once *public_key* is in it, matched as in
|
||||
:meth:`add_local_account`, and never *public_key* itself. Call it so
|
||||
through a login with *public_key*, tried before: netOrk keeps its way
|
||||
in (NetOrk/netork#2462).
|
||||
|
||||
Steps as in :meth:`add_local_account`: ``account``, then ``sudo`` and
|
||||
``keys``, and ``old keys`` with *replaces* when ``keys`` went. The new
|
||||
login itself is for the caller to try.
|
||||
|
||||
An account that is there and cannot log in (``nologin``, ``false``) is
|
||||
another service's -- a satellite's ``netork``, say -- and is left alone.
|
||||
|
||||
:raises ValueError: for a name or key no host takes, a replaced key that
|
||||
is none, root, a uid of 0 or less, or another service's account.
|
||||
:raises RuntimeError: when the login user cannot be told.
|
||||
"""
|
||||
check_public_key(public_key)
|
||||
old = [key for key in _checked_keys(replaces) if _key_blob(key) != _key_blob(public_key)]
|
||||
login, existing = self._accounts_service_target(name, uid)
|
||||
first = self._accounts_service_account_step(name, login, existing, uid)
|
||||
parts = [first]
|
||||
if first["success"]:
|
||||
parts += self._accounts_service_keys(name, public_key, old)
|
||||
return self._accounts_result(name, parts)
|
||||
|
||||
def _accounts_service_account_step(
|
||||
self, name: str, login: str, existing: list[str] | None, uid: int | None
|
||||
) -> FixResultDict:
|
||||
"""The ``account`` step of netOrk's own account; nothing to do when the driver
|
||||
logs in as *name* already."""
|
||||
if name == login:
|
||||
step: FixStepDict = {
|
||||
"step": "account",
|
||||
"ok": True,
|
||||
"output": f"this driver logs in as {name} already",
|
||||
}
|
||||
return _joined([step])
|
||||
return run_fix_steps(
|
||||
[("account", lambda: self._accounts_service_account(name, existing, uid))]
|
||||
)
|
||||
|
||||
def _accounts_service_keys(
|
||||
self, name: str, public_key: str, old: list[str]
|
||||
) -> list[FixResultDict]:
|
||||
"""``sudo`` and ``keys`` of netOrk's own account, then ``old keys`` once the key is in."""
|
||||
parts = [
|
||||
run_fix_steps([("sudo", lambda: self._accounts_grant_service_sudo(name))]),
|
||||
run_fix_steps([("keys", lambda: self._accounts_add_key(name, public_key))]),
|
||||
]
|
||||
if old and parts[-1]["success"]:
|
||||
parts.append(run_fix_steps([("old keys", lambda: self._accounts_drop_keys(name, old))]))
|
||||
return parts
|
||||
|
||||
def _accounts_service_target(self, name: str, uid: int | None) -> tuple[str, list[str] | None]:
|
||||
"""The login user and *name*'s passwd line, once *name* may become netOrk's.
|
||||
|
||||
:raises ValueError: as :meth:`add_service_account` says.
|
||||
"""
|
||||
check_account_name(name)
|
||||
if uid is not None and uid <= 0:
|
||||
raise ValueError(f"not a uid for netOrk's own account: {uid}")
|
||||
login = self._accounts_login()
|
||||
existing = self._accounts_passwd(name)
|
||||
if existing is not None and int(existing[2]) == 0:
|
||||
raise ValueError(f"{name} is root")
|
||||
if existing is not None and existing[6].rsplit("/", 1)[-1] in _NO_LOGIN_SHELLS:
|
||||
raise ValueError(
|
||||
f"{name} is there and cannot log in ({existing[6]}): another service's account"
|
||||
)
|
||||
return login, existing
|
||||
|
||||
def _accounts_service_account(
|
||||
self, name: str, passwd: list[str] | None, uid: int | None
|
||||
) -> FixStepOutcomeDict:
|
||||
"""netOrk's own account opened or made, a new one with *uid* when given."""
|
||||
if uid is None:
|
||||
return self._accounts_open_or_create(name, passwd, None)
|
||||
if passwd is not None:
|
||||
outcome = self._accounts_open_or_create(name, passwd, None)
|
||||
if outcome["ok"] and int(passwd[2]) != uid:
|
||||
outcome["output"] += f"; it keeps its uid {passwd[2]}, not {uid}"
|
||||
return outcome
|
||||
owner = self._accounts_passwd_of_uid(uid)
|
||||
if owner is not None:
|
||||
return {"ok": False, "output": f"uid {uid} is the account {owner}'s"}
|
||||
try:
|
||||
create = self._account_create_with_uid(name, uid)
|
||||
except NotImplementedError:
|
||||
return {"ok": False, "output": f"this driver cannot give an account the uid {uid}"}
|
||||
failed = self._accounts_run(create)
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": _said(failed)}
|
||||
return {"ok": True, "output": f"account {name} created, uid {uid}"}
|
||||
|
||||
def _accounts_passwd_of_uid(self, uid: int) -> str | None:
|
||||
"""The name of the account with *uid*, or None."""
|
||||
result = self.run_command(_command(["getent", "passwd", str(uid)]), timeout=30)
|
||||
if result.exit_code == 2:
|
||||
return None
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"cannot ask who has uid {uid}: {_said(result)}")
|
||||
return result.stdout.split(":", 1)[0].strip() or None
|
||||
|
||||
def _accounts_check_password(
|
||||
self, password_hash: str | None, *, admin: bool, clear: bool
|
||||
) -> None:
|
||||
""":raises ValueError: for a hash the host does not take, or a password to
|
||||
clear that is to be set, or that sudo would ask for."""
|
||||
if clear and password_hash is not None:
|
||||
raise ValueError(
|
||||
"a password to clear cannot be set too: clear_password or password_hash"
|
||||
)
|
||||
if clear and admin:
|
||||
raise ValueError("an account without a password cannot use sudo: its rule asks for it")
|
||||
if password_hash is not None:
|
||||
self._accounts_check_hash(password_hash)
|
||||
|
||||
def _accounts_check_hash(self, password_hash: str) -> None:
|
||||
prefixes = PASSWORD_SCHEMES[self.ACCOUNT_PASSWORD_SCHEME]
|
||||
if not _CRYPT_RE.fullmatch(password_hash) or not password_hash.startswith(prefixes):
|
||||
raise ValueError(f"not a {self.ACCOUNT_PASSWORD_SCHEME} password hash")
|
||||
|
||||
def _accounts_changeable(self, name: str) -> list[str] | None:
|
||||
"""*name*'s passwd line, None when there is none.
|
||||
|
||||
:raises ValueError: for the login user's own account or a system account.
|
||||
:raises RuntimeError: when the login user cannot be told.
|
||||
"""
|
||||
if name == self._accounts_login():
|
||||
raise ValueError(f"{name} is the account this driver logs in with")
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is not None and int(passwd[2]) < self.ACCOUNT_MIN_UID:
|
||||
raise ValueError(f"{name} is a system account (uid {passwd[2]})")
|
||||
return passwd
|
||||
|
||||
def _accounts_login(self) -> str:
|
||||
""":raises RuntimeError: when the login user cannot be told."""
|
||||
login = self.run_command("id -un", timeout=30).stdout.strip()
|
||||
if not login:
|
||||
raise RuntimeError("cannot tell which account this driver logs in with")
|
||||
return login
|
||||
|
||||
def _accounts_result(self, name: str, parts: list[FixResultDict]) -> LocalAccountChangeDict:
|
||||
steps = [s for part in parts for s in part["steps"]]
|
||||
result = _joined(steps)
|
||||
account: LocalAccountDict | None = None
|
||||
try:
|
||||
account = self._accounts_read(name)
|
||||
except RuntimeError as exc:
|
||||
result["output"] += f"\n[read back] {exc}"
|
||||
return {**result, "account": account}
|
||||
|
||||
def _accounts_root(self, argv: Sequence[str]) -> CommandResult:
|
||||
return self.run_command(_command(argv), privileged=True, timeout=60)
|
||||
|
||||
def _accounts_run(self, commands: list[list[str]]) -> CommandResult | None:
|
||||
"""Run *commands* as root in order; the first that failed, or None."""
|
||||
for argv in commands:
|
||||
result = self._accounts_root(argv)
|
||||
if result.exit_code != 0:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _accounts_open_or_create(
|
||||
self, name: str, passwd: list[str] | None, password_hash: str | None
|
||||
) -> FixStepOutcomeDict:
|
||||
if passwd is None:
|
||||
failed = self._accounts_run(self._account_create(name, password_hash))
|
||||
done = f"account {name} created"
|
||||
else:
|
||||
locked = self._account_locked(name, passwd)
|
||||
failed = self._accounts_run(self._account_open(name, password_hash, locked=locked))
|
||||
done = f"account {name} opened again" if locked else f"account {name} is there"
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": _said(failed)}
|
||||
return {"ok": True, "output": done + (", password set" if password_hash else "")}
|
||||
|
||||
def _accounts_clear_password(self, name: str) -> FixStepOutcomeDict:
|
||||
try:
|
||||
commands = self._account_clear_password(name)
|
||||
except NotImplementedError:
|
||||
return {"ok": False, "output": "this driver cannot remove a password"}
|
||||
failed = self._accounts_run(commands)
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": _said(failed)}
|
||||
return {"ok": True, "output": f"{name} has no password: it logs in with a key only"}
|
||||
|
||||
def _accounts_lock(self, name: str) -> FixStepOutcomeDict:
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
locked = self._account_locked(name, passwd)
|
||||
failed = self._accounts_run(self._account_lock(name, locked=locked))
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": _said(failed)}
|
||||
if not self._account_locked(name, passwd):
|
||||
return {"ok": False, "output": f"{name} is still not locked"}
|
||||
return {"ok": True, "output": f"{name} was locked already" if locked else f"{name} locked"}
|
||||
|
||||
# -- sudo --------------------------------------------------------------------------
|
||||
|
||||
def _accounts_set_sudo(
|
||||
self, name: str, *, admin: bool, locked: bool = False
|
||||
) -> FixStepOutcomeDict:
|
||||
path = sudoers_rule_path(self.SUDOERS_DIR, name)
|
||||
if admin:
|
||||
return self._accounts_grant_sudo(name, path)
|
||||
said: list[str] = []
|
||||
removed = self._accounts_root(["rm", "-f", "--", path])
|
||||
if removed.exit_code != 0:
|
||||
return {"ok": False, "output": f"{path}: {_said(removed)}"}
|
||||
groups = self.run_command(_command(["id", "-Gn", name]), timeout=30).stdout.split()
|
||||
for group in self.ACCOUNT_ADMIN_GROUPS:
|
||||
if group not in groups[1:]:
|
||||
continue
|
||||
left = self._accounts_root(self._account_leave_group(name, group, groups))
|
||||
if left.exit_code != 0:
|
||||
return {"ok": False, "output": f"cannot take {name} out of {group}: {_said(left)}"}
|
||||
groups.remove(group)
|
||||
said.append(f"{name} left {group}")
|
||||
if self._accounts_admin(name):
|
||||
rest = f"another rule than {path} still lets {name} run everything as root"
|
||||
if locked:
|
||||
return {"ok": True, "output": f"{rest}; the account is locked, so it cannot use it"}
|
||||
return {"ok": False, "output": rest}
|
||||
said.append(f"{name} has no sudo")
|
||||
return {"ok": True, "output": "\n".join(said)}
|
||||
|
||||
def _accounts_grant_sudo(self, name: str, path: str) -> FixStepOutcomeDict:
|
||||
failed = self._accounts_install_rule(sudoers_rule(name), path)
|
||||
if failed is not None:
|
||||
return failed
|
||||
if not self._accounts_admin(name):
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"{path} is written, but sudo does not read it: "
|
||||
f"does sudoers include {self.SUDOERS_DIR}?",
|
||||
}
|
||||
return {"ok": True, "output": f"{name} may use sudo with its password ({path})"}
|
||||
|
||||
def _accounts_grant_service_sudo(self, name: str) -> FixStepOutcomeDict:
|
||||
path = service_sudoers_rule_path(self.SUDOERS_DIR, name)
|
||||
failed = self._accounts_install_rule(service_sudoers_rule(name), path)
|
||||
if failed is not None:
|
||||
return failed
|
||||
result = self.run_command(_command(["sudo", "-l", "-U", name]), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
return {"ok": False, "output": f"cannot ask sudo about {name}: {_said(result)}"}
|
||||
if not _RUN_ALL_NOPASSWD_RE.search(result.stdout):
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"{path} is written, but sudo does not read it: "
|
||||
f"does sudoers include {self.SUDOERS_DIR}?",
|
||||
}
|
||||
return {"ok": True, "output": f"{name} may use sudo without a password ({path})"}
|
||||
|
||||
def _accounts_install_rule(self, rule: str, path: str) -> FixStepOutcomeDict | None:
|
||||
"""Check *rule* with visudo and install it at *path*; the failure, or None."""
|
||||
staged = self._accounts_stage(rule)
|
||||
try:
|
||||
checked = self._accounts_root(["visudo", "-cf", staged])
|
||||
if checked.exit_code != 0:
|
||||
return {"ok": False, "output": f"visudo refuses the rule: {_said(checked)}"}
|
||||
installed = self._accounts_root(
|
||||
["install", "-m", "440", "-o", "root", "-g", self.ROOT_GROUP, "--", staged, path]
|
||||
)
|
||||
if installed.exit_code != 0:
|
||||
return {"ok": False, "output": f"{path}: {_said(installed)}"}
|
||||
finally:
|
||||
self._accounts_unstage(staged)
|
||||
return None
|
||||
|
||||
# -- keys --------------------------------------------------------------------------
|
||||
|
||||
def _accounts_stage(self, content: str) -> str:
|
||||
"""*content* in a fresh file of the login user's; its path.
|
||||
|
||||
:raises RuntimeError: when it cannot be staged.
|
||||
"""
|
||||
result = self.run_command(_STAGE, timeout=30, stdin=content.encode())
|
||||
path = result.stdout.strip().splitlines()[-1:] or [""]
|
||||
if result.exit_code != 0 or not path[0].startswith("/"):
|
||||
raise RuntimeError(f"cannot stage a file: {_said(result)}")
|
||||
return path[0]
|
||||
|
||||
def _accounts_unstage(self, path: str) -> None:
|
||||
self.run_command(_command(["rm", "-f", "--", path]), timeout=30)
|
||||
|
||||
def _accounts_home(self, name: str) -> str | None:
|
||||
passwd = self._accounts_passwd(name)
|
||||
return passwd[5] if passwd is not None else None
|
||||
|
||||
def _accounts_add_key(self, name: str, public_key: str) -> FixStepOutcomeDict:
|
||||
home = self._accounts_home(name)
|
||||
if home is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
return self._account_add_key(name, home, public_key)
|
||||
|
||||
def _accounts_remove_keys(self, name: str) -> FixStepOutcomeDict:
|
||||
home = self._accounts_home(name)
|
||||
if home is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
return self._account_remove_keys(name, home)
|
||||
|
||||
def _account_add_key(self, name: str, home: str, public_key: str) -> FixStepOutcomeDict:
|
||||
"""Add *public_key* to *name*'s first key file, as *name*; the others stay.
|
||||
|
||||
A driver whose host keeps keys elsewhere overrides this, with
|
||||
:meth:`_account_read_keys` and :meth:`_account_remove_keys`.
|
||||
"""
|
||||
path = authorized_keys_paths(home)[0]
|
||||
current = self._account_read_keys(name, home)
|
||||
if current is None:
|
||||
return {"ok": False, "output": f"cannot read the key files of {name}"}
|
||||
blob = _key_blob(public_key)
|
||||
if any(_key_blob(line) == blob for line in current):
|
||||
return {"ok": True, "output": f"the key is already in {path}"}
|
||||
mine = self._accounts_key_file(name, path)
|
||||
if mine is None:
|
||||
return {"ok": False, "output": f"cannot read {path}"}
|
||||
failed = self._accounts_write_key_file(name, home, path, [*mine, public_key.strip()])
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": f"{path}: {_said(failed)}"}
|
||||
return {"ok": True, "output": f"key added to {path}"}
|
||||
|
||||
def _accounts_write_key_file(
|
||||
self, name: str, home: str, path: str, lines: list[str]
|
||||
) -> CommandResult | None:
|
||||
"""*lines* as *name*'s key file *path*, written as *name*; None, or what failed.
|
||||
|
||||
Without lines the file goes: nothing is staged from an empty stdin.
|
||||
"""
|
||||
if not lines:
|
||||
return self._accounts_run_as(name, [["rm", "-f", "--", path]])
|
||||
staged = self._accounts_stage("".join(f"{line}\n" for line in lines))
|
||||
try:
|
||||
return self._accounts_run_as(
|
||||
name,
|
||||
[
|
||||
["mkdir", "-p", "-m", "700", "--", f"{home}/.ssh"],
|
||||
["install", "-m", "600", "--", staged, path],
|
||||
],
|
||||
)
|
||||
finally:
|
||||
self._accounts_unstage(staged)
|
||||
|
||||
def _accounts_drop_from(
|
||||
self, name: str, home: str, path: str, blobs: set[str | None]
|
||||
) -> FixStepOutcomeDict:
|
||||
"""The keys of *blobs* out of *name*'s key file *path*; no output when none was in it."""
|
||||
lines = self._accounts_key_file(name, path)
|
||||
if lines is None:
|
||||
return {"ok": False, "output": f"cannot read {path}"}
|
||||
kept = [line for line in lines if _key_blob(line) not in blobs]
|
||||
if len(kept) == len(lines):
|
||||
return {"ok": True, "output": ""}
|
||||
failed = self._accounts_write_key_file(name, home, path, kept)
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": f"{path}: {_said(failed)}"}
|
||||
return {"ok": True, "output": f"{len(lines) - len(kept)} removed from {path}"}
|
||||
|
||||
def _accounts_drop_keys(self, name: str, keys: list[str]) -> FixStepOutcomeDict:
|
||||
home = self._accounts_home(name)
|
||||
if home is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
return self._account_drop_keys(name, home, keys)
|
||||
|
||||
def _account_drop_keys(self, name: str, home: str, keys: list[str]) -> FixStepOutcomeDict:
|
||||
"""Remove exactly *keys* from *name*'s key files in *home*, as *name*.
|
||||
|
||||
A key is matched by its base64, whatever a line's options or comment;
|
||||
every other line stays. Afterwards none of *keys* may be left in
|
||||
:meth:`_account_key_files`. A driver whose host keeps keys elsewhere
|
||||
overrides this, with :meth:`_account_add_key`.
|
||||
"""
|
||||
blobs = {_key_blob(key) for key in keys}
|
||||
said: list[str] = []
|
||||
for path in authorized_keys_paths(home):
|
||||
outcome = self._accounts_drop_from(name, home, path, blobs)
|
||||
if not outcome["ok"]:
|
||||
return outcome
|
||||
said += [outcome["output"]] if outcome["output"] else []
|
||||
left = self._account_read_keys(name, home)
|
||||
if left is None:
|
||||
return {"ok": False, "output": f"cannot read the key files of {name}"}
|
||||
if any(_key_blob(line) in blobs for line in left):
|
||||
return {"ok": False, "output": f"{name} still has a key that was to go"}
|
||||
return {"ok": True, "output": "\n".join(said) or f"none of the keys is in {home}/.ssh"}
|
||||
|
||||
def _accounts_key_file(self, name: str, path: str) -> list[str] | None:
|
||||
there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30)
|
||||
if there.exit_code != 0:
|
||||
return []
|
||||
result = self.run_command(_as(name, "cat", "--", path), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
return None
|
||||
return [line for line in result.stdout.splitlines() if line.strip()]
|
||||
|
||||
def _accounts_run_as(self, name: str, commands: list[list[str]]) -> CommandResult | None:
|
||||
for argv in commands:
|
||||
result = self.run_command(_as(name, *argv), privileged=True, timeout=60)
|
||||
if result.exit_code != 0:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _account_remove_keys(self, name: str, home: str) -> FixStepOutcomeDict:
|
||||
"""Remove *name*'s key files in *home*, as *name*; then no key may be left."""
|
||||
paths = authorized_keys_paths(home)
|
||||
failed = self._accounts_run_as(name, [["rm", "-f", "--", *paths]])
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": f"cannot remove the keys of {name}: {_said(failed)}"}
|
||||
if self._account_read_keys(name, home):
|
||||
return {"ok": False, "output": f"{name} still has keys"}
|
||||
return {"ok": True, "output": f"keys of {name} removed"}
|
||||
|
||||
|
||||
def _joined(steps: list[FixStepDict]) -> FixResultDict:
|
||||
return {
|
||||
"success": bool(steps) and all(s["ok"] for s in steps),
|
||||
"steps": steps,
|
||||
"output": "\n".join(f"[{s['step']}] {s['output']}".rstrip() for s in steps),
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ACCOUNT_NAME_RE",
|
||||
"PASSWORD_SCHEMES",
|
||||
"SERVICE_SUDOERS_FILE_PREFIX",
|
||||
"SUDOERS_FILE_PREFIX",
|
||||
"LocalAccountChangeDict",
|
||||
"LocalAccountDict",
|
||||
"LocalAccountsMixin",
|
||||
"authorized_keys_paths",
|
||||
"check_account_name",
|
||||
"check_public_key",
|
||||
"service_sudoers_rule",
|
||||
"service_sudoers_rule_path",
|
||||
"sudoers_rule",
|
||||
"sudoers_rule_path",
|
||||
]
|
||||
@@ -0,0 +1,353 @@
|
||||
"""Where a host's logs go beyond it: what rsyslog forwards, which files it reads
|
||||
in, and whether it gets the journal (NetOrk/netork#2053).
|
||||
|
||||
A log source (:mod:`napalm_device_types.log_sources`) says who writes a log;
|
||||
this says who reads it on. It is read in the same command, so a reading of
|
||||
the logs a host writes also says which of them leave it.
|
||||
|
||||
**rsyslog's configuration, read as text.** Both of its syntaxes are read:
|
||||
the legacy one (``authpriv.* @@logs:514``, ``& @host``, ``:programname, isequal,
|
||||
"sshd" @host``, ``$InputFileName``) and RainerScript (``action(type="omfwd" …)``,
|
||||
``input(type="imfile" …)``, ``ruleset(…) { … }``, ``if … then``). A rule is
|
||||
*complete* when it takes every message of its ruleset -- ``*.*`` with no
|
||||
condition around it. Anything narrower is partial, and keeps its selector or
|
||||
condition for the reader to see: which facility a unit logs to is not
|
||||
computed (decided in #2053).
|
||||
|
||||
**The journal reaches rsyslog** through ``imjournal``, or through ``imuxsock``
|
||||
when journald forwards to syslog (``ForwardToSyslog``). With no setting of its
|
||||
own a host runs on its distribution's default, which ``journald.conf`` ships
|
||||
commented out: ``#ForwardToSyslog=yes``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TypedDict
|
||||
|
||||
|
||||
class ForwardRuleDict(TypedDict):
|
||||
"""One rule sending messages to another host."""
|
||||
|
||||
protocol: str # "udp", "tcp" or "relp"
|
||||
target: str # the host, as configured
|
||||
port: int | None # None: the protocol's default
|
||||
selector: str # "*.*", "authpriv.*", or the condition around it
|
||||
complete: bool # every message of its ruleset goes
|
||||
ruleset: str | None # None: the default ruleset, which gets the journal and syslog
|
||||
#: The template its messages are sent in; None: rsyslog's default, RFC 3164,
|
||||
#: which carries the sender's local time without a zone (NetOrk/netork#493).
|
||||
template: str | None
|
||||
|
||||
|
||||
class FileInputDict(TypedDict):
|
||||
"""A file rsyslog reads in (``imfile``), and the ruleset it hands it to."""
|
||||
|
||||
path: str # as configured: may hold a glob
|
||||
ruleset: str | None
|
||||
|
||||
|
||||
class RsyslogDict(TypedDict):
|
||||
rules: list[ForwardRuleDict]
|
||||
file_inputs: list[FileInputDict]
|
||||
imjournal: bool
|
||||
imuxsock: bool
|
||||
|
||||
|
||||
class LogForwardingDict(TypedDict):
|
||||
"""Where a host's logs go beyond it.
|
||||
|
||||
``journal`` is None when it cannot be told whether the journal reaches
|
||||
rsyslog: ``imuxsock`` is loaded but ``journald.conf`` says nothing.
|
||||
"""
|
||||
|
||||
rsyslog: bool # rsyslogd runs
|
||||
journal: bool | None # the journal reaches rsyslog
|
||||
rules: list[ForwardRuleDict]
|
||||
file_inputs: list[FileInputDict]
|
||||
|
||||
|
||||
#: Selectors that take every message.
|
||||
_EVERYTHING = {"*.*", "*.debug"}
|
||||
_PARAM_RE = re.compile(r'([A-Za-z][\w.]*)\s*=\s*"([^"]*)"')
|
||||
_CALL_RE = re.compile(
|
||||
r"^(?P<before>.*?)\b(?P<name>action|input|module|ruleset)\s*\((?P<args>.*)\)\s*;?$", re.S
|
||||
)
|
||||
_IF_RE = re.compile(r"^(?:else\s+)?if\s+(?P<cond>.*?)\s+then\b\s*(?P<rest>.*)$", re.S)
|
||||
_PROPERTY_RE = re.compile(r'^(?P<sel>:[^,]+,\s*!?[\w-]+,\s*"(?:[^"\\]|\\.)*")\s+(?P<action>.+)$')
|
||||
_LEGACY_RE = re.compile(r"^(?P<sel>\S+)\s+(?P<action>.+)$")
|
||||
_FORWARD_RE = re.compile(
|
||||
r"^(?:(?P<at>@@?)(?:\([^)]*\))?|:omrelp:)"
|
||||
r"(?:\[(?P<v6>[^\]]+)\]|(?P<host>[^:;\s]+))(?::(?P<port>\d+))?"
|
||||
)
|
||||
_FORWARD_TYPES = {"omfwd", "omrelp"}
|
||||
_TRUE = {"yes", "true", "1", "on"}
|
||||
|
||||
|
||||
def _uncomment(text: str) -> str:
|
||||
"""*text* without its comments: ``#`` to the end of the line, outside quotes."""
|
||||
out: list[str] = []
|
||||
quoted = commented = False
|
||||
for char in text:
|
||||
if char == "\n":
|
||||
quoted = commented = False
|
||||
elif commented:
|
||||
continue
|
||||
elif char == '"':
|
||||
quoted = not quoted
|
||||
elif char == "#" and not quoted:
|
||||
commented = True
|
||||
continue
|
||||
out.append(char)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
class _Pieces:
|
||||
"""Cuts a configuration into statements, ``{`` and ``}``: a line runs on
|
||||
while a bracket is open, and a brace outside one stands as a piece of its own."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.pieces: list[str] = []
|
||||
self.current: list[str] = []
|
||||
self.depth = 0
|
||||
self.quoted = False
|
||||
|
||||
def close(self) -> None:
|
||||
piece = "".join(self.current).strip()
|
||||
if piece:
|
||||
self.pieces.append(piece)
|
||||
self.current.clear()
|
||||
|
||||
def bracket(self, char: str) -> None:
|
||||
if char in "([":
|
||||
self.depth += 1
|
||||
elif char in ")]":
|
||||
self.depth = max(self.depth - 1, 0)
|
||||
|
||||
def feed(self, char: str) -> None:
|
||||
if char == '"':
|
||||
self.quoted = not self.quoted
|
||||
elif not self.quoted:
|
||||
self.bracket(char)
|
||||
if self.depth == 0 and char in "{}\n":
|
||||
self.close()
|
||||
if char != "\n":
|
||||
self.pieces.append(char)
|
||||
return
|
||||
self.current.append(char)
|
||||
|
||||
|
||||
def _pieces(text: str) -> list[str]:
|
||||
"""Statements, ``{`` and ``}`` in order (:class:`_Pieces`)."""
|
||||
cutter = _Pieces()
|
||||
for char in text:
|
||||
cutter.feed(char)
|
||||
cutter.close()
|
||||
return cutter.pieces
|
||||
|
||||
|
||||
def _params(args: str) -> dict[str, str]:
|
||||
return {key.lower(): value for key, value in _PARAM_RE.findall(args)}
|
||||
|
||||
|
||||
def _port(value: str | None) -> int | None:
|
||||
return int(value) if value and value.isdigit() else None
|
||||
|
||||
|
||||
class _Reader:
|
||||
"""Walks the pieces of a configuration, keeping the blocks it is in."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.parsed: RsyslogDict = {
|
||||
"rules": [],
|
||||
"file_inputs": [],
|
||||
"imjournal": False,
|
||||
"imuxsock": False,
|
||||
}
|
||||
self.stack: list[tuple[str, str | None]] = []
|
||||
self.pending: tuple[str, str | None] | None = None
|
||||
self.legacy_ruleset: str | None = None
|
||||
self.last_selector = "*.*"
|
||||
#: ``$ActionForwardDefaultTemplate``, for the legacy rules after it.
|
||||
self.legacy_template: str | None = None
|
||||
#: ``module(load="builtin:omfwd" template=…)``, for every omfwd action.
|
||||
self.module_template: str | None = None
|
||||
|
||||
def ruleset(self) -> str | None:
|
||||
names = [value for kind, value in self.stack if kind == "ruleset"]
|
||||
return names[-1] if names else self.legacy_ruleset
|
||||
|
||||
def condition(self, once: str | None) -> str | None:
|
||||
conditions = [value for kind, value in self.stack if kind == "if"]
|
||||
return once or (conditions[-1] if conditions else None)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
protocol: str,
|
||||
target: str,
|
||||
port: int | None,
|
||||
selector: str,
|
||||
once: str | None,
|
||||
template: str | None,
|
||||
) -> None:
|
||||
condition = self.condition(once)
|
||||
self.parsed["rules"].append(
|
||||
{
|
||||
"protocol": protocol,
|
||||
"target": target,
|
||||
"port": port,
|
||||
"selector": condition or selector,
|
||||
"complete": condition is None and selector in _EVERYTHING,
|
||||
"ruleset": self.ruleset(),
|
||||
"template": template,
|
||||
}
|
||||
)
|
||||
|
||||
def piece(self, piece: str) -> None:
|
||||
if piece == "{":
|
||||
self.stack.append(self.pending or ("block", None))
|
||||
self.pending = None
|
||||
return
|
||||
if piece == "}":
|
||||
if self.stack:
|
||||
self.stack.pop()
|
||||
return
|
||||
if piece == "else":
|
||||
self.pending = ("if", "else")
|
||||
return
|
||||
# A condition whose action follows on its own: the action is under it.
|
||||
once = self.pending[1] if self.pending and self.pending[0] == "if" else None
|
||||
self.pending = None
|
||||
match = _IF_RE.match(piece)
|
||||
if match:
|
||||
if match["rest"]:
|
||||
self.statement(match["rest"], once=match["cond"])
|
||||
else:
|
||||
self.pending = ("if", match["cond"])
|
||||
return
|
||||
self.statement(piece, once=once)
|
||||
|
||||
def statement(self, text: str, once: str | None) -> None:
|
||||
call = _CALL_RE.match(text)
|
||||
if call:
|
||||
self.call(call["name"], _params(call["args"]), call["before"].strip(), once)
|
||||
elif text.startswith("$"):
|
||||
self.directive(text)
|
||||
else:
|
||||
self.legacy(text, once)
|
||||
|
||||
def call(self, name: str, params: dict[str, str], before: str, once: str | None) -> None:
|
||||
if name == "module":
|
||||
self.module(params.get("load", ""))
|
||||
if params.get("load", "").removeprefix("builtin:") == "omfwd":
|
||||
self.module_template = params.get("template") or self.module_template
|
||||
elif name == "ruleset":
|
||||
self.pending = ("ruleset", params.get("name"))
|
||||
elif name == "input" and params.get("type") == "imfile" and params.get("file"):
|
||||
self.parsed["file_inputs"].append(
|
||||
{"path": params["file"], "ruleset": params.get("ruleset")}
|
||||
)
|
||||
elif name == "action":
|
||||
self.action(params, before, once)
|
||||
|
||||
def action(self, params: dict[str, str], before: str, once: str | None) -> None:
|
||||
selector = self.last_selector if before == "&" else (before or "*.*")
|
||||
self.last_selector = selector
|
||||
kind = params.get("type", "")
|
||||
if kind in _FORWARD_TYPES and params.get("target"):
|
||||
protocol = "relp" if kind == "omrelp" else params.get("protocol", "udp").lower()
|
||||
template = params.get("template") or (self.module_template if kind == "omfwd" else None)
|
||||
self.forward(
|
||||
protocol, params["target"], _port(params.get("port")), selector, once, template
|
||||
)
|
||||
|
||||
def module(self, name: str) -> None:
|
||||
if name == "imjournal":
|
||||
self.parsed["imjournal"] = True
|
||||
elif name == "imuxsock":
|
||||
self.parsed["imuxsock"] = True
|
||||
|
||||
def directive(self, text: str) -> None:
|
||||
name, _, value = text.partition(" ")
|
||||
name, value = name.lower(), value.strip()
|
||||
if name == "$modload":
|
||||
self.module(value)
|
||||
elif name == "$inputfilename" and value:
|
||||
self.parsed["file_inputs"].append({"path": value, "ruleset": self.legacy_ruleset})
|
||||
elif name == "$ruleset":
|
||||
self.legacy_ruleset = None if value == "RSYSLOG_DefaultRuleset" else value
|
||||
elif name == "$actionforwarddefaulttemplate":
|
||||
self.legacy_template = value or None
|
||||
|
||||
def legacy(self, text: str, once: str | None) -> None:
|
||||
match = _PROPERTY_RE.match(text) or _LEGACY_RE.match(text)
|
||||
if not match:
|
||||
return
|
||||
selector = self.last_selector if match["sel"] == "&" else match["sel"]
|
||||
self.last_selector = selector
|
||||
action = match["action"].strip()
|
||||
forward = _FORWARD_RE.match(action)
|
||||
if forward:
|
||||
protocol = {"@": "udp", "@@": "tcp"}.get(forward["at"] or "", "relp")
|
||||
self.forward(
|
||||
protocol,
|
||||
forward["v6"] or forward["host"],
|
||||
_port(forward["port"]),
|
||||
selector,
|
||||
once,
|
||||
self.legacy_template_of(action[forward.end() :], protocol),
|
||||
)
|
||||
|
||||
def legacy_template_of(self, rest: str, protocol: str) -> str | None:
|
||||
"""The template after a legacy rule's target (``;Name``), else the default
|
||||
set before it; RELP takes no forwarding default."""
|
||||
_, semicolon, named = rest.partition(";")
|
||||
if semicolon and named.strip():
|
||||
return named.strip()
|
||||
return self.legacy_template if protocol != "relp" else None
|
||||
|
||||
|
||||
def parse_rsyslog(text: str) -> RsyslogDict:
|
||||
"""rsyslog's configuration -- ``rsyslog.conf`` and ``rsyslog.d`` as one text --
|
||||
read for its forwarding rules, its file inputs, and the inputs that take
|
||||
the journal."""
|
||||
reader = _Reader()
|
||||
for piece in _pieces(_uncomment(text)):
|
||||
reader.piece(piece)
|
||||
return reader.parsed
|
||||
|
||||
|
||||
def journal_to_syslog(lines: list[str]) -> bool | None:
|
||||
"""Whether journald forwards to syslog, from its ``ForwardToSyslog`` lines in
|
||||
the order journald reads them: the last setting wins; with none, the
|
||||
default the distribution ships commented out; None when nothing says."""
|
||||
setting = shipped = None
|
||||
for line in lines:
|
||||
commented = line.lstrip().startswith("#")
|
||||
_, _, value = line.lstrip("# \t").partition("=")
|
||||
if commented:
|
||||
shipped = value.strip().lower() in _TRUE
|
||||
else:
|
||||
setting = value.strip().lower() in _TRUE
|
||||
return setting if setting is not None else shipped
|
||||
|
||||
|
||||
def log_forwarding(
|
||||
running: bool, rsyslog: RsyslogDict, journald_lines: list[str]
|
||||
) -> LogForwardingDict:
|
||||
"""Where a host's logs go: *rsyslog* is its configuration, read whether it runs or not."""
|
||||
if not running:
|
||||
return {"rsyslog": False, "journal": False, "rules": [], "file_inputs": []}
|
||||
journal: bool | None
|
||||
if rsyslog["imjournal"]:
|
||||
journal = True
|
||||
elif rsyslog["imuxsock"]:
|
||||
journal = journal_to_syslog(journald_lines)
|
||||
else:
|
||||
journal = False
|
||||
return {
|
||||
"rsyslog": True,
|
||||
"journal": journal,
|
||||
"rules": rsyslog["rules"],
|
||||
"file_inputs": rsyslog["file_inputs"],
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Log sources: which logs a host writes, and who writes each of them.
|
||||
|
||||
Before anything can watch a host's logs -- a person, CrowdSec, a syslog
|
||||
forwarder -- it has to know which logs there are. That 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 (NetOrk/netork#2049).
|
||||
|
||||
**Three kinds.** journald names every unit it holds entries for
|
||||
(``journalctl -F _SYSTEMD_UNIT``); only services count, not login sessions.
|
||||
``/proc/<pid>/fd`` shows the files running processes hold open, a log being a
|
||||
``*.log`` / ``*.log.N`` file or anything under ``/var/log``; ``stat -L`` on the
|
||||
descriptor gives its size and last write, also for a file inside a container,
|
||||
whose path is the container's own. The engine's own file of a container's
|
||||
output (``/var/lib/docker/containers/<id>/…``) is that container's stream, not
|
||||
a file of ``dockerd``.
|
||||
|
||||
**Who writes it.** Only a process holding the file open for writing writes
|
||||
it: the access mode in ``/proc/<pid>/fdinfo/<fd>``'s ``flags`` is ``O_WRONLY`` or
|
||||
``O_RDWR``. A reader -- CrowdSec, Promtail, rsyslog's ``imfile``, a ``tail -F``
|
||||
-- holds it too, and is no producer (NetOrk/netork#2092). ``/proc/<pid>/cgroup``
|
||||
says which systemd service or container the first writer runs in, as for
|
||||
listening sockets (:mod:`napalm_device_types.listening`). A file only readers
|
||||
hold is listed without a producer; one only readers in a container hold is left
|
||||
out, its path being the reader's view of a mount. journald's own files, files
|
||||
already deleted and a database's write-ahead log (LevelDB's ``000004.log``) are
|
||||
left out.
|
||||
|
||||
**Where they go** is read in the same round trip
|
||||
(:mod:`napalm_device_types.log_forwarding`, NetOrk/netork#2053): whether
|
||||
rsyslog runs, its configuration -- each line behind ``| ``, so that none reads
|
||||
as a section -- and journald's ``ForwardToSyslog`` lines in the order journald
|
||||
reads them.
|
||||
|
||||
**One round trip, root, and without it.** As for listening sockets the script
|
||||
goes as one ``sh -c`` argument. Without root only the login user's processes
|
||||
show their files; the command then runs again unprivileged, and the reading
|
||||
says it is not ``attributed``. A report whose end is missing raises: a list cut
|
||||
short must never read as logs that went away, and so must a host whose
|
||||
``find`` cannot list open files (busybox): it raises
|
||||
:class:`LogSourcesUnavailable`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from napalm_device_types.listening import _cgroup_paths, _container, _sections, _unit
|
||||
from napalm_device_types.log_forwarding import LogForwardingDict, log_forwarding, parse_rsyslog
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
|
||||
class LogSourceDict(TypedDict):
|
||||
"""A log the host writes: a unit's journal, a file a process holds open, or a
|
||||
container's stream as the engine keeps it.
|
||||
|
||||
``path`` is as its writer sees it: a file a container writes is named inside
|
||||
that container. Whether anything reads the log is the consumer's question.
|
||||
"""
|
||||
|
||||
kind: str # "journald", "file" or "container"
|
||||
path: str | None # the file; None for a journal
|
||||
unit: str | None # the journal's unit, or the file writer's service; without ".service"
|
||||
container_id: str | None # the full container ID: the writer's, or the stream's
|
||||
process: str | None # the first process writing the file; None when only readers hold it
|
||||
size: int | None # bytes; None for a journal, or when the file could not be read
|
||||
modified: str | None # the last write, ISO 8601 UTC; None as for size
|
||||
|
||||
|
||||
class LogSourcesDict(TypedDict):
|
||||
"""What ``LogSourcesMixin.get_log_sources`` read.
|
||||
|
||||
``attributed`` is False when the reading ran without root: only the login
|
||||
user's own processes show their files then, so a missing log means "not
|
||||
told", not "not there". ``journald`` is False on a host without systemd's
|
||||
journal, where no unit has one.
|
||||
"""
|
||||
|
||||
attributed: bool
|
||||
journald: bool
|
||||
sources: list[LogSourceDict]
|
||||
forwarding: LogForwardingDict | None # where the logs go beyond the host
|
||||
|
||||
|
||||
_BEGIN = "LOGS_BEGIN"
|
||||
_END = "LOGS_END"
|
||||
|
||||
#: One line, POSIX ``sh`` with GNU ``find`` (``-lname``, ``-printf``), read-only.
|
||||
#: The frame markers are printed in two halves so that a transport which echoes
|
||||
#: the command does not show them early. ``-printf '%p %l'`` puts the descriptor
|
||||
#: before its target, so a target with a space in it stays whole.
|
||||
LOG_SOURCES_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' LOGS_ BEGIN; "
|
||||
"if [ -d /run/systemd/system ] && command -v journalctl >/dev/null 2>&1; then "
|
||||
"j=journalctl; command -v timeout >/dev/null 2>&1 && j='timeout 30 journalctl'; "
|
||||
"echo '[journald]'; $j -F _SYSTEMD_UNIT 2>/dev/null; fi; "
|
||||
"if find / -maxdepth 0 -lname x -printf '' >/dev/null 2>&1; then "
|
||||
"o=$(find /proc/[0-9]*/fd -mindepth 1 -maxdepth 1 -type l "
|
||||
"\\( -lname '*.log' -o -lname '*.log.[0-9]*' -o -lname '/var/log/*' \\) "
|
||||
"-printf '%p %l\\n' 2>/dev/null); "
|
||||
"echo '[open]'; printf '%s\\n' \"$o\"; "
|
||||
"echo '[stat]'; printf '%s\\n' \"$o\" | cut -d' ' -f1 "
|
||||
"| xargs -r stat -L -c '%n %s %Y' 2>/dev/null; "
|
||||
"echo '[flags]'; printf '%s\\n' \"$o\" | cut -d' ' -f1 | sed 's|/fd/|/fdinfo/|' "
|
||||
"| xargs -r grep -H '^flags:' 2>/dev/null; "
|
||||
"pids=$(printf '%s\\n' \"$o\" | cut -d/ -f3 | sort -un); "
|
||||
"echo '[cgroups]'; for p in $pids; do sed \"s|^|$p |\" /proc/$p/cgroup 2>/dev/null; done; "
|
||||
"echo '[comm]'; for p in $pids; do c=$(cat /proc/$p/comm 2>/dev/null) && echo \"$p $c\"; done; "
|
||||
"else echo '[no-find]'; fi; "
|
||||
"echo '[rsyslog]'; { pidof rsyslogd || pgrep -x rsyslogd; } >/dev/null 2>&1 && echo running; "
|
||||
"echo '[rsyslog-conf]'; cat /etc/rsyslog.conf /etc/rsyslog.d/*.conf 2>/dev/null "
|
||||
"| sed 's/^/| /'; "
|
||||
"echo '[journald-conf]'; cat /etc/systemd/journald.conf "
|
||||
"/usr/lib/systemd/journald.conf.d/*.conf /run/systemd/journald.conf.d/*.conf "
|
||||
"/etc/systemd/journald.conf.d/*.conf 2>/dev/null "
|
||||
"| grep -i '^[#[:space:]]*ForwardToSyslog'; "
|
||||
"printf '%s%s\\n' LOGS_ END"
|
||||
)
|
||||
|
||||
#: ``/proc/900/fd/5`` -- the process and its descriptor.
|
||||
_FD_RE = re.compile(r"^/proc/(\d+)/fd/\d+$")
|
||||
#: ``/proc/900/fdinfo/5:flags:<tab>0102001`` -- the descriptor's open flags, octal.
|
||||
_FLAGS_RE = re.compile(r"^/proc/(\d+)/fdinfo/(\d+):flags:\s*([0-7]+)$")
|
||||
#: The access mode bits of the open flags: 0 is O_RDONLY, 1 O_WRONLY, 2 O_RDWR.
|
||||
_ACCESS_MODE = 0o3
|
||||
#: The engine's file of a container's output: json-file and local drivers.
|
||||
_STREAM_RE = re.compile(r"^/var/lib/docker/containers/([0-9a-f]{64})/")
|
||||
#: Files that are no log to read: journald's store, a file already deleted, and
|
||||
#: the write-ahead log LevelDB and RocksDB name ``000004.log``.
|
||||
_NOT_A_SOURCE = re.compile(r"^/var/log/journal/|\.journal~?$| \(deleted\)$|/\d{6}\.log$")
|
||||
_SERVICE_SUFFIX = ".service"
|
||||
_NO_FIND = "no-find"
|
||||
|
||||
|
||||
class LogSourcesUnavailable(NotImplementedError):
|
||||
"""The host's ``find`` cannot list open files (busybox); nothing to read, nothing to retry."""
|
||||
|
||||
|
||||
def _frame(output: 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 log source report in the output") from None
|
||||
return [line for line in lines[start + 1 : end] if line]
|
||||
|
||||
|
||||
def _stats(lines: list[str]) -> dict[str, tuple[int, str]]:
|
||||
"""Each descriptor's size and last write: ``/proc/900/fd/5 2048 1762250200``."""
|
||||
stats: dict[str, tuple[int, str]] = {}
|
||||
for line in lines:
|
||||
fd, _, rest = line.partition(" ")
|
||||
size, _, mtime = rest.partition(" ")
|
||||
if size.isdigit() and mtime.isdigit():
|
||||
stats[fd] = (int(size), datetime.fromtimestamp(int(mtime), UTC).isoformat())
|
||||
return stats
|
||||
|
||||
|
||||
def _names(lines: list[str]) -> dict[int, str]:
|
||||
names: dict[int, str] = {}
|
||||
for line in lines:
|
||||
pid, _, name = line.partition(" ")
|
||||
if pid.isdigit() and name:
|
||||
names[int(pid)] = name
|
||||
return names
|
||||
|
||||
|
||||
def _journals(units: list[str]) -> list[LogSourceDict]:
|
||||
services = {u[: -len(_SERVICE_SUFFIX)] for u in units if u.endswith(_SERVICE_SUFFIX)}
|
||||
return [
|
||||
{
|
||||
"kind": "journald",
|
||||
"path": None,
|
||||
"unit": unit,
|
||||
"container_id": None,
|
||||
"process": None,
|
||||
"size": None,
|
||||
"modified": None,
|
||||
}
|
||||
for unit in sorted(services)
|
||||
]
|
||||
|
||||
|
||||
def _held(lines: list[str]) -> list[tuple[int, str, str]]:
|
||||
"""(pid, descriptor, target) for every log file a process holds, by pid."""
|
||||
held = []
|
||||
for line in lines:
|
||||
fd, _, target = line.partition(" ")
|
||||
match = _FD_RE.match(fd)
|
||||
if match and target.startswith("/") and not _NOT_A_SOURCE.search(target):
|
||||
held.append((int(match.group(1)), fd, target))
|
||||
return sorted(held)
|
||||
|
||||
|
||||
def _writes(lines: list[str]) -> dict[str, bool]:
|
||||
"""Whether each descriptor is open for writing, by its ``/proc/<pid>/fd/<fd>``."""
|
||||
writes: dict[str, bool] = {}
|
||||
for line in lines:
|
||||
match = _FLAGS_RE.match(line)
|
||||
if match:
|
||||
pid, fd, flags = match.groups()
|
||||
writes[f"/proc/{pid}/fd/{fd}"] = int(flags, 8) & _ACCESS_MODE != 0
|
||||
return writes
|
||||
|
||||
|
||||
_Key = tuple[str, str | None, str]
|
||||
|
||||
|
||||
def _holders(lines: list[str], paths: dict[int, str]) -> dict[_Key, list[tuple[int, str]]]:
|
||||
"""The (pid, descriptor) pairs holding each log, by kind, container and path."""
|
||||
holders: dict[_Key, list[tuple[int, str]]] = {}
|
||||
for pid, fd, target in _held(lines):
|
||||
stream = _STREAM_RE.match(target)
|
||||
kind, container = (
|
||||
("container", stream.group(1)) if stream else ("file", _container(paths.get(pid)))
|
||||
)
|
||||
holders.setdefault((kind, container, target), []).append((pid, fd))
|
||||
return holders
|
||||
|
||||
|
||||
def _writer(held: list[tuple[int, str]], writes: dict[str, bool] | None) -> int | None:
|
||||
"""The first process writing; the first holding for a report without flags,
|
||||
as an older command printed it."""
|
||||
if writes is None:
|
||||
return held[0][0]
|
||||
return next((pid for pid, fd in held if writes.get(fd)), None)
|
||||
|
||||
|
||||
def _producer(
|
||||
kind: str, writer: int | None, paths: dict[int, str], names: dict[int, str]
|
||||
) -> tuple[str | None, str | None]:
|
||||
"""The writer's service and name; a stream's service is its container."""
|
||||
if writer is None:
|
||||
return None, None
|
||||
return (_unit(paths.get(writer)) if kind == "file" else None), names.get(writer)
|
||||
|
||||
|
||||
def _files(sections: dict[str, list[str]]) -> list[LogSourceDict]:
|
||||
stats = _stats(sections.get("stat", []))
|
||||
paths = _cgroup_paths(sections.get("cgroups", []))
|
||||
names = _names(sections.get("comm", []))
|
||||
writes = _writes(sections["flags"]) if "flags" in sections else None
|
||||
found: list[LogSourceDict] = []
|
||||
for (kind, container, target), held in _holders(sections.get("open", []), paths).items():
|
||||
writer = _writer(held, writes)
|
||||
if writer is None and kind == "file" and container is not None:
|
||||
continue # a reader's view of a mount, inside its container
|
||||
unit, process = _producer(kind, writer, paths, names)
|
||||
size, modified = next((stats[fd] for _, fd in held if fd in stats), (None, None))
|
||||
found.append(
|
||||
{
|
||||
"kind": kind,
|
||||
"path": target,
|
||||
"unit": unit,
|
||||
"container_id": container,
|
||||
"process": process,
|
||||
"size": size,
|
||||
"modified": modified,
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def _order(source: LogSourceDict) -> tuple[str, str, str]:
|
||||
return (source["kind"], source["container_id"] or "", source["path"] or source["unit"] or "")
|
||||
|
||||
|
||||
def parse_log_sources(output: str) -> tuple[bool, list[LogSourceDict]]:
|
||||
"""Parse what :data:`LOG_SOURCES_COMMAND` printed: whether the host has a
|
||||
journal, and every source, sorted by kind, container and name.
|
||||
|
||||
:raises LogSourcesUnavailable: when the host has no GNU ``find``.
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
if _NO_FIND in sections:
|
||||
raise LogSourcesUnavailable("the host's find cannot list open files (no GNU find)")
|
||||
journald = "journald" in sections
|
||||
sources = _journals(sections.get("journald", [])) + _files(sections)
|
||||
return journald, sorted(sources, key=_order)
|
||||
|
||||
|
||||
def _reading(output: str, *, attributed: bool) -> LogSourcesDict:
|
||||
journald, sources = parse_log_sources(output)
|
||||
forwarding = parse_log_forwarding(output)
|
||||
return {
|
||||
"attributed": attributed,
|
||||
"journald": journald,
|
||||
"sources": sources,
|
||||
"forwarding": forwarding,
|
||||
}
|
||||
|
||||
|
||||
def parse_log_forwarding(output: str) -> LogForwardingDict | None:
|
||||
"""Parse where the logs go from what :data:`LOG_SOURCES_COMMAND` printed;
|
||||
None for a report without the sections, as an older command printed it.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
if "rsyslog" not in sections:
|
||||
return None
|
||||
config = "\n".join(
|
||||
line[2:] if line.startswith("| ") else line[1:] for line in sections.get("rsyslog-conf", [])
|
||||
)
|
||||
running = "running" in sections["rsyslog"]
|
||||
return log_forwarding(running, parse_rsyslog(config), sections.get("journald-conf", []))
|
||||
|
||||
|
||||
class LogSourcesMixin:
|
||||
"""Adds :meth:`get_log_sources` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse
|
||||
are the same everywhere, so they are concrete here, and a driver supplies
|
||||
only :meth:`_run_log_sources_command` -- how a command reaches its host, and
|
||||
how it gains root there. Mixed in by the drivers that can, so
|
||||
``hasattr(driver, "get_log_sources")`` stays truthful.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root
|
||||
when *privileged*. The command is a single ``sh -c`` invocation."""
|
||||
...
|
||||
|
||||
def get_log_sources(self) -> LogSourcesDict:
|
||||
"""
|
||||
Returns every log the host writes, with the service or container writing it.
|
||||
|
||||
* attributed (bool) - read as root, so every process's files are listed
|
||||
* journald (bool) - the host keeps systemd's journal
|
||||
* sources (list) - see :class:`~napalm_device_types.models.LogSourceDict`
|
||||
* forwarding (dict) - where the logs go beyond the host, see
|
||||
:class:`~napalm_device_types.log_forwarding.LogForwardingDict`
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"attributed": True,
|
||||
"journald": True,
|
||||
"sources": [
|
||||
{"kind": "journald", "path": None, "unit": "nginx",
|
||||
"container_id": None, "process": None, "size": None, "modified": None},
|
||||
{"kind": "file", "path": "/var/log/nginx/access.log", "unit": "nginx",
|
||||
"container_id": None, "process": "nginx", "size": 2048,
|
||||
"modified": "2026-11-04T09:56:40+00:00"},
|
||||
],
|
||||
}
|
||||
|
||||
:raises LogSourcesUnavailable: if the host has no GNU ``find``.
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(LOG_SOURCES_COMMAND)}"
|
||||
try:
|
||||
output = self._run_log_sources_command(command, privileged=True)
|
||||
return _reading(output, attributed=True)
|
||||
except ValueError:
|
||||
pass
|
||||
output = self._run_log_sources_command(command, privileged=False)
|
||||
return _reading(output, attributed=False)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""MAC-based access control, per SSID on an AP and per port on a switch.
|
||||
|
||||
The reader is identical either way; only the writer is AP-specific so far.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: these are contracts, not placeholders.
|
||||
Nothing exists at runtime until a concrete driver implements it, so mixing
|
||||
this class in can never shadow a working implementation from a sibling base.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import MACACLDict
|
||||
|
||||
|
||||
class MacAclMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_mac_acl(self) -> dict[str, MACACLDict]:
|
||||
"""
|
||||
Returns the MAC-address-based access control lists configured per SSID.
|
||||
|
||||
Keys are SSID names. Each value contains:
|
||||
|
||||
* name (string) - SSID name (repeated for convenience)
|
||||
* policy (string) - ACL mode:
|
||||
|
||||
* ``"allow"`` – whitelist: only listed MACs may associate
|
||||
* ``"deny"`` – blacklist: listed MACs are blocked
|
||||
* ``"disabled"`` – no MAC filtering active
|
||||
|
||||
* entries (list) - ACL entries, each with:
|
||||
|
||||
* mac (string) - MAC address (normalised, colon-separated)
|
||||
* action (string) - ``"allow"`` or ``"deny"``
|
||||
* description (string) - optional human-readable label
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"CorpWiFi": {
|
||||
"name": "CorpWiFi",
|
||||
"policy": "allow",
|
||||
"entries": [
|
||||
{"mac": "AA:BB:CC:DD:EE:01", "action": "allow",
|
||||
"description": "CEO-Laptop"},
|
||||
{"mac": "AA:BB:CC:DD:EE:02", "action": "allow",
|
||||
"description": "CFO-Laptop"},
|
||||
],
|
||||
},
|
||||
"GuestNet": {
|
||||
"name": "GuestNet",
|
||||
"policy": "deny",
|
||||
"entries": [
|
||||
{"mac": "DE:AD:BE:EF:00:01", "action": "deny",
|
||||
"description": "blocked device"},
|
||||
],
|
||||
},
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
def push_mac_acl(self, ssid_name: str, mode: str, macs: list[str]) -> None:
|
||||
"""
|
||||
Rewrites the MAC-address access control list for a single SSID.
|
||||
|
||||
Full-rebuild semantics: replaces whatever ACL state currently exists
|
||||
for *ssid_name* with *mode* + *macs* — not a diff/patch.
|
||||
|
||||
:param ssid_name: SSID name to apply the ACL to.
|
||||
:param mode: ``"off"`` | ``"whitelist"`` | ``"blacklist"``.
|
||||
:param macs: MAC addresses for the active list. Ignored when ``mode == "off"``.
|
||||
:raises NotImplementedError: If the driver does not support MAC ACL push.
|
||||
|
||||
Example::
|
||||
|
||||
macs = ["AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"]
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", macs)
|
||||
driver.push_mac_acl("GuestNet", "off", [])
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Abstract base class for server baseboard management controllers (BMCs).
|
||||
|
||||
Usage::
|
||||
|
||||
from napalm_device_types import ManagementControllerDriver
|
||||
|
||||
class IdracDriver(ManagementControllerDriver):
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.models import (
|
||||
EventLogEntryDict,
|
||||
FirmwareDict,
|
||||
HardwareInventoryDict,
|
||||
ManagementProtocolsDict,
|
||||
PowerAction,
|
||||
PowerStateDict,
|
||||
)
|
||||
|
||||
|
||||
class ManagementControllerDriver(DeviceTypeDriver):
|
||||
"""
|
||||
Abstract intermediate driver for the management controller of a server
|
||||
(e.g. Supermicro BMC, Dell iDRAC, HPE iLO, Lenovo XCC), reached over
|
||||
Redfish or IPMI rather than SSH.
|
||||
|
||||
A BMC is not the server it manages. ``reboot_host`` restarts the BMC
|
||||
itself (Redfish ``Manager.Reset``), never the managed server; the server is
|
||||
switched on, off and restarted through :meth:`set_power_state`.
|
||||
|
||||
The BMC's sensors (temperatures, fans, PSU power) come through NAPALM's
|
||||
``get_environment``, with ``cpu`` and ``memory`` empty: a BMC does not know
|
||||
the load of the operating system on its server. There is no
|
||||
``HealthMetricsMixin`` here -- that is SNMP's -- and
|
||||
``CommandChannelMixin`` stays unimplemented: a BMC offers no shell to run a
|
||||
command in.
|
||||
"""
|
||||
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "management_controller"
|
||||
TYPE_LABEL: str = "Management Controller"
|
||||
USES_SSH: bool = False
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_power_state(self) -> PowerStateDict:
|
||||
"""
|
||||
Returns the managed server's power state.
|
||||
|
||||
* state (string) - ``"On"``, ``"Off"``, ``"PoweringOn"`` or ``"PoweringOff"``
|
||||
* actions (list) - the :data:`~napalm_device_types.models.PowerAction`
|
||||
values the BMC accepts right now
|
||||
|
||||
Example::
|
||||
|
||||
{"state": "On", "actions": ["GracefulShutdown", "ForceOff", "ForceRestart"]}
|
||||
"""
|
||||
...
|
||||
|
||||
def set_power_state(self, action: PowerAction) -> None:
|
||||
"""
|
||||
Switches, shuts down or restarts the managed server.
|
||||
|
||||
Returns once the BMC has accepted the request; the server takes its
|
||||
time. ``GracefulShutdown`` and ``GracefulRestart`` ask the operating
|
||||
system (ACPI) and may be ignored by it.
|
||||
|
||||
:param action: One of ``On``, ``GracefulShutdown``, ``ForceOff``,
|
||||
``GracefulRestart``, ``ForceRestart`` or ``PowerCycle``.
|
||||
:raises ValueError: If *action* is not one of them.
|
||||
:raises RuntimeError: If the BMC refuses it, e.g. ``On`` for a
|
||||
server that is already on.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_hardware_inventory(self) -> HardwareInventoryDict:
|
||||
"""
|
||||
Returns the managed server's hardware: CPUs, DIMMs, drives, power
|
||||
supplies and NICs, with the server's serial number, its SMBIOS
|
||||
system UUID and the MAC address of each NIC -- what ties the BMC to
|
||||
the operating system running on the server.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"manufacturer": "Dell Inc.",
|
||||
"model": "PowerEdge R650",
|
||||
"serial_number": "7XK2Q93",
|
||||
"system_uuid": "4c4c4544-0058-4b10-8032-b7c04f513933",
|
||||
"cpus": [{"socket": "CPU.Socket.1", "model": "Intel(R) Xeon(R) Silver 4314",
|
||||
"cores": 16, "threads": 32, "status": "OK"}],
|
||||
"memory": [...],
|
||||
"drives": [...],
|
||||
"power_supplies": [...],
|
||||
"nics": [{"name": "NIC.Integrated.1-1", "mac_address": "b0:7b:25:de:1a:40",
|
||||
"speed_mbps": 10000, "link_up": True}],
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
def get_event_log(self, limit: int = 500) -> list[EventLogEntryDict]:
|
||||
"""
|
||||
Returns the BMC's system event log (SEL, Lifecycle Log, IML),
|
||||
newest first.
|
||||
|
||||
:param limit: At most this many entries.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_firmware_inventory(self) -> list[FirmwareDict]:
|
||||
"""
|
||||
Returns every firmware component the BMC reports: its own, the
|
||||
BIOS, storage controllers, NICs, power supplies.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{"name": "Integrated Dell Remote Access Controller",
|
||||
"version": "7.00.00.172", "updateable": True},
|
||||
{"name": "BIOS", "version": "1.13.2", "updateable": True},
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_management_protocols(self) -> ManagementProtocolsDict:
|
||||
"""
|
||||
Returns what the BMC itself listens on: IPMI, SSH, HTTP, HTTPS,
|
||||
SNMP, the KVM console and virtual media, each with whether it is
|
||||
enabled and its port.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"ipmi": {"enabled": False, "port": 623},
|
||||
"ssh": {"enabled": True, "port": 22},
|
||||
"http": {"enabled": False, "port": 80},
|
||||
"https": {"enabled": True, "port": 443},
|
||||
"snmp": {"enabled": False, "port": 161},
|
||||
"kvm": {"enabled": True, "port": 5900},
|
||||
"virtual_media": {"enabled": True, "port": None},
|
||||
}
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Abstract base class for networked media players.
|
||||
|
||||
Usage::
|
||||
|
||||
from napalm_device_types import MediaDriver
|
||||
|
||||
class SonosDriver(MediaDriver):
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
|
||||
|
||||
class MediaDriver(DeviceTypeDriver):
|
||||
"""
|
||||
Abstract intermediate driver for speakers, streamers and media renderers
|
||||
(e.g. Sonos, Chromecast, Squeezebox, UPnP/DLNA renderers).
|
||||
|
||||
Like :class:`~napalm_device_types.phone.PhoneDriver`, this exists so an
|
||||
endpoint stops being filed under ``AccessPointDriver`` for want of anywhere
|
||||
better. A speaker has no SSIDs, no radio configuration and no AP profile; it
|
||||
has a transport state and a volume.
|
||||
"""
|
||||
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "media"
|
||||
TYPE_LABEL: str = "Media"
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_playback_state(self) -> dict[str, Any]:
|
||||
"""
|
||||
Returns the transport state of the renderer.
|
||||
|
||||
* state (string) - ``"playing"``, ``"paused"``, ``"stopped"``, or ``"transitioning"``
|
||||
* source (string) - input or service currently selected
|
||||
"""
|
||||
...
|
||||
|
||||
def get_volume(self) -> int:
|
||||
"""Returns the current output volume, 0-100."""
|
||||
...
|
||||
|
||||
def set_volume(self, level: int) -> None:
|
||||
"""Sets the output volume, 0-100."""
|
||||
...
|
||||
|
||||
def get_zone_info(self) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Returns the zones or groups this renderer participates in.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - zone/room name
|
||||
* coordinator (bool) - whether this device leads the group
|
||||
* members (list) - names of the other devices in the group
|
||||
"""
|
||||
...
|
||||
+876
-255
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
"""Address translation and VPN tunnels.
|
||||
|
||||
A home gateway does a subset of what a firewall does, and these readers are
|
||||
where the sets overlap exactly.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: these are contracts, not placeholders.
|
||||
Nothing exists at runtime until a concrete driver implements it, so mixing
|
||||
this class in can never shadow a working implementation from a sibling base.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import NATTranslationDict, PortForwardDict, VPNTunnelDict
|
||||
|
||||
|
||||
class NatVpnMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_nat_translations(self) -> list[NATTranslationDict]:
|
||||
"""
|
||||
Returns a list of active NAT translation entries.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* protocol (string) - ``"tcp"``, ``"udp"``, ``"icmp"``
|
||||
* inside_local (string) - original source address (IP or IP:port)
|
||||
* inside_global (string) - translated source address (IP or IP:port)
|
||||
* outside_local (string) - destination as seen from inside
|
||||
* outside_global (string) - actual destination address
|
||||
* age (float) - translation entry age in seconds
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"protocol": "tcp",
|
||||
"inside_local": "192.168.1.10:54321",
|
||||
"inside_global": "203.0.113.1:54321",
|
||||
"outside_local": "1.1.1.1:443",
|
||||
"outside_global": "1.1.1.1:443",
|
||||
"age": 120.5,
|
||||
}
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_port_forwards(self) -> list[PortForwardDict]:
|
||||
"""
|
||||
Returns the port forwards that let traffic in from the WAN.
|
||||
|
||||
A port forward here means destination NAT on an interface facing
|
||||
the internet: whoever reaches the external port is let through to
|
||||
``internal_ip``. A redirect between internal networks is
|
||||
destination NAT as well, but it is **not** a port forward and must
|
||||
be left out -- callers read every entry as "this host is reachable
|
||||
from outside". So are rules that only exempt traffic from
|
||||
redirection.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - the rule's description/name
|
||||
* protocol (string) - ``"TCP"`` or ``"UDP"``; a rule for both is
|
||||
two entries. ``"ANY"`` forwards every protocol
|
||||
* external_port (int) - the WAN-side port; the first of a range,
|
||||
``0`` for every port (a whole host forwarded)
|
||||
* internal_ip (string) - the host the traffic is forwarded to
|
||||
* internal_port (int) - the port on that host
|
||||
* enabled (bool) - whether the rule is currently active
|
||||
* remote_host (string, optional) - restricts the forward to a specific
|
||||
remote source address; empty/absent means "any"
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "Webserver HTTPS",
|
||||
"protocol": "TCP",
|
||||
"external_port": 443,
|
||||
"internal_ip": "192.168.1.10",
|
||||
"internal_port": 443,
|
||||
"enabled": True,
|
||||
}
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_vpn_tunnels(self) -> dict[str, VPNTunnelDict]:
|
||||
"""
|
||||
Returns the status of VPN tunnels.
|
||||
|
||||
Keys are tunnel names or identifiers. Each value contains:
|
||||
|
||||
* type (string) - tunnel type: ``"IPsec"``, ``"SSL"``, ``"GRE"``, ``"WireGuard"``
|
||||
* local_endpoint (string) - local tunnel endpoint IP
|
||||
* remote_endpoint (string) - remote tunnel endpoint IP
|
||||
* is_up (bool) - whether the tunnel is operationally up
|
||||
* uptime (int) - tunnel uptime in seconds (0 if down)
|
||||
* bytes_in (int) - total bytes received through the tunnel
|
||||
* bytes_out (int) - total bytes sent through the tunnel
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"vpn-to-branch": {
|
||||
"type": "IPsec",
|
||||
"local_endpoint": "203.0.113.1",
|
||||
"remote_endpoint": "198.51.100.1",
|
||||
"is_up": True,
|
||||
"uptime": 86400,
|
||||
"bytes_in": 104857600,
|
||||
"bytes_out": 52428800,
|
||||
}
|
||||
}
|
||||
"""
|
||||
...
|
||||
@@ -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",
|
||||
]
|
||||
+144
-377
@@ -10,27 +10,24 @@ Usage::
|
||||
...
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import List, Optional
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
from napalm_device_types._ucd_metrics import IF_SKIP_DEFAULT, collect_ucd_metrics
|
||||
from napalm_device_types.health_metrics import HealthMetricsMixin
|
||||
from napalm_device_types.models import (
|
||||
ApplyUpdatesResultDict,
|
||||
CronJobDict,
|
||||
DeviceActionResultDict,
|
||||
DockerInfoDict,
|
||||
HealthMetricsDict,
|
||||
PackageDict,
|
||||
ProcessDict,
|
||||
ServiceDict,
|
||||
SNMPConfigDict,
|
||||
UpdateDict,
|
||||
UserDict,
|
||||
)
|
||||
from napalm_device_types.packages import PackageManagementMixin
|
||||
from napalm_device_types.services import ServiceControlMixin
|
||||
from napalm_device_types.updates import UpdateMixin
|
||||
|
||||
|
||||
class OSDriver(DeviceTypeDriver):
|
||||
TYPE_LABEL: str = "OS"
|
||||
class OSDriver(
|
||||
UpdateMixin, ServiceControlMixin, PackageManagementMixin, HealthMetricsMixin, DeviceTypeDriver
|
||||
):
|
||||
"""
|
||||
Abstract intermediate driver for general-purpose operating systems
|
||||
(e.g. Linux, BSD, macOS).
|
||||
@@ -39,391 +36,161 @@ class OSDriver(DeviceTypeDriver):
|
||||
operations that concrete drivers must implement.
|
||||
"""
|
||||
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`. A driver for another
|
||||
#: OS sets its own (``ROLE = "windows"``), which replaces this one.
|
||||
ROLE: str = "linux"
|
||||
TYPE_LABEL: str = "OS"
|
||||
|
||||
# Interfaces matching this pattern are excluded from health-metric collection.
|
||||
_SNMP_SKIP_IF: re.Pattern = IF_SKIP_DEFAULT
|
||||
# Set True for drivers where the out-error counter actually reports drops (e.g. OPNsense).
|
||||
_SNMP_TX_ERR_IS_DROP: bool = False
|
||||
|
||||
@classmethod
|
||||
async def get_health_metrics(cls, snmp_get, snmp_walk) -> HealthMetricsDict:
|
||||
"""Collect SNMP health metrics (CPU, memory, uptime, load, interfaces).
|
||||
|
||||
:param snmp_get: async callable ``(oid: str) -> Optional[str]``
|
||||
:param snmp_walk: async callable ``(oid: str) -> Dict[str, str]``
|
||||
"""
|
||||
return await collect_ucd_metrics(
|
||||
snmp_get, snmp_walk,
|
||||
tx_err_is_drop=cls._SNMP_TX_ERR_IS_DROP,
|
||||
if_skip=cls._SNMP_SKIP_IF,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Package management
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_packages(self) -> List[PackageDict]:
|
||||
"""
|
||||
Returns a list of all installed software packages.
|
||||
if TYPE_CHECKING:
|
||||
# ------------------------------------------------------------------
|
||||
# Service management
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
Each entry contains:
|
||||
# ------------------------------------------------------------------
|
||||
# Users
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
* name (string) - package name
|
||||
* version (string) - installed version string
|
||||
* installed (bool) - always ``True`` for this method
|
||||
* description (string) - short package description
|
||||
* size (int) - installed size in bytes; ``0`` if unavailable
|
||||
* source (string) - package source / repository name; empty string if unavailable
|
||||
def get_os_users(self) -> list[UserDict]:
|
||||
"""
|
||||
Returns a list of local OS user accounts.
|
||||
|
||||
Example::
|
||||
Each entry contains:
|
||||
|
||||
[
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"version": "1:9.2p1-2+deb12u2",
|
||||
"installed": True,
|
||||
"description": "secure shell (SSH) server, for secure access from remote machines",
|
||||
"size": 524288,
|
||||
"source": "Debian",
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
* username (string) - login name
|
||||
* uid (int) - numeric user ID
|
||||
* gid (int) - primary group ID
|
||||
* home (string) - home directory path
|
||||
* shell (string) - login shell path
|
||||
* groups (list of strings) - all supplementary group names
|
||||
|
||||
def get_pending_updates(self) -> List[UpdateDict]:
|
||||
"""
|
||||
Returns a list of packages that have a newer version available.
|
||||
Example::
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - package name
|
||||
* current_version (string) - currently installed version
|
||||
* new_version (string) - version available in the repository
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"current_version": "1:9.2p1-2+deb12u1",
|
||||
"new_version": "1:9.2p1-2+deb12u2",
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def apply_updates(self, packages: List[str]) -> ApplyUpdatesResultDict:
|
||||
"""
|
||||
Upgrades the given packages to the newest available version.
|
||||
|
||||
Only packages that are already installed may be upgraded; this method
|
||||
does **not** install new packages. Pass an empty list to upgrade
|
||||
**all** packages that have pending updates.
|
||||
|
||||
:param packages: List of package names to upgrade. Each name must
|
||||
match ``^[a-zA-Z0-9_\\-\\+\\.]+$``; a :exc:`ValueError` is raised
|
||||
for any name that does not conform.
|
||||
:returns: A dict with:
|
||||
|
||||
* success (bool) – ``True`` if the package manager exited without error
|
||||
* output (string) – combined stdout / stderr from the package manager
|
||||
* error (string, optional) – short error message when *success* is ``False``
|
||||
|
||||
:raises ValueError: If any package name fails the safety check.
|
||||
|
||||
Example::
|
||||
|
||||
result = driver.apply_updates(["openssh-server", "curl"])
|
||||
# → {"success": True, "output": "Reading package lists...\\n..."}
|
||||
|
||||
# Upgrade everything:
|
||||
result = driver.apply_updates([])
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Service management
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_services(self) -> List[ServiceDict]:
|
||||
"""
|
||||
Returns a list of system services and their current state.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - service unit name (without ``.service`` suffix)
|
||||
* running (bool) - ``True`` if the service is currently active
|
||||
* enabled (bool) - ``True`` if the service starts automatically on boot
|
||||
* pid (int) - main process ID; ``0`` if not running
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "ssh",
|
||||
"running": True,
|
||||
"enabled": True,
|
||||
"pid": 1234,
|
||||
},
|
||||
{
|
||||
"name": "cron",
|
||||
"running": True,
|
||||
"enabled": True,
|
||||
"pid": 5678,
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Users
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_users(self) -> List[UserDict]:
|
||||
"""
|
||||
Returns a list of local OS user accounts.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* username (string) - login name
|
||||
* uid (int) - numeric user ID
|
||||
* gid (int) - primary group ID
|
||||
* home (string) - home directory path
|
||||
* shell (string) - login shell path
|
||||
* groups (list of strings) - all supplementary group names
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"username": "admin",
|
||||
"uid": 1000,
|
||||
"gid": 1000,
|
||||
"home": "/home/admin",
|
||||
"shell": "/bin/bash",
|
||||
"groups": ["sudo", "docker", "adm"],
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Processes
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_processes(self) -> List[ProcessDict]:
|
||||
"""
|
||||
Returns a snapshot of currently running processes.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* pid (int) - process ID
|
||||
* ppid (int) - parent process ID
|
||||
* user (string) - effective user name
|
||||
* cpu (float) - CPU utilisation percentage
|
||||
* memory (float) - RSS as a percentage of total RAM
|
||||
* vsz (int) - virtual memory size in KiB
|
||||
* rss (int) - resident set size in KiB
|
||||
* tty (string) - controlling terminal; empty string if none
|
||||
* state (string) - process state: ``"R"`` running, ``"S"`` sleeping,
|
||||
``"D"`` uninterruptible, ``"Z"`` zombie, ``"T"`` stopped, etc.
|
||||
* started (string) - start time as printed by ``ps`` (e.g. ``"12:34"`` or ``"May28"``)
|
||||
* command (string) - full command line
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"pid": 1,
|
||||
"ppid": 0,
|
||||
"user": "root",
|
||||
"cpu": 0.0,
|
||||
"memory": 0.1,
|
||||
"vsz": 168576,
|
||||
"rss": 13312,
|
||||
"tty": "",
|
||||
"state": "S",
|
||||
"started": "May28",
|
||||
"command": "/sbin/init",
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Cron jobs
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_cron_jobs(self) -> List[CronJobDict]:
|
||||
"""
|
||||
Returns scheduled cron tasks from all user crontabs and ``/etc/cron.d``.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* user (string) - owner of the crontab entry
|
||||
* schedule (string) - five-field cron expression (e.g. ``"0 * * * *"``)
|
||||
* command (string) - shell command to execute
|
||||
* description (string, optional) - inline comment text if present
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"user": "root",
|
||||
"schedule": "0 4 * * *",
|
||||
"command": "/usr/local/bin/backup.sh",
|
||||
"description": "nightly backup",
|
||||
},
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# SNMP
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_snmp_config(self) -> Optional[SNMPConfigDict]:
|
||||
"""
|
||||
Returns the SNMP agent configuration currently active on the device,
|
||||
or ``None`` if no SNMP daemon is running or detectable.
|
||||
|
||||
The returned dictionary contains:
|
||||
|
||||
* running (bool) - whether the SNMP daemon is currently active
|
||||
* community (string) - the read community string (e.g. ``"public"``)
|
||||
* port (int) - the UDP port the agent listens on (default ``161``)
|
||||
* version (string) - highest supported SNMP version: ``"1"``, ``"2c"``, or ``"3"``
|
||||
|
||||
Example::
|
||||
|
||||
# snmpd running with community "public":
|
||||
{
|
||||
"running": True,
|
||||
"community": "public",
|
||||
"port": 161,
|
||||
"version": "2c",
|
||||
}
|
||||
|
||||
# snmpd not installed / not running:
|
||||
None
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Docker
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_docker_info(self) -> DockerInfoDict:
|
||||
"""
|
||||
Returns information about the local Docker environment.
|
||||
|
||||
If Docker is not installed or the current user lacks access to the
|
||||
Docker socket, returns ``{"available": False}``. When the user has
|
||||
no socket permission, ``permission_denied`` is additionally set to
|
||||
``True``.
|
||||
|
||||
When Docker is available the dict contains:
|
||||
|
||||
* available (bool) - always ``True``
|
||||
* version (string) - Docker Engine version string
|
||||
* containers (list) - all containers (running and stopped), each with:
|
||||
|
||||
* id (string) - short container ID
|
||||
* name (string) - container name(s)
|
||||
* image (string) - image reference
|
||||
* image_version (string) - OCI ``org.opencontainers.image.version`` label; empty if absent
|
||||
* command (string) - entrypoint / command string
|
||||
* created (string) - creation timestamp string
|
||||
* status (string) - human-readable status (e.g. ``"Up 3 hours"``)
|
||||
* ports (string) - port mapping string
|
||||
* state (string) - ``"running"``, ``"exited"``, ``"paused"``, etc.
|
||||
|
||||
* images (list) - local images, each with:
|
||||
|
||||
* id (string) - short image ID
|
||||
* repository (string) - image repository
|
||||
* tag (string) - image tag
|
||||
* size (string) - human-readable size string (e.g. ``"187MB"``)
|
||||
* created (string) - creation timestamp string
|
||||
* version (string) - OCI ``org.opencontainers.image.version`` label; empty if absent
|
||||
|
||||
* volumes (list) - Docker volumes, each with:
|
||||
|
||||
* name (string) - volume name
|
||||
* driver (string) - volume driver
|
||||
* mountpoint (string) - host filesystem path
|
||||
* scope (string) - ``"local"`` or ``"global"``
|
||||
|
||||
* networks (list) - Docker networks, each with:
|
||||
|
||||
* id (string) - short network ID
|
||||
* name (string) - network name
|
||||
* driver (string) - network driver (e.g. ``"bridge"``, ``"host"``, ``"overlay"``)
|
||||
* scope (string) - network scope
|
||||
* ipv6 (string) - ``"true"`` if IPv6 is enabled
|
||||
* internal (string) - ``"true"`` if the network is internal
|
||||
|
||||
* outdated_images (list of strings) - image names where the local digest
|
||||
differs from the latest remote digest; empty list if all images are
|
||||
current or update checks could not be performed.
|
||||
|
||||
Example::
|
||||
|
||||
# Docker not installed:
|
||||
{"available": False}
|
||||
|
||||
# Docker installed, no socket permission:
|
||||
{"available": False, "permission_denied": True}
|
||||
|
||||
# Docker available:
|
||||
{
|
||||
"available": True,
|
||||
"version": "Docker version 27.3.1, build ce12230",
|
||||
"containers": [
|
||||
[
|
||||
{
|
||||
"id": "a1b2c3d4e5f6",
|
||||
"name": "my-app",
|
||||
"image": "nginx:latest",
|
||||
"image_version": "1.27.0",
|
||||
"command": "nginx -g 'daemon off;'",
|
||||
"created": "2026-05-28 10:00:00 +0000 UTC",
|
||||
"status": "Up 3 days",
|
||||
"ports": "0.0.0.0:80->80/tcp",
|
||||
"state": "running",
|
||||
"username": "admin",
|
||||
"uid": 1000,
|
||||
"gid": 1000,
|
||||
"home": "/home/admin",
|
||||
"shell": "/bin/bash",
|
||||
"groups": ["sudo", "docker", "adm"],
|
||||
},
|
||||
],
|
||||
"images": [...],
|
||||
"volumes": [],
|
||||
"networks": [...],
|
||||
"outdated_images": ["nginx:latest"],
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Generic device actions
|
||||
# ------------------------------------------------------------------
|
||||
# ------------------------------------------------------------------
|
||||
# Processes
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run_device_action(self, action: str) -> DeviceActionResultDict:
|
||||
"""
|
||||
Executes a named administrative action on the device.
|
||||
def get_processes(self) -> list[ProcessDict]:
|
||||
"""
|
||||
Returns a snapshot of currently running processes.
|
||||
|
||||
This method is an extensibility point for driver-specific one-off
|
||||
operations that do not fit any other NAPALM API method. Each driver
|
||||
documents the action names it supports.
|
||||
Each entry contains:
|
||||
|
||||
:param action: Action identifier string (e.g. ``"fix_docker_permissions"``).
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If ``action`` is not a recognised action name for
|
||||
this driver.
|
||||
* pid (int) - process ID
|
||||
* ppid (int) - parent process ID
|
||||
* user (string) - effective user name
|
||||
* cpu (float) - CPU utilisation percentage
|
||||
* memory (float) - RSS as a percentage of total RAM
|
||||
* vsz (int) - virtual memory size in KiB
|
||||
* rss (int) - resident set size in KiB
|
||||
* tty (string) - controlling terminal; empty string if none
|
||||
* state (string) - process state: ``"R"`` running, ``"S"`` sleeping,
|
||||
``"D"`` uninterruptible, ``"Z"`` zombie, ``"T"`` stopped, etc.
|
||||
* started (string) - start time as printed by ``ps`` (e.g. ``"12:34"`` or ``"May28"``)
|
||||
* command (string) - full command line
|
||||
|
||||
:returns: A dict with:
|
||||
Example::
|
||||
|
||||
* success (bool) – ``True`` if the action completed without error
|
||||
* output (string) – human-readable output or status message
|
||||
[
|
||||
{
|
||||
"pid": 1,
|
||||
"ppid": 0,
|
||||
"user": "root",
|
||||
"cpu": 0.0,
|
||||
"memory": 0.1,
|
||||
"vsz": 168576,
|
||||
"rss": 13312,
|
||||
"tty": "",
|
||||
"state": "S",
|
||||
"started": "May28",
|
||||
"command": "/sbin/init",
|
||||
},
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
Example::
|
||||
# ------------------------------------------------------------------
|
||||
# SNMP
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
result = driver.run_device_action("fix_docker_permissions")
|
||||
# → {"success": True, "output": "Added 'pi' to the docker group. Reconnect..."}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
def get_snmp_config(self) -> SNMPConfigDict | None:
|
||||
"""
|
||||
Returns the SNMP agent configuration currently active on the device,
|
||||
or ``None`` if no SNMP daemon is running or detectable.
|
||||
|
||||
The returned dictionary contains:
|
||||
|
||||
* running (bool) - whether the SNMP daemon is currently active
|
||||
* community (string) - the read community string (e.g. ``"public"``)
|
||||
* port (int) - the UDP port the agent listens on (default ``161``)
|
||||
* version (string) - highest supported SNMP version: ``"1"``, ``"2c"``, or ``"3"``
|
||||
|
||||
Example::
|
||||
|
||||
# snmpd running with community "public":
|
||||
{
|
||||
"running": True,
|
||||
"community": "public",
|
||||
"port": 161,
|
||||
"version": "2c",
|
||||
}
|
||||
|
||||
# snmpd not installed / not running:
|
||||
None
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Generic device actions
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run_device_action(self, action: str) -> DeviceActionResultDict:
|
||||
"""
|
||||
Executes a named administrative action on the device.
|
||||
|
||||
**Deprecated** (docs/STRUCTURE.md): the actions become fix templates
|
||||
in :mod:`napalm_device_types.fixes`, whose values the caller supplies --
|
||||
``configure_snmp_agent``, ``configure_package_proxy``,
|
||||
``grant_container_engine_access``, ``ensure_package``. Goes in 5.0.
|
||||
|
||||
This method is an extensibility point for driver-specific one-off
|
||||
operations that do not fit any other NAPALM API method. Each driver
|
||||
documents the action names it supports.
|
||||
|
||||
:param action: Action identifier string (e.g. ``"fix_docker_permissions"``).
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If ``action`` is not a recognised action name for
|
||||
this driver.
|
||||
|
||||
:returns: A dict with:
|
||||
|
||||
* success (bool) – ``True`` if the action completed without error
|
||||
* output (string) – human-readable output or status message
|
||||
|
||||
Example::
|
||||
|
||||
result = driver.run_device_action("fix_docker_permissions")
|
||||
# → {"success": True, "output": "Added 'pi' to the docker group. Reconnect..."}
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,30 @@
|
||||
"""A device's OSPF state, in neutral terms.
|
||||
|
||||
The routing daemon's own output (FRR, Quagga, a vendor's CLI) is the driver's
|
||||
to translate; whether an interface without neighbours or without
|
||||
authentication is a problem is the caller's to decide.
|
||||
Declared only; a driver whose device runs OSPF implements it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import OspfDict
|
||||
|
||||
|
||||
class OspfMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_ospf(self) -> OspfDict:
|
||||
"""Router ID, areas and OSPF per interface.
|
||||
|
||||
Example::
|
||||
|
||||
{"router_id": "10.255.0.1", "areas": ["0.0.0.0"],
|
||||
"interfaces": {"wg0": {"address": "10.255.0.1", "prefix_length": 24,
|
||||
"area": "0.0.0.0", "network_type": "POINTOPOINT",
|
||||
"authentication": "MessageDigest", "neighbors": 1,
|
||||
"neighbors_adjacent": 1, "cost": 10}}}
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Whether dnf or yum, apk or opkg was left halfway: the host status's answer for
|
||||
a host without dpkg (NetOrk/netork#851).
|
||||
|
||||
Read the same way as dpkg's state (:mod:`napalm_device_types.host_status`): in the
|
||||
one host status command, without root, and changing nothing. Each manager is asked
|
||||
only where it exists, and while one of its processes runs -- from
|
||||
``/proc/<pid>/comm``, which every Linux has and BusyBox's ``ps`` cannot narrow to --
|
||||
its packages are halfway on purpose and the answer is unknown.
|
||||
|
||||
**dnf and yum** (rpm). A transaction cut off after rpm installed the new version
|
||||
of a package and before it erased the old one leaves both in the rpm database:
|
||||
what ``dnf check --duplicates`` and ``package-cleanup --dupes`` report. Packages
|
||||
dnf installs side by side on purpose do not count: its default ``installonlypkgs``
|
||||
(``kernel``, ``installonlypkg(kernel)`` and the rest), plus any the host adds in
|
||||
``dnf.conf``, asked of rpm by what they provide; and ``gpg-pubkey``, one entry
|
||||
per imported key. The defaults are the ones the host's libdnf was built with, asked
|
||||
of its Python binding, as a distribution may add its own: Oracle Linux adds
|
||||
``kernel-uek`` and its parts, whose packages provide nothing of upstream's list.
|
||||
Upstream's list is the floor where libdnf cannot be asked (dnf 5, yum). Also
|
||||
interrupted is a transaction that never ended: dnf 4's history (libdnf's ``trans``
|
||||
table) holds its row with ``state`` 0 until ``finish()`` writes 1 (done) or 2
|
||||
(error), so the newest row at 0 is one cut off;
|
||||
yum leaves a ``transaction-all.*`` journal in ``/var/lib/yum``, which
|
||||
``yum-complete-transaction`` reads (one renamed ``.disabled`` is given up). The
|
||||
history is read with Python's sqlite3 module in read-only mode, as a stock EL host
|
||||
has no ``sqlite3`` program and a ``dnf`` command loads every plugin and may reach
|
||||
for its repositories. dnf 5's history lives elsewhere and is not read; its
|
||||
duplicates are.
|
||||
|
||||
**apk** (Alpine, OpenWrt from 25.12). apk marks an installed package whose files
|
||||
or scripts failed with ``f:`` in ``/lib/apk/db/installed`` -- ``f`` broken files,
|
||||
``s`` a broken script; ``x`` (xattrs) and ``S`` (the checksum kind) are no fault --
|
||||
and those are exactly the packages ``apk fix`` without arguments picks. A run
|
||||
killed outright leaves no such mark; its next run usually repeats what it left.
|
||||
|
||||
**opkg** (OpenWrt before 25.12). ``/usr/lib/opkg/status`` holds
|
||||
``Status: <want> <flags> <state>`` per package. A run cut off, or a postinst that
|
||||
failed, leaves ``unpacked`` (or ``half-configured``, ``half-installed``), and the
|
||||
``reinstreq`` flag asks for a reinstall; ``opkg configure`` finishes every unpacked
|
||||
package.
|
||||
|
||||
What to do about it is not decided here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import NamedTuple
|
||||
|
||||
from napalm_device_types.models import InterruptedPackageDict
|
||||
|
||||
#: dnf's default ``installonlypkgs``: names and what such packages provide.
|
||||
_INSTALLONLY = (
|
||||
"kernel",
|
||||
"kernel-PAE",
|
||||
"installonlypkg(kernel)",
|
||||
"installonlypkg(kernel-module)",
|
||||
"installonlypkg(vm)",
|
||||
"multiversion(kernel)",
|
||||
)
|
||||
#: Where a host adds its own installonly packages, dnf's then yum's.
|
||||
_DNF_CONF = "/etc/dnf/dnf.conf /etc/yum.conf"
|
||||
DNF_HISTORY = "/var/lib/dnf/history.sqlite"
|
||||
YUM_DIR = "/var/lib/yum"
|
||||
APK_INSTALLED = "/lib/apk/db/installed"
|
||||
OPKG_STATUS = "/usr/lib/opkg/status"
|
||||
|
||||
#: manager -> the process names that leave its packages halfway while they run.
|
||||
_RUNNING = {
|
||||
"rpm": frozenset({"rpm", "dnf", "dnf5", "yum", "dnf-automatic", "packagekitd"}),
|
||||
"apk": frozenset({"apk"}),
|
||||
"opkg": frozenset({"opkg"}),
|
||||
}
|
||||
_UNFINISHED = "0"
|
||||
_YUM_JOURNAL = "transaction-all."
|
||||
_YUM_GIVEN_UP = ".disabled"
|
||||
_APK_FLAGS = (("f", "broken-files"), ("s", "broken-script"))
|
||||
_OPKG_HALFWAY = frozenset({"unpacked", "half-configured", "half-installed"})
|
||||
_OPKG_REINSTALL = "reinstreq"
|
||||
|
||||
#: The newest transaction in dnf's history as ``<id> <state>``; nothing when unreadable.
|
||||
#: One literal, with :data:`DNF_HISTORY` spelt out: a fixed query, nothing put into it.
|
||||
_DNF_HISTORY_PY = (
|
||||
"import sqlite3; "
|
||||
"c = sqlite3.connect('file:/var/lib/dnf/history.sqlite?mode=ro', uri=True); "
|
||||
"r = c.execute('SELECT id, state FROM trans ORDER BY id DESC LIMIT 1').fetchone(); "
|
||||
"r and print(*r)"
|
||||
)
|
||||
#: The ``installonlypkgs`` the host's libdnf (dnf 4) was built with, space-separated;
|
||||
#: nothing where there is no libdnf. ``ConfigMain`` is held in a name: an option
|
||||
#: taken from a temporary one outlives it, and reading it then crashes Python.
|
||||
_LIBDNF_INSTALLONLY_PY = (
|
||||
"import libdnf.conf; c = libdnf.conf.ConfigMain(); "
|
||||
"print(c.installonlypkgs().getValueString().replace(',', ' '))"
|
||||
)
|
||||
|
||||
_RUNNING_PART = (
|
||||
"echo '[pm-running]'; cat /proc/[0-9]*/comm 2>/dev/null | grep -xE '"
|
||||
+ "|".join(sorted(set().union(*_RUNNING.values())))
|
||||
+ "' | sort -u; "
|
||||
)
|
||||
_RPM_PART = (
|
||||
"if command -v rpm >/dev/null 2>&1 && { command -v dnf || command -v yum; } >/dev/null 2>&1; "
|
||||
"then echo '[rpm-frontend]'; { command -v dnf || command -v yum; } | sed 's#.*/##'; "
|
||||
"rpmpy=; for p in /usr/libexec/platform-python python3; do "
|
||||
"if command -v $p >/dev/null 2>&1; then rpmpy=$p; break; fi; done; "
|
||||
f"echo '[rpm-installonly]'; io=\"{' '.join(_INSTALLONLY)} "
|
||||
f'$([ -n "$rpmpy" ] && $rpmpy -c "{_LIBDNF_INSTALLONLY_PY}" 2>/dev/null) '
|
||||
f"$(sed -n 's/^[[:space:]]*installonlypkgs[[:space:]]*=//p' {_DNF_CONF} 2>/dev/null "
|
||||
"| tr ',' ' ')\"; rpm -q --whatprovides $io --qf '%{NAME}\\n' 2>/dev/null "
|
||||
"| grep -v ' ' | sort -u; "
|
||||
"echo '[rpm-dupes]'; rpm -qa --qf '%{NAME} %{ARCH}\\n' 2>/dev/null "
|
||||
"| grep -v '^gpg-pubkey ' | sort | uniq -d | head -n 50; "
|
||||
f"echo '[yum-journal]'; ls -1 {YUM_DIR} 2>/dev/null | grep '^transaction-all\\.' "
|
||||
"| head -n 20; "
|
||||
"echo '[dnf-history]'; "
|
||||
f'[ -n "$rpmpy" ] && $rpmpy -c "{_DNF_HISTORY_PY}" 2>/dev/null; fi; '
|
||||
)
|
||||
_APK_PART = (
|
||||
f"if command -v apk >/dev/null 2>&1 && [ -r {APK_INSTALLED} ]; then echo '[apk-audit]'; "
|
||||
"awk '/^P:/ {p = substr($0, 3)} /^f:/ {f = substr($0, 3)} "
|
||||
'/^$/ {if (f ~ /[fs]/) print f, p; p = ""; f = ""} END {if (f ~ /[fs]/) print f, p}\' '
|
||||
f"{APK_INSTALLED} | head -n 50; fi; "
|
||||
)
|
||||
_OPKG_PART = (
|
||||
f"if command -v opkg >/dev/null 2>&1 && [ -r {OPKG_STATUS} ]; then echo '[opkg-audit]'; "
|
||||
"awk '/^Package:/ {p = $2} /^Status:/ && "
|
||||
"($4 ~ /^(unpacked|half-configured|half-installed)$/ || $3 ~ /reinstreq/) "
|
||||
f"{{print $3, $4, p}}' {OPKG_STATUS} | head -n 50; fi; "
|
||||
)
|
||||
|
||||
#: The part of the host status command that reads them; POSIX ``sh``, BusyBox too.
|
||||
PACKAGE_MANAGERS_COMMAND = _RUNNING_PART + _RPM_PART + _APK_PART + _OPKG_PART
|
||||
|
||||
|
||||
class PackageManagerReading(NamedTuple):
|
||||
"""One package manager's state: halfway or not, None while it is running."""
|
||||
|
||||
manager: str | None
|
||||
interrupted: bool | None
|
||||
packages: list[InterruptedPackageDict]
|
||||
|
||||
|
||||
def _unfinished_transaction(sections: dict[str, list[str]]) -> bool:
|
||||
newest = (sections.get("dnf-history") or [""])[0].split()
|
||||
if len(newest) == 2 and newest[1] == _UNFINISHED:
|
||||
return True
|
||||
return any(
|
||||
name.startswith(_YUM_JOURNAL) and not name.endswith(_YUM_GIVEN_UP)
|
||||
for name in sections.get("yum-journal") or []
|
||||
)
|
||||
|
||||
|
||||
def _rpm(sections: dict[str, list[str]], running: set[str]) -> PackageManagerReading | None:
|
||||
if "rpm-dupes" not in sections:
|
||||
return None
|
||||
manager = (sections.get("rpm-frontend") or ["dnf"])[0]
|
||||
if running & _RUNNING["rpm"]:
|
||||
return PackageManagerReading(manager, None, [])
|
||||
installonly = set(sections.get("rpm-installonly") or [])
|
||||
names = dict.fromkeys(line.split()[0] for line in sections["rpm-dupes"])
|
||||
packages: list[InterruptedPackageDict] = [
|
||||
{"name": name, "state": "duplicate"} for name in names if name not in installonly
|
||||
]
|
||||
return PackageManagerReading(
|
||||
manager, bool(packages) or _unfinished_transaction(sections), packages
|
||||
)
|
||||
|
||||
|
||||
def _apk(sections: dict[str, list[str]], running: set[str]) -> PackageManagerReading | None:
|
||||
if "apk-audit" not in sections:
|
||||
return None
|
||||
if running & _RUNNING["apk"]:
|
||||
return PackageManagerReading("apk", None, [])
|
||||
packages: list[InterruptedPackageDict] = []
|
||||
for line in sections["apk-audit"]:
|
||||
flags, _, name = line.partition(" ")
|
||||
name = name.strip()
|
||||
packages += [
|
||||
{"name": name, "state": state} for flag, state in _APK_FLAGS if name and flag in flags
|
||||
]
|
||||
return PackageManagerReading("apk", bool(packages), packages)
|
||||
|
||||
|
||||
def _opkg_package(line: str) -> InterruptedPackageDict | None:
|
||||
parts = line.split()
|
||||
if len(parts) != 3:
|
||||
return None
|
||||
flags, state, name = parts
|
||||
if _OPKG_REINSTALL in flags.split(","):
|
||||
return {"name": name, "state": "reinstall-required"}
|
||||
return {"name": name, "state": state} if state in _OPKG_HALFWAY else None
|
||||
|
||||
|
||||
def _opkg(sections: dict[str, list[str]], running: set[str]) -> PackageManagerReading | None:
|
||||
if "opkg-audit" not in sections:
|
||||
return None
|
||||
if running & _RUNNING["opkg"]:
|
||||
return PackageManagerReading("opkg", None, [])
|
||||
packages = [p for p in map(_opkg_package, sections["opkg-audit"]) if p is not None]
|
||||
return PackageManagerReading("opkg", bool(packages), packages)
|
||||
|
||||
|
||||
def parse_package_managers(sections: dict[str, list[str]]) -> list[PackageManagerReading]:
|
||||
"""What :data:`PACKAGE_MANAGERS_COMMAND` found, one reading per manager it asked."""
|
||||
running = set(sections.get("pm-running") or [])
|
||||
readings = (read(sections, running) for read in (_rpm, _apk, _opkg))
|
||||
return [reading for reading in readings if reading is not None]
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Pending package updates: which package, from where, and whether it is a security fix.
|
||||
|
||||
A patch deadline -- "security updates within 14 days" -- needs to know which
|
||||
pending update is a security update. apt says so in the suite a candidate comes
|
||||
from (``noble-security``, ``stable-security``), dnf in its update advisories.
|
||||
Reading that is the same for every driver whose host runs apt or dnf, so the
|
||||
parsers live here once and a driver only carries the command across.
|
||||
|
||||
apt: the suites a candidate comes from are its ``origin``; any suite ending in
|
||||
``-security`` makes it a security update. A security fix that a later
|
||||
``-updates`` build superseded shows only ``-updates`` and counts as not
|
||||
security -- netOrk's CVE matching is what catches those.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from napalm_device_types.models import UpdateDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
#: Read-only, no root needed, in a fixed language so the parse holds, and
|
||||
#: through a pipe: without a terminal apt draws no progress and no terminal
|
||||
#: codes, one of which (``ESC >``) a screen-scraping transport took for a shell
|
||||
#: prompt and stopped reading at. Its exit status is printed inside the group,
|
||||
#: so it is apt's, not cat's.
|
||||
APT_UPGRADABLE_COMMAND = "{ LC_ALL=C apt list --upgradable 2>/dev/null; echo __APT_RC=$?; } | cat"
|
||||
|
||||
#: Read-only. Lists the packages that a pending security advisory covers. A
|
||||
#: failed dnf prints nothing, the same as no advisories, so its exit status is
|
||||
#: printed inside the group, as apt's is. It reads the cached metadata only, as
|
||||
#: apt reads its local index: an expired cache otherwise makes dnf download the
|
||||
#: repositories' metadata first, which can take minutes (#76).
|
||||
DNF_SECURITY_COMMAND = (
|
||||
"{ LC_ALL=C dnf --cacheonly updateinfo list --security --quiet 2>/dev/null;"
|
||||
" echo __DNF_RC=$?; } | cat"
|
||||
)
|
||||
|
||||
#: Read-only. Every advisory whose fix the installed packages carry, one line per
|
||||
#: CVE it names (``CVE SEVERITY/Sec. NEVRA``): the distribution's own word that a
|
||||
#: backport is in, where netOrk's knowledge base holds no records of the release
|
||||
#: (netOrk #2394). dnf 4 only: dnf 5 reads ``--with-cve`` as a filter, and
|
||||
#: Fedora's advisories reference bugs rather than CVEs. From the cache, as
|
||||
#: :data:`DNF_SECURITY_COMMAND` reads it; the output is long (90 000 lines on an
|
||||
#: Oracle Linux 9 host), so a caller reads it seldom.
|
||||
DNF_INSTALLED_CVES_COMMAND = (
|
||||
"{ LC_ALL=C dnf --cacheonly updateinfo list --installed --with-cve --quiet 2>/dev/null;"
|
||||
" echo __DNF_RC=$?; } | cat"
|
||||
)
|
||||
|
||||
# openssl/noble-updates,noble-security 3.0.13-0ubuntu3.6 amd64 [upgradable from: 3.0.13-0ubuntu3.5]
|
||||
_APT_LINE = re.compile(r"^(\S+)/(\S+)\s+(\S+)\s+\S+\s+\[upgradable from:\s+(\S+)\]")
|
||||
_SECURITY_SUITE = "-security"
|
||||
_APT_STATUS = re.compile(r"^__APT_RC=(\d+)\s*$", re.MULTILINE)
|
||||
_DNF_STATUS = re.compile(r"^__DNF_RC=(\d+)\s*$", re.MULTILINE)
|
||||
_CVE_ID = re.compile(r"^CVE-\d{4}-\d{4,}$")
|
||||
|
||||
|
||||
def _joined_lines(output: str) -> list[str]:
|
||||
"""Lines as apt printed them: a terminal wraps long ones, and the
|
||||
continuation starts with a space."""
|
||||
lines: list[str] = []
|
||||
for line in output.splitlines():
|
||||
if line.startswith(" ") and lines:
|
||||
lines[-1] += line[1:].rstrip()
|
||||
else:
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _listing(output: str, status: re.Pattern[str], what: str) -> str:
|
||||
"""The listing without its exit status, or ``ValueError`` when the command
|
||||
failed or the output was cut short -- "could not read" must never look like
|
||||
"nothing pending"."""
|
||||
text = strip_terminal_codes(output)
|
||||
statuses = status.findall(text)
|
||||
if not statuses:
|
||||
raise ValueError(f"{what} reported no exit status; the output was cut short")
|
||||
if statuses[-1] != "0":
|
||||
raise ValueError(f"{what} failed with exit status {statuses[-1]}")
|
||||
return status.sub("", text)
|
||||
|
||||
|
||||
def parse_apt_upgradable(output: str) -> list[UpdateDict]:
|
||||
"""Parse :data:`APT_UPGRADABLE_COMMAND`'s output, one entry per package.
|
||||
|
||||
A package listed for several architectures (``libc6`` for amd64 and i386)
|
||||
is one entry; it counts as a security update if any of its lines does.
|
||||
|
||||
:raises ValueError: when apt failed or its exit status never arrived.
|
||||
"""
|
||||
by_name: dict[str, UpdateDict] = {}
|
||||
for line in _joined_lines(_listing(output, _APT_STATUS, "apt list --upgradable")):
|
||||
match = _APT_LINE.match(line)
|
||||
if not match:
|
||||
continue
|
||||
name, listed, new_version, current_version = match.groups()
|
||||
suites = list(dict.fromkeys(listed.split(","))) # apt may list a suite twice
|
||||
security = any(suite.endswith(_SECURITY_SUITE) for suite in suites)
|
||||
seen = by_name.get(name)
|
||||
if seen is not None:
|
||||
seen["security"] = bool(seen.get("security")) or security
|
||||
continue
|
||||
by_name[name] = {
|
||||
"name": name,
|
||||
"current_version": current_version,
|
||||
"new_version": new_version,
|
||||
"origin": ",".join(suites),
|
||||
"security": security,
|
||||
}
|
||||
return list(by_name.values())
|
||||
|
||||
|
||||
def nevra_name(nevra: str) -> str:
|
||||
"""The package name of an RPM ``name-[epoch:]version-release.arch``."""
|
||||
without_arch = nevra.rsplit(".", 1)[0]
|
||||
return without_arch.rsplit("-", 2)[0]
|
||||
|
||||
|
||||
def parse_dnf_security(output: str) -> set[str]:
|
||||
"""The names of the packages a pending security advisory covers.
|
||||
|
||||
Parses :data:`DNF_SECURITY_COMMAND`'s ``ADVISORY SEVERITY/Sec. NEVRA`` lines.
|
||||
|
||||
:raises ValueError: when dnf failed or its exit status never arrived -- every
|
||||
update would otherwise read as not security.
|
||||
"""
|
||||
names: set[str] = set()
|
||||
for line in _listing(output, _DNF_STATUS, "dnf updateinfo list --security").splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 3 and parts[1].endswith("/Sec."):
|
||||
names.add(nevra_name(parts[-1]))
|
||||
return names
|
||||
|
||||
|
||||
def parse_dnf_installed_cves(output: str) -> dict[str, list[str]]:
|
||||
"""The CVEs the installed advisories close, per package name, each once and sorted.
|
||||
|
||||
Parses :data:`DNF_INSTALLED_CVES_COMMAND`'s ``CVE SEVERITY/Sec. NEVRA`` lines;
|
||||
a line that names no CVE (a key prompt, an advisory id) is no statement.
|
||||
|
||||
:raises ValueError: when dnf failed or its exit status never arrived -- "could
|
||||
not read" must not look like "no advisory installed".
|
||||
"""
|
||||
by_name: dict[str, set[str]] = {}
|
||||
listing = _listing(output, _DNF_STATUS, "dnf updateinfo list --installed --with-cve")
|
||||
for line in listing.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 3 and _CVE_ID.match(parts[0]):
|
||||
by_name.setdefault(nevra_name(parts[-1]), set()).add(parts[0])
|
||||
return {name: sorted(cves) for name, cves in by_name.items()}
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Listing and managing installed software.
|
||||
|
||||
Identical on every device type that has a package manager -- this was five
|
||||
byte-identical copies before it moved here. A driver whose device offers no
|
||||
package management simply implements none of it.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: these are contracts, not placeholders.
|
||||
Nothing exists at runtime until a concrete driver implements it, so mixing
|
||||
this class in can never shadow a working implementation from a sibling base.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
|
||||
class PackageManagementMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_packages(self) -> list[PackageDict]:
|
||||
"""
|
||||
Returns all packages currently known to the device's package manager
|
||||
(e.g. ``opkg`` on OpenWrt, ``apk`` on Alpine-based APs).
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - package name
|
||||
* version (string) - installed or available version string
|
||||
* installed (bool) - ``True`` if the package is currently installed
|
||||
* description (string) - short package description
|
||||
* size (int) - package size in bytes (0 if unknown)
|
||||
* source (string) - repository / feed the package comes from
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "luci-app-statistics",
|
||||
"version": "git-24.001.00000-1",
|
||||
"installed": True,
|
||||
"description": "LuCI Statistics application",
|
||||
"size": 20480,
|
||||
"source": "openwrt/packages",
|
||||
},
|
||||
{
|
||||
"name": "collectd-mod-wireless",
|
||||
"version": "5.12.0-24",
|
||||
"installed": False,
|
||||
"description": "Wireless statistics plugin for collectd",
|
||||
"size": 8192,
|
||||
"source": "openwrt/packages",
|
||||
},
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def install_package(self, name: str, version: str = "") -> None:
|
||||
"""
|
||||
Installs a package on the device.
|
||||
|
||||
The method blocks until the installation is complete. After it returns
|
||||
successfully the package is available for use without a reboot
|
||||
(where the underlying package manager supports this).
|
||||
|
||||
:param name: Package name as known to the package manager.
|
||||
:param version: Exact version to install. An empty string (default)
|
||||
installs the latest available version.
|
||||
:raises ValueError: If the package name is unknown or the version does
|
||||
not exist in any configured feed.
|
||||
:raises RuntimeError: If the installation fails on the device side
|
||||
(e.g. dependency conflict, disk full).
|
||||
|
||||
Example::
|
||||
|
||||
driver.install_package("luci-app-statistics")
|
||||
driver.install_package("collectd", version="5.12.0-24")
|
||||
"""
|
||||
...
|
||||
|
||||
def uninstall_package(self, name: str) -> None:
|
||||
"""
|
||||
Removes an installed package from the device.
|
||||
|
||||
The method blocks until the removal is complete.
|
||||
|
||||
:param name: Package name to remove.
|
||||
:raises ValueError: If the package is not currently installed.
|
||||
:raises RuntimeError: If the removal fails on the device side
|
||||
(e.g. other packages depend on it).
|
||||
|
||||
Example::
|
||||
|
||||
driver.uninstall_package("luci-app-statistics")
|
||||
"""
|
||||
...
|
||||
|
||||
def get_package_config(self, name: str) -> dict[str, Any]:
|
||||
"""
|
||||
Returns the current configuration of an installed package as a
|
||||
dictionary. The structure is package-specific.
|
||||
|
||||
:param name: Package name.
|
||||
:raises ValueError: If the package is not installed.
|
||||
|
||||
Example::
|
||||
|
||||
driver.get_package_config("luci-app-statistics")
|
||||
# →
|
||||
{
|
||||
"collectd": {
|
||||
"enabled": True,
|
||||
"interval": 30,
|
||||
},
|
||||
"rrdtool": {
|
||||
"datadir": "/tmp/rrd",
|
||||
"stepsize": 30,
|
||||
"heartbeat": 60,
|
||||
},
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
def set_package_config(self, name: str, config: dict[str, Any]) -> None:
|
||||
"""
|
||||
Writes a new configuration for an installed package.
|
||||
|
||||
The ``config`` dict must match the structure returned by
|
||||
:meth:`get_package_config`. Unknown keys are ignored or raise a
|
||||
``ValueError`` depending on the driver implementation.
|
||||
|
||||
Changes take effect immediately where the package supports live
|
||||
reload; otherwise a package restart or device reboot may be
|
||||
required – behaviour is driver-specific.
|
||||
|
||||
:param name: Package name.
|
||||
:param config: New configuration as a nested dictionary.
|
||||
:raises ValueError: If the package is not installed or the configuration
|
||||
contains invalid values.
|
||||
:raises RuntimeError: If the device rejects the configuration.
|
||||
|
||||
Example::
|
||||
|
||||
driver.set_package_config(
|
||||
"luci-app-statistics",
|
||||
{
|
||||
"collectd": {"enabled": True, "interval": 60},
|
||||
"rrdtool": {"datadir": "/tmp/rrd", "stepsize": 60, "heartbeat": 120},
|
||||
},
|
||||
)
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
Abstract base class for IP telephony endpoints.
|
||||
|
||||
Usage::
|
||||
|
||||
from napalm_device_types import PhoneDriver
|
||||
|
||||
class YealinkDriver(PhoneDriver):
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
|
||||
|
||||
class PhoneDriver(DeviceTypeDriver):
|
||||
"""
|
||||
Abstract intermediate driver for desk phones, conference units and DECT
|
||||
bases (e.g. Yealink T-series, Snom, Grandstream, Fanvil).
|
||||
|
||||
A phone is an endpoint, not infrastructure. It was worth separating from
|
||||
``AccessPointDriver`` — which some phone drivers used to inherit for want of
|
||||
anywhere better — because netOrk offers access points for AP profiles,
|
||||
wireless management and SSID drift, none of which a desk phone should appear
|
||||
in. A WiFi-capable phone still reports its radio through its own methods; it
|
||||
just is not an access point.
|
||||
"""
|
||||
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "phone"
|
||||
TYPE_LABEL: str = "Phone"
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_sip_accounts(self) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Returns the SIP registrations configured on the phone.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* account (string) - display label or line key
|
||||
* user (string) - SIP user / extension
|
||||
* server (string) - registrar host
|
||||
* registered (bool) - whether the registration is currently active
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"account": "Line 1",
|
||||
"user": "201",
|
||||
"server": "pbx.example.com",
|
||||
"registered": True,
|
||||
}
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_call_status(self) -> dict[str, Any]:
|
||||
"""
|
||||
Returns what the phone is doing right now.
|
||||
|
||||
* state (string) - ``"idle"``, ``"ringing"``, ``"talking"``, or ``"held"``
|
||||
* remote (string) - remote party, empty string when idle
|
||||
* duration (int) - seconds in the current state; ``0`` when idle
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Generic ICMP sweep on top of the NAPALM-standard ``ping()``.
|
||||
|
||||
Sweeping a range of addresses is orchestration, not device mechanics: the
|
||||
only vendor-specific part is how a single ``ping`` is executed, and NAPALM
|
||||
already standardises that. So the loop, the reply parsing, the target cap
|
||||
and the progress reporting live here once, and a concrete driver only has
|
||||
to implement ``ping()`` to become a usable sweep source.
|
||||
|
||||
A driver whose device offers a *faster* sweep mechanism (a batch API, a
|
||||
single shell command that pings many hosts in parallel, an ARP-assisted
|
||||
scan) overrides :meth:`PingSweepMixin.ping_sweep` and keeps the same return
|
||||
shape — see ``napalm-opnsense`` for an example.
|
||||
|
||||
The generic implementation is deliberately **sequential**: a NAPALM
|
||||
connection is a single session (SSH channel, HTTP client) and is not safe to
|
||||
drive from several threads at once. Callers that need many addresses covered
|
||||
quickly should either use a driver with its own parallel override or cap the
|
||||
target list (see ``PING_SWEEP_MAX_TARGETS``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm.base import NetworkDriver
|
||||
|
||||
from napalm_device_types.models import PingSweepEntryDict, PingSweepResultDict
|
||||
|
||||
|
||||
def driver_supports_ping(driver_cls: type) -> bool:
|
||||
"""Whether *driver_cls* can actually execute ``ping()``.
|
||||
|
||||
True when the class provides its own ``ping`` implementation instead of
|
||||
inheriting NAPALM's ``NotImplementedError`` stub. A driver that inherits
|
||||
a working ``ping`` but cannot use it (unsupported firmware, disabled
|
||||
service) opts out by setting ``SUPPORTS_PING = False``.
|
||||
"""
|
||||
if getattr(driver_cls, "SUPPORTS_PING", None) is False:
|
||||
return False
|
||||
ping_impl = getattr(driver_cls, "ping", None)
|
||||
if ping_impl is None:
|
||||
return False
|
||||
return ping_impl is not getattr(NetworkDriver, "ping", None)
|
||||
|
||||
|
||||
class PingSweepMixin:
|
||||
"""Adds :meth:`ping_sweep` to any driver that implements ``ping()``.
|
||||
|
||||
Mixed into :class:`~napalm_device_types.base.DeviceTypeDriver`, so every
|
||||
device-type driver inherits it; drivers without a ``ping()`` of their own
|
||||
simply report ``supports_ping() is False`` and raise from ``ping_sweep``.
|
||||
"""
|
||||
|
||||
#: Upper bound on destinations probed in one sweep. The sequential
|
||||
#: default implementation costs roughly ``timeout`` seconds per silent
|
||||
#: host, so an uncapped /24 would keep a device session busy for minutes.
|
||||
#: Drivers with a parallel mechanism raise this.
|
||||
PING_SWEEP_MAX_TARGETS: ClassVar[int] = 256
|
||||
|
||||
#: ``False`` opts a driver out of ping sweeps even though it implements
|
||||
#: ``ping()``. ``None`` (the default) means "decide by introspection".
|
||||
SUPPORTS_PING: ClassVar[bool | None] = None
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def ping(
|
||||
self,
|
||||
destination: str,
|
||||
source: str = "",
|
||||
ttl: int = 255,
|
||||
timeout: int = 2,
|
||||
size: int = 100,
|
||||
count: int = 5,
|
||||
vrf: str = "",
|
||||
) -> dict[str, Any]: ...
|
||||
|
||||
@classmethod
|
||||
def supports_ping(cls) -> bool:
|
||||
"""Whether this driver class can be used as a ping-sweep source."""
|
||||
return driver_supports_ping(cls)
|
||||
|
||||
def ping_sweep(
|
||||
self,
|
||||
destinations: Iterable[str],
|
||||
*,
|
||||
count: int = 1,
|
||||
timeout: int = 1,
|
||||
max_targets: int | None = None,
|
||||
on_progress: Callable[[int, int], None] | None = None,
|
||||
should_stop: Callable[[], bool] | None = None,
|
||||
) -> PingSweepResultDict:
|
||||
"""Ping every address in *destinations* and report who answered.
|
||||
|
||||
:param destinations: IP addresses / hostnames to probe, in order.
|
||||
:param count: probes per destination — 1 is enough for liveness.
|
||||
:param timeout: seconds to wait for a reply per destination.
|
||||
:param max_targets: cap for this call; defaults to
|
||||
``PING_SWEEP_MAX_TARGETS``. Excess destinations are dropped and
|
||||
``truncated`` is set in the result.
|
||||
:param on_progress: called as ``(done, total)`` after each probe.
|
||||
:param should_stop: polled before each probe; returning True ends the
|
||||
sweep early (cancelled job, shutting-down worker).
|
||||
:raises NotImplementedError: if the driver has no ``ping()``.
|
||||
"""
|
||||
if not self.supports_ping():
|
||||
raise NotImplementedError(
|
||||
f"{type(self).__name__} does not implement ping(); cannot run a ping sweep"
|
||||
)
|
||||
|
||||
limit = self.PING_SWEEP_MAX_TARGETS if max_targets is None else max_targets
|
||||
targets = list(destinations)
|
||||
truncated = len(targets) > limit
|
||||
if truncated:
|
||||
targets = targets[:limit]
|
||||
|
||||
total = len(targets)
|
||||
entries: list[PingSweepEntryDict] = []
|
||||
for done, destination in enumerate(targets, start=1):
|
||||
if should_stop is not None and should_stop():
|
||||
break
|
||||
entries.append(self._ping_once(destination, count=count, timeout=timeout))
|
||||
if on_progress is not None:
|
||||
on_progress(done, total)
|
||||
|
||||
return {
|
||||
"entries": entries,
|
||||
"scanned": len(entries),
|
||||
"alive_count": sum(1 for entry in entries if entry["alive"]),
|
||||
"truncated": truncated,
|
||||
}
|
||||
|
||||
# ── internals ────────────────────────────────────────────────────────────
|
||||
|
||||
def _ping_once(self, destination: str, *, count: int, timeout: int) -> PingSweepEntryDict:
|
||||
"""One probe, never raising — a dead session must not abort the sweep."""
|
||||
try:
|
||||
reply = self.ping(destination, count=count, timeout=timeout)
|
||||
except Exception as exc: # noqa: BLE001 - any driver error is just "no answer"
|
||||
return {"ip": destination, "alive": False, "rtt_ms": None, "error": str(exc)}
|
||||
return self._parse_ping_reply(destination, reply)
|
||||
|
||||
@staticmethod
|
||||
def _parse_ping_reply(destination: str, reply: Any) -> PingSweepEntryDict:
|
||||
"""Map a NAPALM ``ping()`` reply onto a sweep entry."""
|
||||
if not isinstance(reply, dict) or "success" not in reply:
|
||||
error = "malformed ping reply"
|
||||
if isinstance(reply, dict) and reply.get("error"):
|
||||
error = str(reply["error"])
|
||||
return {"ip": destination, "alive": False, "rtt_ms": None, "error": error}
|
||||
|
||||
success = reply.get("success") or {}
|
||||
if not isinstance(success, dict):
|
||||
return {
|
||||
"ip": destination,
|
||||
"alive": False,
|
||||
"rtt_ms": None,
|
||||
"error": "malformed ping reply",
|
||||
}
|
||||
probes_sent = _as_int(success.get("probes_sent"))
|
||||
packet_loss = _as_int(success.get("packet_loss"), default=probes_sent)
|
||||
alive = bool(success.get("results")) or probes_sent > packet_loss
|
||||
if not alive:
|
||||
return {"ip": destination, "alive": False, "rtt_ms": None}
|
||||
return {"ip": destination, "alive": True, "rtt_ms": _as_float(success.get("rtt_avg"))}
|
||||
|
||||
|
||||
def _as_int(value: Any, default: int = 0) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _as_float(value: Any) -> float | None:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
@@ -0,0 +1,176 @@
|
||||
"""A time zone as a device takes it: an IANA name, a POSIX TZ rule, or the rule's parts.
|
||||
|
||||
An application names a zone the IANA way (``Europe/Berlin``). Not every device
|
||||
can: OpenWrt hands ``system.timezone`` to libc as ``TZ``, which wants the rule
|
||||
itself (``CET-1CEST,M3.5.0,M10.5.0/3``), and a switch wants a UTC offset and the
|
||||
summer-time rule. A driver translates with these helpers.
|
||||
|
||||
The rule is the footer of the zone's TZif file (version 2 and later): the line
|
||||
after the last transition that says how the zone goes on. OpenWrt's LuCI table is
|
||||
built from the same footers. The files come from the ``tzdata`` package, a
|
||||
declared dependency, so every driver reads the same database whatever its host
|
||||
ships.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from importlib.resources import files
|
||||
from typing import TypedDict
|
||||
|
||||
#: An IANA name: letters, digits, ``_+-`` in ``/``-separated parts. No dots, so
|
||||
#: nothing reaches outside the database.
|
||||
_ZONE_NAME = re.compile(r"[A-Za-z0-9_+-]+(?:/[A-Za-z0-9_+-]+)*")
|
||||
|
||||
_ABBR = r"(?:[A-Za-z]{3,}|<[A-Za-z0-9+-]{3,}>)"
|
||||
_OFFSET = r"[+-]?\d{1,2}(?::\d{1,2}){0,2}"
|
||||
_DATE = r"(?:J\d{1,3}|\d{1,3}|M\d{1,2}\.\d\.\d)(?:/[+-]?\d{1,3}(?::\d{1,2}){0,2})?"
|
||||
#: ``std offset [dst [offset] [,start,end]]`` (POSIX.1, 8.3), and a bare ``UTC`` or
|
||||
#: ``GMT``, which OpenWrt itself writes by default.
|
||||
_POSIX_TZ = re.compile(
|
||||
rf"(?:UTC|GMT)|{_ABBR}{_OFFSET}(?:{_ABBR}(?:{_OFFSET})?(?:,{_DATE},{_DATE})?)?"
|
||||
)
|
||||
|
||||
_PARTS = re.compile(
|
||||
rf"(?P<std>{_ABBR})(?P<offset>{_OFFSET})"
|
||||
rf"(?:(?P<dst>{_ABBR})(?P<dst_offset>{_OFFSET})?"
|
||||
r"(?:,(?P<start>[^,]+),(?P<end>[^,]+))?)?"
|
||||
)
|
||||
_TRANSITION = re.compile(r"M(\d{1,2})\.([1-5])\.([0-6])(?:/([+-]?\d{1,3}(?::\d{1,2}){0,2}))?")
|
||||
#: When a rule names no time of day for a transition: 02:00 local time.
|
||||
_DEFAULT_TRANSITION_TIME = 7200
|
||||
|
||||
|
||||
class DstTransitionDict(TypedDict):
|
||||
"""When summer time starts or ends: a weekday of a week of a month, and a time."""
|
||||
|
||||
month: int # 1-12
|
||||
week: int # 1-5; 5 is the month's last such weekday
|
||||
weekday: int # 0 = Sunday ... 6 = Saturday
|
||||
time: int # seconds after local midnight, in the time then in force; may be < 0 or > 24h
|
||||
|
||||
|
||||
class PosixTzDict(TypedDict):
|
||||
"""A POSIX TZ rule in parts (:func:`parse_posix_tz`)."""
|
||||
|
||||
std_name: str # "CET"; a quoted name without its <> ("-03")
|
||||
utc_offset: int # seconds east of UTC in standard time: CET 3600, EST -18000
|
||||
dst_name: str | None # "CEST"; None for a zone without summer time
|
||||
dst_offset: int | None # seconds east of UTC in summer time; None without it
|
||||
dst_start: DstTransitionDict | None # None without summer time or without a rule for it
|
||||
dst_end: DstTransitionDict | None
|
||||
|
||||
|
||||
class UnknownTimezone(ValueError):
|
||||
"""A zone that is not in the zone database (nor, where one is taken, a POSIX TZ rule)."""
|
||||
|
||||
def __init__(self, zone: str) -> None:
|
||||
super().__init__(zone)
|
||||
self.zone = zone
|
||||
|
||||
def __str__(self) -> str:
|
||||
return (
|
||||
f"unknown time zone {self.zone!r}: not a name of the IANA time zone database"
|
||||
" such as Europe/Berlin"
|
||||
)
|
||||
|
||||
|
||||
def is_posix_tz(value: str) -> bool:
|
||||
"""Whether *value* reads as a POSIX TZ string -- the form libc takes in ``TZ``."""
|
||||
return bool(_POSIX_TZ.fullmatch(value))
|
||||
|
||||
|
||||
@lru_cache(maxsize=512)
|
||||
def _footer(zone: str) -> str | None:
|
||||
"""The POSIX rule at the end of *zone*'s TZif file; None for no such zone."""
|
||||
if not _ZONE_NAME.fullmatch(zone):
|
||||
return None
|
||||
tzfile = files("tzdata").joinpath("zoneinfo", *zone.split("/"))
|
||||
if not tzfile.is_file():
|
||||
return None
|
||||
data = tzfile.read_bytes()
|
||||
if not data.startswith(b"TZif") or data[4:5] not in (b"2", b"3", b"4") or data[-1:] != b"\n":
|
||||
return None
|
||||
footer = data[:-1].rsplit(b"\n", 1)[-1].decode("ascii", "replace")
|
||||
return footer if is_posix_tz(footer) else None
|
||||
|
||||
|
||||
def is_iana_zone(zone: str) -> bool:
|
||||
"""Whether *zone* names a zone of the database (``Europe/Berlin``, ``UTC``)."""
|
||||
return _footer(zone) is not None
|
||||
|
||||
|
||||
def posix_tz(zone: str) -> str | None:
|
||||
"""The POSIX TZ string for *zone*: an IANA name's rule, a POSIX string as it is.
|
||||
|
||||
None when *zone* is neither -- a device given it would run on UTC.
|
||||
"""
|
||||
return _footer(zone) or (zone if is_posix_tz(zone) else None)
|
||||
|
||||
|
||||
def _seconds(value: str) -> int:
|
||||
"""``[+-]hh[:mm[:ss]]`` in seconds."""
|
||||
sign = -1 if value.startswith("-") else 1
|
||||
parts = [int(p) for p in value.lstrip("+-").split(":")]
|
||||
hours, minutes, seconds = (parts + [0, 0])[:3]
|
||||
return sign * (hours * 3600 + minutes * 60 + seconds)
|
||||
|
||||
|
||||
def _transition(value: str) -> DstTransitionDict | None:
|
||||
match = _TRANSITION.fullmatch(value)
|
||||
if match is None:
|
||||
return None
|
||||
month, week, weekday, time = match.groups()
|
||||
return {
|
||||
"month": int(month),
|
||||
"week": int(week),
|
||||
"weekday": int(weekday),
|
||||
"time": _DEFAULT_TRANSITION_TIME if time is None else _seconds(time),
|
||||
}
|
||||
|
||||
|
||||
def parse_posix_tz(rule: str) -> PosixTzDict | None:
|
||||
"""*rule* in parts; None for what is not a rule, or one with Julian-day transitions.
|
||||
|
||||
POSIX counts offsets west of UTC (``CET-1``); the parts count them east, as a
|
||||
device's "UTC+01:00" does. Summer time without an offset of its own is one hour
|
||||
ahead of standard time.
|
||||
"""
|
||||
if rule in ("UTC", "GMT"):
|
||||
rule += "0"
|
||||
match = _PARTS.fullmatch(rule)
|
||||
if match is None or not is_posix_tz(rule):
|
||||
return None
|
||||
utc_offset = -_seconds(match["offset"])
|
||||
parts: PosixTzDict = {
|
||||
"std_name": match["std"].strip("<>"),
|
||||
"utc_offset": utc_offset,
|
||||
"dst_name": None,
|
||||
"dst_offset": None,
|
||||
"dst_start": None,
|
||||
"dst_end": None,
|
||||
}
|
||||
if match["dst"] is None:
|
||||
return parts
|
||||
parts["dst_name"] = match["dst"].strip("<>")
|
||||
parts["dst_offset"] = (
|
||||
utc_offset + 3600 if match["dst_offset"] is None else -_seconds(match["dst_offset"])
|
||||
)
|
||||
if match["start"] is not None:
|
||||
start, end = _transition(match["start"]), _transition(match["end"])
|
||||
if start is None or end is None:
|
||||
return None
|
||||
parts["dst_start"], parts["dst_end"] = start, end
|
||||
return parts
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DstTransitionDict",
|
||||
"PosixTzDict",
|
||||
"UnknownTimezone",
|
||||
"is_iana_zone",
|
||||
"is_posix_tz",
|
||||
"parse_posix_tz",
|
||||
"posix_tz",
|
||||
]
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
What provisioning a VM from a cloud image needs to know about the guest.
|
||||
|
||||
The same for every hypervisor: which agent a guest runs so a QEMU-based
|
||||
hypervisor can read its IP, the network-config cloud-init and FreeBSD's
|
||||
nuageinit both read, how a packed cloud image is unpacked, and how a failure
|
||||
names the VM it left behind. How a hypervisor attaches, boots and talks to
|
||||
the VM stays in its driver.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
#: ``{guest_os: (packages, runcmd)}``: what cloud-init installs and runs so
|
||||
#: the hypervisor can read the guest's IP address back.
|
||||
GuestAgents = Mapping[str, tuple[tuple[str, ...], tuple[str, ...]]]
|
||||
|
||||
#: The QEMU guest agent per guest OS, for hypervisors built on QEMU. Package
|
||||
#: names and service commands were verified on FreeBSD 15.1 and OpenBSD 7.9
|
||||
#: cloud images (NetOrk/netork#793).
|
||||
QEMU_GUEST_AGENTS: GuestAgents = {
|
||||
"linux": (("qemu-guest-agent",), ("systemctl enable --now qemu-guest-agent",)),
|
||||
"freebsd": (
|
||||
("qemu-guest-agent",),
|
||||
("sysrc qemu_guest_agent_enable=YES", "service qemu-guest-agent start"),
|
||||
),
|
||||
"openbsd": (("qemu-ga",), ("rcctl enable qemu_ga", "rcctl start qemu_ga")),
|
||||
}
|
||||
|
||||
#: Suffix of a packed image -> the command that writes it unpacked to stdout.
|
||||
_DECOMPRESSORS = {
|
||||
"xz": "xz -dc",
|
||||
"gz": "gzip -dc",
|
||||
"bz2": "bzip2 -dc",
|
||||
"zst": "zstd -dc",
|
||||
}
|
||||
|
||||
|
||||
class VMProvisionIncomplete(RuntimeError):
|
||||
"""``create_vm_from_cloud_init`` failed after the VM was created.
|
||||
|
||||
The VM is still on the hypervisor, half built: ``vmid`` and ``node`` name it
|
||||
as ``VMProvisionResultDict`` would have, so the caller can remove it with
|
||||
``destroy_vm``. The failure itself is the ``__cause__`` (``raise ... from``),
|
||||
and the message is its own. A failure before the VM exists raises as before.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, vmid: str, node: str) -> None:
|
||||
super().__init__(message)
|
||||
self.vmid = vmid
|
||||
self.node = node
|
||||
|
||||
def __reduce__(self) -> tuple[Any, ...]:
|
||||
# The keyword-only arguments are not in ``args``, which is all that
|
||||
# pickle passes back by default.
|
||||
return (_vm_provision_incomplete, (str(self), self.vmid, self.node))
|
||||
|
||||
|
||||
def _vm_provision_incomplete(message: str, vmid: str, node: str) -> VMProvisionIncomplete:
|
||||
return VMProvisionIncomplete(message, vmid=vmid, node=node)
|
||||
|
||||
|
||||
def network_config(nics: list[tuple[str, bool]]) -> dict[str, Any] | None:
|
||||
"""Network-config v2: DHCP on every ``(mac, dhcp)`` NIC that asks for it.
|
||||
|
||||
Version 2 because FreeBSD's nuageinit reads no other: given the v1 that
|
||||
Proxmox generates, it fails and skips the rest of its first stage,
|
||||
runcmd included. ``None`` when no NIC wants DHCP, so the guest is left
|
||||
alone rather than told to configure nothing.
|
||||
"""
|
||||
ethernets = {
|
||||
f"nic{i}": {"match": {"macaddress": mac.lower()}, "dhcp4": True}
|
||||
for i, (mac, dhcp) in enumerate(nics)
|
||||
if dhcp
|
||||
}
|
||||
return {"version": 2, "ethernets": ethernets} if ethernets else None
|
||||
|
||||
|
||||
def split_compression(filename: str) -> tuple[str, str | None]:
|
||||
"""``(unpacked filename, command that unpacks to stdout)`` for *filename*.
|
||||
|
||||
The command is None for an image that is not packed, which is then
|
||||
imported as it is.
|
||||
"""
|
||||
stem, dot, suffix = filename.rpartition(".")
|
||||
command = _DECOMPRESSORS.get(suffix.lower()) if dot and stem else None
|
||||
return (stem, command) if command else (filename, None)
|
||||
Whitespace-only changes.
@@ -6,8 +6,9 @@ wireless access point in a single consumer device (e.g. AVM FritzBox,
|
||||
ISP-supplied DSL/cable routers). This base class merges the relevant
|
||||
subsets of :class:`~napalm_device_types.firewall.FirewallDriver` and
|
||||
:class:`~napalm_device_types.access_point.AccessPointDriver` plus
|
||||
gateway-specific operations (WAN status, port forwarding, connected
|
||||
hosts).
|
||||
gateway-specific operations (WAN status, connected hosts). Port
|
||||
forwarding is shared with firewalls, in
|
||||
:class:`~napalm_device_types.nat_vpn.NatVpnMixin`.
|
||||
|
||||
Usage::
|
||||
|
||||
@@ -18,24 +19,22 @@ Usage::
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import Dict, List
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
from napalm_device_types._ucd_metrics import IF_SKIP_DEFAULT, collect_ucd_metrics
|
||||
from napalm_device_types.dhcp import DhcpServerMixin
|
||||
from napalm_device_types.health_metrics import HealthMetricsMixin
|
||||
from napalm_device_types.models import (
|
||||
HealthMetricsDict,
|
||||
HostDict,
|
||||
NATTranslationDict,
|
||||
PortForwardDict,
|
||||
RadioStatusDict,
|
||||
SSIDDict,
|
||||
VPNTunnelDict,
|
||||
WANStatusDict,
|
||||
WirelessClientDict,
|
||||
)
|
||||
from napalm_device_types.nat_vpn import NatVpnMixin
|
||||
|
||||
|
||||
class ResidentialGatewayDriver(DeviceTypeDriver):
|
||||
TYPE_LABEL: str = "Gateway"
|
||||
class ResidentialGatewayDriver(NatVpnMixin, HealthMetricsMixin, DhcpServerMixin, DeviceTypeDriver):
|
||||
"""
|
||||
Abstract intermediate driver for residential gateways (router + firewall + AP).
|
||||
|
||||
@@ -44,154 +43,99 @@ class ResidentialGatewayDriver(DeviceTypeDriver):
|
||||
drivers must implement.
|
||||
"""
|
||||
|
||||
_SNMP_SKIP_IF = IF_SKIP_DEFAULT
|
||||
_SNMP_TX_ERR_IS_DROP: bool = False
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "residential_gateway"
|
||||
TYPE_LABEL: str = "Gateway"
|
||||
|
||||
@classmethod
|
||||
async def get_health_metrics(cls, snmp_get, snmp_walk) -> HealthMetricsDict:
|
||||
return await collect_ucd_metrics(
|
||||
snmp_get, snmp_walk,
|
||||
tx_err_is_drop=cls._SNMP_TX_ERR_IS_DROP,
|
||||
if_skip=cls._SNMP_SKIP_IF,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_wan_status(self) -> WANStatusDict:
|
||||
"""
|
||||
Returns the status of the device's internet (WAN) uplink.
|
||||
def get_wan_status(self) -> WANStatusDict:
|
||||
"""
|
||||
Returns the status of the device's internet (WAN) uplink.
|
||||
|
||||
Contains:
|
||||
Contains:
|
||||
|
||||
* connection_type (string) - e.g. ``"DSL"``, ``"Cable"``, ``"PPPoE"``, ``"DHCP"``
|
||||
* is_connected (bool) - whether the WAN connection is currently established
|
||||
* external_ip (string) - the public IPv4 address assigned to the WAN interface
|
||||
* uptime (int) - seconds since the WAN connection was last (re-)established
|
||||
* bytes_sent (int) - total bytes transmitted on the WAN interface
|
||||
* bytes_received (int) - total bytes received on the WAN interface
|
||||
* max_bitrate_up (int) - upstream sync rate in kbit/s
|
||||
* max_bitrate_down (int) - downstream sync rate in kbit/s
|
||||
* external_ipv6 (string, optional) - the public IPv6 address, if any
|
||||
* link_status (string, optional) - physical line state, e.g. ``"Up"`` / ``"Down"``
|
||||
* connection_type (string) - e.g. ``"DSL"``, ``"Cable"``, ``"PPPoE"``, ``"DHCP"``
|
||||
* is_connected (bool) - whether the WAN connection is currently established
|
||||
* external_ip (string) - the public IPv4 address assigned to the WAN interface
|
||||
* uptime (int) - seconds since the WAN connection was last (re-)established
|
||||
* bytes_sent (int) - total bytes transmitted on the WAN interface
|
||||
* bytes_received (int) - total bytes received on the WAN interface
|
||||
* max_bitrate_up (int) - upstream sync rate in kbit/s
|
||||
* max_bitrate_down (int) - downstream sync rate in kbit/s
|
||||
* external_ipv6 (string, optional) - the public IPv6 address, if any
|
||||
* link_status (string, optional) - physical line state, e.g. ``"Up"`` / ``"Down"``
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
{
|
||||
"connection_type": "DSL",
|
||||
"is_connected": True,
|
||||
"external_ip": "203.0.113.7",
|
||||
"uptime": 345600,
|
||||
"bytes_sent": 1234567890,
|
||||
"bytes_received": 9876543210,
|
||||
"max_bitrate_up": 40000,
|
||||
"max_bitrate_down": 250000,
|
||||
"link_status": "Up",
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_port_forwards(self) -> List[PortForwardDict]:
|
||||
"""
|
||||
Returns the configured port forwarding (port mapping) rules.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - the rule's description/name
|
||||
* protocol (string) - ``"TCP"`` or ``"UDP"``
|
||||
* external_port (int) - the WAN-side port
|
||||
* internal_ip (string) - the LAN host the traffic is forwarded to
|
||||
* internal_port (int) - the LAN-side port
|
||||
* enabled (bool) - whether the rule is currently active
|
||||
* remote_host (string, optional) - restricts the forward to a specific
|
||||
remote source address; empty/absent means "any"
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "Webserver HTTPS",
|
||||
"protocol": "TCP",
|
||||
"external_port": 443,
|
||||
"internal_ip": "192.168.1.10",
|
||||
"internal_port": 443,
|
||||
"enabled": True,
|
||||
"connection_type": "DSL",
|
||||
"is_connected": True,
|
||||
"external_ip": "203.0.113.7",
|
||||
"uptime": 345600,
|
||||
"bytes_sent": 1234567890,
|
||||
"bytes_received": 9876543210,
|
||||
"max_bitrate_up": 40000,
|
||||
"max_bitrate_down": 250000,
|
||||
"link_status": "Up",
|
||||
}
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"""
|
||||
...
|
||||
|
||||
def get_hosts(self) -> List[HostDict]:
|
||||
"""
|
||||
Returns the list of hosts known to the gateway (LAN clients).
|
||||
def get_hosts(self) -> list[HostDict]:
|
||||
"""
|
||||
Returns the list of hosts known to the gateway (LAN clients).
|
||||
|
||||
Each entry contains:
|
||||
Each entry contains:
|
||||
|
||||
* mac (string) - the host's MAC address
|
||||
* ip (string) - the host's current IP address
|
||||
* hostname (string) - the host's reported hostname (empty if unknown)
|
||||
* interface_type (string) - how the host is connected, e.g. ``"LAN"``, ``"WLAN"``
|
||||
* is_active (bool) - whether the host is currently online
|
||||
* lease_time_remaining (int, optional) - remaining DHCP lease time in seconds
|
||||
* mac (string) - the host's MAC address
|
||||
* ip (string) - the host's current IP address
|
||||
* hostname (string) - the host's reported hostname (empty if unknown)
|
||||
* interface_type (string) - how the host is connected, e.g. ``"LAN"``, ``"WLAN"``
|
||||
* is_active (bool) - whether the host is currently online
|
||||
* lease_time_remaining (int, optional) - remaining DHCP lease time in seconds
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"mac": "AA:BB:CC:DD:EE:FF",
|
||||
"ip": "192.168.1.42",
|
||||
"hostname": "laptop",
|
||||
"interface_type": "WLAN",
|
||||
"is_active": True,
|
||||
"lease_time_remaining": 3600,
|
||||
}
|
||||
]
|
||||
"""
|
||||
raise NotImplementedError
|
||||
[
|
||||
{
|
||||
"mac": "AA:BB:CC:DD:EE:FF",
|
||||
"ip": "192.168.1.42",
|
||||
"hostname": "laptop",
|
||||
"interface_type": "WLAN",
|
||||
"is_active": True,
|
||||
"lease_time_remaining": 3600,
|
||||
}
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_nat_translations(self) -> List[NATTranslationDict]:
|
||||
"""
|
||||
Returns a list of active NAT translation entries.
|
||||
def get_wireless_clients(self) -> list[WirelessClientDict]:
|
||||
"""
|
||||
Returns the list of wireless clients currently associated with the
|
||||
device's built-in access point(s).
|
||||
|
||||
See :meth:`napalm_device_types.firewall.FirewallDriver.get_nat_translations`
|
||||
for the entry format. Residential gateways typically derive this from
|
||||
the active port-forwarding/NAT-PT table rather than a live connection
|
||||
tracker; drivers that cannot provide this should return an empty list.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
See :meth:`napalm_device_types.access_point.AccessPointDriver.get_wireless_clients`
|
||||
for the entry format.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_vpn_tunnels(self) -> Dict[str, VPNTunnelDict]:
|
||||
"""
|
||||
Returns the status of VPN tunnels (e.g. WireGuard road-warrior
|
||||
access, IPsec site-to-site).
|
||||
def get_ssids(self) -> dict[str, SSIDDict]:
|
||||
"""
|
||||
Returns the configured wireless networks (SSIDs).
|
||||
|
||||
See :meth:`napalm_device_types.firewall.FirewallDriver.get_vpn_tunnels`
|
||||
for the entry format. Drivers that cannot provide this should return
|
||||
an empty dict.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
See :meth:`napalm_device_types.access_point.AccessPointDriver.get_ssids`
|
||||
for the entry format.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_wireless_clients(self) -> List[WirelessClientDict]:
|
||||
"""
|
||||
Returns the list of wireless clients currently associated with the
|
||||
device's built-in access point(s).
|
||||
def get_radio_status(self) -> dict[str, RadioStatusDict]:
|
||||
"""
|
||||
Returns the status of the device's wireless radios.
|
||||
|
||||
See :meth:`napalm_device_types.access_point.AccessPointDriver.get_wireless_clients`
|
||||
for the entry format.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_ssids(self) -> Dict[str, SSIDDict]:
|
||||
"""
|
||||
Returns the configured wireless networks (SSIDs).
|
||||
|
||||
See :meth:`napalm_device_types.access_point.AccessPointDriver.get_ssids`
|
||||
for the entry format.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_radio_status(self) -> Dict[str, RadioStatusDict]:
|
||||
"""
|
||||
Returns the status of the device's wireless radios.
|
||||
|
||||
See :meth:`napalm_device_types.access_point.AccessPointDriver.get_radio_status`
|
||||
for the entry format.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
See :meth:`napalm_device_types.access_point.AccessPointDriver.get_radio_status`
|
||||
for the entry format.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Which roles a driver class fills, and which of them is primary.
|
||||
|
||||
A *role* is what a device is: a firewall, a switch, a NAS. Real devices are
|
||||
often several at once -- a QNAP is storage, hypervisor and Linux host -- so a
|
||||
driver declares every role it fills by inheriting the matching base, and the
|
||||
**order of those bases is the ranking**::
|
||||
|
||||
class QnapQtsDriver(StorageDriver, HypervisorDriver, LinuxDriver):
|
||||
... # primary_role_of(...) == "storage"
|
||||
|
||||
That replaces the older arrangement, where an ``issubclass`` chain in netOrk
|
||||
picked a single winner by a fixed precedence and a ``DEVICE_CLASS`` attribute
|
||||
existed to overrule it. The author already states the ranking in the class
|
||||
definition; nothing needs to restate it.
|
||||
|
||||
Whether a driver can perform a *specific operation* is a separate question with
|
||||
a separate answer: ``hasattr``. Role bases declare their methods under
|
||||
``if TYPE_CHECKING`` and implement nothing, so a method exists at runtime only
|
||||
when a concrete driver provided it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _is_role_base(cls: type) -> bool:
|
||||
"""True for a class that introduces a role, not one that merely inherits one.
|
||||
|
||||
Keyed on ``ROLE`` appearing in the class's own ``__dict__``: a concrete
|
||||
driver inherits the attribute but does not define it, and must not be
|
||||
mistaken for a role base of its own.
|
||||
"""
|
||||
role = vars(cls).get("ROLE")
|
||||
return isinstance(role, str) and bool(role)
|
||||
|
||||
|
||||
def roles_of(driver_cls: type) -> list[type[Any]]:
|
||||
"""Every role base in ``driver_cls``'s MRO, most significant first.
|
||||
|
||||
MRO order is inheritance order, so the list reflects exactly what the driver
|
||||
author wrote in the class definition. A class that sets ``ROLE`` itself
|
||||
replaces the role it inherits rather than adding one: a Windows driver on
|
||||
:class:`~napalm_device_types.os.OSDriver` sets ``ROLE = "windows"`` and is
|
||||
not also ``"linux"``.
|
||||
"""
|
||||
roles = [cls for cls in driver_cls.__mro__ if _is_role_base(cls)]
|
||||
return [cls for cls in roles if not any(o is not cls and issubclass(o, cls) for o in roles)]
|
||||
|
||||
|
||||
def role_keys_of(driver_cls: type) -> list[str]:
|
||||
"""The stable string keys of :func:`roles_of`, e.g. ``["storage", "linux"]``."""
|
||||
return [vars(cls)["ROLE"] for cls in roles_of(driver_cls)]
|
||||
|
||||
|
||||
def primary_role_of(driver_cls: type) -> str | None:
|
||||
"""The driver's headline role, or ``None`` when it declares no role at all.
|
||||
|
||||
This is the value netOrk exposes as ``device_class``.
|
||||
"""
|
||||
keys = role_keys_of(driver_cls)
|
||||
return keys[0] if keys else None
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The backups running on a device right now.
|
||||
|
||||
A restart aborts every backup that runs on the device it restarts: a
|
||||
hypervisor's backup of its guests, a backup server's backup, sync, verify or
|
||||
garbage collection, a host's own file-level backup (restic, borg and the like).
|
||||
A guest's restart breaks the backup its hypervisor is taking of it. So an
|
||||
application that restarts a device asks first, right before the restart.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: a driver mixes this in when it can tell;
|
||||
``hasattr`` tells a caller whether it did. No role base carries it, and a driver
|
||||
without it cannot tell -- which is not the same as "nothing runs".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Literal, TypedDict, get_args
|
||||
|
||||
#: What a running backup does: the backup itself, or one of a backup server's
|
||||
#: jobs (``napalm_device_types.backups.BackupJobKind``).
|
||||
RunningBackupKind = Literal["backup", "sync", "verify", "gc", "prune", "tape"]
|
||||
RUNNING_BACKUP_KINDS: tuple[str, ...] = get_args(RunningBackupKind)
|
||||
|
||||
|
||||
class RunningBackupDict(TypedDict):
|
||||
"""One backup running on the device (``get_running_backups``)."""
|
||||
|
||||
kind: RunningBackupKind
|
||||
job: str | None # the job it runs for, as the platform names it; None: started by hand
|
||||
task: str | None # this run's id on the platform: a task id, a unit, a process id
|
||||
guests: list[str] # the guests (get_vms' ids) it is backing up now; [] for the host's own
|
||||
since: int | None # unix seconds it started; None when the platform does not say
|
||||
|
||||
|
||||
class RunningBackupsMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_running_backups(self) -> list[RunningBackupDict]:
|
||||
"""
|
||||
Returns the backups running on the device now; ``[]`` when none is.
|
||||
|
||||
Every entry runs on this device: restarting the device aborts it.
|
||||
A hypervisor names in ``guests`` the guests a backup is taking right
|
||||
now -- a guest that is locked for its backup counts, with or without
|
||||
a task the platform still shows -- so the application can tell a
|
||||
guest's own restart not to break it.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"kind": "backup",
|
||||
"job": "backup-3f2a9c1e-77d1",
|
||||
"task": "UPID:pve1:0001F2A3:00C4B1D2:6731A0C0:vzdump::root@pam:",
|
||||
"guests": ["101"],
|
||||
"since": 1793660400,
|
||||
},
|
||||
{
|
||||
"kind": "gc",
|
||||
"job": "store1",
|
||||
"task": "UPID:localhost:000004D2:...:garbage_collection:store1:root@pam:",
|
||||
"guests": [],
|
||||
"since": 1793664000,
|
||||
},
|
||||
]
|
||||
|
||||
:raises Exception: when the device could not be read; never an
|
||||
empty list for a failed read.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Scheduled jobs: what a host runs on its own schedule, and switching it on, off and now.
|
||||
|
||||
A host runs work on its own: cron lines, run-parts scripts, anacron, systemd
|
||||
timers, FreeBSD's ``periodic``, a firewall's or a NAS's own scheduled jobs, the
|
||||
Windows Task Scheduler. :class:`ScheduledJobsMixin` reads all of them as one
|
||||
shape, :class:`~napalm_device_types.models.ScheduledJobDict`, and acts on them.
|
||||
Declared under ``if TYPE_CHECKING`` like a role: nothing exists at runtime until
|
||||
a driver implements it. :class:`~napalm_device_types.scheduled_jobs_posix.PosixScheduledJobsMixin`
|
||||
is the implementation for a host reached through the command channel.
|
||||
|
||||
**Who owns a definition** is on every job (``managed_by``): ``package`` (installed
|
||||
by one), ``admin`` (written on the host), ``platform`` (generated by the device's
|
||||
own configuration -- OPNsense, OpenMediaVault, QTS, Windows), ``application`` (written
|
||||
through :meth:`put_scheduled_job`, under the ``name`` the application gave it).
|
||||
What the application makes of that is the application's.
|
||||
|
||||
**What may be done is on every job too** (``actions``): every job a driver can
|
||||
switch takes ``enable``, ``disable`` and ``run``; only an ``application`` job takes
|
||||
``edit`` and ``delete``. A driver never edits or removes a job it did not write.
|
||||
|
||||
**Never over a change it did not see.** Every write names the ``digest`` the caller
|
||||
saw. The driver reads the job again right before it writes and raises
|
||||
:class:`ScheduledJobChanged` when the definition differs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any, NotRequired, TypedDict
|
||||
|
||||
from napalm_device_types.cron import is_reboot, parse_cron
|
||||
|
||||
#: What :meth:`ScheduledJobsMixin.manage_scheduled_job` takes.
|
||||
ACTIONS = ("enable", "disable", "run")
|
||||
|
||||
#: What a job's ``actions`` may list beyond :data:`ACTIONS`.
|
||||
EDIT = "edit"
|
||||
DELETE = "delete"
|
||||
|
||||
KINDS = ("cron", "run_parts", "anacron", "systemd_timer", "periodic", "task")
|
||||
MANAGED_BY = ("package", "admin", "platform", "application")
|
||||
|
||||
#: Seconds a run now may take on the host before ``timeout`` stops it.
|
||||
RUN_TIMEOUT = 300
|
||||
|
||||
#: A job's name becomes a file and a unit name: lower case, digits, dashes.
|
||||
_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
|
||||
#: A user name as useradd and the BSDs take it.
|
||||
_USER = re.compile(r"[A-Za-z_][A-Za-z0-9_.-]{0,31}\$?")
|
||||
|
||||
#: The parts of a job that are its definition; what the host says of its runs is not.
|
||||
_DEFINITION = ("kind", "source", "run_as", "schedule", "command", "enabled")
|
||||
|
||||
|
||||
class ScheduledJobDict(TypedDict):
|
||||
"""A job the host runs on its own schedule (``get_scheduled_jobs``).
|
||||
|
||||
A cron line, a run-parts script, an anacron job, a systemd timer, a FreeBSD
|
||||
``periodic`` script, a platform's own job, a Windows task -- one shape for all
|
||||
of them (``napalm_device_types.scheduled_jobs``).
|
||||
"""
|
||||
|
||||
key: str # stable name on this host: "timer:apt-daily.timer", "cron:/etc/crontab:1a2b3c4d"
|
||||
kind: str # cron | run_parts | anacron | systemd_timer | periodic | task
|
||||
source: str # the file, unit file or configuration it is defined in
|
||||
run_as: str # the user it runs as
|
||||
schedule: str # as the host has it: "*/5 * * * *", "OnCalendar=daily", "daily"
|
||||
schedule_kind: str # cron | calendar | monotonic | period | triggers
|
||||
command: str # as the host has it
|
||||
enabled: bool
|
||||
managed_by: str # package | admin | platform | application
|
||||
digest: str # job_digest(): the definition as it is now
|
||||
actions: list[str] # what the driver can do to this job: enable, disable, run, edit, delete
|
||||
name: NotRequired[str] # the name an application gave a job it wrote (put_scheduled_job)
|
||||
description: NotRequired[str]
|
||||
last_run: NotRequired[str | None] # ISO 8601, UTC; where the host knows it
|
||||
last_result: NotRequired[str | None] # "success", or what the host says went wrong
|
||||
next_run: NotRequired[str | None] # ISO 8601, UTC; where the host knows it
|
||||
|
||||
|
||||
class ScheduledJobsReadingDict(TypedDict):
|
||||
"""Every scheduled job of a host, and the time zone its schedules are in."""
|
||||
|
||||
jobs: list[ScheduledJobDict]
|
||||
time_zone: str | None # IANA name ("Europe/Berlin"); None when the host does not say
|
||||
|
||||
|
||||
class ScheduledJobSpecDict(TypedDict):
|
||||
"""A job an application wants on the host (``put_scheduled_job``)."""
|
||||
|
||||
name: str # the job's name on the host, chosen by the application: [a-z0-9][a-z0-9-]*
|
||||
schedule: str # a cron expression (napalm_device_types.cron), "@reboot" included
|
||||
run_as: str
|
||||
command: str # one or more lines of POSIX sh; a platform may take its own (OPNsense: configd)
|
||||
enabled: bool
|
||||
description: NotRequired[str]
|
||||
|
||||
|
||||
class ScheduledJobResultDict(TypedDict):
|
||||
"""What an action on a scheduled job did."""
|
||||
|
||||
success: bool
|
||||
output: str # what the host said; for a run, what the job printed
|
||||
|
||||
|
||||
class ScheduledJobChanged(Exception): # noqa: N818 - a state, as the callers word it
|
||||
"""The job's definition differs from the digest the caller saw: nothing was written."""
|
||||
|
||||
|
||||
class ScheduledJobRefused(ValueError):
|
||||
"""The job cannot take what was asked of it, or the request itself is not valid."""
|
||||
|
||||
|
||||
def job_digest(job: dict[str, Any], *, content: str = "") -> str:
|
||||
"""The definition of *job* in 16 hex characters.
|
||||
|
||||
Over kind, source, run_as, schedule, command and enabled -- so enabling a job
|
||||
changes it -- and *content*: what the definition points at that the job's
|
||||
fields do not show, such as a run-parts script's checksum.
|
||||
"""
|
||||
parts = [job.get(field) for field in _DEFINITION] + [content]
|
||||
return hashlib.sha256(json.dumps(parts).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def check_job_name(name: str) -> None:
|
||||
""":raises ScheduledJobRefused: for a name a file or a unit could not carry safely."""
|
||||
if not _NAME.fullmatch(name or ""):
|
||||
raise ScheduledJobRefused(f"not a job name: {name!r} (a-z, 0-9 and -, at most 63)")
|
||||
|
||||
|
||||
def check_spec(spec: ScheduledJobSpecDict) -> None:
|
||||
""":raises ScheduledJobRefused: for a spec no host could be given as it is."""
|
||||
check_job_name(spec["name"])
|
||||
if not _USER.fullmatch(spec.get("run_as") or ""):
|
||||
raise ScheduledJobRefused(f"not a user name: {spec.get('run_as')!r}")
|
||||
if not (spec.get("command") or "").strip():
|
||||
raise ScheduledJobRefused("a job needs a command")
|
||||
if "\n" in (spec.get("description") or ""):
|
||||
raise ScheduledJobRefused("a description is one line")
|
||||
if not is_reboot(spec["schedule"]):
|
||||
try:
|
||||
parse_cron(spec["schedule"])
|
||||
except ValueError as exc:
|
||||
raise ScheduledJobRefused(str(exc)) from exc
|
||||
|
||||
|
||||
class ScheduledJobsMixin:
|
||||
"""Declares the scheduled-jobs contract; a driver that can implements it.
|
||||
|
||||
A verb a driver cannot do at all is ``None`` on the driver, as ``manage_service``
|
||||
is; a verb one job cannot take is missing from that job's ``actions``.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
|
||||
"""Every scheduled job of the host.
|
||||
|
||||
:raises ValueError: when the reading came back cut short -- never a
|
||||
shorter list.
|
||||
"""
|
||||
...
|
||||
|
||||
def manage_scheduled_job(
|
||||
self, key: str, action: str, *, digest: str
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Enable, disable or run the job *key* now.
|
||||
|
||||
:raises ScheduledJobChanged: when the job is no longer as *digest* says.
|
||||
:raises ScheduledJobRefused: when the job does not take *action*.
|
||||
:raises LookupError: when the host has no job *key*.
|
||||
"""
|
||||
...
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Create the job ``spec["name"]`` (*digest* None) or change it.
|
||||
|
||||
:raises ScheduledJobChanged: when the job is no longer as *digest*
|
||||
says, or when a job of that name is there although *digest* is None.
|
||||
:raises ScheduledJobRefused: for a spec :func:`check_spec` refuses, or
|
||||
one the host cannot take.
|
||||
"""
|
||||
...
|
||||
|
||||
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Delete the job *key*, which an application wrote.
|
||||
|
||||
:raises ScheduledJobChanged: when the job is no longer as *digest* says.
|
||||
:raises ScheduledJobRefused: when the job is not one an application wrote.
|
||||
:raises LookupError: when the host has no job *key*.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,493 @@
|
||||
"""Scheduled jobs on a POSIX host, over the command channel: cron and systemd timers.
|
||||
|
||||
:class:`PosixScheduledJobsMixin` implements
|
||||
:class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin` for a driver that has
|
||||
:meth:`~napalm_device_types.channel.CommandChannelMixin.run_command`. The driver
|
||||
mixes it in and sets the paths its host keeps jobs in; the defaults are Debian's.
|
||||
|
||||
**Reading** is one framed report as root (:mod:`napalm_device_types._scheduled_reading`).
|
||||
|
||||
**Switching** a cron or anacron line comments it out behind ``#napalm-disabled: ``
|
||||
and takes exactly that marker away again; a run-parts script loses or gets its
|
||||
execute bit; a timer is ``systemctl disable --now`` / ``enable --now``. A timer that
|
||||
cannot be switched (``static``) only runs.
|
||||
|
||||
**Writing** stages the new text as the login user and installs it as root with one
|
||||
fixed command: ``crontab -u <user> <file>`` for a user's crontab, ``install`` with
|
||||
the file's own mode and owner for a system file. Root never reads stdin. Before any
|
||||
write the job is read again and compared with the digest the caller saw.
|
||||
|
||||
**An application's own job** (:meth:`put_scheduled_job`) is a timer on a host with
|
||||
systemd -- ``<name>.timer`` and ``<name>.service`` in :attr:`UNIT_DIR`, the command
|
||||
in :attr:`JOB_SCRIPT_DIR` ``/<name>`` behind a marker and its cron expression --
|
||||
else a file in :attr:`OWN_CRON_D_DIR`, else marked lines in the user's crontab.
|
||||
|
||||
**Running now** is bounded by :data:`~napalm_device_types.scheduled_jobs.RUN_TIMEOUT`:
|
||||
a timer's unit by ``systemctl start`` and its journal since then, a cron line's
|
||||
command as its user the way cron runs it (``_crontab.run_script``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import shlex
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from napalm_device_types._crontab import (
|
||||
JOB_MARKER,
|
||||
CronLine,
|
||||
marked_lines,
|
||||
parse_anacrontab,
|
||||
parse_crontab,
|
||||
run_script,
|
||||
switched,
|
||||
with_job,
|
||||
without_job,
|
||||
)
|
||||
from napalm_device_types._scheduled_reading import (
|
||||
OWNERS_SH,
|
||||
SCHEDULE_HEADER,
|
||||
TIME_ZONE_SH,
|
||||
Paths,
|
||||
Reading,
|
||||
parse_reading,
|
||||
reading_command,
|
||||
)
|
||||
from napalm_device_types.cron import is_reboot, to_on_calendar
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
ACTIONS,
|
||||
RUN_TIMEOUT,
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobResultDict,
|
||||
ScheduledJobsMixin,
|
||||
ScheduledJobSpecDict,
|
||||
ScheduledJobsReadingDict,
|
||||
check_spec,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
_STAGE = 't=$(mktemp) && chmod 644 "$t" && cat > "$t" && printf %s "$t"'
|
||||
#: What a run keeps of the job's output.
|
||||
_OUTPUT_LIMIT = 64 * 1024
|
||||
_READ_TIMEOUT = 120
|
||||
|
||||
|
||||
def _command(argv: Sequence[str]) -> str:
|
||||
return shlex.join(argv)
|
||||
|
||||
|
||||
def _said(result: CommandResult) -> str:
|
||||
return "\n".join(p for p in (result.stdout.strip(), result.stderr.strip()) if p)[
|
||||
-_OUTPUT_LIMIT:
|
||||
]
|
||||
|
||||
|
||||
def _result(result: CommandResult, done: str) -> ScheduledJobResultDict:
|
||||
if result.exit_code != 0:
|
||||
return {"success": False, "output": _said(result) or f"exit {result.exit_code}"}
|
||||
return {"success": True, "output": _said(result) or done}
|
||||
|
||||
|
||||
class PosixScheduledJobsMixin(ScheduledJobsMixin):
|
||||
"""Scheduled jobs of a host reached through ``run_command``; the paths are the driver's."""
|
||||
|
||||
CRON_SYSTEM_FILES: ClassVar[tuple[str, ...]] = ("/etc/crontab",)
|
||||
CRON_D_DIRS: ClassVar[tuple[str, ...]] = ("/etc/cron.d",)
|
||||
CRON_SPOOL_DIRS: ClassVar[tuple[str, ...]] = (
|
||||
"/var/spool/cron/crontabs",
|
||||
"/var/spool/cron",
|
||||
"/etc/crontabs",
|
||||
)
|
||||
RUN_PARTS_DIRS: ClassVar[tuple[tuple[str, str], ...]] = (
|
||||
("hourly", "/etc/cron.hourly"),
|
||||
("daily", "/etc/cron.daily"),
|
||||
("weekly", "/etc/cron.weekly"),
|
||||
("monthly", "/etc/cron.monthly"),
|
||||
)
|
||||
ANACRONTAB: ClassVar[str] = "/etc/anacrontab"
|
||||
JOB_SCRIPT_DIR: ClassVar[str] = "/usr/local/libexec/scheduled-jobs"
|
||||
UNIT_DIR: ClassVar[str] = "/etc/systemd/system"
|
||||
#: Where a host without systemd takes an application's job as a file, if the directory
|
||||
#: is there; else, or None, the user's crontab.
|
||||
OWN_CRON_D_DIR: ClassVar[str | None] = "/etc/cron.d"
|
||||
ROOT_GROUP: ClassVar[str] = "root"
|
||||
#: Prints "<octal mode> <owner> <group>" of the path appended.
|
||||
STAT_ARGV: ClassVar[tuple[str, ...]] = ("stat", "-c", "%a %U %G", "--")
|
||||
#: ``install`` and how it makes missing directories (FreeBSD's ``-D`` is a destdir).
|
||||
INSTALL: ClassVar[tuple[str, ...]] = ("install", "-D")
|
||||
#: ``sh`` that reads definition paths on stdin and prints ``<package>: <path>``.
|
||||
OWNERS_SH: ClassVar[str] = OWNERS_SH
|
||||
#: ``sh`` that prints the time zone: an IANA name, or a path ending in ``zoneinfo/<name>``.
|
||||
TIME_ZONE_SH: ClassVar[str] = TIME_ZONE_SH
|
||||
#: ``fnmatch`` patterns on a job's ``source``: what the platform generates is ``platform``.
|
||||
PLATFORM_SOURCES: ClassVar[tuple[str, ...]] = ()
|
||||
#: Run as root after a user's crontab was written; for a host that keeps it elsewhere too.
|
||||
CRONTAB_AFTER_WRITE: ClassVar[tuple[str, ...] | None] = None
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
def _sj_paths(self) -> Paths:
|
||||
return Paths(
|
||||
system_files=self.CRON_SYSTEM_FILES,
|
||||
cron_d_dirs=self.CRON_D_DIRS,
|
||||
spool_dirs=self.CRON_SPOOL_DIRS,
|
||||
run_parts=self.RUN_PARTS_DIRS,
|
||||
anacrontab=self.ANACRONTAB,
|
||||
script_dir=self.JOB_SCRIPT_DIR,
|
||||
owners_sh=self.OWNERS_SH,
|
||||
time_zone_sh=self.TIME_ZONE_SH,
|
||||
)
|
||||
|
||||
def _sj_read(self) -> Reading:
|
||||
result = self.run_command(
|
||||
reading_command(self._sj_paths()), privileged=True, timeout=_READ_TIMEOUT
|
||||
)
|
||||
reading = parse_reading(result.stdout)
|
||||
for job in reading.jobs:
|
||||
source = str(job["source"])
|
||||
if job["managed_by"] != "application" and any(
|
||||
fnmatch.fnmatchcase(source, p) for p in self.PLATFORM_SOURCES
|
||||
):
|
||||
job["managed_by"] = "platform"
|
||||
return reading
|
||||
|
||||
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
|
||||
"""Every scheduled job of the host, in one round trip.
|
||||
|
||||
:raises ValueError: when the report came back cut short.
|
||||
"""
|
||||
reading = self._sj_read()
|
||||
return {"jobs": reading.jobs, "time_zone": reading.time_zone} # type: ignore[typeddict-item]
|
||||
|
||||
def _sj_job(self, reading: Reading, key: str, digest: str) -> dict[str, object]:
|
||||
job = next((j for j in reading.jobs if j["key"] == key), None)
|
||||
if job is None:
|
||||
raise LookupError(f"no scheduled job {key}")
|
||||
if job["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
|
||||
return job
|
||||
|
||||
# -- commands --------------------------------------------------------------------------------
|
||||
|
||||
def _sj_root(self, argv: Sequence[str], timeout: float = 60) -> CommandResult:
|
||||
return self.run_command(_command(argv), privileged=True, timeout=timeout)
|
||||
|
||||
def _sj_checked(self, argv: Sequence[str]) -> CommandResult:
|
||||
result = self._sj_root(argv)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"{_command(argv)}: {_said(result) or result.exit_code}")
|
||||
return result
|
||||
|
||||
def _sj_stage(self, content: str) -> str:
|
||||
result = self.run_command(_STAGE, timeout=30, stdin=content.encode())
|
||||
path = result.stdout.strip().splitlines()[-1:] or [""]
|
||||
if result.exit_code != 0 or not path[0].startswith("/"):
|
||||
raise RuntimeError(f"cannot stage a file: {_said(result)}")
|
||||
return path[0]
|
||||
|
||||
def _sj_install(self, content: str, path: str, mode: str, owner: str, group: str) -> None:
|
||||
staged = self._sj_stage(content)
|
||||
try:
|
||||
self._sj_checked(
|
||||
[*self.INSTALL, "-m", mode, "-o", owner, "-g", group, "--", staged, path]
|
||||
)
|
||||
finally:
|
||||
self.run_command(_command(["rm", "-f", "--", staged]), timeout=30)
|
||||
|
||||
# -- crontab files ---------------------------------------------------------------------------
|
||||
|
||||
def _sj_spool_user(self, path: str) -> str | None:
|
||||
"""The user whose crontab *path* is; None for a system file."""
|
||||
directory, _, user = path.rpartition("/")
|
||||
return user if directory in self.CRON_SPOOL_DIRS else None
|
||||
|
||||
def _sj_crontab(self, user: str) -> str:
|
||||
result = self._sj_root(["crontab", "-u", user, "-l"])
|
||||
if result.exit_code != 0:
|
||||
if "no crontab" in (result.stderr + result.stdout).lower():
|
||||
return ""
|
||||
raise RuntimeError(f"cannot read the crontab of {user}: {_said(result)}")
|
||||
return result.stdout
|
||||
|
||||
def _sj_text(self, path: str) -> str:
|
||||
user = self._sj_spool_user(path)
|
||||
if user is not None:
|
||||
return self._sj_crontab(user)
|
||||
return self._sj_checked(["cat", "--", path]).stdout
|
||||
|
||||
def _sj_write_crontab(self, user: str, text: str) -> None:
|
||||
staged = self._sj_stage(text)
|
||||
try:
|
||||
self._sj_checked(["crontab", "-u", user, staged])
|
||||
finally:
|
||||
self.run_command(_command(["rm", "-f", "--", staged]), timeout=30)
|
||||
if self.CRONTAB_AFTER_WRITE:
|
||||
self._sj_checked(self.CRONTAB_AFTER_WRITE)
|
||||
|
||||
def _sj_write(self, path: str, text: str) -> None:
|
||||
user = self._sj_spool_user(path)
|
||||
if user is not None:
|
||||
self._sj_write_crontab(user, text)
|
||||
return
|
||||
# Through a symbolic link to the file it names, with that file's mode: the
|
||||
# link's own mode is 777, and cron ignores a file anyone may write.
|
||||
real = self._sj_checked(["readlink", "-f", "--", path]).stdout.strip() or path
|
||||
mode, owner, group = self._sj_checked([*self.STAT_ARGV, real]).stdout.split()[:3]
|
||||
self._sj_install(text, real, mode, owner, group)
|
||||
|
||||
def _sj_line(self, job: dict[str, object], text: str) -> CronLine:
|
||||
"""The job's line in *text* as it is now, read again for the write."""
|
||||
path = str(job["source"])
|
||||
if job["kind"] == "anacron":
|
||||
found = parse_anacrontab(text)
|
||||
else:
|
||||
user = self._sj_spool_user(path)
|
||||
found = parse_crontab(path, text, system=user is None, user=user or "")
|
||||
line = next((ln for ln in found if ln.key == job["key"]), None)
|
||||
if line is None:
|
||||
raise ScheduledJobChanged(f"{job['key']} is no longer in {path}")
|
||||
return line
|
||||
|
||||
# -- switching and running -------------------------------------------------------------------
|
||||
|
||||
def _sj_timer_unit(self, job: dict[str, object]) -> str:
|
||||
key = str(job["key"])
|
||||
return f"{job['name']}.timer" if key.startswith("job:") else key.removeprefix("timer:")
|
||||
|
||||
def _sj_switch(self, job: dict[str, object], enabled: bool) -> ScheduledJobResultDict:
|
||||
word = "enabled" if enabled else "disabled"
|
||||
if job["kind"] == "systemd_timer":
|
||||
verb = "enable" if enabled else "disable"
|
||||
return _result(
|
||||
self._sj_root(["systemctl", verb, "--now", "--", self._sj_timer_unit(job)]), word
|
||||
)
|
||||
if job["kind"] == "run_parts":
|
||||
return _result(
|
||||
self._sj_root(["chmod", "+x" if enabled else "-x", "--", str(job["source"])]), word
|
||||
)
|
||||
path = str(job["source"])
|
||||
text = self._sj_text(path)
|
||||
self._sj_write(path, switched(text, self._sj_line(job, text), enabled=enabled))
|
||||
return {"success": True, "output": f"{job['key']} {word}"}
|
||||
|
||||
def _sj_as(self, user: str, script: str) -> list[str]:
|
||||
"""*script* run by ``sh`` as *user*, from root."""
|
||||
if user == "root":
|
||||
return ["sh", "-c", script]
|
||||
return ["su", "-s", "/bin/sh", user, "-c", script]
|
||||
|
||||
def _sj_run(self, job: dict[str, object], reading: Reading) -> ScheduledJobResultDict:
|
||||
bound = ["timeout", str(RUN_TIMEOUT)]
|
||||
wait = RUN_TIMEOUT + 30
|
||||
if job["kind"] == "systemd_timer":
|
||||
unit = reading.units[str(job["key"])]
|
||||
since = self.run_command("date +%s", timeout=30).stdout.strip()
|
||||
started = self._sj_root([*bound, "systemctl", "start", "--", unit], timeout=wait)
|
||||
journal = self._sj_root(
|
||||
[
|
||||
"journalctl",
|
||||
"-u",
|
||||
unit,
|
||||
"--since",
|
||||
f"@{since}",
|
||||
"--no-pager",
|
||||
"-o",
|
||||
"cat",
|
||||
"-n",
|
||||
"200",
|
||||
]
|
||||
)
|
||||
output = "\n".join(p for p in (_said(started), journal.stdout.strip()) if p)
|
||||
return {"success": started.exit_code == 0, "output": output or f"{unit} ran"}
|
||||
if job["kind"] == "run_parts":
|
||||
return _result(self._sj_root([*bound, str(job["source"])], timeout=wait), "ran")
|
||||
path = str(job["source"])
|
||||
line = self._sj_line(job, self._sj_text(path))
|
||||
script = run_script(line.command, line.env)
|
||||
return _result(
|
||||
self._sj_root([*bound, *self._sj_as(line.run_as, script)], timeout=wait), "ran"
|
||||
)
|
||||
|
||||
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Enable, disable or run the job *key* now; see :class:`ScheduledJobsMixin`."""
|
||||
if action not in ACTIONS:
|
||||
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
|
||||
reading = self._sj_read()
|
||||
job = self._sj_job(reading, key, digest)
|
||||
if action not in job["actions"]: # type: ignore[operator]
|
||||
raise ScheduledJobRefused(f"{key} cannot be told to {action} on this host")
|
||||
if action == "run":
|
||||
return self._sj_run(job, reading)
|
||||
return self._sj_switch(job, action == "enable")
|
||||
|
||||
# -- an application's own jobs ---------------------------------------------------------------
|
||||
|
||||
def _sj_own(
|
||||
self, reading: Reading, spec: ScheduledJobSpecDict, digest: str | None
|
||||
) -> dict[str, object] | None:
|
||||
current = next((j for j in reading.jobs if j["key"] == f"job:{spec['name']}"), None)
|
||||
if digest is None:
|
||||
if current is not None:
|
||||
raise ScheduledJobChanged(f"a job {spec['name']} is there already")
|
||||
return None
|
||||
if current is None:
|
||||
raise LookupError(f"no scheduled job job:{spec['name']}")
|
||||
if current["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"job:{spec['name']} changed on the host since it was read")
|
||||
return current
|
||||
|
||||
def _sj_group(self, user: str) -> str:
|
||||
result = self.run_command(_command(["id", "-gn", "--", user]), timeout=30)
|
||||
if result.exit_code != 0:
|
||||
raise ScheduledJobRefused(f"the host has no user {user}")
|
||||
return result.stdout.strip()
|
||||
|
||||
def _sj_calendar(self, schedule: str) -> list[str]:
|
||||
if is_reboot(schedule):
|
||||
return ["OnBootSec=1min"]
|
||||
lines = to_on_calendar(schedule)
|
||||
for line in lines:
|
||||
checked = self.run_command(
|
||||
_command(["systemd-analyze", "calendar", "--", line]), timeout=30
|
||||
)
|
||||
if checked.exit_code != 0:
|
||||
raise ScheduledJobRefused(f"systemd does not take {line!r}: {_said(checked)}")
|
||||
return [f"OnCalendar={line}" for line in lines]
|
||||
|
||||
def _sj_put_timer(self, spec: ScheduledJobSpecDict) -> None:
|
||||
name, description = spec["name"], spec.get("description") or spec["name"]
|
||||
script = f"{self.JOB_SCRIPT_DIR}/{name}"
|
||||
unit_description = description.replace("%", "%%")
|
||||
timer = "\n".join(
|
||||
[
|
||||
"[Unit]",
|
||||
f"Description={unit_description}",
|
||||
"",
|
||||
"[Timer]",
|
||||
*self._sj_calendar(spec["schedule"]),
|
||||
f"Unit={name}.service",
|
||||
"",
|
||||
"[Install]",
|
||||
"WantedBy=timers.target",
|
||||
"",
|
||||
]
|
||||
)
|
||||
service = "\n".join(
|
||||
[
|
||||
"[Unit]",
|
||||
f"Description={unit_description}",
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=oneshot",
|
||||
f"User={spec['run_as']}",
|
||||
f"ExecStart={script}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
body = f"#!/bin/sh\n{JOB_MARKER}{name} {spec.get('description') or ''}".rstrip()
|
||||
body += f"\n{SCHEDULE_HEADER}{spec['schedule']}\n{spec['command'].strip()}\n"
|
||||
self._sj_install(body, script, "750", "root", self._sj_group(spec["run_as"]))
|
||||
self._sj_install(service, f"{self.UNIT_DIR}/{name}.service", "644", "root", self.ROOT_GROUP)
|
||||
self._sj_install(timer, f"{self.UNIT_DIR}/{name}.timer", "644", "root", self.ROOT_GROUP)
|
||||
self._sj_checked(["systemctl", "daemon-reload"])
|
||||
verb = "enable" if spec["enabled"] else "disable"
|
||||
self._sj_checked(["systemctl", verb, "--now", "--", f"{name}.timer"])
|
||||
|
||||
def _sj_cron_text(self, spec: ScheduledJobSpecDict, *, system: bool) -> list[str]:
|
||||
if "\n" in spec["command"].strip():
|
||||
raise ScheduledJobRefused("a cron line holds one line of command")
|
||||
owner = f" {spec['run_as']}" if system else ""
|
||||
line = f"{spec['schedule']}{owner} {spec['command'].strip()}"
|
||||
return marked_lines(
|
||||
spec["name"], spec.get("description") or "", line, enabled=spec["enabled"]
|
||||
)
|
||||
|
||||
def _sj_cron_d(self) -> str | None:
|
||||
""":attr:`OWN_CRON_D_DIR` where the host has it; BusyBox crond reads none."""
|
||||
directory = self.OWN_CRON_D_DIR
|
||||
if directory is None:
|
||||
return None
|
||||
found = self.run_command(_command(["test", "-d", directory]), timeout=30)
|
||||
return directory if found.exit_code == 0 else None
|
||||
|
||||
def _sj_put_cron(self, spec: ScheduledJobSpecDict, current: dict[str, object] | None) -> None:
|
||||
if self._sj_cron_d() is not None:
|
||||
self._sj_group(spec["run_as"])
|
||||
text = "\n".join(self._sj_cron_text(spec, system=True)) + "\n"
|
||||
self._sj_install(
|
||||
text, f"{self.OWN_CRON_D_DIR}/{spec['name']}", "644", "root", self.ROOT_GROUP
|
||||
)
|
||||
return
|
||||
if current is not None and current["run_as"] != spec["run_as"]:
|
||||
self._sj_delete_cron(current)
|
||||
user = spec["run_as"]
|
||||
text = self._sj_crontab(user)
|
||||
jobs = parse_crontab("", text, system=False, user=user)
|
||||
self._sj_write_crontab(
|
||||
user, with_job(text, jobs, spec["name"], self._sj_cron_text(spec, system=False))
|
||||
)
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Create or change the application's own job; see :class:`ScheduledJobsMixin`."""
|
||||
check_spec(spec)
|
||||
reading = self._sj_read()
|
||||
current = self._sj_own(reading, spec, digest)
|
||||
if reading.systemd:
|
||||
self._sj_put_timer(spec)
|
||||
else:
|
||||
self._sj_put_cron(spec, current)
|
||||
return {
|
||||
"success": True,
|
||||
"output": f"job:{spec['name']} {'changed' if current else 'created'}",
|
||||
}
|
||||
|
||||
def _sj_delete_cron(self, job: dict[str, object]) -> None:
|
||||
path = str(job["source"])
|
||||
if self._sj_spool_user(path) is None:
|
||||
self._sj_checked(["rm", "-f", "--", path])
|
||||
return
|
||||
text = self._sj_text(path)
|
||||
jobs = parse_crontab(path, text, system=False, user=str(job["run_as"]))
|
||||
self._sj_write(path, without_job(text, jobs, str(job["name"])))
|
||||
|
||||
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Delete the application's job *key*; see :class:`ScheduledJobsMixin`."""
|
||||
job = self._sj_job(self._sj_read(), key, digest)
|
||||
if job["managed_by"] != "application":
|
||||
raise ScheduledJobRefused(
|
||||
f"{key} was not written by an application; it is only switched"
|
||||
)
|
||||
name = str(job["name"])
|
||||
if job["kind"] != "systemd_timer":
|
||||
self._sj_delete_cron(job)
|
||||
return {"success": True, "output": f"{key} deleted"}
|
||||
self._sj_root(["systemctl", "disable", "--now", "--", f"{name}.timer"])
|
||||
self._sj_checked(
|
||||
[
|
||||
"rm",
|
||||
"-f",
|
||||
"--",
|
||||
f"{self.UNIT_DIR}/{name}.timer",
|
||||
f"{self.UNIT_DIR}/{name}.service",
|
||||
f"{self.JOB_SCRIPT_DIR}/{name}",
|
||||
]
|
||||
)
|
||||
self._sj_checked(["systemctl", "daemon-reload"])
|
||||
return {"success": True, "output": f"{key} deleted"}
|
||||
@@ -0,0 +1,538 @@
|
||||
"""Service clusters: the configuration that says which services run together.
|
||||
|
||||
Two hosts that answer at one virtual IP may run the same service by accident.
|
||||
What proves a cluster is the configuration its members share. That 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 (netOrk #1125).
|
||||
|
||||
**What is read.**
|
||||
|
||||
- *Patroni*: every ``patroni.service`` and ``patroni@*.service`` unit systemd
|
||||
knows. Its configuration file -- the unit's first non-flag argument, else
|
||||
``/etc/patroni/config.yml`` -- gives ``scope``, ``name`` and
|
||||
``restapi.connect_address``. The REST API there (``/cluster``, which Patroni
|
||||
answers without a login) lists the members its DCS knows, each with its role:
|
||||
``leader``, ``sync_standby``, ``replica``. When it does not answer, the host
|
||||
is a member of its scope on its own.
|
||||
- *adguardhome-sync*: a running container whose image is adguardhome-sync.
|
||||
``ORIGIN_URL`` and ``REPLICA*_URL`` name the AdGuard Home instances it keeps in
|
||||
step: the origin pushes to every replica. A sync configured by a YAML file
|
||||
instead of its environment is not read.
|
||||
- *BunkerWeb*: a running instance container (``bunkerity/bunkerweb``) admits a
|
||||
manager's configuration pushes from the addresses in ``API_WHITELIST_IP``; a
|
||||
manager (``bunkerweb-all-in-one``, ``bunkerweb-scheduler``) names its
|
||||
instances in ``BUNKERWEB_INSTANCES``. BunkerWeb's own default whitelist,
|
||||
loopback and the docker network, names no one. A manager that keeps its
|
||||
instances in its database names none here: its workers name it.
|
||||
|
||||
**Filtered on the host.** The same configuration holds secrets -- Patroni's
|
||||
superuser and REST passwords, the sync's AdGuard logins, BunkerWeb's database
|
||||
URI. The command never prints a configuration: awk programs print allowlisted
|
||||
fields only, and a URL loses its ``user:password@``. The DCS endpoints stay on
|
||||
the host too; the members come from ``/cluster``.
|
||||
|
||||
**None is "did not look".** A Patroni configuration that exists but cannot be
|
||||
read, a host without systemd, a docker the login may not ask, a sync configured
|
||||
by file: that mechanism is None, and the caller keeps what it knew. ``[]`` is a
|
||||
host that has none.
|
||||
|
||||
**Root, and without it.** Patroni's configuration is the postgres user's alone.
|
||||
The whole script goes to the host as one ``sh -c`` argument; when the privileged
|
||||
call brings no report back, it runs again without privilege.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from napalm_device_types.models import (
|
||||
ServiceClusterDict,
|
||||
ServiceClusterMemberDict,
|
||||
ServiceClustersDict,
|
||||
)
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "SVCC_BEGIN"
|
||||
_END = "SVCC_END"
|
||||
#: Exists only while systemd runs as PID 1; a container may carry systemctl without.
|
||||
_SYSTEMD_RUN = "/run/systemd/system"
|
||||
_PATRONI_CONFIG = "/etc/patroni/config.yml"
|
||||
#: The container environment that may leave the host.
|
||||
_ENV_KEYS = "ORIGIN_URL|REPLICA[0-9]*_URL|API_WHITELIST_IP|BUNKERWEB_INSTANCES|API_HTTP_PORT"
|
||||
#: BunkerWeb's instance API, where a manager pushes its configuration.
|
||||
_BUNKERWEB_API_PORT = 5000
|
||||
|
||||
#: Fed a unit's ``systemctl show`` output: ``active <state>`` and ``config <path>``,
|
||||
#: the first argument of the command line that is no flag.
|
||||
_UNIT_AWK = " ".join(
|
||||
(
|
||||
r'/^ActiveState=/ { print "active " substr($0, 13); next }',
|
||||
r'/^ExecStart=/ { s = $0; i = index(s, "argv[]="); if (!i) next; s = substr(s, i + 7);'
|
||||
r' j = index(s, " ;"); if (j) s = substr(s, 1, j - 1); n = split(s, t, " ");'
|
||||
r' for (k = 2; k <= n; k++) if (!c && t[k] !~ /^-/) { print "config " t[k]; c = 1 } }',
|
||||
)
|
||||
)
|
||||
|
||||
#: Fed Patroni's YAML: ``scope``, ``name`` (top level only -- ``tags`` may carry a
|
||||
#: ``name`` too), ``restapi`` (its connect_address) and ``tls yes`` when the REST
|
||||
#: API has a certificate. Nothing else leaves the file.
|
||||
_PATRONI_AWK = " ".join(
|
||||
(
|
||||
r'function v(l) { sub(/^[^:]*:[ \t]*/, "", l); return l }',
|
||||
r'/^[A-Za-z_][A-Za-z0-9_]*:/ { sec = $0; sub(/:.*/, "", sec);'
|
||||
r' if (sec == "scope" || sec == "name") print sec " " v($0); next }',
|
||||
r'sec == "restapi" && /^[ \t]+connect_address:/ { print "restapi " v($0) }',
|
||||
r'sec == "restapi" && /^[ \t]+certfile:/ { print "tls yes" }',
|
||||
)
|
||||
)
|
||||
|
||||
#: Fed a container's environment, one ``KEY=value`` a line: the allowlisted keys,
|
||||
#: each URL without its ``user:password@``.
|
||||
_ENV_AWK = " ".join(
|
||||
(
|
||||
r'{ x = index($0, "="); if (!x) next; k = substr($0, 1, x - 1); v = substr($0, x + 1);',
|
||||
rf" if (k !~ /^({_ENV_KEYS})$/) next;",
|
||||
r' gsub(/:\/\/[^@\/ ]*@/, "://", v); print "env " k " " v }',
|
||||
)
|
||||
)
|
||||
|
||||
_PATRONI_SH = (
|
||||
f"if command -v systemctl >/dev/null 2>&1 && [ -d {_SYSTEMD_RUN} ]; then echo '[systemd]'; "
|
||||
"for u in $(systemctl list-units --all --plain --no-legend --type=service "
|
||||
"patroni.service 'patroni@*' 2>/dev/null | awk '{print $1}'); do "
|
||||
'echo "[patroni $u]"; '
|
||||
'o=$(systemctl show -p ActiveState -p ExecStart "$u" 2>/dev/null | '
|
||||
f"awk {quote(_UNIT_AWK)}); "
|
||||
'echo "$o"; '
|
||||
"f=$(echo \"$o\" | sed -n 's/^config //p' | head -n 1); "
|
||||
f'[ -n "$f" ] || f={_PATRONI_CONFIG}; '
|
||||
'if [ -r "$f" ]; then '
|
||||
f'p=$(awk {quote(_PATRONI_AWK)} "$f"); echo "$p"; '
|
||||
"r=$(echo \"$p\" | sed -n 's/^restapi //p' | head -n 1 | tr -d '\\042\\047 '); "
|
||||
's=http; case "$p" in *"tls yes"*) s=https;; esac; '
|
||||
'if [ -n "$r" ]; then '
|
||||
'b=$(curl -s -k -m 3 "$s://$r/cluster" 2>/dev/null || '
|
||||
'wget -q -T 3 --no-check-certificate -O - "$s://$r/cluster" 2>/dev/null); '
|
||||
'if [ -n "$b" ]; then echo "rest $(echo "$b" | tr -d \'\\n\')"; '
|
||||
"else echo rest-unreachable; fi; fi; "
|
||||
'elif [ -e "$f" ]; then echo "unreadable $f"; '
|
||||
'else echo "missing $f"; fi; '
|
||||
"done; "
|
||||
"else echo '[no-systemd]'; fi; "
|
||||
)
|
||||
|
||||
|
||||
def _docker_sh(binary: str | None) -> str:
|
||||
"""The containers part: running containers of the clustered images, their
|
||||
allowlisted environment. ``[no-docker]`` for a host without the engine."""
|
||||
if not binary:
|
||||
return "echo '[no-docker]'; "
|
||||
return (
|
||||
f"D={quote(binary)}; "
|
||||
'if command -v "$D" >/dev/null 2>&1; then '
|
||||
"if c=$(\"$D\" ps --format '{{.Names}}' 2>/dev/null); then echo '[docker]'; "
|
||||
"for n in $c; do "
|
||||
'i=$("$D" inspect --format \'{{.Config.Image}}\' "$n" 2>/dev/null); '
|
||||
'case "$i" in *adguardhome-sync*|*bunkerweb*) '
|
||||
'echo "[container $n]"; echo "image $i"; '
|
||||
'"$D" inspect --format \'{{range .Config.Env}}{{println .}}{{end}}\' "$n" '
|
||||
f"2>/dev/null | awk {quote(_ENV_AWK)};; esac; done; "
|
||||
"else echo '[docker-unreadable]'; fi; "
|
||||
"else echo '[no-docker]'; fi; "
|
||||
)
|
||||
|
||||
|
||||
def service_clusters_command(docker: str | None = "docker") -> str:
|
||||
"""One line of POSIX ``sh``, read-only. *docker* is the engine's binary as the
|
||||
driver reaches it (QNAP's lives elsewhere), None for a host without one. The
|
||||
frame markers are printed in two halves so that a transport which echoes the
|
||||
command does not show them early."""
|
||||
return (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' SVCC_ BEGIN; "
|
||||
+ _PATRONI_SH
|
||||
+ _docker_sh(docker)
|
||||
+ "printf '%s%s\\n' SVCC_ END"
|
||||
)
|
||||
|
||||
|
||||
SERVICE_CLUSTERS_COMMAND = service_clusters_command()
|
||||
|
||||
_COMMENT_RE = re.compile(r"\s+#.*$")
|
||||
_Record = tuple[str, str]
|
||||
_Section = tuple[str, str, list[_Record]]
|
||||
|
||||
|
||||
def _frame(output: 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 service cluster report in the output") from None
|
||||
return lines[start + 1 : end]
|
||||
|
||||
|
||||
def _sections(lines: list[str]) -> list[_Section]:
|
||||
"""``[<kind> <name>]`` headers, each with its records as ``(kind, rest)``."""
|
||||
sections: list[_Section] = []
|
||||
for line in lines:
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
kind, _, name = line[1:-1].partition(" ")
|
||||
sections.append((kind, name, []))
|
||||
elif line and sections:
|
||||
kind, _, rest = line.partition(" ")
|
||||
sections[-1][2].append((kind, rest.strip()))
|
||||
return sections
|
||||
|
||||
|
||||
def _clean(value: str) -> str:
|
||||
"""Without a trailing ``# comment`` and the quotes around it."""
|
||||
value = _COMMENT_RE.sub("", value.strip())
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
||||
value = value[1:-1]
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _member(
|
||||
*,
|
||||
address: str | None = None,
|
||||
port: int | None = None,
|
||||
name: str | None = None,
|
||||
role: str | None = None,
|
||||
state: str | None = None,
|
||||
this_host: bool = False,
|
||||
config_from: int | None = None,
|
||||
) -> ServiceClusterMemberDict:
|
||||
return {
|
||||
"name": name,
|
||||
"address": address,
|
||||
"port": port,
|
||||
"role": role,
|
||||
"state": state,
|
||||
"this_host": this_host,
|
||||
"config_from": config_from,
|
||||
}
|
||||
|
||||
|
||||
def _cluster(
|
||||
mechanism: str,
|
||||
service: str,
|
||||
source: str,
|
||||
cluster: str | None,
|
||||
members: list[ServiceClusterMemberDict],
|
||||
running: bool | None = True,
|
||||
) -> ServiceClusterDict:
|
||||
return {
|
||||
"mechanism": mechanism,
|
||||
"service": service,
|
||||
"source": source,
|
||||
"cluster": cluster,
|
||||
"running": running,
|
||||
"members": members,
|
||||
}
|
||||
|
||||
|
||||
def _host_port(text: str) -> tuple[str | None, int | None]:
|
||||
"""``"10.0.0.5:8008"`` or ``"[fd00::5]:8008"`` -> host and port."""
|
||||
try:
|
||||
split = urlsplit(f"//{text.strip()}")
|
||||
return split.hostname, split.port
|
||||
except ValueError:
|
||||
return None, None
|
||||
|
||||
|
||||
def _url(text: str) -> tuple[str | None, int | None]:
|
||||
"""A URL's host and port, the scheme's default where it names none."""
|
||||
value = text.strip()
|
||||
if "://" not in value:
|
||||
value = f"http://{value}"
|
||||
try:
|
||||
split = urlsplit(value)
|
||||
port = split.port or {"http": 80, "https": 443}.get(split.scheme)
|
||||
except ValueError:
|
||||
return None, None
|
||||
return split.hostname, port
|
||||
|
||||
|
||||
# --- Patroni ------------------------------------------------------------------
|
||||
|
||||
|
||||
def _patroni_members(rest: str, own: str | None) -> list[ServiceClusterMemberDict] | None:
|
||||
try:
|
||||
members = json.loads(rest).get("members")
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
if not isinstance(members, list):
|
||||
return None
|
||||
found = []
|
||||
for entry in members:
|
||||
if not isinstance(entry, dict) or not entry.get("name"):
|
||||
continue
|
||||
port = entry.get("port")
|
||||
found.append(
|
||||
_member(
|
||||
name=str(entry["name"]),
|
||||
address=str(entry["host"]) if entry.get("host") else None,
|
||||
port=port if isinstance(port, int) else None,
|
||||
role=str(entry["role"]) if entry.get("role") else None,
|
||||
state=str(entry["state"]) if entry.get("state") else None,
|
||||
this_host=entry["name"] == own,
|
||||
)
|
||||
)
|
||||
return sorted(found, key=lambda m: m["name"] or "")
|
||||
|
||||
|
||||
def _patroni(unit: str, records: list[_Record]) -> list[ServiceClusterDict]:
|
||||
values: dict[str, str] = {}
|
||||
rest: str | None = None
|
||||
for kind, text in records:
|
||||
if kind in ("active", "scope", "name", "restapi") and kind not in values:
|
||||
values[kind] = _clean(text)
|
||||
elif kind == "rest":
|
||||
rest = text
|
||||
scope = values.get("scope")
|
||||
if not scope:
|
||||
return []
|
||||
own = values.get("name") or None
|
||||
members = _patroni_members(rest, own) if rest else None
|
||||
if not members:
|
||||
address, _ = _host_port(values.get("restapi", ""))
|
||||
members = [_member(name=own, address=address, this_host=True)]
|
||||
running = values["active"] == "active" if "active" in values else None
|
||||
source = unit[: -len(".service")] if unit.endswith(".service") else unit
|
||||
return [_cluster("patroni", "patroni", source, scope, members, running)]
|
||||
|
||||
|
||||
# --- Containers ----------------------------------------------------------------
|
||||
|
||||
|
||||
def _env(records: list[_Record]) -> dict[str, str]:
|
||||
env: dict[str, str] = {}
|
||||
for kind, text in records:
|
||||
if kind == "env":
|
||||
key, _, value = text.partition(" ")
|
||||
env[key] = value.strip()
|
||||
return env
|
||||
|
||||
|
||||
def _image_name(records: list[_Record]) -> str:
|
||||
"""``bunkerity/bunkerweb@sha256:...`` -> ``bunkerweb``."""
|
||||
image = next((text for kind, text in records if kind == "image"), "")
|
||||
return image.split("@")[0].rsplit("/", 1)[-1].split(":")[0]
|
||||
|
||||
|
||||
def _adguardhome_sync(name: str, records: list[_Record]) -> list[ServiceClusterDict] | None:
|
||||
env = _env(records)
|
||||
origin = _url(env["ORIGIN_URL"]) if env.get("ORIGIN_URL") else (None, None)
|
||||
if origin[0] is None:
|
||||
return None # configured by its YAML file, which is not read
|
||||
replicas = sorted(
|
||||
(key for key in env if re.fullmatch(r"REPLICA[0-9]*_URL", key)),
|
||||
key=lambda key: int(key[7:-4] or 0),
|
||||
)
|
||||
members = [_member(address=origin[0], port=origin[1], role="origin")]
|
||||
for key in replicas:
|
||||
host, port = _url(env[key])
|
||||
if host:
|
||||
members.append(_member(address=host, port=port, role="replica", config_from=0))
|
||||
cluster = f"{origin[0]}:{origin[1]}" if origin[1] else origin[0]
|
||||
return [_cluster("adguardhome-sync", "adguardhome", name, cluster, members)]
|
||||
|
||||
|
||||
def _peer_address(entry: str) -> str | None:
|
||||
"""An entry of a whitelist that names one peer: a single address that is no
|
||||
loopback, link-local or unspecified one -- not a network."""
|
||||
text = entry.strip()
|
||||
if "/" in text:
|
||||
try:
|
||||
network = ipaddress.ip_network(text, strict=False)
|
||||
except ValueError:
|
||||
return None
|
||||
if network.num_addresses != 1:
|
||||
return None
|
||||
text = str(network.network_address)
|
||||
try:
|
||||
address = ipaddress.ip_address(text)
|
||||
except ValueError:
|
||||
return None
|
||||
if address.is_loopback or address.is_link_local or address.is_unspecified:
|
||||
return None
|
||||
return str(address)
|
||||
|
||||
|
||||
def _api_port(env: dict[str, str]) -> int:
|
||||
port = env.get("API_HTTP_PORT", "")
|
||||
return int(port) if port.isdigit() else _BUNKERWEB_API_PORT
|
||||
|
||||
|
||||
def _bunkerweb_worker(name: str, env: dict[str, str]) -> list[ServiceClusterDict]:
|
||||
managers = [
|
||||
address
|
||||
for entry in re.split(r"[\s,]+", env.get("API_WHITELIST_IP", ""))
|
||||
if entry and (address := _peer_address(entry))
|
||||
]
|
||||
if not managers:
|
||||
return []
|
||||
members = [_member(port=_api_port(env), role="worker", this_host=True, config_from=1)]
|
||||
members += [_member(address=address, role="manager") for address in managers]
|
||||
return [_cluster("bunkerweb", "bunkerweb", name, managers[0], members)]
|
||||
|
||||
|
||||
def _bunkerweb_manager(name: str, env: dict[str, str]) -> list[ServiceClusterDict]:
|
||||
instances = [entry for entry in env.get("BUNKERWEB_INSTANCES", "").split() if entry]
|
||||
if not instances:
|
||||
return []
|
||||
members = [_member(role="manager", this_host=True)]
|
||||
for entry in instances:
|
||||
host, port = _host_port(entry)
|
||||
if host:
|
||||
members.append(
|
||||
_member(
|
||||
address=host, port=port or _BUNKERWEB_API_PORT, role="worker", config_from=0
|
||||
)
|
||||
)
|
||||
return [_cluster("bunkerweb", "bunkerweb", name, None, members)] if len(members) > 1 else []
|
||||
|
||||
|
||||
def _bunkerweb(name: str, records: list[_Record]) -> list[ServiceClusterDict]:
|
||||
image = _image_name(records)
|
||||
if image == "bunkerweb":
|
||||
return _bunkerweb_worker(name, _env(records))
|
||||
if image in ("bunkerweb-all-in-one", "bunkerweb-scheduler"):
|
||||
return _bunkerweb_manager(name, _env(records))
|
||||
return [] # the UI, the API, autoconf: no instance and no manager
|
||||
|
||||
|
||||
_CONTAINER_READERS: dict[str, Callable[[str, list[_Record]], list[ServiceClusterDict] | None]] = {
|
||||
"adguardhome_sync": _adguardhome_sync,
|
||||
"bunkerweb": _bunkerweb,
|
||||
}
|
||||
|
||||
|
||||
def _reader_for(records: list[_Record]) -> str | None:
|
||||
image = next((text for kind, text in records if kind == "image"), "")
|
||||
if "adguardhome-sync" in image:
|
||||
return "adguardhome_sync"
|
||||
if "bunkerweb" in image:
|
||||
return "bunkerweb"
|
||||
return None
|
||||
|
||||
|
||||
def _containers(sections: list[_Section]) -> dict[str, list[ServiceClusterDict] | None]:
|
||||
kinds = {kind for kind, _, _ in sections}
|
||||
if "no-docker" in kinds:
|
||||
return {"adguardhome_sync": [], "bunkerweb": []}
|
||||
if "docker" not in kinds:
|
||||
return {"adguardhome_sync": None, "bunkerweb": None}
|
||||
found: dict[str, list[ServiceClusterDict] | None] = {"adguardhome_sync": [], "bunkerweb": []}
|
||||
for kind, name, records in sections:
|
||||
key = _reader_for(records) if kind == "container" else None
|
||||
if key is None or found[key] is None:
|
||||
continue
|
||||
clusters = _CONTAINER_READERS[key](name, records)
|
||||
if clusters is None:
|
||||
found[key] = None
|
||||
else:
|
||||
found[key].extend(clusters) # type: ignore[union-attr]
|
||||
return found
|
||||
|
||||
|
||||
def parse_service_clusters(output: str) -> ServiceClustersDict:
|
||||
"""Parse what :func:`service_clusters_command` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
patroni: list[ServiceClusterDict] | None
|
||||
if any(kind == "no-systemd" for kind, _, _ in sections):
|
||||
patroni = None
|
||||
elif any(
|
||||
kind == "patroni" and any(r[0] == "unreadable" for r in records)
|
||||
for kind, _, records in sections
|
||||
):
|
||||
patroni = None
|
||||
else:
|
||||
patroni = [
|
||||
c
|
||||
for kind, unit, records in sections
|
||||
if kind == "patroni"
|
||||
for c in _patroni(unit, records)
|
||||
]
|
||||
containers = _containers(sections)
|
||||
return {
|
||||
"patroni": patroni,
|
||||
"adguardhome_sync": containers["adguardhome_sync"],
|
||||
"bunkerweb": containers["bunkerweb"],
|
||||
}
|
||||
|
||||
|
||||
class ServiceClustersMixin:
|
||||
"""Adds :meth:`get_service_clusters` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are
|
||||
the same everywhere, so they are concrete here, and a driver supplies only
|
||||
:meth:`_run_service_clusters_command` -- how a command reaches its host, and
|
||||
how it gains root there. A driver with a container engine of its own path
|
||||
(``ContainerEngineMixin._container_engine_binary``) has it asked with that.
|
||||
Mixed in by the drivers that can, so ``hasattr(driver,
|
||||
"get_service_clusters")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_service_clusters_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root when
|
||||
*privileged*. The command is a single ``sh -c`` invocation of a few kB:
|
||||
send it on an exec channel, not typed into a shell."""
|
||||
...
|
||||
|
||||
def _service_clusters_docker(self) -> str:
|
||||
binary = getattr(self, "_container_engine_binary", None)
|
||||
return binary("docker") if callable(binary) else "docker"
|
||||
|
||||
def get_service_clusters(self) -> ServiceClustersDict:
|
||||
"""
|
||||
Returns the clusters the host's configuration says it belongs to, per
|
||||
mechanism: Patroni (its scope and the members its DCS lists),
|
||||
adguardhome-sync (its origin and replicas), BunkerWeb (a worker's manager,
|
||||
a manager's instances). See :class:`~napalm_device_types.models.ServiceClusterDict`.
|
||||
|
||||
None for a mechanism means it could not be read; ``[]`` that the host has none.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"patroni": [
|
||||
{"mechanism": "patroni", "service": "patroni", "source": "patroni",
|
||||
"cluster": "netork-db",
|
||||
"running": True,
|
||||
"members": [
|
||||
{"name": "db-01", "address": "10.7.234.12", "port": 5432,
|
||||
"role": "leader", "state": "running", "this_host": True,
|
||||
"config_from": None},
|
||||
{"name": "db-02", "address": "10.7.234.11", "port": 5432,
|
||||
"role": "sync_standby", "state": "streaming", "this_host": False,
|
||||
"config_from": None},
|
||||
]},
|
||||
],
|
||||
"adguardhome_sync": [],
|
||||
"bunkerweb": [],
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(service_clusters_command(self._service_clusters_docker()))}"
|
||||
try:
|
||||
return parse_service_clusters(
|
||||
self._run_service_clusters_command(command, privileged=True)
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
return parse_service_clusters(self._run_service_clusters_command(command, privileged=False))
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Which installed packages a systemd service is made of.
|
||||
|
||||
A vulnerability is found on a *package*; a statement about a *service* -- the
|
||||
postgresql unit, nginx -- reaches its findings only once it is known which
|
||||
packages that service is. Here that is the package shipping the unit file and
|
||||
the one shipping the binary its ``ExecStart`` runs: ``nginx-common`` and
|
||||
``nginx-core``, ``postgresql-common`` and ``postgresql-16``. Reading it is the
|
||||
same on every systemd host, so the command and its parse live here once and a
|
||||
driver only carries the command across.
|
||||
|
||||
**Only the unit's own packages.** The libraries its binary links against
|
||||
(``libssl3`` under nginx) are every service's at once; a statement about nginx
|
||||
is not one about libc, and following the dependencies would make it one.
|
||||
|
||||
The command is read-only and needs no privileges. It prints ``systemctl show``
|
||||
for every loaded service unit and then asks the package manager about every
|
||||
path at once: ``dpkg -S`` once for all of them -- one call, since each loads the
|
||||
whole file list, and per path that is minutes on an ordinary host -- or
|
||||
``rpm -qf`` per path. dpkg knows a file by the path its package shipped, so each
|
||||
path is asked across the ``/usr`` merge too. The report is framed; one whose end
|
||||
is missing raises, because a list cut short must never read as services that own
|
||||
nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
_BEGIN = "SVCPKG_BEGIN"
|
||||
_END = "SVCPKG_END"
|
||||
_SUFFIX = ".service"
|
||||
|
||||
#: A Debian or RPM package name.
|
||||
_PACKAGE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9+._-]*$")
|
||||
#: The binary of an ``ExecStart`` as ``systemctl show`` prints it.
|
||||
_EXEC_PATH = re.compile(r"\bpath=(/[^ ;]+)")
|
||||
|
||||
#: Every unit file and ``ExecStart`` binary in ``$s``, each also across the
|
||||
#: ``/usr`` merge, one per line.
|
||||
_PATHS = (
|
||||
"printf '%s\\n' \"$s\" | sed -n -e 's/^FragmentPath=\\(\\/.*\\)/\\1/p' "
|
||||
"-e 's/^ExecStart=.*path=\\(\\/[^ ;]*\\).*/\\1/p' | sort -u "
|
||||
"| sed -e 'p' -e 's#^/usr/#/#;t' -e 's#^/#/usr/#'"
|
||||
)
|
||||
|
||||
#: 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.
|
||||
SERVICE_PACKAGES_COMMAND = (
|
||||
"s=$(systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null "
|
||||
"| awk '{print $1}' | tr '\\n' '\\0' | xargs -0 -r systemctl show --no-pager "
|
||||
"-p Id -p FragmentPath -p ExecStart -- 2>/dev/null); "
|
||||
"printf '%s%s\\n' SVCPKG_ BEGIN; echo '[units]'; printf '%s\\n\\n' \"$s\"; "
|
||||
"if command -v dpkg >/dev/null 2>&1; then echo '[dpkg]'; "
|
||||
f"{_PATHS} | tr '\\n' '\\0' | xargs -0 -r dpkg -S 2>/dev/null; "
|
||||
"elif command -v rpm >/dev/null 2>&1; then echo '[rpm]'; "
|
||||
f"{_PATHS} | while IFS= read -r f; do "
|
||||
'printf \'%s\\t%s\\n\' "$f" "$(rpm -qf --qf \'%{NAME} \' "$f" 2>/dev/null)"; done; fi; '
|
||||
"printf '%s%s\\n' SVCPKG_ END"
|
||||
)
|
||||
|
||||
|
||||
def _report(output: str) -> dict[str, list[str]]:
|
||||
lines = [line.rstrip() for line in 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 service package report in the output") from None
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] | None = None
|
||||
for line in lines[start + 1 : end]:
|
||||
if line in ("[units]", "[dpkg]", "[rpm]"):
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
elif current is not None:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _units(lines: list[str]) -> dict[str, set[str]]:
|
||||
"""``systemctl show`` blocks -> ``{unit: its unit file and binary}``."""
|
||||
units: dict[str, set[str]] = {}
|
||||
unit = ""
|
||||
paths: set[str] = set()
|
||||
for line in [*lines, ""]:
|
||||
key, _, value = line.partition("=")
|
||||
if not line.strip():
|
||||
if unit:
|
||||
units[unit] = paths
|
||||
unit, paths = "", set()
|
||||
elif key == "Id" and value.endswith(_SUFFIX):
|
||||
unit = value[: -len(_SUFFIX)]
|
||||
elif key == "FragmentPath" and value.startswith("/"):
|
||||
paths.add(value)
|
||||
elif key == "ExecStart":
|
||||
match = _EXEC_PATH.search(value)
|
||||
if match:
|
||||
paths.add(match.group(1))
|
||||
return units
|
||||
|
||||
|
||||
def _names(raw: str) -> set[str]:
|
||||
"""``libfoo1:amd64, foo-bin`` -> ``{"libfoo1", "foo-bin"}``; nothing else counts."""
|
||||
found = set()
|
||||
for name in raw.replace(",", " ").split():
|
||||
name = name.split(":", 1)[0]
|
||||
if _PACKAGE.match(name):
|
||||
found.add(name)
|
||||
return found
|
||||
|
||||
|
||||
def _owners(sections: dict[str, list[str]]) -> dict[str, set[str]]:
|
||||
"""``{path: the packages owning it}`` from dpkg's or rpm's answer."""
|
||||
owners: dict[str, set[str]] = {}
|
||||
for line in sections.get("dpkg", []):
|
||||
# "pkg[, pkg2][:arch]: /path"; "diversion by x from: /path" is no owner.
|
||||
if line.startswith("diversion by") or ": /" not in line:
|
||||
continue
|
||||
names, _, path = line.partition(": /")
|
||||
owners.setdefault("/" + path.strip(), set()).update(_names(names))
|
||||
for line in sections.get("rpm", []):
|
||||
path, _, names = line.partition("\t")
|
||||
if " is not owned" not in names:
|
||||
owners.setdefault(path.strip(), set()).update(_names(names))
|
||||
return owners
|
||||
|
||||
|
||||
def _across_usr_merge(path: str) -> tuple[str, str]:
|
||||
return (path, path[4:] if path.startswith("/usr/") else "/usr" + path)
|
||||
|
||||
|
||||
def parse_service_packages(output: str) -> dict[str, list[str]]:
|
||||
"""Parse what :data:`SERVICE_PACKAGES_COMMAND` printed.
|
||||
|
||||
``{unit name without ".service": its packages, sorted}``. A unit no package
|
||||
owns -- a unit file an admin wrote -- maps to an empty list: read, and none.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _report(output)
|
||||
owners = _owners(sections)
|
||||
return {
|
||||
unit: sorted(
|
||||
{name for p in paths for alt in _across_usr_merge(p) for name in owners.get(alt, ())}
|
||||
)
|
||||
for unit, paths in _units(sections.get("units", [])).items()
|
||||
}
|
||||
|
||||
|
||||
class ServicePackagesMixin:
|
||||
"""Adds :meth:`get_service_packages` to a driver that can run a command on a systemd host.
|
||||
|
||||
The template form, like :class:`~napalm_device_types.kernel.KernelFactsMixin`:
|
||||
the reading and its parse are concrete here, and a driver supplies only
|
||||
:meth:`_run_service_packages_command` -- how a command reaches its host.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_service_packages_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
def get_service_packages(self) -> dict[str, list[str]]:
|
||||
"""
|
||||
Returns, per systemd service, the installed packages it is made of.
|
||||
|
||||
The package that ships its unit file and the one that ships the binary
|
||||
its ``ExecStart`` runs -- not the libraries that binary links against.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"nginx": ["nginx-common", "nginx-core"],
|
||||
"postgresql@16-main": ["postgresql-16", "postgresql-common"],
|
||||
"local-backup": [],
|
||||
}
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
return parse_service_packages(self._run_service_packages_command(SERVICE_PACKAGES_COMMAND))
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Init-system services: listing them and starting/stopping them.
|
||||
|
||||
Deliberately *not* the same thing as a NAS's exported shares, which live on
|
||||
``StorageDriver`` as ``get_storage_services``. Those two used to
|
||||
share the name ``get_services`` with incompatible return types, which is why
|
||||
a QNAP -- storage and OS at once -- could not satisfy both.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: these are contracts, not placeholders.
|
||||
Nothing exists at runtime until a concrete driver implements it, so mixing
|
||||
this class in can never shadow a working implementation from a sibling base.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import ServiceDict
|
||||
|
||||
|
||||
class ServiceControlMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_services(self) -> list[ServiceDict]:
|
||||
"""
|
||||
Returns the list of system services known to the device's init system.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - service name as registered with the init system
|
||||
* running (bool) - ``True`` if the service process is currently running
|
||||
* enabled (bool) - ``True`` if the service starts automatically at boot
|
||||
* pid (int) - process ID of the main service process; 0 if not running
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{"name": "lldpd", "running": True, "enabled": True, "pid": 2341},
|
||||
{"name": "sshd", "running": True, "enabled": True, "pid": 1198},
|
||||
{"name": "cron", "running": False, "enabled": False, "pid": 0},
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]:
|
||||
"""
|
||||
Execute a lifecycle action on a named service.
|
||||
|
||||
:param name: Service name as returned by :meth:`get_services`.
|
||||
:param action: One of ``start``, ``stop``, ``restart``, ``enable``, ``disable``.
|
||||
:returns: ``{"success": bool, "output": str}``
|
||||
:raises ValueError: If ``name`` or ``action`` is invalid.
|
||||
:raises NotImplementedError: If the driver does not support service management.
|
||||
"""
|
||||
...
|
||||
@@ -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))
|
||||
@@ -0,0 +1,60 @@
|
||||
"""The shape a driver states its device's SNMP health OIDs in (``SNMP_HEALTH_PROFILE``).
|
||||
|
||||
Apart from ``models.py``, which is over the file size limit; ``models`` still exports them.
|
||||
"""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
|
||||
class SnmpValueSpec(TypedDict, total=False):
|
||||
"""Where an SNMP agent publishes one value, inside a ``SnmpHealthProfile``.
|
||||
|
||||
Either ``oids``, scalars asked in order (the first non-empty answer wins), or
|
||||
``table``, a column walked and folded to one value by ``fold``. ``pattern`` is a
|
||||
regular expression whose first group is the number, for an agent that answers
|
||||
with text.
|
||||
|
||||
``unknown`` says the agent answers this value wrongly, or not at all, where it
|
||||
should: the application reports no value -- neither the standard reading nor a
|
||||
default. It stands alone, without ``oids`` or ``table``.
|
||||
"""
|
||||
|
||||
oids: list[str]
|
||||
table: str
|
||||
fold: Literal["first", "average", "max"]
|
||||
pattern: str
|
||||
unknown: bool
|
||||
|
||||
|
||||
class SnmpMemorySpec(TypedDict, total=False):
|
||||
"""Memory: ``total`` with ``used`` or ``free``, or ``percent`` alone."""
|
||||
|
||||
total: SnmpValueSpec
|
||||
used: SnmpValueSpec
|
||||
free: SnmpValueSpec
|
||||
percent: SnmpValueSpec
|
||||
unit: Literal["KiB", "bytes"] # of total, used and free; KiB, as UCD-MIB counts, by default
|
||||
|
||||
|
||||
class SnmpInterfacesSpec(TypedDict, total=False):
|
||||
"""How the IF-MIB counters of a device are to be read."""
|
||||
|
||||
skip: str # a pattern of interface names whose counters are noise, not signal
|
||||
tx_errors_are_drops: bool # the device counts dropped packets as TX errors (OPNsense)
|
||||
|
||||
|
||||
class SnmpHealthProfile(TypedDict, total=False):
|
||||
"""Where a device's SNMP agent publishes its health values.
|
||||
|
||||
A driver declares it as ``SNMP_HEALTH_PROFILE`` when its device does not answer
|
||||
the standard UCD-MIB and IF-MIB; the application polls and computes. What a
|
||||
profile does not name is read the standard way, and what it marks ``unknown`` is
|
||||
not read at all. Uptime is in TimeTicks, CPU in percent busy.
|
||||
"""
|
||||
|
||||
uptime: SnmpValueSpec
|
||||
cpu: SnmpValueSpec
|
||||
memory: SnmpMemorySpec
|
||||
interfaces: SnmpInterfacesSpec
|
||||
@@ -0,0 +1,354 @@
|
||||
"""SSH host keys: trust on first use, and a changed key refused before any login.
|
||||
|
||||
A driver that accepts whatever host key answers at a device's address logs in
|
||||
there with the device's credentials, whoever that is (NetOrk/netork#1167). The
|
||||
layer above keeps the store of the keys it trusts; a driver only verifies:
|
||||
|
||||
* It receives the keys to expect in ``optional_args["ssh_host_keys"]``
|
||||
(:data:`KNOWN_KEYS_ARG`), by the port they were seen on:
|
||||
``{"22": {"key_type": "ssh-ed25519", "key": "<base64>"}}``, the two fields of
|
||||
a ``known_hosts`` line. A driver takes the one for the port it connects to, so
|
||||
the caller need not know which port that is (Proxmox: its API on 8006, SSH on
|
||||
22). With a key, any other key is refused before a password or a private key
|
||||
leaves the caller. Without one, the first key is accepted: trust on first use.
|
||||
* It reports every key it sees through ``optional_args["ssh_host_key_observer"]``
|
||||
(:data:`OBSERVER_ARG`), a callable that receives one dict per connection::
|
||||
|
||||
{"host": str, "port": int,
|
||||
"seen": {"key_type", "key", "fingerprint"},
|
||||
"expected": {...} | None,
|
||||
"accepted": bool}
|
||||
|
||||
``accepted`` is False only for a refused key; the connection then raises
|
||||
:class:`SshHostKeyMismatch`. A failing observer is logged and ignored, so the
|
||||
store being away never stops a connection that verified.
|
||||
|
||||
A caller that passes neither keeps working as before (first use, every time),
|
||||
and a driver that ignores both still connects for a caller that passes them:
|
||||
old and new versions on either side do not break each other.
|
||||
|
||||
A connection sshd turns away before its banner -- OpenSSH 9.8+ does that to a
|
||||
source it has just penalised -- is tried again after a pause
|
||||
(:func:`retry_refused`, :data:`REFUSED_RETRY_WAITS`); :meth:`HostKeyCheck.connect`
|
||||
does so itself, a netmiko driver wraps its ``ConnectHandler`` in it.
|
||||
|
||||
:class:`HostKeyCheck` is the one implementation, for a paramiko ``SSHClient``
|
||||
(:meth:`~HostKeyCheck.connect`) and for netmiko (:meth:`~HostKeyCheck.netmiko`,
|
||||
then :meth:`~HostKeyCheck.observe`). Like :mod:`napalm_device_types.channel` it
|
||||
works on the objects paramiko hands it and imports no SSH library itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The ``optional_args`` key that carries the host keys to expect, by port.
|
||||
KNOWN_KEYS_ARG = "ssh_host_keys"
|
||||
#: The ``optional_args`` key that carries the callable every seen key goes to.
|
||||
OBSERVER_ARG = "ssh_host_key_observer"
|
||||
|
||||
#: The waits before each new attempt when sshd turns a connection away before its
|
||||
#: banner. OpenSSH 9.8+ does that to every connection from a source it has just
|
||||
#: penalised (``PerSourcePenalties``) -- one whose connections did not
|
||||
#: authenticate, a scanner's probes -- for seconds to minutes. 26 s in all
|
||||
#: outlasts the 16 s penalty seen on a new Ubuntu 26.04 host (NetOrk/netork#1800).
|
||||
REFUSED_RETRY_WAITS = (1.0, 3.0, 7.0, 15.0)
|
||||
|
||||
#: The netmiko arguments this module decides; a caller's own values give way.
|
||||
_NETMIKO_HOST_KEY_ARGS = ("ssh_strict", "system_host_keys", "alt_host_keys", "alt_key_file")
|
||||
|
||||
_DEFAULT_SSH_PORT = 22
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SshHostKey:
|
||||
"""A host's public key, as the two fields of a ``known_hosts`` line."""
|
||||
|
||||
key_type: str
|
||||
#: The public key blob, base64.
|
||||
key: str
|
||||
|
||||
@property
|
||||
def fingerprint(self) -> str:
|
||||
"""``SHA256:…``, as ``ssh-keygen -l`` and the ssh client print it."""
|
||||
digest = hashlib.sha256(base64.b64decode(self.key)).digest()
|
||||
return "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("=")
|
||||
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
return {"key_type": self.key_type, "key": self.key, "fingerprint": self.fingerprint}
|
||||
|
||||
@classmethod
|
||||
def from_value(cls, value: Any) -> SshHostKey | None:
|
||||
"""The key in *value* (a mapping with ``key_type`` and ``key``), or None for none."""
|
||||
if not value:
|
||||
return None
|
||||
if not isinstance(value, Mapping) or not value.get("key_type") or not value.get("key"):
|
||||
raise ValueError(f"not an SSH host key: {value!r}")
|
||||
return cls(str(value["key_type"]), str(value["key"]))
|
||||
|
||||
@classmethod
|
||||
def of(cls, pkey: Any) -> SshHostKey:
|
||||
"""The key of a paramiko ``PKey`` (what a transport says the server presented)."""
|
||||
return cls(pkey.get_name(), pkey.get_base64())
|
||||
|
||||
def known_hosts_line(self, host: str, port: int) -> str:
|
||||
"""The line under which an ssh client looks this host up."""
|
||||
name = host if port == _DEFAULT_SSH_PORT else f"[{host}]:{port}"
|
||||
return f"{name} {self.key_type} {self.key}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HostKeyObservation:
|
||||
"""The key one connection saw, against the key it was to expect."""
|
||||
|
||||
host: str
|
||||
port: int
|
||||
seen: SshHostKey
|
||||
expected: SshHostKey | None
|
||||
|
||||
@property
|
||||
def accepted(self) -> bool:
|
||||
"""True on first use and for the expected key; False for a refused one."""
|
||||
return self.expected is None or self.expected == self.seen
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"seen": self.seen.as_dict(),
|
||||
"expected": self.expected.as_dict() if self.expected else None,
|
||||
"accepted": self.accepted,
|
||||
}
|
||||
|
||||
|
||||
class SshHostKeyMismatch(ConnectionException): # type: ignore[misc]
|
||||
"""The device presented another host key than the one it is known by.
|
||||
|
||||
Raised before any authentication: no password and no private key went to it.
|
||||
"""
|
||||
|
||||
def __init__(self, observation: HostKeyObservation) -> None:
|
||||
self.observation = observation
|
||||
expected = observation.expected
|
||||
trusted = f"{expected.fingerprint} ({expected.key_type})" if expected else "none"
|
||||
super().__init__(
|
||||
f"SSH host key mismatch at {observation.host}:{observation.port}: it presented "
|
||||
f"{observation.seen.fingerprint} ({observation.seen.key_type}), the trusted key is "
|
||||
f"{trusted}. Nothing was sent to it."
|
||||
)
|
||||
|
||||
|
||||
class _AcceptFirst:
|
||||
"""A paramiko missing-host-key policy for first use: accept, keep nothing.
|
||||
|
||||
The key is reported once the connection stands (:meth:`HostKeyCheck.observe`);
|
||||
nothing is written to a ``known_hosts`` file.
|
||||
"""
|
||||
|
||||
def missing_host_key(self, client: Any, hostname: str, key: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class _RefuseUnknown:
|
||||
"""A paramiko policy for a host with a known key: refuse anything else.
|
||||
|
||||
paramiko compares a loaded key itself and raises ``BadHostKeyException``
|
||||
for another one; this only answers if the loaded key was not found under
|
||||
the name connected to, which must not turn into an accepted key.
|
||||
"""
|
||||
|
||||
def missing_host_key(self, client: Any, hostname: str, key: Any) -> None:
|
||||
raise ConnectionException(f"SSH host key of {hostname} is not the one expected")
|
||||
|
||||
|
||||
def _expected_key(known: Any, port: int) -> SshHostKey | None:
|
||||
"""The key in *known* (``{port: key}``, the port as text or number) for *port*."""
|
||||
if not known:
|
||||
return None
|
||||
if not isinstance(known, Mapping):
|
||||
raise ValueError(f"SSH host keys must be given by port, not as {type(known).__name__}")
|
||||
return SshHostKey.from_value(known.get(str(port)) or known.get(port))
|
||||
|
||||
|
||||
def _refused_key(exc: BaseException) -> Any | None:
|
||||
"""paramiko's ``BadHostKeyException`` in *exc*'s chain (netmiko and drivers wrap it)."""
|
||||
seen: set[int] = set()
|
||||
stack: list[BaseException | None] = [exc]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
if current is None or id(current) in seen:
|
||||
continue
|
||||
seen.add(id(current))
|
||||
if hasattr(current, "expected_key") and hasattr(current, "key"):
|
||||
return current
|
||||
stack.extend([current.__cause__, current.__context__])
|
||||
return None
|
||||
|
||||
|
||||
def refused_before_banner(exc: BaseException) -> bool:
|
||||
"""Whether *exc*, or what it wraps, is sshd closing the connection before its banner.
|
||||
|
||||
paramiko says "Error reading SSH protocol banner" (netmiko and drivers wrap
|
||||
it), with the connection's EOF or reset underneath. A failed login, a
|
||||
silent host and a closed port are something else: waiting does not end them.
|
||||
"""
|
||||
seen: set[int] = set()
|
||||
stack: list[BaseException | None] = [exc]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
if current is None or id(current) in seen:
|
||||
continue
|
||||
seen.add(id(current))
|
||||
if "protocol banner" in str(current):
|
||||
return True
|
||||
stack.extend([current.__cause__, current.__context__])
|
||||
return False
|
||||
|
||||
|
||||
def retry_refused[T](
|
||||
attempt: Callable[[], T],
|
||||
*,
|
||||
waits: tuple[float, ...] = REFUSED_RETRY_WAITS,
|
||||
sleep: Callable[[float], None] | None = None,
|
||||
) -> T:
|
||||
"""*attempt*, again after each of *waits* while sshd turns it away before its banner.
|
||||
|
||||
Any other error, and the last refusal, go to the caller unchanged.
|
||||
"""
|
||||
pause = sleep or time.sleep
|
||||
for wait in waits:
|
||||
try:
|
||||
return attempt()
|
||||
except Exception as exc:
|
||||
if not refused_before_banner(exc):
|
||||
raise
|
||||
logger.info("SSH connection turned away before its banner; again in %s s", wait)
|
||||
pause(wait)
|
||||
return attempt()
|
||||
|
||||
|
||||
class HostKeyCheck:
|
||||
"""How one driver connection verifies its host's key.
|
||||
|
||||
*optional_args* are the driver's (both keys optional), *host* and *port* the
|
||||
address the connection goes to, as given to paramiko or netmiko.
|
||||
"""
|
||||
|
||||
def __init__(self, optional_args: Mapping[str, Any] | None, host: str, port: int) -> None:
|
||||
args = optional_args or {}
|
||||
self.host = host
|
||||
self.port = int(port)
|
||||
self.expected = _expected_key(args.get(KNOWN_KEYS_ARG), self.port)
|
||||
self._observer = args.get(OBSERVER_ARG)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# paramiko
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def prepare(self, client: Any) -> None:
|
||||
"""Before ``client.connect()``: the known key, or acceptance of the first one.
|
||||
|
||||
The known key goes into the client's host keys, so paramiko asks the
|
||||
server for that key type first and refuses any other key itself.
|
||||
"""
|
||||
if self.expected is None:
|
||||
client.set_missing_host_key_policy(_AcceptFirst())
|
||||
return
|
||||
with self._known_hosts_file(self.expected) as path:
|
||||
client.get_host_keys().load(path)
|
||||
client.set_missing_host_key_policy(_RefuseUnknown())
|
||||
|
||||
def connect(self, client: Any, **kwargs: Any) -> HostKeyObservation:
|
||||
"""``client.connect()`` to this host with *kwargs*, verified and reported."""
|
||||
self.prepare(client)
|
||||
with self.refusing():
|
||||
retry_refused(lambda: client.connect(hostname=self.host, port=self.port, **kwargs))
|
||||
return self.observe(client.get_transport())
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# netmiko
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@contextmanager
|
||||
def netmiko(self, base: Mapping[str, Any]) -> Iterator[dict[str, Any]]:
|
||||
"""``ConnectHandler`` keyword arguments: *base* with the host key decided.
|
||||
|
||||
Open the connection inside the block and call :meth:`observe` on its
|
||||
transport after it. A known key goes to netmiko in a ``known_hosts``
|
||||
file that exists only for the block, with ``ssh_strict``: should the
|
||||
file not be read, netmiko refuses rather than accepts.
|
||||
"""
|
||||
kwargs = {k: v for k, v in base.items() if k not in _NETMIKO_HOST_KEY_ARGS}
|
||||
kwargs["system_host_keys"] = False
|
||||
if self.expected is None:
|
||||
kwargs.update(ssh_strict=False, alt_host_keys=False)
|
||||
with self.refusing():
|
||||
yield kwargs
|
||||
return
|
||||
with self._known_hosts_file(self.expected) as path:
|
||||
kwargs.update(ssh_strict=True, alt_host_keys=True, alt_key_file=path)
|
||||
with self.refusing():
|
||||
yield kwargs
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# both
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@contextmanager
|
||||
def refusing(self) -> Iterator[None]:
|
||||
"""Around a connect: a refused host key becomes :class:`SshHostKeyMismatch`."""
|
||||
try:
|
||||
yield
|
||||
except Exception as exc:
|
||||
refused = _refused_key(exc)
|
||||
if refused is None:
|
||||
raise
|
||||
expected = self.expected or SshHostKey.of(refused.expected_key)
|
||||
offered = SshHostKey.of(refused.key)
|
||||
observation = HostKeyObservation(self.host, self.port, offered, expected)
|
||||
self._report(observation)
|
||||
raise SshHostKeyMismatch(observation) from exc
|
||||
|
||||
def observe(self, transport: Any) -> HostKeyObservation:
|
||||
"""After a connect: the key the server presented on *transport*, reported."""
|
||||
seen = SshHostKey.of(transport.get_remote_server_key())
|
||||
observation = HostKeyObservation(self.host, self.port, seen, self.expected)
|
||||
self._report(observation)
|
||||
return observation
|
||||
|
||||
def _report(self, observation: HostKeyObservation) -> None:
|
||||
if not callable(self._observer):
|
||||
return
|
||||
try:
|
||||
self._observer(observation.as_dict())
|
||||
except Exception: # the store is the caller's; a connection does not hang on it
|
||||
logger.warning(
|
||||
"Could not report the SSH host key of %s:%s", self.host, self.port, exc_info=True
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def _known_hosts_file(self, expected: SshHostKey) -> Iterator[str]:
|
||||
"""A private ``known_hosts`` file holding only *expected*."""
|
||||
fd, path = tempfile.mkstemp(prefix="known_hosts-")
|
||||
try:
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(expected.known_hosts_line(self.host, self.port) + "\n")
|
||||
yield path
|
||||
finally:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,825 @@
|
||||
"""OpenSSH server hardening: taking algorithms out of what sshd offers.
|
||||
|
||||
A scanner such as ssh-audit names algorithms a server should stop offering --
|
||||
``hmac-sha1``, the NIST curves. Taking them out is the same on every host that
|
||||
runs OpenSSH, so the reading, the plan and the write live here once, and a
|
||||
driver only mixes in :class:`OpenSshServerMixin` and supplies ``run_command``.
|
||||
|
||||
**What the server offers is read, not assumed.** ``sshd -T`` prints the lists
|
||||
sshd actually uses, after its defaults, ``sshd_config``, every ``Include`` and
|
||||
first-match-wins. The new list is that one minus what was asked, so nothing the
|
||||
host already restricted comes back, and nothing it allows is dropped by
|
||||
accident.
|
||||
|
||||
**A drop-in, not an edit.** Where ``sshd_config`` includes
|
||||
``/etc/ssh/sshd_config.d/*.conf`` -- Debian and Ubuntu do, at the top -- the
|
||||
lists go to :data:`DROPIN_PATH`, which sorts first and so wins. sshd_config
|
||||
stays as the distribution shipped it, and removing the file undoes the change.
|
||||
Only without such an ``Include`` is sshd_config itself rewritten, after a copy --
|
||||
and not at all on a platform that generates it
|
||||
(:attr:`OpenSshServerMixin.SSHD_CONFIG_GENERATED`).
|
||||
|
||||
**Nobody is locked out, by three checks.**
|
||||
|
||||
1. The plan never removes the last algorithm of a class, and -- given the
|
||||
lists of the client that manages the host -- never the last one that client
|
||||
speaks. Each one kept back is reported, with why. For host key algorithms
|
||||
only those the host has a key for count (``ssh-keygen -l`` on each
|
||||
``HostKey``); when the keys cannot be read, the host key list is not touched.
|
||||
2. ``sshd -t`` must accept the result, and ``sshd -T`` must show the new lists.
|
||||
A file read before ours can set the same directive; ours is then valid and
|
||||
ignored, and that is reported rather than called a success.
|
||||
3. After the reload, *verify* -- the caller's -- opens a new session. The
|
||||
running one survives a reload, so if the new one cannot get in, this one
|
||||
puts the old state back and reloads again.
|
||||
|
||||
**The managing client is exempt from per-source penalties** where sshd has them
|
||||
(OpenSSH 9.8+, :meth:`OpenSshServerMixin.exempt_from_ssh_penalties`). sshd
|
||||
penalises a source whose connections do not authenticate -- a scanner's probes
|
||||
-- and then drops every connection from it, the managing session's included.
|
||||
The address is the one the host sees (``$SSH_CONNECTION``); it joins the
|
||||
host's own ``PerSourcePenaltyExemptList`` in :data:`PENALTY_DROPIN_PATH`, with
|
||||
the same three checks. An older sshd is not touched: it refuses the directive.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import time
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from shlex import quote
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
)
|
||||
|
||||
from napalm_device_types.ssh_server_auth import SSHD_EFFECTIVE_COMMAND, SshServerAuthMixin
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: The algorithm classes: key -> (``sshd -T`` keyword, sshd_config directive).
|
||||
SSH_ALGORITHM_CLASSES: dict[str, tuple[str, str]] = {
|
||||
"kex": ("kexalgorithms", "KexAlgorithms"),
|
||||
"hostkey": ("hostkeyalgorithms", "HostKeyAlgorithms"),
|
||||
"cipher": ("ciphers", "Ciphers"),
|
||||
"mac": ("macs", "MACs"),
|
||||
}
|
||||
|
||||
MAIN_CONFIG = "/etc/ssh/sshd_config"
|
||||
DROPIN_DIR = "/etc/ssh/sshd_config.d"
|
||||
#: ``00-`` so it sorts before every other drop-in: sshd keeps the first value it reads.
|
||||
DROPIN_PATH = f"{DROPIN_DIR}/00-netork-ssh-hardening.conf"
|
||||
#: Where :meth:`OpenSshServerMixin.exempt_from_ssh_penalties` names the managing
|
||||
#: client; ``00-`` like the hardening drop-in, since sshd keeps the first value.
|
||||
PENALTY_DROPIN_PATH = f"{DROPIN_DIR}/00-netork-penalty-exempt.conf"
|
||||
#: What marks a line this module disabled in sshd_config.
|
||||
DISABLED_PREFIX = "# netork: "
|
||||
|
||||
_HEADER = (
|
||||
"# Written by netOrk: the SSH algorithms a security assessment flagged,\n"
|
||||
"# taken out of what this server offers. Delete this file to undo it.\n"
|
||||
)
|
||||
|
||||
_PENALTY_HEADER = (
|
||||
"# Written by netOrk: the address netOrk manages this host from, exempt from\n"
|
||||
"# sshd's per-source penalties (PerSourcePenalties). Delete this file to undo it.\n"
|
||||
)
|
||||
|
||||
#: Host key type, as ``ssh-keygen -l`` prints it -> the algorithms that key serves.
|
||||
#: Certificate algorithms are left out: they also need a HostCertificate.
|
||||
_KEY_TYPE_ALGORITHMS: dict[str, tuple[str, ...]] = {
|
||||
"ED25519": ("ssh-ed25519",),
|
||||
"RSA": ("rsa-sha2-512", "rsa-sha2-256", "ssh-rsa"),
|
||||
"DSA": ("ssh-dss",),
|
||||
"ED25519-SK": ("sk-ssh-ed25519@openssh.com",),
|
||||
"ECDSA-SK": ("sk-ecdsa-sha2-nistp256@openssh.com",),
|
||||
}
|
||||
_ECDSA_CURVES = ("256", "384", "521")
|
||||
|
||||
_RELOAD = (
|
||||
"if systemctl is-active --quiet ssh 2>/dev/null; then systemctl reload ssh;"
|
||||
" elif systemctl is-active --quiet sshd 2>/dev/null; then systemctl reload sshd;"
|
||||
" else for f in /run/sshd.pid /var/run/sshd.pid; do"
|
||||
' [ -r "$f" ] && kill -HUP "$(cat "$f")" && exit 0; done; exit 0; fi'
|
||||
)
|
||||
|
||||
|
||||
def _directive_key(line: str) -> str | None:
|
||||
"""The algorithm class a global sshd_config line sets, if it sets one."""
|
||||
parts = line.split(None, 1)
|
||||
if not parts:
|
||||
return None
|
||||
word = parts[0].lower()
|
||||
for kind, (keyword, _directive) in SSH_ALGORITHM_CLASSES.items():
|
||||
if word == keyword:
|
||||
return kind
|
||||
return None
|
||||
|
||||
|
||||
def parse_sshd_effective(text: str) -> dict[str, list[str]]:
|
||||
"""The four algorithm lists from ``sshd -T`` output, in the server's order.
|
||||
|
||||
:raises ValueError: if a list is missing -- not sshd -T output, or cut short.
|
||||
"""
|
||||
found: dict[str, list[str]] = {}
|
||||
for raw in text.splitlines():
|
||||
parts = raw.strip().split(None, 1)
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
kind = _directive_key(parts[0])
|
||||
if kind and kind not in found:
|
||||
found[kind] = [a for a in parts[1].split(",") if a]
|
||||
missing = [k for k in SSH_ALGORITHM_CLASSES if k not in found]
|
||||
if missing:
|
||||
raise ValueError(f"sshd -T printed no {', '.join(missing)} list")
|
||||
return found
|
||||
|
||||
|
||||
def parse_sshd_hostkeys(text: str) -> list[str]:
|
||||
"""The ``hostkey`` paths from ``sshd -T`` output, in order."""
|
||||
paths: list[str] = []
|
||||
for raw in text.splitlines():
|
||||
parts = raw.strip().split(None, 1)
|
||||
if len(parts) == 2 and parts[0].lower() == "hostkey":
|
||||
paths.append(parts[1].strip())
|
||||
return paths
|
||||
|
||||
|
||||
def host_key_algorithms(fingerprints: str) -> set[str] | None:
|
||||
"""The host key algorithms the keys in ``ssh-keygen -l`` output can serve.
|
||||
|
||||
None when a line is not understood or there is no key: then nothing is known.
|
||||
"""
|
||||
usable: set[str] = set()
|
||||
for raw in fingerprints.splitlines():
|
||||
parts = raw.split()
|
||||
if not parts:
|
||||
continue
|
||||
kind = parts[-1].strip("()")
|
||||
if len(parts) < 3 or not parts[-1].startswith("("):
|
||||
return None
|
||||
if kind == "ECDSA" and parts[0] in _ECDSA_CURVES:
|
||||
usable.add(f"ecdsa-sha2-nistp{parts[0]}")
|
||||
elif kind in _KEY_TYPE_ALGORITHMS:
|
||||
usable.update(_KEY_TYPE_ALGORITHMS[kind])
|
||||
else:
|
||||
return None
|
||||
return usable or None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Refusal:
|
||||
"""One algorithm that was asked to go and stays, with why.
|
||||
|
||||
*reason* is ``"last"`` (the class would be empty -- for host keys: have no
|
||||
algorithm the host has a key for), ``"client"`` (the managing client would
|
||||
share none of the class with the server), ``"host_keys_unknown"`` (the host
|
||||
keys could not be read, so the host key list stays) or ``"not_offered"``
|
||||
(the server does not offer it, so there is nothing to remove).
|
||||
"""
|
||||
|
||||
kind: str
|
||||
algorithm: str
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SshHardeningPlan:
|
||||
keep: dict[str, list[str]]
|
||||
remove: dict[str, list[str]]
|
||||
refused: list[Refusal] = field(default_factory=list)
|
||||
not_offered: list[Refusal] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def changed_classes(self) -> list[str]:
|
||||
return [k for k in SSH_ALGORITHM_CLASSES if self.remove.get(k)]
|
||||
|
||||
|
||||
def plan_ssh_hardening(
|
||||
effective: Mapping[str, Sequence[str]],
|
||||
remove: Mapping[str, Iterable[str]],
|
||||
*,
|
||||
client: Mapping[str, Iterable[str]] | None = None,
|
||||
host_keys: Iterable[str] | None = None,
|
||||
) -> SshHardeningPlan:
|
||||
"""What the lists become when *remove* is taken out of *effective*.
|
||||
|
||||
*client* is what the client managing this host speaks, per class. A class it
|
||||
has no list for is not guarded beyond "never empty".
|
||||
|
||||
*host_keys* are the host key algorithms the host has a key for (see
|
||||
:func:`host_key_algorithms`). Only those count as a host key algorithm that
|
||||
stays: sshd offers the others but cannot use them. Without it nothing is
|
||||
known, and no host key algorithm is removed.
|
||||
|
||||
When a removal would leave a class empty, or without an algorithm *client*
|
||||
speaks, the first of the asked-for algorithms in the server's order that
|
||||
fixes it stays, and is reported in ``refused``.
|
||||
|
||||
:raises ValueError: for a class that is not one of :data:`SSH_ALGORITHM_CLASSES`.
|
||||
"""
|
||||
unknown = [k for k in remove if k not in SSH_ALGORITHM_CLASSES]
|
||||
if unknown:
|
||||
raise ValueError(f"unknown SSH algorithm class: {', '.join(unknown)}")
|
||||
keep: dict[str, list[str]] = {}
|
||||
removed: dict[str, list[str]] = {}
|
||||
refused: list[Refusal] = []
|
||||
not_offered: list[Refusal] = []
|
||||
usable_keys = set(host_keys) if host_keys is not None else None
|
||||
for kind in SSH_ALGORITHM_CLASSES:
|
||||
offered = list(effective.get(kind, []))
|
||||
asked = set(remove.get(kind, []))
|
||||
not_offered += [Refusal(kind, a, "not_offered") for a in sorted(asked - set(offered))]
|
||||
going = [a for a in offered if a in asked]
|
||||
if kind == "hostkey" and usable_keys is None:
|
||||
refused += [Refusal(kind, a, "host_keys_unknown") for a in going]
|
||||
going = []
|
||||
# A host key algorithm without a key is offered, but nobody gets in with it.
|
||||
usable = usable_keys if kind == "hostkey" and usable_keys is not None else set(offered)
|
||||
staying = [a for a in offered if a not in going and a in usable]
|
||||
speaks = set(client[kind]) if client and kind in client else None
|
||||
if going and speaks is not None and not speaks & set(staying):
|
||||
spared = next((a for a in going if a in speaks and a in usable), None)
|
||||
if spared:
|
||||
going.remove(spared)
|
||||
staying.append(spared)
|
||||
refused.append(Refusal(kind, spared, "client"))
|
||||
if going and not staying:
|
||||
spared = next((a for a in going if a in usable), None)
|
||||
if spared is None and not [a for a in offered if a not in going]:
|
||||
spared = going[0]
|
||||
if spared is not None:
|
||||
going.remove(spared)
|
||||
refused.append(Refusal(kind, spared, "last"))
|
||||
keep[kind] = [a for a in offered if a not in going]
|
||||
if going:
|
||||
removed[kind] = going
|
||||
return SshHardeningPlan(keep=keep, remove=removed, refused=refused, not_offered=not_offered)
|
||||
|
||||
|
||||
def render_dropin(keep: Mapping[str, Sequence[str]], kinds: Iterable[str]) -> str:
|
||||
"""The drop-in file stating the full list of each class in *kinds*."""
|
||||
lines = [
|
||||
f"{SSH_ALGORITHM_CLASSES[k][1]} {','.join(keep[k])}\n"
|
||||
for k in SSH_ALGORITHM_CLASSES
|
||||
if k in set(kinds)
|
||||
]
|
||||
return _HEADER + "".join(lines)
|
||||
|
||||
|
||||
def dropin_classes(text: str) -> list[str]:
|
||||
"""The classes an existing drop-in sets."""
|
||||
return [k for k in (_directive_key(line.strip()) for line in text.splitlines()) if k]
|
||||
|
||||
|
||||
def _is_match(line: str) -> bool:
|
||||
parts = line.split(None, 1)
|
||||
return bool(parts) and parts[0].lower() == "match"
|
||||
|
||||
|
||||
def has_dropin_include(text: str) -> bool:
|
||||
"""Whether sshd_config's global section includes :data:`DROPIN_DIR`."""
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if _is_match(line):
|
||||
return False
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[0].lower() == "include":
|
||||
if any(p.startswith(DROPIN_DIR + "/") for p in parts[1:]):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _split_our_block(text: str) -> tuple[list[str], str]:
|
||||
"""(the classes an earlier rewrite put above the file, the file without them)."""
|
||||
if not text.startswith(_HEADER):
|
||||
return [], text
|
||||
lines = text[len(_HEADER) :].splitlines(keepends=True)
|
||||
ours = 0
|
||||
while ours < len(lines) and _directive_key(lines[ours].strip()):
|
||||
ours += 1
|
||||
return dropin_classes("".join(lines[:ours])), "".join(lines[ours:])
|
||||
|
||||
|
||||
def render_main_config(text: str, keep: Mapping[str, Sequence[str]], kinds: Iterable[str]) -> str:
|
||||
"""sshd_config with the lists of *kinds* first and their old global lines disabled.
|
||||
|
||||
First because sshd keeps the first value it reads. A ``Match`` block is left
|
||||
alone -- it is not the global setting. A class an earlier rewrite set stays
|
||||
set, and rewriting a file this already rewrote gives the same file.
|
||||
"""
|
||||
earlier, body = _split_our_block(text)
|
||||
wanted = set(kinds) | set(earlier)
|
||||
out: list[str] = []
|
||||
in_match = False
|
||||
for raw in body.splitlines():
|
||||
if _is_match(raw.strip()):
|
||||
in_match = True
|
||||
if not in_match and _directive_key(raw.strip()) in wanted:
|
||||
out.append(DISABLED_PREFIX + raw)
|
||||
else:
|
||||
out.append(raw)
|
||||
return render_dropin(keep, wanted) + "\n".join(out) + ("\n" if body.endswith("\n") else "")
|
||||
|
||||
|
||||
def parse_penalty_exemptions(text: str) -> list[str] | None:
|
||||
"""The ``persourcepenaltyexemptlist`` from ``sshd -T`` output; None without penalties.
|
||||
|
||||
Per-source penalties came with OpenSSH 9.8. An older sshd prints neither
|
||||
line and refuses ``PerSourcePenaltyExemptList`` outright -- it does not
|
||||
start with it in its configuration -- so None means: write nothing.
|
||||
"""
|
||||
penalties = False
|
||||
exempt: list[str] = []
|
||||
for raw in text.splitlines():
|
||||
parts = raw.strip().split(None, 1)
|
||||
if not parts:
|
||||
continue
|
||||
word = parts[0].lower()
|
||||
if word == "persourcepenalties":
|
||||
penalties = True
|
||||
elif word == "persourcepenaltyexemptlist" and len(parts) == 2:
|
||||
value = parts[1].strip()
|
||||
exempt = [] if value.lower() == "none" else [a for a in value.split(",") if a]
|
||||
return exempt if penalties else None
|
||||
|
||||
|
||||
def client_address(ssh_connection: str) -> str | None:
|
||||
"""The client's address in ``$SSH_CONNECTION`` (``client port server port``), or None."""
|
||||
parts = ssh_connection.split()
|
||||
if len(parts) != 4:
|
||||
return None
|
||||
try:
|
||||
return str(ipaddress.ip_address(parts[0]))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def is_exempt(address: str, exempt: Iterable[str]) -> bool:
|
||||
"""Whether *address* is one of *exempt*'s addresses or inside one of its networks."""
|
||||
ip = ipaddress.ip_address(address)
|
||||
for entry in exempt:
|
||||
try:
|
||||
if ip in ipaddress.ip_network(entry, strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def render_penalty_dropin(exempt: Sequence[str]) -> str:
|
||||
"""The drop-in stating the full exempt list."""
|
||||
return _PENALTY_HEADER + f"PerSourcePenaltyExemptList {','.join(exempt)}\n"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SshHardeningResult:
|
||||
"""What :meth:`OpenSshServerMixin.harden_ssh_server` did.
|
||||
|
||||
*applied* is True only when the new lists are live and a new session got
|
||||
in. *rolled_back* says the host was changed and then put back. *backup* is
|
||||
where sshd_config was copied to, when it was the file changed.
|
||||
"""
|
||||
|
||||
plan: SshHardeningPlan
|
||||
applied: bool = False
|
||||
rolled_back: bool = False
|
||||
path: str | None = None
|
||||
backup: str | None = None
|
||||
message: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SshPenaltyExemption:
|
||||
"""What :meth:`OpenSshServerMixin.exempt_from_ssh_penalties` did.
|
||||
|
||||
*address* is the one the host sees the managing client at. *applied* is
|
||||
True only when sshd uses the exemption and a new session got in;
|
||||
*rolled_back* says the host was changed and then put back.
|
||||
"""
|
||||
|
||||
address: str | None = None
|
||||
applied: bool = False
|
||||
rolled_back: bool = False
|
||||
path: str | None = None
|
||||
message: str = ""
|
||||
|
||||
|
||||
#: Why an algorithm stays, by :class:`Refusal` reason.
|
||||
_WHYS = {
|
||||
"last": "it is the last one",
|
||||
"client": "netOrk could no longer connect",
|
||||
"host_keys_unknown": "the host keys could not be read",
|
||||
}
|
||||
|
||||
|
||||
def _unchanged(
|
||||
result: SshPenaltyExemption, message: str, say: Callable[[str], None]
|
||||
) -> SshPenaltyExemption:
|
||||
result.message = message
|
||||
say(message)
|
||||
return result
|
||||
|
||||
|
||||
class OpenSshServerMixin(SshServerAuthMixin):
|
||||
"""Adds :meth:`harden_ssh_server` to a driver that can run commands as root on an OpenSSH host.
|
||||
|
||||
Mixed in by the drivers whose host runs a stock OpenSSH, not by a base class,
|
||||
so ``hasattr(driver, "harden_ssh_server")`` stays a truthful answer. A driver
|
||||
whose platform writes sshd_config itself (an appliance that regenerates it
|
||||
from its own database) must not inherit this, or must opt out with
|
||||
``harden_ssh_server = None``: its file would be overwritten on the next
|
||||
apply. Where that generated file still includes the drop-in directory, the
|
||||
driver sets :attr:`SSHD_CONFIG_GENERATED` instead and keeps the hardening.
|
||||
|
||||
It carries :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin`:
|
||||
a host whose sshd can be hardened can also say how it lets people log in.
|
||||
"""
|
||||
|
||||
#: True where the platform writes sshd_config from its own database
|
||||
#: (OpenMediaVault): only the drop-in directory is written, and a
|
||||
#: sshd_config that does not include it is left alone, since the platform
|
||||
#: would write over a change to it on its next apply.
|
||||
SSHD_CONFIG_GENERATED: bool = False
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# ── the host ────────────────────────────────────────────────────────
|
||||
|
||||
def _ssh_run(self, command: str, stdin: bytes | None = None) -> CommandResult:
|
||||
return self.run_command(command, privileged=True, timeout=30, stdin=stdin)
|
||||
|
||||
def _ssh_read(self, path: str) -> str | None:
|
||||
result = self._ssh_run(f"cat -- {quote(path)}")
|
||||
return result.stdout if result.exit_code == 0 else None
|
||||
|
||||
def _ssh_write(self, path: str, content: str, mode_of: str | None = None) -> None:
|
||||
"""Replace *path* with *content*, as root, without root reading stdin.
|
||||
|
||||
A driver gains root with ``sudo -S`` and puts the password in front of
|
||||
stdin. A sudo that does not prompt -- NOPASSWD, a cached timestamp --
|
||||
leaves it there, and a ``cat`` under sudo writes it into the file. So the
|
||||
content goes, without privilege, to a file only the login user can read;
|
||||
root then installs that file, owned by root, and removes it.
|
||||
|
||||
The mode is that of *mode_of* (default: *path* itself), so a 0600
|
||||
sshd_config stays 0600 and so does its copy; 644 for a new file.
|
||||
"""
|
||||
staged = self.run_command(
|
||||
'umask 077 && t=$(mktemp /tmp/netork-ssh.XXXXXX) && cat > "$t" && printf %s "$t"',
|
||||
privileged=False,
|
||||
timeout=30,
|
||||
stdin=content.encode(),
|
||||
)
|
||||
tmp = staged.stdout.strip()
|
||||
# A path on the device, made by mktemp under umask 077: not a local temp file.
|
||||
if staged.exit_code != 0 or not tmp.startswith("/tmp/netork-ssh."): # nosec B108
|
||||
raise RuntimeError(
|
||||
f"could not stage {path}: {(staged.stderr or staged.stdout).strip()}"
|
||||
)
|
||||
part = path + ".netork-tmp"
|
||||
result = self._ssh_run(
|
||||
# GNU stat, then BSD's; 644 for a file that does not exist yet.
|
||||
f'r={quote(mode_of or path)}; m=$(stat -c %a -- "$r" 2>/dev/null'
|
||||
f' || stat -f %Lp -- "$r" 2>/dev/null) || m=644;'
|
||||
f' install -m "$m" -- {quote(tmp)} {quote(part)}'
|
||||
f" && mv -f -- {quote(part)} {quote(path)};"
|
||||
f" s=$?; rm -f -- {quote(tmp)} {quote(part)}; exit $s"
|
||||
)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(
|
||||
f"could not write {path}: {(result.stderr or result.stdout).strip()}"
|
||||
)
|
||||
|
||||
def _ssh_remove(self, path: str) -> None:
|
||||
self._ssh_run(f"rm -f -- {quote(path)}")
|
||||
|
||||
def _reload_ssh_server(self) -> None:
|
||||
"""Make the running sshd read its configuration again; sessions stay up."""
|
||||
result = self._ssh_run(_RELOAD)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"could not reload sshd: {(result.stderr or result.stdout).strip()}")
|
||||
|
||||
def get_ssh_server_algorithms(self) -> dict[str, list[str]]:
|
||||
"""The algorithm lists sshd uses now (``sshd -T``), per class.
|
||||
|
||||
:raises RuntimeError: if sshd -T fails -- no OpenSSH, or no root.
|
||||
"""
|
||||
return parse_sshd_effective(self._sshd_effective_text())
|
||||
|
||||
def _sshd_effective_text(self) -> str:
|
||||
result = self._ssh_run(SSHD_EFFECTIVE_COMMAND)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"sshd -T failed: {(result.stderr or result.stdout).strip()}")
|
||||
return result.stdout
|
||||
|
||||
def _ssh_host_key_algorithms(self, sshd_t: str) -> set[str] | None:
|
||||
"""The host key algorithms the host has a key for; None when that cannot be read.
|
||||
|
||||
A ``HostKey`` whose file does not exist is skipped, as sshd skips it.
|
||||
"""
|
||||
paths = parse_sshd_hostkeys(sshd_t)
|
||||
if not paths:
|
||||
return None
|
||||
result = self._ssh_run(
|
||||
f"for k in {' '.join(quote(p) for p in paths)}; do"
|
||||
' [ -e "$k" ] || continue; ssh-keygen -l -f "$k" || exit 1; done'
|
||||
)
|
||||
if result.exit_code != 0:
|
||||
return None
|
||||
return host_key_algorithms(result.stdout)
|
||||
|
||||
def _sshd_accepts(self) -> str | None:
|
||||
"""None when ``sshd -t`` accepts the configuration, else what it said."""
|
||||
result = self._ssh_run("PATH=$PATH:/usr/sbin:/sbin sshd -t")
|
||||
return None if result.exit_code == 0 else (result.stderr or result.stdout).strip()
|
||||
|
||||
# ── the change ──────────────────────────────────────────────────────
|
||||
|
||||
def harden_ssh_server(
|
||||
self,
|
||||
remove: Mapping[str, Iterable[str]],
|
||||
*,
|
||||
client: Mapping[str, Iterable[str]] | None = None,
|
||||
verify: Callable[[], bool] | None = None,
|
||||
log: Callable[[str], None] | None = None,
|
||||
) -> SshHardeningResult:
|
||||
"""Stop the server offering the algorithms in *remove* (class -> names).
|
||||
|
||||
*client* guards the managing client's algorithms (see
|
||||
:func:`plan_ssh_hardening`); *verify* opens a new session after the
|
||||
reload and returns whether it got in; *log* receives a line per step.
|
||||
|
||||
Never raises after the host was touched: a failure from there on puts
|
||||
the previous state back and says so in the result.
|
||||
|
||||
:raises RuntimeError: if the current state cannot be read.
|
||||
"""
|
||||
say = log or (lambda _line: None)
|
||||
plan = self._plan_hardening(remove, client, say)
|
||||
kinds = plan.changed_classes
|
||||
result = SshHardeningResult(plan=plan)
|
||||
if not kinds:
|
||||
result.message = "Nothing to change: the server offers none of the selected algorithms."
|
||||
say(result.message)
|
||||
return result
|
||||
for kind in kinds:
|
||||
say(f"Removing {', '.join(plan.remove[kind])} from {SSH_ALGORITHM_CLASSES[kind][1]}")
|
||||
|
||||
main = self._ssh_read(MAIN_CONFIG)
|
||||
if main is None:
|
||||
raise RuntimeError(f"cannot read {MAIN_CONFIG}")
|
||||
if self.SSHD_CONFIG_GENERATED and not has_dropin_include(main):
|
||||
result.message = (
|
||||
f"Not changed: {MAIN_CONFIG} does not include {DROPIN_DIR}, and this"
|
||||
" platform writes it from its own settings."
|
||||
)
|
||||
say(result.message)
|
||||
return result
|
||||
restore = self._write_change(plan, main, result, say)
|
||||
return self._apply_or_restore(
|
||||
result,
|
||||
restore,
|
||||
verify,
|
||||
say,
|
||||
ignored=lambda: self._algorithms_ignored(plan, result.path),
|
||||
done="The server no longer offers the selected algorithms.",
|
||||
)
|
||||
|
||||
def _plan_hardening(
|
||||
self,
|
||||
remove: Mapping[str, Iterable[str]],
|
||||
client: Mapping[str, Iterable[str]] | None,
|
||||
say: Callable[[str], None],
|
||||
) -> SshHardeningPlan:
|
||||
"""Read what sshd offers and which host keys it has; plan, and say what stays."""
|
||||
say("Reading the algorithms sshd offers (sshd -T)")
|
||||
sshd_t = self._sshd_effective_text()
|
||||
host_keys: set[str] | None = None
|
||||
if remove.get("hostkey"):
|
||||
say("Reading which host keys the server has (ssh-keygen -l)")
|
||||
host_keys = self._ssh_host_key_algorithms(sshd_t)
|
||||
plan = plan_ssh_hardening(
|
||||
parse_sshd_effective(sshd_t), remove, client=client, host_keys=host_keys
|
||||
)
|
||||
for r in plan.refused:
|
||||
last_key = r.reason == "last" and r.kind == "hostkey"
|
||||
why = "it is the last one the host has a key for" if last_key else _WHYS[r.reason]
|
||||
say(f"Keeping {r.algorithm}: {why}")
|
||||
return plan
|
||||
|
||||
def _algorithms_ignored(self, plan: SshHardeningPlan, path: str | None) -> str | None:
|
||||
"""Why sshd does not use the new lists; None when it does."""
|
||||
now = self.get_ssh_server_algorithms()
|
||||
names = [
|
||||
SSH_ALGORITHM_CLASSES[k][1] for k in plan.changed_classes if now[k] != plan.keep[k]
|
||||
]
|
||||
if not names:
|
||||
return None
|
||||
return (
|
||||
f"sshd does not use the new {', '.join(names)}: a setting read before"
|
||||
f" {path} decides them"
|
||||
)
|
||||
|
||||
def _write_change(
|
||||
self,
|
||||
plan: SshHardeningPlan,
|
||||
main: str,
|
||||
result: SshHardeningResult,
|
||||
say: Callable[[str], None],
|
||||
) -> Callable[[], None]:
|
||||
"""Write the new lists; return what puts the previous state back."""
|
||||
if has_dropin_include(main):
|
||||
previous = self._ssh_read(DROPIN_PATH)
|
||||
kinds = set(plan.changed_classes) | set(dropin_classes(previous or ""))
|
||||
self._ssh_run(f"mkdir -p -- {quote(DROPIN_DIR)}")
|
||||
self._ssh_write(DROPIN_PATH, render_dropin(plan.keep, kinds))
|
||||
result.path = DROPIN_PATH
|
||||
say(f"Wrote {DROPIN_PATH}")
|
||||
|
||||
def restore() -> None:
|
||||
if previous is None:
|
||||
self._ssh_remove(DROPIN_PATH)
|
||||
else:
|
||||
self._ssh_write(DROPIN_PATH, previous)
|
||||
|
||||
return restore
|
||||
backup = f"{MAIN_CONFIG}.netork-{time.strftime('%Y%m%d-%H%M%S')}.bak"
|
||||
self._ssh_write(backup, main, mode_of=MAIN_CONFIG)
|
||||
self._ssh_write(MAIN_CONFIG, render_main_config(main, plan.keep, plan.changed_classes))
|
||||
result.path, result.backup = MAIN_CONFIG, backup
|
||||
say(f"{MAIN_CONFIG} has no Include of {DROPIN_DIR}; rewrote it (copy at {backup})")
|
||||
|
||||
def restore_main() -> None:
|
||||
self._ssh_write(MAIN_CONFIG, main)
|
||||
|
||||
return restore_main
|
||||
|
||||
def _apply_or_restore[R: (SshHardeningResult, SshPenaltyExemption)](
|
||||
self,
|
||||
result: R,
|
||||
restore: Callable[[], None],
|
||||
verify: Callable[[], bool] | None,
|
||||
say: Callable[[str], None],
|
||||
*,
|
||||
ignored: Callable[[], str | None],
|
||||
done: str,
|
||||
) -> R:
|
||||
"""Check what was written, reload, verify; put the old state back on any failure.
|
||||
|
||||
*ignored* reads ``sshd -T`` after ``sshd -t`` and says why sshd does not
|
||||
use the change, or None when it does; *done* is the message of success.
|
||||
"""
|
||||
|
||||
def back(message: str, reload: bool) -> R:
|
||||
return self._put_back(result, restore, say, message, reload=reload)
|
||||
|
||||
try:
|
||||
say("Checking the configuration (sshd -t)")
|
||||
complaint = self._sshd_accepts()
|
||||
if complaint:
|
||||
return back(f"sshd rejected the new configuration: {complaint}", reload=False)
|
||||
why = ignored()
|
||||
if why:
|
||||
return back(why, reload=False)
|
||||
say("Reloading sshd")
|
||||
self._reload_ssh_server()
|
||||
if verify is not None:
|
||||
say("Opening a new SSH session to check netOrk still gets in")
|
||||
if not verify():
|
||||
return back("A new SSH session could not log in after the reload", reload=True)
|
||||
except Exception as exc: # noqa: BLE001 - whatever went wrong, the host goes back
|
||||
return back(f"The change failed: {exc}", reload=True)
|
||||
result.applied = True
|
||||
result.message = done
|
||||
say(result.message)
|
||||
return result
|
||||
|
||||
def _put_back[R: (SshHardeningResult, SshPenaltyExemption)](
|
||||
self,
|
||||
result: R,
|
||||
restore: Callable[[], None],
|
||||
say: Callable[[str], None],
|
||||
message: str,
|
||||
*,
|
||||
reload: bool,
|
||||
) -> R:
|
||||
"""Say *message*, put the previous state back, and say whether that worked."""
|
||||
say(message)
|
||||
say("Putting the previous configuration back")
|
||||
try:
|
||||
restore()
|
||||
if reload:
|
||||
self._reload_ssh_server()
|
||||
except Exception as exc: # noqa: BLE001 - report it, the caller must look
|
||||
result.message = f"{message}; putting the previous configuration back failed: {exc}"
|
||||
say(result.message)
|
||||
return result
|
||||
result.rolled_back = True
|
||||
result.message = message
|
||||
return result
|
||||
|
||||
# ── the penalty exemption ───────────────────────────────────────────
|
||||
|
||||
def exempt_from_ssh_penalties(
|
||||
self,
|
||||
*,
|
||||
verify: Callable[[], bool] | None = None,
|
||||
log: Callable[[str], None] | None = None,
|
||||
) -> SshPenaltyExemption:
|
||||
"""Exempt the address this session comes from from sshd's per-source penalties.
|
||||
|
||||
OpenSSH 9.8+ penalises a source whose connections do not authenticate --
|
||||
a scanner's probes -- and then drops every connection from it, the
|
||||
managing client's included (NetOrk/netork#1800). The address is the
|
||||
one the host sees (``$SSH_CONNECTION``), so NAT and relays do not
|
||||
matter. The host's own exemptions stay: the new list is the one sshd
|
||||
uses now plus this address.
|
||||
|
||||
Only into the drop-in directory: a sshd_config that does not include it
|
||||
is left alone, and the result says so. An sshd before 9.8 is not
|
||||
touched -- it would not start with the directive. Checked like
|
||||
:meth:`harden_ssh_server`: ``sshd -t``, ``sshd -T`` shows the address,
|
||||
reload, then *verify*; on any failure the previous state goes back.
|
||||
|
||||
:raises RuntimeError: if the session names no client address, or
|
||||
``sshd -T`` or sshd_config cannot be read.
|
||||
"""
|
||||
say = log or (lambda _line: None)
|
||||
address = self._session_client_address()
|
||||
result = SshPenaltyExemption(address=address)
|
||||
say(f"netOrk connects from {address}")
|
||||
say("Reading sshd's per-source penalties (sshd -T)")
|
||||
exempt = parse_penalty_exemptions(self._sshd_effective_text())
|
||||
reason = self._penalty_exemption_unchanged(address, exempt)
|
||||
if reason is not None or exempt is None:
|
||||
return _unchanged(result, reason or "", say)
|
||||
|
||||
restore = self._write_penalty_dropin([*exempt, address])
|
||||
result.path = PENALTY_DROPIN_PATH
|
||||
say(f"Wrote {PENALTY_DROPIN_PATH}")
|
||||
return self._apply_or_restore(
|
||||
result,
|
||||
restore,
|
||||
verify,
|
||||
say,
|
||||
ignored=lambda: self._exemption_ignored(address),
|
||||
done=f"{address} is exempt from sshd's per-source penalties.",
|
||||
)
|
||||
|
||||
def _session_client_address(self) -> str:
|
||||
"""The address the host sees this session come from (``$SSH_CONNECTION``)."""
|
||||
session = self.run_command('printf %s "$SSH_CONNECTION"', privileged=False, timeout=30)
|
||||
address = client_address(session.stdout)
|
||||
if address is None:
|
||||
raise RuntimeError("the session names no client address ($SSH_CONNECTION)")
|
||||
return address
|
||||
|
||||
def _penalty_exemption_unchanged(self, address: str, exempt: list[str] | None) -> str | None:
|
||||
"""Why the exemption is left as it is; None when it is to be written."""
|
||||
if exempt is None:
|
||||
return "Nothing to change: this sshd has no per-source penalties (before OpenSSH 9.8)."
|
||||
if is_exempt(address, exempt):
|
||||
return f"Nothing to change: {address} is already exempt."
|
||||
main = self._ssh_read(MAIN_CONFIG)
|
||||
if main is None:
|
||||
raise RuntimeError(f"cannot read {MAIN_CONFIG}")
|
||||
if not has_dropin_include(main):
|
||||
return (
|
||||
f"Not changed: {MAIN_CONFIG} does not include {DROPIN_DIR},"
|
||||
" where the exemption would go."
|
||||
)
|
||||
return None
|
||||
|
||||
def _exemption_ignored(self, address: str) -> str | None:
|
||||
"""Why sshd does not use the new exemption; None when it does."""
|
||||
if is_exempt(address, parse_penalty_exemptions(self._sshd_effective_text()) or []):
|
||||
return None
|
||||
return (
|
||||
"sshd does not use the new PerSourcePenaltyExemptList: a setting read before"
|
||||
f" {PENALTY_DROPIN_PATH} decides it"
|
||||
)
|
||||
|
||||
def _write_penalty_dropin(self, exempt: Sequence[str]) -> Callable[[], None]:
|
||||
"""Write the exemption list; return what puts the previous drop-in back."""
|
||||
previous = self._ssh_read(PENALTY_DROPIN_PATH)
|
||||
self._ssh_run(f"mkdir -p -- {quote(DROPIN_DIR)}")
|
||||
self._ssh_write(PENALTY_DROPIN_PATH, render_penalty_dropin(exempt))
|
||||
|
||||
def restore() -> None:
|
||||
if previous is None:
|
||||
self._ssh_remove(PENALTY_DROPIN_PATH)
|
||||
else:
|
||||
self._ssh_write(PENALTY_DROPIN_PATH, previous)
|
||||
|
||||
return restore
|
||||
@@ -0,0 +1,281 @@
|
||||
"""How an OpenSSH server lets people log in: the effective settings and sshd's PAM stack.
|
||||
|
||||
Whether a host takes a password, only a key, or a key *and* a second factor is
|
||||
the same question on every host that runs OpenSSH, so the reading lives here,
|
||||
and a driver only mixes in :class:`SshServerAuthMixin` and supplies
|
||||
``run_command``.
|
||||
|
||||
**What sshd uses, not what a file says.** ``sshd -T`` prints the settings after
|
||||
sshd's defaults, ``sshd_config``, every ``Include`` and first-match-wins -- the
|
||||
same reading :class:`~napalm_device_types.ssh_server.OpenSshServerMixin` plans
|
||||
its hardening on, by the same fixed command (:data:`SSHD_EFFECTIVE_COMMAND`). It
|
||||
needs root: without it sshd cannot load its host keys and exits.
|
||||
|
||||
**PAM, as far as it can be read.** With ``UsePAM yes``, keyboard-interactive
|
||||
asks whatever PAM's ``auth`` stack for sshd asks: a password from
|
||||
``pam_unix.so``, a one-time code from an OTP module, or both. The stack is read
|
||||
from ``/etc/pam.d`` in one listing as the login user (the files are
|
||||
world-readable), and followed through ``@include``, ``include`` and
|
||||
``substack``. Each module is reported with its control and arguments as
|
||||
written; which of them is a second factor, and whether ``nullok`` lets a user
|
||||
without one through, is the consumer's call.
|
||||
|
||||
Not read: ``Match`` blocks (``sshd -T`` without ``-C`` prints the global
|
||||
settings), and what a PAM module's own configuration asks for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: sshd's effective configuration. ``sshd`` lives in ``/usr/sbin``, outside a login
|
||||
#: user's ``PATH``. One fixed command, run as root.
|
||||
SSHD_EFFECTIVE_COMMAND = "PATH=$PATH:/usr/sbin:/sbin sshd -T"
|
||||
|
||||
PAM_DIR = "/etc/pam.d"
|
||||
#: Every file in ``/etc/pam.d``, each after a ``==> path <==`` header (GNU, BSD and
|
||||
#: busybox ``tail`` alike). One fixed command, as the login user.
|
||||
PAM_FILES_COMMAND = f"tail -n +1 -- {PAM_DIR}/*"
|
||||
#: The PAM service sshd runs as.
|
||||
PAM_SERVICE = "sshd"
|
||||
|
||||
_TIMEOUT = 30
|
||||
_HEADER_RE = re.compile(rf"^==> {re.escape(PAM_DIR)}/(?P<name>[^/]+) <==$")
|
||||
#: A service name an include may name: a file in ``/etc/pam.d``, never a path out of it.
|
||||
_SERVICE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
||||
_INCLUDE_CONTROLS = ("include", "substack")
|
||||
|
||||
|
||||
class PamAuthEntryDict(TypedDict):
|
||||
"""One line of a PAM ``auth`` stack: ``auth required pam_unix.so nullok``."""
|
||||
|
||||
#: The module's file name, without its directory: ``pam_unix.so``.
|
||||
module: str
|
||||
#: ``required``, ``requisite``, ``sufficient``, ``optional``, or a bracketed
|
||||
#: ``[value=action ...]`` as written.
|
||||
control: str
|
||||
args: list[str]
|
||||
|
||||
|
||||
class SshServerAuthDict(TypedDict):
|
||||
"""How an OpenSSH server lets people log in, as ``get_ssh_server_auth`` read it.
|
||||
|
||||
The global settings ``sshd -T`` prints. A ``Match`` block can change them for
|
||||
some users or addresses; ``sshd -T`` without ``-C`` does not show that.
|
||||
|
||||
``authentication_methods`` is ``AuthenticationMethods``: each inner list is one
|
||||
way in, every method of it required in turn (``publickey,keyboard-interactive``
|
||||
-> ``["publickey", "keyboard-interactive"]``); empty for ``any``, where any one
|
||||
enabled method is enough. A method keeps its submethod
|
||||
(``keyboard-interactive:pam``).
|
||||
|
||||
``use_pam`` is None where sshd has no PAM (OpenBSD). ``pam_auth_stack`` is the
|
||||
``auth`` stack PAM runs for sshd, includes and substacks followed; None when
|
||||
PAM is off or its files gave nothing for sshd.
|
||||
"""
|
||||
|
||||
password_authentication: bool
|
||||
#: ``KbdInteractiveAuthentication``; before OpenSSH 8.7, either it or
|
||||
#: ``ChallengeResponseAuthentication``.
|
||||
kbd_interactive_authentication: bool
|
||||
pubkey_authentication: bool
|
||||
hostbased_authentication: bool
|
||||
#: False also where sshd was built without GSSAPI.
|
||||
gssapi_authentication: bool
|
||||
authentication_methods: list[list[str]]
|
||||
#: ``yes``, ``prohibit-password`` (``without-password``), ``forced-commands-only`` or ``no``.
|
||||
permit_root_login: str
|
||||
use_pam: bool | None
|
||||
pam_auth_stack: list[PamAuthEntryDict] | None
|
||||
|
||||
|
||||
def _flag(settings: Mapping[str, str], keyword: str) -> bool:
|
||||
return settings.get(keyword, "no") == "yes"
|
||||
|
||||
|
||||
def _settings(text: str) -> dict[str, str]:
|
||||
"""``keyword value`` per line, the first one of each keyword."""
|
||||
found: dict[str, str] = {}
|
||||
for raw in text.splitlines():
|
||||
parts = raw.strip().split(None, 1)
|
||||
if len(parts) == 2:
|
||||
found.setdefault(parts[0].lower(), parts[1].strip())
|
||||
return found
|
||||
|
||||
|
||||
def _methods(value: str) -> list[list[str]]:
|
||||
if value == "any":
|
||||
return []
|
||||
return [[m for m in alternative.split(",") if m] for alternative in value.split()]
|
||||
|
||||
|
||||
def parse_sshd_auth(text: str) -> SshServerAuthDict:
|
||||
"""The authentication settings from ``sshd -T`` output; ``pam_auth_stack`` left None.
|
||||
|
||||
:raises ValueError: if a setting every OpenSSH prints is missing -- not sshd -T
|
||||
output, or cut short.
|
||||
"""
|
||||
settings = _settings(text)
|
||||
missing = [
|
||||
k
|
||||
for k in ("passwordauthentication", "pubkeyauthentication", "permitrootlogin")
|
||||
if k not in settings
|
||||
]
|
||||
if missing:
|
||||
raise ValueError(f"sshd -T printed no {', '.join(missing)}")
|
||||
use_pam = settings.get("usepam")
|
||||
return {
|
||||
"password_authentication": _flag(settings, "passwordauthentication"),
|
||||
"kbd_interactive_authentication": _flag(settings, "kbdinteractiveauthentication")
|
||||
or _flag(settings, "challengeresponseauthentication"),
|
||||
"pubkey_authentication": _flag(settings, "pubkeyauthentication"),
|
||||
"hostbased_authentication": _flag(settings, "hostbasedauthentication"),
|
||||
"gssapi_authentication": _flag(settings, "gssapiauthentication"),
|
||||
"authentication_methods": _methods(settings.get("authenticationmethods", "any")),
|
||||
"permit_root_login": settings["permitrootlogin"],
|
||||
"use_pam": None if use_pam is None else use_pam == "yes",
|
||||
"pam_auth_stack": None,
|
||||
}
|
||||
|
||||
|
||||
def _pam_tokens(line: str) -> list[str]:
|
||||
"""A PAM line's tokens, a bracketed control (``[success=1 default=ignore]``) as one."""
|
||||
tokens: list[str] = []
|
||||
for part in line.split():
|
||||
if tokens and tokens[-1].startswith("[") and not tokens[-1].endswith("]"):
|
||||
tokens[-1] += " " + part
|
||||
else:
|
||||
tokens.append(part)
|
||||
return tokens
|
||||
|
||||
|
||||
def _pam_entry(line: str) -> PamAuthEntryDict | None:
|
||||
tokens = _pam_tokens(line.split("#", 1)[0])
|
||||
if len(tokens) >= 2 and tokens[0] == "@include":
|
||||
tokens = ["auth", "include", tokens[1]]
|
||||
if len(tokens) < 3 or tokens[0].lstrip("-") != "auth":
|
||||
return None
|
||||
control, target, args = tokens[1], tokens[2], tokens[3:]
|
||||
if control in _INCLUDE_CONTROLS:
|
||||
if not _SERVICE_RE.match(target):
|
||||
return None
|
||||
return {"module": target, "control": control, "args": []}
|
||||
return {"module": target.rsplit("/", 1)[-1], "control": control, "args": args}
|
||||
|
||||
|
||||
def parse_pam_auth(text: str) -> list[PamAuthEntryDict]:
|
||||
"""One PAM file's ``auth`` stack, in order.
|
||||
|
||||
A module by its file name (``pam_unix.so``), with its control and arguments.
|
||||
An include is an entry whose control is ``include`` or ``substack`` and whose
|
||||
module is the service it names: ``@include common-auth`` brings in a whole
|
||||
file, ``auth include`` and ``auth substack`` its ``auth`` lines; both are
|
||||
followed by :func:`pam_auth_stack`. An include that names a path rather than
|
||||
a service is left out.
|
||||
"""
|
||||
return [entry for line in text.splitlines() if (entry := _pam_entry(line.strip()))]
|
||||
|
||||
|
||||
def parse_pam_files(text: str) -> dict[str, str]:
|
||||
""":data:`PAM_FILES_COMMAND`'s output, by file name."""
|
||||
files: dict[str, list[str]] = {}
|
||||
current: list[str] | None = None
|
||||
for line in text.splitlines():
|
||||
header = _HEADER_RE.match(line.strip())
|
||||
if header:
|
||||
current = files.setdefault(header["name"], [])
|
||||
elif current is not None:
|
||||
current.append(line)
|
||||
return {name: "\n".join(lines).strip("\n") + "\n" for name, lines in files.items()}
|
||||
|
||||
|
||||
def pam_auth_stack(
|
||||
files: Mapping[str, str], service: str = PAM_SERVICE
|
||||
) -> list[PamAuthEntryDict] | None:
|
||||
"""*service*'s ``auth`` modules, includes and substacks followed, in stack order.
|
||||
|
||||
A file included twice -- or in a loop -- counts once; an include of a file
|
||||
that is not there adds nothing, as with PAM. None without a file for *service*.
|
||||
"""
|
||||
if service not in files:
|
||||
return None
|
||||
stack: list[PamAuthEntryDict] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def walk(name: str) -> None:
|
||||
if name in seen or name not in files:
|
||||
return
|
||||
seen.add(name)
|
||||
for entry in parse_pam_auth(files[name]):
|
||||
if entry["control"] in _INCLUDE_CONTROLS:
|
||||
walk(entry["module"])
|
||||
else:
|
||||
stack.append(entry)
|
||||
|
||||
walk(service)
|
||||
return stack
|
||||
|
||||
|
||||
class SshServerAuthMixin:
|
||||
"""Adds :meth:`get_ssh_server_auth` to a driver that can run commands on an OpenSSH host.
|
||||
|
||||
Mixed in by the drivers whose host runs a stock OpenSSH --
|
||||
:class:`~napalm_device_types.ssh_server.OpenSshServerMixin` carries it -- so
|
||||
``hasattr(driver, "get_ssh_server_auth")`` stays a truthful answer. Reading,
|
||||
not writing: a platform that generates sshd_config itself can carry it too.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def get_ssh_server_auth(self) -> SshServerAuthDict:
|
||||
"""
|
||||
Returns how sshd lets people log in, from ``sshd -T`` and PAM's sshd stack.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"password_authentication": False,
|
||||
"kbd_interactive_authentication": True,
|
||||
"pubkey_authentication": True,
|
||||
"hostbased_authentication": False,
|
||||
"gssapi_authentication": False,
|
||||
"authentication_methods": [["publickey", "keyboard-interactive"]],
|
||||
"permit_root_login": "no",
|
||||
"use_pam": True,
|
||||
"pam_auth_stack": [
|
||||
{"module": "pam_google_authenticator.so", "control": "required", "args": []}
|
||||
],
|
||||
}
|
||||
|
||||
:raises RuntimeError: if ``sshd -T`` fails -- no OpenSSH, or no root.
|
||||
"""
|
||||
result = self.run_command(SSHD_EFFECTIVE_COMMAND, privileged=True, timeout=_TIMEOUT)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"sshd -T failed: {(result.stderr or result.stdout).strip()}")
|
||||
auth = parse_sshd_auth(result.stdout)
|
||||
if auth["use_pam"]:
|
||||
auth["pam_auth_stack"] = self._pam_auth_stack()
|
||||
return auth
|
||||
|
||||
def _pam_auth_stack(self) -> list[PamAuthEntryDict] | None:
|
||||
"""sshd's PAM auth stack; None when ``/etc/pam.d`` gave nothing for sshd.
|
||||
|
||||
``tail`` goes on past a file it cannot open and exits 1, so what it did
|
||||
print is used whatever the exit status.
|
||||
"""
|
||||
result = self.run_command(PAM_FILES_COMMAND, privileged=False, timeout=_TIMEOUT)
|
||||
return pam_auth_stack(parse_pam_files(result.stdout))
|
||||
+437
-536
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,312 @@
|
||||
"""The sudo password an earlier driver left in shell histories, and taking it back.
|
||||
|
||||
A driver that typed ``echo '<password>' | sudo -S -p "" <command>`` into an
|
||||
interactive shell left that line, password and all, in the login user's shell
|
||||
history, once per command -- and where only the part before the first ``&&``
|
||||
ran as root, it left files root should own to the login user. A driver that has
|
||||
stopped doing so still leaves both behind on every host it ever reached.
|
||||
|
||||
:class:`SudoHistoryMixin` reads the first as a fact and takes both back. The
|
||||
commands are the same on every POSIX host, so they live here once; a driver
|
||||
mixes it in, supplies ``run_command`` and says what it once left behind:
|
||||
:attr:`~SudoHistoryMixin.SUDO_HISTORY_MARKER` and
|
||||
:attr:`~SudoHistoryMixin.SUDO_ROOT_FILES`.
|
||||
|
||||
**The password never travels.** Lines are counted with ``grep -c`` and deleted
|
||||
with ``sed``, both matching the marker only, as the login user who owns the
|
||||
history. Nothing of a line's content is read back, and nothing goes to stdin.
|
||||
|
||||
**What is deleted is gone from the disk too, as far as a file can say.** ``sed
|
||||
-i`` with a backup suffix renames the old file to the backup and writes a new
|
||||
one; the backup -- the old file's blocks -- is overwritten with ``shred -u``,
|
||||
or removed with ``rm`` where there is no ``shred``. Backups, snapshots and an
|
||||
audit log of the host may still hold the password: only rotating it ends that.
|
||||
|
||||
**A file given back to root** must exist as a regular file, not be a symbolic
|
||||
link, and be owned by the login user. ``chown -h`` never follows a link that
|
||||
appears in between.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.fixes import run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepDict, FixStepOutcomeDict
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: The shell history files looked at, in the login user's home.
|
||||
HISTORY_FILES = (".bash_history", ".zsh_history", ".ash_history", ".sh_history")
|
||||
|
||||
#: The suffix of the moment's backup ``sed -i`` makes; it carries no application's name.
|
||||
HISTORY_BACKUP_SUFFIX = ".napalm-bak"
|
||||
|
||||
_COUNT = 'LC_ALL=C grep -c -F -e "$m" -- "$p"'
|
||||
|
||||
|
||||
class HistorySudoLinesDict(TypedDict):
|
||||
"""A history file holding lines with the sudo password (``get_history_sudo_lines``)."""
|
||||
|
||||
#: The file, as ``~/<name>``.
|
||||
file: str
|
||||
lines: int
|
||||
|
||||
|
||||
class HistoryCleanupDict(TypedDict):
|
||||
"""What one history file held before the cleanup and holds after it."""
|
||||
|
||||
file: str
|
||||
before: int
|
||||
after: int
|
||||
|
||||
|
||||
class SudoHistoryCleanupDict(FixResultDict):
|
||||
"""The result of ``remove_history_sudo_lines``: the fix, and what it changed."""
|
||||
|
||||
#: Every history file there is, with its lines before and after.
|
||||
files: list[HistoryCleanupDict]
|
||||
#: How many lines were deleted, over all files.
|
||||
removed: int
|
||||
#: The files given back to root.
|
||||
owners_restored: list[str]
|
||||
|
||||
|
||||
def _bre(text: str) -> str:
|
||||
"""*text* as a POSIX basic regular expression matching it literally, for ``sed``."""
|
||||
return "".join("\\" + c if c in "\\.[]*^$/" else c for c in text)
|
||||
|
||||
|
||||
def _history_loop(body: str) -> str:
|
||||
names = " ".join(HISTORY_FILES)
|
||||
return f'for f in {names}; do p="$HOME/$f"; [ -f "$p" ] || continue; {body}; done'
|
||||
|
||||
|
||||
def count_script(marker: str) -> str:
|
||||
"""Print ``<count> <name>`` per history file there is; exit 2 when one cannot be read."""
|
||||
return f"m={quote(marker)}; " + _history_loop(
|
||||
f'n=$({_COUNT}); [ $? -le 1 ] || exit 2; printf "%s %s\\n" "$n" "$f"'
|
||||
)
|
||||
|
||||
|
||||
def cleanup_script(marker: str) -> str:
|
||||
"""Delete the lines holding *marker* from every history file there is.
|
||||
|
||||
Prints per file: ``done <before> <after> <name>``, ``link <count> <name>``
|
||||
(left alone), ``unreadable <name>`` or ``failed <before> <name>``.
|
||||
"""
|
||||
backup = f'"$p"{quote(HISTORY_BACKUP_SUFFIX)}'
|
||||
return f"m={quote(marker)}; r={quote(_bre(marker))}; " + _history_loop(
|
||||
f"b=$({_COUNT}); "
|
||||
'[ $? -le 1 ] || { printf "unreadable %s\\n" "$f"; continue; }; '
|
||||
'if [ -L "$p" ]; then printf "link %s %s\\n" "$b" "$f"; continue; fi; '
|
||||
'if [ "$b" -gt 0 ]; then '
|
||||
f'LC_ALL=C sed -i{quote(HISTORY_BACKUP_SUFFIX)} -e "/$r/d" "$p"; s=$?; '
|
||||
# A sed that renamed the file away and wrote no new one: the backup is the history.
|
||||
f'[ -e "$p" ] || mv -f {backup} "$p"; '
|
||||
f"[ -e {backup} ] && {{ shred -u {backup} 2>/dev/null || rm -f {backup}; }}; "
|
||||
'[ $s -eq 0 ] || { printf "failed %s %s\\n" "$b" "$f"; continue; }; '
|
||||
"fi; "
|
||||
f'a=$({_COUNT}); printf "done %s %s %s\\n" "$b" "$a" "$f"'
|
||||
)
|
||||
|
||||
|
||||
def owners_script(user: str, paths: tuple[str, ...]) -> str:
|
||||
"""As root: give each of *paths* back to root:root where *user* owns it.
|
||||
|
||||
Prints ``fixed <path>`` or ``failed <path>`` per file it changed or tried to.
|
||||
"""
|
||||
return (
|
||||
f"u={quote(user)}; for p in {' '.join(quote(p) for p in paths)}; do "
|
||||
'[ -f "$p" ] && [ ! -L "$p" ] || continue; '
|
||||
'[ -n "$(find "$p" -prune -user "$u" 2>/dev/null)" ] || continue; '
|
||||
'if chown -h 0:0 "$p"; then printf "fixed %s\\n" "$p"; '
|
||||
'else printf "failed %s\\n" "$p"; fi; done'
|
||||
)
|
||||
|
||||
|
||||
def _home(name: str) -> str:
|
||||
return f"~/{name}"
|
||||
|
||||
|
||||
def _lines(n: int) -> str:
|
||||
return "1 line" if n == 1 else f"{n} lines"
|
||||
|
||||
|
||||
def _done(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]:
|
||||
before, after, name = int(rest[0]), int(rest[1]), _home(rest[2])
|
||||
removed = before - after
|
||||
text = (
|
||||
f"{name}: {_lines(removed)} removed ({before} before, {after} after)"
|
||||
if before
|
||||
else f"{name}: no such line"
|
||||
)
|
||||
return after == 0, text, {"file": name, "before": before, "after": after}
|
||||
|
||||
|
||||
def _link(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]:
|
||||
count = int(rest[0])
|
||||
return count == 0, f"{_home(rest[1])}: a symbolic link, left alone ({_lines(count)})", None
|
||||
|
||||
|
||||
def _unreadable(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]:
|
||||
return False, f"{_home(rest[0])}: cannot be read", None
|
||||
|
||||
|
||||
def _failed(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]:
|
||||
kept = _lines(int(rest[0]))
|
||||
return False, f"{_home(rest[1])}: could not be rewritten ({kept} kept)", None
|
||||
|
||||
|
||||
#: Per kind of line :func:`cleanup_script` prints: how many words follow, and what it says.
|
||||
_CLEANUP_LINES: dict[
|
||||
str, tuple[int, Callable[[list[str]], tuple[bool, str, HistoryCleanupDict | None]]]
|
||||
] = {
|
||||
"done": (3, _done),
|
||||
"link": (2, _link),
|
||||
"unreadable": (1, _unreadable),
|
||||
"failed": (2, _failed),
|
||||
}
|
||||
|
||||
|
||||
class SudoHistoryMixin:
|
||||
"""Reads and removes the sudo password an earlier driver left in shell histories.
|
||||
|
||||
Mixed in by the drivers that once typed it into a shell, not by a base
|
||||
class, so ``callable(getattr(driver, "get_history_sudo_lines", None))``
|
||||
stays a truthful answer.
|
||||
"""
|
||||
|
||||
#: What every line carries that typed the sudo password into the shell, as a
|
||||
#: fixed string -- ``"| sudo -S -p "`` for ``echo '<password>' | sudo -S -p ""
|
||||
#: <command>``. None for a driver that never did: nothing is looked for.
|
||||
SUDO_HISTORY_MARKER: ClassVar[str | None] = None
|
||||
|
||||
#: Files an earlier version wrote as the login user where root should have.
|
||||
SUDO_ROOT_FILES: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def get_history_sudo_lines(self) -> list[HistorySudoLinesDict]:
|
||||
"""The login user's history files that hold lines with the sudo password, and how many.
|
||||
|
||||
A fact: counted with ``grep -c`` as the login user; no line is read.
|
||||
An empty list when no file holds one, or the driver never typed it.
|
||||
|
||||
:raises RuntimeError: when a history file cannot be read.
|
||||
"""
|
||||
marker = self.SUDO_HISTORY_MARKER
|
||||
if not marker:
|
||||
return []
|
||||
result = self.run_command(count_script(marker), timeout=30)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(
|
||||
f"cannot count the shell history: {(result.stderr or result.stdout).strip()}"
|
||||
)
|
||||
found: list[HistorySudoLinesDict] = []
|
||||
for line in result.stdout.splitlines():
|
||||
count, _, name = line.strip().partition(" ")
|
||||
if count.isdigit() and int(count) and name:
|
||||
found.append({"file": _home(name), "lines": int(count)})
|
||||
return found
|
||||
|
||||
def remove_history_sudo_lines(self) -> SudoHistoryCleanupDict:
|
||||
"""Delete those lines, as the login user, and give :attr:`SUDO_ROOT_FILES` back to root.
|
||||
|
||||
Two steps, ``history`` and ``owners``; the second runs when the first
|
||||
failed, too. Succeeds when no history file holds such a line any more
|
||||
and every file the login user owned is root's again.
|
||||
"""
|
||||
files: list[HistoryCleanupDict] = []
|
||||
restored: list[str] = []
|
||||
parts = [
|
||||
run_fix_steps([("history", lambda: self._clean_histories(files))]),
|
||||
run_fix_steps([("owners", lambda: self._restore_owners(restored))]),
|
||||
]
|
||||
steps: list[FixStepDict] = [s for part in parts for s in part["steps"]]
|
||||
return {
|
||||
"success": all(part["success"] for part in parts),
|
||||
"steps": steps,
|
||||
"output": "\n".join(f"[{s['step']}] {s['output']}".rstrip() for s in steps),
|
||||
"files": files,
|
||||
"removed": sum(f["before"] - f["after"] for f in files),
|
||||
"owners_restored": restored,
|
||||
}
|
||||
|
||||
def _clean_histories(self, files: list[HistoryCleanupDict]) -> FixStepOutcomeDict:
|
||||
marker = self.SUDO_HISTORY_MARKER
|
||||
if not marker:
|
||||
return {"ok": True, "output": "this driver never typed the sudo password"}
|
||||
result = self.run_command(cleanup_script(marker), timeout=60)
|
||||
said: list[str] = []
|
||||
ok = result.exit_code == 0
|
||||
for line in result.stdout.splitlines():
|
||||
ok = self._history_line(line.split(), files, said) and ok
|
||||
if result.exit_code != 0:
|
||||
said.append((result.stderr or result.stdout).strip())
|
||||
return {"ok": ok, "output": "\n".join(said) or "no shell history"}
|
||||
|
||||
@staticmethod
|
||||
def _history_line(words: list[str], files: list[HistoryCleanupDict], said: list[str]) -> bool:
|
||||
"""Take one line of :func:`cleanup_script` into *files* and *said*; whether it is clean."""
|
||||
kind, rest = (words[0], words[1:]) if words else ("", [])
|
||||
read = _CLEANUP_LINES.get(kind)
|
||||
if read is None or len(rest) != read[0]:
|
||||
return True
|
||||
clean, text, entry = read[1](rest)
|
||||
said.append(text)
|
||||
if entry is not None:
|
||||
files.append(entry)
|
||||
return clean
|
||||
|
||||
def _restore_owners(self, restored: list[str]) -> FixStepOutcomeDict:
|
||||
paths = tuple(self.SUDO_ROOT_FILES)
|
||||
if not paths:
|
||||
return {"ok": True, "output": "no file to check"}
|
||||
who = self.run_command("id -u; id -un", timeout=30).stdout.split()
|
||||
if len(who) < 2:
|
||||
return {"ok": False, "output": "cannot tell who the login user is"}
|
||||
uid, user = who[0], who[1]
|
||||
if uid == "0":
|
||||
return {"ok": True, "output": "logged in as root: every file it wrote is root's"}
|
||||
result = self.run_command(owners_script(user, paths), privileged=True, timeout=30)
|
||||
said: list[str] = []
|
||||
ok = result.exit_code == 0
|
||||
for line in result.stdout.splitlines():
|
||||
kind, _, path = line.strip().partition(" ")
|
||||
if kind == "fixed":
|
||||
restored.append(path)
|
||||
said.append(f"{path}: owned by root again")
|
||||
elif kind == "failed":
|
||||
ok = False
|
||||
said.append(f"{path}: could not be given back to root")
|
||||
if result.exit_code != 0:
|
||||
said.append((result.stderr or result.stdout).strip())
|
||||
return {"ok": ok, "output": "\n".join(said) or f"no file owned by {user}"}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"HISTORY_BACKUP_SUFFIX",
|
||||
"HISTORY_FILES",
|
||||
"HistoryCleanupDict",
|
||||
"HistorySudoLinesDict",
|
||||
"SudoHistoryCleanupDict",
|
||||
"SudoHistoryMixin",
|
||||
"cleanup_script",
|
||||
"count_script",
|
||||
"owners_script",
|
||||
]
|
||||
+334
-359
@@ -10,13 +10,15 @@ Usage::
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import Dict, List
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.base import DeviceTypeDriver
|
||||
from napalm_device_types.mac_acl import MacAclMixin
|
||||
from napalm_device_types.models import (
|
||||
Dot1XPortDict,
|
||||
HealthMetricsDict,
|
||||
InterfaceConfigDict,
|
||||
MACACLDict,
|
||||
PoESummaryDict,
|
||||
PortChannelDict,
|
||||
SpanningTreeDict,
|
||||
@@ -24,8 +26,7 @@ from napalm_device_types.models import (
|
||||
)
|
||||
|
||||
|
||||
class SwitchDriver(DeviceTypeDriver):
|
||||
TYPE_LABEL: str = "Switch"
|
||||
class SwitchDriver(MacAclMixin, DeviceTypeDriver):
|
||||
"""
|
||||
Abstract intermediate driver for Ethernet switches.
|
||||
|
||||
@@ -34,403 +35,377 @@ class SwitchDriver(DeviceTypeDriver):
|
||||
operations that concrete drivers must implement.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
async def get_health_metrics(cls, snmp_get, snmp_walk) -> HealthMetricsDict:
|
||||
"""Collect SNMP health metrics for this switch type.
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
#: driver lists its role bases is the ranking; see
|
||||
#: :func:`napalm_device_types.roles.primary_role_of`.
|
||||
ROLE: str = "switch"
|
||||
TYPE_LABEL: str = "Switch"
|
||||
|
||||
Switch vendors use proprietary OIDs — each concrete driver must
|
||||
override this classmethod.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_spanning_tree(self) -> Dict[str, SpanningTreeDict]:
|
||||
"""
|
||||
Returns spanning tree status for each STP instance.
|
||||
@classmethod
|
||||
async def get_health_metrics(
|
||||
cls,
|
||||
snmp_get: Callable[..., Awaitable[Any]],
|
||||
snmp_walk: Callable[..., Awaitable[dict[str, Any]]],
|
||||
) -> HealthMetricsDict:
|
||||
"""Collect SNMP health metrics for this switch type.
|
||||
|
||||
Keys are STP instance identifiers (e.g. VLAN IDs for PVST,
|
||||
``"MST0"`` for MSTP, or ``"0"`` for a single instance).
|
||||
Each value contains:
|
||||
Switch vendors use proprietary OIDs — each concrete driver must
|
||||
override this classmethod.
|
||||
"""
|
||||
...
|
||||
|
||||
* mode (string) - STP variant: ``"STP"``, ``"RSTP"``, ``"MSTP"``, ``"PVST"``
|
||||
* root_bridge (bool) - whether this device is the root bridge
|
||||
* root_id (string) - root bridge MAC address
|
||||
* root_priority (int) - root bridge priority
|
||||
* bridge_id (string) - this bridge's MAC address
|
||||
* bridge_priority (int) - this bridge's priority
|
||||
* interfaces (dict) - per-interface STP state:
|
||||
def get_spanning_tree(self) -> dict[str, SpanningTreeDict]:
|
||||
"""
|
||||
Returns spanning tree status for each STP instance.
|
||||
|
||||
* role (string) - ``"root"``, ``"designated"``, ``"alternate"``, ``"backup"``
|
||||
* state (string) - ``"forwarding"``, ``"blocking"``, ``"learning"``, ``"listening"``
|
||||
* cost (int) - port path cost
|
||||
* port_priority (int) - port priority
|
||||
Keys are STP instance identifiers (e.g. VLAN IDs for PVST,
|
||||
``"MST0"`` for MSTP, or ``"0"`` for a single instance).
|
||||
Each value contains:
|
||||
|
||||
Example::
|
||||
* mode (string) - STP variant: ``"STP"``, ``"RSTP"``, ``"MSTP"``, ``"PVST"``
|
||||
* root_bridge (bool) - whether this device is the root bridge
|
||||
* root_id (string) - root bridge MAC address
|
||||
* root_priority (int) - root bridge priority
|
||||
* bridge_id (string) - this bridge's MAC address
|
||||
* bridge_priority (int) - this bridge's priority
|
||||
* interfaces (dict) - per-interface STP state:
|
||||
|
||||
{
|
||||
"1": {
|
||||
"mode": "RSTP",
|
||||
"root_bridge": False,
|
||||
"root_id": "00:11:22:33:44:55",
|
||||
"root_priority": 4096,
|
||||
"bridge_id": "AA:BB:CC:DD:EE:FF",
|
||||
"bridge_priority": 32768,
|
||||
"interfaces": {
|
||||
"GigabitEthernet0/1": {
|
||||
"role": "root",
|
||||
"state": "forwarding",
|
||||
"cost": 4,
|
||||
"port_priority": 128,
|
||||
* role (string) - ``"root"``, ``"designated"``, ``"alternate"``, ``"backup"``
|
||||
* state (string) - ``"forwarding"``, ``"blocking"``, ``"learning"``, ``"listening"``
|
||||
* cost (int) - port path cost
|
||||
* port_priority (int) - port priority
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"1": {
|
||||
"mode": "RSTP",
|
||||
"root_bridge": False,
|
||||
"root_id": "00:11:22:33:44:55",
|
||||
"root_priority": 4096,
|
||||
"bridge_id": "AA:BB:CC:DD:EE:FF",
|
||||
"bridge_priority": 32768,
|
||||
"interfaces": {
|
||||
"GigabitEthernet0/1": {
|
||||
"role": "root",
|
||||
"state": "forwarding",
|
||||
"cost": 4,
|
||||
"port_priority": 128,
|
||||
},
|
||||
"GigabitEthernet0/2": {
|
||||
"role": "designated",
|
||||
"state": "forwarding",
|
||||
"cost": 4,
|
||||
"port_priority": 128,
|
||||
},
|
||||
},
|
||||
"GigabitEthernet0/2": {
|
||||
"role": "designated",
|
||||
"state": "forwarding",
|
||||
"cost": 4,
|
||||
"port_priority": 128,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"""
|
||||
...
|
||||
|
||||
def get_port_channels(self) -> Dict[str, PortChannelDict]:
|
||||
"""
|
||||
Returns port-channel (LAG) configuration and status.
|
||||
def get_port_channels(self) -> dict[str, PortChannelDict]:
|
||||
"""
|
||||
Returns port-channel (LAG) configuration and status.
|
||||
|
||||
Keys are port-channel interface names (e.g. ``"Port-Channel1"``).
|
||||
Each value contains:
|
||||
Keys are port-channel interface names (e.g. ``"Port-Channel1"``).
|
||||
Each value contains:
|
||||
|
||||
* members (list of strings) - names of member interfaces
|
||||
* protocol (string) - aggregation protocol: ``"LACP"``, ``"PAgP"``, ``"static"``
|
||||
* min_links (int) - minimum number of active members required
|
||||
* is_up (bool) - whether the LAG is operationally up
|
||||
* members (list of strings) - names of member interfaces
|
||||
* protocol (string) - aggregation protocol: ``"LACP"``, ``"PAgP"``, ``"static"``
|
||||
* min_links (int) - minimum number of active members required
|
||||
* is_up (bool) - whether the LAG is operationally up
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
{
|
||||
"Port-Channel1": {
|
||||
"members": ["GigabitEthernet0/1", "GigabitEthernet0/2"],
|
||||
"protocol": "LACP",
|
||||
"min_links": 1,
|
||||
"is_up": True,
|
||||
{
|
||||
"Port-Channel1": {
|
||||
"members": ["GigabitEthernet0/1", "GigabitEthernet0/2"],
|
||||
"protocol": "LACP",
|
||||
"min_links": 1,
|
||||
"is_up": True,
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
"""
|
||||
...
|
||||
|
||||
def get_mac_acl(self) -> Dict[str, MACACLDict]:
|
||||
"""
|
||||
Returns the MAC-address-based access control lists configured per port.
|
||||
def get_dot1x_ports(self) -> dict[str, Dot1XPortDict]:
|
||||
"""
|
||||
Returns the 802.1X / NAC configuration per switch port.
|
||||
|
||||
Keys are interface names. Each value contains:
|
||||
Keys are interface names. Each value contains:
|
||||
|
||||
* name (string) - interface name (repeated for convenience)
|
||||
* policy (string) - ACL mode:
|
||||
* enabled (bool) - whether 802.1X is active on this port
|
||||
* port_control (string) - authentication mode:
|
||||
|
||||
* ``"allow"`` – whitelist: only listed MACs may use this port
|
||||
* ``"deny"`` – blacklist: listed MACs are blocked
|
||||
* ``"disabled"`` – no MAC filtering active
|
||||
* ``"auto"`` – port authenticates normally
|
||||
* ``"force-authorized"`` – port always passes traffic (bypass)
|
||||
* ``"force-unauthorized"`` – port always blocks traffic
|
||||
|
||||
* entries (list) - ACL entries, each with:
|
||||
* host_mode (string) - how many identities are authenticated per port:
|
||||
|
||||
* mac (string) - MAC address (normalised, colon-separated)
|
||||
* action (string) - ``"allow"`` or ``"deny"``
|
||||
* description (string) - optional human-readable label
|
||||
* ``"single-host"`` – one device, then port is locked
|
||||
* ``"multi-host"`` – first auth unlocks port for all devices
|
||||
* ``"multi-domain"`` – one data + one voice device (IP phone scenario)
|
||||
* ``"multi-auth"`` – each device authenticates individually
|
||||
|
||||
Example::
|
||||
* auth_server (dict) - RADIUS authentication server (host, port, timeout, retries)
|
||||
* acct_server (dict or None) - RADIUS accounting server, ``None`` if unused
|
||||
* reauthentication (bool) - whether periodic re-authentication is enabled
|
||||
* reauth_interval (int) - re-authentication interval in seconds (0 = disabled)
|
||||
* guest_vlan (int) - VLAN ID for unauthenticated clients (0 = disabled)
|
||||
* auth_fail_vlan (int) - VLAN ID for clients that fail authentication (0 = disabled)
|
||||
|
||||
{
|
||||
"GigabitEthernet0/1": {
|
||||
"name": "GigabitEthernet0/1",
|
||||
"policy": "allow",
|
||||
"entries": [
|
||||
{"mac": "AA:BB:CC:DD:EE:01", "action": "allow", "description": "printer"},
|
||||
],
|
||||
},
|
||||
"GigabitEthernet0/2": {
|
||||
"name": "GigabitEthernet0/2",
|
||||
"policy": "disabled",
|
||||
"entries": [],
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
Note: RADIUS shared secrets are intentionally omitted.
|
||||
|
||||
def get_dot1x_config(self) -> Dict[str, Dot1XPortDict]:
|
||||
"""
|
||||
Returns the 802.1X / NAC configuration per switch port.
|
||||
Example::
|
||||
|
||||
Keys are interface names. Each value contains:
|
||||
|
||||
* enabled (bool) - whether 802.1X is active on this port
|
||||
* port_control (string) - authentication mode:
|
||||
|
||||
* ``"auto"`` – port authenticates normally
|
||||
* ``"force-authorized"`` – port always passes traffic (bypass)
|
||||
* ``"force-unauthorized"`` – port always blocks traffic
|
||||
|
||||
* host_mode (string) - how many identities are authenticated per port:
|
||||
|
||||
* ``"single-host"`` – one device, then port is locked
|
||||
* ``"multi-host"`` – first auth unlocks port for all devices
|
||||
* ``"multi-domain"`` – one data + one voice device (IP phone scenario)
|
||||
* ``"multi-auth"`` – each device authenticates individually
|
||||
|
||||
* auth_server (dict) - RADIUS authentication server (host, port, timeout, retries)
|
||||
* acct_server (dict or None) - RADIUS accounting server, ``None`` if unused
|
||||
* reauthentication (bool) - whether periodic re-authentication is enabled
|
||||
* reauth_interval (int) - re-authentication interval in seconds (0 = disabled)
|
||||
* guest_vlan (int) - VLAN ID for unauthenticated clients (0 = disabled)
|
||||
* auth_fail_vlan (int) - VLAN ID for clients that fail authentication (0 = disabled)
|
||||
|
||||
Note: RADIUS shared secrets are intentionally omitted.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"GigabitEthernet0/1": {
|
||||
"enabled": True,
|
||||
"port_control": "auto",
|
||||
"host_mode": "multi-domain",
|
||||
"auth_server": {
|
||||
"host": "radius.corp.example",
|
||||
"port": 1812,
|
||||
"timeout": 5,
|
||||
"retries": 3,
|
||||
},
|
||||
"acct_server": None,
|
||||
"reauthentication": True,
|
||||
"reauth_interval": 3600,
|
||||
"guest_vlan": 99,
|
||||
"auth_fail_vlan": 999,
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_poe_status(self) -> PoESummaryDict:
|
||||
"""
|
||||
Returns the PoE status of the switch as a whole and per port.
|
||||
|
||||
The returned dictionary contains:
|
||||
|
||||
* total_power_budget (float) - total PoE power available in watts
|
||||
* total_power_draw (float) - total PoE power currently consumed in watts
|
||||
* ports (dict) - per-interface PoE state, keyed by interface name:
|
||||
|
||||
* enabled (bool) - whether PoE is configured on this port
|
||||
* status (string) - operational state:
|
||||
|
||||
* ``"delivering"`` – power is being delivered to a PD
|
||||
* ``"searching"`` – port is looking for a powered device
|
||||
* ``"fault"`` – an error condition was detected
|
||||
* ``"disabled"`` – PoE is administratively off
|
||||
* ``"denied"`` – PD detected but power budget exceeded
|
||||
|
||||
* poe_class (string) - IEEE 802.3 class: ``"Class 0"`` … ``"Class 8"``
|
||||
(``"unknown"`` if not yet negotiated)
|
||||
* power_draw (float) - current power consumption in watts
|
||||
* power_budget (float) - per-port power limit in watts
|
||||
* voltage (float) - measured port voltage in volts
|
||||
* current (float) - measured port current in milliamps
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"total_power_budget": 740.0,
|
||||
"total_power_draw": 43.2,
|
||||
"ports": {
|
||||
{
|
||||
"GigabitEthernet0/1": {
|
||||
"enabled": True,
|
||||
"status": "delivering",
|
||||
"poe_class": "Class 3",
|
||||
"power_draw": 12.4,
|
||||
"power_budget": 30.0,
|
||||
"voltage": 53.5,
|
||||
"current": 231.0,
|
||||
"port_control": "auto",
|
||||
"host_mode": "multi-domain",
|
||||
"auth_server": {
|
||||
"host": "radius.corp.example",
|
||||
"port": 1812,
|
||||
"timeout": 5,
|
||||
"retries": 3,
|
||||
},
|
||||
"acct_server": None,
|
||||
"reauthentication": True,
|
||||
"reauth_interval": 3600,
|
||||
"guest_vlan": 99,
|
||||
"auth_fail_vlan": 999,
|
||||
},
|
||||
"GigabitEthernet0/2": {
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
def get_poe_status(self) -> PoESummaryDict:
|
||||
"""
|
||||
Returns the PoE status of the switch as a whole and per port.
|
||||
|
||||
The returned dictionary contains:
|
||||
|
||||
* total_power_budget (float) - total PoE power available in watts
|
||||
* total_power_draw (float) - total PoE power currently consumed in watts
|
||||
* ports (dict) - per-interface PoE state, keyed by interface name:
|
||||
|
||||
* enabled (bool) - whether PoE is configured on this port
|
||||
* status (string) - operational state:
|
||||
|
||||
* ``"delivering"`` – power is being delivered to a PD
|
||||
* ``"searching"`` – port is looking for a powered device
|
||||
* ``"fault"`` – an error condition was detected
|
||||
* ``"disabled"`` – PoE is administratively off
|
||||
* ``"denied"`` – PD detected but power budget exceeded
|
||||
|
||||
* poe_class (string) - IEEE 802.3 class: ``"Class 0"`` … ``"Class 8"``
|
||||
(``"unknown"`` if not yet negotiated)
|
||||
* power_draw (float) - current power consumption in watts
|
||||
* power_budget (float) - per-port power limit in watts
|
||||
* voltage (float) - measured port voltage in volts
|
||||
* current (float) - measured port current in milliamps
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"total_power_budget": 740.0,
|
||||
"total_power_draw": 43.2,
|
||||
"ports": {
|
||||
"GigabitEthernet0/1": {
|
||||
"enabled": True,
|
||||
"status": "delivering",
|
||||
"poe_class": "Class 3",
|
||||
"power_draw": 12.4,
|
||||
"power_budget": 30.0,
|
||||
"voltage": 53.5,
|
||||
"current": 231.0,
|
||||
},
|
||||
"GigabitEthernet0/2": {
|
||||
"enabled": True,
|
||||
"status": "searching",
|
||||
"poe_class": "unknown",
|
||||
"power_draw": 0.0,
|
||||
"power_budget": 30.0,
|
||||
"voltage": 0.0,
|
||||
"current": 0.0,
|
||||
},
|
||||
"GigabitEthernet0/3": {
|
||||
"enabled": False,
|
||||
"status": "disabled",
|
||||
"poe_class": "unknown",
|
||||
"power_draw": 0.0,
|
||||
"power_budget": 0.0,
|
||||
"voltage": 0.0,
|
||||
"current": 0.0,
|
||||
},
|
||||
},
|
||||
}
|
||||
"""
|
||||
...
|
||||
|
||||
def set_vlan(self, vlan_id: int, config: VlanConfigDict) -> None:
|
||||
"""
|
||||
Creates or updates a VLAN on the switch.
|
||||
|
||||
If the VLAN does not yet exist it is created first. Only the keys
|
||||
present in *config* are applied; omitted keys leave the existing VLAN
|
||||
configuration untouched.
|
||||
|
||||
:param vlan_id: VLAN ID (1–4094).
|
||||
:param config: A (partial) :class:`~napalm_device_types.models.VlanConfigDict`
|
||||
containing the fields to set. Supported keys:
|
||||
|
||||
* ``name`` (str) – human-readable VLAN name
|
||||
* ``active`` (bool) – ``True`` = active, ``False`` = suspended
|
||||
* ``interfaces`` (list of str) – access-port names to assign to
|
||||
this VLAN (replaces the current membership list)
|
||||
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *vlan_id* is out of range or a field value is invalid.
|
||||
|
||||
Example – create VLAN 10 with a name::
|
||||
|
||||
driver.set_vlan(10, {"name": "Workstations", "active": True})
|
||||
|
||||
Example – assign ports to an existing VLAN::
|
||||
|
||||
driver.set_vlan(
|
||||
10,
|
||||
{"interfaces": ["GigabitEthernet0/1", "GigabitEthernet0/2"]},
|
||||
)
|
||||
"""
|
||||
...
|
||||
|
||||
def delete_vlan(self, vlan_id: int) -> None:
|
||||
"""
|
||||
Removes a VLAN from the switch.
|
||||
|
||||
All ports that were assigned to this VLAN as their access VLAN are
|
||||
moved to the default VLAN (1) by the driver before deletion. Trunk
|
||||
ports that carry this VLAN will have it removed from their allowed
|
||||
VLAN list.
|
||||
|
||||
:param vlan_id: VLAN ID (1–4094) to delete.
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *vlan_id* is out of range or the VLAN does not
|
||||
exist on the device.
|
||||
|
||||
Example::
|
||||
|
||||
driver.delete_vlan(10)
|
||||
"""
|
||||
...
|
||||
|
||||
def set_interface(self, interface: str, config: InterfaceConfigDict) -> None:
|
||||
"""
|
||||
Applies configuration to a single switch interface.
|
||||
|
||||
Only the keys present in *config* are changed; omitted keys leave the
|
||||
current device configuration untouched.
|
||||
|
||||
:param interface: Interface name (e.g. ``"GigabitEthernet0/1"``).
|
||||
:param config: A (partial) :class:`~napalm_device_types.models.InterfaceConfigDict`
|
||||
containing the fields to update. Supported keys:
|
||||
|
||||
* ``description`` (str) – human-readable port label
|
||||
* ``enabled`` (bool) – administrative state
|
||||
* ``speed`` (int) – link speed in Mbps; ``0`` = auto-negotiate
|
||||
* ``duplex`` (str) – ``"full"``, ``"half"``, or ``"auto"``
|
||||
* ``mtu`` (int) – maximum transmission unit in bytes
|
||||
* ``mode`` (str) – ``"access"``, ``"trunk"``, or ``"routed"``
|
||||
* ``access_vlan`` (int) – untagged VLAN; relevant when mode is ``"access"``
|
||||
* ``voice_vlan`` (int) – voice VLAN ID (``0`` = disabled)
|
||||
* ``trunk_vlans`` (list of int) – tagged VLANs; empty = allow all
|
||||
* ``native_vlan`` (int) – native VLAN on trunk ports
|
||||
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *interface* does not exist or an invalid value is
|
||||
supplied for a configuration field.
|
||||
|
||||
Example – convert port to access VLAN 10 and add a description::
|
||||
|
||||
driver.set_interface(
|
||||
"GigabitEthernet0/1",
|
||||
{
|
||||
"description": "Workstation port",
|
||||
"enabled": True,
|
||||
"status": "searching",
|
||||
"poe_class": "unknown",
|
||||
"power_draw": 0.0,
|
||||
"power_budget": 30.0,
|
||||
"voltage": 0.0,
|
||||
"current": 0.0,
|
||||
"mode": "access",
|
||||
"access_vlan": 10,
|
||||
},
|
||||
"GigabitEthernet0/3": {
|
||||
"enabled": False,
|
||||
"status": "disabled",
|
||||
"poe_class": "unknown",
|
||||
"power_draw": 0.0,
|
||||
"power_budget": 0.0,
|
||||
"voltage": 0.0,
|
||||
"current": 0.0,
|
||||
)
|
||||
|
||||
Example – configure a trunk port::
|
||||
|
||||
driver.set_interface(
|
||||
"GigabitEthernet0/2",
|
||||
{
|
||||
"mode": "trunk",
|
||||
"trunk_vlans": [10, 20, 30],
|
||||
"native_vlan": 1,
|
||||
},
|
||||
},
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
)
|
||||
"""
|
||||
...
|
||||
|
||||
def set_vlan(self, vlan_id: int, config: VlanConfigDict) -> None:
|
||||
"""
|
||||
Creates or updates a VLAN on the switch.
|
||||
def set_lag_members(self, lag_name: str, members: list[str]) -> None:
|
||||
"""
|
||||
Sets the full member-port list of a LAG/trunk interface.
|
||||
|
||||
If the VLAN does not yet exist it is created first. Only the keys
|
||||
present in *config* are applied; omitted keys leave the existing VLAN
|
||||
configuration untouched.
|
||||
Diffs *members* against the LAG's current members (as reported by
|
||||
``get_interfaces()``'s ``lag_members`` field) and adds/removes ports
|
||||
on the device to match. The LAG itself must already exist on the
|
||||
device; this method only manages its membership.
|
||||
|
||||
:param vlan_id: VLAN ID (1–4094).
|
||||
:param config: A (partial) :class:`~napalm_device_types.models.VlanConfigDict`
|
||||
containing the fields to set. Supported keys:
|
||||
:param lag_name: Name of the LAG/trunk interface as returned by
|
||||
``get_interfaces()`` (e.g. ``"Trk1"``, ``"ch1"``, ``"Lag1"``).
|
||||
:param members: Full desired list of member port names.
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *lag_name* does not refer to a valid LAG.
|
||||
|
||||
* ``name`` (str) – human-readable VLAN name
|
||||
* ``active`` (bool) – ``True`` = active, ``False`` = suspended
|
||||
* ``interfaces`` (list of str) – access-port names to assign to
|
||||
this VLAN (replaces the current membership list)
|
||||
Example::
|
||||
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *vlan_id* is out of range or a field value is invalid.
|
||||
driver.set_lag_members("Lag1", ["GigabitEthernet0/1", "GigabitEthernet0/2"])
|
||||
"""
|
||||
...
|
||||
|
||||
Example – create VLAN 10 with a name::
|
||||
def set_poe_enabled(self, interface: str, enabled: bool) -> None:
|
||||
"""
|
||||
Administratively enables or disables PoE on a single port.
|
||||
|
||||
driver.set_vlan(10, {"name": "Workstations", "active": True})
|
||||
:param interface: Interface name (e.g. ``"GigabitEthernet0/1"``).
|
||||
:param enabled: ``True`` to enable PoE, ``False`` to disable it.
|
||||
:raises NotImplementedError: If the driver does not support PoE control.
|
||||
:raises ValueError: If the interface does not exist or does not support PoE.
|
||||
|
||||
Example – assign ports to an existing VLAN::
|
||||
Example::
|
||||
|
||||
driver.set_vlan(
|
||||
10,
|
||||
{"interfaces": ["GigabitEthernet0/1", "GigabitEthernet0/2"]},
|
||||
)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
driver.set_poe_enabled("GigabitEthernet0/1", False) # cut power
|
||||
driver.set_poe_enabled("GigabitEthernet0/1", True) # restore
|
||||
"""
|
||||
...
|
||||
|
||||
def delete_vlan(self, vlan_id: int) -> None:
|
||||
"""
|
||||
Removes a VLAN from the switch.
|
||||
def power_cycle_port(self, interface: str, delay: int = 5) -> None:
|
||||
"""
|
||||
Power-cycles the PoE port: cuts power, waits ``delay`` seconds, then
|
||||
restores power. Useful for rebooting a hung IP camera, AP, or IP phone
|
||||
without physical access.
|
||||
|
||||
All ports that were assigned to this VLAN as their access VLAN are
|
||||
moved to the default VLAN (1) by the driver before deletion. Trunk
|
||||
ports that carry this VLAN will have it removed from their allowed
|
||||
VLAN list.
|
||||
The method blocks until the full cycle (off → wait → on) is complete.
|
||||
After it returns the port is back in the delivering/searching state.
|
||||
|
||||
:param vlan_id: VLAN ID (1–4094) to delete.
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *vlan_id* is out of range or the VLAN does not
|
||||
exist on the device.
|
||||
:param interface: Interface name (e.g. ``"GigabitEthernet0/1"``).
|
||||
:param delay: Seconds to keep the port powered off (default: 5).
|
||||
:raises NotImplementedError: If the driver does not support PoE control.
|
||||
:raises ValueError: If the interface does not exist, does not support PoE,
|
||||
or PoE is administratively disabled on the port.
|
||||
|
||||
Example::
|
||||
Example::
|
||||
|
||||
driver.delete_vlan(10)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def set_interface(self, interface: str, config: InterfaceConfigDict) -> None:
|
||||
"""
|
||||
Applies configuration to a single switch interface.
|
||||
|
||||
Only the keys present in *config* are changed; omitted keys leave the
|
||||
current device configuration untouched.
|
||||
|
||||
:param interface: Interface name (e.g. ``"GigabitEthernet0/1"``).
|
||||
:param config: A (partial) :class:`~napalm_device_types.models.InterfaceConfigDict`
|
||||
containing the fields to update. Supported keys:
|
||||
|
||||
* ``description`` (str) – human-readable port label
|
||||
* ``enabled`` (bool) – administrative state
|
||||
* ``speed`` (int) – link speed in Mbps; ``0`` = auto-negotiate
|
||||
* ``duplex`` (str) – ``"full"``, ``"half"``, or ``"auto"``
|
||||
* ``mtu`` (int) – maximum transmission unit in bytes
|
||||
* ``mode`` (str) – ``"access"``, ``"trunk"``, or ``"routed"``
|
||||
* ``access_vlan`` (int) – untagged VLAN; relevant when mode is ``"access"``
|
||||
* ``voice_vlan`` (int) – voice VLAN ID (``0`` = disabled)
|
||||
* ``trunk_vlans`` (list of int) – tagged VLANs; empty = allow all
|
||||
* ``native_vlan`` (int) – native VLAN on trunk ports
|
||||
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *interface* does not exist or an invalid value is
|
||||
supplied for a configuration field.
|
||||
|
||||
Example – convert port to access VLAN 10 and add a description::
|
||||
|
||||
driver.set_interface(
|
||||
"GigabitEthernet0/1",
|
||||
{
|
||||
"description": "Workstation port",
|
||||
"enabled": True,
|
||||
"mode": "access",
|
||||
"access_vlan": 10,
|
||||
},
|
||||
)
|
||||
|
||||
Example – configure a trunk port::
|
||||
|
||||
driver.set_interface(
|
||||
"GigabitEthernet0/2",
|
||||
{
|
||||
"mode": "trunk",
|
||||
"trunk_vlans": [10, 20, 30],
|
||||
"native_vlan": 1,
|
||||
},
|
||||
)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def set_lag_members(self, lag_name: str, members: List[str]) -> None:
|
||||
"""
|
||||
Sets the full member-port list of a LAG/trunk interface.
|
||||
|
||||
Diffs *members* against the LAG's current members (as reported by
|
||||
``get_interfaces()``'s ``lag_members`` field) and adds/removes ports
|
||||
on the device to match. The LAG itself must already exist on the
|
||||
device; this method only manages its membership.
|
||||
|
||||
:param lag_name: Name of the LAG/trunk interface as returned by
|
||||
``get_interfaces()`` (e.g. ``"Trk1"``, ``"ch1"``, ``"Lag1"``).
|
||||
:param members: Full desired list of member port names.
|
||||
:raises NotImplementedError: If the driver does not implement this method.
|
||||
:raises ValueError: If *lag_name* does not refer to a valid LAG.
|
||||
|
||||
Example::
|
||||
|
||||
driver.set_lag_members("Lag1", ["GigabitEthernet0/1", "GigabitEthernet0/2"])
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def set_poe_enabled(self, interface: str, enabled: bool) -> None:
|
||||
"""
|
||||
Administratively enables or disables PoE on a single port.
|
||||
|
||||
:param interface: Interface name (e.g. ``"GigabitEthernet0/1"``).
|
||||
:param enabled: ``True`` to enable PoE, ``False`` to disable it.
|
||||
:raises NotImplementedError: If the driver does not support PoE control.
|
||||
:raises ValueError: If the interface does not exist or does not support PoE.
|
||||
|
||||
Example::
|
||||
|
||||
driver.set_poe_enabled("GigabitEthernet0/1", False) # cut power
|
||||
driver.set_poe_enabled("GigabitEthernet0/1", True) # restore
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def power_cycle_port(self, interface: str, delay: int = 5) -> None:
|
||||
"""
|
||||
Power-cycles the PoE port: cuts power, waits ``delay`` seconds, then
|
||||
restores power. Useful for rebooting a hung IP camera, AP, or IP phone
|
||||
without physical access.
|
||||
|
||||
The method blocks until the full cycle (off → wait → on) is complete.
|
||||
After it returns the port is back in the delivering/searching state.
|
||||
|
||||
:param interface: Interface name (e.g. ``"GigabitEthernet0/1"``).
|
||||
:param delay: Seconds to keep the port powered off (default: 5).
|
||||
:raises NotImplementedError: If the driver does not support PoE control.
|
||||
:raises ValueError: If the interface does not exist, does not support PoE,
|
||||
or PoE is administratively disabled on the port.
|
||||
|
||||
Example::
|
||||
|
||||
driver.power_cycle_port("GigabitEthernet0/1") # 5 s off
|
||||
driver.power_cycle_port("GigabitEthernet0/1", delay=15) # 15 s off
|
||||
"""
|
||||
raise NotImplementedError
|
||||
driver.power_cycle_port("GigabitEthernet0/1") # 5 s off
|
||||
driver.power_cycle_port("GigabitEthernet0/1", delay=15) # 15 s off
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,183 @@
|
||||
"""The SMBIOS identity of a host: system UUID, product serial, board serial -- and
|
||||
its system firmware (BIOS or UEFI): vendor, version, release date.
|
||||
|
||||
The identity is what ties a server to its BMC. The BMC reports the server's serial number and
|
||||
system UUID; the host reads the same values from its firmware tables. Both sides
|
||||
read them the same way on every Linux host, so the command, its parse and the
|
||||
placeholder filter live here once, and a driver only carries the command across.
|
||||
|
||||
**Placeholders are no identity.** Board vendors leave defaults in the DMI tables
|
||||
that are the same on thousands of machines: a Supermicro board's product serial
|
||||
is ``0123456789``, others read ``To be filled by O.E.M.`` or ``Default string``,
|
||||
and a common UUID on cheap boards is ``03000200-0400-0500-0006-000700080009``.
|
||||
Matching on those would join unrelated machines, so they read as empty.
|
||||
|
||||
**Root.** ``product_uuid`` and ``product_serial`` are readable by root only; without
|
||||
it they come back empty, which is "not known", not a mismatch.
|
||||
|
||||
**The firmware** comes from the same tables in the same round trip, so a driver that
|
||||
reads the identity reads it too. It is a fact about the host, not part of its identity:
|
||||
its placeholders are the vendors' text defaults, never a short value (a version of
|
||||
``1`` is a version), and sysfs's ``MM/DD/YYYY`` release date is given as ISO 8601.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
|
||||
class SystemIdentityDict(TypedDict):
|
||||
"""A host's SMBIOS identity, what ties it to its BMC, and its system firmware.
|
||||
|
||||
Each value is empty when unknown or a vendor placeholder."""
|
||||
|
||||
system_uuid: str # lowercase
|
||||
product_serial: str
|
||||
board_serial: str
|
||||
bios_vendor: str # the system firmware (BIOS or UEFI): its vendor,
|
||||
bios_version: str # its version,
|
||||
bios_date: str # its release date, YYYY-MM-DD
|
||||
|
||||
|
||||
_BEGIN = "IDBEGIN"
|
||||
_END = "IDEND"
|
||||
_DMI = "/sys/class/dmi/id"
|
||||
|
||||
#: The files read, in the order the output carries them.
|
||||
_FILES = (
|
||||
"product_uuid",
|
||||
"product_serial",
|
||||
"board_serial",
|
||||
"bios_vendor",
|
||||
"bios_version",
|
||||
"bios_date",
|
||||
)
|
||||
|
||||
#: Reads the files in one round trip, framed so a banner or prompt around the output
|
||||
#: cannot shift a field.
|
||||
_FIELDS = "%s\\n" * len(_FILES)
|
||||
SYSTEM_IDENTITY_COMMAND = f"printf '{_BEGIN}\\n{_FIELDS}{_END}\\n' " + " ".join(
|
||||
f'"$(cat {_DMI}/{name} 2>/dev/null)"' for name in _FILES
|
||||
)
|
||||
|
||||
#: Lowercased defaults board vendors leave in place.
|
||||
_PLACEHOLDERS = frozenset(
|
||||
{
|
||||
"",
|
||||
"none",
|
||||
"n/a",
|
||||
"na",
|
||||
"not specified",
|
||||
"not applicable",
|
||||
"not available",
|
||||
"to be filled by o.e.m.",
|
||||
"to be filled by oem",
|
||||
"default string",
|
||||
"default",
|
||||
"system serial number",
|
||||
"base board serial number",
|
||||
"chassis serial number",
|
||||
"serial number",
|
||||
"0123456789",
|
||||
"1234567890",
|
||||
"123456789",
|
||||
"o.e.m.",
|
||||
"oem",
|
||||
"03000200-0400-0500-0006-000700080009",
|
||||
}
|
||||
)
|
||||
#: A value of one repeated character ("0", "00000000", "FFFF-...") or of zeros and Fs.
|
||||
_REPEATED = re.compile(r"^(.)\1*$")
|
||||
|
||||
|
||||
def is_placeholder_identity(value: str | None) -> bool:
|
||||
"""Whether *value* is a vendor default rather than this machine's identity."""
|
||||
text = (value or "").strip().lower()
|
||||
if text in _PLACEHOLDERS:
|
||||
return True
|
||||
compact = text.replace("-", "").replace(" ", "")
|
||||
return bool(_REPEATED.match(compact))
|
||||
|
||||
|
||||
def _clean(value: str) -> str:
|
||||
value = value.strip()
|
||||
return "" if is_placeholder_identity(value) else value
|
||||
|
||||
|
||||
def _clean_text(value: str) -> str:
|
||||
"""A firmware text, empty for a vendor's text default; a short value stays."""
|
||||
value = value.strip()
|
||||
return "" if value.lower() in _PLACEHOLDERS else value
|
||||
|
||||
|
||||
def _iso_date(value: str) -> str:
|
||||
"""sysfs's ``MM/DD/YYYY`` as ``YYYY-MM-DD``; anything else is no date."""
|
||||
month, _, rest = value.strip().partition("/")
|
||||
day, _, year = rest.partition("/")
|
||||
try:
|
||||
return date(int(year), int(month), int(day)).isoformat()
|
||||
except ValueError:
|
||||
return ""
|
||||
|
||||
|
||||
def parse_system_identity(output: str) -> SystemIdentityDict:
|
||||
"""The identity from :data:`SYSTEM_IDENTITY_COMMAND`'s output, placeholders empty.
|
||||
|
||||
:raises ValueError: when the output carries no intact frame.
|
||||
"""
|
||||
lines = strip_terminal_codes(output).splitlines()
|
||||
try:
|
||||
start = lines.index(_BEGIN) + 1
|
||||
end = lines.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("system identity: no intact IDBEGIN/IDEND frame") from None
|
||||
fields = (lines[start:end] + [""] * len(_FILES))[: len(_FILES)]
|
||||
uuid, product_serial, board_serial = (_clean(f) for f in fields[:3])
|
||||
bios_vendor, bios_version, bios_date = fields[3:]
|
||||
return {
|
||||
"system_uuid": uuid.lower(),
|
||||
"product_serial": product_serial,
|
||||
"board_serial": board_serial,
|
||||
"bios_vendor": _clean_text(bios_vendor),
|
||||
"bios_version": _clean_text(bios_version),
|
||||
"bios_date": _iso_date(bios_date),
|
||||
}
|
||||
|
||||
|
||||
class SystemIdentityMixin:
|
||||
"""Adds :meth:`get_system_identity` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): command and parse are the same
|
||||
everywhere and concrete here; a driver supplies only
|
||||
:meth:`_run_system_identity_command` -- how a command reaches its host, and how it
|
||||
gains root there. Mixed in by the drivers that can, so
|
||||
``hasattr(driver, "get_system_identity")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_system_identity_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root when
|
||||
*privileged* (``product_uuid`` and ``product_serial`` are root's)."""
|
||||
...
|
||||
|
||||
def get_system_identity(self) -> SystemIdentityDict:
|
||||
"""
|
||||
Returns the host's SMBIOS identity and system firmware, each value empty when
|
||||
unknown or a vendor placeholder:
|
||||
|
||||
* system_uuid (str) - lowercase
|
||||
* product_serial (str)
|
||||
* board_serial (str)
|
||||
* bios_vendor (str) - the system firmware's vendor
|
||||
* bios_version (str)
|
||||
* bios_date (str) - its release date, ``YYYY-MM-DD``
|
||||
|
||||
:raises ValueError: if the output carried no intact reading.
|
||||
"""
|
||||
output = self._run_system_identity_command(SYSTEM_IDENTITY_COMMAND, privileged=True)
|
||||
return parse_system_identity(output)
|
||||
@@ -0,0 +1,328 @@
|
||||
"""systemd services: listing them in one round trip, and starting and stopping them.
|
||||
|
||||
What systemd reports about its services, and how one is started or stopped, is
|
||||
the same on every host that runs it. So the command, its parse, the check of a
|
||||
unit name and the reading of an action's exit status live here once, and a
|
||||
driver only carries a command across: SSH, an API's exec endpoint, whatever it
|
||||
has.
|
||||
|
||||
**Listing.** One command prints the installed unit files and, for every loaded
|
||||
service unit, what ``systemctl show`` knows about it -- state, boot state and
|
||||
main PID together, instead of asking ``systemctl is-enabled`` and ``systemctl
|
||||
show`` once per unit (two hundred round trips on an ordinary Linux host). The
|
||||
report is framed, and a report whose end is missing raises: a list cut short
|
||||
must never read as services that went away.
|
||||
|
||||
**What counts as enabled.** A unit file state of ``enabled`` or
|
||||
``enabled-runtime``. ``static`` does not: such a unit starts only when
|
||||
something else pulls it in, and calling it enabled made every one of them look
|
||||
like a service of the host. The state is read from ``UnitFileState``, never
|
||||
from a column of ``list-unit-files``, whose second column has been followed by
|
||||
a preset column since systemd 245.
|
||||
|
||||
**Starting and stopping.** ``systemctl`` runs bounded by ``timeout`` and never
|
||||
asks for a password, and its exit status is printed after it. The marker also
|
||||
keeps the output from ever being empty, which a transport that retries on an
|
||||
empty answer would otherwise take as a reason to run the action twice.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import ServiceDict
|
||||
from napalm_device_types.services import ServiceControlMixin
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "SVC_BEGIN"
|
||||
_END = "SVC_END"
|
||||
_NO_SYSTEMD = "no-systemd"
|
||||
_SUFFIX = ".service"
|
||||
|
||||
#: What ``systemctl show`` prints per unit. It prints them in its own order.
|
||||
_PROPERTIES = "Id,Names,LoadState,ActiveState,SubState,UnitFileState,MainPID"
|
||||
|
||||
#: Picks the units whose file state is ``generated`` out of ``systemctl show``'s
|
||||
#: output, whatever order it prints the properties in.
|
||||
_GENERATED_AWK = (
|
||||
'awk -F= \'NF<2{id="";g=0;next} $1=="Id"{id=$2} '
|
||||
'$1=="UnitFileState"{g=($2=="generated")} id!=""&&g{print id;id="";g=0}\''
|
||||
)
|
||||
|
||||
#: 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.
|
||||
#: ``xargs -0`` passes escaped names such as ``foo\x2dbar.service`` unchanged.
|
||||
#: A generated unit -- the wrapper systemd makes for a SysV script -- has no unit
|
||||
#: file whose state says whether it starts at boot; ``systemctl is-enabled``
|
||||
#: asks the script's rc links instead, for those few units only.
|
||||
SYSTEMD_SERVICES_COMMAND = (
|
||||
"printf '%s%s\\n' SVC_ BEGIN; "
|
||||
"[ -d /run/systemd/system ] || echo '[no-systemd]'; "
|
||||
"echo '[files]'; systemctl list-unit-files --type=service --no-legend --no-pager 2>/dev/null; "
|
||||
"echo '[units]'; s=$(systemctl list-units --type=service --all --no-legend --no-pager --plain "
|
||||
"2>/dev/null | awk '{print $1}' | tr '\\n' '\\0' | xargs -0 -r systemctl show --no-pager "
|
||||
f"-p {_PROPERTIES} -- 2>/dev/null); printf '%s\\n' \"$s\"; "
|
||||
f"echo '[generated]'; printf '%s\\n' \"$s\" | {_GENERATED_AWK} | while read -r u; do "
|
||||
'printf \'%s %s\\n\' "$u" "$(systemctl is-enabled -- "$u" 2>/dev/null)"; done; '
|
||||
"printf '%s%s\\n' SVC_ END"
|
||||
)
|
||||
|
||||
#: The lifecycle actions :meth:`SystemdServicesMixin.manage_service` accepts.
|
||||
SERVICE_ACTIONS = ("start", "stop", "restart", "enable", "disable")
|
||||
|
||||
#: Seconds an action may run on the host before ``timeout`` stops waiting for
|
||||
#: it. systemd itself carries on with the job.
|
||||
ACTION_TIMEOUT = 45
|
||||
|
||||
#: What a transport should allow for one command: the action's own bound plus
|
||||
#: the round trip around it.
|
||||
_TRANSPORT_TIMEOUT = ACTION_TIMEOUT + 15
|
||||
|
||||
_TIMED_OUT = 124 # timeout(1)'s exit status when the time ran out
|
||||
_RC_MARKER = "__SVC_RC="
|
||||
_RC_RE = re.compile(rf"^{_RC_MARKER}(\d+)\s*$", re.MULTILINE)
|
||||
|
||||
#: The characters systemd allows in a unit name, with ``\xHH`` for any other byte.
|
||||
_UNIT_RE = re.compile(r"(?:[A-Za-z0-9_.:@-]|\\x[0-9A-Fa-f]{2})+")
|
||||
_MAX_UNIT_LENGTH = 255
|
||||
|
||||
_ENABLED = frozenset({"enabled", "enabled-runtime"})
|
||||
#: Unit file states of a service that is installed but need not be loaded.
|
||||
_INSTALLED = frozenset({"enabled", "enabled-runtime", "disabled", "indirect"})
|
||||
|
||||
|
||||
class SystemdUnavailable(NotImplementedError):
|
||||
"""The host does not run systemd; a driver may fall back to another init system."""
|
||||
|
||||
|
||||
def unit_name(name: str) -> str:
|
||||
"""*name* as a service unit's name without ``.service``, or ``ValueError``.
|
||||
|
||||
Accepts template instances (``wg-quick@wg0``), dots (``snapd.apparmor``),
|
||||
colons and systemd's ``\\xHH`` escapes. Refuses a bare template
|
||||
(``getty@``), a leading ``-`` that a command would read as an option, and
|
||||
anything a shell would read.
|
||||
"""
|
||||
base = name[: -len(_SUFFIX)] if name.endswith(_SUFFIX) else name
|
||||
if (
|
||||
not _UNIT_RE.fullmatch(base)
|
||||
or base.startswith("-")
|
||||
or base.endswith("@")
|
||||
or len(base) + len(_SUFFIX) > _MAX_UNIT_LENGTH
|
||||
):
|
||||
raise ValueError(f"Invalid service name: {name!r}")
|
||||
return base
|
||||
|
||||
|
||||
def service_action_command(name: str, action: str) -> str:
|
||||
"""The shell command that applies *action* to the service *name*.
|
||||
|
||||
:raises ValueError: for an unknown action or an invalid name.
|
||||
"""
|
||||
if action not in SERVICE_ACTIONS:
|
||||
raise ValueError(f"Invalid action {action!r}; use one of {', '.join(SERVICE_ACTIONS)}")
|
||||
unit = quote(unit_name(name) + _SUFFIX)
|
||||
return (
|
||||
f"timeout {ACTION_TIMEOUT} systemctl --no-ask-password {action} -- {unit} 2>&1; "
|
||||
f"echo {_RC_MARKER}$?"
|
||||
)
|
||||
|
||||
|
||||
def parse_action_result(output: str) -> dict[str, Any]:
|
||||
"""``{"success", "output"}`` from what :func:`service_action_command` printed.
|
||||
|
||||
Only the exit status decides. A job still running when ``timeout`` gave up
|
||||
is not reported as done, and output without a status is no success.
|
||||
"""
|
||||
output = strip_terminal_codes(output)
|
||||
statuses = _RC_RE.findall(output)
|
||||
text = _RC_RE.sub("", output).strip()
|
||||
if not statuses:
|
||||
return {"success": False, "output": text or "No exit status came back from the host."}
|
||||
status = int(statuses[-1])
|
||||
if status == 0:
|
||||
return {"success": True, "output": text}
|
||||
if status == _TIMED_OUT:
|
||||
note = f"Still running after {ACTION_TIMEOUT} s; systemd carries on with the job."
|
||||
return {"success": False, "output": f"{text}\n{note}".strip()}
|
||||
return {"success": False, "output": text or f"systemctl exited with status {status}."}
|
||||
|
||||
|
||||
def _frame(output: 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 systemd service report in the output") from None
|
||||
return lines[start + 1 : end]
|
||||
|
||||
|
||||
def _sections(lines: list[str]) -> dict[str, list[str]]:
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] = []
|
||||
for line in lines:
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
else:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _unit_blocks(lines: list[str]) -> list[dict[str, str]]:
|
||||
"""``systemctl show``'s output, one dict per unit.
|
||||
|
||||
Units are separated by a blank line -- except where ``xargs`` split the
|
||||
list over two runs and the blocks meet, so a key seen twice starts the next
|
||||
unit as well.
|
||||
"""
|
||||
blocks: list[dict[str, str]] = []
|
||||
current: dict[str, str] = {}
|
||||
for line in lines:
|
||||
key, sep, value = line.partition("=")
|
||||
if not sep or key in current:
|
||||
if current:
|
||||
blocks.append(current)
|
||||
current = {}
|
||||
if sep:
|
||||
current[key] = value
|
||||
if current:
|
||||
blocks.append(current)
|
||||
return blocks
|
||||
|
||||
|
||||
def _base(unit: str) -> str:
|
||||
return unit[: -len(_SUFFIX)]
|
||||
|
||||
|
||||
def _main_pid(block: dict[str, str]) -> int:
|
||||
try:
|
||||
return int(block.get("MainPID") or 0)
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def _loaded(blocks: list[dict[str, str]]) -> tuple[dict[str, ServiceDict], set[str]]:
|
||||
"""The loaded services, and every name they go by (aliases included)."""
|
||||
services: dict[str, ServiceDict] = {}
|
||||
names: set[str] = set()
|
||||
for block in blocks:
|
||||
unit = block.get("Id", "")
|
||||
if not unit.endswith(_SUFFIX) or block.get("LoadState") == "not-found":
|
||||
continue
|
||||
names.update(block.get("Names", unit).split())
|
||||
running = block.get("ActiveState") == "active" and block.get("SubState") == "running"
|
||||
services[_base(unit)] = {
|
||||
"name": _base(unit),
|
||||
"running": running,
|
||||
"enabled": block.get("UnitFileState") in _ENABLED,
|
||||
"pid": _main_pid(block) if running else 0,
|
||||
}
|
||||
return services, names
|
||||
|
||||
|
||||
def _installed(lines: list[str], known: set[str]) -> dict[str, ServiceDict]:
|
||||
"""Installed services that are not loaded: neither running nor starting now.
|
||||
|
||||
Templates, static units and aliases are left out -- the last also when an
|
||||
older systemd lists an alias as ``enabled``, which is why every name a
|
||||
loaded unit goes by is skipped.
|
||||
"""
|
||||
services: dict[str, ServiceDict] = {}
|
||||
for line in lines:
|
||||
parts = line.split()
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
unit, state = parts[0], parts[1]
|
||||
if (
|
||||
not unit.endswith(_SUFFIX)
|
||||
or unit.endswith("@" + _SUFFIX)
|
||||
or unit in known
|
||||
or state not in _INSTALLED
|
||||
):
|
||||
continue
|
||||
services[_base(unit)] = {
|
||||
"name": _base(unit),
|
||||
"running": False,
|
||||
"enabled": state in _ENABLED,
|
||||
"pid": 0,
|
||||
}
|
||||
return services
|
||||
|
||||
|
||||
def _apply_generated(services: dict[str, ServiceDict], lines: list[str]) -> None:
|
||||
"""Take a generated unit's boot state from ``is-enabled``'s answer."""
|
||||
for line in lines:
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[0].endswith(_SUFFIX) and _base(parts[0]) in services:
|
||||
services[_base(parts[0])]["enabled"] = parts[1] in _ENABLED
|
||||
|
||||
|
||||
def parse_systemd_services(output: str) -> list[ServiceDict]:
|
||||
"""Parse what :data:`SYSTEMD_SERVICES_COMMAND` printed, sorted by name.
|
||||
|
||||
Lists every loaded service unit but those that are not found, and every
|
||||
installed one that is not loaded.
|
||||
|
||||
:raises SystemdUnavailable: when the host does not run systemd.
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
if _NO_SYSTEMD in sections:
|
||||
raise SystemdUnavailable("the host does not run systemd")
|
||||
loaded, known = _loaded(_unit_blocks(sections.get("units", [])))
|
||||
_apply_generated(loaded, sections.get("generated", []))
|
||||
merged = {**_installed(sections.get("files", []), known), **loaded}
|
||||
return [merged[name] for name in sorted(merged)]
|
||||
|
||||
|
||||
class SystemdServicesMixin(ServiceControlMixin):
|
||||
"""Implements :class:`ServiceControlMixin` for a driver whose host runs systemd.
|
||||
|
||||
The template form (README, "Function classes"): the command, the parse,
|
||||
the check of the name and the reading of the exit status are the same
|
||||
everywhere, so they are concrete here, and a driver supplies only
|
||||
:meth:`_run_service_command` -- how a command reaches its host, and how it
|
||||
gains root there when it needs to.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_service_command(self, command: str, *, privileged: bool, timeout: int) -> str:
|
||||
"""Run *command* with ``sh`` on the host and return what it printed.
|
||||
|
||||
*privileged* commands change the system and need root; *timeout*
|
||||
is how long the transport should wait for the output, in seconds.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_services(self) -> list[ServiceDict]:
|
||||
"""
|
||||
Returns the services systemd knows, in one round trip.
|
||||
|
||||
* name (string) - the unit name without ``.service``
|
||||
* running (bool) - active and running
|
||||
* enabled (bool) - the unit file is enabled
|
||||
* pid (int) - the main process; 0 when not running
|
||||
|
||||
:raises SystemdUnavailable: if the host does not run systemd.
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
output = self._run_service_command(
|
||||
SYSTEMD_SERVICES_COMMAND, privileged=False, timeout=_TRANSPORT_TIMEOUT
|
||||
)
|
||||
return parse_systemd_services(output)
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]:
|
||||
"""
|
||||
Applies *action* (start, stop, restart, enable, disable) to the service *name*.
|
||||
|
||||
:returns: ``{"success": bool, "output": str}``
|
||||
:raises ValueError: for an unknown action or an invalid name, before
|
||||
anything is sent.
|
||||
"""
|
||||
command = service_action_command(name, action)
|
||||
output = self._run_service_command(command, privileged=True, timeout=_TRANSPORT_TIMEOUT)
|
||||
return parse_action_result(output)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""What a pseudo-terminal adds to a command's output, taken out again.
|
||||
|
||||
A screen-scraping transport (netmiko) gives the remote command a terminal. Tools
|
||||
then colour their output and draw progress: systemctl colours its errors, apt
|
||||
switches the keypad mode with ``ESC =`` / ``ESC >``. Every parser in this package
|
||||
reads the text without them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
#: CSI sequences (colours, cursor), OSC sequences (window titles) and the
|
||||
#: two-character escapes (``ESC =``, ``ESC >``, ``ESC (B``).
|
||||
_TERMINAL_CODES = re.compile(
|
||||
r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|\([0-9A-Za-z]|[=>78DEHMNOc])"
|
||||
)
|
||||
|
||||
|
||||
def strip_terminal_codes(text: str) -> str:
|
||||
"""*text* without terminal escape sequences."""
|
||||
return _TERMINAL_CODES.sub("", text)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""A device's time sources and time zone: read them, and set them to what the caller says.
|
||||
|
||||
An application keeps one list of NTP servers and a time zone per site, and aligns a
|
||||
device that differs. :class:`TimeSyncMixin` is the contract for that:
|
||||
|
||||
* ``get_time_sync()`` -- declared only, so ``callable(getattr(driver,
|
||||
"get_time_sync", None))`` is the truthful answer to "can this driver tell";
|
||||
* ``configure_time_sync(ntp_servers=None, timezone=None)`` -- a fix template
|
||||
(:mod:`napalm_device_types.fixes`): ``None`` leaves that value as it is, and the
|
||||
device ends up configured with exactly the servers given, in their order. A driver
|
||||
implements the steps; one whose device takes the change in a single call
|
||||
overrides the method;
|
||||
* ``time_sync_writes`` -- which of the two values the driver can write. A BMC that
|
||||
runs on UTC only writes ``{"ntp_servers"}``; the application never asks it for a
|
||||
zone.
|
||||
|
||||
A driver that inherits the mixin but cannot run it sets ``get_time_sync`` (and
|
||||
``configure_time_sync``) to ``None``.
|
||||
|
||||
**Servers from DHCP count** (NetOrk/netork#2380). A device that takes its time
|
||||
servers from a DHCP lease (option 42) gets them from whoever serves the subnet --
|
||||
usually the site's time giver. ``ntp_servers`` are only the servers configured on
|
||||
the device; ``dhcp_ntp_servers`` are those the device got by DHCP and uses. A write
|
||||
replaces the configured servers and leaves DHCP's alone: it never switches the use of
|
||||
DHCP-provided servers off, and the ``verify`` step does not count them.
|
||||
|
||||
A zone is an IANA name on the wire. A device that wants a POSIX rule or an offset
|
||||
with a summer-time rule gets it from :mod:`napalm_device_types.posix_tz`.
|
||||
"""
|
||||
|
||||
# No ``from __future__ import annotations`` here: TypedDict tells a NotRequired key
|
||||
# only from an evaluated annotation (``TimeSyncDict.__optional_keys__``).
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, ClassVar, NotRequired, TypedDict
|
||||
|
||||
from napalm_device_types.fixes import FixStep, run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
|
||||
from napalm_device_types.posix_tz import UnknownTimezone, is_iana_zone
|
||||
|
||||
#: The values a driver can write; ``time_sync_writes`` is a subset.
|
||||
TIME_SYNC_VALUES: frozenset[str] = frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
_HOST_NAME = re.compile(
|
||||
r"(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
|
||||
r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*\.?"
|
||||
)
|
||||
|
||||
|
||||
class TimeSyncDict(TypedDict):
|
||||
"""How a device keeps its clock (``get_time_sync``)."""
|
||||
|
||||
ntp_servers: list[str] # configured time sources, in the device's order; [] = none configured
|
||||
timezone: str | None # IANA name ("Europe/Berlin"); None = not readable or no named zone
|
||||
synchronized: bool | None # the clock is synchronised to a source right now; None = unknown
|
||||
daemon: str | None # "chrony", "systemd-timesyncd", "ntpd", "openntpd", ...; None = own client
|
||||
# The servers the device got by DHCP (option 42) and uses, in its order; never in
|
||||
# ntp_servers. [] = none; absent or None = the driver cannot tell.
|
||||
dhcp_ntp_servers: NotRequired[list[str] | None]
|
||||
|
||||
|
||||
def _is_server(name: str) -> bool:
|
||||
try:
|
||||
ipaddress.ip_address(name)
|
||||
except ValueError:
|
||||
return bool(_HOST_NAME.fullmatch(name))
|
||||
return True
|
||||
|
||||
|
||||
def check_ntp_servers(servers: Sequence[str]) -> list[str]:
|
||||
"""*servers* as a driver writes them: stripped, in their order, each once.
|
||||
|
||||
:raises ValueError: for no server at all, or one that is not a host name or
|
||||
an IP address -- before anything reaches a configuration file.
|
||||
:raises TypeError: for a single string instead of a list of them.
|
||||
"""
|
||||
if isinstance(servers, str):
|
||||
raise TypeError("ntp_servers is a list of servers, not one string")
|
||||
kept: list[str] = []
|
||||
for server in (str(s).strip() for s in servers):
|
||||
if not server:
|
||||
continue
|
||||
if not _is_server(server):
|
||||
raise ValueError(f"{server!r} is not a host name or address of an NTP server")
|
||||
if server.lower() not in (k.lower() for k in kept):
|
||||
kept.append(server)
|
||||
if not kept:
|
||||
raise ValueError("name at least one NTP server; None leaves the servers as they are")
|
||||
return kept
|
||||
|
||||
|
||||
class TimeSyncMixin:
|
||||
"""Read and set a device's time sources and time zone; see the module."""
|
||||
|
||||
#: Which of the two values this driver can write: a subset of {"ntp_servers", "timezone"}.
|
||||
#: A BMC that only runs on UTC writes {"ntp_servers"}; an application never asks it for a
|
||||
#: zone. Declared only: a driver that names nothing writes nothing.
|
||||
time_sync_writes: ClassVar[frozenset[str]]
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""How the device keeps its clock now.
|
||||
|
||||
``ntp_servers`` are the sources its configuration names, in its order
|
||||
(a pool by its name, not the addresses it resolved to);
|
||||
``dhcp_ntp_servers`` those a DHCP lease gave it and it uses, apart from
|
||||
them -- left out where the driver cannot tell. ``timezone``
|
||||
is an IANA name, or None where the device keeps an offset and a rule
|
||||
instead of a name. ``daemon`` names the client that keeps the clock on
|
||||
a host that has a choice; None for a device's own.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"ntp_servers": ["ntp1.example.org", "10.0.0.1"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
"dhcp_ntp_servers": ["192.168.1.1"],
|
||||
}
|
||||
|
||||
:raises Exception: when the device could not be read.
|
||||
"""
|
||||
...
|
||||
|
||||
# The steps a driver implements:
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
"""Leave the device configured with exactly *servers*, in this order:
|
||||
sources it had configured elsewhere stop counting (commented out,
|
||||
replaced). Servers it gets by DHCP stay, and so does its use of them."""
|
||||
...
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
"""Set the device's zone to *zone*, an IANA name of the database."""
|
||||
...
|
||||
|
||||
def configure_time_sync(
|
||||
self, ntp_servers: Sequence[str] | None = None, timezone: str | None = None
|
||||
) -> FixResultDict:
|
||||
"""Give the device exactly *ntp_servers*, in order, and *timezone*; None leaves one alone.
|
||||
|
||||
What the device gets by DHCP is not touched: it keeps using those servers too.
|
||||
|
||||
The steps: ``ntp_servers``, ``timezone``, then ``verify``, which reads the
|
||||
device again.
|
||||
|
||||
:raises UnknownTimezone: for a *timezone* that is not an IANA name of the
|
||||
database, before anything is written.
|
||||
:raises ValueError: for a value this driver does not write
|
||||
(:attr:`time_sync_writes`), for no server or a malformed one, or for
|
||||
nothing asked -- before anything is written.
|
||||
"""
|
||||
servers = None if ntp_servers is None else check_ntp_servers(ntp_servers)
|
||||
if timezone is not None and not is_iana_zone(timezone):
|
||||
raise UnknownTimezone(timezone)
|
||||
asked = {name for name, v in (("ntp_servers", servers), ("timezone", timezone)) if v}
|
||||
if not asked:
|
||||
raise ValueError("nothing to configure: name ntp_servers, timezone or both")
|
||||
refused = asked - getattr(self, "time_sync_writes", frozenset())
|
||||
if refused:
|
||||
raise ValueError(f"this driver does not write {', '.join(sorted(refused))}")
|
||||
steps: list[FixStep] = []
|
||||
if servers is not None:
|
||||
steps.append(("ntp_servers", lambda: self._write_ntp_servers(servers)))
|
||||
if timezone is not None:
|
||||
steps.append(("timezone", lambda: self._write_time_zone(timezone)))
|
||||
steps.append(("verify", lambda: self._verify_time_sync(servers, timezone)))
|
||||
return run_fix_steps(steps)
|
||||
|
||||
def _verify_time_sync(self, servers: list[str] | None, zone: str | None) -> FixStepOutcomeDict:
|
||||
"""Read the device again: does it now have what was written?
|
||||
|
||||
Servers compare without case; the servers DHCP brought are not among
|
||||
them. A zone is compared where the device reads one back by name.
|
||||
"""
|
||||
now = self.get_time_sync()
|
||||
wrong: list[str] = []
|
||||
if servers is not None and [s.lower() for s in now["ntp_servers"]] != [
|
||||
s.lower() for s in servers
|
||||
]:
|
||||
wrong.append(f"the device has the servers {', '.join(now['ntp_servers']) or 'none'}")
|
||||
if zone is not None and now["timezone"] is not None and now["timezone"] != zone:
|
||||
wrong.append(f"the device is in the time zone {now['timezone']}")
|
||||
if wrong:
|
||||
return {"ok": False, "output": "; ".join(wrong)}
|
||||
return {"ok": True, "output": "the device reads back what was written"}
|
||||
|
||||
|
||||
__all__ = ["TIME_SYNC_VALUES", "TimeSyncDict", "TimeSyncMixin", "check_ntp_servers"]
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Time sync on a POSIX host, over the command channel: chrony, systemd-timesyncd, timedatectl.
|
||||
|
||||
:class:`PosixTimeSyncMixin` implements
|
||||
:class:`~napalm_device_types.time_sync.TimeSyncMixin` for a driver that has
|
||||
:meth:`~napalm_device_types.channel.CommandChannelMixin.run_command`. The defaults
|
||||
are Debian's paths; a driver sets its host's.
|
||||
|
||||
**Reading** is one round trip as the login user
|
||||
(:mod:`napalm_device_types._time_sync_reading`): ``timedatectl show`` for the zone
|
||||
(``/etc/timezone`` or ``/etc/localtime``'s target without it), which time sync
|
||||
service is active, and that client's configuration -- chrony's files as chronyd
|
||||
reads them, ``timedatectl show-timesync`` for systemd-timesyncd, ``ntp.conf``,
|
||||
OpenNTPD's ``ntpd.conf``. Synchronised is chronyd's own word where it runs (a
|
||||
selected source in ``chronyc -n sources``), else the kernel's (``NTPSynchronized``).
|
||||
|
||||
What DHCP brought (option 42) is read apart, as ``dhcp_ntp_servers``, and never as a
|
||||
configured server: chrony's sources from the DHCP client's ``sourcedir``
|
||||
(:attr:`~PosixTimeSyncMixin.CHRONY_DHCP_DIRS`, the files as chronyd reads them),
|
||||
systemd-timesyncd's ``LinkNTPServers``. Where ntpd or OpenNTPD runs it is unknown.
|
||||
|
||||
**Writing** runs as root through ``run_command(privileged=True)``; root never reads
|
||||
stdin -- a file is staged by the login user and installed by root.
|
||||
|
||||
* The zone: ``timedatectl set-timezone``.
|
||||
* chrony: the servers go to a file of their own and every other configured source is
|
||||
commented out (:mod:`napalm_device_types._chrony`); the DHCP client's ``sourcedir``
|
||||
stays, and one 4.35.0 commented out comes back. Then ``chronyc reload sources``, or
|
||||
a restart of chronyd where its main configuration changed or it cannot reload.
|
||||
* systemd-timesyncd: :attr:`~PosixTimeSyncMixin.TIMESYNCD_DROPIN` resets ``NTP=``,
|
||||
sets the servers and empties ``FallbackNTP=``, then the service restarts. Servers a
|
||||
network link brings (DHCP through systemd-networkd) stay and count.
|
||||
* ntpd, OpenNTPD, or no client: the servers are read, not written -- the step fails
|
||||
and says so.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from napalm_device_types._chrony import (
|
||||
COMMENT_MARK,
|
||||
comment_out_command,
|
||||
include_command,
|
||||
plan_chrony,
|
||||
restore_command,
|
||||
)
|
||||
from napalm_device_types._scheduled_reading import TIME_ZONE_SH
|
||||
from napalm_device_types._time_sync_reading import (
|
||||
CHRONY_DHCP_DIRS,
|
||||
TIME_SYNC_UNITS,
|
||||
Reading,
|
||||
ReadPaths,
|
||||
chrony_synchronized,
|
||||
parse_key_values,
|
||||
parse_reading,
|
||||
parse_time_sync,
|
||||
reading_command,
|
||||
time_sync_of,
|
||||
timesyncd_link_servers,
|
||||
timesyncd_servers,
|
||||
)
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
_STAGE = 't=$(mktemp) && chmod 644 "$t" && cat > "$t" && printf %s "$t"'
|
||||
_WRITERS = "chrony and systemd-timesyncd"
|
||||
|
||||
#: The head of the systemd-timesyncd drop-in.
|
||||
TIMESYNCD_HEADER = (
|
||||
"# The time sources, exactly these: written by napalm-device-types'\n"
|
||||
"# PosixTimeSyncMixin and replaced on every change.\n"
|
||||
)
|
||||
|
||||
|
||||
def _said(result: CommandResult) -> str:
|
||||
return "\n".join(p for p in (result.stdout.strip(), result.stderr.strip()) if p)
|
||||
|
||||
|
||||
def timesyncd_dropin(servers: Sequence[str]) -> str:
|
||||
"""The drop-in that leaves systemd-timesyncd with exactly *servers*."""
|
||||
return f"{TIMESYNCD_HEADER}[Time]\nNTP=\nNTP={' '.join(servers)}\nFallbackNTP=\n"
|
||||
|
||||
|
||||
class PosixTimeSyncMixin(TimeSyncMixin):
|
||||
"""Time sync of a host reached through ``run_command``; the paths are the driver's."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
|
||||
|
||||
#: ``(unit, daemon)``: the services that keep the clock; the first active one counts.
|
||||
TIME_SYNC_UNITS: ClassVar[tuple[tuple[str, str], ...]] = TIME_SYNC_UNITS
|
||||
#: chrony's main configuration: the first that exists.
|
||||
CHRONY_CONFIGS: ClassVar[tuple[str, ...]] = ("/etc/chrony/chrony.conf", "/etc/chrony.conf")
|
||||
#: The servers' file where the main configuration has a ``sourcedir`` of its directory.
|
||||
CHRONY_SOURCES_FILE: ClassVar[str] = "/etc/chrony/sources.d/netork.sources"
|
||||
#: The servers' file otherwise (its name also in a ``confdir``); included if need be.
|
||||
CHRONY_INCLUDE_FILE: ClassVar[str] = "/etc/chrony.d/netork.conf"
|
||||
#: The ``sourcedir`` a DHCP client writes chrony's sources to: read as
|
||||
#: ``dhcp_ntp_servers``, never commented out.
|
||||
CHRONY_DHCP_DIRS: ClassVar[tuple[str, ...]] = CHRONY_DHCP_DIRS
|
||||
TIMESYNCD_DROPIN: ClassVar[str] = "/etc/systemd/timesyncd.conf.d/netork.conf"
|
||||
NTPD_CONFIGS: ClassVar[tuple[str, ...]] = ("/etc/ntpsec/ntp.conf", "/etc/ntp.conf")
|
||||
OPENNTPD_CONFIGS: ClassVar[tuple[str, ...]] = ("/etc/openntpd/ntpd.conf", "/etc/ntpd.conf")
|
||||
#: ``sh`` that prints the zone without timedatectl: a name, or a path ending in it.
|
||||
TIME_ZONE_SH: ClassVar[str] = TIME_ZONE_SH
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
def _ts_read(self) -> Reading:
|
||||
paths = ReadPaths(
|
||||
units=self.TIME_SYNC_UNITS,
|
||||
chrony_configs=self.CHRONY_CONFIGS,
|
||||
ntpd_configs=self.NTPD_CONFIGS,
|
||||
openntpd_configs=self.OPENNTPD_CONFIGS,
|
||||
time_zone_sh=self.TIME_ZONE_SH,
|
||||
)
|
||||
return parse_reading(self.run_command(reading_command(paths), timeout=60).stdout)
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""The host's time sources, zone and client, in one round trip as the login user.
|
||||
|
||||
:raises ValueError: when the reading came back cut short.
|
||||
"""
|
||||
return time_sync_of(self._ts_read(), self.CHRONY_DHCP_DIRS)
|
||||
|
||||
# -- writing ---------------------------------------------------------------------------------
|
||||
|
||||
def _ts_root(self, command: str) -> CommandResult:
|
||||
return self.run_command(command, privileged=True, timeout=60)
|
||||
|
||||
def _ts_checked(self, command: str) -> str:
|
||||
result = self._ts_root(command)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"{command}: {_said(result) or f'exit {result.exit_code}'}")
|
||||
return _said(result)
|
||||
|
||||
def _ts_install(self, path: str, content: str) -> None:
|
||||
"""*content* to *path* as root, staged by the login user: root reads no stdin."""
|
||||
staged = self.run_command(_STAGE, timeout=30, stdin=content.encode())
|
||||
tmp = (staged.stdout.strip().splitlines() or [""])[-1]
|
||||
if staged.exit_code != 0 or not tmp.startswith("/"):
|
||||
raise RuntimeError(f"cannot stage {path}: {_said(staged)}")
|
||||
try:
|
||||
self._ts_checked(shlex.join(["install", "-D", "-m", "644", "--", tmp, path]))
|
||||
finally:
|
||||
self.run_command(shlex.join(["rm", "-f", "--", tmp]), timeout=30)
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
result = self._ts_root(shlex.join(["timedatectl", "set-timezone", zone]))
|
||||
if result.exit_code != 0:
|
||||
return {"ok": False, "output": _said(result) or f"exit {result.exit_code}"}
|
||||
return {"ok": True, "output": f"time zone set to {zone}"}
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
reading = self._ts_read()
|
||||
if reading.daemon == "chrony":
|
||||
return self._ts_chrony(reading, servers)
|
||||
if reading.daemon == "systemd-timesyncd":
|
||||
return self._ts_timesyncd(servers)
|
||||
runs = f"this host runs {reading.daemon}" if reading.daemon else "none runs here"
|
||||
return {"ok": False, "output": f"time sources are written for {_WRITERS}; {runs}"}
|
||||
|
||||
def _ts_timesyncd(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
self._ts_install(self.TIMESYNCD_DROPIN, timesyncd_dropin(servers))
|
||||
self._ts_checked("systemctl restart systemd-timesyncd.service")
|
||||
return {"ok": True, "output": f"wrote {self.TIMESYNCD_DROPIN}; restarted systemd-timesyncd"}
|
||||
|
||||
def _ts_chrony(self, reading: Reading, servers: list[str]) -> FixStepOutcomeDict:
|
||||
plan = plan_chrony(
|
||||
reading.chrony,
|
||||
servers,
|
||||
sources_file=self.CHRONY_SOURCES_FILE,
|
||||
include_file=self.CHRONY_INCLUDE_FILE,
|
||||
dhcp_dirs=self.CHRONY_DHCP_DIRS,
|
||||
)
|
||||
said = [f"wrote {plan.target}"]
|
||||
self._ts_install(plan.target, plan.content)
|
||||
for path, numbers in plan.restore.items():
|
||||
self._ts_checked(restore_command(path, numbers))
|
||||
said.append(f"gave DHCP's sourcedir back in {path}:{','.join(map(str, numbers))}")
|
||||
for path, numbers in plan.comment_out.items():
|
||||
self._ts_checked(comment_out_command(path, numbers))
|
||||
said.append(f"commented out {path}:{','.join(map(str, numbers))}")
|
||||
if plan.include_in is not None:
|
||||
self._ts_checked(include_command(plan.include_in, plan.target))
|
||||
said.append(f"included it from {plan.include_in}")
|
||||
if not (plan.reload and self._ts_root("chronyc reload sources").exit_code == 0):
|
||||
self._ts_checked(shlex.join(["systemctl", "restart", f"{reading.unit}.service"]))
|
||||
said.append(f"restarted {reading.unit}")
|
||||
else:
|
||||
said.append("reloaded the sources")
|
||||
return {"ok": True, "output": "; ".join(said)}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"COMMENT_MARK",
|
||||
"PosixTimeSyncMixin",
|
||||
"chrony_synchronized",
|
||||
"parse_key_values",
|
||||
"parse_time_sync",
|
||||
"timesyncd_dropin",
|
||||
"timesyncd_link_servers",
|
||||
"timesyncd_servers",
|
||||
]
|
||||
@@ -0,0 +1,285 @@
|
||||
"""TLS certificates: trust on first use by fingerprint, a changed one refused before any login.
|
||||
|
||||
Network devices ship self-signed certificates no CA vouches for. A driver that
|
||||
then turns verification off logs in with the device's credentials at whatever
|
||||
answers on its address (NetOrk/netork#1167, NAPALM/napalm-hpe-aruba-procurve#17).
|
||||
The same answer as for SSH host keys (:mod:`napalm_device_types.ssh_host_keys`):
|
||||
the layer above keeps the store of the certificates it trusts, a driver verifies.
|
||||
|
||||
* It receives the fingerprints to expect in ``optional_args["tls_fingerprints"]``
|
||||
(:data:`KNOWN_FINGERPRINTS_ARG`), by the port they were seen on:
|
||||
``{"443": "SHA256:AB:CD:…"}``, the SHA-256 of the DER certificate as
|
||||
``openssl x509 -fingerprint -sha256`` prints it (the ``SHA256:`` prefix,
|
||||
colons and case are optional, :func:`normalise_fingerprint`). With a
|
||||
fingerprint, any other certificate is refused before a password leaves the
|
||||
caller; no CA is consulted. Without one, the first certificate is accepted:
|
||||
trust on first use.
|
||||
* It reports every certificate it sees through
|
||||
``optional_args["tls_certificate_observer"]`` (:data:`OBSERVER_ARG`), a
|
||||
callable that receives one dict per connection::
|
||||
|
||||
{"host": str, "port": int,
|
||||
"seen": {"fingerprint"},
|
||||
"expected": {"fingerprint"} | None,
|
||||
"accepted": bool}
|
||||
|
||||
``accepted`` is False only for a refused certificate; the connection then
|
||||
raises :class:`TlsCertificateMismatch`. A failing observer is logged and
|
||||
ignored.
|
||||
|
||||
A caller that passes neither keeps working as before (first use, every time),
|
||||
and a driver that ignores both still connects for a caller that passes them.
|
||||
|
||||
:class:`CertificateCheck` is the one implementation. :meth:`~CertificateCheck.verify_server`
|
||||
takes the certificate from a handshake of its own, before any request;
|
||||
:meth:`~CertificateCheck.pin` makes every later connection of a ``requests``
|
||||
session present that same certificate (urllib3's ``assert_fingerprint``), so
|
||||
another host cannot step in between the check and the login;
|
||||
:meth:`~CertificateCheck.refusing` turns such a refusal into
|
||||
:class:`TlsCertificateMismatch`; :meth:`~CertificateCheck.observe` reports the
|
||||
certificate once the login stands.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The ``optional_args`` key that carries the fingerprints to expect, by port.
|
||||
KNOWN_FINGERPRINTS_ARG = "tls_fingerprints"
|
||||
#: The ``optional_args`` key that carries the callable every seen certificate goes to.
|
||||
OBSERVER_ARG = "tls_certificate_observer"
|
||||
|
||||
_PREFIX = "SHA256:"
|
||||
_SHA256_HEX = re.compile(r"^[0-9A-F]{64}$")
|
||||
#: What urllib3 says when a connection presents another certificate than the pinned one
|
||||
#: (``got "…"``; 1.26 writes the digest as ``b'…'``, escaped once requests wraps it).
|
||||
_URLLIB3_MISMATCH = re.compile(r"Fingerprints did not match.*?got \"(?:b\\?')?([0-9a-fA-F]{64})")
|
||||
|
||||
|
||||
def fingerprint(der: bytes) -> str:
|
||||
"""``SHA256:AB:CD:…``: the SHA-256 of a DER certificate, as openssl prints it."""
|
||||
return _format(hashlib.sha256(der).hexdigest())
|
||||
|
||||
|
||||
def _format(hex_digest: str) -> str:
|
||||
upper = hex_digest.upper()
|
||||
return _PREFIX + ":".join(upper[i : i + 2] for i in range(0, len(upper), 2))
|
||||
|
||||
|
||||
def normalise_fingerprint(value: Any) -> str:
|
||||
"""*value* as :func:`fingerprint` writes it; ``SHA256:``, colons, spaces and case optional."""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"not a SHA-256 certificate fingerprint: {value!r}")
|
||||
text = value.strip()
|
||||
if text[: len(_PREFIX)].upper() == _PREFIX:
|
||||
text = text[len(_PREFIX) :]
|
||||
digits = re.sub(r"[\s:]", "", text).upper()
|
||||
if not _SHA256_HEX.match(digits):
|
||||
raise ValueError(f"not a SHA-256 certificate fingerprint: {value!r}")
|
||||
return _format(digits)
|
||||
|
||||
|
||||
def _hex(fingerprint_: str) -> str:
|
||||
"""The bare lower-case hex urllib3's ``assert_fingerprint`` takes."""
|
||||
return fingerprint_.removeprefix(_PREFIX).replace(":", "").lower()
|
||||
|
||||
|
||||
def fetch_certificate(
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: float,
|
||||
*,
|
||||
connect: Callable[..., socket.socket] = socket.create_connection,
|
||||
) -> bytes:
|
||||
"""The DER certificate *host* presents on *port*, from a handshake that sends nothing else.
|
||||
|
||||
No CA and no host name are checked: the certificate is judged by its fingerprint.
|
||||
"""
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
with connect((host, port), timeout=timeout) as sock:
|
||||
with context.wrap_socket(sock, server_hostname=host) as tls:
|
||||
der = tls.getpeercert(binary_form=True)
|
||||
if not der: # pragma: no cover - a TLS server always presents one
|
||||
raise ConnectionException(f"{host}:{port} presented no TLS certificate")
|
||||
return der
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CertificateObservation:
|
||||
"""The certificate one connection saw, against the one it was to expect."""
|
||||
|
||||
host: str
|
||||
port: int
|
||||
#: The fingerprint of the certificate presented.
|
||||
seen: str
|
||||
#: The fingerprint it was to present; None on first use.
|
||||
expected: str | None
|
||||
|
||||
@property
|
||||
def accepted(self) -> bool:
|
||||
"""True on first use and for the expected certificate; False for a refused one."""
|
||||
return self.expected is None or self.expected == self.seen
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"seen": {"fingerprint": self.seen},
|
||||
"expected": {"fingerprint": self.expected} if self.expected else None,
|
||||
"accepted": self.accepted,
|
||||
}
|
||||
|
||||
|
||||
class TlsCertificateMismatch(ConnectionException): # type: ignore[misc]
|
||||
"""The device presented another TLS certificate than the one it is known by.
|
||||
|
||||
Raised before any request that carries credentials: nothing was sent to it.
|
||||
"""
|
||||
|
||||
def __init__(self, observation: CertificateObservation) -> None:
|
||||
self.observation = observation
|
||||
super().__init__(
|
||||
f"TLS certificate mismatch at {observation.host}:{observation.port}: it presented "
|
||||
f"{observation.seen}, the trusted certificate is {observation.expected or 'none'}. "
|
||||
"Nothing was sent to it."
|
||||
)
|
||||
|
||||
|
||||
def _expected(known: Any, port: int) -> str | None:
|
||||
"""The fingerprint in *known* (``{port: fingerprint}``, port as text or number) for *port*."""
|
||||
if not known:
|
||||
return None
|
||||
if not isinstance(known, Mapping):
|
||||
raise ValueError(f"TLS fingerprints must be given by port, not as {type(known).__name__}")
|
||||
value = known.get(str(port)) or known.get(port)
|
||||
return normalise_fingerprint(value) if value else None
|
||||
|
||||
|
||||
def _refused_fingerprint(exc: BaseException) -> str | None:
|
||||
"""The fingerprint urllib3 saw when it refused a pinned connection, in *exc*'s chain."""
|
||||
seen: set[int] = set()
|
||||
stack: list[BaseException | None] = [exc]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
if current is None or id(current) in seen:
|
||||
continue
|
||||
seen.add(id(current))
|
||||
match = _URLLIB3_MISMATCH.search(str(current))
|
||||
if match:
|
||||
return _format(match.group(1))
|
||||
stack.extend([current.__cause__, current.__context__])
|
||||
return None
|
||||
|
||||
|
||||
class CertificateCheck:
|
||||
"""How one driver connection verifies its host's TLS certificate.
|
||||
|
||||
*optional_args* are the driver's (both keys optional), *host* and *port* the
|
||||
address the connection goes to.
|
||||
"""
|
||||
|
||||
def __init__(self, optional_args: Mapping[str, Any] | None, host: str, port: int) -> None:
|
||||
args = optional_args or {}
|
||||
self.host = host
|
||||
self.port = int(port)
|
||||
self.expected = _expected(args.get(KNOWN_FINGERPRINTS_ARG), self.port)
|
||||
self._observer = args.get(OBSERVER_ARG)
|
||||
self._verified: CertificateObservation | None = None
|
||||
|
||||
def verify_server(
|
||||
self,
|
||||
timeout: float,
|
||||
*,
|
||||
connect: Callable[..., socket.socket] = socket.create_connection,
|
||||
) -> CertificateObservation:
|
||||
"""Take the certificate from a handshake of its own and :meth:`verify` it."""
|
||||
return self.verify(fetch_certificate(self.host, self.port, timeout, connect=connect))
|
||||
|
||||
def verify(self, der: bytes) -> CertificateObservation:
|
||||
"""Judge the DER certificate *der*: a refused one is reported and raises.
|
||||
|
||||
An accepted one is reported by :meth:`observe`, once the login stands.
|
||||
"""
|
||||
observation = CertificateObservation(self.host, self.port, fingerprint(der), self.expected)
|
||||
if not observation.accepted:
|
||||
self._report(observation)
|
||||
raise TlsCertificateMismatch(observation)
|
||||
self._verified = observation
|
||||
return observation
|
||||
|
||||
def pin(self, session: Any) -> None:
|
||||
"""Every HTTPS connection of the ``requests`` *session* must present the verified one."""
|
||||
verified = self._require_verified()
|
||||
session.mount("https://", _pinned_adapter(_hex(verified.seen)))
|
||||
|
||||
@contextmanager
|
||||
def refusing(self) -> Iterator[None]:
|
||||
"""Around requests on a pinned session: a refused certificate becomes a mismatch."""
|
||||
try:
|
||||
yield
|
||||
except Exception as exc:
|
||||
offered = _refused_fingerprint(exc)
|
||||
if offered is None:
|
||||
raise
|
||||
trusted = self.expected or self._require_verified().seen
|
||||
observation = CertificateObservation(self.host, self.port, offered, trusted)
|
||||
self._report(observation)
|
||||
raise TlsCertificateMismatch(observation) from exc
|
||||
|
||||
def observe(self) -> CertificateObservation:
|
||||
"""After the login: the verified certificate, reported."""
|
||||
verified = self._require_verified()
|
||||
self._report(verified)
|
||||
return verified
|
||||
|
||||
def _require_verified(self) -> CertificateObservation:
|
||||
if self._verified is None:
|
||||
raise RuntimeError("verify the certificate first (verify_server or verify)")
|
||||
return self._verified
|
||||
|
||||
def _report(self, observation: CertificateObservation) -> None:
|
||||
if not callable(self._observer):
|
||||
return
|
||||
try:
|
||||
self._observer(observation.as_dict())
|
||||
except Exception: # the store is the caller's; a connection does not hang on it
|
||||
logger.warning(
|
||||
"Could not report the TLS certificate of %s:%s",
|
||||
self.host,
|
||||
self.port,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
def _pinned_adapter(hex_digest: str) -> Any:
|
||||
"""A ``requests`` adapter whose connections, direct or through a proxy, must match *hex_digest*.
|
||||
|
||||
``requests`` is imported here: it comes with napalm, and a module that only
|
||||
verifies a fingerprint does not need it loaded.
|
||||
"""
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
class _PinnedAdapter(HTTPAdapter): # type: ignore[misc,unused-ignore]
|
||||
def init_poolmanager(self, *args: Any, **kwargs: Any) -> None:
|
||||
kwargs["assert_fingerprint"] = hex_digest
|
||||
super().init_poolmanager(*args, **kwargs)
|
||||
|
||||
def proxy_manager_for(self, proxy: str, **kwargs: Any) -> Any:
|
||||
kwargs["assert_fingerprint"] = hex_digest
|
||||
return super().proxy_manager_for(proxy, **kwargs)
|
||||
|
||||
return _PinnedAdapter()
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Pending package updates and applying them.
|
||||
|
||||
The two device types that offer this used to declare it under two different
|
||||
names -- ``get_available_updates`` and ``get_pending_updates`` -- with
|
||||
``napalm-linux`` carrying an alias between them so netOrk could call either.
|
||||
One name now, the one netOrk and four drivers already used.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: these are contracts, not placeholders.
|
||||
Nothing exists at runtime until a concrete driver implements it, so mixing
|
||||
this class in can never shadow a working implementation from a sibling base.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
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):
|
||||
"""The host holds no package index to read pending updates from.
|
||||
|
||||
Not a fault: OpenWrt keeps its index in RAM and loses it on every reboot.
|
||||
:meth:`UpdateMixin.refresh_available_updates` loads it again, so a caller
|
||||
that sees this can refresh instead of reporting a failed read.
|
||||
"""
|
||||
|
||||
|
||||
class UpdateMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_available_updates(self) -> list[UpdateDict]:
|
||||
"""
|
||||
Returns a list of packages that have a newer version available.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - package name
|
||||
* current_version (string) - currently installed version
|
||||
* new_version (string) - version available in the repository
|
||||
* origin (string, optional) - where it comes from, e.g. apt's suites
|
||||
* security (bool or None, optional) - a security update; leave it
|
||||
out or None when the source does not say
|
||||
|
||||
**An empty list means nothing is pending.** A reader that cannot
|
||||
read -- no package index yet, an API that did not answer -- raises
|
||||
instead: netOrk keeps "pending since" per package, and an empty
|
||||
list for "don't know" would reset every one of those clocks.
|
||||
Without a package index it raises :exc:`PackageIndexMissing`, which
|
||||
:meth:`refresh_available_updates` cures.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"current_version": "1:9.2p1-2+deb12u1",
|
||||
"new_version": "1:9.2p1-2+deb12u2",
|
||||
},
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def get_installed_advisory_cves(self) -> dict[str, list[str]]:
|
||||
"""
|
||||
The CVEs the host's installed security advisories close, per package
|
||||
name: the distribution's own word that a fix is in the installed build,
|
||||
although its upstream version did not move (a backport).
|
||||
|
||||
netOrk asks for it only where its knowledge base holds no records of
|
||||
the host's release (netOrk #2394), since the answer can be long. A
|
||||
package manager whose advisories name no CVEs has nothing to say here.
|
||||
|
||||
**An empty dict means no installed advisory names a CVE.** A reader
|
||||
that cannot read raises, as :meth:`get_available_updates` does.
|
||||
``NotImplementedError`` where the host's package manager keeps no such
|
||||
advisories (:data:`~napalm_device_types.package_updates.DNF_INSTALLED_CVES_COMMAND`
|
||||
is dnf 4's).
|
||||
|
||||
Example::
|
||||
|
||||
{"glibc-common": ["CVE-2023-4911"], "curl": ["CVE-2023-38545"]}
|
||||
"""
|
||||
...
|
||||
|
||||
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`
|
||||
reports what the repositories offer now (``apt-get update``,
|
||||
``dnf makecache``, ``opkg update``, a firmware check). Installs nothing.
|
||||
|
||||
:returns: ``{"success": bool, "output": str}``
|
||||
"""
|
||||
...
|
||||
|
||||
def get_update_progress(self) -> UpdateProgressDict:
|
||||
"""
|
||||
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, 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
|
||||
update is over has nothing to report here.
|
||||
"""
|
||||
...
|
||||
|
||||
def apply_updates(self, packages: list[str]) -> ApplyUpdatesResultDict:
|
||||
"""
|
||||
Upgrades the given packages to the newest available version.
|
||||
|
||||
Only packages that are already installed may be upgraded; this method
|
||||
does **not** install new packages. Pass an empty list to upgrade
|
||||
**all** packages that have pending updates.
|
||||
|
||||
:param packages: List of package names to upgrade. Each name must
|
||||
match ``^[a-zA-Z0-9_\\-\\+\\.]+$``; a :exc:`ValueError` is raised
|
||||
for any name that does not conform.
|
||||
:returns: A dict with:
|
||||
|
||||
* success (bool) – ``True`` if the package manager exited without error
|
||||
* output (string) – combined stdout / stderr from the package manager
|
||||
* error (string, optional) – short error message when *success* is ``False``
|
||||
|
||||
:raises ValueError: If any package name fails the safety check.
|
||||
|
||||
Example::
|
||||
|
||||
result = driver.apply_updates(["openssh-server", "curl"])
|
||||
# → {"success": True, "output": "Reading package lists...\\n..."}
|
||||
|
||||
# Upgrade everything:
|
||||
result = driver.apply_updates([])
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,413 @@
|
||||
"""Virtual IPs: the addresses a host's HA configuration lets float between machines.
|
||||
|
||||
vip-manager and keepalived put a service address on whichever member is master
|
||||
*right now*. The address list of a standby shows no trace of it; what every
|
||||
member has is the configuration that declares it. That 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.
|
||||
|
||||
**Declared, not held.** The reading says which addresses the configuration
|
||||
lets onto this host. Whether the host holds one at the moment is in its
|
||||
interface addresses, which the caller already has.
|
||||
|
||||
**Filtered on the host.** The same files hold secrets -- vip-manager's etcd
|
||||
password, keepalived's ``auth_pass``, notify scripts with their arguments. The
|
||||
command therefore never prints a configuration: an awk program reads the unit's
|
||||
properties and files and prints allowlisted fields only. A secret cannot reach
|
||||
the caller's memory, its log or an exception text, because it never leaves the
|
||||
host.
|
||||
|
||||
**What is read.**
|
||||
|
||||
- *vip-manager*: every ``vip-manager.service`` and ``vip-manager@*.service`` unit
|
||||
systemd knows. The address comes from the first of: a command-line flag
|
||||
(``--ip``; 1.x's ``-ip=${VIP_IP}`` resolved through the unit's environment), the
|
||||
environment (``VIP_IP``, an ``EnvironmentFile`` over ``Environment``), the
|
||||
``--config`` YAML (5.x's ``ip``). Mask, interface and trigger key alike.
|
||||
- *keepalived*: ``keepalived.service``, its ``-f``/``--use-file`` or
|
||||
``/etc/keepalived/keepalived.conf``. The ``virtual_ipaddress`` and
|
||||
``virtual_ipaddress_excluded`` entries of every ``vrrp_instance``, with the
|
||||
instance's ``interface`` and ``virtual_router_id``. ``include`` is followed
|
||||
four levels deep, a relative pattern from the including file's directory. A
|
||||
pattern that is not a plain path glob is not followed: it would otherwise be
|
||||
handed to a root shell.
|
||||
|
||||
**None is "did not look".** A file that exists but cannot be read, an include
|
||||
that cannot be followed, a host without systemd (no ``systemctl``, or systemd not
|
||||
running as PID 1, as in a container): that mechanism is None, and the
|
||||
caller keeps what it knew. ``[]`` is a host that has none.
|
||||
|
||||
**Root, and without it.** The configuration may be root's alone. The whole
|
||||
script goes to the host as one ``sh -c`` argument; when the privileged call
|
||||
brings no report back, it runs again without privilege and reads what it can.
|
||||
|
||||
**An exec channel, not a terminal.** With its awk program the command is about
|
||||
4 kB, past the line an interactive shell reliably takes. A driver sends it the
|
||||
way it runs any command that needs no PTY -- napalm-linux's ``run_command``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import VirtualIpDict, VirtualIpsDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "VIPS_BEGIN"
|
||||
_END = "VIPS_END"
|
||||
_NO_SYSTEMD = "no-systemd"
|
||||
#: Exists only while systemd runs as PID 1; a container may carry systemctl without.
|
||||
_SYSTEMD_RUN = "/run/systemd/system"
|
||||
#: A record that says a mechanism was not fully read.
|
||||
_BLIND = frozenset({"unreadable", "too-deep"})
|
||||
_KEEPALIVED_CONF = "/etc/keepalived/keepalived.conf"
|
||||
_ENV_KEYS = "VIP_(IP|MASK|NETMASK|IFACE|INTERFACE|KEY|TRIGGER_KEY)"
|
||||
_CFG_KEYS = "(ip|netmask|mask|interface|iface|trigger-key|key)"
|
||||
|
||||
#: One line of awk, fed a unit's ``systemctl show`` output with ``-v m=<mechanism>``.
|
||||
#: It prints records, never a line of configuration: ``active <state>``,
|
||||
#: ``arg <flag> <value>``, ``env <VIP_*> <value>``, ``cfg <key> <value>``,
|
||||
#: ``instance <name>`` / ``interface`` / ``virtual_router_id`` / ``vip <addr> [dev <if>]``
|
||||
#: / ``end``, and ``unreadable``/``too-deep``/``missing <path>``. No ``>`` but in
|
||||
#: ``2>/dev/null``: comparisons are written the other way round. ``\047`` is a
|
||||
#: single quote, so the program itself needs none. A statement ends with its line
|
||||
#: unless the next one opens with ``{``: keepalived takes ``vrrp_instance VI_2``
|
||||
#: and its brace on two lines.
|
||||
_AWK = " ".join(
|
||||
(
|
||||
r'function q(p) { return "\047" p "\047" }',
|
||||
r'function ok(f) { if (f == "" || f ~ /\047/) { print "unreadable " f; return 0 }'
|
||||
r' if (system("test -r " q(f)) == 0) return 1;'
|
||||
r' if (system("test -e " q(f)) == 0) print "unreadable " f; else print "missing " f;'
|
||||
r" return 0 }",
|
||||
r"function rf(f, c, l, r, k) { if (!ok(f)) return;"
|
||||
r" while (0 < (r = (getline l < f))) {"
|
||||
rf' if (c == "cfg" && l ~ /^[ \t]*{_CFG_KEYS}[ \t]*:/) {{ sub(/^[ \t]*/, "", l); k = l;'
|
||||
r' sub(/[ \t]*:.*/, "", k); sub(/^[^:]*:[ \t]*/, "", l); print "cfg " k " " l }'
|
||||
rf' else if (c == "env" && l ~ /^[ \t]*(export[ \t]+)?{_ENV_KEYS}[ \t]*=/) {{'
|
||||
r' sub(/^[ \t]*(export[ \t]+)?/, "", l); k = l; sub(/[ \t]*=.*/, "", k);'
|
||||
r' sub(/^[^=]*=[ \t]*/, "", l); print "env " k " " l } }'
|
||||
r' if (r < 0) print "unreadable " f; close(f) }',
|
||||
r'function push(n, a) { st[++sd] = n; if (n == "vrrp_instance") print "instance " a }',
|
||||
r'function pop() { if (0 < sd) { if (st[sd] == "vrrp_instance") print "end"; sd-- } }',
|
||||
r"function stmt(w, nw, f, d, x, i) { if (!nw) return;"
|
||||
r' if (w[1] == "include") { if (1 < nw) inc(w[2], f, d); return }'
|
||||
r' if (sd == 1 && st[1] == "vrrp_instance") {'
|
||||
r' if (1 < nw && (w[1] == "interface" || w[1] == "virtual_router_id")) print w[1] " " w[2];'
|
||||
r" return }"
|
||||
r' if (sd == 2 && st[1] == "vrrp_instance" && st[2] ~ /^virtual_ipaddress(_excluded)?$/) {'
|
||||
r' x = "vip " w[1]; for (i = 2; i < nw; i++) if (w[i] == "dev") x = x " dev " w[i + 1];'
|
||||
r" print x } }",
|
||||
r"function rk(f, d, l, r, n, t, k, w, nw) {"
|
||||
r' if (4 < d || (f in seen)) { print "too-deep " f; return }'
|
||||
r" if (!ok(f)) return; seen[f] = 1;"
|
||||
r' while (0 < (r = (getline l < f))) { sub(/[#!].*/, "", l); gsub(/[{}]/, " & ", l);'
|
||||
r' n = split(l, t, " "); if (n && nw && t[1] != "{") { stmt(w, nw, f, d); nw = 0 }'
|
||||
r" for (k = 1; k <= n; k++) {"
|
||||
r' if (t[k] == "{") { push(nw ? w[1] : "", 1 < nw ? w[2] : ""); nw = 0 }'
|
||||
r' else if (t[k] == "}") { stmt(w, nw, f, d); nw = 0; pop() } else w[++nw] = t[k] } }'
|
||||
r" stmt(w, nw, f, d);"
|
||||
r' if (r < 0) print "unreadable " f; close(f); delete seen[f] }',
|
||||
r"function inc(p, f, d, c, g, dir, fs, n, i) {"
|
||||
r' if (p !~ /^\//) { dir = f; sub(/[^\/]*$/, "", dir); p = dir p }'
|
||||
r' if (p !~ /^[A-Za-z0-9_.\/*?-]+$/) { print "unreadable " p; return }'
|
||||
r' c = "for g in " p "; do [ -e \"$g\" ] && echo \"$g\"; done"; n = 0;'
|
||||
r" while (0 < (c | getline g)) fs[++n] = g; close(c);"
|
||||
r" for (i = 1; i <= n; i++) rk(fs[i], d + 1) }",
|
||||
r'/^ActiveState=/ { print "active " substr($0, 13); next }',
|
||||
r'/^ExecStart=/ { s = $0; i = index(s, "argv[]="); if (!i) next; s = substr(s, i + 7);'
|
||||
r' j = index(s, " ;"); if (j) s = substr(s, 1, j - 1); n = split(s, t, " ");'
|
||||
r' for (k = 2; k <= n; k++) { f = t[k]; if (f !~ /^-/) continue; v = ""; x = index(f, "=");'
|
||||
r" if (x) { v = substr(f, x + 1); f = substr(f, 1, x - 1) }"
|
||||
r' else if (k < n && t[k + 1] !~ /^-/) v = t[++k]; sub(/^--?/, "", f);'
|
||||
r" if (f ~ /^(config|ip|netmask|mask|interface|iface|trigger-key|key|f|use-file)$/) {"
|
||||
r' print "arg " f " " v; a[f] = v } } next }',
|
||||
r'/^EnvironmentFiles=/ { s = substr($0, 18); sub(/ \(ignore_errors=[a-z]*\)$/, "", s);'
|
||||
r' if (s != "") ef[++ne] = s; next }',
|
||||
r'/^Environment=/ { n = split(substr($0, 13), t, " "); for (k = 1; k <= n; k++) {'
|
||||
rf' x = index(t[k], "="); if (x && substr(t[k], 1, x - 1) ~ /^{_ENV_KEYS}$/)'
|
||||
r' print "env " substr(t[k], 1, x - 1) " " substr(t[k], x + 1) } next }',
|
||||
rf'END {{ if (m == "keepalived") {{ p = "{_KEEPALIVED_CONF}";'
|
||||
r' if ("use-file" in a) p = a["use-file"]; if ("f" in a) p = a["f"]; rk(p, 0) }'
|
||||
r' else { for (k = 1; k <= ne; k++) rf(ef[k], "env");'
|
||||
r' if ("config" in a) rf(a["config"], "cfg") } }',
|
||||
)
|
||||
)
|
||||
|
||||
#: 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.
|
||||
VIRTUAL_IPS_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' VIPS_ BEGIN; "
|
||||
f"if command -v systemctl >/dev/null 2>&1 && [ -d {_SYSTEMD_RUN} ]; then echo '[systemd]'; "
|
||||
"for u in $(systemctl list-units --all --plain --no-legend --type=service "
|
||||
"vip-manager.service 'vip-manager@*' keepalived.service 2>/dev/null | awk '{print $1}'); do "
|
||||
"case $u in keepalived*) m=keepalived;; *) m=vip-manager;; esac; "
|
||||
'echo "[$m $u]"; '
|
||||
'systemctl show -p ActiveState -p ExecStart -p EnvironmentFiles -p Environment "$u" '
|
||||
f"2>/dev/null | awk -v m=$m {quote(_AWK)}; done; "
|
||||
"else echo '[no-systemd]'; fi; "
|
||||
"printf '%s%s\\n' VIPS_ END"
|
||||
)
|
||||
|
||||
_COMMENT_RE = re.compile(r"\s+#.*$")
|
||||
_VARIABLE_RE = re.compile(r"^\$\{?(\w+)\}?$")
|
||||
_Record = tuple[str, str]
|
||||
|
||||
|
||||
def _frame(output: 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 virtual IP report in the output") from None
|
||||
return lines[start + 1 : end]
|
||||
|
||||
|
||||
def _sections(lines: list[str]) -> list[tuple[str, str, list[_Record]]]:
|
||||
"""``[<mechanism> <unit>]`` headers, each with its records as ``(kind, rest)``."""
|
||||
sections: list[tuple[str, str, list[_Record]]] = []
|
||||
for line in lines:
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
mechanism, _, unit = line[1:-1].partition(" ")
|
||||
sections.append((mechanism, unit, []))
|
||||
elif line and sections:
|
||||
kind, _, rest = line.partition(" ")
|
||||
sections[-1][2].append((kind, rest.strip()))
|
||||
return sections
|
||||
|
||||
|
||||
def _clean(value: str) -> str:
|
||||
"""Without a trailing ``# comment`` and the quotes around it."""
|
||||
value = _COMMENT_RE.sub("", value.strip())
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
||||
value = value[1:-1]
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _address(text: str) -> tuple[str, int | None] | None:
|
||||
"""``"10.0.0.10/24"`` -> ``("10.0.0.10", 24)``; None for what is no address."""
|
||||
host, slash, prefix = text.partition("/")
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return None
|
||||
if not slash:
|
||||
return str(address), None
|
||||
if not prefix.isdigit() or int(prefix) > address.max_prefixlen:
|
||||
return None
|
||||
return str(address), int(prefix)
|
||||
|
||||
|
||||
def _prefix(mask: str | None) -> int | None:
|
||||
"""``"24"`` or ``"255.255.255.0"`` -> 24."""
|
||||
if not mask:
|
||||
return None
|
||||
if mask.isdigit():
|
||||
return int(mask) if int(mask) <= 128 else None
|
||||
try:
|
||||
return ipaddress.IPv4Network(f"0.0.0.0/{mask}").prefixlen
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _running(records: list[_Record]) -> bool | None:
|
||||
states = [rest for kind, rest in records if kind == "active"]
|
||||
return states[-1] == "active" if states else None
|
||||
|
||||
|
||||
def _vip_manager(unit: str, records: list[_Record]) -> list[VirtualIpDict]:
|
||||
values: dict[str, dict[str, str]] = {"arg": {}, "env": {}, "cfg": {}}
|
||||
for kind, rest in records:
|
||||
if kind in values:
|
||||
key, _, value = rest.partition(" ")
|
||||
values[kind][key] = value
|
||||
env = values["env"]
|
||||
|
||||
def resolve(value: str) -> str | None:
|
||||
value = _clean(value)
|
||||
variable = _VARIABLE_RE.match(value)
|
||||
if variable:
|
||||
value = _clean(env.get(variable.group(1), ""))
|
||||
return value if value and "$" not in value else None
|
||||
|
||||
def pick(args: tuple[str, ...], envs: tuple[str, ...], cfgs: tuple[str, ...]) -> str | None:
|
||||
for kind, names in (("arg", args), ("env", envs), ("cfg", cfgs)):
|
||||
for name in names:
|
||||
if name in values[kind]:
|
||||
found = resolve(values[kind][name])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
ip = pick(("ip",), ("VIP_IP",), ("ip",))
|
||||
parsed = _address(ip) if ip else None
|
||||
if parsed is None:
|
||||
return []
|
||||
address, prefix = parsed
|
||||
mask = pick(("netmask", "mask"), ("VIP_NETMASK", "VIP_MASK"), ("netmask", "mask"))
|
||||
return [
|
||||
{
|
||||
"mechanism": "vip-manager",
|
||||
"instance": unit[: -len(".service")] if unit.endswith(".service") else unit,
|
||||
"address": address,
|
||||
"prefix_length": _prefix(mask) if mask else prefix,
|
||||
"interface": pick(
|
||||
("interface", "iface"), ("VIP_INTERFACE", "VIP_IFACE"), ("interface", "iface")
|
||||
),
|
||||
"group_key": pick(
|
||||
("trigger-key", "key"), ("VIP_TRIGGER_KEY", "VIP_KEY"), ("trigger-key", "key")
|
||||
),
|
||||
"running": _running(records),
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Instance:
|
||||
name: str
|
||||
interface: str | None = None
|
||||
vrid: str = ""
|
||||
vips: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _keepalived(unit: str, records: list[_Record]) -> list[VirtualIpDict]:
|
||||
running = _running(records)
|
||||
instances: list[_Instance] = []
|
||||
current: _Instance | None = None
|
||||
for kind, rest in records:
|
||||
if kind == "instance":
|
||||
current = _Instance(rest or unit)
|
||||
instances.append(current)
|
||||
elif current is None:
|
||||
continue
|
||||
elif kind == "interface":
|
||||
current.interface = rest or None
|
||||
elif kind == "virtual_router_id":
|
||||
current.vrid = rest
|
||||
elif kind == "vip":
|
||||
current.vips.append(rest)
|
||||
elif kind == "end":
|
||||
current = None
|
||||
return [entry for instance in instances for entry in _instance_entries(instance, running)]
|
||||
|
||||
|
||||
def _instance_entries(instance: _Instance, running: bool | None) -> list[VirtualIpDict]:
|
||||
entries: list[VirtualIpDict] = []
|
||||
for vip in instance.vips:
|
||||
tokens = vip.split()
|
||||
parsed = _address(tokens[0]) if tokens else None
|
||||
if parsed is None:
|
||||
continue
|
||||
address, prefix = parsed
|
||||
dev = tokens[tokens.index("dev") + 1] if "dev" in tokens[1:-1] else None
|
||||
entries.append(
|
||||
{
|
||||
"mechanism": "keepalived",
|
||||
"instance": instance.name,
|
||||
"address": address,
|
||||
"prefix_length": prefix if prefix is not None else _host_prefix(address),
|
||||
"interface": dev or instance.interface,
|
||||
"group_key": f"vrid:{instance.vrid}" if instance.vrid.isdigit() else None,
|
||||
"running": running,
|
||||
}
|
||||
)
|
||||
return entries
|
||||
|
||||
|
||||
def _host_prefix(address: str) -> int:
|
||||
"""keepalived's default for an entry without one: the single address."""
|
||||
return ipaddress.ip_address(address).max_prefixlen
|
||||
|
||||
|
||||
_READERS: dict[str, tuple[str, Callable[[str, list[_Record]], list[VirtualIpDict]]]] = {
|
||||
"vip-manager": ("vip_manager", _vip_manager),
|
||||
"keepalived": ("keepalived", _keepalived),
|
||||
}
|
||||
|
||||
|
||||
def _order(entry: VirtualIpDict) -> tuple[int, int, str]:
|
||||
address = ipaddress.ip_address(entry["address"])
|
||||
return address.version, int(address), entry["instance"]
|
||||
|
||||
|
||||
def parse_virtual_ips(output: str) -> VirtualIpsDict:
|
||||
"""Parse what :data:`VIRTUAL_IPS_COMMAND` printed, each mechanism's entries
|
||||
sorted by address.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(_frame(output))
|
||||
if any(mechanism == _NO_SYSTEMD for mechanism, _, _ in sections):
|
||||
return {"vip_manager": None, "keepalived": None}
|
||||
found: dict[str, list[VirtualIpDict]] = {"vip_manager": [], "keepalived": []}
|
||||
blind: set[str] = set()
|
||||
for mechanism, unit, records in sections:
|
||||
if mechanism not in _READERS:
|
||||
continue
|
||||
key, read = _READERS[mechanism]
|
||||
if any(kind in _BLIND for kind, _ in records):
|
||||
blind.add(key)
|
||||
else:
|
||||
found[key].extend(read(unit, records))
|
||||
|
||||
def result(key: str) -> list[VirtualIpDict] | None:
|
||||
return None if key in blind else sorted(found[key], key=_order)
|
||||
|
||||
return {"vip_manager": result("vip_manager"), "keepalived": result("keepalived")}
|
||||
|
||||
|
||||
class VirtualIpsMixin:
|
||||
"""Adds :meth:`get_virtual_ips` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are
|
||||
the same everywhere, so they are concrete here, and a driver supplies only
|
||||
:meth:`_run_virtual_ips_command` -- how a command reaches its host, and how it
|
||||
gains root there. Mixed in by the drivers that can, not by
|
||||
:class:`~napalm_device_types.os.OSDriver`, so ``hasattr(driver,
|
||||
"get_virtual_ips")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_virtual_ips_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root
|
||||
when *privileged*. The command is a single ``sh -c`` invocation of
|
||||
about 4 kB: send it on an exec channel, not typed into a shell."""
|
||||
...
|
||||
|
||||
def get_virtual_ips(self) -> VirtualIpsDict:
|
||||
"""
|
||||
Returns the virtual IPs the host's vip-manager and keepalived configuration
|
||||
declares -- whether or not the host holds them at the moment.
|
||||
|
||||
* vip_manager (list or None) - see :class:`~napalm_device_types.models.VirtualIpDict`
|
||||
* keepalived (list or None)
|
||||
|
||||
None for a mechanism means it could not be read; ``[]`` that the host has none.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"vip_manager": [
|
||||
{"mechanism": "vip-manager", "instance": "vip-manager",
|
||||
"address": "10.7.224.10", "prefix_length": 24, "interface": "ens7",
|
||||
"group_key": "/service/netork-db/leader", "running": True},
|
||||
],
|
||||
"keepalived": [],
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(VIRTUAL_IPS_COMMAND)}"
|
||||
try:
|
||||
return parse_virtual_ips(self._run_virtual_ips_command(command, privileged=True))
|
||||
except ValueError:
|
||||
pass
|
||||
return parse_virtual_ips(self._run_virtual_ips_command(command, privileged=False))
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Moving a guest to another node of its cluster (``HypervisorDriver.migrate_vm``).
|
||||
|
||||
``get_vm_migration_preflight`` reports what the platform says before a move:
|
||||
which nodes would take the guest, which refuse it and why, and what the guest
|
||||
holds on its current node. ``migrate_vm`` then moves it and blocks until the
|
||||
platform's task ended; a failure raises with the platform's own cause.
|
||||
``set_node_maintenance`` switches a node's HA maintenance mode, which makes the
|
||||
HA manager move its HA guests away while it is on.
|
||||
|
||||
Facts only: which node to pick, and whether a local disk is worth copying, is
|
||||
the caller's to decide.
|
||||
"""
|
||||
|
||||
from typing import TypedDict
|
||||
|
||||
|
||||
class MigrationPreflightDict(TypedDict):
|
||||
"""Where a guest could move to, and what stands in the way."""
|
||||
|
||||
running: bool
|
||||
allowed_nodes: list[str] # nodes the platform would move it to
|
||||
refused_nodes: dict[str, str] # node -> the platform's reason, in plain words
|
||||
# volume ids on storage the target does not share; they block nothing by
|
||||
# themselves, the migration copies them
|
||||
local_disks: list[str]
|
||||
local_resources: list[str] # e.g. "hostpci0", "usb0": they block the migration
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Asking for a VM's clean shutdown without waiting for it.
|
||||
|
||||
``HypervisorDriver.stop_vm`` blocks until the VM is stopped, within a limit
|
||||
of the driver's own. A caller that keeps its waits as timers asks with
|
||||
``begin_stop_vm`` and reads ``get_vm_status`` until the VM says it stopped.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: a driver mixes this in when its
|
||||
hypervisor can take the request on its own; ``hasattr`` tells a caller
|
||||
whether it did. No role base carries it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
|
||||
class VmStopRequestMixin:
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def begin_stop_vm(self, name: str) -> None:
|
||||
"""
|
||||
Asks the hypervisor to shut a virtual machine down cleanly (ACPI)
|
||||
and returns as soon as the request was accepted.
|
||||
|
||||
:param name: VM name or its ``vmid``.
|
||||
:raises ValueError: If no VM with the given name/ID exists.
|
||||
:raises RuntimeError: If the hypervisor refuses the request.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,238 @@
|
||||
"""A native Zabbix agent: its configuration and Zabbix's package repository.
|
||||
|
||||
What :class:`~napalm_device_types.fixes.ZabbixAgentMixin` needs that is the same on
|
||||
every host, without I/O: which settings an agent may be given
|
||||
(:func:`check_zabbix_agent_settings`), the agent's configuration file with them
|
||||
(:func:`zabbix_agent_config`), and the command that adds Zabbix's repository where
|
||||
the host's own packages have no agent (:func:`zabbix_repository_command`). A driver
|
||||
reads and writes the file and runs the command.
|
||||
|
||||
**Which lines.** ``Server`` (who may ask, for passive checks), ``ServerActive``
|
||||
(where active checks go), ``ListenPort`` and, when the caller names one,
|
||||
``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>/``,
|
||||
with the rpm in an ``x86_64`` directory. The release line is the server's: an agent
|
||||
may be older than its server, not newer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
|
||||
class ZabbixAgentSettingsDict(TypedDict):
|
||||
"""What the caller wants a native Zabbix agent to be (``ZabbixAgentMixin``)."""
|
||||
|
||||
server: str # Server: the addresses that may ask (passive checks), comma-separated
|
||||
server_active: str # ServerActive: where active checks go, comma-separated; "" for none
|
||||
listen_port: int # ListenPort
|
||||
# addresses or CIDRs let through to the port; [] changes no firewall
|
||||
allowed_sources: list[str]
|
||||
# Hostname: the host's technical name in Zabbix; absent keeps the agent's
|
||||
hostname: NotRequired[str]
|
||||
# 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,
|
||||
#: IPv4, ``[IPv6]`` and ports. Nothing a config line or a shell word breaks out of.
|
||||
_ADDRESSES = re.compile(r"^[A-Za-z0-9.:\[\]-]+(,[A-Za-z0-9.:\[\]-]+)*$")
|
||||
#: What Zabbix allows in a technical host name.
|
||||
_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", "StartAgents")
|
||||
_LINE = re.compile(r"^(\s*)(" + "|".join(_KEYS) + r")\s*=\s*(.*?)\s*$")
|
||||
|
||||
REPOSITORY = "https://repo.zabbix.com/zabbix"
|
||||
#: The distributions Zabbix publishes packages for, by ``/etc/os-release``'s ``ID``:
|
||||
#: the name in the repository's path, and whether they take a deb.
|
||||
_DISTRIBUTIONS: dict[str, tuple[str, bool]] = {
|
||||
"ubuntu": ("ubuntu", True),
|
||||
"debian": ("debian", True),
|
||||
"raspbian": ("raspbian", True),
|
||||
"rhel": ("rhel", False),
|
||||
"centos": ("rhel", False),
|
||||
"ol": ("oracle", False),
|
||||
"almalinux": ("alma", False),
|
||||
"rocky": ("rocky", False),
|
||||
}
|
||||
|
||||
|
||||
def check_zabbix_agent_settings(settings: ZabbixAgentSettingsDict) -> None:
|
||||
"""Refuse what an agent's configuration or a shell line cannot take.
|
||||
|
||||
:raises ValueError: naming the setting.
|
||||
"""
|
||||
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}")
|
||||
port = settings.get("listen_port")
|
||||
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
|
||||
raise ValueError(f"not a port: {port!r}")
|
||||
release = settings.get("release")
|
||||
if release is not None and not _RELEASE.match(release):
|
||||
raise ValueError(f"not a Zabbix release line (major.minor): {release!r}")
|
||||
|
||||
|
||||
def _check_addresses(key: str, value: str, *, required: bool) -> None:
|
||||
if (value or required) and not _ADDRESSES.match(value):
|
||||
raise ValueError(f"not addresses an agent's {key} takes: {value!r}")
|
||||
|
||||
|
||||
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": "" 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. ``active_only`` is the other way round: ``StartAgents=0``
|
||||
and ``Server`` commented out.
|
||||
"""
|
||||
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"))
|
||||
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)
|
||||
_add_missing(
|
||||
lines, [key for key in _KEYS if wanted.get(key) and key not in seen], wanted, changes
|
||||
)
|
||||
return "".join(lines), changes
|
||||
|
||||
|
||||
def _add_missing(
|
||||
lines: list[str], keys: list[str], wanted: dict[str, str], changes: list[str]
|
||||
) -> None:
|
||||
"""*keys*, which the file does not set, at its end."""
|
||||
if keys and lines and not lines[-1].endswith("\n"):
|
||||
lines[-1] += "\n"
|
||||
for key in keys:
|
||||
lines.append(f"{key}={wanted[key]}\n")
|
||||
changes.append(f"{key}: (not set) → {wanted[key]}")
|
||||
|
||||
|
||||
def _set_line(line: str, match: re.Match[str], wanted: dict[str, str], changes: list[str]) -> str:
|
||||
"""*line*, which sets a key the caller wants, as the caller wants it."""
|
||||
indent, key, old = match.groups()
|
||||
end = "\n" if line.endswith("\n") else ""
|
||||
new = wanted[key]
|
||||
if not new:
|
||||
changes.append(f"{key}: {old} → (not set)")
|
||||
return f"{indent}# {key}={old}{end}"
|
||||
if old == new:
|
||||
return line
|
||||
changes.append(f"{key}: {old} → {new}")
|
||||
return f"{indent}{key}={new}{end}"
|
||||
|
||||
|
||||
def _os_release(text: str) -> dict[str, str]:
|
||||
fields = {}
|
||||
for line in text.splitlines():
|
||||
key, sep, value = line.partition("=")
|
||||
if sep:
|
||||
fields[key.strip()] = value.strip().strip("'\"")
|
||||
return fields
|
||||
|
||||
|
||||
def _distribution(fields: dict[str, str]) -> tuple[str, bool]:
|
||||
for candidate in [fields.get("ID", ""), *fields.get("ID_LIKE", "").split()]:
|
||||
if candidate in _DISTRIBUTIONS:
|
||||
return _DISTRIBUTIONS[candidate]
|
||||
raise ValueError(f"Zabbix publishes no repository for {fields.get('ID') or 'this system'}")
|
||||
|
||||
|
||||
def zabbix_repository_command(os_release: str, release: str) -> str:
|
||||
"""The root command that adds Zabbix's *release* repository to the host whose
|
||||
``/etc/os-release`` is *os_release*, and refreshes the package index.
|
||||
|
||||
:raises ValueError: for a release line that is not ``major.minor``, or a
|
||||
distribution Zabbix publishes nothing for.
|
||||
"""
|
||||
match = _RELEASE.match(release)
|
||||
if not match:
|
||||
raise ValueError(f"not a Zabbix release line (major.minor): {release!r}")
|
||||
fields = _os_release(os_release)
|
||||
name, deb = _distribution(fields)
|
||||
version = fields.get("VERSION_ID", "")
|
||||
new_layout = (int(match.group(1)), int(match.group(2))) >= (7, 2)
|
||||
base = f"{REPOSITORY}/{release}/" + ("release/" if new_layout else "") + name
|
||||
if deb:
|
||||
# Raspberry Pi OS's packages are named after the Debian release they follow.
|
||||
label = "debian" if name == "raspbian" else name
|
||||
filename = f"zabbix-release_latest_{release}+{label}{version}_all.deb"
|
||||
url = f"{base}/pool/main/z/zabbix-release/{filename}"
|
||||
package = shlex.quote(url)
|
||||
return (
|
||||
"t=$(mktemp -d) && "
|
||||
f'{{ curl -fsSL -o "$t/zabbix-release.deb" {package} '
|
||||
f'|| wget -qO "$t/zabbix-release.deb" {package}; }} && '
|
||||
'dpkg -i "$t/zabbix-release.deb" && apt-get update; '
|
||||
# The download's directory goes either way; the status is the install's.
|
||||
's=$?; rm -rf "$t"; [ "$s" -eq 0 ]'
|
||||
)
|
||||
major = version.split(".")[0]
|
||||
arch = "noarch" if new_layout else "x86_64"
|
||||
url = f"{base}/{major}/{arch}/zabbix-release-latest-{release}.el{major}.noarch.rpm"
|
||||
return f"dnf -y install {shlex.quote(url)}"
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REPOSITORY",
|
||||
"ZabbixAgentSettingsDict",
|
||||
"check_zabbix_agent_settings",
|
||||
"zabbix_agent_config",
|
||||
"zabbix_repository_command",
|
||||
]
|
||||
+40
-17
@@ -1,14 +1,14 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68", "wheel"]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "0.5.0"
|
||||
version = "4.49.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
license = { text = "Apache-2.0" }
|
||||
requires-python = ">=3.12"
|
||||
license = "Apache-2.0"
|
||||
authors = [
|
||||
{ name = "Christian Manivong", email = "christian@manivong.de" },
|
||||
]
|
||||
@@ -28,39 +28,62 @@ classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: System Administrators",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: System :: Networking",
|
||||
"Topic :: System :: Systems Administration",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"requests>=2.25.0",
|
||||
"typing-extensions>=4.0",
|
||||
"tzdata>=2024.1", # posix_tz reads the zones' TZif files from it
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/chrismanivong/napalm-device-types"
|
||||
Repository = "https://github.com/chrismanivong/napalm-device-types"
|
||||
Issues = "https://github.com/chrismanivong/napalm-device-types/issues"
|
||||
Repository = "https://git.netork.io/NAPALM/napalm-device-types"
|
||||
Issues = "https://git.netork.io/NAPALM/napalm-device-types/issues"
|
||||
Changelog = "https://git.netork.io/NAPALM/napalm-device-types/src/branch/main/CHANGELOG.md"
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest",
|
||||
"mypy",
|
||||
"build",
|
||||
"twine",
|
||||
"pytest>=8",
|
||||
"pytest-cov>=5",
|
||||
"mypy>=1.11",
|
||||
"ruff>=0.6",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["napalm_device_types*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
napalm_device_types = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# Recorded device output keeps its lines.
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.9"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["napalm_device_types"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 95
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"coverage_floor": 95.0,
|
||||
"function_complexity": {
|
||||
"napalm_device_types/_ucd_metrics.py::build_if_metrics": 20,
|
||||
"napalm_device_types/_ucd_metrics.py::collect_ucd_metrics": 17,
|
||||
"napalm_device_types/host_firewall.py::_iptables_rule": 11,
|
||||
"napalm_device_types/host_firewall.py::_module_match": 13,
|
||||
"napalm_device_types/host_firewall.py::_module_options": 14,
|
||||
"napalm_device_types/host_firewall.py::_nft_field": 15,
|
||||
"napalm_device_types/host_firewall.py::_nft_match": 12,
|
||||
"napalm_device_types/host_firewall.py::_nft_rule": 16,
|
||||
"napalm_device_types/host_firewall.py::_parse_nft": 14,
|
||||
"napalm_device_types/host_firewall.py::rule_text": 14,
|
||||
"napalm_device_types/host_status.py::_reboot": 12,
|
||||
"napalm_device_types/lag.py::add_lag_interfaces": 11,
|
||||
"napalm_device_types/listening.py::parse_listening_sockets": 13,
|
||||
"napalm_device_types/service_clusters.py::_patroni": 11,
|
||||
"napalm_device_types/ssh_server.py::plan_ssh_hardening": 38,
|
||||
"napalm_device_types/virtual_ips.py::_keepalived": 12
|
||||
},
|
||||
"function_lines": {
|
||||
"napalm_device_types/_ucd_metrics.py::collect_ucd_metrics": 119,
|
||||
"napalm_device_types/dhcp.py::DhcpServerMixin.diff_dhcp_subnets": 60,
|
||||
"napalm_device_types/firewall_rules.py::FirewallRuleMixin.diff_firewall_rules": 56,
|
||||
"napalm_device_types/hypervisor.py::HypervisorDriver.create_vm_from_cloud_init": 84,
|
||||
"napalm_device_types/hypervisor.py::HypervisorDriver.get_vm_config": 77,
|
||||
"napalm_device_types/ssh_server.py::plan_ssh_hardening": 60,
|
||||
"napalm_device_types/storage.py::StorageDriver.get_volumes": 52,
|
||||
"napalm_device_types/switch.py::SwitchDriver.get_dot1x_ports": 51,
|
||||
"napalm_device_types/switch.py::SwitchDriver.get_poe_status": 63
|
||||
},
|
||||
"mypy_relaxed": [],
|
||||
"python_file_lines": {
|
||||
"napalm_device_types/models.py": 1353
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
"""apt's history log as past transactions (NetOrk/netork#2728).
|
||||
|
||||
The blocks below are written as apt writes them (``apt-pkg/deb/dpkgpm.cc``): two
|
||||
spaces between date and time, ``name:arch (version[, ...])`` entries joined by
|
||||
``, ``, ``Install``'s ``automatic``, ``Upgrade``/``Downgrade`` with old and new,
|
||||
``Remove``/``Purge`` with the version that was installed, ``Error`` before
|
||||
``End-Date``. The ids follow Proxmox VE 9.3's ``GET /nodes/{node}/apt/history``:
|
||||
start time, and the count of earlier transactions with that start in the same file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import UTC, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
APT_HISTORY_COMMAND,
|
||||
AptHistoryMixin,
|
||||
AptHistoryUnreadable,
|
||||
apt_history_command,
|
||||
host_zone,
|
||||
parse_apt_history,
|
||||
)
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
|
||||
def _utc(text: str) -> int:
|
||||
return int(datetime.strptime(text, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC).timestamp())
|
||||
|
||||
|
||||
CURRENT = """
|
||||
Start-Date: 2026-11-26 10:00:00
|
||||
Commandline: apt-get -y upgrade
|
||||
Requested-By: admin (1000)
|
||||
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic), linux-headers-6.12.57+deb13-common:all (6.12.57-1, automatic), htop:amd64 (3.4.1-5)
|
||||
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1), libssl3t64:amd64 (3.5.1-1, 3.5.1-1+deb13u1), libssl3t64:i386 (3.5.1-1, 3.5.1-1+deb13u1)
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
Start-Date: 2026-11-26 10:01:00
|
||||
Commandline: /usr/bin/apt remove wazuh-agent
|
||||
Remove: wazuh-agent:amd64 (4.14.8-1)
|
||||
Error: Sub-process /usr/bin/dpkg returned an error code (1)
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
Start-Date: 2026-11-26 10:01:00
|
||||
Commandline: /usr/bin/apt purge wazuh-agent
|
||||
Purge: wazuh-agent:amd64 (4.14.8-1), linux-image-6.12.48+deb13-amd64:amd64 ()
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
Start-Date: 2026-11-26 10:05:13
|
||||
Commandline: /usr/bin/unattended-upgrade
|
||||
Upgrade: tzdata:all (2025b-4, 2025b-4+deb13u1)
|
||||
"""
|
||||
|
||||
ROTATED = """
|
||||
Start-Date: 2026-07-14 03:12:40
|
||||
Commandline: apt-get install --reinstall libvulkan1
|
||||
Requested-By: admin (1000)
|
||||
Reinstall: libvulkan1:amd64 (1.4.309.0-1), libvulkan1:i386 (1.4.309.0-1)
|
||||
End-Date: 2026-07-14 03:12:41
|
||||
|
||||
Start-Date: 2026-07-14 03:13:05
|
||||
Commandline: apt-get install pve-manager=9.0.10
|
||||
Downgrade: pve-manager:amd64 (9.0.11, 9.0.10)
|
||||
Disappeared: libfoo1 (1.2-3), libbar0
|
||||
End-Date: 2026-07-14 03:13:20
|
||||
"""
|
||||
|
||||
OLDEST = """
|
||||
Start-Date: 2026-01-12 06:25:01
|
||||
Commandline: apt-get dist-upgrade
|
||||
Remove: caribou (0.4.21-9)
|
||||
End-Date: 2026-01-12 06:25:30
|
||||
"""
|
||||
|
||||
|
||||
def _report(files: dict[str, str], zone: str = "/usr/share/zoneinfo/Europe/Berlin") -> str:
|
||||
"""What :data:`APT_HISTORY_COMMAND` prints for *files* (path -> content)."""
|
||||
lines = [f"### apt-history zone {zone}", "### apt-history offset +0100"]
|
||||
for path, content in files.items():
|
||||
lines += [f"### apt-history file {path}", content, "", "### apt-history status 0"]
|
||||
return "\n".join([*lines, "### apt-history end", ""])
|
||||
|
||||
|
||||
LOGS = {
|
||||
"/var/log/apt/history.log": CURRENT,
|
||||
"/var/log/apt/history.log.1.gz": ROTATED,
|
||||
"/var/log/apt/history.log.10.gz": OLDEST,
|
||||
}
|
||||
|
||||
|
||||
class TestParse:
|
||||
def test_newest_first_over_every_file(self):
|
||||
ids = [t["id"] for t in parse_apt_history(_report(LOGS))]
|
||||
assert ids == [
|
||||
f"{_utc('2026-11-26 09:05:13')}-0",
|
||||
f"{_utc('2026-11-26 09:01:00')}-1",
|
||||
f"{_utc('2026-11-26 09:01:00')}-0",
|
||||
f"{_utc('2026-11-26 09:00:00')}-0",
|
||||
f"{_utc('2026-07-14 01:13:05')}-0",
|
||||
f"{_utc('2026-07-14 01:12:40')}-0",
|
||||
f"{_utc('2026-01-12 05:25:01')}-0",
|
||||
]
|
||||
|
||||
def test_a_transaction_with_its_packages(self):
|
||||
upgrade = parse_apt_history(_report(LOGS))[3]
|
||||
assert upgrade == {
|
||||
"id": f"{_utc('2026-11-26 09:00:00')}-0",
|
||||
"start": _utc("2026-11-26 09:00:00"),
|
||||
"end": _utc("2026-11-26 09:01:00"),
|
||||
"packages": [
|
||||
{
|
||||
"name": "linux-image-6.12.57+deb13-amd64",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "6.12.57-1",
|
||||
},
|
||||
{
|
||||
"name": "linux-headers-6.12.57+deb13-common",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "6.12.57-1",
|
||||
},
|
||||
{
|
||||
"name": "htop",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "3.4.1-5",
|
||||
},
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"action": "upgrade",
|
||||
"old_version": "1:10.0p1-7",
|
||||
"new_version": "1:10.0p1-7+deb13u1",
|
||||
},
|
||||
{
|
||||
"name": "libssl3t64",
|
||||
"action": "upgrade",
|
||||
"old_version": "3.5.1-1",
|
||||
"new_version": "3.5.1-1+deb13u1",
|
||||
},
|
||||
{
|
||||
"name": "libssl3t64",
|
||||
"action": "upgrade",
|
||||
"old_version": "3.5.1-1",
|
||||
"new_version": "3.5.1-1+deb13u1",
|
||||
},
|
||||
],
|
||||
"requested_by": "admin",
|
||||
"command": "apt-get -y upgrade",
|
||||
"error": None,
|
||||
}
|
||||
|
||||
def test_the_error_a_run_ended_with(self):
|
||||
failed = parse_apt_history(_report(LOGS))[2]
|
||||
assert failed["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
|
||||
assert failed["requested_by"] is None
|
||||
assert failed["packages"] == [
|
||||
{
|
||||
"name": "wazuh-agent",
|
||||
"action": "remove",
|
||||
"old_version": "4.14.8-1",
|
||||
"new_version": None,
|
||||
}
|
||||
]
|
||||
|
||||
def test_a_purge_of_what_was_removed_before_had_no_version(self):
|
||||
purge = parse_apt_history(_report(LOGS))[1]
|
||||
assert [(p["name"], p["action"], p["old_version"]) for p in purge["packages"]] == [
|
||||
("wazuh-agent", "purge", "4.14.8-1"),
|
||||
("linux-image-6.12.48+deb13-amd64", "purge", None),
|
||||
]
|
||||
|
||||
def test_a_run_without_end_is_running_or_interrupted(self):
|
||||
newest = parse_apt_history(_report(LOGS))[0]
|
||||
assert newest["end"] is None
|
||||
assert newest["command"] == "/usr/bin/unattended-upgrade"
|
||||
|
||||
def test_reinstall_downgrade_disappeared_and_arch_less_names(self):
|
||||
history = parse_apt_history(_report(LOGS))
|
||||
downgrade, reinstall, oldest = history[4], history[5], history[6]
|
||||
assert [(p["name"], p["old_version"], p["new_version"]) for p in reinstall["packages"]] == [
|
||||
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
|
||||
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
|
||||
]
|
||||
assert [
|
||||
(p["action"], p["name"], p["old_version"], p["new_version"])
|
||||
for p in downgrade["packages"]
|
||||
] == [
|
||||
("downgrade", "pve-manager", "9.0.11", "9.0.10"),
|
||||
("disappear", "libfoo1", "1.2-3", None),
|
||||
("disappear", "libbar0", None, None),
|
||||
]
|
||||
assert oldest["packages"] == [
|
||||
{"name": "caribou", "action": "remove", "old_version": "0.4.21-9", "new_version": None}
|
||||
]
|
||||
|
||||
def test_summer_time_is_the_zones(self):
|
||||
reinstall = parse_apt_history(_report(LOGS))[5]
|
||||
assert reinstall["start"] == _utc("2026-07-14 01:12:40") # CEST, UTC+2
|
||||
|
||||
def test_since_filters_by_start_and_keeps_the_ids(self):
|
||||
since = _utc("2026-11-26 09:01:00")
|
||||
ids = [t["id"] for t in parse_apt_history(_report(LOGS), since=since)]
|
||||
assert ids == [f"{_utc('2026-11-26 09:05:13')}-0", f"{since}-1", f"{since}-0"]
|
||||
|
||||
def test_nothing_logged_is_an_empty_list(self):
|
||||
assert parse_apt_history(_report({})) == []
|
||||
assert parse_apt_history(_report({"/var/log/apt/history.log": ""})) == []
|
||||
|
||||
def test_the_index_is_counted_per_file(self):
|
||||
same = "\nStart-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\nEnd-Date: 2026-11-26 10:00:00\n"
|
||||
history = parse_apt_history(
|
||||
_report({"/var/log/apt/history.log": same * 2, "/var/log/apt/history.log.1.gz": same})
|
||||
)
|
||||
start = _utc("2026-11-26 09:00:00")
|
||||
assert [t["id"] for t in history] == [f"{start}-1", f"{start}-0", f"{start}-0"]
|
||||
|
||||
|
||||
class TestStrict:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
"Upgrade: openssh-server:amd64 (1:10.0p1-7)", # an upgrade names old and new
|
||||
"Install: htop:amd64 (3.4.1-5, manual)",
|
||||
"Remove: htop:amd64 (3.4.1-5), ",
|
||||
"Install: htop:amd64 (3.4.1-5", # cut short
|
||||
"Upgrade: htop:amd64 (, 3.4.1-5)",
|
||||
"Disappeared: libfoo1 (1.2-3) (1.2-4)",
|
||||
"a line apt never writes",
|
||||
],
|
||||
)
|
||||
def test_a_malformed_block_is_left_out_but_counted(self, line):
|
||||
log = (
|
||||
f"Start-Date: 2026-11-26 10:00:00\n{line}\nEnd-Date: 2026-11-26 10:00:01\n\n"
|
||||
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
|
||||
"End-Date: 2026-11-26 10:00:02\n"
|
||||
)
|
||||
history = parse_apt_history(_report({"/var/log/apt/history.log": log}))
|
||||
assert [t["id"] for t in history] == [f"{_utc('2026-11-26 09:00:00')}-1"]
|
||||
|
||||
def test_an_unreadable_date_is_no_transaction(self):
|
||||
log = (
|
||||
"Start-Date: yesterday\nInstall: htop:amd64 (3.4.1-5)\n\n"
|
||||
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
|
||||
"End-Date: soon\n"
|
||||
)
|
||||
assert parse_apt_history(_report({"/var/log/apt/history.log": log})) == []
|
||||
|
||||
def test_lines_before_the_first_block_are_ignored(self):
|
||||
log = "Install: htop:amd64 (3.4.1-5)\n" + OLDEST
|
||||
assert len(parse_apt_history(_report({"/var/log/apt/history.log": log}))) == 1
|
||||
|
||||
def test_a_report_cut_short_raises(self):
|
||||
with pytest.raises(ValueError, match="cut short"):
|
||||
parse_apt_history(_report(LOGS).replace("### apt-history end\n", ""))
|
||||
|
||||
def test_a_file_that_could_not_be_read_raises(self):
|
||||
report = _report(LOGS).replace("status 0", "status 1", 1)
|
||||
with pytest.raises(ValueError, match="exit 1"):
|
||||
parse_apt_history(report)
|
||||
|
||||
def test_a_file_the_user_may_not_read_raises(self):
|
||||
report = _report(LOGS).replace(
|
||||
"### apt-history end",
|
||||
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
|
||||
)
|
||||
with pytest.raises(AptHistoryUnreadable, match="history.log.2.gz"):
|
||||
parse_apt_history(report)
|
||||
|
||||
def test_other_files_in_the_directory_are_not_read(self):
|
||||
report = _report({**LOGS, "/var/log/apt/history.log.dpkg-old": OLDEST}).replace(
|
||||
"### apt-history end",
|
||||
"### apt-history unreadable /var/log/apt/history.log.bak\n### apt-history end",
|
||||
)
|
||||
assert len(parse_apt_history(report)) == 7
|
||||
|
||||
|
||||
class TestZone:
|
||||
def test_a_named_zone(self):
|
||||
assert str(host_zone("Europe/Berlin\n", "+0100")) == "Europe/Berlin"
|
||||
assert str(host_zone("/usr/share/zoneinfo/America/New_York", "-0500")) == "America/New_York"
|
||||
|
||||
@pytest.mark.parametrize("name", ["", "Mars/Olympus_Mons", "../../etc/passwd"])
|
||||
def test_without_a_known_name_the_offset(self, name):
|
||||
assert host_zone(name, "+0530") == timezone(timedelta(hours=5, minutes=30))
|
||||
assert host_zone(name, "-0300\n") == timezone(-timedelta(hours=3))
|
||||
|
||||
def test_neither_raises(self):
|
||||
with pytest.raises(ValueError, match="no time zone"):
|
||||
host_zone("", "")
|
||||
|
||||
def test_a_host_on_its_offset_alone(self):
|
||||
history = parse_apt_history(_report({"/var/log/apt/history.log": OLDEST}, zone=""))
|
||||
assert history[0]["start"] == _utc("2026-01-12 05:25:01") # +0100
|
||||
|
||||
|
||||
class TestCommand:
|
||||
"""The command run for real with ``sh`` against a log directory in a temp directory."""
|
||||
|
||||
@staticmethod
|
||||
def _run(log_dir: Path) -> str:
|
||||
done = subprocess.run(
|
||||
["sh", "-c", apt_history_command(str(log_dir))],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return done.stdout
|
||||
|
||||
@staticmethod
|
||||
def _logs(log_dir: Path) -> None:
|
||||
(log_dir / "history.log").write_text(CURRENT)
|
||||
(log_dir / "history.log.1.gz").write_bytes(gzip.compress(ROTATED.encode()))
|
||||
(log_dir / "history.log.10.gz").write_bytes(gzip.compress(OLDEST.encode()))
|
||||
(log_dir / "term.log").write_text("Log started: 2026-11-26 10:00:00\n")
|
||||
|
||||
def test_every_file_rotated_or_not(self, tmp_path):
|
||||
self._logs(tmp_path)
|
||||
history = parse_apt_history(self._run(tmp_path))
|
||||
# Dated in this machine's zone: the order and the fields, not the seconds.
|
||||
assert len(history) == 7
|
||||
assert history[0]["command"] == "/usr/bin/unattended-upgrade"
|
||||
assert history[-1]["command"] == "apt-get dist-upgrade"
|
||||
|
||||
def test_the_zone_and_offset_are_printed(self, tmp_path):
|
||||
out = self._run(tmp_path)
|
||||
assert "### apt-history zone " in out
|
||||
assert "### apt-history offset " in out
|
||||
assert out.endswith("### apt-history end\n")
|
||||
|
||||
def test_no_log_is_no_transaction(self, tmp_path):
|
||||
assert parse_apt_history(self._run(tmp_path / "missing")) == []
|
||||
|
||||
@pytest.mark.skipif(os.geteuid() == 0, reason="root reads every file")
|
||||
def test_an_unreadable_file_is_named(self, tmp_path):
|
||||
self._logs(tmp_path)
|
||||
(tmp_path / "history.log.1.gz").chmod(0)
|
||||
with pytest.raises(AptHistoryUnreadable):
|
||||
parse_apt_history(self._run(tmp_path))
|
||||
|
||||
def test_the_constant_reads_apts_own_directory(self):
|
||||
assert APT_HISTORY_COMMAND == apt_history_command("/var/log/apt")
|
||||
|
||||
|
||||
class _Host(AptHistoryMixin):
|
||||
def __init__(self, *answers: CommandResult) -> None:
|
||||
self.answers = list(answers)
|
||||
self.ran: list[bool] = []
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
assert command == APT_HISTORY_COMMAND
|
||||
assert stdin is None
|
||||
self.ran.append(privileged)
|
||||
return self.answers.pop(0)
|
||||
|
||||
|
||||
UNREADABLE = _report(LOGS).replace(
|
||||
"### apt-history end",
|
||||
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
|
||||
)
|
||||
|
||||
|
||||
class TestMixin:
|
||||
def test_read_as_the_login_user(self):
|
||||
host = _Host(CommandResult(_report(LOGS), "", 0))
|
||||
assert len(host.get_update_history()) == 7
|
||||
assert host.ran == [False]
|
||||
|
||||
def test_since_is_applied(self):
|
||||
host = _Host(CommandResult(_report(LOGS), "", 0))
|
||||
assert len(host.get_update_history(since=_utc("2026-11-26 09:01:00"))) == 3
|
||||
|
||||
def test_a_file_only_root_may_read_is_read_as_root(self):
|
||||
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(_report(LOGS), "", 0))
|
||||
assert len(host.get_update_history()) == 7
|
||||
assert host.ran == [False, True]
|
||||
|
||||
def test_unreadable_even_as_root_raises(self):
|
||||
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(UNREADABLE, "", 0))
|
||||
with pytest.raises(AptHistoryUnreadable):
|
||||
host.get_update_history()
|
||||
|
||||
def test_a_failed_run_raises(self):
|
||||
host = _Host(
|
||||
CommandResult(UNREADABLE, "", 0),
|
||||
CommandResult("", "sudo: a password is required", 1),
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="password is required"):
|
||||
host.get_update_history()
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user