Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e300c740e | ||
|
|
0598a183df | ||
|
|
b6bb13009f | ||
|
|
59839b4efa | ||
|
|
c0453655b7 | ||
|
|
dc0d6345a8 | ||
|
|
f9088bae3a | ||
|
|
ca44e4405d | ||
|
|
b37672a269 | ||
|
|
bc5127b80f | ||
|
|
24089412a7 | ||
|
|
63ffc64050 | ||
|
|
4b423220bf | ||
|
|
b792f6d210 | ||
|
|
75818c3f09 | ||
|
|
1db3fb329f | ||
|
|
ff4ccc4818 | ||
|
|
fddf8af680 | ||
|
|
c2d9d7e75e | ||
|
|
685e995073 | ||
|
|
370aeed482 | ||
|
|
bc3eb86723 | ||
|
|
8159566ff4 | ||
|
|
b80a3950ac | ||
|
|
cae4859383 | ||
|
|
ad3b5b29a9 | ||
|
|
326527ddd5 | ||
|
|
f071c10cd1 | ||
|
|
93c974b8f0 |
No files matched your search
+133
@@ -7,7 +7,136 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.19.0] - 2026-11-28
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
- `install_cpu_microcode()` on both drivers (napalm-device-types' `CpuMicrocodeMixin`, 4.53.0,
|
||||||
|
NetOrk/netork#2838): the CPU vendor's microcode on a node that runs on its own CPU. A Proxmox
|
||||||
|
install enables no `non-free-firmware`, where Debian keeps `intel-microcode` and
|
||||||
|
`amd64-microcode`: it is added to Debian's own sources (never to Proxmox's or another
|
||||||
|
vendor's), the index is loaded with `apt-get update` over the exec path -- waited for, unlike
|
||||||
|
the API's refresh task -- and the package installed. Refused on a node that runs virtualized
|
||||||
|
(a PBS in a VM): its host loads the microcode. The microcode loads at the next boot.
|
||||||
|
- The hardening reading carries `virtualization` and `cpu_vendor` (napalm-device-types 4.53.0).
|
||||||
|
|
||||||
|
## [0.18.0] - 2026-11-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_pve_firewall()` on the PVE driver (NetOrk/netork#2654): the PVE firewall as the operator
|
||||||
|
wrote it, read only -- the datacenter's options, rules, security groups, IP sets and aliases,
|
||||||
|
this node's options and rules, and every guest's on this node with which of its NICs carry
|
||||||
|
`firewall=1`. Each rule keeps PVE's own fields and says where it came from. A part PVE refuses
|
||||||
|
is None, not empty: an unread level is no claim. Nothing is written; pve-firewall rules stay
|
||||||
|
the operator's.
|
||||||
|
- `get_host_firewall()` on the PVE driver (napalm-device-types' `HostFirewallMixin`): what the
|
||||||
|
node has loaded -- proxmox-firewall's nftables tables on PVE 9, pve-firewall's iptables chains
|
||||||
|
before -- read as root over SSH, as for any Linux host.
|
||||||
|
- `get_hardening()` on both drivers (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776):
|
||||||
|
the security modules, SELinux and AppArmor, the crypto policy and FIPS mode, what the kernel
|
||||||
|
reports for each CPU vulnerability, and the kernel command line (`mitigations=`, `nosmt`). One
|
||||||
|
fixed, read-only command over the exec path, which is root's login, so AppArmor's profiles per
|
||||||
|
mode are read too. A hypervisor's guests share its CPU, so its CPU vulnerabilities matter most.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Needs napalm-device-types 4.48.0 or later (`HardeningMixin`).
|
||||||
|
|
||||||
|
## [0.16.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_services_need_restart()` on both drivers (napalm-device-types' `ServicesRestartMixin`,
|
||||||
|
NetOrk/netork#2750): the services that still run code an update replaced on disk, so they
|
||||||
|
keep the old library until they restart. One fixed, read-only command over the exec path,
|
||||||
|
which is root's login: `needs-restarting -s`, else `needrestart` in list-only mode, else the
|
||||||
|
processes whose `/proc/<pid>/maps` maps deleted code, each named by its cgroup's service. A
|
||||||
|
running VM's QEMU (`qemu.slice`) is listed as a process; an LXC container's processes are
|
||||||
|
left out, since a container updates itself. It runs only when the login is root
|
||||||
|
(`id -u` is 0): another login gets no report and the read raises, rather than read as
|
||||||
|
clean what it cannot see. No stdin.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Needs napalm-device-types 4.46.0 or later (`ServicesRestartMixin`, with an LXC
|
||||||
|
container's processes left out).
|
||||||
|
|
||||||
|
## [0.15.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_certificates()` on both drivers (NetOrk/netork#2656): the node's TLS certificates from
|
||||||
|
`GET /nodes/{node}/certificates/info` (PBS: `/nodes/localhost/certificates/info`) in
|
||||||
|
netOrk's certificate contract, `{name, issuer, valid_from, valid_to, in_use_by}` with Unix
|
||||||
|
timestamps, so netOrk's expiry warnings cover a node's web UI and API certificate.
|
||||||
|
`name` is the file name (`pve-root-ca.pem`, `pve-ssl.pem`, `pveproxy-ssl.pem`; `proxy.pem` on
|
||||||
|
PBS), `issuer` and `subject` the common names, `in_use_by` 1 for the certificate the proxy
|
||||||
|
serves. `acme` is true for the certificate ACME renews (`pveproxy-ssl.pem`, PBS `proxy.pem`)
|
||||||
|
when the node's config names a domain, read with one more call (`GET /nodes/{node}/config`);
|
||||||
|
an unreadable config reads as no ACME. The PEM is not returned. Unreadable certificates are
|
||||||
|
`[]`, as on OPNsense.
|
||||||
|
|
||||||
|
## [0.14.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Proxmox VE 9.3's API additions (NetOrk/netork#2728), each taken only on a node whose
|
||||||
|
`GET /version` says 9.3 or later (`_version_at_least`); an older node does what it did.
|
||||||
|
- `get_vms()`: each guest carries PVE 9.3's `uid`, an identity that survives a migration, a
|
||||||
|
restore and a changed vmid, from one `GET /cluster/resources?type=vm` per call, joined by
|
||||||
|
node and vmid (napalm-device-types `VMDict.uid`). A guest without one, an older node and a
|
||||||
|
listing that cannot be read leave the key out; the guests are listed as before.
|
||||||
|
- `get_clusters()`: `id` is the cluster's `cluster-id` from `GET /cluster/status`, or a
|
||||||
|
standalone node's own on its node entry; None on an older node.
|
||||||
|
- `get_credential_expiry()` (napalm-device-types `CredentialExpiryMixin`): the API token
|
||||||
|
(`GET /access/users/{userid}/token/{tokenid}`) or the password's account
|
||||||
|
(`GET /access/users/{userid}`) the driver logged in with, and when it expires; a token
|
||||||
|
without an `expire` of its own expires with its user. A 403 is a `PermissionError`, any
|
||||||
|
other failure a `RuntimeError`.
|
||||||
|
- `get_update_history(since)` (napalm-device-types `UpdateMixin`): the node's APT
|
||||||
|
transactions from `GET /nodes/{node}/apt/history`, newest first, with `id`
|
||||||
|
`"{start-time}-{start-index}"`. A failed read raises; before 9.3 it is
|
||||||
|
`NotImplementedError` (no log is parsed over SSH).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `set_node_maintenance()` uses `PUT /nodes/{node}/maintenance` when the node going into
|
||||||
|
maintenance runs PVE 9.3, and opens no SSH session; that node's own version decides,
|
||||||
|
since a rolling upgrade leaves the members on different releases. An older node still
|
||||||
|
takes `ha-manager crm-command node-maintenance` over SSH.
|
||||||
|
- `resume_vm()` sets the guest's clock to the host's time on PVE 9.3
|
||||||
|
(`sync-time-on-resume=1`, through the guest agent where it runs).
|
||||||
|
- Needs napalm-device-types 4.44.0 or later (`CredentialExpiryMixin`, `UpdateHistoryDict`,
|
||||||
|
`VMDict.uid`).
|
||||||
|
|
||||||
|
## [0.13.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run
|
||||||
|
(`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`,
|
||||||
|
NetOrk/netork#2693). ufw does not say who wrote a rule, so every rule the firewall step
|
||||||
|
adds -- the Zabbix agent's tcp/`listen_port`, SNMP's udp/161 -- is now recorded in
|
||||||
|
`/var/lib/netork/opened-ports` (napalm-device-types `opened_ports`), and only when ufw did
|
||||||
|
not have it before: an identical rule the operator wrote is never recorded. Closing removes
|
||||||
|
exactly the agent's recorded rules, whatever port they opened, and rewrites the record. It
|
||||||
|
reads the record only when it is root's alone, and reports the rules for the port it left
|
||||||
|
in place: the operator's, or ones opened before this version recorded them. pve-firewall's
|
||||||
|
rules stay the operator's.
|
||||||
|
|
||||||
|
## [0.12.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `get_vm_status(vmid)` reports the VM's real state (#72): it reads
|
||||||
|
`GET /nodes/{node}/qemu/{vmid}/status/current` and answers `running`, `stopped`, or
|
||||||
|
`paused` for a `qmpstatus` of paused or suspended, the same as `get_vms()`. It used to say
|
||||||
|
`running` for every VM whose config could be read, so a caller waiting for a clean shutdown
|
||||||
|
never saw the VM stop (NetOrk/netork's workflow step "Shut down Proxmox VM" always ran into
|
||||||
|
its timeout). The guest agent is asked for an address only while the VM runs, and
|
||||||
|
`wait_for_ip=True` ends with a `RuntimeError` at once when the VM is stopped or paused,
|
||||||
|
rather than waiting out its timeout for an address that cannot come.
|
||||||
|
|
||||||
|
## [0.11.0] - 2026-11-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `resume_vm(name)` (napalm-device-types' `HypervisorDriver`, NetOrk/netork#2658): a paused
|
||||||
|
VM continues where `suspend_vm` stopped it, through `status/resume`, and the driver waits
|
||||||
|
for its task. A VM that is not paused is refused (PVE answers a running one with success
|
||||||
|
and does nothing), and so is a container: the driver does not suspend one, PVE's
|
||||||
|
container suspend is experimental, and its listing does not tell a suspended container
|
||||||
|
from another.
|
||||||
- A native Zabbix agent on both drivers (napalm-device-types `ZabbixAgentMixin`,
|
- A native Zabbix agent on both drivers (napalm-device-types `ZabbixAgentMixin`,
|
||||||
NetOrk/netork#2571): a node runs no container engine. `configure_zabbix_agent(settings)`
|
NetOrk/netork#2571): a node runs no container engine. `configure_zabbix_agent(settings)`
|
||||||
installs Debian's `zabbix-agent`, and where Debian has none and the caller names the
|
installs Debian's `zabbix-agent`, and where Debian has none and the caller names the
|
||||||
@@ -53,6 +182,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
|
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
- `get_vms()` reports a paused VM as `"paused"`, no longer as `"running"` (NetOrk/netork#2658).
|
||||||
|
PVE says `status: running` for a guest that `status/suspend` paused, or that sleeps in
|
||||||
|
S3; only the full listing (`GET /nodes/{node}/qemu?full=1`) has its `qmpstatus`, so the
|
||||||
|
driver asks for it.
|
||||||
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
|
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
|
||||||
- The SNMP agent's ufw step is the shared `_allow_sources(allowed, port, proto)`; the rule
|
- The SNMP agent's ufw step is the shared `_allow_sources(allowed, port, proto)`; the rule
|
||||||
it writes for udp/161 is the same.
|
it writes for udp/161 is the same.
|
||||||
|
|||||||
@@ -131,6 +131,12 @@ device = driver(
|
|||||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
|
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
|
||||||
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
||||||
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
||||||
|
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
|
||||||
|
| `get_services_need_restart` | the services that still run code an update replaced on disk, as root over SSH (napalm-device-types' `ServicesRestartMixin`): `needrestart` in list-only mode where it is installed, else the processes whose `/proc/<pid>/maps` maps deleted code. A running VM's QEMU is a process (`processes`), an LXC container's processes are left out (the container updates itself). Only as root: another SSH login gets no reading, rather than a clean one |
|
||||||
|
| `get_pve_firewall` | the PVE firewall as the operator wrote it, read only (NetOrk/netork#2654): the datacenter's `options`, `rules`, security `groups` (name → rules), `ipsets` (name → `[{cidr, nomatch, comment}]`) and `aliases` (name → cidr), this node's `options` and `rules`, and every guest's on this node (`vmid`, `type`, `name`, `options`, `rules`, and `nics`: `[{name, firewall}]` from `netN … firewall=1`). Each rule keeps PVE's fields and its `origin` (`cluster`, `group`, `node`, `guest`). A part PVE refuses is `null`, never empty |
|
||||||
|
| `get_host_firewall` | what the node has loaded, as for any Linux host (napalm-device-types' `HostFirewallMixin`): `nft list ruleset` (PVE 9's proxmox-firewall) or `iptables-save` (pve-firewall), as root over SSH |
|
||||||
|
| `get_hardening` | how the node is hardened (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776): security modules, SELinux and AppArmor, crypto policy, FIPS mode, CPU vulnerabilities, kernel command line, whether the node runs virtualized and its CPU vendor, as root over SSH. On the backup server too |
|
||||||
|
| `install_cpu_microcode` | the CPU vendor's microcode (`intel-microcode`, `amd64-microcode`; napalm-device-types' `CpuMicrocodeMixin`, NetOrk/netork#2838): Debian's `non-free-firmware` added to Debian's own sources where missing, `apt-get update` over SSH (waited for, unlike the API's refresh task), then the install. Refused on a node that runs virtualized. Loads at the next boot. On the backup server too |
|
||||||
|
|
||||||
**Not implemented** (raise `NotImplementedError`):
|
**Not implemented** (raise `NotImplementedError`):
|
||||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||||
@@ -188,9 +194,10 @@ the disks and ZFS pools the server manages itself.
|
|||||||
| `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH |
|
| `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH |
|
||||||
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
||||||
| `get_licenses` | `pbs-subscription` |
|
| `get_licenses` | `pbs-subscription` |
|
||||||
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
| packages, updates, services, kernel, listening sockets, services still running replaced code, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
||||||
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
||||||
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
||||||
|
| `get_certificates` | as on Proxmox VE, from `/nodes/localhost/certificates/info` and `/nodes/localhost/config`: one certificate, `proxy.pem`, which ACME renews where a domain is configured |
|
||||||
|
|
||||||
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
||||||
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
||||||
@@ -235,6 +242,8 @@ napalm_proxmox/
|
|||||||
├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup)
|
├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup)
|
||||||
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
|
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
|
||||||
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
|
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
|
||||||
|
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
|
||||||
|
├── firewall_mixin.py # get_pve_firewall: the PVE firewall at every level, read only
|
||||||
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
||||||
tests/
|
tests/
|
||||||
├── conftest.py # Shared fixtures and mock API payloads
|
├── conftest.py # Shared fixtures and mock API payloads
|
||||||
@@ -246,6 +255,9 @@ tests/
|
|||||||
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
|
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
|
||||||
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||||
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||||
|
├── test_certificates.py # get_certificates on both drivers
|
||||||
|
├── test_firewall.py # get_pve_firewall and get_host_firewall
|
||||||
|
├── test_hardening.py # get_hardening and install_cpu_microcode on both drivers
|
||||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import io
|
import io
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
@@ -39,6 +40,9 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The release at the start of a product version, ``"9.3"`` of ``"9.3.0"``.
|
||||||
|
_RELEASE = re.compile(r"^(\d+)\.(\d+)")
|
||||||
|
|
||||||
#: The API port of each proxmoxer service this package drives.
|
#: The API port of each proxmoxer service this package drives.
|
||||||
DEFAULT_PORTS = {"PVE": 8006, "PBS": 8007}
|
DEFAULT_PORTS = {"PVE": 8006, "PBS": 8007}
|
||||||
|
|
||||||
@@ -301,6 +305,24 @@ class ProxmoxBase:
|
|||||||
logger.debug("Failed to fetch version info: %s", exc)
|
logger.debug("Failed to fetch version info: %s", exc)
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
def _version_at_least(self, major: int, minor: int, node: str | None = None) -> bool:
|
||||||
|
"""Whether the product on the node is release *major*.*minor* or newer.
|
||||||
|
|
||||||
|
Read from ``GET /version`` of the node the driver is connected to, or with
|
||||||
|
*node* from ``GET /nodes/{node}/version``: during a rolling upgrade the
|
||||||
|
cluster's members run different releases. The package ``version``
|
||||||
|
(``"9.3.0"``) decides, else the point ``release`` (``"9.3"``). A version it
|
||||||
|
cannot parse counts as older, so the caller takes the path every release
|
||||||
|
has. An API error propagates.
|
||||||
|
"""
|
||||||
|
source = self._api.nodes(node).version if node else self._api.version
|
||||||
|
info = source.get() or {}
|
||||||
|
for raw in (info.get("version"), info.get("release")):
|
||||||
|
match = _RELEASE.match(str(raw or ""))
|
||||||
|
if match:
|
||||||
|
return (int(match[1]), int(match[2])) >= (major, minor)
|
||||||
|
return False
|
||||||
|
|
||||||
def _get_node_status(self) -> _JsonDict:
|
def _get_node_status(self) -> _JsonDict:
|
||||||
"""Return the node's status from the Proxmox API."""
|
"""Return the node's status from the Proxmox API."""
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -17,8 +17,10 @@ from typing import Any
|
|||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
BackupServerDriver,
|
BackupServerDriver,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
FingerprintRule,
|
FingerprintRule,
|
||||||
|
HardeningMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
@@ -27,6 +29,7 @@ from napalm_device_types import (
|
|||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
PortSpec,
|
PortSpec,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
StorageDriver,
|
StorageDriver,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
@@ -38,6 +41,7 @@ except ImportError as exc: # pragma: no cover - proxmoxer is a dependency
|
|||||||
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
|
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
|
||||||
|
|
||||||
from napalm_proxmox._base import ProxmoxBase
|
from napalm_proxmox._base import ProxmoxBase
|
||||||
|
from napalm_proxmox.certificates import PbsCertificatesMixin
|
||||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
|
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
|
||||||
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
||||||
@@ -59,18 +63,22 @@ class ProxmoxBackupDriver(
|
|||||||
ProxmoxPbsHostMixin,
|
ProxmoxPbsHostMixin,
|
||||||
ProxmoxHostMixin,
|
ProxmoxHostMixin,
|
||||||
ProxmoxTimeSyncMixin,
|
ProxmoxTimeSyncMixin,
|
||||||
|
PbsCertificatesMixin,
|
||||||
BackupServerDriver,
|
BackupServerDriver,
|
||||||
StorageDriver,
|
StorageDriver,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
|
HardeningMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
LogSourcesMixin,
|
LogSourcesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
ProxmoxScheduledJobsMixin,
|
ProxmoxScheduledJobsMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
ProxmoxZabbixAgentMixin,
|
ProxmoxZabbixAgentMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
|
||||||
|
|
||||||
|
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
|
||||||
|
driver set: one ``{name, issuer, valid_from, valid_to, in_use_by}`` per
|
||||||
|
certificate, the validity as Unix timestamps. netOrk's expiry warnings read it
|
||||||
|
from every driver that has it.
|
||||||
|
|
||||||
|
Both products list their certificates at ``GET /nodes/{node}/certificates/info``
|
||||||
|
(PBS: ``/nodes/localhost/certificates/info``). Proxmox VE has three: its
|
||||||
|
cluster's CA (``pve-root-ca.pem``), the node certificate the CA signed
|
||||||
|
(``pve-ssl.pem``) and, where one was uploaded or ACME ordered one,
|
||||||
|
``pveproxy-ssl.pem``, which ``pveproxy`` then serves instead. A backup server has
|
||||||
|
one, ``proxy.pem``. ``in_use_by`` is 1 for the certificate the web UI and API
|
||||||
|
serve, 0 for the others.
|
||||||
|
|
||||||
|
One call more, the node's ``config``, says whether ACME renews the served
|
||||||
|
certificate (``acme``): a domain is configured (``acmedomain0``…, or
|
||||||
|
``domains=`` in the older ``acme`` property). The daily update job of either
|
||||||
|
product renews it 30 days before it runs out, so an ACME certificate close to
|
||||||
|
its end means the renewal failed. A config that cannot be read means no ACME.
|
||||||
|
|
||||||
|
``name`` is the file name, as the products' own certificate lists show it;
|
||||||
|
``issuer`` and ``subject`` are the common names. The PEM never leaves the node
|
||||||
|
reading: netOrk keeps only what it shows.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Any, ClassVar
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: ``CN=x`` in either form the products print a name in: ``/O=y/CN=x`` (PVE) or
|
||||||
|
#: ``CN = x, O = y`` (PBS).
|
||||||
|
_COMMON_NAME = re.compile(r"(?:^|[/,])\s*CN\s*=\s*([^/,]+)")
|
||||||
|
|
||||||
|
|
||||||
|
def common_name(name: str | None) -> str:
|
||||||
|
"""The CN of a distinguished name as Proxmox prints it, else the name itself."""
|
||||||
|
if not name:
|
||||||
|
return ""
|
||||||
|
found = _COMMON_NAME.search(name)
|
||||||
|
return found.group(1).strip() if found else name.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _seconds(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(value or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def acme_configured(config: _JsonDict) -> bool:
|
||||||
|
"""Whether the node's config names a domain for ACME to order a certificate for."""
|
||||||
|
if any(key.startswith("acmedomain") and value for key, value in config.items()):
|
||||||
|
return True
|
||||||
|
return "domains=" in str(config.get("acme") or "")
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxCertificatesMixin:
|
||||||
|
"""``get_certificates`` for a Proxmox VE node; the backup server sets its file names."""
|
||||||
|
|
||||||
|
#: The files the proxy serves, the first one present wins.
|
||||||
|
served_certificates: ClassVar[tuple[str, ...]] = ("pveproxy-ssl.pem", "pve-ssl.pem")
|
||||||
|
#: The file an ACME order writes.
|
||||||
|
acme_certificate: ClassVar[str] = "pveproxy-ssl.pem"
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
|
||||||
|
def get_certificates(self) -> list[_JsonDict]:
|
||||||
|
"""The node's certificates in netOrk's contract shape; ``[]`` when unreadable."""
|
||||||
|
try:
|
||||||
|
rows = self._node_api().certificates.info.get() or []
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("get_certificates() failed on %s: %s", self._node_name, exc)
|
||||||
|
return []
|
||||||
|
files = [row.get("filename") for row in rows]
|
||||||
|
served = next((f for f in self.served_certificates if f in files), None)
|
||||||
|
acme = self.acme_certificate in files and self._acme_configured()
|
||||||
|
return [self._certificate(row, served, acme) for row in rows]
|
||||||
|
|
||||||
|
def _acme_configured(self) -> bool:
|
||||||
|
try:
|
||||||
|
return acme_configured(self._node_api().config.get() or {})
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("node config unreadable on %s: %s", self._node_name, exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _certificate(self, row: _JsonDict, served: str | None, acme: bool) -> _JsonDict:
|
||||||
|
filename = str(row.get("filename") or "")
|
||||||
|
return {
|
||||||
|
"name": filename,
|
||||||
|
"issuer": common_name(row.get("issuer")),
|
||||||
|
"valid_from": _seconds(row.get("notbefore")),
|
||||||
|
"valid_to": _seconds(row.get("notafter")),
|
||||||
|
"in_use_by": 1 if filename == served else 0,
|
||||||
|
"subject": common_name(row.get("subject")),
|
||||||
|
"fingerprint": row.get("fingerprint") or "",
|
||||||
|
"acme": acme and filename == self.acme_certificate,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class PbsCertificatesMixin(ProxmoxCertificatesMixin):
|
||||||
|
"""A backup server has one certificate, ``proxy.pem``, which ACME renews too."""
|
||||||
|
|
||||||
|
served_certificates: ClassVar[tuple[str, ...]] = ("proxy.pem",)
|
||||||
|
acme_certificate: ClassVar[str] = "proxy.pem"
|
||||||
@@ -4,8 +4,8 @@ Every PVE node can read its whole cluster, so the getter always reports exactly
|
|||||||
one cluster, the one the connected node is a member of (a standalone node is a
|
one cluster, the one the connected node is a member of (a standalone node is a
|
||||||
cluster of one, without a name). Read from:
|
cluster of one, without a name). Read from:
|
||||||
|
|
||||||
- ``GET /cluster/status``: the cluster's name and quorum, and every member with
|
- ``GET /cluster/status``: the cluster's name, quorum and (PVE 9.3) ``cluster-id``,
|
||||||
``online`` and ``local``;
|
and every member with ``online`` and ``local``;
|
||||||
- ``GET /cluster/resources``: per node ``maxcpu``, ``cpu``, ``maxmem``, ``mem``;
|
- ``GET /cluster/resources``: per node ``maxcpu``, ``cpu``, ``maxmem``, ``mem``;
|
||||||
per node and storage one row with ``plugintype``, ``shared``, ``content``,
|
per node and storage one row with ``plugintype``, ``shared``, ``content``,
|
||||||
``maxdisk``, ``disk`` and ``status``;
|
``maxdisk``, ``disk`` and ``status``;
|
||||||
@@ -124,6 +124,12 @@ def _name_backup_servers(storages: list[ClusterStorageDict], api: Any) -> None:
|
|||||||
storage["backup_server"] = _backup_server_ref(config) if config else None
|
storage["backup_server"] = _backup_server_ref(config) if config else None
|
||||||
|
|
||||||
|
|
||||||
|
def _cluster_id(head: _JsonDict | None, status: list[_JsonDict]) -> str | None:
|
||||||
|
"""``cluster-id`` (PVE 9.3) of the cluster entry, or of a standalone node's own entry."""
|
||||||
|
entry = head or next((s for s in status if s.get("type") == "node"), {})
|
||||||
|
return str(entry.get("cluster-id") or "") or None
|
||||||
|
|
||||||
|
|
||||||
def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]:
|
def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]:
|
||||||
merged: dict[str, ClusterNetworkDict] = {}
|
merged: dict[str, ClusterNetworkDict] = {}
|
||||||
for node, network in per_node:
|
for node, network in per_node:
|
||||||
@@ -149,9 +155,10 @@ class ProxmoxClusterMixin:
|
|||||||
"""
|
"""
|
||||||
Return the one cluster this node belongs to, its nodes, storages and networks.
|
Return the one cluster this node belongs to, its nodes, storages and networks.
|
||||||
|
|
||||||
- ``id`` is always None: PVE gives a cluster no identity beyond its name.
|
- ``id`` is the ``cluster-id`` of PVE 9.3, a random identifier the cluster
|
||||||
``name`` and ``quorate`` are None on a standalone node, which reports
|
keeps when it is renamed; a standalone node reports its own on its node
|
||||||
itself as a cluster of one.
|
entry. None on an older node. ``name`` and ``quorate`` are None on a
|
||||||
|
standalone node, which reports itself as a cluster of one.
|
||||||
- Every member is listed. An offline node has ``status`` ``"offline"`` and
|
- Every member is listed. An offline node has ``status`` ``"offline"`` and
|
||||||
no capacity values: its own API cannot be asked. ``local`` marks the
|
no capacity values: its own API cannot be asked. ``local`` marks the
|
||||||
node ``/cluster/status`` calls local, or else the node this driver
|
node ``/cluster/status`` calls local, or else the node this driver
|
||||||
@@ -181,7 +188,7 @@ class ProxmoxClusterMixin:
|
|||||||
_name_backup_servers(storages, self._api)
|
_name_backup_servers(storages, self._api)
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
"id": None,
|
"id": _cluster_id(head, status),
|
||||||
"name": (head.get("name") or None) if head else None,
|
"name": (head.get("name") or None) if head else None,
|
||||||
"quorate": _flag(head.get("quorate")) if head else None,
|
"quorate": _flag(head.get("quorate")) if head else None,
|
||||||
"nodes": self._cluster_nodes(members, resources),
|
"nodes": self._cluster_nodes(members, resources),
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""When the credential the Proxmox VE driver logs in with expires (NetOrk/netork#2728).
|
||||||
|
|
||||||
|
``CredentialExpiryMixin`` of napalm-device-types. The driver logs in either with
|
||||||
|
an API token (``user@realm!tokenid``) or with a user's password:
|
||||||
|
|
||||||
|
- a token: ``GET /access/users/{userid}/token/{tokenid}``, its ``expire``. A token
|
||||||
|
without one of its own expires with its user (the schema's default, "same as
|
||||||
|
user"), read as for a password;
|
||||||
|
- a password: ``GET /access/users/{userid}``, the account's ``expire``.
|
||||||
|
|
||||||
|
``0`` or no value is never. PVE 9.3's datacenter ``token-policy`` can require an
|
||||||
|
expiry on every token; the fields themselves are older, so every release is read.
|
||||||
|
PVE lets a user read itself and its tokens; a privilege-separated token may be
|
||||||
|
refused its user (``User.Modify`` or ``Sys.Audit`` on the user's group), and a
|
||||||
|
403 is a ``PermissionError``, as the contract says.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from napalm_device_types import CredentialExpiryDict, CredentialExpiryMixin
|
||||||
|
from proxmoxer.core import ResourceException
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _expires(value: Any) -> int | None:
|
||||||
|
"""PVE's ``expire``: unix seconds, ``0`` or none for never."""
|
||||||
|
return int(value or 0) or None
|
||||||
|
|
||||||
|
|
||||||
|
def _read(get: Callable[[], Any], what: str) -> _JsonDict:
|
||||||
|
"""``get()``'s answer; a refusal as ``PermissionError``, another failure as
|
||||||
|
``RuntimeError``."""
|
||||||
|
try:
|
||||||
|
answer = get()
|
||||||
|
except ResourceException as exc:
|
||||||
|
if exc.status_code == 403:
|
||||||
|
raise PermissionError(f"Proxmox VE will not tell {what}'s expiry: {exc}") from exc
|
||||||
|
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||||
|
return dict(answer or {})
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
|
||||||
|
"""Relies on the driver's ``_api`` and its login (``_api_kwargs``)."""
|
||||||
|
|
||||||
|
_api: Any
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
|
||||||
|
def _api_kwargs(self) -> _JsonDict: ...
|
||||||
|
|
||||||
|
def get_credential_expiry(self) -> CredentialExpiryDict:
|
||||||
|
"""The API token or the account this connection logged in with, and its expiry."""
|
||||||
|
login = self._api_kwargs()
|
||||||
|
userid = str(login["user"])
|
||||||
|
if "token_value" not in login:
|
||||||
|
return {"kind": "account", "name": userid, "expires": self._user_expiry(userid)}
|
||||||
|
name = f"{userid}!{login['token_name']}"
|
||||||
|
token = _read(lambda: self._api.access.users(userid).token(login["token_name"]).get(), name)
|
||||||
|
expire = token.get("expire")
|
||||||
|
return {
|
||||||
|
"kind": "api-token",
|
||||||
|
"name": name,
|
||||||
|
"expires": self._user_expiry(userid) if expire is None else _expires(expire),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _user_expiry(self, userid: str) -> int | None:
|
||||||
|
return _expires(_read(lambda: self._api.access.users(userid).get(), userid).get("expire"))
|
||||||
@@ -27,8 +27,11 @@ from typing import Any
|
|||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
FingerprintRule,
|
FingerprintRule,
|
||||||
|
HardeningMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
HypervisorDriver,
|
HypervisorDriver,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
@@ -38,6 +41,7 @@ from napalm_device_types import (
|
|||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
PortSpec,
|
PortSpec,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
@@ -49,8 +53,11 @@ except ImportError as exc:
|
|||||||
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
|
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
|
||||||
|
|
||||||
from napalm_proxmox._base import ProxmoxBase
|
from napalm_proxmox._base import ProxmoxBase
|
||||||
|
from napalm_proxmox.certificates import ProxmoxCertificatesMixin
|
||||||
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
||||||
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
||||||
|
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
||||||
|
from napalm_proxmox.firewall_mixin import ProxmoxFirewallMixin
|
||||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||||
@@ -60,6 +67,7 @@ from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduled
|
|||||||
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
||||||
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
|
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
|
||||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||||
|
from napalm_proxmox.update_history import ProxmoxUpdateHistoryMixin
|
||||||
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
||||||
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||||
@@ -94,19 +102,27 @@ class ProxmoxDriver(
|
|||||||
ProxmoxRoutingMixin,
|
ProxmoxRoutingMixin,
|
||||||
ProxmoxSystemMixin,
|
ProxmoxSystemMixin,
|
||||||
ProxmoxHostMixin,
|
ProxmoxHostMixin,
|
||||||
|
ProxmoxFirewallMixin,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
|
HardeningMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
LogSourcesMixin,
|
LogSourcesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
ProxmoxScheduledJobsMixin,
|
ProxmoxScheduledJobsMixin,
|
||||||
ProxmoxRunningBackupsMixin,
|
ProxmoxRunningBackupsMixin,
|
||||||
ProxmoxTimeSyncMixin,
|
ProxmoxTimeSyncMixin,
|
||||||
|
ProxmoxCertificatesMixin,
|
||||||
|
ProxmoxCredentialExpiryMixin,
|
||||||
|
ProxmoxUpdateHistoryMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
ProxmoxZabbixAgentMixin,
|
ProxmoxZabbixAgentMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
"""The PVE firewall of the cluster, read-only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall()`` reads what the operator wrote, at every level PVE has one:
|
||||||
|
the datacenter's options, rules, security groups, IP sets and aliases, the node's
|
||||||
|
options and rules, and each guest's on this node -- options, rules, and which NICs
|
||||||
|
carry ``firewall=1``. The datacenter level is the cluster's (pmxcfs keeps it once
|
||||||
|
for every node), so every node reads the same; a node reads its own guests, the
|
||||||
|
ones it runs. Nothing is written: pve-firewall rules are the operator's (see
|
||||||
|
``host_mixin``), and netOrk only reads them.
|
||||||
|
|
||||||
|
Each rule keeps PVE's own fields -- ``pos``, ``type`` (``in``, ``out``, ``group``,
|
||||||
|
``forward``), ``action`` (``ACCEPT``, ``DROP``, ``REJECT``, or a group's name),
|
||||||
|
``macro``, ``source``, ``dest``, ``proto``, ``dport``, ``sport``, ``iface``,
|
||||||
|
``enable``, ``comment`` -- and says where it came from (``origin``: ``cluster``,
|
||||||
|
``node``, ``guest`` or ``group``). A level whose call is refused (no
|
||||||
|
``Sys.Audit``/``VM.Audit``) is None, not empty: an unread level is no claim.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The rule fields kept as PVE returns them.
|
||||||
|
_RULE_FIELDS = (
|
||||||
|
"pos",
|
||||||
|
"type",
|
||||||
|
"action",
|
||||||
|
"macro",
|
||||||
|
"source",
|
||||||
|
"dest",
|
||||||
|
"proto",
|
||||||
|
"dport",
|
||||||
|
"sport",
|
||||||
|
"iface",
|
||||||
|
"comment",
|
||||||
|
"log",
|
||||||
|
"icmp-type",
|
||||||
|
)
|
||||||
|
#: A guest's NIC keys: ``net0`` … for both QEMU and LXC.
|
||||||
|
_NIC = re.compile(r"^net\d+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _rule(raw: _JsonDict, origin: str) -> _JsonDict:
|
||||||
|
found = {k.replace("-", "_"): raw[k] for k in _RULE_FIELDS if raw.get(k) not in (None, "")}
|
||||||
|
found["enable"] = str(raw.get("enable", 1)) not in ("0", "")
|
||||||
|
found["origin"] = origin
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _rules(rows: Any, origin: str) -> list[_JsonDict]:
|
||||||
|
return [_rule(r, origin) for r in rows or [] if isinstance(r, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def nic_firewalls(config: _JsonDict) -> list[_JsonDict]:
|
||||||
|
"""Each NIC of a guest config with whether ``firewall=1`` is set on it."""
|
||||||
|
found = []
|
||||||
|
for key in sorted(k for k in config if _NIC.match(k)):
|
||||||
|
options = dict(part.split("=", 1) for part in str(config[key]).split(",") if "=" in part)
|
||||||
|
found.append({"name": key, "firewall": options.get("firewall") == "1"})
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _read(call: Any, what: str) -> Any:
|
||||||
|
"""One GET; None when PVE refuses or fails it -- an unread level, not an empty one."""
|
||||||
|
try:
|
||||||
|
return call.get()
|
||||||
|
except Exception as exc: # noqa: BLE001 - proxmoxer raises its own and requests' errors
|
||||||
|
logger.warning("get_pve_firewall: %s not read: %s", what, exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _rules_or_none(rows: Any, origin: str) -> list[_JsonDict] | None:
|
||||||
|
return None if rows is None else _rules(rows, origin)
|
||||||
|
|
||||||
|
|
||||||
|
def _named(rows: Any, key: str) -> list[str]:
|
||||||
|
return [str(r[key]) for r in rows or [] if isinstance(r, dict) and r.get(key)]
|
||||||
|
|
||||||
|
|
||||||
|
def _groups(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
"""Each security group's rules; a group whose rules are refused has none listed."""
|
||||||
|
listed = _read(fw.groups, "security groups")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: _rules(_read(fw.groups(name), f"group {name}"), "group")
|
||||||
|
for name in _named(listed, "group")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _entry(raw: _JsonDict) -> _JsonDict:
|
||||||
|
return {
|
||||||
|
"cidr": raw.get("cidr"),
|
||||||
|
"nomatch": bool(raw.get("nomatch")),
|
||||||
|
"comment": raw.get("comment"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ipsets(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
listed = _read(fw.ipset, "IP sets")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: [
|
||||||
|
_entry(e) for e in _read(fw.ipset(name), f"IP set {name}") or [] if isinstance(e, dict)
|
||||||
|
]
|
||||||
|
for name in _named(listed, "name")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _aliases(rows: Any) -> dict[str, Any] | None:
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(a["name"]): a.get("cidr") for a in rows if isinstance(a, dict) and a.get("name")}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxFirewallMixin:
|
||||||
|
"""``get_pve_firewall`` for the PVE driver: the cluster's firewall as written, read only."""
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
_api: Any
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
|
||||||
|
def _cluster_firewall(self) -> _JsonDict:
|
||||||
|
fw = self._api.cluster.firewall
|
||||||
|
return {
|
||||||
|
"options": _read(fw.options, "datacenter options"),
|
||||||
|
"rules": _rules_or_none(_read(fw.rules, "datacenter rules"), "cluster"),
|
||||||
|
"groups": _groups(fw),
|
||||||
|
"ipsets": _ipsets(fw),
|
||||||
|
"aliases": _aliases(_read(fw.aliases, "aliases")),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guest_firewall(self, kind: str, guest: _JsonDict) -> _JsonDict:
|
||||||
|
vmid = int(guest.get("vmid", 0))
|
||||||
|
api = getattr(self._node_api(), kind)(vmid)
|
||||||
|
rules = _read(api.firewall.rules, f"{kind} {vmid} rules")
|
||||||
|
config = _read(api.config, f"{kind} {vmid} config")
|
||||||
|
return {
|
||||||
|
"vmid": str(vmid),
|
||||||
|
"type": "vm" if kind == "qemu" else "container",
|
||||||
|
"name": guest.get("name") or "",
|
||||||
|
"node": self._node_name,
|
||||||
|
"options": _read(api.firewall.options, f"{kind} {vmid} options"),
|
||||||
|
"rules": _rules_or_none(rules, "guest"),
|
||||||
|
"nics": None if config is None else nic_firewalls(config),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guests(self) -> list[_JsonDict]:
|
||||||
|
found: list[_JsonDict] = []
|
||||||
|
for kind in ("qemu", "lxc"):
|
||||||
|
for guest in _read(getattr(self._node_api(), kind), f"{kind} guests") or []:
|
||||||
|
if isinstance(guest, dict) and guest.get("vmid") is not None:
|
||||||
|
found.append(self._guest_firewall(kind, guest))
|
||||||
|
return found
|
||||||
|
|
||||||
|
def get_pve_firewall(self) -> _JsonDict:
|
||||||
|
"""
|
||||||
|
Return the PVE firewall as the operator wrote it: the datacenter level, this
|
||||||
|
node's, and every guest's on this node. Read only.
|
||||||
|
|
||||||
|
* cluster (dict) - ``options``, ``rules``, ``groups`` (name -> rules),
|
||||||
|
``ipsets`` (name -> ``[{cidr, nomatch, comment}]``), ``aliases`` (name -> cidr)
|
||||||
|
* node (dict) - ``name``, ``options``, ``rules``
|
||||||
|
* guests (list) - ``vmid``, ``type`` (``vm``/``container``), ``name``, ``node``,
|
||||||
|
``options``, ``rules``, ``nics`` (``[{name, firewall}]``)
|
||||||
|
|
||||||
|
Any part PVE refuses is None, never empty. Each rule carries PVE's fields and
|
||||||
|
its ``origin`` (``cluster``, ``group``, ``node``, ``guest``).
|
||||||
|
"""
|
||||||
|
node = self._node_api().firewall
|
||||||
|
rules = _read(node.rules, "node rules")
|
||||||
|
return {
|
||||||
|
"cluster": self._cluster_firewall(),
|
||||||
|
"node": {
|
||||||
|
"name": self._node_name,
|
||||||
|
"options": _read(node.options, "node options"),
|
||||||
|
"rules": _rules_or_none(rules, "node"),
|
||||||
|
},
|
||||||
|
"guests": self._guests(),
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
|
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
|
||||||
|
|
||||||
The transports for napalm-device-types' host readers (kernel facts, service
|
The transports for napalm-device-types' host readers (kernel facts, service
|
||||||
packages, system identity, listening sockets, systemd services, host status,
|
packages, system identity, listening sockets, the services that still run replaced
|
||||||
apt's proxy), packages and APT updates, the subscription, root file writes,
|
code, systemd services, host status, apt's proxy), packages and APT updates, the
|
||||||
and restarting or shutting the host down. All of it is the same on both
|
subscription, root file writes, and restarting or shutting the host down. All of it
|
||||||
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status``
|
is the same on both products: the same ``/nodes/{node}/apt``, ``/subscription`` and
|
||||||
endpoints, and root's shell over the driver's own SSH session.
|
``/status`` endpoints, and root's shell over the driver's own SSH session.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -17,7 +17,18 @@ import re
|
|||||||
import shlex
|
import shlex
|
||||||
from typing import TYPE_CHECKING, Any, cast
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
|
from napalm_device_types import (
|
||||||
|
APT_UPGRADABLE_COMMAND,
|
||||||
|
OPENED_PORTS_RECORD,
|
||||||
|
OpenedRuleDict,
|
||||||
|
parse_apt_upgradable,
|
||||||
|
parse_opened_ports_record,
|
||||||
|
read_opened_ports_command,
|
||||||
|
revoke_recorded_rules,
|
||||||
|
revoked_output,
|
||||||
|
ufw_allow_recorded_command,
|
||||||
|
ufw_delete_command,
|
||||||
|
)
|
||||||
from napalm_device_types.models import (
|
from napalm_device_types.models import (
|
||||||
FixStepOutcomeDict,
|
FixStepOutcomeDict,
|
||||||
LicenseDict,
|
LicenseDict,
|
||||||
@@ -61,6 +72,18 @@ class ProxmoxHostMixin:
|
|||||||
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
||||||
return self._exec_ssh_command(command)
|
return self._exec_ssh_command(command)
|
||||||
|
|
||||||
|
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HardeningMixin.get_hardening`` (NetOrk/netork#2776): the exec
|
||||||
|
path, which is root's login, so AppArmor's profiles per mode are read too. Another
|
||||||
|
login reads the rest without them, as napalm-device-types' fallback does. No stdin."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_host_firewall_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HostFirewallMixin.get_host_firewall``: the exec path, which
|
||||||
|
runs as root either way. What the node has loaded -- proxmox-firewall's nftables
|
||||||
|
tables on PVE 9, pve-firewall's iptables chains before (NetOrk/netork#2654)."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
def _run_service_packages_command(self, command: str) -> str:
|
def _run_service_packages_command(self, command: str) -> str:
|
||||||
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
||||||
return str(self._exec_ssh_command(command))
|
return str(self._exec_ssh_command(command))
|
||||||
@@ -80,6 +103,13 @@ class ProxmoxHostMixin:
|
|||||||
which runs as root either way."""
|
which runs as root either way."""
|
||||||
return str(self._exec_ssh_command(command))
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_services_restart_command(self, command: str) -> str:
|
||||||
|
"""The transport for ``ServicesRestartMixin.get_services_need_restart``: the exec
|
||||||
|
path, which is root's login as a rule. Run only as root: a reading of the login's
|
||||||
|
own processes would read as clean, so another login prints nothing and the parse
|
||||||
|
raises (NetOrk/netork#2750). No stdin."""
|
||||||
|
return str(self._exec_ssh_command(f'[ "$(id -u)" = 0 ] && {command}'))
|
||||||
|
|
||||||
def get_packages(self) -> list[PackageDict]:
|
def get_packages(self) -> list[PackageDict]:
|
||||||
"""Return installed Debian packages with available-update info.
|
"""Return installed Debian packages with available-update info.
|
||||||
|
|
||||||
@@ -231,17 +261,66 @@ class ProxmoxHostMixin:
|
|||||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
return self._write_root_file(path, content)
|
return self._write_root_file(path, content)
|
||||||
|
|
||||||
def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict:
|
def _reload_package_index(self) -> FixStepOutcomeDict:
|
||||||
|
"""``CpuMicrocodeMixin``'s index load (NetOrk/netork#2838): ``apt-get update`` on the
|
||||||
|
exec path, done when it returns. ``refresh_available_updates`` only starts the API's
|
||||||
|
task, and the install that follows would race it."""
|
||||||
|
return self._step(
|
||||||
|
"DEBIAN_FRONTEND=noninteractive apt-get update", "package index loaded again"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _allow_sources(
|
||||||
|
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||||
|
) -> FixStepOutcomeDict:
|
||||||
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
|
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
|
||||||
sources or no ufw -- pve-firewall's rules are the operator's."""
|
sources or no ufw -- pve-firewall's rules are the operator's. Each rule ufw adds
|
||||||
|
is recorded under *purpose* (napalm-device-types ``opened_ports``,
|
||||||
|
NetOrk/netork#2693); one ufw had is not."""
|
||||||
sources = [str(ipaddress.ip_network(s.strip(), strict=False)) for s in allowed]
|
sources = [str(ipaddress.ip_network(s.strip(), strict=False)) for s in allowed]
|
||||||
if not sources:
|
if not sources:
|
||||||
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
||||||
if self._rc("command -v ufw")[1] != 0:
|
if self._rc("command -v ufw")[1] != 0:
|
||||||
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
|
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
|
||||||
rules = " && ".join(f"ufw allow from {s} to any port {port} proto {proto}" for s in sources)
|
rules = " && ".join(ufw_allow_recorded_command(s, port, proto, purpose) for s in sources)
|
||||||
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
|
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
|
||||||
|
|
||||||
|
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict:
|
||||||
|
"""Remove the ufw rules recorded under *purpose*, whatever port they opened, and
|
||||||
|
nothing else; report what ufw has left for *proto*/*port*. Not ``ok`` where
|
||||||
|
the record may not be trusted -- nothing is removed then -- or a rule would not
|
||||||
|
go, which stays in the record."""
|
||||||
|
read, status = self._rc(read_opened_ports_command())
|
||||||
|
if status != 0:
|
||||||
|
return {"ok": False, "output": f"reading {OPENED_PORTS_RECORD}: {read[-300:]}"}
|
||||||
|
record = parse_opened_ports_record(read)
|
||||||
|
if record["problem"]:
|
||||||
|
return {"ok": False, "output": record["problem"]}
|
||||||
|
done = revoke_recorded_rules(record, purpose, self._remove_recorded_rule)
|
||||||
|
failed = done["failed"]
|
||||||
|
if done["removed"]:
|
||||||
|
written = self._write_root_file(OPENED_PORTS_RECORD, done["record"])
|
||||||
|
if not written["ok"]:
|
||||||
|
failed.append(f"writing {OPENED_PORTS_RECORD}: {written['output']}")
|
||||||
|
left = 0
|
||||||
|
if self._rc("command -v ufw")[1] == 0:
|
||||||
|
counted, _ = self._rc(
|
||||||
|
f"LC_ALL=C ufw show added"
|
||||||
|
f" | grep -cE '(port {port} proto {proto}| {port}/{proto})( |$)'"
|
||||||
|
)
|
||||||
|
last = counted.strip().splitlines()[-1:] or ["0"]
|
||||||
|
left = int(last[0]) if last[0].isdigit() else 0
|
||||||
|
output = revoked_output(
|
||||||
|
done["removed"], unknown=record["unknown"], left=left, proto=proto, port=port
|
||||||
|
)
|
||||||
|
if failed:
|
||||||
|
output = f"{output}; not removed: {'; '.join(failed)}"
|
||||||
|
return {"ok": not failed, "output": output}
|
||||||
|
|
||||||
|
def _remove_recorded_rule(self, rule: OpenedRuleDict) -> FixStepOutcomeDict:
|
||||||
|
if rule["backend"] != "ufw":
|
||||||
|
return {"ok": False, "output": f"a {rule['backend']} rule; a node's rules are ufw's"}
|
||||||
|
return self._step(ufw_delete_command(rule), "")
|
||||||
|
|
||||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
||||||
encoded = base64.b64encode(content.encode()).decode()
|
encoded = base64.b64encode(content.encode()).decode()
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ from typing import Any
|
|||||||
|
|
||||||
_LIST_SEPARATORS = re.compile(r"[\s,;\0]+")
|
_LIST_SEPARATORS = re.compile(r"[\s,;\0]+")
|
||||||
|
|
||||||
|
#: The first release with node maintenance over REST, guest uids, the cluster id,
|
||||||
|
#: clock sync on resume and the APT history (NetOrk/netork#2728).
|
||||||
|
PVE_9_3 = (9, 3)
|
||||||
|
|
||||||
|
|
||||||
def to_int(value: Any) -> int | None:
|
def to_int(value: Any) -> int | None:
|
||||||
return None if value is None else int(value)
|
return None if value is None else int(value)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import shlex
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm.base.exceptions import CommandErrorException
|
from napalm.base.exceptions import CommandErrorException
|
||||||
|
from napalm_device_types import SNMP_PURPOSE
|
||||||
|
|
||||||
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
||||||
|
|
||||||
@@ -362,7 +363,9 @@ class ProxmoxSystemMixin:
|
|||||||
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
|
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
|
||||||
|
|
||||||
def _allow_snmp_sources(self, settings: dict) -> dict:
|
def _allow_snmp_sources(self, settings: dict) -> dict:
|
||||||
return dict(self._allow_sources(settings.get("allowed_sources", []), 161, "udp"))
|
return dict(
|
||||||
|
self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE)
|
||||||
|
)
|
||||||
|
|
||||||
def _start_snmp_agent(self) -> dict:
|
def _start_snmp_agent(self) -> dict:
|
||||||
return self._step(
|
return self._step(
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""The node's past APT transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||||
|
|
||||||
|
PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
||||||
|
first, also the transactions netOrk did not start (an operator's ``apt``,
|
||||||
|
unattended-upgrades). A transaction is named by its ``start-time`` and its
|
||||||
|
``start-index`` among those that started in the same second of the same log
|
||||||
|
file. An older node has no such endpoint: the driver raises
|
||||||
|
``NotImplementedError`` and parses no log over SSH.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
|
from napalm_device_types import UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict
|
||||||
|
|
||||||
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any) -> str | None:
|
||||||
|
return str(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
|
def _package(row: _JsonDict) -> UpdateHistoryPackageDict:
|
||||||
|
return {
|
||||||
|
"name": str(row.get("package") or ""),
|
||||||
|
"action": cast(UpdateHistoryAction, row.get("action")),
|
||||||
|
"old_version": _text(row.get("old-version")),
|
||||||
|
"new_version": _text(row.get("new-version")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _transaction(row: _JsonDict) -> UpdateHistoryDict:
|
||||||
|
start = int(row["start-time"])
|
||||||
|
end = row.get("end-time")
|
||||||
|
return {
|
||||||
|
"id": f"{start}-{int(row.get('start-index') or 0)}",
|
||||||
|
"start": start,
|
||||||
|
"end": None if end is None else int(end),
|
||||||
|
"packages": [_package(p) for p in row.get("packages") or []],
|
||||||
|
"requested_by": _text(row.get("requested-by")),
|
||||||
|
"command": _text(row.get("command-line")),
|
||||||
|
"error": _text(row.get("error")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxUpdateHistoryMixin:
|
||||||
|
"""Relies on the driver's ``_node_api`` and ``_version_at_least``."""
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
def _version_at_least(self, major: int, minor: int) -> bool: ...
|
||||||
|
|
||||||
|
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||||
|
"""The node's APT transactions, newest first, from ``since`` (unix seconds) on.
|
||||||
|
|
||||||
|
:raises NotImplementedError: before PVE 9.3, which has no history endpoint.
|
||||||
|
:raises RuntimeError: the history could not be read; never an empty list.
|
||||||
|
"""
|
||||||
|
if not self._version_at_least(*PVE_9_3):
|
||||||
|
raise NotImplementedError(
|
||||||
|
f"Proxmox VE on {self._node_name} keeps no APT history its API reports "
|
||||||
|
"(from 9.3 on)"
|
||||||
|
)
|
||||||
|
params = {} if since is None else {"since": since}
|
||||||
|
try:
|
||||||
|
rows = self._node_api().apt.history.get(**params) or []
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
|
||||||
|
return [_transaction(row) for row in rows]
|
||||||
@@ -19,6 +19,9 @@ from napalm_device_types.models import (
|
|||||||
VMPassthroughDict,
|
VMPassthroughDict,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
from napalm_proxmox.vm_mixin import qemu_status
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
_POWER_TIMEOUT = 120
|
_POWER_TIMEOUT = 120
|
||||||
@@ -150,9 +153,9 @@ class ProxmoxVMContractMixin:
|
|||||||
node = self._node_api()
|
node = self._node_api()
|
||||||
return node.qemu(vmid) if vm_type == "vm" else node.lxc(vmid)
|
return node.qemu(vmid) if vm_type == "vm" else node.lxc(vmid)
|
||||||
|
|
||||||
def _run_power(self, vmid: int, vm_type: str, action: str) -> None:
|
def _run_power(self, vmid: int, vm_type: str, action: str, **params: Any) -> None:
|
||||||
try:
|
try:
|
||||||
upid = getattr(self._guest_api(vmid, vm_type).status, action).post()
|
upid = getattr(self._guest_api(vmid, vm_type).status, action).post(**params)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise RuntimeError(f"{action} of {vm_type} {vmid} failed: {exc}") from exc
|
raise RuntimeError(f"{action} of {vm_type} {vmid} failed: {exc}") from exc
|
||||||
if upid:
|
if upid:
|
||||||
@@ -188,6 +191,30 @@ class ProxmoxVMContractMixin:
|
|||||||
raise RuntimeError(f"Proxmox cannot suspend container {vmid}")
|
raise RuntimeError(f"Proxmox cannot suspend container {vmid}")
|
||||||
self._run_power(vmid, vm_type, "suspend")
|
self._run_power(vmid, vm_type, "suspend")
|
||||||
|
|
||||||
|
def resume_vm(self, name: str) -> None:
|
||||||
|
"""``status/resume`` for a paused QEMU guest (NetOrk/netork#2658).
|
||||||
|
|
||||||
|
A container is refused: this driver does not suspend one, PVE's container
|
||||||
|
suspend is experimental (CRIU), and its listing does not tell a suspended
|
||||||
|
container from another. A guest that is not paused is refused too: PVE would
|
||||||
|
answer a running one with success and do nothing.
|
||||||
|
|
||||||
|
From PVE 9.3 the guest agent sets the guest's clock to the host's time after
|
||||||
|
it resumes (``sync-time-on-resume``); PVE skips that where the guest has no
|
||||||
|
agent enabled and running.
|
||||||
|
"""
|
||||||
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
|
if vm_type != "vm":
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Proxmox cannot resume container {vmid}: only a paused VM can be resumed"
|
||||||
|
)
|
||||||
|
current = self._guest_api(vmid, vm_type).status.current.get() or {}
|
||||||
|
state = qemu_status(current)
|
||||||
|
if state != "paused":
|
||||||
|
raise RuntimeError(f"Cannot resume VM {vmid}: it is not paused ({state})")
|
||||||
|
params = {"sync-time-on-resume": 1} if self._version_at_least(*PVE_9_3) else {}
|
||||||
|
self._run_power(vmid, vm_type, "resume", **params)
|
||||||
|
|
||||||
def get_vm_config(self, name: str) -> VMConfigDict:
|
def get_vm_config(self, name: str) -> VMConfigDict:
|
||||||
vmid, vm_type = self._resolve_vm(name)
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
cfg = self._guest_api(vmid, vm_type).config.get() or {}
|
cfg = self._guest_api(vmid, vm_type).config.get() or {}
|
||||||
|
|||||||
@@ -12,9 +12,10 @@ on the node the driver is connected to (``_resolve_vm``).
|
|||||||
manages migrates through a ``hamigrate`` task that only hands the request to
|
manages migrates through a ``hamigrate`` task that only hands the request to
|
||||||
the HA manager; the driver then follows ``/cluster/ha/status/current`` until
|
the HA manager; the driver then follows ``/cluster/ha/status/current`` until
|
||||||
the guest is on the target, and on a failure reads the migration task's log.
|
the guest is on the target, and on a failure reads the migration task's log.
|
||||||
- ``set_node_maintenance``: PVE has no REST endpoint for it; it runs
|
- ``set_node_maintenance``: from PVE 9.3 ``PUT /nodes/{node}/maintenance``; an
|
||||||
``ha-manager crm-command node-maintenance`` over the driver's SSH session.
|
older node has no REST endpoint for it, and the driver runs
|
||||||
The HA manager moves the node's HA guests away after the command returned.
|
``ha-manager crm-command node-maintenance`` over its SSH session. Either way the
|
||||||
|
HA manager moves the node's HA guests away after the request returned.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -25,7 +26,7 @@ from time import monotonic, sleep
|
|||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from napalm_proxmox.migration import lxc_local, qemu_local, refusal, task_errors, upid_field
|
from napalm_proxmox.migration import lxc_local, qemu_local, refusal, task_errors, upid_field
|
||||||
from napalm_proxmox.pve_values import to_flag
|
from napalm_proxmox.pve_values import PVE_9_3, to_flag
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
|
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
|
||||||
@@ -57,6 +58,7 @@ class ProxmoxVMMigrateMixin:
|
|||||||
_wait_for_task: Any
|
_wait_for_task: Any
|
||||||
_node_ssh: Any
|
_node_ssh: Any
|
||||||
_run_node_command: Any
|
_run_node_command: Any
|
||||||
|
_version_at_least: Any
|
||||||
|
|
||||||
# -- cluster membership -------------------------------------------------------
|
# -- cluster membership -------------------------------------------------------
|
||||||
|
|
||||||
@@ -232,13 +234,30 @@ class ProxmoxVMMigrateMixin:
|
|||||||
# -- HA maintenance -----------------------------------------------------------
|
# -- HA maintenance -----------------------------------------------------------
|
||||||
|
|
||||||
def set_node_maintenance(self, node: str, enabled: bool) -> None:
|
def set_node_maintenance(self, node: str, enabled: bool) -> None:
|
||||||
"""Switch HA maintenance mode of a cluster node, over SSH (no REST endpoint)."""
|
"""Switch HA maintenance mode of a cluster node: over REST from PVE 9.3, else
|
||||||
|
with ``ha-manager`` over SSH."""
|
||||||
names = [m.name for m in self._cluster_members()]
|
names = [m.name for m in self._cluster_members()]
|
||||||
if node not in names:
|
if node not in names:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"{node!r} is not a member of the cluster (members: {', '.join(names)})"
|
f"{node!r} is not a member of the cluster (members: {', '.join(names)})"
|
||||||
)
|
)
|
||||||
action = "enable" if enabled else "disable"
|
action = "enable" if enabled else "disable"
|
||||||
|
# The request is served by *node* itself, which may not run 9.3 yet mid-upgrade.
|
||||||
|
try:
|
||||||
|
over_rest = self._version_at_least(*PVE_9_3, node=node)
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the Proxmox VE version of {node!r}: {exc}") from exc
|
||||||
|
if over_rest:
|
||||||
|
try:
|
||||||
|
self._api.nodes(node).maintenance.put(**{"maintenance-mode": action})
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Proxmox VE refused to {action} maintenance of {node!r}: {exc}"
|
||||||
|
) from exc
|
||||||
|
return
|
||||||
|
self._ha_manager_maintenance(node, action)
|
||||||
|
|
||||||
|
def _ha_manager_maintenance(self, node: str, action: str) -> None:
|
||||||
try:
|
try:
|
||||||
self._node_ssh()
|
self._node_ssh()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
|||||||
@@ -20,10 +20,26 @@ import logging
|
|||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The QMP states of a guest whose QEMU process holds its memory but does not run it:
|
||||||
|
#: paused (``status/suspend``, the GUI's Pause) and asleep in S3. ``status/resume``
|
||||||
|
#: brings either back. PVE's ``status`` says ``running`` for both (NetOrk/netork#2658).
|
||||||
|
PAUSED_QMP_STATES = ("paused", "suspended")
|
||||||
|
|
||||||
|
|
||||||
|
def qemu_status(vm: _JsonDict) -> str:
|
||||||
|
"""A QEMU guest's status as the contract names it: ``paused`` where PVE's full
|
||||||
|
status (``qmpstatus``) says the running process does not execute the guest."""
|
||||||
|
status = str(vm.get("status", "unknown"))
|
||||||
|
if status == "running" and vm.get("qmpstatus") in PAUSED_QMP_STATES:
|
||||||
|
return "paused"
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxVMMixin:
|
class ProxmoxVMMixin:
|
||||||
"""Mixin providing VM and container NAPALM methods."""
|
"""Mixin providing VM and container NAPALM methods."""
|
||||||
@@ -215,7 +231,7 @@ class ProxmoxVMMixin:
|
|||||||
* vmid (str) - Proxmox VM/container ID, e.g. ``"100"``
|
* vmid (str) - Proxmox VM/container ID, e.g. ``"100"``
|
||||||
* name (str) - display name
|
* name (str) - display name
|
||||||
* type (str) - ``"vm"`` or ``"container"``
|
* type (str) - ``"vm"`` or ``"container"``
|
||||||
* status (str) - ``"running"``, ``"stopped"``, etc.
|
* status (str) - ``"running"``, ``"stopped"``, ``"paused"`` (``qemu_status``)
|
||||||
* vcpus (int) - allocated vCPUs
|
* vcpus (int) - allocated vCPUs
|
||||||
* memory (int) - configured RAM in megabytes
|
* memory (int) - configured RAM in megabytes
|
||||||
* cpu_usage (float) - current CPU utilisation 0.0–1.0 (from last stats cycle)
|
* cpu_usage (float) - current CPU utilisation 0.0–1.0 (from last stats cycle)
|
||||||
@@ -224,15 +240,15 @@ class ProxmoxVMMixin:
|
|||||||
* node (str) - cluster node name
|
* node (str) - cluster node name
|
||||||
* interfaces (dict) - network interfaces (NAPALM format + ipv4 field)
|
* interfaces (dict) - network interfaces (NAPALM format + ipv4 field)
|
||||||
* ipv4 (str) - primary IPv4 address (empty string if unknown)
|
* ipv4 (str) - primary IPv4 address (empty string if unknown)
|
||||||
|
* uid (str) - PVE 9.3's identity of the guest (``_with_uids``); absent before
|
||||||
"""
|
"""
|
||||||
result: list[_JsonDict] = []
|
result: list[_JsonDict] = []
|
||||||
|
# QEMU VMs; only the full status has ``qmpstatus``, which tells paused from running.
|
||||||
# QEMU VMs
|
|
||||||
try:
|
try:
|
||||||
for vm in self._node_api().qemu.get() or []:
|
for vm in self._node_api().qemu.get(full=1) or []:
|
||||||
vmid = int(vm.get("vmid", 0))
|
vmid = int(vm.get("vmid", 0))
|
||||||
name = vm.get("name", f"vm-{vmid}")
|
name = vm.get("name", f"vm-{vmid}")
|
||||||
status = vm.get("status", "unknown")
|
status = qemu_status(vm)
|
||||||
cpu_usage = float(vm.get("cpu", 0.0) or 0.0)
|
cpu_usage = float(vm.get("cpu", 0.0) or 0.0)
|
||||||
uptime = int(vm.get("uptime", 0) or 0)
|
uptime = int(vm.get("uptime", 0) or 0)
|
||||||
|
|
||||||
@@ -321,7 +337,36 @@ class ProxmoxVMMixin:
|
|||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("get_vms: failed to list LXC containers: %s", exc)
|
logger.warning("get_vms: failed to list LXC containers: %s", exc)
|
||||||
|
|
||||||
return sorted(result, key=lambda x: int(x["vmid"]))
|
return self._with_uids(sorted(result, key=lambda x: int(x["vmid"])))
|
||||||
|
|
||||||
|
def _with_uids(self, vms: list[_JsonDict]) -> list[_JsonDict]:
|
||||||
|
"""Give each guest in *vms* its ``uid``, joined by node and vmid.
|
||||||
|
|
||||||
|
PVE 9.3 gives every guest a random identifier that survives a migration, a
|
||||||
|
restore and a changed vmid; only ``GET /cluster/resources?type=vm`` reports
|
||||||
|
it. A guest without one, an older node and a listing that cannot be read
|
||||||
|
leave the key out: the guest is still listed, known by its vmid alone.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
uids = self._guest_uids()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("get_vms: cannot read the guests' uids: %s", exc)
|
||||||
|
return vms
|
||||||
|
for vm in vms:
|
||||||
|
uid = uids.get((vm["node"], vm["vmid"]))
|
||||||
|
if uid:
|
||||||
|
vm["uid"] = uid
|
||||||
|
return vms
|
||||||
|
|
||||||
|
def _guest_uids(self) -> dict[tuple[str, str], str]:
|
||||||
|
if not self._version_at_least(*PVE_9_3):
|
||||||
|
return {}
|
||||||
|
rows = self._api.cluster.resources.get(type="vm") or []
|
||||||
|
return {
|
||||||
|
(str(row.get("node")), str(row.get("vmid"))): str(row["uid"])
|
||||||
|
for row in rows
|
||||||
|
if row.get("uid")
|
||||||
|
}
|
||||||
|
|
||||||
# Disk-key prefixes for QEMU: scsi, virtio, ide, sata (exclude cdrom/none entries)
|
# Disk-key prefixes for QEMU: scsi, virtio, ide, sata (exclude cdrom/none entries)
|
||||||
_DISK_KEYS_VM = re.compile(r"^(scsi|virtio|ide|sata)\d+$")
|
_DISK_KEYS_VM = re.compile(r"^(scsi|virtio|ide|sata)\d+$")
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from napalm_device_types.provisioning import (
|
|||||||
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
||||||
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||||
from napalm_proxmox.utils import cpu_flags
|
from napalm_proxmox.utils import cpu_flags
|
||||||
|
from napalm_proxmox.vm_mixin import qemu_status
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
|
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
|
||||||
@@ -874,6 +875,11 @@ class ProxmoxVMProvisionMixin:
|
|||||||
"""
|
"""
|
||||||
Get the runtime status of a virtual machine.
|
Get the runtime status of a virtual machine.
|
||||||
|
|
||||||
|
The status is what ``GET /nodes/{node}/qemu/{vmid}/status/current`` says:
|
||||||
|
``running``, ``stopped``, or ``paused`` where its ``qmpstatus`` is paused or
|
||||||
|
suspended (``qemu_status``, as ``get_vms()`` lists it). Only a running VM's
|
||||||
|
guest agent is asked for an address (NAPALM/napalm-proxmox#72).
|
||||||
|
|
||||||
Optionally waits for the guest-agent to report an IP address on the
|
Optionally waits for the guest-agent to report an IP address on the
|
||||||
management NIC (net0), useful after provisioning.
|
management NIC (net0), useful after provisioning.
|
||||||
|
|
||||||
@@ -885,70 +891,36 @@ class ProxmoxVMProvisionMixin:
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
||||||
(ip_address, hostname, mac_address only if VM is running and has network info)
|
(ip_address, hostname, mac_address only if VM is running and has network
|
||||||
|
info); {"status": "unknown"} when Proxmox gives no status for the vmid.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
RuntimeError: VM doesn't exist or wait_for_ip times out
|
RuntimeError: wait_for_ip times out, or the VM is not running while
|
||||||
|
waiting (a stopped or paused VM reports no address)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
vmid_int = int(vmid)
|
vm = self._node_api().qemu(int(vmid))
|
||||||
_logger.debug(f"Getting status for VM {vmid}")
|
_logger.debug(f"Getting status for VM {vmid}")
|
||||||
|
# The VM must exist / be readable before we start polling.
|
||||||
# VM must exist / be readable before we start polling.
|
status = self._qemu_current_status(vm, vmid)
|
||||||
try:
|
if status is None:
|
||||||
self._node_api().qemu(vmid_int).config.get()
|
|
||||||
except Exception:
|
|
||||||
# VM may not exist yet or config not readable
|
|
||||||
return {"status": "unknown"}
|
return {"status": "unknown"}
|
||||||
|
|
||||||
# Polling loop
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
while True:
|
while True:
|
||||||
elapsed = time.time() - start_time
|
if status != "running":
|
||||||
if wait_for_ip and elapsed > timeout:
|
if wait_for_ip:
|
||||||
|
raise RuntimeError(f"VM {vmid} is {status}: it reports no IP address")
|
||||||
|
return {"status": status}
|
||||||
|
if wait_for_ip and time.time() - start_time > timeout:
|
||||||
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
||||||
|
address = self._guest_agent_address(vm, vmid)
|
||||||
try:
|
if address is not None:
|
||||||
# Query guest-agent network interfaces. Proxmox's REST path is
|
return {"status": "running", **address}
|
||||||
# "network-get-interfaces" (hyphens) — it must be passed as a
|
|
||||||
# resource id via __call__, not dotted attribute access (which
|
|
||||||
# would silently build a non-existent "network_get_interfaces"
|
|
||||||
# path and 404 on every poll).
|
|
||||||
agent_info = (
|
|
||||||
self._node_api().qemu(vmid_int).agent("network-get-interfaces").get()
|
|
||||||
)
|
|
||||||
interfaces = (agent_info or {}).get("result", [])
|
|
||||||
|
|
||||||
# The guest agent does not report interfaces in a fixed order —
|
|
||||||
# loopback commonly comes first, named "lo" on Linux and
|
|
||||||
# "lo0" on the BSDs. Skip loopback addresses, whatever the
|
|
||||||
# interface is called, and take the first IPv4 address.
|
|
||||||
for iface in interfaces:
|
|
||||||
name = iface.get("name", "")
|
|
||||||
if not name:
|
|
||||||
continue
|
|
||||||
for addr in iface.get("ip-addresses", []):
|
|
||||||
if addr.get("ip-address-type") != "ipv4":
|
|
||||||
continue
|
|
||||||
ip_addr = addr.get("ip-address", "")
|
|
||||||
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
|
||||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
|
||||||
return {
|
|
||||||
"status": "running",
|
|
||||||
"ip_address": ip_addr,
|
|
||||||
"hostname": name,
|
|
||||||
"mac_address": iface.get("hardware-address", ""),
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
|
||||||
|
|
||||||
if not wait_for_ip:
|
if not wait_for_ip:
|
||||||
# Return immediate status without IP
|
|
||||||
return {"status": "running"}
|
return {"status": "running"}
|
||||||
|
|
||||||
# Wait before next poll
|
|
||||||
time.sleep(poll_interval)
|
time.sleep(poll_interval)
|
||||||
|
# A status that does not read this round keeps the last one.
|
||||||
|
status = self._qemu_current_status(vm, vmid) or status
|
||||||
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
raise
|
raise
|
||||||
@@ -956,6 +928,48 @@ class ProxmoxVMProvisionMixin:
|
|||||||
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
||||||
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _qemu_current_status(vm: Any, vmid: str) -> str | None:
|
||||||
|
"""The VM's status from ``status/current``; None when it does not read."""
|
||||||
|
try:
|
||||||
|
return qemu_status(vm.status.current.get() or {})
|
||||||
|
except Exception as e:
|
||||||
|
_logger.debug(f"Could not read the status of VM {vmid}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _guest_agent_address(vm: Any, vmid: str) -> dict[str, str] | None:
|
||||||
|
"""The first non-loopback IPv4 address the guest agent reports, or None."""
|
||||||
|
try:
|
||||||
|
# Proxmox's REST path is "network-get-interfaces" (hyphens) — it must
|
||||||
|
# be passed as a resource id via __call__, not dotted attribute access
|
||||||
|
# (which would silently build a non-existent "network_get_interfaces"
|
||||||
|
# path and 404 on every poll).
|
||||||
|
agent_info = vm.agent("network-get-interfaces").get()
|
||||||
|
except Exception as e:
|
||||||
|
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
||||||
|
return None
|
||||||
|
# The guest agent does not report interfaces in a fixed order — loopback
|
||||||
|
# commonly comes first, named "lo" on Linux and "lo0" on the BSDs. Skip
|
||||||
|
# loopback addresses, whatever the interface is called, and take the first
|
||||||
|
# IPv4 address.
|
||||||
|
for iface in (agent_info or {}).get("result", []):
|
||||||
|
name = iface.get("name", "")
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
for addr in iface.get("ip-addresses", []):
|
||||||
|
if addr.get("ip-address-type") != "ipv4":
|
||||||
|
continue
|
||||||
|
ip_addr = addr.get("ip-address", "")
|
||||||
|
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
||||||
|
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||||
|
return {
|
||||||
|
"ip_address": ip_addr,
|
||||||
|
"hostname": name,
|
||||||
|
"mac_address": iface.get("hardware-address", ""),
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
|
||||||
def get_network_targets(self) -> list[NetworkTargetDict]:
|
def get_network_targets(self) -> list[NetworkTargetDict]:
|
||||||
"""
|
"""
|
||||||
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
|
ZABBIX_AGENT_PURPOSE,
|
||||||
FixStepOutcomeDict,
|
FixStepOutcomeDict,
|
||||||
ZabbixAgentMixin,
|
ZabbixAgentMixin,
|
||||||
ZabbixAgentSettingsDict,
|
ZabbixAgentSettingsDict,
|
||||||
@@ -53,7 +54,14 @@ class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
|
|||||||
return {"ok": True, "output": "; ".join(changes)}
|
return {"ok": True, "output": "; ".join(changes)}
|
||||||
|
|
||||||
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||||
return self._allow_sources(settings["allowed_sources"], int(settings["listen_port"]), "tcp")
|
return self._allow_sources(
|
||||||
|
settings["allowed_sources"], int(settings["listen_port"]), "tcp", ZABBIX_AGENT_PURPOSE
|
||||||
|
)
|
||||||
|
|
||||||
|
def _revoke_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||||
|
"""For an active-only agent: remove the ufw rules recorded for the agent on an
|
||||||
|
earlier passive run, whatever port they opened (NetOrk/netork#2693)."""
|
||||||
|
return self._revoke_sources(ZABBIX_AGENT_PURPOSE, int(settings["listen_port"]), "tcp")
|
||||||
|
|
||||||
if TYPE_CHECKING: # pragma: no cover - ProxmoxHostMixin's
|
if TYPE_CHECKING: # pragma: no cover - ProxmoxHostMixin's
|
||||||
|
|
||||||
@@ -64,5 +72,7 @@ class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
|
|||||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
|
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
|
||||||
|
|
||||||
def _allow_sources(
|
def _allow_sources(
|
||||||
self, allowed: list[str], port: int, proto: str
|
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||||
) -> FixStepOutcomeDict: ...
|
) -> FixStepOutcomeDict: ...
|
||||||
|
|
||||||
|
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ...
|
||||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "napalm-proxmox"
|
name = "napalm-proxmox"
|
||||||
version = "0.10.0"
|
version = "0.19.0"
|
||||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -21,7 +21,7 @@ classifiers = [
|
|||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"napalm>=5.0.0",
|
"napalm>=5.0.0",
|
||||||
"napalm_device_types>=4.40.0", # ZabbixAgentMixin
|
"napalm_device_types>=4.53.0", # CpuMicrocodeMixin; virtualization in the hardening
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||||
"proxmoxer>=2.0.0",
|
"proxmoxer>=2.0.0",
|
||||||
"netaddr>=0.9.0",
|
"netaddr>=0.9.0",
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 37,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 37,
|
||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 21,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 21,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 18,
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 18,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 12
|
||||||
},
|
},
|
||||||
"function_lines": {
|
"function_lines": {
|
||||||
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 220,
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 220,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 92
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 63
|
||||||
},
|
},
|
||||||
"mypy_relaxed": [
|
"mypy_relaxed": [
|
||||||
"napalm_proxmox.config_mixin",
|
"napalm_proxmox.config_mixin",
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
|
||||||
|
|
||||||
|
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
|
||||||
|
driver set: ``{name, issuer, valid_from, valid_to, in_use_by}`` with Unix
|
||||||
|
timestamps, so netOrk's expiry warnings apply to a Proxmox node as to any device.
|
||||||
|
The source is ``GET /nodes/{node}/certificates/info`` (PBS:
|
||||||
|
``/nodes/localhost/certificates/info``), and one more call, the node's
|
||||||
|
``config``, tells whether ACME renews the certificate the proxy serves.
|
||||||
|
|
||||||
|
The responses are shaped as Proxmox VE 8 and PBS 3 answer (``pvenode cert info``,
|
||||||
|
``proxmox-backup-manager cert info``), the PEM left out.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from proxmoxer.core import ResourceException
|
||||||
|
|
||||||
|
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
from tests.pbs_fake import FakePbsApi
|
||||||
|
|
||||||
|
ROOT_CA = {
|
||||||
|
"filename": "pve-root-ca.pem",
|
||||||
|
"fingerprint": "5E:41:...:0A",
|
||||||
|
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
|
||||||
|
"notafter": 2017526400,
|
||||||
|
"notbefore": 1702166400,
|
||||||
|
"public-key-bits": 2048,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": [],
|
||||||
|
"subject": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
|
||||||
|
}
|
||||||
|
PVE_SSL = {
|
||||||
|
"filename": "pve-ssl.pem",
|
||||||
|
"fingerprint": "A1:B2:...:C3",
|
||||||
|
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
|
||||||
|
"notafter": 1765238400,
|
||||||
|
"notbefore": 1702166400,
|
||||||
|
"public-key-bits": 2048,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": [
|
||||||
|
"127.0.0.1",
|
||||||
|
"0000:0000:0000:0000:0000:0000:0000:0001",
|
||||||
|
"localhost",
|
||||||
|
"pve1",
|
||||||
|
"pve1.example.com",
|
||||||
|
],
|
||||||
|
"subject": "/OU=PVE Cluster Node/O=Proxmox Virtual Environment/CN=pve1.example.com",
|
||||||
|
}
|
||||||
|
PVEPROXY_SSL = {
|
||||||
|
"filename": "pveproxy-ssl.pem",
|
||||||
|
"fingerprint": "D4:E5:...:F6",
|
||||||
|
"issuer": "/C=US/O=Let's Encrypt/CN=R11",
|
||||||
|
"notafter": 1771977600,
|
||||||
|
"notbefore": 1764201600,
|
||||||
|
"public-key-bits": 2048,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": ["pve1.example.com"],
|
||||||
|
"subject": "/CN=pve1.example.com",
|
||||||
|
}
|
||||||
|
ACME_CONFIG = {
|
||||||
|
"acme": "account=default",
|
||||||
|
"acmedomain0": "domain=pve1.example.com,plugin=cloudflare",
|
||||||
|
"digest": "4f0c...",
|
||||||
|
}
|
||||||
|
|
||||||
|
PROXY_PEM = {
|
||||||
|
"filename": "proxy.pem",
|
||||||
|
"fingerprint": "0A:1B:...:2C",
|
||||||
|
"issuer": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
|
||||||
|
"notafter": 2017526400,
|
||||||
|
"notbefore": 1702166400,
|
||||||
|
"public-key-bits": 4096,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": ["IP Address:127.0.0.1", "DNS:localhost", "DNS:pbs1", "DNS:pbs1.example.com"],
|
||||||
|
"subject": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _pve(info: Any, config: Any = None) -> tuple[ProxmoxDriver, Any]:
|
||||||
|
driver = ProxmoxDriver(
|
||||||
|
"pve1.example.com", "root", "secret", optional_args={"verify_ssl": False}
|
||||||
|
)
|
||||||
|
api = _build_mock_api()
|
||||||
|
node = api.nodes.return_value
|
||||||
|
if isinstance(info, Exception):
|
||||||
|
node.certificates.info.get.side_effect = info
|
||||||
|
else:
|
||||||
|
node.certificates.info.get.return_value = info
|
||||||
|
if isinstance(config, Exception):
|
||||||
|
node.config.get.side_effect = config
|
||||||
|
else:
|
||||||
|
node.config.get.return_value = config or {}
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||||
|
driver.open()
|
||||||
|
return driver, api
|
||||||
|
|
||||||
|
|
||||||
|
def _pbs(**responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi]:
|
||||||
|
api = FakePbsApi(**responses)
|
||||||
|
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
|
||||||
|
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
|
||||||
|
driver.open()
|
||||||
|
return driver, api
|
||||||
|
|
||||||
|
|
||||||
|
# -- Proxmox VE -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_certificate_of_the_node_in_the_contract_shape() -> None:
|
||||||
|
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL])
|
||||||
|
|
||||||
|
certs = driver.get_certificates()
|
||||||
|
|
||||||
|
api.nodes.assert_any_call("pve1")
|
||||||
|
assert certs == [
|
||||||
|
{
|
||||||
|
"name": "pve-root-ca.pem",
|
||||||
|
"issuer": "Proxmox Virtual Environment",
|
||||||
|
"valid_from": 1702166400,
|
||||||
|
"valid_to": 2017526400,
|
||||||
|
"in_use_by": 0,
|
||||||
|
"subject": "Proxmox Virtual Environment",
|
||||||
|
"fingerprint": "5E:41:...:0A",
|
||||||
|
"acme": False,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pve-ssl.pem",
|
||||||
|
"issuer": "Proxmox Virtual Environment",
|
||||||
|
"valid_from": 1702166400,
|
||||||
|
"valid_to": 1765238400,
|
||||||
|
"in_use_by": 0,
|
||||||
|
"subject": "pve1.example.com",
|
||||||
|
"fingerprint": "A1:B2:...:C3",
|
||||||
|
"acme": False,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pveproxy-ssl.pem",
|
||||||
|
"issuer": "R11",
|
||||||
|
"valid_from": 1764201600,
|
||||||
|
"valid_to": 1771977600,
|
||||||
|
"in_use_by": 1,
|
||||||
|
"subject": "pve1.example.com",
|
||||||
|
"fingerprint": "D4:E5:...:F6",
|
||||||
|
"acme": False,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_timestamps_are_integers() -> None:
|
||||||
|
driver, _ = _pve([{**PVE_SSL, "notafter": "1765238400", "notbefore": None}])
|
||||||
|
|
||||||
|
(cert,) = driver.get_certificates()
|
||||||
|
|
||||||
|
assert cert["valid_to"] == 1765238400
|
||||||
|
assert cert["valid_from"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_a_custom_certificate_pveproxy_serves_pve_ssl() -> None:
|
||||||
|
driver, _ = _pve([ROOT_CA, PVE_SSL])
|
||||||
|
|
||||||
|
in_use = {c["name"]: c["in_use_by"] for c in driver.get_certificates()}
|
||||||
|
|
||||||
|
assert in_use == {"pve-root-ca.pem": 0, "pve-ssl.pem": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_renews_the_certificate_pveproxy_serves() -> None:
|
||||||
|
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL], ACME_CONFIG)
|
||||||
|
|
||||||
|
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
|
||||||
|
|
||||||
|
assert acme == {"pve-root-ca.pem": False, "pve-ssl.pem": False, "pveproxy-ssl.pem": True}
|
||||||
|
# One call more than the certificates: the node's config.
|
||||||
|
api.nodes.return_value.config.get.assert_called_once_with()
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_in_its_older_form_names_the_domains_in_acme() -> None:
|
||||||
|
config = {"acme": "account=default,domains=pve1.example.com"}
|
||||||
|
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], config)
|
||||||
|
|
||||||
|
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
|
||||||
|
|
||||||
|
assert acme == {"pve-ssl.pem": False, "pveproxy-ssl.pem": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_acme_account_without_domains_renews_nothing() -> None:
|
||||||
|
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], {"acme": "account=default"})
|
||||||
|
|
||||||
|
assert not any(c["acme"] for c in driver.get_certificates())
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_never_renews_pve_ssl() -> None:
|
||||||
|
# Without pveproxy-ssl.pem there is no ACME certificate yet, even with domains set.
|
||||||
|
driver, _ = _pve([ROOT_CA, PVE_SSL], ACME_CONFIG)
|
||||||
|
|
||||||
|
assert not any(c["acme"] for c in driver.get_certificates())
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unreadable_config_reads_as_no_acme() -> None:
|
||||||
|
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], ResourceException(403, "Forbidden", "no Sys.Audit"))
|
||||||
|
|
||||||
|
certs = driver.get_certificates()
|
||||||
|
|
||||||
|
assert [c["name"] for c in certs] == ["pve-ssl.pem", "pveproxy-ssl.pem"]
|
||||||
|
assert not any(c["acme"] for c in certs)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreadable_certificates_are_none_rather_than_a_failed_poll() -> None:
|
||||||
|
driver, api = _pve(ResourceException(403, "Forbidden", "no Sys.Audit"))
|
||||||
|
|
||||||
|
assert driver.get_certificates() == []
|
||||||
|
api.nodes.return_value.config.get.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
# -- Proxmox Backup Server ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_localhost() -> None:
|
||||||
|
driver, api = _pbs(
|
||||||
|
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": {}}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert driver.get_certificates() == [
|
||||||
|
{
|
||||||
|
"name": "proxy.pem",
|
||||||
|
"issuer": "pbs1.example.com",
|
||||||
|
"valid_from": 1702166400,
|
||||||
|
"valid_to": 2017526400,
|
||||||
|
"in_use_by": 1,
|
||||||
|
"subject": "pbs1.example.com",
|
||||||
|
"fingerprint": "0A:1B:...:2C",
|
||||||
|
"acme": False,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
assert ("GET", "nodes/localhost/certificates/info", {}) in api.calls
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_renews_the_backup_servers_proxy_certificate() -> None:
|
||||||
|
config = {"acme": "account=default", "acmedomain0": "domain=pbs1.example.com"}
|
||||||
|
driver, _ = _pbs(
|
||||||
|
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": config}
|
||||||
|
)
|
||||||
|
|
||||||
|
(cert,) = driver.get_certificates()
|
||||||
|
|
||||||
|
assert cert["acme"] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
|
||||||
|
def test_both_drivers_have_it(cls: type) -> None:
|
||||||
|
assert callable(getattr(cls, "get_certificates", None))
|
||||||
@@ -266,6 +266,11 @@ class TestCluster:
|
|||||||
def test_every_member_listed_in_cluster_order(self):
|
def test_every_member_listed_in_cluster_order(self):
|
||||||
assert [n["name"] for n in _cluster()["nodes"]] == ["pve1", "pve2", "pve3"]
|
assert [n["name"] for n in _cluster()["nodes"]] == ["pve1", "pve2", "pve3"]
|
||||||
|
|
||||||
|
def test_pve_9_3_names_the_cluster_by_its_id(self):
|
||||||
|
"""``cluster-id``: a random identifier, kept when the cluster is renamed."""
|
||||||
|
status = [dict(CLUSTER_STATUS[0], **{"cluster-id": "a1b2c3d4e5"}), *CLUSTER_STATUS[1:]]
|
||||||
|
assert _cluster(cluster_status=status)["id"] == "a1b2c3d4e5"
|
||||||
|
|
||||||
|
|
||||||
class TestNodes:
|
class TestNodes:
|
||||||
def test_online_node(self):
|
def test_online_node(self):
|
||||||
@@ -349,6 +354,12 @@ class TestStandalone:
|
|||||||
assert node["memory_total"] == 128 * GIB
|
assert node["memory_total"] == 128 * GIB
|
||||||
assert _by_name(cluster["storages"])["local"]["nodes"] == ["pve1"]
|
assert _by_name(cluster["storages"])["local"]["nodes"] == ["pve1"]
|
||||||
|
|
||||||
|
def test_pve_9_3_names_a_standalone_node_by_its_own_id(self):
|
||||||
|
status = [dict(self.STATUS[0], **{"cluster-id": "f6e5d4c3b2"})]
|
||||||
|
cluster = _cluster(cluster_status=status, resources=self.RESOURCES, ha=RuntimeError())
|
||||||
|
assert cluster["id"] == "f6e5d4c3b2"
|
||||||
|
assert cluster["name"] is None
|
||||||
|
|
||||||
|
|
||||||
class TestStorages:
|
class TestStorages:
|
||||||
def test_local_storage_grouped_over_its_nodes(self):
|
def test_local_storage_grouped_over_its_nodes(self):
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""When the credential the driver logs in with stops working (NetOrk/netork#2728).
|
||||||
|
|
||||||
|
PVE 9.3's datacenter ``token-policy`` can require an expiry on every API token;
|
||||||
|
the platform keeps one on every token and account anyway. A token is read with
|
||||||
|
``GET /access/users/{userid}/token/{tokenid}``; a token without an ``expire``
|
||||||
|
of its own expires with its user (``default: same as user``), read with
|
||||||
|
``GET /access/users/{userid}``, which is also where a password's account says
|
||||||
|
when it expires. ``0`` is never.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from proxmoxer.core import ResourceException
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
|
||||||
|
|
||||||
|
def _driver(**optional_args: Any) -> tuple[ProxmoxDriver, MagicMock]:
|
||||||
|
password = "" if optional_args else "secret"
|
||||||
|
drv = ProxmoxDriver("pve1", "netork", password, optional_args=optional_args)
|
||||||
|
api = _build_mock_api()
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||||
|
drv.open()
|
||||||
|
return drv, api
|
||||||
|
|
||||||
|
|
||||||
|
def _token_driver(token_name: str = "netork@pve!poll") -> tuple[ProxmoxDriver, MagicMock]:
|
||||||
|
return _driver(token_name=token_name, token_value="s3cret", realm="pve")
|
||||||
|
|
||||||
|
|
||||||
|
def _forbidden() -> ResourceException:
|
||||||
|
return ResourceException(403, "Forbidden", "Permission check failed (/access, User.Modify)")
|
||||||
|
|
||||||
|
|
||||||
|
class TestApiToken:
|
||||||
|
def test_the_tokens_own_expiry(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {
|
||||||
|
"expire": 1767225600,
|
||||||
|
"privsep": 1,
|
||||||
|
}
|
||||||
|
assert drv.get_credential_expiry() == {
|
||||||
|
"kind": "api-token",
|
||||||
|
"name": "netork@pve!poll",
|
||||||
|
"expires": 1767225600,
|
||||||
|
}
|
||||||
|
api.access.users.assert_called_with("netork@pve")
|
||||||
|
api.access.users.return_value.token.assert_called_once_with("poll")
|
||||||
|
|
||||||
|
def test_zero_never_expires(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||||
|
assert drv.get_credential_expiry()["expires"] is None
|
||||||
|
api.access.users.return_value.get.assert_not_called()
|
||||||
|
|
||||||
|
def test_a_token_without_expiry_expires_with_its_user(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {"privsep": 1}
|
||||||
|
api.access.users.return_value.get.return_value = {
|
||||||
|
"userid": "netork@pve",
|
||||||
|
"expire": 1798761600,
|
||||||
|
}
|
||||||
|
assert drv.get_credential_expiry()["expires"] == 1798761600
|
||||||
|
|
||||||
|
def test_a_token_name_without_user_is_the_login_users(self):
|
||||||
|
drv, api = _token_driver(token_name="poll")
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||||
|
assert drv.get_credential_expiry()["name"] == "netork@pve!poll"
|
||||||
|
api.access.users.assert_called_with("netork@pve")
|
||||||
|
|
||||||
|
def test_a_refused_read_is_a_permission_error(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError, match="User.Modify"):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
def test_a_refused_read_of_the_user_is_a_permission_error(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {}
|
||||||
|
api.access.users.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
|
||||||
|
class TestAccount:
|
||||||
|
def test_a_password_login_reads_its_account(self):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.return_value = {
|
||||||
|
"userid": "netork@pam",
|
||||||
|
"expire": 1767225600,
|
||||||
|
}
|
||||||
|
assert drv.get_credential_expiry() == {
|
||||||
|
"kind": "account",
|
||||||
|
"name": "netork@pam",
|
||||||
|
"expires": 1767225600,
|
||||||
|
}
|
||||||
|
api.access.users.assert_called_with("netork@pam")
|
||||||
|
|
||||||
|
def test_an_account_without_expiry_never_expires(self):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.return_value = {"userid": "netork@pam", "enable": 1}
|
||||||
|
assert drv.get_credential_expiry()["expires"] is None
|
||||||
|
|
||||||
|
def test_a_refused_read_is_a_permission_error(self):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"error",
|
||||||
|
[
|
||||||
|
ResourceException(500, "Internal Server Error", "cfs lock timeout"),
|
||||||
|
ConnectionError("reset"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_another_failure_is_a_runtime_error(self, error):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.side_effect = error
|
||||||
|
with pytest.raises(RuntimeError, match="netork@pam"):
|
||||||
|
drv.get_credential_expiry()
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"""The PVE firewall, read only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall`` reads the datacenter level -- options, rules, security groups,
|
||||||
|
IP sets, aliases -- the node's options and rules, and every guest's on the node with
|
||||||
|
which of its NICs carry ``firewall=1``. Each rule says where it came from. A level
|
||||||
|
PVE refuses is None, not empty. ``get_host_firewall`` reads what the node has loaded
|
||||||
|
(``nft list ruleset`` / ``iptables-save``), as for any Linux host.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.firewall_mixin import nic_firewalls
|
||||||
|
|
||||||
|
DC_OPTIONS = {"enable": 1, "policy_in": "DROP", "policy_out": "ACCEPT"}
|
||||||
|
DC_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"macro": "SSH",
|
||||||
|
"source": "+dc/admins",
|
||||||
|
"enable": 1,
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
GROUP_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "proto": "tcp", "dport": "80,443", "enable": 1}
|
||||||
|
]
|
||||||
|
IPSET = [{"cidr": "198.51.100.0/24", "comment": "office"}, {"cidr": "198.51.100.7", "nomatch": 1}]
|
||||||
|
ALIASES = [{"name": "monitor", "cidr": "203.0.113.5/32", "comment": "zabbix"}]
|
||||||
|
NODE_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "dport": "8006", "proto": "tcp", "enable": 0}
|
||||||
|
]
|
||||||
|
GUEST_OPTIONS = {"enable": 1, "policy_in": "DROP"}
|
||||||
|
GUEST_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"enable": 1,
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _api() -> MagicMock:
|
||||||
|
api = MagicMock()
|
||||||
|
fw = api.cluster.firewall
|
||||||
|
fw.options.get.return_value = DC_OPTIONS
|
||||||
|
fw.rules.get.return_value = DC_RULES
|
||||||
|
fw.groups.get.return_value = [{"group": "web", "comment": "web servers"}]
|
||||||
|
fw.groups.return_value.get.return_value = GROUP_RULES
|
||||||
|
fw.ipset.get.return_value = [{"name": "admins"}]
|
||||||
|
fw.ipset.return_value.get.return_value = IPSET
|
||||||
|
fw.aliases.get.return_value = ALIASES
|
||||||
|
node = api.nodes.return_value
|
||||||
|
node.firewall.options.get.return_value = {"enable": 1}
|
||||||
|
node.firewall.rules.get.return_value = NODE_RULES
|
||||||
|
node.qemu.get.return_value = [{"vmid": 100, "name": "web-01"}]
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
vm.firewall.options.get.return_value = GUEST_OPTIONS
|
||||||
|
vm.firewall.rules.get.return_value = GUEST_RULES
|
||||||
|
vm.config.get.return_value = {
|
||||||
|
"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=1",
|
||||||
|
"net1": "virtio=AA:BB:CC:DD:EE:02,bridge=vmbr1",
|
||||||
|
"name": "web-01",
|
||||||
|
}
|
||||||
|
node.lxc.get.return_value = [{"vmid": 200, "name": "dns-01"}]
|
||||||
|
ct = node.lxc.return_value
|
||||||
|
ct.firewall.options.get.return_value = {}
|
||||||
|
ct.firewall.rules.get.return_value = []
|
||||||
|
ct.config.get.return_value = {"net0": "name=eth0,bridge=vmbr0,firewall=1,ip=dhcp"}
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fw_driver(driver):
|
||||||
|
driver._api = _api()
|
||||||
|
return driver
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheDatacenter:
|
||||||
|
def test_options_rules_groups_ipsets_aliases(self, fw_driver):
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["options"] == DC_OPTIONS
|
||||||
|
assert [
|
||||||
|
(r["origin"], r["type"], r.get("macro"), r["enable"]) for r in cluster["rules"]
|
||||||
|
] == [
|
||||||
|
("cluster", "in", "SSH", True),
|
||||||
|
("cluster", "group", None, True),
|
||||||
|
]
|
||||||
|
assert cluster["groups"] == {
|
||||||
|
"web": [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "80,443",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "group",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["ipsets"] == {
|
||||||
|
"admins": [
|
||||||
|
{"cidr": "198.51.100.0/24", "nomatch": False, "comment": "office"},
|
||||||
|
{"cidr": "198.51.100.7", "nomatch": True, "comment": None},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
def test_a_level_pve_refuses_is_none_not_empty(self, fw_driver):
|
||||||
|
fw_driver._api.cluster.firewall.ipset.get.side_effect = RuntimeError("403 Forbidden")
|
||||||
|
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["ipsets"] is None
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheNodeAndItsGuests:
|
||||||
|
def test_the_nodes_rules_keep_their_switch(self, fw_driver):
|
||||||
|
node = fw_driver.get_pve_firewall()["node"]
|
||||||
|
|
||||||
|
assert node["name"] == fw_driver._node_name
|
||||||
|
assert node["options"] == {"enable": 1}
|
||||||
|
assert node["rules"][0]["enable"] is False
|
||||||
|
assert node["rules"][0]["origin"] == "node"
|
||||||
|
|
||||||
|
def test_every_guest_with_its_rules_and_nics(self, fw_driver):
|
||||||
|
guests = fw_driver.get_pve_firewall()["guests"]
|
||||||
|
|
||||||
|
assert [(g["vmid"], g["type"], g["name"]) for g in guests] == [
|
||||||
|
("100", "vm", "web-01"),
|
||||||
|
("200", "container", "dns-01"),
|
||||||
|
]
|
||||||
|
vm = guests[0]
|
||||||
|
assert vm["options"] == GUEST_OPTIONS
|
||||||
|
assert vm["rules"][0] == {
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "guest",
|
||||||
|
}
|
||||||
|
assert vm["nics"] == [
|
||||||
|
{"name": "net0", "firewall": True},
|
||||||
|
{"name": "net1", "firewall": False},
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_a_guest_whose_config_is_refused_has_no_nics_reading(self, fw_driver):
|
||||||
|
fw_driver._api.nodes.return_value.qemu.return_value.config.get.side_effect = RuntimeError(
|
||||||
|
"403"
|
||||||
|
)
|
||||||
|
|
||||||
|
vm = fw_driver.get_pve_firewall()["guests"][0]
|
||||||
|
|
||||||
|
assert vm["nics"] is None
|
||||||
|
assert vm["rules"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_nic_without_the_flag_is_not_filtered():
|
||||||
|
assert nic_firewalls({"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=0"}) == [
|
||||||
|
{"name": "net0", "firewall": False}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheLoadedRuleset:
|
||||||
|
def test_the_node_reads_its_netfilter_rules_like_a_linux_host(self, driver):
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
def run(command: str) -> str:
|
||||||
|
seen.append(command)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
driver._exec_ssh_command = run # type: ignore[method-assign]
|
||||||
|
|
||||||
|
assert hasattr(driver, "get_host_firewall")
|
||||||
|
try:
|
||||||
|
driver.get_host_firewall()
|
||||||
|
except Exception:
|
||||||
|
pass # an empty answer is no report; the transport is what is tested here
|
||||||
|
assert seen and "nft" in seen[0] and "iptables-save" in seen[0]
|
||||||
@@ -82,7 +82,8 @@ class TestSnmpAgent:
|
|||||||
def test_no_temp_file_with_an_application_name(self, driver, node):
|
def test_no_temp_file_with_an_application_name(self, driver, node):
|
||||||
driver.configure_snmp_agent(SETTINGS)
|
driver.configure_snmp_agent(SETTINGS)
|
||||||
|
|
||||||
assert not any("netork" in c for c in node.ran)
|
# The record of opened rules (/var/lib/netork, NetOrk/netork#2693) is no temp file.
|
||||||
|
assert not any(re.search(r"/tmp/\S*netork", c) for c in node.ran)
|
||||||
|
|
||||||
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
|
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
|
||||||
node.status["command -v ufw"] = 0
|
node.status["command -v ufw"] = 0
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""`get_hardening`: how the node is hardened (NetOrk/netork#2776).
|
||||||
|
|
||||||
|
A hypervisor is where CPU vulnerabilities matter most: its guests share the CPU.
|
||||||
|
The command and its parse are napalm-device-types' (``HardeningMixin``); both
|
||||||
|
drivers carry the command over their own exec path, which is root's login, so
|
||||||
|
AppArmor's profiles per mode are read as well.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import HardeningMixin
|
||||||
|
|
||||||
|
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
WIRE = "\n".join(
|
||||||
|
[
|
||||||
|
"HARDENING_BEGIN",
|
||||||
|
"[lsm]",
|
||||||
|
"lockdown,capability,landlock,yama,apparmor,bpf",
|
||||||
|
"[cmdline]",
|
||||||
|
"BOOT_IMAGE=/boot/vmlinuz-6.8.12-4-pve root=/dev/mapper/pve-root ro mitigations=off",
|
||||||
|
"[fips]",
|
||||||
|
"0",
|
||||||
|
"[apparmor_enabled]",
|
||||||
|
"Y",
|
||||||
|
"[os]",
|
||||||
|
"ID=debian",
|
||||||
|
"[cpu_vulnerabilities]",
|
||||||
|
"/sys/devices/system/cpu/vulnerabilities/mds:Vulnerable; SMT vulnerable",
|
||||||
|
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected",
|
||||||
|
"HARDENING_END",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_declare_the_contract(cls):
|
||||||
|
assert issubclass(cls, HardeningMixin)
|
||||||
|
assert hasattr(cls, "get_hardening")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_node_runs_the_shared_command_over_its_exec_path(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
reading = driver.get_hardening()
|
||||||
|
|
||||||
|
exec_.assert_called_once()
|
||||||
|
assert "HARDENING_" in exec_.call_args.args[0]
|
||||||
|
assert reading["lsm"] == ["lockdown", "capability", "landlock", "yama", "apparmor", "bpf"]
|
||||||
|
assert reading["mitigations"] == "off"
|
||||||
|
assert reading["cpu_vulnerabilities"]["mds"] == "Vulnerable; SMT vulnerable"
|
||||||
|
assert reading["os_ids"] == ["debian"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_it_the_same_way():
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
|
||||||
|
with patch.object(drv, "_exec_ssh_command", return_value=WIRE):
|
||||||
|
reading = drv.get_hardening()
|
||||||
|
|
||||||
|
assert reading["cpu_vulnerabilities"]["meltdown"] == "Not affected"
|
||||||
|
|
||||||
|
|
||||||
|
def test_output_without_a_report_raises(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_hardening()
|
||||||
|
|
||||||
|
|
||||||
|
class TestCpuMicrocode:
|
||||||
|
"""``install_cpu_microcode`` (napalm-device-types ``CpuMicrocodeMixin``, NetOrk/netork#2838):
|
||||||
|
a node runs on its own CPU, and Proxmox's own install enables no ``non-free-firmware``."""
|
||||||
|
|
||||||
|
SOURCES = "/etc/apt/sources.list.d/debian.sources"
|
||||||
|
TEXT = (
|
||||||
|
"Types: deb\nURIs: http://deb.debian.org/debian/\nSuites: trixie trixie-updates\n"
|
||||||
|
"Components: main contrib\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _node(self, drv, *, virtualization="none"):
|
||||||
|
import base64
|
||||||
|
|
||||||
|
ran: list[str] = []
|
||||||
|
file_lines = "".join(f"|{line}\n" for line in self.TEXT.split("\n"))
|
||||||
|
report = (
|
||||||
|
"ARELEASE_BEGIN\n@@os\n|ID=debian\n|VERSION_CODENAME=trixie\n"
|
||||||
|
f"@@file {self.SOURCES}\n{file_lines}ARELEASE_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def exec_(command):
|
||||||
|
ran.append(command)
|
||||||
|
if command.startswith("base64 "):
|
||||||
|
return base64.b64encode(self.TEXT.encode()).decode()
|
||||||
|
if "ARELEASE_" in command:
|
||||||
|
return report
|
||||||
|
return "done\n__PVE_RC=0"
|
||||||
|
|
||||||
|
drv.get_hardening = lambda: {
|
||||||
|
"os_ids": ["debian"],
|
||||||
|
"virtualization": virtualization,
|
||||||
|
"cpu_vendor": "GenuineIntel",
|
||||||
|
}
|
||||||
|
drv.get_packages = lambda: []
|
||||||
|
drv.refresh_available_updates = lambda: pytest.fail("the API refresh does not wait")
|
||||||
|
drv._exec_ssh_command = exec_
|
||||||
|
return ran
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_carry_it(self, cls):
|
||||||
|
assert callable(getattr(cls, "install_cpu_microcode", None))
|
||||||
|
|
||||||
|
def test_the_component_then_apt_get_update_then_the_package(self, driver):
|
||||||
|
ran = self._node(driver)
|
||||||
|
|
||||||
|
result = driver.install_cpu_microcode()
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
assert result["sources_changed"] is True
|
||||||
|
written = next(c for c in ran if "install -m 644" in c)
|
||||||
|
assert self.SOURCES in written
|
||||||
|
update = next(i for i, c in enumerate(ran) if "apt-get update" in c)
|
||||||
|
install = next(i for i, c in enumerate(ran) if "apt-get install -y intel-microcode" in c)
|
||||||
|
assert ran.index(written) < update < install
|
||||||
|
|
||||||
|
def test_a_virtual_backup_server_installs_nothing(self):
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
ran = self._node(drv, virtualization="kvm")
|
||||||
|
|
||||||
|
result = drv.install_cpu_microcode()
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "its host does" in result["output"]
|
||||||
|
assert ran == []
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Which Proxmox VE release the node runs, for what only newer releases offer.
|
||||||
|
|
||||||
|
``GET /version`` names the pve-manager package's version (``"9.3.0"``) and the
|
||||||
|
point release (``"9.3"``). PVE 9.3 added the REST calls of NetOrk/netork#2728;
|
||||||
|
the driver takes them only on a node that has them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("version", "expected"),
|
||||||
|
[
|
||||||
|
({"version": "9.3.0", "release": "9.3"}, True),
|
||||||
|
({"version": "9.3.2", "release": "9.3"}, True),
|
||||||
|
({"version": "10.0.1", "release": "10.0"}, True),
|
||||||
|
({"version": "9.2.4", "release": "9.2"}, False),
|
||||||
|
({"version": "8.4.1", "release": "8.4"}, False),
|
||||||
|
# No package version: the point release tells.
|
||||||
|
({"release": "9.3"}, True),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_at_least(driver, version, expected):
|
||||||
|
driver._api.version.get.return_value = version
|
||||||
|
assert driver._version_at_least(9, 3) is expected
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("version", [{}, {"version": "unknown", "release": ""}])
|
||||||
|
def test_a_version_it_cannot_read_counts_as_older(driver, version):
|
||||||
|
driver._api.version.get.return_value = version
|
||||||
|
assert driver._version_at_least(9, 3) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_api_error_propagates(driver):
|
||||||
|
driver._api.version.get.side_effect = ConnectionError("node unreachable")
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
driver._version_at_least(9, 3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_another_node_is_asked_for_its_own_version(driver):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
driver._api.nodes("pve2").version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
assert driver._version_at_least(9, 3, node="pve2") is False
|
||||||
|
driver._api.nodes.assert_called_with("pve2")
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""`get_services_need_restart`: the services on the node that still run replaced code.
|
||||||
|
|
||||||
|
An openssl or glibc update replaces the files on disk; every daemon that had them
|
||||||
|
loaded keeps the old code until it restarts (NetOrk/netork#2750). On a hypervisor that
|
||||||
|
is where a restart instead of a reboot matters most. The command and its parse are
|
||||||
|
napalm-device-types' (``ServicesRestartMixin``); the driver only carries the command
|
||||||
|
over its exec path, which runs as root. A login that is not root gets no reading: it
|
||||||
|
would see only its own processes and read as clean.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import ServicesRestartMixin
|
||||||
|
|
||||||
|
from napalm_proxmox import ProxmoxBackupDriver
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
#: A PVE node after an openssl update, read by the /proc scan (no needrestart):
|
||||||
|
#: pveproxy and a running VM's QEMU still map the old library, and so does a
|
||||||
|
#: container's own nginx, which the container updates itself.
|
||||||
|
WIRE = (
|
||||||
|
"RST_BEGIN\n[maps]\n"
|
||||||
|
"2101 pveproxy worker\n"
|
||||||
|
"3100 kvm\n"
|
||||||
|
"4100 nginx\n"
|
||||||
|
"[cgroups]\n"
|
||||||
|
"2101 0::/system.slice/pveproxy.service\n"
|
||||||
|
"3100 0::/qemu.slice/101.scope\n"
|
||||||
|
"4100 0::/lxc/200/ns/system.slice/nginx.service\n"
|
||||||
|
"RST_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("driver_class", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_declare_the_contract(driver_class):
|
||||||
|
assert issubclass(driver_class, ServicesRestartMixin)
|
||||||
|
|
||||||
|
|
||||||
|
def test_it_reads_as_root_over_the_exec_path(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
reading = driver.get_services_need_restart()
|
||||||
|
|
||||||
|
[command] = [c.args[0] for c in exec_.call_args_list]
|
||||||
|
assert command.startswith('[ "$(id -u)" = 0 ] && sh -c \'')
|
||||||
|
assert reading == {
|
||||||
|
"source": "maps",
|
||||||
|
"units": ["pveproxy"],
|
||||||
|
"processes": [{"pid": 3100, "name": "kvm"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_it_the_same_way():
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
wire = "RST_BEGIN\n[needrestart]\nNEEDRESTART-SVC: proxmox-backup-proxy.service\nRST_END\n"
|
||||||
|
|
||||||
|
with patch.object(drv, "_exec_ssh_command", return_value=wire):
|
||||||
|
reading = drv.get_services_need_restart()
|
||||||
|
|
||||||
|
assert reading["units"] == ["proxmox-backup-proxy"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_login_other_than_root_gets_no_reading(driver):
|
||||||
|
"""The guard runs nothing but as root, so no report comes back and the parse raises."""
|
||||||
|
|
||||||
|
def as_this_user(command: str) -> str:
|
||||||
|
return subprocess.run(["sh", "-c", command], capture_output=True, text=True).stdout
|
||||||
|
|
||||||
|
if subprocess.run(["id", "-u"], capture_output=True, text=True).stdout.strip() == "0":
|
||||||
|
pytest.skip("runs as root here")
|
||||||
|
with patch.object(driver, "_exec_ssh_command", side_effect=as_this_user):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_services_need_restart()
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""The node's past APT transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||||
|
|
||||||
|
PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
||||||
|
first. The payload below follows its schema: a transaction is identified by
|
||||||
|
``start-time`` with ``start-index`` (default 0) among those that started in the
|
||||||
|
same second; ``end-time`` is missing while it runs or after it was interrupted.
|
||||||
|
An older node has no such endpoint, and the driver parses no log over SSH.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
HISTORY = [
|
||||||
|
{
|
||||||
|
"start-time": 1764158400,
|
||||||
|
"start-index": 1,
|
||||||
|
"end-time": 1764158460,
|
||||||
|
"command-line": "apt-get -y dist-upgrade",
|
||||||
|
"requested-by": "admin",
|
||||||
|
"requested-by-uid": 1000,
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"package": "openssh-server",
|
||||||
|
"action": "upgrade",
|
||||||
|
"arch": "amd64",
|
||||||
|
"old-version": "1:10.0p1-7",
|
||||||
|
"new-version": "1:10.0p1-7+deb13u1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"package": "proxmox-kernel-6.17.2-1-pve-signed",
|
||||||
|
"action": "install",
|
||||||
|
"new-version": "6.17.2-1",
|
||||||
|
"automatic": 1,
|
||||||
|
},
|
||||||
|
{"package": "ifupdown", "action": "purge", "old-version": "0.8.44"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
# unattended-upgrades, interrupted: no end, no user, the error dpkg left.
|
||||||
|
"start-time": 1764072000,
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"package": "libssl3t64",
|
||||||
|
"action": "upgrade",
|
||||||
|
"old-version": "3.5.1-1",
|
||||||
|
"new-version": "3.5.1-1+deb13u1",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"error": "Sub-process /usr/bin/dpkg returned an error code (1)",
|
||||||
|
"running": 0,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def history(driver) -> MagicMock:
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
getter = driver._node_api().apt.history.get
|
||||||
|
getter.return_value = HISTORY
|
||||||
|
return getter
|
||||||
|
|
||||||
|
|
||||||
|
class TestUpdateHistory:
|
||||||
|
def test_transactions_newest_first(self, driver, history):
|
||||||
|
newest, older = driver.get_update_history()
|
||||||
|
assert newest == {
|
||||||
|
"id": "1764158400-1",
|
||||||
|
"start": 1764158400,
|
||||||
|
"end": 1764158460,
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"name": "openssh-server",
|
||||||
|
"action": "upgrade",
|
||||||
|
"old_version": "1:10.0p1-7",
|
||||||
|
"new_version": "1:10.0p1-7+deb13u1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "proxmox-kernel-6.17.2-1-pve-signed",
|
||||||
|
"action": "install",
|
||||||
|
"old_version": None,
|
||||||
|
"new_version": "6.17.2-1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ifupdown",
|
||||||
|
"action": "purge",
|
||||||
|
"old_version": "0.8.44",
|
||||||
|
"new_version": None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"requested_by": "admin",
|
||||||
|
"command": "apt-get -y dist-upgrade",
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
assert older["id"] == "1764072000-0"
|
||||||
|
history.assert_called_once_with()
|
||||||
|
|
||||||
|
def test_what_the_log_does_not_keep_is_none(self, driver, history):
|
||||||
|
older = driver.get_update_history()[1]
|
||||||
|
assert older["end"] is None
|
||||||
|
assert older["requested_by"] is None
|
||||||
|
assert older["command"] is None
|
||||||
|
assert older["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
|
||||||
|
|
||||||
|
def test_since_is_passed_on(self, driver, history):
|
||||||
|
driver.get_update_history(since=1764100000)
|
||||||
|
history.assert_called_once_with(since=1764100000)
|
||||||
|
|
||||||
|
def test_no_transaction_is_an_empty_list(self, driver, history):
|
||||||
|
history.return_value = []
|
||||||
|
assert driver.get_update_history() == []
|
||||||
|
|
||||||
|
def test_a_failed_read_raises(self, driver, history):
|
||||||
|
history.side_effect = Exception("596 Connection timed out")
|
||||||
|
with pytest.raises(RuntimeError, match="timed out"):
|
||||||
|
driver.get_update_history()
|
||||||
|
|
||||||
|
def test_an_older_node_has_no_history(self, driver, history):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
with pytest.raises(NotImplementedError):
|
||||||
|
driver.get_update_history()
|
||||||
|
history.assert_not_called()
|
||||||
@@ -41,6 +41,90 @@ class TestGetVmsReportsStringIds:
|
|||||||
assert [vm["vmid"] for vm in driver.get_vms()] == ["99", "1000"]
|
assert [vm["vmid"] for vm in driver.get_vms()] == ["99", "1000"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetVmsGuestUid:
|
||||||
|
"""PVE 9.3 gives every guest a ``uid`` that survives a migration, a restore and a
|
||||||
|
changed vmid; only ``/cluster/resources`` reports it (NetOrk/netork#2728)."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def listed(self, driver, api):
|
||||||
|
driver.get_vm_interfaces = MagicMock(return_value=({}, False, False))
|
||||||
|
driver._get_vm_disk_and_boot = MagicMock(return_value=([], False))
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
return driver._api.cluster.resources.get
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row(vmid, kind, uid=None, node="pve1"):
|
||||||
|
row = {"id": f"{kind}/{vmid}", "type": kind, "vmid": vmid, "node": node}
|
||||||
|
return {**row, "uid": uid} if uid else row
|
||||||
|
|
||||||
|
def test_each_guest_carries_its_uid_from_one_resources_call(self, driver, listed):
|
||||||
|
listed.return_value = [
|
||||||
|
self._row(100, "qemu", "abcdefghijklmnopqrst"),
|
||||||
|
self._row(200, "lxc", "bcdefghijklmnopqrstu"),
|
||||||
|
]
|
||||||
|
assert {vm["vmid"]: vm["uid"] for vm in driver.get_vms()} == {
|
||||||
|
"100": "abcdefghijklmnopqrst",
|
||||||
|
"200": "bcdefghijklmnopqrstu",
|
||||||
|
}
|
||||||
|
listed.assert_called_once_with(type="vm")
|
||||||
|
|
||||||
|
def test_a_guest_without_uid_has_no_key(self, driver, listed):
|
||||||
|
listed.return_value = [
|
||||||
|
self._row(100, "qemu"),
|
||||||
|
# The same vmid on another node is another guest.
|
||||||
|
self._row(200, "lxc", "bcdefghijklmnopqrstu", node="pve2"),
|
||||||
|
]
|
||||||
|
assert all("uid" not in vm for vm in driver.get_vms())
|
||||||
|
|
||||||
|
def test_unreadable_resources_leave_the_listing_without_uids(self, driver, listed):
|
||||||
|
listed.side_effect = Exception("403 Forbidden")
|
||||||
|
vms = driver.get_vms()
|
||||||
|
assert [vm["vmid"] for vm in vms] == ["100", "200"]
|
||||||
|
assert all("uid" not in vm for vm in vms)
|
||||||
|
|
||||||
|
def test_an_older_node_is_not_asked(self, driver, listed):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
assert all("uid" not in vm for vm in driver.get_vms())
|
||||||
|
listed.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetVmsTellsPausedFromRunning:
|
||||||
|
"""PVE reports a paused guest ``status: running``; only ``qmpstatus`` tells, and only
|
||||||
|
when the listing is asked for the full status (NetOrk/netork#2658)."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def listed(self, driver, api):
|
||||||
|
driver.get_vm_interfaces = MagicMock(return_value=({}, False, False))
|
||||||
|
driver._get_vm_disk_and_boot = MagicMock(return_value=([], False))
|
||||||
|
api.lxc.get.return_value = []
|
||||||
|
|
||||||
|
def statuses(*qemu):
|
||||||
|
api.qemu.get.return_value = [
|
||||||
|
{"vmid": 100 + i, "name": f"vm{i}", **row} for i, row in enumerate(qemu)
|
||||||
|
]
|
||||||
|
return {vm["vmid"]: vm["status"] for vm in driver.get_vms()}
|
||||||
|
|
||||||
|
return statuses
|
||||||
|
|
||||||
|
def test_the_listing_asks_for_the_full_status(self, listed, api):
|
||||||
|
listed({"status": "running", "qmpstatus": "running"})
|
||||||
|
api.qemu.get.assert_called_once_with(full=1)
|
||||||
|
|
||||||
|
def test_a_paused_guest_is_paused(self, listed):
|
||||||
|
assert listed({"status": "running", "qmpstatus": "paused"}) == {"100": "paused"}
|
||||||
|
|
||||||
|
def test_a_guest_asleep_in_s3_is_paused(self, listed):
|
||||||
|
"""Its QEMU process still holds its memory; ``status/resume`` wakes it."""
|
||||||
|
assert listed({"status": "running", "qmpstatus": "suspended"}) == {"100": "paused"}
|
||||||
|
|
||||||
|
def test_running_and_stopped_stay_as_they_are(self, listed):
|
||||||
|
assert listed(
|
||||||
|
{"status": "running", "qmpstatus": "running"},
|
||||||
|
{"status": "stopped", "qmpstatus": "stopped"},
|
||||||
|
{"status": "running"},
|
||||||
|
) == {"100": "running", "101": "stopped", "102": "running"}
|
||||||
|
|
||||||
|
|
||||||
class TestResolveVm:
|
class TestResolveVm:
|
||||||
def test_by_vmid_string(self, driver, api):
|
def test_by_vmid_string(self, driver, api):
|
||||||
assert driver._resolve_vm("100") == (100, "vm")
|
assert driver._resolve_vm("100") == (100, "vm")
|
||||||
@@ -84,6 +168,44 @@ class TestPowerActions:
|
|||||||
with pytest.raises(RuntimeError, match="container"):
|
with pytest.raises(RuntimeError, match="container"):
|
||||||
driver.suspend_vm("200")
|
driver.suspend_vm("200")
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||||
|
def test_resume_posts_status_resume_and_waits(self, driver, api, qmpstatus):
|
||||||
|
guest = api.qemu.return_value
|
||||||
|
guest.status.current.get.return_value = {"status": "running", "qmpstatus": qmpstatus}
|
||||||
|
guest.status.resume.post.return_value = "UPID:resume"
|
||||||
|
driver.resume_vm("web01")
|
||||||
|
guest.status.resume.post.assert_called_once()
|
||||||
|
driver._wait_for_task.assert_called_once_with("UPID:resume", timeout=120)
|
||||||
|
|
||||||
|
def test_resume_on_pve_9_3_sets_the_guests_clock(self, driver, api):
|
||||||
|
"""``sync-time-on-resume``: the guest agent sets the guest's clock (NetOrk/netork#2728)."""
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
guest = api.qemu.return_value
|
||||||
|
guest.status.current.get.return_value = {"status": "running", "qmpstatus": "paused"}
|
||||||
|
driver.resume_vm("100")
|
||||||
|
guest.status.resume.post.assert_called_once_with(**{"sync-time-on-resume": 1})
|
||||||
|
|
||||||
|
def test_resume_on_an_older_node_sends_no_clock_sync(self, driver, api):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
guest = api.qemu.return_value
|
||||||
|
guest.status.current.get.return_value = {"status": "running", "qmpstatus": "paused"}
|
||||||
|
driver.resume_vm("100")
|
||||||
|
guest.status.resume.post.assert_called_once_with()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"current", [{"status": "running", "qmpstatus": "running"}, {"status": "stopped"}]
|
||||||
|
)
|
||||||
|
def test_resume_of_a_guest_that_is_not_paused_is_refused(self, driver, api, current):
|
||||||
|
api.qemu.return_value.status.current.get.return_value = current
|
||||||
|
with pytest.raises(RuntimeError, match="not paused"):
|
||||||
|
driver.resume_vm("100")
|
||||||
|
api.qemu.return_value.status.resume.post.assert_not_called()
|
||||||
|
|
||||||
|
def test_resume_of_a_container_is_refused(self, driver, api):
|
||||||
|
with pytest.raises(RuntimeError, match="container 200"):
|
||||||
|
driver.resume_vm("200")
|
||||||
|
api.lxc.return_value.status.resume.post.assert_not_called()
|
||||||
|
|
||||||
def test_api_error_becomes_runtime_error(self, driver, api):
|
def test_api_error_becomes_runtime_error(self, driver, api):
|
||||||
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
||||||
with pytest.raises(RuntimeError, match="locked"):
|
with pytest.raises(RuntimeError, match="locked"):
|
||||||
|
|||||||
@@ -201,7 +201,7 @@ class TestLoopbackIsNeverTheVmsAddress:
|
|||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
node = MagicMock()
|
node = MagicMock()
|
||||||
mixin._node_api = MagicMock(return_value=node)
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
node.qemu.return_value.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
node.qemu.return_value.status.current.get.return_value = {"status": "running"}
|
||||||
node.qemu.return_value.agent.return_value.get.return_value = {"result": interfaces}
|
node.qemu.return_value.agent.return_value.get.return_value = {"result": interfaces}
|
||||||
with patch("time.sleep"):
|
with patch("time.sleep"):
|
||||||
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
|
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
|
||||||
|
|||||||
@@ -380,3 +380,65 @@ class TestNodeMaintenance:
|
|||||||
run.side_effect = RuntimeError("Command failed (exit 255): ...\nno such node 'pve2'")
|
run.side_effect = RuntimeError("Command failed (exit 255): ...\nno such node 'pve2'")
|
||||||
with pytest.raises(RuntimeError, match="no such node"):
|
with pytest.raises(RuntimeError, match="no such node"):
|
||||||
drv.set_node_maintenance("pve2", True)
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
|
||||||
|
|
||||||
|
class TestNodeMaintenanceOverRest:
|
||||||
|
"""PVE 9.3 has ``PUT /nodes/{node}/maintenance``: no SSH session at all."""
|
||||||
|
|
||||||
|
def _driver(self, version: str = "9.3.0") -> tuple[Any, MagicMock]:
|
||||||
|
api, _ = _migration_api()
|
||||||
|
api.version.get.return_value = {"version": version, "release": version[:3]}
|
||||||
|
api.nodes("pve2").version.get.return_value = {"version": version, "release": version[:3]}
|
||||||
|
drv = _driver(api)
|
||||||
|
drv._node_ssh = MagicMock() # type: ignore[method-assign]
|
||||||
|
drv._run_node_command = MagicMock(return_value="") # type: ignore[method-assign]
|
||||||
|
return drv, api
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("enabled", "mode"), [(True, "enable"), (False, "disable")])
|
||||||
|
def test_puts_the_mode_and_opens_no_ssh(self, enabled, mode):
|
||||||
|
drv, api = self._driver()
|
||||||
|
drv.set_node_maintenance("pve2", enabled)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_called_once_with(**{"maintenance-mode": mode})
|
||||||
|
drv._node_ssh.assert_not_called()
|
||||||
|
drv._run_node_command.assert_not_called()
|
||||||
|
|
||||||
|
def test_not_a_member_puts_nothing(self):
|
||||||
|
drv, api = self._driver()
|
||||||
|
with pytest.raises(ValueError, match="not a member"):
|
||||||
|
drv.set_node_maintenance("pve9", True)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
|
|
||||||
|
def test_refused(self):
|
||||||
|
drv, api = self._driver()
|
||||||
|
api.nodes("pve2").maintenance.put.side_effect = Exception(
|
||||||
|
"403 Forbidden: Permission check failed (/, Sys.Modify)"
|
||||||
|
)
|
||||||
|
with pytest.raises(RuntimeError, match="Sys.Modify"):
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
drv._node_ssh.assert_not_called()
|
||||||
|
|
||||||
|
def test_older_node_uses_ha_manager_over_ssh(self):
|
||||||
|
drv, api = self._driver("9.2.4")
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
drv._run_node_command.assert_called_once_with(
|
||||||
|
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||||
|
)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
|
|
||||||
|
def test_the_target_nodes_version_decides_mid_upgrade(self):
|
||||||
|
# A rolling upgrade: the node the driver is connected to runs 9.3 already,
|
||||||
|
# the one going into maintenance does not, and has no endpoint to proxy to.
|
||||||
|
drv, api = self._driver("9.3.0")
|
||||||
|
api.nodes("pve2").version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
drv._run_node_command.assert_called_once_with(
|
||||||
|
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||||
|
)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
|
|
||||||
|
def test_an_unreadable_target_version_is_a_runtime_error(self):
|
||||||
|
drv, api = self._driver()
|
||||||
|
api.nodes("pve2").version.get.side_effect = ConnectionError("pve2 unreachable")
|
||||||
|
with pytest.raises(RuntimeError, match="pve2"):
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
@@ -336,7 +336,7 @@ def test_get_vm_status_with_wait_for_ip():
|
|||||||
# Mock VM config
|
# Mock VM config
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0,tag=10"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
||||||
# reached via agent(...) as a callable resource, not dotted attribute
|
# reached via agent(...) as a callable resource, not dotted attribute
|
||||||
@@ -375,7 +375,7 @@ def test_get_vm_status_skips_loopback_interface():
|
|||||||
|
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
mock_agent_call = MagicMock()
|
mock_agent_call = MagicMock()
|
||||||
mock_vm.agent.return_value = mock_agent_call
|
mock_vm.agent.return_value = mock_agent_call
|
||||||
@@ -410,7 +410,7 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
|||||||
# Mock VM config
|
# Mock VM config
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
# Mock guest-agent that never returns IP
|
# Mock guest-agent that never returns IP
|
||||||
mock_agent_call = MagicMock()
|
mock_agent_call = MagicMock()
|
||||||
@@ -424,6 +424,114 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
|||||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
||||||
|
|
||||||
|
|
||||||
|
_RUNNING = {"status": "running", "qmpstatus": "running"}
|
||||||
|
_ETH0 = {
|
||||||
|
"name": "eth0",
|
||||||
|
"hardware-address": "aa:bb:cc:dd:ee:00",
|
||||||
|
"ip-addresses": [{"ip-address": "10.0.0.100", "ip-address-type": "ipv4"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _status_of(current, interfaces=()):
|
||||||
|
"""A mixin whose VM 101 answers ``status/current`` with *current*."""
|
||||||
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
node = MagicMock()
|
||||||
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
if isinstance(current, list):
|
||||||
|
vm.status.current.get.side_effect = current
|
||||||
|
else:
|
||||||
|
vm.status.current.get.return_value = current
|
||||||
|
vm.agent.return_value.get.return_value = {"result": list(interfaces)}
|
||||||
|
return mixin, vm
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheStatusIsWhatProxmoxSays:
|
||||||
|
"""``status/current``, not whether the config reads (NAPALM/napalm-proxmox#72).
|
||||||
|
|
||||||
|
The guest agent is asked for an address only while the VM runs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_a_stopped_vm_is_stopped(self):
|
||||||
|
mixin, vm = _status_of({"status": "stopped", "qmpstatus": "stopped"})
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "stopped"}
|
||||||
|
vm.status.current.get.assert_called_once_with()
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||||
|
def test_a_paused_vm_is_paused(self, qmpstatus):
|
||||||
|
mixin, vm = _status_of({"status": "running", "qmpstatus": qmpstatus})
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "paused"}
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
def test_a_running_vm_is_running_with_its_address(self):
|
||||||
|
mixin, _vm = _status_of(_RUNNING, [_ETH0])
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {
|
||||||
|
"status": "running",
|
||||||
|
"ip_address": "10.0.0.100",
|
||||||
|
"hostname": "eth0",
|
||||||
|
"mac_address": "aa:bb:cc:dd:ee:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_a_running_vm_whose_agent_does_not_answer_is_running(self):
|
||||||
|
mixin, vm = _status_of(_RUNNING)
|
||||||
|
vm.agent.return_value.get.side_effect = Exception("QEMU guest agent is not running")
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "running"}
|
||||||
|
|
||||||
|
def test_a_vm_proxmox_does_not_have_is_unknown(self):
|
||||||
|
mixin, vm = _status_of({})
|
||||||
|
vm.status.current.get.side_effect = Exception("Configuration file does not exist")
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("999") == {"status": "unknown"}
|
||||||
|
|
||||||
|
def test_waiting_for_an_address_ends_when_the_vm_stops(self):
|
||||||
|
"""A VM that stopped will report no address: the wait ends with an error at once."""
|
||||||
|
mixin, vm = _status_of([_RUNNING, {"status": "stopped"}])
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="stopped"):
|
||||||
|
with patch("time.sleep"):
|
||||||
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
assert vm.agent.return_value.get.call_count == 1
|
||||||
|
|
||||||
|
def test_waiting_for_an_address_of_a_paused_vm_does_not_ask_the_agent(self):
|
||||||
|
mixin, vm = _status_of({"status": "running", "qmpstatus": "paused"})
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="paused"):
|
||||||
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
def test_waiting_reads_the_status_again_on_each_round(self):
|
||||||
|
mixin, vm = _status_of([_RUNNING, _RUNNING, _RUNNING])
|
||||||
|
vm.agent.return_value.get.side_effect = [
|
||||||
|
{"result": []},
|
||||||
|
{"result": []},
|
||||||
|
{"result": [_ETH0]},
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("time.sleep"):
|
||||||
|
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
|
||||||
|
assert result["ip_address"] == "10.0.0.100"
|
||||||
|
assert vm.status.current.get.call_count == 3
|
||||||
|
|
||||||
|
def test_a_status_that_does_not_read_while_waiting_keeps_the_wait_going(self):
|
||||||
|
mixin, vm = _status_of([_RUNNING, Exception("timed out"), _RUNNING])
|
||||||
|
vm.agent.return_value.get.side_effect = [
|
||||||
|
{"result": []},
|
||||||
|
{"result": []},
|
||||||
|
{"result": [_ETH0]},
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("time.sleep"):
|
||||||
|
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
|
||||||
|
assert result["ip_address"] == "10.0.0.100"
|
||||||
|
|
||||||
|
|
||||||
def test_destroy_vm_success():
|
def test_destroy_vm_success():
|
||||||
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import base64
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from napalm_device_types import OPENED_PORTS_RECORD
|
||||||
|
|
||||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||||
|
|
||||||
@@ -38,6 +39,11 @@ class _Node:
|
|||||||
self.installed = False
|
self.installed = False
|
||||||
self.refuse = refuse
|
self.refuse = refuse
|
||||||
self.ran: list[str] = []
|
self.ran: list[str] = []
|
||||||
|
#: What reading the record of opened rules prints (NetOrk/netork#2693).
|
||||||
|
self.record = ""
|
||||||
|
#: What counting the rules left for the port prints.
|
||||||
|
self.left = "0"
|
||||||
|
self.record_written: str | None = None
|
||||||
|
|
||||||
def __call__(self, command: str) -> str:
|
def __call__(self, command: str) -> str:
|
||||||
self.ran.append(command)
|
self.ran.append(command)
|
||||||
@@ -50,6 +56,14 @@ class _Node:
|
|||||||
def _answer(self, command: str) -> tuple[str, int]:
|
def _answer(self, command: str) -> tuple[str, int]:
|
||||||
if self.refuse and self.refuse in command:
|
if self.refuse and self.refuse in command:
|
||||||
return "E: refused", 1
|
return "E: refused", 1
|
||||||
|
if "stat -c" in command and OPENED_PORTS_RECORD in command:
|
||||||
|
return self.record, 0
|
||||||
|
if "grep -c" in command:
|
||||||
|
return self.left, 0
|
||||||
|
if "base64 -d" in command and OPENED_PORTS_RECORD in command:
|
||||||
|
written = re.search(r"echo (\S*) \|", command).group(1)
|
||||||
|
self.record_written = base64.b64decode(written).decode()
|
||||||
|
return "", 0
|
||||||
if command.startswith("dpkg-query"):
|
if command.startswith("dpkg-query"):
|
||||||
return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0
|
return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0
|
||||||
if f"cat {CONFIG}" in command:
|
if f"cat {CONFIG}" in command:
|
||||||
@@ -144,3 +158,86 @@ def test_a_config_that_cannot_be_read_stops_the_fix(driver, node):
|
|||||||
|
|
||||||
assert result["success"] is False
|
assert result["success"] is False
|
||||||
assert result["steps"][-1]["step"] == "configure"
|
assert result["steps"][-1]["step"] == "configure"
|
||||||
|
|
||||||
|
|
||||||
|
# --- The record of the rules netOrk opened (NetOrk/netork#2693) ---------------------
|
||||||
|
|
||||||
|
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
|
||||||
|
ROOT = "0 755 directory\n0 644 regular file\n"
|
||||||
|
ZABBIX_UFW = "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
|
||||||
|
SNMP_UFW = "v1 snmp ufw udp 161 10.40.100.254/32"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ufw_records_the_rule_it_added_under_the_agent(driver, node):
|
||||||
|
driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
opened = next(c for c in node.ran if "ufw allow" in c)
|
||||||
|
assert "*Skipping*) ;;" in opened
|
||||||
|
assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_snmp_rule_is_recorded_under_snmp(node):
|
||||||
|
driver = ProxmoxDriver("pve", "root@pam", "pw")
|
||||||
|
driver._exec_ssh_command = node
|
||||||
|
|
||||||
|
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.40.100.254"]})
|
||||||
|
|
||||||
|
assert any(f'"{SNMP_UFW}" >>' in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, node):
|
||||||
|
node.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\n"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
deletes = [c for c in node.ran if "ufw delete" in c]
|
||||||
|
assert len(deletes) == 1
|
||||||
|
assert "ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp" in deletes[0]
|
||||||
|
assert node.record_written == f"{SNMP_UFW}\n"
|
||||||
|
assert "removed" in result["steps"][2]["output"]
|
||||||
|
assert not any("ufw allow" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, node):
|
||||||
|
node.left = "1"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is True
|
||||||
|
assert not any("ufw delete" in c for c in node.ran)
|
||||||
|
assert node.record_written is None
|
||||||
|
firewall = result["steps"][2]["output"]
|
||||||
|
assert "netOrk recorded no rule" in firewall
|
||||||
|
assert "1 rule(s) for tcp/10050" in firewall
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_record_someone_else_could_write_is_not_acted_on(driver, node):
|
||||||
|
node.record = f"0 755 directory\n0 666 regular file\n{ZABBIX_UFW}\n"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "writable" in result["output"]
|
||||||
|
assert not any("ufw delete" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_rule_that_will_not_go_stays_in_the_record(driver, node):
|
||||||
|
node.record = ROOT + f"{ZABBIX_UFW}\n"
|
||||||
|
node.refuse = "ufw delete"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert node.record_written is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_recorded_rule_of_another_firewall_is_not_touched(driver, node):
|
||||||
|
"""A node's rules are ufw's; a firewalld line is not one this driver removes."""
|
||||||
|
node.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.40.100.254/32\n"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "iptables" in result["output"]
|
||||||
|
assert node.record_written is None
|
||||||
Reference in new issue
Block a user