Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e9d21c368 | ||
|
|
25f28297e4 | ||
|
|
847c902193 | ||
|
|
fdf2f89115 | ||
|
|
d63abff467 | ||
|
|
9d6a1a65ed | ||
|
|
95e3aa1e26 | ||
|
|
a0901e3277 | ||
|
|
060e210130 | ||
|
|
31973d2d5f | ||
|
|
abda0973e7 | ||
|
|
4eeaaef236 | ||
|
|
3490d8b62a | ||
|
|
2542081c6f | ||
|
|
4427be35cc | ||
|
|
ad9ec0fb4d | ||
|
|
8dd7e8ab9a | ||
|
|
935fad2a2d | ||
|
|
f337ae7fb8 | ||
|
|
c7ea15dbb4 | ||
|
|
01fe680456 |
No files matched your search
@@ -7,6 +7,54 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
@@ -47,6 +47,18 @@ UUID and NIC MACs -- what ties the BMC to the host it manages. Its sensors come
|
||||
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
|
||||
@@ -179,6 +191,16 @@ without `ss` is read with `netstat -lntup` (OpenWrt's busybox, old net-tools); o
|
||||
cgroup names the procd service (`/services/<name>/<instance>`). A host with neither raises
|
||||
`ListeningSocketsUnavailable`.
|
||||
|
||||
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`.
|
||||
@@ -451,6 +473,7 @@ Requires Python ≥ 3.12 (tested up to 3.13) and NAPALM ≥ 4.0.
|
||||
| `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
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
# 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`, `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)` |
|
||||
| `fix_docker_permissions` | `grant_container_engine_access(user)` |
|
||||
| `install_lldpd`, `install_auc` | `ensure_package(name)` |
|
||||
|
||||
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` |
|
||||
| `kernel` | `/proc`, `/lib/modules`, gzip, base64 |
|
||||
| `listening` | `ss`, `netstat`, `/proc/<pid>/cgroup` |
|
||||
| `systemd` | `systemctl` |
|
||||
| `virtual_ips` | vip-manager, keepalived, awk |
|
||||
| `system_identity` | SMBIOS via sysfs and `dmidecode` |
|
||||
| `package_updates` | apt and dnf output |
|
||||
| `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 |
|
||||
@@ -22,6 +22,7 @@ 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`
|
||||
@@ -78,6 +79,22 @@ from napalm_device_types.apt_proxy import (
|
||||
same_proxy_url,
|
||||
)
|
||||
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,
|
||||
@@ -135,6 +152,13 @@ from napalm_device_types.listening import (
|
||||
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,
|
||||
@@ -249,6 +273,19 @@ from napalm_device_types.vm_migration import MigrationPreflightDict
|
||||
from napalm_device_types.vm_stop_request import VmStopRequestMixin
|
||||
|
||||
__all__ = [
|
||||
"BACKUP_JOB_KINDS",
|
||||
"BackupDatastoreDict",
|
||||
"BackupGroupDict",
|
||||
"BackupJobKind",
|
||||
"BackupRemoteDict",
|
||||
"BackupRunState",
|
||||
"BackupServerJobDict",
|
||||
"BackupServerRefDict",
|
||||
"BackupSnapshotDict",
|
||||
"BackupSnapshotRefDict",
|
||||
"BackupTaskDict",
|
||||
"BackupTaskStatusDict",
|
||||
"BackupVerifyState",
|
||||
"BackupDict",
|
||||
"BackupJobDict",
|
||||
"ClusterDict",
|
||||
@@ -288,6 +325,7 @@ __all__ = [
|
||||
"SnmpMemorySpec",
|
||||
"SnmpValueSpec",
|
||||
"AccessPointDriver",
|
||||
"BackupServerDriver",
|
||||
"ByteStream",
|
||||
"CommandChannelMixin",
|
||||
"CommandResult",
|
||||
@@ -348,6 +386,12 @@ __all__ = [
|
||||
"ListeningSocketsMixin",
|
||||
"ListeningSocketsUnavailable",
|
||||
"parse_listening_sockets",
|
||||
"LLDPCTL_KEYVALUE_COMMAND",
|
||||
"LldpNeighborDict",
|
||||
"LldpNeighborRow",
|
||||
"lldp_neighbors",
|
||||
"lldp_neighbors_detail",
|
||||
"parse_lldpctl_keyvalue",
|
||||
"LocalAccountsMixin",
|
||||
"LocalAccountDict",
|
||||
"LocalAccountChangeDict",
|
||||
|
||||
@@ -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
|
||||
@@ -5,6 +5,8 @@ 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
|
||||
@@ -34,6 +36,9 @@ class ClusterStorageDict(TypedDict):
|
||||
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):
|
||||
|
||||
@@ -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"]
|
||||
@@ -28,9 +28,12 @@ APT_UPGRADABLE_COMMAND = "{ LC_ALL=C apt list --upgradable 2>/dev/null; echo __A
|
||||
|
||||
#: 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.
|
||||
#: 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 updateinfo list --security --quiet 2>/dev/null; echo __DNF_RC=$?; } | cat"
|
||||
"{ LC_ALL=C dnf --cacheonly updateinfo list --security --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]
|
||||
|
||||
@@ -15,7 +15,9 @@ accident.
|
||||
``/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.
|
||||
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.**
|
||||
|
||||
@@ -426,9 +428,16 @@ class OpenSshServerMixin:
|
||||
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.
|
||||
apply. Where that generated file still includes the drop-in directory, the
|
||||
driver sets :attr:`SSHD_CONFIG_GENERATED` instead and keeps the hardening.
|
||||
"""
|
||||
|
||||
#: 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(
|
||||
@@ -565,6 +574,13 @@ class OpenSshServerMixin:
|
||||
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,
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "4.23.0"
|
||||
version = "4.26.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""A backup server is a role of its own (NAPALM/napalm-device-types#82).
|
||||
|
||||
What makes a device a backup server -- datastores, the backup groups in them,
|
||||
the jobs that keep them (garbage collection, verify, prune, sync, tape) and the
|
||||
remotes it syncs with -- has no counterpart in ``StorageDriver``. A backup
|
||||
server that also manages its own disks lists ``StorageDriver`` as a second role.
|
||||
|
||||
The declarations sit under ``TYPE_CHECKING`` (see test_role_contracts), so the
|
||||
signatures are read from the source rather than from the class.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
from typing import NotRequired, get_args, get_type_hints
|
||||
|
||||
import pytest
|
||||
|
||||
import napalm_device_types.backup_server as backup_server_module
|
||||
from napalm_device_types import (
|
||||
BACKUP_JOB_KINDS,
|
||||
BackupDatastoreDict,
|
||||
BackupGroupDict,
|
||||
BackupRemoteDict,
|
||||
BackupServerDriver,
|
||||
BackupServerJobDict,
|
||||
BackupServerRefDict,
|
||||
BackupSnapshotDict,
|
||||
BackupSnapshotRefDict,
|
||||
BackupTaskDict,
|
||||
BackupTaskStatusDict,
|
||||
ClusterStorageDict,
|
||||
OSDriver,
|
||||
StorageDriver,
|
||||
)
|
||||
from napalm_device_types.backups import BackupJobKind, BackupRunState, BackupVerifyState
|
||||
from napalm_device_types.roles import primary_role_of, role_keys_of
|
||||
|
||||
|
||||
def _declared(name: str) -> ast.FunctionDef:
|
||||
tree = ast.parse(inspect.getsource(backup_server_module))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FunctionDef) and node.name == name:
|
||||
return node
|
||||
raise AssertionError(f"BackupServerDriver does not declare {name}()")
|
||||
|
||||
|
||||
def _signature(name: str) -> tuple[list[str], str]:
|
||||
fn = _declared(name)
|
||||
params = ast.unparse(fn.args).split(", ")[1:]
|
||||
return params, ast.unparse(fn.returns) if fn.returns else ""
|
||||
|
||||
|
||||
class TestRole:
|
||||
def test_role_key_and_label(self):
|
||||
assert vars(BackupServerDriver)["ROLE"] == "backup_server"
|
||||
assert BackupServerDriver.TYPE_LABEL == "Backup Server"
|
||||
|
||||
def test_backup_server_first_storage_second(self):
|
||||
"""A PBS manages its disks and ZFS pools too; that part is storage."""
|
||||
|
||||
class Pbs(BackupServerDriver, StorageDriver, OSDriver):
|
||||
pass
|
||||
|
||||
assert role_keys_of(Pbs) == ["backup_server", "storage", "linux"]
|
||||
assert primary_role_of(Pbs) == "backup_server"
|
||||
|
||||
|
||||
class TestDeclarations:
|
||||
@pytest.mark.parametrize(
|
||||
("name", "params", "returns"),
|
||||
[
|
||||
("get_backup_datastores", [], "list[BackupDatastoreDict]"),
|
||||
("get_backup_groups", ["datastore: str=''"], "list[BackupGroupDict]"),
|
||||
(
|
||||
"get_backup_snapshots",
|
||||
["datastore: str", "namespace: str", "group_type: str", "group_id: str"],
|
||||
"list[BackupSnapshotDict]",
|
||||
),
|
||||
("get_backup_jobs", [], "list[BackupServerJobDict]"),
|
||||
("get_backup_remotes", [], "list[BackupRemoteDict]"),
|
||||
("start_garbage_collection", ["datastore: str"], "BackupTaskDict"),
|
||||
("run_backup_job", ["kind: BackupJobKind", "job_id: str"], "BackupTaskDict"),
|
||||
("verify_backup_snapshot", ["snapshot: BackupSnapshotRefDict"], "BackupTaskDict"),
|
||||
(
|
||||
"set_backup_snapshot_protected",
|
||||
["snapshot: BackupSnapshotRefDict", "protected: bool"],
|
||||
"None",
|
||||
),
|
||||
("delete_backup_snapshot", ["snapshot: BackupSnapshotRefDict"], "None"),
|
||||
("get_backup_task", ["task: str"], "BackupTaskStatusDict"),
|
||||
],
|
||||
)
|
||||
def test_declared_with_its_signature(self, name, params, returns):
|
||||
got_params, got_returns = _signature(name)
|
||||
assert [p.replace(" ", "") for p in got_params] == [p.replace(" ", "") for p in params]
|
||||
assert got_returns == returns
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"get_backup_datastores",
|
||||
"get_backup_groups",
|
||||
"get_backup_snapshots",
|
||||
"get_backup_jobs",
|
||||
"get_backup_remotes",
|
||||
"start_garbage_collection",
|
||||
"run_backup_job",
|
||||
"verify_backup_snapshot",
|
||||
"set_backup_snapshot_protected",
|
||||
"delete_backup_snapshot",
|
||||
"get_backup_task",
|
||||
],
|
||||
)
|
||||
def test_absent_until_a_driver_implements_it(self, name):
|
||||
assert not hasattr(BackupServerDriver, name)
|
||||
|
||||
def test_every_declaration_has_a_docstring(self):
|
||||
tree = ast.parse(inspect.getsource(backup_server_module))
|
||||
missing = [
|
||||
n.name
|
||||
for n in ast.walk(tree)
|
||||
if isinstance(n, ast.FunctionDef) and not ast.get_docstring(n)
|
||||
]
|
||||
assert missing == []
|
||||
|
||||
|
||||
class TestShapes:
|
||||
"""Neutral names: nothing here is Proxmox's. A value the platform does not
|
||||
report is None; it is never guessed."""
|
||||
|
||||
def test_datastore(self):
|
||||
assert set(get_type_hints(BackupDatastoreDict)) == {
|
||||
"name",
|
||||
"path",
|
||||
"backend",
|
||||
"total",
|
||||
"used",
|
||||
"available",
|
||||
"estimated_full",
|
||||
"maintenance",
|
||||
"comment",
|
||||
}
|
||||
|
||||
def test_group_carries_its_newest_snapshot_not_all_of_them(self):
|
||||
assert set(get_type_hints(BackupGroupDict)) == {
|
||||
"datastore",
|
||||
"namespace",
|
||||
"type",
|
||||
"id",
|
||||
"owner",
|
||||
"count",
|
||||
"newest",
|
||||
"oldest_time",
|
||||
"comment",
|
||||
}
|
||||
assert get_type_hints(BackupGroupDict)["newest"] == BackupSnapshotDict | None
|
||||
|
||||
def test_snapshot(self):
|
||||
assert set(get_type_hints(BackupSnapshotDict)) == {
|
||||
"time",
|
||||
"size",
|
||||
"verify",
|
||||
"protected",
|
||||
"comment",
|
||||
}
|
||||
assert set(get_args(BackupVerifyState)) == {"ok", "failed"}
|
||||
|
||||
def test_snapshot_reference_names_one_snapshot(self):
|
||||
assert set(get_type_hints(BackupSnapshotRefDict)) == {
|
||||
"datastore",
|
||||
"namespace",
|
||||
"group_type",
|
||||
"group_id",
|
||||
"time",
|
||||
}
|
||||
|
||||
def test_job_kinds_include_garbage_collection(self):
|
||||
"""GC is a job with a schedule and a last run like the others, so it is
|
||||
listed with them rather than restated on the datastore."""
|
||||
assert set(get_args(BackupJobKind)) == {"gc", "verify", "prune", "sync", "tape"}
|
||||
assert set(BACKUP_JOB_KINDS) == set(get_args(BackupJobKind))
|
||||
|
||||
def test_job(self):
|
||||
assert set(get_type_hints(BackupServerJobDict)) == {
|
||||
"id",
|
||||
"kind",
|
||||
"datastore",
|
||||
"namespace",
|
||||
"schedule",
|
||||
"enabled",
|
||||
"last_run",
|
||||
"last_state",
|
||||
"last_error",
|
||||
"next_run",
|
||||
"remote",
|
||||
"direction",
|
||||
"comment",
|
||||
}
|
||||
assert set(get_args(BackupRunState)) == {"ok", "warning", "error", "running"}
|
||||
|
||||
def test_remote_never_carries_its_secret(self):
|
||||
fields = set(get_type_hints(BackupRemoteDict))
|
||||
assert fields == {"name", "host", "port", "fingerprint", "auth_id", "comment"}
|
||||
assert not fields & {"password", "secret", "token"}
|
||||
|
||||
def test_task(self):
|
||||
assert set(get_type_hints(BackupTaskDict)) == {"task"}
|
||||
assert set(get_type_hints(BackupTaskStatusDict)) == {
|
||||
"task",
|
||||
"running",
|
||||
"state",
|
||||
"error",
|
||||
"log",
|
||||
}
|
||||
|
||||
|
||||
class TestClusterStorageNamesItsBackupServer:
|
||||
"""A hypervisor's backup storage says which server and datastore it points
|
||||
at, so an application can tie the server's groups to the cluster's guests."""
|
||||
|
||||
def test_backup_server_reference_is_optional_on_a_storage(self):
|
||||
hints = get_type_hints(ClusterStorageDict, include_extras=True)
|
||||
assert hints["backup_server"] == NotRequired[BackupServerRefDict | None]
|
||||
|
||||
def test_reference(self):
|
||||
assert set(get_type_hints(BackupServerRefDict)) == {
|
||||
"server",
|
||||
"port",
|
||||
"datastore",
|
||||
"namespace",
|
||||
"fingerprint",
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import napalm_device_types.hypervisor as hypervisor_module
|
||||
from napalm_device_types import (
|
||||
BackupDict,
|
||||
BackupJobDict,
|
||||
BackupServerRefDict,
|
||||
ClusterDict,
|
||||
ClusterNetworkDict,
|
||||
ClusterNodeDict,
|
||||
@@ -92,7 +93,8 @@ class TestClusterShape:
|
||||
assert "votes" not in ClusterNodeDict.__required_keys__
|
||||
|
||||
def test_storage(self):
|
||||
assert get_type_hints(ClusterStorageDict) == {
|
||||
hints = get_type_hints(ClusterStorageDict, include_extras=True)
|
||||
assert hints == {
|
||||
"name": str,
|
||||
"type": str,
|
||||
"shared": bool,
|
||||
@@ -100,7 +102,10 @@ class TestClusterShape:
|
||||
"nodes": list[str],
|
||||
"total": int | None,
|
||||
"used": int | None,
|
||||
"backup_server": NotRequired[BackupServerRefDict | None],
|
||||
}
|
||||
# A driver written before backup servers were part of the report stays valid.
|
||||
assert "backup_server" not in ClusterStorageDict.__required_keys__
|
||||
|
||||
def test_network(self):
|
||||
hints = get_type_hints(ClusterNetworkDict, include_extras=True)
|
||||
|
||||
@@ -11,6 +11,7 @@ import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
AccessPointDriver,
|
||||
BackupServerDriver,
|
||||
EnsurePackageMixin,
|
||||
FirewallDriver,
|
||||
HypervisorDriver,
|
||||
@@ -28,7 +29,7 @@ from napalm_device_types import (
|
||||
)
|
||||
|
||||
ROLE_BASES = [
|
||||
AccessPointDriver, FirewallDriver, HypervisorDriver, ManagementControllerDriver, MediaDriver,
|
||||
AccessPointDriver, BackupServerDriver, FirewallDriver, HypervisorDriver, ManagementControllerDriver, MediaDriver,
|
||||
OSDriver, PhoneDriver, ResidentialGatewayDriver, StorageDriver, SwitchDriver,
|
||||
] # fmt: skip
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""LLDP rows projected into NAPALM's ``get_lldp_neighbors`` and ``get_lldp_neighbors_detail``.
|
||||
|
||||
A driver reads its neighbours into :class:`LldpNeighborRow` (from ``lldpctl``,
|
||||
an API, a CLI) and the two NAPALM shapes come from those rows the same way for
|
||||
every driver (NAPALM/napalm-device-types#10).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import get_type_hints
|
||||
|
||||
from napalm_device_types import LldpNeighborRow, lldp_neighbors, lldp_neighbors_detail
|
||||
|
||||
|
||||
def _row(local_port: str, name: str, **fields: object) -> LldpNeighborRow:
|
||||
row: LldpNeighborRow = {
|
||||
"local_port": local_port,
|
||||
"chassis_id": "",
|
||||
"chassis_id_type": "",
|
||||
"port_id": "",
|
||||
"port_id_type": "",
|
||||
"port_description": "",
|
||||
"system_name": name,
|
||||
"system_description": "",
|
||||
"management_addresses": [],
|
||||
"capabilities": [],
|
||||
"enabled_capabilities": [],
|
||||
}
|
||||
row.update(fields) # type: ignore[typeddict-item]
|
||||
return row
|
||||
|
||||
|
||||
PHONE = _row(
|
||||
"eth0.1",
|
||||
"desk-phone",
|
||||
chassis_id="00:11:22:33:44:AB",
|
||||
chassis_id_type="mac",
|
||||
port_id="00:11:22:33:44:01",
|
||||
port_id_type="mac",
|
||||
port_description="WAN",
|
||||
system_description="SIP phone",
|
||||
capabilities=["bridge", "telephone"],
|
||||
enabled_capabilities=["telephone"],
|
||||
)
|
||||
PC = _row("eth0.1", "desk-pc", port_id="eno1", port_id_type="ifname")
|
||||
SWITCH = _row("eth1", "access-sw", port_id="gi1/0/7", port_id_type="local")
|
||||
|
||||
|
||||
def test_a_row_names_its_fields():
|
||||
assert set(get_type_hints(LldpNeighborRow)) == {
|
||||
"local_port",
|
||||
"chassis_id",
|
||||
"chassis_id_type",
|
||||
"port_id",
|
||||
"port_id_type",
|
||||
"port_description",
|
||||
"system_name",
|
||||
"system_description",
|
||||
"management_addresses",
|
||||
"capabilities",
|
||||
"enabled_capabilities",
|
||||
}
|
||||
|
||||
|
||||
class TestNeighbors:
|
||||
def test_every_neighbour_of_a_port_is_listed(self):
|
||||
assert lldp_neighbors([PHONE, PC, SWITCH]) == {
|
||||
"eth0.1": [
|
||||
{"hostname": "desk-phone", "port": "00:11:22:33:44:01", "mac": "00:11:22:33:44:ab"},
|
||||
{"hostname": "desk-pc", "port": "eno1"},
|
||||
],
|
||||
"eth1": [{"hostname": "access-sw", "port": "gi1/0/7"}],
|
||||
}
|
||||
|
||||
def test_no_rows_is_no_neighbour(self):
|
||||
assert lldp_neighbors([]) == {}
|
||||
|
||||
def test_a_chassis_mac_is_reported_in_lower_case(self):
|
||||
# netOrk matches a neighbour by this MAC first (NAPALM/napalm-openwrt#31).
|
||||
assert lldp_neighbors([PHONE])["eth0.1"][0]["mac"] == "00:11:22:33:44:ab"
|
||||
|
||||
def test_a_chassis_named_otherwise_has_no_mac(self):
|
||||
switch = _row("eth1", "sw", chassis_id="00:11:22:33:44:55", chassis_id_type="local")
|
||||
|
||||
assert "mac" not in lldp_neighbors([switch])["eth1"][0]
|
||||
|
||||
def test_a_mac_id_that_is_no_mac_address_is_left_out(self):
|
||||
odd = _row("eth1", "sw", chassis_id="00:11", chassis_id_type="mac")
|
||||
|
||||
assert "mac" not in lldp_neighbors([odd])["eth1"][0]
|
||||
|
||||
|
||||
class TestNeighborsDetail:
|
||||
def test_every_field_napalm_names(self):
|
||||
assert lldp_neighbors_detail([PHONE]) == {
|
||||
"eth0.1": [
|
||||
{
|
||||
"parent_interface": "",
|
||||
"remote_port": "00:11:22:33:44:01",
|
||||
"remote_port_description": "WAN",
|
||||
"remote_chassis_id": "00:11:22:33:44:AB",
|
||||
"remote_system_name": "desk-phone",
|
||||
"remote_system_description": "SIP phone",
|
||||
"remote_system_capab": ["bridge", "telephone"],
|
||||
"remote_system_enable_capab": ["telephone"],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
def test_every_neighbour_of_a_port_is_listed(self):
|
||||
detail = lldp_neighbors_detail([PHONE, PC, SWITCH])
|
||||
|
||||
assert [n["remote_system_name"] for n in detail["eth0.1"]] == ["desk-phone", "desk-pc"]
|
||||
assert [n["remote_system_name"] for n in detail["eth1"]] == ["access-sw"]
|
||||
|
||||
def test_one_interface_only(self):
|
||||
assert list(lldp_neighbors_detail([PHONE, PC, SWITCH], "eth1")) == ["eth1"]
|
||||
|
||||
def test_an_interface_without_neighbours_is_empty(self):
|
||||
assert lldp_neighbors_detail([PHONE], "eth9") == {}
|
||||
|
||||
def test_the_lists_are_the_rows_own_copies(self):
|
||||
detail = lldp_neighbors_detail([PHONE])
|
||||
|
||||
detail["eth0.1"][0]["remote_system_capab"].append("router")
|
||||
|
||||
assert PHONE["capabilities"] == ["bridge", "telephone"]
|
||||
@@ -0,0 +1,308 @@
|
||||
"""``lldpctl -f keyvalue``: one row per LLDP neighbour, for every driver that reads lldpd.
|
||||
|
||||
napalm-linux, napalm-openwrt and napalm-proxmox each parsed this output on their
|
||||
own, and each copy grouped the lines by interface, so two neighbours on one port
|
||||
merged (NAPALM/napalm-openwrt#9, NAPALM/napalm-linux#58), split ``eth0.1`` at its
|
||||
dot (NAPALM/napalm-openwrt#26) and looked for ``chassis.id.value``, a key lldpd
|
||||
never prints. The parse lives here once now.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND, parse_lldpctl_keyvalue
|
||||
|
||||
# The recording napalm-openwrt's tests have used since the driver was written
|
||||
# (tests/unit/test_driver.py, ``LLDPCTL_KV``): one neighbour on eth0. Its two
|
||||
# ``chassis.cap.*`` lines are not lldpd's format (lldpd prints one
|
||||
# ``chassis.<Capability>.enabled=on|off`` line per capability), so they yield none.
|
||||
OPENWRT_ONE_NEIGHBOUR = """\
|
||||
lldp.eth0.via=LLDP
|
||||
lldp.eth0.rid=1
|
||||
lldp.eth0.age=0 day, 01:23:45
|
||||
lldp.eth0.chassis.mac=00:aa:bb:cc:dd:ee
|
||||
lldp.eth0.chassis.name=core-router
|
||||
lldp.eth0.chassis.descr=RouterOS 7.x
|
||||
lldp.eth0.chassis.mgmt-ip=10.0.0.1
|
||||
lldp.eth0.chassis.cap.available=Router, Bridge
|
||||
lldp.eth0.chassis.cap.enabled=Router
|
||||
lldp.eth0.port.ifname=ether1
|
||||
lldp.eth0.port.descr=uplink
|
||||
"""
|
||||
|
||||
# Laid out the way lldpd 1.0's keyvalue writer prints ``show neighbors details``
|
||||
# (src/client/display.c ``display_interface``, ``display_chassis``,
|
||||
# ``display_port``, ``display_vlans``, ``display_med``; src/client/kv_writer.c):
|
||||
# a neighbour opens with the local interface's optional ``alias`` and ``via``,
|
||||
# an id is printed under its type (``chassis.mac``, ``port.local``), a
|
||||
# capability as ``chassis.<Symbol>.enabled``, a management address once per
|
||||
# address. Not recorded from a device.
|
||||
#
|
||||
# On ``eth0.1`` (a VLAN interface, its name holds a dot) a phone and a PC behind
|
||||
# an unmanaged switch; on ``eth1`` a switch that names its port by a local id and
|
||||
# itself by an address.
|
||||
TWO_ON_ONE_DOTTED_PORT = """\
|
||||
lldp.eth0.1.alias=desk
|
||||
lldp.eth0.1.via=LLDP
|
||||
lldp.eth0.1.rid=1
|
||||
lldp.eth0.1.age=0 day, 00:10:00
|
||||
lldp.eth0.1.chassis.mac=00:11:22:33:44:01
|
||||
lldp.eth0.1.chassis.name=desk-phone
|
||||
lldp.eth0.1.chassis.descr=SIP phone, firmware a=1
|
||||
lldp.eth0.1.chassis.mgmt-ip=10.0.0.21
|
||||
lldp.eth0.1.chassis.mgmt-iface=2
|
||||
lldp.eth0.1.chassis.mgmt-ip=fe80::211:22ff:fe33:4401
|
||||
lldp.eth0.1.chassis.mgmt-iface=2
|
||||
lldp.eth0.1.chassis.Bridge.enabled=off
|
||||
lldp.eth0.1.chassis.Tel.enabled=on
|
||||
lldp.eth0.1.port.mac=00:11:22:33:44:01
|
||||
lldp.eth0.1.port.descr=WAN
|
||||
lldp.eth0.1.port.ttl=120
|
||||
lldp.eth0.1.port.auto-negotiation.supported=yes
|
||||
lldp.eth0.1.port.auto-negotiation.enabled=yes
|
||||
lldp.eth0.1.port.auto-negotiation.100Base-TX.hd=yes
|
||||
lldp.eth0.1.port.auto-negotiation.100Base-TX.fd=yes
|
||||
lldp.eth0.1.port.auto-negotiation.current=100BaseTXFD - 2 pair category 5 UTP, full duplex mode
|
||||
lldp.eth0.1.vlan.vlan-id=10
|
||||
lldp.eth0.1.vlan.pvid=yes
|
||||
lldp.eth0.1.vlan=voice
|
||||
lldp.eth0.1.lldp-med.device-type=Communication Device Endpoint (Class III)
|
||||
lldp.eth0.1.lldp-med.Capabilities.available=yes
|
||||
lldp.eth0.1.lldp-med.inventory.software=2.1.4
|
||||
lldp.eth0.1.alias=desk
|
||||
lldp.eth0.1.via=LLDP
|
||||
lldp.eth0.1.rid=2
|
||||
lldp.eth0.1.age=0 day, 00:09:00
|
||||
lldp.eth0.1.chassis.mac=00:11:22:33:44:02
|
||||
lldp.eth0.1.chassis.name=desk-pc
|
||||
lldp.eth0.1.chassis.descr=Debian GNU/Linux 12 (bookworm) Linux 6.1.0-25-amd64
|
||||
lldp.eth0.1.chassis.Bridge.enabled=off
|
||||
lldp.eth0.1.chassis.Router.enabled=off
|
||||
lldp.eth0.1.chassis.Wlan.enabled=off
|
||||
lldp.eth0.1.chassis.Station.enabled=on
|
||||
lldp.eth0.1.port.ifname=eno1
|
||||
lldp.eth0.1.port.ttl=120
|
||||
lldp.eth0.1.unknown-tlvs.unknown-tlv.oui=00,80,C2
|
||||
lldp.eth0.1.unknown-tlvs.unknown-tlv.subtype=9
|
||||
lldp.eth0.1.unknown-tlvs.unknown-tlv.len=1
|
||||
lldp.eth0.1.unknown-tlvs.unknown-tlv=01
|
||||
lldp.eth1.via=LLDP
|
||||
lldp.eth1.rid=3
|
||||
lldp.eth1.age=1 day, 02:00:00
|
||||
lldp.eth1.chassis.ip=192.0.2.7
|
||||
lldp.eth1.chassis.name=access-sw
|
||||
lldp.eth1.chassis.Bridge.enabled=on
|
||||
lldp.eth1.chassis.Router.enabled=off
|
||||
lldp.eth1.chassis.CVLAN.enabled=on
|
||||
lldp.eth1.port.local=gi1/0/7
|
||||
lldp.eth1.port.descr=GigabitEthernet1/0/7
|
||||
lldp.eth1.ppvid.supported=no
|
||||
lldp.eth1.ppvid.enabled=no
|
||||
lldp.eth1.pi=88cc
|
||||
"""
|
||||
|
||||
|
||||
def _rows(output: str = TWO_ON_ONE_DOTTED_PORT) -> list[dict[str, object]]:
|
||||
return [dict(row) for row in parse_lldpctl_keyvalue(output)]
|
||||
|
||||
|
||||
class TestOneRowPerNeighbour:
|
||||
def test_the_openwrt_recording_is_one_neighbour_with_its_fields(self):
|
||||
assert _rows(OPENWRT_ONE_NEIGHBOUR) == [
|
||||
{
|
||||
"local_port": "eth0",
|
||||
"chassis_id": "00:aa:bb:cc:dd:ee",
|
||||
"chassis_id_type": "mac",
|
||||
"port_id": "ether1",
|
||||
"port_id_type": "ifname",
|
||||
"port_description": "uplink",
|
||||
"system_name": "core-router",
|
||||
"system_description": "RouterOS 7.x",
|
||||
"management_addresses": ["10.0.0.1"],
|
||||
"capabilities": [],
|
||||
"enabled_capabilities": [],
|
||||
}
|
||||
]
|
||||
|
||||
def test_two_neighbours_on_one_port_stay_apart(self):
|
||||
rows = _rows()
|
||||
|
||||
assert [(r["local_port"], r["system_name"]) for r in rows] == [
|
||||
("eth0.1", "desk-phone"),
|
||||
("eth0.1", "desk-pc"),
|
||||
("eth1", "access-sw"),
|
||||
]
|
||||
|
||||
def test_a_neighbour_keeps_only_its_own_fields(self):
|
||||
pc = _rows()[1]
|
||||
|
||||
assert pc["chassis_id"] == "00:11:22:33:44:02"
|
||||
assert pc["port_description"] == ""
|
||||
assert pc["management_addresses"] == []
|
||||
|
||||
def test_neighbours_without_alias_are_split_at_via(self):
|
||||
output = OPENWRT_ONE_NEIGHBOUR + OPENWRT_ONE_NEIGHBOUR.replace("core-router", "edge")
|
||||
|
||||
assert [r["system_name"] for r in _rows(output)] == ["core-router", "edge"]
|
||||
|
||||
|
||||
class TestInterfaceName:
|
||||
def test_a_dotted_interface_name_survives(self):
|
||||
assert {r["local_port"] for r in _rows()} == {"eth0.1", "eth1"}
|
||||
|
||||
def test_an_interface_named_like_a_field_survives(self):
|
||||
output = (
|
||||
"lldp.vlan.100.via=LLDP\n"
|
||||
"lldp.vlan.100.chassis.mac=00:aa:bb:cc:dd:01\n"
|
||||
"lldp.vlan.100.port.ifname=port1\n"
|
||||
)
|
||||
|
||||
(row,) = _rows(output)
|
||||
|
||||
assert (row["local_port"], row["chassis_id"], row["port_id"]) == (
|
||||
"vlan.100",
|
||||
"00:aa:bb:cc:dd:01",
|
||||
"port1",
|
||||
)
|
||||
|
||||
def test_without_via_the_name_ends_at_the_first_field(self):
|
||||
output = "lldp.br-lan.10.chassis.name=sw\nlldp.br-lan.10.port.ifname=1\n"
|
||||
|
||||
(row,) = _rows(output)
|
||||
|
||||
assert (row["local_port"], row["system_name"], row["port_id"]) == ("br-lan.10", "sw", "1")
|
||||
|
||||
|
||||
class TestIds:
|
||||
def test_a_port_given_by_its_mac_is_read(self):
|
||||
phone = _rows()[0]
|
||||
|
||||
assert (phone["port_id"], phone["port_id_type"]) == ("00:11:22:33:44:01", "mac")
|
||||
|
||||
def test_a_port_given_by_a_local_id_is_read(self):
|
||||
switch = _rows()[2]
|
||||
|
||||
assert (switch["port_id"], switch["port_id_type"]) == ("gi1/0/7", "local")
|
||||
|
||||
def test_a_chassis_given_by_its_address_is_read(self):
|
||||
switch = _rows()[2]
|
||||
|
||||
assert (switch["chassis_id"], switch["chassis_id_type"]) == ("192.0.2.7", "ip")
|
||||
|
||||
@pytest.mark.parametrize("kind", ["local", "ifname", "ifalias", "unhandled"])
|
||||
def test_every_id_type_lldpd_names_is_read(self, kind):
|
||||
output = f"lldp.eth0.via=LLDP\nlldp.eth0.chassis.{kind}=c1\nlldp.eth0.port.{kind}=p1\n"
|
||||
|
||||
(row,) = _rows(output)
|
||||
|
||||
assert (row["chassis_id"], row["chassis_id_type"]) == ("c1", kind)
|
||||
assert (row["port_id"], row["port_id_type"]) == ("p1", kind)
|
||||
|
||||
def test_a_neighbour_without_ids_has_empty_ones(self):
|
||||
(row,) = _rows("lldp.eth0.via=CDPv2\nlldp.eth0.chassis.name=sw\n")
|
||||
|
||||
assert (row["chassis_id"], row["chassis_id_type"]) == ("", "")
|
||||
assert (row["port_id"], row["port_id_type"]) == ("", "")
|
||||
|
||||
|
||||
class TestOtherFields:
|
||||
def test_every_management_address_is_kept(self):
|
||||
phone = _rows()[0]
|
||||
|
||||
assert phone["management_addresses"] == ["10.0.0.21", "fe80::211:22ff:fe33:4401"]
|
||||
|
||||
def test_a_value_may_hold_an_equals_sign(self):
|
||||
assert _rows()[0]["system_description"] == "SIP phone, firmware a=1"
|
||||
|
||||
def test_capabilities_in_napalm_names_and_which_are_enabled(self):
|
||||
phone, pc, switch = _rows()
|
||||
|
||||
assert phone["capabilities"] == ["bridge", "telephone"]
|
||||
assert phone["enabled_capabilities"] == ["telephone"]
|
||||
assert pc["capabilities"] == ["bridge", "router", "wlan-access-point", "station"]
|
||||
assert pc["enabled_capabilities"] == ["station"]
|
||||
assert switch["capabilities"] == ["bridge", "router", "cvlan"]
|
||||
assert switch["enabled_capabilities"] == ["bridge", "cvlan"]
|
||||
|
||||
def test_every_napalm_capability_name(self):
|
||||
symbols = ["Other", "Repeater", "Bridge", "Router", "Wlan", "Tel", "Docsis", "Station"]
|
||||
output = "lldp.eth0.via=LLDP\n" + "".join(
|
||||
f"lldp.eth0.chassis.{s}.enabled=on\n" for s in symbols
|
||||
)
|
||||
|
||||
(row,) = _rows(output)
|
||||
|
||||
assert row["capabilities"] == [
|
||||
"other",
|
||||
"repeater",
|
||||
"bridge",
|
||||
"router",
|
||||
"wlan-access-point",
|
||||
"telephone",
|
||||
"docsis-cable-device",
|
||||
"station",
|
||||
]
|
||||
assert row["enabled_capabilities"] == row["capabilities"]
|
||||
|
||||
def test_a_capability_line_needs_on_or_off(self):
|
||||
(row,) = _rows(OPENWRT_ONE_NEIGHBOUR)
|
||||
|
||||
assert row["capabilities"] == []
|
||||
|
||||
|
||||
class TestReadOrFailure:
|
||||
"""A failed read raises; ``[]`` only when lldpctl ran and listed nobody."""
|
||||
|
||||
def test_no_output_is_no_neighbour(self):
|
||||
assert parse_lldpctl_keyvalue("") == []
|
||||
|
||||
def test_a_zero_exit_status_without_neighbours_is_no_neighbour(self):
|
||||
assert parse_lldpctl_keyvalue("__LLDPCTL_RC=0\n") == []
|
||||
|
||||
def test_a_missing_lldpctl_raises(self):
|
||||
with pytest.raises(ValueError, match="lldpctl: not found"):
|
||||
parse_lldpctl_keyvalue("sh: lldpctl: not found\n")
|
||||
|
||||
def test_a_non_zero_exit_status_raises_with_what_lldpctl_said(self):
|
||||
output = (
|
||||
"[WARN/control] unable to connect to socket /var/run/lldpd.socket: "
|
||||
"No such file or directory\n"
|
||||
"__LLDPCTL_RC=1\n"
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="unable to connect to socket"):
|
||||
parse_lldpctl_keyvalue(output)
|
||||
|
||||
def test_a_non_zero_exit_status_without_a_message_names_the_status(self):
|
||||
with pytest.raises(ValueError, match="exit status 127"):
|
||||
parse_lldpctl_keyvalue("__LLDPCTL_RC=127\n")
|
||||
|
||||
def test_with_status_zero_a_warning_beside_the_neighbours_is_ignored(self):
|
||||
output = (
|
||||
"lldpctl -f keyvalue 2>&1; echo __LLDPCTL_RC=$?\n"
|
||||
"[WARN/lldpctl] something lldpd wants to say\n"
|
||||
+ OPENWRT_ONE_NEIGHBOUR
|
||||
+ "__LLDPCTL_RC=0\n"
|
||||
)
|
||||
|
||||
assert [r["system_name"] for r in _rows(output)] == ["core-router"]
|
||||
|
||||
def test_a_line_outside_lldp_is_no_neighbour(self):
|
||||
output = "lldpd.config.tx-delay=30\n" + OPENWRT_ONE_NEIGHBOUR
|
||||
|
||||
assert len(_rows(output)) == 1
|
||||
|
||||
def test_a_key_without_a_known_field_is_skipped(self):
|
||||
output = "lldp.summary=1\nlldp.eth9.future-field=x\n" + OPENWRT_ONE_NEIGHBOUR
|
||||
|
||||
assert [r["local_port"] for r in _rows(output)] == ["eth0"]
|
||||
|
||||
|
||||
class TestCommand:
|
||||
def test_the_command_reads_the_neighbours_in_keyvalue_form(self):
|
||||
assert LLDPCTL_KEYVALUE_COMMAND.startswith("lldpctl -f keyvalue ")
|
||||
|
||||
def test_the_command_brings_back_the_error_text_and_the_exit_status(self):
|
||||
assert "2>&1" in LLDPCTL_KEYVALUE_COMMAND
|
||||
assert LLDPCTL_KEYVALUE_COMMAND.endswith("echo __LLDPCTL_RC=$?")
|
||||
@@ -176,6 +176,18 @@ __DNF_RC=0
|
||||
with pytest.raises(ValueError, match="exit status 1"):
|
||||
parse_dnf_security(out)
|
||||
|
||||
def test_the_command_reads_only_the_cached_metadata(self, tmp_path):
|
||||
"""An expired cache made dnf download the repositories' metadata inside the
|
||||
poll, which outlasted its whole budget (#76)."""
|
||||
args = tmp_path / "args"
|
||||
dnf = tmp_path / "dnf"
|
||||
dnf.write_text(f"#!/bin/sh\nprintf '%s\\n' \"$@\" > {args}\n")
|
||||
dnf.chmod(0o755)
|
||||
env = {"PATH": f"{tmp_path}:{os.environ.get('PATH', '/usr/bin:/bin')}"}
|
||||
subprocess.run(["sh", "-c", DNF_SECURITY_COMMAND], capture_output=True, env=env)
|
||||
|
||||
assert "--cacheonly" in args.read_text().split()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("nevra", "name"),
|
||||
[
|
||||
|
||||
@@ -18,6 +18,7 @@ import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
AccessPointDriver,
|
||||
BackupServerDriver,
|
||||
DeviceTypeDriver,
|
||||
FirewallDriver,
|
||||
HypervisorDriver,
|
||||
@@ -33,6 +34,7 @@ from napalm_device_types.roles import primary_role_of, roles_of
|
||||
|
||||
ROLE_BASES = [
|
||||
AccessPointDriver,
|
||||
BackupServerDriver,
|
||||
FirewallDriver,
|
||||
HypervisorDriver,
|
||||
ManagementControllerDriver,
|
||||
@@ -75,6 +77,8 @@ class TestDeclaredMethodsDoNotExistAtRuntime:
|
||||
@pytest.mark.parametrize(
|
||||
("base", "method"),
|
||||
[
|
||||
(BackupServerDriver, "get_backup_datastores"),
|
||||
(BackupServerDriver, "run_backup_job"),
|
||||
(StorageDriver, "get_disks"),
|
||||
(StorageDriver, "get_volumes"),
|
||||
(HypervisorDriver, "get_vms"),
|
||||
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
|
||||
from napalm_device_types.channel import CommandResult
|
||||
from napalm_device_types.ssh_server import (
|
||||
DROPIN_DIR,
|
||||
DROPIN_PATH,
|
||||
MAIN_CONFIG,
|
||||
OpenSshServerMixin,
|
||||
@@ -401,6 +402,32 @@ def test_mixin_falls_back_to_sshd_config_without_an_include():
|
||||
assert host._effective()["mac"] == ["hmac-sha2-256"]
|
||||
|
||||
|
||||
class GeneratedConfigHost(FakeHost):
|
||||
"""A platform that writes sshd_config from its own database (OpenMediaVault)."""
|
||||
|
||||
SSHD_CONFIG_GENERATED = True
|
||||
|
||||
|
||||
def test_generated_sshd_config_still_gets_the_dropin():
|
||||
host = GeneratedConfigHost()
|
||||
result = host.harden_ssh_server({"mac": ["hmac-sha1"]})
|
||||
assert result.applied
|
||||
assert result.path == DROPIN_PATH
|
||||
assert host.files[MAIN_CONFIG] == "Include /etc/ssh/sshd_config.d/*.conf\nPort 22\n"
|
||||
|
||||
|
||||
def test_generated_sshd_config_without_an_include_is_left_alone():
|
||||
"""The platform would write its own file over the change on its next apply."""
|
||||
host = GeneratedConfigHost(main="Port 22\nMACs hmac-sha1,hmac-sha2-256\n")
|
||||
result = host.harden_ssh_server({"mac": ["hmac-sha1"]})
|
||||
assert not result.applied and not result.rolled_back
|
||||
assert result.path is None
|
||||
assert host.files[MAIN_CONFIG] == "Port 22\nMACs hmac-sha1,hmac-sha2-256\n"
|
||||
assert list(host.files) == [MAIN_CONFIG]
|
||||
assert host.reloads == 0
|
||||
assert DROPIN_DIR in result.message
|
||||
|
||||
|
||||
def test_mixin_restores_when_sshd_rejects_the_config():
|
||||
host = FakeHost()
|
||||
host.syntax_ok = False
|
||||
|
||||
@@ -4,6 +4,7 @@ import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
AccessPointDriver,
|
||||
BackupServerDriver,
|
||||
FirewallDriver,
|
||||
HypervisorDriver,
|
||||
ManagementControllerDriver,
|
||||
@@ -15,6 +16,7 @@ from napalm_device_types import (
|
||||
|
||||
BASE_CLASSES = [
|
||||
(AccessPointDriver, "Access Point"),
|
||||
(BackupServerDriver, "Backup Server"),
|
||||
(FirewallDriver, "Firewall"),
|
||||
(HypervisorDriver, "Hypervisor"),
|
||||
(ManagementControllerDriver, "Management Controller"),
|
||||
|
||||
Reference in new issue
Block a user