Compare commits

...
90 Commits
Author SHA1 Message Date
christianmanivong 4b423220bf Merge pull request 'chore(release): 0.14.0' (#76) from feature/pve93-2728 into main
driver / lint (push) Successful in 12s
driver / test (3.13) (push) Successful in 1m16s
driver / build (push) Successful in 33s
driver / security (push) Successful in 1m4s
driver / publish (push) Successful in 33s
driver / lowest (push) Successful in 32s
driver / types (push) Successful in 1m19s
driver / test (3.12) (push) Successful in 1m21s
driver / standard (push) Successful in 15s
CI / driver (push) Successful in 10m54s
2026-11-26 18:00:48 +00:00
Christian Manivong 75818c3f09 chore(release): 0.14.0
driver / security (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 32s
CI / driver (pull_request) Successful in 2m21s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 58s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
2026-11-26 18:05:48 +01:00
Christian Manivong fddf8af680 feat: Proxmox VE 9.3 API additions (NetOrk/netork#2728)
On a node running 9.3: HA maintenance over PUT /nodes/{node}/maintenance
(the target node's version decides, SSH below it), the guest uid in
get_vms, the cluster-id as ClusterDict.id, sync-time-on-resume on resume.
get_credential_expiry reads the expiry of the token or account the driver
logged in with; get_update_history lists the node's APT transactions.
Needs napalm-device-types 4.44.0.
2026-11-26 17:35:50 +01:00
christianmanivong c2d9d7e75e Merge pull request 'chore(release): 0.13.0' (#74) from chore/release-0.13.0 into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 58s
driver / build (push) Successful in 30s
driver / security (push) Successful in 57s
driver / publish (push) Successful in 28s
driver / lowest (push) Successful in 32s
driver / types (push) Successful in 54s
driver / test (3.12) (push) Successful in 1m6s
driver / standard (push) Successful in 17s
CI / driver (push) Successful in 3m1s
2026-11-26 12:26:06 +00:00
Christian Manivong 685e995073 chore(release): 0.13.0
driver / security (pull_request) Successful in 51s
CI / driver (pull_request) Successful in 2m20s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / lowest (pull_request) Successful in 30s
driver / test (3.13) (pull_request) Successful in 49s
driver / build (pull_request) Successful in 26s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 49s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
2026-11-26 08:26:35 +01:00
Christian Manivong 370aeed482 feat(zabbix): an active-only agent closes the port netOrk opened for it (NetOrk/netork#2693)
Every rule the firewall step adds in ufw is recorded in napalm-device-types'
opened_ports record, only when ufw did not have it before. For an active-only
agent, _revoke_zabbix_agent_sources removes exactly the agent's recorded rules
and reports what ufw has left for the port.
2026-11-26 08:21:53 +01:00
christianmanivong bc3eb86723 Merge pull request 'chore(release): 0.12.0' (#73) from chore/release-0.12.0 into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m0s
driver / build (push) Successful in 26s
driver / security (push) Successful in 1m1s
driver / publish (push) Successful in 32s
driver / lowest (push) Successful in 29s
driver / types (push) Successful in 58s
driver / test (3.12) (push) Successful in 1m4s
driver / standard (push) Successful in 14s
CI / driver (push) Successful in 3m6s
2026-11-26 05:12:53 +00:00
Christian Manivong 8159566ff4 chore(release): 0.12.0
driver / security (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 53s
driver / test (3.12) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 28s
driver / build (pull_request) Successful in 36s
CI / driver (pull_request) Successful in 2m15s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 55s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
2026-11-26 00:34:01 +01:00
Christian Manivong b80a3950ac Merge branch 'fix/vm-status-snapshot-2696-pve72' 2026-11-26 00:33:53 +01:00
Christian Manivong cae4859383 fix(vm): get_vm_status reads status/current (NetOrk/netork#2696)
get_vm_status answered "running" for every VM whose config could be read
and never asked Proxmox for the VM's state, so a caller waiting for a clean
shutdown never saw the VM stop. It now reads status/current and maps it with
qemu_status, the mapping get_vms() uses: running, stopped, or paused for a
qmpstatus of paused or suspended. The guest agent is asked for an address
only while the VM runs; wait_for_ip ends at once with a RuntimeError when the
VM is stopped or paused.

Closes #72
2026-11-26 00:21:40 +01:00
christianmanivong ad3b5b29a9 Merge pull request 'chore(release): 0.11.0' (#71) from chore/release-0.11.0 into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m1s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m4s
driver / publish (push) Successful in 31s
driver / lowest (push) Successful in 32s
driver / types (push) Successful in 58s
driver / test (3.12) (push) Successful in 1m8s
driver / standard (push) Successful in 18s
CI / driver (push) Successful in 6m47s
2026-11-25 21:17:17 +00:00
Christian Manivong 326527ddd5 chore(release): 0.11.0
driver / security (pull_request) Successful in 1m14s
CI / driver (pull_request) Successful in 2m57s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 39s
driver / build (pull_request) Successful in 36s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 58s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
2026-11-25 22:09:47 +01:00
Christian Manivong f071c10cd1 Merge branch 'fix/vm-resume-2658' 2026-11-25 22:09:31 +01:00
Christian Manivong 93c974b8f0 feat(vm): resume a paused VM, and list it as paused (NetOrk/netork#2658)
driver / security (pull_request) Successful in 1m13s
driver / test (3.13) (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 33s
CI / driver (pull_request) Successful in 2m43s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 52s
driver / test (3.12) (pull_request) Successful in 1m1s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
suspend_vm paused a QEMU guest that nothing could bring back: start is
refused because PVE still says the guest is running. resume_vm posts
status/resume for a paused VM and refuses a container or a guest that is
not paused. get_vms() asks for the full status and reports a guest whose
qmpstatus is paused or suspended as paused, not running.
2026-11-25 21:28:46 +01:00
christianmanivong 449230c624 Merge pull request 'feat(zabbix): a native Zabbix agent on both drivers through ZabbixAgentMixin (NetOrk/netork#2571)' (#69) from feat/zabbix-agent-native into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 54s
driver / build (push) Successful in 24s
driver / security (push) Successful in 52s
driver / publish (push) Skipped
driver / lowest (push) Successful in 28s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 1m5s
driver / standard (push) Successful in 16s
CI / driver (push) Successful in 2m28s
2026-11-17 04:32:23 +00:00
Christian Manivong 92108f0ff3 feat(zabbix): a native Zabbix agent on both drivers through ZabbixAgentMixin (NetOrk/netork#2571)
driver / security (pull_request) Successful in 48s
driver / lowest (pull_request) Successful in 26s
driver / test (3.13) (pull_request) Successful in 54s
driver / build (pull_request) Successful in 24s
CI / driver (pull_request) Successful in 2m13s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 46s
driver / test (3.12) (pull_request) Successful in 57s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
A node runs no container engine. configure_zabbix_agent(settings) installs
Debian's zabbix-agent, and where Debian has none, Zabbix's from its repository
for the server's release line. It writes the caller's values into
/etc/zabbix/zabbix_agentd.conf (the old file stays as .bak) and opens
tcp/ListenPort in ufw where the node has it; pve-firewall's rules are the
operator's, as for the SNMP agent.

The SNMP agent's ufw step is the shared _allow_sources(allowed, port, proto) in
ProxmoxHostMixin now; the rule it writes for udp/161 is the same.
Needs napalm-device-types 4.40.0.
2026-11-17 04:50:55 +01:00
christianmanivong 5a5ed8eac7 Merge pull request 'test(system-identity): compare the identity's keys only' (#68) from chore/identity-test-keys into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m0s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m1s
driver / publish (push) Skipped
driver / lowest (push) Successful in 31s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 1m4s
driver / standard (push) Successful in 17s
CI / driver (push) Successful in 2m36s
2026-11-13 22:11:25 +00:00
Christian Manivong dc24dd636b test(system-identity): compare the identity's keys only
driver / security (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 37s
driver / build (pull_request) Successful in 30s
CI / driver (pull_request) Successful in 2m44s
driver / standard (pull_request) Successful in 15s
driver / types (pull_request) Successful in 58s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
napalm-device-types reads the system firmware in the same round trip
(bios_vendor, bios_version, bios_date). The driver only carries the
command across, so its test checks the identity it reads and passes
against napalm-device-types with and without the firmware.

NetOrk/netork#2518
2026-11-13 23:00:31 +01:00
christianmanivong eff6af8b45 Merge pull request 'fix(system): set_hostname writes /etc/hosts through a mktemp file in /etc (#66)' (#67) from fix/hosts-tempfile-2446 into main
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 54s
driver / build (push) Successful in 29s
driver / security (push) Successful in 54s
driver / publish (push) Skipped
driver / lowest (push) Successful in 29s
driver / types (push) Successful in 50s
driver / test (3.12) (push) Successful in 1m0s
driver / standard (push) Successful in 14s
CI / driver (push) Successful in 2m21s
2026-11-13 09:09:28 +00:00
Christian Manivong a421a595d4 Merge remote-tracking branch 'origin/main' into fix/hosts-tempfile-2446
driver / security (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 58s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 25s
CI / driver (pull_request) Successful in 2m23s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 50s
driver / test (3.12) (pull_request) Successful in 58s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
2026-11-13 09:56:57 +01:00
christianmanivong 6fccd7a8f0 Merge pull request 'fix(system): set_hostname quotes the name in its root commands (#64)' (#65) from fix/hostname-quote-2456 into main
driver / lint (push) Successful in 12s
driver / test (3.13) (push) Successful in 52s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m1s
driver / publish (push) Skipped
driver / lowest (push) Successful in 30s
driver / types (push) Successful in 55s
driver / test (3.12) (push) Successful in 1m0s
driver / standard (push) Successful in 15s
CI / driver (push) Successful in 2m28s
2026-11-13 08:55:13 +00:00
Christian Manivong 610d6f1093 chore(ratchet): set_hostname is a line shorter (#66)
driver / security (pull_request) Successful in 1m3s
CI / driver (pull_request) Successful in 16m53s
driver / test (3.12) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 29s
driver / test (3.13) (pull_request) Successful in 56s
driver / build (pull_request) Successful in 28s
driver / standard (pull_request) Successful in 14m29s
driver / types (pull_request) Successful in 58s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
The mktemp write of /etc/hosts made set_hostname one line shorter, and
the quality ratchet fails on a baseline entry that is no longer reached
(stale). Lowered with napalm-standard ratchet --write.
2026-11-13 08:55:48 +01:00
Christian Manivong 66828a9564 test(time-sync): follow napalm-device-types 4.36.0, which keeps DHCP's servers
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Successful in 2m3s
driver / test (3.13) (pull_request) Successful in 53s
driver / test (3.12) (pull_request) Successful in 1m0s
driver / lowest (pull_request) Successful in 28s
driver / build (pull_request) Successful in 25s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 51s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
napalm-device-types 4.36.0 (released after main's last CI run) changed
PosixTimeSyncMixin: get_time_sync() reports DHCP-provided servers apart
(dhcp_ntp_servers), and configure_time_sync() no longer comments out the
DHCP client's chrony sourcedir; it gives back one that 4.35.0 took out
(NetOrk/netork#2380). CI installs the newest release, so five time-sync
tests failed on every branch.

The tests now expect that behaviour, read DHCP's servers apart, and check
that a node 4.35.0 aligned gets its DHCP sourcedir back. The floor moves
to 4.36.0, so the lowest-versions job tests the same behaviour; README,
CHANGELOG and the module docstring say what a write leaves alone.
2026-11-13 08:55:37 +01:00
Christian Manivong 83d1ef780e test(time-sync): follow napalm-device-types 4.36.0, which keeps DHCP's servers
napalm-device-types 4.36.0 (released after main's last CI run) changed
PosixTimeSyncMixin: get_time_sync() reports DHCP-provided servers apart
(dhcp_ntp_servers), and configure_time_sync() no longer comments out the
DHCP client's chrony sourcedir; it gives back one that 4.35.0 took out
(NetOrk/netork#2380). CI installs the newest release, so five time-sync
tests failed on every branch.

The tests now expect that behaviour, read DHCP's servers apart, and check
that a node 4.35.0 aligned gets its DHCP sourcedir back. The floor moves
to 4.36.0, so the lowest-versions job tests the same behaviour; README,
CHANGELOG and the module docstring say what a write leaves alone.
2026-11-13 08:55:37 +01:00
Christian Manivong a67e8492ee fix(system): set_hostname writes /etc/hosts through a mktemp file in /etc (#66)
driver / security (pull_request) Successful in 1m7s
driver / test (3.13) (pull_request) Failing after 57s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 34s
CI / driver (pull_request) Failing after 2m48s
driver / standard (pull_request) Failing after 18s
driver / types (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Failing after 1m8s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 17s
The new /etc/hosts was written as root to the fixed /tmp/_netork_hosts
and moved over /etc/hosts. A local user could create that file (or a
symlink) beforehand: root's write went into the user's file, and the
user owned /etc/hosts afterwards (NetOrk/netork#2446).

The file is now made with mktemp beside the target (/etc/.hosts.XXXXXX,
root's directory, same filesystem), written, set to 644 and moved into
place; a failed step removes it.
2026-11-12 22:33:38 +01:00
Christian Manivong a13cd0202f fix(system): set_hostname quotes the name in its root commands (#64)
driver / security (pull_request) Successful in 1m19s
driver / test (3.13) (pull_request) Failing after 1m6s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 30s
CI / driver (pull_request) Failing after 2m58s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Failing after 1m6s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
`postconf -e 'myhostname = <fqdn>'`, `hostname '<name>'` and the
/etc/pve/nodes move put the name between single quotes of their own, so
a name with a single quote ended them and the rest ran as root
(NetOrk/netork#2456). Each value is now passed through shlex.quote.
/etc/hostname, /etc/hosts and /etc/mailname were already written
through base64.
2026-11-12 22:25:56 +01:00
christianmanivong 042b21d3d9 Merge pull request 'feat(time-sync): servers and zone on Proxmox VE and Backup Server' (#63) from feature/time-sync-2365 into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 56s
driver / build (push) Successful in 29s
driver / security (push) Successful in 57s
driver / publish (push) Skipped
driver / lowest (push) Successful in 30s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 1m4s
driver / standard (push) Successful in 14s
CI / driver (push) Successful in 2m28s
2026-11-11 14:26:16 +00:00
Christian Manivong 410d34bdee feat(time-sync): servers and zone on Proxmox VE and Backup Server
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Successful in 2m41s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / test (3.13) (pull_request) Successful in 59s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 31s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 56s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
netOrk keeps one list of NTP servers and a time zone per site and aligns
a device that differs (NetOrk/netork#2360, #2365). Both drivers now
implement napalm-device-types' TimeSyncMixin (4.35.0) and write both
values.

Neither API keeps time servers: /nodes/{node}/time knows only the zone,
and both products run chrony on Debian. The servers are therefore
PosixTimeSyncMixin's, over the driver's existing SSH session
(run_command, root): read from chrony's configuration, written to
/etc/chrony/sources.d/netork.sources with every other source commented
out, then a reload or a restart of chrony.

The zone is read with them from the host (timedatectl: the zone the
clock really runs in), and from GET /nodes/{node}/time only where the
host names none. It is written through PUT /nodes/{node}/time rather
than timedatectl set-timezone: Proxmox's own call validates the name and
keeps /etc/timezone, which its web UI and API show, in step with
/etc/localtime.

One device is one node: in a PVE cluster every node has its own clock,
and only the node this connection resolved is read and written.

get_ntp_servers() read GET /nodes/{node}/ntp, a path Proxmox VE does not
have, so it always reported no servers. It now reports what
get_time_sync() reads, on the backup server too.
2026-11-11 15:18:08 +01:00
christianmanivong aeb12eae00 Merge pull request 'feat(running-backups): what a restart of a PVE node, a guest or a PBS would abort' (#62) from feature/running-backups-2318 into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 1m9s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m4s
driver / publish (push) Skipped
driver / lowest (push) Successful in 34s
driver / types (push) Successful in 1m19s
driver / test (3.12) (push) Successful in 1m15s
driver / standard (push) Successful in 16s
CI / driver (push) Successful in 2m30s
2026-11-11 07:40:53 +00:00
Christian Manivong 3877a5425a feat(running-backups): what a restart of a PVE node, a guest or a PBS would abort
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Successful in 2m10s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 26s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 54s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
netOrk holds a host's restart after patching while a backup runs on it, and
a guest's restart while its hypervisor is backing it up (NetOrk/netork#2318).
It asks right before the restart, so both drivers answer
get_running_backups() from napalm-device-types 4.34.0:

- PVE: the node's active vzdump tasks, each with the guests it is taking now
  (its own guest, or for a job the guests locked for their backup), and a
  guest locked without a task on its own, since the task list can lag and a
  lock can outlive its task.
- PBS: the running backup, sync, verify, gc, prune and tape tasks; a restore
  or housekeeping is no backup.

A failed read raises, so netOrk reads it as "not checked", never as "none".
2026-11-10 23:45:48 +01:00
christianmanivong b1252878a5 Merge pull request 'feat(log-sources): which logs a PVE or PBS node writes' (#61) from feature/log-sources-2049 into main
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m10s
driver / build (push) Successful in 40s
driver / security (push) Successful in 1m11s
driver / publish (push) Skipped
driver / lowest (push) Successful in 44s
driver / types (push) Successful in 57s
driver / test (3.12) (push) Successful in 1m10s
driver / standard (push) Successful in 16s
CI / driver (push) Successful in 2m36s
2026-11-05 00:05:48 +00:00
Christian Manivong 9c16586028 feat(log-sources): which logs a PVE or PBS node writes
driver / security (pull_request) Successful in 52s
driver / test (3.13) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 27s
CI / driver (pull_request) Successful in 2m16s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 59s
driver / test (3.12) (pull_request) Successful in 1m14s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
Both drivers mix in napalm-device-types' LogSourcesMixin (4.30.0) and
carry its command over the exec path, which runs as root either way.

Refs NetOrk/netork#2049
2026-11-05 00:24:33 +01:00
christianmanivong 1f88f50f15 Merge pull request 'feat(scheduled-jobs): scheduled jobs on Proxmox VE and Backup Server (#56)' (#59) from feature/scheduled-jobs into main
driver / lint (push) Successful in 20s
driver / test (3.13) (push) Successful in 1m15s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m5s
driver / publish (push) Skipped
driver / lowest (push) Successful in 34s
driver / types (push) Successful in 1m20s
driver / test (3.12) (push) Successful in 1m26s
driver / standard (push) Successful in 20s
CI / driver (push) Successful in 2m40s
Reviewed-on: #59
2026-11-03 15:05:16 +00:00
Christian Manivong 25363ac7b0 chore(scheduled-jobs): require napalm-device-types 4.27.0
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 2m12s
driver / test (3.13) (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 25s
driver / lint (pull_request) Successful in 12s
driver / standard (pull_request) Successful in 15s
driver / types (pull_request) Successful in 53s
driver / publish (pull_request) Skipped
4.26.0 went out with the sshd drop-in change; the scheduled-jobs
contract is in 4.27.0.
2026-11-03 08:35:41 +01:00
Christian Manivong 4e7e29b598 docs(scheduled-jobs): a vzdump line only runs because of pmxcfs (#56)
driver / security (pull_request) Failing after 43s
CI / driver (pull_request) Failing after 1m35s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 15s
driver / lowest (pull_request) Failing after 19s
driver / build (pull_request) Successful in 35s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Failing after 30s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
The guard is not about the link: napalm-device-types now writes the file a
link names. /etc/cron.d/vzdump points into /etc/pve, the cluster file
system, where installing a file with a mode and owner is not safe.

Refs #56
2026-11-03 05:40:27 +01:00
Christian Manivong dce794644c feat(scheduled-jobs): scheduled jobs on Proxmox VE and Backup Server (#56)
driver / security (pull_request) Failing after 37s
driver / test (3.13) (pull_request) Failing after 15s
driver / lowest (pull_request) Failing after 19s
driver / build (pull_request) Successful in 33s
CI / driver (pull_request) Failing after 1m12s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Failing after 28s
driver / test (3.12) (pull_request) Failing after 17s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
Both drivers mix in napalm-device-types' PosixScheduledJobsMixin over the
node's root SSH session: get_scheduled_jobs reads cron, run-parts, anacron
and every systemd timer in one round trip; manage_scheduled_job enables,
disables or runs one now; put_ and delete_scheduled_job write and remove an
application's own job.

What Proxmox ships is platform, so it is only switched and run: pve-*
units, pvesr.timer and /etc/cron.d/vzdump on Proxmox VE, proxmox-backup*
units on a backup server. A vzdump cron line is only run, because the file
is a link into /etc/pve and rewriting it would replace the link with a
plain file.

Backup jobs (/cluster/backup), replication and a backup server's verify,
prune, sync and GC jobs run in Proxmox's own daemons and stay with the
backup features.

Requires napalm-device-types 4.26.0.

Closes #56
2026-11-03 05:39:04 +01:00
christianmanivong d369f1ad76 Merge pull request 'chore(release): 0.10.0' (#58) from chore/release-0.10.0 into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m12s
driver / build (push) Successful in 33s
driver / security (push) Successful in 1m25s
driver / publish (push) Successful in 58s
driver / lowest (push) Successful in 34s
driver / types (push) Successful in 1m13s
driver / test (3.12) (push) Successful in 1m21s
driver / standard (push) Successful in 19s
CI / driver (push) Successful in 4m20s
2026-11-03 04:18:55 +00:00
Christian Manivong ff5018a3b4 chore(release): 0.10.0
driver / security (pull_request) Successful in 1m18s
driver / test (3.13) (pull_request) Successful in 1m7s
driver / build (pull_request) Successful in 37s
driver / lowest (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 3m5s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m8s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
2026-11-03 05:13:54 +01:00
christianmanivong ced34c35ba Merge pull request 'feat(clusters): name the backup server behind a pbs storage (#55)' (#57) from fix/pbs-storage-ref into main
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m4s
driver / build (push) Successful in 51s
driver / security (push) Successful in 1m17s
driver / publish (push) Skipped
driver / lowest (push) Successful in 40s
driver / types (push) Successful in 54s
driver / test (3.12) (push) Successful in 1m8s
driver / standard (push) Successful in 15s
CI / driver (push) Successful in 2m37s
2026-11-03 04:13:53 +00:00
Christian Manivong 44b260b2c4 feat(clusters): name the backup server behind a pbs storage (#55)
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 3m31s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 1m15s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 50s
driver / standard (pull_request) Successful in 1m26s
driver / types (pull_request) Successful in 2m17s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 1m25s
get_clusters() lists a pbs storage like any other, so nothing told an
application which Proxmox Backup Server and datastore it writes to.
Each pbs storage now carries ClusterStorageDict.backup_server
(napalm-device-types 4.25.0): server, port, datastore, namespace and
fingerprint from /storage, never the password or encryption key. An
unreadable /storage leaves it None; other storages carry no such key.

This was step 6 of #52 and was left out there.
2026-11-03 04:26:09 +01:00
christianmanivong 983553cf11 Merge pull request 'chore(release): 0.9.0' (#54) from chore/release-0.9.0 into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 1m1s
driver / build (push) Successful in 25s
driver / security (push) Successful in 59s
driver / publish (push) Successful in 25s
driver / lowest (push) Successful in 32s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 1m5s
driver / standard (push) Successful in 14s
CI / driver (push) Successful in 2m44s
2026-11-02 21:40:34 +00:00
Christian Manivong 0bb25a0c86 chore(release): 0.9.0
driver / security (pull_request) Successful in 53s
CI / driver (pull_request) Successful in 2m30s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 25s
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m4s
driver / publish (pull_request) Skipped
2026-11-02 22:36:06 +01:00
christianmanivong c040dfdaa2 Merge pull request 'feat(pbs): Proxmox Backup Server as entry point proxmox_backup (#52)' (#53) from feat/proxmox-backup into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 1m1s
driver / build (push) Successful in 25s
driver / security (push) Successful in 59s
driver / publish (push) Skipped
driver / lowest (push) Successful in 34s
driver / types (push) Successful in 58s
driver / test (3.12) (push) Successful in 1m8s
driver / standard (push) Successful in 14s
CI / driver (push) Successful in 2m15s
2026-11-02 21:35:53 +00:00
Christian Manivong 2b2cd9b867 feat(pbs): Proxmox Backup Server as entry point proxmox_backup (#52)
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m20s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 30s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m5s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
A second driver in this package, ProxmoxBackupDriver. Its API and web UI
are on 8007, not on PVE's 8006, and its node is always localhost; open()
proves the login with GET /version, so a bad token fails there.

Roles: BackupServerDriver (napalm-device-types 4.25.0) first, then
StorageDriver for the disks and ZFS pools the server manages. It reads
datastores, the backup groups of every namespace with their newest
snapshot, a group's snapshots, the GC, verify, prune, sync and tape jobs
with how their last run ended, and the remotes without their secrets;
it starts garbage collection and jobs, verifies, protects and deletes
snapshots, and follows the tasks. As a host it reports facts,
interfaces, CPU and memory, disks, pools, its pbs-subscription and the
same packages, updates, host readers and sshd hardening as a PVE node.

A privilege-separated token without an ACL entry gets an empty list from
PBS, not a refusal, so every read checks /access/permissions and raises
PermissionError. A removable datastore that is not mounted is reported
as unmounted and left out of the group listing.

The fixture is what a PBS 4.2 answered, sanitised; groups, snapshots and
jobs it did not have yet follow the API schema.
2026-11-02 22:29:21 +01:00
Christian Manivong 0b5f82cc02 refactor: share connection and Debian host code for a second product (#52)
Proxmox Backup Server speaks the same REST dialect, logs in the same way
and runs on Debian too, so what a second driver needs moves out of
ProxmoxDriver first:

- napalm_proxmox._base: the connection (proxmoxer service PVE or PBS,
  each with its port), the token split, the SSH session, run_command,
  the node helpers and the DMI read.
- napalm_proxmox.host_mixin: packages and APT updates, the subscription,
  restart and shutdown through the API, root file writes and the
  transports of the host readers (kernel, listening sockets, identity,
  systemd, host status, apt's proxy).

The PVE driver behaves as before; what it hands proxmoxer is pinned by
tests first, and it now names service="PVE" explicitly. get_packages is
split so the dpkg line parser stands alone; get_facts and get_packages
leave the quality baseline.
2026-11-02 22:29:04 +01:00
christianmanivong a4c220d2e3 Merge pull request 'feat(ssh): harden the node's sshd through a run_command channel (#50)' (#51) from feat/ssh-hardening into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 1m6s
driver / build (push) Successful in 26s
driver / security (push) Successful in 1m5s
driver / publish (push) Skipped
driver / lowest (push) Successful in 32s
driver / test (3.12) (push) Failing after 5s
driver / types (push) Successful in 1m1s
driver / standard (push) Successful in 15s
CI / driver (push) Failing after 1m56s
2026-11-02 11:39:45 +00:00
christianmanivong 8521cff935 Merge remote-tracking branch 'origin/main' into feat/ssh-hardening
driver / security (pull_request) Successful in 1m16s
driver / test (3.12) (pull_request) Successful in 1m25s
driver / test (3.13) (pull_request) Successful in 1m11s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 35s
CI / driver (pull_request) Successful in 3m4s
driver / standard (pull_request) Successful in 20s
driver / types (pull_request) Successful in 1m27s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 17s
2026-11-02 12:07:33 +01:00
christianmanivong 321cef3426 Merge pull request 'fix(lldp): read lldpd through the shared parser and raise on failure' (#46) from fix/lldp-keyvalue into main
driver / lint (push) Successful in 22s
driver / test (3.13) (push) Successful in 1m7s
driver / build (push) Failing after 7s
driver / security (push) Successful in 1m27s
driver / publish (push) Skipped
driver / lowest (push) Successful in 39s
driver / types (push) Successful in 1m7s
driver / test (3.12) (push) Successful in 1m13s
driver / standard (push) Successful in 22s
CI / driver (push) Failing after 3m24s
2026-11-02 11:06:19 +00:00
christianmanivong d4ed73c52b Merge remote-tracking branch 'origin/main' into feat/ssh-hardening
driver / security (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / lowest (pull_request) Successful in 39s
driver / build (pull_request) Successful in 33s
CI / driver (pull_request) Successful in 3m7s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m22s
driver / test (3.12) (pull_request) Successful in 1m27s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 16s
2026-11-02 12:02:12 +01:00
Christian Manivong 7259c842e3 Merge remote-tracking branch 'origin/main' into fix/lldp-keyvalue
driver / security (pull_request) Successful in 1m9s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 30s
CI / driver (pull_request) Successful in 2m44s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 58s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 12s
2026-11-02 11:08:11 +01:00
christianmanivong a73dcf79fe Merge pull request 'fix: SSH only with the given credentials, quote the snippet path (#48, #47)' (#49) from fix/bugs-2026-11-02b into main
driver / lint (push) Failing after 7s
driver / test (3.13) (push) Successful in 1m7s
driver / build (push) Successful in 37s
driver / security (push) Successful in 1m9s
driver / publish (push) Skipped
driver / lowest (push) Successful in 35s
driver / types (push) Successful in 1m12s
driver / test (3.12) (push) Successful in 1m17s
driver / standard (push) Successful in 17s
CI / driver (push) Failing after 2m50s
2026-11-02 09:40:50 +00:00
christianmanivong ef1900c32a feat(ssh): harden the node's sshd through a run_command channel (#50)
driver / security (pull_request) Successful in 1m13s
driver / lowest (pull_request) Successful in 44s
driver / test (3.13) (pull_request) Successful in 1m23s
driver / build (pull_request) Successful in 34s
CI / driver (pull_request) Successful in 2m55s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m13s
driver / test (3.12) (pull_request) Successful in 1m23s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
A Proxmox node runs Debian's stock OpenSSH, so OpenSshServerMixin works
there as on a plain Linux host. What it needed was run_command: an exec
channel on the node's SSH session, via napalm-device-types'
run_on_transport. The USES_SSH comment said there was no SSH session;
it now says what the flag means to netOrk.
2026-11-02 10:09:27 +01:00
Christian Manivong 4ffe93fe4c Merge remote-tracking branch 'origin/main' into fix/lldp-keyvalue
driver / security (pull_request) Failing after 37s
CI / driver (pull_request) Failing after 1m39s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 15s
driver / lowest (pull_request) Failing after 18s
driver / build (pull_request) Successful in 33s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Failing after 27s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
# Conflicts:
#	README.md
#	tests/test_misc.py
2026-11-02 09:29:44 +01:00
Christian Manivong dffb19e3df fix(vm-provision): quote the cloud-init snippet path in its root command
driver / security (pull_request) Successful in 1m21s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 39s
driver / build (pull_request) Successful in 33s
CI / driver (pull_request) Successful in 3m1s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
_write_snippet put the snippet storage's path and the snippet's file
name unquoted into the command that writes the snippet as root on the
node; a space, ; or $(...) in either was acted on by the shell. Both now
go through shlex.quote, and a file name that is not one plain name
(a path, a shell character) is refused before anything runs.

Closes #47
2026-11-02 09:25:45 +01:00
Christian Manivong b3fe5009c8 fix(ssh): log in only with the credentials the driver is given
paramiko's look_for_keys and allow_agent stayed at their default True,
so the node login also tried every key in the running process's own
~/.ssh and any SSH agent it could reach. The driver standard lets a
driver authenticate only with what it was handed; both are now False
on every connect.

Closes #48
2026-11-02 09:25:04 +01:00
christianmanivong b368ad9856 Merge pull request 'fix: quote the cloud image URL, raise when a node command cannot run (#43, #17)' (#45) from fix/bugs-2026-11-02 into main
driver / lint (push) Successful in 17s
driver / test (3.13) (push) Successful in 1m8s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m13s
driver / publish (push) Skipped
driver / lowest (push) Successful in 34s
driver / types (push) Successful in 1m15s
driver / test (3.12) (push) Successful in 1m26s
driver / standard (push) Successful in 17s
CI / driver (push) Successful in 3m7s
2026-11-02 08:23:52 +00:00
Christian Manivong f93daa381e fix(lldp): read lldpd through the shared parser and raise on failure
driver / security (pull_request) Failing after 45s
driver / test (3.13) (pull_request) Failing after 17s
driver / lowest (pull_request) Failing after 18s
driver / build (pull_request) Successful in 35s
CI / driver (pull_request) Failing after 1m43s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Failing after 29s
driver / test (3.12) (pull_request) Failing after 20s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 16s
lldpcli's text was read with 2>/dev/null || true, so lldpd not running,
lldpctl missing or the command not running at all came back as a node
without neighbours. Capabilities were lldpd's symbols lower-cased (tel,
wlan, docsis) rather than NAPALM's names.

The node now runs napalm-device-types' LLDPCTL_KEYVALUE_COMMAND, whose
output carries lldpctl's exit status; parse_lldpctl_keyvalue raises on a
failure, an empty answer raises too, and the lldp_neighbors projections
give NAPALM's capability names and the chassis MAC. The module is under
strict mypy now; the floor on napalm-device-types rises to 4.24.0.

Closes #44
2026-11-02 08:55:59 +01:00
Christian Manivong daf1b519eb fix(ssh): raise when a node command cannot run, drop the execute call
driver / security (pull_request) Successful in 1m15s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 40s
CI / driver (pull_request) Successful in 2m53s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 16s
_exec_ssh_command returned "" on any failure (no SSH credential, a
refused login or host key, an unreachable node, a timeout), so a
getter that could not look read like one that found nothing; on
API-token-only nodes get_snmp_config answered None and the SSH-backed
getters empty lists on every poll. It now raises ConnectionException
with the cause (SshHostKeyMismatch as it is), and refuses before
connecting when there is neither a password nor a usable key.

It returned stderr when stdout was empty; output is stdout now. It
first posted every command to /nodes/{node}/execute, which runs a
batch of API calls rather than a shell; that dead round trip is gone.

The key types, the key before the password, the host-key check and the
single connect path were done in f491f9f and 6bb3035. The shared
transport is NAPALM/napalm-device-types#35.

Closes #17
2026-11-02 08:52:32 +01:00
Christian Manivong bfba804ec2 fix(vm-provision): quote the image URL in the node's root commands
The cloud-image download put image_url, hand-wrapped in single quotes,
and the cache path built from its basename unquoted into commands that
run as root on the node: a quote, $(...), ; or space in a URL from a
release feed was acted on by the shell. The URL and every path built
from it now go through shlex.quote (exists check, wget, mv, checksum,
rm, unpack, qm importdisk), and the cache file name keeps only the
characters Proxmox keeps in a content file name, as the import volume
name already did. The checksum algorithm is checked against the ones
Proxmox knows, since it is part of the command name.

The file-name helpers move to image_names.py; vm_provision_mixin.py
would otherwise cross the 1000-line limit. _download_cloud_image
drops below 50 lines, so its baseline entry goes.

Closes #43
2026-11-02 08:46:44 +01:00
christianmanivong 6a8132e234 Merge pull request 'fix: name the VM a failed create_vm_from_cloud_init leaves behind (#28)' (#41) from fix/half-built-vm-28 into main
driver / lint (push) Successful in 16s
driver / test (3.13) (push) Successful in 1m11s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m13s
driver / publish (push) Skipped
driver / lowest (push) Successful in 46s
driver / types (push) Successful in 1m2s
driver / test (3.12) (push) Successful in 1m21s
driver / standard (push) Successful in 16s
CI / driver (push) Successful in 2m40s
2026-11-01 23:57:55 +00:00
Christian Manivong 3233ee24a0 chore(deps): floor napalm-device-types at 4.23.0
driver / security (pull_request) Successful in 1m14s
CI / driver (pull_request) Successful in 2m47s
driver / test (3.13) (pull_request) Successful in 1m9s
driver / test (3.12) (pull_request) Successful in 1m21s
driver / lowest (pull_request) Successful in 43s
driver / build (pull_request) Successful in 32s
driver / standard (pull_request) Successful in 21s
driver / types (pull_request) Successful in 1m12s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 24s
4.23.0 is on PyPI with everything this branch uses; the git pre-install
in CI is no longer needed.
2026-11-02 00:34:19 +01:00
Christian Manivong 0f1918f230 Merge remote-tracking branch 'origin/main' into fix/half-built-vm-28
# Conflicts:
#	CHANGELOG.md
#	tests/quality_baseline.json
2026-11-02 00:33:52 +01:00
christianmanivong a8d73d95b4 Merge pull request 'fix: twelve open bugs, set_vlan uplink first (#37, #30, #23, #22, #21, #20, #19, #18, #17, #15, #12, #3)' (#40) from fix/bugs-2026-11 into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 1m24s
driver / build (push) Successful in 28s
driver / security (push) Successful in 1m17s
driver / publish (push) Skipped
driver / lowest (push) Successful in 37s
driver / types (push) Successful in 1m27s
driver / test (3.12) (push) Successful in 1m43s
driver / standard (push) Successful in 17s
CI / driver (push) Successful in 3m33s
2026-11-01 22:50:18 +00:00
christianmanivong 8dad7c3767 Merge pull request 'feat: HA state, backups and votes in get_clusters(); migrate_vm, preflight, maintenance' (#42) from feat/vm-lifecycle into main
driver / lint (push) Successful in 16s
driver / test (3.13) (push) Successful in 1m18s
driver / build (push) Successful in 38s
driver / security (push) Successful in 1m31s
driver / publish (push) Skipped
driver / lowest (push) Successful in 1m0s
driver / types (push) Successful in 1m12s
driver / test (3.12) (push) Successful in 1m20s
driver / standard (push) Successful in 18s
CI / driver (push) Successful in 3m16s
2026-11-01 22:02:36 +00:00
Christian Manivong 0704d9a102 feat: HA state, backups and votes in get_clusters(); migrate_vm, preflight, maintenance
driver / security (pull_request) Successful in 1m27s
CI / driver (pull_request) Successful in 3m4s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 33s
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m3s
driver / publish (pull_request) Skipped
get_clusters() reads /cluster/ha/* (PVE 8 and 9), /cluster/backup with pool
members, the newest backup per guest on each backup storage (PBS included) and
/cluster/config/nodes votes; each read is best-effort. migrate_vm() moves a
guest of the connected node and follows the task (HA-managed guests through
the HA manager), raising with the task log's ERROR lines;
get_vm_migration_preflight() maps PVE's own pre-flight; set_node_maintenance()
runs ha-manager over SSH.

Part of NetOrk/netork#1820 (stage 7: #759, #760, #761).
2026-11-01 22:15:01 +01:00
Christian Manivong 61821cd607 fix: name the VM a failed create_vm_from_cloud_init leaves behind
driver / security (pull_request) Successful in 1m9s
CI / driver (pull_request) Failing after 2m49s
driver / test (3.12) (pull_request) Failing after 1m6s
driver / lowest (pull_request) Failing after 5s
driver / test (3.13) (pull_request) Failing after 58s
driver / build (pull_request) Successful in 31s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m5s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
A failure after the VM shell existed (disk import, NIC or snippet config,
start) raised without the VMID, so the caller could not remove the
half-built VM and it stayed on the node. It now raises napalm-device-types'
VMProvisionIncomplete with vmid and node, the failure as its cause. A
failure before the shell exists raises as before.

The NIC config strings are built by a helper of their own, which keeps
create_vm_from_cloud_init within its quality baseline.

Closes #28
2026-11-01 22:11:13 +01:00
Christian Manivong 8ef880b73b fix(hostname): refuse to rename a clustered node
driver / security (pull_request) Successful in 1m20s
driver / test (3.12) (pull_request) Successful in 1m26s
driver / lowest (pull_request) Successful in 43s
driver / test (3.13) (pull_request) Successful in 1m21s
driver / build (pull_request) Successful in 38s
CI / driver (pull_request) Successful in 3m12s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m20s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
The rename moves /etc/pve/nodes/<old> while the node still runs as <old>,
which Proxmox does not support for a cluster member. set_hostname now
checks for a corosync.conf first and raises before touching anything on
a member, or when the check cannot be read; a single node renames as
before.

The check is the file, not `pvecm status`: pvecm decides membership by
/etc/pve/corosync.conf itself, and its status also fails on a member
whose corosync is down. /etc/corosync/corosync.conf covers a member
whose /etc/pve is not mounted.

Closes #21
2026-11-01 22:08:54 +01:00
Christian Manivong 9c7b64ba64 fix(vm-provision): say why a cloud-image download failed, drop its tmp
driver / security (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m26s
driver / lowest (pull_request) Successful in 37s
driver / build (pull_request) Successful in 32s
CI / driver (pull_request) Successful in 3m19s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m29s
driver / test (3.12) (pull_request) Successful in 1m39s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
wget ran with -q, so a failure carried no reason, and a failed
download left its partial .tmp in the cache, taking the same space
again on every retry. wget now runs with -nv and the .tmp is removed
on failure, keeping wget's exit status.

Closes #3
2026-11-01 21:57:36 +01:00
Christian Manivong 10cf788b86 fix(ping): parse each reply into results
The probe pattern expected "from" after icmp_seq, but iputils prints
"bytes from <ip>: icmp_seq=... time=... ms", so results was always
empty. Replies by name ("from host (ip)") and over IPv6 are read too.

Closes #12
2026-11-01 21:57:36 +01:00
Christian Manivong 29ed59c8d1 fix(vm-provision): wait for destroy_vm's delete task
DELETE /nodes/{node}/qemu/{vmid} starts a task and returns its UPID;
destroy_vm ignored it and returned while the VM could still exist, and
a failed delete went unnoticed. The task is now awaited. Reading the
snippets before the delete, the issue's first point, was fixed in
ecff2b4.

Closes #15
2026-11-01 21:57:36 +01:00
Christian Manivong f491f9f9ec fix(ssh): log in with any key type, the key before the password
Only RSA keys were read, and a key was used only when no password was
set; with the API password always present it never was. The key is now
read as Ed25519, ECDSA or RSA and offered first, the password second.

The rest of the issue (the API exec branch, errors read as empty
output) belongs to the shared transport of NAPALM/napalm-device-types#35.

Refs #17
2026-11-01 21:57:36 +01:00
Christian Manivong 5195cebfca fix(ntp): read chrony's sources in get_ntp_stats
The getter ran "chronyc tracking || ntpq -pn" and parsed ntpq's format.
Proxmox VE ships chrony, so ntpq never ran and nothing matched. chrony
is now read in CSV mode (sources plus sourcestats); ntpq stays the
fallback and keeps peers without a tally mark.

Closes #18
2026-11-01 21:52:03 +01:00
Christian Manivong 4ee74e4b3d fix(users): list real login accounts and read admins from the ACL
The passwd filter's precedence was inverted: it listed uid < 1000
(daemon, bin, ...) and skipped regular users. The level check looked
for "Administrator" in the user record, which never names roles. The
level now comes from /access/acl (Administrator on /, by user or
group), root@pam always 15.

Closes #19
2026-11-01 21:50:16 +01:00
Christian Manivong 037a725b74 fix(updates): report a failed apply_updates as a failure
apt-get ran with "|| true" and the result was always success, so a
failed upgrade read as done. The exit status is read now and a failure
names it.

Closes #20
2026-11-01 21:48:48 +01:00
Christian Manivong 8f10bef7c5 fix(hostname): rename only the node's own names in /etc/hosts
The rename replaced \b<old>\b, which also matches before "." and "-":
"pve.old.lan pve" became "new.dom.old.lan new.dom" and "pve-backup"
became "new-backup". Whole whitespace-separated names are renamed now,
comments left alone.

The live move of /etc/pve/nodes/<old> the issue also asks about is not
changed here; it needs a decision on clustered nodes.

Refs #21
2026-11-01 21:48:06 +01:00
Christian Manivong 89c70d85be fix(lldp): keep every neighbour of a port apart
lldpcli prints one Interface block per neighbour. The summary parser
reused the port's last entry, so a second neighbour overwrote the
first, and a neighbour without SysName was dropped. Each block now
starts an entry of its own.

Closes #22
2026-11-01 21:46:51 +01:00
Christian Manivong 0779695349 fix(vm-provision): pass every SSH key, one per line
Proxmox's sshkeys holds one OpenSSH key per line, URL-encoded. The keys
were joined with ";", so only the first one worked, and quote() kept
"/" unescaped, which Proxmox's urlencoded format refuses.

Closes #23
2026-11-01 21:45:49 +01:00
Christian Manivong 52d63eb689 fix(snmp): let the snmpd.conf write report its exit status
The write ended in `exit $s`, which ends the shell inside the braces
_rc wraps around every command, so __PVE_RC was never printed and the
step always failed. The write now shares the apt file writer, which
ends in a test instead of exit.

Closes #30
2026-11-01 21:44:23 +01:00
Christian Manivong d142db73e5 fix(sdn): restore the virtual interface prefixes for set_vlan
b1ba991 removed _VIRTUAL_IFACE_PREFIXES while _is_physical_uplink still
read it. The AttributeError was swallowed by _find_switch_uplink, so
set_vlan never found an uplink on any node. Restore the constant and
cover both helpers with tests.

Closes #37
2026-11-01 21:43:09 +01:00
christianmanivong cb29a42c31 Merge pull request 'feat: get_clusters() for the whole cluster, node= refused for another node' (#39) from feat/cluster-inventory into main
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m6s
driver / build (push) Successful in 26s
driver / security (push) Successful in 1m10s
driver / publish (push) Skipped
driver / lowest (push) Successful in 39s
driver / test (3.12) (push) Failing after 6s
driver / types (push) Successful in 1m4s
driver / standard (push) Successful in 15s
CI / driver (push) Failing after 2m8s
2026-11-01 19:06:53 +00:00
Christian Manivong 25369df572 refactor: import the cluster shapes from the package root
driver / security (pull_request) Successful in 1m21s
CI / driver (pull_request) Successful in 2m58s
driver / test (3.12) (pull_request) Successful in 1m16s
driver / test (3.13) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 32s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m10s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
napalm-device-types keeps them in a module of their own now; the package exports them.

Refs NetOrk/netork#484
2026-11-01 17:08:10 +01:00
Christian Manivong f60532e434 feat: get_clusters() for the whole cluster, node= refused for another node
driver / security (pull_request) Successful in 1m3s
driver / test (3.13) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 28s
CI / driver (pull_request) Failing after 2m42s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Failing after 1m2s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
Every PVE node can read its whole cluster, so get_clusters() reports the
one it belongs to: name and quorum from /cluster/status, every member
(offline ones as offline, without capacity), CPU and memory from
/cluster/resources and each online node's cpuinfo, maintenance from the
HA manager where it can be read, storages grouped by name with the nodes
they are available on, and bridges and vnets with the nodes that carry
them. A standalone node is a cluster of one.

The bridge part of get_network_targets() moved to network_targets.py so
both use it. create_vm_from_cloud_init() takes node= and refuses any node
but its own before creating anything.

Refs NetOrk/netork#484, NetOrk/netork#1822
2026-11-01 16:38:38 +01:00
christianmanivong d8ac209fb9 Merge pull request 'feat: get_network_targets names each bridge's uplinks (NetOrk/netork#1325)' (#38) from feat/network-target-uplinks into main
driver / lint (push) Successful in 16s
driver / test (3.13) (push) Successful in 1m7s
driver / build (push) Successful in 47s
driver / security (push) Successful in 1m23s
driver / publish (push) Skipped
driver / lowest (push) Successful in 34s
driver / types (push) Failing after 6s
driver / test (3.12) (push) Successful in 1m12s
driver / standard (push) Successful in 20s
CI / driver (push) Failing after 2m56s
2026-10-30 09:20:32 +00:00
christianmanivong d5ae2e2915 Merge pull request 'fix: an unknown IPv6 neighbour age is -1.0, not 0.0' (#36) from fix/arp-unknown-age into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m35s
driver / build (push) Successful in 36s
driver / security (push) Successful in 1m27s
driver / publish (push) Skipped
driver / lowest (push) Successful in 36s
driver / types (push) Successful in 1m32s
driver / test (3.12) (push) Successful in 1m36s
driver / standard (push) Successful in 18s
CI / driver (push) Successful in 3m37s
2026-10-30 09:11:46 +00:00
Christian Manivong 72c30dd4c2 feat: get_network_targets names each bridge's uplinks (NetOrk/netork#1325)
driver / security (pull_request) Successful in 1m21s
driver / test (3.13) (pull_request) Successful in 1m11s
driver / test (3.12) (pull_request) Successful in 1m15s
driver / lowest (pull_request) Successful in 38s
driver / build (pull_request) Successful in 37s
CI / driver (pull_request) Successful in 3m5s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m7s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
netOrk's VM dialog follows a bridge's physical NICs to the switch port
behind it, to warn when a VM without a VLAN tag would land nowhere. The
driver knows those NICs from the node's network config.

uplinks is read from bridge_ports (Linux bridge) or ovs_ports (OVS
bridge), one group per bridge port: a bond (slaves / ovs_bonds) as its
NICs together, a NIC alone. Internal ports (OVSIntPort) and VLAN
subinterfaces leave out, as they never carry the bridge's untagged
traffic to the switch. A port missing from the config or of a kind the
driver cannot place leaves the key out rather than guessing.
2026-10-30 09:28:07 +01:00
Christian Manivong cc9752499e fix: an unknown IPv6 neighbour age is -1.0, not 0.0
driver / security (pull_request) Successful in 1m17s
driver / test (3.13) (pull_request) Successful in 59s
driver / lowest (pull_request) Successful in 38s
driver / build (pull_request) Successful in 39s
CI / driver (pull_request) Successful in 2m50s
driver / standard (pull_request) Successful in 15s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m5s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
get_ipv6_neighbors_table reports ARP_AGE_UNKNOWN, as get_arp_table already
did, instead of 0.0 ("confirmed just now").

NetOrk/netork#1327
2026-10-30 08:37:08 +01:00
christianmanivong d577e7aae2 Merge pull request 'chore: Python 3.12 is the floor (NAPALM/driver-standard#6)' (#35) from chore/python-312-floor into main
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m1s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m14s
driver / publish (push) Skipped
driver / lowest (push) Successful in 33s
driver / types (push) Successful in 1m3s
driver / test (3.12) (push) Successful in 1m10s
driver / standard (push) Successful in 17s
CI / driver (push) Successful in 2m54s
2026-10-27 09:46:57 +00:00
Christian Manivong 739d12a3db chore: Python 3.12 is the floor (NAPALM/driver-standard#6)
driver / security (pull_request) Successful in 1m25s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 32s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / build (pull_request) Successful in 30s
CI / driver (pull_request) Successful in 3m1s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 59s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
netOrk runs every driver in its own containers on Python 3.12, so 3.10
and 3.11 are no longer supported or tested. requires-python, mypy and
ruff move to 3.12, along with what ruff's pyupgrade rules then rewrite.
2026-10-27 10:18:59 +01:00
christianmanivong 8205829437 Merge pull request 'feat: shutdown_host and begin_stop_vm through the API' (#34) from feat/shutdown-requests into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m4s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m10s
driver / publish (push) Skipped
driver / test (3.11) (push) Successful in 1m19s
driver / lowest (push) Successful in 36s
driver / types (push) Successful in 1m10s
driver / test (3.12) (push) Successful in 1m9s
driver / standard (push) Successful in 17s
driver / test (3.10) (push) Successful in 1m18s
CI / driver (push) Successful in 3m38s
2026-10-27 07:41:23 +00:00
Christian Manivong 16f1b87392 feat: shutdown_host and begin_stop_vm through the API
driver / test (3.10) (pull_request) Successful in 1m9s
driver / test (3.11) (pull_request) Successful in 1m8s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 3m17s
driver / lowest (pull_request) Successful in 34s
driver / test (3.12) (pull_request) Successful in 1m3s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / build (pull_request) Successful in 26s
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 11s
driver / types (pull_request) Successful in 1m2s
driver / publish (pull_request) Skipped
shutdown_host() posts command=shutdown to the node itself; its guests
stop as on any shutdown. begin_stop_vm(name) asks a guest for its clean
shutdown and returns once Proxmox took it, without waiting for the
task: the caller reads get_vm_status until it stopped. Both raise
RuntimeError when Proxmox refuses; an unknown guest is a ValueError.

The contracts HostShutdownMixin and VmStopRequestMixin of
napalm-device-types (NAPALM/napalm-device-types#55); for netOrk's graph
workflows (NetOrk/netork#1636).
2026-10-27 00:39:17 +01:00
78 changed files with 12006 additions and 1099 deletions

No files matched your search

-2
View File
@@ -11,7 +11,5 @@ jobs:
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
with:
standard-ref: main
# Until napalm-device-types 4.22.0 (AptProxyMixin, #53) is on PyPI.
pre-install: "git+https://git.netork.io/NAPALM/napalm-device-types.git"
secrets:
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+310
View File
@@ -7,6 +7,316 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [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`,
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
server's release line, Zabbix's from its repository; writes the caller's values into
`/etc/zabbix/zabbix_agentd.conf` (the old file stays as `.bak`); opens tcp/`listen_port`
in ufw where the node has it (pve-firewall's rules are the operator's); enables and
restarts the service.
- Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types'
`TimeSyncMixin` (4.36.0); both write the servers and the zone. Neither API keeps time
servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's
sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised and
the zone (`timedatectl`) in one round trip over the driver's SSH session
(`PosixTimeSyncMixin`), and the zone from `GET /nodes/{node}/time` only where the host
names none. `configure_time_sync()` writes the servers to
`/etc/chrony/sources.d/netork.sources` with every other configured source commented out
(Debian's vendor pool; the DHCP `sourcedir` stays) and reloads or restarts chrony; the zone
goes through `PUT /nodes/{node}/time`, Proxmox's own call, so `/etc/timezone` and the
web UI follow `/etc/localtime`. The token needs `Sys.Modify` for it (PVE on
`/nodes/{node}`, PBS on `/system/time`). Only the node of the connection is read and
written: in a PVE cluster each node keeps its own clock.
- What a restart would abort, on both drivers (NetOrk/netork#2318), through
napalm-device-types' `RunningBackupsMixin` (4.34.0): `get_running_backups()` lists on
Proxmox VE the node's active vzdump tasks with the guests each is taking now -- the task's
own guest, or for a job the guests locked for their backup (`lock: backup`) -- and a guest
locked without a task on its own; on a backup server the running backup, sync, verify,
garbage collection, prune and tape tasks. A failed read raises.
- Log sources on both drivers (NetOrk/netork#2049), through napalm-device-types'
`LogSourcesMixin` (4.30.0): `get_log_sources()` reads the units journald holds entries for
and the log files running processes hold open, with the service or container writing each,
over the exec path as root.
- Scheduled jobs on both drivers (NetOrk/netork#1933, #56), through napalm-device-types'
`PosixScheduledJobsMixin`: `get_scheduled_jobs()` reads `/etc/crontab`, `/etc/cron.d`,
the user crontabs, the run-parts directories, `/etc/anacrontab` and every systemd timer
in one round trip as root; `manage_scheduled_job()` enables, disables or runs one now;
`put_scheduled_job()` and `delete_scheduled_job()` write and remove an application's own.
What Proxmox ships is `platform`: on Proxmox VE `pve-*` units (`pve-daily-update.timer`),
`pvesr.timer` and `/etc/cron.d/vzdump`; on a backup server `proxmox-backup*` units
(`proxmox-backup-daily-update.timer`). A line in `/etc/cron.d/vzdump` is only run, never
switched: the file is a link to `/etc/pve/vzdump.cron` on the cluster file system
(pmxcfs), where installing a file with a mode and owner is not safe.
Not scheduled jobs here: Proxmox VE's backup jobs (`/cluster/backup`) and replication,
and a backup server's verify, prune, sync and garbage collection jobs. Proxmox runs them
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
### 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`).
- The SNMP agent's ufw step is the shared `_allow_sources(allowed, port, proto)`; the rule
it writes for udp/161 is the same.
### Fixed
- `set_hostname()` hands the name to the shell quoted (`shlex.quote`): to `hostname`, to
`postconf -e` and in the paths of the `/etc/pve/nodes` move (#64, NetOrk/netork#2456). They
stood between single quotes of their own, so a name with a single quote ended them and
the rest ran as root (`x';reboot;'`).
- `set_hostname()` writes the new `/etc/hosts` to a `mktemp` file beside it
(`/etc/.hosts.XXXXXX`), sets its mode and moves it into place; a failed step removes
it (#66, NetOrk/netork#2446). It wrote as root to the fixed `/tmp/_netork_hosts` and
moved that over `/etc/hosts`, so a local user who created the file first owned
`/etc/hosts` afterwards.
- `get_ntp_servers()` read `GET /nodes/{node}/ntp`, a path Proxmox VE does not have, and so
always reported no servers. It now reports chrony's configured sources, the ones
`get_time_sync()` reads, and the backup server has it too.
## [0.10.0] - 2026-11-03
### Added
- `get_clusters()` names the backup server behind each `pbs` storage
(`ClusterStorageDict.backup_server`: server, port, datastore, namespace, fingerprint,
read from `/storage`; never its password or encryption key), so an application can tie a
Proxmox Backup Server's groups to the cluster's guests (#55). An unreadable `/storage`
leaves it `None`; every other storage carries no such key.
## [0.9.0] - 2026-11-02
### Added
- **Proxmox Backup Server** as a second driver of this package, entry point
`proxmox_backup` (`ProxmoxBackupDriver`, #52). Its API is on **8007**, not 8006; the
node is always `localhost`. Roles: `BackupServerDriver` (napalm-device-types 4.25.0)
first, `StorageDriver` second. It reads datastores (usage, estimated full date,
backend, maintenance or `unmounted`), backup groups in every namespace with their
newest snapshot and its verify state, a group's snapshots, the GC, verify, prune,
sync and tape jobs with the state of their last run, and the remotes without their
secrets; it starts garbage collection and jobs, verifies, protects and deletes
snapshots, and follows the tasks. As a host it reports facts, interfaces, CPU and
memory, disks and ZFS pools, its `pbs-subscription`, packages and updates, and has
the same host readers and sshd hardening as a PVE node.
- A token without an ACL entry gets an empty list from PBS rather than a refusal; every
read checks `/access/permissions` first and raises `PermissionError`.
- The node's sshd can be hardened: `OpenSshServerMixin` (napalm-device-types) gives
`harden_ssh_server` and `exempt_from_ssh_penalties`, so netOrk's SSH algorithm fix
works on a Proxmox node as on a plain Linux host. A node runs Debian's stock
OpenSSH with an `sshd_config.d` include, so the change is a drop-in there (#50).
- `run_command(command, *, privileged=False, timeout=60, stdin=None)`, the public
command channel: an exec channel on the node's SSH session with stdout, stderr and
the exit status kept apart. `privileged` needs nothing more on a node logged in as
root; a command that cannot run or outlasts its timeout raises `ConnectionException`.
### Changed
- The floor on napalm-device-types is 4.25.0, the first release with
`BackupServerDriver` (4.24.0 brought the shared `lldpctl` parser).
- What the two drivers share moved out of `ProxmoxDriver`: the connection, token split,
SSH session and node helpers into `napalm_proxmox._base`, the Debian host's packages,
updates, subscription and the host readers' transports into
`napalm_proxmox.host_mixin`. The PVE driver behaves as before, pinned by tests first;
it now names proxmoxer's `service="PVE"` explicitly.
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
### Added
- `get_clusters()` reports quorum `votes` per node (`/cluster/config/nodes`), the
guests HA manages in `ha_resources` (`/cluster/ha/resources`, the CRM state and
node from `/cluster/ha/status/current`, the ids of the PVE 9 HA rules that name
each from `/cluster/ha/rules`, `[]` on PVE 8), the vzdump jobs in `backup_jobs`
(`/cluster/backup`; a pool job lists the pool's guests from `/pools?poolid=`, or
`/pools/{pool}` before PVE 8.1; old `starttime`/`dow` jobs get the schedule PVE
itself derives) and per guest and storage the newest backup in `backups` (each
storage with backup content read once if shared, on each node if local; PBS
included). Each is best-effort: one that cannot be read is None and the rest of
the report stands.
- `get_vm_migration_preflight(name)`: a VM's nodes and blockers from
`GET .../qemu/{vmid}/migrate` in plain words, a local ISO in a CD drive as a
blocking resource, the cloud-init drive left out; a container's candidates are the
online members, its local volumes and unshared bind mounts read from its config.
An offline member is refused as `"node offline"` for both.
- `migrate_vm(name, target_node, online=True, target_storage=None, timeout=3600)`:
`POST .../{qemu|lxc}/{vmid}/migrate` (`online` for a running VM, `with-local-disks`
when it has local disks, restart mode for a running container), followed to the
end; a failure raises with the task log's `ERROR:` lines. A target that is not
another cluster member is refused before the API is called. A guest HA manages is
followed through the HA manager until it is on the target.
- `set_node_maintenance(node, enabled)`: `ha-manager crm-command node-maintenance`
over the driver's SSH session, for a cluster member only and quoted; raises
RuntimeError when SSH is not available. Needs the shapes and contracts of the
next napalm-device-types release for type checking (runtime imports none).
- `get_clusters()`: the cluster the node belongs to, always exactly one, read
from `/cluster/status`, `/cluster/resources`, each online node's status and
network, SDN vnets/zones and the HA manager. Every member is listed, an
offline one with `status` `"offline"` and no capacity; `maintenance` is None
when the HA manager cannot be read. Storages are grouped by name with the
nodes they are available on (size: one node's figure for a shared storage,
the sum over its nodes for a local one); bridges are merged across nodes,
VLAN aware only if they are on every node; a vnet is on its zone's nodes. A
standalone node is a cluster of one without a name. `create_vm_from_cloud_init()`
takes `node` and raises ValueError, before creating anything, for a node
other than its own (NetOrk/netork#484, NetOrk/netork#1822). Needs the cluster
models and `get_clusters()` contract of napalm-device-types.
- `get_network_targets()` names each bridge's physical NICs in `uplinks`, read
from `bridge_ports`/`ovs_ports`, one group per bridge port: a bond's slaves
together, a NIC alone, without internal ports (`OVSIntPort`) and VLAN
subinterfaces. Left out when a port is missing from the
node's network config or of a kind it cannot place (NetOrk/netork#1325). Needs
the `uplinks` field of napalm-device-types' `NetworkTargetDict`.
- `shutdown_host()`: the node shuts itself down through the API
(`POST /nodes/{node}/status command=shutdown`), and `begin_stop_vm(name)`: a
guest's clean shutdown, returning once Proxmox took it instead of waiting for
the task — the contracts `HostShutdownMixin` and `VmStopRequestMixin` of
napalm-device-types (NetOrk/netork#1636).
### Fixed
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` raise when lldpctl fails
(lldpd not running, lldpctl missing) or the node gives no answer, with lldpctl's
message; they used to return no neighbours, the same answer as a node without any
(#44). Capabilities carry NAPALM's names (`telephone`, `wlan-access-point`,
`docsis-cable-device`) instead of lldpd's symbols (`tel`, `wlan`, `docsis`).
lldpd is read with `lldpctl -f keyvalue` through napalm-device-types' shared
parser, so a neighbour named by its chassis MAC also carries it as `mac`, and an
interface name with a dot stays whole.
- `get_ipv6_neighbors_table()` reports an unknown age as `-1.0`, as `get_arp_table()`
already did (napalm-device-types' `ARP_AGE_UNKNOWN`), instead of `0.0`, which
means "confirmed just now" (NetOrk/netork#1327).
- `set_vlan()` finds the node's switch uplink again. Since 0.8.0 every call failed
with "no LLDP-detected switch uplink found", whatever LLDP reported (#37).
- `configure_snmp_agent()` completes: its "configure" step reported a failure
with empty output although `/etc/snmp/snmpd.conf` was written, so the firewall
and start steps never ran (#30).
- `create_vm_from_cloud_init(ssh_public_keys=...)` installs every key, one per
line, instead of only the first; a key containing `/` or `+` is no longer
refused by Proxmox (#23).
- `get_lldp_neighbors()` lists every neighbour of a port: a second neighbour on
the same port no longer overwrites the first, and a neighbour that sends no
system name is listed with an empty `hostname` instead of being dropped (#22).
- `set_hostname()` renames only the node's own names in `/etc/hosts`: other
hosts whose names start with the old one (`pve-backup`) and comments stay as
they are, and the old FQDN becomes the new one instead of a mix of both (#21).
- `set_hostname()` refuses a node that is part of a cluster (a
`/etc/pve/corosync.conf` or `/etc/corosync/corosync.conf` exists) with a
`CommandErrorException`, before changing anything: it moved
`/etc/pve/nodes/<old>` while the cluster still knew the node as `<old>`. Also
refused when the check cannot be read. A single node renames as before (#21).
- `apply_updates()` reports a failed upgrade as `success: False`, with apt-get's
exit status in `error`; it reported success whatever apt-get did (#20).
- `get_users()` lists the node's root and regular login accounts (uid 1000 and
up) instead of its system accounts (`daemon`, `bin`, …), and gives a Proxmox
user level 15 when the ACL grants it the Administrator role on `/`, directly
or through a group; `root@pam` is always 15. Before, practically every
Proxmox user was level 1 (#19).
- `get_ntp_stats()` reports chrony's sources, Proxmox VE's default, instead of
always returning an empty list: offset in ms, the poll interval in seconds,
the offset's standard deviation as `jitter`; chrony reports no delay, so
`delay` is 0.0. On ntpd, a peer without tally mark is no longer dropped (#18).
- The SSH login to the node takes an Ed25519 or ECDSA key in
`ssh_private_key_str`, not only RSA, and uses the key even when a password is
set too (the password stays the fallback). A key that cannot be read is
logged as a warning and the password used (#17).
- `destroy_vm()` returns once Proxmox has deleted the VM, not as soon as the
delete was queued, and raises when the delete fails (#15).
- `ping()` fills `results` with each reply's address and round-trip time; it
was always empty (#12).
- A failed cloud-image download in `create_vm_from_cloud_init()` says why
(wget's own message, such as "No space left on device") and removes its
partial `.tmp` file instead of leaving it to fill the node's disk (#3).
- A `create_vm_from_cloud_init()` that fails once the VM shell exists (disk import,
storage, NIC or snippet configuration, start) raises `VMProvisionIncomplete`, a
`RuntimeError` with the VMID and node of the VM it left behind and the failure as
its cause, so the caller can remove it with `destroy_vm()`. Failures there that
were a `ValueError` (no snippet storage, a NIC without a bridge) are its cause now.
Needs `VMProvisionIncomplete` from napalm-device-types (#28).
- `create_vm_from_cloud_init()` quotes the image URL and every path built from it in
the commands it runs as root on the node (download, checksum, unpack, disk
import). A URL with a quote, `$(…)`, `;` or a space no longer reaches the shell:
the node's cache file name keeps only the characters Proxmox keeps in a file
name, the others become `_`. A checksum algorithm other than md5, sha1, sha224,
sha256, sha384 or sha512 is refused with a `ValueError` before anything runs on
the node (#43).
- Commands on the node (ARP, IPv6 neighbours, packages, users, NTP, SNMP config,
services, kernel facts, `cli()`, …) raise `ConnectionException` when they cannot run:
no SSH password or key (a node reached with an API token only), a refused login, an
unreachable node, a timeout; a changed host key raises `SshHostKeyMismatch` as
before. They returned empty output, so "could not look" read as "nothing there":
`get_snmp_config()` answered None on token-only nodes and the getters empty lists.
Only what a command prints on stdout is its output; stderr no longer stands in when
stdout is empty. Each command goes straight to SSH: the driver first posted it to
`/nodes/{node}/execute`, which runs API calls, not a shell, and always failed (#17).
- The SSH login to the node uses only the credentials it is given
(`ssh_private_key_str`, `ssh_password` or the API password): paramiko no longer also
tries the keys in the running process's `~/.ssh` or an SSH agent it can reach (#48).
- `create_vm_from_cloud_init()` quotes the snippet storage's path and the snippet's
file name in the command that writes the cloud-init snippets as root on the node,
and refuses a snippet name that is not one plain file name (#47).
## [0.8.0] - 2026-10-23
The first release on PyPI. It collects everything since 0.1.0.
+95 -15
View File
@@ -1,6 +1,9 @@
# napalm-proxmox
A [NAPALM](https://napalm.readthedocs.io/) driver for [Proxmox VE](https://www.proxmox.com/en/proxmox-virtual-environment/overview) nodes.
[NAPALM](https://napalm.readthedocs.io/) drivers for [Proxmox VE](https://www.proxmox.com/en/proxmox-virtual-environment/overview) nodes
(`proxmox`) and for [Proxmox Backup Server](https://www.proxmox.com/en/proxmox-backup-server/overview) (`proxmox_backup`).
The Proxmox VE driver is described first; the backup server's is
[below](#proxmox-backup-server).
It supports all three networking domains of Proxmox VE:
@@ -12,7 +15,7 @@ It supports all three networking domains of Proxmox VE:
## Requirements
- Python ≥ 3.10
- Python ≥ 3.12
- NAPALM ≥ 5.0.0
- napalm-device-types ≥ 4.22.0
- proxmoxer ≥ 2.0.0
@@ -103,11 +106,11 @@ device = driver(
| `get_interfaces_ip` | IPv4/IPv6 from classic ifaces + SDN subnet gateways |
| `get_interfaces_counters` | From `node/netstat` RRD data |
| `get_environment` | CPU %, memory (bytes), hardware temperature sensors |
| `get_arp_table` | Reads `/proc/net/arp` via exec endpoint |
| `get_arp_table` | Reads `/proc/net/arp` over SSH |
| `get_mac_address_table` | `bridge fdb show` (Linux) + `ovs-appctl fdb/show` (OVS) |
| `get_vlans` | SDN VNet tags + `bridge vlan show` |
| `get_network_instances` | SDN zones (VLAN→L2VPN, EVPN→L3VRF) + default instance |
| `get_ntp_servers` | From `node/ntp` API |
| `get_ntp_servers` | chrony's configured sources, as `get_time_sync` reads them |
| `get_ntp_stats` | Parses `chronyc` / `ntpq -pn` output |
| `get_snmp_information` | Parses `/etc/snmp/snmpd.conf` |
| `get_users` | Proxmox access/users API + local `/etc/passwd` |
@@ -116,13 +119,18 @@ device = driver(
| `compare_config` | Unified diff |
| `commit_config` | Writes `/etc/network/interfaces` + `ifreload -a` |
| `discard_config` / `rollback` | Revert candidate |
| `get_lldp_neighbors` | `lldpcli show neighbors` via exec |
| `get_lldp_neighbors_detail` | Full LLDP detail |
| `get_lldp_neighbors` | `lldpctl -f keyvalue` over SSH (napalm-device-types' parser); raises when lldpctl fails |
| `get_lldp_neighbors_detail` | Full LLDP detail, capabilities in NAPALM's names |
| `get_ipv6_neighbors_table` | `ip -6 neigh show` |
| `ping` | Linux `ping` via exec endpoint |
| `traceroute` | `traceroute -n` via exec endpoint |
| `cli` | Arbitrary command execution via exec endpoint |
| `get_route_to` | `ip route show` via exec endpoint |
| `ping` | Linux `ping` over SSH |
| `traceroute` | `traceroute -n` over SSH |
| `cli` | Arbitrary commands over SSH (stdout) |
| `get_route_to` | `ip route show` over SSH |
| `get_scheduled_jobs` | cron, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers, as root over SSH (napalm-device-types' `PosixScheduledJobsMixin`); `pve-*` units, `pvesr.timer` and `/etc/cron.d/vzdump` are `platform` |
| `manage_scheduled_job(key, action, digest=)` | enable, disable, run now; a `/etc/cron.d/vzdump` line only runs |
| `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 |
| `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 |
**Not implemented** (raise `NotImplementedError`):
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
@@ -138,6 +146,69 @@ device = driver(
| `node` | str | *auto* | Override target node name |
| `token_name` | str | `None` | API token identifier (`user@realm!tokenid`) |
| `token_value` | str | `None` | API token secret |
| `ssh_username` | str | *username* | Login for the node's SSH (port 22) |
| `ssh_password` | str | *password* | SSH password; the API password when not set |
| `ssh_private_key_str` | str | `None` | SSH private key (Ed25519, ECDSA or RSA), tried before the password |
What the API does not offer (ARP, LLDP, packages, SNMP config, `cli`, …) runs in the
node's shell over SSH. Without an SSH password or key — a node reached with an API
token only — those calls raise `ConnectionException` instead of reading as empty.
## Proxmox Backup Server
```python
driver = get_network_driver("proxmox_backup")
device = driver(
hostname="pbs1.example.com",
username="",
password="",
optional_args={
"token_name": "root@pam!monitoring",
"token_value": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"ssh_private_key_str": open("id_ed25519").read(), # optional, see below
},
)
```
**The API and web UI listen on 8007**, not on Proxmox VE's 8006; `port` defaults to
8007 here. The node is always `localhost`: a backup server has no cluster. The
optional arguments are the ones above, except `node`.
Roles (napalm-device-types): `BackupServerDriver` first, `StorageDriver` second for
the disks and ZFS pools the server manages itself.
| Method | Source |
|--------|--------|
| `get_backup_datastores` | `/config/datastore` + `/status/datastore-usage`: usage, estimated full date, backend (`local`, `s3`, `removable`), maintenance or `unmounted` |
| `get_backup_groups` / `get_backup_snapshots` | `/admin/datastore/{store}/{namespace,groups,snapshots}`, every namespace; a group carries its newest snapshot with its verify state |
| `get_backup_jobs` | `/admin/{gc,verify,prune,sync}`, `/tape/backup`, with the state of the last run |
| `get_backup_remotes` | `/config/remote`, without secrets |
| `start_garbage_collection`, `run_backup_job`, `verify_backup_snapshot` | start a task; `get_backup_task` follows it |
| `set_backup_snapshot_protected`, `delete_backup_snapshot` | on one snapshot |
| `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_licenses` | `pbs-subscription` |
| packages, updates, services, kernel, listening sockets, 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 |
| `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`) |
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
`Audit` does not include. A privilege-separated token needs an ACL entry of its own:
```bash
proxmox-backup-manager acl update / Audit --auth-id 'root@pam!monitoring'
```
Without it PBS does not refuse a listing, it answers with an empty one. The driver
therefore checks `/access/permissions` before every read and raises
`PermissionError`, so a token without rights does not read as a server without
backups. The actions need `DatastoreAdmin` on `/datastore` (GC, verify, prune,
protect, delete) and `Sys.Modify` / `Sys.PowerManagement` on `/system` (services,
reboot).
A removable datastore that is not mounted is reported as `maintenance: "unmounted"`
and left out of `get_backup_groups()`; asked for by name, it raises `ValueError`.
## Development
@@ -157,9 +228,14 @@ ruff check napalm_proxmox
```
napalm_proxmox/
├── __init__.py # Exports ProxmoxDriver
├── driver.py # ProxmoxDriver — all NAPALM methods
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
├── __init__.py # Exports ProxmoxDriver and ProxmoxBackupDriver
├── _base.py # What both share: connection, token split, SSH session, node helpers
├── host_mixin.py # Both as Debian hosts: apt, packages, subscription, host readers' transports
├── driver.py # ProxmoxDriver (proxmox)
├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup)
├── 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
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
tests/
├── conftest.py # Shared fixtures and mock API payloads
├── test_connection.py # open / close / is_alive
@@ -168,8 +244,12 @@ tests/
├── test_environment.py # get_environment
├── test_sdn.py # get_vlans, get_network_instances
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
├── test_misc.py # NTP, SNMP, users, config, ping, traceroute, CLI, LLDP
└── test_utils.py # Unit tests for napalm_proxmox.utils
├── 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_utils.py # Unit tests for napalm_proxmox.utils
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
└── test_pbs_*.py # The backup server driver
```
## License
+3 -2
View File
@@ -1,5 +1,6 @@
"""NAPALM driver for Proxmox VE."""
"""NAPALM drivers for Proxmox VE and Proxmox Backup Server."""
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
from napalm_proxmox.driver import ProxmoxDriver
__all__ = ["ProxmoxDriver"]
__all__ = ["ProxmoxBackupDriver", "ProxmoxDriver"]
+430
View File
@@ -0,0 +1,430 @@
"""What the Proxmox VE and the Proxmox Backup Server drivers share.
Both products speak the same REST dialect (``/api2/json``, ``/nodes/{node}/...``),
authenticate the same way (``user@realm`` with a password, or an API token
``user@realm!name``) and run on Debian, where the driver opens its own SSH
session as root for what the API does not offer. They differ in the service
proxmoxer talks to, its port (PVE 8006, PBS 8007) and how the node is found.
Optional args
-------------
verify_ssl : bool
Verify TLS certificates (default: True). ``ssl_verify`` and ``verify`` are
accepted as well.
port : int
API port (default: the service's, 8006 for PVE, 8007 for PBS).
realm : str
Realm a bare username logs in to (default: ``pam``).
token_name : str
API token name (e.g. ``root@pam!netork``).
token_value : str
API token secret. With both token_name and token_value, the token is used
instead of the password.
ssh_username, ssh_password, ssh_private_key_str : str
The node's SSH login; the API login's username and password otherwise.
"""
from __future__ import annotations
import io
import logging
import re
from typing import Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types import CommandResult
from napalm_device_types.channel import run_on_transport
from napalm_device_types.ssh_host_keys import HostKeyCheck
logger = logging.getLogger(__name__)
_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.
DEFAULT_PORTS = {"PVE": 8006, "PBS": 8007}
class ProxmoxBase:
"""Connection, SSH session and node helpers of a Proxmox product's driver.
A concrete driver sets :attr:`SERVICE`, says how it finds its node
(:meth:`_resolve_node`) and constructs the proxmoxer client
(:meth:`_proxmox_api`), so its own module names the client class.
"""
#: The proxmoxer service: ``"PVE"`` or ``"PBS"``.
SERVICE = "PVE"
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: _JsonDict | None = None,
) -> None:
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.optional_args: _JsonDict = optional_args or {}
self._port: int = self.optional_args.get("port", DEFAULT_PORTS[self.SERVICE])
verify: Any = self.optional_args.get(
"verify_ssl",
self.optional_args.get("ssl_verify", self.optional_args.get("verify", True)),
)
self._verify_ssl: bool = verify
self._realm: str = self.optional_args.get("realm", "pam")
self._token_name: str | None = self.optional_args.get("token_name")
self._token_value: str | None = self.optional_args.get("token_value")
self._ssh_username: str | None = self.optional_args.get("ssh_username")
self._ssh_password: str | None = self.optional_args.get("ssh_password")
self._ssh_key: str | None = self.optional_args.get("ssh_private_key_str")
self._api: Any = None # proxmoxer.ProxmoxAPI
self._node_name: str = ""
# paramiko.SSHClient; paramiko is imported lazily (see _node_ssh).
self._ssh_client: Any = None
# ------------------------------------------------------------------ #
# Connection management
# ------------------------------------------------------------------ #
def _proxmox_api(self, **kwargs: Any) -> Any:
"""The proxmoxer client for *kwargs*; the concrete driver's module names the class."""
raise NotImplementedError
def _resolve_node(self) -> str:
"""Find the node this connection talks to and set ``_node_name``.
API errors propagate, so that ``open()`` fails with the real cause.
"""
raise NotImplementedError
def _api_kwargs(self) -> _JsonDict:
# Use the HTTPS backend for proper REST API support.
# The openssh backend tunnels all kwargs through to
# openssh_wrapper.CommandBaseSession, which does not
# accept password/verify_ssl/token params.
# Proxmox authenticates against "<user>@<realm>" and rejects a bare
# username outright. A caller who typed a realm keeps it; one who
# did not gets self._realm, which is what the documented `realm`
# optional_arg is for -- it was read in __init__ and then never
# used, so the option had no effect and a bare username failed.
user = self.username or ""
if user and "@" not in user:
user = f"{user}@{self._realm}"
kwargs: _JsonDict = {
"host": self.hostname,
"user": user,
"password": self.password,
"port": self._port,
"verify_ssl": self._verify_ssl,
"backend": "https",
"service": self.SERVICE,
}
if self._token_name and self._token_value:
kwargs.pop("password", None)
kwargs["token_value"] = self._token_value
# token_name may be in "<user>!<tokenid>" format (e.g.
# "root@pam!netork"). proxmoxer expects them split:
# user="root@pam", token_name="netork"
user_part, _, token_id = self._token_name.partition("!")
if token_id:
kwargs["user"] = user_part
kwargs["token_name"] = token_id
else:
kwargs["token_name"] = self._token_name
return kwargs
def open(self) -> None:
"""Open the connection to the Proxmox API."""
try:
self._api = self._proxmox_api(**self._api_kwargs())
# Validate the connection: finding the node needs a working login.
self._resolve_node()
except Exception as exc:
raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
def close(self) -> None:
"""Close the connection."""
self._api = None
if self._ssh_client:
try:
self._ssh_client.close()
except Exception:
logger.debug("%s: closing the SSH session: ignored", self.hostname, exc_info=True)
self._ssh_client = None
def is_alive(self) -> _JsonDict:
"""Return connection liveness.
Probes ``GET /version``, the cheapest endpoint that proves the session
still authenticates. It used to call ``_resolve_node()``, which returns
early without touching the API whenever a node was configured via
optional_args — so a dead connection reported itself alive.
"""
alive = False
if self._api:
try:
self._api.version.get()
alive = True
except Exception:
logger.debug("%s: liveness probe failed", self.hostname, exc_info=True)
return {"is_alive": alive}
# ------------------------------------------------------------------ #
# Internal API helpers
# ------------------------------------------------------------------ #
def _node_api(self) -> Any:
"""Return the API resource for the current node."""
return self._api.nodes(self._node_name)
def _get_node_network(self) -> list[_JsonDict]:
"""Return the node's network interface list from the Proxmox API."""
try:
return self._node_api().network.get() or []
except Exception as exc:
logger.debug("Failed to fetch node network: %s", exc)
return []
def _exec_ssh_command(self, command: str) -> str:
"""Run *command* in the node's shell over SSH and return what it printed.
Stdout only: stderr is not output (a command that wants it says
``2>&1``). The exit status is not checked; a caller that needs it asks
for it (``_rc``). The node has no API endpoint that runs a shell command
(``/nodes/{node}/execute`` runs a batch of API calls), so this is the
one way, the same session ``_run_node_command`` uses (see
NAPALM/napalm-device-types#35 for the shared transport).
:raises ConnectionException: when the command could not run: no SSH
credential, a refused login or host key (``SshHostKeyMismatch``),
an unreachable node, a timeout.
"""
try:
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=self.timeout)
out: str = stdout.read().decode(errors="replace")
err: str = stderr.read().decode(errors="replace").strip()
except ConnectionException:
raise
except _ssh_errors() as exc:
raise ConnectionException(
f"Cannot run a command on {self.hostname} over SSH: {exc}"
) from exc
if err:
logger.debug("%s: stderr of a node command: %s", self.hostname, err[-300:])
return out.strip()
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult:
"""Run *command* on an exec channel of the node's SSH session (``CommandChannelMixin``).
stdout, stderr and the exit status come back apart; *stdin*, if given, is
written and then closed. *privileged* needs nothing more: the node is
logged in as root, as for every other command this driver runs there.
:raises ConnectionException: when the command could not run, or did not
finish within *timeout* seconds.
"""
try:
transport = self._node_ssh().get_transport()
return run_on_transport(transport, command, stdin=stdin, timeout=timeout)
except ConnectionException:
raise
except _ssh_errors() as exc:
raise ConnectionException(
f"Cannot run a command on {self.hostname} over SSH: {exc}"
) from exc
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
"""The SSH session to the node on port 22, opened once.
Its host key is the one the caller expects for port 22, or on first use
whichever the node presents; either way it is reported (netork#1167).
:raises ConnectionException: without a password or a usable key.
"""
import paramiko
if self._ssh_client is None:
# A key is tried first; paramiko falls back to the password. Only
# these: not the keys in the process's own ~/.ssh, nor an agent.
connect_kwargs: _JsonDict = {
"username": self._ssh_username or self.username,
"timeout": self.timeout,
"look_for_keys": False,
"allow_agent": False,
}
password = self._ssh_password or self.password
if password:
connect_kwargs["password"] = password
pkey = _load_private_key(self._ssh_key) if self._ssh_key else None
if pkey is not None:
connect_kwargs["pkey"] = pkey
if not password and pkey is None:
# An API-token-only node: nothing to log in with, so no connection.
raise ConnectionException(
f"no SSH credential for {self.hostname}: set ssh_password or "
"ssh_private_key_str"
)
client = paramiko.SSHClient()
try:
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
client, **connect_kwargs
)
except Exception:
client.close()
raise
self._ssh_client = client
return self._ssh_client
# ------------------------------------------------------------------ #
# Node info helpers
# ------------------------------------------------------------------ #
def _get_version_info(self) -> _JsonDict:
"""Return the product's version info from the API."""
try:
return self._api.version.get() or {}
except Exception as exc:
logger.debug("Failed to fetch version info: %s", exc)
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:
"""Return the node's status from the Proxmox API."""
try:
return self._node_api().status.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node status: %s", exc)
return {}
def _get_node_subscription(self) -> _JsonDict:
"""Return subscription status for this node."""
try:
return self._node_api().subscription.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node subscription: %s", exc)
return {}
def _get_node_dns(self) -> _JsonDict:
"""Return DNS configuration for this node."""
try:
return self._node_api().dns.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node DNS: %s", exc)
return {}
def _get_node_time(self) -> _JsonDict:
"""Return time configuration for this node."""
try:
return self._node_api().time.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node time: %s", exc)
return {}
def _hardware(self) -> tuple[str, str, str]:
"""The physical machine's vendor, model and serial number, from the Linux DMI
sysfs entries over SSH; empty strings where they cannot be read."""
# Physical hardware info from Linux DMI sysfs.
# Read each field separately to avoid shell quoting issues with printf.
# Field priority for model:
# product_name — human-readable name on most vendors (e.g. "NUC6CAYH",
# "ThinkCentre M910x")
# product_version — sometimes the marketing name on Lenovo; on Intel NUC
# it is the board part number (less useful as model name)
# We prefer product_name; fall back to product_version only when
# product_name looks like a raw type code (all uppercase + digits, no spaces).
vendor = ""
model = ""
serial = ""
try:
dmi_cmd = (
"v=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null); "
"n=$(cat /sys/class/dmi/id/product_name 2>/dev/null); "
"r=$(cat /sys/class/dmi/id/product_version 2>/dev/null); "
"s=$(cat /sys/class/dmi/id/product_serial 2>/dev/null); "
'printf \'%s\\n%s\\n%s\\n%s\\n\' "$v" "$n" "$r" "$s"'
)
lines = self._exec_ssh_command(dmi_cmd).splitlines()
if len(lines) >= 4:
vendor = lines[0].strip()
product_name = lines[1].strip()
product_version = lines[2].strip()
serial = lines[3].strip()
_bad = {"none", "n/a", "not specified", "to be filled by o.e.m."}
pv_usable = (
product_version
and product_version.lower() not in _bad
and product_version != product_name
# Only prefer product_version when it contains a space —
# that indicates a human-readable marketing name like
# "ThinkCentre M910x" rather than a part code like "J26843-409".
and " " in product_version
)
model = product_version if pv_usable else product_name
except Exception as exc:
logger.debug("Failed to read DMI info via SSH: %s", exc)
return vendor, model, serial
# ------------------------------------------------------------------ #
# CLI passthrough
# ------------------------------------------------------------------ #
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
"""Execute a list of shell commands and return their outputs."""
return {cmd: self._exec_ssh_command(cmd) for cmd in commands}
def _load_private_key(text: str) -> Any: # paramiko.PKey; paramiko is imported lazily
"""The SSH private key in *text*, whatever its type, or None when it cannot be read."""
import paramiko
for key_class in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
try:
return key_class.from_private_key(io.StringIO(text))
except (paramiko.SSHException, ValueError):
continue
logger.warning("The SSH private key could not be read; logging in with the password")
return None
def _ssh_errors() -> tuple[type[Exception], ...]:
"""What a command that could not run raises: the socket's errors, timeouts
included, and paramiko's (a refused login, a closed session)."""
import paramiko
return (OSError, paramiko.SSHException)
+117
View File
@@ -0,0 +1,117 @@
"""NAPALM driver for Proxmox Backup Server (entry point ``proxmox_backup``).
A PBS is a Debian host with one node, always ``localhost`` in its API, and no
cluster. Its API and web UI listen on **8007**, not on PVE's 8006. The
connection, the SSH session and the node helpers are the ones the PVE driver
uses (``napalm_proxmox._base``).
Roles: a backup server first (datastores, backup groups, jobs, remotes), and
storage second for the disks and ZFS pools it manages itself.
"""
from __future__ import annotations
import logging
from typing import Any
from napalm_device_types import (
AptProxyMixin,
BackupServerDriver,
EnsurePackageMixin,
FingerprintRule,
HostStatusMixin,
KernelFactsMixin,
LicenseMixin,
ListeningSocketsMixin,
LogSourcesMixin,
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
StorageDriver,
SystemdServicesMixin,
SystemIdentityMixin,
)
try:
from proxmoxer import ProxmoxAPI
except ImportError as exc: # pragma: no cover - proxmoxer is a dependency
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
#: The node name the PBS API answers to; a PBS has exactly one.
PBS_NODE = "localhost"
class ProxmoxBackupDriver(
ProxmoxBase,
ProxmoxBackupServerMixin,
PbsRunningBackupsMixin,
ProxmoxPbsHostMixin,
ProxmoxHostMixin,
ProxmoxTimeSyncMixin,
BackupServerDriver,
StorageDriver,
KernelFactsMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
LogSourcesMixin,
SystemIdentityMixin,
SystemdServicesMixin,
ProxmoxScheduledJobsMixin,
HostStatusMixin,
LicenseMixin,
ProxmoxZabbixAgentMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
):
"""NAPALM driver for Proxmox Backup Server."""
SERVICE = "PBS"
VENDOR = "Proxmox"
DRIVER_NAME = "proxmox_backup"
# netOrk reaches the server through the REST API and does not log in over
# SSH itself; the driver's own SSH session (_node_ssh) runs the shell.
USES_SSH = False
#: A PBS upgrades like a PVE node: a plain ``apt-get upgrade`` holds back
#: what needs new or removed packages.
FULL_UPGRADE = True
#: The backup server's own timer is ``platform``.
PLATFORM_SOURCES = PBS_PLATFORM_SOURCES
PORT_SPECS = [
PortSpec("https", 8007, weight=8.0),
]
SSH_FINGERPRINT = [
FingerprintRule("debian", weight=3.0),
]
HTTP_FINGERPRINT = [
FingerprintRule("proxmox backup server", weight=9.0, mandatory=True),
FingerprintRule("proxmox", weight=5.0),
FingerprintRule("pbs", weight=2.0),
]
platform = "proxmox_backup"
PACKAGE_SOURCE = "pbs"
SUBSCRIPTION_LICENSE = "pbs-subscription"
def _proxmox_api(self, **kwargs: Any) -> Any:
return ProxmoxAPI(**kwargs)
def _resolve_node(self) -> str:
"""The node is always ``localhost``; ``GET /version`` proves the login.
proxmoxer logs in lazily with a token, so without a request here a bad
token would only fail at the first getter.
"""
self._api.version.get()
self._node_name = PBS_NODE
return self._node_name
+151
View File
@@ -0,0 +1,151 @@
"""get_clusters() for Proxmox VE: the backup jobs, and the backups on the storages.
Read from:
- ``GET /cluster/backup``: each vzdump job. ``enabled`` absent means enabled;
old jobs carry ``starttime``/``dow`` instead of ``schedule``, which PVE itself
turns into ``"<dow> <starttime>"`` (``PVE/API2/Backup.pm``). ``storage`` and
``mode`` are None where the job does not set them: a node's
``/etc/vzdump.conf`` then decides.
- a pool job's guests: ``GET /pools?poolid=<pool>`` (PVE 8.1 and later), else
``GET /pools/<pool>``, which older releases have;
- ``GET /nodes/<node>/storage/<storage>/content?content=backup`` for each storage
that holds backups (PBS answers the same): a shared one once, on the own node
if it sees it, else on the next node that does; a local one on every node
that has it.
Each list is best-effort: when part of it cannot be read it is None, because
half a list would say a guest has no backup, or a job no guest, when it may.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm_proxmox.pve_values import split_list, to_flag, to_int, vmid_list
if TYPE_CHECKING:
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
from napalm_device_types import BackupDict, BackupJobDict, ClusterStorageDict
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
_ALL_DAYS = "mon,tue,wed,thu,fri,sat,sun"
_GUEST_TYPES = ("qemu", "lxc")
def _schedule(job: _JsonDict) -> str | None:
if job.get("schedule"):
return str(job["schedule"])
start = job.get("starttime")
if not start:
return None
dow = ",".join(split_list(job.get("dow")))
return str(start) if dow in ("", _ALL_DAYS) else f"{dow} {start}"
def _pool_info(api: Any, pool: str) -> _JsonDict:
try:
for entry in api.pools.get(poolid=pool) or []:
if entry.get("poolid") == pool:
return dict(entry)
except Exception as exc:
logger.debug("GET /pools?poolid=%s failed, trying /pools/%s: %s", pool, pool, exc)
return dict(api.pools(pool).get() or {})
def _pool_members(api: Any, pool: str) -> list[int]:
members = _pool_info(api, pool).get("members") or []
return [
int(m["vmid"])
for m in members
if m.get("type") in _GUEST_TYPES and m.get("vmid") is not None
]
def _job(api: Any, job: _JsonDict) -> BackupJobDict:
pool = job.get("pool") or None
return {
"id": str(job.get("id") or ""),
"enabled": to_flag(job.get("enabled", 1)),
"schedule": _schedule(job),
"storage": job.get("storage") or None,
"mode": job.get("mode") or None,
"all": to_flag(job.get("all")),
"vmids": _pool_members(api, str(pool)) if pool else vmid_list(job.get("vmid")),
"exclude": vmid_list(job.get("exclude")),
"pool": pool,
"node": job.get("node") or None,
}
def read_backup_jobs(api: Any) -> list[BackupJobDict] | None:
"""The cluster's backup jobs; None when they, or a pool's guests, cannot be read."""
try:
return [_job(api, job) for job in api.cluster.backup.get() or []]
except Exception as exc:
logger.debug("Cannot read the backup jobs: %s", exc)
return None
def _content(api: Any, node: str, storage: str) -> list[_JsonDict]:
return list(api.nodes(node).storage(storage).content.get(content="backup") or [])
def _first_answer(api: Any, storage: str, nodes: list[str]) -> list[_JsonDict]:
error: Exception | None = None
for node in nodes:
try:
return _content(api, node, storage)
except Exception as exc:
logger.debug("Cannot read backups on %s from %s: %s", storage, node, exc)
error = exc
if error is not None:
raise error
return []
def _storage_rows(api: Any, storage: ClusterStorageDict, local_node: str) -> list[_JsonDict]:
nodes = storage["nodes"]
if storage["shared"]:
return _first_answer(api, storage["name"], sorted(nodes, key=lambda n: n != local_node))
return [row for node in nodes for row in _content(api, node, storage["name"])]
def _merge(rows: list[_JsonDict], storage: str, merged: dict[tuple[int, str], BackupDict]) -> None:
for row in rows:
if row.get("vmid") is None or row.get("ctime") is None:
continue # not a vzdump/PBS backup of a guest
key, ctime = (int(row["vmid"]), storage), int(row["ctime"])
entry = merged.get(key)
if entry is None:
merged[key] = {
"vmid": key[0],
"storage": storage,
"time": ctime,
"size": to_int(row.get("size")),
"count": 1,
}
continue
entry["count"] += 1
if ctime > entry["time"]:
entry["time"], entry["size"] = ctime, to_int(row.get("size"))
def read_backups(
api: Any, storages: list[ClusterStorageDict], local_node: str
) -> list[BackupDict] | None:
"""One entry per guest and storage with its newest backup; None if a storage
that holds backups cannot be read."""
merged: dict[tuple[int, str], BackupDict] = {}
try:
for storage in storages:
if "backup" in storage["content"]:
_merge(_storage_rows(api, storage, local_node), storage["name"], merged)
except Exception as exc:
logger.debug("Cannot read the backups: %s", exc)
return None
return [merged[key] for key in sorted(merged, key=lambda k: (k[1], k[0]))]
+105
View File
@@ -0,0 +1,105 @@
"""get_clusters() for Proxmox VE: quorum votes and the guests the HA manager keeps.
Read from:
- ``GET /cluster/config/nodes``: corosync's nodelist, ``quorum_votes`` per node;
- ``GET /cluster/ha/resources``: each HA resource's ``sid`` (``vm:100``,
``ct:101``), requested ``state`` and, on PVE 8, ``group``;
- ``GET /cluster/ha/status/current``: per ``service`` entry the ``node`` and the
CRM's ``crm_state`` (only the verbose ``state`` while the CRM has not taken it
up yet);
- ``GET /cluster/ha/rules`` (PVE 9): each rule's ``rule`` id and its
``resources``, a comma-separated list of sids. PVE 8 has no such endpoint.
Each read is best-effort: what cannot be read is None, never a guess.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm_proxmox.pve_values import split_list
if TYPE_CHECKING:
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
from napalm_device_types import HAResourceDict
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: HA resource type prefix -> guest kind.
_KINDS = {"vm": "qemu", "ct": "lxc"}
#: corosync counts a node without ``quorum_votes`` as one vote.
_DEFAULT_VOTES = 1
#: What HA keeps a resource at when its config names no state.
_DEFAULT_REQUESTED = "started"
def read_votes(api: Any) -> dict[str, int] | None:
"""Quorum votes per node name; None when the nodelist cannot be read."""
try:
rows = api.cluster.config.nodes.get() or []
except Exception as exc:
logger.debug("Cannot read the corosync nodelist: %s", exc)
return None
return {
str(row.get("node") or row.get("name")): int(row.get("quorum_votes", _DEFAULT_VOTES))
for row in rows
if row.get("node") or row.get("name")
}
def _services(api: Any) -> dict[str, _JsonDict] | None:
try:
rows = api.cluster.ha.status.current.get() or []
except Exception as exc:
logger.debug("Cannot read the HA status: %s", exc)
return None
return {str(r["sid"]): r for r in rows if r.get("type") == "service" and r.get("sid")}
def _rules(api: Any) -> dict[str, list[str]]:
"""Rule ids per sid. PVE 8 answers with an error: no rules there."""
try:
rows = api.cluster.ha.rules.get() or []
except Exception as exc:
logger.debug("No HA rules (PVE 8 has none): %s", exc)
return {}
by_sid: dict[str, list[str]] = {}
for rule in rows:
for sid in split_list(rule.get("resources")):
by_sid.setdefault(sid, []).append(str(rule.get("rule")))
return by_sid
def _resource(
row: _JsonDict, services: dict[str, _JsonDict] | None, rules: dict[str, list[str]]
) -> HAResourceDict | None:
sid = str(row.get("sid") or "")
prefix, _, vmid = sid.partition(":")
if prefix not in _KINDS or not vmid.isdigit():
return None
service = (services or {}).get(sid, {})
return {
"vmid": int(vmid),
"kind": _KINDS[prefix],
"requested": str(row.get("state") or _DEFAULT_REQUESTED),
"status": service.get("crm_state") or service.get("state") or None,
"node": service.get("node") or None,
"group": row.get("group") or None,
"rules": rules.get(sid, []),
}
def read_ha_resources(api: Any) -> list[HAResourceDict] | None:
"""Every guest HA manages, by vmid; None when the HA resources cannot be read."""
try:
rows = api.cluster.ha.resources.get() or []
except Exception as exc:
logger.debug("Cannot read the HA resources: %s", exc)
return None
services, rules = _services(api), _rules(api)
resources = [_resource(row, services, rules) for row in rows]
return sorted((r for r in resources if r is not None), key=lambda r: r["vmid"])
+309
View File
@@ -0,0 +1,309 @@
"""HypervisorDriver.get_clusters() for Proxmox VE: the cluster this node belongs to.
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
cluster of one, without a name). Read from:
- ``GET /cluster/status``: the cluster's name, quorum and (PVE 9.3) ``cluster-id``,
and every member with ``online`` and ``local``;
- ``GET /cluster/resources``: per node ``maxcpu``, ``cpu``, ``maxmem``, ``mem``;
per node and storage one row with ``plugintype``, ``shared``, ``content``,
``maxdisk``, ``disk`` and ``status``;
- ``GET /nodes/{node}/status`` of each online node: ``cpuinfo``;
- ``GET /nodes/{node}/network`` of each online node: its bridges;
- ``GET /cluster/sdn/vnets`` and ``/cluster/sdn/zones``: the vnets, on the nodes
of their zone;
- ``GET /cluster/ha/status/manager_status``: which node is in maintenance;
- quorum votes and HA resources: see ``cluster_ha``; backup jobs and backups:
see ``cluster_backups``. Each of those is best-effort and None when it cannot
be read, without failing the rest of the report.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, NamedTuple
from napalm_proxmox.cluster_backups import read_backup_jobs, read_backups
from napalm_proxmox.cluster_ha import read_ha_resources, read_votes
from napalm_proxmox.network_targets import bridge_targets, vnet_target
from napalm_proxmox.pve_values import split_list as _list
from napalm_proxmox.pve_values import to_flag as _flag
from napalm_proxmox.pve_values import to_int as _int
from napalm_proxmox.utils import cpu_flags
if TYPE_CHECKING:
# Type-only: the cluster models are newer than the napalm_device_types floor
# in pyproject.toml, and nothing here needs them at runtime.
from napalm_device_types import (
BackupServerRefDict,
ClusterDict,
ClusterNetworkDict,
ClusterNodeDict,
ClusterStorageDict,
)
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
class _Member(NamedTuple):
name: str
online: bool
local: bool
class _Cpu(NamedTuple):
cores: int | None = None
model: str | None = None
flags: list[str] | None = None
def _float(value: Any) -> float | None:
return None if value is None else float(value)
def _size(rows: list[_JsonDict], key: str, shared: bool) -> int | None:
"""One storage's size over the nodes in *rows*: summed unless it is shared."""
values = [row.get(key) for row in rows]
if not values or any(value is None for value in values):
return None
sizes = [int(value) for value in values if value is not None]
return sizes[0] if shared else sum(sizes)
def _storage(name: str, rows: list[_JsonDict]) -> ClusterStorageDict:
shared = any(_flag(row.get("shared")) for row in rows)
available = [row for row in rows if row.get("status") == "available"]
return {
"name": name,
"type": str(rows[0].get("plugintype") or ""),
"shared": shared,
"content": _list(rows[0].get("content")),
"nodes": [str(row.get("node")) for row in available],
"total": _size(available, "maxdisk", shared),
"used": _size(available, "disk", shared),
}
def _storages(resources: list[_JsonDict]) -> list[ClusterStorageDict]:
groups: dict[str, list[_JsonDict]] = {}
for row in resources:
if row.get("type") == "storage" and row.get("storage"):
groups.setdefault(str(row["storage"]), []).append(row)
return [_storage(name, rows) for name, rows in groups.items()]
def _backup_server_ref(config: _JsonDict) -> BackupServerRefDict:
"""Which server and datastore a ``pbs`` storage writes to (``/storage``); never
its password or encryption key."""
port = config.get("port")
return {
"server": str(config.get("server") or ""),
"port": int(port) if port else None,
"datastore": str(config.get("datastore") or ""),
"namespace": config.get("namespace") or None,
"fingerprint": config.get("fingerprint") or None,
}
def _name_backup_servers(storages: list[ClusterStorageDict], api: Any) -> None:
"""Give each ``pbs`` storage in *storages* its ``backup_server`` (#55); None for
all of them when ``/storage`` cannot be read."""
pbs = [s for s in storages if s["type"] == "pbs"]
if not pbs:
return
try:
configs = {str(c.get("storage")): c for c in api.storage.get() or []}
except Exception:
logger.debug("/storage could not be read; the backup servers stay unnamed", exc_info=True)
configs = None
for storage in pbs:
config = configs.get(storage["name"]) if configs is not None 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]:
merged: dict[str, ClusterNetworkDict] = {}
for node, network in per_node:
for target in bridge_targets(network):
entry = merged.setdefault(
target["name"],
{"name": target["name"], "kind": "bridge", "vlan_aware": True, "nodes": []},
)
entry["vlan_aware"] = entry["vlan_aware"] and target["vlan_aware"]
entry["nodes"].append(node)
return list(merged.values())
class ProxmoxClusterMixin:
"""Relies on ``_api``/``_node_name`` from the driver and the SDN readers."""
_api: Any
_node_name: str
_get_sdn_vnets: Any
_get_sdn_zones: Any
def get_clusters(self) -> list[ClusterDict]:
"""
Return the one cluster this node belongs to, its nodes, storages and networks.
- ``id`` is the ``cluster-id`` of PVE 9.3, a random identifier the cluster
keeps when it is renamed; a standalone node reports its own on its node
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
no capacity values: its own API cannot be asked. ``local`` marks the
node ``/cluster/status`` calls local, or else the node this driver
talks to. ``maintenance`` comes from the HA manager; when that cannot
be read (no HA stack, no permission) or does not track a node, it is
None. If another node's status cannot be read although the cluster
calls it online, its CPU fields are None and its bridges are not
listed; the own node's must be readable.
- A storage is one entry per name, with the nodes it is ``available``
on. ``total``/``used``: a shared storage is the same space on every
node, so it is one node's figure; a local storage of that name is a
separate disk on each node, so the figures of its nodes add up — the
room any single node has is less. None when no node reports it.
- Networks: each bridge once, with every online node that has one of
that name; ``vlan_aware`` only if it is on all of them. A vnet is on
the nodes of its zone, all members when the zone names none.
Raises:
Whatever the API raises for ``/cluster/status``, ``/cluster/resources``
or the own node: a getter that cannot read does not report less.
"""
status = self._api.cluster.status.get() or []
resources = self._api.cluster.resources.get() or []
head = next((s for s in status if s.get("type") == "cluster"), None)
members = self._members(status if head else [])
storages = _storages(resources)
_name_backup_servers(storages, self._api)
return [
{
"id": _cluster_id(head, status),
"name": (head.get("name") or None) if head else None,
"quorate": _flag(head.get("quorate")) if head else None,
"nodes": self._cluster_nodes(members, resources),
"storages": storages,
"networks": self._networks(members),
"ha_resources": read_ha_resources(self._api),
"backup_jobs": read_backup_jobs(self._api),
"backups": read_backups(self._api, storages, self._node_name),
}
]
def _cluster_nodes(
self, members: list[_Member], resources: list[_JsonDict]
) -> list[ClusterNodeDict]:
rows = {r.get("node"): r for r in resources if r.get("type") == "node"}
maintenance, votes = self._maintenance(), read_votes(self._api)
return [self._cluster_node(m, rows.get(m.name, {}), maintenance, votes) for m in members]
def _networks(self, members: list[_Member]) -> list[ClusterNetworkDict]:
online = [m for m in members if m.online]
return [
*_merge_bridges([(m.name, self._node_network(m)) for m in online]),
*self._vnets([m.name for m in members]),
]
def _members(self, status: list[_JsonDict]) -> list[_Member]:
entries = [s for s in status if s.get("type") == "node" and s.get("name")]
if not entries:
return [_Member(self._node_name, online=True, local=True)]
any_local = any(_flag(s.get("local")) for s in entries)
return [
_Member(
str(s["name"]),
online=_flag(s.get("online")),
local=_flag(s.get("local")) if any_local else s["name"] == self._node_name,
)
for s in entries
]
def _maintenance(self) -> dict[str, bool] | None:
try:
status = self._api.cluster.ha.status.manager_status.get() or {}
except Exception as exc:
logger.debug("Cannot read the HA manager status: %s", exc)
return None
node_status = (status.get("manager_status") or {}).get("node_status") or {}
return {str(node): state == "maintenance" for node, state in node_status.items()}
def _read_node(self, member: _Member, path: str) -> Any:
"""``GET /nodes/{node}/{path}``; None for another node that does not answer."""
try:
return getattr(self._api.nodes(member.name), path).get()
except Exception as exc:
if member.local:
raise
logger.warning("Cannot read %s of cluster node %s: %s", path, member.name, exc)
return None
def _node_network(self, member: _Member) -> list[_JsonDict]:
return self._read_node(member, "network") or []
def _cpu(self, member: _Member) -> _Cpu:
status = self._read_node(member, "status")
if status is None:
return _Cpu()
info = status.get("cpuinfo") or {}
cores, sockets = info.get("cores"), info.get("sockets")
return _Cpu(
cores=int(cores) * int(sockets) if cores and sockets else None,
model=info.get("model") or None,
flags=cpu_flags(status),
)
def _cluster_node(
self,
member: _Member,
row: _JsonDict,
maintenance: dict[str, bool] | None,
votes: dict[str, int] | None,
) -> ClusterNodeDict:
if not member.online:
row, cpu = {}, _Cpu()
else:
cpu = self._cpu(member)
return {
"name": member.name,
"status": "online" if member.online else "offline",
"local": member.local,
"maintenance": None if maintenance is None else maintenance.get(member.name),
"cpu_threads": _int(row.get("maxcpu")),
"cpu_cores": cpu.cores,
"cpu_model": cpu.model,
"cpu_flags": cpu.flags,
"cpu_usage": _float(row.get("cpu")),
"memory_total": _int(row.get("maxmem")),
"memory_used": _int(row.get("mem")),
"votes": None if votes is None else votes.get(member.name),
}
def _vnets(self, members: list[str]) -> list[ClusterNetworkDict]:
vnets = self._get_sdn_vnets()
zones = {z.get("zone"): z for z in self._get_sdn_zones()} if vnets else {}
networks: list[ClusterNetworkDict] = []
for vnet in vnets:
target, zone = vnet_target(vnet), zones.get(vnet.get("zone"))
if target is None or zone is None:
continue
only = set(_list(zone.get("nodes")))
networks.append(
{
"name": target["name"],
"kind": "vnet",
"vlan_aware": False,
"fixed_vlan_tag": target.get("fixed_vlan_tag"),
"nodes": [n for n in members if not only or n in only],
}
)
return networks
+3 -3
View File
@@ -114,12 +114,12 @@ class ProxmoxConfigMixin:
.. note::
Full programmatic apply requires the Proxmox API to accept raw
interface configs. This implementation uses ``pvesh`` via exec
which requires the node exec endpoint to be available.
interface configs. This implementation uses ``pvesh`` over the
node's SSH session.
"""
if not self._candidate_config:
return
# Write via exec endpoint
# Write over the node's SSH session
escaped = self._candidate_config.replace("'", "'\\''")
self._exec_ssh_command(
f"printf '%s' '{escaped}' > /etc/network/interfaces && "
+73
View File
@@ -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"))
+37 -293
View File
@@ -12,19 +12,11 @@ NAPALM API allows it.
Optional args
-------------
verify_ssl : bool
Verify TLS certificates (default: True).
port : int
Proxmox API port (default: 8006).
The connection's are the shared base's (``napalm_proxmox._base``; the API port
defaults to 8006 here). In addition:
node : str
Override the target node name (default: auto-detected from hostname).
realm : str
PAM realm (default: ``pam``).
token_name : str
API token name (e.g. ``napalm@pam!mytoken``).
token_value : str
API token secret. When both token_name and token_value are provided,
token-based auth is used instead of password auth.
"""
from __future__ import annotations
@@ -42,29 +34,40 @@ from napalm_device_types import (
KernelFactsMixin,
LicenseMixin,
ListeningSocketsMixin,
LogSourcesMixin,
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
SnmpAgentMixin,
SystemdServicesMixin,
SystemIdentityMixin,
)
from napalm_device_types.ssh_host_keys import HostKeyCheck, SshHostKeyMismatch
try:
from proxmoxer import ProxmoxAPI
except ImportError as exc:
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
from napalm_proxmox.running_backups import ProxmoxRunningBackupsMixin
from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
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_migrate_mixin import ProxmoxVMMigrateMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
@@ -79,6 +82,7 @@ _JsonDict = dict[str, Any]
class ProxmoxDriver(
ProxmoxBase,
ProxmoxInterfaceMixin,
ProxmoxSDNMixin,
ProxmoxLLDPMixin,
@@ -87,25 +91,37 @@ class ProxmoxDriver(
ProxmoxVMContractMixin,
ProxmoxVMSnapshotMixin,
ProxmoxVMProvisionMixin,
ProxmoxClusterMixin,
ProxmoxVMMigrateMixin,
ProxmoxRoutingMixin,
ProxmoxSystemMixin,
ProxmoxHostMixin,
KernelFactsMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
LogSourcesMixin,
SystemIdentityMixin,
SystemdServicesMixin,
ProxmoxScheduledJobsMixin,
ProxmoxRunningBackupsMixin,
ProxmoxTimeSyncMixin,
ProxmoxCredentialExpiryMixin,
ProxmoxUpdateHistoryMixin,
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
ProxmoxZabbixAgentMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
HypervisorDriver,
):
"""NAPALM driver for Proxmox VE nodes."""
VENDOR = "Proxmox"
DRIVER_NAME = "proxmox"
# Everything runs over the Proxmox REST API; there is no SSH session.
# netOrk reaches the node through the REST API and does not log in over SSH
# itself; the driver's own SSH session (_node_ssh) runs the node's shell.
USES_SSH = False
# A PVE node reboots through a full init sequence plus storage checks.
REBOOT_SETTLE_SECONDS = 90
@@ -113,6 +129,10 @@ class ProxmoxDriver(
#: ``apt-get upgrade`` holds back what needs new or removed packages and can
#: leave the node half updated. netOrk reads this when it upgrades the host.
FULL_UPGRADE = True
#: Proxmox VE's own timers and cron file are ``platform``.
PLATFORM_SOURCES = PVE_PLATFORM_SOURCES
#: ``/etc/cron.d/vzdump`` links into ``/etc/pve`` (pmxcfs); its lines are only run.
RUN_ONLY_SOURCES = ("/etc/cron.d/vzdump",)
PORT_SPECS = [
PortSpec("https", 8006, weight=8.0),
]
@@ -134,31 +154,9 @@ class ProxmoxDriver(
timeout: int = 60,
optional_args: _JsonDict | None = None,
) -> None:
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.optional_args: _JsonDict = optional_args or {}
self._port: int = self.optional_args.get("port", 8006)
self._verify_ssl: bool = self.optional_args.get(
"verify_ssl",
self.optional_args.get("ssl_verify", self.optional_args.get("verify", True)),
)
self._realm: str = self.optional_args.get("realm", "pam")
self._token_name: str | None = self.optional_args.get("token_name")
self._token_value: str | None = self.optional_args.get("token_value")
super().__init__(hostname, username, password, timeout, optional_args)
self._node: str | None = self.optional_args.get("node")
self._ssh_username: str | None = self.optional_args.get("ssh_username")
self._ssh_password: str | None = self.optional_args.get("ssh_password")
self._ssh_key: str | None = self.optional_args.get("ssh_private_key_str")
self._api: ProxmoxAPI | None = None
self._node_name: str = ""
# paramiko.SSHClient; paramiko is imported lazily (see _node_ssh).
self._ssh_client: Any = None
# Candidate config (merge/replace)
self._candidate_config: str = ""
self._running_config: str = ""
@@ -167,51 +165,8 @@ class ProxmoxDriver(
# Connection management
# ------------------------------------------------------------------ #
def open(self) -> None:
"""Open the connection to the Proxmox API."""
try:
# Use the HTTPS backend for proper REST API support.
# The openssh backend tunnels all kwargs through to
# openssh_wrapper.CommandBaseSession, which does not
# accept password/verify_ssl/token params.
# Proxmox authenticates against "<user>@<realm>" and rejects a bare
# username outright. A caller who typed a realm keeps it; one who
# did not gets self._realm, which is what the documented `realm`
# optional_arg is for -- it was read in __init__ and then never
# used, so the option had no effect and a bare username failed.
user = self.username or ""
if user and "@" not in user:
user = f"{user}@{self._realm}"
kwargs: _JsonDict = {
"host": self.hostname,
"user": user,
"password": self.password,
"port": self._port,
"verify_ssl": self._verify_ssl,
"backend": "https",
}
if self._token_name and self._token_value:
kwargs.pop("password", None)
kwargs["token_value"] = self._token_value
# token_name may be in "<user>!<tokenid>" format (e.g.
# "root@pam!netork"). proxmoxer expects them split:
# user="root@pam", token_name="netork"
user_part, _, token_id = self._token_name.partition("!")
if token_id:
kwargs["user"] = user_part
kwargs["token_name"] = token_id
else:
kwargs["token_name"] = self._token_name
self._api = ProxmoxAPI(**kwargs)
# Validate connection by fetching node status
self._resolve_node()
except Exception as exc:
raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
def _proxmox_api(self, **kwargs: Any) -> Any:
return ProxmoxAPI(**kwargs)
def _resolve_node(self) -> str:
"""Resolve the PVE node this connection talks to.
@@ -251,170 +206,6 @@ class ProxmoxDriver(
f"set the 'node' driver argument"
)
def close(self) -> None:
"""Close the connection."""
self._api = None
if self._ssh_client:
try:
self._ssh_client.close()
except Exception:
logger.debug("%s: closing the SSH session: ignored", self.hostname, exc_info=True)
self._ssh_client = None
def is_alive(self) -> _JsonDict:
"""Return connection liveness.
Probes ``GET /version``, the cheapest endpoint that proves the session
still authenticates. It used to call ``_resolve_node()``, which returns
early without touching the API whenever a node was configured via
optional_args — so a dead connection reported itself alive.
"""
alive = False
if self._api:
try:
self._api.version.get()
alive = True
except Exception:
logger.debug("%s: liveness probe failed", self.hostname, exc_info=True)
return {"is_alive": alive}
# ------------------------------------------------------------------ #
# Internal API helpers
# ------------------------------------------------------------------ #
def _node_api(self):
"""Return the API resource for the current node."""
return self._api.nodes(self._node_name)
def _get_node_network(self) -> list[_JsonDict]:
"""Return the node's network interface list from the Proxmox API."""
try:
return self._node_api().network.get() or []
except Exception as exc:
logger.debug("Failed to fetch node network: %s", exc)
return []
def _exec_ssh_command(self, command: str) -> str:
"""Execute a shell command on the Proxmox node and return output.
Tries the Proxmox API exec endpoint first. If that fails,
falls back to a direct paramiko SSH connection.
"""
import base64 as _b64
# Try API exec endpoint
try:
encoded = _b64.b64encode(command.encode()).decode()
result = self._node_api().execute.post("command", f"echo {encoded} | base64 -d | sh")
# On PVE 8.x the exec endpoint returns a dict with 'data' key
if isinstance(result, dict):
raw = result.get("data", result.get("output", ""))
else:
raw = result
if raw:
return str(raw).strip()
except Exception as exc:
logger.debug("API exec failed, falling back to SSH: %s", exc)
# Fallback: direct paramiko SSH
try:
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=self.timeout)
err = stderr.read().decode().strip()
out = stdout.read().decode().strip()
return out or err
except ImportError:
logger.warning("paramiko not installed — cannot exec SSH commands")
except SshHostKeyMismatch as exc:
# Refused before any login, and already reported to the caller's store.
logger.warning("%s", exc)
except Exception as exc:
logger.debug("SSH exec command failed: %s", exc)
return ""
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
"""The SSH session to the node on port 22, opened once.
Its host key is the one the caller expects for port 22, or on first use
whichever the node presents; either way it is reported (netork#1167).
"""
import paramiko
if self._ssh_client is None:
ssh_pass = self._ssh_password or self.password
connect_kwargs: _JsonDict = {
"username": self._ssh_username or self.username,
"timeout": self.timeout,
}
if self._ssh_key and not ssh_pass:
from io import StringIO as _StringIO
connect_kwargs["pkey"] = paramiko.RSAKey.from_private_key(_StringIO(self._ssh_key))
else:
connect_kwargs["password"] = ssh_pass
client = paramiko.SSHClient()
try:
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
client, **connect_kwargs
)
except Exception:
client.close()
raise
self._ssh_client = client
return self._ssh_client
# ------------------------------------------------------------------ #
# Node info helpers
# ------------------------------------------------------------------ #
def _get_version_info(self) -> _JsonDict:
"""Return Proxmox VE version info from the API."""
try:
return self._api.version.get() or {}
except Exception as exc:
logger.debug("Failed to fetch version info: %s", exc)
return {}
def _get_node_status(self) -> _JsonDict:
"""Return the node's status from the Proxmox API."""
try:
return self._node_api().status.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node status: %s", exc)
return {}
def _get_node_subscription(self) -> _JsonDict:
"""Return subscription status for this node."""
try:
return self._node_api().subscription.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node subscription: %s", exc)
return {}
def _get_node_dns(self) -> _JsonDict:
"""Return DNS configuration for this node."""
try:
return self._node_api().dns.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node DNS: %s", exc)
return {}
def _get_node_time(self) -> _JsonDict:
"""Return time configuration for this node."""
try:
return self._node_api().time.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node time: %s", exc)
return {}
def _get_node_ntp(self) -> _JsonDict:
"""Return NTP configuration for this node."""
try:
return self._node_api().ntp.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node NTP: %s", exc)
return {}
# ------------------------------------------------------------------ #
# NAPALM getters kept in driver
# ------------------------------------------------------------------ #
@@ -441,46 +232,7 @@ class ProxmoxDriver(
release = version.get("release", "")
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
# Physical hardware info from Linux DMI sysfs.
# Read each field separately to avoid shell quoting issues with printf.
# Field priority for model:
# product_name — human-readable name on most vendors (e.g. "NUC6CAYH",
# "ThinkCentre M910x")
# product_version — sometimes the marketing name on Lenovo; on Intel NUC
# it is the board part number (less useful as model name)
# We prefer product_name; fall back to product_version only when
# product_name looks like a raw type code (all uppercase + digits, no spaces).
vendor = ""
model = ""
serial = ""
try:
dmi_cmd = (
"v=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null); "
"n=$(cat /sys/class/dmi/id/product_name 2>/dev/null); "
"r=$(cat /sys/class/dmi/id/product_version 2>/dev/null); "
"s=$(cat /sys/class/dmi/id/product_serial 2>/dev/null); "
'printf \'%s\\n%s\\n%s\\n%s\\n\' "$v" "$n" "$r" "$s"'
)
lines = self._exec_ssh_command(dmi_cmd).splitlines()
if len(lines) >= 4:
vendor = lines[0].strip()
product_name = lines[1].strip()
product_version = lines[2].strip()
serial = lines[3].strip()
_bad = {"none", "n/a", "not specified", "to be filled by o.e.m."}
pv_usable = (
product_version
and product_version.lower() not in _bad
and product_version != product_name
# Only prefer product_version when it contains a space —
# that indicates a human-readable marketing name like
# "ThinkCentre M910x" rather than a part code like "J26843-409".
and " " in product_version
)
model = product_version if pv_usable else product_name
except Exception as exc:
logger.debug("Failed to read DMI info via SSH: %s", exc)
vendor, model, serial = self._hardware()
# Currently-booted kernel release (uname -r) — distinct from any newer
# kernel that is merely installed and pending a reboot.
@@ -501,11 +253,3 @@ class ProxmoxDriver(
"interface_list": iface_list,
"running_kernel": running_kernel,
}
# ------------------------------------------------------------------ #
# CLI passthrough
# ------------------------------------------------------------------ #
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
"""Execute a list of shell commands and return their outputs."""
return {cmd: self._exec_ssh_command(cmd) for cmd in commands}
+376
View File
@@ -0,0 +1,376 @@
"""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
packages, system identity, listening sockets, systemd services, host status,
apt's proxy), packages and APT updates, the subscription, root file writes,
and restarting or shutting the host down. All of it is the same on both
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status``
endpoints, and root's shell over the driver's own SSH session.
"""
from __future__ import annotations
import base64
import ipaddress
import logging
import re
import shlex
from typing import TYPE_CHECKING, Any, cast
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 (
FixStepOutcomeDict,
LicenseDict,
LicenseStatus,
PackageDict,
)
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: The subscription API's status (lower-cased) as a napalm-device-types
#: ``LicenseStatus``; "new" and "suspended" have none of their own.
_SUBSCRIPTION_STATUS: dict[str, LicenseStatus] = {
"notfound": "none",
"active": "active",
"invalid": "invalid",
"expired": "expired",
}
_PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.+:~-]*$")
class ProxmoxHostMixin:
"""The Debian host under a Proxmox product."""
#: ``source`` of every package ``get_packages`` reports.
PACKAGE_SOURCE = "pve"
#: ``name`` of the subscription ``get_licenses`` reports.
SUBSCRIPTION_LICENSE = "pve-subscription"
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _exec_ssh_command(self, command: str) -> str: ...
def _node_api(self) -> Any: ...
def _get_node_subscription(self) -> _JsonDict: ...
def _run_kernel_facts_command(self, command: str) -> str:
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
return self._exec_ssh_command(command)
def _run_service_packages_command(self, command: str) -> str:
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
return str(self._exec_ssh_command(command))
def _run_system_identity_command(self, command: str, *, privileged: bool) -> str:
"""The transport for ``SystemIdentityMixin.get_system_identity``: the exec path,
which runs as root either way."""
return str(self._exec_ssh_command(command))
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
"""The transport for ``ListeningSocketsMixin.get_listening_sockets``:
the exec path, which runs as root either way."""
return str(self._exec_ssh_command(command))
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
"""The transport for ``LogSourcesMixin.get_log_sources``: the exec path,
which runs as root either way."""
return str(self._exec_ssh_command(command))
def get_packages(self) -> list[PackageDict]:
"""Return installed Debian packages with available-update info.
Installed list comes from ``dpkg-query`` via SSH (the Proxmox API
``/apt/installed`` endpoint is not implemented on PVE 8.x).
Available updates come from the Proxmox API ``/apt/update``.
"""
upgradable = self._upgradable_versions()
# Installed packages via SSH dpkg-query
raw = self._exec_ssh_command(
"dpkg-query -W -f="
"'${Package}\\t${Version}\\t${db:Status-Status}\\t${Installed-Size}"
"\\t${source:Package}\\t${source:Version}\\n'"
" 2>/dev/null"
)
result = []
for line in raw.splitlines():
pkg = parse_dpkg_line(line, self.PACKAGE_SOURCE)
if pkg is not None:
pkg["upgrade_version"] = upgradable.get(pkg["name"], "")
result.append(pkg)
# PackageDict has no source_package, source_version and upgrade_version
# yet (NAPALM/napalm-device-types#85); every reader of these
# packages relies on them, so they stay.
return cast(list[PackageDict], result)
def _upgradable_versions(self) -> dict[str, str]:
"""The candidate version of every upgradable package, from ``/apt/update``."""
upgradable: dict[str, str] = {}
try:
for upd in self._node_api().apt.update.get():
pkg = upd.get("Package", "")
if pkg:
upgradable[pkg] = upd.get("Version", "")
except Exception as exc:
logger.debug("Failed to fetch available APT updates: %s", exc)
return upgradable
def get_licenses(self) -> list[LicenseDict]:
"""The node's subscription, as the API reports it.
A fact for the caller: whether running without one is a problem is not
the driver's to say. An unreadable subscription reports nothing.
"""
sub = self._get_node_subscription()
raw = str(sub.get("status", ""))
if not raw:
return []
lic: LicenseDict = {
"name": self.SUBSCRIPTION_LICENSE,
"status": _SUBSCRIPTION_STATUS.get(raw.lower(), "unknown"),
"detail": str(sub.get("message") or raw),
}
if sub.get("productname"):
lic["edition"] = sub["productname"]
if sub.get("nextduedate"):
lic["expires"] = sub["nextduedate"]
return [lic]
def _run_service_command(self, command: str, *, privileged: bool, timeout: int) -> str:
"""The transport for ``SystemdServicesMixin``: the exec path, as root.
*privileged* needs nothing more on a node the driver reaches as root, and
the exec path keeps its own timeout.
"""
return str(self._exec_ssh_command(command))
def get_available_updates(self) -> list[_JsonDict]:
"""Return the node's upgradable packages, with origin and security status.
``apt list --upgradable`` over the exec path names each candidate's suite
(``trixie-security``); the APT API names only an Origin ("Debian",
"Proxmox") and is the fallback, with the security status unknown.
:raises Exception: when neither answers -- never an empty list for
"could not read".
"""
updates: list[_JsonDict]
try:
raw = self._exec_ssh_command(APT_UPGRADABLE_COMMAND) or ""
updates = [dict(u) for u in parse_apt_upgradable(raw)]
except ValueError as exc:
logger.debug("apt list over the exec path failed, using the API: %s", exc)
updates = self._updates_from_api()
return sorted(updates, key=lambda u: u["name"])
def _updates_from_api(self) -> list[_JsonDict]:
return [
{
"name": upd["Package"],
"current_version": upd.get("OldVersion", ""),
"new_version": upd.get("Version", ""),
"origin": upd.get("Origin"),
"security": None,
}
for upd in self._node_api().apt.update.get()
if upd.get("Package")
]
def refresh_available_updates(self) -> _JsonDict:
"""Resynchronise the node's package index (``POST nodes/{n}/apt/update``)."""
try:
task = self._node_api().apt.update.post()
except Exception as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": f"Package index refresh started ({task})"}
def _run_host_status_command(self, command: str) -> str:
"""The transport for ``HostStatusMixin.get_host_status``: the exec path."""
return str(self._exec_ssh_command(command))
def apply_updates(self, packages: list[str]) -> _JsonDict:
"""Upgrade the given packages via ``apt-get install`` over SSH."""
for pkg in packages:
if not re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
raise ValueError(f"Invalid package name: {pkg!r}")
pkg_args = " ".join(packages)
output, status = self._rc(
f"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y {pkg_args}"
)
if status == 0:
return {"success": True, "output": output}
error = (
f"apt-get exited with status {status}"
if status >= 0
else "apt-get's exit status could not be read"
)
return {"success": False, "output": output, "error": error}
def _rc(self, command: str) -> tuple[str, int]:
"""Run *command* and return its output and exit status (-1 when unknown)."""
out = self._exec_ssh_command(f"{{ {command}; }} 2>&1; echo __PVE_RC=$?")
text, _, tail = out.rpartition("__PVE_RC=")
try:
return text.strip(), int(tail.strip())
except ValueError:
return out.strip(), -1
def _step(self, command: str, done: str) -> FixStepOutcomeDict:
output, status = self._rc(command)
return {"ok": status == 0, "output": done if status == 0 else output[-300:]}
def _run_apt_command(self, command: str) -> str:
return str(self._exec_ssh_command(command))
def _run_apt_root_command(self, command: str, done: str) -> FixStepOutcomeDict:
return self._step(command, done)
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
return self._write_root_file(path, content)
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
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]
if not sources:
return {"ok": True, "output": "no sources given; firewall unchanged"}
if self._rc("command -v ufw")[1] != 0:
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
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)}")
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:
"""Write *content* to *path* as root, mode 644, through a temporary file."""
encoded = base64.b64encode(content.encode()).decode()
# No ``exit`` here: it would end the shell before ``_rc`` reads the status.
return self._step(
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
f'install -m 644 -o root -g root "$t" {shlex.quote(path)}; '
's=$?; rm -f "$t"; [ "$s" -eq 0 ]',
f"wrote {path}",
)
def install_package(self, name: str, version: str = "") -> None:
"""apt-get install *name* (``PackageManagementMixin``); raises when apt fails."""
if not _PACKAGE_NAME.match(name) or (version and not _PACKAGE_NAME.match(version)):
raise ValueError(f"not a package name: {name!r}")
target = f"{name}={version}" if version else name
output, status = self._rc(f"DEBIAN_FRONTEND=noninteractive apt-get install -y {target}")
if status != 0:
raise RuntimeError(f"apt-get install {target} failed: {output[-300:]}")
def get_management_peer(self) -> str | None:
"""The address the node sees the SSH connection come from (``SSH_CONNECTION``)."""
out = self._exec_ssh_command('printf "%s\\n" "$SSH_CONNECTION"').split()
try:
return str(ipaddress.ip_address(out[0])) if out else None
except ValueError:
return None
def reboot_host(self) -> None:
"""Restart the node through the API (no SSH involved)."""
try:
self._node_api().status.post(command="reboot")
except Exception as exc:
raise RuntimeError(f"Reboot of node {self._node_name!r} refused: {exc}") from exc
def shutdown_host(self) -> None:
"""Shut the node down through the API; on PVE its guests stop as on any shutdown."""
try:
self._node_api().status.post(command="shutdown")
except Exception as exc:
raise RuntimeError(f"Shutdown of node {self._node_name!r} refused: {exc}") from exc
def parse_dpkg_line(line: str, source: str) -> _JsonDict | None:
"""One installed package from a line of the ``dpkg-query`` format above, or
None for a line that is not an installed package."""
parts = line.strip().split("\t")
if len(parts) < 2 or not parts[0]:
return None
name, version = parts[0], parts[1]
status = parts[2] if len(parts) > 2 else "installed"
if status != "installed":
return None
size_kb, source_package_field, source_version_field = (parts[3:] + ["", "", ""])[:3]
# Debian source package (differs from the binary for split packages,
# e.g. openssh-server → openssh). Needed for accurate OSV matching.
source_package = source_package_field or name
# And its version, which is a different number from this package's.
#
# OSV states Debian ranges in *source* versions, so a consumer given
# the source package and only the binary version compares two
# unrelated numbers: libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while
# its source, samba, is 2:4.22.11+dfsg-…. Reporting the source
# without its version is worse than reporting neither, because it
# looks usable. Every package on all three Proxmox nodes was in that
# state — the format string never asked for the field.
#
# dpkg leaves it empty when it equals `Version`, and so does an
# older dpkg that does not know the field at all.
source_version = source_version_field or version
return {
"name": name,
"version": version,
"installed": True,
"description": "",
"size": int(size_kb) * 1024 if size_kb.isdigit() else 0,
"source": source,
"source_package": source_package,
"source_version": source_version,
}
+70
View File
@@ -0,0 +1,70 @@
"""File names and checksums of the cloud images a VM is provisioned from.
The image URL comes from whoever publishes the image (a release feed), so
nothing taken from it reaches a file name on the node unless Proxmox would keep
it in a content file name too.
"""
from __future__ import annotations
import hashlib
import re
# Proxmox reads an import volume's format off its extension and accepts only
# these. Ubuntu ships its qcow2 cloud images as ".img", so that is stored as
# qcow2: if an .img is really raw, the import fails loudly, whereas guessing
# raw for a qcow2 would attach the qcow2 container as a raw disk silently.
_IMPORT_EXTENSIONS = {"qcow2": "qcow2", "raw": "raw", "vmdk": "vmdk", "img": "qcow2"}
# Characters Proxmox keeps in a content file name (PVE::Storage's
# SAFE_CHAR_CLASS_RE); anything else it would rewrite behind our back.
_UNSAFE_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9\-.+=_]")
# The checksum algorithms Proxmox's download-url accepts; each has a coreutils
# "<algo>sum" on the node.
_CHECKSUM_ALGORITHMS = frozenset({"md5", "sha1", "sha224", "sha256", "sha384", "sha512"})
def url_key(image_url: str) -> str:
"""Short hash of the full URL — Ubuntu and others publish a new build
under the same basename every day, so the basename alone is no cache key."""
return hashlib.sha256(image_url.encode()).hexdigest()[:12]
def _basename(image_url: str) -> str:
return image_url.rstrip("/").rsplit("/", 1)[-1]
def split_checksum(image_checksum: str) -> tuple[str, str]:
"""``"<algo>:<hex>"`` as ``(algo, hex)``; the algorithm defaults to sha256.
:raises ValueError: for an algorithm Proxmox does not know.
"""
algo, _, expected = image_checksum.partition(":")
algo = (algo or "sha256").lower()
if algo not in _CHECKSUM_ALGORITHMS:
raise ValueError(f"unknown checksum algorithm {algo!r}")
return algo, expected
def cache_name(image_url: str) -> str:
"""The file name *image_url* gets in the node's image cache.
The URL's hash, then its basename with every character Proxmox would not
keep replaced by ``_``.
"""
return f"{url_key(image_url)}-{_UNSAFE_FILENAME_CHARS.sub('_', _basename(image_url))}"
def import_volume_name(image_url: str) -> str | None:
"""The file name *image_url* gets in an import storage.
None when Proxmox cannot import the image's type at all (compressed,
ISO, no extension) — provisioning then downloads it over SSH as before.
"""
stem, dot, ext = _basename(image_url).rpartition(".")
extension = _IMPORT_EXTENSIONS.get(ext.lower()) if dot and stem else None
if extension is None:
return None
safe_stem = _UNSAFE_FILENAME_CHARS.sub("_", stem)
return f"netork-{url_key(image_url)}-{safe_stem}.{extension}"
+7 -5
View File
@@ -148,8 +148,10 @@ class ProxmoxInterfaceMixin:
"interface": iface,
"mac": utils.normalize_mac(mac),
"ip": parts[0],
# `ip neigh` reports no age; NAPALM's shape requires the key.
"age": 0.0,
# `ip neigh` reports no age; NAPALM's shape requires the key,
# and -1.0 is napalm-device-types' ARP_AGE_UNKNOWN -- 0.0
# would mean "confirmed just now".
"age": -1.0,
"state": state,
}
)
@@ -158,9 +160,9 @@ class ProxmoxInterfaceMixin:
def get_arp_table(self, vrf: str = "") -> list[_JsonDict]:
"""Return ARP table.
Proxmox does not expose ARP via the REST API directly. We attempt
to read it via the node's ``/proc/net/arp`` through the Proxmox
exec endpoint. If that is unavailable, an empty list is returned.
Proxmox does not expose ARP via the REST API, so the node's
``/proc/net/arp`` is read over SSH; a node that cannot be reached
there raises.
"""
raw = self._exec_ssh_command("cat /proc/net/arp")
if not raw:
+44 -74
View File
@@ -12,91 +12,61 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""LLDP-related NAPALM getters for Proxmox VE nodes."""
"""LLDP-related NAPALM getters for Proxmox VE nodes.
lldpd's neighbours come from ``lldpctl -f keyvalue``, parsed and projected by
napalm-device-types (``parse_lldpctl_keyvalue``, ``lldp_neighbors``,
``lldp_neighbors_detail``), as on every host that runs lldpd.
"""
from __future__ import annotations
import re
from typing import Any
from typing import TYPE_CHECKING
_JsonDict = dict[str, Any]
from napalm.base.models import LLDPNeighborDetailDict
from napalm_device_types import (
LLDPCTL_KEYVALUE_COMMAND,
LldpNeighborDict,
LldpNeighborRow,
lldp_neighbors,
lldp_neighbors_detail,
parse_lldpctl_keyvalue,
)
class ProxmoxLLDPMixin:
"""Mixin providing LLDP NAPALM methods."""
def get_lldp_neighbors(self) -> dict[str, list[_JsonDict]]:
"""Return LLDP neighbours (requires lldpd on the Proxmox node)."""
result: dict[str, list[_JsonDict]] = {}
raw = self._exec_ssh_command("lldpcli show neighbors summary 2>/dev/null || true")
current_iface = ""
for line in raw.splitlines():
m_iface = re.match(r"^\s*Interface:\s+(\S+?),?\s", line)
if m_iface:
current_iface = m_iface.group(1)
result.setdefault(current_iface, [])
continue
m_sys = re.match(r"^\s*SysName:\s+(.+)", line)
m_port = re.match(r"^\s*PortID:\s+\S+\s+(.+)", line)
if m_sys and current_iface:
hostname = m_sys.group(1).strip()
if result[current_iface]:
result[current_iface][-1]["hostname"] = hostname
else:
result[current_iface].append({"hostname": hostname, "port": ""})
if m_port and current_iface and result[current_iface]:
result[current_iface][-1]["port"] = m_port.group(1).strip()
return result
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
"""Return LLDP neighbours (requires lldpd on the Proxmox node).
def get_lldp_neighbors_detail(self, interface: str = "") -> dict[str, list[_JsonDict]]:
"""Return detailed LLDP neighbour information."""
result: dict[str, list[_JsonDict]] = {}
raw = self._exec_ssh_command("lldpcli show neighbors details 2>/dev/null || true")
current_iface = ""
current_entry: _JsonDict = {}
Every neighbour of a port is its own entry; one that names its chassis
by a MAC address carries it as ``mac``.
def _flush():
if current_iface and current_entry:
result.setdefault(current_iface, []).append(current_entry.copy())
:raises ValueError: when lldpctl failed or gave no answer.
"""
return lldp_neighbors(self._get_lldp_table())
for line in raw.splitlines():
m_iface = re.match(r"^\s*Interface:\s+(\S+?),?\s", line)
if m_iface:
_flush()
current_iface = m_iface.group(1)
if interface and current_iface != interface:
current_iface = ""
current_entry = {
"parent_interface": "",
"remote_chassis_id": "",
"remote_system_name": "",
"remote_port": "",
"remote_port_description": "",
"remote_system_description": "",
"remote_system_capab": [],
"remote_system_enable_capab": [],
}
continue
if not current_iface:
continue
for key, pattern in (
("remote_chassis_id", r"ChassisID:\s+\S+\s+(.+)"),
("remote_system_name", r"SysName:\s+(.+)"),
("remote_port", r"PortID:\s+\S+\s+(.+)"),
("remote_port_description", r"PortDescr:\s+(.+)"),
("remote_system_description", r"SysDescr:\s+(.+)"),
):
m = re.match(rf"^\s*{pattern}", line)
if m:
current_entry[key] = m.group(1).strip()
def get_lldp_neighbors_detail(
self, interface: str = ""
) -> dict[str, list[LLDPNeighborDetailDict]]:
"""Return detailed LLDP neighbour information, of *interface* only when given.
m_cap = re.match(r"^\s*Capability:\s+(\S+),\s+(\w+)", line)
if m_cap:
cap = m_cap.group(1).lower()
enabled = m_cap.group(2).lower() == "on"
current_entry["remote_system_capab"].append(cap)
if enabled:
current_entry["remote_system_enable_capab"].append(cap)
:raises ValueError: when lldpctl failed or gave no answer.
"""
return lldp_neighbors_detail(self._get_lldp_table(), interface)
_flush()
return result
def _get_lldp_table(self) -> list[LldpNeighborRow]:
"""``lldpctl -f keyvalue`` on the node, one row per neighbour.
The command always prints lldpctl's exit status, so an empty answer
means it never ran: that is no answer, not a node without neighbours.
"""
raw = self._exec_ssh_command(LLDPCTL_KEYVALUE_COMMAND)
if not raw.strip():
raise ValueError("lldpctl gave no answer on the node")
return parse_lldpctl_keyvalue(raw)
if TYPE_CHECKING: # pragma: no cover - the driver's
def _exec_ssh_command(self, command: str) -> str: ...
+115
View File
@@ -0,0 +1,115 @@
"""Reading Proxmox VE's answers about a guest's migration: refusal reasons, local
volumes and resources, task log errors.
- ``GET /nodes/{node}/qemu/{vmid}/migrate`` (qemu-server's
``migrate_vm_precondition``): ``not_allowed_nodes`` maps a node to its
blockers -- ``unavailable_storages``, ``unavailable-resources`` (mappings the
node lacks), ``blocking-ha-resources`` (PVE 9 HA rules); ``local_disks`` lists
volumes on non-shared storage, CD drives included; ``local_resources``
(``hostpci0``, ``usb0``, ``clipboard=vnc``) block the migration.
- A container has no such endpoint; its config says what it keeps locally
(``PVE/LXC/Migrate.pm``): a bind or device mount point that is not marked
``shared`` stops the migration, a volume on non-shared storage is copied.
- A task log is rows of ``{"n": <line>, "t": <text>}``; a failure writes
``ERROR: ...`` lines.
"""
from __future__ import annotations
import re
from typing import Any
from napalm_proxmox.pve_values import to_flag
_JsonDict = dict[str, Any]
_ERROR = re.compile(r"\bERROR: (.*\S)")
#: The cloud-init drive is a CD drive the migration regenerates on the target.
_CLOUDINIT = re.compile(r"vm-\d+-cloudinit")
_CT_VOLUME_KEY = re.compile(r"^(rootfs|mp\d+|unused\d+)$")
def task_errors(log: list[_JsonDict]) -> list[str]:
"""The ``ERROR:`` lines of a task log, without their timestamps, each once."""
errors: list[str] = []
for row in log:
match = _ERROR.search(str(row.get("t") or ""))
if match and match.group(1) not in errors:
errors.append(match.group(1))
return errors
def upid_field(upid: str, index: int) -> str:
"""A field of ``UPID:node:pid:pstart:starttime:type:id:user:``; "" if absent."""
parts = upid.split(":")
return parts[index] if len(parts) > index else ""
def _names(kind: str, items: list[Any]) -> str:
names = ", ".join(str(item) for item in items)
return f"{kind} {names} is" if len(items) == 1 else f"{kind}s {names} are"
def _ha_block(item: Any) -> str:
if not isinstance(item, dict):
return f"HA resource {item} blocks it"
cause = f" ({item['cause']} rule)" if item.get("cause") else ""
return f"HA resource {item.get('sid')} blocks it{cause}"
def _reason(key: str, value: Any) -> str:
items = value if isinstance(value, list) else [value]
if key == "unavailable_storages":
return f"{_names('storage', items)} not available there"
if key == "unavailable-resources":
return f"{_names('mapped resource', items)} not available there"
if key == "blocking-ha-resources":
return "; ".join(_ha_block(item) for item in items)
return f"{key}: {', '.join(str(item) for item in items)}"
def refusal(blockers: Any) -> str:
"""One node's ``not_allowed_nodes`` entry in plain words."""
if not isinstance(blockers, dict) or not blockers:
return "refused by Proxmox VE"
return "; ".join(_reason(key, blockers[key]) for key in sorted(blockers))
def qemu_local(answer: _JsonDict) -> tuple[list[str], list[str]]:
"""``(local_disks, local_resources)`` of a VM's migrate precondition answer.
A local ISO in a CD drive stops the migration, so it is a resource
(``cdrom=<volid>``, after PVE's own ``clipboard=vnc``), not a disk.
"""
disks: list[str] = []
resources = [str(r) for r in answer.get("local_resources") or []]
for disk in answer.get("local_disks") or []:
volid = str(disk.get("volid") or "")
if not volid or _CLOUDINIT.search(volid):
continue
if to_flag(disk.get("cdrom")):
resources.append(f"cdrom={volid}")
else:
disks.append(volid)
return sorted(disks), resources
def lxc_local(config: _JsonDict, shared: dict[str, bool]) -> tuple[list[str], list[str]]:
"""``(local_disks, local_resources)`` of a container's config.
*shared* says per storage whether it is shared; a storage it does not know is
taken as local, which blocks nothing.
"""
disks: list[str] = []
resources: list[str] = []
for key in sorted(config):
if not _CT_VOLUME_KEY.match(key):
continue
volume, *options = str(config[key]).split(",")
volume = volume.removeprefix("volume=")
if volume.startswith("/"):
if "shared=1" not in options:
resources.append(key)
elif not shared.get(volume.split(":", 1)[0], False):
disks.append(volume)
return sorted(disks), resources
+51
View File
@@ -0,0 +1,51 @@
"""What a VM's NIC may attach to on a node (``NetworkTargetDict``).
A Linux or OVS bridge from the node's network config (``GET /nodes/{node}/network``),
or an SDN vnet (``GET /cluster/sdn/vnets``). Physical NICs, bonds and other
interface types are never valid ``NICConfigDict.bridge`` values on Proxmox.
Shared by ``get_network_targets()`` (the own node) and ``get_clusters()`` (every
online node of the cluster).
"""
from __future__ import annotations
from typing import Any
from napalm_device_types.models import NetworkTargetDict
from napalm_proxmox.uplinks import bridge_uplinks
_BRIDGE_TYPES = frozenset({"bridge", "OVSBridge"})
def bridge_targets(network: list[dict[str, Any]]) -> list[NetworkTargetDict]:
"""The bridges in one node's *network* config, with their uplinks where known."""
targets: list[NetworkTargetDict] = []
for iface in network:
iface_type = iface.get("type")
name = iface.get("iface", "")
if not name or iface_type not in _BRIDGE_TYPES:
continue
# OVS bridges tag per-port regardless of a dedicated "VLAN aware" setting.
vlan_aware = iface_type == "OVSBridge" or bool(int(iface.get("bridge_vlan_aware", 0) or 0))
target: NetworkTargetDict = {"name": name, "kind": "bridge", "vlan_aware": vlan_aware}
uplinks = bridge_uplinks(iface, network)
if uplinks is not None:
target["uplinks"] = uplinks
targets.append(target)
return targets
def vnet_target(vnet: dict[str, Any]) -> NetworkTargetDict | None:
"""An SDN *vnet* as a target, or None when it has no name."""
name = vnet.get("vnet", "")
if not name:
return None
# A vnet's VLAN is already fixed by its zone/tag — no separate vlan_tag applies.
tag = vnet.get("tag")
return {
"name": name,
"kind": "vnet",
"vlan_aware": False,
"fixed_vlan_tag": int(tag) if tag is not None else None,
}
+113
View File
@@ -0,0 +1,113 @@
"""NTP statistics (``get_ntp_stats``) from chrony or ntpd, in NAPALM's NTPStats shape.
Proxmox VE ships chrony; ntpd is read only where chrony is not installed.
chrony is read in its CSV mode (``chronyc -c``): ``sources`` names each source
with its state, ``sourcestats`` adds the spread of its offset, reported as
jitter. chrony reports no delay per source, so ``delay`` is 0.0. Times are in
milliseconds and the poll interval in seconds, as ``ntpq -pn`` gives them.
"""
from __future__ import annotations
import re
from typing import Any
CHRONY_SOURCES_MARK = "CHRONY_SOURCES"
CHRONY_SOURCESTATS_MARK = "CHRONY_SOURCESTATS"
#: chrony when it is installed, ntpd's ntpq otherwise.
NTP_STATS_COMMAND = (
"if command -v chronyc >/dev/null 2>&1; then "
f"echo {CHRONY_SOURCES_MARK}; chronyc -n -c sources; "
f"echo {CHRONY_SOURCESTATS_MARK}; chronyc -n -c sourcestats; "
"else ntpq -pn; fi 2>/dev/null"
)
#: chrony's source mode as ntpq's type: server (unicast), peer (symmetric), refclock (local).
_CHRONY_TYPES = {"^": "u", "=": "s", "#": "l"}
_MS_PER_S = 1000.0
#: ``*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123``; the first
#: column is the tally mark, a space for a peer without one.
_NTPQ_LINE = re.compile(
r"^([ *+#ox.-])(\S+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)"
r"\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)"
)
def parse_ntp_stats(output: str) -> list[dict[str, Any]]:
"""The NTPStats list in the output of :data:`NTP_STATS_COMMAND`."""
if output.lstrip().startswith(CHRONY_SOURCES_MARK):
return parse_chrony(output)
return parse_ntpq(output)
def parse_chrony(output: str) -> list[dict[str, Any]]:
"""Sources and their statistics from ``chronyc -n -c sources`` / ``sourcestats``."""
sources, _, sourcestats = output.partition(CHRONY_SOURCESTATS_MARK)
jitter = _chrony_jitter(sourcestats)
stats = []
for line in sources.splitlines():
fields = line.strip().split(",")
if len(fields) < 10:
continue
mode, state, name, stratum, poll, reach, last_rx, _, offset, _ = fields[:10]
try:
stats.append(
{
"remote": name,
"referenceid": "",
"synchronized": state == "*",
"stratum": int(stratum),
"type": _CHRONY_TYPES.get(mode, ""),
"when": last_rx,
"hostpoll": 2 ** int(poll),
"reachability": int(reach),
"delay": 0.0,
"offset": float(offset) * _MS_PER_S,
"jitter": jitter.get(name, 0.0),
}
)
except ValueError:
continue
return stats
def _chrony_jitter(sourcestats: str) -> dict[str, float]:
"""Each source's offset standard deviation in ms (``sourcestats``' last column)."""
jitter = {}
for line in sourcestats.splitlines():
fields = line.strip().split(",")
if len(fields) < 8:
continue
try:
jitter[fields[0]] = float(fields[7]) * _MS_PER_S
except ValueError:
continue
return jitter
def parse_ntpq(output: str) -> list[dict[str, Any]]:
"""Peers from ``ntpq -pn``."""
stats = []
for line in output.splitlines():
m = _NTPQ_LINE.match(line)
if not m:
continue
tally, remote, refid, stratum, kind, when, poll, reach, delay, offset, jitter = m.groups()
stats.append(
{
"remote": remote,
"referenceid": refid,
"synchronized": tally == "*",
"stratum": int(stratum),
"type": kind,
"when": when,
"hostpoll": int(poll),
"reachability": int(reach),
"delay": float(delay),
"offset": float(offset),
"jitter": float(jitter),
}
)
return stats
+314
View File
@@ -0,0 +1,314 @@
"""The backup-server role of the Proxmox Backup Server driver.
Datastores, backup groups with their snapshots, the jobs that keep them
(garbage collection, verify, prune, sync, tape) and the remotes, read through
the PBS REST API, plus the actions on them.
A privilege-separated API token without an ACL entry does not get a 403 for a
listing: PBS filters the list by privilege and answers ``[]``. An empty list
therefore says nothing until ``/access/permissions`` shows the privilege, so
every read checks it first.
"""
from __future__ import annotations
from typing import Any
from napalm_device_types import (
BackupDatastoreDict,
BackupGroupDict,
BackupJobKind,
BackupRemoteDict,
BackupRunState,
BackupServerJobDict,
BackupSnapshotDict,
BackupSnapshotRefDict,
BackupTaskDict,
BackupTaskStatusDict,
)
from proxmoxer.core import ResourceException
_JsonDict = dict[str, Any]
#: Where "run this job now" is, per kind; ``{id}`` is the job, for GC the datastore.
_RUN_PATHS: dict[str, str] = {
"gc": "admin/datastore/{id}/gc",
"verify": "admin/verify/{id}/run",
"prune": "admin/prune/{id}/run",
"sync": "admin/sync/{id}/run",
"tape": "tape/backup/{id}",
}
#: Where each kind's jobs are listed with the state of their last run.
_JOB_LISTS: dict[BackupJobKind, str] = {
"gc": "admin/gc",
"verify": "admin/verify",
"prune": "admin/prune",
"sync": "admin/sync",
"tape": "tape/backup",
}
def run_state(text: str | None) -> tuple[BackupRunState | None, str | None]:
"""A job's ``last-run-state`` or a task's ``exitstatus``: the state and the error."""
if not text:
return None, None
if text == "OK":
return "ok", None
if text.startswith("WARNINGS"):
return "warning", text
return "error", text
def _granted(rights: dict[str, dict[str, Any]], privilege: str, path: str) -> bool:
"""Whether *privilege* holds on *path*, given on the path itself or propagated
from a parent (``/access/permissions``: privilege -> propagate flag)."""
for granted_on, privileges in rights.items():
if privilege not in privileges:
continue
if granted_on == path:
return True
parent = granted_on.rstrip("/") + "/"
if path.startswith(parent) and privileges[privilege]:
return True
return False
def _maintenance(config: _JsonDict, mount_status: str | None) -> str | None:
for part in str(config.get("maintenance-mode") or "").split(","):
key, _, value = part.partition("=")
if key == "type" and value:
return value
return "unmounted" if mount_status == "notmounted" else None
def _datastore(usage: _JsonDict, config: _JsonDict) -> BackupDatastoreDict:
"""One datastore from its ``status/datastore-usage`` row and its configuration."""
if usage.get("backend-type") == "s3":
backend = "s3"
elif config.get("backing-device"):
backend = "removable"
else:
backend = "local"
# A removable datastore's path is relative to wherever it is mounted.
path = config.get("path")
full = usage.get("estimated-full-date")
return {
"name": usage["store"],
"path": path if isinstance(path, str) and path.startswith("/") else None,
"backend": backend,
"total": usage.get("total"),
"used": usage.get("used"),
"available": usage.get("avail"),
"estimated_full": full if isinstance(full, int) and full > 0 else None,
"maintenance": _maintenance(config, usage.get("mount-status")),
"comment": config.get("comment"),
}
def _snapshot(raw: _JsonDict) -> BackupSnapshotDict:
state = (raw.get("verification") or {}).get("state")
return {
"time": int(raw["backup-time"]),
"size": raw.get("size"),
"verify": state if state in ("ok", "failed") else None,
"protected": bool(raw.get("protected")),
"comment": raw.get("comment"),
}
def _job(kind: BackupJobKind, raw: _JsonDict) -> BackupServerJobDict:
state, error = run_state(raw.get("last-run-state"))
if state is None and raw.get("last-run-upid") and not raw.get("last-run-endtime"):
state = "running"
sync = kind == "sync"
enabled = not raw.get("disable") if kind == "prune" else bool(raw.get("schedule"))
return {
"id": raw["store"] if kind == "gc" else raw["id"],
"kind": kind,
"datastore": raw.get("store"),
"namespace": raw.get("ns"),
"schedule": raw.get("schedule"),
"enabled": enabled,
"last_run": raw.get("last-run-endtime"),
"last_state": state,
"last_error": error,
"next_run": raw.get("next-run"),
"remote": raw.get("remote") if sync else None,
"direction": (raw.get("sync-direction") or "pull") if sync else None,
"comment": raw.get("comment"),
}
def _snapshot_params(snapshot: BackupSnapshotRefDict) -> _JsonDict:
params: _JsonDict = {
"backup-type": snapshot["group_type"],
"backup-id": snapshot["group_id"],
"backup-time": snapshot["time"],
}
if snapshot["namespace"]:
params["ns"] = snapshot["namespace"]
return params
class ProxmoxBackupServerMixin:
"""``BackupServerDriver`` for Proxmox Backup Server."""
_api: Any
_node_name: str
# ------------------------------------------------------------------ #
# Plumbing
# ------------------------------------------------------------------ #
def _pbs(self, method: str, path: str, **params: Any) -> Any:
"""One API call. A 400 or 404 is the caller's mistake (no such datastore,
job, snapshot or task): ValueError. Everything else propagates."""
try:
return getattr(self._api, method)(path, **params)
except ResourceException as exc:
if exc.status_code in (400, 404):
raise ValueError(f"{method.upper()} {path}: {exc}") from exc
raise
def _require(self, privilege: str, path: str) -> None:
rights = self._pbs("get", "access/permissions") or {}
if not _granted(rights, privilege, path):
raise PermissionError(
f"the API login lacks {privilege} on {path}; the server would answer "
"with an empty list rather than refuse"
)
@staticmethod
def _task(upid: Any, what: str) -> BackupTaskDict:
if not isinstance(upid, str) or not upid:
raise RuntimeError(f"{what}: the server returned no task id")
return {"task": upid}
# ------------------------------------------------------------------ #
# Read
# ------------------------------------------------------------------ #
def get_backup_datastores(self) -> list[BackupDatastoreDict]:
self._require("Datastore.Audit", "/datastore")
configs = {c["name"]: c for c in self._pbs("get", "config/datastore") or []}
return [
_datastore(usage, configs.get(usage["store"], {}))
for usage in self._pbs("get", "status/datastore-usage") or []
]
def get_backup_groups(self, datastore: str = "") -> list[BackupGroupDict]:
"""The groups of *datastore*, or of every datastore whose content can be
read: a removable one that is not mounted is left out of the listing
(``get_backup_datastores`` reports it as ``"unmounted"``), and raises
ValueError when asked for by name."""
self._require("Datastore.Audit", "/datastore")
stores = (
[datastore]
if datastore
else [
d["store"]
for d in self._pbs("get", "admin/datastore") or []
if d.get("mount-status") != "notmounted"
]
)
groups: list[BackupGroupDict] = []
for store in stores:
for ns in self._pbs("get", f"admin/datastore/{store}/namespace") or []:
groups.extend(self._groups_in(store, ns.get("ns") or ""))
return groups
def _groups_in(self, store: str, namespace: str) -> list[BackupGroupDict]:
params = {"ns": namespace} if namespace else {}
snapshots: dict[tuple[str, str], list[BackupSnapshotDict]] = {}
for raw in self._pbs("get", f"admin/datastore/{store}/snapshots", **params) or []:
key = (raw["backup-type"], raw["backup-id"])
snapshots.setdefault(key, []).append(_snapshot(raw))
groups: list[BackupGroupDict] = []
for raw in self._pbs("get", f"admin/datastore/{store}/groups", **params) or []:
own = snapshots.get((raw["backup-type"], raw["backup-id"]), [])
groups.append(
{
"datastore": store,
"namespace": namespace,
"type": raw["backup-type"],
"id": raw["backup-id"],
"owner": raw.get("owner"),
"count": int(raw.get("backup-count") or 0),
"newest": max(own, key=lambda s: s["time"]) if own else None,
"oldest_time": min(s["time"] for s in own) if own else None,
"comment": raw.get("comment"),
}
)
return groups
def get_backup_snapshots(
self, datastore: str, namespace: str, group_type: str, group_id: str
) -> list[BackupSnapshotDict]:
self._require("Datastore.Audit", "/datastore")
params: _JsonDict = {"backup-type": group_type, "backup-id": group_id}
if namespace:
params["ns"] = namespace
raw = self._pbs("get", f"admin/datastore/{datastore}/snapshots", **params) or []
return sorted((_snapshot(s) for s in raw), key=lambda s: s["time"], reverse=True)
def get_backup_jobs(self) -> list[BackupServerJobDict]:
self._require("Datastore.Audit", "/datastore")
jobs: list[BackupServerJobDict] = []
for kind, path in _JOB_LISTS.items():
jobs.extend(_job(kind, raw) for raw in self._pbs("get", path) or [])
return jobs
def get_backup_remotes(self) -> list[BackupRemoteDict]:
self._require("Remote.Audit", "/remote")
return [
{
"name": raw["name"],
"host": raw["host"],
"port": raw.get("port"),
"fingerprint": raw.get("fingerprint"),
"auth_id": raw.get("auth-id"),
"comment": raw.get("comment"),
}
for raw in self._pbs("get", "config/remote") or []
]
# ------------------------------------------------------------------ #
# Actions
# ------------------------------------------------------------------ #
def start_garbage_collection(self, datastore: str) -> BackupTaskDict:
return self.run_backup_job("gc", datastore)
def run_backup_job(self, kind: BackupJobKind, job_id: str) -> BackupTaskDict:
if kind not in _RUN_PATHS:
raise ValueError(f"unknown job kind {kind!r}; one of {', '.join(_RUN_PATHS)}")
path = _RUN_PATHS[kind].format(id=job_id)
return self._task(self._pbs("post", path), f"{kind} job {job_id}")
def verify_backup_snapshot(self, snapshot: BackupSnapshotRefDict) -> BackupTaskDict:
path = f"admin/datastore/{snapshot['datastore']}/verify"
return self._task(self._pbs("post", path, **_snapshot_params(snapshot)), "verify")
def set_backup_snapshot_protected(
self, snapshot: BackupSnapshotRefDict, protected: bool
) -> None:
path = f"admin/datastore/{snapshot['datastore']}/protected"
self._pbs("put", path, **_snapshot_params(snapshot), protected=int(protected))
def delete_backup_snapshot(self, snapshot: BackupSnapshotRefDict) -> None:
path = f"admin/datastore/{snapshot['datastore']}/snapshots"
self._pbs("delete", path, **_snapshot_params(snapshot))
def get_backup_task(self, task: str) -> BackupTaskStatusDict:
base = f"nodes/{self._node_name}/tasks/{task}"
status = self._pbs("get", f"{base}/status") or {}
log = self._pbs("get", f"{base}/log", limit=0) or []
running = status.get("status") == "running"
state, error = ("running", None) if running else run_state(status.get("exitstatus"))
return {
"task": task,
"running": running,
"state": state,
"error": error,
"log": [str(line.get("t", "")) for line in log],
}
+168
View File
@@ -0,0 +1,168 @@
"""The Proxmox Backup Server as a host: facts, interfaces, environment, and the
disks and ZFS pools it manages (``StorageDriver``, its second role).
The API answers most of it; the shell over SSH adds what the API does not
carry (the host name, DMI, the interfaces' MAC addresses). Without an SSH login
those stay at what the API alone can say.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types.models import DiskPoolDict, PhysicalDiskDict
from napalm_proxmox import utils
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: Each interface's name and MAC address, one per line.
LINK_ADDRESSES_COMMAND = (
'for i in /sys/class/net/*; do echo "${i##*/} $(cat "$i/address" 2>/dev/null)"; done'
)
_HEALTH = {"passed": "healthy", "failed": "failed"}
_POOL_STATUS = {"online": "online", "degraded": "degraded", "faulted": "faulted"}
class ProxmoxPbsHostMixin:
"""Host getters of the PBS driver."""
hostname: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _exec_ssh_command(self, command: str) -> str: ...
def _node_api(self) -> Any: ...
def _hardware(self) -> tuple[str, str, str]: ...
def _get_node_status(self) -> _JsonDict: ...
def _get_node_network(self) -> list[_JsonDict]: ...
def _get_version_info(self) -> _JsonDict: ...
def _shell(self, command: str) -> str | None:
"""*command*'s output, or None where the server has no SSH login for us."""
try:
return self._exec_ssh_command(command)
except ConnectionException as exc:
logger.debug("%s: no shell for %r: %s", self.hostname, command, exc)
return None
def get_facts(self) -> _JsonDict:
"""Facts from the API, with the host name and DMI over SSH where it is open."""
status = self._get_node_status()
version = self._get_version_info().get("version", "")
fqdn = (self._shell("hostname -f") or "").strip() or self.hostname
vendor, model, serial = self._hardware()
return {
"uptime": float(status.get("uptime", 0)),
"vendor": vendor or "Proxmox Server Solutions GmbH",
"model": model or "Proxmox Backup Server",
"hostname": fqdn.split(".")[0] if fqdn != self.hostname else fqdn,
"fqdn": fqdn,
"os_version": f"Proxmox Backup Server {version}".strip(),
"serial_number": serial,
"interface_list": sorted(
i["iface"] for i in self._get_node_network() if i.get("iface")
),
"running_kernel": (status.get("current-kernel") or {}).get("release", ""),
}
def _link_macs(self) -> dict[str, str]:
out = self._shell(LINK_ADDRESSES_COMMAND) or ""
macs: dict[str, str] = {}
for line in out.splitlines():
name, _, mac = line.strip().partition(" ")
if name and mac:
macs[name] = utils.normalize_mac(mac.strip())
return macs
def get_interfaces(self) -> dict[str, _JsonDict]:
"""The interfaces the server's network configuration lists. The API carries
no MAC address; it is read over SSH, and empty without it."""
macs = self._link_macs()
result: dict[str, _JsonDict] = {}
for iface in self._get_node_network():
name = iface.get("iface", "")
if not name:
continue
result[name] = {
"is_up": bool(iface.get("active")),
"is_enabled": bool(iface.get("autostart")) or bool(iface.get("active")),
"description": (iface.get("comments") or "").strip(),
"last_flapped": -1.0,
"speed": utils.speed_mbps(iface),
"mtu": int(iface.get("mtu") or 1500),
"mac_address": macs.get(name, utils.normalize_mac(iface.get("hwaddr", ""))),
}
return result
def get_interfaces_ip(self) -> dict[str, _JsonDict]:
result: dict[str, _JsonDict] = {}
for iface in self._get_node_network():
addrs = utils.addresses_from_node_network(iface)
if iface.get("iface") and addrs:
result[iface["iface"]] = addrs
return result
def get_environment(self) -> _JsonDict:
"""CPU and memory from the node status; a PBS reports no sensors."""
status = self._get_node_status()
mem = status.get("memory") or {}
return {
"fans": {},
"temperature": {},
"power": {},
"cpu": {"0": {"%usage": round(float(status.get("cpu") or 0.0) * 100, 2)}},
"memory": {
"available_ram": int(mem.get("total") or 0),
"used_ram": int(mem.get("used") or 0),
},
}
# ------------------------------------------------------------------ #
# Storage role
# ------------------------------------------------------------------ #
def get_disks(self) -> list[PhysicalDiskDict]:
"""The server's disks (``/nodes/{node}/disks/list``), as it classifies them."""
disks: list[PhysicalDiskDict] = []
for raw in self._node_api().disks.list.get() or []:
kind = raw.get("disk-type")
disks.append(
{
"slot": raw.get("name") or raw.get("devpath", ""),
"model": raw.get("model") or "",
"serial": raw.get("serial") or "",
"vendor": raw.get("vendor") or "",
"type": kind if kind in ("ssd", "nvme") else "hdd",
"size": int(raw.get("size") or 0),
"rpm": int(raw.get("rpm") or 0),
"temperature": -1,
"health": _HEALTH.get(str(raw.get("status", "")).lower(), "unknown"),
"pool": "",
}
)
return disks
def get_disk_pools(self) -> dict[str, DiskPoolDict]:
"""The ZFS pools the server manages (``/nodes/{node}/disks/zfs``)."""
pools: dict[str, DiskPoolDict] = {}
for raw in self._node_api().disks.zfs.get() or []:
name = raw["name"]
pools[name] = {
"name": name,
"type": "zfs",
"level": "",
"status": _POOL_STATUS.get(str(raw.get("health", "")).lower(), "unknown"),
"total": int(raw.get("size") or 0),
"used": int(raw.get("alloc") or 0),
"available": int(raw.get("free") or 0),
"disks": [],
"auto_expand": False,
"dedup": float(raw.get("dedup") or 1.0) > 1.0,
"compression": "",
}
return pools
+31
View File
@@ -0,0 +1,31 @@
"""How the Proxmox VE API writes plain values: numbers as strings, flags as 0/1, lists
as comma-separated strings."""
from __future__ import annotations
import re
from typing import Any
_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:
return None if value is None else int(value)
def to_flag(value: Any) -> bool:
return bool(int(value or 0))
def split_list(value: Any) -> list[str]:
"""``"a,b"`` -> ``["a", "b"]``; PVE also separates with ``;``, blanks or NUL."""
return [part for part in _LIST_SEPARATORS.split(str(value or "")) if part]
def vmid_list(value: Any) -> list[int]:
"""``"100,101"`` -> ``[100, 101]``; what is not a number is left out."""
return [int(part) for part in split_list(value) if part.isdigit()]
+9 -5
View File
@@ -23,6 +23,10 @@ import napalm.base.constants as C
_JsonDict = dict[str, Any]
#: One reply in iputils' ping output, by address or by name with the address
#: in brackets: "64 bytes from dns.google (8.8.4.4): icmp_seq=1 ttl=118 time=10.5 ms".
_PING_REPLY = re.compile(r"bytes from (?:\S+ \()?([0-9a-fA-F.:]+)\)?: .*?time=([\d.]+) ms")
class ProxmoxRoutingMixin:
"""Mixin providing routing NAPALM methods (get_route_to, ping, traceroute)."""
@@ -54,7 +58,7 @@ class ProxmoxRoutingMixin:
raw = self._exec_ssh_command(f"{cmd} 2>&1 || true")
if not raw:
return {"error": "Ping command not available via exec endpoint"}
return {"error": "ping printed nothing on the node"}
# Detect common failure strings before parsing statistics
_error_patterns = (
@@ -90,9 +94,9 @@ class ProxmoxRoutingMixin:
rtt_std = float(m_rtt.group(4)) if m_rtt else 0.0
# Individual probe lines
probes = []
for m_probe in re.finditer(r"icmp_seq=\d+.*?time=([\d.]+) ms.*?from ([\d.a-fA-F:]+)", raw):
probes.append({"ip_address": m_probe.group(2), "rtt": float(m_probe.group(1))})
probes = [
{"ip_address": m.group(1), "rtt": float(m.group(2))} for m in _PING_REPLY.finditer(raw)
]
return {
"success": {
@@ -122,7 +126,7 @@ class ProxmoxRoutingMixin:
raw = self._exec_ssh_command(" ".join(cmd_parts) + " 2>&1 || true")
if not raw:
return {"error": "traceroute not available via exec endpoint"}
return {"error": "traceroute printed nothing on the node"}
hops: _JsonDict = {}
for line in raw.splitlines():
+126
View File
@@ -0,0 +1,126 @@
"""get_running_backups() for Proxmox VE and Proxmox Backup Server.
What a restart would abort (napalm-device-types' ``RunningBackupsMixin``):
- **PVE:** the node's active vzdump tasks (``GET /nodes/<node>/tasks?source=active&
typefilter=vzdump``) and the guests on the node locked for their backup
(``GET /cluster/resources?type=vm``, ``lock: backup``). A task started for one
guest names it in its id; a job's task does not, and the guests it is taking now
are the locked ones. A guest locked without a task -- the list can lag behind,
a lock can outlive its task -- is listed on its own: its restart waits too.
- **PBS:** the running tasks that are a backup or one of the server's jobs
(``GET /nodes/localhost/tasks?running=1``). A restore or housekeeping is not.
PVE does not tell which scheduled job started a vzdump task, so ``job`` is None
there. A failed read raises: an empty list would say nothing runs.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from napalm_device_types import RunningBackupDict, RunningBackupKind, RunningBackupsMixin
_JsonDict = dict[str, Any]
#: PBS worker types that are a backup or one of a backup server's jobs.
_PBS_KINDS: dict[str, RunningBackupKind] = {
"backup": "backup",
"sync": "sync",
"syncjob": "sync",
"verify": "verify",
"verificationjob": "verify",
"verify_group": "verify",
"verify_snapshot": "verify",
"garbage_collection": "gc",
"prune": "prune",
"prunejob": "prune",
"tape-backup": "tape",
"tape-backup-job": "tape",
}
def _since(task: _JsonDict) -> int | None:
value = task.get("starttime")
return int(value) if isinstance(value, int | float) and value else None
def _text(value: Any) -> str | None:
return str(value) if value not in (None, "") else None
class ProxmoxRunningBackupsMixin(RunningBackupsMixin):
"""PVE: the node's vzdump tasks and the guests locked for their backup."""
_api: Any
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the base's, declared for type checkers
def _node_api(self) -> Any: ...
def _locked_guests(self) -> list[str]:
"""The guests on this node locked for their backup, in the API's order."""
return [
str(guest["vmid"])
for guest in self._api.cluster.resources.get(type="vm") or []
if guest.get("node") == self._node_name and guest.get("lock") == "backup"
]
def _vzdump_tasks(self) -> list[_JsonDict]:
tasks = self._node_api().tasks.get(source="active", typefilter="vzdump") or []
return [t for t in tasks if t.get("type") == "vzdump"]
def get_running_backups(self) -> list[RunningBackupDict]:
tasks = self._vzdump_tasks()
named = {str(t["id"]) for t in tasks if t.get("id")}
unnamed = [g for g in self._locked_guests() if g not in named]
found = [_vzdump(task, unnamed) for task in tasks]
if all(t.get("id") for t in tasks):
found += [_locked(guest) for guest in unnamed]
return found
def _vzdump(task: _JsonDict, unnamed: list[str]) -> RunningBackupDict:
"""A vzdump task: its own guest, or -- a job's task -- the guests locked now."""
guest = _text(task.get("id"))
return {
"kind": "backup",
"job": None,
"task": _text(task.get("upid")),
"guests": [guest] if guest else list(unnamed),
"since": _since(task),
}
def _locked(guest: str) -> RunningBackupDict:
"""A guest locked for its backup without a task that takes it."""
return {"kind": "backup", "job": None, "task": None, "guests": [guest], "since": None}
class PbsRunningBackupsMixin(RunningBackupsMixin):
"""PBS: the running backup, sync, verify, gc, prune and tape tasks."""
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the backup-server mixin's, for type checkers
def _pbs(self, method: str, path: str, **params: Any) -> Any: ...
def get_running_backups(self) -> list[RunningBackupDict]:
tasks = self._pbs("get", f"nodes/{self._node_name}/tasks", running=1) or []
found: list[RunningBackupDict] = []
for task in tasks:
kind = _PBS_KINDS.get(str(task.get("worker_type") or ""))
if kind is None:
continue
found.append(
{
"kind": kind,
"job": _text(task.get("worker_id")),
"task": _text(task.get("upid")),
"guests": [],
"since": _since(task),
}
)
return found
+51
View File
@@ -0,0 +1,51 @@
"""Scheduled jobs of a Proxmox VE node or a Proxmox Backup Server (#56).
Both are Debian hosts: napalm-device-types' ``PosixScheduledJobsMixin`` reads
cron, run-parts, anacron and systemd timers over ``run_command`` as root, and
switches, runs and writes them. What this module adds is which of them Proxmox
itself ships -- ``platform`` -- and that a line in a file the cluster file
system holds is only run.
Not here: Proxmox VE's backup jobs (``/cluster/backup``) and replication, and a
backup server's verify, prune, sync and garbage collection jobs. Proxmox runs
those in its own daemons, not from cron or a timer, and the backup features
(``get_clusters``, ``get_backup_jobs``) keep them.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from napalm_device_types import PosixScheduledJobsMixin
if TYPE_CHECKING:
from napalm_device_types._scheduled_reading import Reading
_UNITS = ("/usr/lib/systemd/system", "/lib/systemd/system")
#: What Proxmox VE ships: ``pve-daily-update.timer`` (pve-manager), ``pvesr.timer``
#: (replication before Proxmox VE 7) and ``/etc/cron.d/vzdump``, the backup schedule of
#: releases before ``pvescheduler``, a link to ``/etc/pve/vzdump.cron``.
PVE_PLATFORM_SOURCES = (
*(f"{d}/pve-*" for d in _UNITS),
*(f"{d}/pvesr.timer" for d in _UNITS),
"/etc/cron.d/vzdump",
)
#: What a Proxmox Backup Server ships: ``proxmox-backup-daily-update.timer``.
PBS_PLATFORM_SOURCES = tuple(f"{d}/proxmox-backup*" for d in _UNITS)
class ProxmoxScheduledJobsMixin(PosixScheduledJobsMixin):
"""Scheduled jobs of a Proxmox host; a driver sets ``PLATFORM_SOURCES``."""
#: Sources a job is only run from: links into ``/etc/pve``, the cluster file system
#: (pmxcfs), where a switch's ``install`` with a mode and owner is not safe.
RUN_ONLY_SOURCES: ClassVar[tuple[str, ...]] = ()
def _sj_read(self) -> Reading:
reading = super()._sj_read()
for job in reading.jobs:
if job["source"] in self.RUN_ONLY_SOURCES:
job["actions"] = [a for a in job["actions"] if a == "run"] # type: ignore[attr-defined]
return reading
+11
View File
@@ -33,6 +33,17 @@ _JsonDict = dict[str, Any]
class ProxmoxSDNMixin:
"""Mixin providing SDN, VLAN and network-instance NAPALM methods."""
#: Name prefixes of Proxmox-internal and runtime virtual interfaces, never a switch uplink.
_VIRTUAL_IFACE_PREFIXES: tuple[str, ...] = (
"fwpr", # Proxmox firewall proxy veth
"fwln", # Proxmox firewall link veth
"tap", # VM tap devices
"veth", # generic veth pairs (containers)
"virbr", # libvirt bridges
"docker", # Docker virtual interfaces
"lxcbr", # LXC bridges
)
def _get_sdn_zones(self) -> list[_JsonDict]:
try:
return self._api.cluster.sdn.zones.get() or [] # type: ignore[union-attr]
+147 -355
View File
@@ -14,37 +14,94 @@
"""System-level NAPALM getters for Proxmox VE nodes.
Environment, NTP, SNMP, users, packages, services, updates and disk SMART.
Environment, NTP, SNMP, users, hostname and disk SMART. What a PVE node shares
with a Proxmox Backup Server as a Debian host is in ``host_mixin``.
"""
from __future__ import annotations
import base64
import ipaddress
import logging
import re
import shlex
from typing import Any
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import SNMP_PURPOSE
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: The subscription API's status (lower-cased) as a napalm-device-types
#: ``LicenseStatus``; "new" and "suspended" have none of their own.
_SUBSCRIPTION_STATUS = {
"notfound": "none",
"active": "active",
"invalid": "invalid",
"expired": "expired",
}
_PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.+:~-]*$")
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
_SNMP_WORD = re.compile(r'^[^\s"#]+$')
#: The net-snmp agent's configuration file.
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
#: Exit status 0 when the node is a cluster member. pvecm itself decides
#: membership by /etc/pve/corosync.conf; /etc/corosync/corosync.conf is the
#: local copy every member keeps, there even when /etc/pve is not mounted.
#: Not ``pvecm status``: it also fails on a member whose corosync is down.
_CLUSTER_MEMBER_CHECK = "[ -e /etc/pve/corosync.conf ] || [ -e /etc/corosync/corosync.conf ]"
def _rename_in_hosts(hosts: str, old_short: str, new_short: str, new_domain: str | None) -> str:
"""*hosts* (an /etc/hosts) with the node's names renamed from *old_short*.
Only whole names change: ``old_short`` becomes ``new_short``, and
``old_short.<domain>`` becomes ``new_short.<new_domain>`` (the old domain
kept when *new_domain* is None). Other names that merely start with the
old name (``pve-backup``) and comments stay as they are.
"""
def rename(match: re.Match[str]) -> str:
name = match.group(0)
if name == old_short:
return new_short
if name.startswith(f"{old_short}."):
return f"{new_short}.{new_domain or name[len(old_short) + 1 :]}"
return name
lines = []
for line in hosts.splitlines(keepends=True):
entry, hash_, comment = line.partition("#")
lines.append(re.sub(r"\S+", rename, entry) + hash_ + comment)
return "".join(lines)
#: Proxmox's superuser, whatever the ACL says.
_PVE_SUPERUSER = "root@pam"
#: The role that makes a Proxmox user an administrator of the node.
_PVE_ADMIN_ROLE = "Administrator"
#: Regular login accounts: Debian gives them uids from 1000 up; 65534 is nobody.
_FIRST_REGULAR_UID = 1000
_NOBODY_UID = 65534
def _words(value: Any, sep: str | None = None) -> list[str]:
return [w.strip() for w in str(value or "").split(sep) if w.strip()]
def _user_entry(level: int) -> _JsonDict:
# NAPALM's get_users shape; the password is never read.
return {"level": level, "password": "", "sshkeys": []} # nosec B105
def _login_accounts(passwd: str) -> list[tuple[str, int]]:
"""``(name, uid)`` of root and every regular account in *passwd*."""
accounts = []
for line in passwd.splitlines():
parts = line.split(":")
if len(parts) < 7:
continue
try:
uid = int(parts[2])
except ValueError:
continue
if uid == 0 or _FIRST_REGULAR_UID <= uid < _NOBODY_UID:
accounts.append((parts[0], uid))
return accounts
def _net(value: str) -> str:
@@ -121,52 +178,12 @@ class ProxmoxSystemMixin:
return env
# ------------------------------------------------------------------ #
# get_ntp_servers / get_ntp_stats
# get_ntp_stats (get_ntp_servers: time_sync.ProxmoxTimeSyncMixin)
# ------------------------------------------------------------------ #
def get_ntp_servers(self) -> dict[str, _JsonDict]:
"""Return configured NTP servers."""
ntp = self._get_node_ntp()
servers: dict[str, _JsonDict] = {}
# Proxmox reports a comma-separated or space-separated server list
raw = ntp.get("server", "") or ntp.get("servers", "")
for srv in re.split(r"[\s,]+", raw):
srv = srv.strip()
if srv:
servers[srv] = {}
return servers
def get_ntp_stats(self) -> list[_JsonDict]:
"""Return NTP synchronisation statistics from chronyc/ntpq output."""
raw = self._exec_ssh_command(
"chronyc -n tracking 2>/dev/null || ntpq -pn 2>/dev/null || true"
)
stats: list[_JsonDict] = []
for line in raw.splitlines():
line = line.strip()
# ntpq -pn format: *remote refid st t when poll reach delay offset jitter
m = re.match(
r"^([\*\+\-\s])([\d.]+)\s+([\d.]+)\s+(\d+)\s+\S+\s+(\S+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+([-\d.]+)\s+([\d.]+)",
line,
)
if m:
synced = m.group(1).strip() == "*"
stats.append(
{
"remote": m.group(2),
"referenceid": m.group(3),
"synchronized": synced,
"stratum": int(m.group(4)),
"type": "",
"when": m.group(5),
"hostpoll": int(m.group(6)),
"reachability": int(m.group(7)),
"delay": float(m.group(8)),
"offset": float(m.group(9)),
"jitter": float(m.group(10)),
}
)
return stats
"""Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing."""
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND))
# ------------------------------------------------------------------ #
# get_snmp_information
@@ -213,247 +230,76 @@ class ProxmoxSystemMixin:
def get_users(self) -> dict[str, _JsonDict]:
"""Return users configured on the Proxmox node.
Reads from both the Proxmox access/users API and local /etc/passwd.
Proxmox's own users (``/access/users``) at level 15 when they hold the
Administrator role on the whole datacenter (``/``), directly or through
a group, 1 otherwise; ``root@pam`` is always 15. Then the node's login
accounts from the passwd database: root (15) and regular users
(uid 1000 and up, without ``nobody``) at 0; system accounts are left out.
"""
result: dict[str, _JsonDict] = {}
try:
pve_users = self._api.access.users.get() or [] # type: ignore[union-attr]
except Exception as exc:
logger.debug("Failed to fetch Proxmox users: %s", exc)
pve_users = []
for user in pve_users:
admins, admin_groups = self._pve_administrators()
for user in self._pve_users():
uid = user.get("userid", "")
if not uid:
continue
# Proxmox roles: Administrator -> 15, otherwise 1
level = 1
try:
roles = self._api.access.users(uid).get() or {} # type: ignore[union-attr]
if "Administrator" in str(roles):
level = 15
except Exception as exc:
logger.debug("Failed to fetch roles for user %s: %s", uid, exc)
result[uid] = {
"level": level,
# NAPALM's get_users shape; the password is never read.
"password": "", # nosec B105
"sshkeys": [],
}
groups = set(_words(user.get("groups"), sep=","))
is_admin = uid == _PVE_SUPERUSER or uid in admins or bool(groups & admin_groups)
result[uid] = _user_entry(15 if is_admin else 1)
# Merge local OS users from /etc/passwd
raw = self._exec_ssh_command("getent passwd 2>/dev/null || cat /etc/passwd")
for line in raw.splitlines():
parts = line.split(":")
if len(parts) < 7:
continue
uname, _, uid_str, *_ = parts
try:
uid_int = int(uid_str)
except ValueError:
continue
if uname not in result and uid_int < 1000 or uid_int == 0:
result[uname] = {
"level": 15 if uid_int == 0 else 0,
# NAPALM's get_users shape; the password is never read.
"password": "", # nosec B105
"sshkeys": [],
}
for uname, uid_int in _login_accounts(raw):
result.setdefault(uname, _user_entry(15 if uid_int == 0 else 0))
return result
def _pve_users(self) -> list[_JsonDict]:
try:
return self._api.access.users.get() or [] # type: ignore[union-attr]
except Exception as exc:
logger.debug("Failed to fetch Proxmox users: %s", exc)
return []
def _pve_administrators(self) -> tuple[set[str], set[str]]:
"""Users and groups holding the Administrator role on ``/`` (``/access/acl``)."""
try:
acl = self._api.access.acl.get() or [] # type: ignore[union-attr]
except Exception as exc:
logger.debug("Failed to fetch the Proxmox ACL: %s", exc)
acl = []
users: set[str] = set()
groups: set[str] = set()
for entry in acl:
if entry.get("path") != "/" or entry.get("roleid") != _PVE_ADMIN_ROLE:
continue
if entry.get("type") == "user":
users.add(entry.get("ugid", ""))
elif entry.get("type") == "group":
groups.add(entry.get("ugid", ""))
return users, groups
# ------------------------------------------------------------------ #
# Kernel facts (KernelFactsMixin supplies get_kernel_facts)
# ------------------------------------------------------------------ #
def _run_kernel_facts_command(self, command: str) -> str:
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
return self._exec_ssh_command(command)
def _run_service_packages_command(self, command: str) -> str:
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
return str(self._exec_ssh_command(command))
# ------------------------------------------------------------------ #
# Listening sockets (ListeningSocketsMixin supplies get_listening_sockets)
# ------------------------------------------------------------------ #
def _run_system_identity_command(self, command: str, *, privileged: bool) -> str:
"""The transport for ``SystemIdentityMixin.get_system_identity``: the exec path,
which runs as root either way."""
return str(self._exec_ssh_command(command))
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
"""The transport for ``ListeningSocketsMixin.get_listening_sockets``:
the exec path, which runs as root either way."""
return str(self._exec_ssh_command(command))
# ------------------------------------------------------------------ #
# Packages (Debian APT)
# ------------------------------------------------------------------ #
def get_packages(self) -> list[_JsonDict]:
"""Return installed Debian packages with available-update info.
Installed list comes from ``dpkg-query`` via SSH (the Proxmox API
``/apt/installed`` endpoint is not implemented on PVE 8.x).
Available updates come from the Proxmox API ``/apt/update``.
"""
# Available updates from Proxmox API (keyed by package name)
upgradable: dict[str, str] = {}
try:
for upd in self._api.nodes(self._node_name).apt.update.get():
pkg = upd.get("Package", "")
if pkg:
upgradable[pkg] = upd.get("Version", "")
except Exception as exc:
logger.debug("Failed to fetch available APT updates: %s", exc)
# Installed packages via SSH dpkg-query
raw = self._exec_ssh_command(
"dpkg-query -W -f="
"'${Package}\\t${Version}\\t${db:Status-Status}\\t${Installed-Size}"
"\\t${source:Package}\\t${source:Version}\\n'"
" 2>/dev/null"
)
result: list[_JsonDict] = []
for line in raw.splitlines():
parts = line.strip().split("\t")
if len(parts) < 2:
continue
name = parts[0]
version = parts[1] if len(parts) > 1 else ""
status = parts[2] if len(parts) > 2 else "installed"
size_kb = parts[3] if len(parts) > 3 else "0"
# Debian source package (differs from the binary for split packages,
# e.g. openssh-server → openssh). Needed for accurate OSV matching.
source_package = parts[4] if len(parts) > 4 and parts[4] else name
# And its version, which is a different number from this package's.
#
# OSV states Debian ranges in *source* versions, so a consumer given
# the source package and only the binary version compares two
# unrelated numbers: libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while
# its source, samba, is 2:4.22.11+dfsg-…. Reporting the source
# without its version is worse than reporting neither, because it
# looks usable. Every package on all three Proxmox nodes was in that
# state — the format string never asked for the field.
#
# dpkg leaves it empty when it equals `Version`, and so does an
# older dpkg that does not know the field at all.
source_version = parts[5] if len(parts) > 5 and parts[5] else version
if not name or status != "installed":
continue
size_bytes = int(size_kb) * 1024 if size_kb.isdigit() else 0
result.append(
{
"name": name,
"version": version,
"installed": True,
"description": "",
"size": size_bytes,
"source": "pve",
"source_package": source_package,
"source_version": source_version,
"upgrade_version": upgradable.get(name, ""),
}
)
return result
# ------------------------------------------------------------------ #
# Licenses (napalm-device-types' LicenseMixin)
# ------------------------------------------------------------------ #
def get_licenses(self) -> list[_JsonDict]:
"""The node's subscription, as the API reports it.
A fact for the caller: whether running without one is a problem is not
the driver's to say. An unreadable subscription reports nothing.
"""
sub = self._get_node_subscription()
raw = str(sub.get("status", ""))
if not raw:
return []
lic: _JsonDict = {
"name": "pve-subscription",
"status": _SUBSCRIPTION_STATUS.get(raw.lower(), "unknown"),
"detail": sub.get("message") or raw,
}
if sub.get("productname"):
lic["edition"] = sub["productname"]
if sub.get("nextduedate"):
lic["expires"] = sub["nextduedate"]
return [lic]
# ------------------------------------------------------------------ #
# Services (systemd, through napalm-device-types' SystemdServicesMixin)
# ------------------------------------------------------------------ #
def _run_service_command(self, command: str, *, privileged: bool, timeout: int) -> str:
"""The transport for ``SystemdServicesMixin``: the exec path, as root.
*privileged* needs nothing more on a node the driver reaches as root, and
the exec path keeps its own timeout.
"""
return str(self._exec_ssh_command(command))
# ------------------------------------------------------------------ #
# Available updates
# ------------------------------------------------------------------ #
def get_available_updates(self) -> list[_JsonDict]:
"""Return the node's upgradable packages, with origin and security status.
``apt list --upgradable`` over the exec path names each candidate's suite
(``trixie-security``); the APT API names only an Origin ("Debian",
"Proxmox") and is the fallback, with the security status unknown.
:raises Exception: when neither answers -- never an empty list for
"could not read".
"""
try:
updates = parse_apt_upgradable(self._exec_ssh_command(APT_UPGRADABLE_COMMAND) or "")
except ValueError as exc:
logger.debug("apt list over the exec path failed, using the API: %s", exc)
updates = self._updates_from_api()
return sorted(updates, key=lambda u: u["name"])
def _updates_from_api(self) -> list[_JsonDict]:
return [
{
"name": upd["Package"],
"current_version": upd.get("OldVersion", ""),
"new_version": upd.get("Version", ""),
"origin": upd.get("Origin"),
"security": None,
}
for upd in self._api.nodes(self._node_name).apt.update.get() # type: ignore[union-attr]
if upd.get("Package")
]
def refresh_available_updates(self) -> _JsonDict:
"""Resynchronise the node's package index (``POST nodes/{n}/apt/update``)."""
try:
task = self._api.nodes(self._node_name).apt.update.post() # type: ignore[union-attr]
except Exception as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": f"Package index refresh started ({task})"}
def _run_host_status_command(self, command: str) -> str:
"""The transport for ``HostStatusMixin.get_host_status``: the exec path."""
return str(self._exec_ssh_command(command))
def apply_updates(self, packages: list[str]) -> _JsonDict:
"""Upgrade the given packages via ``apt-get install`` over SSH."""
for pkg in packages:
if not re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
raise ValueError(f"Invalid package name: {pkg!r}")
pkg_args = " ".join(packages)
output = self._exec_ssh_command(
"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y "
f"{pkg_args} 2>&1 || true"
)
return {"success": True, "output": output}
# ------------------------------------------------------------------ #
# SNMP / Health
# ------------------------------------------------------------------ #
@@ -461,7 +307,8 @@ class ProxmoxSystemMixin:
def get_snmp_config(self):
"""Return SNMP agent config if snmpd is installed and running on the node.
Uses _exec_ssh_command (Proxmox API exec or SSH) to inspect the node.
Uses _exec_ssh_command (the node's SSH session) to inspect the node;
raises when the node cannot be reached there.
Returns a SNMPConfigDict or None.
"""
try:
@@ -504,77 +351,21 @@ class ProxmoxSystemMixin:
# caller's values. The node's shell runs as root.
# ------------------------------------------------------------------
def _rc(self, command: str) -> tuple[str, int]:
"""Run *command* and return its output and exit status (-1 when unknown)."""
out = self._exec_ssh_command(f"{{ {command}; }} 2>&1; echo __PVE_RC=$?")
text, _, tail = out.rpartition("__PVE_RC=")
try:
return text.strip(), int(tail.strip())
except ValueError:
return out.strip(), -1
def _step(self, command: str, done: str) -> dict:
output, status = self._rc(command)
return {"ok": status == 0, "output": done if status == 0 else output[-300:]}
# apt's proxy (napalm-device-types AptProxyMixin): the transports. The node
# is logged in as root, so every command runs as root.
def _run_apt_command(self, command: str) -> str:
return str(self._exec_ssh_command(command))
def _run_apt_root_command(self, command: str, done: str) -> dict:
return self._step(command, done)
def _write_apt_file(self, path: str, content: str) -> dict:
encoded = base64.b64encode(content.encode()).decode()
# No ``exit`` here: ``_rc`` reads the status after the command's braces.
return self._step(
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
f'install -m 644 -o root -g root "$t" {shlex.quote(path)}; '
's=$?; rm -f "$t"; [ "$s" -eq 0 ]',
f"wrote {path}",
)
def install_package(self, name: str, version: str = "") -> None:
"""apt-get install *name* (``PackageManagementMixin``); raises when apt fails."""
if not _PACKAGE_NAME.match(name) or (version and not _PACKAGE_NAME.match(version)):
raise ValueError(f"not a package name: {name!r}")
target = f"{name}={version}" if version else name
output, status = self._rc(f"DEBIAN_FRONTEND=noninteractive apt-get install -y {target}")
if status != 0:
raise RuntimeError(f"apt-get install {target} failed: {output[-300:]}")
def get_management_peer(self) -> str | None:
"""The address the node sees the SSH connection come from (``SSH_CONNECTION``)."""
out = self._exec_ssh_command('printf "%s\\n" "$SSH_CONNECTION"').split()
try:
return str(ipaddress.ip_address(out[0])) if out else None
except ValueError:
return None
def _install_snmp_agent(self) -> dict:
return self._step(
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp", "net-snmp installed"
)
def _write_snmp_agent_config(self, settings: dict) -> dict:
encoded = base64.b64encode(render_snmpd_conf(settings).encode()).decode()
return self._step(
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
f'install -m 644 -o root -g root "$t" /etc/snmp/snmpd.conf; '
's=$?; rm -f "$t"; exit $s',
"wrote /etc/snmp/snmpd.conf",
)
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
def _allow_snmp_sources(self, settings: dict) -> dict:
sources = [_net(s) for s in settings.get("allowed_sources", [])]
if not sources:
return {"ok": True, "output": "no sources given; firewall unchanged"}
if self._rc("command -v ufw")[1] != 0:
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
rules = " && ".join(f"ufw allow from {s} to any port 161 proto udp" for s in sources)
return self._step(rules, f"udp/161 open for {', '.join(sources)}")
return dict(
self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE)
)
def _start_snmp_agent(self) -> dict:
return self._step(
@@ -582,6 +373,18 @@ class ProxmoxSystemMixin:
"snmpd enabled and running",
)
def _refuse_clustered_node(self) -> None:
_, status = self._rc(_CLUSTER_MEMBER_CHECK)
if status == 0:
raise CommandErrorException(
"set_hostname refused: the node is part of a cluster; rename a cluster"
" member by Proxmox's own procedure, not in place"
)
if status != 1:
raise CommandErrorException(
"set_hostname refused: could not tell whether the node is part of a cluster"
)
def set_hostname(self, new_hostname: str) -> None:
"""Set the system hostname on the Proxmox node.
@@ -599,16 +402,16 @@ class ProxmoxSystemMixin:
7. Proxmox node TLS certificate — regenerated via
``pvenode cert create --overwrite``.
**Important**: the Proxmox *node name* (shown in the web UI and stored
in ``/etc/pve/nodes/<name>/``) only changes after a full reboot.
Until then the web UI still shows the old node name, but the OS-level
hostname and the SSL certificate already reflect the new value.
The Proxmox *node name* (web UI, ``/etc/pve/nodes/<name>/``) only
changes after a reboot. Accepts a bare hostname or an FQDN.
Accepts a bare hostname (``pve-see``) or an FQDN
(``pve-see.see.local``).
Raises CommandErrorException, before changing anything, on a cluster
member (a corosync.conf exists): its rename is the cluster's procedure.
"""
import base64 as _b64
self._refuse_clustered_node()
if "." in new_hostname:
short_hostname, domain = new_hostname.split(".", 1)
fqdn = new_hostname
@@ -633,22 +436,11 @@ class ProxmoxSystemMixin:
# write back via base64 to avoid shell-escaping issues.
if old_short and old_short != short_hostname:
hosts_raw = self._exec_ssh_command("cat /etc/hosts 2>/dev/null")
# Replace whole-word occurrences of the old short hostname.
# Both "hostname" and "hostname.domain" forms are covered because
# the new value is the full fqdn when a domain was given.
import re as _re
new_replace = fqdn if domain else short_hostname
hosts_new = _re.sub(
r"\b" + _re.escape(old_short) + r"\b",
new_replace,
hosts_raw,
)
hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain)
hosts_b64 = _b64.b64encode(hosts_new.encode()).decode()
self._exec_ssh_command(
f"echo {hosts_b64} | base64 -d > /tmp/_netork_hosts"
f" && mv /tmp/_netork_hosts /etc/hosts"
f" && chmod 644 /etc/hosts"
f't=$(mktemp /etc/.hosts.XXXXXX) && echo {hosts_b64} | base64 -d > "$t"'
' && chmod 644 "$t" && mv "$t" /etc/hosts || { rm -f "$t"; false; }'
)
# ── 3. /etc/mailname ─────────────────────────────────────────────
@@ -658,12 +450,13 @@ class ProxmoxSystemMixin:
)
# ── 4. Postfix myhostname ─────────────────────────────────────────
postfix = shlex.quote(f"myhostname = {fqdn}")
self._exec_ssh_command(
f"command -v postconf >/dev/null 2>&1 && postconf -e 'myhostname = {fqdn}' || true"
f"command -v postconf >/dev/null 2>&1 && postconf -e {postfix} || true"
)
# ── 5. Apply hostname at runtime ─────────────────────────────────
self._exec_ssh_command(f"hostname '{short_hostname}'")
self._exec_ssh_command(f"hostname {shlex.quote(short_hostname)}")
# ── 6. Migrate /etc/pve/nodes/<old> → /etc/pve/nodes/<new> ──────
# Proxmox stores VM and CT configs under /etc/pve/nodes/<nodename>/.
@@ -672,16 +465,15 @@ class ProxmoxSystemMixin:
# Without this step the node boots under the new hostname, finds an
# empty /etc/pve/nodes/<new>/ and all VMs appear missing.
if old_short and old_short != short_hostname:
pve_old = f"/etc/pve/nodes/{old_short}"
pve_new = f"/etc/pve/nodes/{short_hostname}"
pve_old = shlex.quote(f"/etc/pve/nodes/{old_short}")
pve_new = shlex.quote(f"/etc/pve/nodes/{short_hostname}")
migrate_out = self._exec_ssh_command(
f"if [ -d '{pve_old}' ] && [ ! -e '{pve_new}' ]; then"
f" mv '{pve_old}' '{pve_new}'"
f" && echo 'migrated {pve_old} -> {pve_new}';"
f"elif [ -d '{pve_new}' ]; then"
f"if [ -d {pve_old} ] && [ ! -e {pve_new} ]; then"
f" mv {pve_old} {pve_new} && echo migrated {pve_old} '->' {pve_new};"
f"elif [ -d {pve_new} ]; then"
f" echo 'target already exists, skipping migration';"
f"else"
f" echo 'source {pve_old} not found, skipping migration';"
f" echo source {pve_old} 'not found, skipping migration';"
f"fi"
)
logger.info("Proxmox node dir migration: %s", migrate_out)
+66
View File
@@ -0,0 +1,66 @@
"""Time sync on a Proxmox VE node and a Proxmox Backup Server (``TimeSyncMixin``).
Neither API keeps time servers: ``/nodes/{node}/time`` knows only the zone, and
both products run chrony on Debian. So the servers are
:class:`~napalm_device_types.PosixTimeSyncMixin`'s, over the driver's SSH session
(``run_command``, root): read from chrony's configuration, DHCP's apart, written to
``/etc/chrony/sources.d/netork.sources`` with every other configured source commented
out; the DHCP client's ``sourcedir`` stays.
The zone is read with them, from the host (``timedatectl``, the zone the node's
clock really runs in), and the API's ``GET /nodes/{node}/time`` answers only when
the host names none. It is written through ``PUT /nodes/{node}/time``, not
``timedatectl set-timezone``: Proxmox's own call validates the name and keeps
``/etc/timezone``, which its web UI and API show, in step with ``/etc/localtime``.
The token needs ``Sys.Modify`` for it (PVE on ``/nodes/{node}``, PBS on
``/system/time``).
One device is one node: in a PVE cluster every node has its own clock, and only
the node this connection resolved is read and written.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar
from napalm_device_types import TIME_SYNC_VALUES, PosixTimeSyncMixin, TimeSyncDict
from napalm_device_types.models import FixStepOutcomeDict
_JsonDict = dict[str, Any]
class ProxmoxTimeSyncMixin(PosixTimeSyncMixin):
"""Servers through chrony over SSH, the zone through the node's API."""
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _node_api(self) -> Any: ...
def _get_node_time(self) -> _JsonDict: ...
def get_time_sync(self) -> TimeSyncDict:
"""The node's time sources, zone and client: one round trip over SSH, and the
API's zone only where the host names none.
:raises ValueError: when the reading came back cut short.
:raises ConnectionException: when the node's shell could not be reached.
"""
found = super().get_time_sync()
if found["timezone"] is None:
found["timezone"] = self._get_node_time().get("timezone") or None
return found
def get_ntp_servers(self) -> dict[str, _JsonDict]:
"""NAPALM's shape of the servers ``get_time_sync`` reads, in chrony's order."""
return {server: {} for server in super().get_time_sync()["ntp_servers"]}
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
path = f"PUT /nodes/{self._node_name}/time"
try:
self._node_api().time.put(timezone=zone)
except Exception as exc:
return {"ok": False, "output": f"{path}: {exc}"}
return {"ok": True, "output": f"time zone set to {zone} ({path})"}
+75
View File
@@ -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]
+67
View File
@@ -0,0 +1,67 @@
"""The physical NICs a bridge leaves the node through (``NetworkTargetDict.uplinks``).
One group per way out of the bridge: a bond's slaves together, a single NIC alone.
Read from the node's network config (``GET /nodes/{node}/network``): a Linux
bridge names its ports in ``bridge_ports``, an OVS bridge in ``ovs_ports``. A
Linux bond lists its NICs in ``slaves``, an OVS bond in ``ovs_bonds``. Internal
ports (``OVSIntPort``) and VLAN subinterfaces are no uplinks: the first never
leaves the node, the second leaves it tagged, so the switch port's untagged
VLAN is not the bridge's.
"""
from __future__ import annotations
from typing import Any
#: Types of a port that is a physical NIC of its own.
_NIC_TYPES = frozenset({"eth", "OVSPort"})
#: Types of a port that leaves the node through its member NICs.
_BOND_TYPES = frozenset({"bond", "OVSBond"})
#: Types of a port that is no uplink.
_NOT_UPLINK_TYPES = frozenset({"vlan", "OVSIntPort"})
class _Unknown(Exception):
"""A port whose kind the network config does not tell."""
def _words(value: Any) -> list[str]:
return [w for w in str(value or "").split() if w != "none"]
def _nics_of(port: str, by_name: dict[str, dict[str, Any]], in_bond: bool = False) -> list[str]:
info = by_name.get(port)
if info is None:
raise _Unknown(port)
kind = info.get("type", "")
if kind in _BOND_TYPES:
return _bond_nics(info, by_name)
# An OVS bond's slave can come without a type of its own.
if kind in _NIC_TYPES or (in_bond and not kind):
# A VLAN subinterface added to an OVS bridge is an OVSPort too.
return [] if "." in port else [port]
if kind in _NOT_UPLINK_TYPES:
return []
raise _Unknown(port)
def _bond_nics(bond: dict[str, Any], by_name: dict[str, dict[str, Any]]) -> list[str]:
members = _words(bond.get("slaves") or bond.get("ovs_bonds"))
return [nic for member in members for nic in _nics_of(member, by_name, in_bond=True)]
def bridge_uplinks(bridge: dict[str, Any], network: list[dict[str, Any]]) -> list[list[str]] | None:
"""The physical NICs *bridge* leaves the node through, per port, or None when unknown.
An empty list is a bridge without uplink. None means a port is missing from
the network config or of a kind this cannot place — a guess would send the
caller to the wrong switch port.
"""
by_name = {iface["iface"]: iface for iface in network if iface.get("iface")}
ports = _words(bridge.get("ovs_ports") or bridge.get("bridge_ports"))
try:
groups = [_nics_of(port, by_name) for port in ports]
except _Unknown:
return None
return [group for group in groups if group]
+6
View File
@@ -120,6 +120,12 @@ def is_ovs_interface(iface_data: dict[str, Any]) -> bool:
return iface_data.get("type", "") in OVS_TYPES
def cpu_flags(node_status: dict[str, Any]) -> list[str] | None:
"""The CPU flags in a ``GET /nodes/{node}/status`` answer, None when it names none."""
flags = (node_status.get("cpuinfo") or {}).get("flags")
return None if flags is None else str(flags).split()
def is_sdn_vnet(name: str) -> bool:
return bool(re.fullmatch(r"vnet\d+", name))
+40 -10
View File
@@ -2,7 +2,9 @@
``power_vm`` stays for callers that already use it; these are what a
hypervisor-neutral caller talks to. They raise instead of returning a
``{"success": ...}`` dict, and block until Proxmox reports the task finished.
``{"success": ...}`` dict, and block until Proxmox reports the task finished —
except ``begin_stop_vm`` and ``shutdown_host``, which return once Proxmox took
the request (``VmStopRequestMixin``, ``HostShutdownMixin``).
"""
from __future__ import annotations
@@ -17,6 +19,9 @@ from napalm_device_types.models import (
VMPassthroughDict,
)
from napalm_proxmox.pve_values import PVE_9_3
from napalm_proxmox.vm_mixin import qemu_status
_JsonDict = dict[str, Any]
_POWER_TIMEOUT = 120
@@ -148,9 +153,9 @@ class ProxmoxVMContractMixin:
node = self._node_api()
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:
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:
raise RuntimeError(f"{action} of {vm_type} {vmid} failed: {exc}") from exc
if upid:
@@ -162,6 +167,14 @@ class ProxmoxVMContractMixin:
def stop_vm(self, name: str, force: bool = False) -> None:
self._run_power(*self._resolve_vm(name), "stop" if force else "shutdown")
def begin_stop_vm(self, name: str) -> None:
"""Ask for the guest's clean shutdown; return once Proxmox accepted it."""
vmid, vm_type = self._resolve_vm(name)
try:
self._guest_api(vmid, vm_type).status.shutdown.post()
except Exception as exc:
raise RuntimeError(f"shutdown of {vm_type} {vmid} refused: {exc}") from exc
def reboot_vm(self, name: str, force: bool = False) -> None:
vmid, vm_type = self._resolve_vm(name)
if not force:
@@ -178,16 +191,33 @@ class ProxmoxVMContractMixin:
raise RuntimeError(f"Proxmox cannot suspend container {vmid}")
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:
vmid, vm_type = self._resolve_vm(name)
cfg = self._guest_api(vmid, vm_type).config.get() or {}
return parse_vm_config(str(vmid), vm_type, cfg)
# -- the node itself --------------------------------------------------------
def reboot_host(self) -> None:
"""Restart this Proxmox node through the API (no SSH involved)."""
try:
self._node_api().status.post(command="reboot")
except Exception as exc:
raise RuntimeError(f"Reboot of node {self._node_name!r} refused: {exc}") from exc
+274
View File
@@ -0,0 +1,274 @@
"""HypervisorDriver migration methods for Proxmox VE: preflight, migrate, HA maintenance.
A guest is addressed like every other VM method of this driver: by vmid or name,
on the node the driver is connected to (``_resolve_vm``).
- ``get_vm_migration_preflight``: a VM asks ``GET .../qemu/{vmid}/migrate``; a
container has no such endpoint, so the online members are its candidates.
A member the cluster calls offline is refused (``"node offline"``) for both,
also where the VM endpoint would list it as allowed.
- ``migrate_vm``: ``POST .../{qemu|lxc}/{vmid}/migrate`` and the task is followed
to its end; a failure raises with the task log's ``ERROR:`` lines. A guest HA
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 guest is on the target, and on a failure reads the migration task's log.
- ``set_node_maintenance``: from PVE 9.3 ``PUT /nodes/{node}/maintenance``; an
older node has no REST endpoint for it, and the driver runs
``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
import logging
import shlex
from time import monotonic, sleep
from typing import TYPE_CHECKING, Any
from napalm_proxmox.migration import lxc_local, qemu_local, refusal, task_errors, upid_field
from napalm_proxmox.pve_values import PVE_9_3, to_flag
if TYPE_CHECKING:
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
from napalm_device_types import MigrationPreflightDict
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: Enough to reach the ERROR lines at the end of a long storage migration's log.
_TASK_LOG_LINES = 50000
_HA_POLL_SECONDS = 5
#: CRM states while the HA manager is moving a guest.
_HA_MOVING = frozenset({"migrate", "relocate"})
class ProxmoxVMMigrateMixin:
"""Relies on the driver, ``_resolve_vm``/``_guest_api``, ``_members`` and
``_wait_for_task``/``_run_node_command``/``_node_ssh``."""
_api: Any
_node_name: str
hostname: str
timeout: int
_node_api: Any
_resolve_vm: Any
_guest_api: Any
_members: Any
_wait_for_task: Any
_node_ssh: Any
_run_node_command: Any
_version_at_least: Any
# -- cluster membership -------------------------------------------------------
def _cluster_members(self) -> list[Any]:
status = self._api.cluster.status.get() or []
clustered = any(s.get("type") == "cluster" for s in status)
return list(self._members(status if clustered else []))
def _other_member(self, node: str) -> None:
names = [m.name for m in self._cluster_members()]
if node == self._node_name or node not in names:
raise ValueError(
f"{node!r} is not another member of the cluster of {self._node_name!r} "
f"(members: {', '.join(names)})"
)
def _storage_sharing(self) -> dict[str, bool]:
rows = self._api.cluster.resources.get(type="storage") or []
sharing: dict[str, bool] = {}
for row in rows:
if row.get("type") == "storage" and row.get("storage"):
name = str(row["storage"])
sharing[name] = sharing.get(name, False) or to_flag(row.get("shared"))
return sharing
# -- preflight ----------------------------------------------------------------
def get_vm_migration_preflight(self, name: str) -> MigrationPreflightDict:
"""Where the guest could move to within its cluster, and what blocks it."""
vmid, vm_type = self._resolve_vm(name)
others = [m for m in self._cluster_members() if m.name != self._node_name]
offline = [m.name for m in others if not m.online]
if vm_type == "vm":
return self._qemu_preflight(vmid, offline)
return self._lxc_preflight(vmid, [m.name for m in others if m.online], offline)
def _qemu_preflight(self, vmid: int, offline: list[str]) -> MigrationPreflightDict:
answer = self._guest_api(vmid, "vm").migrate.get() or {}
refused = {
str(node): refusal(blockers)
for node, blockers in (answer.get("not_allowed_nodes") or {}).items()
}
for node in offline:
refused[node] = "; ".join(filter(None, ["node offline", refused.get(node)]))
disks, resources = qemu_local(answer)
return {
"running": to_flag(answer.get("running")),
"allowed_nodes": [
str(n) for n in answer.get("allowed_nodes") or [] if n not in offline
],
"refused_nodes": refused,
"local_disks": disks,
"local_resources": resources,
}
def _lxc_running(self, vmid: int) -> bool:
status = self._guest_api(vmid, "container").status.current.get() or {}
return bool(status.get("status") == "running")
def _lxc_preflight(
self, vmid: int, online: list[str], offline: list[str]
) -> MigrationPreflightDict:
config = self._guest_api(vmid, "container").config.get() or {}
disks, resources = lxc_local(config, self._storage_sharing())
return {
"running": self._lxc_running(vmid),
"allowed_nodes": online,
"refused_nodes": {n: "node offline" for n in offline},
"local_disks": disks,
"local_resources": resources,
}
# -- migration ----------------------------------------------------------------
def migrate_vm(
self,
name: str,
target_node: str,
online: bool = True,
target_storage: str | None = None,
timeout: int = 3600,
) -> None:
"""Move the guest to *target_node*; block until Proxmox VE finished."""
vmid, vm_type = self._resolve_vm(name)
self._other_member(target_node)
deadline = monotonic() + timeout
params = self._qemu_params(vmid, online) if vm_type == "vm" else self._lxc_params(vmid)
if target_storage:
params["targetstorage" if vm_type == "vm" else "target-storage"] = target_storage
try:
upid = str(self._guest_api(vmid, vm_type).migrate.post(target=target_node, **params))
except Exception as exc:
raise RuntimeError(
f"Migration of {vm_type} {vmid} to {target_node!r} refused: {exc}"
) from exc
self._follow_task(upid, vmid, timeout)
if upid_field(upid, 5) == "hamigrate":
self._follow_ha(vmid, vm_type, target_node, deadline, upid)
def _qemu_params(self, vmid: int, online: bool) -> dict[str, Any]:
answer = self._guest_api(vmid, "vm").migrate.get() or {}
params: dict[str, Any] = {}
if online and to_flag(answer.get("running")):
params["online"] = 1
if qemu_local(answer)[0]:
params["with-local-disks"] = 1
return params
def _lxc_params(self, vmid: int) -> dict[str, Any]:
# A container cannot move while running; restart mode stops and restarts it.
return {"restart": 1} if self._lxc_running(vmid) else {}
def _task_errors(self, upid: str) -> list[str]:
try:
log = self._node_api().tasks(upid).log.get(limit=_TASK_LOG_LINES) or []
except Exception as exc:
logger.debug("Cannot read the log of task %s: %s", upid, exc)
return []
return task_errors(log)
def _follow_task(self, upid: str, vmid: int, timeout: int) -> None:
try:
self._wait_for_task(upid, timeout=timeout)
except RuntimeError as exc:
errors = self._task_errors(upid)
if not errors:
raise
raise RuntimeError(f"Migration of guest {vmid} failed: {'; '.join(errors)}") from exc
# -- a guest HA manages -------------------------------------------------------
def _ha_state(self, sid: str) -> tuple[str | None, str | None]:
rows = self._api.cluster.ha.status.current.get() or []
service: _JsonDict = next((r for r in rows if r.get("sid") == sid), {})
return service.get("node"), service.get("crm_state") or service.get("state")
def _follow_ha(
self, vmid: int, vm_type: str, target: str, deadline: float, ha_upid: str
) -> None:
sid = f"{'vm' if vm_type == 'vm' else 'ct'}:{vmid}"
moving_seen = False
while True:
node, state = self._ha_state(sid)
if node == target and state not in _HA_MOVING:
return
if state == "error":
self._ha_failed(vmid, vm_type, ha_upid, f"HA manager put {sid} into error state")
if state in _HA_MOVING:
moving_seen = True
elif moving_seen:
self._ha_failed(
vmid, vm_type, ha_upid, f"HA manager left {sid} on {node} ({state})"
)
if monotonic() > deadline:
raise RuntimeError(
f"Migration of {sid} to {target!r} timed out on {node} ({state})"
)
sleep(_HA_POLL_SECONDS)
def _ha_failed(self, vmid: int, vm_type: str, ha_upid: str, what: str) -> None:
"""Raise *what* with the ERROR lines of the migration the HA manager ran."""
errors: list[str] = []
kind = "qmigrate" if vm_type == "vm" else "vzmigrate"
try:
tasks = self._node_api().tasks.get(vmid=vmid, typefilter=kind, limit=1) or []
since = int(upid_field(ha_upid, 4) or "0", 16)
if tasks and int(tasks[0].get("starttime") or 0) >= since:
errors = self._task_errors(str(tasks[0].get("upid")))
except Exception as exc:
logger.debug("Cannot find the migration task of guest %s: %s", vmid, exc)
raise RuntimeError(f"{what}: {'; '.join(errors)}" if errors else what)
# -- HA maintenance -----------------------------------------------------------
def set_node_maintenance(self, node: str, enabled: bool) -> None:
"""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()]
if node not in names:
raise ValueError(
f"{node!r} is not a member of the cluster (members: {', '.join(names)})"
)
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:
self._node_ssh()
except Exception as exc:
raise RuntimeError(
f"Cannot {action} HA maintenance of node {node!r}: SSH to {self.hostname} "
f"is not available ({exc})"
) from exc
command = f"ha-manager crm-command node-maintenance {action} {shlex.quote(node)}"
try:
self._run_node_command(command, timeout=self.timeout)
except Exception as exc:
raise RuntimeError(
f"ha-manager refused to {action} maintenance of {node!r}: {exc}"
) from exc
+51 -6
View File
@@ -20,10 +20,26 @@ import logging
import re
from typing import Any
from napalm_proxmox.pve_values import PVE_9_3
logger = logging.getLogger(__name__)
_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:
"""Mixin providing VM and container NAPALM methods."""
@@ -215,7 +231,7 @@ class ProxmoxVMMixin:
* vmid (str) - Proxmox VM/container ID, e.g. ``"100"``
* name (str) - display name
* type (str) - ``"vm"`` or ``"container"``
* status (str) - ``"running"``, ``"stopped"``, etc.
* status (str) - ``"running"``, ``"stopped"``, ``"paused"`` (``qemu_status``)
* vcpus (int) - allocated vCPUs
* memory (int) - configured RAM in megabytes
* 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
* interfaces (dict) - network interfaces (NAPALM format + ipv4 field)
* 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] = []
# QEMU VMs
# QEMU VMs; only the full status has ``qmpstatus``, which tells paused from running.
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))
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)
uptime = int(vm.get("uptime", 0) or 0)
@@ -321,7 +337,36 @@ class ProxmoxVMMixin:
except Exception as 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_KEYS_VM = re.compile(r"^(scsi|virtio|ide|sata)\d+$")
+202 -199
View File
@@ -3,10 +3,10 @@
from __future__ import annotations
import base64
import hashlib
import ipaddress
import logging
import re
import shlex
import time
from typing import TYPE_CHECKING, Any
from urllib.parse import quote
@@ -21,10 +21,16 @@ from napalm_device_types.models import (
from napalm_device_types.provisioning import (
QEMU_GUEST_AGENTS,
GuestAgents,
VMProvisionIncomplete,
network_config,
split_compression,
)
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.utils import cpu_flags
from napalm_proxmox.vm_mixin import qemu_status
if TYPE_CHECKING:
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
# pyproject.toml, and nothing here needs it at runtime.
@@ -77,12 +83,6 @@ _HOST_CPU_DESCRIPTION = (
# download cost once.
_IMAGE_CACHE_DIR = "/var/lib/vz/template/netork-images"
# Proxmox reads an import volume's format off its extension and accepts only
# these. Ubuntu ships its qcow2 cloud images as ".img", so that is stored as
# qcow2: if an .img is really raw, the import fails loudly, whereas guessing
# raw for a qcow2 would attach the qcow2 container as a raw disk silently.
_IMPORT_EXTENSIONS = {"qcow2": "qcow2", "raw": "raw", "vmdk": "vmdk", "img": "qcow2"}
# The VM shell each guest needs. OpenBSD's qemu-ga cannot use virtio-serial,
# and over ISA serial it answers only as the second port (cua01): the OpenBSD
# cloud image keeps its console on com0, which serial0 takes (netork#793).
@@ -92,39 +92,34 @@ _GUEST_VM_SETTINGS: dict[str, dict[str, str]] = {
"openbsd": {"ostype": "other", "agent": "1,type=isa", "serial0": "socket"},
}
# A snippet's file name: one plain name in the snippets directory, no path.
_SNIPPET_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+=-]*")
# A NIC as Proxmox reports it: "virtio=BC:24:11:AA:BB:02,bridge=vmbr0".
_NIC_MAC = re.compile(r"^[a-z0-9]+=([0-9A-Fa-f:]{17})")
# Characters Proxmox keeps in a content file name (PVE::Storage's
# SAFE_CHAR_CLASS_RE); anything else it would rewrite behind our back.
_UNSAFE_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9\-.+=_]")
def _nic_config_args(nics: list[dict[str, Any]]) -> dict[str, str]:
"""``{"net<i>": "virtio[=<mac>],bridge=<bridge>[,tag=|,trunks=]"}`` per NIC."""
config_args: dict[str, str] = {}
for i, nic in enumerate(nics):
bridge = nic.get("bridge")
if not bridge:
raise ValueError(f"NIC {i}: bridge is required")
def _url_key(image_url: str) -> str:
"""Short hash of the full URL — Ubuntu and others publish a new build
under the same basename every day, so the basename alone is no cache key."""
return hashlib.sha256(image_url.encode()).hexdigest()[:12]
# Build base config: model[=mac] + bridge
mac = nic.get("mac")
net_config = f"virtio={mac},bridge={bridge}" if mac else f"virtio,bridge={bridge}"
# Add VLAN configuration (access vs trunk)
if "trunk_vlan_tags" in nic and nic["trunk_vlan_tags"]:
vlan_list = ";".join(str(v) for v in nic["trunk_vlan_tags"])
net_config += f",trunks={vlan_list}"
elif "vlan_tag" in nic and nic["vlan_tag"] is not None:
net_config += f",tag={nic['vlan_tag']}"
def _split_checksum(image_checksum: str) -> tuple[str, str]:
"""``"<algo>:<hex>"`` as ``(algo, hex)``; the algorithm defaults to sha256."""
algo, _, expected = image_checksum.partition(":")
return (algo or "sha256").lower(), expected
def _import_volume_name(image_url: str) -> str | None:
"""The file name *image_url* gets in an import storage.
None when Proxmox cannot import the image's type at all (compressed,
ISO, no extension) — provisioning then downloads it over SSH as before.
"""
basename = image_url.rstrip("/").rsplit("/", 1)[-1]
stem, dot, ext = basename.rpartition(".")
extension = _IMPORT_EXTENSIONS.get(ext.lower()) if dot and stem else None
if extension is None:
return None
safe_stem = _UNSAFE_FILENAME_CHARS.sub("_", stem)
return f"netork-{_url_key(image_url)}-{safe_stem}.{extension}"
config_args[f"net{i}"] = net_config
return config_args
class ProxmoxVMProvisionMixin:
@@ -138,10 +133,10 @@ class ProxmoxVMProvisionMixin:
"""
Execute a shell command on the Proxmox node via SSH, raising on failure.
Unlike ``_exec_ssh_command`` (best-effort, fixed timeout, swallows
errors), this is for critical provisioning steps — image download,
disk import — where a non-zero exit or a caller-specific timeout must
surface as a hard failure rather than an empty string.
Unlike ``_exec_ssh_command`` (fixed timeout, exit status not checked),
this is for critical provisioning steps — image download, disk import —
where a non-zero exit or a caller-specific timeout must surface as a
hard failure.
"""
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=timeout)
exit_status = stdout.channel.recv_exit_status()
@@ -170,38 +165,26 @@ class ProxmoxVMProvisionMixin:
once (covers a corrupted/partial transfer or a stale same-keyed file)
before raising.
"""
filename = image_url.rstrip("/").rsplit("/", 1)[-1]
local_path = f"{_IMAGE_CACHE_DIR}/{_url_key(image_url)}-{filename}"
algo, expected = _split_checksum(image_checksum or "")
local_path = f"{_IMAGE_CACHE_DIR}/{cache_name(image_url)}"
algo, expected = split_checksum(image_checksum or "")
max_attempts = 2
for attempt in range(1, max_attempts + 1):
exists = self._run_node_command(
f"mkdir -p {_IMAGE_CACHE_DIR} && test -f {local_path} "
f"&& echo EXISTS || echo MISSING",
timeout=30,
)
if "EXISTS" not in exists:
_logger.info(f"Downloading cloud image {image_url} -> {local_path}")
self._run_node_command(
f"wget -q -O {local_path}.tmp '{image_url}' "
f"&& mv {local_path}.tmp {local_path}",
timeout=timeout,
)
if not self._cached_on_node(local_path):
self._fetch_image(image_url, local_path, timeout)
if not image_checksum:
return local_path
actual = self._run_node_command(
f"{algo}sum {local_path} | awk '{{print $1}}'", timeout=60
f"{algo}sum {shlex.quote(local_path)} | awk '{{print $1}}'", timeout=60
)
if actual.lower() == expected.lower():
return local_path
# Remove the bad file so the next attempt re-downloads instead of
# reusing it.
self._run_node_command(f"rm -f {local_path}", timeout=30)
self._run_node_command(f"rm -f {shlex.quote(local_path)}", timeout=30)
if attempt == max_attempts:
raise RuntimeError(
f"Checksum mismatch for {image_url}: expected {expected}, got {actual}"
@@ -213,6 +196,30 @@ class ProxmoxVMProvisionMixin:
raise AssertionError("unreachable") # loop always returns or raises above
def _cached_on_node(self, path: str) -> bool:
"""Whether *path* is already in the node's image cache (made if missing)."""
found = self._run_node_command(
f"mkdir -p {shlex.quote(_IMAGE_CACHE_DIR)} && test -f {shlex.quote(path)} "
"&& echo EXISTS || echo MISSING",
timeout=30,
)
return "EXISTS" in found
def _fetch_image(self, image_url: str, local_path: str, timeout: int) -> None:
"""Download *image_url* to *local_path* on the node, through a ``.tmp``.
wget runs with ``-nv`` so its reason ("No space left on device")
reaches the error, and a failed download leaves no partial ``.tmp``.
"""
_logger.info(f"Downloading cloud image {image_url} -> {local_path}")
tmp = shlex.quote(f"{local_path}.tmp")
path = shlex.quote(local_path)
self._run_node_command(
f"wget -nv -O {tmp} {shlex.quote(image_url)} && mv {tmp} {path} "
f"|| {{ s=$?; rm -f {tmp}; exit $s; }}",
timeout=timeout,
)
def _cloud_image_on_node(self, image_url: str, image_checksum: str | None, timeout: int) -> str:
"""The node path of the image, downloaded, verified and unpacked.
@@ -221,22 +228,19 @@ class ProxmoxVMProvisionMixin:
the unpacked file is kept. Proxmox's download-url unpacks ISOs only,
so a packed image always comes this way.
"""
filename = image_url.rstrip("/").rsplit("/", 1)[-1]
unpacked_name, unpack = split_compression(filename)
unpacked_name, unpack = split_compression(cache_name(image_url))
if unpack is None:
return self._download_cloud_image(image_url, image_checksum, timeout=timeout)
unpacked = f"{_IMAGE_CACHE_DIR}/{_url_key(image_url)}-{unpacked_name}"
cached = self._run_node_command(
f"mkdir -p {_IMAGE_CACHE_DIR} && test -f {unpacked} && echo EXISTS || echo MISSING",
timeout=30,
)
if "EXISTS" in cached:
unpacked = f"{_IMAGE_CACHE_DIR}/{unpacked_name}"
if self._cached_on_node(unpacked):
return unpacked
packed = self._download_cloud_image(image_url, image_checksum, timeout=timeout)
_logger.info(f"Unpacking {packed} -> {unpacked}")
tmp = shlex.quote(f"{unpacked}.tmp")
self._run_node_command(
f"{unpack} {packed} > {unpacked}.tmp && mv {unpacked}.tmp {unpacked} && rm -f {packed}",
f"{unpack} {shlex.quote(packed)} > {tmp} && mv {tmp} {shlex.quote(unpacked)} "
f"&& rm -f {shlex.quote(packed)}",
timeout=timeout,
)
return unpacked
@@ -248,12 +252,17 @@ class ProxmoxVMProvisionMixin:
{iso, vztmpl, import} — "snippets" is rejected outright ("does not
have a value in the enumeration"). Snippets can only be written
directly to the filesystem, so this goes over SSH.
:raises ValueError: for a *filename* that is not one plain file name.
"""
if not _SNIPPET_NAME.fullmatch(filename):
raise ValueError(f"not a snippet file name: {filename!r}")
_logger.debug(f"Writing Cloud-Init snippet {filename} to {storage_path}/snippets")
encoded = base64.b64encode(content.encode("utf-8")).decode("ascii")
snippets = f"{storage_path}/snippets"
self._run_node_command(
f"mkdir -p {storage_path}/snippets && "
f"echo {encoded} | base64 -d > {storage_path}/snippets/{filename}",
f"mkdir -p {shlex.quote(snippets)} && echo {encoded} | base64 -d > "
f"{shlex.quote(f'{snippets}/{filename}')}",
timeout=30,
)
@@ -308,7 +317,7 @@ class ProxmoxVMProvisionMixin:
params: dict[str, Any] = {"url": image_url, "content": "import", "filename": filename}
if image_checksum:
algo, expected = _split_checksum(image_checksum)
algo, expected = split_checksum(image_checksum)
params["checksum"] = expected
params["checksum-algorithm"] = algo
_logger.info(f"Downloading cloud image {image_url} into {volid}")
@@ -333,7 +342,8 @@ class ProxmoxVMProvisionMixin:
local_path = self._cloud_image_on_node(image_url, image_checksum, download_timeout)
_logger.info(f"Importing {local_path} into VM {vmid} on storage {image_storage}")
self._run_node_command(
f"qm importdisk {vmid} {local_path} {image_storage} --format qcow2",
f"qm importdisk {int(vmid)} {shlex.quote(local_path)} {shlex.quote(image_storage)} "
"--format qcow2",
timeout=timeout,
)
@@ -365,7 +375,7 @@ class ProxmoxVMProvisionMixin:
verifies and copies the image itself — and over SSH otherwise.
"""
import_storage = self._find_import_storage()
filename = _import_volume_name(image_url) if import_storage else None
filename = import_volume_name(image_url) if import_storage else None
if not import_storage or not filename:
self._import_over_ssh(
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
@@ -455,8 +465,7 @@ class ProxmoxVMProvisionMixin:
return self._cpu_types_for(self._node_cpu_flags())
def _node_cpu_flags(self) -> set[str]:
status = self._node_api().status.get() or {}
return set(str((status.get("cpuinfo") or {}).get("flags", "")).split())
return set(cpu_flags(self._node_api().status.get() or {}) or [])
@staticmethod
def _cpu_types_for(node_flags: set[str]) -> list[VMCpuTypeDict]:
@@ -531,6 +540,19 @@ class ProxmoxVMProvisionMixin:
time.sleep(2)
def _check_placement(self, guest_os: str, node: str | None) -> None:
"""Refuse a guest this driver cannot provision, or a node other than its own."""
if guest_os not in self.GUEST_AGENTS:
raise ValueError(
f"Cannot provision a {guest_os!r} guest; this driver provisions "
f"{', '.join(sorted(self.GUEST_AGENTS))}"
)
if node is not None and node != self._node_name:
raise ValueError(
f"Cannot create a VM on node {node!r} through {self._node_name!r}; "
f"connect to {node!r} itself"
)
def create_vm_from_cloud_init(
self,
name: str,
@@ -546,6 +568,7 @@ class ProxmoxVMProvisionMixin:
storage: str | None = None,
cpu_type: str | None = None,
guest_os: str = "linux",
node: str | None = None,
download_timeout: int = 300,
timeout: int = 180,
) -> VMProvisionResultDict:
@@ -583,6 +606,9 @@ class ProxmoxVMProvisionMixin:
OS type and how the agent is attached; a guest other than Linux
also gets a network-config v2 snippet of its own, because
FreeBSD's nuageinit skips runcmd on the v1 Proxmox writes.
node: the cluster node to create on; only this driver's own node
(None = that node). netOrk creates on another node through
that node's own device.
download_timeout: max seconds for the image download (skipped if cached)
timeout: max seconds for the remaining provisioning steps
@@ -590,16 +616,18 @@ class ProxmoxVMProvisionMixin:
{"vmid": str, "name": str, "node": str}
Raises:
RuntimeError: provisioning failure (download, import, config, timeout, etc.)
ValueError: invalid storage or configuration, or a cpu_type that is
unknown or that this node's CPU cannot run (raised before
anything is created)
VMProvisionIncomplete: any failure once the VM shell exists (download,
import, storage, NIC or snippet config, start, timeout, ...); a
RuntimeError that carries the half-built VM's vmid and node, with
the failure as its cause
RuntimeError: a failure taking the VMID or creating the shell (no VM
is left behind)
ValueError: a cpu_type that is unknown or that this node's CPU cannot
run, a guest_os it cannot provision, or another node (raised
before anything is created)
"""
if guest_os not in self.GUEST_AGENTS:
raise ValueError(
f"Cannot provision a {guest_os!r} guest; this driver provisions "
f"{', '.join(sorted(self.GUEST_AGENTS))}"
)
self._check_placement(guest_os, node)
created: int | None = None # the VMID once the shell exists on the node
try:
_logger.info(f"Creating {guest_os} VM '{name}' from image {image_url}")
cpu_model = self._resolve_cpu_type(cpu_type)
@@ -623,6 +651,7 @@ class ProxmoxVMProvisionMixin:
# queries (below) would have nothing to talk to.
**_GUEST_VM_SETTINGS[guest_os],
)
created = vmid
# Step 3: Download cloud image (cached) and import as root disk
image_storage = storage or self._find_default_image_storage()
@@ -632,29 +661,7 @@ class ProxmoxVMProvisionMixin:
# Step 4: Configure network interfaces (CPU/memory already set at shell creation)
_logger.info(f"Configuring {len(nics)} NIC(s) for VM {vmid}")
config_args: dict[str, Any] = {}
# Build NIC config strings generically
for i, nic in enumerate(nics):
bridge = nic.get("bridge")
if not bridge:
raise ValueError(f"NIC {i}: bridge is required")
# Build base config: model[=mac] + bridge
mac = nic.get("mac")
net_config = f"virtio={mac},bridge={bridge}" if mac else f"virtio,bridge={bridge}"
# Add VLAN configuration (access vs trunk)
if "trunk_vlan_tags" in nic and nic["trunk_vlan_tags"]:
vlan_list = ";".join(str(v) for v in nic["trunk_vlan_tags"])
net_config += f",trunks={vlan_list}"
elif "vlan_tag" in nic and nic["vlan_tag"] is not None:
net_config += f",tag={nic['vlan_tag']}"
config_args[f"net{i}"] = net_config
self._node_api().qemu(vmid).config.post(**config_args)
self._node_api().qemu(vmid).config.post(**_nic_config_args(nics))
# Step 5: Verify snippet storage exists
# (enabled is absent-not-falsy, and node-scoping matters — see
@@ -721,9 +728,9 @@ class ProxmoxVMProvisionMixin:
cloud_init_args[f"ipconfig{i}"] = "ip=dhcp"
if ssh_public_keys:
# URL-encode SSH keys for Proxmox API
sshkeys = ";".join(ssh_public_keys)
cloud_init_args["sshkeys"] = quote(sshkeys)
# One key per line, URL-encoded without exception: Proxmox's
# "urlencoded" format refuses an unescaped "/" or "+".
cloud_init_args["sshkeys"] = quote("\n".join(ssh_public_keys), safe="")
self._node_api().qemu(vmid).config.post(**cloud_init_args)
@@ -762,7 +769,10 @@ class ProxmoxVMProvisionMixin:
except Exception as e:
_logger.exception(f"Failed to create VM '{name}': {e}")
raise
if created is None:
raise
# The VM stays behind half built; the caller removes it by its id.
raise VMProvisionIncomplete(str(e), vmid=str(created), node=self._node_name) from e
def destroy_vm(
self,
@@ -804,16 +814,7 @@ class ProxmoxVMProvisionMixin:
snippets = self._cicustom_snippets(vmid_int)
# Step 2: Delete VM
# Proxmox's API parameter is hyphenated (destroy-unreferenced-disks),
# not a valid Python identifier — proxmoxer forwards kwargs to the
# request verbatim with no underscore-to-hyphen translation, so this
# must be built as a dict and unpacked rather than passed as a kwarg.
_logger.debug(f"Deleting VM {vmid} configuration and disks")
delete_params = {
"purge": 1,
"destroy-unreferenced-disks": 1 if remove_disk else 0,
}
self._node_api().qemu(vmid_int).delete(**delete_params)
self._delete_vm(vmid_int, remove_disk, timeout)
# Step 3: Clean up Cloud-Init snippets
# (This is best-effort; snippet files may be unreachable if storage is unavailable)
@@ -830,6 +831,21 @@ class ProxmoxVMProvisionMixin:
_logger.exception(f"Failed to destroy VM {vmid}: {e}")
raise
def _delete_vm(self, vmid: int, remove_disk: bool, timeout: int) -> None:
"""Delete the VM and wait for it to be gone: the delete is a task."""
_logger.debug(f"Deleting VM {vmid} configuration and disks")
# Proxmox's API parameter is hyphenated (destroy-unreferenced-disks),
# not a valid Python identifier — proxmoxer forwards kwargs to the
# request verbatim with no underscore-to-hyphen translation, so this
# must be built as a dict and unpacked rather than passed as a kwarg.
delete_params = {
"purge": 1,
"destroy-unreferenced-disks": 1 if remove_disk else 0,
}
upid = self._node_api().qemu(vmid).delete(**delete_params)
if upid:
self._wait_for_task(upid, timeout=timeout)
def _cicustom_snippets(self, vmid: int) -> list[tuple[str, str]]:
"""``(storage, path)`` of every snippet the VM's cicustom names.
@@ -859,6 +875,11 @@ class ProxmoxVMProvisionMixin:
"""
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
management NIC (net0), useful after provisioning.
@@ -870,70 +891,36 @@ class ProxmoxVMProvisionMixin:
Returns:
{"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:
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:
vmid_int = int(vmid)
vm = self._node_api().qemu(int(vmid))
_logger.debug(f"Getting status for VM {vmid}")
# VM must exist / be readable before we start polling.
try:
self._node_api().qemu(vmid_int).config.get()
except Exception:
# VM may not exist yet or config not readable
# The VM must exist / be readable before we start polling.
status = self._qemu_current_status(vm, vmid)
if status is None:
return {"status": "unknown"}
# Polling loop
start_time = time.time()
while True:
elapsed = time.time() - start_time
if wait_for_ip and elapsed > timeout:
if status != "running":
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")
try:
# Query guest-agent network interfaces. 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 = (
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}")
address = self._guest_agent_address(vm, vmid)
if address is not None:
return {"status": "running", **address}
if not wait_for_ip:
# Return immediate status without IP
return {"status": "running"}
# Wait before next poll
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:
raise
@@ -941,6 +928,48 @@ class ProxmoxVMProvisionMixin:
_logger.exception(f"Error getting status for VM {vmid}: {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]:
"""
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
@@ -948,35 +977,9 @@ class ProxmoxVMProvisionMixin:
Excludes physical NICs, bonds, and other non-bridge interface types —
those are never valid ``NICConfigDict.bridge`` values on Proxmox.
"""
targets: list[NetworkTargetDict] = []
for iface in self._get_node_network():
iface_type = iface.get("type")
name = iface.get("iface", "")
if not name:
continue
if iface_type == "bridge":
vlan_aware = bool(int(iface.get("bridge_vlan_aware", 0) or 0))
targets.append({"name": name, "kind": "bridge", "vlan_aware": vlan_aware})
elif iface_type == "OVSBridge":
# OVS bridges tag per-port regardless of a dedicated "VLAN aware" setting.
targets.append({"name": name, "kind": "bridge", "vlan_aware": True})
targets = bridge_targets(self._get_node_network())
for vnet in self._get_sdn_vnets():
name = vnet.get("vnet", "")
if not name:
continue
# A vnet's VLAN is already fixed by its zone/tag — no separate vlan_tag applies.
tag = vnet.get("tag")
fixed_vlan_tag = int(tag) if tag is not None else None
targets.append(
{
"name": name,
"kind": "vnet",
"vlan_aware": False,
"fixed_vlan_tag": fixed_vlan_tag,
}
)
target = vnet_target(vnet)
if target is not None:
targets.append(target)
return targets
+78
View File
@@ -0,0 +1,78 @@
"""A native Zabbix agent on a Proxmox node: napalm-device-types' ``ZabbixAgentMixin``.
A node runs no container engine (NetOrk/netork#2571). The template installs Debian's
``zabbix-agent`` -- or, where Debian has none, Zabbix's from its repository -- and
enables and restarts it. This writes the caller's values into
``/etc/zabbix/zabbix_agentd.conf`` and opens tcp/``listen_port`` in ufw where the node
has it; pve-firewall's rules are the operator's, as for the SNMP agent. The node's
shell runs as root.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from napalm_device_types import (
ZABBIX_AGENT_PURPOSE,
FixStepOutcomeDict,
ZabbixAgentMixin,
ZabbixAgentSettingsDict,
zabbix_agent_config,
zabbix_repository_command,
)
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
"""``zabbix-agent`` from Debian, or else from Zabbix's repository."""
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
os_release, status = self._rc("cat /etc/os-release")
if status != 0:
return {"ok": False, "output": f"reading /etc/os-release: {os_release[-300:]}"}
try:
command = zabbix_repository_command(os_release, release)
except ValueError as exc:
return {"ok": False, "output": str(exc)}
return self._step(command, f"Zabbix {release} repository added")
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
text, status = self._rc(f"cat {CONFIG}")
if status != 0:
return {"ok": False, "output": f"reading {CONFIG}: {text[-300:]}"}
# _rc strips the output; the file ends with a newline.
new, changes = zabbix_agent_config(f"{text}\n", settings)
if not changes:
return {"ok": True, "output": f"{CONFIG} already says it"}
kept = self._step(f"cp -p {CONFIG} {CONFIG}.bak", "")
if not kept["ok"]:
return kept
written = self._write_root_file(CONFIG, new)
if not written["ok"]:
return written
return {"ok": True, "output": "; ".join(changes)}
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
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
def _rc(self, command: str) -> tuple[str, int]: ...
def _step(self, command: str, done: str) -> FixStepOutcomeDict: ...
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
def _allow_sources(
self, allowed: list[str], port: int, proto: str, purpose: str
) -> FixStepOutcomeDict: ...
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ...
+8 -10
View File
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-proxmox"
version = "0.8.0"
description = "NAPALM driver for Proxmox VE (classic Linux networking, SDN, OVS)"
version = "0.14.0"
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
readme = "README.md"
license = "Apache-2.0"
authors = [{ name = "Christian Manivong" }]
@@ -15,16 +15,14 @@ classifiers = [
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: System :: Networking",
]
requires-python = ">=3.10"
requires-python = ">=3.12"
dependencies = [
"napalm>=5.0.0",
"napalm_device_types>=4.22.0",
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for SSH fallback (driver.py)
"napalm_device_types>=4.44.0", # CredentialExpiryMixin, UpdateHistoryDict, VMDict.uid
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
"proxmoxer>=2.0.0",
"netaddr>=0.9.0",
"requests>=2.31.0",
@@ -35,6 +33,7 @@ dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6"]
[project.entry-points."napalm.drivers"]
proxmox = "napalm_proxmox:ProxmoxDriver"
proxmox_backup = "napalm_proxmox:ProxmoxBackupDriver"
[project.urls]
Repository = "https://git.netork.io/NAPALM/napalm-proxmox"
@@ -50,7 +49,7 @@ napalm_proxmox = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
@@ -60,7 +59,7 @@ select = ["E", "F", "I", "UP", "B"]
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
@@ -75,7 +74,6 @@ module = [
"napalm_proxmox.config_mixin",
"napalm_proxmox.driver",
"napalm_proxmox.interfaces_mixin",
"napalm_proxmox.lldp_mixin",
"napalm_proxmox.routing_mixin",
"napalm_proxmox.sdn_mixin",
"napalm_proxmox.system_mixin",
+34 -8
View File
@@ -96,8 +96,6 @@ SDN_SUBNETS_VNET2: list = []
# driver bug rather than bad test data.
DNS_INFO = {"search": "example.com", "dns1": "8.8.8.8"}
NTP_INFO = {"server": "pool.ntp.org,time.cloudflare.com"}
NODE_NETSTAT = [
{
"dev": "eth0",
@@ -120,6 +118,36 @@ PVE_USERS = [
]
# ---------------------------------------------------------------------------
# The node's shell
# ---------------------------------------------------------------------------
class _Stream:
def __init__(self, data: str) -> None:
self._data = data.encode()
def read(self) -> bytes:
return self._data
class NodeShell:
"""The node's SSH session for the driver fixtures.
Every command prints ``output`` on stdout, or ``outputs[command]`` when the
command is there. A test sets either through ``driver._node_ssh()``.
"""
def __init__(self, output: str = "") -> None:
self.output = output
self.outputs: dict[str, str] = {}
self.commands: list[str] = []
def exec_command(self, command: str, timeout: int | None = None):
self.commands.append(command)
return None, _Stream(self.outputs.get(command, self.output)), _Stream("")
# ---------------------------------------------------------------------------
# Driver fixture
# ---------------------------------------------------------------------------
@@ -134,10 +162,8 @@ def _build_mock_api(
sdn_vnets=None,
sdn_subnets=None,
dns=None,
ntp=None,
netstat=None,
pve_users=None,
exec_return="",
sensors=None,
cluster_status=None,
):
@@ -157,9 +183,7 @@ def _build_mock_api(
node_res.status.get.return_value = node_status or NODE_STATUS
node_res.network.get.return_value = network if network is not None else NODE_NETWORK
node_res.dns.get.return_value = dns or DNS_INFO
node_res.ntp.get.return_value = ntp or NTP_INFO
node_res.netstat.get.return_value = netstat or NODE_NETSTAT
node_res.execute.post.return_value = {"data": exec_return}
node_res.hardware.sensors.get.return_value = sensors or []
node_res.time.get.return_value = {}
node_res.subscription.get.return_value = {}
@@ -204,12 +228,13 @@ def driver():
mock_api = _build_mock_api()
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
drv.open()
drv._node_ssh = MagicMock(return_value=NodeShell())
return drv
@pytest.fixture
def driver_with_exec(request):
"""Return a driver whose exec endpoint returns a parametrised string."""
"""Return a driver whose node shell prints a parametrised string."""
exec_output = getattr(request, "param", "")
drv = ProxmoxDriver(
hostname="pve1.example.com",
@@ -217,7 +242,8 @@ def driver_with_exec(request):
password="secret",
optional_args={"verify_ssl": False},
)
mock_api = _build_mock_api(exec_return=exec_output)
mock_api = _build_mock_api()
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
drv.open()
drv._node_ssh = MagicMock(return_value=NodeShell(exec_output))
return drv
+2159
View File
File diff suppressed because it is too large. Load diff
+99
View File
@@ -0,0 +1,99 @@
"""A stand-in for proxmoxer's PBS client, answering from recorded responses.
``tests/fixtures/pbs_api.json`` holds what a real Proxmox Backup Server 4.2
answered (sanitised). Paths a test adds on top -- backup groups, snapshots and
jobs, which that server did not have yet -- follow the shapes of the PBS API
schema (``pbs.proxmox.com/docs/api-viewer``).
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
from proxmoxer.core import ResourceException
RECORDED: dict[str, Any] = json.loads(
(Path(__file__).parent / "fixtures" / "pbs_api.json").read_text()
)
def _key(path: str, params: dict[str, Any]) -> str:
query = "&".join(f"{k}={params[k]}" for k in sorted(params))
return f"{path.strip('/')}?{query}" if query else path.strip("/")
class _Resource:
"""proxmoxer's chained form: ``api.nodes("localhost").status.get()``."""
def __init__(self, api: FakePbsApi, path: str) -> None:
self._api, self._path = api, path
def __getattr__(self, name: str) -> _Resource:
return _Resource(self._api, f"{self._path}/{name}")
def __call__(self, segment: str) -> _Resource:
return _Resource(self._api, f"{self._path}/{segment}")
def get(self, **params: Any) -> Any:
return self._api.get(self._path, **params)
def post(self, **params: Any) -> Any:
return self._api.post(self._path, **params)
def put(self, **params: Any) -> Any:
return self._api.put(self._path, **params)
class FakePbsApi:
"""``get``/``post``/``put``/``delete`` by path, like ``ProxmoxAPI.get("admin/gc")``,
or chained, like ``ProxmoxAPI.nodes("localhost").status.get()``.
A response is looked up as ``"path?k=v&..."`` first, then as ``"path"``. A
value that is an exception is raised. Every call is recorded in ``calls``.
"""
def __init__(self, **overrides: Any) -> None:
self.responses: dict[str, Any] = copy.deepcopy(RECORDED)
self.responses.update(overrides)
self.calls: list[tuple[str, str, dict[str, Any]]] = []
def _answer(self, method: str, path: str, params: dict[str, Any]) -> Any:
self.calls.append((method, path.strip("/"), params))
for key in (f"{method} {_key(path, params)}", f"{method} {path.strip('/')}"):
if key in self.responses:
return self._value(self.responses[key])
if method == "GET":
for key in (_key(path, params), path.strip("/")):
if key in self.responses:
return self._value(self.responses[key])
raise ResourceException(404, "Not Found", f"no recorded answer for {method} {path}")
@staticmethod
def _value(value: Any) -> Any:
if isinstance(value, Exception):
raise value
return copy.deepcopy(value)
def __getattr__(self, name: str) -> _Resource:
if name.startswith("_"):
raise AttributeError(name)
return _Resource(self, name)
def get(self, path: str, **params: Any) -> Any:
return self._answer("GET", path, params)
def post(self, path: str, **params: Any) -> Any:
return self._answer("POST", path, params)
def put(self, path: str, **params: Any) -> Any:
return self._answer("PUT", path, params)
def delete(self, path: str, **params: Any) -> Any:
return self._answer("DELETE", path, params)
def forbidden() -> ResourceException:
return ResourceException(403, "Forbidden", "permission check failed")
+6 -15
View File
@@ -2,7 +2,6 @@
"coverage_floor": 68.0,
"function_complexity": {
"napalm_proxmox/driver.py::ProxmoxDriver._resolve_node": 13,
"napalm_proxmox/driver.py::ProxmoxDriver.get_facts": 16,
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_interfaces_counters": 14,
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 22,
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.get_route_to": 13,
@@ -15,40 +14,32 @@
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 16,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 13,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 22,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 16,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_users": 15,
"napalm_proxmox/utils.py::addresses_from_node_network": 15,
"napalm_proxmox/vm_contract_mixin.py::parse_vm_config": 16,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin._get_vm_disk_and_boot": 16,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 37,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 21,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 26,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 18,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 12
},
"function_lines": {
"napalm_proxmox/driver.py::ProxmoxDriver.get_facts": 82,
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
"napalm_proxmox/lldp_mixin.py::ProxmoxLLDPMixin.get_lldp_neighbors_detail": 52,
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.ping": 78,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._get_vm_vlan_tags": 54,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 66,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 70,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 66,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_users": 51,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 124,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 113,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin._download_cloud_image": 61,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 232,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 65,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 92
"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.get_vm_status": 63
},
"mypy_relaxed": [
"napalm_proxmox.config_mixin",
"napalm_proxmox.driver",
"napalm_proxmox.interfaces_mixin",
"napalm_proxmox.lldp_mixin",
"napalm_proxmox.routing_mixin",
"napalm_proxmox.sdn_mixin",
"napalm_proxmox.system_mixin",
+555
View File
@@ -0,0 +1,555 @@
"""get_clusters(): quorum votes, the HA manager's guests, backup jobs and backups.
Each of these is read on top of the cluster report and is best-effort: a read
that fails leaves its key None and the rest of the report stands.
Payloads: ``/cluster/config/nodes`` is corosync's nodelist; ``/cluster/ha/*``
follow pve-ha-manager's API (``src/PVE/API2/HA/{Resources,Status,Rules}.pm``,
master = PVE 9 and stable-4 = PVE 8): a service entry of ``status/current``
carries ``crm_state`` and ``request_state``, a rule carries ``rule``, ``type``
and ``resources`` as a sorted, comma-separated list of sids, and PVE 8 has no
``/cluster/ha/rules``. ``/cluster/backup`` follows pve-manager's
``PVE/API2/Backup.pm``; storage content rows follow
``/nodes/{node}/storage/{storage}/content``.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
from tests.test_clusters import (
CLUSTER_RESOURCES,
GIB,
_api,
_by_name,
_driver,
_storage_row,
)
def _report(api: MagicMock) -> dict[str, Any]:
[cluster] = _driver(api).get_clusters()
return dict(cluster)
class TestVotes:
def test_each_node_has_its_quorum_votes(self):
nodes = _by_name(_report(_api())["nodes"])
assert [nodes[n]["votes"] for n in ("pve1", "pve2", "pve3")] == [1, 1, 2]
def test_unreadable_nodelist_leaves_votes_unknown(self):
api = _api()
api.cluster.config.nodes.get.side_effect = RuntimeError("403 Forbidden")
nodes = _report(api)["nodes"]
assert [n["votes"] for n in nodes] == [None, None, None]
# The rest of the node still stands.
assert nodes[0]["cpu_threads"] == 32
def test_standalone_node_has_no_votes(self):
# A node without corosync.conf answers with an empty nodelist.
api = _api()
api.cluster.config.nodes.get.return_value = []
assert [n["votes"] for n in _report(api)["nodes"]] == [None, None, None]
def test_node_without_quorum_votes_counts_the_default(self):
"""corosync counts a node without quorum_votes as one vote."""
api = _api()
api.cluster.config.nodes.get.return_value = [{"node": "pve1", "name": "pve1"}]
nodes = _by_name(_report(api)["nodes"])
assert nodes["pve1"]["votes"] == 1
assert nodes["pve2"]["votes"] is None
# --------------------------------------------------------------------------- HA
HA_RESOURCES_PVE8 = [
{
"sid": "vm:100",
"type": "vm",
"state": "started",
"group": "prefer-pve1",
"max_restart": 1,
"max_relocate": 1,
"digest": "3f1c",
},
# No state in the config: HA's default, "started".
{"sid": "ct:101", "type": "ct", "digest": "3f1c"},
{"sid": "vm:102", "type": "vm", "state": "disabled", "digest": "3f1c"},
]
HA_STATUS = [
{"id": "quorum", "type": "quorum", "node": "pve1", "quorate": 1, "status": "OK"},
{
"id": "master",
"type": "master",
"node": "pve1",
"status": "pve1 (active, Sun Nov 1 10:00:00 2026)",
"timestamp": 1793527200,
},
{
"id": "lrm:pve1",
"type": "lrm",
"node": "pve1",
"status": "pve1 (active, Sun Nov 1 10:00:00 2026)",
"timestamp": 1793527200,
},
{
"id": "service:vm:100",
"type": "service",
"sid": "vm:100",
"node": "pve2",
"crm_state": "migrate",
"state": "migrate",
"status": "vm:100 (pve2, migrate)",
"request_state": "started",
"group": "prefer-pve1",
"max_restart": 1,
"max_relocate": 1,
},
{
"id": "service:ct:101",
"type": "service",
"sid": "ct:101",
"node": "pve1",
"crm_state": "started",
"state": "started",
"status": "ct:101 (pve1, started)",
"request_state": "started",
},
# Not yet processed by the CRM: no crm_state, a verbose state only.
{
"id": "service:vm:102",
"type": "service",
"sid": "vm:102",
"state": "queued",
"status": "vm:102 (---, queued)",
"request_state": "disabled",
},
]
# PVE 9: groups were migrated into node-affinity rules, so resources lose "group".
HA_RESOURCES_PVE9 = [{k: v for k, v in r.items() if k != "group"} for r in HA_RESOURCES_PVE8]
HA_RULES_PVE9 = [
{
"rule": "ha-group-prefer-pve1",
"type": "node-affinity",
"resources": "vm:100",
"nodes": "pve1:2,pve2:1",
"strict": 0,
"digest": "9ac2",
"order": 1,
},
{
"rule": "keep-apart",
"type": "resource-affinity",
"affinity": "negative",
"resources": "ct:101,vm:100",
"digest": "9ac2",
"order": 2,
},
]
def _ha_api(
resources: Any = HA_RESOURCES_PVE8,
status: Any = HA_STATUS,
rules: Any = None,
) -> MagicMock:
api = _api()
ha = api.cluster.ha
for endpoint, value in ((ha.resources, resources), (ha.status.current, status)):
if isinstance(value, Exception):
endpoint.get.side_effect = value
else:
endpoint.get.return_value = value
if rules is None:
# PVE 8 has no rules endpoint.
ha.rules.get.side_effect = RuntimeError(
"501 Not Implemented: Method 'GET /cluster/ha/rules' not implemented"
)
else:
ha.rules.get.return_value = rules
return api
def _ha(api: MagicMock) -> dict[int, dict[str, Any]] | None:
resources = _report(api)["ha_resources"]
return None if resources is None else {r["vmid"]: r for r in resources}
class TestHAResources:
def test_pve8_resource_with_group(self):
ha = _ha(_ha_api())
assert ha is not None
assert ha[100] == {
"vmid": 100,
"kind": "qemu",
"requested": "started",
"status": "migrate",
"node": "pve2",
"group": "prefer-pve1",
"rules": [],
}
def test_container_and_default_requested_state(self):
ha = _ha(_ha_api())
assert ha is not None
assert ha[101]["kind"] == "lxc"
assert ha[101]["requested"] == "started"
assert ha[101]["status"] == "started"
assert ha[101]["node"] == "pve1"
assert ha[101]["group"] is None
def test_not_yet_processed_reports_the_verbose_state(self):
ha = _ha(_ha_api())
assert ha is not None
assert ha[102]["requested"] == "disabled"
assert ha[102]["status"] == "queued"
assert ha[102]["node"] is None
def test_pve9_rules_name_their_resources(self):
ha = _ha(_ha_api(resources=HA_RESOURCES_PVE9, rules=HA_RULES_PVE9))
assert ha is not None
assert ha[100]["rules"] == ["ha-group-prefer-pve1", "keep-apart"]
assert ha[101]["rules"] == ["keep-apart"]
assert ha[102]["rules"] == []
assert ha[100]["group"] is None
def test_no_ha_configured_is_an_empty_list(self):
assert _report(_ha_api(resources=[], status=[]))["ha_resources"] == []
def test_unreadable_resources_leave_the_list_unknown(self):
api = _ha_api(resources=RuntimeError("403 Forbidden: Permission check failed"))
report = _report(api)
assert report["ha_resources"] is None
assert report["name"] == "lab"
def test_unreadable_status_leaves_status_and_node_unknown(self):
ha = _ha(_ha_api(status=RuntimeError("500 cfs lock")))
assert ha is not None
assert (ha[100]["status"], ha[100]["node"]) == (None, None)
assert ha[100]["requested"] == "started"
# ---------------------------------------------------------------------- backups
BACKUP_JOBS = [
{
"id": "backup-5a1b2c3d-e4f5",
"type": "vzdump",
"enabled": 1,
"schedule": "sat 02:00",
"storage": "pbs",
"mode": "snapshot",
"all": 1,
"exclude": "105,106",
"compress": "zstd",
"mailnotification": "always",
"next-run": 1793584800,
"notes-template": "{{guestname}}",
},
{
"id": "backup-7e8f9a0b-1c2d",
"type": "vzdump",
"enabled": 0,
"schedule": "mon..fri 21:00",
"storage": "local",
"mode": "stop",
"vmid": "100,101",
"node": "pve1",
},
# No "enabled": a job is enabled unless it says otherwise.
{
"id": "backup-0b1c2d3e-4f5a",
"type": "vzdump",
"schedule": "daily",
"storage": "pbs",
"mode": "suspend",
"pool": "prod",
},
]
# PVE >= 8.1: GET /pools?poolid=prod
POOL_INDEX = [
{
"poolid": "prod",
"comment": "",
"members": [
{"id": "qemu/100", "type": "qemu", "vmid": 100, "node": "pve1", "name": "web"},
{"id": "lxc/101", "type": "lxc", "vmid": 101, "node": "pve1", "name": "dns"},
{"id": "storage/pve1/local", "type": "storage", "storage": "local", "node": "pve1"},
],
}
]
def _backup_api(jobs: Any = BACKUP_JOBS) -> MagicMock:
api = _api()
if isinstance(jobs, Exception):
api.cluster.backup.get.side_effect = jobs
else:
api.cluster.backup.get.return_value = jobs
api.pools.get.return_value = POOL_INDEX
return api
def _jobs(api: MagicMock) -> dict[str, dict[str, Any]]:
jobs = _report(api)["backup_jobs"]
assert jobs is not None
return {j["id"]: j for j in jobs}
class TestBackupJobs:
def test_all_guests_job(self):
assert _jobs(_backup_api())["backup-5a1b2c3d-e4f5"] == {
"id": "backup-5a1b2c3d-e4f5",
"enabled": True,
"schedule": "sat 02:00",
"storage": "pbs",
"mode": "snapshot",
"all": True,
"vmids": [],
"exclude": [105, 106],
"pool": None,
"node": None,
}
def test_disabled_job_for_named_guests_on_one_node(self):
job = _jobs(_backup_api())["backup-7e8f9a0b-1c2d"]
assert job["enabled"] is False
assert job["all"] is False
assert job["vmids"] == [100, 101]
assert job["exclude"] == []
assert job["node"] == "pve1"
def test_pool_job_lists_the_pools_guests(self):
api = _backup_api()
job = _jobs(api)["backup-0b1c2d3e-4f5a"]
assert job["enabled"] is True
assert job["pool"] == "prod"
assert job["vmids"] == [100, 101]
api.pools.get.assert_called_with(poolid="prod")
def test_pool_read_falls_back_to_the_old_endpoint(self):
"""Before PVE 8.1, /pools takes no poolid; /pools/{poolid} answers instead."""
api = _backup_api()
api.pools.get.side_effect = RuntimeError("400 Bad Request: Parameter verification failed")
pool = MagicMock()
pool.get.return_value = {"comment": "", "members": POOL_INDEX[0]["members"]}
api.pools.side_effect = lambda name: pool if name == "prod" else MagicMock()
assert _jobs(api)["backup-0b1c2d3e-4f5a"]["vmids"] == [100, 101]
def test_old_style_start_time_and_days(self):
"""Jobs from vzdump.cron carry starttime/dow; PVE turns them into a schedule."""
jobs = [
{"id": "a", "starttime": "02:30", "dow": "sat,sun", "storage": "local", "vmid": "102"},
{
"id": "b",
"starttime": "03:00",
"dow": "mon,tue,wed,thu,fri,sat,sun",
"storage": "local",
"all": 1,
},
{"id": "c", "starttime": "04:00", "storage": "local", "all": 1},
]
found = _jobs(_backup_api(jobs))
assert [found[i]["schedule"] for i in "abc"] == ["sat,sun 02:30", "03:00", "04:00"]
def test_job_with_a_dump_directory_has_no_storage(self):
jobs = [{"id": "d", "schedule": "daily", "dumpdir": "/mnt/backup", "all": 1}]
job = _jobs(_backup_api(jobs))["d"]
assert job["storage"] is None
assert job["mode"] is None
def test_no_jobs_is_an_empty_list(self):
assert _report(_backup_api([]))["backup_jobs"] == []
def test_unreadable_jobs_leave_the_list_unknown(self):
report = _report(_backup_api(RuntimeError("403 Forbidden")))
assert report["backup_jobs"] is None
assert report["nodes"]
def test_unreadable_pool_leaves_the_list_unknown(self):
"""A pool job whose guests cannot be read would look like a job for none."""
api = _backup_api()
api.pools.get.side_effect = RuntimeError("403 Forbidden")
api.pools.return_value.get.side_effect = RuntimeError("403 Forbidden")
api.pools.side_effect = None
assert _report(api)["backup_jobs"] is None
BACKUP_RESOURCES = [
*CLUSTER_RESOURCES,
_storage_row("pve1", "pbs", "pbs", 1, "backup", 8000 * GIB, 2000 * GIB),
_storage_row("pve2", "pbs", "pbs", 1, "backup", 8000 * GIB, 2000 * GIB),
_storage_row("pve1", "local", "dir", 0, "iso,vztmpl,backup", 100 * GIB, 20 * GIB),
_storage_row("pve2", "local", "dir", 0, "iso,vztmpl,backup", 100 * GIB, 30 * GIB),
_storage_row("pve3", "local", "dir", 0, "iso,vztmpl,backup", 0, 0, status="unknown"),
]
PBS_CONTENT = [
{
"volid": "pbs:backup/vm/100/2026-10-31T01:00:00Z",
"content": "backup",
"format": "pbs-vm",
"ctime": 1793408400,
"size": 32 * GIB,
"vmid": 100,
"subtype": "qemu",
"notes": "web",
"protected": 0,
"verification": {"state": "ok", "upid": "UPID:pbs:0000:0000:0000:verify:x:root@pam:"},
},
{
"volid": "pbs:backup/vm/100/2026-10-24T01:00:00Z",
"content": "backup",
"format": "pbs-vm",
"ctime": 1792803600,
"size": 31 * GIB,
"vmid": 100,
"subtype": "qemu",
},
{
"volid": "pbs:backup/ct/101/2026-10-31T01:05:00Z",
"content": "backup",
"format": "pbs-ct",
"ctime": 1793408700,
"size": 2 * GIB,
"vmid": 101,
"subtype": "lxc",
},
]
LOCAL_CONTENT = {
"pve1": [
{
"volid": "local:backup/vzdump-qemu-100-2026_10_30-21_00_02.vma.zst",
"content": "backup",
"format": "vma.zst",
"ctime": 1793394002,
"size": 1234567,
"vmid": 100,
"subtype": "qemu",
},
# A file that does not follow vzdump's naming has no vmid.
{"volid": "local:backup/manual.tar", "content": "backup", "format": "tar", "size": 10},
],
"pve2": [
{
"volid": "local:backup/vzdump-qemu-100-2026_10_29-21_00_01.vma.zst",
"content": "backup",
"format": "vma.zst",
"ctime": 1793307601,
"size": 1200000,
"vmid": 100,
"subtype": "qemu",
},
],
}
def _storage_api(
content: dict[tuple[str, str], Any] | None = None,
) -> tuple[MagicMock, dict[tuple[str, str], MagicMock]]:
"""The cluster with backup storages; *content* per (node, storage)."""
rows = content or {
("pve1", "pbs"): PBS_CONTENT,
("pve2", "pbs"): PBS_CONTENT,
("pve1", "local"): LOCAL_CONTENT["pve1"],
("pve2", "local"): LOCAL_CONTENT["pve2"],
}
api = _api(resources=BACKUP_RESOURCES)
calls: dict[tuple[str, str], MagicMock] = {}
for node in ("pve1", "pve2"):
def storage(name: str, node: str = node) -> MagicMock:
res = calls.setdefault((node, name), MagicMock())
value = rows.get((node, name), [])
if isinstance(value, Exception):
res.content.get.side_effect = value
else:
res.content.get.return_value = value
return res
api.nodes(node).storage.side_effect = storage
return api, calls
def _backups(api: MagicMock) -> dict[tuple[int, str], dict[str, Any]] | None:
backups = _report(api)["backups"]
return None if backups is None else {(b["vmid"], b["storage"]): b for b in backups}
class TestBackups:
def test_newest_backup_per_guest_and_storage(self):
api, _ = _storage_api()
backups = _backups(api)
assert backups is not None
assert backups[(100, "pbs")] == {
"vmid": 100,
"storage": "pbs",
"time": 1793408400,
"size": 32 * GIB,
"count": 2,
}
assert backups[(101, "pbs")]["count"] == 1
def test_shared_storage_read_once_on_the_own_node(self):
api, calls = _storage_api()
_report(api)
calls[("pve1", "pbs")].content.get.assert_called_once_with(content="backup")
assert ("pve2", "pbs") not in calls
def test_local_storage_read_on_each_node_that_has_it(self):
api, calls = _storage_api()
backups = _backups(api)
assert backups is not None
# The same guest backed up to "local" on two nodes: counted together.
assert backups[(100, "local")] == {
"vmid": 100,
"storage": "local",
"time": 1793394002,
"size": 1234567,
"count": 2,
}
assert ("pve1", "local") in calls and ("pve2", "local") in calls
def test_storage_without_backup_content_is_not_read(self):
api, calls = _storage_api()
_report(api)
assert not [key for key in calls if key[1] in ("ceph-vm", "local-lvm", "nfs-iso")]
def test_entry_without_vmid_is_skipped(self):
api, _ = _storage_api()
backups = _backups(api)
assert backups is not None
assert {vmid for vmid, _ in backups} == {100, 101}
def test_shared_storage_tried_on_the_next_node(self):
api, _ = _storage_api(
{
("pve1", "pbs"): RuntimeError("pbs: datastore not reachable from pve1"),
("pve2", "pbs"): PBS_CONTENT,
}
)
backups = _backups(api)
assert backups is not None
assert backups[(100, "pbs")]["count"] == 2
def test_unreadable_storage_leaves_backups_unknown(self):
"""Half a list would say a guest has no backup when it may have one."""
api, _ = _storage_api(
{
("pve1", "pbs"): PBS_CONTENT,
("pve1", "local"): LOCAL_CONTENT["pve1"],
("pve2", "local"): RuntimeError("596 Connection timed out"),
}
)
report = _report(api)
assert report["backups"] is None
assert report["storages"]
def test_no_backup_storage_is_an_empty_list(self):
assert _report(_api())["backups"] == []
+577
View File
@@ -0,0 +1,577 @@
"""get_clusters(): the cluster a node belongs to, its nodes, storages and networks.
A Proxmox node can read its whole cluster: ``/cluster/status`` names the members
and the quorum, ``/cluster/resources`` their capacity and every storage per
node, ``/nodes/{node}/status`` the CPU, ``/nodes/{node}/network`` the bridges.
netOrk uses it to tell where a new VM may go (NetOrk/netork#484, #1822). The
payloads below follow PVE 8.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import _build_mock_api
GIB = 1024**3
CLUSTER_STATUS = [
{"type": "cluster", "id": "cluster", "name": "lab", "nodes": 3, "quorate": 1, "version": 7},
{
"type": "node",
"id": "node/pve1",
"name": "pve1",
"nodeid": 1,
"ip": "10.0.0.1",
"local": 1,
"online": 1,
"level": "",
},
{
"type": "node",
"id": "node/pve2",
"name": "pve2",
"nodeid": 2,
"ip": "10.0.0.2",
"local": 0,
"online": 1,
"level": "",
},
{
"type": "node",
"id": "node/pve3",
"name": "pve3",
"nodeid": 3,
"ip": "10.0.0.3",
"local": 0,
"online": 0,
"level": "",
},
]
def _node_row(node: str, maxcpu: int, cpu: float, maxmem: int, mem: int) -> dict[str, Any]:
return {
"id": f"node/{node}",
"type": "node",
"node": node,
"status": "online",
"cpu": cpu,
"maxcpu": maxcpu,
"mem": mem,
"maxmem": maxmem,
"disk": 5 * GIB,
"maxdisk": 100 * GIB,
"uptime": 86400,
"level": "",
"cgroup-mode": 2,
}
def _storage_row(
node: str,
storage: str,
plugintype: str,
shared: int,
content: str,
maxdisk: int,
disk: int,
status: str = "available",
) -> dict[str, Any]:
return {
"id": f"storage/{node}/{storage}",
"type": "storage",
"node": node,
"storage": storage,
"plugintype": plugintype,
"shared": shared,
"content": content,
"maxdisk": maxdisk,
"disk": disk,
"status": status,
}
CLUSTER_RESOURCES = [
_node_row("pve1", 32, 0.25, 128 * GIB, 64 * GIB),
_node_row("pve2", 16, 0.5, 64 * GIB, 16 * GIB),
# An offline node keeps a row, with what PVE last knew of it.
{"id": "node/pve3", "type": "node", "node": "pve3", "status": "offline", "maxcpu": 8},
_storage_row("pve1", "local-lvm", "lvmthin", 0, "rootdir,images", 400 * GIB, 100 * GIB),
_storage_row("pve2", "local-lvm", "lvmthin", 0, "rootdir,images", 200 * GIB, 50 * GIB),
_storage_row("pve3", "local-lvm", "lvmthin", 0, "rootdir,images", 0, 0, status="unknown"),
_storage_row("pve1", "ceph-vm", "rbd", 1, "images,rootdir", 3000 * GIB, 1000 * GIB),
_storage_row("pve2", "ceph-vm", "rbd", 1, "images,rootdir", 3000 * GIB, 1000 * GIB),
_storage_row("pve1", "nfs-iso", "nfs", 1, "iso,vztmpl,snippets", 1000 * GIB, 10 * GIB),
# The NFS server cannot be reached from pve2.
_storage_row("pve2", "nfs-iso", "nfs", 1, "iso,vztmpl,snippets", 0, 0, status="unavailable"),
{"id": "qemu/100", "type": "qemu", "vmid": 100, "node": "pve1", "status": "running"},
{"id": "sdn/pve1/localnetwork", "type": "sdn", "sdn": "localnetwork", "node": "pve1"},
]
def _cpuinfo(cores: int, sockets: int, model: str, flags: str) -> dict[str, Any]:
return {
"cpuinfo": {
"cores": cores,
"sockets": sockets,
"cpus": cores * sockets * 2,
"model": model,
"flags": flags,
"mhz": "2100.000",
"hvm": "1",
"user_hz": 100,
},
"memory": {"total": 128 * GIB, "used": 64 * GIB, "free": 64 * GIB},
"uptime": 86400,
"pveversion": "pve-manager/8.2.4/faa83925c9641325",
}
NODE_STATUS = {
"pve1": _cpuinfo(8, 2, "Intel(R) Xeon(R) Silver 4110 CPU @ 2.10GHz", "fpu vme sse4_2 avx2"),
"pve2": _cpuinfo(8, 1, "AMD EPYC 7302P 16-Core Processor", "fpu vme sse4_2"),
}
NODE_NETWORK = {
"pve1": [
{"iface": "eno1", "type": "eth", "active": 1},
{
"iface": "vmbr0",
"type": "bridge",
"active": 1,
"bridge_ports": "eno1",
"bridge_vlan_aware": 1,
},
{"iface": "vmbr9", "type": "bridge", "active": 1, "bridge_ports": "none"},
],
"pve2": [
{"iface": "eno1", "type": "eth", "active": 1},
# Same name, but not VLAN aware on this node.
{"iface": "vmbr0", "type": "bridge", "active": 1, "bridge_ports": "eno1"},
{"iface": "vmbr1", "type": "OVSBridge", "active": 1, "ovs_ports": ""},
],
}
SDN_ZONES = [
{"zone": "edge", "type": "vlan", "bridge": "vmbr0", "nodes": "pve2", "digest": "x"},
{"zone": "fabric", "type": "vxlan", "peers": "10.0.0.1,10.0.0.2", "digest": "x"},
]
SDN_VNETS = [
{"vnet": "dmz", "zone": "edge", "tag": 30, "type": "vnet", "digest": "x"},
{"vnet": "overlay", "zone": "fabric", "tag": 100000, "type": "vnet", "digest": "x"},
]
# /cluster/config/nodes: corosync's nodelist; corosync.conf keeps every value a string.
CONFIG_NODES = [
{"node": "pve1", "name": "pve1", "nodeid": "1", "quorum_votes": "1", "ring0_addr": "10.0.0.1"},
{"node": "pve2", "name": "pve2", "nodeid": "2", "quorum_votes": "1", "ring0_addr": "10.0.0.2"},
{"node": "pve3", "name": "pve3", "nodeid": "3", "quorum_votes": "2", "ring0_addr": "10.0.0.3"},
]
HA_MANAGER_STATUS = {
"manager_status": {
"master_node": "pve1",
"node_status": {"pve1": "online", "pve2": "maintenance", "pve3": "unknown"},
"service_status": {},
"timestamp": 1730000000,
},
"quorum": {"node": "pve1", "quorate": "1"},
}
def _api(
cluster_status: list[dict[str, Any]] | None = None,
resources: list[dict[str, Any]] | None = None,
node_status: dict[str, Any] | None = None,
node_network: dict[str, Any] | None = None,
zones: list[dict[str, Any]] | None = None,
vnets: list[dict[str, Any]] | None = None,
ha: dict[str, Any] | Exception | None = None,
) -> MagicMock:
api = _build_mock_api(cluster_status=cluster_status or CLUSTER_STATUS)
statuses = NODE_STATUS if node_status is None else node_status
networks = NODE_NETWORK if node_network is None else node_network
nodes: dict[str, MagicMock] = {}
def node_res(name: str) -> MagicMock:
if name not in nodes:
res = MagicMock()
if name in statuses:
res.status.get.return_value = statuses[name]
else:
res.status.get.side_effect = ConnectionError(f"{name} unreachable")
res.network.get.return_value = networks.get(name, [])
nodes[name] = res
return nodes[name]
api.nodes.side_effect = node_res
api.nodes.return_value = None
api.cluster.resources.get.return_value = CLUSTER_RESOURCES if resources is None else resources
api.cluster.sdn.zones.get.return_value = SDN_ZONES if zones is None else zones
api.cluster.sdn.vnets.get.return_value = SDN_VNETS if vnets is None else vnets
manager = api.cluster.ha.status.manager_status.get
if isinstance(ha, Exception):
manager.side_effect = ha
else:
manager.return_value = HA_MANAGER_STATUS if ha is None else ha
# Read for get_clusters' votes, HA resources and backups; see test_cluster_ha_backups.
api.cluster.config.nodes.get.return_value = CONFIG_NODES
api.cluster.ha.resources.get.return_value = []
api.cluster.ha.status.current.get.return_value = []
api.cluster.ha.rules.get.return_value = []
api.cluster.backup.get.return_value = []
api.storage.get.return_value = []
return api
def _driver(api: MagicMock, node: str = "pve1") -> ProxmoxDriver:
drv = ProxmoxDriver(
hostname=f"{node}.example.com",
username="root",
password="secret",
optional_args={"verify_ssl": False, "node": node},
)
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
drv.open()
return drv
def _cluster(**kwargs: Any) -> dict[str, Any]:
clusters = _driver(_api(**kwargs)).get_clusters()
assert len(clusters) == 1
return dict(clusters[0])
def _by_name(items: list[Any]) -> dict[str, Any]:
return {item["name"]: item for item in items}
class TestCluster:
def test_name_and_quorum(self):
cluster = _cluster()
assert cluster["id"] is None
assert cluster["name"] == "lab"
assert cluster["quorate"] is True
def test_lost_quorum(self):
status = [dict(CLUSTER_STATUS[0], quorate=0), *CLUSTER_STATUS[1:]]
assert _cluster(cluster_status=status)["quorate"] is False
def test_every_member_listed_in_cluster_order(self):
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:
def test_online_node(self):
pve1 = _by_name(_cluster()["nodes"])["pve1"]
assert pve1 == {
"name": "pve1",
"status": "online",
"local": True,
"maintenance": False,
"cpu_threads": 32,
"cpu_cores": 16,
"cpu_model": "Intel(R) Xeon(R) Silver 4110 CPU @ 2.10GHz",
"cpu_flags": ["fpu", "vme", "sse4_2", "avx2"],
"cpu_usage": 0.25,
"memory_total": 128 * GIB,
"memory_used": 64 * GIB,
"votes": 1,
}
def test_other_member_is_not_local(self):
pve2 = _by_name(_cluster()["nodes"])["pve2"]
assert pve2["local"] is False
assert pve2["cpu_cores"] == 8
assert pve2["cpu_threads"] == 16
def test_offline_node_is_listed_without_capacity(self):
api = _api()
pve3 = _by_name(_driver(api).get_clusters()[0]["nodes"])["pve3"]
assert pve3["status"] == "offline"
assert pve3["local"] is False
for key in (
"cpu_threads",
"cpu_cores",
"cpu_model",
"cpu_flags",
"cpu_usage",
"memory_total",
"memory_used",
):
assert pve3[key] is None, key
# An offline node is not asked: the request would only time out.
assert all(call.args != ("pve3",) for call in api.nodes.call_args_list)
def test_local_falls_back_to_the_resolved_node(self):
status = [dict(s, local=0) if s["type"] == "node" else s for s in CLUSTER_STATUS]
nodes = _by_name(
_driver(_api(cluster_status=status), node="pve2").get_clusters()[0]["nodes"]
)
assert nodes["pve2"]["local"] is True
assert nodes["pve1"]["local"] is False
class TestStandalone:
STATUS = [
{
"type": "node",
"id": "node/pve1",
"name": "pve1",
"nodeid": 0,
"ip": "10.0.0.1",
"local": 1,
"online": 1,
"level": "",
}
]
RESOURCES = [
_node_row("pve1", 32, 0.25, 128 * GIB, 64 * GIB),
_storage_row("pve1", "local", "dir", 0, "iso,vztmpl,backup", 100 * GIB, 5 * GIB),
]
def test_a_cluster_of_one_without_name(self):
cluster = _cluster(cluster_status=self.STATUS, resources=self.RESOURCES, ha=RuntimeError())
assert cluster["id"] is None
assert cluster["name"] is None
assert cluster["quorate"] is None
[node] = cluster["nodes"]
assert node["name"] == "pve1"
assert node["status"] == "online"
assert node["local"] is True
assert node["cpu_cores"] == 16
assert node["memory_total"] == 128 * GIB
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:
def test_local_storage_grouped_over_its_nodes(self):
lvm = _by_name(_cluster()["storages"])["local-lvm"]
assert lvm == {
"name": "local-lvm",
"type": "lvmthin",
"shared": False,
"content": ["rootdir", "images"],
# pve3 is offline: its storage is "unknown", not available.
"nodes": ["pve1", "pve2"],
# Separate disks on each node: their sizes add up.
"total": 600 * GIB,
"used": 150 * GIB,
}
def test_shared_storage_counted_once(self):
ceph = _by_name(_cluster()["storages"])["ceph-vm"]
assert ceph["shared"] is True
assert ceph["type"] == "rbd"
assert ceph["nodes"] == ["pve1", "pve2"]
assert ceph["total"] == 3000 * GIB
assert ceph["used"] == 1000 * GIB
def test_storage_unavailable_on_a_node_leaves_it_out(self):
nfs = _by_name(_cluster()["storages"])["nfs-iso"]
assert nfs["nodes"] == ["pve1"]
assert nfs["content"] == ["iso", "vztmpl", "snippets"]
assert nfs["total"] == 1000 * GIB
def test_storage_available_nowhere_has_no_size(self):
resources = [
*CLUSTER_RESOURCES[:3],
_storage_row("pve1", "nas", "cifs", 1, "backup", 0, 0, status="unavailable"),
]
nas = _by_name(_cluster(resources=resources)["storages"])["nas"]
assert nas["nodes"] == []
assert nas["total"] is None
assert nas["used"] is None
class TestNetworks:
def test_bridge_merged_across_nodes_vlan_aware_only_if_everywhere(self):
vmbr0 = _by_name(_cluster()["networks"])["vmbr0"]
assert vmbr0 == {
"name": "vmbr0",
"kind": "bridge",
"vlan_aware": False,
"nodes": ["pve1", "pve2"],
}
def test_bridge_on_one_node(self):
networks = _by_name(_cluster()["networks"])
assert networks["vmbr9"]["nodes"] == ["pve1"]
assert networks["vmbr1"] == {
"name": "vmbr1",
"kind": "bridge",
"vlan_aware": True,
"nodes": ["pve2"],
}
def test_vlan_aware_on_every_node(self):
network = {
n: [dict(i, bridge_vlan_aware=1) for i in NODE_NETWORK["pve1"]] for n in NODE_NETWORK
}
assert _by_name(_cluster(node_network=network)["networks"])["vmbr0"]["vlan_aware"] is True
def test_vnet_on_its_zones_nodes(self):
dmz = _by_name(_cluster()["networks"])["dmz"]
assert dmz == {
"name": "dmz",
"kind": "vnet",
"vlan_aware": False,
"fixed_vlan_tag": 30,
"nodes": ["pve2"],
}
def test_vnet_of_a_zone_without_nodes_is_everywhere(self):
overlay = _by_name(_cluster()["networks"])["overlay"]
assert overlay["nodes"] == ["pve1", "pve2", "pve3"]
assert overlay["fixed_vlan_tag"] == 100000
def test_get_network_targets_unchanged_for_the_own_node(self):
targets = _by_name(_driver(_api()).get_network_targets())
assert targets["vmbr0"] == {
"name": "vmbr0",
"kind": "bridge",
"vlan_aware": True,
"uplinks": [["eno1"]],
}
assert targets["dmz"]["fixed_vlan_tag"] == 30
class TestMaintenance:
def test_ha_reports_maintenance(self):
nodes = _by_name(_cluster()["nodes"])
assert nodes["pve1"]["maintenance"] is False
assert nodes["pve2"]["maintenance"] is True
def test_ha_unreadable_leaves_maintenance_unknown(self):
nodes = _cluster(ha=RuntimeError("403 Forbidden: Permission check failed"))["nodes"]
assert [n["maintenance"] for n in nodes] == [None, None, None]
def test_node_the_ha_manager_does_not_track_is_unknown(self):
ha = {"manager_status": {"node_status": {"pve1": "online"}}, "quorum": {}}
nodes = _by_name(_cluster(ha=ha)["nodes"])
assert nodes["pve1"]["maintenance"] is False
assert nodes["pve2"]["maintenance"] is None
class TestReadFailures:
def test_cluster_resources_unreadable_raises(self):
api = _api()
api.cluster.resources.get.side_effect = ConnectionError("pveproxy down")
with pytest.raises(ConnectionError):
_driver(api).get_clusters()
def test_cluster_status_unreadable_raises(self):
api = _api()
drv = _driver(api)
api.cluster.status.get.side_effect = ConnectionError("pveproxy down")
with pytest.raises(ConnectionError):
drv.get_clusters()
def test_own_node_status_unreadable_raises(self):
status = {"pve2": NODE_STATUS["pve2"]}
with pytest.raises(ConnectionError):
_driver(_api(node_status=status)).get_clusters()
def test_other_node_status_unreadable_leaves_its_cpu_unknown(self):
status = {"pve1": NODE_STATUS["pve1"]}
pve2 = _by_name(_cluster(node_status=status)["nodes"])["pve2"]
assert pve2["status"] == "online"
assert pve2["cpu_cores"] is None
assert pve2["cpu_model"] is None
assert pve2["cpu_flags"] is None
# What /cluster/resources says still stands.
assert pve2["cpu_threads"] == 16
class TestCreateOnAnotherNode:
def test_other_node_raises_before_anything_is_created(self):
api = _api()
drv = _driver(api)
with pytest.raises(ValueError, match="pve2"):
drv.create_vm_from_cloud_init(
"vm1",
image_url="https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2",
cpu=2,
memory=2048,
nics=[{"bridge": "vmbr0"}],
cloud_init_config={},
node="pve2",
)
api.cluster.nextid.get.assert_not_called()
for res in [api.nodes(n) for n in ("pve1", "pve2")]:
assert not [c for c in res.mock_calls if "post" in c[0]]
# /storage: what a pbs storage writes to (napalm-device-types 4.25, #55). The password
# and the encryption key are never in this answer's use.
PBS_ROW = _storage_row("pve1", "pbs-01", "pbs", 1, "backup", 1000 * GIB, 30 * GIB)
STORAGE_CONFIG = [
{"storage": "local", "type": "dir", "path": "/var/lib/vz", "content": "iso,backup"},
{
"storage": "pbs-01",
"type": "pbs",
"server": "192.0.2.80",
"port": 8007,
"datastore": "backup",
"namespace": "lab",
"fingerprint": "aa:bb",
"username": "root@pam",
"content": "backup",
},
]
class TestBackupServerRef:
def _storages(self, config):
api = _api(resources=[*CLUSTER_RESOURCES, PBS_ROW])
if isinstance(config, Exception):
api.storage.get.side_effect = config
else:
api.storage.get.return_value = config
return _by_name(_driver(api).get_clusters()[0]["storages"])
def test_a_pbs_storage_names_its_server(self):
assert self._storages(STORAGE_CONFIG)["pbs-01"]["backup_server"] == {
"server": "192.0.2.80",
"port": 8007,
"datastore": "backup",
"namespace": "lab",
"fingerprint": "aa:bb",
}
def test_what_it_does_not_set_is_none(self):
bare = [{"storage": "pbs-01", "type": "pbs", "server": "pbs.example.com", "datastore": "b"}]
assert self._storages(bare)["pbs-01"]["backup_server"] == {
"server": "pbs.example.com",
"port": None,
"datastore": "b",
"namespace": None,
"fingerprint": None,
}
def test_other_storages_carry_no_reference(self):
storages = self._storages(STORAGE_CONFIG)
assert "backup_server" not in storages["local-lvm"]
assert "backup_server" not in storages["ceph-vm"]
def test_an_unreadable_storage_config_says_none(self):
storages = self._storages(PermissionError("403 Forbidden"))
assert storages["pbs-01"]["backup_server"] is None
assert "backup_server" not in storages["local-lvm"]
+54
View File
@@ -0,0 +1,54 @@
"""What the PVE driver hands proxmoxer, pinned before the connection moved into a
base it shares with the Proxmox Backup Server driver (#52)."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import _build_mock_api
def _kwargs(username: str = "root", password: str = "secret", **optional_args) -> dict:
drv = ProxmoxDriver("pve1", username, password, optional_args=optional_args)
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=_build_mock_api()) as api:
drv.open()
return api.call_args.kwargs
def test_password_login_on_the_pve_port():
assert _kwargs() == {
"host": "pve1",
"user": "root@pam",
"password": "secret",
"port": 8006,
"verify_ssl": True,
"backend": "https",
"service": "PVE",
}
def test_port_and_realm_from_the_arguments():
kwargs = _kwargs(port=443, realm="pve")
assert (kwargs["port"], kwargs["user"]) == (443, "root@pve")
def test_a_username_with_a_realm_keeps_it():
assert _kwargs("admin@ldap")["user"] == "admin@ldap"
@pytest.mark.parametrize("arg", ["verify_ssl", "ssl_verify", "verify"])
def test_tls_verification_under_each_name(arg):
assert _kwargs(**{arg: False})["verify_ssl"] is False
def test_token_without_a_user_part_is_passed_as_given():
kwargs = _kwargs(token_name="mytoken", token_value="s3cret")
assert (kwargs["user"], kwargs["token_name"], kwargs["token_value"]) == (
"root@pam",
"mytoken",
"s3cret",
)
assert "password" not in kwargs
+126
View File
@@ -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()
+36 -1
View File
@@ -10,6 +10,7 @@ contract's ``install_package``. Every step reads its exit status.
from __future__ import annotations
import re
import subprocess
import pytest
@@ -36,6 +37,18 @@ class _Node:
return f"{out}\n__PVE_RC={rc}" if "__PVE_RC" in command else out
def _shell_driver(prelude: str) -> ProxmoxDriver:
"""A driver whose node shell is a real local ``sh``, *prelude* run first."""
def shell(command: str) -> str:
run = subprocess.run(["sh", "-c", prelude + command], capture_output=True, text=True)
return run.stdout
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = shell
return d
@pytest.fixture
def node():
return _Node()
@@ -69,7 +82,8 @@ class TestSnmpAgent:
def test_no_temp_file_with_an_application_name(self, driver, node):
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):
node.status["command -v ufw"] = 0
@@ -87,6 +101,27 @@ class TestSnmpAgent:
assert result["success"] is False
assert not any("/etc/snmp/snmpd.conf" in c for c in node.ran)
def test_the_written_config_reports_success_through_a_real_shell(self, tmp_path):
"""The configure step's own exit status must reach ``_rc`` (#30).
``_Node`` answers ``__PVE_RC=0`` on its own; a real ``sh`` shows whether the
wrapped command still prints it. ``install`` is a function writing to tmp_path.
"""
target = tmp_path / "snmpd.conf"
d = _shell_driver(f'install() {{ cat "$7" > {target}; }}; ')
step = d._write_snmp_agent_config(SETTINGS)
assert step == {"ok": True, "output": "wrote /etc/snmp/snmpd.conf"}
assert "rocommunity c0mm 10.7.224.20/32" in target.read_text()
def test_a_refused_write_reports_failure_through_a_real_shell(self):
d = _shell_driver('install() { echo "install: read-only file system"; return 1; }; ')
step = d._write_snmp_agent_config(SETTINGS)
assert step == {"ok": False, "output": "install: read-only file system"}
def test_the_management_peer(self, driver):
assert driver.get_management_peer() == "10.7.224.20"
+145
View File
@@ -0,0 +1,145 @@
"""LLDP neighbours read from lldpd's ``lldpctl -f keyvalue`` (#44).
The output is parsed by napalm-device-types' ``parse_lldpctl_keyvalue`` and
projected by its ``lldp_neighbors`` / ``lldp_neighbors_detail``. Before, the
driver parsed ``lldpcli show neighbors`` text with ``2>/dev/null || true``, so
a failed read came back as no neighbours, and capabilities were lldpd's own
symbols lower-cased (``tel``, ``wlan``) instead of NAPALM's names.
"""
from __future__ import annotations
import pytest
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND
from napalm_proxmox import ProxmoxDriver
# Laid out the way lldpd's keyvalue writer prints ``show neighbors details``
# (src/client/display.c, kv_writer.c): every neighbour opens with ``via``, an id
# is printed under its type, a capability as ``chassis.<Symbol>.enabled``. Not
# recorded from a device. On eno1 a switch and a phone behind it (the phone
# sends no SysName), on eno2 a second switch; lldpctl's exit status follows, as
# LLDPCTL_KEYVALUE_COMMAND prints it.
TWO_NEIGHBOURS_ON_ONE_PORT = """\
lldp.eno1.via=LLDP
lldp.eno1.rid=1
lldp.eno1.age=0 day, 00:10:12
lldp.eno1.chassis.mac=00:11:22:33:44:55
lldp.eno1.chassis.name=sw1
lldp.eno1.chassis.descr=Switch OS 2.4
lldp.eno1.chassis.Bridge.enabled=on
lldp.eno1.chassis.Router.enabled=off
lldp.eno1.port.ifname=gi1/0/1
lldp.eno1.port.descr=GigabitEthernet1/0/1
lldp.eno1.via=LLDP
lldp.eno1.rid=2
lldp.eno1.age=0 day, 00:01:02
lldp.eno1.chassis.mac=AA:BB:CC:DD:EE:FF
lldp.eno1.chassis.Bridge.enabled=off
lldp.eno1.chassis.Tel.enabled=on
lldp.eno1.port.mac=aa:bb:cc:dd:ee:ff
lldp.eno2.via=LLDP
lldp.eno2.rid=3
lldp.eno2.age=0 day, 00:10:12
lldp.eno2.chassis.mac=00:11:22:33:44:66
lldp.eno2.chassis.name=sw2
lldp.eno2.chassis.Wlan.enabled=on
lldp.eno2.port.ifname=gi1/0/2
__LLDPCTL_RC=0
"""
def _driver(output: str, sent: list[str] | None = None) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
def run(command: str) -> str:
if sent is not None:
sent.append(command)
return output
d._exec_ssh_command = run # type: ignore[method-assign]
return d
class TestGetLldpNeighbors:
def test_every_neighbour_on_a_port_is_its_own_entry(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors()
assert result == {
"eno1": [
{"hostname": "sw1", "port": "gi1/0/1", "mac": "00:11:22:33:44:55"},
{"hostname": "", "port": "aa:bb:cc:dd:ee:ff", "mac": "aa:bb:cc:dd:ee:ff"},
],
"eno2": [{"hostname": "sw2", "port": "gi1/0/2", "mac": "00:11:22:33:44:66"}],
}
def test_lldpctl_without_neighbours_lists_none(self):
assert _driver("__LLDPCTL_RC=0").get_lldp_neighbors() == {}
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
def test_lldpctl_is_asked_with_its_exit_status(self, getter):
sent: list[str] = []
getattr(_driver(TWO_NEIGHBOURS_ON_ONE_PORT, sent), getter)()
assert sent == [LLDPCTL_KEYVALUE_COMMAND]
class TestGetLldpNeighborsDetail:
def test_every_neighbour_on_a_port_is_its_own_entry(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()
assert [e["remote_system_name"] for e in result["eno1"]] == ["sw1", ""]
assert result["eno1"][1]["remote_chassis_id"] == "AA:BB:CC:DD:EE:FF"
def test_capabilities_carry_napalm_names(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()
phone = result["eno1"][1]
assert phone["remote_system_capab"] == ["bridge", "telephone"]
assert phone["remote_system_enable_capab"] == ["telephone"]
assert result["eno2"][0]["remote_system_capab"] == ["wlan-access-point"]
def test_the_fields_of_a_neighbour(self):
switch = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()["eno1"][0]
assert switch == {
"parent_interface": "",
"remote_port": "gi1/0/1",
"remote_port_description": "GigabitEthernet1/0/1",
"remote_chassis_id": "00:11:22:33:44:55",
"remote_system_name": "sw1",
"remote_system_description": "Switch OS 2.4",
"remote_system_capab": ["bridge", "router"],
"remote_system_enable_capab": ["bridge"],
}
def test_one_interface_only(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail("eno2")
assert list(result) == ["eno2"]
class TestFailedRead:
"""A failed read raises; ``{}`` only when lldpctl ran and listed nobody."""
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
def test_lldpctl_failing_raises(self, getter):
output = (
"[WARN/control] unable to connect to socket /run/lldpd.socket: "
"No such file or directory\n__LLDPCTL_RC=1"
)
with pytest.raises(ValueError, match="unable to connect"):
getattr(_driver(output), getter)()
def test_a_missing_lldpctl_raises(self):
with pytest.raises(ValueError, match="not found"):
_driver("sh: 1: lldpctl: not found\n__LLDPCTL_RC=127").get_lldp_neighbors()
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
def test_no_answer_at_all_raises(self, getter):
# lldpctl's exit status is always printed; nothing at all means the
# command never ran on the node.
with pytest.raises(ValueError, match="no answer"):
getattr(_driver(""), getter)()
+43
View File
@@ -0,0 +1,43 @@
"""`get_log_sources`: which logs the node writes, and which service writes each.
pveproxy, pvedaemon, the Ceph daemons and a backup server's proxy write to
journald and to files under ``/var/log``. The command and its parse are
napalm-device-types'; the driver only carries the command over its exec path,
which already runs as root (NetOrk/netork#2049).
"""
from __future__ import annotations
from unittest.mock import patch
from napalm_device_types import LogSourcesMixin
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
from napalm_proxmox.driver import ProxmoxDriver
WIRE = (
"LOGS_BEGIN\n[journald]\npveproxy.service\n"
"[open]\n/proc/2101/fd/7 /var/log/pveproxy/access.log\n"
"[stat]\n/proc/2101/fd/7 4096 1762250200\n"
"[cgroups]\n2101 0::/system.slice/pveproxy.service\n"
"[comm]\n2101 pveproxy worker\n"
"LOGS_END\n"
)
def test_both_drivers_declare_the_contract():
assert issubclass(ProxmoxDriver, LogSourcesMixin)
assert issubclass(ProxmoxBackupDriver, LogSourcesMixin)
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_log_sources()
[command] = [c.args[0] for c in exec_.call_args_list]
assert command.startswith("sh -c '")
assert reading["attributed"] is True
access = [s for s in reading["sources"] if s["kind"] == "file"]
assert [(s["path"], s["unit"]) for s in access] == [
("/var/log/pveproxy/access.log", "pveproxy")
]
+75 -73
View File
@@ -1,4 +1,4 @@
"""Tests for NTP, SNMP, users, config management, ping, traceroute, CLI."""
"""Tests for NTP statistics, SNMP, users, config management, ping, traceroute, CLI."""
from __future__ import annotations
@@ -7,18 +7,6 @@ from unittest.mock import patch
import pytest
class TestGetNTPServers:
def test_returns_configured_servers(self, driver):
result = driver.get_ntp_servers()
assert "pool.ntp.org" in result
assert "time.cloudflare.com" in result
def test_empty_when_no_ntp(self, driver):
driver._node_api().ntp.get.return_value = {}
result = driver.get_ntp_servers()
assert result == {}
class TestGetNTPStats:
NTP_OUTPUT = (
"*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123\n"
@@ -26,19 +14,19 @@ class TestGetNTPStats:
)
def test_synchronized_server(self, driver):
driver._node_api().execute.post.return_value = {"data": self.NTP_OUTPUT}
driver._node_ssh().output = self.NTP_OUTPUT
stats = driver.get_ntp_stats()
synced = [s for s in stats if s["synchronized"]]
assert len(synced) == 1
assert synced[0]["remote"] == "192.168.1.1"
def test_stratum(self, driver):
driver._node_api().execute.post.return_value = {"data": self.NTP_OUTPUT}
driver._node_ssh().output = self.NTP_OUTPUT
stats = driver.get_ntp_stats()
assert stats[0]["stratum"] == 4
def test_empty_when_no_ntp_command(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
driver._node_ssh().output = ""
stats = driver.get_ntp_stats()
assert stats == []
@@ -53,7 +41,7 @@ class TestGetSNMPInformation:
)
def test_communities(self, driver):
driver._node_api().execute.post.return_value = {"data": self.SNMP_CONF}
driver._node_ssh().output = self.SNMP_CONF
result = driver.get_snmp_information()
assert "public" in result["community"]
assert result["community"]["public"]["mode"] == "ro"
@@ -61,30 +49,30 @@ class TestGetSNMPInformation:
assert result["community"]["private"]["mode"] == "rw"
def test_location(self, driver):
driver._node_api().execute.post.return_value = {"data": self.SNMP_CONF}
driver._node_ssh().output = self.SNMP_CONF
result = driver.get_snmp_information()
assert result["location"] == "Server Room A"
def test_contact(self, driver):
driver._node_api().execute.post.return_value = {"data": self.SNMP_CONF}
driver._node_ssh().output = self.SNMP_CONF
result = driver.get_snmp_information()
assert result["contact"] == "admin@example.com"
def test_chassis_id_is_node_name(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
driver._node_ssh().output = ""
result = driver.get_snmp_information()
assert result["chassis_id"] == "pve1"
class TestGetUsers:
def test_pve_users_returned(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
driver._node_ssh().output = ""
result = driver.get_users()
assert "root@pam" in result
assert "napalm@pam" in result
def test_user_has_required_keys(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
driver._node_ssh().output = ""
result = driver.get_users()
for _user, data in result.items():
assert "level" in data
@@ -93,7 +81,7 @@ class TestGetUsers:
def test_root_local_user_from_passwd(self, driver):
passwd_output = "root:x:0:0:root:/root:/bin/bash\n"
driver._node_api().execute.post.return_value = {"data": passwd_output}
driver._node_ssh().output = passwd_output
result = driver.get_users()
assert "root" in result
assert result["root"]["level"] == 15
@@ -136,14 +124,14 @@ class TestConfigManagement:
assert diff == ""
def test_get_config_running(self, driver):
driver._node_api().execute.post.return_value = {"data": self.RUNNING}
driver._node_ssh().output = self.RUNNING
result = driver.get_config(retrieve="running")
assert self.RUNNING in result["running"]
assert result["candidate"] == ""
def test_get_config_sanitized_redacts_password(self, driver):
raw = "password mysecret\nauto eth0\n"
driver._node_api().execute.post.return_value = {"data": raw}
driver._node_ssh().output = raw
result = driver.get_config(retrieve="running", sanitized=True)
assert "mysecret" not in result["running"]
assert "****" in result["running"]
@@ -168,20 +156,45 @@ class TestPing:
)
def test_success(self, driver):
driver._node_api().execute.post.return_value = {"data": self.PING_SUCCESS}
driver._node_ssh().output = self.PING_SUCCESS
result = driver.ping("8.8.8.8")
assert "success" in result
assert result["success"]["probes_sent"] == 2
assert result["success"]["packet_loss"] == 0
assert result["success"]["rtt_min"] == pytest.approx(10.5, abs=0.01)
def test_every_reply_is_a_result(self, driver):
"""iputils puts "from <ip>" before icmp_seq (napalm-proxmox#12)."""
driver._node_ssh().output = self.PING_SUCCESS
result = driver.ping("8.8.8.8")
assert result["success"]["results"] == [
{"ip_address": "8.8.8.8", "rtt": 10.5},
{"ip_address": "8.8.8.8", "rtt": 11.2},
]
def test_a_reply_by_name_and_over_ipv6(self, driver):
output = (
"PING dns.google (8.8.4.4) 56(84) bytes of data.\n"
"64 bytes from dns.google (8.8.4.4): icmp_seq=1 ttl=118 time=123 ms\n"
"64 bytes from 2001:db8::1: icmp_seq=2 ttl=64 time=0.045 ms\n"
"--- dns.google ping statistics ---\n"
"2 packets transmitted, 2 received, 0% packet loss, time 1001ms\n"
"rtt min/avg/max/mdev = 0.045/61.5/123.0/61.4 ms\n"
)
driver._node_ssh().output = output
result = driver.ping("dns.google")
assert result["success"]["results"] == [
{"ip_address": "8.8.4.4", "rtt": 123.0},
{"ip_address": "2001:db8::1", "rtt": 0.045},
]
def test_failure(self, driver):
driver._node_api().execute.post.return_value = {"data": self.PING_FAIL}
driver._node_ssh().output = self.PING_FAIL
result = driver.ping("badhost")
assert "error" in result
def test_exec_unavailable(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
def test_no_output(self, driver):
driver._node_ssh().output = ""
result = driver.ping("8.8.8.8")
assert "error" in result
@@ -195,44 +208,34 @@ class TestTraceroute:
)
def test_success_hops(self, driver):
driver._node_api().execute.post.return_value = {"data": self.TR_OUTPUT}
driver._node_ssh().output = self.TR_OUTPUT
result = driver.traceroute("8.8.8.8")
assert "success" in result
assert 1 in result["success"]
assert 3 in result["success"]
def test_hop_rtt(self, driver):
driver._node_api().execute.post.return_value = {"data": self.TR_OUTPUT}
driver._node_ssh().output = self.TR_OUTPUT
result = driver.traceroute("8.8.8.8")
hop1 = result["success"][1]["probes"]
assert hop1[1]["ip_address"] == "10.0.0.254"
def test_empty_returns_error(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
driver._node_ssh().output = ""
result = driver.traceroute("8.8.8.8")
assert "error" in result
class TestCLI:
def test_cli_single_command(self, driver):
driver._node_api().execute.post.return_value = {"data": "hello world"}
driver._node_ssh().output = "hello world"
result = driver.cli(["echo hello world"])
assert result["echo hello world"] == "hello world"
def test_cli_multiple_commands(self, driver):
responses = {"uptime": "up 2 days", "hostname": "pve1"}
call_count = 0
def _exec(command):
nonlocal call_count
cmd = command
call_count += 1
return {"data": responses.get(cmd, "")}
driver._node_api().execute.post.side_effect = _exec
driver._node_ssh().outputs = {"uptime": "up 2 days", "hostname": "pve1"}
result = driver.cli(["uptime", "hostname"])
assert "uptime" in result
assert "hostname" in result
assert result == {"uptime": "up 2 days", "hostname": "pve1"}
class TestGetRouteTo:
@@ -242,12 +245,12 @@ class TestGetRouteTo:
)
def test_returns_routes(self, driver):
driver._node_api().execute.post.return_value = {"data": self.ROUTE_OUTPUT}
driver._node_ssh().output = self.ROUTE_OUTPUT
result = driver.get_route_to(destination="10.0.0.0/24")
assert "10.0.0.0/24" in result
def test_route_fields(self, driver):
driver._node_api().execute.post.return_value = {"data": self.ROUTE_OUTPUT}
driver._node_ssh().output = self.ROUTE_OUTPUT
result = driver.get_route_to()
for _prefix, routes in result.items():
for route in routes:
@@ -256,7 +259,7 @@ class TestGetRouteTo:
assert "outgoing_interface" in route
def test_protocol_filter(self, driver):
driver._node_api().execute.post.return_value = {"data": self.ROUTE_OUTPUT}
driver._node_ssh().output = self.ROUTE_OUTPUT
result = driver.get_route_to(protocol="dhcp")
for _prefix, routes in result.items():
for route in routes:
@@ -264,35 +267,27 @@ class TestGetRouteTo:
class TestLLDPNeighbors:
# Real `lldpcli show neighbors summary` output. The interface line carries
# ", via: LLDP, ..." after the name, which is what the parser matches on —
# the previous fixture stopped at the name and matched nothing.
LLDP_SUMMARY = (
"LLDP neighbors:\n"
"-------------------------------------------------------------------------------\n"
"Interface: eth0, via: LLDP, RID: 1, Time: 0 day, 00:11:22\n"
" Chassis:\n"
" SysName: sw01.example.com\n"
" Port:\n"
" PortID: ifname GigabitEthernet1/0/1\n"
"-------------------------------------------------------------------------------\n"
"Interface: eth1, via: LLDP, RID: 2, Time: 0 day, 00:11:22\n"
" Chassis:\n"
" SysName: sw02.example.com\n"
" Port:\n"
" PortID: ifname GigabitEthernet1/0/2\n"
"-------------------------------------------------------------------------------\n"
# ``lldpctl -f keyvalue`` with its exit status, as LLDPCTL_KEYVALUE_COMMAND prints
# it (the parse itself is covered in test_lldp.py).
LLDP_KEYVALUE = (
"lldp.eth0.via=LLDP\n"
"lldp.eth0.chassis.name=sw01.example.com\n"
"lldp.eth0.port.ifname=GigabitEthernet1/0/1\n"
"lldp.eth1.via=LLDP\n"
"lldp.eth1.chassis.name=sw02.example.com\n"
"lldp.eth1.port.ifname=GigabitEthernet1/0/2\n"
"__LLDPCTL_RC=0\n"
)
def test_neighbors_found(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value=self.LLDP_SUMMARY):
with patch.object(driver, "_exec_ssh_command", return_value=self.LLDP_KEYVALUE):
result = driver.get_lldp_neighbors()
assert "eth0" in result
assert result["eth0"][0]["hostname"] == "sw01.example.com"
def test_empty_when_no_lldp(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
result = driver.get_lldp_neighbors()
def test_empty_when_no_lldp_neighbour(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value="__LLDPCTL_RC=0"):
result = driver.get_lldp_neighbors()
assert result == {}
@@ -304,22 +299,29 @@ class TestIPv6Neighbors:
)
def test_neighbors_parsed(self, driver):
driver._node_api().execute.post.return_value = {"data": self.IPV6_NEIGH}
driver._node_ssh().output = self.IPV6_NEIGH
result = driver.get_ipv6_neighbors_table()
assert len(result) == 2 # FAILED entry excluded
def test_mac_normalized(self, driver):
driver._node_api().execute.post.return_value = {"data": self.IPV6_NEIGH}
driver._node_ssh().output = self.IPV6_NEIGH
result = driver.get_ipv6_neighbors_table()
macs = {e["mac"] for e in result}
assert "aa:bb:cc:dd:ee:ff" in macs
def test_state_present(self, driver):
driver._node_api().execute.post.return_value = {"data": self.IPV6_NEIGH}
driver._node_ssh().output = self.IPV6_NEIGH
result = driver.get_ipv6_neighbors_table()
states = {e["state"] for e in result}
assert "REACHABLE" in states
def test_age_is_unknown(self, driver):
# `ip neigh` reports no age, as for the IPv4 table; 0.0 would read as
# "confirmed just now" (NetOrk/netork#1327).
driver._node_ssh().output = self.IPV6_NEIGH
result = driver.get_ipv6_neighbors_table()
assert {e["age"] for e in result} == {-1.0}
class TestNotImplemented:
def test_get_bgp_config_raises(self, driver):
+135
View File
@@ -0,0 +1,135 @@
"""get_network_targets names the physical NICs each bridge leaves the node through.
NetOrk follows their LLDP neighbours to the switch port behind the bridge, to
tell whether a VM without a VLAN tag lands in a network at all
(NetOrk/netork#1325). They come in groups, one per way out of the bridge: a
bond's slaves together, a single NIC alone. Internal ports, VLAN subinterfaces
and virtual ports are no uplinks. When a port cannot be told
apart, ``uplinks`` is left out rather than guessed.
"""
from __future__ import annotations
from unittest.mock import MagicMock
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
def _targets(network: list[dict]) -> dict[str, dict]:
mixin = ProxmoxVMProvisionMixin()
mixin._get_node_network = MagicMock(return_value=network)
mixin._get_sdn_vnets = MagicMock(return_value=[])
return {t["name"]: t for t in mixin.get_network_targets()}
def test_linux_bridge_on_a_nic():
targets = _targets(
[
{"iface": "eno1", "type": "eth"},
{"iface": "vmbr0", "type": "bridge", "bridge_ports": "eno1", "bridge_vlan_aware": 1},
]
)
assert targets["vmbr0"]["uplinks"] == [["eno1"]]
def test_linux_bridge_on_a_bond_lists_the_slaves():
targets = _targets(
[
{"iface": "eno1", "type": "eth"},
{"iface": "eno2", "type": "eth"},
{"iface": "bond0", "type": "bond", "slaves": "eno1 eno2"},
{"iface": "vmbr0", "type": "bridge", "bridge_ports": "bond0"},
]
)
assert targets["vmbr0"]["uplinks"] == [["eno1", "eno2"]]
def test_linux_bridge_on_a_vlan_subinterface_has_no_uplink():
"""A bridge on ``eno1.40`` leaves tagged; the port's untagged VLAN is not its."""
targets = _targets(
[
{"iface": "eno1", "type": "eth"},
{"iface": "eno1.40", "type": "vlan", "vlan-raw-device": "eno1"},
{"iface": "vmbr40", "type": "bridge", "bridge_ports": "eno1.40"},
]
)
assert targets["vmbr40"]["uplinks"] == []
def test_host_only_bridge_has_no_uplink():
targets = _targets([{"iface": "vmbr9", "type": "bridge"}])
assert targets["vmbr9"]["uplinks"] == []
def test_ovs_bridge_with_bond_and_internal_port():
"""pve-dual's shape: vmbr0 carries an LACP bond and the management OVSIntPort."""
targets = _targets(
[
{"iface": "nic0", "type": "OVSPort"},
{"iface": "nic1", "type": "OVSPort"},
{
"iface": "bond0",
"type": "OVSBond",
"ovs_bonds": "nic0 nic1",
"ovs_bridge": "vmbr0",
},
{"iface": "mgmt_vlan", "type": "OVSIntPort", "ovs_bridge": "vmbr0", "ovs_tag": 8},
{"iface": "vmbr0", "type": "OVSBridge", "ovs_ports": "bond0 mgmt_vlan"},
]
)
assert targets["vmbr0"]["uplinks"] == [["nic0", "nic1"]]
def test_ovs_bridge_on_a_single_port():
targets = _targets(
[
{"iface": "eno1", "type": "OVSPort", "ovs_bridge": "vmbr1"},
{"iface": "vmbr1", "type": "OVSBridge", "ovs_ports": "eno1"},
]
)
assert targets["vmbr1"]["uplinks"] == [["eno1"]]
def test_ovs_bridge_on_two_single_ports_has_two_groups():
targets = _targets(
[
{"iface": "eno1", "type": "OVSPort", "ovs_bridge": "vmbr1"},
{"iface": "eno2", "type": "OVSPort", "ovs_bridge": "vmbr1"},
{"iface": "vmbr1", "type": "OVSBridge", "ovs_ports": "eno1 eno2"},
]
)
assert targets["vmbr1"]["uplinks"] == [["eno1"], ["eno2"]]
def test_port_missing_from_the_network_config_leaves_uplinks_out():
targets = _targets([{"iface": "vmbr0", "type": "bridge", "bridge_ports": "enp9s0"}])
assert "uplinks" not in targets["vmbr0"]
def test_port_of_an_unknown_kind_leaves_uplinks_out():
targets = _targets(
[
{"iface": "wg0", "type": "unknown"},
{"iface": "vmbr0", "type": "bridge", "bridge_ports": "wg0"},
]
)
assert "uplinks" not in targets["vmbr0"]
def test_vnet_has_no_uplinks():
mixin = ProxmoxVMProvisionMixin()
mixin._get_node_network = MagicMock(return_value=[])
mixin._get_sdn_vnets = MagicMock(return_value=[{"vnet": "vnet0", "zone": "z", "tag": 10}])
(target,) = mixin.get_network_targets()
assert "uplinks" not in target
+109
View File
@@ -0,0 +1,109 @@
"""Commands on the node run over its SSH session, and a failure to run one raises (#17).
``_exec_ssh_command`` used to post to ``/nodes/{node}/execute`` first (a batch of API
calls, not a shell), to return stderr as output, and to return ``""`` whenever the
command could not run at all: no credential, a refused login, a changed host key, a
timeout. "Nothing there" and "could not look" read the same.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import paramiko
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_proxmox.driver import ProxmoxDriver
from tests.test_ssh_host_key import client # noqa: F401 - the fake paramiko client
class _Stream:
def __init__(self, data: bytes | Exception) -> None:
self._data = data
def read(self) -> bytes:
if isinstance(self._data, Exception):
raise self._data
return self._data
class _Shell:
"""The node's SSH session: prints *out* on stdout and *err* on stderr."""
def __init__(self, out: bytes | Exception = b"", err: bytes = b"") -> None:
self.out, self.err = out, err
self.commands: list[str] = []
def exec_command(self, command: str, timeout: int | None = None):
self.commands.append(command)
return None, _Stream(self.out), _Stream(self.err)
def _driver(shell: _Shell | None = None, **kwargs) -> ProxmoxDriver:
driver = ProxmoxDriver("10.0.0.9", "root", kwargs.pop("password", "s3cret"), **kwargs)
driver._node_name = "pve1"
driver._api = MagicMock()
if shell is not None:
driver._node_ssh = MagicMock(return_value=shell) # type: ignore[method-assign]
return driver
def test_a_command_goes_straight_to_the_ssh_session():
shell = _Shell(b"6.8.12-4-pve\n")
driver = _driver(shell)
assert driver._exec_ssh_command("uname -r") == "6.8.12-4-pve"
assert shell.commands == ["uname -r"]
driver._api.nodes.return_value.execute.post.assert_not_called()
def test_stderr_is_not_output():
shell = _Shell(b"", b"cat: /etc/snmp/snmpd.conf: No such file or directory\n")
assert _driver(shell)._exec_ssh_command("cat /etc/snmp/snmpd.conf") == ""
def test_a_refused_login_raises():
driver = _driver()
driver._node_ssh = MagicMock( # type: ignore[method-assign]
side_effect=paramiko.AuthenticationException("Authentication failed.")
)
with pytest.raises(ConnectionException, match="Authentication failed") as err:
driver._exec_ssh_command("uptime")
assert isinstance(err.value.__cause__, paramiko.AuthenticationException)
def test_an_unreachable_node_raises():
driver = _driver()
driver._node_ssh = MagicMock( # type: ignore[method-assign]
side_effect=OSError(113, "No route to host")
)
with pytest.raises(ConnectionException, match="No route to host"):
driver._exec_ssh_command("uptime")
def test_a_timeout_raises():
shell = _Shell(TimeoutError("timed out"))
with pytest.raises(ConnectionException, match="timed out"):
_driver(shell)._exec_ssh_command("apt list --upgradable")
def test_without_an_ssh_credential_nothing_connects(client): # noqa: F811
# An API-token-only node: no API password, no SSH password, no key.
driver = _driver(password="", optional_args={"token_name": "root@pam!t", "token_value": "x"})
with pytest.raises(ConnectionException, match="no SSH credential"):
driver._exec_ssh_command("command -v lldpd")
assert client.connected_with is None
def test_get_snmp_config_raises_where_it_cannot_look(client): # noqa: F811
"""netOrk reads an exception as "SSH not available" and raises no SNMP alarm."""
driver = _driver(password="", optional_args={"token_name": "root@pam!t", "token_value": "x"})
with pytest.raises(ConnectionException):
driver.get_snmp_config()
+86
View File
@@ -0,0 +1,86 @@
"""get_ntp_stats on chrony (Proxmox VE's default) and on ntpd (#18)."""
from __future__ import annotations
from unittest.mock import patch
import pytest
# chrony 4.x, ``chronyc -n -c sources`` then ``chronyc -n -c sourcestats``,
# behind the markers the driver's command prints.
CHRONY = """\
CHRONY_SOURCES
^,*,192.168.1.1,2,6,377,8,-0.000012345,-0.000013000,0.012345678
^,+,10.0.0.2,3,10,17,301,0.000250000,0.000251000,0.020000000
^,?,10.0.0.3,0,6,0,-,0.000000000,0.000000000,0.000000000
CHRONY_SOURCESTATS
192.168.1.1,10,6,320,-0.012,0.150,-0.000001234,0.000045678
10.0.0.2,6,4,1200,0.003,0.400,0.000200000,0.000500000
"""
# ntpd's ``ntpq -pn``: a candidate without tally mark keeps its leading space.
NTPQ = """\
remote refid st t when poll reach delay offset jitter
==============================================================================
*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123
192.168.1.5 10.0.0.1 3 u 40 64 377 2.000 0.100 0.050
"""
def _stats(driver, output):
with patch.object(driver, "_exec_ssh_command", return_value=output):
return driver.get_ntp_stats()
class TestChrony:
def test_every_source_is_reported(self, driver):
assert [s["remote"] for s in _stats(driver, CHRONY)] == [
"192.168.1.1",
"10.0.0.2",
"10.0.0.3",
]
def test_the_selected_source_is_synchronized(self, driver):
stats = _stats(driver, CHRONY)
assert [s["synchronized"] for s in stats] == [True, False, False]
def test_fields_in_ntpq_units(self, driver):
first = _stats(driver, CHRONY)[0]
assert first == {
"remote": "192.168.1.1",
"referenceid": "",
"synchronized": True,
"stratum": 2,
"type": "u",
"when": "8",
"hostpoll": 64,
"reachability": 377,
"delay": 0.0,
"offset": pytest.approx(-0.013),
"jitter": pytest.approx(0.045678),
}
def test_a_source_without_statistics_has_no_jitter(self, driver):
last = _stats(driver, CHRONY)[2]
assert last["jitter"] == 0.0
assert last["when"] == "-"
assert last["reachability"] == 0
def test_the_command_asks_chrony_first(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value="") as exec_:
driver.get_ntp_stats()
assert "chronyc -n -c sources" in exec_.call_args[0][0]
assert "ntpq -pn" in exec_.call_args[0][0]
class TestNtpd:
def test_a_peer_without_tally_mark_is_kept(self, driver):
stats = _stats(driver, NTPQ)
assert [s["remote"] for s in stats] == ["192.168.1.1", "192.168.1.5"]
assert [s["synchronized"] for s in stats] == [True, False]
assert stats[1]["stratum"] == 3
+5 -5
View File
@@ -103,23 +103,23 @@ class TestGetARPTable:
)
def test_arp_entries_returned(self, driver):
driver._node_api().execute.post.return_value = {"data": self.PROC_ARP}
driver._node_ssh().output = self.PROC_ARP
result = driver.get_arp_table()
assert len(result) == 2 # 00:00:00:00:00:00 excluded
def test_mac_normalized(self, driver):
driver._node_api().execute.post.return_value = {"data": self.PROC_ARP}
driver._node_ssh().output = self.PROC_ARP
result = driver.get_arp_table()
macs = {e["mac"] for e in result}
assert "aa:bb:cc:dd:ee:ff" in macs
def test_vrf_filter(self, driver):
driver._node_api().execute.post.return_value = {"data": self.PROC_ARP}
driver._node_ssh().output = self.PROC_ARP
result = driver.get_arp_table(vrf="vmbr0")
assert all(e["interface"] == "vmbr0" for e in result)
def test_empty_when_exec_unavailable(self, driver):
driver._node_api().execute.post.return_value = {"data": ""}
def test_empty_when_the_node_prints_nothing(self, driver):
driver._node_ssh().output = ""
result = driver.get_arp_table()
assert result == []
+2 -2
View File
@@ -60,8 +60,8 @@ def test_the_query_asks_for_the_field():
not, so no amount of parsing could have produced one."""
import inspect
from napalm_proxmox import system_mixin
from napalm_proxmox import host_mixin
source = inspect.getsource(system_mixin.ProxmoxSystemMixin.get_packages)
source = inspect.getsource(host_mixin.ProxmoxHostMixin.get_packages)
assert "source:Version" in source
+553
View File
@@ -0,0 +1,553 @@
"""The backup-server role of the PBS driver: datastores, groups, jobs, remotes and
the actions on them (#52)."""
from __future__ import annotations
import pytest
from proxmoxer.core import ResourceException
from napalm_proxmox import ProxmoxBackupDriver
from tests.pbs_fake import FakePbsApi, forbidden
# --------------------------------------------------------------------------- #
# What the recorded server did not have yet, in the shapes of the PBS API schema
# --------------------------------------------------------------------------- #
T0 = 1793487600 # 2026-11-01
GROUPS_ROOT = [
{
"backup-type": "vm",
"backup-id": "101",
"backup-count": 3,
"last-backup": T0 + 2 * 86400,
"owner": "backup@pbs",
"files": ["drive-scsi0.img.fidx", "index.json.blob"],
"comment": "web-01",
},
{
"backup-type": "ct",
"backup-id": "200",
"backup-count": 1,
"last-backup": T0,
"owner": "backup@pbs",
"files": ["root.pxar.didx"],
},
]
SNAPSHOTS_ROOT = [
{
"backup-type": "vm",
"backup-id": "101",
"backup-time": T0,
"size": 1000,
"protected": False,
"files": [],
"verification": {"state": "ok", "upid": "UPID:pbs:1"},
},
{
"backup-type": "vm",
"backup-id": "101",
"backup-time": T0 + 86400,
"size": 1100,
"protected": False,
"files": [],
"verification": {"state": "failed", "upid": "UPID:pbs:2"},
},
{
"backup-type": "vm",
"backup-id": "101",
"backup-time": T0 + 2 * 86400,
"size": 1200,
"protected": True,
"files": [],
"comment": "before upgrade",
},
{
"backup-type": "ct",
"backup-id": "200",
"backup-time": T0,
"protected": False,
"files": [],
},
]
GROUPS_PROD = [
{"backup-type": "host", "backup-id": "db-01", "backup-count": 0, "last-backup": T0, "files": []}
]
GC = [
{
"store": "backup",
"schedule": "daily",
"last-run-state": "OK",
"last-run-endtime": T0 + 3600,
"next-run": T0 + 86400,
"upid": "UPID:pbs:gc",
"disk-bytes": 0,
"disk-chunks": 0,
"index-data-bytes": 0,
"index-file-count": 0,
"pending-bytes": 0,
"pending-chunks": 0,
"removed-bad": 0,
"removed-bytes": 0,
"removed-chunks": 0,
"still-bad": 0,
}
]
VERIFY = [
{
"id": "v-weekly",
"store": "backup",
"schedule": "sat 03:00",
"last-run-state": "WARNINGS: 2",
"last-run-endtime": T0,
"next-run": T0 + 7 * 86400,
}
]
PRUNE = [{"id": "p-daily", "store": "backup", "ns": "prod", "schedule": "daily", "disable": True}]
SYNC = [
{
"id": "offsite",
"store": "backup",
"remote": "pbs-offsite",
"remote-store": "mirror",
"sync-direction": "push",
"schedule": "hourly",
"last-run-state": "connection refused",
"last-run-endtime": T0,
"next-run": T0 + 3600,
"comment": "second site",
}
]
TAPE = [
{
"id": "t-monthly",
"store": "backup",
"pool": "monthly",
"drive": "lto8",
"schedule": "monthly",
"last-run-upid": "UPID:pbs:tape",
}
]
REMOTES = [
{
"name": "pbs-offsite",
"host": "pbs2.example.com",
"port": 8007,
"auth-id": "sync@pbs",
"fingerprint": "bb:" * 31 + "bb",
"password": "never-reported",
}
]
ALL_RIGHTS = {"/": {"Datastore.Audit": True, "Sys.Audit": True, "Remote.Audit": True}}
def _driver(**responses) -> tuple[ProxmoxBackupDriver, FakePbsApi]:
drv = ProxmoxBackupDriver("pbs1", "root", "secret")
api = FakePbsApi(**responses)
drv._api = api
drv._node_name = "localhost"
return drv, api
def _with_groups(**more):
return _driver(
**{
"admin/datastore/backup/namespace": [{"ns": ""}, {"ns": "prod"}],
"admin/datastore/backup/groups": GROUPS_ROOT,
"admin/datastore/backup/groups?ns=prod": GROUPS_PROD,
"admin/datastore/backup/snapshots": SNAPSHOTS_ROOT,
"admin/datastore/backup/snapshots?ns=prod": [],
**more,
}
)
# --------------------------------------------------------------------------- #
# Rights: a list the token may not see comes back empty, not refused
# --------------------------------------------------------------------------- #
class TestRights:
def test_a_token_without_datastore_audit_is_refused_not_read_as_empty(self):
"""A privilege-separated token without an ACL entry gets [] for the
datastore list; that is no answer, not a server without datastores."""
drv, _ = _driver(**{"access/permissions": {}, "admin/datastore": []})
with pytest.raises(PermissionError, match="Datastore.Audit"):
drv.get_backup_datastores()
def test_remotes_need_remote_audit(self):
drv, _ = _driver(**{"config/remote": []}) # recorded rights lack Remote.Audit
with pytest.raises(PermissionError, match="Remote.Audit"):
drv.get_backup_remotes()
def test_a_right_on_a_parent_path_counts(self):
drv, _ = _driver(**{"access/permissions": ALL_RIGHTS, "config/remote": REMOTES})
assert [r["name"] for r in drv.get_backup_remotes()] == ["pbs-offsite"]
def test_a_refused_path_raises(self):
drv, _ = _driver(**{"status/datastore-usage": forbidden()})
with pytest.raises(Exception, match="403"):
drv.get_backup_datastores()
# --------------------------------------------------------------------------- #
# Datastores (recorded)
# --------------------------------------------------------------------------- #
class TestDatastores:
def test_recorded_removable_datastore(self):
drv, _ = _driver()
assert drv.get_backup_datastores() == [
{
"name": "backup",
# a removable datastore's path is relative to its mount point
"path": None,
"backend": "removable",
"total": 999715438592,
"used": 34838138880,
"available": 964877299712,
"estimated_full": None,
"maintenance": None,
"comment": None,
}
]
def test_s3_backend_estimate_and_maintenance(self):
drv, _ = _driver(
**{
"config/datastore": [
{
"name": "cold",
"path": "/var/cache/pbs/cold",
"backend": "type=s3,client=minio,bucket=pbs",
"maintenance-mode": "type=read-only,message=migrating",
"comment": "object store",
}
],
"status/datastore-usage": [
{
"store": "cold",
"backend-type": "s3",
"mount-status": "nonremovable",
"total": 100,
"used": 40,
"avail": 60,
"estimated-full-date": 1800000000,
}
],
}
)
(store,) = drv.get_backup_datastores()
assert (store["backend"], store["path"], store["estimated_full"]) == (
"s3",
"/var/cache/pbs/cold",
1800000000,
)
assert (store["maintenance"], store["comment"]) == ("read-only", "object store")
def test_an_unmounted_removable_datastore_is_offline(self):
drv, _ = _driver(
**{
"status/datastore-usage": [
{"store": "backup", "backend-type": "filesystem", "mount-status": "notmounted"}
]
}
)
(store,) = drv.get_backup_datastores()
assert (store["maintenance"], store["total"], store["used"]) == ("unmounted", None, None)
# --------------------------------------------------------------------------- #
# Groups and snapshots
# --------------------------------------------------------------------------- #
class TestGroups:
def test_recorded_empty_datastore_has_no_groups(self):
drv, _ = _driver(
**{"admin/datastore/backup/groups": [], "admin/datastore/backup/snapshots": []}
)
assert drv.get_backup_groups() == []
def test_each_group_with_its_newest_snapshot(self):
drv, _ = _with_groups()
groups = {(g["namespace"], g["type"], g["id"]): g for g in drv.get_backup_groups()}
assert groups[("", "vm", "101")] == {
"datastore": "backup",
"namespace": "",
"type": "vm",
"id": "101",
"owner": "backup@pbs",
"count": 3,
"newest": {
"time": T0 + 2 * 86400,
"size": 1200,
"verify": None, # the newest was never verified
"protected": True,
"comment": "before upgrade",
},
"oldest_time": T0,
"comment": "web-01",
}
assert groups[("", "ct", "200")]["newest"]["size"] is None
def test_namespaces_are_walked(self):
drv, _ = _with_groups()
prod = [g for g in drv.get_backup_groups() if g["namespace"] == "prod"]
assert [(g["type"], g["id"], g["count"], g["newest"]) for g in prod] == [
("host", "db-01", 0, None)
]
def test_one_datastore_only(self):
drv, api = _with_groups()
drv.get_backup_groups("backup")
assert all("/other/" not in path for _, path, _ in api.calls)
def test_an_unmounted_removable_datastore_is_left_out_of_the_listing(self):
"""Recorded: the USB disk behind the datastore was unplugged. Its content
cannot be read (400), which must not fail the listing of every datastore;
get_backup_datastores reports it as "unmounted"."""
not_mounted = ResourceException(400, "Bad Request", "datastore 'backup' is not mounted")
drv, _ = _driver(
**{
"admin/datastore": [
{"backend-type": "filesystem", "mount-status": "notmounted", "store": "backup"}
],
"admin/datastore/backup/namespace": not_mounted,
}
)
assert drv.get_backup_groups() == []
with pytest.raises(ValueError, match="not mounted"):
drv.get_backup_groups("backup")
def test_snapshots_of_one_group_newest_first(self):
drv, api = _with_groups(
**{
"admin/datastore/backup/snapshots?backup-id=101&backup-type=vm": [
s for s in SNAPSHOTS_ROOT if s["backup-id"] == "101"
]
}
)
snaps = drv.get_backup_snapshots("backup", "", "vm", "101")
assert [(s["time"], s["verify"]) for s in snaps] == [
(T0 + 2 * 86400, None),
(T0 + 86400, "failed"),
(T0, "ok"),
]
def test_snapshots_in_a_namespace_name_it(self):
drv, api = _with_groups(
**{"admin/datastore/backup/snapshots?backup-id=db-01&backup-type=host&ns=prod": []}
)
assert drv.get_backup_snapshots("backup", "prod", "host", "db-01") == []
# --------------------------------------------------------------------------- #
# Jobs
# --------------------------------------------------------------------------- #
class TestJobs:
def test_recorded_server_has_only_its_unscheduled_gc(self):
drv, _ = _driver()
assert drv.get_backup_jobs() == [
{
"id": "backup",
"kind": "gc",
"datastore": "backup",
"namespace": None,
"schedule": None,
"enabled": False,
"last_run": None,
"last_state": None,
"last_error": None,
"next_run": None,
"remote": None,
"direction": None,
"comment": None,
}
]
def test_every_kind_and_how_its_last_run_ended(self):
drv, _ = _driver(
**{
"admin/gc": GC,
"admin/verify": VERIFY,
"admin/prune": PRUNE,
"admin/sync": SYNC,
"tape/backup": TAPE,
}
)
jobs = {(j["kind"], j["id"]): j for j in drv.get_backup_jobs()}
assert set(jobs) == {
("gc", "backup"),
("verify", "v-weekly"),
("prune", "p-daily"),
("sync", "offsite"),
("tape", "t-monthly"),
}
gc = jobs[("gc", "backup")]
assert (gc["enabled"], gc["last_state"], gc["last_run"], gc["next_run"]) == (
True,
"ok",
T0 + 3600,
T0 + 86400,
)
verify = jobs[("verify", "v-weekly")]
assert (verify["last_state"], verify["last_error"]) == ("warning", "WARNINGS: 2")
prune = jobs[("prune", "p-daily")]
assert (prune["enabled"], prune["namespace"], prune["last_state"]) == (False, "prod", None)
sync = jobs[("sync", "offsite")]
assert (sync["last_state"], sync["last_error"]) == ("error", "connection refused")
assert (sync["remote"], sync["direction"], sync["comment"]) == (
"pbs-offsite",
"push",
"second site",
)
tape = jobs[("tape", "t-monthly")]
assert (tape["last_state"], tape["last_run"]) == ("running", None)
def test_a_sync_without_a_remote_is_local(self):
local = [{**SYNC[0], "remote": None, "sync-direction": None, "id": "local"}]
drv, _ = _driver(
**{"admin/sync": local, "admin/verify": [], "admin/prune": [], "tape/backup": []}
)
sync = next(j for j in drv.get_backup_jobs() if j["kind"] == "sync")
assert (sync["remote"], sync["direction"]) == (None, "pull")
def test_a_failed_listing_fails_the_whole_read(self):
drv, _ = _driver(**{"admin/sync": forbidden()})
with pytest.raises(Exception, match="403"):
drv.get_backup_jobs()
# --------------------------------------------------------------------------- #
# Remotes
# --------------------------------------------------------------------------- #
def test_remotes_never_carry_their_secret():
drv, _ = _driver(**{"access/permissions": ALL_RIGHTS, "config/remote": REMOTES})
assert drv.get_backup_remotes() == [
{
"name": "pbs-offsite",
"host": "pbs2.example.com",
"port": 8007,
"fingerprint": "bb:" * 31 + "bb",
"auth_id": "sync@pbs",
"comment": None,
}
]
# --------------------------------------------------------------------------- #
# Actions and tasks
# --------------------------------------------------------------------------- #
SNAPSHOT = {
"datastore": "backup",
"namespace": "",
"group_type": "vm",
"group_id": "101",
"time": T0,
}
class TestActions:
def test_garbage_collection(self):
drv, api = _driver(**{"POST admin/datastore/backup/gc": "UPID:pbs:gc-now"})
assert drv.start_garbage_collection("backup") == {"task": "UPID:pbs:gc-now"}
@pytest.mark.parametrize(
("kind", "method", "path"),
[
("verify", "POST", "admin/verify/j1/run"),
("prune", "POST", "admin/prune/j1/run"),
("sync", "POST", "admin/sync/j1/run"),
("tape", "POST", "tape/backup/j1"),
("gc", "POST", "admin/datastore/j1/gc"),
],
)
def test_run_a_job_now(self, kind, method, path):
drv, api = _driver(**{f"{method} {path}": "UPID:pbs:run"})
assert drv.run_backup_job(kind, "j1") == {"task": "UPID:pbs:run"}
assert api.calls[-1][:2] == (method, path)
def test_an_unknown_kind_is_refused(self):
drv, _ = _driver()
with pytest.raises(ValueError, match="kind"):
drv.run_backup_job("restore", "j1") # type: ignore[arg-type]
def test_a_run_without_a_task_id_is_an_error(self):
drv, _ = _driver(**{"POST admin/sync/j1/run": None})
with pytest.raises(RuntimeError, match="task"):
drv.run_backup_job("sync", "j1")
def test_verify_one_snapshot(self):
drv, api = _driver(**{"POST admin/datastore/backup/verify": "UPID:pbs:verify"})
assert drv.verify_backup_snapshot(SNAPSHOT) == {"task": "UPID:pbs:verify"}
assert api.calls[-1][2] == {"backup-type": "vm", "backup-id": "101", "backup-time": T0}
def test_namespace_is_passed_where_given(self):
drv, api = _driver(**{"POST admin/datastore/backup/verify": "UPID:pbs:verify"})
drv.verify_backup_snapshot({**SNAPSHOT, "namespace": "prod"})
assert api.calls[-1][2]["ns"] == "prod"
def test_protect_and_unprotect(self):
drv, api = _driver(**{"PUT admin/datastore/backup/protected": None})
drv.set_backup_snapshot_protected(SNAPSHOT, True)
assert api.calls[-1] == (
"PUT",
"admin/datastore/backup/protected",
{"backup-type": "vm", "backup-id": "101", "backup-time": T0, "protected": 1},
)
drv.set_backup_snapshot_protected(SNAPSHOT, False)
assert api.calls[-1][2]["protected"] == 0
def test_delete(self):
drv, api = _driver(**{"DELETE admin/datastore/backup/snapshots": None})
drv.delete_backup_snapshot(SNAPSHOT)
assert api.calls[-1] == (
"DELETE",
"admin/datastore/backup/snapshots",
{"backup-type": "vm", "backup-id": "101", "backup-time": T0},
)
class TestTasks:
UPID = "UPID:pbs:000003E8:0000A000:00000002:6AE8E898:garbage_collection:backup:root@pam!netork:"
def _task(self, status, log=()):
return _driver(
**{
f"nodes/localhost/tasks/{self.UPID}/status": status,
f"nodes/localhost/tasks/{self.UPID}/log?limit=0": [
{"n": i + 1, "t": t} for i, t in enumerate(log)
],
}
)[0]
def test_running(self):
drv = self._task({"upid": self.UPID, "status": "running"}, ["starting garbage collection"])
assert drv.get_backup_task(self.UPID) == {
"task": self.UPID,
"running": True,
"state": "running",
"error": None,
"log": ["starting garbage collection"],
}
@pytest.mark.parametrize(
("exitstatus", "state", "error"),
[
("OK", "ok", None),
("WARNINGS: 1", "warning", "WARNINGS: 1"),
("unable to acquire lock", "error", "unable to acquire lock"),
],
)
def test_finished(self, exitstatus, state, error):
drv = self._task({"upid": self.UPID, "status": "stopped", "exitstatus": exitstatus})
task = drv.get_backup_task(self.UPID)
assert (task["running"], task["state"], task["error"]) == (False, state, error)
+96
View File
@@ -0,0 +1,96 @@
"""Proxmox Backup Server: the second driver of this package (#52).
Its API and web UI listen on 8007, not on PVE's 8006, and its node is always
``localhost``: a PBS has no cluster to look itself up in.
"""
from __future__ import annotations
import tomllib
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_device_types.roles import role_keys_of
from napalm_proxmox import ProxmoxBackupDriver
def _open(username: str = "root", password: str = "secret", **optional_args):
drv = ProxmoxBackupDriver("pbs1", username, password, optional_args=optional_args)
api = MagicMock()
api.version.get.return_value = {"version": "4.0.14", "release": "4.0", "repoid": "abc"}
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api) as cls:
drv.open()
return drv, api, cls.call_args.kwargs
class TestOpen:
def test_password_login_on_the_pbs_port(self):
_, _, kwargs = _open()
assert kwargs == {
"host": "pbs1",
"user": "root@pam",
"password": "secret",
"port": 8007,
"verify_ssl": True,
"backend": "https",
"service": "PBS",
}
def test_token_is_split_for_proxmoxer(self):
_, _, kwargs = _open(token_name="root@pam!netork", token_value="s3cret")
assert (kwargs["user"], kwargs["token_name"], kwargs["token_value"]) == (
"root@pam",
"netork",
"s3cret",
)
assert "password" not in kwargs
def test_port_from_the_arguments(self):
assert _open(port=443)[2]["port"] == 443
def test_node_is_localhost_without_asking_a_cluster(self):
drv, api, _ = _open()
assert drv._node_name == "localhost"
api.cluster.status.get.assert_not_called()
def test_open_proves_the_login(self):
"""proxmoxer logs in lazily for a token; open() must fail on a bad one,
not the first getter."""
drv = ProxmoxBackupDriver("pbs1", "root", "", optional_args={"token_name": "a!b"})
api = MagicMock()
api.version.get.side_effect = Exception("401 Unauthorized")
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
with pytest.raises(ConnectionException, match="401"):
drv.open()
def test_alive_and_closed(self):
drv, api, _ = _open()
assert drv.is_alive() == {"is_alive": True}
drv.close()
assert drv.is_alive() == {"is_alive": False}
class TestDriverFacts:
def test_backup_server_first_storage_second(self):
assert role_keys_of(ProxmoxBackupDriver)[:2] == ["backup_server", "storage"]
def test_found_on_8007_by_its_own_banner(self):
assert [(p.scheme, p.port) for p in ProxmoxBackupDriver.PORT_SPECS] == [("https", 8007)]
mandatory = [r.pattern for r in ProxmoxBackupDriver.HTTP_FINGERPRINT if r.mandatory]
assert mandatory == ["proxmox backup server"]
def test_names(self):
assert ProxmoxBackupDriver.DRIVER_NAME == "proxmox_backup"
assert ProxmoxBackupDriver.platform == "proxmox_backup"
assert ProxmoxBackupDriver.VENDOR == "Proxmox"
assert ProxmoxBackupDriver.FULL_UPGRADE is True
def test_entry_point(self):
project = tomllib.loads((Path(__file__).parents[1] / "pyproject.toml").read_text())
assert project["project"]["entry-points"]["napalm.drivers"] == {
"proxmox": "napalm_proxmox:ProxmoxDriver",
"proxmox_backup": "napalm_proxmox:ProxmoxBackupDriver",
}
+193
View File
@@ -0,0 +1,193 @@
"""The PBS driver as a host: facts, interfaces, environment, disks and pools for
the storage role, subscription and packages (#52)."""
from __future__ import annotations
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_proxmox import ProxmoxBackupDriver
from tests.pbs_fake import FakePbsApi
DMI = "QEMU\nStandard PC (Q35 + ICH9, 2009)\npc-q35-10.0\n\n"
LINKS = "lo 00:00:00:00:00:00\nnic0 02:00:00:00:00:80\n"
def _driver(ssh: dict[str, str] | None = None, **responses) -> ProxmoxBackupDriver:
"""A PBS driver on recorded answers; *ssh* maps a command's start to its output,
and without it the server has no SSH login."""
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
api = FakePbsApi(**responses)
drv._api = api
drv._node_name = "localhost"
def exec_ssh(command: str) -> str:
if ssh is None:
raise ConnectionException("no SSH credential for 192.0.2.80")
for start, output in ssh.items():
if start in command:
return output
return ""
drv._exec_ssh_command = exec_ssh # type: ignore[method-assign]
return drv
SSH = {"hostname -f": "pbs.example.com", "dmi": DMI, "/sys/class/net": LINKS}
class TestFacts:
def test_from_the_api_and_ssh(self):
facts = _driver(SSH).get_facts()
assert facts == {
"uptime": 5234.0,
"vendor": "QEMU",
"model": "Standard PC (Q35 + ICH9, 2009)",
"hostname": "pbs",
"fqdn": "pbs.example.com",
"os_version": "Proxmox Backup Server 4.2",
"serial_number": "",
"interface_list": ["nic0"],
"running_kernel": "7.0.0-3-pve",
}
def test_without_ssh_the_api_alone(self):
"""A token-only server: no shell, so no DMI and no host name of its own."""
facts = _driver().get_facts()
assert (facts["hostname"], facts["fqdn"]) == ("192.0.2.80", "192.0.2.80")
assert (facts["vendor"], facts["model"]) == (
"Proxmox Server Solutions GmbH",
"Proxmox Backup Server",
)
assert facts["running_kernel"] == "7.0.0-3-pve"
class TestInterfaces:
def test_recorded_interface_with_its_mac_over_ssh(self):
assert _driver(SSH).get_interfaces() == {
"nic0": {
"is_up": True,
"is_enabled": True,
"description": "",
"last_flapped": -1.0,
"speed": -1.0,
"mtu": 1500,
"mac_address": "02:00:00:00:00:80",
}
}
def test_without_ssh_no_mac(self):
assert _driver().get_interfaces()["nic0"]["mac_address"] == ""
def test_addresses(self):
assert _driver().get_interfaces_ip() == {
"nic0": {"ipv4": {"192.0.2.80": {"prefix_length": 24}}}
}
def test_environment_from_the_node_status():
env = _driver().get_environment()
assert env["cpu"] == {"0": {"%usage": 1.49}}
assert env["memory"] == {"available_ram": 4103909376, "used_ram": 541790208}
assert (env["fans"], env["temperature"], env["power"]) == ({}, {}, {})
class TestStorageRole:
def test_recorded_disks(self):
disks = _driver().get_disks()
assert [d["slot"] for d in disks] == ["sda", "sdc"]
assert disks[1] == {
"slot": "sdc",
"model": "Samsung_SSD_850_EVO_1TB",
"serial": "S0000000000000X",
"vendor": "ASMT",
# as the server reports it: behind a USB bridge it took the SSD for a disk
"type": "hdd",
"size": 1000204886016,
"rpm": 0,
"temperature": -1,
"health": "healthy",
"pool": "",
}
assert disks[0]["type"] == "ssd"
@pytest.mark.parametrize(
("status", "health"), [("passed", "healthy"), ("failed", "failed"), ("unknown", "unknown")]
)
def test_disk_health(self, status, health):
drv = _driver(
**{
"nodes/localhost/disks/list": [
{"name": "sdc", "devpath": "/dev/sdc", "status": status}
]
}
)
assert drv.get_disks()[0]["health"] == health
def test_recorded_server_has_no_zfs_pool(self):
assert _driver().get_disk_pools() == {}
def test_zfs_pool(self):
drv = _driver(
**{
"nodes/localhost/disks/zfs": [
{
"name": "tank",
"size": 1000,
"alloc": 400,
"free": 600,
"health": "DEGRADED",
"dedup": 1.0,
"frag": 3,
}
]
}
)
assert drv.get_disk_pools() == {
"tank": {
"name": "tank",
"type": "zfs",
"level": "",
"status": "degraded",
"total": 1000,
"used": 400,
"available": 600,
"disks": [],
"auto_expand": False,
"dedup": False,
"compression": "",
}
}
class TestHost:
def test_subscription_is_the_pbs_one(self):
assert _driver().get_licenses() == [
{"name": "pbs-subscription", "status": "none", "detail": "There is no subscription key"}
]
def test_reboot_and_shutdown_through_the_api(self):
drv = _driver(**{"POST nodes/localhost/status": None})
drv.reboot_host()
drv.shutdown_host()
calls = [c for c in drv._api.calls if c[0] == "POST"]
assert calls == [
("POST", "nodes/localhost/status", {"command": "reboot"}),
("POST", "nodes/localhost/status", {"command": "shutdown"}),
]
def test_packages_name_their_source(self):
drv = _driver({"dpkg-query": "proxmox-backup-server\t4.2.0-1\tinstalled\t100\t\t\n"})
(pkg,) = drv.get_packages()
assert (pkg["name"], pkg["source"]) == ("proxmox-backup-server", "pbs")
def test_os_capabilities_present(self):
for name in (
"get_kernel_facts",
"get_listening_sockets",
"get_available_updates",
"apply_updates",
"get_ssh_server_algorithms",
"get_services",
):
assert hasattr(ProxmoxBackupDriver, name), name
+46
View File
@@ -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")
+151
View File
@@ -0,0 +1,151 @@
"""get_running_backups: what a restart of the node, or of one of its guests, would abort.
PVE: the node's active vzdump tasks, and the guests locked for their backup
(``lock: backup``); a task names its guest when it backs up one, else the
guests it is taking now are the locked ones. PBS: the running backup, sync,
verify, garbage collection, prune and tape tasks. A failed read raises: an
empty list would say nothing runs (NetOrk/netork#2318).
"""
from __future__ import annotations
import pytest
from proxmoxer.core import ResourceException
from napalm_proxmox import ProxmoxBackupDriver
from tests.pbs_fake import FakePbsApi
T0 = 1793660400
UPID_JOB = "UPID:pve1:0001F2A3:00C4B1D2:6731A0C0:vzdump::root@pam:"
UPID_ONE = "UPID:pve1:0001F2A4:00C4B1D3:6731A0D0:vzdump:105:root@pam:"
def _pve(driver, tasks, resources):
node = driver._api.nodes.return_value
node.tasks.get.return_value = tasks
driver._api.cluster.resources.get.return_value = resources
return node
def test_nothing_runs(driver):
_pve(driver, [], [{"vmid": 101, "node": "pve1", "type": "qemu"}])
assert driver.get_running_backups() == []
def test_asks_for_the_nodes_active_vzdump_tasks_and_the_guests(driver):
node = _pve(driver, [], [])
driver.get_running_backups()
node.tasks.get.assert_called_once_with(source="active", typefilter="vzdump")
driver._api.cluster.resources.get.assert_called_once_with(type="vm")
def test_a_job_takes_the_guests_locked_on_this_node(driver):
_pve(
driver,
[{"upid": UPID_JOB, "type": "vzdump", "id": "", "starttime": T0}],
[
{"vmid": 101, "node": "pve1", "type": "qemu", "lock": "backup"},
{"vmid": 102, "node": "pve1", "type": "lxc"},
{"vmid": 103, "node": "pve2", "type": "qemu", "lock": "backup"},
{"vmid": 104, "node": "pve1", "type": "qemu", "lock": "migrate"},
],
)
assert driver.get_running_backups() == [
{"kind": "backup", "job": None, "task": UPID_JOB, "guests": ["101"], "since": T0}
]
def test_a_task_for_one_guest_names_it(driver):
_pve(
driver,
[{"upid": UPID_ONE, "type": "vzdump", "id": "105", "starttime": T0}],
[{"vmid": 105, "node": "pve1", "type": "qemu", "lock": "backup"}],
)
assert driver.get_running_backups() == [
{"kind": "backup", "job": None, "task": UPID_ONE, "guests": ["105"], "since": T0}
]
def test_a_guest_locked_without_a_task_still_counts(driver):
"""The task list can lag, or a lock outlive its task: the guest is not restarted."""
_pve(driver, [], [{"vmid": 101, "node": "pve1", "type": "qemu", "lock": "backup"}])
assert driver.get_running_backups() == [
{"kind": "backup", "job": None, "task": None, "guests": ["101"], "since": None}
]
def test_another_tasks_type_is_left_out(driver):
_pve(driver, [{"upid": "UPID:pve1:1:2:3:qmstart:101:root@pam:", "type": "qmstart"}], [])
assert driver.get_running_backups() == []
def test_a_failed_read_raises(driver):
driver._api.nodes.return_value.tasks.get.side_effect = ResourceException(
403, "Forbidden", "Permission check failed (/nodes/pve1, Sys.Audit)"
)
with pytest.raises(ResourceException):
driver.get_running_backups()
# --------------------------------------------------------------------------- #
# Proxmox Backup Server
# --------------------------------------------------------------------------- #
def _pbs(tasks):
drv = ProxmoxBackupDriver("pbs1", "root", "secret")
drv._api = FakePbsApi(**{"nodes/localhost/tasks?running=1": tasks})
drv._node_name = "localhost"
return drv
def _task(worker_type: str, worker_id: str | None, n: int = 1) -> dict:
upid = f"UPID:localhost:{n:08X}:00000000:00000000:6731A0C0:{worker_type}:{worker_id or ''}:root@pam:"
return {"upid": upid, "worker_type": worker_type, "worker_id": worker_id, "starttime": T0 + n}
def test_pbs_kinds():
tasks = [
_task("backup", "store1:vm/101", 1),
_task("syncjob", "store1:offsite:store1::s-1a2b", 2),
_task("verificationjob", "store1:v-3c4d", 3),
_task("verify_snapshot", "store1:vm/101/2026-11-01T00:00:00Z", 4),
_task("garbage_collection", "store1", 5),
_task("prunejob", "store1:p-5e6f", 6),
_task("tape-backup-job", "weekly", 7),
]
found = _pbs(tasks).get_running_backups()
assert [(b["kind"], b["job"]) for b in found] == [
("backup", "store1:vm/101"),
("sync", "store1:offsite:store1::s-1a2b"),
("verify", "store1:v-3c4d"),
("verify", "store1:vm/101/2026-11-01T00:00:00Z"),
("gc", "store1"),
("prune", "store1:p-5e6f"),
("tape", "weekly"),
]
assert all(b["guests"] == [] for b in found)
assert found[0]["task"] == tasks[0]["upid"]
assert found[0]["since"] == T0 + 1
def test_pbs_leaves_out_what_is_no_backup():
"""A restore reads, a log rotation is housekeeping: neither is broken by a restart
the way a backup is."""
assert (
_pbs([_task("reader", "store1:vm/101"), _task("logrotate", None)]).get_running_backups()
== []
)
def test_pbs_nothing_runs():
assert _pbs([]).get_running_backups() == []
def test_pbs_a_failed_read_raises():
drv = _pbs([])
drv._api.responses["nodes/localhost/tasks?running=1"] = ResourceException(
403, "Forbidden", "permission check failed"
)
with pytest.raises(ResourceException):
drv.get_running_backups()
+137
View File
@@ -0,0 +1,137 @@
"""Scheduled jobs on a Proxmox VE node and a Proxmox Backup Server (#56).
The report, its parse and every write are napalm-device-types'
``PosixScheduledJobsMixin``'s; the drivers carry the command across
``run_command`` as root in one round trip and say which jobs Proxmox itself
ships (``platform``).
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from napalm_device_types import CommandResult, PosixScheduledJobsMixin, ScheduledJobRefused
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
_TIMER = """|Id={name}.timer
|Unit={name}.service
|Description={name}
|TimersCalendar={{ OnCalendar=*-*-* 06:00:00 ; next_elapse=n/a }}
|NextElapseUSecRealtime=@1762236000
|LastTriggerUSec=@1762149600
|UnitFileState=enabled
|ActiveState=active
|FragmentPath={path}
|"""
_UNIT = """|Id={name}.service
|ExecStart={{ path=/usr/bin/{name} ; argv[]=/usr/bin/{name} ; }}
|Result=success
|FragmentPath={path}
|"""
def _report(*timers: tuple[str, str]) -> str:
return "\n".join(
[
"SJ_BEGIN",
"[system /etc/cron.d/vzdump]",
"|0 1 * * 6 root vzdump 100 --mode snapshot --quiet 1",
"[system /etc/cron.d/zfsutils-linux]",
"|0 0 * * 0 root /usr/lib/zfs-linux/scrub",
"[user /var/spool/cron/crontabs/root]",
"|*/5 * * * * /root/check.sh",
"[systemd]",
"[timers]",
*(_TIMER.format(name=n, path=p) for n, p in timers),
"[units]",
*(_UNIT.format(name=n, path=p.replace(".timer", ".service")) for n, p in timers),
"[tz]",
"/usr/share/zoneinfo/Europe/Berlin",
"[owners]",
"zfsutils-linux: /etc/cron.d/zfsutils-linux",
*(f"{n.split('-')[0]}: {p}" for n, p in timers),
"SJ_END",
"",
]
)
PVE_REPORT = _report(
("pve-daily-update", "/lib/systemd/system/pve-daily-update.timer"),
("pvesr", "/usr/lib/systemd/system/pvesr.timer"),
("apt-daily", "/usr/lib/systemd/system/apt-daily.timer"),
)
PBS_REPORT = _report(
("proxmox-backup-daily-update", "/usr/lib/systemd/system/proxmox-backup-daily-update.timer"),
("pve-daily-update", "/lib/systemd/system/pve-daily-update.timer"),
("apt-daily", "/usr/lib/systemd/system/apt-daily.timer"),
)
VERBS = ("get_scheduled_jobs", "manage_scheduled_job", "put_scheduled_job", "delete_scheduled_job")
def _driver(cls: type, report: str) -> MagicMock:
driver = cls("host", "root@pam", "pw")
driver.run_command = MagicMock(return_value=CommandResult(report, "", 0))
return driver
def _by_source(driver: MagicMock) -> dict[str, dict[str, object]]:
return {str(j["source"]): dict(j) for j in driver.get_scheduled_jobs()["jobs"]}
@pytest.mark.parametrize(
("cls", "report"),
[(ProxmoxDriver, PVE_REPORT), (ProxmoxBackupDriver, PBS_REPORT)],
ids=["pve", "pbs"],
)
def test_each_driver_offers_every_verb_and_reads_as_root_once(cls: type, report: str) -> None:
assert issubclass(cls, PosixScheduledJobsMixin)
for verb in VERBS:
assert callable(getattr(cls, verb))
driver = _driver(cls, report)
reading = driver.get_scheduled_jobs()
assert reading["time_zone"] == "Europe/Berlin"
assert len(reading["jobs"]) == 6
driver.run_command.assert_called_once()
assert driver.run_command.call_args.kwargs["privileged"] is True
def test_what_proxmox_ve_ships_is_platform() -> None:
jobs = _by_source(_driver(ProxmoxDriver, PVE_REPORT))
managed = {source: job["managed_by"] for source, job in jobs.items()}
assert managed == {
"/lib/systemd/system/pve-daily-update.timer": "platform",
"/usr/lib/systemd/system/pvesr.timer": "platform",
"/etc/cron.d/vzdump": "platform",
"/usr/lib/systemd/system/apt-daily.timer": "package",
"/etc/cron.d/zfsutils-linux": "package",
"/var/spool/cron/crontabs/root": "admin",
}
assert jobs["/lib/systemd/system/pve-daily-update.timer"]["actions"] == [
"enable",
"disable",
"run",
]
def test_what_a_backup_server_ships_is_platform() -> None:
jobs = _by_source(_driver(ProxmoxBackupDriver, PBS_REPORT))
managed = {source: job["managed_by"] for source, job in jobs.items()}
assert managed["/usr/lib/systemd/system/proxmox-backup-daily-update.timer"] == "platform"
# Proxmox VE's names mean nothing on a backup server.
assert managed["/lib/systemd/system/pve-daily-update.timer"] == "package"
assert managed["/etc/cron.d/vzdump"] == "admin"
assert managed["/usr/lib/systemd/system/apt-daily.timer"] == "package"
def test_a_vzdump_cron_line_only_runs() -> None:
"""``/etc/cron.d/vzdump`` links into pmxcfs (``/etc/pve``), where no switch writes."""
driver = _driver(ProxmoxDriver, PVE_REPORT)
job = _by_source(driver)["/etc/cron.d/vzdump"]
assert job["actions"] == ["run"]
with pytest.raises(ScheduledJobRefused):
driver.manage_scheduled_job(str(job["key"]), "disable", digest=str(job["digest"]))
assert driver.run_command.call_count == 2 # two readings, nothing written
+180
View File
@@ -0,0 +1,180 @@
"""set_hostname: what it writes to /etc/hosts, and that it leaves a clustered node alone
(napalm-proxmox#21)."""
from __future__ import annotations
import base64
import re
import shlex
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_proxmox import ProxmoxDriver
HOSTS = """\
127.0.0.1 localhost.localdomain localhost
# pve is the node; pve-backup its backup target
10.0.0.1 pve.old.lan pve
10.0.0.2 pve-backup.old.lan pve-backup
"""
class _Node:
"""The node's shell: /etc/hostname reads "pve", /etc/hosts reads HOSTS.
*cluster_check* is what the test for a corosync.conf prints: exit status 1
(no corosync.conf, a single node) unless a test says otherwise.
"""
def __init__(self) -> None:
self.ran: list[str] = []
self.cluster_check = "__PVE_RC=1"
def __call__(self, command: str) -> str:
self.ran.append(command)
if "corosync.conf" in command:
return self.cluster_check
if command.startswith("cat /etc/hostname"):
return "pve\n"
if command.startswith("cat /etc/hosts"):
return HOSTS
return ""
def written_hosts(self) -> str:
write = next(c for c in self.ran if "/etc/hosts" in c and "base64 -d" in c)
return base64.b64decode(re.search(r"echo (\S+) \| base64 -d", write).group(1)).decode()
@pytest.fixture
def node() -> _Node:
return _Node()
@pytest.fixture
def driver(node: _Node) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = node
return d
def test_an_fqdn_renames_the_nodes_names_and_nothing_else(driver, node):
driver.set_hostname("new.dom.lan")
assert node.written_hosts() == (
"127.0.0.1 localhost.localdomain localhost\n"
"# pve is the node; pve-backup its backup target\n"
"10.0.0.1 new.dom.lan new\n"
"10.0.0.2 pve-backup.old.lan pve-backup\n"
)
def test_a_short_name_keeps_the_old_domain(driver, node):
driver.set_hostname("new")
assert "10.0.0.1 new.old.lan new\n" in node.written_hosts()
assert "10.0.0.2 pve-backup.old.lan pve-backup\n" in node.written_hosts()
def test_the_same_name_leaves_hosts_alone(driver, node):
driver.set_hostname("pve")
assert not any("/etc/hosts" in c and "base64 -d" in c for c in node.ran)
def test_a_clustered_node_is_refused_before_anything_changes(driver, node):
node.cluster_check = "__PVE_RC=0"
with pytest.raises(CommandErrorException, match="part of a cluster"):
driver.set_hostname("new")
assert [c for c in node.ran if "corosync.conf" not in c] == []
def test_the_cluster_check_looks_at_both_corosync_confs(driver, node):
driver.set_hostname("new")
check = next(c for c in node.ran if "corosync.conf" in c)
assert "/etc/pve/corosync.conf" in check
assert "/etc/corosync/corosync.conf" in check
def test_an_unreadable_cluster_check_refuses_too(driver, node):
node.cluster_check = ""
with pytest.raises(CommandErrorException, match="could not tell"):
driver.set_hostname("new")
assert [c for c in node.ran if "corosync.conf" not in c] == []
# ── the name reaches the shell quoted (NetOrk/netork#2456) ──────────────────
#
# The name went into the root commands between single quotes of their own, so a name
# with a single quote ended them: ``x';reboot;'`` ran ``reboot``. Each command now
# hands it on as one shell word, whatever it holds.
INJECTED = "x';reboot;'"
def _run(node: _Node, start: str) -> str:
return next(c for c in node.ran if c.startswith(start))
def test_the_runtime_hostname_is_one_word(driver, node):
driver.set_hostname(f"{INJECTED}.dom.lan")
assert shlex.split(_run(node, "hostname ")) == ["hostname", INJECTED]
def test_postfix_gets_the_fqdn_as_one_word(driver, node):
driver.set_hostname(f"{INJECTED}.dom.lan")
words = shlex.split(_run(node, "command -v postconf"))
assert words[words.index("-e") + 1] == f"myhostname = {INJECTED}.dom.lan"
def test_the_node_directory_is_moved_by_quoted_paths(driver, node):
driver.set_hostname(INJECTED)
words = shlex.split(_run(node, "if [ -d"))
assert words[words.index("mv") + 1 : words.index("mv") + 3] == [
"/etc/pve/nodes/pve",
f"/etc/pve/nodes/{INJECTED}",
]
@pytest.mark.parametrize("name", [INJECTED, "$(reboot)", "`reboot`", "a b"])
def test_no_command_runs_what_the_name_holds(driver, node, name):
driver.set_hostname(name)
for command in node.ran:
words = list(shlex.shlex(command, posix=True, punctuation_chars=True))
assert "reboot" not in words, command
# ── /etc/hosts is written through a private temporary file (#66, NetOrk/netork#2446) ──
#
# The new file was written as root to the fixed /tmp/_netork_hosts and moved over
# /etc/hosts: a local user could create that file (or a symlink) beforehand and own
# /etc/hosts afterwards. It is now a mktemp file beside the target, in root's /etc.
def _hosts_write(node: _Node) -> str:
return next(c for c in node.ran if "/etc/hosts" in c and "base64 -d" in c)
def test_hosts_goes_through_a_mktemp_file_in_etc(driver, node):
driver.set_hostname("new")
write = _hosts_write(node)
assert "/tmp/" not in write
assert write.startswith("t=$(mktemp /etc/.hosts.XXXXXX) && ")
assert ' | base64 -d > "$t" && chmod 644 "$t" && mv "$t" /etc/hosts' in write
assert write.endswith(' || { rm -f "$t"; false; }')
def test_what_is_written_is_still_the_new_hosts(driver, node):
driver.set_hostname("new")
assert "10.0.0.1 new.old.lan new\n" in node.written_hosts()
+74
View File
@@ -0,0 +1,74 @@
"""shutdown_host and begin_stop_vm: shutting down without waiting.
Through the API, never over SSH: ``shutdown_host`` asks the node to shut
itself down, ``begin_stop_vm`` asks a guest for its clean (ACPI) shutdown and
returns once Proxmox accepted it — the caller reads ``get_vm_status`` until it
stopped (NetOrk/netork#1636). Neither waits for a task.
"""
from __future__ import annotations
import pytest
def test_shutdown_host_posts_shutdown_to_the_node(driver):
driver.shutdown_host()
driver._node_api().status.post.assert_called_once_with(command="shutdown")
def test_a_refused_shutdown_is_a_runtime_error(driver):
driver._node_api().status.post.side_effect = Exception("Permission check failed")
with pytest.raises(RuntimeError, match="Permission check failed"):
driver.shutdown_host()
def _guests(driver, qemu, lxc=()):
node = driver._node_api()
node.qemu.get.return_value = list(qemu)
node.lxc.get.return_value = list(lxc)
return node
def test_begin_stop_vm_asks_for_a_clean_shutdown_and_does_not_wait(driver, monkeypatch):
node = _guests(driver, [{"vmid": 650, "name": "build-01"}])
waited = []
monkeypatch.setattr(driver, "_wait_for_task", lambda *a, **k: waited.append(a), raising=False)
driver.begin_stop_vm("650")
node.qemu.assert_called_with(650)
node.qemu(650).status.shutdown.post.assert_called_once_with()
assert waited == []
def test_begin_stop_vm_finds_a_guest_by_name(driver):
node = _guests(driver, [{"vmid": 650, "name": "build-01"}])
driver.begin_stop_vm("build-01")
node.qemu(650).status.shutdown.post.assert_called_once_with()
def test_begin_stop_vm_of_a_container(driver):
node = _guests(driver, [], [{"vmid": 700, "name": "ct"}])
driver.begin_stop_vm("700")
node.lxc(700).status.shutdown.post.assert_called_once_with()
def test_an_unknown_guest_is_a_value_error(driver):
_guests(driver, [])
with pytest.raises(ValueError):
driver.begin_stop_vm("999")
def test_a_refused_request_is_a_runtime_error(driver):
node = _guests(driver, [{"vmid": 650, "name": "build-01"}])
node.qemu(650).status.shutdown.post.side_effect = Exception("VM is locked")
with pytest.raises(RuntimeError, match="VM is locked"):
driver.begin_stop_vm("650")
+6 -5
View File
@@ -1,7 +1,7 @@
"""The node's SSH session verifies its host key, and reports the one it sees (NetOrk/netork#1167).
Both ways onto the node's shell — the best-effort ``_exec_ssh_command`` and the
provisioning steps' ``_run_node_command`` — share one session, opened on port 22.
Both ways onto the node's shell — ``_exec_ssh_command`` and the provisioning
steps' ``_run_node_command`` — share one session, opened on port 22.
"""
from __future__ import annotations
@@ -87,7 +87,6 @@ def _driver(seen: list, known: dict | None = None) -> ProxmoxDriver:
if known is not None:
args[KNOWN_KEYS_ARG] = known
driver = ProxmoxDriver("10.0.0.9", "root", "s3cret", optional_args=args)
driver._node_api = MagicMock(side_effect=RuntimeError("no exec endpoint")) # type: ignore[method-assign]
return driver
@@ -116,10 +115,12 @@ def test_a_changed_key_stops_a_provisioning_step(client):
assert seen[0]["accepted"] is False
def test_a_changed_key_leaves_the_best_effort_read_empty(client):
def test_a_changed_key_stops_a_read_too(client):
"""It used to read as empty output, "nothing there" (#17)."""
seen: list = []
driver = _driver(seen, {"22": SshHostKey.of(OTHER_KEY).as_dict()})
assert driver._exec_ssh_command("cat /etc/os-release") == ""
with pytest.raises(SshHostKeyMismatch):
driver._exec_ssh_command("cat /etc/os-release")
assert client.commands == []
assert seen[0]["accepted"] is False
+92
View File
@@ -0,0 +1,92 @@
"""The node's SSH login takes any key type, and a key wins over the API password (#17)."""
from __future__ import annotations
import io
import paramiko
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
from napalm_proxmox.driver import ProxmoxDriver
from tests.test_ssh_host_key import client # noqa: F401 - the fake paramiko client fixture
def _ed25519_pem() -> str:
key = ed25519.Ed25519PrivateKey.generate()
return key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.OpenSSH,
serialization.NoEncryption(),
).decode()
def _paramiko_pem(key: paramiko.PKey) -> str:
out = io.StringIO()
key.write_private_key(out)
return out.getvalue()
def _driver(key: str, ssh_password: str | None = None) -> ProxmoxDriver:
args = {"ssh_private_key_str": key}
if ssh_password is not None:
args["ssh_password"] = ssh_password
return ProxmoxDriver("10.0.0.9", "root", "api-s3cret", optional_args=args)
@pytest.mark.parametrize(
("pem", "kind"),
[
(_ed25519_pem(), paramiko.Ed25519Key),
(_paramiko_pem(paramiko.ECDSAKey.generate()), paramiko.ECDSAKey),
(_paramiko_pem(paramiko.RSAKey.generate(1024)), paramiko.RSAKey),
],
)
def test_any_key_type_logs_in_although_an_api_password_is_set(client, pem, kind): # noqa: F811
_driver(pem)._node_ssh()
assert isinstance(client.connected_with["pkey"], kind)
def test_the_password_stays_as_the_fallback(client): # noqa: F811
_driver(_ed25519_pem(), ssh_password="ssh-pw")._node_ssh()
assert client.connected_with["password"] == "ssh-pw"
def test_without_key_the_password_logs_in(client): # noqa: F811
ProxmoxDriver("10.0.0.9", "root", "api-s3cret")._node_ssh()
assert client.connected_with["password"] == "api-s3cret"
assert "pkey" not in client.connected_with
def test_a_key_that_cannot_be_read_leaves_the_password(client, caplog): # noqa: F811
_driver("not a key")._node_ssh()
assert "pkey" not in client.connected_with
assert client.connected_with["password"] == "api-s3cret"
assert "not a key" not in caplog.text
assert "could not be read" in caplog.text
def test_a_token_only_login_sends_no_empty_password(client): # noqa: F811
ProxmoxDriver(
"10.0.0.9", "root", "", optional_args={"ssh_private_key_str": _ed25519_pem()}
)._node_ssh()
assert "password" not in client.connected_with
@pytest.mark.parametrize(
"args",
[{"ssh_private_key_str": _ed25519_pem()}, {"ssh_password": "ssh-pw"}, {}],
ids=["key", "ssh-password", "api-password"],
)
def test_only_the_given_credentials_log_in(client, args): # noqa: F811
"""Neither the keys in the worker's own ~/.ssh nor an SSH agent it reaches (#48)."""
ProxmoxDriver("10.0.0.9", "root", "api-s3cret", optional_args=args)._node_ssh()
assert client.connected_with["look_for_keys"] is False
assert client.connected_with["allow_agent"] is False
+125
View File
@@ -0,0 +1,125 @@
"""The node's sshd can be hardened: a node runs Debian's stock OpenSSH (NetOrk/netork#1027).
Proxmox VE leaves sshd_config to Debian, with ``Include /etc/ssh/sshd_config.d/*.conf``,
so napalm-device-types' ``OpenSshServerMixin`` works as it does on a plain Linux host.
What it needs from the driver is ``run_command``: an exec channel on the node's SSH
session, with stdin, stderr and the exit status kept apart.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import paramiko
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_device_types import CommandResult
from napalm_proxmox.driver import ProxmoxDriver
class _Channel:
"""An exec channel that prints *out* and *err* and exits with *status*."""
def __init__(self, out: bytes = b"", err: bytes = b"", status: int = 0) -> None:
self._out, self._err, self._status = out, err, status
self.command: str | None = None
self.stdin = b""
self.write_shut = False
self.closed = False
def settimeout(self, timeout: float | None) -> None:
pass
def exec_command(self, command: str) -> None:
self.command = command
def sendall(self, data: bytes) -> None:
self.stdin += data
def shutdown_write(self) -> None:
self.write_shut = True
def recv_ready(self) -> bool:
return bool(self._out)
def recv_stderr_ready(self) -> bool:
return bool(self._err)
def exit_status_ready(self) -> bool:
return True
def recv(self, size: int) -> bytes:
chunk, self._out = self._out[:size], self._out[size:]
return chunk
def recv_stderr(self, size: int) -> bytes:
chunk, self._err = self._err[:size], self._err[size:]
return chunk
def recv_exit_status(self) -> int:
return self._status
def close(self) -> None:
self.closed = True
def _driver(channel: _Channel) -> ProxmoxDriver:
driver = ProxmoxDriver("10.0.0.9", "root", "s3cret")
driver._node_name = "pve1"
driver._api = MagicMock()
session = MagicMock()
session.get_transport.return_value.open_session.return_value = channel
driver._node_ssh = MagicMock(return_value=session) # type: ignore[method-assign]
return driver
def test_the_driver_offers_the_ssh_hardening():
assert callable(getattr(ProxmoxDriver, "harden_ssh_server", None))
assert callable(getattr(ProxmoxDriver, "exempt_from_ssh_penalties", None))
def test_a_command_reports_stdout_stderr_and_its_exit_status():
channel = _Channel(b"root\n", b"a warning\n", 3)
result = _driver(channel).run_command("id -un")
assert result == CommandResult("root\n", "a warning\n", 3)
assert channel.command == "id -un"
assert channel.closed
def test_stdin_reaches_the_command_and_is_closed():
channel = _Channel()
_driver(channel).run_command("cat > /tmp/x", stdin=b"PasswordAuthentication no\n")
assert channel.stdin == b"PasswordAuthentication no\n"
assert channel.write_shut
def test_privileged_needs_nothing_more_as_the_node_is_logged_in_as_root():
channel = _Channel()
_driver(channel).run_command("sshd -T", privileged=True)
assert channel.command == "sshd -T"
def test_a_command_that_cannot_run_raises():
driver = _driver(_Channel())
driver._node_ssh = MagicMock( # type: ignore[method-assign]
side_effect=paramiko.AuthenticationException("Authentication failed.")
)
with pytest.raises(ConnectionException, match="Authentication failed"):
driver.run_command("true")
def test_a_command_that_outlasts_its_timeout_raises():
class _Hangs(_Channel):
def exit_status_ready(self) -> bool:
return False
with pytest.raises(ConnectionException, match="did not finish"):
_driver(_Hangs()).run_command("sleep 60", timeout=0.05)
+58
View File
@@ -0,0 +1,58 @@
"""The physical port set_vlan configures: _find_switch_uplink / _is_physical_uplink."""
from __future__ import annotations
from unittest.mock import MagicMock
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
NETWORK = [
{"iface": "eno1", "type": "eth"},
{"iface": "vmbr0", "type": "bridge", "bridge_ports": "eno1"},
]
def _mixin(detail: dict, basic: dict) -> ProxmoxSDNMixin:
m = ProxmoxSDNMixin()
m._get_node_network = MagicMock(return_value=NETWORK)
m.get_lldp_neighbors_detail = MagicMock(return_value=detail)
m.get_lldp_neighbors = MagicMock(return_value=basic)
return m
class TestFindSwitchUplink:
def test_physical_port_with_a_bridge_neighbour_is_the_uplink(self):
m = _mixin(
detail={
"tap100i0": [{"remote_system_capab": ["bridge"]}],
"eno1": [{"remote_system_capab": ["bridge", "router"]}],
},
basic={},
)
assert m._find_switch_uplink() == "eno1"
def test_basic_lldp_fallback_skips_a_virtual_port(self):
m = _mixin(
detail={},
basic={"fwpr100p0": [{"hostname": "sw"}], "eno1": [{"hostname": "sw"}]},
)
assert m._find_switch_uplink() == "eno1"
def test_no_physical_neighbour_is_none(self):
m = _mixin(detail={"tap100i0": [{"remote_system_capab": ["bridge"]}]}, basic={})
assert m._find_switch_uplink() is None
class TestIsPhysicalUplink:
def test_eth_in_the_network_config_is_physical(self):
assert ProxmoxSDNMixin()._is_physical_uplink("eno1", {"eno1": {"type": "eth"}})
def test_virtual_prefix_is_never_physical(self):
network = {"tap100i0": {"type": ""}}
assert not ProxmoxSDNMixin()._is_physical_uplink("tap100i0", network)
def test_port_missing_from_the_network_config_is_not_physical(self):
assert not ProxmoxSDNMixin()._is_physical_uplink("eno9", {})
def test_bridge_is_not_physical(self):
assert not ProxmoxSDNMixin()._is_physical_uplink("vmbr0", {"vmbr0": {"type": "bridge"}})
+2 -1
View File
@@ -25,7 +25,8 @@ def test_it_runs_the_shared_command(driver):
identity = driver.get_system_identity()
exec_.assert_called_once_with(SYSTEM_IDENTITY_COMMAND)
assert identity == {
# The identity's keys only: napalm-device-types reads more in the same round trip.
assert {k: identity[k] for k in ("system_uuid", "product_serial", "board_serial")} == {
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
"product_serial": "",
"board_serial": "ZM155S026022",
+397
View File
@@ -0,0 +1,397 @@
"""Time sync on a Proxmox VE node and a Proxmox Backup Server (NetOrk/netork#2365).
Neither API keeps time servers: both products run chrony on Debian. The servers
are napalm-device-types' ``PosixTimeSyncMixin``'s, over the driver's SSH session
(``run_command``, as root); the zone is read from the host the same way and
written through the product's own ``PUT /nodes/{node}/time``, which also keeps
``/etc/timezone`` for the web UI. One netOrk device is one node: a PVE node in a
cluster has its own clock, and only that node is written.
The readings are what ``reading_command`` prints on a PVE 8 / PBS 3 host (Debian
12's chrony 4.3, its configuration comments shortened).
"""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from napalm_device_types import CommandResult, PosixTimeSyncMixin, TimeSyncMixin
from proxmoxer.core import ResourceException
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
from tests.conftest import _build_mock_api
from tests.pbs_fake import FakePbsApi, forbidden
_ACTIVE_CHRONY = """\
chrony chrony active
chronyd chrony active
systemd-timesyncd systemd-timesyncd inactive
ntpsec ntpd inactive
ntp ntpd inactive
ntpd ntpd inactive
openntpd openntpd inactive"""
_CHRONYC_SYNCED = """\
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^- 162.159.200.123 3 6 377 41 +814us[ +814us] +/- 14ms
^* 185.248.188.98 2 6 377 40 -45us[ -63us] +/- 10ms"""
#: Debian 12's /etc/chrony/chrony.conf as Proxmox VE 8 and PBS 3 ship it.
_CHRONY_CONF = """\
# Welcome to the chrony configuration file. See chrony.conf(5) for more
# information about usable directives.
# Include configuration files found in /etc/chrony/conf.d.
confdir /etc/chrony/conf.d
# Use Debian vendor zone.
{pool}pool 2.debian.pool.ntp.org iburst
# Use time sources from DHCP.
{dhcp}sourcedir /run/chrony-dhcp
# Use NTP sources found in /etc/chrony/sources.d.
sourcedir /etc/chrony/sources.d
keyfile /etc/chrony/chrony.keys
driftfile /var/lib/chrony/chrony.drift
ntsdumpdir /var/lib/chrony
logdir /var/log/chrony
maxupdateskew 100.0
rtcsync
makestep 1 3
leapsectz right/UTC"""
_MARK = "#napalm-time-sync: "
def _reading(
zone: str = "Europe/Berlin",
*,
servers: tuple[str, ...] = (),
dhcp: tuple[str, ...] = (),
deaf_to_dhcp: bool = False,
timedatectl: bool = True,
) -> str:
"""What the reading prints; *servers* in netOrk's sources file, the vendor's pool
commented out with it (as a write leaves the host), *dhcp* in the DHCP client's
sources file. *deaf_to_dhcp* is a host napalm-device-types 4.35.0 aligned: its write
commented out the DHCP ``sourcedir`` too."""
written = bool(servers)
conf = _CHRONY_CONF.format(pool=_MARK if written else "", dhcp=_MARK if deaf_to_dhcp else "")
parts = ["@@ts timedatectl"]
if timedatectl:
parts += [
f"Timezone={zone}",
"LocalRTC=no",
"CanNTP=yes",
"NTP=yes",
"NTPSynchronized=yes",
"TimeUSec=Wed 2026-11-11 14:23:16 CET",
"RTCTimeUSec=Wed 2026-11-11 13:23:16 CET",
]
parts += ["@@ts zone", zone if timedatectl else ""]
parts += ["@@ts active", _ACTIVE_CHRONY, "@@ts timesync", "@@ts chronyc", _CHRONYC_SYNCED]
parts += ["@@ts chrony 0 main /etc/chrony/chrony.conf", conf, ""]
if dhcp:
parts += ["@@ts chrony 11 sourcedir /run/chrony-dhcp/vmbr0.sources"]
parts += [f"server {s} iburst" for s in dhcp]
parts += [""]
if written:
parts += ["@@ts chrony 14 sourcedir /etc/chrony/sources.d/netork.sources"]
parts += [f"{'pool' if '.pool.' in s else 'server'} {s} iburst" for s in servers]
parts += [""]
parts += ["@@ts end", ""]
return "\n".join(parts)
class Node:
"""The node's command channel: the readings in turn (the last one stays), and
every other command succeeds. Records ``(command, privileged, stdin)``."""
def __init__(self, *readings: str) -> None:
self.readings = list(readings)
self.calls: list[tuple[str, bool, bytes | None]] = []
def __call__(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult:
self.calls.append((command, privileged, stdin))
if "@@ts timedatectl" in command:
reading = self.readings.pop(0) if len(self.readings) > 1 else self.readings[0]
return CommandResult(reading, "", 0)
if command.startswith("t=$(mktemp)"):
return CommandResult("/tmp/tmp.Xk3fQ9", "", 0)
return CommandResult("", "", 0)
def root(self) -> list[str]:
return [c for c, privileged, _ in self.calls if privileged]
def staged(self) -> list[bytes]:
return [stdin for _, _, stdin in self.calls if stdin is not None]
def _pve(*readings: str, node: str | None = None) -> tuple[ProxmoxDriver, Any, Node]:
args = {"verify_ssl": False} if node is None else {"verify_ssl": False, "node": node}
driver = ProxmoxDriver("pve1.example.com", "root", "secret", optional_args=args)
api = _build_mock_api()
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
driver.open()
shell = Node(*readings)
driver.run_command = shell # type: ignore[method-assign]
return driver, api, shell
def _pbs(*readings: str, **responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi, Node]:
api = FakePbsApi(**responses)
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
driver.open()
shell = Node(*readings)
driver.run_command = shell # type: ignore[method-assign]
return driver, api, shell
# -- the contract -----------------------------------------------------------------------------
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
def test_both_drivers_read_and_write_servers_and_zone(cls: type) -> None:
assert issubclass(cls, TimeSyncMixin)
assert issubclass(cls, PosixTimeSyncMixin)
assert callable(getattr(cls, "get_time_sync", None))
assert callable(getattr(cls, "configure_time_sync", None))
assert cls.time_sync_writes == frozenset({"ntp_servers", "timezone"})
# -- reading ----------------------------------------------------------------------------------
def test_pve_reads_chrony_and_the_zone_in_one_round_trip() -> None:
driver, api, shell = _pve(_reading())
assert driver.get_time_sync() == {
"ntp_servers": ["2.debian.pool.ntp.org"],
"dhcp_ntp_servers": [],
"timezone": "Europe/Berlin",
"synchronized": True,
"daemon": "chrony",
}
assert len(shell.calls) == 1
assert shell.root() == [] # the reading writes nothing
api.nodes.return_value.time.put.assert_not_called()
def test_pbs_reads_chrony_and_the_zone() -> None:
driver, api, shell = _pbs(_reading("Europe/Vienna", servers=("10.0.0.1",)))
assert driver.get_time_sync() == {
"ntp_servers": ["10.0.0.1"],
"dhcp_ntp_servers": [],
"timezone": "Europe/Vienna",
"synchronized": True,
"daemon": "chrony",
}
assert len(shell.calls) == 1
assert not [c for c in api.calls if c[0] != "GET"]
def test_servers_from_dhcp_are_read_apart_from_the_configured_ones() -> None:
"""A node that gets its time giver by DHCP (option 42): chrony reads the DHCP
client's sources file, and those servers are not the node's own (NetOrk/netork#2380)."""
driver, _, _ = _pve(_reading(dhcp=("192.168.1.1",)))
reading = driver.get_time_sync()
assert reading["ntp_servers"] == ["2.debian.pool.ntp.org"]
assert reading["dhcp_ntp_servers"] == ["192.168.1.1"]
def test_a_host_without_a_zone_of_its_own_reads_the_apis() -> None:
"""No timedatectl and no /etc/timezone or /etc/localtime link: the API's word."""
driver, api, _ = _pve(_reading(timedatectl=False))
api.nodes.return_value.time.get.return_value = {"timezone": "Europe/Paris"}
assert driver.get_time_sync()["timezone"] == "Europe/Paris"
def test_no_zone_anywhere_reads_none() -> None:
driver, _, _ = _pbs(_reading(timedatectl=False), **{"nodes/localhost/time": forbidden()})
assert driver.get_time_sync()["timezone"] is None
def test_a_cut_reading_raises() -> None:
driver, _, _ = _pve("@@ts timedatectl\nTimezone=Europe/Berlin\n")
with pytest.raises(ValueError, match="cut short"):
driver.get_time_sync()
@pytest.mark.parametrize("make", [_pve, _pbs], ids=["pve", "pbs"])
def test_get_ntp_servers_is_what_get_time_sync_reads(make: Any) -> None:
servers = ("10.0.0.1", "0.de.pool.ntp.org")
driver, _, _ = make(_reading(servers=servers))
assert list(driver.get_ntp_servers()) == list(servers)
assert driver.get_ntp_servers() == {s: {} for s in driver.get_time_sync()["ntp_servers"]}
def test_get_ntp_servers_no_longer_asks_an_api_path_pve_does_not_have() -> None:
"""``GET /nodes/{node}/ntp`` does not exist; asking it read as "no servers"."""
driver, api, _ = _pve(_reading())
assert driver.get_ntp_servers() == {"2.debian.pool.ntp.org": {}}
api.nodes.return_value.ntp.get.assert_not_called()
# -- writing the zone -------------------------------------------------------------------------
def test_pve_writes_the_zone_through_its_node_api_and_reads_it_back() -> None:
driver, api, shell = _pve(_reading("Europe/Vienna"))
result = driver.configure_time_sync(timezone="Europe/Vienna")
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["timezone", "verify"]
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
assert shell.root() == [] # not timedatectl: the API keeps /etc/timezone as well
def test_in_a_cluster_only_this_node_is_written() -> None:
driver, api, _ = _pve(_reading("Europe/Vienna"), node="pve2")
api.nodes.reset_mock()
driver.configure_time_sync(timezone="Europe/Vienna")
assert {c.args for c in api.nodes.call_args_list} == {("pve2",)}
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
def test_pbs_writes_the_zone_through_its_api() -> None:
driver, api, _ = _pbs(_reading("Europe/Vienna"), **{"PUT nodes/localhost/time": None})
result = driver.configure_time_sync(timezone="Europe/Vienna")
assert result["success"], result["output"]
assert ("PUT", "nodes/localhost/time", {"timezone": "Europe/Vienna"}) in api.calls
def test_a_refused_zone_fails_the_step_and_says_why() -> None:
"""An API token without ``Sys.Modify``: the step fails, nothing else is tried."""
driver, api, shell = _pbs(_reading(), **{"PUT nodes/localhost/time": forbidden()})
result = driver.configure_time_sync(timezone="Europe/Vienna")
assert not result["success"]
assert result["steps"][-1]["step"] == "timezone"
assert "403" in result["steps"][-1]["output"]
assert shell.calls == []
def test_a_zone_the_device_did_not_take_fails_verify() -> None:
driver, api, _ = _pve(_reading("Europe/Berlin"))
result = driver.configure_time_sync(timezone="Europe/Vienna")
assert not result["success"]
assert result["steps"][-1] == {
"step": "verify",
"ok": False,
"output": "the device is in the time zone Europe/Berlin",
}
def test_a_proxmoxer_error_on_the_zone_is_the_steps_output() -> None:
driver, api, _ = _pve(_reading())
api.nodes.return_value.time.put.side_effect = ResourceException(
400, "Bad Request", "Parameter verification failed: timezone: No such timezone"
)
result = driver.configure_time_sync(timezone="Europe/Vienna")
assert not result["success"]
assert "No such timezone" in result["steps"][0]["output"]
# -- writing the servers ----------------------------------------------------------------------
@pytest.mark.parametrize("make", [_pve, _pbs], ids=["pve", "pbs"])
def test_servers_go_to_chronys_sources_d_and_the_vendor_pool_stops_counting(make: Any) -> None:
servers = ["10.0.0.1", "0.de.pool.ntp.org"]
driver, _, shell = make(_reading(), _reading(servers=tuple(servers)))
result = driver.configure_time_sync(ntp_servers=servers)
assert result["success"], result["output"]
assert shell.staged() == [b"server 10.0.0.1 iburst\npool 0.de.pool.ntp.org iburst\n"]
root = shell.root()
assert any(
"/etc/chrony/sources.d/netork.sources" in c and c.startswith("install") for c in root
)
# line 8 is the vendor's pool, in the main file, which chronyd reads only when it
# starts. Line 11, the DHCP client's sourcedir, stays: DHCP's servers count.
sed = next(c for c in root if c.startswith("sed -i"))
assert "8{" in sed and "11{" not in sed and sed.endswith("/etc/chrony/chrony.conf")
assert root[-1] == "systemctl restart chrony.service"
def test_a_write_gives_back_the_dhcp_sourcedir_an_earlier_write_took() -> None:
"""A node napalm-device-types 4.35.0 aligned hears DHCP again (NetOrk/netork#2380)."""
servers = ("10.0.0.1",)
driver, _, shell = _pve(_reading(servers=servers, deaf_to_dhcp=True), _reading(servers=servers))
result = driver.configure_time_sync(ntp_servers=list(servers))
assert result["success"], result["output"]
root = shell.root()
sed = next(c for c in root if c.startswith("sed -i"))
assert "11{s/^#napalm-time-sync: (sourcedir" in sed
assert sed.endswith("/etc/chrony/chrony.conf")
assert root[-1] == "systemctl restart chrony.service"
def test_servers_already_written_are_written_the_same_way_again() -> None:
"""No churn: the second write stages the same file and comments out nothing."""
servers = ("10.0.0.1",)
driver, _, shell = _pve(_reading(servers=servers))
result = driver.configure_time_sync(ntp_servers=list(servers))
assert result["success"], result["output"]
assert shell.staged() == [b"server 10.0.0.1 iburst\n"]
assert not [c for c in shell.root() if c.startswith("sed")]
assert "chronyc reload sources" in shell.root()
def test_both_values_in_one_change() -> None:
driver, api, _ = _pve(_reading(), _reading("Europe/Vienna", servers=("10.0.0.1",)))
result = driver.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="Europe/Vienna")
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
def test_the_templates_refusals_hold() -> None:
driver, api, shell = _pve(_reading())
with pytest.raises(ValueError):
driver.configure_time_sync()
with pytest.raises(ValueError):
driver.configure_time_sync(ntp_servers=["not a server"])
with pytest.raises(ValueError):
driver.configure_time_sync(timezone="CET-1CEST,M3.5.0,M10.5.0/3")
assert shell.calls == []
api.nodes.return_value.time.put.assert_not_called()
+124
View File
@@ -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()
+29
View File
@@ -104,6 +104,35 @@ class TestRefresh:
assert result == {"success": False, "output": "403 Permission check failed"}
class TestApplyUpdates:
def test_a_clean_upgrade_succeeds(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value="Done.\n__PVE_RC=0") as exec_:
result = driver.apply_updates(["curl"])
assert "apt-get install --only-upgrade -y curl" in exec_.call_args[0][0]
assert result == {"success": True, "output": "Done."}
def test_a_failed_upgrade_is_a_failure(self, driver):
out = "E: Could not get lock /var/lib/dpkg/lock-frontend\n__PVE_RC=100"
with patch.object(driver, "_exec_ssh_command", return_value=out):
result = driver.apply_updates(["curl"])
assert result["success"] is False
assert result["output"] == "E: Could not get lock /var/lib/dpkg/lock-frontend"
assert result["error"] == "apt-get exited with status 100"
def test_an_unread_exit_status_is_no_success(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value=""):
result = driver.apply_updates(["curl"])
assert result["success"] is False
assert result["error"] == "apt-get's exit status could not be read"
def test_a_name_that_is_no_package_name_is_refused(self, driver):
with pytest.raises(ValueError):
driver.apply_updates(["curl;reboot"])
class TestHostStatus:
def test_the_node_is_read_over_the_exec_path(self, driver):
report = (
+66
View File
@@ -0,0 +1,66 @@
"""get_users: Proxmox users with their level, and the node's login accounts (#19)."""
from __future__ import annotations
from unittest.mock import patch
PASSWD = """\
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
alice:x:1000:1000:Alice:/home/alice:/bin/bash
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
"""
# GET /access/acl: who holds which role where.
ACL = [
{"path": "/", "roleid": "Administrator", "type": "user", "ugid": "admin@pve", "propagate": 1},
{"path": "/", "roleid": "Administrator", "type": "group", "ugid": "ops", "propagate": 1},
{"path": "/vms/100", "roleid": "Administrator", "type": "user", "ugid": "vm@pve"},
{"path": "/", "roleid": "PVEAuditor", "type": "user", "ugid": "audit@pve", "propagate": 1},
]
USERS = [
{"userid": "root@pam", "groups": ""},
{"userid": "admin@pve", "groups": ""},
{"userid": "bob@pve", "groups": "ops,dev"},
{"userid": "vm@pve", "groups": ""},
{"userid": "audit@pve", "groups": ""},
]
def _users(driver, passwd=PASSWD):
driver._api.access.users.get.return_value = USERS
driver._api.access.acl.get.return_value = ACL
with patch.object(driver, "_exec_ssh_command", return_value=passwd):
return driver.get_users()
class TestLocalAccounts:
def test_root_and_real_users_not_system_accounts(self, driver):
result = _users(driver)
assert result["root"]["level"] == 15
assert "alice" in result
for system in ("daemon", "bin", "www-data", "nobody"):
assert system not in result
class TestProxmoxUsers:
def test_administrator_on_the_whole_datacenter_is_level_15(self, driver):
result = _users(driver)
assert result["admin@pve"]["level"] == 15
def test_administrator_through_a_group_is_level_15(self, driver):
assert _users(driver)["bob@pve"]["level"] == 15
def test_root_at_pam_is_always_level_15(self, driver):
assert _users(driver)["root@pam"]["level"] == 15
def test_another_role_or_a_narrower_path_is_level_1(self, driver):
result = _users(driver)
assert result["audit@pve"]["level"] == 1
assert result["vm@pve"]["level"] == 1
+122
View File
@@ -41,6 +41,90 @@ class TestGetVmsReportsStringIds:
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:
def test_by_vmid_string(self, driver, api):
assert driver._resolve_vm("100") == (100, "vm")
@@ -84,6 +168,44 @@ class TestPowerActions:
with pytest.raises(RuntimeError, match="container"):
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):
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
with pytest.raises(RuntimeError, match="locked"):
+1 -1
View File
@@ -201,7 +201,7 @@ class TestLoopbackIsNeverTheVmsAddress:
mixin = ProxmoxVMProvisionMixin()
node = MagicMock()
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}
with patch("time.sleep"):
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
+125
View File
@@ -0,0 +1,125 @@
"""A creation that fails once the VM exists names that VM (#28).
Without its id the caller cannot remove the half-built VM, and it stays on the
node. A failure before the VM shell exists leaves nothing behind and raises
as it did.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from napalm_device_types.provisioning import VMProvisionIncomplete
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
_DEBIAN_URL = (
"https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2"
)
def _mixin() -> tuple:
"""A mixin whose node answers like Proxmox and hands out VMID 101."""
mixin = ProxmoxVMProvisionMixin()
mixin._node_name = "pve1"
api = MagicMock()
api.cluster.nextid.get.return_value = 101
api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
node = MagicMock()
node.storage.get.return_value = [
{"storage": "local-lvm", "type": "lvmthin", "content": "images,rootdir", "enabled": 1},
{"storage": "local", "type": "dir", "content": "snippets,iso", "enabled": 1},
]
vm = MagicMock()
node.qemu.return_value = vm
vm.config.get.return_value = {"unused0": "local-lvm:vm-101-disk-0"}
vm.status.start.post.return_value = "UPID:pve1:start"
node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
mixin._api = api
mixin._node_api = MagicMock(return_value=node)
mixin._download_cloud_image = MagicMock(
return_value="/var/lib/vz/template/netork-images/x.qcow2"
)
mixin._run_node_command = MagicMock(return_value="")
return mixin, node, vm
def _create(mixin):
with patch("time.sleep"):
return mixin.create_vm_from_cloud_init(
name="half-built",
image_url=_DEBIAN_URL,
cpu=2,
memory=2048,
nics=[{"bridge": "vmbr0"}],
cloud_init_config={"hostname": "half-built"},
)
def test_a_failed_disk_import_names_the_vm_it_left_behind():
mixin, _node, _vm = _mixin()
failure = RuntimeError("qm importdisk 101: storage 'local-lvm' is full")
mixin._download_cloud_image.side_effect = failure
with pytest.raises(VMProvisionIncomplete) as caught:
_create(mixin)
assert (caught.value.vmid, caught.value.node) == ("101", "pve1")
assert caught.value.__cause__ is failure
assert str(caught.value) == str(failure)
def test_a_failed_start_names_the_vm_it_left_behind():
mixin, node, _vm = _mixin()
node.tasks.return_value.status.get.return_value = {
"status": "stopped",
"exitstatus": "start failed: QEMU exited with code 1",
}
with pytest.raises(VMProvisionIncomplete, match="QEMU exited") as caught:
_create(mixin)
assert (caught.value.vmid, caught.value.node) == ("101", "pve1")
def test_an_invalid_nic_after_the_shell_exists_names_the_vm_too():
mixin, _node, _vm = _mixin()
with pytest.raises(VMProvisionIncomplete, match="bridge is required") as caught:
with patch("time.sleep"):
mixin.create_vm_from_cloud_init(
name="half-built",
image_url=_DEBIAN_URL,
cpu=2,
memory=2048,
nics=[{"vlan_tag": 10}],
cloud_init_config={},
)
assert isinstance(caught.value.__cause__, ValueError)
assert caught.value.vmid == "101"
def test_a_failure_creating_the_shell_leaves_no_vm_to_name():
mixin, node, _vm = _mixin()
failure = RuntimeError("VM 101 already exists")
node.qemu.post.side_effect = failure
with pytest.raises(RuntimeError) as caught:
_create(mixin)
assert caught.value is failure
assert not isinstance(caught.value, VMProvisionIncomplete)
def test_a_failure_taking_the_vmid_leaves_no_vm_to_name():
mixin, node, _vm = _mixin()
failure = RuntimeError("cluster not ready - no quorum?")
mixin._api.cluster.nextid.get.side_effect = failure
with pytest.raises(RuntimeError) as caught:
_create(mixin)
assert caught.value is failure
node.qemu.post.assert_not_called()
+2 -4
View File
@@ -10,10 +10,8 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
from napalm_proxmox.vm_provision_mixin import (
ProxmoxVMProvisionMixin,
_import_volume_name,
)
from napalm_proxmox.image_names import import_volume_name as _import_volume_name
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
_UBUNTU = (
"https://cloud-images.ubuntu.com/releases/26.04/release/ubuntu-26.04-server-cloudimg-amd64.img"
+444
View File
@@ -0,0 +1,444 @@
"""Moving a guest to another node: preflight, migration, HA maintenance mode.
Payloads: ``GET /nodes/{node}/qemu/{vmid}/migrate`` follows qemu-server's
``migrate_vm_precondition`` (PVE 9: ``not_allowed_nodes`` may name
``unavailable_storages``, ``unavailable-resources`` and
``blocking-ha-resources``); the task log follows ``/nodes/{node}/tasks/{upid}/log``
(``n``/``t`` rows). A guest that HA manages migrates through a ``hamigrate``
task that only hands the request to the HA manager.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from tests.test_clusters import CLUSTER_RESOURCES, CLUSTER_STATUS, GIB, _api, _driver, _storage_row
QEMU_LIST = [
{"vmid": 100, "name": "web", "status": "running", "maxmem": 4 * GIB},
{"vmid": 102, "name": "idle", "status": "stopped", "maxmem": 2 * GIB},
]
LXC_LIST = [{"vmid": "101", "name": "dns", "status": "running", "type": "lxc"}]
PREFLIGHT_RUNNING = {
"running": 1,
"allowed_nodes": ["pve2", "pve3"],
"not_allowed_nodes": {},
"local_disks": [
{
"volid": "local-lvm:vm-100-disk-0",
"size": 32 * GIB,
"drivename": "scsi0",
"is_attached": 1,
"referenced_in_config": 1,
},
{"volid": "local:iso/debian-13.iso", "cdrom": 1, "size": 700 * 1024**2},
# Regenerated on the target: neither a disk to copy nor a blocker.
{"volid": "local-lvm:vm-100-cloudinit", "cdrom": 1, "size": 4 * 1024**2},
],
"local_resources": [],
"mapped-resources": [],
"mapped-resource-info": {},
"has-dbus-vmstate": 1,
}
PREFLIGHT_BLOCKED = {
"running": 0,
"allowed_nodes": [],
"not_allowed_nodes": {
"pve2": {"unavailable_storages": ["local-zfs"]},
"pve3": {
"blocking-ha-resources": [{"sid": "vm:101", "cause": "resource-affinity"}],
"unavailable-resources": ["gpu-a"],
},
},
"local_disks": [],
"local_resources": ["hostpci0", "usb0"],
"mapped-resources": ["gpu-a"],
"mapped-resource-info": {"gpu-a": {"live-migration": 0}},
"has-dbus-vmstate": 1,
}
LXC_CONFIG = {
"hostname": "dns",
"rootfs": "local-lvm:vm-101-disk-0,size=8G",
"mp0": "ceph-vm:vm-101-disk-1,mp=/data,size=32G",
"mp1": "/srv/share,mp=/share",
"mp2": "/mnt/nfs,mp=/nfs,shared=1",
"unused0": "local-lvm:vm-101-disk-2",
"net0": "name=eth0,bridge=vmbr0,ip=dhcp",
"digest": "abc",
}
UPID_QEMU = "UPID:pve1:000ABCDE:0123ABCD:672AB000:qmigrate:100:root@pam:"
UPID_LXC = "UPID:pve1:000ABCDF:0123ABCE:672AB001:vzmigrate:101:root@pam:"
UPID_HA = "UPID:pve1:000ABCE0:0123ABCF:672AB002:hamigrate:100:root@pam:"
FAILED_LOG = [
{"n": 1, "t": "2026-11-01 10:00:00 starting migration of VM 100 to node 'pve2' (10.0.0.2)"},
{"n": 2, "t": "2026-11-01 10:00:01 starting VM 100 on remote node 'pve2'"},
{
"n": 3,
"t": "2026-11-01 10:00:02 ERROR: online migrate failure - remote command failed "
"with exit code 255",
},
{"n": 4, "t": "2026-11-01 10:00:02 aborting phase 2 - cleanup resources"},
{
"n": 5,
"t": "2026-11-01 10:00:03 ERROR: migration finished with problems (duration 00:00:03)",
},
{"n": 6, "t": "TASK ERROR: migration problems"},
]
def _migration_api(
preflight: dict[str, Any] | None = None,
task: dict[str, Any] | None = None,
log: list[dict[str, Any]] | None = None,
status: list[dict[str, Any]] | None = None,
) -> tuple[MagicMock, MagicMock]:
resources = [
*CLUSTER_RESOURCES,
_storage_row("pve1", "local", "dir", 0, "iso,vztmpl,backup", 100 * GIB, 20 * GIB),
]
api = _api(cluster_status=status, resources=resources)
node = api.nodes("pve1")
node.qemu.get.return_value = QEMU_LIST
node.lxc.get.return_value = LXC_LIST
node.qemu.return_value.migrate.get.return_value = preflight or PREFLIGHT_RUNNING
node.qemu.return_value.migrate.post.return_value = UPID_QEMU
node.lxc.return_value.migrate.post.return_value = UPID_LXC
node.lxc.return_value.status.current.get.return_value = {"status": "running", "vmid": 101}
node.lxc.return_value.config.get.return_value = LXC_CONFIG
node.tasks.return_value.status.get.return_value = task or {
"status": "stopped",
"exitstatus": "OK",
}
node.tasks.return_value.log.get.return_value = log or []
return api, node
class TestPreflightQemu:
def test_allowed_nodes_and_local_disks(self):
api, node = _migration_api()
result = _driver(api).get_vm_migration_preflight("web")
assert result == {
"running": True,
# pve3 is offline: the platform would allow it, it cannot take the VM now.
"allowed_nodes": ["pve2"],
"refused_nodes": {"pve3": "node offline"},
"local_disks": ["local-lvm:vm-100-disk-0"],
# A local ISO in a CD drive stops the migration.
"local_resources": ["cdrom=local:iso/debian-13.iso"],
}
node.qemu.assert_any_call(100)
def test_refusal_reasons_in_plain_words(self):
all_online = [dict(s, online=1) if s["type"] == "node" else s for s in CLUSTER_STATUS]
api, _ = _migration_api(preflight=PREFLIGHT_BLOCKED, status=all_online)
result = _driver(api).get_vm_migration_preflight("100")
assert result["running"] is False
assert result["allowed_nodes"] == []
assert result["refused_nodes"] == {
"pve2": "storage local-zfs is not available there",
"pve3": "HA resource vm:101 blocks it (resource-affinity rule); "
"mapped resource gpu-a is not available there",
}
assert result["local_resources"] == ["hostpci0", "usb0"]
def test_unknown_reason_is_passed_on(self):
preflight = {
"running": 0,
"allowed_nodes": [],
"not_allowed_nodes": {"pve2": {"some-future-check": ["x", "y"]}},
"local_disks": [],
"local_resources": [],
}
api, _ = _migration_api(preflight=preflight)
refused = _driver(api).get_vm_migration_preflight("web")["refused_nodes"]
assert refused["pve2"] == "some-future-check: x, y"
def test_unknown_guest(self):
api, _ = _migration_api()
with pytest.raises(ValueError, match="nope"):
_driver(api).get_vm_migration_preflight("nope")
class TestPreflightLxc:
def test_members_and_local_volumes(self):
api, node = _migration_api()
result = _driver(api).get_vm_migration_preflight("dns")
assert result == {
"running": True,
"allowed_nodes": ["pve2"],
"refused_nodes": {"pve3": "node offline"},
# ceph-vm is shared; local-lvm is not.
"local_disks": ["local-lvm:vm-101-disk-0", "local-lvm:vm-101-disk-2"],
# A bind mount that is not marked shared stops the migration.
"local_resources": ["mp1"],
}
node.qemu.return_value.migrate.get.assert_not_called()
def test_stopped_container(self):
api, node = _migration_api()
node.lxc.return_value.status.current.get.return_value = {"status": "stopped"}
assert _driver(api).get_vm_migration_preflight("101")["running"] is False
class TestMigrateQemu:
def test_running_vm_moves_online_with_its_local_disks(self):
api, node = _migration_api()
_driver(api).migrate_vm("web", "pve2")
node.qemu.return_value.migrate.post.assert_called_once_with(
target="pve2", online=1, **{"with-local-disks": 1}
)
node.tasks.assert_called_with(UPID_QEMU)
def test_target_storage_and_offline(self):
preflight = dict(PREFLIGHT_RUNNING, local_disks=[])
api, node = _migration_api(preflight=preflight)
_driver(api).migrate_vm("web", "pve2", online=False, target_storage="ceph-vm")
node.qemu.return_value.migrate.post.assert_called_once_with(
target="pve2", targetstorage="ceph-vm"
)
def test_stopped_vm_is_not_moved_online(self):
preflight = dict(PREFLIGHT_RUNNING, running=0, local_disks=[])
api, node = _migration_api(preflight=preflight)
_driver(api).migrate_vm("idle", "pve2")
node.qemu.return_value.migrate.post.assert_called_once_with(target="pve2")
def test_failure_raises_with_the_task_logs_errors(self):
api, node = _migration_api(
task={"status": "stopped", "exitstatus": "migration problems"}, log=FAILED_LOG
)
with pytest.raises(RuntimeError) as exc:
_driver(api).migrate_vm("web", "pve2")
message = str(exc.value)
assert "online migrate failure - remote command failed with exit code 255" in message
assert "migration finished with problems (duration 00:00:03)" in message
assert "starting VM 100" not in message
node.tasks.return_value.log.get.assert_called_once()
def test_failure_without_error_lines_keeps_the_task_status(self):
api, _ = _migration_api(
task={"status": "stopped", "exitstatus": "migration aborted"},
log=[{"n": 1, "t": "starting migration"}],
)
with pytest.raises(RuntimeError, match="migration aborted"):
_driver(api).migrate_vm("web", "pve2")
def test_refused_request_raises(self):
api, node = _migration_api()
node.qemu.return_value.migrate.post.side_effect = RuntimeError(
"500 Internal Server Error: VM is locked (backup)"
)
with pytest.raises(RuntimeError, match="VM is locked"):
_driver(api).migrate_vm("web", "pve2")
class TestMigrateLxc:
def test_running_container_moves_in_restart_mode(self):
api, node = _migration_api()
_driver(api).migrate_vm("dns", "pve2", target_storage="local-lvm")
node.lxc.return_value.migrate.post.assert_called_once_with(
target="pve2", restart=1, **{"target-storage": "local-lvm"}
)
node.tasks.assert_called_with(UPID_LXC)
def test_stopped_container(self):
api, node = _migration_api()
node.lxc.return_value.status.current.get.return_value = {"status": "stopped"}
_driver(api).migrate_vm("dns", "pve2")
node.lxc.return_value.migrate.post.assert_called_once_with(target="pve2")
class TestTargetRefusedBeforeTheApi:
@pytest.mark.parametrize("target", ["pve1", "pve9", "pve2; reboot"])
def test_not_another_member(self, target):
api, node = _migration_api()
with pytest.raises(ValueError, match="not another member"):
_driver(api).migrate_vm("web", target)
node.qemu.return_value.migrate.post.assert_not_called()
def _ha_status(node: str, crm_state: str) -> list[dict[str, Any]]:
return [
{"id": "quorum", "type": "quorum", "node": "pve1", "quorate": 1, "status": "OK"},
{
"id": "service:vm:100",
"type": "service",
"sid": "vm:100",
"node": node,
"crm_state": crm_state,
"state": crm_state,
"status": f"vm:100 ({node}, {crm_state})",
"request_state": "started",
},
]
class TestMigrateHaManaged:
"""PVE hands an HA guest's migration to the HA manager: the hamigrate task only
queues the request, so the driver follows the HA manager until the guest is there."""
def _api(self, states: list[list[dict[str, Any]]]) -> tuple[MagicMock, MagicMock]:
api, node = _migration_api()
node.qemu.return_value.migrate.post.return_value = UPID_HA
api.cluster.ha.status.current.get.side_effect = states
return api, node
def test_waits_until_the_guest_runs_on_the_target(self):
api, _ = self._api(
[
_ha_status("pve1", "started"),
_ha_status("pve1", "migrate"),
_ha_status("pve2", "started"),
]
)
with patch("napalm_proxmox.vm_migrate_mixin.sleep") as sleep:
_driver(api).migrate_vm("web", "pve2")
assert api.cluster.ha.status.current.get.call_count == 3
assert sleep.call_count == 2
def test_back_on_the_source_node_is_a_failure_with_the_migration_log(self):
api, node = self._api([_ha_status("pve1", "migrate"), _ha_status("pve1", "started")])
node.tasks.get.return_value = [
{
"upid": UPID_QEMU,
"type": "qmigrate",
"id": "100",
"starttime": 0x672AB002 + 12,
"status": "migration problems",
}
]
node.tasks.return_value.log.get.return_value = FAILED_LOG
with patch("napalm_proxmox.vm_migrate_mixin.sleep"):
with pytest.raises(RuntimeError, match="online migrate failure"):
_driver(api).migrate_vm("web", "pve2")
node.tasks.get.assert_called_once_with(vmid=100, typefilter="qmigrate", limit=1)
def test_error_state_raises(self):
api, node = self._api([_ha_status("pve1", "error")])
node.tasks.get.return_value = []
with patch("napalm_proxmox.vm_migrate_mixin.sleep"):
with pytest.raises(RuntimeError, match="error"):
_driver(api).migrate_vm("web", "pve2")
def test_times_out(self):
api, _ = self._api([_ha_status("pve1", "migrate")] * 50)
clock = iter(range(0, 10000, 30))
with (
patch("napalm_proxmox.vm_migrate_mixin.sleep"),
patch("napalm_proxmox.vm_migrate_mixin.monotonic", lambda: next(clock)),
):
with pytest.raises(RuntimeError, match="timed out"):
_driver(api).migrate_vm("web", "pve2", timeout=120)
class TestNodeMaintenance:
def _driver(self) -> tuple[Any, MagicMock]:
api, _ = _migration_api()
drv = _driver(api)
drv._node_ssh = MagicMock() # type: ignore[method-assign]
drv._run_node_command = MagicMock(return_value="") # type: ignore[method-assign]
return drv, drv._run_node_command
def test_enable(self):
drv, run = self._driver()
drv.set_node_maintenance("pve2", True)
run.assert_called_once_with(
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
)
def test_disable(self):
drv, run = self._driver()
drv.set_node_maintenance("pve3", False)
run.assert_called_once_with(
"ha-manager crm-command node-maintenance disable pve3", timeout=drv.timeout
)
@pytest.mark.parametrize("node", ["pve9", "pve2; reboot", "$(reboot)"])
def test_not_a_member_runs_nothing(self, node):
drv, run = self._driver()
with pytest.raises(ValueError, match="not a member"):
drv.set_node_maintenance(node, True)
run.assert_not_called()
def test_no_ssh(self):
drv, run = self._driver()
drv._node_ssh.side_effect = OSError("Authentication failed")
with pytest.raises(RuntimeError, match="SSH"):
drv.set_node_maintenance("pve2", True)
run.assert_not_called()
def test_command_refused(self):
drv, run = self._driver()
run.side_effect = RuntimeError("Command failed (exit 255): ...\nno such node 'pve2'")
with pytest.raises(RuntimeError, match="no such node"):
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()
+361 -5
View File
@@ -6,6 +6,7 @@ import base64
from unittest.mock import MagicMock, patch
import pytest
from napalm_device_types.provisioning import VMProvisionIncomplete
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
@@ -220,7 +221,8 @@ def test_create_vm_from_cloud_init_dual_nic_trunk():
def test_create_vm_missing_snippet_storage():
"""create_vm_from_cloud_init raises ValueError if snippet storage unavailable."""
"""No snippet storage fails the creation; the VM shell exists by then, so the
ValueError arrives as the cause of VMProvisionIncomplete naming it (#28)."""
mixin = ProxmoxVMProvisionMixin()
mixin._node_name = "pve1"
@@ -250,7 +252,7 @@ def test_create_vm_missing_snippet_storage():
mock_task.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
mock_node.tasks.return_value = mock_task
with pytest.raises(ValueError, match="snippet"):
with pytest.raises(VMProvisionIncomplete, match="snippet") as caught:
with patch("napalm_proxmox.vm_provision_mixin.time.sleep"):
mixin.create_vm_from_cloud_init(
name="test-vm",
@@ -260,6 +262,8 @@ def test_create_vm_missing_snippet_storage():
nics=[{"bridge": "vmbr0"}],
cloud_init_config={},
)
assert isinstance(caught.value.__cause__, ValueError)
assert caught.value.vmid == "101"
def test_create_vm_with_disk_resize():
@@ -332,7 +336,7 @@ def test_get_vm_status_with_wait_for_ip():
# Mock VM config
mock_vm = MagicMock()
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),
# reached via agent(...) as a callable resource, not dotted attribute
@@ -371,7 +375,7 @@ def test_get_vm_status_skips_loopback_interface():
mock_vm = MagicMock()
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_vm.agent.return_value = mock_agent_call
@@ -406,7 +410,7 @@ def test_get_vm_status_timeout_waiting_for_ip():
# Mock VM config
mock_vm = MagicMock()
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_agent_call = MagicMock()
@@ -420,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)
_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():
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
mixin = ProxmoxVMProvisionMixin()
@@ -484,6 +596,42 @@ def test_destroy_vm_already_stopped():
assert mock_vm.delete.called
def _destroy_mixin(delete_task: dict) -> tuple[ProxmoxVMProvisionMixin, MagicMock]:
mixin = ProxmoxVMProvisionMixin()
node = MagicMock()
mixin._node_api = MagicMock(return_value=node)
vm = node.qemu.return_value
vm.status.stop.post.return_value = "UPID:pve1:125:stop"
vm.config.get.return_value = {}
vm.delete.return_value = "UPID:pve1:126:qmdestroy"
tasks = {
"UPID:pve1:125:stop": {"status": "stopped", "exitstatus": "OK"},
"UPID:pve1:126:qmdestroy": delete_task,
}
node.tasks.side_effect = lambda upid: MagicMock(**{"status.get.return_value": tasks[upid]})
return mixin, node
def test_destroy_vm_waits_for_the_delete_task():
"""destroy_vm returns once the VM is gone, not when its delete was queued (#15)."""
mixin, node = _destroy_mixin({"status": "stopped", "exitstatus": "OK"})
with patch("time.sleep"):
mixin.destroy_vm("101")
assert [c.args[0] for c in node.tasks.call_args_list] == [
"UPID:pve1:125:stop",
"UPID:pve1:126:qmdestroy",
]
def test_destroy_vm_raises_when_the_delete_task_fails():
mixin, _ = _destroy_mixin({"status": "stopped", "exitstatus": "VM is locked (backup)"})
with patch("time.sleep"), pytest.raises(RuntimeError, match="VM is locked"):
mixin.destroy_vm("101")
# ---------------------------------------------------------------------------
# get_network_targets
# ---------------------------------------------------------------------------
@@ -1280,3 +1428,211 @@ def test_create_vm_cloudinit_drive_uses_image_storage_not_snippet_storage():
cloud_init_call = next(c for c in mock_vm.config.post.call_args_list if "ide2" in c[1])
assert cloud_init_call[1]["ide2"] == "local-zfs:cloudinit"
assert cloud_init_call[1]["cicustom"].startswith("user=local:snippets/")
def test_create_vm_passes_every_ssh_key_one_per_line():
"""Proxmox's sshkeys is one key per line, URL-encoded (napalm-proxmox#23).
Joined with ";", only the first key worked. Base64 keys carry "/" and "+",
which Proxmox's urlencoded format refuses unescaped.
"""
import re
from urllib.parse import unquote
mixin = ProxmoxVMProvisionMixin()
mixin._node_name = "pve1"
mock_api = MagicMock()
mock_api.cluster.nextid.get.return_value = 110
mock_api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
mock_node = MagicMock()
mock_node.storage.get.return_value = [
{"storage": "local", "type": "dir", "content": "images,snippets", "enabled": 1},
]
mixin._api = mock_api
mixin._node_api = MagicMock(return_value=mock_node)
mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/x.qcow2")
mixin._run_node_command = MagicMock(return_value="")
mock_vm = mock_node.qemu.return_value
mock_vm.config.get.return_value = {"unused0": "local:vm-110-disk-0"}
mock_vm.status.start.post.return_value = "UPID:pve1:136:start"
mock_node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI/+k1 alice@example",
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB/+k2 bob@example",
]
with patch("time.sleep"):
mixin.create_vm_from_cloud_init(
name="keys-vm",
image_url="https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
cpu=1,
memory=512,
nics=[{"bridge": "vmbr0"}],
cloud_init_config={},
ssh_public_keys=keys,
)
call = next(c for c in mock_vm.config.post.call_args_list if "sshkeys" in c[1])
sshkeys = call[1]["sshkeys"]
assert unquote(sshkeys) == "\n".join(keys)
assert re.fullmatch(r"[-%a-zA-Z0-9_.!~*'()]*", sshkeys)
class _LocalShell:
"""The node's SSH session as a local ``sh``, *prelude* run before each command."""
def __init__(self, prelude: str) -> None:
self.prelude = prelude
def exec_command(self, command: str, timeout: int | None = None):
import subprocess
run = subprocess.run(
["sh", "-c", self.prelude + command], capture_output=True, timeout=timeout
)
return _mock_ssh_exec(run.returncode, run.stdout.decode(), run.stderr.decode())
# wget as it fails on a full disk: part of the file written, the reason on stderr.
_WGET_DISK_FULL = (
"wget() { "
'while [ $# -gt 0 ]; do [ "$1" = -O ] && o=$2; shift; done; '
'echo partial > "$o"; '
'echo "$o: No space left on device" >&2; return 3; }; '
)
def test_download_cloud_image_failure_says_why_and_leaves_no_tmp(tmp_path, monkeypatch):
"""A failed download names wget's reason and removes its .tmp (napalm-proxmox#3)."""
import napalm_proxmox.vm_provision_mixin as module
monkeypatch.setattr(module, "_IMAGE_CACHE_DIR", str(tmp_path))
mixin = ProxmoxVMProvisionMixin()
mixin._node_ssh = MagicMock(return_value=_LocalShell(_WGET_DISK_FULL))
with pytest.raises(RuntimeError, match="No space left on device") as err:
mixin._download_cloud_image("https://example.org/img/debian.qcow2", None, timeout=10)
assert "exit 3" in str(err.value)
assert list(tmp_path.iterdir()) == []
def test_download_cloud_image_does_not_silence_wget():
mixin = ProxmoxVMProvisionMixin()
mixin._run_node_command = MagicMock(side_effect=["MISSING", ""])
mixin._download_cloud_image("https://example.org/img/debian.qcow2", None, timeout=10)
download = mixin._run_node_command.call_args_list[1][0][0]
assert download.startswith("wget -nv ")
# ---------------------------------------------------------------------------
# The image URL in root shell commands (#43)
# ---------------------------------------------------------------------------
# A URL a tampered release feed could publish: a quote that ends hand-written
# quoting, a command substitution and a space, each of which the node's shell
# would act on if the URL or the file name built from it went in unquoted.
_HOSTILE_URL = "https://example.org/$(reboot)/a b/x';reboot;'.img"
# reboot() records that the shell ran it; wget() saves the URL it was given as
# the "image", so the file's content shows whether the URL arrived as one argument.
_HOSTILE_PRELUDE = (
'reboot() { echo injected >> "$MARK"; }; '
"wget() { "
"while [ $# -gt 0 ]; do "
'[ "$1" = -O ] && o=$2; [ $# -eq 1 ] && u=$1; shift; done; '
'printf \'%s\' "$u" > "$o"; }; '
# The unpack step of a packed image: "xz -dc <file>" as a plain copy.
'xz() { cat "$2"; }; '
)
def _hostile_shell(tmp_path, monkeypatch) -> ProxmoxVMProvisionMixin:
import napalm_proxmox.vm_provision_mixin as module
cache = tmp_path / "cache"
monkeypatch.setattr(module, "_IMAGE_CACHE_DIR", str(cache))
monkeypatch.setenv("MARK", str(tmp_path / "injected"))
mixin = ProxmoxVMProvisionMixin()
mixin._node_ssh = MagicMock(return_value=_LocalShell(_HOSTILE_PRELUDE))
return mixin
def test_a_hostile_image_url_stays_one_argument_in_every_command(tmp_path, monkeypatch):
import hashlib
from pathlib import Path
mixin = _hostile_shell(tmp_path, monkeypatch)
checksum = "sha256:" + hashlib.sha256(_HOSTILE_URL.encode()).hexdigest()
path = mixin._download_cloud_image(_HOSTILE_URL, checksum, timeout=10)
assert not (tmp_path / "injected").exists()
assert Path(path).read_text() == _HOSTILE_URL # wget got the whole URL
assert Path(path).parent == tmp_path / "cache"
def test_the_cache_file_name_keeps_only_safe_characters(tmp_path, monkeypatch):
import re
from pathlib import Path
mixin = _hostile_shell(tmp_path, monkeypatch)
path = mixin._download_cloud_image(_HOSTILE_URL, None, timeout=10)
assert re.fullmatch(r"[A-Za-z0-9._+=-]+", Path(path).name)
assert Path(path).name.endswith("-x__reboot__.img")
def test_a_packed_hostile_image_is_unpacked_without_running_anything(tmp_path, monkeypatch):
from pathlib import Path
mixin = _hostile_shell(tmp_path, monkeypatch)
url = _HOSTILE_URL + ".xz"
path = mixin._cloud_image_on_node(url, None, timeout=10)
assert not (tmp_path / "injected").exists()
assert Path(path).read_text() == url
assert not path.endswith(".xz")
def test_a_checksum_algorithm_outside_the_known_ones_is_refused():
mixin = ProxmoxVMProvisionMixin()
mixin._run_node_command = MagicMock(return_value="EXISTS")
with pytest.raises(ValueError, match="checksum algorithm"):
mixin._download_cloud_image(
"https://example.org/img/debian.qcow2", "sha256;reboot;:abc", timeout=10
)
assert not any("reboot" in c.args[0] for c in mixin._run_node_command.call_args_list)
# ---------------------------------------------------------------------------
# The cloud-init snippet's path in a root shell command (#47)
# ---------------------------------------------------------------------------
def test_a_snippet_storage_path_stays_one_argument(tmp_path, monkeypatch):
storage = tmp_path / "a b;reboot;$(reboot)"
mixin = _hostile_shell(tmp_path, monkeypatch)
mixin._write_snippet(str(storage), "101-user-data.yaml", "#cloud-config\n")
assert not (tmp_path / "injected").exists()
assert (storage / "snippets" / "101-user-data.yaml").read_text() == "#cloud-config\n"
@pytest.mark.parametrize(
"filename", ["x;reboot;.yaml", "../../etc/cron.d/x", "a b.yaml", "$(reboot).yaml", ""]
)
def test_a_snippet_name_that_is_not_a_plain_file_name_is_refused(filename):
mixin = ProxmoxVMProvisionMixin()
mixin._run_node_command = MagicMock(return_value="")
with pytest.raises(ValueError, match="snippet"):
mixin._write_snippet("/var/lib/vz", filename, "#cloud-config\n")
mixin._run_node_command.assert_not_called()
+243
View File
@@ -0,0 +1,243 @@
"""configure_zabbix_agent on a Proxmox node (NetOrk/netork#2571).
A node runs no container engine, so the agent cannot run as a container there. The
template installs Debian's ``zabbix-agent`` -- or Zabbix's, where Debian has none -- and
enables and restarts it; the node writes the configuration and opens ufw where there is
one. pve-firewall's rules are the operator's.
"""
from __future__ import annotations
import base64
import re
import pytest
from napalm_device_types import OPENED_PORTS_RECORD
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
DEBIAN = 'PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n'
SETTINGS = {
"server": "zabbix.example.com",
"server_active": "zabbix.example.com",
"listen_port": 10050,
"allowed_sources": ["10.40.100.254"],
"hostname": "pve-01",
"release": "7.4",
}
class _Node:
"""The node's root shell: files it reads, packages Debian has, what is refused."""
def __init__(self, *, config=STOCK, ufw=True, debian_has_it=True, refuse=""):
self.config = config
self.ufw = ufw
self.debian_has_it = debian_has_it
self.installed = False
self.refuse = refuse
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:
self.ran.append(command)
out, rc = self._answer(command)
for marker in ("__PVE_RC=", "__SVC_RC="):
if marker in command:
return f"{out}\n{marker}{rc}"
return out
def _answer(self, command: str) -> tuple[str, int]:
if self.refuse and self.refuse in command:
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"):
return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0
if f"cat {CONFIG}" in command:
return self.config, 0
if "cat /etc/os-release" in command:
return DEBIAN, 0
if "command -v ufw" in command:
return ("/usr/sbin/ufw", 0) if self.ufw else ("", 1)
if "repo.zabbix.com" in command:
self.debian_has_it = True
return "ok", 0
if "apt-get install" in command and "zabbix-agent" in command:
if not self.debian_has_it:
return "E: Unable to locate package zabbix-agent", 100
self.installed = True
return "ok", 0
if "base64 -d" in command and CONFIG in command:
self.config = base64.b64decode(re.search(r"echo (\S+) \|", command).group(1)).decode()
return "ok", 0
@pytest.fixture
def node():
return _Node()
@pytest.fixture(params=[ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
def driver(request, node):
d = request.param("pve", "root@pam", "pw")
d._exec_ssh_command = node
return d
def test_installs_writes_opens_and_starts(driver, node):
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
assert any("apt-get install" in c and "zabbix-agent" in c for c in node.ran)
assert any("systemctl" in c and "restart" in c and "zabbix-agent" in c for c in node.ran)
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, node):
driver.configure_zabbix_agent(SETTINGS)
assert "Server=zabbix.example.com\n" in node.config
assert "Hostname=pve-01\n" in node.config
assert node.config.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
assert any(f"cp -p {CONFIG} {CONFIG}.bak" in c for c in node.ran)
def test_a_config_that_already_says_it_is_not_written(driver, node):
driver.configure_zabbix_agent(SETTINGS)
node.ran.clear()
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert not any("base64 -d" in c for c in node.ran)
def test_without_debian_s_package_zabbix_s_repository_is_added(driver, node):
node.debian_has_it = False
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
repository = next(c for c in node.ran if "repo.zabbix.com" in c)
assert "zabbix-release_latest_7.4+debian13_all.deb" in repository
def test_ufw_opens_the_listen_port_for_the_sources(driver, node):
driver.configure_zabbix_agent(SETTINGS)
assert any("ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in c for c in node.ran)
def test_without_ufw_the_firewall_is_the_operator_s(driver, node):
node.ufw = False
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert "pve-firewall rules are the operator's" in result["output"]
assert not any("ufw allow" in c for c in node.ran)
def test_a_config_that_cannot_be_read_stops_the_fix(driver, node):
node.refuse = f"cat {CONFIG}"
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
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