Compare commits
112
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2d9d7e75e | ||
|
|
685e995073 | ||
|
|
370aeed482 | ||
|
|
bc3eb86723 | ||
|
|
8159566ff4 | ||
|
|
b80a3950ac | ||
|
|
cae4859383 | ||
|
|
ad3b5b29a9 | ||
|
|
326527ddd5 | ||
|
|
f071c10cd1 | ||
|
|
93c974b8f0 | ||
|
|
449230c624 | ||
|
|
92108f0ff3 | ||
|
|
5a5ed8eac7 | ||
|
|
dc24dd636b | ||
|
|
eff6af8b45 | ||
|
|
a421a595d4 | ||
|
|
6fccd7a8f0 | ||
|
|
610d6f1093 | ||
|
|
66828a9564 | ||
|
|
83d1ef780e | ||
|
|
a67e8492ee | ||
|
|
a13cd0202f | ||
|
|
042b21d3d9 | ||
|
|
410d34bdee | ||
|
|
aeb12eae00 | ||
|
|
3877a5425a | ||
|
|
b1252878a5 | ||
|
|
9c16586028 | ||
|
|
1f88f50f15 | ||
|
|
25363ac7b0 | ||
|
|
4e7e29b598 | ||
|
|
dce794644c | ||
|
|
d369f1ad76 | ||
|
|
ff5018a3b4 | ||
|
|
ced34c35ba | ||
|
|
44b260b2c4 | ||
|
|
983553cf11 | ||
|
|
0bb25a0c86 | ||
|
|
c040dfdaa2 | ||
|
|
2b2cd9b867 | ||
|
|
0b5f82cc02 | ||
|
|
a4c220d2e3 | ||
|
|
8521cff935 | ||
|
|
321cef3426 | ||
|
|
d4ed73c52b | ||
|
|
7259c842e3 | ||
|
|
a73dcf79fe | ||
|
|
ef1900c32a | ||
|
|
4ffe93fe4c | ||
|
|
dffb19e3df | ||
|
|
b3fe5009c8 | ||
|
|
b368ad9856 | ||
|
|
f93daa381e | ||
|
|
daf1b519eb | ||
|
|
bfba804ec2 | ||
|
|
6a8132e234 | ||
|
|
3233ee24a0 | ||
|
|
0f1918f230 | ||
|
|
a8d73d95b4 | ||
|
|
8dad7c3767 | ||
|
|
0704d9a102 | ||
|
|
61821cd607 | ||
|
|
8ef880b73b | ||
|
|
9c7b64ba64 | ||
|
|
10cf788b86 | ||
|
|
29ed59c8d1 | ||
|
|
f491f9f9ec | ||
|
|
5195cebfca | ||
|
|
4ee74e4b3d | ||
|
|
037a725b74 | ||
|
|
8f10bef7c5 | ||
|
|
89c70d85be | ||
|
|
0779695349 | ||
|
|
52d63eb689 | ||
|
|
d142db73e5 | ||
|
|
cb29a42c31 | ||
|
|
25369df572 | ||
|
|
f60532e434 | ||
|
|
d8ac209fb9 | ||
|
|
d5ae2e2915 | ||
|
|
72c30dd4c2 | ||
|
|
cc9752499e | ||
|
|
d577e7aae2 | ||
|
|
739d12a3db | ||
|
|
8205829437 | ||
|
|
16f1b87392 | ||
|
|
f3639d9990 | ||
|
|
711d5f2705 | ||
|
|
457c1ca7ed | ||
|
|
3365207c98 | ||
|
|
3b873d91fe | ||
|
|
1f6859de08 | ||
|
|
7776bb904a | ||
|
|
03c7cdfa02 | ||
|
|
e0d0147d75 | ||
|
|
d210c9abe8 | ||
|
|
6bb3035857 | ||
|
|
d134ccbb89 | ||
|
|
1100560f85 | ||
|
|
8cf334aaf5 | ||
|
|
377e849237 | ||
|
|
890e84ca6b | ||
|
|
98df0e21ca | ||
|
|
363f93c895 | ||
|
|
ecff2b430d | ||
|
|
0d71b98e6a | ||
|
|
0dc6fcb43a | ||
|
|
80e9fc3c81 | ||
|
|
171ab8888f | ||
|
|
c644519af6 | ||
|
|
6c9a6e7017 |
No files matched your search
@@ -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 }}
|
||||
+338
@@ -7,7 +7,345 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.13.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run
|
||||
(`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`,
|
||||
NetOrk/netork#2693). ufw does not say who wrote a rule, so every rule the firewall step
|
||||
adds -- the Zabbix agent's tcp/`listen_port`, SNMP's udp/161 -- is now recorded in
|
||||
`/var/lib/netork/opened-ports` (napalm-device-types `opened_ports`), and only when ufw did
|
||||
not have it before: an identical rule the operator wrote is never recorded. Closing removes
|
||||
exactly the agent's recorded rules, whatever port they opened, and rewrites the record. It
|
||||
reads the record only when it is root's alone, and reports the rules for the port it left
|
||||
in place: the operator's, or ones opened before this version recorded them. pve-firewall's
|
||||
rules stay the operator's.
|
||||
|
||||
## [0.12.0] - 2026-11-26
|
||||
|
||||
### Fixed
|
||||
- `get_vm_status(vmid)` reports the VM's real state (#72): it reads
|
||||
`GET /nodes/{node}/qemu/{vmid}/status/current` and answers `running`, `stopped`, or
|
||||
`paused` for a `qmpstatus` of paused or suspended, the same as `get_vms()`. It used to say
|
||||
`running` for every VM whose config could be read, so a caller waiting for a clean shutdown
|
||||
never saw the VM stop (NetOrk/netork's workflow step "Shut down Proxmox VM" always ran into
|
||||
its timeout). The guest agent is asked for an address only while the VM runs, and
|
||||
`wait_for_ip=True` ends with a `RuntimeError` at once when the VM is stopped or paused,
|
||||
rather than waiting out its timeout for an address that cannot come.
|
||||
|
||||
## [0.11.0] - 2026-11-25
|
||||
|
||||
### Added
|
||||
- `resume_vm(name)` (napalm-device-types' `HypervisorDriver`, NetOrk/netork#2658): a paused
|
||||
VM continues where `suspend_vm` stopped it, through `status/resume`, and the driver waits
|
||||
for its task. A VM that is not paused is refused (PVE answers a running one with success
|
||||
and does nothing), and so is a container: the driver does not suspend one, PVE's
|
||||
container suspend is experimental, and its listing does not tell a suspended container
|
||||
from another.
|
||||
- A native Zabbix agent on both drivers (napalm-device-types `ZabbixAgentMixin`,
|
||||
NetOrk/netork#2571): a node runs no container engine. `configure_zabbix_agent(settings)`
|
||||
installs Debian's `zabbix-agent`, and where Debian has none and the caller names the
|
||||
server's release line, Zabbix's from its repository; writes the caller's values into
|
||||
`/etc/zabbix/zabbix_agentd.conf` (the old file stays as `.bak`); opens tcp/`listen_port`
|
||||
in ufw where the node has it (pve-firewall's rules are the operator's); enables and
|
||||
restarts the service.
|
||||
- Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types'
|
||||
`TimeSyncMixin` (4.36.0); both write the servers and the zone. Neither API keeps time
|
||||
servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's
|
||||
sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised and
|
||||
the zone (`timedatectl`) in one round trip over the driver's SSH session
|
||||
(`PosixTimeSyncMixin`), and the zone from `GET /nodes/{node}/time` only where the host
|
||||
names none. `configure_time_sync()` writes the servers to
|
||||
`/etc/chrony/sources.d/netork.sources` with every other configured source commented out
|
||||
(Debian's vendor pool; the DHCP `sourcedir` stays) and reloads or restarts chrony; the zone
|
||||
goes through `PUT /nodes/{node}/time`, Proxmox's own call, so `/etc/timezone` and the
|
||||
web UI follow `/etc/localtime`. The token needs `Sys.Modify` for it (PVE on
|
||||
`/nodes/{node}`, PBS on `/system/time`). Only the node of the connection is read and
|
||||
written: in a PVE cluster each node keeps its own clock.
|
||||
- What a restart would abort, on both drivers (NetOrk/netork#2318), through
|
||||
napalm-device-types' `RunningBackupsMixin` (4.34.0): `get_running_backups()` lists on
|
||||
Proxmox VE the node's active vzdump tasks with the guests each is taking now -- the task's
|
||||
own guest, or for a job the guests locked for their backup (`lock: backup`) -- and a guest
|
||||
locked without a task on its own; on a backup server the running backup, sync, verify,
|
||||
garbage collection, prune and tape tasks. A failed read raises.
|
||||
- Log sources on both drivers (NetOrk/netork#2049), through napalm-device-types'
|
||||
`LogSourcesMixin` (4.30.0): `get_log_sources()` reads the units journald holds entries for
|
||||
and the log files running processes hold open, with the service or container writing each,
|
||||
over the exec path as root.
|
||||
- Scheduled jobs on both drivers (NetOrk/netork#1933, #56), through napalm-device-types'
|
||||
`PosixScheduledJobsMixin`: `get_scheduled_jobs()` reads `/etc/crontab`, `/etc/cron.d`,
|
||||
the user crontabs, the run-parts directories, `/etc/anacrontab` and every systemd timer
|
||||
in one round trip as root; `manage_scheduled_job()` enables, disables or runs one now;
|
||||
`put_scheduled_job()` and `delete_scheduled_job()` write and remove an application's own.
|
||||
What Proxmox ships is `platform`: on Proxmox VE `pve-*` units (`pve-daily-update.timer`),
|
||||
`pvesr.timer` and `/etc/cron.d/vzdump`; on a backup server `proxmox-backup*` units
|
||||
(`proxmox-backup-daily-update.timer`). A line in `/etc/cron.d/vzdump` is only run, never
|
||||
switched: the file is a link to `/etc/pve/vzdump.cron` on the cluster file system
|
||||
(pmxcfs), where installing a file with a mode and owner is not safe.
|
||||
Not scheduled jobs here: Proxmox VE's backup jobs (`/cluster/backup`) and replication,
|
||||
and a backup server's verify, prune, sync and garbage collection jobs. Proxmox runs them
|
||||
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
|
||||
|
||||
### Changed
|
||||
- `get_vms()` reports a paused VM as `"paused"`, no longer as `"running"` (NetOrk/netork#2658).
|
||||
PVE says `status: running` for a guest that `status/suspend` paused, or that sleeps in
|
||||
S3; only the full listing (`GET /nodes/{node}/qemu?full=1`) has its `qmpstatus`, so the
|
||||
driver asks for it.
|
||||
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
|
||||
- The SNMP agent's ufw step is the shared `_allow_sources(allowed, port, proto)`; the rule
|
||||
it writes for udp/161 is the same.
|
||||
|
||||
### Fixed
|
||||
- `set_hostname()` hands the name to the shell quoted (`shlex.quote`): to `hostname`, to
|
||||
`postconf -e` and in the paths of the `/etc/pve/nodes` move (#64, NetOrk/netork#2456). They
|
||||
stood between single quotes of their own, so a name with a single quote ended them and
|
||||
the rest ran as root (`x';reboot;'`).
|
||||
- `set_hostname()` writes the new `/etc/hosts` to a `mktemp` file beside it
|
||||
(`/etc/.hosts.XXXXXX`), sets its mode and moves it into place; a failed step removes
|
||||
it (#66, NetOrk/netork#2446). It wrote as root to the fixed `/tmp/_netork_hosts` and
|
||||
moved that over `/etc/hosts`, so a local user who created the file first owned
|
||||
`/etc/hosts` afterwards.
|
||||
- `get_ntp_servers()` read `GET /nodes/{node}/ntp`, a path Proxmox VE does not have, and so
|
||||
always reported no servers. It now reports chrony's configured sources, the ones
|
||||
`get_time_sync()` reads, and the backup server has it too.
|
||||
|
||||
## [0.10.0] - 2026-11-03
|
||||
|
||||
### Added
|
||||
- `get_clusters()` names the backup server behind each `pbs` storage
|
||||
(`ClusterStorageDict.backup_server`: server, port, datastore, namespace, fingerprint,
|
||||
read from `/storage`; never its password or encryption key), so an application can tie a
|
||||
Proxmox Backup Server's groups to the cluster's guests (#55). An unreadable `/storage`
|
||||
leaves it `None`; every other storage carries no such key.
|
||||
|
||||
## [0.9.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
- **Proxmox Backup Server** as a second driver of this package, entry point
|
||||
`proxmox_backup` (`ProxmoxBackupDriver`, #52). Its API is on **8007**, not 8006; the
|
||||
node is always `localhost`. Roles: `BackupServerDriver` (napalm-device-types 4.25.0)
|
||||
first, `StorageDriver` second. It reads datastores (usage, estimated full date,
|
||||
backend, maintenance or `unmounted`), backup groups in every namespace with their
|
||||
newest snapshot and its verify state, a group's snapshots, the GC, verify, prune,
|
||||
sync and tape jobs with the state of their last run, and the remotes without their
|
||||
secrets; it starts garbage collection and jobs, verifies, protects and deletes
|
||||
snapshots, and follows the tasks. As a host it reports facts, interfaces, CPU and
|
||||
memory, disks and ZFS pools, its `pbs-subscription`, packages and updates, and has
|
||||
the same host readers and sshd hardening as a PVE node.
|
||||
- A token without an ACL entry gets an empty list from PBS rather than a refusal; every
|
||||
read checks `/access/permissions` first and raises `PermissionError`.
|
||||
- The node's sshd can be hardened: `OpenSshServerMixin` (napalm-device-types) gives
|
||||
`harden_ssh_server` and `exempt_from_ssh_penalties`, so netOrk's SSH algorithm fix
|
||||
works on a Proxmox node as on a plain Linux host. A node runs Debian's stock
|
||||
OpenSSH with an `sshd_config.d` include, so the change is a drop-in there (#50).
|
||||
- `run_command(command, *, privileged=False, timeout=60, stdin=None)`, the public
|
||||
command channel: an exec channel on the node's SSH session with stdout, stderr and
|
||||
the exit status kept apart. `privileged` needs nothing more on a node logged in as
|
||||
root; a command that cannot run or outlasts its timeout raises `ConnectionException`.
|
||||
|
||||
### Changed
|
||||
- The floor on napalm-device-types is 4.25.0, the first release with
|
||||
`BackupServerDriver` (4.24.0 brought the shared `lldpctl` parser).
|
||||
- What the two drivers share moved out of `ProxmoxDriver`: the connection, token split,
|
||||
SSH session and node helpers into `napalm_proxmox._base`, the Debian host's packages,
|
||||
updates, subscription and the host readers' transports into
|
||||
`napalm_proxmox.host_mixin`. The PVE driver behaves as before, pinned by tests first;
|
||||
it now names proxmoxer's `service="PVE"` explicitly.
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
|
||||
### Added
|
||||
- `get_clusters()` reports quorum `votes` per node (`/cluster/config/nodes`), the
|
||||
guests HA manages in `ha_resources` (`/cluster/ha/resources`, the CRM state and
|
||||
node from `/cluster/ha/status/current`, the ids of the PVE 9 HA rules that name
|
||||
each from `/cluster/ha/rules`, `[]` on PVE 8), the vzdump jobs in `backup_jobs`
|
||||
(`/cluster/backup`; a pool job lists the pool's guests from `/pools?poolid=`, or
|
||||
`/pools/{pool}` before PVE 8.1; old `starttime`/`dow` jobs get the schedule PVE
|
||||
itself derives) and per guest and storage the newest backup in `backups` (each
|
||||
storage with backup content read once if shared, on each node if local; PBS
|
||||
included). Each is best-effort: one that cannot be read is None and the rest of
|
||||
the report stands.
|
||||
- `get_vm_migration_preflight(name)`: a VM's nodes and blockers from
|
||||
`GET .../qemu/{vmid}/migrate` in plain words, a local ISO in a CD drive as a
|
||||
blocking resource, the cloud-init drive left out; a container's candidates are the
|
||||
online members, its local volumes and unshared bind mounts read from its config.
|
||||
An offline member is refused as `"node offline"` for both.
|
||||
- `migrate_vm(name, target_node, online=True, target_storage=None, timeout=3600)`:
|
||||
`POST .../{qemu|lxc}/{vmid}/migrate` (`online` for a running VM, `with-local-disks`
|
||||
when it has local disks, restart mode for a running container), followed to the
|
||||
end; a failure raises with the task log's `ERROR:` lines. A target that is not
|
||||
another cluster member is refused before the API is called. A guest HA manages is
|
||||
followed through the HA manager until it is on the target.
|
||||
- `set_node_maintenance(node, enabled)`: `ha-manager crm-command node-maintenance`
|
||||
over the driver's SSH session, for a cluster member only and quoted; raises
|
||||
RuntimeError when SSH is not available. Needs the shapes and contracts of the
|
||||
next napalm-device-types release for type checking (runtime imports none).
|
||||
- `get_clusters()`: the cluster the node belongs to, always exactly one, read
|
||||
from `/cluster/status`, `/cluster/resources`, each online node's status and
|
||||
network, SDN vnets/zones and the HA manager. Every member is listed, an
|
||||
offline one with `status` `"offline"` and no capacity; `maintenance` is None
|
||||
when the HA manager cannot be read. Storages are grouped by name with the
|
||||
nodes they are available on (size: one node's figure for a shared storage,
|
||||
the sum over its nodes for a local one); bridges are merged across nodes,
|
||||
VLAN aware only if they are on every node; a vnet is on its zone's nodes. A
|
||||
standalone node is a cluster of one without a name. `create_vm_from_cloud_init()`
|
||||
takes `node` and raises ValueError, before creating anything, for a node
|
||||
other than its own (NetOrk/netork#484, NetOrk/netork#1822). Needs the cluster
|
||||
models and `get_clusters()` contract of napalm-device-types.
|
||||
- `get_network_targets()` names each bridge's physical NICs in `uplinks`, read
|
||||
from `bridge_ports`/`ovs_ports`, one group per bridge port: a bond's slaves
|
||||
together, a NIC alone, without internal ports (`OVSIntPort`) and VLAN
|
||||
subinterfaces. Left out when a port is missing from the
|
||||
node's network config or of a kind it cannot place (NetOrk/netork#1325). Needs
|
||||
the `uplinks` field of napalm-device-types' `NetworkTargetDict`.
|
||||
- `shutdown_host()`: the node shuts itself down through the API
|
||||
(`POST /nodes/{node}/status command=shutdown`), and `begin_stop_vm(name)`: a
|
||||
guest's clean shutdown, returning once Proxmox took it instead of waiting for
|
||||
the task — the contracts `HostShutdownMixin` and `VmStopRequestMixin` of
|
||||
napalm-device-types (NetOrk/netork#1636).
|
||||
|
||||
### Fixed
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` raise when lldpctl fails
|
||||
(lldpd not running, lldpctl missing) or the node gives no answer, with lldpctl's
|
||||
message; they used to return no neighbours, the same answer as a node without any
|
||||
(#44). Capabilities carry NAPALM's names (`telephone`, `wlan-access-point`,
|
||||
`docsis-cable-device`) instead of lldpd's symbols (`tel`, `wlan`, `docsis`).
|
||||
lldpd is read with `lldpctl -f keyvalue` through napalm-device-types' shared
|
||||
parser, so a neighbour named by its chassis MAC also carries it as `mac`, and an
|
||||
interface name with a dot stays whole.
|
||||
- `get_ipv6_neighbors_table()` reports an unknown age as `-1.0`, as `get_arp_table()`
|
||||
already did (napalm-device-types' `ARP_AGE_UNKNOWN`), instead of `0.0`, which
|
||||
means "confirmed just now" (NetOrk/netork#1327).
|
||||
- `set_vlan()` finds the node's switch uplink again. Since 0.8.0 every call failed
|
||||
with "no LLDP-detected switch uplink found", whatever LLDP reported (#37).
|
||||
- `configure_snmp_agent()` completes: its "configure" step reported a failure
|
||||
with empty output although `/etc/snmp/snmpd.conf` was written, so the firewall
|
||||
and start steps never ran (#30).
|
||||
- `create_vm_from_cloud_init(ssh_public_keys=...)` installs every key, one per
|
||||
line, instead of only the first; a key containing `/` or `+` is no longer
|
||||
refused by Proxmox (#23).
|
||||
- `get_lldp_neighbors()` lists every neighbour of a port: a second neighbour on
|
||||
the same port no longer overwrites the first, and a neighbour that sends no
|
||||
system name is listed with an empty `hostname` instead of being dropped (#22).
|
||||
- `set_hostname()` renames only the node's own names in `/etc/hosts`: other
|
||||
hosts whose names start with the old one (`pve-backup`) and comments stay as
|
||||
they are, and the old FQDN becomes the new one instead of a mix of both (#21).
|
||||
- `set_hostname()` refuses a node that is part of a cluster (a
|
||||
`/etc/pve/corosync.conf` or `/etc/corosync/corosync.conf` exists) with a
|
||||
`CommandErrorException`, before changing anything: it moved
|
||||
`/etc/pve/nodes/<old>` while the cluster still knew the node as `<old>`. Also
|
||||
refused when the check cannot be read. A single node renames as before (#21).
|
||||
- `apply_updates()` reports a failed upgrade as `success: False`, with apt-get's
|
||||
exit status in `error`; it reported success whatever apt-get did (#20).
|
||||
- `get_users()` lists the node's root and regular login accounts (uid 1000 and
|
||||
up) instead of its system accounts (`daemon`, `bin`, …), and gives a Proxmox
|
||||
user level 15 when the ACL grants it the Administrator role on `/`, directly
|
||||
or through a group; `root@pam` is always 15. Before, practically every
|
||||
Proxmox user was level 1 (#19).
|
||||
- `get_ntp_stats()` reports chrony's sources, Proxmox VE's default, instead of
|
||||
always returning an empty list: offset in ms, the poll interval in seconds,
|
||||
the offset's standard deviation as `jitter`; chrony reports no delay, so
|
||||
`delay` is 0.0. On ntpd, a peer without tally mark is no longer dropped (#18).
|
||||
- The SSH login to the node takes an Ed25519 or ECDSA key in
|
||||
`ssh_private_key_str`, not only RSA, and uses the key even when a password is
|
||||
set too (the password stays the fallback). A key that cannot be read is
|
||||
logged as a warning and the password used (#17).
|
||||
- `destroy_vm()` returns once Proxmox has deleted the VM, not as soon as the
|
||||
delete was queued, and raises when the delete fails (#15).
|
||||
- `ping()` fills `results` with each reply's address and round-trip time; it
|
||||
was always empty (#12).
|
||||
- A failed cloud-image download in `create_vm_from_cloud_init()` says why
|
||||
(wget's own message, such as "No space left on device") and removes its
|
||||
partial `.tmp` file instead of leaving it to fill the node's disk (#3).
|
||||
- A `create_vm_from_cloud_init()` that fails once the VM shell exists (disk import,
|
||||
storage, NIC or snippet configuration, start) raises `VMProvisionIncomplete`, a
|
||||
`RuntimeError` with the VMID and node of the VM it left behind and the failure as
|
||||
its cause, so the caller can remove it with `destroy_vm()`. Failures there that
|
||||
were a `ValueError` (no snippet storage, a NIC without a bridge) are its cause now.
|
||||
Needs `VMProvisionIncomplete` from napalm-device-types (#28).
|
||||
- `create_vm_from_cloud_init()` quotes the image URL and every path built from it in
|
||||
the commands it runs as root on the node (download, checksum, unpack, disk
|
||||
import). A URL with a quote, `$(…)`, `;` or a space no longer reaches the shell:
|
||||
the node's cache file name keeps only the characters Proxmox keeps in a file
|
||||
name, the others become `_`. A checksum algorithm other than md5, sha1, sha224,
|
||||
sha256, sha384 or sha512 is refused with a `ValueError` before anything runs on
|
||||
the node (#43).
|
||||
- Commands on the node (ARP, IPv6 neighbours, packages, users, NTP, SNMP config,
|
||||
services, kernel facts, `cli()`, …) raise `ConnectionException` when they cannot run:
|
||||
no SSH password or key (a node reached with an API token only), a refused login, an
|
||||
unreachable node, a timeout; a changed host key raises `SshHostKeyMismatch` as
|
||||
before. They returned empty output, so "could not look" read as "nothing there":
|
||||
`get_snmp_config()` answered None on token-only nodes and the getters empty lists.
|
||||
Only what a command prints on stdout is its output; stderr no longer stands in when
|
||||
stdout is empty. Each command goes straight to SSH: the driver first posted it to
|
||||
`/nodes/{node}/execute`, which runs API calls, not a shell, and always failed (#17).
|
||||
- The SSH login to the node uses only the credentials it is given
|
||||
(`ssh_private_key_str`, `ssh_password` or the API password): paramiko no longer also
|
||||
tries the keys in the running process's `~/.ssh` or an SSH agent it can reach (#48).
|
||||
- `create_vm_from_cloud_init()` quotes the snippet storage's path and the snippet's
|
||||
file name in the command that writes the cloud-init snippets as root on the node,
|
||||
and refuses a snippet name that is not one plain file name (#47).
|
||||
|
||||
## [0.8.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI. It collects everything since 0.1.0.
|
||||
|
||||
### 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=`),
|
||||
because FreeBSD's nuageinit skips runcmd on the v1 Proxmox generates.
|
||||
OpenBSD's agent runs over ISA serial behind `serial0`, as the image keeps
|
||||
its console on com0. An unknown `guest_os` is refused before anything is
|
||||
created.
|
||||
- Packed cloud images (FreeBSD's `.qcow2.xz`) are unpacked on the node after
|
||||
the packed file's checksum is verified; only the unpacked file is cached.
|
||||
Proxmox's `download-url` unpacks ISOs only, so they always go over SSH.
|
||||
|
||||
### Fixed
|
||||
- `get_vm_status` no longer reports a loopback address as the VM's IP when
|
||||
the agent lists loopback under another name than `lo` (`lo0` on the BSDs,
|
||||
listed first by OpenBSD).
|
||||
- `destroy_vm` reads the VM's cloud-init snippets before deleting the VM, and
|
||||
removes all of them; it read them afterwards, when the config was gone (#15).
|
||||
- Cloud images for `create_vm_from_cloud_init` are downloaded by Proxmox itself
|
||||
when the node has an active storage with content type `import` (Proxmox
|
||||
8.2+): `download-url` with checksum verification, then `import-from` as the
|
||||
|
||||
@@ -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 .
|
||||
```
|
||||
@@ -102,11 +106,11 @@ device = driver(
|
||||
| `get_interfaces_ip` | IPv4/IPv6 from classic ifaces + SDN subnet gateways |
|
||||
| `get_interfaces_counters` | From `node/netstat` RRD data |
|
||||
| `get_environment` | CPU %, memory (bytes), hardware temperature sensors |
|
||||
| `get_arp_table` | Reads `/proc/net/arp` via exec endpoint |
|
||||
| `get_arp_table` | Reads `/proc/net/arp` over SSH |
|
||||
| `get_mac_address_table` | `bridge fdb show` (Linux) + `ovs-appctl fdb/show` (OVS) |
|
||||
| `get_vlans` | SDN VNet tags + `bridge vlan show` |
|
||||
| `get_network_instances` | SDN zones (VLAN→L2VPN, EVPN→L3VRF) + default instance |
|
||||
| `get_ntp_servers` | From `node/ntp` API |
|
||||
| `get_ntp_servers` | chrony's configured sources, as `get_time_sync` reads them |
|
||||
| `get_ntp_stats` | Parses `chronyc` / `ntpq -pn` output |
|
||||
| `get_snmp_information` | Parses `/etc/snmp/snmpd.conf` |
|
||||
| `get_users` | Proxmox access/users API + local `/etc/passwd` |
|
||||
@@ -115,13 +119,18 @@ device = driver(
|
||||
| `compare_config` | Unified diff |
|
||||
| `commit_config` | Writes `/etc/network/interfaces` + `ifreload -a` |
|
||||
| `discard_config` / `rollback` | Revert candidate |
|
||||
| `get_lldp_neighbors` | `lldpcli show neighbors` via exec |
|
||||
| `get_lldp_neighbors_detail` | Full LLDP detail |
|
||||
| `get_lldp_neighbors` | `lldpctl -f keyvalue` over SSH (napalm-device-types' parser); raises when lldpctl fails |
|
||||
| `get_lldp_neighbors_detail` | Full LLDP detail, capabilities in NAPALM's names |
|
||||
| `get_ipv6_neighbors_table` | `ip -6 neigh show` |
|
||||
| `ping` | Linux `ping` via exec endpoint |
|
||||
| `traceroute` | `traceroute -n` via exec endpoint |
|
||||
| `cli` | Arbitrary command execution via exec endpoint |
|
||||
| `get_route_to` | `ip route show` via exec endpoint |
|
||||
| `ping` | Linux `ping` over SSH |
|
||||
| `traceroute` | `traceroute -n` over SSH |
|
||||
| `cli` | Arbitrary commands over SSH (stdout) |
|
||||
| `get_route_to` | `ip route show` over SSH |
|
||||
| `get_scheduled_jobs` | cron, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers, as root over SSH (napalm-device-types' `PosixScheduledJobsMixin`); `pve-*` units, `pvesr.timer` and `/etc/cron.d/vzdump` are `platform` |
|
||||
| `manage_scheduled_job(key, action, digest=)` | enable, disable, run now; a `/etc/cron.d/vzdump` line only runs |
|
||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
|
||||
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
||||
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
||||
|
||||
**Not implemented** (raise `NotImplementedError`):
|
||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||
@@ -137,6 +146,69 @@ device = driver(
|
||||
| `node` | str | *auto* | Override target node name |
|
||||
| `token_name` | str | `None` | API token identifier (`user@realm!tokenid`) |
|
||||
| `token_value` | str | `None` | API token secret |
|
||||
| `ssh_username` | str | *username* | Login for the node's SSH (port 22) |
|
||||
| `ssh_password` | str | *password* | SSH password; the API password when not set |
|
||||
| `ssh_private_key_str` | str | `None` | SSH private key (Ed25519, ECDSA or RSA), tried before the password |
|
||||
|
||||
What the API does not offer (ARP, LLDP, packages, SNMP config, `cli`, …) runs in the
|
||||
node's shell over SSH. Without an SSH password or key — a node reached with an API
|
||||
token only — those calls raise `ConnectionException` instead of reading as empty.
|
||||
|
||||
## Proxmox Backup Server
|
||||
|
||||
```python
|
||||
driver = get_network_driver("proxmox_backup")
|
||||
device = driver(
|
||||
hostname="pbs1.example.com",
|
||||
username="",
|
||||
password="",
|
||||
optional_args={
|
||||
"token_name": "root@pam!monitoring",
|
||||
"token_value": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
||||
"ssh_private_key_str": open("id_ed25519").read(), # optional, see below
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
**The API and web UI listen on 8007**, not on Proxmox VE's 8006; `port` defaults to
|
||||
8007 here. The node is always `localhost`: a backup server has no cluster. The
|
||||
optional arguments are the ones above, except `node`.
|
||||
|
||||
Roles (napalm-device-types): `BackupServerDriver` first, `StorageDriver` second for
|
||||
the disks and ZFS pools the server manages itself.
|
||||
|
||||
| Method | Source |
|
||||
|--------|--------|
|
||||
| `get_backup_datastores` | `/config/datastore` + `/status/datastore-usage`: usage, estimated full date, backend (`local`, `s3`, `removable`), maintenance or `unmounted` |
|
||||
| `get_backup_groups` / `get_backup_snapshots` | `/admin/datastore/{store}/{namespace,groups,snapshots}`, every namespace; a group carries its newest snapshot with its verify state |
|
||||
| `get_backup_jobs` | `/admin/{gc,verify,prune,sync}`, `/tape/backup`, with the state of the last run |
|
||||
| `get_backup_remotes` | `/config/remote`, without secrets |
|
||||
| `start_garbage_collection`, `run_backup_job`, `verify_backup_snapshot` | start a task; `get_backup_task` follows it |
|
||||
| `set_backup_snapshot_protected`, `delete_backup_snapshot` | on one snapshot |
|
||||
| `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH |
|
||||
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
||||
| `get_licenses` | `pbs-subscription` |
|
||||
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
||||
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
||||
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
||||
|
||||
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
||||
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
||||
`Audit` does not include. A privilege-separated token needs an ACL entry of its own:
|
||||
|
||||
```bash
|
||||
proxmox-backup-manager acl update / Audit --auth-id 'root@pam!monitoring'
|
||||
```
|
||||
|
||||
Without it PBS does not refuse a listing, it answers with an empty one. The driver
|
||||
therefore checks `/access/permissions` before every read and raises
|
||||
`PermissionError`, so a token without rights does not read as a server without
|
||||
backups. The actions need `DatastoreAdmin` on `/datastore` (GC, verify, prune,
|
||||
protect, delete) and `Sys.Modify` / `Sys.PowerManagement` on `/system` (services,
|
||||
reboot).
|
||||
|
||||
A removable datastore that is not mounted is reported as `maintenance: "unmounted"`
|
||||
and left out of `get_backup_groups()`; asked for by name, it raises `ValueError`.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -156,8 +228,13 @@ ruff check napalm_proxmox
|
||||
|
||||
```
|
||||
napalm_proxmox/
|
||||
├── __init__.py # Exports ProxmoxDriver
|
||||
├── driver.py # ProxmoxDriver — all NAPALM methods
|
||||
├── __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
|
||||
@@ -167,8 +244,12 @@ tests/
|
||||
├── test_environment.py # get_environment
|
||||
├── test_sdn.py # get_vlans, get_network_instances
|
||||
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
|
||||
├── test_misc.py # NTP, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||
└── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||
└── test_pbs_*.py # The backup server driver
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
@@ -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"]
|
||||
@@ -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)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""NAPALM driver for Proxmox Backup Server (entry point ``proxmox_backup``).
|
||||
|
||||
A PBS is a Debian host with one node, always ``localhost`` in its API, and no
|
||||
cluster. Its API and web UI listen on **8007**, not on PVE's 8006. The
|
||||
connection, the SSH session and the node helpers are the ones the PVE driver
|
||||
uses (``napalm_proxmox._base``).
|
||||
|
||||
Roles: a backup server first (datastores, backup groups, jobs, remotes), and
|
||||
storage second for the disks and ZFS pools it manages itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import (
|
||||
AptProxyMixin,
|
||||
BackupServerDriver,
|
||||
EnsurePackageMixin,
|
||||
FingerprintRule,
|
||||
HostStatusMixin,
|
||||
KernelFactsMixin,
|
||||
LicenseMixin,
|
||||
ListeningSocketsMixin,
|
||||
LogSourcesMixin,
|
||||
OpenSshServerMixin,
|
||||
PortSpec,
|
||||
ServicePackagesMixin,
|
||||
StorageDriver,
|
||||
SystemdServicesMixin,
|
||||
SystemIdentityMixin,
|
||||
)
|
||||
|
||||
try:
|
||||
from proxmoxer import ProxmoxAPI
|
||||
except ImportError as exc: # pragma: no cover - proxmoxer is a dependency
|
||||
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
|
||||
|
||||
from napalm_proxmox._base import ProxmoxBase
|
||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
|
||||
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
||||
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
|
||||
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The node name the PBS API answers to; a PBS has exactly one.
|
||||
PBS_NODE = "localhost"
|
||||
|
||||
|
||||
class ProxmoxBackupDriver(
|
||||
ProxmoxBase,
|
||||
ProxmoxBackupServerMixin,
|
||||
PbsRunningBackupsMixin,
|
||||
ProxmoxPbsHostMixin,
|
||||
ProxmoxHostMixin,
|
||||
ProxmoxTimeSyncMixin,
|
||||
BackupServerDriver,
|
||||
StorageDriver,
|
||||
KernelFactsMixin,
|
||||
ServicePackagesMixin,
|
||||
ListeningSocketsMixin,
|
||||
LogSourcesMixin,
|
||||
SystemIdentityMixin,
|
||||
SystemdServicesMixin,
|
||||
ProxmoxScheduledJobsMixin,
|
||||
HostStatusMixin,
|
||||
LicenseMixin,
|
||||
ProxmoxZabbixAgentMixin,
|
||||
EnsurePackageMixin,
|
||||
AptProxyMixin,
|
||||
OpenSshServerMixin,
|
||||
):
|
||||
"""NAPALM driver for Proxmox Backup Server."""
|
||||
|
||||
SERVICE = "PBS"
|
||||
VENDOR = "Proxmox"
|
||||
DRIVER_NAME = "proxmox_backup"
|
||||
# netOrk reaches the server through the REST API and does not log in over
|
||||
# SSH itself; the driver's own SSH session (_node_ssh) runs the shell.
|
||||
USES_SSH = False
|
||||
#: A PBS upgrades like a PVE node: a plain ``apt-get upgrade`` holds back
|
||||
#: what needs new or removed packages.
|
||||
FULL_UPGRADE = True
|
||||
#: The backup server's own timer is ``platform``.
|
||||
PLATFORM_SOURCES = PBS_PLATFORM_SOURCES
|
||||
PORT_SPECS = [
|
||||
PortSpec("https", 8007, weight=8.0),
|
||||
]
|
||||
SSH_FINGERPRINT = [
|
||||
FingerprintRule("debian", weight=3.0),
|
||||
]
|
||||
HTTP_FINGERPRINT = [
|
||||
FingerprintRule("proxmox backup server", weight=9.0, mandatory=True),
|
||||
FingerprintRule("proxmox", weight=5.0),
|
||||
FingerprintRule("pbs", weight=2.0),
|
||||
]
|
||||
platform = "proxmox_backup"
|
||||
PACKAGE_SOURCE = "pbs"
|
||||
SUBSCRIPTION_LICENSE = "pbs-subscription"
|
||||
|
||||
def _proxmox_api(self, **kwargs: Any) -> Any:
|
||||
return ProxmoxAPI(**kwargs)
|
||||
|
||||
def _resolve_node(self) -> str:
|
||||
"""The node is always ``localhost``; ``GET /version`` proves the login.
|
||||
|
||||
proxmoxer logs in lazily with a token, so without a request here a bad
|
||||
token would only fail at the first getter.
|
||||
"""
|
||||
self._api.version.get()
|
||||
self._node_name = PBS_NODE
|
||||
return self._node_name
|
||||
@@ -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]))]
|
||||
@@ -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"])
|
||||
@@ -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
|
||||
@@ -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 && "
|
||||
|
||||
+60
-303
@@ -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,35 +24,50 @@ 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,
|
||||
LogSourcesMixin,
|
||||
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.running_backups import ProxmoxRunningBackupsMixin
|
||||
from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
||||
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
||||
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
|
||||
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Type aliases
|
||||
@@ -73,6 +80,7 @@ _JsonDict = dict[str, Any]
|
||||
|
||||
|
||||
class ProxmoxDriver(
|
||||
ProxmoxBase,
|
||||
ProxmoxInterfaceMixin,
|
||||
ProxmoxSDNMixin,
|
||||
ProxmoxLLDPMixin,
|
||||
@@ -81,18 +89,35 @@ class ProxmoxDriver(
|
||||
ProxmoxVMContractMixin,
|
||||
ProxmoxVMSnapshotMixin,
|
||||
ProxmoxVMProvisionMixin,
|
||||
ProxmoxClusterMixin,
|
||||
ProxmoxVMMigrateMixin,
|
||||
ProxmoxRoutingMixin,
|
||||
ProxmoxSystemMixin,
|
||||
ProxmoxHostMixin,
|
||||
KernelFactsMixin,
|
||||
ServicePackagesMixin,
|
||||
ListeningSocketsMixin,
|
||||
LogSourcesMixin,
|
||||
SystemIdentityMixin,
|
||||
SystemdServicesMixin,
|
||||
ProxmoxScheduledJobsMixin,
|
||||
ProxmoxRunningBackupsMixin,
|
||||
ProxmoxTimeSyncMixin,
|
||||
HostStatusMixin,
|
||||
LicenseMixin,
|
||||
SnmpAgentMixin,
|
||||
ProxmoxZabbixAgentMixin,
|
||||
EnsurePackageMixin,
|
||||
AptProxyMixin,
|
||||
OpenSshServerMixin,
|
||||
HypervisorDriver,
|
||||
):
|
||||
"""NAPALM driver for Proxmox VE nodes."""
|
||||
|
||||
VENDOR = "Proxmox"
|
||||
DRIVER_NAME = "proxmox"
|
||||
# Everything runs over the Proxmox REST API; there is no SSH session.
|
||||
# netOrk reaches the node through the REST API and does not log in over SSH
|
||||
# itself; the driver's own SSH session (_node_ssh) runs the node's shell.
|
||||
USES_SSH = False
|
||||
# A PVE node reboots through a full init sequence plus storage checks.
|
||||
REBOOT_SETTLE_SECONDS = 90
|
||||
@@ -100,6 +125,10 @@ class ProxmoxDriver(
|
||||
#: ``apt-get upgrade`` holds back what needs new or removed packages and can
|
||||
#: leave the node half updated. netOrk reads this when it upgrades the host.
|
||||
FULL_UPGRADE = True
|
||||
#: Proxmox VE's own timers and cron file are ``platform``.
|
||||
PLATFORM_SOURCES = PVE_PLATFORM_SOURCES
|
||||
#: ``/etc/cron.d/vzdump`` links into ``/etc/pve`` (pmxcfs); its lines are only run.
|
||||
RUN_ONLY_SOURCES = ("/etc/cron.d/vzdump",)
|
||||
PORT_SPECS = [
|
||||
PortSpec("https", 8006, weight=8.0),
|
||||
]
|
||||
@@ -121,29 +150,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 = ""
|
||||
@@ -152,53 +161,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.
|
||||
@@ -216,9 +180,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"),
|
||||
@@ -240,159 +202,6 @@ class ProxmoxDriver(
|
||||
f"set the 'node' driver argument"
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the connection."""
|
||||
self._api = None
|
||||
if self._ssh_client:
|
||||
try:
|
||||
self._ssh_client.close()
|
||||
except Exception:
|
||||
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
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
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:
|
||||
return self._node_api().ntp.get() or {}
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to fetch node NTP: %s", exc)
|
||||
return {}
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# NAPALM getters kept in driver
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -411,57 +220,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.
|
||||
@@ -482,13 +249,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}
|
||||
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
|
||||
|
||||
The transports for napalm-device-types' host readers (kernel facts, service
|
||||
packages, system identity, listening sockets, systemd services, host status,
|
||||
apt's proxy), packages and APT updates, the subscription, root file writes,
|
||||
and restarting or shutting the host down. All of it is the same on both
|
||||
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status``
|
||||
endpoints, and root's shell over the driver's own SSH session.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from napalm_device_types import (
|
||||
APT_UPGRADABLE_COMMAND,
|
||||
OPENED_PORTS_RECORD,
|
||||
OpenedRuleDict,
|
||||
parse_apt_upgradable,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
revoke_recorded_rules,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
from napalm_device_types.models import (
|
||||
FixStepOutcomeDict,
|
||||
LicenseDict,
|
||||
LicenseStatus,
|
||||
PackageDict,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: The subscription API's status (lower-cased) as a napalm-device-types
|
||||
#: ``LicenseStatus``; "new" and "suspended" have none of their own.
|
||||
_SUBSCRIPTION_STATUS: dict[str, LicenseStatus] = {
|
||||
"notfound": "none",
|
||||
"active": "active",
|
||||
"invalid": "invalid",
|
||||
"expired": "expired",
|
||||
}
|
||||
|
||||
_PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.+:~-]*$")
|
||||
|
||||
|
||||
class ProxmoxHostMixin:
|
||||
"""The Debian host under a Proxmox product."""
|
||||
|
||||
#: ``source`` of every package ``get_packages`` reports.
|
||||
PACKAGE_SOURCE = "pve"
|
||||
#: ``name`` of the subscription ``get_licenses`` reports.
|
||||
SUBSCRIPTION_LICENSE = "pve-subscription"
|
||||
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||
|
||||
def _exec_ssh_command(self, command: str) -> str: ...
|
||||
def _node_api(self) -> Any: ...
|
||||
def _get_node_subscription(self) -> _JsonDict: ...
|
||||
|
||||
def _run_kernel_facts_command(self, command: str) -> str:
|
||||
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
||||
return self._exec_ssh_command(command)
|
||||
|
||||
def _run_service_packages_command(self, command: str) -> str:
|
||||
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def _run_system_identity_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""The transport for ``SystemIdentityMixin.get_system_identity``: the exec path,
|
||||
which runs as root either way."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""The transport for ``ListeningSocketsMixin.get_listening_sockets``:
|
||||
the exec path, which runs as root either way."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""The transport for ``LogSourcesMixin.get_log_sources``: the exec path,
|
||||
which runs as root either way."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def get_packages(self) -> list[PackageDict]:
|
||||
"""Return installed Debian packages with available-update info.
|
||||
|
||||
Installed list comes from ``dpkg-query`` via SSH (the Proxmox API
|
||||
``/apt/installed`` endpoint is not implemented on PVE 8.x).
|
||||
Available updates come from the Proxmox API ``/apt/update``.
|
||||
"""
|
||||
upgradable = self._upgradable_versions()
|
||||
# Installed packages via SSH dpkg-query
|
||||
raw = self._exec_ssh_command(
|
||||
"dpkg-query -W -f="
|
||||
"'${Package}\\t${Version}\\t${db:Status-Status}\\t${Installed-Size}"
|
||||
"\\t${source:Package}\\t${source:Version}\\n'"
|
||||
" 2>/dev/null"
|
||||
)
|
||||
result = []
|
||||
for line in raw.splitlines():
|
||||
pkg = parse_dpkg_line(line, self.PACKAGE_SOURCE)
|
||||
if pkg is not None:
|
||||
pkg["upgrade_version"] = upgradable.get(pkg["name"], "")
|
||||
result.append(pkg)
|
||||
# PackageDict has no source_package, source_version and upgrade_version
|
||||
# yet (NAPALM/napalm-device-types#85); every reader of these
|
||||
# packages relies on them, so they stay.
|
||||
return cast(list[PackageDict], result)
|
||||
|
||||
def _upgradable_versions(self) -> dict[str, str]:
|
||||
"""The candidate version of every upgradable package, from ``/apt/update``."""
|
||||
upgradable: dict[str, str] = {}
|
||||
try:
|
||||
for upd in self._node_api().apt.update.get():
|
||||
pkg = upd.get("Package", "")
|
||||
if pkg:
|
||||
upgradable[pkg] = upd.get("Version", "")
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to fetch available APT updates: %s", exc)
|
||||
return upgradable
|
||||
|
||||
def get_licenses(self) -> list[LicenseDict]:
|
||||
"""The node's subscription, as the API reports it.
|
||||
|
||||
A fact for the caller: whether running without one is a problem is not
|
||||
the driver's to say. An unreadable subscription reports nothing.
|
||||
"""
|
||||
sub = self._get_node_subscription()
|
||||
raw = str(sub.get("status", ""))
|
||||
if not raw:
|
||||
return []
|
||||
lic: LicenseDict = {
|
||||
"name": self.SUBSCRIPTION_LICENSE,
|
||||
"status": _SUBSCRIPTION_STATUS.get(raw.lower(), "unknown"),
|
||||
"detail": str(sub.get("message") or raw),
|
||||
}
|
||||
if sub.get("productname"):
|
||||
lic["edition"] = sub["productname"]
|
||||
if sub.get("nextduedate"):
|
||||
lic["expires"] = sub["nextduedate"]
|
||||
return [lic]
|
||||
|
||||
def _run_service_command(self, command: str, *, privileged: bool, timeout: int) -> str:
|
||||
"""The transport for ``SystemdServicesMixin``: the exec path, as root.
|
||||
|
||||
*privileged* needs nothing more on a node the driver reaches as root, and
|
||||
the exec path keeps its own timeout.
|
||||
"""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def get_available_updates(self) -> list[_JsonDict]:
|
||||
"""Return the node's upgradable packages, with origin and security status.
|
||||
|
||||
``apt list --upgradable`` over the exec path names each candidate's suite
|
||||
(``trixie-security``); the APT API names only an Origin ("Debian",
|
||||
"Proxmox") and is the fallback, with the security status unknown.
|
||||
|
||||
:raises Exception: when neither answers -- never an empty list for
|
||||
"could not read".
|
||||
"""
|
||||
updates: list[_JsonDict]
|
||||
try:
|
||||
raw = self._exec_ssh_command(APT_UPGRADABLE_COMMAND) or ""
|
||||
updates = [dict(u) for u in parse_apt_upgradable(raw)]
|
||||
except ValueError as exc:
|
||||
logger.debug("apt list over the exec path failed, using the API: %s", exc)
|
||||
updates = self._updates_from_api()
|
||||
return sorted(updates, key=lambda u: u["name"])
|
||||
|
||||
def _updates_from_api(self) -> list[_JsonDict]:
|
||||
return [
|
||||
{
|
||||
"name": upd["Package"],
|
||||
"current_version": upd.get("OldVersion", ""),
|
||||
"new_version": upd.get("Version", ""),
|
||||
"origin": upd.get("Origin"),
|
||||
"security": None,
|
||||
}
|
||||
for upd in self._node_api().apt.update.get()
|
||||
if upd.get("Package")
|
||||
]
|
||||
|
||||
def refresh_available_updates(self) -> _JsonDict:
|
||||
"""Resynchronise the node's package index (``POST nodes/{n}/apt/update``)."""
|
||||
try:
|
||||
task = self._node_api().apt.update.post()
|
||||
except Exception as exc:
|
||||
return {"success": False, "output": str(exc)}
|
||||
return {"success": True, "output": f"Package index refresh started ({task})"}
|
||||
|
||||
def _run_host_status_command(self, command: str) -> str:
|
||||
"""The transport for ``HostStatusMixin.get_host_status``: the exec path."""
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def apply_updates(self, packages: list[str]) -> _JsonDict:
|
||||
"""Upgrade the given packages via ``apt-get install`` over SSH."""
|
||||
for pkg in packages:
|
||||
if not re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
|
||||
raise ValueError(f"Invalid package name: {pkg!r}")
|
||||
pkg_args = " ".join(packages)
|
||||
output, status = self._rc(
|
||||
f"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y {pkg_args}"
|
||||
)
|
||||
if status == 0:
|
||||
return {"success": True, "output": output}
|
||||
error = (
|
||||
f"apt-get exited with status {status}"
|
||||
if status >= 0
|
||||
else "apt-get's exit status could not be read"
|
||||
)
|
||||
return {"success": False, "output": output, "error": error}
|
||||
|
||||
def _rc(self, command: str) -> tuple[str, int]:
|
||||
"""Run *command* and return its output and exit status (-1 when unknown)."""
|
||||
out = self._exec_ssh_command(f"{{ {command}; }} 2>&1; echo __PVE_RC=$?")
|
||||
text, _, tail = out.rpartition("__PVE_RC=")
|
||||
try:
|
||||
return text.strip(), int(tail.strip())
|
||||
except ValueError:
|
||||
return out.strip(), -1
|
||||
|
||||
def _step(self, command: str, done: str) -> FixStepOutcomeDict:
|
||||
output, status = self._rc(command)
|
||||
return {"ok": status == 0, "output": done if status == 0 else output[-300:]}
|
||||
|
||||
def _run_apt_command(self, command: str) -> str:
|
||||
return str(self._exec_ssh_command(command))
|
||||
|
||||
def _run_apt_root_command(self, command: str, done: str) -> FixStepOutcomeDict:
|
||||
return self._step(command, done)
|
||||
|
||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
return self._write_root_file(path, content)
|
||||
|
||||
def _allow_sources(
|
||||
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
|
||||
sources or no ufw -- pve-firewall's rules are the operator's. Each rule ufw adds
|
||||
is recorded under *purpose* (napalm-device-types ``opened_ports``,
|
||||
NetOrk/netork#2693); one ufw had is not."""
|
||||
sources = [str(ipaddress.ip_network(s.strip(), strict=False)) for s in allowed]
|
||||
if not sources:
|
||||
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
||||
if self._rc("command -v ufw")[1] != 0:
|
||||
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
|
||||
rules = " && ".join(ufw_allow_recorded_command(s, port, proto, purpose) for s in sources)
|
||||
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
|
||||
|
||||
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict:
|
||||
"""Remove the ufw rules recorded under *purpose*, whatever port they opened, and
|
||||
nothing else; report what ufw has left for *proto*/*port*. Not ``ok`` where
|
||||
the record may not be trusted -- nothing is removed then -- or a rule would not
|
||||
go, which stays in the record."""
|
||||
read, status = self._rc(read_opened_ports_command())
|
||||
if status != 0:
|
||||
return {"ok": False, "output": f"reading {OPENED_PORTS_RECORD}: {read[-300:]}"}
|
||||
record = parse_opened_ports_record(read)
|
||||
if record["problem"]:
|
||||
return {"ok": False, "output": record["problem"]}
|
||||
done = revoke_recorded_rules(record, purpose, self._remove_recorded_rule)
|
||||
failed = done["failed"]
|
||||
if done["removed"]:
|
||||
written = self._write_root_file(OPENED_PORTS_RECORD, done["record"])
|
||||
if not written["ok"]:
|
||||
failed.append(f"writing {OPENED_PORTS_RECORD}: {written['output']}")
|
||||
left = 0
|
||||
if self._rc("command -v ufw")[1] == 0:
|
||||
counted, _ = self._rc(
|
||||
f"LC_ALL=C ufw show added"
|
||||
f" | grep -cE '(port {port} proto {proto}| {port}/{proto})( |$)'"
|
||||
)
|
||||
last = counted.strip().splitlines()[-1:] or ["0"]
|
||||
left = int(last[0]) if last[0].isdigit() else 0
|
||||
output = revoked_output(
|
||||
done["removed"], unknown=record["unknown"], left=left, proto=proto, port=port
|
||||
)
|
||||
if failed:
|
||||
output = f"{output}; not removed: {'; '.join(failed)}"
|
||||
return {"ok": not failed, "output": output}
|
||||
|
||||
def _remove_recorded_rule(self, rule: OpenedRuleDict) -> FixStepOutcomeDict:
|
||||
if rule["backend"] != "ufw":
|
||||
return {"ok": False, "output": f"a {rule['backend']} rule; a node's rules are ufw's"}
|
||||
return self._step(ufw_delete_command(rule), "")
|
||||
|
||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
||||
encoded = base64.b64encode(content.encode()).decode()
|
||||
# No ``exit`` here: it would end the shell before ``_rc`` reads the status.
|
||||
return self._step(
|
||||
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
|
||||
f'install -m 644 -o root -g root "$t" {shlex.quote(path)}; '
|
||||
's=$?; rm -f "$t"; [ "$s" -eq 0 ]',
|
||||
f"wrote {path}",
|
||||
)
|
||||
|
||||
def install_package(self, name: str, version: str = "") -> None:
|
||||
"""apt-get install *name* (``PackageManagementMixin``); raises when apt fails."""
|
||||
if not _PACKAGE_NAME.match(name) or (version and not _PACKAGE_NAME.match(version)):
|
||||
raise ValueError(f"not a package name: {name!r}")
|
||||
target = f"{name}={version}" if version else name
|
||||
output, status = self._rc(f"DEBIAN_FRONTEND=noninteractive apt-get install -y {target}")
|
||||
if status != 0:
|
||||
raise RuntimeError(f"apt-get install {target} failed: {output[-300:]}")
|
||||
|
||||
def get_management_peer(self) -> str | None:
|
||||
"""The address the node sees the SSH connection come from (``SSH_CONNECTION``)."""
|
||||
out = self._exec_ssh_command('printf "%s\\n" "$SSH_CONNECTION"').split()
|
||||
try:
|
||||
return str(ipaddress.ip_address(out[0])) if out else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def reboot_host(self) -> None:
|
||||
"""Restart the node through the API (no SSH involved)."""
|
||||
try:
|
||||
self._node_api().status.post(command="reboot")
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Reboot of node {self._node_name!r} refused: {exc}") from exc
|
||||
|
||||
def shutdown_host(self) -> None:
|
||||
"""Shut the node down through the API; on PVE its guests stop as on any shutdown."""
|
||||
try:
|
||||
self._node_api().status.post(command="shutdown")
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Shutdown of node {self._node_name!r} refused: {exc}") from exc
|
||||
|
||||
|
||||
def parse_dpkg_line(line: str, source: str) -> _JsonDict | None:
|
||||
"""One installed package from a line of the ``dpkg-query`` format above, or
|
||||
None for a line that is not an installed package."""
|
||||
parts = line.strip().split("\t")
|
||||
if len(parts) < 2 or not parts[0]:
|
||||
return None
|
||||
name, version = parts[0], parts[1]
|
||||
status = parts[2] if len(parts) > 2 else "installed"
|
||||
if status != "installed":
|
||||
return None
|
||||
size_kb, source_package_field, source_version_field = (parts[3:] + ["", "", ""])[:3]
|
||||
# Debian source package (differs from the binary for split packages,
|
||||
# e.g. openssh-server → openssh). Needed for accurate OSV matching.
|
||||
source_package = source_package_field or name
|
||||
# And its version, which is a different number from this package's.
|
||||
#
|
||||
# OSV states Debian ranges in *source* versions, so a consumer given
|
||||
# the source package and only the binary version compares two
|
||||
# unrelated numbers: libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while
|
||||
# its source, samba, is 2:4.22.11+dfsg-…. Reporting the source
|
||||
# without its version is worse than reporting neither, because it
|
||||
# looks usable. Every package on all three Proxmox nodes was in that
|
||||
# state — the format string never asked for the field.
|
||||
#
|
||||
# dpkg leaves it empty when it equals `Version`, and so does an
|
||||
# older dpkg that does not know the field at all.
|
||||
source_version = source_version_field or version
|
||||
return {
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": int(size_kb) * 1024 if size_kb.isdigit() else 0,
|
||||
"source": source,
|
||||
"source_package": source_package,
|
||||
"source_version": source_version,
|
||||
}
|
||||
@@ -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}"
|
||||
@@ -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:
|
||||
|
||||
@@ -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: ...
|
||||
@@ -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
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
@@ -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],
|
||||
}
|
||||
@@ -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
|
||||
@@ -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()]
|
||||
Whitespace-only changes.
@@ -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():
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""get_running_backups() for Proxmox VE and Proxmox Backup Server.
|
||||
|
||||
What a restart would abort (napalm-device-types' ``RunningBackupsMixin``):
|
||||
|
||||
- **PVE:** the node's active vzdump tasks (``GET /nodes/<node>/tasks?source=active&
|
||||
typefilter=vzdump``) and the guests on the node locked for their backup
|
||||
(``GET /cluster/resources?type=vm``, ``lock: backup``). A task started for one
|
||||
guest names it in its id; a job's task does not, and the guests it is taking now
|
||||
are the locked ones. A guest locked without a task -- the list can lag behind,
|
||||
a lock can outlive its task -- is listed on its own: its restart waits too.
|
||||
- **PBS:** the running tasks that are a backup or one of the server's jobs
|
||||
(``GET /nodes/localhost/tasks?running=1``). A restore or housekeeping is not.
|
||||
|
||||
PVE does not tell which scheduled job started a vzdump task, so ``job`` is None
|
||||
there. A failed read raises: an empty list would say nothing runs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import RunningBackupDict, RunningBackupKind, RunningBackupsMixin
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: PBS worker types that are a backup or one of a backup server's jobs.
|
||||
_PBS_KINDS: dict[str, RunningBackupKind] = {
|
||||
"backup": "backup",
|
||||
"sync": "sync",
|
||||
"syncjob": "sync",
|
||||
"verify": "verify",
|
||||
"verificationjob": "verify",
|
||||
"verify_group": "verify",
|
||||
"verify_snapshot": "verify",
|
||||
"garbage_collection": "gc",
|
||||
"prune": "prune",
|
||||
"prunejob": "prune",
|
||||
"tape-backup": "tape",
|
||||
"tape-backup-job": "tape",
|
||||
}
|
||||
|
||||
|
||||
def _since(task: _JsonDict) -> int | None:
|
||||
value = task.get("starttime")
|
||||
return int(value) if isinstance(value, int | float) and value else None
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
return str(value) if value not in (None, "") else None
|
||||
|
||||
|
||||
class ProxmoxRunningBackupsMixin(RunningBackupsMixin):
|
||||
"""PVE: the node's vzdump tasks and the guests locked for their backup."""
|
||||
|
||||
_api: Any
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the base's, declared for type checkers
|
||||
|
||||
def _node_api(self) -> Any: ...
|
||||
|
||||
def _locked_guests(self) -> list[str]:
|
||||
"""The guests on this node locked for their backup, in the API's order."""
|
||||
return [
|
||||
str(guest["vmid"])
|
||||
for guest in self._api.cluster.resources.get(type="vm") or []
|
||||
if guest.get("node") == self._node_name and guest.get("lock") == "backup"
|
||||
]
|
||||
|
||||
def _vzdump_tasks(self) -> list[_JsonDict]:
|
||||
tasks = self._node_api().tasks.get(source="active", typefilter="vzdump") or []
|
||||
return [t for t in tasks if t.get("type") == "vzdump"]
|
||||
|
||||
def get_running_backups(self) -> list[RunningBackupDict]:
|
||||
tasks = self._vzdump_tasks()
|
||||
named = {str(t["id"]) for t in tasks if t.get("id")}
|
||||
unnamed = [g for g in self._locked_guests() if g not in named]
|
||||
found = [_vzdump(task, unnamed) for task in tasks]
|
||||
if all(t.get("id") for t in tasks):
|
||||
found += [_locked(guest) for guest in unnamed]
|
||||
return found
|
||||
|
||||
|
||||
def _vzdump(task: _JsonDict, unnamed: list[str]) -> RunningBackupDict:
|
||||
"""A vzdump task: its own guest, or -- a job's task -- the guests locked now."""
|
||||
guest = _text(task.get("id"))
|
||||
return {
|
||||
"kind": "backup",
|
||||
"job": None,
|
||||
"task": _text(task.get("upid")),
|
||||
"guests": [guest] if guest else list(unnamed),
|
||||
"since": _since(task),
|
||||
}
|
||||
|
||||
|
||||
def _locked(guest: str) -> RunningBackupDict:
|
||||
"""A guest locked for its backup without a task that takes it."""
|
||||
return {"kind": "backup", "job": None, "task": None, "guests": [guest], "since": None}
|
||||
|
||||
|
||||
class PbsRunningBackupsMixin(RunningBackupsMixin):
|
||||
"""PBS: the running backup, sync, verify, gc, prune and tape tasks."""
|
||||
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the backup-server mixin's, for type checkers
|
||||
|
||||
def _pbs(self, method: str, path: str, **params: Any) -> Any: ...
|
||||
|
||||
def get_running_backups(self) -> list[RunningBackupDict]:
|
||||
tasks = self._pbs("get", f"nodes/{self._node_name}/tasks", running=1) or []
|
||||
found: list[RunningBackupDict] = []
|
||||
for task in tasks:
|
||||
kind = _PBS_KINDS.get(str(task.get("worker_type") or ""))
|
||||
if kind is None:
|
||||
continue
|
||||
found.append(
|
||||
{
|
||||
"kind": kind,
|
||||
"job": _text(task.get("worker_id")),
|
||||
"task": _text(task.get("upid")),
|
||||
"guests": [],
|
||||
"since": _since(task),
|
||||
}
|
||||
)
|
||||
return found
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Scheduled jobs of a Proxmox VE node or a Proxmox Backup Server (#56).
|
||||
|
||||
Both are Debian hosts: napalm-device-types' ``PosixScheduledJobsMixin`` reads
|
||||
cron, run-parts, anacron and systemd timers over ``run_command`` as root, and
|
||||
switches, runs and writes them. What this module adds is which of them Proxmox
|
||||
itself ships -- ``platform`` -- and that a line in a file the cluster file
|
||||
system holds is only run.
|
||||
|
||||
Not here: Proxmox VE's backup jobs (``/cluster/backup``) and replication, and a
|
||||
backup server's verify, prune, sync and garbage collection jobs. Proxmox runs
|
||||
those in its own daemons, not from cron or a timer, and the backup features
|
||||
(``get_clusters``, ``get_backup_jobs``) keep them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from napalm_device_types import PosixScheduledJobsMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types._scheduled_reading import Reading
|
||||
|
||||
_UNITS = ("/usr/lib/systemd/system", "/lib/systemd/system")
|
||||
|
||||
#: What Proxmox VE ships: ``pve-daily-update.timer`` (pve-manager), ``pvesr.timer``
|
||||
#: (replication before Proxmox VE 7) and ``/etc/cron.d/vzdump``, the backup schedule of
|
||||
#: releases before ``pvescheduler``, a link to ``/etc/pve/vzdump.cron``.
|
||||
PVE_PLATFORM_SOURCES = (
|
||||
*(f"{d}/pve-*" for d in _UNITS),
|
||||
*(f"{d}/pvesr.timer" for d in _UNITS),
|
||||
"/etc/cron.d/vzdump",
|
||||
)
|
||||
|
||||
#: What a Proxmox Backup Server ships: ``proxmox-backup-daily-update.timer``.
|
||||
PBS_PLATFORM_SOURCES = tuple(f"{d}/proxmox-backup*" for d in _UNITS)
|
||||
|
||||
|
||||
class ProxmoxScheduledJobsMixin(PosixScheduledJobsMixin):
|
||||
"""Scheduled jobs of a Proxmox host; a driver sets ``PLATFORM_SOURCES``."""
|
||||
|
||||
#: Sources a job is only run from: links into ``/etc/pve``, the cluster file system
|
||||
#: (pmxcfs), where a switch's ``install`` with a mode and owner is not safe.
|
||||
RUN_ONLY_SOURCES: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
def _sj_read(self) -> Reading:
|
||||
reading = super()._sj_read()
|
||||
for job in reading.jobs:
|
||||
if job["source"] in self.RUN_ONLY_SOURCES:
|
||||
job["actions"] = [a for a in job["actions"] if a == "run"] # type: ignore[attr-defined]
|
||||
return reading
|
||||
+16
-12
@@ -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()
|
||||
|
||||
+206
-416
@@ -12,22 +12,119 @@
|
||||
# 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
|
||||
import shlex
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import SNMP_PURPOSE
|
||||
|
||||
from napalm_proxmox 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."""
|
||||
@@ -81,52 +178,12 @@ class ProxmoxSystemMixin:
|
||||
return env
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# get_ntp_servers / get_ntp_stats
|
||||
# get_ntp_stats (get_ntp_servers: time_sync.ProxmoxTimeSyncMixin)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, _JsonDict]:
|
||||
"""Return configured NTP servers."""
|
||||
ntp = self._get_node_ntp()
|
||||
servers: dict[str, _JsonDict] = {}
|
||||
# Proxmox reports a comma-separated or space-separated server list
|
||||
raw = ntp.get("server", "") or ntp.get("servers", "")
|
||||
for srv in re.split(r"[\s,]+", raw):
|
||||
srv = srv.strip()
|
||||
if srv:
|
||||
servers[srv] = {}
|
||||
return servers
|
||||
|
||||
def get_ntp_stats(self) -> list[_JsonDict]:
|
||||
"""Return NTP synchronisation statistics from chronyc/ntpq output."""
|
||||
raw = self._exec_ssh_command(
|
||||
"chronyc -n tracking 2>/dev/null || ntpq -pn 2>/dev/null || true"
|
||||
)
|
||||
stats: list[_JsonDict] = []
|
||||
for line in raw.splitlines():
|
||||
line = line.strip()
|
||||
# ntpq -pn format: *remote refid st t when poll reach delay offset jitter
|
||||
m = re.match(
|
||||
r"^([\*\+\-\s])([\d.]+)\s+([\d.]+)\s+(\d+)\s+\S+\s+(\S+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+([-\d.]+)\s+([\d.]+)",
|
||||
line,
|
||||
)
|
||||
if m:
|
||||
synced = m.group(1).strip() == "*"
|
||||
stats.append(
|
||||
{
|
||||
"remote": m.group(2),
|
||||
"referenceid": m.group(3),
|
||||
"synchronized": synced,
|
||||
"stratum": int(m.group(4)),
|
||||
"type": "",
|
||||
"when": m.group(5),
|
||||
"hostpoll": int(m.group(6)),
|
||||
"reachability": int(m.group(7)),
|
||||
"delay": float(m.group(8)),
|
||||
"offset": float(m.group(9)),
|
||||
"jitter": float(m.group(10)),
|
||||
}
|
||||
)
|
||||
return stats
|
||||
"""Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing."""
|
||||
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND))
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# get_snmp_information
|
||||
@@ -138,9 +195,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,247 +230,76 @@ class ProxmoxSystemMixin:
|
||||
def get_users(self) -> dict[str, _JsonDict]:
|
||||
"""Return users configured on the Proxmox node.
|
||||
|
||||
Reads from both the Proxmox access/users API and local /etc/passwd.
|
||||
Proxmox's own users (``/access/users``) at level 15 when they hold the
|
||||
Administrator role on the whole datacenter (``/``), directly or through
|
||||
a group, 1 otherwise; ``root@pam`` is always 15. Then the node's login
|
||||
accounts from the passwd database: root (15) and regular users
|
||||
(uid 1000 and up, without ``nobody``) at 0; system accounts are left out.
|
||||
"""
|
||||
result: dict[str, _JsonDict] = {}
|
||||
try:
|
||||
pve_users = self._api.access.users.get() or [] # type: ignore[union-attr]
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to fetch Proxmox users: %s", exc)
|
||||
pve_users = []
|
||||
|
||||
for user in pve_users:
|
||||
admins, admin_groups = self._pve_administrators()
|
||||
for user in self._pve_users():
|
||||
uid = user.get("userid", "")
|
||||
if not uid:
|
||||
continue
|
||||
# Proxmox roles: Administrator -> 15, otherwise 1
|
||||
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)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 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
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -423,7 +307,8 @@ class ProxmoxSystemMixin:
|
||||
def get_snmp_config(self):
|
||||
"""Return SNMP agent config if snmpd is installed and running on the node.
|
||||
|
||||
Uses _exec_ssh_command (Proxmox API exec or SSH) to inspect the node.
|
||||
Uses _exec_ssh_command (the node's SSH session) to inspect the node;
|
||||
raises when the node cannot be reached there.
|
||||
Returns a SNMPConfigDict or None.
|
||||
"""
|
||||
try:
|
||||
@@ -442,7 +327,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()
|
||||
@@ -460,131 +346,44 @@ 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:
|
||||
return dict(
|
||||
self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE)
|
||||
)
|
||||
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"
|
||||
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"[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"
|
||||
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"
|
||||
)
|
||||
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"
|
||||
if status != 1:
|
||||
raise CommandErrorException(
|
||||
"set_hostname refused: could not tell whether the node is part of a cluster"
|
||||
)
|
||||
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 set_hostname(self, new_hostname: str) -> None:
|
||||
"""Set the system hostname on the Proxmox node.
|
||||
@@ -603,16 +402,16 @@ class ProxmoxSystemMixin:
|
||||
7. Proxmox node TLS certificate — regenerated via
|
||||
``pvenode cert create --overwrite``.
|
||||
|
||||
**Important**: the Proxmox *node name* (shown in the web UI and stored
|
||||
in ``/etc/pve/nodes/<name>/``) only changes after a full reboot.
|
||||
Until then the web UI still shows the old node name, but the OS-level
|
||||
hostname and the SSL certificate already reflect the new value.
|
||||
The Proxmox *node name* (web UI, ``/etc/pve/nodes/<name>/``) only
|
||||
changes after a reboot. Accepts a bare hostname or an FQDN.
|
||||
|
||||
Accepts a bare hostname (``pve-see``) or an FQDN
|
||||
(``pve-see.see.local``).
|
||||
Raises CommandErrorException, before changing anything, on a cluster
|
||||
member (a corosync.conf exists): its rename is the cluster's procedure.
|
||||
"""
|
||||
import base64 as _b64
|
||||
|
||||
self._refuse_clustered_node()
|
||||
|
||||
if "." in new_hostname:
|
||||
short_hostname, domain = new_hostname.split(".", 1)
|
||||
fqdn = new_hostname
|
||||
@@ -622,9 +421,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()
|
||||
@@ -635,40 +436,27 @@ class ProxmoxSystemMixin:
|
||||
# write back via base64 to avoid shell-escaping issues.
|
||||
if old_short and old_short != short_hostname:
|
||||
hosts_raw = self._exec_ssh_command("cat /etc/hosts 2>/dev/null")
|
||||
# Replace whole-word occurrences of the old short hostname.
|
||||
# Both "hostname" and "hostname.domain" forms are covered because
|
||||
# the new value is the full fqdn when a domain was given.
|
||||
import re as _re
|
||||
new_replace = fqdn if domain else short_hostname
|
||||
hosts_new = _re.sub(
|
||||
r"\b" + _re.escape(old_short) + r"\b",
|
||||
new_replace,
|
||||
hosts_raw,
|
||||
)
|
||||
hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain)
|
||||
hosts_b64 = _b64.b64encode(hosts_new.encode()).decode()
|
||||
self._exec_ssh_command(
|
||||
f"echo {hosts_b64} | base64 -d > /tmp/_netork_hosts"
|
||||
f" && mv /tmp/_netork_hosts /etc/hosts"
|
||||
f" && chmod 644 /etc/hosts"
|
||||
f't=$(mktemp /etc/.hosts.XXXXXX) && echo {hosts_b64} | base64 -d > "$t"'
|
||||
' && chmod 644 "$t" && mv "$t" /etc/hosts || { rm -f "$t"; false; }'
|
||||
)
|
||||
|
||||
# ── 3. /etc/mailname ─────────────────────────────────────────────
|
||||
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 ─────────────────────────────────────────
|
||||
postfix = shlex.quote(f"myhostname = {fqdn}")
|
||||
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 {postfix} || true"
|
||||
)
|
||||
|
||||
# ── 5. Apply hostname at runtime ─────────────────────────────────
|
||||
self._exec_ssh_command(f"hostname '{short_hostname}'")
|
||||
self._exec_ssh_command(f"hostname {shlex.quote(short_hostname)}")
|
||||
|
||||
# ── 6. Migrate /etc/pve/nodes/<old> → /etc/pve/nodes/<new> ──────
|
||||
# Proxmox stores VM and CT configs under /etc/pve/nodes/<nodename>/.
|
||||
@@ -677,16 +465,15 @@ class ProxmoxSystemMixin:
|
||||
# Without this step the node boots under the new hostname, finds an
|
||||
# empty /etc/pve/nodes/<new>/ and all VMs appear missing.
|
||||
if old_short and old_short != short_hostname:
|
||||
pve_old = f"/etc/pve/nodes/{old_short}"
|
||||
pve_new = f"/etc/pve/nodes/{short_hostname}"
|
||||
pve_old = shlex.quote(f"/etc/pve/nodes/{old_short}")
|
||||
pve_new = shlex.quote(f"/etc/pve/nodes/{short_hostname}")
|
||||
migrate_out = self._exec_ssh_command(
|
||||
f"if [ -d '{pve_old}' ] && [ ! -e '{pve_new}' ]; then"
|
||||
f" mv '{pve_old}' '{pve_new}'"
|
||||
f" && echo 'migrated {pve_old} -> {pve_new}';"
|
||||
f"elif [ -d '{pve_new}' ]; then"
|
||||
f"if [ -d {pve_old} ] && [ ! -e {pve_new} ]; then"
|
||||
f" mv {pve_old} {pve_new} && echo migrated {pve_old} '->' {pve_new};"
|
||||
f"elif [ -d {pve_new} ]; then"
|
||||
f" echo 'target already exists, skipping migration';"
|
||||
f"else"
|
||||
f" echo 'source {pve_old} not found, skipping migration';"
|
||||
f" echo source {pve_old} 'not found, skipping migration';"
|
||||
f"fi"
|
||||
)
|
||||
logger.info("Proxmox node dir migration: %s", migrate_out)
|
||||
@@ -707,7 +494,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,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -818,7 +607,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
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Time sync on a Proxmox VE node and a Proxmox Backup Server (``TimeSyncMixin``).
|
||||
|
||||
Neither API keeps time servers: ``/nodes/{node}/time`` knows only the zone, and
|
||||
both products run chrony on Debian. So the servers are
|
||||
:class:`~napalm_device_types.PosixTimeSyncMixin`'s, over the driver's SSH session
|
||||
(``run_command``, root): read from chrony's configuration, DHCP's apart, written to
|
||||
``/etc/chrony/sources.d/netork.sources`` with every other configured source commented
|
||||
out; the DHCP client's ``sourcedir`` stays.
|
||||
|
||||
The zone is read with them, from the host (``timedatectl``, the zone the node's
|
||||
clock really runs in), and the API's ``GET /nodes/{node}/time`` answers only when
|
||||
the host names none. It is written through ``PUT /nodes/{node}/time``, not
|
||||
``timedatectl set-timezone``: Proxmox's own call validates the name and keeps
|
||||
``/etc/timezone``, which its web UI and API show, in step with ``/etc/localtime``.
|
||||
The token needs ``Sys.Modify`` for it (PVE on ``/nodes/{node}``, PBS on
|
||||
``/system/time``).
|
||||
|
||||
One device is one node: in a PVE cluster every node has its own clock, and only
|
||||
the node this connection resolved is read and written.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm_device_types import TIME_SYNC_VALUES, PosixTimeSyncMixin, TimeSyncDict
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
|
||||
class ProxmoxTimeSyncMixin(PosixTimeSyncMixin):
|
||||
"""Servers through chrony over SSH, the zone through the node's API."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
|
||||
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||
|
||||
def _node_api(self) -> Any: ...
|
||||
def _get_node_time(self) -> _JsonDict: ...
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""The node's time sources, zone and client: one round trip over SSH, and the
|
||||
API's zone only where the host names none.
|
||||
|
||||
:raises ValueError: when the reading came back cut short.
|
||||
:raises ConnectionException: when the node's shell could not be reached.
|
||||
"""
|
||||
found = super().get_time_sync()
|
||||
if found["timezone"] is None:
|
||||
found["timezone"] = self._get_node_time().get("timezone") or None
|
||||
return found
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, _JsonDict]:
|
||||
"""NAPALM's shape of the servers ``get_time_sync`` reads, in chrony's order."""
|
||||
return {server: {} for server in super().get_time_sync()["ntp_servers"]}
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
path = f"PUT /nodes/{self._node_name}/time"
|
||||
try:
|
||||
self._node_api().time.put(timezone=zone)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "output": f"{path}: {exc}"}
|
||||
return {"ok": True, "output": f"time zone set to {zone} ({path})"}
|
||||
@@ -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]
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
``power_vm`` stays for callers that already use it; these are what a
|
||||
hypervisor-neutral caller talks to. They raise instead of returning a
|
||||
``{"success": ...}`` dict, and block until Proxmox reports the task finished.
|
||||
``{"success": ...}`` dict, and block until Proxmox reports the task finished —
|
||||
except ``begin_stop_vm`` and ``shutdown_host``, which return once Proxmox took
|
||||
the request (``VmStopRequestMixin``, ``HostShutdownMixin``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +19,8 @@ from napalm_device_types.models import (
|
||||
VMPassthroughDict,
|
||||
)
|
||||
|
||||
from napalm_proxmox.vm_mixin import qemu_status
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
_POWER_TIMEOUT = 120
|
||||
@@ -162,6 +166,14 @@ class ProxmoxVMContractMixin:
|
||||
def stop_vm(self, name: str, force: bool = False) -> None:
|
||||
self._run_power(*self._resolve_vm(name), "stop" if force else "shutdown")
|
||||
|
||||
def begin_stop_vm(self, name: str) -> None:
|
||||
"""Ask for the guest's clean shutdown; return once Proxmox accepted it."""
|
||||
vmid, vm_type = self._resolve_vm(name)
|
||||
try:
|
||||
self._guest_api(vmid, vm_type).status.shutdown.post()
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"shutdown of {vm_type} {vmid} refused: {exc}") from exc
|
||||
|
||||
def reboot_vm(self, name: str, force: bool = False) -> None:
|
||||
vmid, vm_type = self._resolve_vm(name)
|
||||
if not force:
|
||||
@@ -178,16 +190,28 @@ class ProxmoxVMContractMixin:
|
||||
raise RuntimeError(f"Proxmox cannot suspend container {vmid}")
|
||||
self._run_power(vmid, vm_type, "suspend")
|
||||
|
||||
def resume_vm(self, name: str) -> None:
|
||||
"""``status/resume`` for a paused QEMU guest (NetOrk/netork#2658).
|
||||
|
||||
A container is refused: this driver does not suspend one, PVE's container
|
||||
suspend is experimental (CRIU), and its listing does not tell a suspended
|
||||
container from another. A guest that is not paused is refused too: PVE would
|
||||
answer a running one with success and do nothing.
|
||||
"""
|
||||
vmid, vm_type = self._resolve_vm(name)
|
||||
if vm_type != "vm":
|
||||
raise RuntimeError(
|
||||
f"Proxmox cannot resume container {vmid}: only a paused VM can be resumed"
|
||||
)
|
||||
current = self._guest_api(vmid, vm_type).status.current.get() or {}
|
||||
state = qemu_status(current)
|
||||
if state != "paused":
|
||||
raise RuntimeError(f"Cannot resume VM {vmid}: it is not paused ({state})")
|
||||
self._run_power(vmid, vm_type, "resume")
|
||||
|
||||
def get_vm_config(self, name: str) -> VMConfigDict:
|
||||
vmid, vm_type = self._resolve_vm(name)
|
||||
cfg = self._guest_api(vmid, vm_type).config.get() or {}
|
||||
return parse_vm_config(str(vmid), vm_type, cfg)
|
||||
|
||||
# -- the node itself --------------------------------------------------------
|
||||
|
||||
def reboot_host(self) -> None:
|
||||
"""Restart this Proxmox node through the API (no SSH involved)."""
|
||||
try:
|
||||
self._node_api().status.post(command="reboot")
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Reboot of node {self._node_name!r} refused: {exc}") from exc
|
||||
@@ -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
|
||||
+40
-23
@@ -20,19 +20,29 @@ import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm_proxmox import utils
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: The QMP states of a guest whose QEMU process holds its memory but does not run it:
|
||||
#: paused (``status/suspend``, the GUI's Pause) and asleep in S3. ``status/resume``
|
||||
#: brings either back. PVE's ``status`` says ``running`` for both (NetOrk/netork#2658).
|
||||
PAUSED_QMP_STATES = ("paused", "suspended")
|
||||
|
||||
|
||||
def qemu_status(vm: _JsonDict) -> str:
|
||||
"""A QEMU guest's status as the contract names it: ``paused`` where PVE's full
|
||||
status (``qmpstatus``) says the running process does not execute the guest."""
|
||||
status = str(vm.get("status", "unknown"))
|
||||
if status == "running" and vm.get("qmpstatus") in PAUSED_QMP_STATES:
|
||||
return "paused"
|
||||
return status
|
||||
|
||||
|
||||
class ProxmoxVMMixin:
|
||||
"""Mixin providing VM and container NAPALM methods."""
|
||||
|
||||
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 +115,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
|
||||
@@ -219,7 +229,7 @@ class ProxmoxVMMixin:
|
||||
* vmid (str) - Proxmox VM/container ID, e.g. ``"100"``
|
||||
* name (str) - display name
|
||||
* type (str) - ``"vm"`` or ``"container"``
|
||||
* status (str) - ``"running"``, ``"stopped"``, etc.
|
||||
* status (str) - ``"running"``, ``"stopped"``, ``"paused"`` (``qemu_status``)
|
||||
* vcpus (int) - allocated vCPUs
|
||||
* memory (int) - configured RAM in megabytes
|
||||
* cpu_usage (float) - current CPU utilisation 0.0–1.0 (from last stats cycle)
|
||||
@@ -231,12 +241,12 @@ class ProxmoxVMMixin:
|
||||
"""
|
||||
result: list[_JsonDict] = []
|
||||
|
||||
# QEMU VMs
|
||||
# QEMU VMs; only the full status has ``qmpstatus``, which tells paused from running.
|
||||
try:
|
||||
for vm in (self._node_api().qemu.get() or []):
|
||||
for vm in self._node_api().qemu.get(full=1) or []:
|
||||
vmid = int(vm.get("vmid", 0))
|
||||
name = vm.get("name", f"vm-{vmid}")
|
||||
status = vm.get("status", "unknown")
|
||||
status = qemu_status(vm)
|
||||
cpu_usage = float(vm.get("cpu", 0.0) or 0.0)
|
||||
uptime = int(vm.get("uptime", 0) or 0)
|
||||
|
||||
@@ -256,7 +266,8 @@ class ProxmoxVMMixin:
|
||||
)
|
||||
|
||||
disks, onboot = self._get_vm_disk_and_boot(vmid, "qemu")
|
||||
result.append({
|
||||
result.append(
|
||||
{
|
||||
"vmid": str(vmid),
|
||||
"name": name,
|
||||
"type": "vm",
|
||||
@@ -273,13 +284,14 @@ class ProxmoxVMMixin:
|
||||
"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,7 +312,8 @@ class ProxmoxVMMixin:
|
||||
)
|
||||
|
||||
disks, onboot = self._get_vm_disk_and_boot(vmid, "lxc")
|
||||
result.append({
|
||||
result.append(
|
||||
{
|
||||
"vmid": str(vmid),
|
||||
"name": name,
|
||||
"type": "container",
|
||||
@@ -317,7 +330,8 @@ class ProxmoxVMMixin:
|
||||
"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 +342,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 +388,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 +397,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:
|
||||
|
||||
@@ -3,20 +3,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
import time
|
||||
import yaml
|
||||
from typing import TYPE_CHECKING, Any, Dict, List
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import quote
|
||||
|
||||
import yaml
|
||||
from napalm_device_types.models import (
|
||||
NetworkTargetDict,
|
||||
StorageTargetDict,
|
||||
VMProvisionResultDict,
|
||||
VMStatusDict,
|
||||
)
|
||||
from napalm_device_types.provisioning import (
|
||||
QEMU_GUEST_AGENTS,
|
||||
GuestAgents,
|
||||
VMProvisionIncomplete,
|
||||
network_config,
|
||||
split_compression,
|
||||
)
|
||||
|
||||
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
||||
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||
from napalm_proxmox.utils import cpu_flags
|
||||
from napalm_proxmox.vm_mixin import qemu_status
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
|
||||
@@ -70,81 +83,62 @@ _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).
|
||||
_GUEST_VM_SETTINGS: dict[str, dict[str, str]] = {
|
||||
"linux": {"ostype": "l26", "agent": "1"},
|
||||
"freebsd": {"ostype": "other", "agent": "1"},
|
||||
"openbsd": {"ostype": "other", "agent": "1,type=isa", "serial0": "socket"},
|
||||
}
|
||||
|
||||
# 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\-.+=_]")
|
||||
# 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})")
|
||||
|
||||
|
||||
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 _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")
|
||||
|
||||
# Build base config: model[=mac] + bridge
|
||||
mac = nic.get("mac")
|
||||
net_config = f"virtio={mac},bridge={bridge}" if mac else f"virtio,bridge={bridge}"
|
||||
|
||||
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
|
||||
# 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 _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:
|
||||
"""Mixin to add VM provisioning to ProxmoxDriver."""
|
||||
|
||||
#: Every guest QEMU's agent runs on; see _GUEST_VM_SETTINGS for the VM
|
||||
#: hardware each one needs.
|
||||
GUEST_AGENTS: GuestAgents = QEMU_GUEST_AGENTS
|
||||
|
||||
def _run_node_command(self, command: str, timeout: int) -> str:
|
||||
"""
|
||||
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()
|
||||
@@ -171,38 +165,26 @@ class ProxmoxVMProvisionMixin:
|
||||
once (covers a corrupted/partial transfer or a stale same-keyed file)
|
||||
before raising.
|
||||
"""
|
||||
filename = image_url.rstrip("/").rsplit("/", 1)[-1]
|
||||
local_path = f"{_IMAGE_CACHE_DIR}/{_url_key(image_url)}-{filename}"
|
||||
|
||||
algo, expected = _split_checksum(image_checksum or "")
|
||||
local_path = f"{_IMAGE_CACHE_DIR}/{cache_name(image_url)}"
|
||||
algo, expected = split_checksum(image_checksum or "")
|
||||
|
||||
max_attempts = 2
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
exists = self._run_node_command(
|
||||
f"mkdir -p {_IMAGE_CACHE_DIR} && test -f {local_path} "
|
||||
f"&& echo EXISTS || echo MISSING",
|
||||
timeout=30,
|
||||
)
|
||||
if "EXISTS" not in exists:
|
||||
_logger.info(f"Downloading cloud image {image_url} -> {local_path}")
|
||||
self._run_node_command(
|
||||
f"wget -q -O {local_path}.tmp '{image_url}' "
|
||||
f"&& mv {local_path}.tmp {local_path}",
|
||||
timeout=timeout,
|
||||
)
|
||||
if not self._cached_on_node(local_path):
|
||||
self._fetch_image(image_url, local_path, timeout)
|
||||
|
||||
if not image_checksum:
|
||||
return local_path
|
||||
|
||||
actual = self._run_node_command(
|
||||
f"{algo}sum {local_path} | awk '{{print $1}}'", timeout=60
|
||||
f"{algo}sum {shlex.quote(local_path)} | awk '{{print $1}}'", timeout=60
|
||||
)
|
||||
if actual.lower() == expected.lower():
|
||||
return local_path
|
||||
|
||||
# Remove the bad file so the next attempt re-downloads instead of
|
||||
# reusing it.
|
||||
self._run_node_command(f"rm -f {local_path}", timeout=30)
|
||||
self._run_node_command(f"rm -f {shlex.quote(local_path)}", timeout=30)
|
||||
if attempt == max_attempts:
|
||||
raise RuntimeError(
|
||||
f"Checksum mismatch for {image_url}: expected {expected}, got {actual}"
|
||||
@@ -214,6 +196,87 @@ 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.
|
||||
|
||||
A packed image (FreeBSD ships .qcow2.xz) is unpacked on the node after
|
||||
its checksum, which covers the packed file, has been verified; only
|
||||
the unpacked file is kept. Proxmox's download-url unpacks ISOs only,
|
||||
so a packed image always comes this way.
|
||||
"""
|
||||
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}/{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} {shlex.quote(packed)} > {tmp} && mv {tmp} {shlex.quote(unpacked)} "
|
||||
f"&& rm -f {shlex.quote(packed)}",
|
||||
timeout=timeout,
|
||||
)
|
||||
return unpacked
|
||||
|
||||
def _write_snippet(self, storage_path: str, filename: str, content: str) -> None:
|
||||
"""Write a cloud-init snippet into *storage_path*/snippets on the node.
|
||||
|
||||
Proxmox's /storage/{s}/upload API only accepts content in
|
||||
{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 {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]]:
|
||||
"""``(mac, dhcp)`` per NIC, with the MAC Proxmox assigned where none was given."""
|
||||
config = self._node_api().qemu(vmid).config.get()
|
||||
macs = []
|
||||
for i, nic in enumerate(nics):
|
||||
match = _NIC_MAC.match(config.get(f"net{i}", ""))
|
||||
if not match:
|
||||
raise RuntimeError(f"VM {vmid} has no MAC address on net{i}")
|
||||
macs.append((match.group(1), nic.get("dhcp", i == 0)))
|
||||
return macs
|
||||
|
||||
def _find_import_storage(self) -> str | None:
|
||||
"""The first storage on this node that accepts content "import".
|
||||
|
||||
@@ -254,7 +317,7 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
params: dict[str, Any] = {"url": image_url, "content": "import", "filename": filename}
|
||||
if image_checksum:
|
||||
algo, expected = _split_checksum(image_checksum)
|
||||
algo, expected = split_checksum(image_checksum)
|
||||
params["checksum"] = expected
|
||||
params["checksum-algorithm"] = algo
|
||||
_logger.info(f"Downloading cloud image {image_url} into {volid}")
|
||||
@@ -276,10 +339,11 @@ class ProxmoxVMProvisionMixin:
|
||||
The path for nodes without an import storage, or for an image type
|
||||
Proxmox cannot import itself.
|
||||
"""
|
||||
local_path = self._download_cloud_image(image_url, image_checksum, timeout=download_timeout)
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -311,7 +375,7 @@ class ProxmoxVMProvisionMixin:
|
||||
verifies and copies the image itself — and over SSH otherwise.
|
||||
"""
|
||||
import_storage = self._find_import_storage()
|
||||
filename = _import_volume_name(image_url) if import_storage else None
|
||||
filename = import_volume_name(image_url) if import_storage else None
|
||||
if not import_storage or not filename:
|
||||
self._import_over_ssh(
|
||||
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
|
||||
@@ -375,9 +439,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:
|
||||
@@ -401,8 +465,7 @@ class ProxmoxVMProvisionMixin:
|
||||
return self._cpu_types_for(self._node_cpu_flags())
|
||||
|
||||
def _node_cpu_flags(self) -> set[str]:
|
||||
status = self._node_api().status.get() or {}
|
||||
return set(str((status.get("cpuinfo") or {}).get("flags", "")).split())
|
||||
return set(cpu_flags(self._node_api().status.get() or {}) or [])
|
||||
|
||||
@staticmethod
|
||||
def _cpu_types_for(node_flags: set[str]) -> list[VMCpuTypeDict]:
|
||||
@@ -477,6 +540,19 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
def _check_placement(self, guest_os: str, node: str | None) -> None:
|
||||
"""Refuse a guest this driver cannot provision, or a node other than its own."""
|
||||
if guest_os not in self.GUEST_AGENTS:
|
||||
raise ValueError(
|
||||
f"Cannot provision a {guest_os!r} guest; this driver provisions "
|
||||
f"{', '.join(sorted(self.GUEST_AGENTS))}"
|
||||
)
|
||||
if node is not None and node != self._node_name:
|
||||
raise ValueError(
|
||||
f"Cannot create a VM on node {node!r} through {self._node_name!r}; "
|
||||
f"connect to {node!r} itself"
|
||||
)
|
||||
|
||||
def create_vm_from_cloud_init(
|
||||
self,
|
||||
name: str,
|
||||
@@ -484,13 +560,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:
|
||||
@@ -524,6 +602,13 @@ class ProxmoxVMProvisionMixin:
|
||||
storage: storage pool for the root disk (None = auto-detect first
|
||||
enabled, node-available storage with content='images')
|
||||
cpu_type: CPU model from get_vm_cpu_types() (None = x86-64-v2-AES)
|
||||
guest_os: the OS in the image, a key of GUEST_AGENTS. It sets the
|
||||
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
|
||||
|
||||
@@ -531,13 +616,20 @@ 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)
|
||||
"""
|
||||
self._check_placement(guest_os, node)
|
||||
created: int | None = None # the VMID once the shell exists on the node
|
||||
try:
|
||||
_logger.info(f"Creating VM '{name}' from image {image_url}")
|
||||
_logger.info(f"Creating {guest_os} VM '{name}' from image {image_url}")
|
||||
cpu_model = self._resolve_cpu_type(cpu_type)
|
||||
|
||||
# Step 1: Get next VMID
|
||||
@@ -553,13 +645,13 @@ class ProxmoxVMProvisionMixin:
|
||||
memory=memory,
|
||||
cores=cpu,
|
||||
cpu=cpu_model,
|
||||
ostype="l26",
|
||||
scsihw="virtio-scsi-pci",
|
||||
# Without this, Proxmox never attaches the virtio-serial
|
||||
# channel the QEMU guest agent needs — get_vm_status's
|
||||
# agent queries (below) would have nothing to talk to.
|
||||
agent="1",
|
||||
# Includes agent: without it Proxmox never attaches the
|
||||
# channel the QEMU guest agent needs — get_vm_status's agent
|
||||
# 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()
|
||||
@@ -569,29 +661,7 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
# Step 4: Configure network interfaces (CPU/memory already set at shell creation)
|
||||
_logger.info(f"Configuring {len(nics)} NIC(s) for VM {vmid}")
|
||||
|
||||
config_args: Dict[str, Any] = {}
|
||||
|
||||
# Build NIC config strings generically
|
||||
for i, nic in enumerate(nics):
|
||||
bridge = nic.get("bridge")
|
||||
if not bridge:
|
||||
raise ValueError(f"NIC {i}: bridge is required")
|
||||
|
||||
# Build base config: model[=mac] + bridge
|
||||
mac = nic.get("mac")
|
||||
net_config = f"virtio={mac},bridge={bridge}" if mac else f"virtio,bridge={bridge}"
|
||||
|
||||
# Add VLAN configuration (access vs trunk)
|
||||
if "trunk_vlan_tags" in nic and nic["trunk_vlan_tags"]:
|
||||
vlan_list = ";".join(str(v) for v in nic["trunk_vlan_tags"])
|
||||
net_config += f",trunks={vlan_list}"
|
||||
elif "vlan_tag" in nic and nic["vlan_tag"] is not None:
|
||||
net_config += f",tag={nic['vlan_tag']}"
|
||||
|
||||
config_args[f"net{i}"] = net_config
|
||||
|
||||
self._node_api().qemu(vmid).config.post(**config_args)
|
||||
self._node_api().qemu(vmid).config.post(**_nic_config_args(nics))
|
||||
|
||||
# Step 5: Verify snippet storage exists
|
||||
# (enabled is absent-not-falsy, and node-scoping matters — see
|
||||
@@ -621,20 +691,20 @@ class ProxmoxVMProvisionMixin:
|
||||
)
|
||||
|
||||
filename = f"{vmid}-user-data.yaml"
|
||||
_logger.debug(f"Writing Cloud-Init snippet {filename} to {snippet_storage}")
|
||||
|
||||
# Proxmox's /storage/{s}/upload API only accepts content in
|
||||
# {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 resolve the storage's
|
||||
# backing path and write the file over SSH instead.
|
||||
storage_path = self._get_storage_path(snippet_storage)
|
||||
encoded = base64.b64encode(user_data_yaml.encode("utf-8")).decode("ascii")
|
||||
self._run_node_command(
|
||||
f"mkdir -p {storage_path}/snippets && "
|
||||
f"echo {encoded} | base64 -d > {storage_path}/snippets/{filename}",
|
||||
timeout=30,
|
||||
self._write_snippet(storage_path, filename, user_data_yaml)
|
||||
cicustom = f"user={snippet_storage}:snippets/{filename}"
|
||||
|
||||
# Proxmox writes network-config v1, and FreeBSD's nuageinit fails
|
||||
# on it and then skips runcmd, which starts the guest agent. A
|
||||
# guest other than Linux gets the v2 every cloud-init reads.
|
||||
network = network_config(self._nic_macs(vmid, nics)) if guest_os != "linux" else None
|
||||
if network:
|
||||
network_filename = f"{vmid}-network-config.yaml"
|
||||
self._write_snippet(
|
||||
storage_path, network_filename, yaml.safe_dump(network, sort_keys=False)
|
||||
)
|
||||
cicustom += f",network={snippet_storage}:snippets/{network_filename}"
|
||||
|
||||
# Step 7: Configure Cloud-Init references and SSH keys
|
||||
_logger.info(f"Setting Cloud-Init config for VM {vmid}")
|
||||
@@ -648,7 +718,7 @@ class ProxmoxVMProvisionMixin:
|
||||
# this points at a snippets-only storage.
|
||||
"ide2": f"{image_storage}:cloudinit",
|
||||
"citype": "nocloud",
|
||||
"cicustom": f"user={snippet_storage}:snippets/{filename}",
|
||||
"cicustom": cicustom,
|
||||
}
|
||||
|
||||
# Configure DHCP for NICs where enabled (default True for index 0, False otherwise)
|
||||
@@ -658,9 +728,9 @@ class ProxmoxVMProvisionMixin:
|
||||
cloud_init_args[f"ipconfig{i}"] = "ip=dhcp"
|
||||
|
||||
if ssh_public_keys:
|
||||
# URL-encode SSH keys for Proxmox API
|
||||
sshkeys = ";".join(ssh_public_keys)
|
||||
cloud_init_args["sshkeys"] = quote(sshkeys)
|
||||
# One key per line, URL-encoded without exception: Proxmox's
|
||||
# "urlencoded" format refuses an unescaped "/" or "+".
|
||||
cloud_init_args["sshkeys"] = quote("\n".join(ssh_public_keys), safe="")
|
||||
|
||||
self._node_api().qemu(vmid).config.post(**cloud_init_args)
|
||||
|
||||
@@ -699,7 +769,10 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
except Exception as e:
|
||||
_logger.exception(f"Failed to create VM '{name}': {e}")
|
||||
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,
|
||||
@@ -736,35 +809,21 @@ class ProxmoxVMProvisionMixin:
|
||||
except Exception as e:
|
||||
_logger.debug(f"VM {vmid} stop failed (may already be stopped): {e}")
|
||||
|
||||
# The snippets have to be known before the delete: afterwards the
|
||||
# VM's config is gone (napalm-proxmox#15).
|
||||
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)
|
||||
try:
|
||||
config = self._node_api().qemu(vmid_int).config.get()
|
||||
cicustom = config.get("cicustom", "")
|
||||
if "snippets/" in cicustom:
|
||||
parts = cicustom.split("=")
|
||||
if len(parts) >= 2:
|
||||
snippet_ref = parts[1] # e.g. "snippets:snippets/101-user-data.yaml"
|
||||
storage, filepath = snippet_ref.split(":", 1)
|
||||
for storage, filepath in snippets:
|
||||
_logger.debug(f"Deleting snippet {filepath} from {storage}")
|
||||
try:
|
||||
self._node_api().storage(storage).content(filepath).delete()
|
||||
except Exception as e:
|
||||
_logger.warning(f"Failed to delete snippet {filepath}: {e}")
|
||||
except Exception as e:
|
||||
_logger.debug(f"Could not clean up snippets for VM {vmid}: {e}")
|
||||
|
||||
_logger.info(f"VM {vmid} destroyed successfully")
|
||||
|
||||
@@ -772,6 +831,39 @@ 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.
|
||||
|
||||
cicustom reads "user=local:snippets/101-user-data.yaml,network=...".
|
||||
Best-effort: a VM whose config cannot be read has none to clean up.
|
||||
"""
|
||||
try:
|
||||
cicustom = self._node_api().qemu(vmid).config.get().get("cicustom", "")
|
||||
except Exception as e:
|
||||
_logger.debug(f"Could not read the snippets of VM {vmid}: {e}")
|
||||
return []
|
||||
snippets = []
|
||||
for entry in cicustom.split(","):
|
||||
storage, _, path = entry.partition("=")[2].partition(":")
|
||||
if path.startswith("snippets/"):
|
||||
snippets.append((storage, path))
|
||||
return snippets
|
||||
|
||||
def get_vm_status(
|
||||
self,
|
||||
vmid: str,
|
||||
@@ -783,6 +875,11 @@ class ProxmoxVMProvisionMixin:
|
||||
"""
|
||||
Get the runtime status of a virtual machine.
|
||||
|
||||
The status is what ``GET /nodes/{node}/qemu/{vmid}/status/current`` says:
|
||||
``running``, ``stopped``, or ``paused`` where its ``qmpstatus`` is paused or
|
||||
suspended (``qemu_status``, as ``get_vms()`` lists it). Only a running VM's
|
||||
guest agent is asked for an address (NAPALM/napalm-proxmox#72).
|
||||
|
||||
Optionally waits for the guest-agent to report an IP address on the
|
||||
management NIC (net0), useful after provisioning.
|
||||
|
||||
@@ -794,112 +891,95 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
Returns:
|
||||
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
||||
(ip_address, hostname, mac_address only if VM is running and has network info)
|
||||
(ip_address, hostname, mac_address only if VM is running and has network
|
||||
info); {"status": "unknown"} when Proxmox gives no status for the vmid.
|
||||
|
||||
Raises:
|
||||
RuntimeError: VM doesn't exist or wait_for_ip times out
|
||||
RuntimeError: wait_for_ip times out, or the VM is not running while
|
||||
waiting (a stopped or paused VM reports no address)
|
||||
"""
|
||||
try:
|
||||
vmid_int = int(vmid)
|
||||
vm = self._node_api().qemu(int(vmid))
|
||||
_logger.debug(f"Getting status for VM {vmid}")
|
||||
|
||||
# VM must exist / be readable before we start polling.
|
||||
try:
|
||||
self._node_api().qemu(vmid_int).config.get()
|
||||
except Exception:
|
||||
# VM may not exist yet or config not readable
|
||||
# The VM must exist / be readable before we start polling.
|
||||
status = self._qemu_current_status(vm, vmid)
|
||||
if status is None:
|
||||
return {"status": "unknown"}
|
||||
|
||||
# Polling loop
|
||||
start_time = time.time()
|
||||
while True:
|
||||
elapsed = time.time() - start_time
|
||||
if wait_for_ip and elapsed > timeout:
|
||||
if status != "running":
|
||||
if wait_for_ip:
|
||||
raise RuntimeError(f"VM {vmid} is {status}: it reports no IP address")
|
||||
return {"status": status}
|
||||
if wait_for_ip and time.time() - start_time > timeout:
|
||||
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
||||
|
||||
try:
|
||||
# Query guest-agent network interfaces. Proxmox's REST path is
|
||||
# "network-get-interfaces" (hyphens) — it must be passed as a
|
||||
# resource id via __call__, not dotted attribute access (which
|
||||
# would silently build a non-existent "network_get_interfaces"
|
||||
# path and 404 on every poll).
|
||||
agent_info = (
|
||||
self._node_api().qemu(vmid_int).agent("network-get-interfaces").get()
|
||||
)
|
||||
interfaces = (agent_info or {}).get("result", [])
|
||||
|
||||
# The guest agent does not report interfaces in a fixed order —
|
||||
# "lo" commonly comes first. Skip it and take the first real
|
||||
# NIC that has an IPv4 address.
|
||||
for iface in interfaces:
|
||||
name = iface.get("name", "")
|
||||
if not name or name == "lo":
|
||||
continue
|
||||
for addr in iface.get("ip-addresses", []):
|
||||
if addr.get("ip-address-type") != "ipv4":
|
||||
continue
|
||||
ip_addr = addr.get("ip-address", "")
|
||||
if ip_addr:
|
||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||
return {
|
||||
"status": "running",
|
||||
"ip_address": ip_addr,
|
||||
"hostname": name,
|
||||
"mac_address": iface.get("hardware-address", ""),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
||||
|
||||
address = self._guest_agent_address(vm, vmid)
|
||||
if address is not None:
|
||||
return {"status": "running", **address}
|
||||
if not wait_for_ip:
|
||||
# Return immediate status without IP
|
||||
return {"status": "running"}
|
||||
|
||||
# Wait before next poll
|
||||
time.sleep(poll_interval)
|
||||
# A status that does not read this round keeps the last one.
|
||||
status = self._qemu_current_status(vm, vmid) or status
|
||||
|
||||
except RuntimeError:
|
||||
raise
|
||||
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]:
|
||||
@staticmethod
|
||||
def _qemu_current_status(vm: Any, vmid: str) -> str | None:
|
||||
"""The VM's status from ``status/current``; None when it does not read."""
|
||||
try:
|
||||
return qemu_status(vm.status.current.get() or {})
|
||||
except Exception as e:
|
||||
_logger.debug(f"Could not read the status of VM {vmid}: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _guest_agent_address(vm: Any, vmid: str) -> dict[str, str] | None:
|
||||
"""The first non-loopback IPv4 address the guest agent reports, or None."""
|
||||
try:
|
||||
# Proxmox's REST path is "network-get-interfaces" (hyphens) — it must
|
||||
# be passed as a resource id via __call__, not dotted attribute access
|
||||
# (which would silently build a non-existent "network_get_interfaces"
|
||||
# path and 404 on every poll).
|
||||
agent_info = vm.agent("network-get-interfaces").get()
|
||||
except Exception as e:
|
||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
||||
return None
|
||||
# The guest agent does not report interfaces in a fixed order — loopback
|
||||
# commonly comes first, named "lo" on Linux and "lo0" on the BSDs. Skip
|
||||
# loopback addresses, whatever the interface is called, and take the first
|
||||
# IPv4 address.
|
||||
for iface in (agent_info or {}).get("result", []):
|
||||
name = iface.get("name", "")
|
||||
if not name:
|
||||
continue
|
||||
for addr in iface.get("ip-addresses", []):
|
||||
if addr.get("ip-address-type") != "ipv4":
|
||||
continue
|
||||
ip_addr = addr.get("ip-address", "")
|
||||
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||
return {
|
||||
"ip_address": ip_addr,
|
||||
"hostname": name,
|
||||
"mac_address": iface.get("hardware-address", ""),
|
||||
}
|
||||
return None
|
||||
|
||||
def get_network_targets(self) -> list[NetworkTargetDict]:
|
||||
"""
|
||||
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
||||
|
||||
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
|
||||
@@ -0,0 +1,78 @@
|
||||
"""A native Zabbix agent on a Proxmox node: napalm-device-types' ``ZabbixAgentMixin``.
|
||||
|
||||
A node runs no container engine (NetOrk/netork#2571). The template installs Debian's
|
||||
``zabbix-agent`` -- or, where Debian has none, Zabbix's from its repository -- and
|
||||
enables and restarts it. This writes the caller's values into
|
||||
``/etc/zabbix/zabbix_agentd.conf`` and opens tcp/``listen_port`` in ufw where the node
|
||||
has it; pve-firewall's rules are the operator's, as for the SNMP agent. The node's
|
||||
shell runs as root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import (
|
||||
ZABBIX_AGENT_PURPOSE,
|
||||
FixStepOutcomeDict,
|
||||
ZabbixAgentMixin,
|
||||
ZabbixAgentSettingsDict,
|
||||
zabbix_agent_config,
|
||||
zabbix_repository_command,
|
||||
)
|
||||
|
||||
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
|
||||
|
||||
|
||||
class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
|
||||
"""``zabbix-agent`` from Debian, or else from Zabbix's repository."""
|
||||
|
||||
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
|
||||
os_release, status = self._rc("cat /etc/os-release")
|
||||
if status != 0:
|
||||
return {"ok": False, "output": f"reading /etc/os-release: {os_release[-300:]}"}
|
||||
try:
|
||||
command = zabbix_repository_command(os_release, release)
|
||||
except ValueError as exc:
|
||||
return {"ok": False, "output": str(exc)}
|
||||
return self._step(command, f"Zabbix {release} repository added")
|
||||
|
||||
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
text, status = self._rc(f"cat {CONFIG}")
|
||||
if status != 0:
|
||||
return {"ok": False, "output": f"reading {CONFIG}: {text[-300:]}"}
|
||||
# _rc strips the output; the file ends with a newline.
|
||||
new, changes = zabbix_agent_config(f"{text}\n", settings)
|
||||
if not changes:
|
||||
return {"ok": True, "output": f"{CONFIG} already says it"}
|
||||
kept = self._step(f"cp -p {CONFIG} {CONFIG}.bak", "")
|
||||
if not kept["ok"]:
|
||||
return kept
|
||||
written = self._write_root_file(CONFIG, new)
|
||||
if not written["ok"]:
|
||||
return written
|
||||
return {"ok": True, "output": "; ".join(changes)}
|
||||
|
||||
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
return self._allow_sources(
|
||||
settings["allowed_sources"], int(settings["listen_port"]), "tcp", ZABBIX_AGENT_PURPOSE
|
||||
)
|
||||
|
||||
def _revoke_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
"""For an active-only agent: remove the ufw rules recorded for the agent on an
|
||||
earlier passive run, whatever port they opened (NetOrk/netork#2693)."""
|
||||
return self._revoke_sources(ZABBIX_AGENT_PURPOSE, int(settings["listen_port"]), "tcp")
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - ProxmoxHostMixin's
|
||||
|
||||
def _rc(self, command: str) -> tuple[str, int]: ...
|
||||
|
||||
def _step(self, command: str, done: str) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _allow_sources(
|
||||
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||
) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ...
|
||||
+54
-26
@@ -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.13.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>=2.3.0",
|
||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for SSH fallback (driver.py)
|
||||
"napalm_device_types>=4.43.0", # ZabbixAgentMixin, opened_ports
|
||||
"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
-10
@@ -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
|
||||
@@ -96,8 +96,6 @@ SDN_SUBNETS_VNET2: list = []
|
||||
# driver bug rather than bad test data.
|
||||
DNS_INFO = {"search": "example.com", "dns1": "8.8.8.8"}
|
||||
|
||||
NTP_INFO = {"server": "pool.ntp.org,time.cloudflare.com"}
|
||||
|
||||
NODE_NETSTAT = [
|
||||
{
|
||||
"dev": "eth0",
|
||||
@@ -120,10 +118,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,
|
||||
@@ -133,10 +162,8 @@ def _build_mock_api(
|
||||
sdn_vnets=None,
|
||||
sdn_subnets=None,
|
||||
dns=None,
|
||||
ntp=None,
|
||||
netstat=None,
|
||||
pve_users=None,
|
||||
exec_return="",
|
||||
sensors=None,
|
||||
cluster_status=None,
|
||||
):
|
||||
@@ -156,9 +183,7 @@ def _build_mock_api(
|
||||
node_res.status.get.return_value = node_status or NODE_STATUS
|
||||
node_res.network.get.return_value = network if network is not None else NODE_NETWORK
|
||||
node_res.dns.get.return_value = dns or DNS_INFO
|
||||
node_res.ntp.get.return_value = ntp or NTP_INFO
|
||||
node_res.netstat.get.return_value = netstat or NODE_NETSTAT
|
||||
node_res.execute.post.return_value = {"data": exec_return}
|
||||
node_res.hardware.sensors.get.return_value = sensors or []
|
||||
node_res.time.get.return_value = {}
|
||||
node_res.subscription.get.return_value = {}
|
||||
@@ -203,12 +228,13 @@ def driver():
|
||||
mock_api = _build_mock_api()
|
||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||
drv.open()
|
||||
drv._node_ssh = MagicMock(return_value=NodeShell())
|
||||
return drv
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver_with_exec(request):
|
||||
"""Return a driver whose exec endpoint returns a parametrised string."""
|
||||
"""Return a driver whose node shell prints a parametrised string."""
|
||||
exec_output = getattr(request, "param", "")
|
||||
drv = ProxmoxDriver(
|
||||
hostname="pve1.example.com",
|
||||
@@ -216,7 +242,8 @@ def driver_with_exec(request):
|
||||
password="secret",
|
||||
optional_args={"verify_ssl": False},
|
||||
)
|
||||
mock_api = _build_mock_api(exec_return=exec_output)
|
||||
mock_api = _build_mock_api()
|
||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||
drv.open()
|
||||
drv._node_ssh = MagicMock(return_value=NodeShell(exec_output))
|
||||
return drv
|
||||
Vendored
+2159
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,99 @@
|
||||
"""A stand-in for proxmoxer's PBS client, answering from recorded responses.
|
||||
|
||||
``tests/fixtures/pbs_api.json`` holds what a real Proxmox Backup Server 4.2
|
||||
answered (sanitised). Paths a test adds on top -- backup groups, snapshots and
|
||||
jobs, which that server did not have yet -- follow the shapes of the PBS API
|
||||
schema (``pbs.proxmox.com/docs/api-viewer``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
RECORDED: dict[str, Any] = json.loads(
|
||||
(Path(__file__).parent / "fixtures" / "pbs_api.json").read_text()
|
||||
)
|
||||
|
||||
|
||||
def _key(path: str, params: dict[str, Any]) -> str:
|
||||
query = "&".join(f"{k}={params[k]}" for k in sorted(params))
|
||||
return f"{path.strip('/')}?{query}" if query else path.strip("/")
|
||||
|
||||
|
||||
class _Resource:
|
||||
"""proxmoxer's chained form: ``api.nodes("localhost").status.get()``."""
|
||||
|
||||
def __init__(self, api: FakePbsApi, path: str) -> None:
|
||||
self._api, self._path = api, path
|
||||
|
||||
def __getattr__(self, name: str) -> _Resource:
|
||||
return _Resource(self._api, f"{self._path}/{name}")
|
||||
|
||||
def __call__(self, segment: str) -> _Resource:
|
||||
return _Resource(self._api, f"{self._path}/{segment}")
|
||||
|
||||
def get(self, **params: Any) -> Any:
|
||||
return self._api.get(self._path, **params)
|
||||
|
||||
def post(self, **params: Any) -> Any:
|
||||
return self._api.post(self._path, **params)
|
||||
|
||||
def put(self, **params: Any) -> Any:
|
||||
return self._api.put(self._path, **params)
|
||||
|
||||
|
||||
class FakePbsApi:
|
||||
"""``get``/``post``/``put``/``delete`` by path, like ``ProxmoxAPI.get("admin/gc")``,
|
||||
or chained, like ``ProxmoxAPI.nodes("localhost").status.get()``.
|
||||
|
||||
A response is looked up as ``"path?k=v&..."`` first, then as ``"path"``. A
|
||||
value that is an exception is raised. Every call is recorded in ``calls``.
|
||||
"""
|
||||
|
||||
def __init__(self, **overrides: Any) -> None:
|
||||
self.responses: dict[str, Any] = copy.deepcopy(RECORDED)
|
||||
self.responses.update(overrides)
|
||||
self.calls: list[tuple[str, str, dict[str, Any]]] = []
|
||||
|
||||
def _answer(self, method: str, path: str, params: dict[str, Any]) -> Any:
|
||||
self.calls.append((method, path.strip("/"), params))
|
||||
for key in (f"{method} {_key(path, params)}", f"{method} {path.strip('/')}"):
|
||||
if key in self.responses:
|
||||
return self._value(self.responses[key])
|
||||
if method == "GET":
|
||||
for key in (_key(path, params), path.strip("/")):
|
||||
if key in self.responses:
|
||||
return self._value(self.responses[key])
|
||||
raise ResourceException(404, "Not Found", f"no recorded answer for {method} {path}")
|
||||
|
||||
@staticmethod
|
||||
def _value(value: Any) -> Any:
|
||||
if isinstance(value, Exception):
|
||||
raise value
|
||||
return copy.deepcopy(value)
|
||||
|
||||
def __getattr__(self, name: str) -> _Resource:
|
||||
if name.startswith("_"):
|
||||
raise AttributeError(name)
|
||||
return _Resource(self, name)
|
||||
|
||||
def get(self, path: str, **params: Any) -> Any:
|
||||
return self._answer("GET", path, params)
|
||||
|
||||
def post(self, path: str, **params: Any) -> Any:
|
||||
return self._answer("POST", path, params)
|
||||
|
||||
def put(self, path: str, **params: Any) -> Any:
|
||||
return self._answer("PUT", path, params)
|
||||
|
||||
def delete(self, path: str, **params: Any) -> Any:
|
||||
return self._answer("DELETE", path, params)
|
||||
|
||||
|
||||
def forbidden() -> ResourceException:
|
||||
return ResourceException(403, "Forbidden", "permission check failed")
|
||||
@@ -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": 12
|
||||
},
|
||||
"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": 113,
|
||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179,
|
||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 220,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 63
|
||||
},
|
||||
"mypy_relaxed": [
|
||||
"napalm_proxmox.config_mixin",
|
||||
"napalm_proxmox.driver",
|
||||
"napalm_proxmox.interfaces_mixin",
|
||||
"napalm_proxmox.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"
|
||||
]
|
||||
}
|
||||
@@ -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"] == []
|
||||
@@ -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"]
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""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)
|
||||
|
||||
# The record of opened rules (/var/lib/netork, NetOrk/netork#2693) is no temp file.
|
||||
assert not any(re.search(r"/tmp/\S*netork", c) for c in node.ran)
|
||||
|
||||
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
|
||||
node.status["command -v ufw"] = 0
|
||||
|
||||
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": ""}
|
||||
@@ -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
|
||||
|
||||
@@ -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}"
|
||||
|
||||
|
||||
@@ -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 = (
|
||||
|
||||
@@ -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")
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""`get_listening_sockets`: what listens on the node, and which service it is.
|
||||
|
||||
Whether pveproxy, a Ceph manager or a guest-facing service is reachable from
|
||||
outside the node is decided by the address it listens on. The command and its
|
||||
parse are napalm-device-types'; the driver only carries the command over its
|
||||
exec path, which already runs as root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from napalm_device_types import ListeningSocketsMixin
|
||||
|
||||
from napalm_proxmox.driver import ProxmoxDriver
|
||||
|
||||
WIRE = (
|
||||
"SOCK_BEGIN\n[ss]\n"
|
||||
'tcp LISTEN 0 4096 *:8006 *:* users:(("pveproxy worker",pid=2101,fd=6))\n'
|
||||
"__SS_RC=0\n[cgroups]\n"
|
||||
"2101 0::/system.slice/pveproxy.service\n"
|
||||
"SOCK_END\n"
|
||||
)
|
||||
|
||||
|
||||
def test_the_driver_declares_the_contract():
|
||||
assert issubclass(ProxmoxDriver, ListeningSocketsMixin)
|
||||
|
||||
|
||||
def test_it_reads_as_root_over_the_exec_path(driver):
|
||||
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||
reading = driver.get_listening_sockets()
|
||||
|
||||
[command] = [c.args[0] for c in exec_.call_args_list]
|
||||
assert command.startswith("sh -c '")
|
||||
assert reading["attributed"] is True
|
||||
[socket] = reading["sockets"]
|
||||
assert (socket["address"], socket["port"], socket["unit"]) == ("*", 8006, "pveproxy")
|
||||
@@ -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)()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""`get_log_sources`: which logs the node writes, and which service writes each.
|
||||
|
||||
pveproxy, pvedaemon, the Ceph daemons and a backup server's proxy write to
|
||||
journald and to files under ``/var/log``. The command and its parse are
|
||||
napalm-device-types'; the driver only carries the command over its exec path,
|
||||
which already runs as root (NetOrk/netork#2049).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from napalm_device_types import LogSourcesMixin
|
||||
|
||||
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
|
||||
from napalm_proxmox.driver import ProxmoxDriver
|
||||
|
||||
WIRE = (
|
||||
"LOGS_BEGIN\n[journald]\npveproxy.service\n"
|
||||
"[open]\n/proc/2101/fd/7 /var/log/pveproxy/access.log\n"
|
||||
"[stat]\n/proc/2101/fd/7 4096 1762250200\n"
|
||||
"[cgroups]\n2101 0::/system.slice/pveproxy.service\n"
|
||||
"[comm]\n2101 pveproxy worker\n"
|
||||
"LOGS_END\n"
|
||||
)
|
||||
|
||||
|
||||
def test_both_drivers_declare_the_contract():
|
||||
assert issubclass(ProxmoxDriver, LogSourcesMixin)
|
||||
assert issubclass(ProxmoxBackupDriver, LogSourcesMixin)
|
||||
|
||||
|
||||
def test_it_reads_as_root_over_the_exec_path(driver):
|
||||
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||
reading = driver.get_log_sources()
|
||||
|
||||
[command] = [c.args[0] for c in exec_.call_args_list]
|
||||
assert command.startswith("sh -c '")
|
||||
assert reading["attributed"] is True
|
||||
access = [s for s in reading["sources"] if s["kind"] == "file"]
|
||||
assert [(s["path"], s["unit"]) for s in access] == [
|
||||
("/var/log/pveproxy/access.log", "pveproxy")
|
||||
]
|
||||
+79
-76
@@ -1,21 +1,10 @@
|
||||
"""Tests for NTP, SNMP, users, config management, ping, traceroute, CLI."""
|
||||
"""Tests for NTP statistics, SNMP, users, config management, ping, traceroute, CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
class TestGetNTPServers:
|
||||
def test_returns_configured_servers(self, driver):
|
||||
result = driver.get_ntp_servers()
|
||||
assert "pool.ntp.org" in result
|
||||
assert "time.cloudflare.com" in result
|
||||
|
||||
def test_empty_when_no_ntp(self, driver):
|
||||
driver._node_api().ntp.get.return_value = {}
|
||||
result = driver.get_ntp_servers()
|
||||
assert result == {}
|
||||
|
||||
|
||||
class TestGetNTPStats:
|
||||
@@ -25,19 +14,19 @@ class TestGetNTPStats:
|
||||
)
|
||||
|
||||
def test_synchronized_server(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.NTP_OUTPUT}
|
||||
driver._node_ssh().output = self.NTP_OUTPUT
|
||||
stats = driver.get_ntp_stats()
|
||||
synced = [s for s in stats if s["synchronized"]]
|
||||
assert len(synced) == 1
|
||||
assert synced[0]["remote"] == "192.168.1.1"
|
||||
|
||||
def test_stratum(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.NTP_OUTPUT}
|
||||
driver._node_ssh().output = self.NTP_OUTPUT
|
||||
stats = driver.get_ntp_stats()
|
||||
assert stats[0]["stratum"] == 4
|
||||
|
||||
def test_empty_when_no_ntp_command(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": ""}
|
||||
driver._node_ssh().output = ""
|
||||
stats = driver.get_ntp_stats()
|
||||
assert stats == []
|
||||
|
||||
@@ -52,7 +41,7 @@ class TestGetSNMPInformation:
|
||||
)
|
||||
|
||||
def test_communities(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.SNMP_CONF}
|
||||
driver._node_ssh().output = self.SNMP_CONF
|
||||
result = driver.get_snmp_information()
|
||||
assert "public" in result["community"]
|
||||
assert result["community"]["public"]["mode"] == "ro"
|
||||
@@ -60,39 +49,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 +124,14 @@ class TestConfigManagement:
|
||||
assert diff == ""
|
||||
|
||||
def test_get_config_running(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.RUNNING}
|
||||
driver._node_ssh().output = self.RUNNING
|
||||
result = driver.get_config(retrieve="running")
|
||||
assert self.RUNNING in result["running"]
|
||||
assert result["candidate"] == ""
|
||||
|
||||
def test_get_config_sanitized_redacts_password(self, driver):
|
||||
raw = "password mysecret\nauto eth0\n"
|
||||
driver._node_api().execute.post.return_value = {"data": raw}
|
||||
driver._node_ssh().output = raw
|
||||
result = driver.get_config(retrieve="running", sanitized=True)
|
||||
assert "mysecret" not in result["running"]
|
||||
assert "****" in result["running"]
|
||||
@@ -167,20 +156,45 @@ class TestPing:
|
||||
)
|
||||
|
||||
def test_success(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.PING_SUCCESS}
|
||||
driver._node_ssh().output = self.PING_SUCCESS
|
||||
result = driver.ping("8.8.8.8")
|
||||
assert "success" in result
|
||||
assert result["success"]["probes_sent"] == 2
|
||||
assert result["success"]["packet_loss"] == 0
|
||||
assert result["success"]["rtt_min"] == pytest.approx(10.5, abs=0.01)
|
||||
|
||||
def test_every_reply_is_a_result(self, driver):
|
||||
"""iputils puts "from <ip>" before icmp_seq (napalm-proxmox#12)."""
|
||||
driver._node_ssh().output = self.PING_SUCCESS
|
||||
result = driver.ping("8.8.8.8")
|
||||
assert result["success"]["results"] == [
|
||||
{"ip_address": "8.8.8.8", "rtt": 10.5},
|
||||
{"ip_address": "8.8.8.8", "rtt": 11.2},
|
||||
]
|
||||
|
||||
def test_a_reply_by_name_and_over_ipv6(self, driver):
|
||||
output = (
|
||||
"PING dns.google (8.8.4.4) 56(84) bytes of data.\n"
|
||||
"64 bytes from dns.google (8.8.4.4): icmp_seq=1 ttl=118 time=123 ms\n"
|
||||
"64 bytes from 2001:db8::1: icmp_seq=2 ttl=64 time=0.045 ms\n"
|
||||
"--- dns.google ping statistics ---\n"
|
||||
"2 packets transmitted, 2 received, 0% packet loss, time 1001ms\n"
|
||||
"rtt min/avg/max/mdev = 0.045/61.5/123.0/61.4 ms\n"
|
||||
)
|
||||
driver._node_ssh().output = output
|
||||
result = driver.ping("dns.google")
|
||||
assert result["success"]["results"] == [
|
||||
{"ip_address": "8.8.4.4", "rtt": 123.0},
|
||||
{"ip_address": "2001:db8::1", "rtt": 0.045},
|
||||
]
|
||||
|
||||
def test_failure(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.PING_FAIL}
|
||||
driver._node_ssh().output = self.PING_FAIL
|
||||
result = driver.ping("badhost")
|
||||
assert "error" in result
|
||||
|
||||
def test_exec_unavailable(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": ""}
|
||||
def test_no_output(self, driver):
|
||||
driver._node_ssh().output = ""
|
||||
result = driver.ping("8.8.8.8")
|
||||
assert "error" in result
|
||||
|
||||
@@ -194,44 +208,34 @@ class TestTraceroute:
|
||||
)
|
||||
|
||||
def test_success_hops(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.TR_OUTPUT}
|
||||
driver._node_ssh().output = self.TR_OUTPUT
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
assert "success" in result
|
||||
assert 1 in result["success"]
|
||||
assert 3 in result["success"]
|
||||
|
||||
def test_hop_rtt(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.TR_OUTPUT}
|
||||
driver._node_ssh().output = self.TR_OUTPUT
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
hop1 = result["success"][1]["probes"]
|
||||
assert hop1[1]["ip_address"] == "10.0.0.254"
|
||||
|
||||
def test_empty_returns_error(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": ""}
|
||||
driver._node_ssh().output = ""
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
assert "error" in result
|
||||
|
||||
|
||||
class TestCLI:
|
||||
def test_cli_single_command(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": "hello world"}
|
||||
driver._node_ssh().output = "hello world"
|
||||
result = driver.cli(["echo hello world"])
|
||||
assert result["echo hello world"] == "hello world"
|
||||
|
||||
def test_cli_multiple_commands(self, driver):
|
||||
responses = {"uptime": "up 2 days", "hostname": "pve1"}
|
||||
call_count = 0
|
||||
|
||||
def _exec(command):
|
||||
nonlocal call_count
|
||||
cmd = command
|
||||
call_count += 1
|
||||
return {"data": responses.get(cmd, "")}
|
||||
|
||||
driver._node_api().execute.post.side_effect = _exec
|
||||
driver._node_ssh().outputs = {"uptime": "up 2 days", "hostname": "pve1"}
|
||||
result = driver.cli(["uptime", "hostname"])
|
||||
assert "uptime" in result
|
||||
assert "hostname" in result
|
||||
assert result == {"uptime": "up 2 days", "hostname": "pve1"}
|
||||
|
||||
|
||||
class TestGetRouteTo:
|
||||
@@ -241,56 +245,48 @@ 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": ""}
|
||||
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 +299,29 @@ class TestIPv6Neighbors:
|
||||
)
|
||||
|
||||
def test_neighbors_parsed(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.IPV6_NEIGH}
|
||||
driver._node_ssh().output = self.IPV6_NEIGH
|
||||
result = driver.get_ipv6_neighbors_table()
|
||||
assert len(result) == 2 # FAILED entry excluded
|
||||
|
||||
def test_mac_normalized(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.IPV6_NEIGH}
|
||||
driver._node_ssh().output = self.IPV6_NEIGH
|
||||
result = driver.get_ipv6_neighbors_table()
|
||||
macs = {e["mac"] for e in result}
|
||||
assert "aa:bb:cc:dd:ee:ff" in macs
|
||||
|
||||
def test_state_present(self, driver):
|
||||
driver._node_api().execute.post.return_value = {"data": self.IPV6_NEIGH}
|
||||
driver._node_ssh().output = self.IPV6_NEIGH
|
||||
result = driver.get_ipv6_neighbors_table()
|
||||
states = {e["state"] for e in result}
|
||||
assert "REACHABLE" in states
|
||||
|
||||
def test_age_is_unknown(self, driver):
|
||||
# `ip neigh` reports no age, as for the IPv4 table; 0.0 would read as
|
||||
# "confirmed just now" (NetOrk/netork#1327).
|
||||
driver._node_ssh().output = self.IPV6_NEIGH
|
||||
result = driver.get_ipv6_neighbors_table()
|
||||
assert {e["age"] for e in result} == {-1.0}
|
||||
|
||||
|
||||
class TestNotImplemented:
|
||||
def test_get_bgp_config_raises(self, driver):
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,151 @@
|
||||
"""get_running_backups: what a restart of the node, or of one of its guests, would abort.
|
||||
|
||||
PVE: the node's active vzdump tasks, and the guests locked for their backup
|
||||
(``lock: backup``); a task names its guest when it backs up one, else the
|
||||
guests it is taking now are the locked ones. PBS: the running backup, sync,
|
||||
verify, garbage collection, prune and tape tasks. A failed read raises: an
|
||||
empty list would say nothing runs (NetOrk/netork#2318).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver
|
||||
from tests.pbs_fake import FakePbsApi
|
||||
|
||||
T0 = 1793660400
|
||||
UPID_JOB = "UPID:pve1:0001F2A3:00C4B1D2:6731A0C0:vzdump::root@pam:"
|
||||
UPID_ONE = "UPID:pve1:0001F2A4:00C4B1D3:6731A0D0:vzdump:105:root@pam:"
|
||||
|
||||
|
||||
def _pve(driver, tasks, resources):
|
||||
node = driver._api.nodes.return_value
|
||||
node.tasks.get.return_value = tasks
|
||||
driver._api.cluster.resources.get.return_value = resources
|
||||
return node
|
||||
|
||||
|
||||
def test_nothing_runs(driver):
|
||||
_pve(driver, [], [{"vmid": 101, "node": "pve1", "type": "qemu"}])
|
||||
assert driver.get_running_backups() == []
|
||||
|
||||
|
||||
def test_asks_for_the_nodes_active_vzdump_tasks_and_the_guests(driver):
|
||||
node = _pve(driver, [], [])
|
||||
driver.get_running_backups()
|
||||
node.tasks.get.assert_called_once_with(source="active", typefilter="vzdump")
|
||||
driver._api.cluster.resources.get.assert_called_once_with(type="vm")
|
||||
|
||||
|
||||
def test_a_job_takes_the_guests_locked_on_this_node(driver):
|
||||
_pve(
|
||||
driver,
|
||||
[{"upid": UPID_JOB, "type": "vzdump", "id": "", "starttime": T0}],
|
||||
[
|
||||
{"vmid": 101, "node": "pve1", "type": "qemu", "lock": "backup"},
|
||||
{"vmid": 102, "node": "pve1", "type": "lxc"},
|
||||
{"vmid": 103, "node": "pve2", "type": "qemu", "lock": "backup"},
|
||||
{"vmid": 104, "node": "pve1", "type": "qemu", "lock": "migrate"},
|
||||
],
|
||||
)
|
||||
assert driver.get_running_backups() == [
|
||||
{"kind": "backup", "job": None, "task": UPID_JOB, "guests": ["101"], "since": T0}
|
||||
]
|
||||
|
||||
|
||||
def test_a_task_for_one_guest_names_it(driver):
|
||||
_pve(
|
||||
driver,
|
||||
[{"upid": UPID_ONE, "type": "vzdump", "id": "105", "starttime": T0}],
|
||||
[{"vmid": 105, "node": "pve1", "type": "qemu", "lock": "backup"}],
|
||||
)
|
||||
assert driver.get_running_backups() == [
|
||||
{"kind": "backup", "job": None, "task": UPID_ONE, "guests": ["105"], "since": T0}
|
||||
]
|
||||
|
||||
|
||||
def test_a_guest_locked_without_a_task_still_counts(driver):
|
||||
"""The task list can lag, or a lock outlive its task: the guest is not restarted."""
|
||||
_pve(driver, [], [{"vmid": 101, "node": "pve1", "type": "qemu", "lock": "backup"}])
|
||||
assert driver.get_running_backups() == [
|
||||
{"kind": "backup", "job": None, "task": None, "guests": ["101"], "since": None}
|
||||
]
|
||||
|
||||
|
||||
def test_another_tasks_type_is_left_out(driver):
|
||||
_pve(driver, [{"upid": "UPID:pve1:1:2:3:qmstart:101:root@pam:", "type": "qmstart"}], [])
|
||||
assert driver.get_running_backups() == []
|
||||
|
||||
|
||||
def test_a_failed_read_raises(driver):
|
||||
driver._api.nodes.return_value.tasks.get.side_effect = ResourceException(
|
||||
403, "Forbidden", "Permission check failed (/nodes/pve1, Sys.Audit)"
|
||||
)
|
||||
with pytest.raises(ResourceException):
|
||||
driver.get_running_backups()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Proxmox Backup Server
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _pbs(tasks):
|
||||
drv = ProxmoxBackupDriver("pbs1", "root", "secret")
|
||||
drv._api = FakePbsApi(**{"nodes/localhost/tasks?running=1": tasks})
|
||||
drv._node_name = "localhost"
|
||||
return drv
|
||||
|
||||
|
||||
def _task(worker_type: str, worker_id: str | None, n: int = 1) -> dict:
|
||||
upid = f"UPID:localhost:{n:08X}:00000000:00000000:6731A0C0:{worker_type}:{worker_id or ''}:root@pam:"
|
||||
return {"upid": upid, "worker_type": worker_type, "worker_id": worker_id, "starttime": T0 + n}
|
||||
|
||||
|
||||
def test_pbs_kinds():
|
||||
tasks = [
|
||||
_task("backup", "store1:vm/101", 1),
|
||||
_task("syncjob", "store1:offsite:store1::s-1a2b", 2),
|
||||
_task("verificationjob", "store1:v-3c4d", 3),
|
||||
_task("verify_snapshot", "store1:vm/101/2026-11-01T00:00:00Z", 4),
|
||||
_task("garbage_collection", "store1", 5),
|
||||
_task("prunejob", "store1:p-5e6f", 6),
|
||||
_task("tape-backup-job", "weekly", 7),
|
||||
]
|
||||
found = _pbs(tasks).get_running_backups()
|
||||
assert [(b["kind"], b["job"]) for b in found] == [
|
||||
("backup", "store1:vm/101"),
|
||||
("sync", "store1:offsite:store1::s-1a2b"),
|
||||
("verify", "store1:v-3c4d"),
|
||||
("verify", "store1:vm/101/2026-11-01T00:00:00Z"),
|
||||
("gc", "store1"),
|
||||
("prune", "store1:p-5e6f"),
|
||||
("tape", "weekly"),
|
||||
]
|
||||
assert all(b["guests"] == [] for b in found)
|
||||
assert found[0]["task"] == tasks[0]["upid"]
|
||||
assert found[0]["since"] == T0 + 1
|
||||
|
||||
|
||||
def test_pbs_leaves_out_what_is_no_backup():
|
||||
"""A restore reads, a log rotation is housekeeping: neither is broken by a restart
|
||||
the way a backup is."""
|
||||
assert (
|
||||
_pbs([_task("reader", "store1:vm/101"), _task("logrotate", None)]).get_running_backups()
|
||||
== []
|
||||
)
|
||||
|
||||
|
||||
def test_pbs_nothing_runs():
|
||||
assert _pbs([]).get_running_backups() == []
|
||||
|
||||
|
||||
def test_pbs_a_failed_read_raises():
|
||||
drv = _pbs([])
|
||||
drv._api.responses["nodes/localhost/tasks?running=1"] = ResourceException(
|
||||
403, "Forbidden", "permission check failed"
|
||||
)
|
||||
with pytest.raises(ResourceException):
|
||||
drv.get_running_backups()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Scheduled jobs on a Proxmox VE node and a Proxmox Backup Server (#56).
|
||||
|
||||
The report, its parse and every write are napalm-device-types'
|
||||
``PosixScheduledJobsMixin``'s; the drivers carry the command across
|
||||
``run_command`` as root in one round trip and say which jobs Proxmox itself
|
||||
ships (``platform``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult, PosixScheduledJobsMixin, ScheduledJobRefused
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||
|
||||
_TIMER = """|Id={name}.timer
|
||||
|Unit={name}.service
|
||||
|Description={name}
|
||||
|TimersCalendar={{ OnCalendar=*-*-* 06:00:00 ; next_elapse=n/a }}
|
||||
|NextElapseUSecRealtime=@1762236000
|
||||
|LastTriggerUSec=@1762149600
|
||||
|UnitFileState=enabled
|
||||
|ActiveState=active
|
||||
|FragmentPath={path}
|
||||
|"""
|
||||
|
||||
_UNIT = """|Id={name}.service
|
||||
|ExecStart={{ path=/usr/bin/{name} ; argv[]=/usr/bin/{name} ; }}
|
||||
|Result=success
|
||||
|FragmentPath={path}
|
||||
|"""
|
||||
|
||||
|
||||
def _report(*timers: tuple[str, str]) -> str:
|
||||
return "\n".join(
|
||||
[
|
||||
"SJ_BEGIN",
|
||||
"[system /etc/cron.d/vzdump]",
|
||||
"|0 1 * * 6 root vzdump 100 --mode snapshot --quiet 1",
|
||||
"[system /etc/cron.d/zfsutils-linux]",
|
||||
"|0 0 * * 0 root /usr/lib/zfs-linux/scrub",
|
||||
"[user /var/spool/cron/crontabs/root]",
|
||||
"|*/5 * * * * /root/check.sh",
|
||||
"[systemd]",
|
||||
"[timers]",
|
||||
*(_TIMER.format(name=n, path=p) for n, p in timers),
|
||||
"[units]",
|
||||
*(_UNIT.format(name=n, path=p.replace(".timer", ".service")) for n, p in timers),
|
||||
"[tz]",
|
||||
"/usr/share/zoneinfo/Europe/Berlin",
|
||||
"[owners]",
|
||||
"zfsutils-linux: /etc/cron.d/zfsutils-linux",
|
||||
*(f"{n.split('-')[0]}: {p}" for n, p in timers),
|
||||
"SJ_END",
|
||||
"",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
PVE_REPORT = _report(
|
||||
("pve-daily-update", "/lib/systemd/system/pve-daily-update.timer"),
|
||||
("pvesr", "/usr/lib/systemd/system/pvesr.timer"),
|
||||
("apt-daily", "/usr/lib/systemd/system/apt-daily.timer"),
|
||||
)
|
||||
PBS_REPORT = _report(
|
||||
("proxmox-backup-daily-update", "/usr/lib/systemd/system/proxmox-backup-daily-update.timer"),
|
||||
("pve-daily-update", "/lib/systemd/system/pve-daily-update.timer"),
|
||||
("apt-daily", "/usr/lib/systemd/system/apt-daily.timer"),
|
||||
)
|
||||
VERBS = ("get_scheduled_jobs", "manage_scheduled_job", "put_scheduled_job", "delete_scheduled_job")
|
||||
|
||||
|
||||
def _driver(cls: type, report: str) -> MagicMock:
|
||||
driver = cls("host", "root@pam", "pw")
|
||||
driver.run_command = MagicMock(return_value=CommandResult(report, "", 0))
|
||||
return driver
|
||||
|
||||
|
||||
def _by_source(driver: MagicMock) -> dict[str, dict[str, object]]:
|
||||
return {str(j["source"]): dict(j) for j in driver.get_scheduled_jobs()["jobs"]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("cls", "report"),
|
||||
[(ProxmoxDriver, PVE_REPORT), (ProxmoxBackupDriver, PBS_REPORT)],
|
||||
ids=["pve", "pbs"],
|
||||
)
|
||||
def test_each_driver_offers_every_verb_and_reads_as_root_once(cls: type, report: str) -> None:
|
||||
assert issubclass(cls, PosixScheduledJobsMixin)
|
||||
for verb in VERBS:
|
||||
assert callable(getattr(cls, verb))
|
||||
driver = _driver(cls, report)
|
||||
reading = driver.get_scheduled_jobs()
|
||||
assert reading["time_zone"] == "Europe/Berlin"
|
||||
assert len(reading["jobs"]) == 6
|
||||
driver.run_command.assert_called_once()
|
||||
assert driver.run_command.call_args.kwargs["privileged"] is True
|
||||
|
||||
|
||||
def test_what_proxmox_ve_ships_is_platform() -> None:
|
||||
jobs = _by_source(_driver(ProxmoxDriver, PVE_REPORT))
|
||||
managed = {source: job["managed_by"] for source, job in jobs.items()}
|
||||
assert managed == {
|
||||
"/lib/systemd/system/pve-daily-update.timer": "platform",
|
||||
"/usr/lib/systemd/system/pvesr.timer": "platform",
|
||||
"/etc/cron.d/vzdump": "platform",
|
||||
"/usr/lib/systemd/system/apt-daily.timer": "package",
|
||||
"/etc/cron.d/zfsutils-linux": "package",
|
||||
"/var/spool/cron/crontabs/root": "admin",
|
||||
}
|
||||
assert jobs["/lib/systemd/system/pve-daily-update.timer"]["actions"] == [
|
||||
"enable",
|
||||
"disable",
|
||||
"run",
|
||||
]
|
||||
|
||||
|
||||
def test_what_a_backup_server_ships_is_platform() -> None:
|
||||
jobs = _by_source(_driver(ProxmoxBackupDriver, PBS_REPORT))
|
||||
managed = {source: job["managed_by"] for source, job in jobs.items()}
|
||||
assert managed["/usr/lib/systemd/system/proxmox-backup-daily-update.timer"] == "platform"
|
||||
# Proxmox VE's names mean nothing on a backup server.
|
||||
assert managed["/lib/systemd/system/pve-daily-update.timer"] == "package"
|
||||
assert managed["/etc/cron.d/vzdump"] == "admin"
|
||||
assert managed["/usr/lib/systemd/system/apt-daily.timer"] == "package"
|
||||
|
||||
|
||||
def test_a_vzdump_cron_line_only_runs() -> None:
|
||||
"""``/etc/cron.d/vzdump`` links into pmxcfs (``/etc/pve``), where no switch writes."""
|
||||
driver = _driver(ProxmoxDriver, PVE_REPORT)
|
||||
job = _by_source(driver)["/etc/cron.d/vzdump"]
|
||||
assert job["actions"] == ["run"]
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.manage_scheduled_job(str(job["key"]), "disable", digest=str(job["digest"]))
|
||||
assert driver.run_command.call_count == 2 # two readings, nothing written
|
||||
+2
-3
@@ -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})
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,180 @@
|
||||
"""set_hostname: what it writes to /etc/hosts, and that it leaves a clustered node alone
|
||||
(napalm-proxmox#21)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
import shlex
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_proxmox import ProxmoxDriver
|
||||
|
||||
HOSTS = """\
|
||||
127.0.0.1 localhost.localdomain localhost
|
||||
# pve is the node; pve-backup its backup target
|
||||
10.0.0.1 pve.old.lan pve
|
||||
10.0.0.2 pve-backup.old.lan pve-backup
|
||||
"""
|
||||
|
||||
|
||||
class _Node:
|
||||
"""The node's shell: /etc/hostname reads "pve", /etc/hosts reads HOSTS.
|
||||
|
||||
*cluster_check* is what the test for a corosync.conf prints: exit status 1
|
||||
(no corosync.conf, a single node) unless a test says otherwise.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.ran: list[str] = []
|
||||
self.cluster_check = "__PVE_RC=1"
|
||||
|
||||
def __call__(self, command: str) -> str:
|
||||
self.ran.append(command)
|
||||
if "corosync.conf" in command:
|
||||
return self.cluster_check
|
||||
if command.startswith("cat /etc/hostname"):
|
||||
return "pve\n"
|
||||
if command.startswith("cat /etc/hosts"):
|
||||
return HOSTS
|
||||
return ""
|
||||
|
||||
def written_hosts(self) -> str:
|
||||
write = next(c for c in self.ran if "/etc/hosts" in c and "base64 -d" in c)
|
||||
return base64.b64decode(re.search(r"echo (\S+) \| base64 -d", write).group(1)).decode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def node() -> _Node:
|
||||
return _Node()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver(node: _Node) -> ProxmoxDriver:
|
||||
d = ProxmoxDriver("pve", "root@pam", "pw")
|
||||
d._exec_ssh_command = node
|
||||
return d
|
||||
|
||||
|
||||
def test_an_fqdn_renames_the_nodes_names_and_nothing_else(driver, node):
|
||||
driver.set_hostname("new.dom.lan")
|
||||
|
||||
assert node.written_hosts() == (
|
||||
"127.0.0.1 localhost.localdomain localhost\n"
|
||||
"# pve is the node; pve-backup its backup target\n"
|
||||
"10.0.0.1 new.dom.lan new\n"
|
||||
"10.0.0.2 pve-backup.old.lan pve-backup\n"
|
||||
)
|
||||
|
||||
|
||||
def test_a_short_name_keeps_the_old_domain(driver, node):
|
||||
driver.set_hostname("new")
|
||||
|
||||
assert "10.0.0.1 new.old.lan new\n" in node.written_hosts()
|
||||
assert "10.0.0.2 pve-backup.old.lan pve-backup\n" in node.written_hosts()
|
||||
|
||||
|
||||
def test_the_same_name_leaves_hosts_alone(driver, node):
|
||||
driver.set_hostname("pve")
|
||||
|
||||
assert not any("/etc/hosts" in c and "base64 -d" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_a_clustered_node_is_refused_before_anything_changes(driver, node):
|
||||
node.cluster_check = "__PVE_RC=0"
|
||||
|
||||
with pytest.raises(CommandErrorException, match="part of a cluster"):
|
||||
driver.set_hostname("new")
|
||||
|
||||
assert [c for c in node.ran if "corosync.conf" not in c] == []
|
||||
|
||||
|
||||
def test_the_cluster_check_looks_at_both_corosync_confs(driver, node):
|
||||
driver.set_hostname("new")
|
||||
|
||||
check = next(c for c in node.ran if "corosync.conf" in c)
|
||||
assert "/etc/pve/corosync.conf" in check
|
||||
assert "/etc/corosync/corosync.conf" in check
|
||||
|
||||
|
||||
def test_an_unreadable_cluster_check_refuses_too(driver, node):
|
||||
node.cluster_check = ""
|
||||
|
||||
with pytest.raises(CommandErrorException, match="could not tell"):
|
||||
driver.set_hostname("new")
|
||||
|
||||
assert [c for c in node.ran if "corosync.conf" not in c] == []
|
||||
|
||||
|
||||
# ── the name reaches the shell quoted (NetOrk/netork#2456) ──────────────────
|
||||
#
|
||||
# The name went into the root commands between single quotes of their own, so a name
|
||||
# with a single quote ended them: ``x';reboot;'`` ran ``reboot``. Each command now
|
||||
# hands it on as one shell word, whatever it holds.
|
||||
|
||||
INJECTED = "x';reboot;'"
|
||||
|
||||
|
||||
def _run(node: _Node, start: str) -> str:
|
||||
return next(c for c in node.ran if c.startswith(start))
|
||||
|
||||
|
||||
def test_the_runtime_hostname_is_one_word(driver, node):
|
||||
driver.set_hostname(f"{INJECTED}.dom.lan")
|
||||
|
||||
assert shlex.split(_run(node, "hostname ")) == ["hostname", INJECTED]
|
||||
|
||||
|
||||
def test_postfix_gets_the_fqdn_as_one_word(driver, node):
|
||||
driver.set_hostname(f"{INJECTED}.dom.lan")
|
||||
|
||||
words = shlex.split(_run(node, "command -v postconf"))
|
||||
assert words[words.index("-e") + 1] == f"myhostname = {INJECTED}.dom.lan"
|
||||
|
||||
|
||||
def test_the_node_directory_is_moved_by_quoted_paths(driver, node):
|
||||
driver.set_hostname(INJECTED)
|
||||
|
||||
words = shlex.split(_run(node, "if [ -d"))
|
||||
assert words[words.index("mv") + 1 : words.index("mv") + 3] == [
|
||||
"/etc/pve/nodes/pve",
|
||||
f"/etc/pve/nodes/{INJECTED}",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", [INJECTED, "$(reboot)", "`reboot`", "a b"])
|
||||
def test_no_command_runs_what_the_name_holds(driver, node, name):
|
||||
driver.set_hostname(name)
|
||||
|
||||
for command in node.ran:
|
||||
words = list(shlex.shlex(command, posix=True, punctuation_chars=True))
|
||||
assert "reboot" not in words, command
|
||||
|
||||
|
||||
# ── /etc/hosts is written through a private temporary file (#66, NetOrk/netork#2446) ──
|
||||
#
|
||||
# The new file was written as root to the fixed /tmp/_netork_hosts and moved over
|
||||
# /etc/hosts: a local user could create that file (or a symlink) beforehand and own
|
||||
# /etc/hosts afterwards. It is now a mktemp file beside the target, in root's /etc.
|
||||
|
||||
|
||||
def _hosts_write(node: _Node) -> str:
|
||||
return next(c for c in node.ran if "/etc/hosts" in c and "base64 -d" in c)
|
||||
|
||||
|
||||
def test_hosts_goes_through_a_mktemp_file_in_etc(driver, node):
|
||||
driver.set_hostname("new")
|
||||
|
||||
write = _hosts_write(node)
|
||||
assert "/tmp/" not in write
|
||||
assert write.startswith("t=$(mktemp /etc/.hosts.XXXXXX) && ")
|
||||
assert ' | base64 -d > "$t" && chmod 644 "$t" && mv "$t" /etc/hosts' in write
|
||||
assert write.endswith(' || { rm -f "$t"; false; }')
|
||||
|
||||
|
||||
def test_what_is_written_is_still_the_new_hosts(driver, node):
|
||||
driver.set_hostname("new")
|
||||
|
||||
assert "10.0.0.1 new.old.lan new\n" in node.written_hosts()
|
||||
@@ -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")
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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"}})
|
||||
@@ -0,0 +1,33 @@
|
||||
"""`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)
|
||||
# The identity's keys only: napalm-device-types reads more in the same round trip.
|
||||
assert {k: identity[k] for k in ("system_uuid", "product_serial", "board_serial")} == {
|
||||
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
|
||||
"product_serial": "",
|
||||
"board_serial": "ZM155S026022",
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
"""Time sync on a Proxmox VE node and a Proxmox Backup Server (NetOrk/netork#2365).
|
||||
|
||||
Neither API keeps time servers: both products run chrony on Debian. The servers
|
||||
are napalm-device-types' ``PosixTimeSyncMixin``'s, over the driver's SSH session
|
||||
(``run_command``, as root); the zone is read from the host the same way and
|
||||
written through the product's own ``PUT /nodes/{node}/time``, which also keeps
|
||||
``/etc/timezone`` for the web UI. One netOrk device is one node: a PVE node in a
|
||||
cluster has its own clock, and only that node is written.
|
||||
|
||||
The readings are what ``reading_command`` prints on a PVE 8 / PBS 3 host (Debian
|
||||
12's chrony 4.3, its configuration comments shortened).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult, PosixTimeSyncMixin, TimeSyncMixin
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||
from tests.conftest import _build_mock_api
|
||||
from tests.pbs_fake import FakePbsApi, forbidden
|
||||
|
||||
_ACTIVE_CHRONY = """\
|
||||
chrony chrony active
|
||||
chronyd chrony active
|
||||
systemd-timesyncd systemd-timesyncd inactive
|
||||
ntpsec ntpd inactive
|
||||
ntp ntpd inactive
|
||||
ntpd ntpd inactive
|
||||
openntpd openntpd inactive"""
|
||||
|
||||
_CHRONYC_SYNCED = """\
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^- 162.159.200.123 3 6 377 41 +814us[ +814us] +/- 14ms
|
||||
^* 185.248.188.98 2 6 377 40 -45us[ -63us] +/- 10ms"""
|
||||
|
||||
#: Debian 12's /etc/chrony/chrony.conf as Proxmox VE 8 and PBS 3 ship it.
|
||||
_CHRONY_CONF = """\
|
||||
# Welcome to the chrony configuration file. See chrony.conf(5) for more
|
||||
# information about usable directives.
|
||||
|
||||
# Include configuration files found in /etc/chrony/conf.d.
|
||||
confdir /etc/chrony/conf.d
|
||||
|
||||
# Use Debian vendor zone.
|
||||
{pool}pool 2.debian.pool.ntp.org iburst
|
||||
|
||||
# Use time sources from DHCP.
|
||||
{dhcp}sourcedir /run/chrony-dhcp
|
||||
|
||||
# Use NTP sources found in /etc/chrony/sources.d.
|
||||
sourcedir /etc/chrony/sources.d
|
||||
|
||||
keyfile /etc/chrony/chrony.keys
|
||||
driftfile /var/lib/chrony/chrony.drift
|
||||
ntsdumpdir /var/lib/chrony
|
||||
logdir /var/log/chrony
|
||||
maxupdateskew 100.0
|
||||
rtcsync
|
||||
makestep 1 3
|
||||
leapsectz right/UTC"""
|
||||
|
||||
_MARK = "#napalm-time-sync: "
|
||||
|
||||
|
||||
def _reading(
|
||||
zone: str = "Europe/Berlin",
|
||||
*,
|
||||
servers: tuple[str, ...] = (),
|
||||
dhcp: tuple[str, ...] = (),
|
||||
deaf_to_dhcp: bool = False,
|
||||
timedatectl: bool = True,
|
||||
) -> str:
|
||||
"""What the reading prints; *servers* in netOrk's sources file, the vendor's pool
|
||||
commented out with it (as a write leaves the host), *dhcp* in the DHCP client's
|
||||
sources file. *deaf_to_dhcp* is a host napalm-device-types 4.35.0 aligned: its write
|
||||
commented out the DHCP ``sourcedir`` too."""
|
||||
written = bool(servers)
|
||||
conf = _CHRONY_CONF.format(pool=_MARK if written else "", dhcp=_MARK if deaf_to_dhcp else "")
|
||||
parts = ["@@ts timedatectl"]
|
||||
if timedatectl:
|
||||
parts += [
|
||||
f"Timezone={zone}",
|
||||
"LocalRTC=no",
|
||||
"CanNTP=yes",
|
||||
"NTP=yes",
|
||||
"NTPSynchronized=yes",
|
||||
"TimeUSec=Wed 2026-11-11 14:23:16 CET",
|
||||
"RTCTimeUSec=Wed 2026-11-11 13:23:16 CET",
|
||||
]
|
||||
parts += ["@@ts zone", zone if timedatectl else ""]
|
||||
parts += ["@@ts active", _ACTIVE_CHRONY, "@@ts timesync", "@@ts chronyc", _CHRONYC_SYNCED]
|
||||
parts += ["@@ts chrony 0 main /etc/chrony/chrony.conf", conf, ""]
|
||||
if dhcp:
|
||||
parts += ["@@ts chrony 11 sourcedir /run/chrony-dhcp/vmbr0.sources"]
|
||||
parts += [f"server {s} iburst" for s in dhcp]
|
||||
parts += [""]
|
||||
if written:
|
||||
parts += ["@@ts chrony 14 sourcedir /etc/chrony/sources.d/netork.sources"]
|
||||
parts += [f"{'pool' if '.pool.' in s else 'server'} {s} iburst" for s in servers]
|
||||
parts += [""]
|
||||
parts += ["@@ts end", ""]
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
class Node:
|
||||
"""The node's command channel: the readings in turn (the last one stays), and
|
||||
every other command succeeds. Records ``(command, privileged, stdin)``."""
|
||||
|
||||
def __init__(self, *readings: str) -> None:
|
||||
self.readings = list(readings)
|
||||
self.calls: list[tuple[str, bool, bytes | None]] = []
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.calls.append((command, privileged, stdin))
|
||||
if "@@ts timedatectl" in command:
|
||||
reading = self.readings.pop(0) if len(self.readings) > 1 else self.readings[0]
|
||||
return CommandResult(reading, "", 0)
|
||||
if command.startswith("t=$(mktemp)"):
|
||||
return CommandResult("/tmp/tmp.Xk3fQ9", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def root(self) -> list[str]:
|
||||
return [c for c, privileged, _ in self.calls if privileged]
|
||||
|
||||
def staged(self) -> list[bytes]:
|
||||
return [stdin for _, _, stdin in self.calls if stdin is not None]
|
||||
|
||||
|
||||
def _pve(*readings: str, node: str | None = None) -> tuple[ProxmoxDriver, Any, Node]:
|
||||
args = {"verify_ssl": False} if node is None else {"verify_ssl": False, "node": node}
|
||||
driver = ProxmoxDriver("pve1.example.com", "root", "secret", optional_args=args)
|
||||
api = _build_mock_api()
|
||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||
driver.open()
|
||||
shell = Node(*readings)
|
||||
driver.run_command = shell # type: ignore[method-assign]
|
||||
return driver, api, shell
|
||||
|
||||
|
||||
def _pbs(*readings: str, **responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi, Node]:
|
||||
api = FakePbsApi(**responses)
|
||||
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
|
||||
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
|
||||
driver.open()
|
||||
shell = Node(*readings)
|
||||
driver.run_command = shell # type: ignore[method-assign]
|
||||
return driver, api, shell
|
||||
|
||||
|
||||
# -- the contract -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
|
||||
def test_both_drivers_read_and_write_servers_and_zone(cls: type) -> None:
|
||||
assert issubclass(cls, TimeSyncMixin)
|
||||
assert issubclass(cls, PosixTimeSyncMixin)
|
||||
assert callable(getattr(cls, "get_time_sync", None))
|
||||
assert callable(getattr(cls, "configure_time_sync", None))
|
||||
assert cls.time_sync_writes == frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
|
||||
# -- reading ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pve_reads_chrony_and_the_zone_in_one_round_trip() -> None:
|
||||
driver, api, shell = _pve(_reading())
|
||||
|
||||
assert driver.get_time_sync() == {
|
||||
"ntp_servers": ["2.debian.pool.ntp.org"],
|
||||
"dhcp_ntp_servers": [],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
}
|
||||
assert len(shell.calls) == 1
|
||||
assert shell.root() == [] # the reading writes nothing
|
||||
api.nodes.return_value.time.put.assert_not_called()
|
||||
|
||||
|
||||
def test_pbs_reads_chrony_and_the_zone() -> None:
|
||||
driver, api, shell = _pbs(_reading("Europe/Vienna", servers=("10.0.0.1",)))
|
||||
|
||||
assert driver.get_time_sync() == {
|
||||
"ntp_servers": ["10.0.0.1"],
|
||||
"dhcp_ntp_servers": [],
|
||||
"timezone": "Europe/Vienna",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
}
|
||||
assert len(shell.calls) == 1
|
||||
assert not [c for c in api.calls if c[0] != "GET"]
|
||||
|
||||
|
||||
def test_servers_from_dhcp_are_read_apart_from_the_configured_ones() -> None:
|
||||
"""A node that gets its time giver by DHCP (option 42): chrony reads the DHCP
|
||||
client's sources file, and those servers are not the node's own (NetOrk/netork#2380)."""
|
||||
driver, _, _ = _pve(_reading(dhcp=("192.168.1.1",)))
|
||||
|
||||
reading = driver.get_time_sync()
|
||||
|
||||
assert reading["ntp_servers"] == ["2.debian.pool.ntp.org"]
|
||||
assert reading["dhcp_ntp_servers"] == ["192.168.1.1"]
|
||||
|
||||
|
||||
def test_a_host_without_a_zone_of_its_own_reads_the_apis() -> None:
|
||||
"""No timedatectl and no /etc/timezone or /etc/localtime link: the API's word."""
|
||||
driver, api, _ = _pve(_reading(timedatectl=False))
|
||||
api.nodes.return_value.time.get.return_value = {"timezone": "Europe/Paris"}
|
||||
|
||||
assert driver.get_time_sync()["timezone"] == "Europe/Paris"
|
||||
|
||||
|
||||
def test_no_zone_anywhere_reads_none() -> None:
|
||||
driver, _, _ = _pbs(_reading(timedatectl=False), **{"nodes/localhost/time": forbidden()})
|
||||
|
||||
assert driver.get_time_sync()["timezone"] is None
|
||||
|
||||
|
||||
def test_a_cut_reading_raises() -> None:
|
||||
driver, _, _ = _pve("@@ts timedatectl\nTimezone=Europe/Berlin\n")
|
||||
|
||||
with pytest.raises(ValueError, match="cut short"):
|
||||
driver.get_time_sync()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", [_pve, _pbs], ids=["pve", "pbs"])
|
||||
def test_get_ntp_servers_is_what_get_time_sync_reads(make: Any) -> None:
|
||||
servers = ("10.0.0.1", "0.de.pool.ntp.org")
|
||||
driver, _, _ = make(_reading(servers=servers))
|
||||
|
||||
assert list(driver.get_ntp_servers()) == list(servers)
|
||||
assert driver.get_ntp_servers() == {s: {} for s in driver.get_time_sync()["ntp_servers"]}
|
||||
|
||||
|
||||
def test_get_ntp_servers_no_longer_asks_an_api_path_pve_does_not_have() -> None:
|
||||
"""``GET /nodes/{node}/ntp`` does not exist; asking it read as "no servers"."""
|
||||
driver, api, _ = _pve(_reading())
|
||||
|
||||
assert driver.get_ntp_servers() == {"2.debian.pool.ntp.org": {}}
|
||||
api.nodes.return_value.ntp.get.assert_not_called()
|
||||
|
||||
|
||||
# -- writing the zone -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pve_writes_the_zone_through_its_node_api_and_reads_it_back() -> None:
|
||||
driver, api, shell = _pve(_reading("Europe/Vienna"))
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["timezone", "verify"]
|
||||
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
|
||||
assert shell.root() == [] # not timedatectl: the API keeps /etc/timezone as well
|
||||
|
||||
|
||||
def test_in_a_cluster_only_this_node_is_written() -> None:
|
||||
driver, api, _ = _pve(_reading("Europe/Vienna"), node="pve2")
|
||||
api.nodes.reset_mock()
|
||||
|
||||
driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert {c.args for c in api.nodes.call_args_list} == {("pve2",)}
|
||||
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
|
||||
|
||||
|
||||
def test_pbs_writes_the_zone_through_its_api() -> None:
|
||||
driver, api, _ = _pbs(_reading("Europe/Vienna"), **{"PUT nodes/localhost/time": None})
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert ("PUT", "nodes/localhost/time", {"timezone": "Europe/Vienna"}) in api.calls
|
||||
|
||||
|
||||
def test_a_refused_zone_fails_the_step_and_says_why() -> None:
|
||||
"""An API token without ``Sys.Modify``: the step fails, nothing else is tried."""
|
||||
driver, api, shell = _pbs(_reading(), **{"PUT nodes/localhost/time": forbidden()})
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1]["step"] == "timezone"
|
||||
assert "403" in result["steps"][-1]["output"]
|
||||
assert shell.calls == []
|
||||
|
||||
|
||||
def test_a_zone_the_device_did_not_take_fails_verify() -> None:
|
||||
driver, api, _ = _pve(_reading("Europe/Berlin"))
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1] == {
|
||||
"step": "verify",
|
||||
"ok": False,
|
||||
"output": "the device is in the time zone Europe/Berlin",
|
||||
}
|
||||
|
||||
|
||||
def test_a_proxmoxer_error_on_the_zone_is_the_steps_output() -> None:
|
||||
driver, api, _ = _pve(_reading())
|
||||
api.nodes.return_value.time.put.side_effect = ResourceException(
|
||||
400, "Bad Request", "Parameter verification failed: timezone: No such timezone"
|
||||
)
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert not result["success"]
|
||||
assert "No such timezone" in result["steps"][0]["output"]
|
||||
|
||||
|
||||
# -- writing the servers ----------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", [_pve, _pbs], ids=["pve", "pbs"])
|
||||
def test_servers_go_to_chronys_sources_d_and_the_vendor_pool_stops_counting(make: Any) -> None:
|
||||
servers = ["10.0.0.1", "0.de.pool.ntp.org"]
|
||||
driver, _, shell = make(_reading(), _reading(servers=tuple(servers)))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=servers)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert shell.staged() == [b"server 10.0.0.1 iburst\npool 0.de.pool.ntp.org iburst\n"]
|
||||
root = shell.root()
|
||||
assert any(
|
||||
"/etc/chrony/sources.d/netork.sources" in c and c.startswith("install") for c in root
|
||||
)
|
||||
# line 8 is the vendor's pool, in the main file, which chronyd reads only when it
|
||||
# starts. Line 11, the DHCP client's sourcedir, stays: DHCP's servers count.
|
||||
sed = next(c for c in root if c.startswith("sed -i"))
|
||||
assert "8{" in sed and "11{" not in sed and sed.endswith("/etc/chrony/chrony.conf")
|
||||
assert root[-1] == "systemctl restart chrony.service"
|
||||
|
||||
|
||||
def test_a_write_gives_back_the_dhcp_sourcedir_an_earlier_write_took() -> None:
|
||||
"""A node napalm-device-types 4.35.0 aligned hears DHCP again (NetOrk/netork#2380)."""
|
||||
servers = ("10.0.0.1",)
|
||||
driver, _, shell = _pve(_reading(servers=servers, deaf_to_dhcp=True), _reading(servers=servers))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=list(servers))
|
||||
|
||||
assert result["success"], result["output"]
|
||||
root = shell.root()
|
||||
sed = next(c for c in root if c.startswith("sed -i"))
|
||||
assert "11{s/^#napalm-time-sync: (sourcedir" in sed
|
||||
assert sed.endswith("/etc/chrony/chrony.conf")
|
||||
assert root[-1] == "systemctl restart chrony.service"
|
||||
|
||||
|
||||
def test_servers_already_written_are_written_the_same_way_again() -> None:
|
||||
"""No churn: the second write stages the same file and comments out nothing."""
|
||||
servers = ("10.0.0.1",)
|
||||
driver, _, shell = _pve(_reading(servers=servers))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=list(servers))
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert shell.staged() == [b"server 10.0.0.1 iburst\n"]
|
||||
assert not [c for c in shell.root() if c.startswith("sed")]
|
||||
assert "chronyc reload sources" in shell.root()
|
||||
|
||||
|
||||
def test_both_values_in_one_change() -> None:
|
||||
driver, api, _ = _pve(_reading(), _reading("Europe/Vienna", servers=("10.0.0.1",)))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="Europe/Vienna")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
|
||||
|
||||
|
||||
def test_the_templates_refusals_hold() -> None:
|
||||
driver, api, shell = _pve(_reading())
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.configure_time_sync()
|
||||
with pytest.raises(ValueError):
|
||||
driver.configure_time_sync(ntp_servers=["not a server"])
|
||||
with pytest.raises(ValueError):
|
||||
driver.configure_time_sync(timezone="CET-1CEST,M3.5.0,M10.5.0/3")
|
||||
assert shell.calls == []
|
||||
api.nodes.return_value.time.put.assert_not_called()
|
||||
@@ -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 = (
|
||||
|
||||
@@ -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
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from napalm_proxmox import utils
|
||||
|
||||
|
||||
|
||||
@@ -41,6 +41,43 @@ class TestGetVmsReportsStringIds:
|
||||
assert [vm["vmid"] for vm in driver.get_vms()] == ["99", "1000"]
|
||||
|
||||
|
||||
class TestGetVmsTellsPausedFromRunning:
|
||||
"""PVE reports a paused guest ``status: running``; only ``qmpstatus`` tells, and only
|
||||
when the listing is asked for the full status (NetOrk/netork#2658)."""
|
||||
|
||||
@pytest.fixture
|
||||
def listed(self, driver, api):
|
||||
driver.get_vm_interfaces = MagicMock(return_value=({}, False, False))
|
||||
driver._get_vm_disk_and_boot = MagicMock(return_value=([], False))
|
||||
api.lxc.get.return_value = []
|
||||
|
||||
def statuses(*qemu):
|
||||
api.qemu.get.return_value = [
|
||||
{"vmid": 100 + i, "name": f"vm{i}", **row} for i, row in enumerate(qemu)
|
||||
]
|
||||
return {vm["vmid"]: vm["status"] for vm in driver.get_vms()}
|
||||
|
||||
return statuses
|
||||
|
||||
def test_the_listing_asks_for_the_full_status(self, listed, api):
|
||||
listed({"status": "running", "qmpstatus": "running"})
|
||||
api.qemu.get.assert_called_once_with(full=1)
|
||||
|
||||
def test_a_paused_guest_is_paused(self, listed):
|
||||
assert listed({"status": "running", "qmpstatus": "paused"}) == {"100": "paused"}
|
||||
|
||||
def test_a_guest_asleep_in_s3_is_paused(self, listed):
|
||||
"""Its QEMU process still holds its memory; ``status/resume`` wakes it."""
|
||||
assert listed({"status": "running", "qmpstatus": "suspended"}) == {"100": "paused"}
|
||||
|
||||
def test_running_and_stopped_stay_as_they_are(self, listed):
|
||||
assert listed(
|
||||
{"status": "running", "qmpstatus": "running"},
|
||||
{"status": "stopped", "qmpstatus": "stopped"},
|
||||
{"status": "running"},
|
||||
) == {"100": "running", "101": "stopped", "102": "running"}
|
||||
|
||||
|
||||
class TestResolveVm:
|
||||
def test_by_vmid_string(self, driver, api):
|
||||
assert driver._resolve_vm("100") == (100, "vm")
|
||||
@@ -84,6 +121,29 @@ class TestPowerActions:
|
||||
with pytest.raises(RuntimeError, match="container"):
|
||||
driver.suspend_vm("200")
|
||||
|
||||
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||
def test_resume_posts_status_resume_and_waits(self, driver, api, qmpstatus):
|
||||
guest = api.qemu.return_value
|
||||
guest.status.current.get.return_value = {"status": "running", "qmpstatus": qmpstatus}
|
||||
guest.status.resume.post.return_value = "UPID:resume"
|
||||
driver.resume_vm("web01")
|
||||
guest.status.resume.post.assert_called_once()
|
||||
driver._wait_for_task.assert_called_once_with("UPID:resume", timeout=120)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"current", [{"status": "running", "qmpstatus": "running"}, {"status": "stopped"}]
|
||||
)
|
||||
def test_resume_of_a_guest_that_is_not_paused_is_refused(self, driver, api, current):
|
||||
api.qemu.return_value.status.current.get.return_value = current
|
||||
with pytest.raises(RuntimeError, match="not paused"):
|
||||
driver.resume_vm("100")
|
||||
api.qemu.return_value.status.resume.post.assert_not_called()
|
||||
|
||||
def test_resume_of_a_container_is_refused(self, driver, api):
|
||||
with pytest.raises(RuntimeError, match="container 200"):
|
||||
driver.resume_vm("200")
|
||||
api.lxc.return_value.status.resume.post.assert_not_called()
|
||||
|
||||
def test_api_error_becomes_runtime_error(self, driver, api):
|
||||
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
||||
with pytest.raises(RuntimeError, match="locked"):
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Provisioning guests other than Linux: FreeBSD and OpenBSD (NetOrk/netork#794).
|
||||
|
||||
What each guest needs was found on FreeBSD 15.1 and OpenBSD 7.9 cloud images
|
||||
(NetOrk/netork#793).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from napalm_device_types.provisioning import QEMU_GUEST_AGENTS
|
||||
|
||||
from napalm_proxmox.driver import ProxmoxDriver
|
||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||
|
||||
_FREEBSD_URL = (
|
||||
"https://download.freebsd.org/releases/VM-IMAGES/15.1-RELEASE/amd64/Latest/"
|
||||
"FreeBSD-15.1-RELEASE-amd64-BASIC-CLOUDINIT-ufs.qcow2.xz"
|
||||
)
|
||||
_DEBIAN_URL = (
|
||||
"https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2"
|
||||
)
|
||||
|
||||
|
||||
def _mixin(net0: str = "virtio=BC:24:11:AA:BB:02,bridge=vmbr0") -> tuple:
|
||||
"""A mixin whose node answers like Proxmox; the VM config carries *net0*."""
|
||||
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", "net0": net0}
|
||||
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, guest_os: str, image_url: str = _DEBIAN_URL, **kwargs):
|
||||
with patch("time.sleep"):
|
||||
return mixin.create_vm_from_cloud_init(
|
||||
name="bsd-vm",
|
||||
image_url=image_url,
|
||||
cpu=2,
|
||||
memory=2048,
|
||||
nics=[{"bridge": "vmbr0"}],
|
||||
cloud_init_config={"hostname": "bsd-vm"},
|
||||
guest_os=guest_os,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _all_config_posts(vm) -> dict:
|
||||
merged: dict = {}
|
||||
for call in vm.config.post.call_args_list:
|
||||
merged.update(call.kwargs)
|
||||
return merged
|
||||
|
||||
|
||||
def _written_snippet(mixin, name: str) -> str | None:
|
||||
"""The content of the snippet *name* the driver wrote over SSH, if any."""
|
||||
for call in mixin._run_node_command.call_args_list:
|
||||
command = call.args[0]
|
||||
if f"snippets/{name}" in command and "base64 -d" in command:
|
||||
encoded = command.split("echo ", 1)[1].split(" |", 1)[0]
|
||||
return base64.b64decode(encoded).decode()
|
||||
return None
|
||||
|
||||
|
||||
class TestWhichGuestsProxmoxProvisions:
|
||||
def test_all_qemu_guests(self):
|
||||
assert ProxmoxDriver.GUEST_AGENTS == QEMU_GUEST_AGENTS
|
||||
|
||||
def test_an_unknown_guest_is_refused_before_anything_is_created(self):
|
||||
mixin, node, _ = _mixin()
|
||||
with pytest.raises(ValueError, match="windows"):
|
||||
_create(mixin, "windows")
|
||||
mixin._api.cluster.nextid.get.assert_not_called()
|
||||
node.qemu.post.assert_not_called()
|
||||
|
||||
|
||||
class TestVmShellPerGuest:
|
||||
@pytest.mark.parametrize(
|
||||
("guest_os", "ostype"), [("linux", "l26"), ("freebsd", "other"), ("openbsd", "other")]
|
||||
)
|
||||
def test_ostype(self, guest_os, ostype):
|
||||
mixin, node, _ = _mixin()
|
||||
_create(mixin, guest_os)
|
||||
assert node.qemu.post.call_args.kwargs["ostype"] == ostype
|
||||
|
||||
@pytest.mark.parametrize("guest_os", ["linux", "freebsd"])
|
||||
def test_agent_over_virtio_serial(self, guest_os):
|
||||
mixin, node, _ = _mixin()
|
||||
_create(mixin, guest_os)
|
||||
shell = node.qemu.post.call_args.kwargs
|
||||
assert shell["agent"] == "1"
|
||||
assert "serial0" not in shell
|
||||
|
||||
def test_openbsd_agent_on_the_second_isa_serial_port(self):
|
||||
"""OpenBSD's qemu-ga cannot use virtio-serial, and the image keeps its
|
||||
console on com0: the agent only answers as cua01, behind serial0."""
|
||||
mixin, node, _ = _mixin()
|
||||
_create(mixin, "openbsd")
|
||||
shell = node.qemu.post.call_args.kwargs
|
||||
assert shell["agent"] == "1,type=isa"
|
||||
assert shell["serial0"] == "socket"
|
||||
|
||||
|
||||
class TestNetworkConfigPerGuest:
|
||||
def test_linux_keeps_proxmoxs_own_network_config(self):
|
||||
mixin, _, vm = _mixin()
|
||||
_create(mixin, "linux")
|
||||
config = _all_config_posts(vm)
|
||||
assert config["cicustom"] == "user=local:snippets/101-user-data.yaml"
|
||||
assert config["ipconfig0"] == "ip=dhcp"
|
||||
assert _written_snippet(mixin, "101-network-config.yaml") is None
|
||||
|
||||
@pytest.mark.parametrize("guest_os", ["freebsd", "openbsd"])
|
||||
def test_a_bsd_guest_gets_a_v2_network_config_matched_by_its_mac(self, guest_os):
|
||||
"""FreeBSD's nuageinit fails on the v1 Proxmox writes and then skips
|
||||
runcmd, which is what starts the guest agent."""
|
||||
mixin, _, vm = _mixin(net0="virtio=BC:24:11:AA:BB:02,bridge=vmbr0")
|
||||
_create(mixin, guest_os)
|
||||
config = _all_config_posts(vm)
|
||||
assert config["cicustom"] == (
|
||||
"user=local:snippets/101-user-data.yaml,network=local:snippets/101-network-config.yaml"
|
||||
)
|
||||
assert yaml.safe_load(_written_snippet(mixin, "101-network-config.yaml")) == {
|
||||
"version": 2,
|
||||
"ethernets": {"nic0": {"match": {"macaddress": "bc:24:11:aa:bb:02"}, "dhcp4": True}},
|
||||
}
|
||||
|
||||
|
||||
class TestPackedImages:
|
||||
"""Proxmox's download-url unpacks ISOs only, so a packed image goes over SSH."""
|
||||
|
||||
def test_an_xz_image_is_unpacked_on_the_node_and_the_unpacked_file_imported(self):
|
||||
mixin, _, _ = _mixin()
|
||||
mixin._run_node_command = MagicMock(
|
||||
side_effect=lambda cmd, timeout: "MISSING" if "test -f" in cmd else ""
|
||||
)
|
||||
mixin._download_cloud_image = MagicMock(
|
||||
return_value="/var/lib/vz/template/netork-images/k-FreeBSD-15.1-ufs.qcow2.xz"
|
||||
)
|
||||
_create(mixin, "freebsd", image_url=_FREEBSD_URL, image_checksum="sha256:abc")
|
||||
|
||||
mixin._download_cloud_image.assert_called_once()
|
||||
assert mixin._download_cloud_image.call_args.args[1] == "sha256:abc" # the .xz is verified
|
||||
commands = [c.args[0] for c in mixin._run_node_command.call_args_list]
|
||||
unpack = next(c for c in commands if c.startswith("xz -dc "))
|
||||
assert "k-FreeBSD-15.1-ufs.qcow2.xz" in unpack
|
||||
importdisk = next(c for c in commands if c.startswith("qm importdisk"))
|
||||
assert ".qcow2.xz" not in importdisk
|
||||
assert ".qcow2 " in importdisk
|
||||
|
||||
def test_an_unpacked_image_already_on_the_node_is_not_downloaded_again(self):
|
||||
mixin, _, _ = _mixin()
|
||||
mixin._run_node_command = MagicMock(
|
||||
side_effect=lambda cmd, timeout: "EXISTS" if "test -f" in cmd else ""
|
||||
)
|
||||
_create(mixin, "freebsd", image_url=_FREEBSD_URL)
|
||||
|
||||
mixin._download_cloud_image.assert_not_called()
|
||||
commands = [c.args[0] for c in mixin._run_node_command.call_args_list]
|
||||
assert not any(c.startswith("xz -dc ") for c in commands)
|
||||
|
||||
def test_a_packed_image_never_goes_through_an_import_storage(self):
|
||||
mixin, node, _ = _mixin()
|
||||
node.storage.get.return_value = [
|
||||
{"storage": "local-lvm", "content": "images,rootdir", "enabled": 1},
|
||||
{"storage": "local", "content": "snippets,import", "enabled": 1},
|
||||
]
|
||||
mixin._run_node_command = MagicMock(
|
||||
side_effect=lambda cmd, timeout: "MISSING" if "test -f" in cmd else ""
|
||||
)
|
||||
_create(mixin, "freebsd", image_url=_FREEBSD_URL)
|
||||
# storage(name)("download-url").post(...) is the import-storage download.
|
||||
node.storage.return_value.return_value.post.assert_not_called()
|
||||
mixin._download_cloud_image.assert_called_once()
|
||||
|
||||
|
||||
class TestLoopbackIsNeverTheVmsAddress:
|
||||
"""OpenBSD's agent lists lo0 first (#793); Linux names it lo."""
|
||||
|
||||
def _status(self, interfaces: list) -> dict:
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
node = MagicMock()
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
node.qemu.return_value.status.current.get.return_value = {"status": "running"}
|
||||
node.qemu.return_value.agent.return_value.get.return_value = {"result": interfaces}
|
||||
with patch("time.sleep"):
|
||||
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
|
||||
|
||||
def test_openbsd_answer(self):
|
||||
"""The raw answer of OpenBSD 7.9's qemu-ga, from the spike."""
|
||||
result = self._status(
|
||||
[
|
||||
{
|
||||
"name": "lo0",
|
||||
"ip-addresses": [
|
||||
{"ip-address-type": "ipv6", "ip-address": "::1", "prefix": 128},
|
||||
{"ip-address-type": "ipv6", "ip-address": "fe80:3::1", "prefix": 64},
|
||||
{"ip-address-type": "ipv4", "ip-address": "127.0.0.1", "prefix": 8},
|
||||
],
|
||||
"hardware-address": "00:00:00:00:00:00",
|
||||
},
|
||||
{
|
||||
"name": "vio0",
|
||||
"ip-addresses": [
|
||||
{"ip-address-type": "ipv4", "ip-address": "10.0.2.15", "prefix": 24}
|
||||
],
|
||||
"hardware-address": "bc:24:11:aa:bb:04",
|
||||
},
|
||||
{"name": "enc0", "hardware-address": "00:00:00:00:00:00"},
|
||||
{"name": "pflog0", "hardware-address": "00:00:00:00:00:00"},
|
||||
]
|
||||
)
|
||||
assert result["ip_address"] == "10.0.2.15"
|
||||
assert result["mac_address"] == "bc:24:11:aa:bb:04"
|
||||
|
||||
def test_any_loopback_address_is_skipped_whatever_the_interface_is_called(self):
|
||||
result = self._status(
|
||||
[
|
||||
{
|
||||
"name": "lo1",
|
||||
"ip-addresses": [{"ip-address-type": "ipv4", "ip-address": "127.0.0.2"}],
|
||||
},
|
||||
{
|
||||
"name": "vtnet0",
|
||||
"ip-addresses": [{"ip-address-type": "ipv4", "ip-address": "10.0.0.5"}],
|
||||
},
|
||||
]
|
||||
)
|
||||
assert result["ip_address"] == "10.0.0.5"
|
||||
|
||||
|
||||
class TestDestroyRemovesEverySnippet:
|
||||
def test_user_and_network_snippets_are_read_before_the_vm_is_deleted(self):
|
||||
"""After the delete the config is gone, and the snippets stayed behind
|
||||
(napalm-proxmox#15)."""
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
node = MagicMock()
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
vm = node.qemu.return_value
|
||||
order: list[str] = []
|
||||
vm.config.get.side_effect = lambda: (
|
||||
order.append("config")
|
||||
or {
|
||||
"cicustom": "user=local:snippets/101-user-data.yaml,"
|
||||
"network=local:snippets/101-network-config.yaml"
|
||||
}
|
||||
)
|
||||
vm.delete.side_effect = lambda **kw: order.append("delete")
|
||||
node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
|
||||
|
||||
with patch("time.sleep"):
|
||||
mixin.destroy_vm("101")
|
||||
|
||||
assert order.index("config") < order.index("delete")
|
||||
deleted = [c.args[0] for c in node.storage.return_value.content.call_args_list]
|
||||
assert deleted == ["snippets/101-user-data.yaml", "snippets/101-network-config.yaml"]
|
||||
@@ -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()
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
@@ -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():
|
||||
@@ -333,7 +336,7 @@ def test_get_vm_status_with_wait_for_ip():
|
||||
# Mock VM config
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0,tag=10"}
|
||||
mock_vm.status.current.get.return_value = _RUNNING
|
||||
|
||||
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
||||
# reached via agent(...) as a callable resource, not dotted attribute
|
||||
@@ -372,7 +375,7 @@ def test_get_vm_status_skips_loopback_interface():
|
||||
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
||||
mock_vm.status.current.get.return_value = _RUNNING
|
||||
|
||||
mock_agent_call = MagicMock()
|
||||
mock_vm.agent.return_value = mock_agent_call
|
||||
@@ -407,7 +410,7 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
||||
# Mock VM config
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
||||
mock_vm.status.current.get.return_value = _RUNNING
|
||||
|
||||
# Mock guest-agent that never returns IP
|
||||
mock_agent_call = MagicMock()
|
||||
@@ -421,6 +424,114 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
||||
|
||||
|
||||
_RUNNING = {"status": "running", "qmpstatus": "running"}
|
||||
_ETH0 = {
|
||||
"name": "eth0",
|
||||
"hardware-address": "aa:bb:cc:dd:ee:00",
|
||||
"ip-addresses": [{"ip-address": "10.0.0.100", "ip-address-type": "ipv4"}],
|
||||
}
|
||||
|
||||
|
||||
def _status_of(current, interfaces=()):
|
||||
"""A mixin whose VM 101 answers ``status/current`` with *current*."""
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
node = MagicMock()
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
vm = node.qemu.return_value
|
||||
if isinstance(current, list):
|
||||
vm.status.current.get.side_effect = current
|
||||
else:
|
||||
vm.status.current.get.return_value = current
|
||||
vm.agent.return_value.get.return_value = {"result": list(interfaces)}
|
||||
return mixin, vm
|
||||
|
||||
|
||||
class TestTheStatusIsWhatProxmoxSays:
|
||||
"""``status/current``, not whether the config reads (NAPALM/napalm-proxmox#72).
|
||||
|
||||
The guest agent is asked for an address only while the VM runs.
|
||||
"""
|
||||
|
||||
def test_a_stopped_vm_is_stopped(self):
|
||||
mixin, vm = _status_of({"status": "stopped", "qmpstatus": "stopped"})
|
||||
|
||||
assert mixin.get_vm_status("101") == {"status": "stopped"}
|
||||
vm.status.current.get.assert_called_once_with()
|
||||
vm.agent.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||
def test_a_paused_vm_is_paused(self, qmpstatus):
|
||||
mixin, vm = _status_of({"status": "running", "qmpstatus": qmpstatus})
|
||||
|
||||
assert mixin.get_vm_status("101") == {"status": "paused"}
|
||||
vm.agent.assert_not_called()
|
||||
|
||||
def test_a_running_vm_is_running_with_its_address(self):
|
||||
mixin, _vm = _status_of(_RUNNING, [_ETH0])
|
||||
|
||||
assert mixin.get_vm_status("101") == {
|
||||
"status": "running",
|
||||
"ip_address": "10.0.0.100",
|
||||
"hostname": "eth0",
|
||||
"mac_address": "aa:bb:cc:dd:ee:00",
|
||||
}
|
||||
|
||||
def test_a_running_vm_whose_agent_does_not_answer_is_running(self):
|
||||
mixin, vm = _status_of(_RUNNING)
|
||||
vm.agent.return_value.get.side_effect = Exception("QEMU guest agent is not running")
|
||||
|
||||
assert mixin.get_vm_status("101") == {"status": "running"}
|
||||
|
||||
def test_a_vm_proxmox_does_not_have_is_unknown(self):
|
||||
mixin, vm = _status_of({})
|
||||
vm.status.current.get.side_effect = Exception("Configuration file does not exist")
|
||||
|
||||
assert mixin.get_vm_status("999") == {"status": "unknown"}
|
||||
|
||||
def test_waiting_for_an_address_ends_when_the_vm_stops(self):
|
||||
"""A VM that stopped will report no address: the wait ends with an error at once."""
|
||||
mixin, vm = _status_of([_RUNNING, {"status": "stopped"}])
|
||||
|
||||
with pytest.raises(RuntimeError, match="stopped"):
|
||||
with patch("time.sleep"):
|
||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
assert vm.agent.return_value.get.call_count == 1
|
||||
|
||||
def test_waiting_for_an_address_of_a_paused_vm_does_not_ask_the_agent(self):
|
||||
mixin, vm = _status_of({"status": "running", "qmpstatus": "paused"})
|
||||
|
||||
with pytest.raises(RuntimeError, match="paused"):
|
||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
vm.agent.assert_not_called()
|
||||
|
||||
def test_waiting_reads_the_status_again_on_each_round(self):
|
||||
mixin, vm = _status_of([_RUNNING, _RUNNING, _RUNNING])
|
||||
vm.agent.return_value.get.side_effect = [
|
||||
{"result": []},
|
||||
{"result": []},
|
||||
{"result": [_ETH0]},
|
||||
]
|
||||
|
||||
with patch("time.sleep"):
|
||||
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
|
||||
assert result["ip_address"] == "10.0.0.100"
|
||||
assert vm.status.current.get.call_count == 3
|
||||
|
||||
def test_a_status_that_does_not_read_while_waiting_keeps_the_wait_going(self):
|
||||
mixin, vm = _status_of([_RUNNING, Exception("timed out"), _RUNNING])
|
||||
vm.agent.return_value.get.side_effect = [
|
||||
{"result": []},
|
||||
{"result": []},
|
||||
{"result": [_ETH0]},
|
||||
]
|
||||
|
||||
with patch("time.sleep"):
|
||||
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
|
||||
assert result["ip_address"] == "10.0.0.100"
|
||||
|
||||
|
||||
def test_destroy_vm_success():
|
||||
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
@@ -459,7 +570,13 @@ def test_destroy_vm_success():
|
||||
|
||||
|
||||
def test_destroy_vm_already_stopped():
|
||||
"""destroy_vm succeeds even if VM already stopped."""
|
||||
"""destroy_vm succeeds even if VM already stopped.
|
||||
|
||||
Proxmox refuses to stop a VM that is not running, so the stop call raises.
|
||||
(A bare MagicMock as the stop task never reports "stopped": _wait_for_task
|
||||
then spun for the full timeout with sleep patched out, and every recorded
|
||||
mock call made the test take 60 s and several GB, enough for CI to kill it.)
|
||||
"""
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
|
||||
mock_node = MagicMock()
|
||||
@@ -468,6 +585,7 @@ def test_destroy_vm_already_stopped():
|
||||
# Mock VM operations
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.status.stop.post.side_effect = Exception("VM 101 not running")
|
||||
mock_vm.config.get.return_value = {}
|
||||
mock_vm.delete.return_value = None
|
||||
|
||||
@@ -478,6 +596,42 @@ def test_destroy_vm_already_stopped():
|
||||
assert mock_vm.delete.called
|
||||
|
||||
|
||||
def _destroy_mixin(delete_task: dict) -> tuple[ProxmoxVMProvisionMixin, MagicMock]:
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
node = MagicMock()
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
vm = node.qemu.return_value
|
||||
vm.status.stop.post.return_value = "UPID:pve1:125:stop"
|
||||
vm.config.get.return_value = {}
|
||||
vm.delete.return_value = "UPID:pve1:126:qmdestroy"
|
||||
tasks = {
|
||||
"UPID:pve1:125:stop": {"status": "stopped", "exitstatus": "OK"},
|
||||
"UPID:pve1:126:qmdestroy": delete_task,
|
||||
}
|
||||
node.tasks.side_effect = lambda upid: MagicMock(**{"status.get.return_value": tasks[upid]})
|
||||
return mixin, node
|
||||
|
||||
|
||||
def test_destroy_vm_waits_for_the_delete_task():
|
||||
"""destroy_vm returns once the VM is gone, not when its delete was queued (#15)."""
|
||||
mixin, node = _destroy_mixin({"status": "stopped", "exitstatus": "OK"})
|
||||
|
||||
with patch("time.sleep"):
|
||||
mixin.destroy_vm("101")
|
||||
|
||||
assert [c.args[0] for c in node.tasks.call_args_list] == [
|
||||
"UPID:pve1:125:stop",
|
||||
"UPID:pve1:126:qmdestroy",
|
||||
]
|
||||
|
||||
|
||||
def test_destroy_vm_raises_when_the_delete_task_fails():
|
||||
mixin, _ = _destroy_mixin({"status": "stopped", "exitstatus": "VM is locked (backup)"})
|
||||
|
||||
with patch("time.sleep"), pytest.raises(RuntimeError, match="VM is locked"):
|
||||
mixin.destroy_vm("101")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_network_targets
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -609,8 +763,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)
|
||||
|
||||
@@ -619,10 +774,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)
|
||||
@@ -1274,3 +1428,211 @@ def test_create_vm_cloudinit_drive_uses_image_storage_not_snippet_storage():
|
||||
cloud_init_call = next(c for c in mock_vm.config.post.call_args_list if "ide2" in c[1])
|
||||
assert cloud_init_call[1]["ide2"] == "local-zfs:cloudinit"
|
||||
assert cloud_init_call[1]["cicustom"].startswith("user=local:snippets/")
|
||||
|
||||
|
||||
def test_create_vm_passes_every_ssh_key_one_per_line():
|
||||
"""Proxmox's sshkeys is one key per line, URL-encoded (napalm-proxmox#23).
|
||||
|
||||
Joined with ";", only the first key worked. Base64 keys carry "/" and "+",
|
||||
which Proxmox's urlencoded format refuses unescaped.
|
||||
"""
|
||||
import re
|
||||
from urllib.parse import unquote
|
||||
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
mixin._node_name = "pve1"
|
||||
mock_api = MagicMock()
|
||||
mock_api.cluster.nextid.get.return_value = 110
|
||||
mock_api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
|
||||
mock_node = MagicMock()
|
||||
mock_node.storage.get.return_value = [
|
||||
{"storage": "local", "type": "dir", "content": "images,snippets", "enabled": 1},
|
||||
]
|
||||
mixin._api = mock_api
|
||||
mixin._node_api = MagicMock(return_value=mock_node)
|
||||
mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/x.qcow2")
|
||||
mixin._run_node_command = MagicMock(return_value="")
|
||||
mock_vm = mock_node.qemu.return_value
|
||||
mock_vm.config.get.return_value = {"unused0": "local:vm-110-disk-0"}
|
||||
mock_vm.status.start.post.return_value = "UPID:pve1:136:start"
|
||||
mock_node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
|
||||
keys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI/+k1 alice@example",
|
||||
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB/+k2 bob@example",
|
||||
]
|
||||
|
||||
with patch("time.sleep"):
|
||||
mixin.create_vm_from_cloud_init(
|
||||
name="keys-vm",
|
||||
image_url="https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
|
||||
cpu=1,
|
||||
memory=512,
|
||||
nics=[{"bridge": "vmbr0"}],
|
||||
cloud_init_config={},
|
||||
ssh_public_keys=keys,
|
||||
)
|
||||
|
||||
call = next(c for c in mock_vm.config.post.call_args_list if "sshkeys" in c[1])
|
||||
sshkeys = call[1]["sshkeys"]
|
||||
assert unquote(sshkeys) == "\n".join(keys)
|
||||
assert re.fullmatch(r"[-%a-zA-Z0-9_.!~*'()]*", sshkeys)
|
||||
|
||||
|
||||
class _LocalShell:
|
||||
"""The node's SSH session as a local ``sh``, *prelude* run before each command."""
|
||||
|
||||
def __init__(self, prelude: str) -> None:
|
||||
self.prelude = prelude
|
||||
|
||||
def exec_command(self, command: str, timeout: int | None = None):
|
||||
import subprocess
|
||||
|
||||
run = subprocess.run(
|
||||
["sh", "-c", self.prelude + command], capture_output=True, timeout=timeout
|
||||
)
|
||||
return _mock_ssh_exec(run.returncode, run.stdout.decode(), run.stderr.decode())
|
||||
|
||||
|
||||
# wget as it fails on a full disk: part of the file written, the reason on stderr.
|
||||
_WGET_DISK_FULL = (
|
||||
"wget() { "
|
||||
'while [ $# -gt 0 ]; do [ "$1" = -O ] && o=$2; shift; done; '
|
||||
'echo partial > "$o"; '
|
||||
'echo "$o: No space left on device" >&2; return 3; }; '
|
||||
)
|
||||
|
||||
|
||||
def test_download_cloud_image_failure_says_why_and_leaves_no_tmp(tmp_path, monkeypatch):
|
||||
"""A failed download names wget's reason and removes its .tmp (napalm-proxmox#3)."""
|
||||
import napalm_proxmox.vm_provision_mixin as module
|
||||
|
||||
monkeypatch.setattr(module, "_IMAGE_CACHE_DIR", str(tmp_path))
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
mixin._node_ssh = MagicMock(return_value=_LocalShell(_WGET_DISK_FULL))
|
||||
|
||||
with pytest.raises(RuntimeError, match="No space left on device") as err:
|
||||
mixin._download_cloud_image("https://example.org/img/debian.qcow2", None, timeout=10)
|
||||
|
||||
assert "exit 3" in str(err.value)
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
|
||||
def test_download_cloud_image_does_not_silence_wget():
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
mixin._run_node_command = MagicMock(side_effect=["MISSING", ""])
|
||||
|
||||
mixin._download_cloud_image("https://example.org/img/debian.qcow2", None, timeout=10)
|
||||
|
||||
download = mixin._run_node_command.call_args_list[1][0][0]
|
||||
assert download.startswith("wget -nv ")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The image URL in root shell commands (#43)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# A URL a tampered release feed could publish: a quote that ends hand-written
|
||||
# quoting, a command substitution and a space, each of which the node's shell
|
||||
# would act on if the URL or the file name built from it went in unquoted.
|
||||
_HOSTILE_URL = "https://example.org/$(reboot)/a b/x';reboot;'.img"
|
||||
|
||||
# reboot() records that the shell ran it; wget() saves the URL it was given as
|
||||
# the "image", so the file's content shows whether the URL arrived as one argument.
|
||||
_HOSTILE_PRELUDE = (
|
||||
'reboot() { echo injected >> "$MARK"; }; '
|
||||
"wget() { "
|
||||
"while [ $# -gt 0 ]; do "
|
||||
'[ "$1" = -O ] && o=$2; [ $# -eq 1 ] && u=$1; shift; done; '
|
||||
'printf \'%s\' "$u" > "$o"; }; '
|
||||
# The unpack step of a packed image: "xz -dc <file>" as a plain copy.
|
||||
'xz() { cat "$2"; }; '
|
||||
)
|
||||
|
||||
|
||||
def _hostile_shell(tmp_path, monkeypatch) -> ProxmoxVMProvisionMixin:
|
||||
import napalm_proxmox.vm_provision_mixin as module
|
||||
|
||||
cache = tmp_path / "cache"
|
||||
monkeypatch.setattr(module, "_IMAGE_CACHE_DIR", str(cache))
|
||||
monkeypatch.setenv("MARK", str(tmp_path / "injected"))
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
mixin._node_ssh = MagicMock(return_value=_LocalShell(_HOSTILE_PRELUDE))
|
||||
return mixin
|
||||
|
||||
|
||||
def test_a_hostile_image_url_stays_one_argument_in_every_command(tmp_path, monkeypatch):
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
mixin = _hostile_shell(tmp_path, monkeypatch)
|
||||
checksum = "sha256:" + hashlib.sha256(_HOSTILE_URL.encode()).hexdigest()
|
||||
|
||||
path = mixin._download_cloud_image(_HOSTILE_URL, checksum, timeout=10)
|
||||
|
||||
assert not (tmp_path / "injected").exists()
|
||||
assert Path(path).read_text() == _HOSTILE_URL # wget got the whole URL
|
||||
assert Path(path).parent == tmp_path / "cache"
|
||||
|
||||
|
||||
def test_the_cache_file_name_keeps_only_safe_characters(tmp_path, monkeypatch):
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
mixin = _hostile_shell(tmp_path, monkeypatch)
|
||||
|
||||
path = mixin._download_cloud_image(_HOSTILE_URL, None, timeout=10)
|
||||
|
||||
assert re.fullmatch(r"[A-Za-z0-9._+=-]+", Path(path).name)
|
||||
assert Path(path).name.endswith("-x__reboot__.img")
|
||||
|
||||
|
||||
def test_a_packed_hostile_image_is_unpacked_without_running_anything(tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
|
||||
mixin = _hostile_shell(tmp_path, monkeypatch)
|
||||
url = _HOSTILE_URL + ".xz"
|
||||
|
||||
path = mixin._cloud_image_on_node(url, None, timeout=10)
|
||||
|
||||
assert not (tmp_path / "injected").exists()
|
||||
assert Path(path).read_text() == url
|
||||
assert not path.endswith(".xz")
|
||||
|
||||
|
||||
def test_a_checksum_algorithm_outside_the_known_ones_is_refused():
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
mixin._run_node_command = MagicMock(return_value="EXISTS")
|
||||
|
||||
with pytest.raises(ValueError, match="checksum algorithm"):
|
||||
mixin._download_cloud_image(
|
||||
"https://example.org/img/debian.qcow2", "sha256;reboot;:abc", timeout=10
|
||||
)
|
||||
|
||||
assert not any("reboot" in c.args[0] for c in mixin._run_node_command.call_args_list)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The cloud-init snippet's path in a root shell command (#47)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_snippet_storage_path_stays_one_argument(tmp_path, monkeypatch):
|
||||
storage = tmp_path / "a b;reboot;$(reboot)"
|
||||
mixin = _hostile_shell(tmp_path, monkeypatch)
|
||||
|
||||
mixin._write_snippet(str(storage), "101-user-data.yaml", "#cloud-config\n")
|
||||
|
||||
assert not (tmp_path / "injected").exists()
|
||||
assert (storage / "snippets" / "101-user-data.yaml").read_text() == "#cloud-config\n"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filename", ["x;reboot;.yaml", "../../etc/cron.d/x", "a b.yaml", "$(reboot).yaml", ""]
|
||||
)
|
||||
def test_a_snippet_name_that_is_not_a_plain_file_name_is_refused(filename):
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
mixin._run_node_command = MagicMock(return_value="")
|
||||
|
||||
with pytest.raises(ValueError, match="snippet"):
|
||||
mixin._write_snippet("/var/lib/vz", filename, "#cloud-config\n")
|
||||
mixin._run_node_command.assert_not_called()
|
||||
@@ -0,0 +1,243 @@
|
||||
"""configure_zabbix_agent on a Proxmox node (NetOrk/netork#2571).
|
||||
|
||||
A node runs no container engine, so the agent cannot run as a container there. The
|
||||
template installs Debian's ``zabbix-agent`` -- or Zabbix's, where Debian has none -- and
|
||||
enables and restarts it; the node writes the configuration and opens ufw where there is
|
||||
one. pve-firewall's rules are the operator's.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import OPENED_PORTS_RECORD
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||
|
||||
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
|
||||
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
|
||||
DEBIAN = 'PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n'
|
||||
SETTINGS = {
|
||||
"server": "zabbix.example.com",
|
||||
"server_active": "zabbix.example.com",
|
||||
"listen_port": 10050,
|
||||
"allowed_sources": ["10.40.100.254"],
|
||||
"hostname": "pve-01",
|
||||
"release": "7.4",
|
||||
}
|
||||
|
||||
|
||||
class _Node:
|
||||
"""The node's root shell: files it reads, packages Debian has, what is refused."""
|
||||
|
||||
def __init__(self, *, config=STOCK, ufw=True, debian_has_it=True, refuse=""):
|
||||
self.config = config
|
||||
self.ufw = ufw
|
||||
self.debian_has_it = debian_has_it
|
||||
self.installed = False
|
||||
self.refuse = refuse
|
||||
self.ran: list[str] = []
|
||||
#: What reading the record of opened rules prints (NetOrk/netork#2693).
|
||||
self.record = ""
|
||||
#: What counting the rules left for the port prints.
|
||||
self.left = "0"
|
||||
self.record_written: str | None = None
|
||||
|
||||
def __call__(self, command: str) -> str:
|
||||
self.ran.append(command)
|
||||
out, rc = self._answer(command)
|
||||
for marker in ("__PVE_RC=", "__SVC_RC="):
|
||||
if marker in command:
|
||||
return f"{out}\n{marker}{rc}"
|
||||
return out
|
||||
|
||||
def _answer(self, command: str) -> tuple[str, int]:
|
||||
if self.refuse and self.refuse in command:
|
||||
return "E: refused", 1
|
||||
if "stat -c" in command and OPENED_PORTS_RECORD in command:
|
||||
return self.record, 0
|
||||
if "grep -c" in command:
|
||||
return self.left, 0
|
||||
if "base64 -d" in command and OPENED_PORTS_RECORD in command:
|
||||
written = re.search(r"echo (\S*) \|", command).group(1)
|
||||
self.record_written = base64.b64decode(written).decode()
|
||||
return "", 0
|
||||
if command.startswith("dpkg-query"):
|
||||
return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0
|
||||
if f"cat {CONFIG}" in command:
|
||||
return self.config, 0
|
||||
if "cat /etc/os-release" in command:
|
||||
return DEBIAN, 0
|
||||
if "command -v ufw" in command:
|
||||
return ("/usr/sbin/ufw", 0) if self.ufw else ("", 1)
|
||||
if "repo.zabbix.com" in command:
|
||||
self.debian_has_it = True
|
||||
return "ok", 0
|
||||
if "apt-get install" in command and "zabbix-agent" in command:
|
||||
if not self.debian_has_it:
|
||||
return "E: Unable to locate package zabbix-agent", 100
|
||||
self.installed = True
|
||||
return "ok", 0
|
||||
if "base64 -d" in command and CONFIG in command:
|
||||
self.config = base64.b64decode(re.search(r"echo (\S+) \|", command).group(1)).decode()
|
||||
return "ok", 0
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def node():
|
||||
return _Node()
|
||||
|
||||
|
||||
@pytest.fixture(params=[ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
|
||||
def driver(request, node):
|
||||
d = request.param("pve", "root@pam", "pw")
|
||||
d._exec_ssh_command = node
|
||||
return d
|
||||
|
||||
|
||||
def test_installs_writes_opens_and_starts(driver, node):
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
assert any("apt-get install" in c and "zabbix-agent" in c for c in node.ran)
|
||||
assert any("systemctl" in c and "restart" in c and "zabbix-agent" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, node):
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert "Server=zabbix.example.com\n" in node.config
|
||||
assert "Hostname=pve-01\n" in node.config
|
||||
assert node.config.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
|
||||
assert any(f"cp -p {CONFIG} {CONFIG}.bak" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_a_config_that_already_says_it_is_not_written(driver, node):
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
node.ran.clear()
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any("base64 -d" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_without_debian_s_package_zabbix_s_repository_is_added(driver, node):
|
||||
node.debian_has_it = False
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
repository = next(c for c in node.ran if "repo.zabbix.com" in c)
|
||||
assert "zabbix-release_latest_7.4+debian13_all.deb" in repository
|
||||
|
||||
|
||||
def test_ufw_opens_the_listen_port_for_the_sources(driver, node):
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert any("ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_without_ufw_the_firewall_is_the_operator_s(driver, node):
|
||||
node.ufw = False
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "pve-firewall rules are the operator's" in result["output"]
|
||||
assert not any("ufw allow" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_a_config_that_cannot_be_read_stops_the_fix(driver, node):
|
||||
node.refuse = f"cat {CONFIG}"
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "configure"
|
||||
|
||||
|
||||
# --- The record of the rules netOrk opened (NetOrk/netork#2693) ---------------------
|
||||
|
||||
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
|
||||
ROOT = "0 755 directory\n0 644 regular file\n"
|
||||
ZABBIX_UFW = "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
|
||||
SNMP_UFW = "v1 snmp ufw udp 161 10.40.100.254/32"
|
||||
|
||||
|
||||
def test_ufw_records_the_rule_it_added_under_the_agent(driver, node):
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
opened = next(c for c in node.ran if "ufw allow" in c)
|
||||
assert "*Skipping*) ;;" in opened
|
||||
assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened
|
||||
|
||||
|
||||
def test_the_snmp_rule_is_recorded_under_snmp(node):
|
||||
driver = ProxmoxDriver("pve", "root@pam", "pw")
|
||||
driver._exec_ssh_command = node
|
||||
|
||||
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.40.100.254"]})
|
||||
|
||||
assert any(f'"{SNMP_UFW}" >>' in c for c in node.ran)
|
||||
|
||||
|
||||
def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, node):
|
||||
node.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\n"
|
||||
|
||||
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
deletes = [c for c in node.ran if "ufw delete" in c]
|
||||
assert len(deletes) == 1
|
||||
assert "ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp" in deletes[0]
|
||||
assert node.record_written == f"{SNMP_UFW}\n"
|
||||
assert "removed" in result["steps"][2]["output"]
|
||||
assert not any("ufw allow" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, node):
|
||||
node.left = "1"
|
||||
|
||||
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any("ufw delete" in c for c in node.ran)
|
||||
assert node.record_written is None
|
||||
firewall = result["steps"][2]["output"]
|
||||
assert "netOrk recorded no rule" in firewall
|
||||
assert "1 rule(s) for tcp/10050" in firewall
|
||||
|
||||
|
||||
def test_a_record_someone_else_could_write_is_not_acted_on(driver, node):
|
||||
node.record = f"0 755 directory\n0 666 regular file\n{ZABBIX_UFW}\n"
|
||||
|
||||
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is False
|
||||
assert "writable" in result["output"]
|
||||
assert not any("ufw delete" in c for c in node.ran)
|
||||
|
||||
|
||||
def test_a_rule_that_will_not_go_stays_in_the_record(driver, node):
|
||||
node.record = ROOT + f"{ZABBIX_UFW}\n"
|
||||
node.refuse = "ufw delete"
|
||||
|
||||
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is False
|
||||
assert node.record_written is None
|
||||
|
||||
|
||||
def test_a_recorded_rule_of_another_firewall_is_not_touched(driver, node):
|
||||
"""A node's rules are ufw's; a firewalld line is not one this driver removes."""
|
||||
node.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.40.100.254/32\n"
|
||||
|
||||
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is False
|
||||
assert "iptables" in result["output"]
|
||||
assert node.record_written is None
|
||||
Reference in new issue
Block a user