72 Commits
Author SHA1 Message Date
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 / types (push) Successful in 1m13s
driver / lowest (push) Successful in 34s
driver / standard (push) Successful in 19s
driver / test (3.12) (push) Successful in 1m21s
CI / driver (push) Successful in 4m20s
2026-11-03 04:18:55 +00:00
Christian Manivong ff5018a3b4 chore(release): 0.10.0
driver / build (pull_request) Successful in 37s
driver / security (pull_request) Successful in 1m18s
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 / test (3.13) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 1m10s
driver / lint (pull_request) Successful in 13s
driver / publish (pull_request) Skipped
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 / types (push) Successful in 54s
driver / lowest (push) Successful in 40s
driver / standard (push) Successful in 15s
driver / test (3.12) (push) Successful in 1m8s
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
driver / build (pull_request) Successful in 50s
CI / driver (pull_request) Successful in 3m31s
driver / standard (pull_request) Successful in 1m26s
driver / types (pull_request) Successful in 2m17s
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 / 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 / types (push) Successful in 56s
driver / lowest (push) Successful in 32s
driver / standard (push) Successful in 14s
driver / test (3.12) (push) Successful in 1m5s
CI / driver (push) Successful in 2m44s
2026-11-02 21:40:34 +00:00
Christian Manivong 0bb25a0c86 chore(release): 0.9.0
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 53s
CI / driver (pull_request) Successful in 2m30s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m4s
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 / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
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 / types (push) Successful in 58s
driver / lowest (push) Successful in 34s
driver / standard (push) Successful in 14s
driver / test (3.12) (push) Successful in 1m8s
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 / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m20s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m5s
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 / 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 / types (push) Successful in 1m1s
driver / standard (push) Successful in 15s
driver / test (3.12) (push) Failing after 5s
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 / build (pull_request) Successful in 35s
driver / security (pull_request) Successful in 1m16s
CI / driver (pull_request) Successful in 3m4s
driver / standard (pull_request) Successful in 20s
driver / test (3.12) (pull_request) Successful in 1m25s
driver / types (pull_request) Successful in 1m27s
driver / test (3.13) (pull_request) Successful in 1m11s
driver / lowest (pull_request) Successful in 35s
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 / types (push) Successful in 1m7s
driver / lowest (push) Successful in 39s
driver / standard (push) Successful in 22s
driver / test (3.12) (push) Successful in 1m13s
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 / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m9s
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 / test (3.13) (pull_request) Successful in 1m12s
driver / lowest (pull_request) Successful in 39s
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 / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m9s
CI / driver (pull_request) Successful in 2m44s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 58s
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 / 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 / types (push) Successful in 1m12s
driver / lowest (push) Successful in 35s
driver / standard (push) Successful in 17s
driver / test (3.12) (push) Successful in 1m17s
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 / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m13s
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 / lowest (pull_request) Successful in 44s
driver / test (3.13) (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
driver / build (pull_request) Successful in 33s
CI / driver (pull_request) Failing after 1m39s
driver / standard (pull_request) Successful in 18s
driver / test (3.12) (pull_request) Failing after 17s
driver / types (pull_request) Failing after 27s
driver / test (3.13) (pull_request) Failing after 15s
driver / lowest (pull_request) Failing after 18s
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 / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m21s
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 / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 39s
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 / types (push) Successful in 1m15s
driver / lowest (push) Successful in 34s
driver / standard (push) Successful in 17s
driver / test (3.12) (push) Successful in 1m26s
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 / 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 / test (3.13) (pull_request) Failing after 17s
driver / lowest (pull_request) Failing after 18s
driver / lint (pull_request) Successful in 16s
driver / publish (pull_request) Skipped
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 / build (pull_request) Successful in 40s
driver / security (pull_request) Successful in 1m15s
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 / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 35s
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 / types (push) Successful in 1m2s
driver / lowest (push) Successful in 46s
driver / standard (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m21s
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 / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m14s
CI / driver (pull_request) Successful in 2m47s
driver / standard (pull_request) Successful in 21s
driver / types (pull_request) Successful in 1m12s
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 / 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 / types (push) Successful in 1m27s
driver / lowest (push) Successful in 37s
driver / standard (push) Successful in 17s
driver / test (3.12) (push) Successful in 1m43s
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 / types (push) Successful in 1m12s
driver / lowest (push) Successful in 1m0s
driver / standard (push) Successful in 18s
driver / test (3.12) (push) Successful in 1m20s
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 / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m27s
CI / driver (pull_request) Successful in 3m4s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m3s
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 / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
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 / build (pull_request) Successful in 31s
driver / security (pull_request) Successful in 1m9s
CI / driver (pull_request) Failing after 2m49s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m5s
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 / 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 / build (pull_request) Successful in 38s
driver / security (pull_request) Successful in 1m20s
CI / driver (pull_request) Successful in 3m12s
driver / standard (pull_request) Successful in 18s
driver / types (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 / 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 / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Successful in 3m19s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m29s
driver / test (3.13) (pull_request) Successful in 1m26s
driver / test (3.12) (pull_request) Successful in 1m39s
driver / lowest (pull_request) Successful in 37s
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 / types (push) Successful in 1m4s
driver / standard (push) Successful in 15s
driver / test (3.12) (push) Failing after 6s
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 / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m21s
CI / driver (pull_request) Successful in 2m58s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m10s
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 / 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 / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 1m3s
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 / test (3.13) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 31s
driver / lint (pull_request) Successful in 13s
driver / publish (pull_request) Skipped
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 / types (push) Failing after 6s
driver / lowest (push) Successful in 34s
driver / standard (push) Successful in 20s
driver / test (3.12) (push) Successful in 1m12s
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 / types (push) Successful in 1m32s
driver / lowest (push) Successful in 36s
driver / standard (push) Successful in 18s
driver / test (3.12) (push) Successful in 1m36s
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 / build (pull_request) Successful in 37s
driver / security (pull_request) Successful in 1m21s
CI / driver (pull_request) Successful in 3m5s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m7s
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 / 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 / build (pull_request) Successful in 39s
driver / security (pull_request) Successful in 1m17s
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 / test (3.13) (pull_request) Successful in 59s
driver / lowest (pull_request) Successful in 38s
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 / types (push) Successful in 1m3s
driver / lowest (push) Successful in 33s
driver / standard (push) Successful in 17s
driver / test (3.12) (push) Successful in 1m10s
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 / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m25s
CI / driver (pull_request) Successful in 3m1s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 59s
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 / 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 / types (push) Successful in 1m10s
driver / test (3.11) (push) Successful in 1m19s
driver / lowest (push) Successful in 36s
driver / standard (push) Successful in 17s
driver / test (3.10) (push) Successful in 1m18s
driver / test (3.12) (push) Successful in 1m9s
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 / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 3m17s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m2s
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 / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 11s
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
christianmanivong f3639d9990 Merge pull request 'chore: adopt the NAPALM driver standard' (#33) from chore/driver-standard into main
driver / lint (push) Successful in 17s
driver / test (3.13) (push) Successful in 1m9s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m10s
driver / publish (push) Successful in 32s
driver / types (push) Successful in 1m8s
driver / test (3.11) (push) Successful in 1m23s
driver / lowest (push) Successful in 42s
driver / standard (push) Successful in 17s
driver / test (3.10) (push) Successful in 1m26s
driver / test (3.12) (push) Successful in 1m14s
CI / driver (push) Successful in 4m6s
2026-10-23 12:17:27 +00:00
Christian Manivong 711d5f2705 chore(release): 0.8.0
driver / test (3.10) (pull_request) Successful in 1m13s
driver / test (3.11) (pull_request) Successful in 1m18s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m9s
CI / driver (pull_request) Successful in 3m29s
driver / standard (pull_request) Successful in 15s
driver / types (pull_request) Successful in 59s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 59s
driver / lowest (pull_request) Successful in 45s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 12s
2026-10-23 12:02:11 +02:00
Christian Manivong 457c1ca7ed chore: adopt the NAPALM driver standard
driver / test (3.10) (pull_request) Failing after 44s
driver / test (3.11) (pull_request) Failing after 1m6s
driver / security (pull_request) Failing after 46s
driver / build (pull_request) Successful in 22s
CI / driver (pull_request) Failing after 6m3s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Failing after 53s
driver / test (3.12) (pull_request) Failing after 47s
driver / test (3.13) (pull_request) Failing after 36s
driver / lowest (pull_request) Failing after 19s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
- CI moves to .gitea/workflows/ci.yml and calls the shared driver workflow
  of NAPALM/driver-standard; .github/ is gone. napalm-device-types comes
  from git until 4.22.0 (AptProxyMixin) is on PyPI; the floor stays at
  4.22.0.
- requires-python >=3.10 (napalm-device-types needs it), py.typed, SPDX
  license string, a dev extra with floors (pytest-mock and responses are
  dropped: no test uses them), links to git.netork.io (README included).
  pytest no longer adds --cov by itself; CI passes it.
- mypy strict for the package; exempt for now, with 204 errors between
  them: napalm_proxmox.config_mixin, .driver, .interfaces_mixin,
  .lldp_mixin, .routing_mixin, .sdn_mixin, .system_mixin, .utils,
  .vm_contract_mixin, .vm_mixin and .vm_provision_mixin. They are recorded
  in the quality baseline with the long and complex functions and the two
  unannotated public methods.
- Coverage floor 68 % (measured 68.94 %).
2026-10-23 08:40:41 +02:00
Christian Manivong 3365207c98 fix: what bandit and the remaining lint rules found
- driver.py: the logger is defined after the imports (E402). The lazy
  paramiko client is annotated Any, as _node_ssh already is; the quoted
  paramiko.SSHClient named a module that is never imported there (F821).
- Unused locals are gone: get_facts' hostname, get_users' groups (both
  read a value nobody used), the ARP flags column is _flags; the output is
  unchanged.
- Long lines are wrapped: the apt-get and snmpd.conf commands are split
  into adjacent string literals, the power-action error message and the
  system mixin's docstring are wrapped; the text is unchanged.
- get_vm_status re-raises with raise ... from e (B904).
- The two except Exception: pass (closing the SSH session, the is_alive
  probe) now log at debug level (B110), so a swallowed failure leaves a
  trace.
- nosec for the empty "password" field of NAPALM's get_users shape and
  the ssh_password_auth flag (B105); all three are false positives.
- tests: unused loop variables.
2026-10-23 08:39:01 +02:00
Christian Manivong 3b873d91fe style: ruff format and the lint rules of the driver standard
Mechanical: ruff format, and ruff check --fix with the rule set every NAPALM
driver uses (E, F, I, UP, B at line length 100, Python 3.10). What ruff
cannot fix comes in the next commit.
2026-10-23 08:37:27 +02:00
christianmanivong 1f6859de08 Merge pull request 'feat: apt's proxy on a Proxmox VE node (NetOrk/netork#1397)' (#31) from feat/apt-proxy-verify into master
CI / test (3.10) (push) Failing after 14s
CI / test (3.11) (push) Failing after 13s
CI / test (3.12) (push) Failing after 13s
2026-10-22 22:08:25 +00:00
Christian Manivong 7776bb904a feat: apt's proxy on a Proxmox VE node (NetOrk/netork#1397)
CI / test (3.10) (push) Failing after 19s
CI / test (3.11) (push) Failing after 17s
CI / test (3.10) (pull_request) Failing after 18s
CI / test (3.12) (push) Failing after 20s
CI / test (3.12) (pull_request) Failing after 19s
CI / test (3.11) (pull_request) Failing after 20s
The node is Debian: AptProxyMixin gives it get_package_proxy(),
get_package_proxy_report(), check_package_proxy() and the fix
configure_package_proxy(), as on any Debian host. Logged in as root, the
transports are the exec path; the file is written without an exit inside
_rc's braces, which would end the shell before the status (see #30).

Requires napalm-device-types 4.22.0; version 0.7.0.
2026-10-22 19:16:40 +02:00
christianmanivong 03c7cdfa02 Merge pull request 'feat: get_service_packages, which packages a node's systemd unit is (NetOrk/netork#1236)' (#29) from feat/service-packages-1236 into master
CI / test (3.10) (push) Successful in 38s
CI / test (3.11) (push) Successful in 42s
CI / test (3.12) (push) Successful in 52s
2026-10-19 17:08:12 +00:00
Christian Manivong e0d0147d75 feat: get_service_packages, which packages a node's systemd unit is (NetOrk/netork#1236)
CI / test (3.10) (pull_request) Successful in 42s
CI / test (3.10) (push) Successful in 53s
CI / test (3.11) (push) Successful in 46s
CI / test (3.12) (pull_request) Successful in 37s
CI / test (3.12) (push) Successful in 43s
CI / test (3.11) (pull_request) Successful in 33s
Mixes in napalm-device-types' ServicePackagesMixin; the transport is the
node's exec path, as for the kernel facts. Read-only. Requires
napalm-device-types 4.20.0; version 0.6.0.
2026-10-19 17:41:14 +02:00
christianmanivong d210c9abe8 Merge pull request 'fix(ssh): verify the host key netOrk expects, report the one seen (NetOrk/netork#1167)' (#27) from fix/ssh-host-key-tofu-1167 into master
CI / test (3.10) (push) Successful in 44s
CI / test (3.11) (push) Successful in 46s
CI / test (3.12) (push) Successful in 46s
2026-10-18 19:23:46 +00:00
Christian Manivong 6bb3035857 fix(ssh): verify the host key netOrk expects, report the one seen (NetOrk/netork#1167)
CI / test (3.10) (push) Successful in 54s
CI / test (3.11) (push) Successful in 40s
CI / test (3.10) (pull_request) Successful in 42s
CI / test (3.12) (push) Successful in 51s
CI / test (3.12) (pull_request) Successful in 49s
CI / test (3.11) (pull_request) Successful in 35s
The driver accepted any SSH host key. It now verifies through
napalm-device-types' HostKeyCheck (>= 4.19.0): with a known key in
optional_args["ssh_host_keys"] any other key is refused before login, and
every key seen is reported to optional_args["ssh_host_key_observer"].
Without either argument it connects as before (first use).
2026-10-18 21:23:46 +02:00
christianmanivong d134ccbb89 Merge pull request 'feat!: report the subscription as a license, not a warning (0.4.0)' (#26) from feat/facts-not-warnings into master
CI / test (3.10) (push) Successful in 44s
CI / test (3.11) (push) Successful in 39s
CI / test (3.12) (push) Successful in 37s
2026-10-17 08:34:56 +00:00
Christian Manivong 1100560f85 feat!: report the subscription as a license, not a warning (0.4.0)
CI / test (3.10) (push) Successful in 33s
CI / test (3.11) (push) Successful in 30s
CI / test (3.10) (pull_request) Successful in 32s
CI / test (3.12) (pull_request) Successful in 34s
CI / test (3.12) (push) Successful in 35s
CI / test (3.11) (pull_request) Successful in 31s
get_device_warnings is gone; netOrk names the warnings from facts
(netOrk #1111). lldpd and the pending updates were already facts
(get_packages, get_available_updates). The subscription is now
get_licenses() from napalm-device-types 4.14's LicenseMixin: one
pve-subscription entry, the API status mapped to a LicenseStatus.

The old check compared against "NotFound" while the API answers
"notfound" (seen on all four nodes), so it never fired; the mapping is
case-insensitive.
2026-10-17 09:36:18 +02:00
christianmanivong 8cf334aaf5 Merge pull request 'feat!: fix templates with the caller's values replace run_device_action (0.3.0)' (#25) from feat/fix-templates into master
CI / test (3.10) (push) Successful in 42s
CI / test (3.11) (push) Successful in 41s
CI / test (3.12) (push) Successful in 46s
2026-10-17 06:48:18 +00:00
Christian Manivong 377e849237 docs: changelog for 0.3.0
CI / test (3.10) (push) Successful in 32s
CI / test (3.11) (push) Successful in 30s
CI / test (3.10) (pull_request) Successful in 32s
CI / test (3.12) (pull_request) Successful in 34s
CI / test (3.12) (push) Successful in 35s
CI / test (3.11) (pull_request) Successful in 30s
2026-10-17 08:29:05 +02:00
Christian Manivong 890e84ca6b feat!: fix templates with the caller's values replace run_device_action (0.3.0)
CI / test (3.10) (push) Successful in 33s
CI / test (3.11) (push) Successful in 32s
CI / test (3.10) (pull_request) Successful in 32s
CI / test (3.12) (push) Successful in 35s
CI / test (3.12) (pull_request) Successful in 35s
CI / test (3.11) (pull_request) Successful in 30s
fix_snmp overwrote snmpd.conf with an application's values (community
"public", "Managed by netOrk", netork@localhost) through a fixed
/tmp/netork_snmpd.conf, and opened ufw for a /24 guessed from ss;
install_lldpd was an action of its own. Neither read an exit status.

The driver implements napalm-device-types 4.13's templates instead:
- configure_snmp_agent(settings): net-snmp installed, snmpd.conf with
  one rocommunity line per allowed source (mktemp, install as root),
  ufw opened for those sources only (pve-firewall stays the
  operator's), snmpd enabled and restarted;
- get_management_peer() from SSH_CONNECTION;
- install_package(name), as the contract says (raises when apt fails),
  so ensure_package comes from the base package.
Every step reads its exit status.

BREAKING CHANGE: run_device_action is removed. Requires
napalm-device-types 4.13.

Part of #24.
2026-10-17 08:28:50 +02:00
christianmanivong 98df0e21ca feat: get_system_identity for matching a node to its BMC (0.2.0)
CI / test (3.10) (push) Successful in 37s
CI / test (3.11) (push) Successful in 37s
CI / test (3.12) (push) Successful in 39s
Mixes in napalm-device-types 4.9's SystemIdentityMixin over the exec
path, which runs as root: the node's SMBIOS system UUID, product serial
and board serial, vendor placeholders empty. pve-dual, a Supermicro
X10DRL-i, reports the product serial 0123456789; its board serial and
UUID are what tie it to its BMC.
2026-10-13 12:20:14 +02:00
christianmanivong 363f93c895 Merge pull request 'feat(vm-provision): provision FreeBSD and OpenBSD guests' (#16) from feat/guest-os into master
CI / test (3.10) (push) Successful in 34s
CI / test (3.11) (push) Successful in 31s
CI / test (3.12) (push) Successful in 35s
2026-10-08 06:05:05 +00:00
74 changed files with 10273 additions and 1292 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
name: CI
on:
push:
branches: [main, master]
tags: ["v*"]
pull_request:
jobs:
driver:
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
with:
standard-ref: main
secrets:
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
-48
View File
@@ -1,48 +0,0 @@
name: CI
on:
push:
branches: ["**"]
pull_request:
branches: ["**"]
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
- name: Install package with dev extras
run: |
python -m pip install --upgrade pip
# napalm-device-types lives in git.netork.io/NAPALM, not on PyPI: without this
# pip looks there, finds an unrelated 0.1.0 and the job dies before any test.
python -m pip install "napalm-device-types @ git+https://git.netork.io/NAPALM/napalm-device-types.git"
python -m pip install -e ".[dev]"
- name: Run unit tests
run: |
python -m pytest -q --tb=short
- name: Build wheel and sdist
run: |
python -m pip install build
python -m build
- name: Upload dist artifacts
# v4 refuses to run on Gitea ("not currently supported on GHES").
uses: actions/upload-artifact@v3
with:
name: dist-${{ matrix.python-version }}
path: dist/*
+219
View File
@@ -7,7 +7,226 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [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.
### Changed
- The driver follows the NAPALM driver standard
(https://git.netork.io/NAPALM/driver-standard): CI on Gitea runs ruff, mypy, the
tests on Python 3.10–3.13 and at the lowest declared versions, bandit, pip-audit and
a build check, and a release tag publishes to PyPI. The package now ships `py.typed`.
**Python 3.9 is no longer supported**; napalm-device-types never ran on it.
- Exceptions the driver deliberately ignores (closing the node's SSH session, the
`is_alive()` probe) are now logged at debug level.
- The project links point at git.netork.io.
### Added
- apt's proxy (napalm-device-types' `AptProxyMixin`, NetOrk/netork#1397): `get_package_proxy()`, `get_package_proxy_report()`, `check_package_proxy(url, expect)` and the fix `configure_package_proxy(url)`, as on any Debian host. The node is logged in as root, so the file is written and other proxy lines are commented out over the exec path. Requires napalm-device-types 4.22.0; version 0.7.0.
- `get_service_packages()` (napalm-device-types' `ServicePackagesMixin`, NetOrk/netork#1236): which installed packages each systemd unit of the node is made of — the one shipping its unit file and the one shipping its `ExecStart` binary. Read-only, over the exec path. Requires napalm-device-types 4.20.0; version 0.6.0.
### Security
- The node's SSH session (the fallback for node commands and the provisioning steps) verifies its host key (NetOrk/netork#1167): the key the caller expects for port 22 in `optional_args["ssh_host_keys"]`, else the first one; every key seen goes to `optional_args["ssh_host_key_observer"]`. A changed key is refused before any login: a provisioning step fails, a best-effort read returns nothing. Both paths now share one session (`_node_ssh`). Replaces paramiko's `AutoAddPolicy`. Requires napalm-device-types 4.19.0; version 0.5.0.
### Changed
- **Breaking:** `get_device_warnings` is gone; the node reports facts and the caller
names the warnings (netOrk #1111). lldpd and the pending updates were already facts
(`get_packages`, `get_available_updates`). The subscription is now
`get_licenses()` (napalm-device-types 4.14 `LicenseMixin`): one `pve-subscription`
entry with the API's status as a `LicenseStatus` (`notfound` → `none`, `new` and
`suspended` → `unknown`), its message as `detail`, product name and due date when
subscribed. The old check compared against `NotFound` while the API answers
`notfound`, so it never fired. Requires napalm-device-types 4.14.0; version 0.4.0.
- **Breaking:** `run_device_action` (`fix_snmp`, `install_lldpd`) is gone. The driver
implements napalm-device-types 4.13's fix templates: `configure_snmp_agent(settings)`
with the caller's community and allowed sources (one `rocommunity` line each, ufw only
for those sources, no fixed temp file), `get_management_peer()`, and
`install_package(name)` as the contract says, so `ensure_package` comes from the base
package. Every step reads its exit status. Requires napalm-device-types 4.13.0;
version 0.3.0.
### Added
- `get_system_identity()` (napalm-device-types 4.9 `SystemIdentityMixin`): the node's SMBIOS
system UUID, product serial and board serial over the exec path, vendor placeholders
empty. netOrk matches a server to its BMC on these. Requires napalm-device-types 4.9.0;
version 0.2.0.
- FreeBSD and OpenBSD guests: `create_vm_from_cloud_init(guest_os=...)` with
`GUEST_AGENTS` from napalm-device-types 3.0. A BSD guest gets OS type
`other` and a network-config v2 snippet of its own (`cicustom network=`),
+90 -17
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,8 +15,9 @@ It supports all three networking domains of Proxmox VE:
## Requirements
- Python ≥ 3.9
- Python ≥ 3.12
- NAPALM ≥ 5.0.0
- napalm-device-types ≥ 4.22.0
- proxmoxer ≥ 2.0.0
- netaddr ≥ 0.9.0
- requests ≥ 2.31.0
@@ -27,7 +31,7 @@ pip install napalm-proxmox
Or directly from source:
```bash
git clone https://github.com/example/napalm-proxmox.git
git clone https://git.netork.io/NAPALM/napalm-proxmox.git
cd napalm-proxmox
pip install -e .
```
@@ -45,9 +49,9 @@ device = driver(
username="root",
password="secret",
optional_args={
"realm": "pam", # default: "pam"
"port": 8006, # default: 8006
"verify_ssl": True, # default: True
"realm": "pam", # default: "pam"
"port": 8006, # default: 8006
"verify_ssl": True, # default: True
},
)
@@ -102,7 +106,7 @@ 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 |
@@ -115,13 +119,13 @@ 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 |
**Not implemented** (raise `NotImplementedError`):
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
@@ -137,6 +141,67 @@ 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 |
**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
@@ -156,9 +221,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,7 +238,10 @@ tests/
├── 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_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"]
+408
View File
@@ -0,0 +1,408 @@
"""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
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 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 _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)
+105
View File
@@ -0,0 +1,105 @@
"""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,
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
logger = logging.getLogger(__name__)
#: The node name the PBS API answers to; a PBS has exactly one.
PBS_NODE = "localhost"
class ProxmoxBackupDriver(
ProxmoxBase,
ProxmoxBackupServerMixin,
ProxmoxPbsHostMixin,
ProxmoxHostMixin,
BackupServerDriver,
StorageDriver,
KernelFactsMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
SystemIdentityMixin,
SystemdServicesMixin,
HostStatusMixin,
LicenseMixin,
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
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"])
+302
View File
@@ -0,0 +1,302 @@
"""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 and quorum, 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 _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 always None: PVE gives a cluster no identity beyond its name.
``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": None,
"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
+5 -10
View File
@@ -19,7 +19,6 @@ from __future__ import annotations
import re
from typing import Any
_JsonDict = dict[str, Any]
@@ -44,13 +43,9 @@ class ProxmoxConfigMixin:
configs: _JsonDict = {"running": "", "candidate": "", "startup": ""}
if retrieve in ("running", "all", "startup"):
raw = self._exec_ssh_command(
"cat /etc/network/interfaces 2>/dev/null || true"
)
raw = self._exec_ssh_command("cat /etc/network/interfaces 2>/dev/null || true")
# Append SDN config if available
sdn_raw = self._exec_ssh_command(
"cat /etc/pve/sdn/vnets.cfg 2>/dev/null || true"
)
sdn_raw = self._exec_ssh_command("cat /etc/pve/sdn/vnets.cfg 2>/dev/null || true")
running = raw
if sdn_raw:
running += "\n# === SDN VNets ===\n" + sdn_raw
@@ -119,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 && "
+45 -292
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
@@ -32,36 +24,45 @@ from __future__ import annotations
import logging
from typing import Any
logger = logging.getLogger(__name__)
from napalm.base.exceptions import ConnectionException
from napalm_device_types import (
AptProxyMixin,
EnsurePackageMixin,
FingerprintRule,
HostStatusMixin,
HypervisorDriver,
KernelFactsMixin,
LicenseMixin,
ListeningSocketsMixin,
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
SnmpAgentMixin,
SystemdServicesMixin,
SystemIdentityMixin,
)
from napalm.base.exceptions import ConnectionException
try:
from proxmoxer import ProxmoxAPI
except ImportError as exc:
raise ImportError(
"proxmoxer is required: pip install proxmoxer"
) from exc
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
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.sdn_mixin import ProxmoxSDNMixin
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
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
logger = logging.getLogger(__name__)
# --------------------------------------------------------------------------- #
# Type aliases
@@ -74,6 +75,7 @@ _JsonDict = dict[str, Any]
class ProxmoxDriver(
ProxmoxBase,
ProxmoxInterfaceMixin,
ProxmoxSDNMixin,
ProxmoxLLDPMixin,
@@ -82,19 +84,30 @@ class ProxmoxDriver(
ProxmoxVMContractMixin,
ProxmoxVMSnapshotMixin,
ProxmoxVMProvisionMixin,
ProxmoxClusterMixin,
ProxmoxVMMigrateMixin,
ProxmoxRoutingMixin,
ProxmoxSystemMixin,
ProxmoxHostMixin,
KernelFactsMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
SystemIdentityMixin,
SystemdServicesMixin,
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
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
@@ -123,29 +136,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 = ""
self._ssh_client: "paramiko.SSHClient | None" = None
# Candidate config (merge/replace)
self._candidate_config: str = ""
self._running_config: str = ""
@@ -154,53 +147,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.
@@ -218,9 +166,7 @@ class ProxmoxDriver(
self._node_name = self._node
return self._node_name
members = [
s for s in (self._api.cluster.status.get() or []) if s.get("type") == "node"
]
members = [s for s in (self._api.cluster.status.get() or []) if s.get("type") == "node"]
short_host = self.hostname.split(".")[0]
for pick in (
lambda s: s.get("local"),
@@ -242,151 +188,10 @@ 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:
pass
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:
pass
return {"is_alive": alive}
# ------------------------------------------------------------------ #
# Internal API helpers
# Node info helpers (PVE only)
# ------------------------------------------------------------------ #
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
import time as _time
# 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:
import paramiko
if self._ssh_client is None:
ssh_user = self._ssh_username or self.username
ssh_pass = self._ssh_password or self.password
ssh_pkey = None
if self._ssh_key and not ssh_pass:
from io import StringIO as _StringIO
ssh_pkey = paramiko.RSAKey.from_private_key(_StringIO(self._ssh_key))
self._ssh_client = paramiko.SSHClient()
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
connect_kwargs: _JsonDict = {
"hostname": self.hostname,
"port": 22,
"username": ssh_user,
"timeout": self.timeout,
}
if ssh_pkey:
connect_kwargs["pkey"] = ssh_pkey
else:
connect_kwargs["password"] = ssh_pass
self._ssh_client.connect(**connect_kwargs)
_, stdout, stderr = self._ssh_client.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 Exception as exc:
logger.debug("SSH exec command failed: %s", exc)
return ""
# ------------------------------------------------------------------ #
# 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:
@@ -413,57 +218,15 @@ class ProxmoxDriver(
uptime = float(status.get("uptime", 0))
dns_search = dns.get("search", "")
hostname = self._node_name
fqdn = f"{self._node_name}.{dns_search}" if dns_search else self.hostname
iface_list = sorted(
iface["iface"] for iface in network if iface.get("iface")
)
iface_list = sorted(iface["iface"] for iface in network if iface.get("iface"))
pve_version = version.get("version", "")
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.
@@ -484,13 +247,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}
+308
View File
@@ -0,0 +1,308 @@
"""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, parse_apt_upgradable
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 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 _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}"
+16 -13
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:
@@ -174,8 +176,13 @@ class ProxmoxInterfaceMixin:
parts = line.split()
if len(parts) < 6:
continue
ip_addr, _, flags, mac, _, iface = (
parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]
ip_addr, _, _flags, mac, _, iface = (
parts[0],
parts[1],
parts[2],
parts[3],
parts[4],
parts[5],
)
if mac in ("00:00:00:00:00:00", ""):
continue
@@ -202,9 +209,7 @@ class ProxmoxInterfaceMixin:
if iface.get("type") in ("bridge",) and iface.get("iface")
]
for bridge in linux_bridges:
raw = self._exec_ssh_command(
f"bridge fdb show br {bridge} 2>/dev/null || true"
)
raw = self._exec_ssh_command(f"bridge fdb show br {bridge} 2>/dev/null || true")
for line in raw.splitlines():
parts = line.split()
if len(parts) < 3:
@@ -240,9 +245,7 @@ class ProxmoxInterfaceMixin:
if iface.get("type") in ("OVSBridge",) and iface.get("iface")
]
for bridge in ovs_bridges:
raw = self._exec_ssh_command(
f"ovs-appctl fdb/show {bridge} 2>/dev/null || true"
)
raw = self._exec_ssh_command(f"ovs-appctl fdb/show {bridge} 2>/dev/null || true")
for line in raw.splitlines():
parts = line.split()
if len(parts) < 4:
+44 -79
View File
@@ -12,96 +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
+27
View File
@@ -0,0 +1,27 @@
"""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]+")
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()]
View File
Whitespace-only changes.
+9 -10
View File
@@ -21,9 +21,12 @@ from typing import Any
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)."""
@@ -55,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 = (
@@ -91,13 +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": {
@@ -127,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():
+16 -12
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]
@@ -153,7 +164,7 @@ class ProxmoxSDNMixin:
tags.setdefault(str(tag), set()).add(bridge)
try:
for vm in (self._node_api().qemu.get() or []):
for vm in self._node_api().qemu.get() or []:
vmid = int(vm.get("vmid", 0))
try:
config = self._node_api().qemu(vmid).config.get() or {}
@@ -164,7 +175,7 @@ class ProxmoxSDNMixin:
logger.warning("_get_vm_vlan_tags: failed to list QEMU VMs: %s", exc)
try:
for ct in (self._node_api().lxc.get() or []):
for ct in self._node_api().lxc.get() or []:
vmid = int(ct.get("vmid", 0))
try:
config = self._node_api().lxc(vmid).config.get() or {}
@@ -238,9 +249,7 @@ class ProxmoxSDNMixin:
2. LLDP basic fallback: first physical port with any LLDP neighbour.
"""
network = {
iface["iface"]: iface
for iface in self._get_node_network()
if iface.get("iface")
iface["iface"]: iface for iface in self._get_node_network() if iface.get("iface")
}
try:
@@ -309,10 +318,7 @@ class ProxmoxSDNMixin:
return True
min_id = min(int(n.get("nodeid", 9999)) for n in online_nodes)
for n in online_nodes:
if (
n.get("name") == self._node_name
and int(n.get("nodeid", 9999)) == min_id
):
if n.get("name") == self._node_name and int(n.get("nodeid", 9999)) == min_id:
return True
return False
except Exception as exc:
@@ -361,9 +367,7 @@ class ProxmoxSDNMixin:
vlan_id: VLAN identifier (1-4094).
config: Dict that may contain ``"name"`` for the VLAN alias.
"""
name: str = (
(config.get("name") or f"VLAN{vlan_id}") if config else f"VLAN{vlan_id}"
)
name: str = (config.get("name") or f"VLAN{vlan_id}") if config else f"VLAN{vlan_id}"
vnet_id = f"vlan{vlan_id:04d}"
uplink = self._find_switch_uplink()
+205 -409
View File
@@ -12,22 +12,117 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""System-level NAPALM getters for Proxmox VE nodes (environment, NTP, SNMP, users, packages, services, updates, disk SMART)."""
"""System-level NAPALM getters for Proxmox VE nodes.
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 ipaddress
import logging
import re
from typing import Any
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
from napalm.base.exceptions import CommandErrorException
from napalm_proxmox import utils
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: 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:
return str(ipaddress.ip_network(value.strip(), strict=False))
def render_snmpd_conf(settings: dict) -> str:
"""net-snmp's configuration for *settings*: read-only v2c, per allowed source."""
community = settings["community"]
if not _SNMP_WORD.match(community):
raise ValueError("the community must be one word without quotes or #")
listen = settings.get("listen")
lines = [f"agentAddress udp:{listen + ':' if listen else ''}161"]
sources = [_net(s) for s in settings.get("allowed_sources", [])]
lines += [f"rocommunity {community} {s}" for s in sources] or [f"rocommunity {community}"]
for key, directive in (("location", "sysLocation"), ("contact", "sysContact")):
value = settings.get(key, "")
if value:
if "\n" in value:
raise ValueError(f"{key} must be one line")
lines.append(f"{directive} {value}")
return "\n".join(lines) + "\n"
class ProxmoxSystemMixin:
"""Mixin providing system-level NAPALM methods."""
@@ -97,36 +192,8 @@ class ProxmoxSystemMixin:
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
@@ -138,9 +205,7 @@ class ProxmoxSystemMixin:
Proxmox does not expose SNMP configuration via the REST API.
We read /etc/snmp/snmpd.conf via exec if available.
"""
raw = self._exec_ssh_command(
"cat /etc/snmp/snmpd.conf 2>/dev/null || true"
)
raw = self._exec_ssh_command("cat /etc/snmp/snmpd.conf 2>/dev/null || true")
communities: dict[str, _JsonDict] = {}
location = ""
contact = ""
@@ -175,256 +240,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
groups = user.get("groups", "") or ""
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,
"password": "",
"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,
"password": "",
"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)
# ------------------------------------------------------------------ #
# Listening sockets (ListeningSocketsMixin supplies get_listening_sockets)
# ------------------------------------------------------------------ #
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
# ------------------------------------------------------------------ #
# Device warnings
# Licenses (napalm-device-types' LicenseMixin)
# ------------------------------------------------------------------ #
def get_device_warnings(self) -> list[_JsonDict]:
"""Return warnings for the Proxmox node.
Currently detects:
- lldpd not installed (LLDP neighbor discovery unavailable)
- Available package updates (via Proxmox APT API)
- Missing / invalid subscription
"""
warnings: list[_JsonDict] = []
# 0. LLDP daemon
try:
lldpd_path = self._exec_ssh_command("command -v lldpd 2>/dev/null").strip()
if not lldpd_path:
warnings.append({"code": "lldpd_not_installed"})
except Exception as exc:
logger.debug("Failed to check for lldpd: %s", exc)
# 1. Available package updates
try:
updates = self.get_available_updates()
if updates:
warnings.append({
"code": "updates_available",
"meta": {
"count": len(updates),
"packages": [u["name"] for u in updates],
},
})
except Exception as exc:
logger.debug("Failed to check available updates: %s", exc)
# 2. Subscription status
try:
sub = self._get_node_subscription()
status = sub.get("status", "")
if status in ("NotFound", "Invalid", "Expired"):
warnings.append({"code": "no_subscription", "meta": {"status": status}})
except Exception as exc:
logger.debug("Failed to check subscription status: %s", exc)
return warnings
# ------------------------------------------------------------------ #
# 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(
f"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y {pkg_args} 2>&1 || true"
)
return {"success": True, "output": output}
# ------------------------------------------------------------------ #
# SNMP / Health
# ------------------------------------------------------------------ #
@@ -432,7 +317,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:
@@ -451,7 +337,8 @@ class ProxmoxSystemMixin:
port = 161
try:
conf = self._exec_ssh_command(
"grep -E '^[[:space:]]*(ro|rw)?community' /etc/snmp/snmpd.conf 2>/dev/null | head -5"
"grep -E '^[[:space:]]*(ro|rw)?community' /etc/snmp/snmpd.conf "
"2>/dev/null | head -5"
)
for line in conf.splitlines():
parts = line.split()
@@ -469,131 +356,48 @@ class ProxmoxSystemMixin:
return SNMPConfigDict(running=True, community=community, port=port, version="2c")
def run_device_action(self, action: str) -> dict:
"""Execute a named administrative action on the Proxmox node."""
if action == "fix_snmp":
return self._action_fix_snmp()
if action == "install_lldpd":
return self._action_install_lldpd()
raise NotImplementedError(f"Unknown action: {action!r}")
# ------------------------------------------------------------------
# Fixes (napalm-device-types SnmpAgentMixin, EnsurePackageMixin): the
# caller's values. The node's shell runs as root.
# ------------------------------------------------------------------
def _action_install_lldpd(self) -> dict:
"""Install, enable and start lldpd on the Proxmox node.
# apt's proxy (napalm-device-types AptProxyMixin): the transports. The node
# is logged in as root, so every command runs as root.
Proxmox runs Debian/Linux underneath, so this is a plain apt install
followed by enabling the systemd service. lldpd's defaults (listen on
all interfaces) are sufficient to discover the directly-connected
switch via the management bridge (e.g. vmbr0).
"""
lines: list[str] = []
install_out = self._exec_ssh_command(
"DEBIAN_FRONTEND=noninteractive apt-get install -y lldpd 2>&1 | tail -5"
def _install_snmp_agent(self) -> dict:
return self._step(
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp", "net-snmp installed"
)
lines.append(f"[install] {install_out.strip()[-200:]}")
enable_out = self._exec_ssh_command(
"systemctl enable --now lldpd 2>&1 || service lldpd start 2>&1 || true"
def _write_snmp_agent_config(self, settings: dict) -> dict:
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)}")
def _start_snmp_agent(self) -> dict:
return self._step(
"systemctl enable snmpd && systemctl restart snmpd && systemctl is-active snmpd",
"snmpd enabled and running",
)
lines.append(f"[service] {enable_out.strip()[-200:]}")
verify = self._exec_ssh_command("command -v lldpd 2>/dev/null").strip()
success = bool(verify)
if success:
lines.append("[ok] lldpd installed. Neighbors will appear after a short warm-up period.")
else:
lines.append("[warn] lldpd does not appear to be installed after the attempt.")
return {"success": success, "output": "\n".join(lines)}
def _action_fix_snmp(self) -> dict:
"""Install, configure and start snmpd on the Proxmox node.
Proxmox runs Debian/Linux underneath. _exec_ssh_command runs as root
(either via Proxmox API execute endpoint or SSH with root credentials),
so no sudo is needed.
"""
import base64 as _b64
lines: list[str] = []
# 1. Install snmpd and snmp client tools
install_out = self._exec_ssh_command(
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1 | tail -5"
)
lines.append(f"[install] {install_out.strip()[-200:]}")
# 2. Detect the IP this connection comes from (for firewall rule)
netork_ip = ""
try:
raw = self._exec_ssh_command(
"ss -tnp 2>/dev/null | awk '/sshd/{print $5}' | head -1 | cut -d: -f1"
).strip()
if raw and raw not in ("", "0.0.0.0", "::", "127.0.0.1"):
netork_ip = raw
except Exception as exc:
logger.debug("Failed to detect network origin IP: %s", exc)
# 3. Write snmpd.conf via /tmp (no permission issues)
conf_str = (
"agentAddress udp:161\n"
"rocommunity public\n"
"sysLocation Managed by netOrk\n"
"sysContact netork@localhost\n"
)
conf_b64 = _b64.b64encode(conf_str.encode()).decode()
self._exec_ssh_command(f"echo {conf_b64} | base64 -d > /tmp/netork_snmpd.conf")
self._exec_ssh_command(
"mv /tmp/netork_snmpd.conf /etc/snmp/snmpd.conf && "
"chown root:root /etc/snmp/snmpd.conf && chmod 644 /etc/snmp/snmpd.conf"
)
verify = self._exec_ssh_command("cat /etc/snmp/snmpd.conf 2>/dev/null").strip()
if "agentAddress" in verify and "rocommunity" in verify:
lines.append("[config] Wrote /etc/snmp/snmpd.conf - agentAddress udp:161, rocommunity public.")
else:
lines.append(f"[warn] snmpd.conf write may have failed: {verify[:100]}")
# 4. Open firewall if ufw is present
if netork_ip:
try:
ufw = self._exec_ssh_command("command -v ufw 2>/dev/null").strip()
if ufw:
parts = netork_ip.rsplit(".", 1)
subnet = f"{parts[0]}.0/24" if len(parts) == 2 else netork_ip
fw_out = self._exec_ssh_command(
f"ufw allow from {subnet} to any port 161 proto udp 2>&1"
)
lines.append(f"[firewall/ufw] {fw_out.strip()[:200]}")
except Exception as exc:
lines.append(f"[firewall] skipped - {exc}")
# 5. Stop and restart snmpd cleanly (no DBus needed for stop+start)
self._exec_ssh_command(
"service snmpd stop 2>/dev/null; pkill -9 snmpd 2>/dev/null; true"
)
import time as _time
_time.sleep(1)
start_out = self._exec_ssh_command(
"service snmpd start 2>&1 || systemctl start snmpd 2>&1 || true"
)
lines.append(f"[service] {start_out.strip()[-200:]}")
# 6. Verify via local probe
_time.sleep(2)
probe_out = self._exec_ssh_command(
"snmpget -v2c -cpublic -t2 -r0 -Ov 127.0.0.1 1.3.6.1.2.1.1.1.0 2>&1 || true"
).strip()
_snmp_types = ("STRING:", "INTEGER:", "OID:", "Timeticks:", "Hex-STRING:", "IpAddress:")
success = any(t in probe_out for t in _snmp_types)
if success:
lines.append("[ok] SNMP probe successful - community 'public' is working.")
else:
lines.append(f"[warn] SNMP probe failed - output: {probe_out[:200]}")
return {"success": success, "output": "\n".join(lines)}
# ------------------------------------------------------------------ #
# set_hostname
# ------------------------------------------------------------------ #
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.
@@ -612,16 +416,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
@@ -631,9 +435,11 @@ class ProxmoxSystemMixin:
fqdn = new_hostname
# Derive old short hostname for substitution in /etc/hosts
old_short = self._exec_ssh_command(
"cat /etc/hostname 2>/dev/null || hostname -s 2>/dev/null"
).strip().split(".")[0]
old_short = (
self._exec_ssh_command("cat /etc/hostname 2>/dev/null || hostname -s 2>/dev/null")
.strip()
.split(".")[0]
)
# ── 1. /etc/hostname ─────────────────────────────────────────────
hostname_b64 = _b64.b64encode(f"{short_hostname}\n".encode()).decode()
@@ -644,16 +450,7 @@ 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"
@@ -664,16 +461,12 @@ class ProxmoxSystemMixin:
# ── 3. /etc/mailname ─────────────────────────────────────────────
mailname_b64 = _b64.b64encode(f"{fqdn}\n".encode()).decode()
self._exec_ssh_command(
f"[ -f /etc/mailname ]"
f" && echo {mailname_b64} | base64 -d > /etc/mailname"
f" || true"
f"[ -f /etc/mailname ] && echo {mailname_b64} | base64 -d > /etc/mailname || true"
)
# ── 4. Postfix myhostname ─────────────────────────────────────────
self._exec_ssh_command(
f"command -v postconf >/dev/null 2>&1"
f" && postconf -e 'myhostname = {fqdn}'"
f" || true"
f"command -v postconf >/dev/null 2>&1 && postconf -e 'myhostname = {fqdn}' || true"
)
# ── 5. Apply hostname at runtime ─────────────────────────────────
@@ -716,7 +509,9 @@ class ProxmoxSystemMixin:
logger.info(
"Proxmox set_hostname: %s → %s (fqdn: %s). "
"Reboot required for node name to update in web UI / cluster.",
old_short, short_hostname, fqdn,
old_short,
short_hostname,
fqdn,
)
# ------------------------------------------------------------------ #
@@ -753,12 +548,12 @@ class ProxmoxSystemMixin:
if not dev:
continue
entry: dict = {
"model": disk.get("model", ""),
"serial": disk.get("serial", ""),
"type": disk.get("type", ""),
"size": disk.get("size", 0),
"health": disk.get("health", "unknown").lower(),
"wearout": disk.get("wearout"), # NVMe wear indicator 0-100
"model": disk.get("model", ""),
"serial": disk.get("serial", ""),
"type": disk.get("type", ""),
"size": disk.get("size", 0),
"health": disk.get("health", "unknown").lower(),
"wearout": disk.get("wearout"), # NVMe wear indicator 0-100
"temperature": None,
"percentage_used": None,
"available_spare": None,
@@ -789,7 +584,7 @@ class ProxmoxSystemMixin:
# HDD-specific SMART attributes
for attr in smart.get("attributes", []):
name = attr.get("name", "").lower()
raw = attr.get("raw", "")
raw = attr.get("raw", "")
try:
raw_int = int(str(raw).split()[0])
except (ValueError, TypeError):
@@ -827,7 +622,8 @@ class ProxmoxSystemMixin:
"timezone": None,
"ntp_servers": [],
"ssh_port": 22,
"ssh_password_auth": False,
# A flag, not a password.
"ssh_password_auth": False, # nosec B105
}
# Cluster name and node list from /cluster/status
+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]
+9 -1
View File
@@ -14,7 +14,6 @@ from typing import Any
from netaddr import EUI, AddrFormatError
# ---------------------------------------------------------------------------
# MAC address helpers
# ---------------------------------------------------------------------------
@@ -47,6 +46,7 @@ def normalize_mac(mac: str) -> str:
# IP / prefix helpers
# ---------------------------------------------------------------------------
def prefix_length(cidr: str) -> int:
"""Return prefix length from a CIDR string such as '192.168.1.0/24' → 24."""
try:
@@ -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))
@@ -141,6 +147,7 @@ def speed_mbps(iface_data: dict[str, Any]) -> float:
# ARP / neighbour table helpers
# ---------------------------------------------------------------------------
def parse_arp_output(raw: str) -> list[dict[str, Any]]:
"""Parse Linux ``arp -n`` text output into NAPALM ARP dicts.
@@ -202,6 +209,7 @@ def sdn_zone_to_network_instance(zone: dict[str, Any]) -> dict[str, Any]:
# OVS helpers
# ---------------------------------------------------------------------------
def parse_ovs_vsctl_show(raw: str) -> dict[str, Any]:
"""Very lightweight parser for ``ovs-vsctl show`` output.
+11 -8
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
@@ -162,6 +164,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:
@@ -184,10 +194,3 @@ class ProxmoxVMContractMixin:
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
+255
View File
@@ -0,0 +1,255 @@
"""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``: PVE has no REST endpoint for it; it runs
``ha-manager crm-command node-maintenance`` over the driver's SSH session.
The HA manager moves the node's HA guests away after the command 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 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
# -- 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 SSH (no REST endpoint)."""
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"
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
+55 -52
View File
@@ -20,8 +20,6 @@ import logging
import re
from typing import Any
from napalm_proxmox import utils
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
@@ -30,9 +28,7 @@ _JsonDict = dict[str, Any]
class ProxmoxVMMixin:
"""Mixin providing VM and container NAPALM methods."""
def get_vm_interfaces(
self, vmid: int, vm_type: str
) -> tuple[dict[str, _JsonDict], bool, bool]:
def get_vm_interfaces(self, vmid: int, vm_type: str) -> tuple[dict[str, _JsonDict], bool, bool]:
"""Return network interfaces for a single VM or LXC container.
Returns a 3-tuple ``(interfaces, agent_running, agent_enabled)``:
@@ -105,7 +101,7 @@ class ProxmoxVMMixin:
logger.debug("get_vm_interfaces: LXC %s config failed: %s", vmid, exc)
try:
for iface in (self._node_api().lxc(vmid).interfaces.get() or []):
for iface in self._node_api().lxc(vmid).interfaces.get() or []:
name = iface.get("name", "")
if not name or name == "lo":
continue
@@ -233,7 +229,7 @@ class ProxmoxVMMixin:
# QEMU VMs
try:
for vm in (self._node_api().qemu.get() or []):
for vm in self._node_api().qemu.get() or []:
vmid = int(vm.get("vmid", 0))
name = vm.get("name", f"vm-{vmid}")
status = vm.get("status", "unknown")
@@ -256,30 +252,32 @@ class ProxmoxVMMixin:
)
disks, onboot = self._get_vm_disk_and_boot(vmid, "qemu")
result.append({
"vmid": str(vmid),
"name": name,
"type": "vm",
"status": status,
"vcpus": vcpus,
"memory": memory_mb,
"cpu_usage": round(cpu_usage, 4),
"memory_usage": memory_usage_mb,
"uptime": uptime,
"node": self._node_name,
"interfaces": interfaces,
"ipv4": ipv4,
"agent_enabled": agent_enabled,
"agent_running": agent_running,
"disks": disks,
"onboot": onboot,
})
result.append(
{
"vmid": str(vmid),
"name": name,
"type": "vm",
"status": status,
"vcpus": vcpus,
"memory": memory_mb,
"cpu_usage": round(cpu_usage, 4),
"memory_usage": memory_usage_mb,
"uptime": uptime,
"node": self._node_name,
"interfaces": interfaces,
"ipv4": ipv4,
"agent_enabled": agent_enabled,
"agent_running": agent_running,
"disks": disks,
"onboot": onboot,
}
)
except Exception as exc:
logger.warning("get_vms: failed to list QEMU VMs: %s", exc)
# LXC containers
try:
for ct in (self._node_api().lxc.get() or []):
for ct in self._node_api().lxc.get() or []:
vmid = int(ct.get("vmid", 0))
name = ct.get("name", f"ct-{vmid}")
status = ct.get("status", "unknown")
@@ -300,24 +298,26 @@ class ProxmoxVMMixin:
)
disks, onboot = self._get_vm_disk_and_boot(vmid, "lxc")
result.append({
"vmid": str(vmid),
"name": name,
"type": "container",
"status": status,
"vcpus": vcpus,
"memory": memory_mb,
"cpu_usage": round(cpu_usage, 4),
"memory_usage": memory_usage_mb,
"uptime": uptime,
"node": self._node_name,
"interfaces": interfaces,
"ipv4": ipv4,
"agent_enabled": agent_enabled,
"agent_running": agent_running,
"disks": disks,
"onboot": onboot,
})
result.append(
{
"vmid": str(vmid),
"name": name,
"type": "container",
"status": status,
"vcpus": vcpus,
"memory": memory_mb,
"cpu_usage": round(cpu_usage, 4),
"memory_usage": memory_usage_mb,
"uptime": uptime,
"node": self._node_name,
"interfaces": interfaces,
"ipv4": ipv4,
"agent_enabled": agent_enabled,
"agent_running": agent_running,
"disks": disks,
"onboot": onboot,
}
)
except Exception as exc:
logger.warning("get_vms: failed to list LXC containers: %s", exc)
@@ -328,9 +328,7 @@ class ProxmoxVMMixin:
# Disk-key prefix for LXC: rootfs, mp (mount points)
_DISK_KEYS_CT = re.compile(r"^(rootfs|mp\d+)$")
def _get_vm_disk_and_boot(
self, vmid: int, vm_type: str
) -> tuple[list[dict], bool]:
def _get_vm_disk_and_boot(self, vmid: int, vm_type: str) -> tuple[list[dict], bool]:
"""Return (disks, onboot) for a VM or container.
Fetches config from /nodes/{node}/{qemu|lxc}/{vmid}/config.
@@ -376,8 +374,8 @@ class ProxmoxVMMixin:
logger.debug("Failed to fetch disk/boot config for vmid %s: %s", vmid, exc)
return [], False
_POWER_ACTIONS_VM = {'start', 'stop', 'shutdown', 'reboot', 'reset'}
_POWER_ACTIONS_CT = {'start', 'stop', 'shutdown', 'reboot'}
_POWER_ACTIONS_VM = {"start", "stop", "shutdown", "reboot", "reset"}
_POWER_ACTIONS_CT = {"start", "stop", "shutdown", "reboot"}
def power_vm(self, vmid: int, vm_type: str, action: str) -> dict:
"""Send a power action to a VM or container on this node.
@@ -385,11 +383,16 @@ class ProxmoxVMMixin:
Supported actions for VMs: start, stop, shutdown, reboot, reset
Supported actions for containers: start, stop, shutdown, reboot
"""
allowed = self._POWER_ACTIONS_VM if vm_type == 'vm' else self._POWER_ACTIONS_CT
allowed = self._POWER_ACTIONS_VM if vm_type == "vm" else self._POWER_ACTIONS_CT
if action not in allowed:
return {"success": False, "error": f"Action '{action}' not supported for {vm_type} (allowed: {sorted(allowed)})"}
return {
"success": False,
"error": (
f"Action '{action}' not supported for {vm_type} (allowed: {sorted(allowed)})"
),
}
try:
vm_api = self._node_api().qemu(vmid) if vm_type == 'vm' else self._node_api().lxc(vmid)
vm_api = self._node_api().qemu(vmid) if vm_type == "vm" else self._node_api().lxc(vmid)
task_id = getattr(vm_api.status, action).post()
return {"success": True, "task_id": task_id or ""}
except Exception as exc:
+146 -181
View File
@@ -3,12 +3,12 @@
from __future__ import annotations
import base64
import hashlib
import ipaddress
import logging
import re
import shlex
import time
from typing import TYPE_CHECKING, Any, Dict, List
from typing import TYPE_CHECKING, Any
from urllib.parse import quote
import yaml
@@ -21,10 +21,15 @@ 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
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 +82,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 +91,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,36 +132,12 @@ 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.
"""
import paramiko
if self._ssh_client is None:
ssh_user = self._ssh_username or self.username
ssh_pass = self._ssh_password or self.password
ssh_pkey = None
if self._ssh_key and not ssh_pass:
from io import StringIO as _StringIO
ssh_pkey = paramiko.RSAKey.from_private_key(_StringIO(self._ssh_key))
self._ssh_client = paramiko.SSHClient()
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
connect_kwargs: Dict[str, Any] = {
"hostname": self.hostname,
"port": 22,
"username": ssh_user,
"timeout": self.timeout,
}
if ssh_pkey:
connect_kwargs["pkey"] = ssh_pkey
else:
connect_kwargs["password"] = ssh_pass
self._ssh_client.connect(**connect_kwargs)
_, stdout, stderr = self._ssh_client.exec_command(command, timeout=timeout)
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=timeout)
exit_status = stdout.channel.recv_exit_status()
out = stdout.read().decode().strip()
err = stderr.read().decode().strip()
@@ -194,38 +164,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}"
@@ -237,6 +195,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.
@@ -245,22 +227,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
@@ -272,16 +251,21 @@ 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,
)
def _nic_macs(self, vmid: int, nics: List[Dict[str, Any]]) -> list[tuple[str, bool]]:
def _nic_macs(self, vmid: int, nics: list[dict[str, Any]]) -> list[tuple[str, bool]]:
"""``(mac, dhcp)`` per NIC, with the MAC Proxmox assigned where none was given."""
config = self._node_api().qemu(vmid).config.get()
macs = []
@@ -332,7 +316,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}")
@@ -357,7 +341,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,
)
@@ -389,7 +374,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
@@ -453,9 +438,9 @@ class ProxmoxVMProvisionMixin:
)
return path
def get_image_storages(self) -> List[StorageTargetDict]:
def get_image_storages(self) -> list[StorageTargetDict]:
"""List node-available storage pools suitable for a new VM's root disk."""
targets: List[StorageTargetDict] = []
targets: list[StorageTargetDict] = []
for storage in self._node_api().storage.get():
content = storage.get("content", "")
if "images" not in content or storage.get("enabled", 1) == 0:
@@ -479,8 +464,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]:
@@ -555,6 +539,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,
@@ -562,14 +559,15 @@ class ProxmoxVMProvisionMixin:
image_url: str,
cpu: int,
memory: int,
nics: List[Dict[str, Any]],
cloud_init_config: Dict[str, Any],
nics: list[dict[str, Any]],
cloud_init_config: dict[str, Any],
image_checksum: str | None = None,
ssh_public_keys: List[str] | None = None,
ssh_public_keys: list[str] | None = None,
disk_resize_gb: int | None = None,
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:
@@ -607,6 +605,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
@@ -614,16 +615,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)
@@ -647,6 +650,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()
@@ -656,29 +660,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
@@ -745,9 +727,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)
@@ -786,7 +768,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,
@@ -828,16 +813,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)
@@ -854,6 +830,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.
@@ -963,44 +954,18 @@ class ProxmoxVMProvisionMixin:
raise
except Exception as e:
_logger.exception(f"Error getting status for VM {vmid}: {e}")
raise RuntimeError(f"Failed to get VM {vmid} status: {e}")
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
def get_network_targets(self) -> List[NetworkTargetDict]:
def get_network_targets(self) -> list[NetworkTargetDict]:
"""
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
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
+54 -26
View File
@@ -1,66 +1,94 @@
[build-system]
requires = ["setuptools>=61", "wheel"]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "napalm-proxmox"
version = "0.1.0"
description = "NAPALM driver for Proxmox VE (classic Linux networking, SDN, OVS)"
version = "0.10.0"
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
readme = "README.md"
license = { text = "Apache-2.0" }
license = "Apache-2.0"
authors = [{ name = "Christian Manivong" }]
keywords = ["napalm", "proxmox", "network", "sdn", "ovs", "automation"]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: System :: Networking",
]
requires-python = ">=3.9"
requires-python = ">=3.12"
dependencies = [
"napalm>=5.0.0",
"napalm_device_types>=3.0.0",
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for SSH fallback (driver.py)
"napalm_device_types>=4.25.0", # BackupServerDriver
"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",
]
[project.optional-dependencies]
dev = [
"pytest>=7.4",
"pytest-cov>=4.1",
"pytest-mock>=3.12",
"responses>=0.24",
"ruff>=0.1",
"mypy>=1.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"
Issues = "https://git.netork.io/NAPALM/napalm-proxmox/issues"
Changelog = "https://git.netork.io/NAPALM/napalm-proxmox/src/branch/main/CHANGELOG.md"
[tool.setuptools.packages.find]
where = ["."]
include = ["napalm_proxmox*"]
[tool.setuptools.package-data]
napalm_proxmox = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py39"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP"]
select = ["E", "F", "I", "UP", "B"]
[tool.ruff.lint.per-file-ignores]
# Recorded device output keeps its lines.
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
[[tool.mypy.overrides]]
module = ["napalm.*", "proxmoxer.*", "paramiko.*", "netaddr.*", "yaml.*"]
ignore_missing_imports = true
[[tool.mypy.overrides]]
# Not yet under strict mypy (quality baseline); may only shrink.
module = [
"napalm_proxmox.config_mixin",
"napalm_proxmox.driver",
"napalm_proxmox.interfaces_mixin",
"napalm_proxmox.routing_mixin",
"napalm_proxmox.sdn_mixin",
"napalm_proxmox.system_mixin",
"napalm_proxmox.utils",
"napalm_proxmox.vm_contract_mixin",
"napalm_proxmox.vm_mixin",
"napalm_proxmox.vm_provision_mixin",
]
ignore_errors = true
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=napalm_proxmox --cov-report=term-missing"
[tool.mypy]
python_version = "3.9"
warn_return_any = true
warn_unused_configs = true
[tool.coverage.run]
source = ["napalm_proxmox"]
[tool.coverage.report]
fail_under = 68
+37 -6
View File
@@ -2,11 +2,11 @@
from __future__ import annotations
import pytest
from unittest.mock import MagicMock, patch
from napalm_proxmox.driver import ProxmoxDriver
import pytest
from napalm_proxmox.driver import ProxmoxDriver
# ---------------------------------------------------------------------------
# Sample API payloads
@@ -120,10 +120,41 @@ 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
# ---------------------------------------------------------------------------
def _build_mock_api(
nodes=None,
node_status=None,
@@ -136,7 +167,6 @@ def _build_mock_api(
ntp=None,
netstat=None,
pve_users=None,
exec_return="",
sensors=None,
cluster_status=None,
):
@@ -158,7 +188,6 @@ def _build_mock_api(
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 = {}
@@ -203,12 +232,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",
@@ -216,7 +246,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
+96
View File
@@ -0,0 +1,96 @@
"""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)
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")
+56
View File
@@ -0,0 +1,56 @@
{
"coverage_floor": 68.0,
"function_complexity": {
"napalm_proxmox/driver.py::ProxmoxDriver._resolve_node": 13,
"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,
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.ping": 12,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._find_switch_uplink": 13,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._get_ovs_bridge_for_port": 13,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._get_vm_vlan_tags": 11,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._is_cluster_master": 13,
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_network_instances": 13,
"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/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": 18,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
},
"function_lines": {
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
"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.set_hostname": 114,
"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.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": 92
},
"mypy_relaxed": [
"napalm_proxmox.config_mixin",
"napalm_proxmox.driver",
"napalm_proxmox.interfaces_mixin",
"napalm_proxmox.routing_mixin",
"napalm_proxmox.sdn_mixin",
"napalm_proxmox.system_mixin",
"napalm_proxmox.utils",
"napalm_proxmox.vm_contract_mixin",
"napalm_proxmox.vm_mixin",
"napalm_proxmox.vm_provision_mixin"
],
"python_file_lines": {},
"untyped_public": [
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan",
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_snmp_config"
]
}
+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"] == []
+566
View File
@@ -0,0 +1,566 @@
"""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"]
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"]
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"]
+6 -9
View File
@@ -2,12 +2,13 @@
from __future__ import annotations
import pytest
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import _build_mock_api, NODES_LIST
from tests.conftest import _build_mock_api
class TestOpen:
@@ -101,9 +102,7 @@ def _open_with(hostname, **api_kwargs):
class TestClusterNodeResolution:
def test_local_node_wins_over_first_listed(self):
drv = _open_with(
"172.22.8.120", nodes=CLUSTER_NODES_LIST, cluster_status=CLUSTER_STATUS
)
drv = _open_with("172.22.8.120", nodes=CLUSTER_NODES_LIST, cluster_status=CLUSTER_STATUS)
assert drv._node_name == "pve-dual"
def test_matches_by_ip_without_local_flag(self):
@@ -118,9 +117,7 @@ class TestClusterNodeResolution:
def test_matches_short_name_of_fqdn(self):
status = [{**n, "local": 0} for n in CLUSTER_STATUS if n["type"] == "node"]
drv = _open_with(
"pve-01.mgmt.example.com", nodes=CLUSTER_NODES_LIST, cluster_status=status
)
drv = _open_with("pve-01.mgmt.example.com", nodes=CLUSTER_NODES_LIST, cluster_status=status)
assert drv._node_name == "pve-01"
def test_single_node_without_cluster_status(self):
+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
+3 -8
View File
@@ -2,11 +2,12 @@
from __future__ import annotations
import pytest
from tests.conftest import _build_mock_api, NODE_STATUS
from unittest.mock import patch
import pytest
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import _build_mock_api
class TestGetEnvironment:
@@ -25,9 +26,6 @@ class TestGetEnvironment:
assert isinstance(result["fans"], dict)
def test_temperature_with_sensors(self):
from tests.conftest import _build_mock_api, NODE_STATUS
from unittest.mock import patch
from napalm_proxmox.driver import ProxmoxDriver
sensors_data = [
{"name": "CPU Package", "value": "55.0"},
@@ -49,9 +47,6 @@ class TestGetEnvironment:
assert result["temperature"]["GPU Core"]["is_critical"] is False
def test_temperature_critical(self):
from tests.conftest import _build_mock_api
from unittest.mock import patch
from napalm_proxmox.driver import ProxmoxDriver
sensors_data = [{"name": "NVMe", "value": "98.0"}]
mock_api = _build_mock_api(sensors=sensors_data)
+226
View File
@@ -0,0 +1,226 @@
"""The fixes as napalm-device-types templates, with the caller's values (netOrk #1105).
``fix_snmp`` wrote an application's snmpd.conf (community "public", "Managed by
netOrk") and opened ufw for the caller's /24 guessed from ``ss``;
``install_lldpd`` was an action of its own. Now ``configure_snmp_agent(settings)``
takes every value from the caller, and ``ensure_package`` installs through the
contract's ``install_package``. Every step reads its exit status.
"""
from __future__ import annotations
import re
import subprocess
import pytest
from napalm_proxmox import ProxmoxDriver
SETTINGS = {"community": "c0mm", "allowed_sources": ["10.7.224.20"], "location": "rack 1"}
class _Node:
"""The node's shell: answers by command fragment, with an exit status."""
def __init__(self, **status):
self.status = status # fragment -> exit status
self.ran: list[str] = []
def __call__(self, command: str) -> str:
self.ran.append(command)
if "SSH_CONNECTION" in command:
return "10.7.224.20 51234 10.0.0.9 22\n"
if command.startswith("dpkg-query"):
return "curl\tinstalled\n"
rc = next((code for frag, code in self.status.items() if frag in command), 0)
out = "ok" if rc == 0 else "E: failed"
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()
@pytest.fixture
def driver(node):
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = node
return d
class TestSnmpAgent:
def test_install_write_open_start_with_the_callers_values(self, driver, node):
result = driver.configure_snmp_agent(SETTINGS)
assert result["success"] is True
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
assert any("apt-get install -y snmpd snmp" in c for c in node.ran)
write = next(c for c in node.ran if "/etc/snmp/snmpd.conf" in c)
assert "install -m 644" in write
b64 = re.search(r"echo ([A-Za-z0-9+/=]+) \| base64 -d", write).group(1)
import base64
conf = base64.b64decode(b64).decode()
assert "rocommunity c0mm 10.7.224.20/32" in conf
assert "sysLocation rack 1" in conf
assert "public" not in conf and "netork" not in conf.lower()
assert any("systemctl restart snmpd" in c for c in node.ran)
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)
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
node.status["command -v ufw"] = 0
driver.configure_snmp_agent(SETTINGS)
assert any("ufw allow from 10.7.224.20/32 to any port 161 proto udp" in c for c in node.ran)
assert not any(".0/24" in c for c in node.ran)
def test_a_failed_install_stops_the_fix(self, driver, node):
node.status["apt-get install -y snmpd"] = 100
result = driver.configure_snmp_agent(SETTINGS)
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"
class TestPackages:
def test_ensure_package_installs_what_is_missing(self, driver, node):
result = driver.ensure_package("lldpd")
assert result["success"] is True
assert any("apt-get install -y lldpd" in c for c in node.ran)
def test_ensure_package_leaves_alone_what_is_there(self, driver, node):
assert driver.ensure_package("curl")["success"] is True
assert not any("apt-get install" in c for c in node.ran)
def test_install_package_raises_when_apt_fails(self, driver, node):
node.status["apt-get install -y lldpd"] = 100
with pytest.raises(RuntimeError, match="lldpd"):
driver.install_package("lldpd")
def test_a_name_that_is_no_package_name_is_refused(self, driver):
with pytest.raises(ValueError):
driver.install_package("lldpd; reboot")
def test_the_old_actions_are_gone():
for name in ("run_device_action", "_action_fix_snmp", "_action_install_lldpd"):
assert not hasattr(ProxmoxDriver, name), name
_APT_REPORT = (
"APROXY_BEGIN\n[dump]\n{dump}[parts]\n{parts}[main]\n[sources]\n"
"http://download.proxmox.com/debian/pve/dists/trixie/\nAPROXY_END\n"
)
class _AptNode(_Node):
"""A node that answers apt's proxy report and a fetch."""
def __init__(self, proxy="", parts=""):
super().__init__()
self.proxy = proxy
self.parts = parts
def __call__(self, command: str) -> str:
if "apt-config dump" in command:
self.ran.append(command)
dump = f'Acquire::http::Proxy "{self.proxy}";\n' if self.proxy else ""
return _APT_REPORT.format(dump=dump, parts=self.parts)
if "apt-helper" in command:
self.ran.append(command)
return "APROXY_BEGIN\n[fetch]\nGet:1 x\n[rc]\n0\n[match]\n2\nAPROXY_END\n"
return super().__call__(command)
class TestPackageProxy:
"""Proxmox VE is Debian: apt's proxy is set and read as on any Debian host (netOrk #1397)."""
def test_it_takes_the_fix(self):
assert callable(getattr(ProxmoxDriver, "configure_package_proxy", None))
def test_the_fact(self):
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = _AptNode(proxy="http://c:3142")
assert d.get_package_proxy() == "http://c:3142"
def test_written_as_root_read_back_and_fetched_through(self):
node = _AptNode(proxy="http://c:3142")
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = node
result = d.configure_package_proxy("http://c:3142")
assert result["success"] is True, result["output"]
write = next(c for c in node.ran if "/etc/apt/apt.conf.d/00proxy" in c)
assert "install -m 644" in write
b64 = re.search(r"echo ([A-Za-z0-9+/=]+) \| base64 -d", write).group(1)
import base64
assert base64.b64decode(b64).decode() == 'Acquire::http::Proxy "http://c:3142";\n'
assert any("dists/trixie/InRelease" in c for c in node.ran)
def test_another_proxy_is_commented_out(self):
node = _AptNode(
proxy="http://c:3142",
parts='/etc/apt/apt.conf.d/90curtin-aptproxy:1:Acquire::http::Proxy "http://old:3128";\n',
)
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = node
d.configure_package_proxy("http://c:3142")
assert any(c.startswith("{ sed -i -e '1{") for c in node.ran)
def test_the_proxy_answers(self):
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = _AptNode()
result = d.check_package_proxy("http://c:3142/acng-report.html", expect="Cache")
assert result == {"reachable": True, "expected": True, "error": ""}
+1 -3
View File
@@ -3,10 +3,8 @@
from __future__ import annotations
import pytest
from tests.conftest import _build_mock_api, NODE_NETWORK
from unittest.mock import patch
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import NODE_NETWORK
@pytest.fixture
+13 -9
View File
@@ -2,11 +2,7 @@
from __future__ import annotations
import pytest
from tests.conftest import _build_mock_api, NODE_NETWORK
from unittest.mock import patch
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import NODE_NETWORK
class TestGetInterfaces:
@@ -89,10 +85,18 @@ class TestGetInterfacesCounters:
result = driver.get_interfaces_counters()
eth0 = result["eth0"]
for field in (
"tx_errors", "rx_errors", "tx_discards", "rx_discards",
"tx_octets", "rx_octets", "tx_unicast_packets", "rx_unicast_packets",
"tx_multicast_packets", "rx_multicast_packets",
"tx_broadcast_packets", "rx_broadcast_packets",
"tx_errors",
"rx_errors",
"tx_discards",
"rx_discards",
"tx_octets",
"rx_octets",
"tx_unicast_packets",
"rx_unicast_packets",
"tx_multicast_packets",
"rx_multicast_packets",
"tx_broadcast_packets",
"rx_broadcast_packets",
):
assert field in eth0, f"Missing field: {field}"
+1 -1
View File
@@ -12,9 +12,9 @@ import gzip
from unittest.mock import patch
import pytest
from napalm_device_types import KernelFactsMixin
from napalm_device_types.kernel import KERNEL_FACTS_COMMAND
from napalm_proxmox.driver import ProxmoxDriver
REPORT = (
+65
View File
@@ -0,0 +1,65 @@
"""The node's subscription as a fact (netOrk #1111).
The driver named ``no_subscription`` itself, comparing against "NotFound" while
the API answers "notfound" -- so it never fired. It reports the subscription
now; whether a missing one is a warning is the caller's decision.
"""
from __future__ import annotations
import pytest
from napalm_proxmox import ProxmoxDriver
def _driver(subscription: dict) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
d._get_node_subscription = lambda: subscription
return d
@pytest.mark.parametrize(
"raw, status",
[
("notfound", "none"),
("NotFound", "none"),
("active", "active"),
("invalid", "invalid"),
("expired", "expired"),
("new", "unknown"),
("suspended", "unknown"),
],
)
def test_the_api_status_as_a_license_status(raw, status):
[lic] = _driver({"status": raw, "message": "There is no subscription key"}).get_licenses()
assert lic["name"] == "pve-subscription"
assert lic["status"] == status
assert lic["detail"] == "There is no subscription key"
def test_level_and_due_date_when_subscribed():
sub = {
"status": "active",
"productname": "Proxmox VE Community Subscription 1 CPU/year",
"nextduedate": "2027-03-01",
}
[lic] = _driver(sub).get_licenses()
assert lic["edition"] == "Proxmox VE Community Subscription 1 CPU/year"
assert lic["expires"] == "2027-03-01"
def test_an_unreadable_subscription_reports_nothing():
"""``_get_node_subscription`` gives {} when the API call fails: no fact, not "none"."""
assert _driver({}).get_licenses() == []
def test_no_warnings_of_its_own():
"""lldpd, the updates and the subscription are facts the caller reads
(get_packages, get_available_updates, get_licenses)."""
assert not any(
"get_device_warnings" in vars(c)
for c in ProxmoxDriver.__mro__[:-1]
if c.__module__.startswith("napalm_proxmox")
)
+1
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
from unittest.mock import patch
from napalm_device_types import ListeningSocketsMixin
from napalm_proxmox.driver import ProxmoxDriver
WIRE = (
+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)()
+79 -64
View File
@@ -2,8 +2,9 @@
from __future__ import annotations
from unittest.mock import patch
import pytest
from unittest.mock import MagicMock, patch
class TestGetNTPServers:
@@ -25,19 +26,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 == []
@@ -52,7 +53,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"
@@ -60,39 +61,39 @@ 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():
for _user, data in result.items():
assert "level" in data
assert "password" in data
assert "sshkeys" in data
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
@@ -135,14 +136,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"]
@@ -167,20 +168,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
@@ -194,44 +220,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:
@@ -241,57 +257,49 @@ 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 _prefix, routes in result.items():
for route in routes:
assert "protocol" in route
assert "next_hop" in route
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 _prefix, routes in result.items():
for route in routes:
assert "dhcp" in route["protocol"].lower()
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 == {}
@@ -303,22 +311,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
+6 -11
View File
@@ -2,12 +2,10 @@
from __future__ import annotations
import pytest
from unittest.mock import patch
from napalm_proxmox import utils
PROC_NET_ARP = """\
IP address HW type Flags HW address Mask Device
10.0.0.254 0x1 0x2 aa:bb:cc:dd:ee:ff * eth0
@@ -105,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 == []
@@ -137,10 +135,7 @@ class TestGetMACAddressTable:
"cc:dd:ee:ff:00:11 dev eth0 vlan 20 master vmbr0\n"
)
OVS_APPCTL = (
" LOCAL 0 aa:bb:cc:dd:ee:03 0\n"
" 1 10 11:22:33:44:55:66 100\n"
)
OVS_APPCTL = " LOCAL 0 aa:bb:cc:dd:ee:03 0\n 1 10 11:22:33:44:55:66 100\n"
def test_linux_bridge_entries(self, driver):
def _exec(cmd):
+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
+2 -3
View File
@@ -2,8 +2,7 @@
from __future__ import annotations
import pytest
from tests.conftest import _build_mock_api, SDN_ZONES, SDN_VNETS
from tests.conftest import _build_mock_api
class TestGetVlans:
@@ -52,8 +51,8 @@ class TestGetVlans:
def test_empty_sdn_returns_dict(self):
from unittest.mock import patch
from napalm_proxmox.driver import ProxmoxDriver
from tests.conftest import _build_mock_api
mock_api = _build_mock_api(sdn_vnets=[], sdn_zones=[])
drv = ProxmoxDriver("pve1", "root", "secret", optional_args={"verify_ssl": False})
+43
View File
@@ -0,0 +1,43 @@
"""`get_service_packages`: which installed packages each systemd unit of the node is.
The node's own services -- pveproxy, corosync, ceph -- are where a decision
about a service lands on a hypervisor (NetOrk/netork#1236). The command and its
parse are napalm-device-types'; the driver only carries the command over its
exec path.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from napalm_device_types import ServicePackagesMixin
from napalm_device_types.service_packages import SERVICE_PACKAGES_COMMAND
from napalm_proxmox.driver import ProxmoxDriver
WIRE = (
"SVCPKG_BEGIN\n[units]\nId=pveproxy.service\n"
"FragmentPath=/lib/systemd/system/pveproxy.service\n"
"ExecStart={ path=/usr/bin/pveproxy ; argv[]=/usr/bin/pveproxy start }\n\n"
"[dpkg]\npve-manager: /lib/systemd/system/pveproxy.service\n"
"pve-manager: /usr/bin/pveproxy\nSVCPKG_END"
)
def test_the_driver_declares_the_contract():
assert issubclass(ProxmoxDriver, ServicePackagesMixin)
def test_it_runs_the_shared_command(driver):
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
found = driver.get_service_packages()
exec_.assert_called_once_with(SERVICE_PACKAGES_COMMAND)
assert found == {"pveproxy": ["pve-manager"]}
def test_output_without_a_report_raises(driver):
with patch.object(driver, "_exec_ssh_command", return_value=""):
with pytest.raises(ValueError):
driver.get_service_packages()
+107
View File
@@ -0,0 +1,107 @@
"""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 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 c.rstrip().endswith("chmod 644 /etc/hosts"))
return base64.b64decode(re.match(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] == []
+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")
+134
View File
@@ -0,0 +1,134 @@
"""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 — ``_exec_ssh_command`` and the provisioning
steps' ``_run_node_command`` — share one session, opened on port 22.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import paramiko
import pytest
from napalm_device_types.ssh_host_keys import (
KNOWN_KEYS_ARG,
OBSERVER_ARG,
SshHostKey,
SshHostKeyMismatch,
)
from napalm_proxmox.driver import ProxmoxDriver
SERVER_KEY = paramiko.ECDSAKey.generate()
OTHER_KEY = paramiko.ECDSAKey.generate()
class _Stream:
def __init__(self, data: bytes) -> None:
self._data = data
self.channel = MagicMock()
self.channel.recv_exit_status.return_value = 0
def read(self) -> bytes:
return self._data
class _Client:
"""paramiko.SSHClient as far as the driver uses it; refuses like paramiko would."""
def __init__(self) -> None:
self.lines: list[str] = []
self.policy = None
self.connected_with: dict | None = None
self.commands: list[str] = []
def set_missing_host_key_policy(self, policy) -> None:
self.policy = policy
def get_host_keys(self):
client = self
class _Keys:
def load(self, path: str) -> None:
with open(path) as f:
client.lines += f.read().splitlines()
return _Keys()
def connect(self, hostname, **kwargs) -> None:
if self.lines and SshHostKey.of(SERVER_KEY).key not in self.lines[0]:
raise paramiko.BadHostKeyException(hostname, SERVER_KEY, OTHER_KEY)
if not self.lines:
self.policy.missing_host_key(self, hostname, SERVER_KEY)
self.connected_with = {"hostname": hostname, **kwargs}
def get_transport(self):
transport = MagicMock()
transport.get_remote_server_key.return_value = SERVER_KEY
return transport
def exec_command(self, command, timeout=None):
self.commands.append(command)
return None, _Stream(b"ok"), _Stream(b"")
def close(self) -> None:
pass
@pytest.fixture
def client(monkeypatch) -> _Client:
fake = _Client()
monkeypatch.setattr(paramiko, "SSHClient", lambda: fake)
return fake
def _driver(seen: list, known: dict | None = None) -> ProxmoxDriver:
args: dict = {"port": 8006, OBSERVER_ARG: seen.append}
if known is not None:
args[KNOWN_KEYS_ARG] = known
driver = ProxmoxDriver("10.0.0.9", "root", "s3cret", optional_args=args)
return driver
def test_first_use_runs_the_command_and_reports_the_key(client):
seen: list = []
assert _driver(seen)._run_node_command("true", timeout=5) == "ok"
assert client.connected_with["port"] == 22
assert seen[0]["accepted"] is True
assert (seen[0]["host"], seen[0]["port"]) == ("10.0.0.9", 22)
def test_the_key_for_the_api_port_is_not_the_ssh_one(client):
seen: list = []
other = SshHostKey.of(OTHER_KEY).as_dict()
_driver(seen, {"8006": other})._run_node_command("true", timeout=5)
assert seen[0]["expected"] is None
def test_a_changed_key_stops_a_provisioning_step(client):
seen: list = []
driver = _driver(seen, {"22": SshHostKey.of(OTHER_KEY).as_dict()})
with pytest.raises(SshHostKeyMismatch):
driver._run_node_command("qm importdisk …", timeout=5)
assert client.commands == []
assert client.connected_with is None
assert seen[0]["accepted"] is False
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()})
with pytest.raises(SshHostKeyMismatch):
driver._exec_ssh_command("cat /etc/os-release")
assert client.commands == []
assert seen[0]["accepted"] is False
def test_the_known_key_reuses_one_session(client):
seen: list = []
driver = _driver(seen, {"22": SshHostKey.of(SERVER_KEY).as_dict()})
driver._exec_ssh_command("uptime")
driver._run_node_command("true", timeout=5)
assert client.commands == ["uptime", "true"]
assert len(seen) == 1 and seen[0]["accepted"] is True
+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"}})
+32
View File
@@ -0,0 +1,32 @@
"""`get_system_identity`: the node's SMBIOS identity, what ties it to its BMC.
The command, its parse and the placeholder filter are napalm-device-types'; the driver
only carries the command over its exec path, which runs as root.
"""
from __future__ import annotations
from unittest.mock import patch
from napalm_device_types import SYSTEM_IDENTITY_COMMAND, SystemIdentityMixin
from napalm_proxmox.driver import ProxmoxDriver
# pve-dual, a Supermicro X10DRL-i: the product serial is the board vendor's default.
WIRE = "IDBEGIN\n31303043-534D-C40C-7A72-6F1300000000\n0123456789\nZM155S026022\nIDEND\n"
def test_the_driver_declares_the_contract():
assert issubclass(ProxmoxDriver, SystemIdentityMixin)
def test_it_runs_the_shared_command(driver):
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
identity = driver.get_system_identity()
exec_.assert_called_once_with(SYSTEM_IDENTITY_COMMAND)
assert identity == {
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
"product_serial": "",
"board_serial": "ZM155S026022",
}
+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
-1
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import pytest
from napalm_proxmox import utils
+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"
+382
View File
@@ -0,0 +1,382 @@
"""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)
+258 -11
View File
@@ -3,12 +3,12 @@
from __future__ import annotations
import base64
from unittest.mock import MagicMock, patch
import pytest
from unittest.mock import MagicMock, patch
from napalm_proxmox.driver import ProxmoxDriver
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_device_types.provisioning import VMProvisionIncomplete
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
# ---------------------------------------------------------------------------
# Tests
@@ -221,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"
@@ -251,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",
@@ -261,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():
@@ -485,6 +488,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
# ---------------------------------------------------------------------------
@@ -616,8 +655,9 @@ def _mock_ssh_exec(exit_status: int, stdout_text: str = "", stderr_text: str = "
def test_run_node_command_success_returns_stdout():
mixin = ProxmoxVMProvisionMixin()
mixin._ssh_client = MagicMock()
mixin._ssh_client.exec_command.return_value = _mock_ssh_exec(0, stdout_text="hello\n")
ssh = MagicMock()
ssh.exec_command.return_value = _mock_ssh_exec(0, stdout_text="hello\n")
mixin._node_ssh = MagicMock(return_value=ssh) # the driver's verified session
result = mixin._run_node_command("echo hello", timeout=10)
@@ -626,10 +666,9 @@ def test_run_node_command_success_returns_stdout():
def test_run_node_command_nonzero_exit_raises():
mixin = ProxmoxVMProvisionMixin()
mixin._ssh_client = MagicMock()
mixin._ssh_client.exec_command.return_value = _mock_ssh_exec(
1, stderr_text="No such file or directory"
)
ssh = MagicMock()
ssh.exec_command.return_value = _mock_ssh_exec(1, stderr_text="No such file or directory")
mixin._node_ssh = MagicMock(return_value=ssh)
with pytest.raises(RuntimeError, match="No such file or directory"):
mixin._run_node_command("cat /nonexistent", timeout=10)
@@ -1281,3 +1320,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()