Compare commits
144
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e300c740e | ||
|
|
0598a183df | ||
|
|
b6bb13009f | ||
|
|
59839b4efa | ||
|
|
c0453655b7 | ||
|
|
dc0d6345a8 | ||
|
|
f9088bae3a | ||
|
|
ca44e4405d | ||
|
|
b37672a269 | ||
|
|
bc5127b80f | ||
|
|
24089412a7 | ||
|
|
63ffc64050 | ||
|
|
4b423220bf | ||
|
|
b792f6d210 | ||
|
|
75818c3f09 | ||
|
|
1db3fb329f | ||
|
|
ff4ccc4818 | ||
|
|
fddf8af680 | ||
|
|
c2d9d7e75e | ||
|
|
685e995073 | ||
|
|
370aeed482 | ||
|
|
bc3eb86723 | ||
|
|
8159566ff4 | ||
|
|
b80a3950ac | ||
|
|
cae4859383 | ||
|
|
ad3b5b29a9 | ||
|
|
326527ddd5 | ||
|
|
f071c10cd1 | ||
|
|
93c974b8f0 | ||
|
|
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 | ||
|
|
66c9be7d25 | ||
|
|
222cd45c66 | ||
|
|
02a441ff09 | ||
|
|
1881ee7330 | ||
|
|
6bf1736619 | ||
|
|
ea74e84387 | ||
|
|
52074620ef | ||
|
|
ccb9585f4e | ||
|
|
77e65ea7bd | ||
|
|
6464a6c728 | ||
|
|
a13af149d9 | ||
|
|
a9f4cd249f | ||
|
|
741a26566f | ||
|
|
abce85d6ef |
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 }}
|
||||||
+441
@@ -7,7 +7,448 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.19.0] - 2026-11-28
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
- `install_cpu_microcode()` on both drivers (napalm-device-types' `CpuMicrocodeMixin`, 4.53.0,
|
||||||
|
NetOrk/netork#2838): the CPU vendor's microcode on a node that runs on its own CPU. A Proxmox
|
||||||
|
install enables no `non-free-firmware`, where Debian keeps `intel-microcode` and
|
||||||
|
`amd64-microcode`: it is added to Debian's own sources (never to Proxmox's or another
|
||||||
|
vendor's), the index is loaded with `apt-get update` over the exec path -- waited for, unlike
|
||||||
|
the API's refresh task -- and the package installed. Refused on a node that runs virtualized
|
||||||
|
(a PBS in a VM): its host loads the microcode. The microcode loads at the next boot.
|
||||||
|
- The hardening reading carries `virtualization` and `cpu_vendor` (napalm-device-types 4.53.0).
|
||||||
|
|
||||||
|
## [0.18.0] - 2026-11-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_pve_firewall()` on the PVE driver (NetOrk/netork#2654): the PVE firewall as the operator
|
||||||
|
wrote it, read only -- the datacenter's options, rules, security groups, IP sets and aliases,
|
||||||
|
this node's options and rules, and every guest's on this node with which of its NICs carry
|
||||||
|
`firewall=1`. Each rule keeps PVE's own fields and says where it came from. A part PVE refuses
|
||||||
|
is None, not empty: an unread level is no claim. Nothing is written; pve-firewall rules stay
|
||||||
|
the operator's.
|
||||||
|
- `get_host_firewall()` on the PVE driver (napalm-device-types' `HostFirewallMixin`): what the
|
||||||
|
node has loaded -- proxmox-firewall's nftables tables on PVE 9, pve-firewall's iptables chains
|
||||||
|
before -- read as root over SSH, as for any Linux host.
|
||||||
|
- `get_hardening()` on both drivers (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776):
|
||||||
|
the security modules, SELinux and AppArmor, the crypto policy and FIPS mode, what the kernel
|
||||||
|
reports for each CPU vulnerability, and the kernel command line (`mitigations=`, `nosmt`). One
|
||||||
|
fixed, read-only command over the exec path, which is root's login, so AppArmor's profiles per
|
||||||
|
mode are read too. A hypervisor's guests share its CPU, so its CPU vulnerabilities matter most.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Needs napalm-device-types 4.48.0 or later (`HardeningMixin`).
|
||||||
|
|
||||||
|
## [0.16.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_services_need_restart()` on both drivers (napalm-device-types' `ServicesRestartMixin`,
|
||||||
|
NetOrk/netork#2750): the services that still run code an update replaced on disk, so they
|
||||||
|
keep the old library until they restart. One fixed, read-only command over the exec path,
|
||||||
|
which is root's login: `needs-restarting -s`, else `needrestart` in list-only mode, else the
|
||||||
|
processes whose `/proc/<pid>/maps` maps deleted code, each named by its cgroup's service. A
|
||||||
|
running VM's QEMU (`qemu.slice`) is listed as a process; an LXC container's processes are
|
||||||
|
left out, since a container updates itself. It runs only when the login is root
|
||||||
|
(`id -u` is 0): another login gets no report and the read raises, rather than read as
|
||||||
|
clean what it cannot see. No stdin.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Needs napalm-device-types 4.46.0 or later (`ServicesRestartMixin`, with an LXC
|
||||||
|
container's processes left out).
|
||||||
|
|
||||||
|
## [0.15.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_certificates()` on both drivers (NetOrk/netork#2656): the node's TLS certificates from
|
||||||
|
`GET /nodes/{node}/certificates/info` (PBS: `/nodes/localhost/certificates/info`) in
|
||||||
|
netOrk's certificate contract, `{name, issuer, valid_from, valid_to, in_use_by}` with Unix
|
||||||
|
timestamps, so netOrk's expiry warnings cover a node's web UI and API certificate.
|
||||||
|
`name` is the file name (`pve-root-ca.pem`, `pve-ssl.pem`, `pveproxy-ssl.pem`; `proxy.pem` on
|
||||||
|
PBS), `issuer` and `subject` the common names, `in_use_by` 1 for the certificate the proxy
|
||||||
|
serves. `acme` is true for the certificate ACME renews (`pveproxy-ssl.pem`, PBS `proxy.pem`)
|
||||||
|
when the node's config names a domain, read with one more call (`GET /nodes/{node}/config`);
|
||||||
|
an unreadable config reads as no ACME. The PEM is not returned. Unreadable certificates are
|
||||||
|
`[]`, as on OPNsense.
|
||||||
|
|
||||||
|
## [0.14.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Proxmox VE 9.3's API additions (NetOrk/netork#2728), each taken only on a node whose
|
||||||
|
`GET /version` says 9.3 or later (`_version_at_least`); an older node does what it did.
|
||||||
|
- `get_vms()`: each guest carries PVE 9.3's `uid`, an identity that survives a migration, a
|
||||||
|
restore and a changed vmid, from one `GET /cluster/resources?type=vm` per call, joined by
|
||||||
|
node and vmid (napalm-device-types `VMDict.uid`). A guest without one, an older node and a
|
||||||
|
listing that cannot be read leave the key out; the guests are listed as before.
|
||||||
|
- `get_clusters()`: `id` is the cluster's `cluster-id` from `GET /cluster/status`, or a
|
||||||
|
standalone node's own on its node entry; None on an older node.
|
||||||
|
- `get_credential_expiry()` (napalm-device-types `CredentialExpiryMixin`): the API token
|
||||||
|
(`GET /access/users/{userid}/token/{tokenid}`) or the password's account
|
||||||
|
(`GET /access/users/{userid}`) the driver logged in with, and when it expires; a token
|
||||||
|
without an `expire` of its own expires with its user. A 403 is a `PermissionError`, any
|
||||||
|
other failure a `RuntimeError`.
|
||||||
|
- `get_update_history(since)` (napalm-device-types `UpdateMixin`): the node's APT
|
||||||
|
transactions from `GET /nodes/{node}/apt/history`, newest first, with `id`
|
||||||
|
`"{start-time}-{start-index}"`. A failed read raises; before 9.3 it is
|
||||||
|
`NotImplementedError` (no log is parsed over SSH).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `set_node_maintenance()` uses `PUT /nodes/{node}/maintenance` when the node going into
|
||||||
|
maintenance runs PVE 9.3, and opens no SSH session; that node's own version decides,
|
||||||
|
since a rolling upgrade leaves the members on different releases. An older node still
|
||||||
|
takes `ha-manager crm-command node-maintenance` over SSH.
|
||||||
|
- `resume_vm()` sets the guest's clock to the host's time on PVE 9.3
|
||||||
|
(`sync-time-on-resume=1`, through the guest agent where it runs).
|
||||||
|
- Needs napalm-device-types 4.44.0 or later (`CredentialExpiryMixin`, `UpdateHistoryDict`,
|
||||||
|
`VMDict.uid`).
|
||||||
|
|
||||||
|
## [0.13.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run
|
||||||
|
(`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`,
|
||||||
|
NetOrk/netork#2693). ufw does not say who wrote a rule, so every rule the firewall step
|
||||||
|
adds -- the Zabbix agent's tcp/`listen_port`, SNMP's udp/161 -- is now recorded in
|
||||||
|
`/var/lib/netork/opened-ports` (napalm-device-types `opened_ports`), and only when ufw did
|
||||||
|
not have it before: an identical rule the operator wrote is never recorded. Closing removes
|
||||||
|
exactly the agent's recorded rules, whatever port they opened, and rewrites the record. It
|
||||||
|
reads the record only when it is root's alone, and reports the rules for the port it left
|
||||||
|
in place: the operator's, or ones opened before this version recorded them. pve-firewall's
|
||||||
|
rules stay the operator's.
|
||||||
|
|
||||||
|
## [0.12.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `get_vm_status(vmid)` reports the VM's real state (#72): it reads
|
||||||
|
`GET /nodes/{node}/qemu/{vmid}/status/current` and answers `running`, `stopped`, or
|
||||||
|
`paused` for a `qmpstatus` of paused or suspended, the same as `get_vms()`. It used to say
|
||||||
|
`running` for every VM whose config could be read, so a caller waiting for a clean shutdown
|
||||||
|
never saw the VM stop (NetOrk/netork's workflow step "Shut down Proxmox VM" always ran into
|
||||||
|
its timeout). The guest agent is asked for an address only while the VM runs, and
|
||||||
|
`wait_for_ip=True` ends with a `RuntimeError` at once when the VM is stopped or paused,
|
||||||
|
rather than waiting out its timeout for an address that cannot come.
|
||||||
|
|
||||||
|
## [0.11.0] - 2026-11-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `resume_vm(name)` (napalm-device-types' `HypervisorDriver`, NetOrk/netork#2658): a paused
|
||||||
|
VM continues where `suspend_vm` stopped it, through `status/resume`, and the driver waits
|
||||||
|
for its task. A VM that is not paused is refused (PVE answers a running one with success
|
||||||
|
and does nothing), and so is a container: the driver does not suspend one, PVE's
|
||||||
|
container suspend is experimental, and its listing does not tell a suspended container
|
||||||
|
from another.
|
||||||
|
- A native Zabbix agent on both drivers (napalm-device-types `ZabbixAgentMixin`,
|
||||||
|
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
|
||||||
|
root disk. The image no longer passes through the node's root filesystem.
|
||||||
|
Files are named `netork-<url hash>-<name>.<qcow2|raw|vmdk>` and reused;
|
||||||
|
Ubuntu's `.img` is stored as `.qcow2`. Without such a storage, or for an
|
||||||
|
image type Proxmox cannot import, the SSH download into
|
||||||
|
`/var/lib/vz/template/netork-images` is used as before.
|
||||||
- `HypervisorDriver` contract methods `start_vm`, `stop_vm`, `reboot_vm`,
|
- `HypervisorDriver` contract methods `start_vm`, `stop_vm`, `reboot_vm`,
|
||||||
`suspend_vm` and `get_vm_config`. They accept a VM's name or vmid, raise
|
`suspend_vm` and `get_vm_config`. They accept a VM's name or vmid, raise
|
||||||
`ValueError`/`RuntimeError` instead of returning a result dict, and wait
|
`ValueError`/`RuntimeError` instead of returning a result dict, and wait
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
# napalm-proxmox
|
# 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:
|
It supports all three networking domains of Proxmox VE:
|
||||||
|
|
||||||
@@ -12,8 +15,9 @@ It supports all three networking domains of Proxmox VE:
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Python ≥ 3.9
|
- Python ≥ 3.12
|
||||||
- NAPALM ≥ 5.0.0
|
- NAPALM ≥ 5.0.0
|
||||||
|
- napalm-device-types ≥ 4.22.0
|
||||||
- proxmoxer ≥ 2.0.0
|
- proxmoxer ≥ 2.0.0
|
||||||
- netaddr ≥ 0.9.0
|
- netaddr ≥ 0.9.0
|
||||||
- requests ≥ 2.31.0
|
- requests ≥ 2.31.0
|
||||||
@@ -27,7 +31,7 @@ pip install napalm-proxmox
|
|||||||
Or directly from source:
|
Or directly from source:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/example/napalm-proxmox.git
|
git clone https://git.netork.io/NAPALM/napalm-proxmox.git
|
||||||
cd napalm-proxmox
|
cd napalm-proxmox
|
||||||
pip install -e .
|
pip install -e .
|
||||||
```
|
```
|
||||||
@@ -45,9 +49,9 @@ device = driver(
|
|||||||
username="root",
|
username="root",
|
||||||
password="secret",
|
password="secret",
|
||||||
optional_args={
|
optional_args={
|
||||||
"realm": "pam", # default: "pam"
|
"realm": "pam", # default: "pam"
|
||||||
"port": 8006, # default: 8006
|
"port": 8006, # default: 8006
|
||||||
"verify_ssl": True, # default: True
|
"verify_ssl": True, # default: True
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -102,11 +106,11 @@ device = driver(
|
|||||||
| `get_interfaces_ip` | IPv4/IPv6 from classic ifaces + SDN subnet gateways |
|
| `get_interfaces_ip` | IPv4/IPv6 from classic ifaces + SDN subnet gateways |
|
||||||
| `get_interfaces_counters` | From `node/netstat` RRD data |
|
| `get_interfaces_counters` | From `node/netstat` RRD data |
|
||||||
| `get_environment` | CPU %, memory (bytes), hardware temperature sensors |
|
| `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_mac_address_table` | `bridge fdb show` (Linux) + `ovs-appctl fdb/show` (OVS) |
|
||||||
| `get_vlans` | SDN VNet tags + `bridge vlan show` |
|
| `get_vlans` | SDN VNet tags + `bridge vlan show` |
|
||||||
| `get_network_instances` | SDN zones (VLAN→L2VPN, EVPN→L3VRF) + default instance |
|
| `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_ntp_stats` | Parses `chronyc` / `ntpq -pn` output |
|
||||||
| `get_snmp_information` | Parses `/etc/snmp/snmpd.conf` |
|
| `get_snmp_information` | Parses `/etc/snmp/snmpd.conf` |
|
||||||
| `get_users` | Proxmox access/users API + local `/etc/passwd` |
|
| `get_users` | Proxmox access/users API + local `/etc/passwd` |
|
||||||
@@ -115,13 +119,24 @@ device = driver(
|
|||||||
| `compare_config` | Unified diff |
|
| `compare_config` | Unified diff |
|
||||||
| `commit_config` | Writes `/etc/network/interfaces` + `ifreload -a` |
|
| `commit_config` | Writes `/etc/network/interfaces` + `ifreload -a` |
|
||||||
| `discard_config` / `rollback` | Revert candidate |
|
| `discard_config` / `rollback` | Revert candidate |
|
||||||
| `get_lldp_neighbors` | `lldpcli show neighbors` via exec |
|
| `get_lldp_neighbors` | `lldpctl -f keyvalue` over SSH (napalm-device-types' parser); raises when lldpctl fails |
|
||||||
| `get_lldp_neighbors_detail` | Full LLDP detail |
|
| `get_lldp_neighbors_detail` | Full LLDP detail, capabilities in NAPALM's names |
|
||||||
| `get_ipv6_neighbors_table` | `ip -6 neigh show` |
|
| `get_ipv6_neighbors_table` | `ip -6 neigh show` |
|
||||||
| `ping` | Linux `ping` via exec endpoint |
|
| `ping` | Linux `ping` over SSH |
|
||||||
| `traceroute` | `traceroute -n` via exec endpoint |
|
| `traceroute` | `traceroute -n` over SSH |
|
||||||
| `cli` | Arbitrary command execution via exec endpoint |
|
| `cli` | Arbitrary commands over SSH (stdout) |
|
||||||
| `get_route_to` | `ip route show` via exec endpoint |
|
| `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 |
|
||||||
|
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
|
||||||
|
| `get_services_need_restart` | the services that still run code an update replaced on disk, as root over SSH (napalm-device-types' `ServicesRestartMixin`): `needrestart` in list-only mode where it is installed, else the processes whose `/proc/<pid>/maps` maps deleted code. A running VM's QEMU is a process (`processes`), an LXC container's processes are left out (the container updates itself). Only as root: another SSH login gets no reading, rather than a clean one |
|
||||||
|
| `get_pve_firewall` | the PVE firewall as the operator wrote it, read only (NetOrk/netork#2654): the datacenter's `options`, `rules`, security `groups` (name → rules), `ipsets` (name → `[{cidr, nomatch, comment}]`) and `aliases` (name → cidr), this node's `options` and `rules`, and every guest's on this node (`vmid`, `type`, `name`, `options`, `rules`, and `nics`: `[{name, firewall}]` from `netN … firewall=1`). Each rule keeps PVE's fields and its `origin` (`cluster`, `group`, `node`, `guest`). A part PVE refuses is `null`, never empty |
|
||||||
|
| `get_host_firewall` | what the node has loaded, as for any Linux host (napalm-device-types' `HostFirewallMixin`): `nft list ruleset` (PVE 9's proxmox-firewall) or `iptables-save` (pve-firewall), as root over SSH |
|
||||||
|
| `get_hardening` | how the node is hardened (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776): security modules, SELinux and AppArmor, crypto policy, FIPS mode, CPU vulnerabilities, kernel command line, whether the node runs virtualized and its CPU vendor, as root over SSH. On the backup server too |
|
||||||
|
| `install_cpu_microcode` | the CPU vendor's microcode (`intel-microcode`, `amd64-microcode`; napalm-device-types' `CpuMicrocodeMixin`, NetOrk/netork#2838): Debian's `non-free-firmware` added to Debian's own sources where missing, `apt-get update` over SSH (waited for, unlike the API's refresh task), then the install. Refused on a node that runs virtualized. Loads at the next boot. On the backup server too |
|
||||||
|
|
||||||
**Not implemented** (raise `NotImplementedError`):
|
**Not implemented** (raise `NotImplementedError`):
|
||||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||||
@@ -137,6 +152,70 @@ device = driver(
|
|||||||
| `node` | str | *auto* | Override target node name |
|
| `node` | str | *auto* | Override target node name |
|
||||||
| `token_name` | str | `None` | API token identifier (`user@realm!tokenid`) |
|
| `token_name` | str | `None` | API token identifier (`user@realm!tokenid`) |
|
||||||
| `token_value` | str | `None` | API token secret |
|
| `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, services still running replaced code, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
||||||
|
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
||||||
|
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
||||||
|
| `get_certificates` | as on Proxmox VE, from `/nodes/localhost/certificates/info` and `/nodes/localhost/config`: one certificate, `proxy.pem`, which ACME renews where a domain is configured |
|
||||||
|
|
||||||
|
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
||||||
|
`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
|
## Development
|
||||||
|
|
||||||
@@ -156,9 +235,16 @@ ruff check napalm_proxmox
|
|||||||
|
|
||||||
```
|
```
|
||||||
napalm_proxmox/
|
napalm_proxmox/
|
||||||
├── __init__.py # Exports ProxmoxDriver
|
├── __init__.py # Exports ProxmoxDriver and ProxmoxBackupDriver
|
||||||
├── driver.py # ProxmoxDriver — all NAPALM methods
|
├── _base.py # What both share: connection, token split, SSH session, node helpers
|
||||||
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
├── 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
|
||||||
|
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
|
||||||
|
├── firewall_mixin.py # get_pve_firewall: the PVE firewall at every level, read only
|
||||||
|
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
||||||
tests/
|
tests/
|
||||||
├── conftest.py # Shared fixtures and mock API payloads
|
├── conftest.py # Shared fixtures and mock API payloads
|
||||||
├── test_connection.py # open / close / is_alive
|
├── test_connection.py # open / close / is_alive
|
||||||
@@ -167,8 +253,15 @@ tests/
|
|||||||
├── test_environment.py # get_environment
|
├── test_environment.py # get_environment
|
||||||
├── test_sdn.py # get_vlans, get_network_instances
|
├── test_sdn.py # get_vlans, get_network_instances
|
||||||
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
|
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
|
||||||
├── test_misc.py # NTP, SNMP, users, config, ping, traceroute, CLI, LLDP
|
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||||
└── test_utils.py # Unit tests for napalm_proxmox.utils
|
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||||
|
├── test_certificates.py # get_certificates on both drivers
|
||||||
|
├── test_firewall.py # get_pve_firewall and get_host_firewall
|
||||||
|
├── test_hardening.py # get_hardening and install_cpu_microcode on both drivers
|
||||||
|
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||||
|
├── 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
|
## 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
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
__all__ = ["ProxmoxDriver"]
|
__all__ = ["ProxmoxBackupDriver", "ProxmoxDriver"]
|
||||||
@@ -0,0 +1,430 @@
|
|||||||
|
"""What the Proxmox VE and the Proxmox Backup Server drivers share.
|
||||||
|
|
||||||
|
Both products speak the same REST dialect (``/api2/json``, ``/nodes/{node}/...``),
|
||||||
|
authenticate the same way (``user@realm`` with a password, or an API token
|
||||||
|
``user@realm!name``) and run on Debian, where the driver opens its own SSH
|
||||||
|
session as root for what the API does not offer. They differ in the service
|
||||||
|
proxmoxer talks to, its port (PVE 8006, PBS 8007) and how the node is found.
|
||||||
|
|
||||||
|
Optional args
|
||||||
|
-------------
|
||||||
|
verify_ssl : bool
|
||||||
|
Verify TLS certificates (default: True). ``ssl_verify`` and ``verify`` are
|
||||||
|
accepted as well.
|
||||||
|
port : int
|
||||||
|
API port (default: the service's, 8006 for PVE, 8007 for PBS).
|
||||||
|
realm : str
|
||||||
|
Realm a bare username logs in to (default: ``pam``).
|
||||||
|
token_name : str
|
||||||
|
API token name (e.g. ``root@pam!netork``).
|
||||||
|
token_value : str
|
||||||
|
API token secret. With both token_name and token_value, the token is used
|
||||||
|
instead of the password.
|
||||||
|
ssh_username, ssh_password, ssh_private_key_str : str
|
||||||
|
The node's SSH login; the API login's username and password otherwise.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from napalm.base.exceptions import ConnectionException
|
||||||
|
from napalm_device_types import CommandResult
|
||||||
|
from napalm_device_types.channel import run_on_transport
|
||||||
|
from napalm_device_types.ssh_host_keys import HostKeyCheck
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The release at the start of a product version, ``"9.3"`` of ``"9.3.0"``.
|
||||||
|
_RELEASE = re.compile(r"^(\d+)\.(\d+)")
|
||||||
|
|
||||||
|
#: The API port of each proxmoxer service this package drives.
|
||||||
|
DEFAULT_PORTS = {"PVE": 8006, "PBS": 8007}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxBase:
|
||||||
|
"""Connection, SSH session and node helpers of a Proxmox product's driver.
|
||||||
|
|
||||||
|
A concrete driver sets :attr:`SERVICE`, says how it finds its node
|
||||||
|
(:meth:`_resolve_node`) and constructs the proxmoxer client
|
||||||
|
(:meth:`_proxmox_api`), so its own module names the client class.
|
||||||
|
"""
|
||||||
|
|
||||||
|
#: The proxmoxer service: ``"PVE"`` or ``"PBS"``.
|
||||||
|
SERVICE = "PVE"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hostname: str,
|
||||||
|
username: str,
|
||||||
|
password: str,
|
||||||
|
timeout: int = 60,
|
||||||
|
optional_args: _JsonDict | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.hostname = hostname
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
self.timeout = timeout
|
||||||
|
self.optional_args: _JsonDict = optional_args or {}
|
||||||
|
|
||||||
|
self._port: int = self.optional_args.get("port", DEFAULT_PORTS[self.SERVICE])
|
||||||
|
verify: Any = self.optional_args.get(
|
||||||
|
"verify_ssl",
|
||||||
|
self.optional_args.get("ssl_verify", self.optional_args.get("verify", True)),
|
||||||
|
)
|
||||||
|
self._verify_ssl: bool = verify
|
||||||
|
self._realm: str = self.optional_args.get("realm", "pam")
|
||||||
|
self._token_name: str | None = self.optional_args.get("token_name")
|
||||||
|
self._token_value: str | None = self.optional_args.get("token_value")
|
||||||
|
|
||||||
|
self._ssh_username: str | None = self.optional_args.get("ssh_username")
|
||||||
|
self._ssh_password: str | None = self.optional_args.get("ssh_password")
|
||||||
|
self._ssh_key: str | None = self.optional_args.get("ssh_private_key_str")
|
||||||
|
|
||||||
|
self._api: Any = None # proxmoxer.ProxmoxAPI
|
||||||
|
self._node_name: str = ""
|
||||||
|
# paramiko.SSHClient; paramiko is imported lazily (see _node_ssh).
|
||||||
|
self._ssh_client: Any = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Connection management
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def _proxmox_api(self, **kwargs: Any) -> Any:
|
||||||
|
"""The proxmoxer client for *kwargs*; the concrete driver's module names the class."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _resolve_node(self) -> str:
|
||||||
|
"""Find the node this connection talks to and set ``_node_name``.
|
||||||
|
|
||||||
|
API errors propagate, so that ``open()`` fails with the real cause.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _api_kwargs(self) -> _JsonDict:
|
||||||
|
# Use the HTTPS backend for proper REST API support.
|
||||||
|
# The openssh backend tunnels all kwargs through to
|
||||||
|
# openssh_wrapper.CommandBaseSession, which does not
|
||||||
|
# accept password/verify_ssl/token params.
|
||||||
|
# Proxmox authenticates against "<user>@<realm>" and rejects a bare
|
||||||
|
# username outright. A caller who typed a realm keeps it; one who
|
||||||
|
# did not gets self._realm, which is what the documented `realm`
|
||||||
|
# optional_arg is for -- it was read in __init__ and then never
|
||||||
|
# used, so the option had no effect and a bare username failed.
|
||||||
|
user = self.username or ""
|
||||||
|
if user and "@" not in user:
|
||||||
|
user = f"{user}@{self._realm}"
|
||||||
|
|
||||||
|
kwargs: _JsonDict = {
|
||||||
|
"host": self.hostname,
|
||||||
|
"user": user,
|
||||||
|
"password": self.password,
|
||||||
|
"port": self._port,
|
||||||
|
"verify_ssl": self._verify_ssl,
|
||||||
|
"backend": "https",
|
||||||
|
"service": self.SERVICE,
|
||||||
|
}
|
||||||
|
|
||||||
|
if self._token_name and self._token_value:
|
||||||
|
kwargs.pop("password", None)
|
||||||
|
kwargs["token_value"] = self._token_value
|
||||||
|
# token_name may be in "<user>!<tokenid>" format (e.g.
|
||||||
|
# "root@pam!netork"). proxmoxer expects them split:
|
||||||
|
# user="root@pam", token_name="netork"
|
||||||
|
user_part, _, token_id = self._token_name.partition("!")
|
||||||
|
if token_id:
|
||||||
|
kwargs["user"] = user_part
|
||||||
|
kwargs["token_name"] = token_id
|
||||||
|
else:
|
||||||
|
kwargs["token_name"] = self._token_name
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
def open(self) -> None:
|
||||||
|
"""Open the connection to the Proxmox API."""
|
||||||
|
try:
|
||||||
|
self._api = self._proxmox_api(**self._api_kwargs())
|
||||||
|
# Validate the connection: finding the node needs a working login.
|
||||||
|
self._resolve_node()
|
||||||
|
except Exception as exc:
|
||||||
|
raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""Close the connection."""
|
||||||
|
self._api = None
|
||||||
|
if self._ssh_client:
|
||||||
|
try:
|
||||||
|
self._ssh_client.close()
|
||||||
|
except Exception:
|
||||||
|
logger.debug("%s: closing the SSH session: ignored", self.hostname, exc_info=True)
|
||||||
|
self._ssh_client = None
|
||||||
|
|
||||||
|
def is_alive(self) -> _JsonDict:
|
||||||
|
"""Return connection liveness.
|
||||||
|
|
||||||
|
Probes ``GET /version``, the cheapest endpoint that proves the session
|
||||||
|
still authenticates. It used to call ``_resolve_node()``, which returns
|
||||||
|
early without touching the API whenever a node was configured via
|
||||||
|
optional_args — so a dead connection reported itself alive.
|
||||||
|
"""
|
||||||
|
alive = False
|
||||||
|
if self._api:
|
||||||
|
try:
|
||||||
|
self._api.version.get()
|
||||||
|
alive = True
|
||||||
|
except Exception:
|
||||||
|
logger.debug("%s: liveness probe failed", self.hostname, exc_info=True)
|
||||||
|
return {"is_alive": alive}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Internal API helpers
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def _node_api(self) -> Any:
|
||||||
|
"""Return the API resource for the current node."""
|
||||||
|
return self._api.nodes(self._node_name)
|
||||||
|
|
||||||
|
def _get_node_network(self) -> list[_JsonDict]:
|
||||||
|
"""Return the node's network interface list from the Proxmox API."""
|
||||||
|
try:
|
||||||
|
return self._node_api().network.get() or []
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node network: %s", exc)
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _exec_ssh_command(self, command: str) -> str:
|
||||||
|
"""Run *command* in the node's shell over SSH and return what it printed.
|
||||||
|
|
||||||
|
Stdout only: stderr is not output (a command that wants it says
|
||||||
|
``2>&1``). The exit status is not checked; a caller that needs it asks
|
||||||
|
for it (``_rc``). The node has no API endpoint that runs a shell command
|
||||||
|
(``/nodes/{node}/execute`` runs a batch of API calls), so this is the
|
||||||
|
one way, the same session ``_run_node_command`` uses (see
|
||||||
|
NAPALM/napalm-device-types#35 for the shared transport).
|
||||||
|
|
||||||
|
:raises ConnectionException: when the command could not run: no SSH
|
||||||
|
credential, a refused login or host key (``SshHostKeyMismatch``),
|
||||||
|
an unreachable node, a timeout.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=self.timeout)
|
||||||
|
out: str = stdout.read().decode(errors="replace")
|
||||||
|
err: str = stderr.read().decode(errors="replace").strip()
|
||||||
|
except ConnectionException:
|
||||||
|
raise
|
||||||
|
except _ssh_errors() as exc:
|
||||||
|
raise ConnectionException(
|
||||||
|
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
||||||
|
) from exc
|
||||||
|
if err:
|
||||||
|
logger.debug("%s: stderr of a node command: %s", self.hostname, err[-300:])
|
||||||
|
return out.strip()
|
||||||
|
|
||||||
|
def run_command(
|
||||||
|
self,
|
||||||
|
command: str,
|
||||||
|
*,
|
||||||
|
privileged: bool = False,
|
||||||
|
timeout: float = 60,
|
||||||
|
stdin: bytes | None = None,
|
||||||
|
) -> CommandResult:
|
||||||
|
"""Run *command* on an exec channel of the node's SSH session (``CommandChannelMixin``).
|
||||||
|
|
||||||
|
stdout, stderr and the exit status come back apart; *stdin*, if given, is
|
||||||
|
written and then closed. *privileged* needs nothing more: the node is
|
||||||
|
logged in as root, as for every other command this driver runs there.
|
||||||
|
|
||||||
|
:raises ConnectionException: when the command could not run, or did not
|
||||||
|
finish within *timeout* seconds.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
transport = self._node_ssh().get_transport()
|
||||||
|
return run_on_transport(transport, command, stdin=stdin, timeout=timeout)
|
||||||
|
except ConnectionException:
|
||||||
|
raise
|
||||||
|
except _ssh_errors() as exc:
|
||||||
|
raise ConnectionException(
|
||||||
|
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
|
||||||
|
"""The SSH session to the node on port 22, opened once.
|
||||||
|
|
||||||
|
Its host key is the one the caller expects for port 22, or on first use
|
||||||
|
whichever the node presents; either way it is reported (netork#1167).
|
||||||
|
|
||||||
|
:raises ConnectionException: without a password or a usable key.
|
||||||
|
"""
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
if self._ssh_client is None:
|
||||||
|
# A key is tried first; paramiko falls back to the password. Only
|
||||||
|
# these: not the keys in the process's own ~/.ssh, nor an agent.
|
||||||
|
connect_kwargs: _JsonDict = {
|
||||||
|
"username": self._ssh_username or self.username,
|
||||||
|
"timeout": self.timeout,
|
||||||
|
"look_for_keys": False,
|
||||||
|
"allow_agent": False,
|
||||||
|
}
|
||||||
|
password = self._ssh_password or self.password
|
||||||
|
if password:
|
||||||
|
connect_kwargs["password"] = password
|
||||||
|
pkey = _load_private_key(self._ssh_key) if self._ssh_key else None
|
||||||
|
if pkey is not None:
|
||||||
|
connect_kwargs["pkey"] = pkey
|
||||||
|
if not password and pkey is None:
|
||||||
|
# An API-token-only node: nothing to log in with, so no connection.
|
||||||
|
raise ConnectionException(
|
||||||
|
f"no SSH credential for {self.hostname}: set ssh_password or "
|
||||||
|
"ssh_private_key_str"
|
||||||
|
)
|
||||||
|
client = paramiko.SSHClient()
|
||||||
|
try:
|
||||||
|
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
|
||||||
|
client, **connect_kwargs
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
client.close()
|
||||||
|
raise
|
||||||
|
self._ssh_client = client
|
||||||
|
return self._ssh_client
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Node info helpers
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def _get_version_info(self) -> _JsonDict:
|
||||||
|
"""Return the product's version info from the API."""
|
||||||
|
try:
|
||||||
|
return self._api.version.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch version info: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _version_at_least(self, major: int, minor: int, node: str | None = None) -> bool:
|
||||||
|
"""Whether the product on the node is release *major*.*minor* or newer.
|
||||||
|
|
||||||
|
Read from ``GET /version`` of the node the driver is connected to, or with
|
||||||
|
*node* from ``GET /nodes/{node}/version``: during a rolling upgrade the
|
||||||
|
cluster's members run different releases. The package ``version``
|
||||||
|
(``"9.3.0"``) decides, else the point ``release`` (``"9.3"``). A version it
|
||||||
|
cannot parse counts as older, so the caller takes the path every release
|
||||||
|
has. An API error propagates.
|
||||||
|
"""
|
||||||
|
source = self._api.nodes(node).version if node else self._api.version
|
||||||
|
info = source.get() or {}
|
||||||
|
for raw in (info.get("version"), info.get("release")):
|
||||||
|
match = _RELEASE.match(str(raw or ""))
|
||||||
|
if match:
|
||||||
|
return (int(match[1]), int(match[2])) >= (major, minor)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _get_node_status(self) -> _JsonDict:
|
||||||
|
"""Return the node's status from the Proxmox API."""
|
||||||
|
try:
|
||||||
|
return self._node_api().status.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node status: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_subscription(self) -> _JsonDict:
|
||||||
|
"""Return subscription status for this node."""
|
||||||
|
try:
|
||||||
|
return self._node_api().subscription.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node subscription: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_dns(self) -> _JsonDict:
|
||||||
|
"""Return DNS configuration for this node."""
|
||||||
|
try:
|
||||||
|
return self._node_api().dns.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node DNS: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_time(self) -> _JsonDict:
|
||||||
|
"""Return time configuration for this node."""
|
||||||
|
try:
|
||||||
|
return self._node_api().time.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node time: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _hardware(self) -> tuple[str, str, str]:
|
||||||
|
"""The physical machine's vendor, model and serial number, from the Linux DMI
|
||||||
|
sysfs entries over SSH; empty strings where they cannot be read."""
|
||||||
|
# Physical hardware info from Linux DMI sysfs.
|
||||||
|
# Read each field separately to avoid shell quoting issues with printf.
|
||||||
|
# Field priority for model:
|
||||||
|
# product_name — human-readable name on most vendors (e.g. "NUC6CAYH",
|
||||||
|
# "ThinkCentre M910x")
|
||||||
|
# product_version — sometimes the marketing name on Lenovo; on Intel NUC
|
||||||
|
# it is the board part number (less useful as model name)
|
||||||
|
# We prefer product_name; fall back to product_version only when
|
||||||
|
# product_name looks like a raw type code (all uppercase + digits, no spaces).
|
||||||
|
vendor = ""
|
||||||
|
model = ""
|
||||||
|
serial = ""
|
||||||
|
try:
|
||||||
|
dmi_cmd = (
|
||||||
|
"v=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null); "
|
||||||
|
"n=$(cat /sys/class/dmi/id/product_name 2>/dev/null); "
|
||||||
|
"r=$(cat /sys/class/dmi/id/product_version 2>/dev/null); "
|
||||||
|
"s=$(cat /sys/class/dmi/id/product_serial 2>/dev/null); "
|
||||||
|
'printf \'%s\\n%s\\n%s\\n%s\\n\' "$v" "$n" "$r" "$s"'
|
||||||
|
)
|
||||||
|
lines = self._exec_ssh_command(dmi_cmd).splitlines()
|
||||||
|
if len(lines) >= 4:
|
||||||
|
vendor = lines[0].strip()
|
||||||
|
product_name = lines[1].strip()
|
||||||
|
product_version = lines[2].strip()
|
||||||
|
serial = lines[3].strip()
|
||||||
|
|
||||||
|
_bad = {"none", "n/a", "not specified", "to be filled by o.e.m."}
|
||||||
|
pv_usable = (
|
||||||
|
product_version
|
||||||
|
and product_version.lower() not in _bad
|
||||||
|
and product_version != product_name
|
||||||
|
# Only prefer product_version when it contains a space —
|
||||||
|
# that indicates a human-readable marketing name like
|
||||||
|
# "ThinkCentre M910x" rather than a part code like "J26843-409".
|
||||||
|
and " " in product_version
|
||||||
|
)
|
||||||
|
model = product_version if pv_usable else product_name
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to read DMI info via SSH: %s", exc)
|
||||||
|
return vendor, model, serial
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# CLI passthrough
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
|
||||||
|
"""Execute a list of shell commands and return their outputs."""
|
||||||
|
return {cmd: self._exec_ssh_command(cmd) for cmd in commands}
|
||||||
|
|
||||||
|
|
||||||
|
def _load_private_key(text: str) -> Any: # paramiko.PKey; paramiko is imported lazily
|
||||||
|
"""The SSH private key in *text*, whatever its type, or None when it cannot be read."""
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
for key_class in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
|
||||||
|
try:
|
||||||
|
return key_class.from_private_key(io.StringIO(text))
|
||||||
|
except (paramiko.SSHException, ValueError):
|
||||||
|
continue
|
||||||
|
logger.warning("The SSH private key could not be read; logging in with the password")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _ssh_errors() -> tuple[type[Exception], ...]:
|
||||||
|
"""What a command that could not run raises: the socket's errors, timeouts
|
||||||
|
included, and paramiko's (a refused login, a closed session)."""
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
return (OSError, paramiko.SSHException)
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""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,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
|
EnsurePackageMixin,
|
||||||
|
FingerprintRule,
|
||||||
|
HardeningMixin,
|
||||||
|
HostStatusMixin,
|
||||||
|
KernelFactsMixin,
|
||||||
|
LicenseMixin,
|
||||||
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
|
OpenSshServerMixin,
|
||||||
|
PortSpec,
|
||||||
|
ServicePackagesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
|
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.certificates import PbsCertificatesMixin
|
||||||
|
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,
|
||||||
|
PbsCertificatesMixin,
|
||||||
|
BackupServerDriver,
|
||||||
|
StorageDriver,
|
||||||
|
KernelFactsMixin,
|
||||||
|
HardeningMixin,
|
||||||
|
ServicePackagesMixin,
|
||||||
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
|
SystemIdentityMixin,
|
||||||
|
SystemdServicesMixin,
|
||||||
|
ProxmoxScheduledJobsMixin,
|
||||||
|
HostStatusMixin,
|
||||||
|
LicenseMixin,
|
||||||
|
ProxmoxZabbixAgentMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
|
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,115 @@
|
|||||||
|
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
|
||||||
|
|
||||||
|
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
|
||||||
|
driver set: one ``{name, issuer, valid_from, valid_to, in_use_by}`` per
|
||||||
|
certificate, the validity as Unix timestamps. netOrk's expiry warnings read it
|
||||||
|
from every driver that has it.
|
||||||
|
|
||||||
|
Both products list their certificates at ``GET /nodes/{node}/certificates/info``
|
||||||
|
(PBS: ``/nodes/localhost/certificates/info``). Proxmox VE has three: its
|
||||||
|
cluster's CA (``pve-root-ca.pem``), the node certificate the CA signed
|
||||||
|
(``pve-ssl.pem``) and, where one was uploaded or ACME ordered one,
|
||||||
|
``pveproxy-ssl.pem``, which ``pveproxy`` then serves instead. A backup server has
|
||||||
|
one, ``proxy.pem``. ``in_use_by`` is 1 for the certificate the web UI and API
|
||||||
|
serve, 0 for the others.
|
||||||
|
|
||||||
|
One call more, the node's ``config``, says whether ACME renews the served
|
||||||
|
certificate (``acme``): a domain is configured (``acmedomain0``…, or
|
||||||
|
``domains=`` in the older ``acme`` property). The daily update job of either
|
||||||
|
product renews it 30 days before it runs out, so an ACME certificate close to
|
||||||
|
its end means the renewal failed. A config that cannot be read means no ACME.
|
||||||
|
|
||||||
|
``name`` is the file name, as the products' own certificate lists show it;
|
||||||
|
``issuer`` and ``subject`` are the common names. The PEM never leaves the node
|
||||||
|
reading: netOrk keeps only what it shows.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Any, ClassVar
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: ``CN=x`` in either form the products print a name in: ``/O=y/CN=x`` (PVE) or
|
||||||
|
#: ``CN = x, O = y`` (PBS).
|
||||||
|
_COMMON_NAME = re.compile(r"(?:^|[/,])\s*CN\s*=\s*([^/,]+)")
|
||||||
|
|
||||||
|
|
||||||
|
def common_name(name: str | None) -> str:
|
||||||
|
"""The CN of a distinguished name as Proxmox prints it, else the name itself."""
|
||||||
|
if not name:
|
||||||
|
return ""
|
||||||
|
found = _COMMON_NAME.search(name)
|
||||||
|
return found.group(1).strip() if found else name.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _seconds(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(value or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def acme_configured(config: _JsonDict) -> bool:
|
||||||
|
"""Whether the node's config names a domain for ACME to order a certificate for."""
|
||||||
|
if any(key.startswith("acmedomain") and value for key, value in config.items()):
|
||||||
|
return True
|
||||||
|
return "domains=" in str(config.get("acme") or "")
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxCertificatesMixin:
|
||||||
|
"""``get_certificates`` for a Proxmox VE node; the backup server sets its file names."""
|
||||||
|
|
||||||
|
#: The files the proxy serves, the first one present wins.
|
||||||
|
served_certificates: ClassVar[tuple[str, ...]] = ("pveproxy-ssl.pem", "pve-ssl.pem")
|
||||||
|
#: The file an ACME order writes.
|
||||||
|
acme_certificate: ClassVar[str] = "pveproxy-ssl.pem"
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
|
||||||
|
def get_certificates(self) -> list[_JsonDict]:
|
||||||
|
"""The node's certificates in netOrk's contract shape; ``[]`` when unreadable."""
|
||||||
|
try:
|
||||||
|
rows = self._node_api().certificates.info.get() or []
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("get_certificates() failed on %s: %s", self._node_name, exc)
|
||||||
|
return []
|
||||||
|
files = [row.get("filename") for row in rows]
|
||||||
|
served = next((f for f in self.served_certificates if f in files), None)
|
||||||
|
acme = self.acme_certificate in files and self._acme_configured()
|
||||||
|
return [self._certificate(row, served, acme) for row in rows]
|
||||||
|
|
||||||
|
def _acme_configured(self) -> bool:
|
||||||
|
try:
|
||||||
|
return acme_configured(self._node_api().config.get() or {})
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("node config unreadable on %s: %s", self._node_name, exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _certificate(self, row: _JsonDict, served: str | None, acme: bool) -> _JsonDict:
|
||||||
|
filename = str(row.get("filename") or "")
|
||||||
|
return {
|
||||||
|
"name": filename,
|
||||||
|
"issuer": common_name(row.get("issuer")),
|
||||||
|
"valid_from": _seconds(row.get("notbefore")),
|
||||||
|
"valid_to": _seconds(row.get("notafter")),
|
||||||
|
"in_use_by": 1 if filename == served else 0,
|
||||||
|
"subject": common_name(row.get("subject")),
|
||||||
|
"fingerprint": row.get("fingerprint") or "",
|
||||||
|
"acme": acme and filename == self.acme_certificate,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class PbsCertificatesMixin(ProxmoxCertificatesMixin):
|
||||||
|
"""A backup server has one certificate, ``proxy.pem``, which ACME renews too."""
|
||||||
|
|
||||||
|
served_certificates: ClassVar[tuple[str, ...]] = ("proxy.pem",)
|
||||||
|
acme_certificate: ClassVar[str] = "proxy.pem"
|
||||||
@@ -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,309 @@
|
|||||||
|
"""HypervisorDriver.get_clusters() for Proxmox VE: the cluster this node belongs to.
|
||||||
|
|
||||||
|
Every PVE node can read its whole cluster, so the getter always reports exactly
|
||||||
|
one cluster, the one the connected node is a member of (a standalone node is a
|
||||||
|
cluster of one, without a name). Read from:
|
||||||
|
|
||||||
|
- ``GET /cluster/status``: the cluster's name, quorum and (PVE 9.3) ``cluster-id``,
|
||||||
|
and every member with ``online`` and ``local``;
|
||||||
|
- ``GET /cluster/resources``: per node ``maxcpu``, ``cpu``, ``maxmem``, ``mem``;
|
||||||
|
per node and storage one row with ``plugintype``, ``shared``, ``content``,
|
||||||
|
``maxdisk``, ``disk`` and ``status``;
|
||||||
|
- ``GET /nodes/{node}/status`` of each online node: ``cpuinfo``;
|
||||||
|
- ``GET /nodes/{node}/network`` of each online node: its bridges;
|
||||||
|
- ``GET /cluster/sdn/vnets`` and ``/cluster/sdn/zones``: the vnets, on the nodes
|
||||||
|
of their zone;
|
||||||
|
- ``GET /cluster/ha/status/manager_status``: which node is in maintenance;
|
||||||
|
- quorum votes and HA resources: see ``cluster_ha``; backup jobs and backups:
|
||||||
|
see ``cluster_backups``. Each of those is best-effort and None when it cannot
|
||||||
|
be read, without failing the rest of the report.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||||
|
|
||||||
|
from napalm_proxmox.cluster_backups import read_backup_jobs, read_backups
|
||||||
|
from napalm_proxmox.cluster_ha import read_ha_resources, read_votes
|
||||||
|
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||||
|
from napalm_proxmox.pve_values import split_list as _list
|
||||||
|
from napalm_proxmox.pve_values import to_flag as _flag
|
||||||
|
from napalm_proxmox.pve_values import to_int as _int
|
||||||
|
from napalm_proxmox.utils import cpu_flags
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
# Type-only: the cluster models are newer than the napalm_device_types floor
|
||||||
|
# in pyproject.toml, and nothing here needs them at runtime.
|
||||||
|
from napalm_device_types import (
|
||||||
|
BackupServerRefDict,
|
||||||
|
ClusterDict,
|
||||||
|
ClusterNetworkDict,
|
||||||
|
ClusterNodeDict,
|
||||||
|
ClusterStorageDict,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
class _Member(NamedTuple):
|
||||||
|
name: str
|
||||||
|
online: bool
|
||||||
|
local: bool
|
||||||
|
|
||||||
|
|
||||||
|
class _Cpu(NamedTuple):
|
||||||
|
cores: int | None = None
|
||||||
|
model: str | None = None
|
||||||
|
flags: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _float(value: Any) -> float | None:
|
||||||
|
return None if value is None else float(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _size(rows: list[_JsonDict], key: str, shared: bool) -> int | None:
|
||||||
|
"""One storage's size over the nodes in *rows*: summed unless it is shared."""
|
||||||
|
values = [row.get(key) for row in rows]
|
||||||
|
if not values or any(value is None for value in values):
|
||||||
|
return None
|
||||||
|
sizes = [int(value) for value in values if value is not None]
|
||||||
|
return sizes[0] if shared else sum(sizes)
|
||||||
|
|
||||||
|
|
||||||
|
def _storage(name: str, rows: list[_JsonDict]) -> ClusterStorageDict:
|
||||||
|
shared = any(_flag(row.get("shared")) for row in rows)
|
||||||
|
available = [row for row in rows if row.get("status") == "available"]
|
||||||
|
return {
|
||||||
|
"name": name,
|
||||||
|
"type": str(rows[0].get("plugintype") or ""),
|
||||||
|
"shared": shared,
|
||||||
|
"content": _list(rows[0].get("content")),
|
||||||
|
"nodes": [str(row.get("node")) for row in available],
|
||||||
|
"total": _size(available, "maxdisk", shared),
|
||||||
|
"used": _size(available, "disk", shared),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _storages(resources: list[_JsonDict]) -> list[ClusterStorageDict]:
|
||||||
|
groups: dict[str, list[_JsonDict]] = {}
|
||||||
|
for row in resources:
|
||||||
|
if row.get("type") == "storage" and row.get("storage"):
|
||||||
|
groups.setdefault(str(row["storage"]), []).append(row)
|
||||||
|
return [_storage(name, rows) for name, rows in groups.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_server_ref(config: _JsonDict) -> BackupServerRefDict:
|
||||||
|
"""Which server and datastore a ``pbs`` storage writes to (``/storage``); never
|
||||||
|
its password or encryption key."""
|
||||||
|
port = config.get("port")
|
||||||
|
return {
|
||||||
|
"server": str(config.get("server") or ""),
|
||||||
|
"port": int(port) if port else None,
|
||||||
|
"datastore": str(config.get("datastore") or ""),
|
||||||
|
"namespace": config.get("namespace") or None,
|
||||||
|
"fingerprint": config.get("fingerprint") or None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _name_backup_servers(storages: list[ClusterStorageDict], api: Any) -> None:
|
||||||
|
"""Give each ``pbs`` storage in *storages* its ``backup_server`` (#55); None for
|
||||||
|
all of them when ``/storage`` cannot be read."""
|
||||||
|
pbs = [s for s in storages if s["type"] == "pbs"]
|
||||||
|
if not pbs:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
configs = {str(c.get("storage")): c for c in api.storage.get() or []}
|
||||||
|
except Exception:
|
||||||
|
logger.debug("/storage could not be read; the backup servers stay unnamed", exc_info=True)
|
||||||
|
configs = None
|
||||||
|
for storage in pbs:
|
||||||
|
config = configs.get(storage["name"]) if configs is not None else None
|
||||||
|
storage["backup_server"] = _backup_server_ref(config) if config else None
|
||||||
|
|
||||||
|
|
||||||
|
def _cluster_id(head: _JsonDict | None, status: list[_JsonDict]) -> str | None:
|
||||||
|
"""``cluster-id`` (PVE 9.3) of the cluster entry, or of a standalone node's own entry."""
|
||||||
|
entry = head or next((s for s in status if s.get("type") == "node"), {})
|
||||||
|
return str(entry.get("cluster-id") or "") or None
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]:
|
||||||
|
merged: dict[str, ClusterNetworkDict] = {}
|
||||||
|
for node, network in per_node:
|
||||||
|
for target in bridge_targets(network):
|
||||||
|
entry = merged.setdefault(
|
||||||
|
target["name"],
|
||||||
|
{"name": target["name"], "kind": "bridge", "vlan_aware": True, "nodes": []},
|
||||||
|
)
|
||||||
|
entry["vlan_aware"] = entry["vlan_aware"] and target["vlan_aware"]
|
||||||
|
entry["nodes"].append(node)
|
||||||
|
return list(merged.values())
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxClusterMixin:
|
||||||
|
"""Relies on ``_api``/``_node_name`` from the driver and the SDN readers."""
|
||||||
|
|
||||||
|
_api: Any
|
||||||
|
_node_name: str
|
||||||
|
_get_sdn_vnets: Any
|
||||||
|
_get_sdn_zones: Any
|
||||||
|
|
||||||
|
def get_clusters(self) -> list[ClusterDict]:
|
||||||
|
"""
|
||||||
|
Return the one cluster this node belongs to, its nodes, storages and networks.
|
||||||
|
|
||||||
|
- ``id`` is the ``cluster-id`` of PVE 9.3, a random identifier the cluster
|
||||||
|
keeps when it is renamed; a standalone node reports its own on its node
|
||||||
|
entry. None on an older node. ``name`` and ``quorate`` are None on a
|
||||||
|
standalone node, which reports itself as a cluster of one.
|
||||||
|
- Every member is listed. An offline node has ``status`` ``"offline"`` and
|
||||||
|
no capacity values: its own API cannot be asked. ``local`` marks the
|
||||||
|
node ``/cluster/status`` calls local, or else the node this driver
|
||||||
|
talks to. ``maintenance`` comes from the HA manager; when that cannot
|
||||||
|
be read (no HA stack, no permission) or does not track a node, it is
|
||||||
|
None. If another node's status cannot be read although the cluster
|
||||||
|
calls it online, its CPU fields are None and its bridges are not
|
||||||
|
listed; the own node's must be readable.
|
||||||
|
- A storage is one entry per name, with the nodes it is ``available``
|
||||||
|
on. ``total``/``used``: a shared storage is the same space on every
|
||||||
|
node, so it is one node's figure; a local storage of that name is a
|
||||||
|
separate disk on each node, so the figures of its nodes add up — the
|
||||||
|
room any single node has is less. None when no node reports it.
|
||||||
|
- Networks: each bridge once, with every online node that has one of
|
||||||
|
that name; ``vlan_aware`` only if it is on all of them. A vnet is on
|
||||||
|
the nodes of its zone, all members when the zone names none.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
Whatever the API raises for ``/cluster/status``, ``/cluster/resources``
|
||||||
|
or the own node: a getter that cannot read does not report less.
|
||||||
|
"""
|
||||||
|
status = self._api.cluster.status.get() or []
|
||||||
|
resources = self._api.cluster.resources.get() or []
|
||||||
|
head = next((s for s in status if s.get("type") == "cluster"), None)
|
||||||
|
members = self._members(status if head else [])
|
||||||
|
storages = _storages(resources)
|
||||||
|
_name_backup_servers(storages, self._api)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": _cluster_id(head, status),
|
||||||
|
"name": (head.get("name") or None) if head else None,
|
||||||
|
"quorate": _flag(head.get("quorate")) if head else None,
|
||||||
|
"nodes": self._cluster_nodes(members, resources),
|
||||||
|
"storages": storages,
|
||||||
|
"networks": self._networks(members),
|
||||||
|
"ha_resources": read_ha_resources(self._api),
|
||||||
|
"backup_jobs": read_backup_jobs(self._api),
|
||||||
|
"backups": read_backups(self._api, storages, self._node_name),
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
def _cluster_nodes(
|
||||||
|
self, members: list[_Member], resources: list[_JsonDict]
|
||||||
|
) -> list[ClusterNodeDict]:
|
||||||
|
rows = {r.get("node"): r for r in resources if r.get("type") == "node"}
|
||||||
|
maintenance, votes = self._maintenance(), read_votes(self._api)
|
||||||
|
return [self._cluster_node(m, rows.get(m.name, {}), maintenance, votes) for m in members]
|
||||||
|
|
||||||
|
def _networks(self, members: list[_Member]) -> list[ClusterNetworkDict]:
|
||||||
|
online = [m for m in members if m.online]
|
||||||
|
return [
|
||||||
|
*_merge_bridges([(m.name, self._node_network(m)) for m in online]),
|
||||||
|
*self._vnets([m.name for m in members]),
|
||||||
|
]
|
||||||
|
|
||||||
|
def _members(self, status: list[_JsonDict]) -> list[_Member]:
|
||||||
|
entries = [s for s in status if s.get("type") == "node" and s.get("name")]
|
||||||
|
if not entries:
|
||||||
|
return [_Member(self._node_name, online=True, local=True)]
|
||||||
|
any_local = any(_flag(s.get("local")) for s in entries)
|
||||||
|
return [
|
||||||
|
_Member(
|
||||||
|
str(s["name"]),
|
||||||
|
online=_flag(s.get("online")),
|
||||||
|
local=_flag(s.get("local")) if any_local else s["name"] == self._node_name,
|
||||||
|
)
|
||||||
|
for s in entries
|
||||||
|
]
|
||||||
|
|
||||||
|
def _maintenance(self) -> dict[str, bool] | None:
|
||||||
|
try:
|
||||||
|
status = self._api.cluster.ha.status.manager_status.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Cannot read the HA manager status: %s", exc)
|
||||||
|
return None
|
||||||
|
node_status = (status.get("manager_status") or {}).get("node_status") or {}
|
||||||
|
return {str(node): state == "maintenance" for node, state in node_status.items()}
|
||||||
|
|
||||||
|
def _read_node(self, member: _Member, path: str) -> Any:
|
||||||
|
"""``GET /nodes/{node}/{path}``; None for another node that does not answer."""
|
||||||
|
try:
|
||||||
|
return getattr(self._api.nodes(member.name), path).get()
|
||||||
|
except Exception as exc:
|
||||||
|
if member.local:
|
||||||
|
raise
|
||||||
|
logger.warning("Cannot read %s of cluster node %s: %s", path, member.name, exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _node_network(self, member: _Member) -> list[_JsonDict]:
|
||||||
|
return self._read_node(member, "network") or []
|
||||||
|
|
||||||
|
def _cpu(self, member: _Member) -> _Cpu:
|
||||||
|
status = self._read_node(member, "status")
|
||||||
|
if status is None:
|
||||||
|
return _Cpu()
|
||||||
|
info = status.get("cpuinfo") or {}
|
||||||
|
cores, sockets = info.get("cores"), info.get("sockets")
|
||||||
|
return _Cpu(
|
||||||
|
cores=int(cores) * int(sockets) if cores and sockets else None,
|
||||||
|
model=info.get("model") or None,
|
||||||
|
flags=cpu_flags(status),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _cluster_node(
|
||||||
|
self,
|
||||||
|
member: _Member,
|
||||||
|
row: _JsonDict,
|
||||||
|
maintenance: dict[str, bool] | None,
|
||||||
|
votes: dict[str, int] | None,
|
||||||
|
) -> ClusterNodeDict:
|
||||||
|
if not member.online:
|
||||||
|
row, cpu = {}, _Cpu()
|
||||||
|
else:
|
||||||
|
cpu = self._cpu(member)
|
||||||
|
return {
|
||||||
|
"name": member.name,
|
||||||
|
"status": "online" if member.online else "offline",
|
||||||
|
"local": member.local,
|
||||||
|
"maintenance": None if maintenance is None else maintenance.get(member.name),
|
||||||
|
"cpu_threads": _int(row.get("maxcpu")),
|
||||||
|
"cpu_cores": cpu.cores,
|
||||||
|
"cpu_model": cpu.model,
|
||||||
|
"cpu_flags": cpu.flags,
|
||||||
|
"cpu_usage": _float(row.get("cpu")),
|
||||||
|
"memory_total": _int(row.get("maxmem")),
|
||||||
|
"memory_used": _int(row.get("mem")),
|
||||||
|
"votes": None if votes is None else votes.get(member.name),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _vnets(self, members: list[str]) -> list[ClusterNetworkDict]:
|
||||||
|
vnets = self._get_sdn_vnets()
|
||||||
|
zones = {z.get("zone"): z for z in self._get_sdn_zones()} if vnets else {}
|
||||||
|
networks: list[ClusterNetworkDict] = []
|
||||||
|
for vnet in vnets:
|
||||||
|
target, zone = vnet_target(vnet), zones.get(vnet.get("zone"))
|
||||||
|
if target is None or zone is None:
|
||||||
|
continue
|
||||||
|
only = set(_list(zone.get("nodes")))
|
||||||
|
networks.append(
|
||||||
|
{
|
||||||
|
"name": target["name"],
|
||||||
|
"kind": "vnet",
|
||||||
|
"vlan_aware": False,
|
||||||
|
"fixed_vlan_tag": target.get("fixed_vlan_tag"),
|
||||||
|
"nodes": [n for n in members if not only or n in only],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return networks
|
||||||
@@ -19,7 +19,6 @@ from __future__ import annotations
|
|||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
@@ -44,13 +43,9 @@ class ProxmoxConfigMixin:
|
|||||||
configs: _JsonDict = {"running": "", "candidate": "", "startup": ""}
|
configs: _JsonDict = {"running": "", "candidate": "", "startup": ""}
|
||||||
|
|
||||||
if retrieve in ("running", "all", "startup"):
|
if retrieve in ("running", "all", "startup"):
|
||||||
raw = self._exec_ssh_command(
|
raw = self._exec_ssh_command("cat /etc/network/interfaces 2>/dev/null || true")
|
||||||
"cat /etc/network/interfaces 2>/dev/null || true"
|
|
||||||
)
|
|
||||||
# Append SDN config if available
|
# Append SDN config if available
|
||||||
sdn_raw = self._exec_ssh_command(
|
sdn_raw = self._exec_ssh_command("cat /etc/pve/sdn/vnets.cfg 2>/dev/null || true")
|
||||||
"cat /etc/pve/sdn/vnets.cfg 2>/dev/null || true"
|
|
||||||
)
|
|
||||||
running = raw
|
running = raw
|
||||||
if sdn_raw:
|
if sdn_raw:
|
||||||
running += "\n# === SDN VNets ===\n" + sdn_raw
|
running += "\n# === SDN VNets ===\n" + sdn_raw
|
||||||
@@ -119,12 +114,12 @@ class ProxmoxConfigMixin:
|
|||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
Full programmatic apply requires the Proxmox API to accept raw
|
Full programmatic apply requires the Proxmox API to accept raw
|
||||||
interface configs. This implementation uses ``pvesh`` via exec
|
interface configs. This implementation uses ``pvesh`` over the
|
||||||
which requires the node exec endpoint to be available.
|
node's SSH session.
|
||||||
"""
|
"""
|
||||||
if not self._candidate_config:
|
if not self._candidate_config:
|
||||||
return
|
return
|
||||||
# Write via exec endpoint
|
# Write over the node's SSH session
|
||||||
escaped = self._candidate_config.replace("'", "'\\''")
|
escaped = self._candidate_config.replace("'", "'\\''")
|
||||||
self._exec_ssh_command(
|
self._exec_ssh_command(
|
||||||
f"printf '%s' '{escaped}' > /etc/network/interfaces && "
|
f"printf '%s' '{escaped}' > /etc/network/interfaces && "
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""When the credential the Proxmox VE driver logs in with expires (NetOrk/netork#2728).
|
||||||
|
|
||||||
|
``CredentialExpiryMixin`` of napalm-device-types. The driver logs in either with
|
||||||
|
an API token (``user@realm!tokenid``) or with a user's password:
|
||||||
|
|
||||||
|
- a token: ``GET /access/users/{userid}/token/{tokenid}``, its ``expire``. A token
|
||||||
|
without one of its own expires with its user (the schema's default, "same as
|
||||||
|
user"), read as for a password;
|
||||||
|
- a password: ``GET /access/users/{userid}``, the account's ``expire``.
|
||||||
|
|
||||||
|
``0`` or no value is never. PVE 9.3's datacenter ``token-policy`` can require an
|
||||||
|
expiry on every token; the fields themselves are older, so every release is read.
|
||||||
|
PVE lets a user read itself and its tokens; a privilege-separated token may be
|
||||||
|
refused its user (``User.Modify`` or ``Sys.Audit`` on the user's group), and a
|
||||||
|
403 is a ``PermissionError``, as the contract says.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from napalm_device_types import CredentialExpiryDict, CredentialExpiryMixin
|
||||||
|
from proxmoxer.core import ResourceException
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _expires(value: Any) -> int | None:
|
||||||
|
"""PVE's ``expire``: unix seconds, ``0`` or none for never."""
|
||||||
|
return int(value or 0) or None
|
||||||
|
|
||||||
|
|
||||||
|
def _read(get: Callable[[], Any], what: str) -> _JsonDict:
|
||||||
|
"""``get()``'s answer; a refusal as ``PermissionError``, another failure as
|
||||||
|
``RuntimeError``."""
|
||||||
|
try:
|
||||||
|
answer = get()
|
||||||
|
except ResourceException as exc:
|
||||||
|
if exc.status_code == 403:
|
||||||
|
raise PermissionError(f"Proxmox VE will not tell {what}'s expiry: {exc}") from exc
|
||||||
|
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||||
|
return dict(answer or {})
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
|
||||||
|
"""Relies on the driver's ``_api`` and its login (``_api_kwargs``)."""
|
||||||
|
|
||||||
|
_api: Any
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
|
||||||
|
def _api_kwargs(self) -> _JsonDict: ...
|
||||||
|
|
||||||
|
def get_credential_expiry(self) -> CredentialExpiryDict:
|
||||||
|
"""The API token or the account this connection logged in with, and its expiry."""
|
||||||
|
login = self._api_kwargs()
|
||||||
|
userid = str(login["user"])
|
||||||
|
if "token_value" not in login:
|
||||||
|
return {"kind": "account", "name": userid, "expires": self._user_expiry(userid)}
|
||||||
|
name = f"{userid}!{login['token_name']}"
|
||||||
|
token = _read(lambda: self._api.access.users(userid).token(login["token_name"]).get(), name)
|
||||||
|
expire = token.get("expire")
|
||||||
|
return {
|
||||||
|
"kind": "api-token",
|
||||||
|
"name": name,
|
||||||
|
"expires": self._user_expiry(userid) if expire is None else _expires(expire),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _user_expiry(self, userid: str) -> int | None:
|
||||||
|
return _expires(_read(lambda: self._api.access.users(userid).get(), userid).get("expire"))
|
||||||
+119
-318
@@ -12,19 +12,11 @@ NAPALM API allows it.
|
|||||||
|
|
||||||
Optional args
|
Optional args
|
||||||
-------------
|
-------------
|
||||||
verify_ssl : bool
|
The connection's are the shared base's (``napalm_proxmox._base``; the API port
|
||||||
Verify TLS certificates (default: True).
|
defaults to 8006 here). In addition:
|
||||||
port : int
|
|
||||||
Proxmox API port (default: 8006).
|
|
||||||
node : str
|
node : str
|
||||||
Override the target node name (default: auto-detected from hostname).
|
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
|
from __future__ import annotations
|
||||||
@@ -32,28 +24,58 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
from napalm_device_types import FingerprintRule, HypervisorDriver, PortSpec
|
|
||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
|
from napalm_device_types import (
|
||||||
|
AptProxyMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
|
EnsurePackageMixin,
|
||||||
|
FingerprintRule,
|
||||||
|
HardeningMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
|
HostStatusMixin,
|
||||||
|
HypervisorDriver,
|
||||||
|
KernelFactsMixin,
|
||||||
|
LicenseMixin,
|
||||||
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
|
OpenSshServerMixin,
|
||||||
|
PortSpec,
|
||||||
|
ServicePackagesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
|
SnmpAgentMixin,
|
||||||
|
SystemdServicesMixin,
|
||||||
|
SystemIdentityMixin,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from proxmoxer import ProxmoxAPI
|
from proxmoxer import ProxmoxAPI
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
raise ImportError(
|
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
|
||||||
"proxmoxer is required: pip install proxmoxer"
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
from napalm_proxmox._base import ProxmoxBase
|
||||||
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
from napalm_proxmox.certificates import ProxmoxCertificatesMixin
|
||||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
||||||
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
||||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
||||||
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
from napalm_proxmox.firewall_mixin import ProxmoxFirewallMixin
|
||||||
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||||
|
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||||
from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
|
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.system_mixin import ProxmoxSystemMixin
|
||||||
|
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||||
|
from napalm_proxmox.update_history import ProxmoxUpdateHistoryMixin
|
||||||
|
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
||||||
|
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||||
|
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||||
|
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||||
|
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
|
||||||
|
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
# Type aliases
|
# Type aliases
|
||||||
@@ -66,6 +88,7 @@ _JsonDict = dict[str, Any]
|
|||||||
|
|
||||||
|
|
||||||
class ProxmoxDriver(
|
class ProxmoxDriver(
|
||||||
|
ProxmoxBase,
|
||||||
ProxmoxInterfaceMixin,
|
ProxmoxInterfaceMixin,
|
||||||
ProxmoxSDNMixin,
|
ProxmoxSDNMixin,
|
||||||
ProxmoxLLDPMixin,
|
ProxmoxLLDPMixin,
|
||||||
@@ -74,18 +97,54 @@ class ProxmoxDriver(
|
|||||||
ProxmoxVMContractMixin,
|
ProxmoxVMContractMixin,
|
||||||
ProxmoxVMSnapshotMixin,
|
ProxmoxVMSnapshotMixin,
|
||||||
ProxmoxVMProvisionMixin,
|
ProxmoxVMProvisionMixin,
|
||||||
|
ProxmoxClusterMixin,
|
||||||
|
ProxmoxVMMigrateMixin,
|
||||||
ProxmoxRoutingMixin,
|
ProxmoxRoutingMixin,
|
||||||
ProxmoxSystemMixin,
|
ProxmoxSystemMixin,
|
||||||
|
ProxmoxHostMixin,
|
||||||
|
ProxmoxFirewallMixin,
|
||||||
|
KernelFactsMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
|
HardeningMixin,
|
||||||
|
ServicePackagesMixin,
|
||||||
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
|
SystemIdentityMixin,
|
||||||
|
SystemdServicesMixin,
|
||||||
|
ProxmoxScheduledJobsMixin,
|
||||||
|
ProxmoxRunningBackupsMixin,
|
||||||
|
ProxmoxTimeSyncMixin,
|
||||||
|
ProxmoxCertificatesMixin,
|
||||||
|
ProxmoxCredentialExpiryMixin,
|
||||||
|
ProxmoxUpdateHistoryMixin,
|
||||||
|
HostStatusMixin,
|
||||||
|
LicenseMixin,
|
||||||
|
SnmpAgentMixin,
|
||||||
|
ProxmoxZabbixAgentMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
|
EnsurePackageMixin,
|
||||||
|
AptProxyMixin,
|
||||||
|
OpenSshServerMixin,
|
||||||
HypervisorDriver,
|
HypervisorDriver,
|
||||||
):
|
):
|
||||||
"""NAPALM driver for Proxmox VE nodes."""
|
"""NAPALM driver for Proxmox VE nodes."""
|
||||||
|
|
||||||
VENDOR = "Proxmox"
|
VENDOR = "Proxmox"
|
||||||
DRIVER_NAME = "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
|
USES_SSH = False
|
||||||
# A PVE node reboots through a full init sequence plus storage checks.
|
# A PVE node reboots through a full init sequence plus storage checks.
|
||||||
REBOOT_SETTLE_SECONDS = 90
|
REBOOT_SETTLE_SECONDS = 90
|
||||||
|
#: "Upgrade everything" must be a full upgrade on Proxmox VE: a plain
|
||||||
|
#: ``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 = [
|
PORT_SPECS = [
|
||||||
PortSpec("https", 8006, weight=8.0),
|
PortSpec("https", 8006, weight=8.0),
|
||||||
]
|
]
|
||||||
@@ -107,29 +166,9 @@ class ProxmoxDriver(
|
|||||||
timeout: int = 60,
|
timeout: int = 60,
|
||||||
optional_args: _JsonDict | None = None,
|
optional_args: _JsonDict | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.hostname = hostname
|
super().__init__(hostname, username, password, timeout, optional_args)
|
||||||
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")
|
|
||||||
self._node: str | None = self.optional_args.get("node")
|
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)
|
# Candidate config (merge/replace)
|
||||||
self._candidate_config: str = ""
|
self._candidate_config: str = ""
|
||||||
self._running_config: str = ""
|
self._running_config: str = ""
|
||||||
@@ -138,232 +177,46 @@ class ProxmoxDriver(
|
|||||||
# Connection management
|
# Connection management
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def open(self) -> None:
|
def _proxmox_api(self, **kwargs: Any) -> Any:
|
||||||
"""Open the connection to the Proxmox API."""
|
return ProxmoxAPI(**kwargs)
|
||||||
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 _resolve_node(self) -> str:
|
def _resolve_node(self) -> str:
|
||||||
"""Resolve the node name from the hostname or optional_args."""
|
"""Resolve the PVE node this connection talks to.
|
||||||
|
|
||||||
|
In a cluster, ``GET /nodes`` lists every member, so its first entry is
|
||||||
|
just some node, not necessarily the one at ``self.hostname``. That used
|
||||||
|
to be taken blindly, and a device then reported another node's name and
|
||||||
|
VMs. ``GET /cluster/status`` marks the node the session landed on with
|
||||||
|
``local: 1``; failing that, the node is matched by IP or name.
|
||||||
|
|
||||||
|
API errors propagate so that ``open()`` fails with the real cause (e.g.
|
||||||
|
a TLS verification error) rather than succeeding on a guessed name.
|
||||||
|
"""
|
||||||
if self._node:
|
if self._node:
|
||||||
self._node_name = self._node
|
self._node_name = self._node
|
||||||
return self._node_name
|
return self._node_name
|
||||||
|
|
||||||
# Try the node's hostname via API cluster/resources
|
members = [s for s in (self._api.cluster.status.get() or []) if s.get("type") == "node"]
|
||||||
try:
|
short_host = self.hostname.split(".")[0]
|
||||||
nodes = self._api.nodes.get()
|
for pick in (
|
||||||
# Match by hostname or IP
|
lambda s: s.get("local"),
|
||||||
for n in nodes:
|
lambda s: s.get("ip") == self.hostname,
|
||||||
n_node = n.get("node", "")
|
lambda s: s.get("name") in (self.hostname, short_host),
|
||||||
if n_node:
|
):
|
||||||
# First match: the node exists in the cluster
|
match = next((s for s in members if pick(s)), None)
|
||||||
self._node_name = n_node
|
if match:
|
||||||
return self._node_name
|
self._node_name = match["name"]
|
||||||
except Exception:
|
return self._node_name
|
||||||
pass
|
|
||||||
|
|
||||||
# Fallback: use the configured hostname as node name
|
names = [n.get("node") for n in (self._api.nodes.get() or []) if n.get("node")]
|
||||||
# (may not match the PVE node name — SSH-based methods will fail,
|
if len(names) == 1:
|
||||||
# but API methods that target a specific node name require correct
|
self._node_name = names[0]
|
||||||
# resolution)
|
return self._node_name
|
||||||
self._node_name = self.hostname
|
|
||||||
return self._node_name
|
|
||||||
|
|
||||||
def close(self) -> None:
|
raise ConnectionException(
|
||||||
"""Close the connection."""
|
f"Cannot tell which PVE node {self.hostname} is among {names}; "
|
||||||
self._api = None
|
f"set the 'node' driver argument"
|
||||||
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
|
# NAPALM getters kept in driver
|
||||||
@@ -383,57 +236,15 @@ class ProxmoxDriver(
|
|||||||
|
|
||||||
uptime = float(status.get("uptime", 0))
|
uptime = float(status.get("uptime", 0))
|
||||||
dns_search = dns.get("search", "")
|
dns_search = dns.get("search", "")
|
||||||
hostname = self._node_name
|
|
||||||
fqdn = f"{self._node_name}.{dns_search}" if dns_search else self.hostname
|
fqdn = f"{self._node_name}.{dns_search}" if dns_search else self.hostname
|
||||||
|
|
||||||
iface_list = sorted(
|
iface_list = sorted(iface["iface"] for iface in network if iface.get("iface"))
|
||||||
iface["iface"] for iface in network if iface.get("iface")
|
|
||||||
)
|
|
||||||
|
|
||||||
pve_version = version.get("version", "")
|
pve_version = version.get("version", "")
|
||||||
release = version.get("release", "")
|
release = version.get("release", "")
|
||||||
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
|
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
|
||||||
|
|
||||||
# Physical hardware info from Linux DMI sysfs.
|
vendor, model, serial = self._hardware()
|
||||||
# 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)
|
|
||||||
|
|
||||||
# Currently-booted kernel release (uname -r) — distinct from any newer
|
# Currently-booted kernel release (uname -r) — distinct from any newer
|
||||||
# kernel that is merely installed and pending a reboot.
|
# kernel that is merely installed and pending a reboot.
|
||||||
@@ -454,13 +265,3 @@ class ProxmoxDriver(
|
|||||||
"interface_list": iface_list,
|
"interface_list": iface_list,
|
||||||
"running_kernel": running_kernel,
|
"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,190 @@
|
|||||||
|
"""The PVE firewall of the cluster, read-only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall()`` reads what the operator wrote, at every level PVE has one:
|
||||||
|
the datacenter's options, rules, security groups, IP sets and aliases, the node's
|
||||||
|
options and rules, and each guest's on this node -- options, rules, and which NICs
|
||||||
|
carry ``firewall=1``. The datacenter level is the cluster's (pmxcfs keeps it once
|
||||||
|
for every node), so every node reads the same; a node reads its own guests, the
|
||||||
|
ones it runs. Nothing is written: pve-firewall rules are the operator's (see
|
||||||
|
``host_mixin``), and netOrk only reads them.
|
||||||
|
|
||||||
|
Each rule keeps PVE's own fields -- ``pos``, ``type`` (``in``, ``out``, ``group``,
|
||||||
|
``forward``), ``action`` (``ACCEPT``, ``DROP``, ``REJECT``, or a group's name),
|
||||||
|
``macro``, ``source``, ``dest``, ``proto``, ``dport``, ``sport``, ``iface``,
|
||||||
|
``enable``, ``comment`` -- and says where it came from (``origin``: ``cluster``,
|
||||||
|
``node``, ``guest`` or ``group``). A level whose call is refused (no
|
||||||
|
``Sys.Audit``/``VM.Audit``) is None, not empty: an unread level is no claim.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The rule fields kept as PVE returns them.
|
||||||
|
_RULE_FIELDS = (
|
||||||
|
"pos",
|
||||||
|
"type",
|
||||||
|
"action",
|
||||||
|
"macro",
|
||||||
|
"source",
|
||||||
|
"dest",
|
||||||
|
"proto",
|
||||||
|
"dport",
|
||||||
|
"sport",
|
||||||
|
"iface",
|
||||||
|
"comment",
|
||||||
|
"log",
|
||||||
|
"icmp-type",
|
||||||
|
)
|
||||||
|
#: A guest's NIC keys: ``net0`` … for both QEMU and LXC.
|
||||||
|
_NIC = re.compile(r"^net\d+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _rule(raw: _JsonDict, origin: str) -> _JsonDict:
|
||||||
|
found = {k.replace("-", "_"): raw[k] for k in _RULE_FIELDS if raw.get(k) not in (None, "")}
|
||||||
|
found["enable"] = str(raw.get("enable", 1)) not in ("0", "")
|
||||||
|
found["origin"] = origin
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _rules(rows: Any, origin: str) -> list[_JsonDict]:
|
||||||
|
return [_rule(r, origin) for r in rows or [] if isinstance(r, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def nic_firewalls(config: _JsonDict) -> list[_JsonDict]:
|
||||||
|
"""Each NIC of a guest config with whether ``firewall=1`` is set on it."""
|
||||||
|
found = []
|
||||||
|
for key in sorted(k for k in config if _NIC.match(k)):
|
||||||
|
options = dict(part.split("=", 1) for part in str(config[key]).split(",") if "=" in part)
|
||||||
|
found.append({"name": key, "firewall": options.get("firewall") == "1"})
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _read(call: Any, what: str) -> Any:
|
||||||
|
"""One GET; None when PVE refuses or fails it -- an unread level, not an empty one."""
|
||||||
|
try:
|
||||||
|
return call.get()
|
||||||
|
except Exception as exc: # noqa: BLE001 - proxmoxer raises its own and requests' errors
|
||||||
|
logger.warning("get_pve_firewall: %s not read: %s", what, exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _rules_or_none(rows: Any, origin: str) -> list[_JsonDict] | None:
|
||||||
|
return None if rows is None else _rules(rows, origin)
|
||||||
|
|
||||||
|
|
||||||
|
def _named(rows: Any, key: str) -> list[str]:
|
||||||
|
return [str(r[key]) for r in rows or [] if isinstance(r, dict) and r.get(key)]
|
||||||
|
|
||||||
|
|
||||||
|
def _groups(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
"""Each security group's rules; a group whose rules are refused has none listed."""
|
||||||
|
listed = _read(fw.groups, "security groups")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: _rules(_read(fw.groups(name), f"group {name}"), "group")
|
||||||
|
for name in _named(listed, "group")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _entry(raw: _JsonDict) -> _JsonDict:
|
||||||
|
return {
|
||||||
|
"cidr": raw.get("cidr"),
|
||||||
|
"nomatch": bool(raw.get("nomatch")),
|
||||||
|
"comment": raw.get("comment"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ipsets(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
listed = _read(fw.ipset, "IP sets")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: [
|
||||||
|
_entry(e) for e in _read(fw.ipset(name), f"IP set {name}") or [] if isinstance(e, dict)
|
||||||
|
]
|
||||||
|
for name in _named(listed, "name")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _aliases(rows: Any) -> dict[str, Any] | None:
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(a["name"]): a.get("cidr") for a in rows if isinstance(a, dict) and a.get("name")}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxFirewallMixin:
|
||||||
|
"""``get_pve_firewall`` for the PVE driver: the cluster's firewall as written, read only."""
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
_api: Any
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
|
||||||
|
def _cluster_firewall(self) -> _JsonDict:
|
||||||
|
fw = self._api.cluster.firewall
|
||||||
|
return {
|
||||||
|
"options": _read(fw.options, "datacenter options"),
|
||||||
|
"rules": _rules_or_none(_read(fw.rules, "datacenter rules"), "cluster"),
|
||||||
|
"groups": _groups(fw),
|
||||||
|
"ipsets": _ipsets(fw),
|
||||||
|
"aliases": _aliases(_read(fw.aliases, "aliases")),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guest_firewall(self, kind: str, guest: _JsonDict) -> _JsonDict:
|
||||||
|
vmid = int(guest.get("vmid", 0))
|
||||||
|
api = getattr(self._node_api(), kind)(vmid)
|
||||||
|
rules = _read(api.firewall.rules, f"{kind} {vmid} rules")
|
||||||
|
config = _read(api.config, f"{kind} {vmid} config")
|
||||||
|
return {
|
||||||
|
"vmid": str(vmid),
|
||||||
|
"type": "vm" if kind == "qemu" else "container",
|
||||||
|
"name": guest.get("name") or "",
|
||||||
|
"node": self._node_name,
|
||||||
|
"options": _read(api.firewall.options, f"{kind} {vmid} options"),
|
||||||
|
"rules": _rules_or_none(rules, "guest"),
|
||||||
|
"nics": None if config is None else nic_firewalls(config),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guests(self) -> list[_JsonDict]:
|
||||||
|
found: list[_JsonDict] = []
|
||||||
|
for kind in ("qemu", "lxc"):
|
||||||
|
for guest in _read(getattr(self._node_api(), kind), f"{kind} guests") or []:
|
||||||
|
if isinstance(guest, dict) and guest.get("vmid") is not None:
|
||||||
|
found.append(self._guest_firewall(kind, guest))
|
||||||
|
return found
|
||||||
|
|
||||||
|
def get_pve_firewall(self) -> _JsonDict:
|
||||||
|
"""
|
||||||
|
Return the PVE firewall as the operator wrote it: the datacenter level, this
|
||||||
|
node's, and every guest's on this node. Read only.
|
||||||
|
|
||||||
|
* cluster (dict) - ``options``, ``rules``, ``groups`` (name -> rules),
|
||||||
|
``ipsets`` (name -> ``[{cidr, nomatch, comment}]``), ``aliases`` (name -> cidr)
|
||||||
|
* node (dict) - ``name``, ``options``, ``rules``
|
||||||
|
* guests (list) - ``vmid``, ``type`` (``vm``/``container``), ``name``, ``node``,
|
||||||
|
``options``, ``rules``, ``nics`` (``[{name, firewall}]``)
|
||||||
|
|
||||||
|
Any part PVE refuses is None, never empty. Each rule carries PVE's fields and
|
||||||
|
its ``origin`` (``cluster``, ``group``, ``node``, ``guest``).
|
||||||
|
"""
|
||||||
|
node = self._node_api().firewall
|
||||||
|
rules = _read(node.rules, "node rules")
|
||||||
|
return {
|
||||||
|
"cluster": self._cluster_firewall(),
|
||||||
|
"node": {
|
||||||
|
"name": self._node_name,
|
||||||
|
"options": _read(node.options, "node options"),
|
||||||
|
"rules": _rules_or_none(rules, "node"),
|
||||||
|
},
|
||||||
|
"guests": self._guests(),
|
||||||
|
}
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
"""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, the services that still run replaced
|
||||||
|
code, 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_hardening_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HardeningMixin.get_hardening`` (NetOrk/netork#2776): the exec
|
||||||
|
path, which is root's login, so AppArmor's profiles per mode are read too. Another
|
||||||
|
login reads the rest without them, as napalm-device-types' fallback does. No stdin."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_host_firewall_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HostFirewallMixin.get_host_firewall``: the exec path, which
|
||||||
|
runs as root either way. What the node has loaded -- proxmox-firewall's nftables
|
||||||
|
tables on PVE 9, pve-firewall's iptables chains before (NetOrk/netork#2654)."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_service_packages_command(self, command: str) -> str:
|
||||||
|
"""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 _run_services_restart_command(self, command: str) -> str:
|
||||||
|
"""The transport for ``ServicesRestartMixin.get_services_need_restart``: the exec
|
||||||
|
path, which is root's login as a rule. Run only as root: a reading of the login's
|
||||||
|
own processes would read as clean, so another login prints nothing and the parse
|
||||||
|
raises (NetOrk/netork#2750). No stdin."""
|
||||||
|
return str(self._exec_ssh_command(f'[ "$(id -u)" = 0 ] && {command}'))
|
||||||
|
|
||||||
|
def get_packages(self) -> list[PackageDict]:
|
||||||
|
"""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 _reload_package_index(self) -> FixStepOutcomeDict:
|
||||||
|
"""``CpuMicrocodeMixin``'s index load (NetOrk/netork#2838): ``apt-get update`` on the
|
||||||
|
exec path, done when it returns. ``refresh_available_updates`` only starts the API's
|
||||||
|
task, and the install that follows would race it."""
|
||||||
|
return self._step(
|
||||||
|
"DEBIAN_FRONTEND=noninteractive apt-get update", "package index loaded again"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _allow_sources(
|
||||||
|
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||||
|
) -> FixStepOutcomeDict:
|
||||||
|
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
|
||||||
|
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,
|
"interface": iface,
|
||||||
"mac": utils.normalize_mac(mac),
|
"mac": utils.normalize_mac(mac),
|
||||||
"ip": parts[0],
|
"ip": parts[0],
|
||||||
# `ip neigh` reports no age; NAPALM's shape requires the key.
|
# `ip neigh` reports no age; NAPALM's shape requires the key,
|
||||||
"age": 0.0,
|
# and -1.0 is napalm-device-types' ARP_AGE_UNKNOWN -- 0.0
|
||||||
|
# would mean "confirmed just now".
|
||||||
|
"age": -1.0,
|
||||||
"state": state,
|
"state": state,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -158,9 +160,9 @@ class ProxmoxInterfaceMixin:
|
|||||||
def get_arp_table(self, vrf: str = "") -> list[_JsonDict]:
|
def get_arp_table(self, vrf: str = "") -> list[_JsonDict]:
|
||||||
"""Return ARP table.
|
"""Return ARP table.
|
||||||
|
|
||||||
Proxmox does not expose ARP via the REST API directly. We attempt
|
Proxmox does not expose ARP via the REST API, so the node's
|
||||||
to read it via the node's ``/proc/net/arp`` through the Proxmox
|
``/proc/net/arp`` is read over SSH; a node that cannot be reached
|
||||||
exec endpoint. If that is unavailable, an empty list is returned.
|
there raises.
|
||||||
"""
|
"""
|
||||||
raw = self._exec_ssh_command("cat /proc/net/arp")
|
raw = self._exec_ssh_command("cat /proc/net/arp")
|
||||||
if not raw:
|
if not raw:
|
||||||
@@ -174,8 +176,13 @@ class ProxmoxInterfaceMixin:
|
|||||||
parts = line.split()
|
parts = line.split()
|
||||||
if len(parts) < 6:
|
if len(parts) < 6:
|
||||||
continue
|
continue
|
||||||
ip_addr, _, flags, mac, _, iface = (
|
ip_addr, _, _flags, mac, _, iface = (
|
||||||
parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]
|
parts[0],
|
||||||
|
parts[1],
|
||||||
|
parts[2],
|
||||||
|
parts[3],
|
||||||
|
parts[4],
|
||||||
|
parts[5],
|
||||||
)
|
)
|
||||||
if mac in ("00:00:00:00:00:00", ""):
|
if mac in ("00:00:00:00:00:00", ""):
|
||||||
continue
|
continue
|
||||||
@@ -202,9 +209,7 @@ class ProxmoxInterfaceMixin:
|
|||||||
if iface.get("type") in ("bridge",) and iface.get("iface")
|
if iface.get("type") in ("bridge",) and iface.get("iface")
|
||||||
]
|
]
|
||||||
for bridge in linux_bridges:
|
for bridge in linux_bridges:
|
||||||
raw = self._exec_ssh_command(
|
raw = self._exec_ssh_command(f"bridge fdb show br {bridge} 2>/dev/null || true")
|
||||||
f"bridge fdb show br {bridge} 2>/dev/null || true"
|
|
||||||
)
|
|
||||||
for line in raw.splitlines():
|
for line in raw.splitlines():
|
||||||
parts = line.split()
|
parts = line.split()
|
||||||
if len(parts) < 3:
|
if len(parts) < 3:
|
||||||
@@ -240,9 +245,7 @@ class ProxmoxInterfaceMixin:
|
|||||||
if iface.get("type") in ("OVSBridge",) and iface.get("iface")
|
if iface.get("type") in ("OVSBridge",) and iface.get("iface")
|
||||||
]
|
]
|
||||||
for bridge in ovs_bridges:
|
for bridge in ovs_bridges:
|
||||||
raw = self._exec_ssh_command(
|
raw = self._exec_ssh_command(f"ovs-appctl fdb/show {bridge} 2>/dev/null || true")
|
||||||
f"ovs-appctl fdb/show {bridge} 2>/dev/null || true"
|
|
||||||
)
|
|
||||||
for line in raw.splitlines():
|
for line in raw.splitlines():
|
||||||
parts = line.split()
|
parts = line.split()
|
||||||
if len(parts) < 4:
|
if len(parts) < 4:
|
||||||
|
|||||||
@@ -12,96 +12,61 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# 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
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
from typing import TYPE_CHECKING
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
|
from napalm.base.models import LLDPNeighborDetailDict
|
||||||
_JsonDict = dict[str, Any]
|
from napalm_device_types import (
|
||||||
|
LLDPCTL_KEYVALUE_COMMAND,
|
||||||
|
LldpNeighborDict,
|
||||||
|
LldpNeighborRow,
|
||||||
|
lldp_neighbors,
|
||||||
|
lldp_neighbors_detail,
|
||||||
|
parse_lldpctl_keyvalue,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxLLDPMixin:
|
class ProxmoxLLDPMixin:
|
||||||
"""Mixin providing LLDP NAPALM methods."""
|
"""Mixin providing LLDP NAPALM methods."""
|
||||||
|
|
||||||
def get_lldp_neighbors(self) -> dict[str, list[_JsonDict]]:
|
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
|
||||||
"""Return LLDP neighbours (requires lldpd on the Proxmox node)."""
|
"""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_detail(self, interface: str = "") -> dict[str, list[_JsonDict]]:
|
Every neighbour of a port is its own entry; one that names its chassis
|
||||||
"""Return detailed LLDP neighbour information."""
|
by a MAC address carries it as ``mac``.
|
||||||
result: dict[str, list[_JsonDict]] = {}
|
|
||||||
raw = self._exec_ssh_command(
|
|
||||||
"lldpcli show neighbors details 2>/dev/null || true"
|
|
||||||
)
|
|
||||||
current_iface = ""
|
|
||||||
current_entry: _JsonDict = {}
|
|
||||||
|
|
||||||
def _flush():
|
:raises ValueError: when lldpctl failed or gave no answer.
|
||||||
if current_iface and current_entry:
|
"""
|
||||||
result.setdefault(current_iface, []).append(current_entry.copy())
|
return lldp_neighbors(self._get_lldp_table())
|
||||||
|
|
||||||
for line in raw.splitlines():
|
def get_lldp_neighbors_detail(
|
||||||
m_iface = re.match(r"^\s*Interface:\s+(\S+?),?\s", line)
|
self, interface: str = ""
|
||||||
if m_iface:
|
) -> dict[str, list[LLDPNeighborDetailDict]]:
|
||||||
_flush()
|
"""Return detailed LLDP neighbour information, of *interface* only when given.
|
||||||
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()
|
|
||||||
|
|
||||||
m_cap = re.match(r"^\s*Capability:\s+(\S+),\s+(\w+)", line)
|
:raises ValueError: when lldpctl failed or gave no answer.
|
||||||
if m_cap:
|
"""
|
||||||
cap = m_cap.group(1).lower()
|
return lldp_neighbors_detail(self._get_lldp_table(), interface)
|
||||||
enabled = m_cap.group(2).lower() == "on"
|
|
||||||
current_entry["remote_system_capab"].append(cap)
|
|
||||||
if enabled:
|
|
||||||
current_entry["remote_system_enable_capab"].append(cap)
|
|
||||||
|
|
||||||
_flush()
|
def _get_lldp_table(self) -> list[LldpNeighborRow]:
|
||||||
return result
|
"""``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,31 @@
|
|||||||
|
"""How the Proxmox VE API writes plain values: numbers as strings, flags as 0/1, lists
|
||||||
|
as comma-separated strings."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
_LIST_SEPARATORS = re.compile(r"[\s,;\0]+")
|
||||||
|
|
||||||
|
#: The first release with node maintenance over REST, guest uids, the cluster id,
|
||||||
|
#: clock sync on resume and the APT history (NetOrk/netork#2728).
|
||||||
|
PVE_9_3 = (9, 3)
|
||||||
|
|
||||||
|
|
||||||
|
def to_int(value: Any) -> int | None:
|
||||||
|
return None if value is None else int(value)
|
||||||
|
|
||||||
|
|
||||||
|
def to_flag(value: Any) -> bool:
|
||||||
|
return bool(int(value or 0))
|
||||||
|
|
||||||
|
|
||||||
|
def split_list(value: Any) -> list[str]:
|
||||||
|
"""``"a,b"`` -> ``["a", "b"]``; PVE also separates with ``;``, blanks or NUL."""
|
||||||
|
return [part for part in _LIST_SEPARATORS.split(str(value or "")) if part]
|
||||||
|
|
||||||
|
|
||||||
|
def vmid_list(value: Any) -> list[int]:
|
||||||
|
"""``"100,101"`` -> ``[100, 101]``; what is not a number is left out."""
|
||||||
|
return [int(part) for part in split_list(value) if part.isdigit()]
|
||||||
Whitespace-only changes.
@@ -21,9 +21,12 @@ from typing import Any
|
|||||||
|
|
||||||
import napalm.base.constants as C
|
import napalm.base.constants as C
|
||||||
|
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_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:
|
class ProxmoxRoutingMixin:
|
||||||
"""Mixin providing routing NAPALM methods (get_route_to, ping, traceroute)."""
|
"""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")
|
raw = self._exec_ssh_command(f"{cmd} 2>&1 || true")
|
||||||
if not raw:
|
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
|
# Detect common failure strings before parsing statistics
|
||||||
_error_patterns = (
|
_error_patterns = (
|
||||||
@@ -91,13 +94,9 @@ class ProxmoxRoutingMixin:
|
|||||||
rtt_std = float(m_rtt.group(4)) if m_rtt else 0.0
|
rtt_std = float(m_rtt.group(4)) if m_rtt else 0.0
|
||||||
|
|
||||||
# Individual probe lines
|
# Individual probe lines
|
||||||
probes = []
|
probes = [
|
||||||
for m_probe in re.finditer(
|
{"ip_address": m.group(1), "rtt": float(m.group(2))} for m in _PING_REPLY.finditer(raw)
|
||||||
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))}
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"success": {
|
"success": {
|
||||||
@@ -127,7 +126,7 @@ class ProxmoxRoutingMixin:
|
|||||||
raw = self._exec_ssh_command(" ".join(cmd_parts) + " 2>&1 || true")
|
raw = self._exec_ssh_command(" ".join(cmd_parts) + " 2>&1 || true")
|
||||||
|
|
||||||
if not raw:
|
if not raw:
|
||||||
return {"error": "traceroute not available via exec endpoint"}
|
return {"error": "traceroute printed nothing on the node"}
|
||||||
|
|
||||||
hops: _JsonDict = {}
|
hops: _JsonDict = {}
|
||||||
for line in raw.splitlines():
|
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:
|
class ProxmoxSDNMixin:
|
||||||
"""Mixin providing SDN, VLAN and network-instance NAPALM methods."""
|
"""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]:
|
def _get_sdn_zones(self) -> list[_JsonDict]:
|
||||||
try:
|
try:
|
||||||
return self._api.cluster.sdn.zones.get() or [] # type: ignore[union-attr]
|
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)
|
tags.setdefault(str(tag), set()).add(bridge)
|
||||||
|
|
||||||
try:
|
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))
|
vmid = int(vm.get("vmid", 0))
|
||||||
try:
|
try:
|
||||||
config = self._node_api().qemu(vmid).config.get() or {}
|
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)
|
logger.warning("_get_vm_vlan_tags: failed to list QEMU VMs: %s", exc)
|
||||||
|
|
||||||
try:
|
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))
|
vmid = int(ct.get("vmid", 0))
|
||||||
try:
|
try:
|
||||||
config = self._node_api().lxc(vmid).config.get() or {}
|
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.
|
2. LLDP basic fallback: first physical port with any LLDP neighbour.
|
||||||
"""
|
"""
|
||||||
network = {
|
network = {
|
||||||
iface["iface"]: iface
|
iface["iface"]: iface for iface in self._get_node_network() if iface.get("iface")
|
||||||
for iface in self._get_node_network()
|
|
||||||
if iface.get("iface")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -309,10 +318,7 @@ class ProxmoxSDNMixin:
|
|||||||
return True
|
return True
|
||||||
min_id = min(int(n.get("nodeid", 9999)) for n in online_nodes)
|
min_id = min(int(n.get("nodeid", 9999)) for n in online_nodes)
|
||||||
for n in online_nodes:
|
for n in online_nodes:
|
||||||
if (
|
if n.get("name") == self._node_name and int(n.get("nodeid", 9999)) == min_id:
|
||||||
n.get("name") == self._node_name
|
|
||||||
and int(n.get("nodeid", 9999)) == min_id
|
|
||||||
):
|
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -361,9 +367,7 @@ class ProxmoxSDNMixin:
|
|||||||
vlan_id: VLAN identifier (1-4094).
|
vlan_id: VLAN identifier (1-4094).
|
||||||
config: Dict that may contain ``"name"`` for the VLAN alias.
|
config: Dict that may contain ``"name"`` for the VLAN alias.
|
||||||
"""
|
"""
|
||||||
name: str = (
|
name: str = (config.get("name") or f"VLAN{vlan_id}") if config else f"VLAN{vlan_id}"
|
||||||
(config.get("name") or f"VLAN{vlan_id}") if config else f"VLAN{vlan_id}"
|
|
||||||
)
|
|
||||||
vnet_id = f"vlan{vlan_id:04d}"
|
vnet_id = f"vlan{vlan_id:04d}"
|
||||||
|
|
||||||
uplink = self._find_switch_uplink()
|
uplink = self._find_switch_uplink()
|
||||||
|
|||||||
+222
-460
@@ -12,20 +12,119 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# 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
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
import shlex
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm_proxmox import utils
|
from napalm.base.exceptions import CommandErrorException
|
||||||
|
from napalm_device_types import SNMP_PURPOSE
|
||||||
|
|
||||||
|
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_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:
|
class ProxmoxSystemMixin:
|
||||||
"""Mixin providing system-level NAPALM methods."""
|
"""Mixin providing system-level NAPALM methods."""
|
||||||
@@ -79,52 +178,12 @@ class ProxmoxSystemMixin:
|
|||||||
return env
|
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]:
|
def get_ntp_stats(self) -> list[_JsonDict]:
|
||||||
"""Return NTP synchronisation statistics from chronyc/ntpq output."""
|
"""Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing."""
|
||||||
raw = self._exec_ssh_command(
|
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_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
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# get_snmp_information
|
# get_snmp_information
|
||||||
@@ -136,9 +195,7 @@ class ProxmoxSystemMixin:
|
|||||||
Proxmox does not expose SNMP configuration via the REST API.
|
Proxmox does not expose SNMP configuration via the REST API.
|
||||||
We read /etc/snmp/snmpd.conf via exec if available.
|
We read /etc/snmp/snmpd.conf via exec if available.
|
||||||
"""
|
"""
|
||||||
raw = self._exec_ssh_command(
|
raw = self._exec_ssh_command("cat /etc/snmp/snmpd.conf 2>/dev/null || true")
|
||||||
"cat /etc/snmp/snmpd.conf 2>/dev/null || true"
|
|
||||||
)
|
|
||||||
communities: dict[str, _JsonDict] = {}
|
communities: dict[str, _JsonDict] = {}
|
||||||
location = ""
|
location = ""
|
||||||
contact = ""
|
contact = ""
|
||||||
@@ -173,277 +230,76 @@ class ProxmoxSystemMixin:
|
|||||||
def get_users(self) -> dict[str, _JsonDict]:
|
def get_users(self) -> dict[str, _JsonDict]:
|
||||||
"""Return users configured on the Proxmox node.
|
"""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] = {}
|
result: dict[str, _JsonDict] = {}
|
||||||
try:
|
admins, admin_groups = self._pve_administrators()
|
||||||
pve_users = self._api.access.users.get() or [] # type: ignore[union-attr]
|
for user in self._pve_users():
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch Proxmox users: %s", exc)
|
|
||||||
pve_users = []
|
|
||||||
|
|
||||||
for user in pve_users:
|
|
||||||
uid = user.get("userid", "")
|
uid = user.get("userid", "")
|
||||||
if not uid:
|
if not uid:
|
||||||
continue
|
continue
|
||||||
# Proxmox roles: Administrator -> 15, otherwise 1
|
groups = set(_words(user.get("groups"), sep=","))
|
||||||
groups = user.get("groups", "") or ""
|
is_admin = uid == _PVE_SUPERUSER or uid in admins or bool(groups & admin_groups)
|
||||||
level = 1
|
result[uid] = _user_entry(15 if is_admin else 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": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
# Merge local OS users from /etc/passwd
|
|
||||||
raw = self._exec_ssh_command("getent passwd 2>/dev/null || cat /etc/passwd")
|
raw = self._exec_ssh_command("getent passwd 2>/dev/null || cat /etc/passwd")
|
||||||
for line in raw.splitlines():
|
for uname, uid_int in _login_accounts(raw):
|
||||||
parts = line.split(":")
|
result.setdefault(uname, _user_entry(15 if uid_int == 0 else 0))
|
||||||
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": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
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)
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Listening sockets (ListeningSocketsMixin supplies get_listening_sockets)
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Packages (Debian APT)
|
# 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)
|
# Services (systemd, through napalm-device-types' SystemdServicesMixin)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def get_services(self) -> list[_JsonDict]:
|
|
||||||
"""Return systemd services with running and enabled state.
|
|
||||||
|
|
||||||
Uses two ``systemctl`` invocations combined in a single SSH command:
|
|
||||||
- ``list-unit-files`` for the static enabled/disabled state
|
|
||||||
- ``list-units`` for the live running state
|
|
||||||
"""
|
|
||||||
raw = self._exec_ssh_command(
|
|
||||||
"{ systemctl list-unit-files --type=service --no-pager --no-legend --full 2>/dev/null;"
|
|
||||||
" echo '---UNITS---';"
|
|
||||||
" systemctl list-units --type=service --all --no-pager --no-legend --full 2>/dev/null;"
|
|
||||||
" } || true"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Parse enabled state from list-unit-files
|
|
||||||
enabled_map: dict[str, bool] = {}
|
|
||||||
section = "files"
|
|
||||||
for line in raw.splitlines():
|
|
||||||
if line.strip() == "---UNITS---":
|
|
||||||
section = "units"
|
|
||||||
continue
|
|
||||||
parts = line.strip().split(None, 1)
|
|
||||||
if len(parts) < 1:
|
|
||||||
continue
|
|
||||||
unit = parts[0].lstrip("\u25cf").strip()
|
|
||||||
if not unit.endswith(".service"):
|
|
||||||
continue
|
|
||||||
name = unit[: -len(".service")]
|
|
||||||
if section == "files":
|
|
||||||
state = parts[1].strip() if len(parts) > 1 else ""
|
|
||||||
enabled_map[name] = state in ("enabled", "enabled-runtime", "static")
|
|
||||||
|
|
||||||
# Parse running state from list-units
|
|
||||||
running_map: dict[str, bool] = {}
|
|
||||||
section = "files"
|
|
||||||
for line in raw.splitlines():
|
|
||||||
if line.strip() == "---UNITS---":
|
|
||||||
section = "units"
|
|
||||||
continue
|
|
||||||
if section != "units":
|
|
||||||
continue
|
|
||||||
parts = line.strip().lstrip("\u25cf").strip().split(None, 4)
|
|
||||||
if len(parts) < 4:
|
|
||||||
continue
|
|
||||||
unit = parts[0]
|
|
||||||
if not unit.endswith(".service"):
|
|
||||||
continue
|
|
||||||
name = unit[: -len(".service")]
|
|
||||||
sub_state = parts[3]
|
|
||||||
running_map[name] = sub_state == "running"
|
|
||||||
|
|
||||||
all_names = sorted(set(enabled_map) | set(running_map))
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
"name": name,
|
|
||||||
"running": running_map.get(name, False),
|
|
||||||
"enabled": enabled_map.get(name, False),
|
|
||||||
"pid": 0,
|
|
||||||
}
|
|
||||||
for name in all_names
|
|
||||||
]
|
|
||||||
|
|
||||||
def manage_service(self, name: str, action: str) -> _JsonDict:
|
|
||||||
"""Start / stop / restart / enable / disable a systemd service."""
|
|
||||||
if not re.match(r'^[a-zA-Z0-9_\-\.@]+$', name):
|
|
||||||
raise ValueError(f"Invalid service name: {name!r}")
|
|
||||||
if action not in ('start', 'stop', 'restart', 'enable', 'disable'):
|
|
||||||
raise ValueError(f"Invalid action: {action!r}")
|
|
||||||
output = self._exec_ssh_command(f"systemctl {action} {name}.service 2>&1 || true")
|
|
||||||
return {"success": True, "output": output}
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Available updates
|
# Available updates
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def get_available_updates(self) -> list[_JsonDict]:
|
|
||||||
"""Return list of upgradable packages from the Proxmox APT API."""
|
|
||||||
updates: list[_JsonDict] = []
|
|
||||||
try:
|
|
||||||
for upd in self._api.nodes(self._node_name).apt.update.get():
|
|
||||||
pkg = upd.get("Package", "")
|
|
||||||
if not pkg:
|
|
||||||
continue
|
|
||||||
updates.append({
|
|
||||||
"name": pkg,
|
|
||||||
"current_version": upd.get("OldVersion", ""),
|
|
||||||
"new_version": upd.get("Version", ""),
|
|
||||||
})
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch available updates: %s", exc)
|
|
||||||
return sorted(updates, key=lambda u: u["name"])
|
|
||||||
|
|
||||||
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
|
# SNMP / Health
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
@@ -451,7 +307,8 @@ class ProxmoxSystemMixin:
|
|||||||
def get_snmp_config(self):
|
def get_snmp_config(self):
|
||||||
"""Return SNMP agent config if snmpd is installed and running on the node.
|
"""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.
|
Returns a SNMPConfigDict or None.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
@@ -470,7 +327,8 @@ class ProxmoxSystemMixin:
|
|||||||
port = 161
|
port = 161
|
||||||
try:
|
try:
|
||||||
conf = self._exec_ssh_command(
|
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():
|
for line in conf.splitlines():
|
||||||
parts = line.split()
|
parts = line.split()
|
||||||
@@ -488,131 +346,44 @@ class ProxmoxSystemMixin:
|
|||||||
|
|
||||||
return SNMPConfigDict(running=True, community=community, port=port, version="2c")
|
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."""
|
# Fixes (napalm-device-types SnmpAgentMixin, EnsurePackageMixin): the
|
||||||
if action == "fix_snmp":
|
# caller's values. The node's shell runs as root.
|
||||||
return self._action_fix_snmp()
|
# ------------------------------------------------------------------
|
||||||
if action == "install_lldpd":
|
|
||||||
return self._action_install_lldpd()
|
|
||||||
raise NotImplementedError(f"Unknown action: {action!r}")
|
|
||||||
|
|
||||||
def _action_install_lldpd(self) -> dict:
|
# apt's proxy (napalm-device-types AptProxyMixin): the transports. The node
|
||||||
"""Install, enable and start lldpd on the Proxmox node.
|
# is logged in as root, so every command runs as root.
|
||||||
|
|
||||||
Proxmox runs Debian/Linux underneath, so this is a plain apt install
|
def _install_snmp_agent(self) -> dict:
|
||||||
followed by enabling the systemd service. lldpd's defaults (listen on
|
return self._step(
|
||||||
all interfaces) are sufficient to discover the directly-connected
|
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp", "net-snmp installed"
|
||||||
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"
|
|
||||||
)
|
)
|
||||||
lines.append(f"[install] {install_out.strip()[-200:]}")
|
|
||||||
|
|
||||||
enable_out = self._exec_ssh_command(
|
def _write_snmp_agent_config(self, settings: dict) -> dict:
|
||||||
"systemctl enable --now lldpd 2>&1 || service lldpd start 2>&1 || true"
|
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()
|
def _start_snmp_agent(self) -> dict:
|
||||||
success = bool(verify)
|
return self._step(
|
||||||
if success:
|
"systemctl enable snmpd && systemctl restart snmpd && systemctl is-active snmpd",
|
||||||
lines.append("[ok] lldpd installed. Neighbors will appear after a short warm-up period.")
|
"snmpd enabled and running",
|
||||||
else:
|
|
||||||
lines.append("[warn] lldpd does not appear to be installed after the attempt.")
|
|
||||||
|
|
||||||
return {"success": success, "output": "\n".join(lines)}
|
|
||||||
|
|
||||||
def _action_fix_snmp(self) -> dict:
|
|
||||||
"""Install, configure and start snmpd on the Proxmox node.
|
|
||||||
|
|
||||||
Proxmox runs Debian/Linux underneath. _exec_ssh_command runs as root
|
|
||||||
(either via Proxmox API execute endpoint or SSH with root credentials),
|
|
||||||
so no sudo is needed.
|
|
||||||
"""
|
|
||||||
import base64 as _b64
|
|
||||||
lines: list[str] = []
|
|
||||||
|
|
||||||
# 1. Install snmpd and snmp client tools
|
|
||||||
install_out = self._exec_ssh_command(
|
|
||||||
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1 | tail -5"
|
|
||||||
)
|
)
|
||||||
lines.append(f"[install] {install_out.strip()[-200:]}")
|
|
||||||
|
|
||||||
# 2. Detect the IP this connection comes from (for firewall rule)
|
def _refuse_clustered_node(self) -> None:
|
||||||
netork_ip = ""
|
_, status = self._rc(_CLUSTER_MEMBER_CHECK)
|
||||||
try:
|
if status == 0:
|
||||||
raw = self._exec_ssh_command(
|
raise CommandErrorException(
|
||||||
"ss -tnp 2>/dev/null | awk '/sshd/{print $5}' | head -1 | cut -d: -f1"
|
"set_hostname refused: the node is part of a cluster; rename a cluster"
|
||||||
).strip()
|
" member by Proxmox's own procedure, not in place"
|
||||||
if raw and raw not in ("", "0.0.0.0", "::", "127.0.0.1"):
|
)
|
||||||
netork_ip = raw
|
if status != 1:
|
||||||
except Exception as exc:
|
raise CommandErrorException(
|
||||||
logger.debug("Failed to detect network origin IP: %s", exc)
|
"set_hostname refused: could not tell whether the node is part of a cluster"
|
||||||
|
)
|
||||||
# 3. Write snmpd.conf via /tmp (no permission issues)
|
|
||||||
conf_str = (
|
|
||||||
"agentAddress udp:161\n"
|
|
||||||
"rocommunity public\n"
|
|
||||||
"sysLocation Managed by netOrk\n"
|
|
||||||
"sysContact netork@localhost\n"
|
|
||||||
)
|
|
||||||
conf_b64 = _b64.b64encode(conf_str.encode()).decode()
|
|
||||||
self._exec_ssh_command(f"echo {conf_b64} | base64 -d > /tmp/netork_snmpd.conf")
|
|
||||||
self._exec_ssh_command(
|
|
||||||
"mv /tmp/netork_snmpd.conf /etc/snmp/snmpd.conf && "
|
|
||||||
"chown root:root /etc/snmp/snmpd.conf && chmod 644 /etc/snmp/snmpd.conf"
|
|
||||||
)
|
|
||||||
verify = self._exec_ssh_command("cat /etc/snmp/snmpd.conf 2>/dev/null").strip()
|
|
||||||
if "agentAddress" in verify and "rocommunity" in verify:
|
|
||||||
lines.append("[config] Wrote /etc/snmp/snmpd.conf - agentAddress udp:161, rocommunity public.")
|
|
||||||
else:
|
|
||||||
lines.append(f"[warn] snmpd.conf write may have failed: {verify[:100]}")
|
|
||||||
|
|
||||||
# 4. Open firewall if ufw is present
|
|
||||||
if netork_ip:
|
|
||||||
try:
|
|
||||||
ufw = self._exec_ssh_command("command -v ufw 2>/dev/null").strip()
|
|
||||||
if ufw:
|
|
||||||
parts = netork_ip.rsplit(".", 1)
|
|
||||||
subnet = f"{parts[0]}.0/24" if len(parts) == 2 else netork_ip
|
|
||||||
fw_out = self._exec_ssh_command(
|
|
||||||
f"ufw allow from {subnet} to any port 161 proto udp 2>&1"
|
|
||||||
)
|
|
||||||
lines.append(f"[firewall/ufw] {fw_out.strip()[:200]}")
|
|
||||||
except Exception as exc:
|
|
||||||
lines.append(f"[firewall] skipped - {exc}")
|
|
||||||
|
|
||||||
# 5. Stop and restart snmpd cleanly (no DBus needed for stop+start)
|
|
||||||
self._exec_ssh_command(
|
|
||||||
"service snmpd stop 2>/dev/null; pkill -9 snmpd 2>/dev/null; true"
|
|
||||||
)
|
|
||||||
import time as _time
|
|
||||||
_time.sleep(1)
|
|
||||||
start_out = self._exec_ssh_command(
|
|
||||||
"service snmpd start 2>&1 || systemctl start snmpd 2>&1 || true"
|
|
||||||
)
|
|
||||||
lines.append(f"[service] {start_out.strip()[-200:]}")
|
|
||||||
|
|
||||||
# 6. Verify via local probe
|
|
||||||
_time.sleep(2)
|
|
||||||
probe_out = self._exec_ssh_command(
|
|
||||||
"snmpget -v2c -cpublic -t2 -r0 -Ov 127.0.0.1 1.3.6.1.2.1.1.1.0 2>&1 || true"
|
|
||||||
).strip()
|
|
||||||
_snmp_types = ("STRING:", "INTEGER:", "OID:", "Timeticks:", "Hex-STRING:", "IpAddress:")
|
|
||||||
success = any(t in probe_out for t in _snmp_types)
|
|
||||||
if success:
|
|
||||||
lines.append("[ok] SNMP probe successful - community 'public' is working.")
|
|
||||||
else:
|
|
||||||
lines.append(f"[warn] SNMP probe failed - output: {probe_out[:200]}")
|
|
||||||
|
|
||||||
return {"success": success, "output": "\n".join(lines)}
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
# set_hostname
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
|
|
||||||
def set_hostname(self, new_hostname: str) -> None:
|
def set_hostname(self, new_hostname: str) -> None:
|
||||||
"""Set the system hostname on the Proxmox node.
|
"""Set the system hostname on the Proxmox node.
|
||||||
@@ -631,16 +402,16 @@ class ProxmoxSystemMixin:
|
|||||||
7. Proxmox node TLS certificate — regenerated via
|
7. Proxmox node TLS certificate — regenerated via
|
||||||
``pvenode cert create --overwrite``.
|
``pvenode cert create --overwrite``.
|
||||||
|
|
||||||
**Important**: the Proxmox *node name* (shown in the web UI and stored
|
The Proxmox *node name* (web UI, ``/etc/pve/nodes/<name>/``) only
|
||||||
in ``/etc/pve/nodes/<name>/``) only changes after a full reboot.
|
changes after a reboot. Accepts a bare hostname or an FQDN.
|
||||||
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.
|
|
||||||
|
|
||||||
Accepts a bare hostname (``pve-see``) or an FQDN
|
Raises CommandErrorException, before changing anything, on a cluster
|
||||||
(``pve-see.see.local``).
|
member (a corosync.conf exists): its rename is the cluster's procedure.
|
||||||
"""
|
"""
|
||||||
import base64 as _b64
|
import base64 as _b64
|
||||||
|
|
||||||
|
self._refuse_clustered_node()
|
||||||
|
|
||||||
if "." in new_hostname:
|
if "." in new_hostname:
|
||||||
short_hostname, domain = new_hostname.split(".", 1)
|
short_hostname, domain = new_hostname.split(".", 1)
|
||||||
fqdn = new_hostname
|
fqdn = new_hostname
|
||||||
@@ -650,9 +421,11 @@ class ProxmoxSystemMixin:
|
|||||||
fqdn = new_hostname
|
fqdn = new_hostname
|
||||||
|
|
||||||
# Derive old short hostname for substitution in /etc/hosts
|
# Derive old short hostname for substitution in /etc/hosts
|
||||||
old_short = self._exec_ssh_command(
|
old_short = (
|
||||||
"cat /etc/hostname 2>/dev/null || hostname -s 2>/dev/null"
|
self._exec_ssh_command("cat /etc/hostname 2>/dev/null || hostname -s 2>/dev/null")
|
||||||
).strip().split(".")[0]
|
.strip()
|
||||||
|
.split(".")[0]
|
||||||
|
)
|
||||||
|
|
||||||
# ── 1. /etc/hostname ─────────────────────────────────────────────
|
# ── 1. /etc/hostname ─────────────────────────────────────────────
|
||||||
hostname_b64 = _b64.b64encode(f"{short_hostname}\n".encode()).decode()
|
hostname_b64 = _b64.b64encode(f"{short_hostname}\n".encode()).decode()
|
||||||
@@ -663,40 +436,27 @@ class ProxmoxSystemMixin:
|
|||||||
# write back via base64 to avoid shell-escaping issues.
|
# write back via base64 to avoid shell-escaping issues.
|
||||||
if old_short and old_short != short_hostname:
|
if old_short and old_short != short_hostname:
|
||||||
hosts_raw = self._exec_ssh_command("cat /etc/hosts 2>/dev/null")
|
hosts_raw = self._exec_ssh_command("cat /etc/hosts 2>/dev/null")
|
||||||
# Replace whole-word occurrences of the old short hostname.
|
hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain)
|
||||||
# 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_b64 = _b64.b64encode(hosts_new.encode()).decode()
|
hosts_b64 = _b64.b64encode(hosts_new.encode()).decode()
|
||||||
self._exec_ssh_command(
|
self._exec_ssh_command(
|
||||||
f"echo {hosts_b64} | base64 -d > /tmp/_netork_hosts"
|
f't=$(mktemp /etc/.hosts.XXXXXX) && echo {hosts_b64} | base64 -d > "$t"'
|
||||||
f" && mv /tmp/_netork_hosts /etc/hosts"
|
' && chmod 644 "$t" && mv "$t" /etc/hosts || { rm -f "$t"; false; }'
|
||||||
f" && chmod 644 /etc/hosts"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── 3. /etc/mailname ─────────────────────────────────────────────
|
# ── 3. /etc/mailname ─────────────────────────────────────────────
|
||||||
mailname_b64 = _b64.b64encode(f"{fqdn}\n".encode()).decode()
|
mailname_b64 = _b64.b64encode(f"{fqdn}\n".encode()).decode()
|
||||||
self._exec_ssh_command(
|
self._exec_ssh_command(
|
||||||
f"[ -f /etc/mailname ]"
|
f"[ -f /etc/mailname ] && echo {mailname_b64} | base64 -d > /etc/mailname || true"
|
||||||
f" && echo {mailname_b64} | base64 -d > /etc/mailname"
|
|
||||||
f" || true"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── 4. Postfix myhostname ─────────────────────────────────────────
|
# ── 4. Postfix myhostname ─────────────────────────────────────────
|
||||||
|
postfix = shlex.quote(f"myhostname = {fqdn}")
|
||||||
self._exec_ssh_command(
|
self._exec_ssh_command(
|
||||||
f"command -v postconf >/dev/null 2>&1"
|
f"command -v postconf >/dev/null 2>&1 && postconf -e {postfix} || true"
|
||||||
f" && postconf -e 'myhostname = {fqdn}'"
|
|
||||||
f" || true"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── 5. Apply hostname at runtime ─────────────────────────────────
|
# ── 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> ──────
|
# ── 6. Migrate /etc/pve/nodes/<old> → /etc/pve/nodes/<new> ──────
|
||||||
# Proxmox stores VM and CT configs under /etc/pve/nodes/<nodename>/.
|
# Proxmox stores VM and CT configs under /etc/pve/nodes/<nodename>/.
|
||||||
@@ -705,16 +465,15 @@ class ProxmoxSystemMixin:
|
|||||||
# Without this step the node boots under the new hostname, finds an
|
# Without this step the node boots under the new hostname, finds an
|
||||||
# empty /etc/pve/nodes/<new>/ and all VMs appear missing.
|
# empty /etc/pve/nodes/<new>/ and all VMs appear missing.
|
||||||
if old_short and old_short != short_hostname:
|
if old_short and old_short != short_hostname:
|
||||||
pve_old = f"/etc/pve/nodes/{old_short}"
|
pve_old = shlex.quote(f"/etc/pve/nodes/{old_short}")
|
||||||
pve_new = f"/etc/pve/nodes/{short_hostname}"
|
pve_new = shlex.quote(f"/etc/pve/nodes/{short_hostname}")
|
||||||
migrate_out = self._exec_ssh_command(
|
migrate_out = self._exec_ssh_command(
|
||||||
f"if [ -d '{pve_old}' ] && [ ! -e '{pve_new}' ]; then"
|
f"if [ -d {pve_old} ] && [ ! -e {pve_new} ]; then"
|
||||||
f" mv '{pve_old}' '{pve_new}'"
|
f" mv {pve_old} {pve_new} && echo migrated {pve_old} '->' {pve_new};"
|
||||||
f" && echo 'migrated {pve_old} -> {pve_new}';"
|
f"elif [ -d {pve_new} ]; then"
|
||||||
f"elif [ -d '{pve_new}' ]; then"
|
|
||||||
f" echo 'target already exists, skipping migration';"
|
f" echo 'target already exists, skipping migration';"
|
||||||
f"else"
|
f"else"
|
||||||
f" echo 'source {pve_old} not found, skipping migration';"
|
f" echo source {pve_old} 'not found, skipping migration';"
|
||||||
f"fi"
|
f"fi"
|
||||||
)
|
)
|
||||||
logger.info("Proxmox node dir migration: %s", migrate_out)
|
logger.info("Proxmox node dir migration: %s", migrate_out)
|
||||||
@@ -735,7 +494,9 @@ class ProxmoxSystemMixin:
|
|||||||
logger.info(
|
logger.info(
|
||||||
"Proxmox set_hostname: %s → %s (fqdn: %s). "
|
"Proxmox set_hostname: %s → %s (fqdn: %s). "
|
||||||
"Reboot required for node name to update in web UI / cluster.",
|
"Reboot required for node name to update in web UI / cluster.",
|
||||||
old_short, short_hostname, fqdn,
|
old_short,
|
||||||
|
short_hostname,
|
||||||
|
fqdn,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
@@ -772,12 +533,12 @@ class ProxmoxSystemMixin:
|
|||||||
if not dev:
|
if not dev:
|
||||||
continue
|
continue
|
||||||
entry: dict = {
|
entry: dict = {
|
||||||
"model": disk.get("model", ""),
|
"model": disk.get("model", ""),
|
||||||
"serial": disk.get("serial", ""),
|
"serial": disk.get("serial", ""),
|
||||||
"type": disk.get("type", ""),
|
"type": disk.get("type", ""),
|
||||||
"size": disk.get("size", 0),
|
"size": disk.get("size", 0),
|
||||||
"health": disk.get("health", "unknown").lower(),
|
"health": disk.get("health", "unknown").lower(),
|
||||||
"wearout": disk.get("wearout"), # NVMe wear indicator 0-100
|
"wearout": disk.get("wearout"), # NVMe wear indicator 0-100
|
||||||
"temperature": None,
|
"temperature": None,
|
||||||
"percentage_used": None,
|
"percentage_used": None,
|
||||||
"available_spare": None,
|
"available_spare": None,
|
||||||
@@ -808,7 +569,7 @@ class ProxmoxSystemMixin:
|
|||||||
# HDD-specific SMART attributes
|
# HDD-specific SMART attributes
|
||||||
for attr in smart.get("attributes", []):
|
for attr in smart.get("attributes", []):
|
||||||
name = attr.get("name", "").lower()
|
name = attr.get("name", "").lower()
|
||||||
raw = attr.get("raw", "")
|
raw = attr.get("raw", "")
|
||||||
try:
|
try:
|
||||||
raw_int = int(str(raw).split()[0])
|
raw_int = int(str(raw).split()[0])
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
@@ -846,7 +607,8 @@ class ProxmoxSystemMixin:
|
|||||||
"timezone": None,
|
"timezone": None,
|
||||||
"ntp_servers": [],
|
"ntp_servers": [],
|
||||||
"ssh_port": 22,
|
"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
|
# 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,75 @@
|
|||||||
|
"""The node's past APT transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||||
|
|
||||||
|
PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
||||||
|
first, also the transactions netOrk did not start (an operator's ``apt``,
|
||||||
|
unattended-upgrades). A transaction is named by its ``start-time`` and its
|
||||||
|
``start-index`` among those that started in the same second of the same log
|
||||||
|
file. An older node has no such endpoint: the driver raises
|
||||||
|
``NotImplementedError`` and parses no log over SSH.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
|
from napalm_device_types import UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict
|
||||||
|
|
||||||
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any) -> str | None:
|
||||||
|
return str(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
|
def _package(row: _JsonDict) -> UpdateHistoryPackageDict:
|
||||||
|
return {
|
||||||
|
"name": str(row.get("package") or ""),
|
||||||
|
"action": cast(UpdateHistoryAction, row.get("action")),
|
||||||
|
"old_version": _text(row.get("old-version")),
|
||||||
|
"new_version": _text(row.get("new-version")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _transaction(row: _JsonDict) -> UpdateHistoryDict:
|
||||||
|
start = int(row["start-time"])
|
||||||
|
end = row.get("end-time")
|
||||||
|
return {
|
||||||
|
"id": f"{start}-{int(row.get('start-index') or 0)}",
|
||||||
|
"start": start,
|
||||||
|
"end": None if end is None else int(end),
|
||||||
|
"packages": [_package(p) for p in row.get("packages") or []],
|
||||||
|
"requested_by": _text(row.get("requested-by")),
|
||||||
|
"command": _text(row.get("command-line")),
|
||||||
|
"error": _text(row.get("error")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxUpdateHistoryMixin:
|
||||||
|
"""Relies on the driver's ``_node_api`` and ``_version_at_least``."""
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
def _version_at_least(self, major: int, minor: int) -> bool: ...
|
||||||
|
|
||||||
|
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||||
|
"""The node's APT transactions, newest first, from ``since`` (unix seconds) on.
|
||||||
|
|
||||||
|
:raises NotImplementedError: before PVE 9.3, which has no history endpoint.
|
||||||
|
:raises RuntimeError: the history could not be read; never an empty list.
|
||||||
|
"""
|
||||||
|
if not self._version_at_least(*PVE_9_3):
|
||||||
|
raise NotImplementedError(
|
||||||
|
f"Proxmox VE on {self._node_name} keeps no APT history its API reports "
|
||||||
|
"(from 9.3 on)"
|
||||||
|
)
|
||||||
|
params = {} if since is None else {"since": since}
|
||||||
|
try:
|
||||||
|
rows = self._node_api().apt.history.get(**params) or []
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
|
||||||
|
return [_transaction(row) for row in rows]
|
||||||
@@ -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
|
from netaddr import EUI, AddrFormatError
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# MAC address helpers
|
# MAC address helpers
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -47,6 +46,7 @@ def normalize_mac(mac: str) -> str:
|
|||||||
# IP / prefix helpers
|
# IP / prefix helpers
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def prefix_length(cidr: str) -> int:
|
def prefix_length(cidr: str) -> int:
|
||||||
"""Return prefix length from a CIDR string such as '192.168.1.0/24' → 24."""
|
"""Return prefix length from a CIDR string such as '192.168.1.0/24' → 24."""
|
||||||
try:
|
try:
|
||||||
@@ -120,6 +120,12 @@ def is_ovs_interface(iface_data: dict[str, Any]) -> bool:
|
|||||||
return iface_data.get("type", "") in OVS_TYPES
|
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:
|
def is_sdn_vnet(name: str) -> bool:
|
||||||
return bool(re.fullmatch(r"vnet\d+", name))
|
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
|
# ARP / neighbour table helpers
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def parse_arp_output(raw: str) -> list[dict[str, Any]]:
|
def parse_arp_output(raw: str) -> list[dict[str, Any]]:
|
||||||
"""Parse Linux ``arp -n`` text output into NAPALM ARP dicts.
|
"""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
|
# OVS helpers
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def parse_ovs_vsctl_show(raw: str) -> dict[str, Any]:
|
def parse_ovs_vsctl_show(raw: str) -> dict[str, Any]:
|
||||||
"""Very lightweight parser for ``ovs-vsctl show`` output.
|
"""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
|
``power_vm`` stays for callers that already use it; these are what a
|
||||||
hypervisor-neutral caller talks to. They raise instead of returning 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
|
from __future__ import annotations
|
||||||
@@ -17,6 +19,9 @@ from napalm_device_types.models import (
|
|||||||
VMPassthroughDict,
|
VMPassthroughDict,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
from napalm_proxmox.vm_mixin import qemu_status
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
_POWER_TIMEOUT = 120
|
_POWER_TIMEOUT = 120
|
||||||
@@ -148,9 +153,9 @@ class ProxmoxVMContractMixin:
|
|||||||
node = self._node_api()
|
node = self._node_api()
|
||||||
return node.qemu(vmid) if vm_type == "vm" else node.lxc(vmid)
|
return node.qemu(vmid) if vm_type == "vm" else node.lxc(vmid)
|
||||||
|
|
||||||
def _run_power(self, vmid: int, vm_type: str, action: str) -> None:
|
def _run_power(self, vmid: int, vm_type: str, action: str, **params: Any) -> None:
|
||||||
try:
|
try:
|
||||||
upid = getattr(self._guest_api(vmid, vm_type).status, action).post()
|
upid = getattr(self._guest_api(vmid, vm_type).status, action).post(**params)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise RuntimeError(f"{action} of {vm_type} {vmid} failed: {exc}") from exc
|
raise RuntimeError(f"{action} of {vm_type} {vmid} failed: {exc}") from exc
|
||||||
if upid:
|
if upid:
|
||||||
@@ -162,6 +167,14 @@ class ProxmoxVMContractMixin:
|
|||||||
def stop_vm(self, name: str, force: bool = False) -> None:
|
def stop_vm(self, name: str, force: bool = False) -> None:
|
||||||
self._run_power(*self._resolve_vm(name), "stop" if force else "shutdown")
|
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:
|
def reboot_vm(self, name: str, force: bool = False) -> None:
|
||||||
vmid, vm_type = self._resolve_vm(name)
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
if not force:
|
if not force:
|
||||||
@@ -178,16 +191,33 @@ class ProxmoxVMContractMixin:
|
|||||||
raise RuntimeError(f"Proxmox cannot suspend container {vmid}")
|
raise RuntimeError(f"Proxmox cannot suspend container {vmid}")
|
||||||
self._run_power(vmid, vm_type, "suspend")
|
self._run_power(vmid, vm_type, "suspend")
|
||||||
|
|
||||||
|
def resume_vm(self, name: str) -> None:
|
||||||
|
"""``status/resume`` for a paused QEMU guest (NetOrk/netork#2658).
|
||||||
|
|
||||||
|
A container is refused: this driver does not suspend one, PVE's container
|
||||||
|
suspend is experimental (CRIU), and its listing does not tell a suspended
|
||||||
|
container from another. A guest that is not paused is refused too: PVE would
|
||||||
|
answer a running one with success and do nothing.
|
||||||
|
|
||||||
|
From PVE 9.3 the guest agent sets the guest's clock to the host's time after
|
||||||
|
it resumes (``sync-time-on-resume``); PVE skips that where the guest has no
|
||||||
|
agent enabled and running.
|
||||||
|
"""
|
||||||
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
|
if vm_type != "vm":
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Proxmox cannot resume container {vmid}: only a paused VM can be resumed"
|
||||||
|
)
|
||||||
|
current = self._guest_api(vmid, vm_type).status.current.get() or {}
|
||||||
|
state = qemu_status(current)
|
||||||
|
if state != "paused":
|
||||||
|
raise RuntimeError(f"Cannot resume VM {vmid}: it is not paused ({state})")
|
||||||
|
params = {"sync-time-on-resume": 1} if self._version_at_least(*PVE_9_3) else {}
|
||||||
|
self._run_power(vmid, vm_type, "resume", **params)
|
||||||
|
|
||||||
def get_vm_config(self, name: str) -> VMConfigDict:
|
def get_vm_config(self, name: str) -> VMConfigDict:
|
||||||
vmid, vm_type = self._resolve_vm(name)
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
cfg = self._guest_api(vmid, vm_type).config.get() or {}
|
cfg = self._guest_api(vmid, vm_type).config.get() or {}
|
||||||
return parse_vm_config(str(vmid), vm_type, cfg)
|
return parse_vm_config(str(vmid), vm_type, cfg)
|
||||||
|
|
||||||
# -- the node itself --------------------------------------------------------
|
# -- 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,274 @@
|
|||||||
|
"""HypervisorDriver migration methods for Proxmox VE: preflight, migrate, HA maintenance.
|
||||||
|
|
||||||
|
A guest is addressed like every other VM method of this driver: by vmid or name,
|
||||||
|
on the node the driver is connected to (``_resolve_vm``).
|
||||||
|
|
||||||
|
- ``get_vm_migration_preflight``: a VM asks ``GET .../qemu/{vmid}/migrate``; a
|
||||||
|
container has no such endpoint, so the online members are its candidates.
|
||||||
|
A member the cluster calls offline is refused (``"node offline"``) for both,
|
||||||
|
also where the VM endpoint would list it as allowed.
|
||||||
|
- ``migrate_vm``: ``POST .../{qemu|lxc}/{vmid}/migrate`` and the task is followed
|
||||||
|
to its end; a failure raises with the task log's ``ERROR:`` lines. A guest HA
|
||||||
|
manages migrates through a ``hamigrate`` task that only hands the request to
|
||||||
|
the HA manager; the driver then follows ``/cluster/ha/status/current`` until
|
||||||
|
the guest is on the target, and on a failure reads the migration task's log.
|
||||||
|
- ``set_node_maintenance``: from PVE 9.3 ``PUT /nodes/{node}/maintenance``; an
|
||||||
|
older node has no REST endpoint for it, and the driver runs
|
||||||
|
``ha-manager crm-command node-maintenance`` over its SSH session. Either way the
|
||||||
|
HA manager moves the node's HA guests away after the request returned.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shlex
|
||||||
|
from time import monotonic, sleep
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from napalm_proxmox.migration import lxc_local, qemu_local, refusal, task_errors, upid_field
|
||||||
|
from napalm_proxmox.pve_values import PVE_9_3, to_flag
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
|
||||||
|
from napalm_device_types import MigrationPreflightDict
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: Enough to reach the ERROR lines at the end of a long storage migration's log.
|
||||||
|
_TASK_LOG_LINES = 50000
|
||||||
|
_HA_POLL_SECONDS = 5
|
||||||
|
#: CRM states while the HA manager is moving a guest.
|
||||||
|
_HA_MOVING = frozenset({"migrate", "relocate"})
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxVMMigrateMixin:
|
||||||
|
"""Relies on the driver, ``_resolve_vm``/``_guest_api``, ``_members`` and
|
||||||
|
``_wait_for_task``/``_run_node_command``/``_node_ssh``."""
|
||||||
|
|
||||||
|
_api: Any
|
||||||
|
_node_name: str
|
||||||
|
hostname: str
|
||||||
|
timeout: int
|
||||||
|
_node_api: Any
|
||||||
|
_resolve_vm: Any
|
||||||
|
_guest_api: Any
|
||||||
|
_members: Any
|
||||||
|
_wait_for_task: Any
|
||||||
|
_node_ssh: Any
|
||||||
|
_run_node_command: Any
|
||||||
|
_version_at_least: Any
|
||||||
|
|
||||||
|
# -- cluster membership -------------------------------------------------------
|
||||||
|
|
||||||
|
def _cluster_members(self) -> list[Any]:
|
||||||
|
status = self._api.cluster.status.get() or []
|
||||||
|
clustered = any(s.get("type") == "cluster" for s in status)
|
||||||
|
return list(self._members(status if clustered else []))
|
||||||
|
|
||||||
|
def _other_member(self, node: str) -> None:
|
||||||
|
names = [m.name for m in self._cluster_members()]
|
||||||
|
if node == self._node_name or node not in names:
|
||||||
|
raise ValueError(
|
||||||
|
f"{node!r} is not another member of the cluster of {self._node_name!r} "
|
||||||
|
f"(members: {', '.join(names)})"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _storage_sharing(self) -> dict[str, bool]:
|
||||||
|
rows = self._api.cluster.resources.get(type="storage") or []
|
||||||
|
sharing: dict[str, bool] = {}
|
||||||
|
for row in rows:
|
||||||
|
if row.get("type") == "storage" and row.get("storage"):
|
||||||
|
name = str(row["storage"])
|
||||||
|
sharing[name] = sharing.get(name, False) or to_flag(row.get("shared"))
|
||||||
|
return sharing
|
||||||
|
|
||||||
|
# -- preflight ----------------------------------------------------------------
|
||||||
|
|
||||||
|
def get_vm_migration_preflight(self, name: str) -> MigrationPreflightDict:
|
||||||
|
"""Where the guest could move to within its cluster, and what blocks it."""
|
||||||
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
|
others = [m for m in self._cluster_members() if m.name != self._node_name]
|
||||||
|
offline = [m.name for m in others if not m.online]
|
||||||
|
if vm_type == "vm":
|
||||||
|
return self._qemu_preflight(vmid, offline)
|
||||||
|
return self._lxc_preflight(vmid, [m.name for m in others if m.online], offline)
|
||||||
|
|
||||||
|
def _qemu_preflight(self, vmid: int, offline: list[str]) -> MigrationPreflightDict:
|
||||||
|
answer = self._guest_api(vmid, "vm").migrate.get() or {}
|
||||||
|
refused = {
|
||||||
|
str(node): refusal(blockers)
|
||||||
|
for node, blockers in (answer.get("not_allowed_nodes") or {}).items()
|
||||||
|
}
|
||||||
|
for node in offline:
|
||||||
|
refused[node] = "; ".join(filter(None, ["node offline", refused.get(node)]))
|
||||||
|
disks, resources = qemu_local(answer)
|
||||||
|
return {
|
||||||
|
"running": to_flag(answer.get("running")),
|
||||||
|
"allowed_nodes": [
|
||||||
|
str(n) for n in answer.get("allowed_nodes") or [] if n not in offline
|
||||||
|
],
|
||||||
|
"refused_nodes": refused,
|
||||||
|
"local_disks": disks,
|
||||||
|
"local_resources": resources,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _lxc_running(self, vmid: int) -> bool:
|
||||||
|
status = self._guest_api(vmid, "container").status.current.get() or {}
|
||||||
|
return bool(status.get("status") == "running")
|
||||||
|
|
||||||
|
def _lxc_preflight(
|
||||||
|
self, vmid: int, online: list[str], offline: list[str]
|
||||||
|
) -> MigrationPreflightDict:
|
||||||
|
config = self._guest_api(vmid, "container").config.get() or {}
|
||||||
|
disks, resources = lxc_local(config, self._storage_sharing())
|
||||||
|
return {
|
||||||
|
"running": self._lxc_running(vmid),
|
||||||
|
"allowed_nodes": online,
|
||||||
|
"refused_nodes": {n: "node offline" for n in offline},
|
||||||
|
"local_disks": disks,
|
||||||
|
"local_resources": resources,
|
||||||
|
}
|
||||||
|
|
||||||
|
# -- migration ----------------------------------------------------------------
|
||||||
|
|
||||||
|
def migrate_vm(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
target_node: str,
|
||||||
|
online: bool = True,
|
||||||
|
target_storage: str | None = None,
|
||||||
|
timeout: int = 3600,
|
||||||
|
) -> None:
|
||||||
|
"""Move the guest to *target_node*; block until Proxmox VE finished."""
|
||||||
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
|
self._other_member(target_node)
|
||||||
|
deadline = monotonic() + timeout
|
||||||
|
params = self._qemu_params(vmid, online) if vm_type == "vm" else self._lxc_params(vmid)
|
||||||
|
if target_storage:
|
||||||
|
params["targetstorage" if vm_type == "vm" else "target-storage"] = target_storage
|
||||||
|
try:
|
||||||
|
upid = str(self._guest_api(vmid, vm_type).migrate.post(target=target_node, **params))
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Migration of {vm_type} {vmid} to {target_node!r} refused: {exc}"
|
||||||
|
) from exc
|
||||||
|
self._follow_task(upid, vmid, timeout)
|
||||||
|
if upid_field(upid, 5) == "hamigrate":
|
||||||
|
self._follow_ha(vmid, vm_type, target_node, deadline, upid)
|
||||||
|
|
||||||
|
def _qemu_params(self, vmid: int, online: bool) -> dict[str, Any]:
|
||||||
|
answer = self._guest_api(vmid, "vm").migrate.get() or {}
|
||||||
|
params: dict[str, Any] = {}
|
||||||
|
if online and to_flag(answer.get("running")):
|
||||||
|
params["online"] = 1
|
||||||
|
if qemu_local(answer)[0]:
|
||||||
|
params["with-local-disks"] = 1
|
||||||
|
return params
|
||||||
|
|
||||||
|
def _lxc_params(self, vmid: int) -> dict[str, Any]:
|
||||||
|
# A container cannot move while running; restart mode stops and restarts it.
|
||||||
|
return {"restart": 1} if self._lxc_running(vmid) else {}
|
||||||
|
|
||||||
|
def _task_errors(self, upid: str) -> list[str]:
|
||||||
|
try:
|
||||||
|
log = self._node_api().tasks(upid).log.get(limit=_TASK_LOG_LINES) or []
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Cannot read the log of task %s: %s", upid, exc)
|
||||||
|
return []
|
||||||
|
return task_errors(log)
|
||||||
|
|
||||||
|
def _follow_task(self, upid: str, vmid: int, timeout: int) -> None:
|
||||||
|
try:
|
||||||
|
self._wait_for_task(upid, timeout=timeout)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
errors = self._task_errors(upid)
|
||||||
|
if not errors:
|
||||||
|
raise
|
||||||
|
raise RuntimeError(f"Migration of guest {vmid} failed: {'; '.join(errors)}") from exc
|
||||||
|
|
||||||
|
# -- a guest HA manages -------------------------------------------------------
|
||||||
|
|
||||||
|
def _ha_state(self, sid: str) -> tuple[str | None, str | None]:
|
||||||
|
rows = self._api.cluster.ha.status.current.get() or []
|
||||||
|
service: _JsonDict = next((r for r in rows if r.get("sid") == sid), {})
|
||||||
|
return service.get("node"), service.get("crm_state") or service.get("state")
|
||||||
|
|
||||||
|
def _follow_ha(
|
||||||
|
self, vmid: int, vm_type: str, target: str, deadline: float, ha_upid: str
|
||||||
|
) -> None:
|
||||||
|
sid = f"{'vm' if vm_type == 'vm' else 'ct'}:{vmid}"
|
||||||
|
moving_seen = False
|
||||||
|
while True:
|
||||||
|
node, state = self._ha_state(sid)
|
||||||
|
if node == target and state not in _HA_MOVING:
|
||||||
|
return
|
||||||
|
if state == "error":
|
||||||
|
self._ha_failed(vmid, vm_type, ha_upid, f"HA manager put {sid} into error state")
|
||||||
|
if state in _HA_MOVING:
|
||||||
|
moving_seen = True
|
||||||
|
elif moving_seen:
|
||||||
|
self._ha_failed(
|
||||||
|
vmid, vm_type, ha_upid, f"HA manager left {sid} on {node} ({state})"
|
||||||
|
)
|
||||||
|
if monotonic() > deadline:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Migration of {sid} to {target!r} timed out on {node} ({state})"
|
||||||
|
)
|
||||||
|
sleep(_HA_POLL_SECONDS)
|
||||||
|
|
||||||
|
def _ha_failed(self, vmid: int, vm_type: str, ha_upid: str, what: str) -> None:
|
||||||
|
"""Raise *what* with the ERROR lines of the migration the HA manager ran."""
|
||||||
|
errors: list[str] = []
|
||||||
|
kind = "qmigrate" if vm_type == "vm" else "vzmigrate"
|
||||||
|
try:
|
||||||
|
tasks = self._node_api().tasks.get(vmid=vmid, typefilter=kind, limit=1) or []
|
||||||
|
since = int(upid_field(ha_upid, 4) or "0", 16)
|
||||||
|
if tasks and int(tasks[0].get("starttime") or 0) >= since:
|
||||||
|
errors = self._task_errors(str(tasks[0].get("upid")))
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Cannot find the migration task of guest %s: %s", vmid, exc)
|
||||||
|
raise RuntimeError(f"{what}: {'; '.join(errors)}" if errors else what)
|
||||||
|
|
||||||
|
# -- HA maintenance -----------------------------------------------------------
|
||||||
|
|
||||||
|
def set_node_maintenance(self, node: str, enabled: bool) -> None:
|
||||||
|
"""Switch HA maintenance mode of a cluster node: over REST from PVE 9.3, else
|
||||||
|
with ``ha-manager`` over SSH."""
|
||||||
|
names = [m.name for m in self._cluster_members()]
|
||||||
|
if node not in names:
|
||||||
|
raise ValueError(
|
||||||
|
f"{node!r} is not a member of the cluster (members: {', '.join(names)})"
|
||||||
|
)
|
||||||
|
action = "enable" if enabled else "disable"
|
||||||
|
# The request is served by *node* itself, which may not run 9.3 yet mid-upgrade.
|
||||||
|
try:
|
||||||
|
over_rest = self._version_at_least(*PVE_9_3, node=node)
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Cannot read the Proxmox VE version of {node!r}: {exc}") from exc
|
||||||
|
if over_rest:
|
||||||
|
try:
|
||||||
|
self._api.nodes(node).maintenance.put(**{"maintenance-mode": action})
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Proxmox VE refused to {action} maintenance of {node!r}: {exc}"
|
||||||
|
) from exc
|
||||||
|
return
|
||||||
|
self._ha_manager_maintenance(node, action)
|
||||||
|
|
||||||
|
def _ha_manager_maintenance(self, node: str, action: str) -> None:
|
||||||
|
try:
|
||||||
|
self._node_ssh()
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Cannot {action} HA maintenance of node {node!r}: SSH to {self.hostname} "
|
||||||
|
f"is not available ({exc})"
|
||||||
|
) from exc
|
||||||
|
command = f"ha-manager crm-command node-maintenance {action} {shlex.quote(node)}"
|
||||||
|
try:
|
||||||
|
self._run_node_command(command, timeout=self.timeout)
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"ha-manager refused to {action} maintenance of {node!r}: {exc}"
|
||||||
|
) from exc
|
||||||
+104
-56
@@ -20,19 +20,31 @@ import logging
|
|||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm_proxmox import utils
|
from napalm_proxmox.pve_values import PVE_9_3
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The QMP states of a guest whose QEMU process holds its memory but does not run it:
|
||||||
|
#: paused (``status/suspend``, the GUI's Pause) and asleep in S3. ``status/resume``
|
||||||
|
#: brings either back. PVE's ``status`` says ``running`` for both (NetOrk/netork#2658).
|
||||||
|
PAUSED_QMP_STATES = ("paused", "suspended")
|
||||||
|
|
||||||
|
|
||||||
|
def qemu_status(vm: _JsonDict) -> str:
|
||||||
|
"""A QEMU guest's status as the contract names it: ``paused`` where PVE's full
|
||||||
|
status (``qmpstatus``) says the running process does not execute the guest."""
|
||||||
|
status = str(vm.get("status", "unknown"))
|
||||||
|
if status == "running" and vm.get("qmpstatus") in PAUSED_QMP_STATES:
|
||||||
|
return "paused"
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxVMMixin:
|
class ProxmoxVMMixin:
|
||||||
"""Mixin providing VM and container NAPALM methods."""
|
"""Mixin providing VM and container NAPALM methods."""
|
||||||
|
|
||||||
def get_vm_interfaces(
|
def get_vm_interfaces(self, vmid: int, vm_type: str) -> tuple[dict[str, _JsonDict], bool, bool]:
|
||||||
self, vmid: int, vm_type: str
|
|
||||||
) -> tuple[dict[str, _JsonDict], bool, bool]:
|
|
||||||
"""Return network interfaces for a single VM or LXC container.
|
"""Return network interfaces for a single VM or LXC container.
|
||||||
|
|
||||||
Returns a 3-tuple ``(interfaces, agent_running, agent_enabled)``:
|
Returns a 3-tuple ``(interfaces, agent_running, agent_enabled)``:
|
||||||
@@ -105,7 +117,7 @@ class ProxmoxVMMixin:
|
|||||||
logger.debug("get_vm_interfaces: LXC %s config failed: %s", vmid, exc)
|
logger.debug("get_vm_interfaces: LXC %s config failed: %s", vmid, exc)
|
||||||
|
|
||||||
try:
|
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", "")
|
name = iface.get("name", "")
|
||||||
if not name or name == "lo":
|
if not name or name == "lo":
|
||||||
continue
|
continue
|
||||||
@@ -219,7 +231,7 @@ class ProxmoxVMMixin:
|
|||||||
* vmid (str) - Proxmox VM/container ID, e.g. ``"100"``
|
* vmid (str) - Proxmox VM/container ID, e.g. ``"100"``
|
||||||
* name (str) - display name
|
* name (str) - display name
|
||||||
* type (str) - ``"vm"`` or ``"container"``
|
* type (str) - ``"vm"`` or ``"container"``
|
||||||
* status (str) - ``"running"``, ``"stopped"``, etc.
|
* status (str) - ``"running"``, ``"stopped"``, ``"paused"`` (``qemu_status``)
|
||||||
* vcpus (int) - allocated vCPUs
|
* vcpus (int) - allocated vCPUs
|
||||||
* memory (int) - configured RAM in megabytes
|
* memory (int) - configured RAM in megabytes
|
||||||
* cpu_usage (float) - current CPU utilisation 0.0–1.0 (from last stats cycle)
|
* cpu_usage (float) - current CPU utilisation 0.0–1.0 (from last stats cycle)
|
||||||
@@ -228,15 +240,15 @@ class ProxmoxVMMixin:
|
|||||||
* node (str) - cluster node name
|
* node (str) - cluster node name
|
||||||
* interfaces (dict) - network interfaces (NAPALM format + ipv4 field)
|
* interfaces (dict) - network interfaces (NAPALM format + ipv4 field)
|
||||||
* ipv4 (str) - primary IPv4 address (empty string if unknown)
|
* ipv4 (str) - primary IPv4 address (empty string if unknown)
|
||||||
|
* uid (str) - PVE 9.3's identity of the guest (``_with_uids``); absent before
|
||||||
"""
|
"""
|
||||||
result: list[_JsonDict] = []
|
result: list[_JsonDict] = []
|
||||||
|
# QEMU VMs; only the full status has ``qmpstatus``, which tells paused from running.
|
||||||
# QEMU VMs
|
|
||||||
try:
|
try:
|
||||||
for vm in (self._node_api().qemu.get() or []):
|
for vm in self._node_api().qemu.get(full=1) or []:
|
||||||
vmid = int(vm.get("vmid", 0))
|
vmid = int(vm.get("vmid", 0))
|
||||||
name = vm.get("name", f"vm-{vmid}")
|
name = vm.get("name", f"vm-{vmid}")
|
||||||
status = vm.get("status", "unknown")
|
status = qemu_status(vm)
|
||||||
cpu_usage = float(vm.get("cpu", 0.0) or 0.0)
|
cpu_usage = float(vm.get("cpu", 0.0) or 0.0)
|
||||||
uptime = int(vm.get("uptime", 0) or 0)
|
uptime = int(vm.get("uptime", 0) or 0)
|
||||||
|
|
||||||
@@ -256,30 +268,32 @@ class ProxmoxVMMixin:
|
|||||||
)
|
)
|
||||||
|
|
||||||
disks, onboot = self._get_vm_disk_and_boot(vmid, "qemu")
|
disks, onboot = self._get_vm_disk_and_boot(vmid, "qemu")
|
||||||
result.append({
|
result.append(
|
||||||
"vmid": str(vmid),
|
{
|
||||||
"name": name,
|
"vmid": str(vmid),
|
||||||
"type": "vm",
|
"name": name,
|
||||||
"status": status,
|
"type": "vm",
|
||||||
"vcpus": vcpus,
|
"status": status,
|
||||||
"memory": memory_mb,
|
"vcpus": vcpus,
|
||||||
"cpu_usage": round(cpu_usage, 4),
|
"memory": memory_mb,
|
||||||
"memory_usage": memory_usage_mb,
|
"cpu_usage": round(cpu_usage, 4),
|
||||||
"uptime": uptime,
|
"memory_usage": memory_usage_mb,
|
||||||
"node": self._node_name,
|
"uptime": uptime,
|
||||||
"interfaces": interfaces,
|
"node": self._node_name,
|
||||||
"ipv4": ipv4,
|
"interfaces": interfaces,
|
||||||
"agent_enabled": agent_enabled,
|
"ipv4": ipv4,
|
||||||
"agent_running": agent_running,
|
"agent_enabled": agent_enabled,
|
||||||
"disks": disks,
|
"agent_running": agent_running,
|
||||||
"onboot": onboot,
|
"disks": disks,
|
||||||
})
|
"onboot": onboot,
|
||||||
|
}
|
||||||
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("get_vms: failed to list QEMU VMs: %s", exc)
|
logger.warning("get_vms: failed to list QEMU VMs: %s", exc)
|
||||||
|
|
||||||
# LXC containers
|
# LXC containers
|
||||||
try:
|
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))
|
vmid = int(ct.get("vmid", 0))
|
||||||
name = ct.get("name", f"ct-{vmid}")
|
name = ct.get("name", f"ct-{vmid}")
|
||||||
status = ct.get("status", "unknown")
|
status = ct.get("status", "unknown")
|
||||||
@@ -300,37 +314,66 @@ class ProxmoxVMMixin:
|
|||||||
)
|
)
|
||||||
|
|
||||||
disks, onboot = self._get_vm_disk_and_boot(vmid, "lxc")
|
disks, onboot = self._get_vm_disk_and_boot(vmid, "lxc")
|
||||||
result.append({
|
result.append(
|
||||||
"vmid": str(vmid),
|
{
|
||||||
"name": name,
|
"vmid": str(vmid),
|
||||||
"type": "container",
|
"name": name,
|
||||||
"status": status,
|
"type": "container",
|
||||||
"vcpus": vcpus,
|
"status": status,
|
||||||
"memory": memory_mb,
|
"vcpus": vcpus,
|
||||||
"cpu_usage": round(cpu_usage, 4),
|
"memory": memory_mb,
|
||||||
"memory_usage": memory_usage_mb,
|
"cpu_usage": round(cpu_usage, 4),
|
||||||
"uptime": uptime,
|
"memory_usage": memory_usage_mb,
|
||||||
"node": self._node_name,
|
"uptime": uptime,
|
||||||
"interfaces": interfaces,
|
"node": self._node_name,
|
||||||
"ipv4": ipv4,
|
"interfaces": interfaces,
|
||||||
"agent_enabled": agent_enabled,
|
"ipv4": ipv4,
|
||||||
"agent_running": agent_running,
|
"agent_enabled": agent_enabled,
|
||||||
"disks": disks,
|
"agent_running": agent_running,
|
||||||
"onboot": onboot,
|
"disks": disks,
|
||||||
})
|
"onboot": onboot,
|
||||||
|
}
|
||||||
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("get_vms: failed to list LXC containers: %s", exc)
|
logger.warning("get_vms: failed to list LXC containers: %s", exc)
|
||||||
|
|
||||||
return sorted(result, key=lambda x: int(x["vmid"]))
|
return self._with_uids(sorted(result, key=lambda x: int(x["vmid"])))
|
||||||
|
|
||||||
|
def _with_uids(self, vms: list[_JsonDict]) -> list[_JsonDict]:
|
||||||
|
"""Give each guest in *vms* its ``uid``, joined by node and vmid.
|
||||||
|
|
||||||
|
PVE 9.3 gives every guest a random identifier that survives a migration, a
|
||||||
|
restore and a changed vmid; only ``GET /cluster/resources?type=vm`` reports
|
||||||
|
it. A guest without one, an older node and a listing that cannot be read
|
||||||
|
leave the key out: the guest is still listed, known by its vmid alone.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
uids = self._guest_uids()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("get_vms: cannot read the guests' uids: %s", exc)
|
||||||
|
return vms
|
||||||
|
for vm in vms:
|
||||||
|
uid = uids.get((vm["node"], vm["vmid"]))
|
||||||
|
if uid:
|
||||||
|
vm["uid"] = uid
|
||||||
|
return vms
|
||||||
|
|
||||||
|
def _guest_uids(self) -> dict[tuple[str, str], str]:
|
||||||
|
if not self._version_at_least(*PVE_9_3):
|
||||||
|
return {}
|
||||||
|
rows = self._api.cluster.resources.get(type="vm") or []
|
||||||
|
return {
|
||||||
|
(str(row.get("node")), str(row.get("vmid"))): str(row["uid"])
|
||||||
|
for row in rows
|
||||||
|
if row.get("uid")
|
||||||
|
}
|
||||||
|
|
||||||
# Disk-key prefixes for QEMU: scsi, virtio, ide, sata (exclude cdrom/none entries)
|
# Disk-key prefixes for QEMU: scsi, virtio, ide, sata (exclude cdrom/none entries)
|
||||||
_DISK_KEYS_VM = re.compile(r"^(scsi|virtio|ide|sata)\d+$")
|
_DISK_KEYS_VM = re.compile(r"^(scsi|virtio|ide|sata)\d+$")
|
||||||
# Disk-key prefix for LXC: rootfs, mp (mount points)
|
# Disk-key prefix for LXC: rootfs, mp (mount points)
|
||||||
_DISK_KEYS_CT = re.compile(r"^(rootfs|mp\d+)$")
|
_DISK_KEYS_CT = re.compile(r"^(rootfs|mp\d+)$")
|
||||||
|
|
||||||
def _get_vm_disk_and_boot(
|
def _get_vm_disk_and_boot(self, vmid: int, vm_type: str) -> tuple[list[dict], bool]:
|
||||||
self, vmid: int, vm_type: str
|
|
||||||
) -> tuple[list[dict], bool]:
|
|
||||||
"""Return (disks, onboot) for a VM or container.
|
"""Return (disks, onboot) for a VM or container.
|
||||||
|
|
||||||
Fetches config from /nodes/{node}/{qemu|lxc}/{vmid}/config.
|
Fetches config from /nodes/{node}/{qemu|lxc}/{vmid}/config.
|
||||||
@@ -376,8 +419,8 @@ class ProxmoxVMMixin:
|
|||||||
logger.debug("Failed to fetch disk/boot config for vmid %s: %s", vmid, exc)
|
logger.debug("Failed to fetch disk/boot config for vmid %s: %s", vmid, exc)
|
||||||
return [], False
|
return [], False
|
||||||
|
|
||||||
_POWER_ACTIONS_VM = {'start', 'stop', 'shutdown', 'reboot', 'reset'}
|
_POWER_ACTIONS_VM = {"start", "stop", "shutdown", "reboot", "reset"}
|
||||||
_POWER_ACTIONS_CT = {'start', 'stop', 'shutdown', 'reboot'}
|
_POWER_ACTIONS_CT = {"start", "stop", "shutdown", "reboot"}
|
||||||
|
|
||||||
def power_vm(self, vmid: int, vm_type: str, action: str) -> dict:
|
def power_vm(self, vmid: int, vm_type: str, action: str) -> dict:
|
||||||
"""Send a power action to a VM or container on this node.
|
"""Send a power action to a VM or container on this node.
|
||||||
@@ -385,11 +428,16 @@ class ProxmoxVMMixin:
|
|||||||
Supported actions for VMs: start, stop, shutdown, reboot, reset
|
Supported actions for VMs: start, stop, shutdown, reboot, reset
|
||||||
Supported actions for containers: start, stop, shutdown, reboot
|
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:
|
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:
|
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()
|
task_id = getattr(vm_api.status, action).post()
|
||||||
return {"success": True, "task_id": task_id or ""}
|
return {"success": True, "task_id": task_id or ""}
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
|||||||
@@ -3,65 +3,142 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
import hashlib
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
import time
|
import time
|
||||||
import yaml
|
from typing import TYPE_CHECKING, Any
|
||||||
from typing import Any, Dict, List
|
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import yaml
|
||||||
from napalm_device_types.models import (
|
from napalm_device_types.models import (
|
||||||
NetworkTargetDict,
|
NetworkTargetDict,
|
||||||
StorageTargetDict,
|
StorageTargetDict,
|
||||||
VMProvisionResultDict,
|
VMProvisionResultDict,
|
||||||
VMStatusDict,
|
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
|
||||||
|
# pyproject.toml, and nothing here needs it at runtime.
|
||||||
|
from napalm_device_types.models import VMCpuTypeDict
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# The CPU models a new VM may be given. Each lists the /proc/cpuinfo flags it
|
||||||
|
# adds on top of QEMU's qemu64 baseline: what the node's CPU must have for the
|
||||||
|
# model to start at all, and what a guest can count on. The sets follow
|
||||||
|
# Proxmox's own x86-64-v* definitions (qemu-server, PVE/QemuServer/CPUConfig.pm).
|
||||||
|
#
|
||||||
|
# Leaving the model out of qemu.post is not neutral: Proxmox then falls back to
|
||||||
|
# kvm64, which lacks even AES-NI, let alone the AVX MongoDB 5.0+ needs
|
||||||
|
# (netOrk#494). The default below is what the Proxmox GUI picks since PVE 8.
|
||||||
|
_X86_64_V2_AES_FLAGS = ("aes", "popcnt", "pni", "sse4_1", "sse4_2", "ssse3")
|
||||||
|
_X86_64_V3_FLAGS = _X86_64_V2_AES_FLAGS + (
|
||||||
|
"avx",
|
||||||
|
"avx2",
|
||||||
|
"bmi1",
|
||||||
|
"bmi2",
|
||||||
|
"f16c",
|
||||||
|
"fma",
|
||||||
|
"abm",
|
||||||
|
"movbe",
|
||||||
|
"xsave",
|
||||||
|
)
|
||||||
|
_DEFAULT_CPU_TYPE = "x86-64-v2-AES"
|
||||||
|
_CPU_MODELS = (
|
||||||
|
(
|
||||||
|
"x86-64-v2-AES",
|
||||||
|
_X86_64_V2_AES_FLAGS,
|
||||||
|
"Proxmox's own default: runs on practically any x86-64 server CPU and "
|
||||||
|
"can live-migrate between different ones. No AVX.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"x86-64-v3",
|
||||||
|
_X86_64_V3_FLAGS,
|
||||||
|
"Adds AVX and AVX2 (which MongoDB 5.0 and later need). Every node the VM "
|
||||||
|
"may run on needs an Intel Haswell or AMD Excavator CPU (2013) or newer.",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
_HOST_CPU_DESCRIPTION = (
|
||||||
|
"This node's CPU, passed through unchanged: fastest, with every feature it "
|
||||||
|
"has, but the VM can only live-migrate to nodes with the same CPU."
|
||||||
|
)
|
||||||
|
|
||||||
# Downloaded cloud images are cached here on the hypervisor node, keyed by
|
# Downloaded cloud images are cached here on the hypervisor node, keyed by
|
||||||
# filename, so provisioning multiple VMs from the same image only pays the
|
# filename, so provisioning multiple VMs from the same image only pays the
|
||||||
# download cost once.
|
# download cost once.
|
||||||
_IMAGE_CACHE_DIR = "/var/lib/vz/template/netork-images"
|
_IMAGE_CACHE_DIR = "/var/lib/vz/template/netork-images"
|
||||||
|
|
||||||
|
# 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"},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 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 _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}"
|
||||||
|
|
||||||
|
# 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
|
||||||
|
return config_args
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxVMProvisionMixin:
|
class ProxmoxVMProvisionMixin:
|
||||||
"""Mixin to add VM provisioning to ProxmoxDriver."""
|
"""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:
|
def _run_node_command(self, command: str, timeout: int) -> str:
|
||||||
"""
|
"""
|
||||||
Execute a shell command on the Proxmox node via SSH, raising on failure.
|
Execute a shell command on the Proxmox node via SSH, raising on failure.
|
||||||
|
|
||||||
Unlike ``_exec_ssh_command`` (best-effort, fixed timeout, swallows
|
Unlike ``_exec_ssh_command`` (fixed timeout, exit status not checked),
|
||||||
errors), this is for critical provisioning steps — image download,
|
this is for critical provisioning steps — image download, disk import —
|
||||||
disk import — where a non-zero exit or a caller-specific timeout must
|
where a non-zero exit or a caller-specific timeout must surface as a
|
||||||
surface as a hard failure rather than an empty string.
|
hard failure.
|
||||||
"""
|
"""
|
||||||
import paramiko
|
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=timeout)
|
||||||
|
|
||||||
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)
|
|
||||||
exit_status = stdout.channel.recv_exit_status()
|
exit_status = stdout.channel.recv_exit_status()
|
||||||
out = stdout.read().decode().strip()
|
out = stdout.read().decode().strip()
|
||||||
err = stderr.read().decode().strip()
|
err = stderr.read().decode().strip()
|
||||||
@@ -88,40 +165,26 @@ class ProxmoxVMProvisionMixin:
|
|||||||
once (covers a corrupted/partial transfer or a stale same-keyed file)
|
once (covers a corrupted/partial transfer or a stale same-keyed file)
|
||||||
before raising.
|
before raising.
|
||||||
"""
|
"""
|
||||||
filename = image_url.rstrip("/").rsplit("/", 1)[-1]
|
local_path = f"{_IMAGE_CACHE_DIR}/{cache_name(image_url)}"
|
||||||
url_hash = hashlib.sha256(image_url.encode()).hexdigest()[:12]
|
algo, expected = split_checksum(image_checksum or "")
|
||||||
local_path = f"{_IMAGE_CACHE_DIR}/{url_hash}-{filename}"
|
|
||||||
|
|
||||||
algo, _, expected = (image_checksum or "").partition(":")
|
|
||||||
algo = (algo or "sha256").lower()
|
|
||||||
|
|
||||||
max_attempts = 2
|
max_attempts = 2
|
||||||
for attempt in range(1, max_attempts + 1):
|
for attempt in range(1, max_attempts + 1):
|
||||||
exists = self._run_node_command(
|
if not self._cached_on_node(local_path):
|
||||||
f"mkdir -p {_IMAGE_CACHE_DIR} && test -f {local_path} "
|
self._fetch_image(image_url, local_path, timeout)
|
||||||
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 image_checksum:
|
if not image_checksum:
|
||||||
return local_path
|
return local_path
|
||||||
|
|
||||||
actual = self._run_node_command(
|
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():
|
if actual.lower() == expected.lower():
|
||||||
return local_path
|
return local_path
|
||||||
|
|
||||||
# Remove the bad file so the next attempt re-downloads instead of
|
# Remove the bad file so the next attempt re-downloads instead of
|
||||||
# reusing it.
|
# 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:
|
if attempt == max_attempts:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"Checksum mismatch for {image_url}: expected {expected}, got {actual}"
|
f"Checksum mismatch for {image_url}: expected {expected}, got {actual}"
|
||||||
@@ -133,6 +196,207 @@ class ProxmoxVMProvisionMixin:
|
|||||||
|
|
||||||
raise AssertionError("unreachable") # loop always returns or raises above
|
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".
|
||||||
|
|
||||||
|
Such a storage (Proxmox 8.2+) can take a cloud image straight from its
|
||||||
|
URL. Inactive storages (typically a share that is not mounted) are
|
||||||
|
skipped rather than failed on: the SSH path still works without them.
|
||||||
|
Node-scoped for the same reason as _find_default_image_storage.
|
||||||
|
"""
|
||||||
|
for storage in self._node_api().storage.get():
|
||||||
|
content = storage.get("content", "").split(",")
|
||||||
|
if "import" not in content:
|
||||||
|
continue
|
||||||
|
if storage.get("enabled", 1) == 0 or storage.get("active", 1) == 0:
|
||||||
|
continue
|
||||||
|
return storage["storage"]
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _import_cloud_image(
|
||||||
|
self,
|
||||||
|
storage: str,
|
||||||
|
filename: str,
|
||||||
|
image_url: str,
|
||||||
|
image_checksum: str | None,
|
||||||
|
timeout: int,
|
||||||
|
) -> str:
|
||||||
|
"""Have Proxmox download *image_url* into *storage*; returns the volume id.
|
||||||
|
|
||||||
|
Proxmox runs the download as a task and verifies the checksum itself.
|
||||||
|
A file already in the storage is reused — the name carries a hash of
|
||||||
|
the full URL, and Proxmox only creates it once the download (and its
|
||||||
|
checksum check) has succeeded, so an existing file is a complete one.
|
||||||
|
"""
|
||||||
|
volid = f"{storage}:import/{filename}"
|
||||||
|
present = self._node_api().storage(storage).content.get(content="import")
|
||||||
|
if any(item.get("volid") == volid for item in present):
|
||||||
|
_logger.info(f"Cloud image already in {storage}: {volid}")
|
||||||
|
return volid
|
||||||
|
|
||||||
|
params: dict[str, Any] = {"url": image_url, "content": "import", "filename": filename}
|
||||||
|
if 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}")
|
||||||
|
upid = self._node_api().storage(storage)("download-url").post(**params)
|
||||||
|
self._wait_for_task(upid, timeout=timeout)
|
||||||
|
return volid
|
||||||
|
|
||||||
|
def _import_over_ssh(
|
||||||
|
self,
|
||||||
|
vmid: int,
|
||||||
|
image_storage: str,
|
||||||
|
image_url: str,
|
||||||
|
image_checksum: str | None,
|
||||||
|
download_timeout: int,
|
||||||
|
timeout: int,
|
||||||
|
) -> None:
|
||||||
|
"""Download the image on the node and import it as the root disk.
|
||||||
|
|
||||||
|
The path for nodes without an import storage, or for an image type
|
||||||
|
Proxmox cannot import itself.
|
||||||
|
"""
|
||||||
|
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 {int(vmid)} {shlex.quote(local_path)} {shlex.quote(image_storage)} "
|
||||||
|
"--format qcow2",
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Proxmox leaves the imported disk as an "unusedN" reference — find
|
||||||
|
# it and attach it as the boot disk.
|
||||||
|
imported_config = self._node_api().qemu(vmid).config.get()
|
||||||
|
unused_value = next((v for k, v in imported_config.items() if k.startswith("unused")), None)
|
||||||
|
if not unused_value:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Disk import for VM {vmid} did not produce an unused disk reference"
|
||||||
|
)
|
||||||
|
self._node_api().qemu(vmid).config.post(
|
||||||
|
scsi0=f"{unused_value},discard=on",
|
||||||
|
boot="order=scsi0",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _attach_root_disk(
|
||||||
|
self,
|
||||||
|
vmid: int,
|
||||||
|
image_storage: str,
|
||||||
|
image_url: str,
|
||||||
|
image_checksum: str | None,
|
||||||
|
download_timeout: int,
|
||||||
|
timeout: int,
|
||||||
|
) -> None:
|
||||||
|
"""Get the cloud image onto the node and make it the VM's root disk.
|
||||||
|
|
||||||
|
Through an import storage when the node has one — Proxmox downloads,
|
||||||
|
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
|
||||||
|
if not import_storage or not filename:
|
||||||
|
self._import_over_ssh(
|
||||||
|
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
volid = self._import_cloud_image(
|
||||||
|
import_storage, filename, image_url, image_checksum, timeout=download_timeout
|
||||||
|
)
|
||||||
|
_logger.info(f"Importing {volid} into VM {vmid} on storage {image_storage}")
|
||||||
|
upid = (
|
||||||
|
self._node_api()
|
||||||
|
.qemu(vmid)
|
||||||
|
.config.post(
|
||||||
|
scsi0=f"{image_storage}:0,import-from={volid},discard=on",
|
||||||
|
boot="order=scsi0",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if upid:
|
||||||
|
self._wait_for_task(upid, timeout=timeout)
|
||||||
|
|
||||||
def _find_default_image_storage(self) -> str:
|
def _find_default_image_storage(self) -> str:
|
||||||
"""Find a storage suitable for VM root disks (content includes 'images').
|
"""Find a storage suitable for VM root disks (content includes 'images').
|
||||||
|
|
||||||
@@ -175,9 +439,9 @@ class ProxmoxVMProvisionMixin:
|
|||||||
)
|
)
|
||||||
return path
|
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."""
|
"""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():
|
for storage in self._node_api().storage.get():
|
||||||
content = storage.get("content", "")
|
content = storage.get("content", "")
|
||||||
if "images" not in content or storage.get("enabled", 1) == 0:
|
if "images" not in content or storage.get("enabled", 1) == 0:
|
||||||
@@ -196,6 +460,55 @@ class ProxmoxVMProvisionMixin:
|
|||||||
)
|
)
|
||||||
return targets
|
return targets
|
||||||
|
|
||||||
|
def get_vm_cpu_types(self) -> list[VMCpuTypeDict]:
|
||||||
|
"""List the CPU models a new VM may be given, judged against this node's CPU."""
|
||||||
|
return self._cpu_types_for(self._node_cpu_flags())
|
||||||
|
|
||||||
|
def _node_cpu_flags(self) -> set[str]:
|
||||||
|
return set(cpu_flags(self._node_api().status.get() or {}) or [])
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _cpu_types_for(node_flags: set[str]) -> list[VMCpuTypeDict]:
|
||||||
|
types: list[VMCpuTypeDict] = [
|
||||||
|
{
|
||||||
|
"name": name,
|
||||||
|
"description": description,
|
||||||
|
"features": list(flags),
|
||||||
|
"available": set(flags) <= node_flags,
|
||||||
|
"default": name == _DEFAULT_CPU_TYPE,
|
||||||
|
}
|
||||||
|
for name, flags, description in _CPU_MODELS
|
||||||
|
]
|
||||||
|
types.append(
|
||||||
|
{
|
||||||
|
"name": "host",
|
||||||
|
"description": _HOST_CPU_DESCRIPTION,
|
||||||
|
"features": sorted(node_flags),
|
||||||
|
"available": True,
|
||||||
|
"default": False,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return types
|
||||||
|
|
||||||
|
def _resolve_cpu_type(self, cpu_type: str | None) -> str:
|
||||||
|
"""The model to create the VM with. A model asked for by name is checked
|
||||||
|
against this node's CPU first: one it cannot run would fail only at VM
|
||||||
|
start, after the disk import, leaving a half-built VM behind."""
|
||||||
|
if cpu_type is None:
|
||||||
|
return _DEFAULT_CPU_TYPE
|
||||||
|
node_flags = self._node_cpu_flags()
|
||||||
|
offered = {t["name"]: t for t in self._cpu_types_for(node_flags)}
|
||||||
|
entry = offered.get(cpu_type)
|
||||||
|
if entry is None:
|
||||||
|
raise ValueError(f"Unknown CPU type {cpu_type!r}; choose one of {', '.join(offered)}")
|
||||||
|
if not entry["available"]:
|
||||||
|
missing = sorted(set(entry["features"]) - node_flags)
|
||||||
|
raise ValueError(
|
||||||
|
f"CPU type {cpu_type!r} needs {', '.join(missing)}, which the CPU of "
|
||||||
|
f"node {self._node_name} does not have"
|
||||||
|
)
|
||||||
|
return cpu_type
|
||||||
|
|
||||||
def _wait_for_task(self, upid: str, timeout: int = 120) -> None:
|
def _wait_for_task(self, upid: str, timeout: int = 120) -> None:
|
||||||
"""
|
"""
|
||||||
Poll a Proxmox task until completion.
|
Poll a Proxmox task until completion.
|
||||||
@@ -227,6 +540,19 @@ class ProxmoxVMProvisionMixin:
|
|||||||
|
|
||||||
time.sleep(2)
|
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(
|
def create_vm_from_cloud_init(
|
||||||
self,
|
self,
|
||||||
name: str,
|
name: str,
|
||||||
@@ -234,12 +560,15 @@ class ProxmoxVMProvisionMixin:
|
|||||||
image_url: str,
|
image_url: str,
|
||||||
cpu: int,
|
cpu: int,
|
||||||
memory: int,
|
memory: int,
|
||||||
nics: List[Dict[str, Any]],
|
nics: list[dict[str, Any]],
|
||||||
cloud_init_config: Dict[str, Any],
|
cloud_init_config: dict[str, Any],
|
||||||
image_checksum: str | None = None,
|
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,
|
disk_resize_gb: int | None = None,
|
||||||
storage: str | None = None,
|
storage: str | None = None,
|
||||||
|
cpu_type: str | None = None,
|
||||||
|
guest_os: str = "linux",
|
||||||
|
node: str | None = None,
|
||||||
download_timeout: int = 300,
|
download_timeout: int = 300,
|
||||||
timeout: int = 180,
|
timeout: int = 180,
|
||||||
) -> VMProvisionResultDict:
|
) -> VMProvisionResultDict:
|
||||||
@@ -272,6 +601,14 @@ class ProxmoxVMProvisionMixin:
|
|||||||
disk_resize_gb: resize root disk to this size (None = no resize)
|
disk_resize_gb: resize root disk to this size (None = no resize)
|
||||||
storage: storage pool for the root disk (None = auto-detect first
|
storage: storage pool for the root disk (None = auto-detect first
|
||||||
enabled, node-available storage with content='images')
|
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)
|
download_timeout: max seconds for the image download (skipped if cached)
|
||||||
timeout: max seconds for the remaining provisioning steps
|
timeout: max seconds for the remaining provisioning steps
|
||||||
|
|
||||||
@@ -279,11 +616,21 @@ class ProxmoxVMProvisionMixin:
|
|||||||
{"vmid": str, "name": str, "node": str}
|
{"vmid": str, "name": str, "node": str}
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
RuntimeError: provisioning failure (download, import, config, timeout, etc.)
|
VMProvisionIncomplete: any failure once the VM shell exists (download,
|
||||||
ValueError: invalid storage or configuration
|
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:
|
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
|
# Step 1: Get next VMID
|
||||||
next_vmid = self._api.cluster.nextid.get()
|
next_vmid = self._api.cluster.nextid.get()
|
||||||
@@ -297,66 +644,24 @@ class ProxmoxVMProvisionMixin:
|
|||||||
name=name,
|
name=name,
|
||||||
memory=memory,
|
memory=memory,
|
||||||
cores=cpu,
|
cores=cpu,
|
||||||
ostype="l26",
|
cpu=cpu_model,
|
||||||
scsihw="virtio-scsi-pci",
|
scsihw="virtio-scsi-pci",
|
||||||
# Without this, Proxmox never attaches the virtio-serial
|
# Includes agent: without it Proxmox never attaches the
|
||||||
# channel the QEMU guest agent needs — get_vm_status's
|
# channel the QEMU guest agent needs — get_vm_status's agent
|
||||||
# agent queries (below) would have nothing to talk to.
|
# queries (below) would have nothing to talk to.
|
||||||
agent="1",
|
**_GUEST_VM_SETTINGS[guest_os],
|
||||||
)
|
)
|
||||||
|
created = vmid
|
||||||
|
|
||||||
# Step 3: Download cloud image (cached) and import as root disk
|
# Step 3: Download cloud image (cached) and import as root disk
|
||||||
local_path = self._download_cloud_image(
|
|
||||||
image_url, image_checksum, timeout=download_timeout
|
|
||||||
)
|
|
||||||
image_storage = storage or self._find_default_image_storage()
|
image_storage = storage or self._find_default_image_storage()
|
||||||
|
self._attach_root_disk(
|
||||||
_logger.info(f"Importing {local_path} into VM {vmid} on storage {image_storage}")
|
vmid, image_storage, image_url, image_checksum, download_timeout, timeout
|
||||||
self._run_node_command(
|
|
||||||
f"qm importdisk {vmid} {local_path} {image_storage} --format qcow2",
|
|
||||||
timeout=timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Proxmox leaves the imported disk as an "unusedN" reference — find
|
|
||||||
# it and attach it as the boot disk.
|
|
||||||
imported_config = self._node_api().qemu(vmid).config.get()
|
|
||||||
unused_value = next(
|
|
||||||
(v for k, v in imported_config.items() if k.startswith("unused")), None
|
|
||||||
)
|
|
||||||
if not unused_value:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"Disk import for VM {vmid} did not produce an unused disk reference"
|
|
||||||
)
|
|
||||||
self._node_api().qemu(vmid).config.post(
|
|
||||||
scsi0=f"{unused_value},discard=on",
|
|
||||||
boot="order=scsi0",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Step 4: Configure network interfaces (CPU/memory already set at shell creation)
|
# Step 4: Configure network interfaces (CPU/memory already set at shell creation)
|
||||||
_logger.info(f"Configuring {len(nics)} NIC(s) for VM {vmid}")
|
_logger.info(f"Configuring {len(nics)} NIC(s) for VM {vmid}")
|
||||||
|
self._node_api().qemu(vmid).config.post(**_nic_config_args(nics))
|
||||||
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)
|
|
||||||
|
|
||||||
# Step 5: Verify snippet storage exists
|
# Step 5: Verify snippet storage exists
|
||||||
# (enabled is absent-not-falsy, and node-scoping matters — see
|
# (enabled is absent-not-falsy, and node-scoping matters — see
|
||||||
@@ -386,20 +691,20 @@ class ProxmoxVMProvisionMixin:
|
|||||||
)
|
)
|
||||||
|
|
||||||
filename = f"{vmid}-user-data.yaml"
|
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)
|
storage_path = self._get_storage_path(snippet_storage)
|
||||||
encoded = base64.b64encode(user_data_yaml.encode("utf-8")).decode("ascii")
|
self._write_snippet(storage_path, filename, user_data_yaml)
|
||||||
self._run_node_command(
|
cicustom = f"user={snippet_storage}:snippets/{filename}"
|
||||||
f"mkdir -p {storage_path}/snippets && "
|
|
||||||
f"echo {encoded} | base64 -d > {storage_path}/snippets/{filename}",
|
# Proxmox writes network-config v1, and FreeBSD's nuageinit fails
|
||||||
timeout=30,
|
# 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
|
# Step 7: Configure Cloud-Init references and SSH keys
|
||||||
_logger.info(f"Setting Cloud-Init config for VM {vmid}")
|
_logger.info(f"Setting Cloud-Init config for VM {vmid}")
|
||||||
@@ -413,7 +718,7 @@ class ProxmoxVMProvisionMixin:
|
|||||||
# this points at a snippets-only storage.
|
# this points at a snippets-only storage.
|
||||||
"ide2": f"{image_storage}:cloudinit",
|
"ide2": f"{image_storage}:cloudinit",
|
||||||
"citype": "nocloud",
|
"citype": "nocloud",
|
||||||
"cicustom": f"user={snippet_storage}:snippets/{filename}",
|
"cicustom": cicustom,
|
||||||
}
|
}
|
||||||
|
|
||||||
# Configure DHCP for NICs where enabled (default True for index 0, False otherwise)
|
# Configure DHCP for NICs where enabled (default True for index 0, False otherwise)
|
||||||
@@ -423,9 +728,9 @@ class ProxmoxVMProvisionMixin:
|
|||||||
cloud_init_args[f"ipconfig{i}"] = "ip=dhcp"
|
cloud_init_args[f"ipconfig{i}"] = "ip=dhcp"
|
||||||
|
|
||||||
if ssh_public_keys:
|
if ssh_public_keys:
|
||||||
# URL-encode SSH keys for Proxmox API
|
# One key per line, URL-encoded without exception: Proxmox's
|
||||||
sshkeys = ";".join(ssh_public_keys)
|
# "urlencoded" format refuses an unescaped "/" or "+".
|
||||||
cloud_init_args["sshkeys"] = quote(sshkeys)
|
cloud_init_args["sshkeys"] = quote("\n".join(ssh_public_keys), safe="")
|
||||||
|
|
||||||
self._node_api().qemu(vmid).config.post(**cloud_init_args)
|
self._node_api().qemu(vmid).config.post(**cloud_init_args)
|
||||||
|
|
||||||
@@ -464,7 +769,10 @@ class ProxmoxVMProvisionMixin:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_logger.exception(f"Failed to create VM '{name}': {e}")
|
_logger.exception(f"Failed to create VM '{name}': {e}")
|
||||||
raise
|
if created is None:
|
||||||
|
raise
|
||||||
|
# The VM stays behind half built; the caller removes it by its id.
|
||||||
|
raise VMProvisionIncomplete(str(e), vmid=str(created), node=self._node_name) from e
|
||||||
|
|
||||||
def destroy_vm(
|
def destroy_vm(
|
||||||
self,
|
self,
|
||||||
@@ -501,35 +809,21 @@ class ProxmoxVMProvisionMixin:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
_logger.debug(f"VM {vmid} stop failed (may already be stopped): {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
|
# Step 2: Delete VM
|
||||||
# Proxmox's API parameter is hyphenated (destroy-unreferenced-disks),
|
self._delete_vm(vmid_int, remove_disk, timeout)
|
||||||
# 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)
|
|
||||||
|
|
||||||
# Step 3: Clean up Cloud-Init snippets
|
# Step 3: Clean up Cloud-Init snippets
|
||||||
# (This is best-effort; snippet files may be unreachable if storage is unavailable)
|
# (This is best-effort; snippet files may be unreachable if storage is unavailable)
|
||||||
try:
|
for storage, filepath in snippets:
|
||||||
config = self._node_api().qemu(vmid_int).config.get()
|
_logger.debug(f"Deleting snippet {filepath} from {storage}")
|
||||||
cicustom = config.get("cicustom", "")
|
try:
|
||||||
if "snippets/" in cicustom:
|
self._node_api().storage(storage).content(filepath).delete()
|
||||||
parts = cicustom.split("=")
|
except Exception as e:
|
||||||
if len(parts) >= 2:
|
_logger.warning(f"Failed to delete snippet {filepath}: {e}")
|
||||||
snippet_ref = parts[1] # e.g. "snippets:snippets/101-user-data.yaml"
|
|
||||||
storage, filepath = snippet_ref.split(":", 1)
|
|
||||||
_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")
|
_logger.info(f"VM {vmid} destroyed successfully")
|
||||||
|
|
||||||
@@ -537,6 +831,39 @@ class ProxmoxVMProvisionMixin:
|
|||||||
_logger.exception(f"Failed to destroy VM {vmid}: {e}")
|
_logger.exception(f"Failed to destroy VM {vmid}: {e}")
|
||||||
raise
|
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(
|
def get_vm_status(
|
||||||
self,
|
self,
|
||||||
vmid: str,
|
vmid: str,
|
||||||
@@ -548,6 +875,11 @@ class ProxmoxVMProvisionMixin:
|
|||||||
"""
|
"""
|
||||||
Get the runtime status of a virtual machine.
|
Get the runtime status of a virtual machine.
|
||||||
|
|
||||||
|
The status is what ``GET /nodes/{node}/qemu/{vmid}/status/current`` says:
|
||||||
|
``running``, ``stopped``, or ``paused`` where its ``qmpstatus`` is paused or
|
||||||
|
suspended (``qemu_status``, as ``get_vms()`` lists it). Only a running VM's
|
||||||
|
guest agent is asked for an address (NAPALM/napalm-proxmox#72).
|
||||||
|
|
||||||
Optionally waits for the guest-agent to report an IP address on the
|
Optionally waits for the guest-agent to report an IP address on the
|
||||||
management NIC (net0), useful after provisioning.
|
management NIC (net0), useful after provisioning.
|
||||||
|
|
||||||
@@ -559,112 +891,95 @@ class ProxmoxVMProvisionMixin:
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
||||||
(ip_address, hostname, mac_address only if VM is running and has network info)
|
(ip_address, hostname, mac_address only if VM is running and has network
|
||||||
|
info); {"status": "unknown"} when Proxmox gives no status for the vmid.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
RuntimeError: VM doesn't exist or wait_for_ip times out
|
RuntimeError: wait_for_ip times out, or the VM is not running while
|
||||||
|
waiting (a stopped or paused VM reports no address)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
vmid_int = int(vmid)
|
vm = self._node_api().qemu(int(vmid))
|
||||||
_logger.debug(f"Getting status for VM {vmid}")
|
_logger.debug(f"Getting status for VM {vmid}")
|
||||||
|
# The VM must exist / be readable before we start polling.
|
||||||
# VM must exist / be readable before we start polling.
|
status = self._qemu_current_status(vm, vmid)
|
||||||
try:
|
if status is None:
|
||||||
self._node_api().qemu(vmid_int).config.get()
|
|
||||||
except Exception:
|
|
||||||
# VM may not exist yet or config not readable
|
|
||||||
return {"status": "unknown"}
|
return {"status": "unknown"}
|
||||||
|
|
||||||
# Polling loop
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
while True:
|
while True:
|
||||||
elapsed = time.time() - start_time
|
if status != "running":
|
||||||
if wait_for_ip and elapsed > timeout:
|
if wait_for_ip:
|
||||||
|
raise RuntimeError(f"VM {vmid} is {status}: it reports no IP address")
|
||||||
|
return {"status": status}
|
||||||
|
if wait_for_ip and time.time() - start_time > timeout:
|
||||||
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
||||||
|
address = self._guest_agent_address(vm, vmid)
|
||||||
try:
|
if address is not None:
|
||||||
# Query guest-agent network interfaces. Proxmox's REST path is
|
return {"status": "running", **address}
|
||||||
# "network-get-interfaces" (hyphens) — it must be passed as a
|
|
||||||
# resource id via __call__, not dotted attribute access (which
|
|
||||||
# would silently build a non-existent "network_get_interfaces"
|
|
||||||
# path and 404 on every poll).
|
|
||||||
agent_info = (
|
|
||||||
self._node_api().qemu(vmid_int).agent("network-get-interfaces").get()
|
|
||||||
)
|
|
||||||
interfaces = (agent_info or {}).get("result", [])
|
|
||||||
|
|
||||||
# The guest agent does not report interfaces in a fixed order —
|
|
||||||
# "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}")
|
|
||||||
|
|
||||||
if not wait_for_ip:
|
if not wait_for_ip:
|
||||||
# Return immediate status without IP
|
|
||||||
return {"status": "running"}
|
return {"status": "running"}
|
||||||
|
|
||||||
# Wait before next poll
|
|
||||||
time.sleep(poll_interval)
|
time.sleep(poll_interval)
|
||||||
|
# A status that does not read this round keeps the last one.
|
||||||
|
status = self._qemu_current_status(vm, vmid) or status
|
||||||
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
||||||
raise RuntimeError(f"Failed to get VM {vmid} status: {e}")
|
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.
|
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
||||||
|
|
||||||
Excludes physical NICs, bonds, and other non-bridge interface types —
|
Excludes physical NICs, bonds, and other non-bridge interface types —
|
||||||
those are never valid ``NICConfigDict.bridge`` values on Proxmox.
|
those are never valid ``NICConfigDict.bridge`` values on Proxmox.
|
||||||
"""
|
"""
|
||||||
targets: List[NetworkTargetDict] = []
|
targets = bridge_targets(self._get_node_network())
|
||||||
|
|
||||||
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})
|
|
||||||
|
|
||||||
for vnet in self._get_sdn_vnets():
|
for vnet in self._get_sdn_vnets():
|
||||||
name = vnet.get("vnet", "")
|
target = vnet_target(vnet)
|
||||||
if not name:
|
if target is not None:
|
||||||
continue
|
targets.append(target)
|
||||||
# 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,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
return targets
|
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]
|
[build-system]
|
||||||
requires = ["setuptools>=61", "wheel"]
|
requires = ["setuptools>=77"]
|
||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "napalm-proxmox"
|
name = "napalm-proxmox"
|
||||||
version = "0.1.0"
|
version = "0.19.0"
|
||||||
description = "NAPALM driver for Proxmox VE (classic Linux networking, SDN, OVS)"
|
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = { text = "Apache-2.0" }
|
license = "Apache-2.0"
|
||||||
authors = [{ name = "Christian Manivong" }]
|
authors = [{ name = "Christian Manivong" }]
|
||||||
keywords = ["napalm", "proxmox", "network", "sdn", "ovs", "automation"]
|
keywords = ["napalm", "proxmox", "network", "sdn", "ovs", "automation"]
|
||||||
classifiers = [
|
classifiers = [
|
||||||
"Development Status :: 3 - Alpha",
|
"Development Status :: 3 - Alpha",
|
||||||
"Intended Audience :: Developers",
|
"Intended Audience :: Developers",
|
||||||
"Intended Audience :: System Administrators",
|
"Intended Audience :: System Administrators",
|
||||||
"License :: OSI Approved :: Apache Software License",
|
|
||||||
"Programming Language :: Python :: 3",
|
"Programming Language :: Python :: 3",
|
||||||
"Programming Language :: Python :: 3.9",
|
|
||||||
"Programming Language :: Python :: 3.10",
|
|
||||||
"Programming Language :: Python :: 3.11",
|
|
||||||
"Programming Language :: Python :: 3.12",
|
"Programming Language :: Python :: 3.12",
|
||||||
"Topic :: System :: Networking",
|
"Topic :: System :: Networking",
|
||||||
]
|
]
|
||||||
requires-python = ">=3.9"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"napalm>=5.0.0",
|
"napalm>=5.0.0",
|
||||||
"napalm_device_types>=2.0.0",
|
"napalm_device_types>=4.53.0", # CpuMicrocodeMixin; virtualization in the hardening
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for SSH fallback (driver.py)
|
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||||
"proxmoxer>=2.0.0",
|
"proxmoxer>=2.0.0",
|
||||||
"netaddr>=0.9.0",
|
"netaddr>=0.9.0",
|
||||||
"requests>=2.31.0",
|
"requests>=2.31.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
dev = [
|
dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6"]
|
||||||
"pytest>=7.4",
|
|
||||||
"pytest-cov>=4.1",
|
|
||||||
"pytest-mock>=3.12",
|
|
||||||
"responses>=0.24",
|
|
||||||
"ruff>=0.1",
|
|
||||||
"mypy>=1.7",
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.entry-points."napalm.drivers"]
|
[project.entry-points."napalm.drivers"]
|
||||||
proxmox = "napalm_proxmox:ProxmoxDriver"
|
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]
|
[tool.setuptools.packages.find]
|
||||||
where = ["."]
|
where = ["."]
|
||||||
include = ["napalm_proxmox*"]
|
include = ["napalm_proxmox*"]
|
||||||
|
|
||||||
|
[tool.setuptools.package-data]
|
||||||
|
napalm_proxmox = ["py.typed"]
|
||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
line-length = 100
|
line-length = 100
|
||||||
target-version = "py39"
|
target-version = "py312"
|
||||||
|
|
||||||
[tool.ruff.lint]
|
[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]
|
[tool.pytest.ini_options]
|
||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
addopts = "--cov=napalm_proxmox --cov-report=term-missing"
|
|
||||||
|
|
||||||
[tool.mypy]
|
[tool.coverage.run]
|
||||||
python_version = "3.9"
|
source = ["napalm_proxmox"]
|
||||||
warn_return_any = true
|
|
||||||
warn_unused_configs = true
|
[tool.coverage.report]
|
||||||
|
fail_under = 68
|
||||||
+39
-10
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Sample API payloads
|
# Sample API payloads
|
||||||
@@ -96,8 +96,6 @@ SDN_SUBNETS_VNET2: list = []
|
|||||||
# driver bug rather than bad test data.
|
# driver bug rather than bad test data.
|
||||||
DNS_INFO = {"search": "example.com", "dns1": "8.8.8.8"}
|
DNS_INFO = {"search": "example.com", "dns1": "8.8.8.8"}
|
||||||
|
|
||||||
NTP_INFO = {"server": "pool.ntp.org,time.cloudflare.com"}
|
|
||||||
|
|
||||||
NODE_NETSTAT = [
|
NODE_NETSTAT = [
|
||||||
{
|
{
|
||||||
"dev": "eth0",
|
"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
|
# Driver fixture
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def _build_mock_api(
|
def _build_mock_api(
|
||||||
nodes=None,
|
nodes=None,
|
||||||
node_status=None,
|
node_status=None,
|
||||||
@@ -133,11 +162,10 @@ def _build_mock_api(
|
|||||||
sdn_vnets=None,
|
sdn_vnets=None,
|
||||||
sdn_subnets=None,
|
sdn_subnets=None,
|
||||||
dns=None,
|
dns=None,
|
||||||
ntp=None,
|
|
||||||
netstat=None,
|
netstat=None,
|
||||||
pve_users=None,
|
pve_users=None,
|
||||||
exec_return="",
|
|
||||||
sensors=None,
|
sensors=None,
|
||||||
|
cluster_status=None,
|
||||||
):
|
):
|
||||||
"""Build a MagicMock ProxmoxAPI with pre-configured return values."""
|
"""Build a MagicMock ProxmoxAPI with pre-configured return values."""
|
||||||
api = MagicMock()
|
api = MagicMock()
|
||||||
@@ -155,9 +183,7 @@ def _build_mock_api(
|
|||||||
node_res.status.get.return_value = node_status or NODE_STATUS
|
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.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.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.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.hardware.sensors.get.return_value = sensors or []
|
||||||
node_res.time.get.return_value = {}
|
node_res.time.get.return_value = {}
|
||||||
node_res.subscription.get.return_value = {}
|
node_res.subscription.get.return_value = {}
|
||||||
@@ -165,6 +191,7 @@ def _build_mock_api(
|
|||||||
# SDN
|
# SDN
|
||||||
cluster = MagicMock()
|
cluster = MagicMock()
|
||||||
api.cluster = cluster
|
api.cluster = cluster
|
||||||
|
cluster.status.get.return_value = cluster_status or []
|
||||||
cluster.sdn.zones.get.return_value = sdn_zones or SDN_ZONES
|
cluster.sdn.zones.get.return_value = sdn_zones or SDN_ZONES
|
||||||
cluster.sdn.vnets.get.return_value = sdn_vnets or SDN_VNETS
|
cluster.sdn.vnets.get.return_value = sdn_vnets or SDN_VNETS
|
||||||
|
|
||||||
@@ -201,12 +228,13 @@ def driver():
|
|||||||
mock_api = _build_mock_api()
|
mock_api = _build_mock_api()
|
||||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||||
drv.open()
|
drv.open()
|
||||||
|
drv._node_ssh = MagicMock(return_value=NodeShell())
|
||||||
return drv
|
return drv
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def driver_with_exec(request):
|
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", "")
|
exec_output = getattr(request, "param", "")
|
||||||
drv = ProxmoxDriver(
|
drv = ProxmoxDriver(
|
||||||
hostname="pve1.example.com",
|
hostname="pve1.example.com",
|
||||||
@@ -214,7 +242,8 @@ def driver_with_exec(request):
|
|||||||
password="secret",
|
password="secret",
|
||||||
optional_args={"verify_ssl": False},
|
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):
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||||
drv.open()
|
drv.open()
|
||||||
|
drv._node_ssh = MagicMock(return_value=NodeShell(exec_output))
|
||||||
return drv
|
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,255 @@
|
|||||||
|
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
|
||||||
|
|
||||||
|
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
|
||||||
|
driver set: ``{name, issuer, valid_from, valid_to, in_use_by}`` with Unix
|
||||||
|
timestamps, so netOrk's expiry warnings apply to a Proxmox node as to any device.
|
||||||
|
The source is ``GET /nodes/{node}/certificates/info`` (PBS:
|
||||||
|
``/nodes/localhost/certificates/info``), and one more call, the node's
|
||||||
|
``config``, tells whether ACME renews the certificate the proxy serves.
|
||||||
|
|
||||||
|
The responses are shaped as Proxmox VE 8 and PBS 3 answer (``pvenode cert info``,
|
||||||
|
``proxmox-backup-manager cert info``), the PEM left out.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from proxmoxer.core import ResourceException
|
||||||
|
|
||||||
|
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
from tests.pbs_fake import FakePbsApi
|
||||||
|
|
||||||
|
ROOT_CA = {
|
||||||
|
"filename": "pve-root-ca.pem",
|
||||||
|
"fingerprint": "5E:41:...:0A",
|
||||||
|
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
|
||||||
|
"notafter": 2017526400,
|
||||||
|
"notbefore": 1702166400,
|
||||||
|
"public-key-bits": 2048,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": [],
|
||||||
|
"subject": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
|
||||||
|
}
|
||||||
|
PVE_SSL = {
|
||||||
|
"filename": "pve-ssl.pem",
|
||||||
|
"fingerprint": "A1:B2:...:C3",
|
||||||
|
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
|
||||||
|
"notafter": 1765238400,
|
||||||
|
"notbefore": 1702166400,
|
||||||
|
"public-key-bits": 2048,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": [
|
||||||
|
"127.0.0.1",
|
||||||
|
"0000:0000:0000:0000:0000:0000:0000:0001",
|
||||||
|
"localhost",
|
||||||
|
"pve1",
|
||||||
|
"pve1.example.com",
|
||||||
|
],
|
||||||
|
"subject": "/OU=PVE Cluster Node/O=Proxmox Virtual Environment/CN=pve1.example.com",
|
||||||
|
}
|
||||||
|
PVEPROXY_SSL = {
|
||||||
|
"filename": "pveproxy-ssl.pem",
|
||||||
|
"fingerprint": "D4:E5:...:F6",
|
||||||
|
"issuer": "/C=US/O=Let's Encrypt/CN=R11",
|
||||||
|
"notafter": 1771977600,
|
||||||
|
"notbefore": 1764201600,
|
||||||
|
"public-key-bits": 2048,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": ["pve1.example.com"],
|
||||||
|
"subject": "/CN=pve1.example.com",
|
||||||
|
}
|
||||||
|
ACME_CONFIG = {
|
||||||
|
"acme": "account=default",
|
||||||
|
"acmedomain0": "domain=pve1.example.com,plugin=cloudflare",
|
||||||
|
"digest": "4f0c...",
|
||||||
|
}
|
||||||
|
|
||||||
|
PROXY_PEM = {
|
||||||
|
"filename": "proxy.pem",
|
||||||
|
"fingerprint": "0A:1B:...:2C",
|
||||||
|
"issuer": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
|
||||||
|
"notafter": 2017526400,
|
||||||
|
"notbefore": 1702166400,
|
||||||
|
"public-key-bits": 4096,
|
||||||
|
"public-key-type": "rsaEncryption",
|
||||||
|
"san": ["IP Address:127.0.0.1", "DNS:localhost", "DNS:pbs1", "DNS:pbs1.example.com"],
|
||||||
|
"subject": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _pve(info: Any, config: Any = None) -> tuple[ProxmoxDriver, Any]:
|
||||||
|
driver = ProxmoxDriver(
|
||||||
|
"pve1.example.com", "root", "secret", optional_args={"verify_ssl": False}
|
||||||
|
)
|
||||||
|
api = _build_mock_api()
|
||||||
|
node = api.nodes.return_value
|
||||||
|
if isinstance(info, Exception):
|
||||||
|
node.certificates.info.get.side_effect = info
|
||||||
|
else:
|
||||||
|
node.certificates.info.get.return_value = info
|
||||||
|
if isinstance(config, Exception):
|
||||||
|
node.config.get.side_effect = config
|
||||||
|
else:
|
||||||
|
node.config.get.return_value = config or {}
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||||
|
driver.open()
|
||||||
|
return driver, api
|
||||||
|
|
||||||
|
|
||||||
|
def _pbs(**responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi]:
|
||||||
|
api = FakePbsApi(**responses)
|
||||||
|
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
|
||||||
|
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
|
||||||
|
driver.open()
|
||||||
|
return driver, api
|
||||||
|
|
||||||
|
|
||||||
|
# -- Proxmox VE -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_certificate_of_the_node_in_the_contract_shape() -> None:
|
||||||
|
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL])
|
||||||
|
|
||||||
|
certs = driver.get_certificates()
|
||||||
|
|
||||||
|
api.nodes.assert_any_call("pve1")
|
||||||
|
assert certs == [
|
||||||
|
{
|
||||||
|
"name": "pve-root-ca.pem",
|
||||||
|
"issuer": "Proxmox Virtual Environment",
|
||||||
|
"valid_from": 1702166400,
|
||||||
|
"valid_to": 2017526400,
|
||||||
|
"in_use_by": 0,
|
||||||
|
"subject": "Proxmox Virtual Environment",
|
||||||
|
"fingerprint": "5E:41:...:0A",
|
||||||
|
"acme": False,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pve-ssl.pem",
|
||||||
|
"issuer": "Proxmox Virtual Environment",
|
||||||
|
"valid_from": 1702166400,
|
||||||
|
"valid_to": 1765238400,
|
||||||
|
"in_use_by": 0,
|
||||||
|
"subject": "pve1.example.com",
|
||||||
|
"fingerprint": "A1:B2:...:C3",
|
||||||
|
"acme": False,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pveproxy-ssl.pem",
|
||||||
|
"issuer": "R11",
|
||||||
|
"valid_from": 1764201600,
|
||||||
|
"valid_to": 1771977600,
|
||||||
|
"in_use_by": 1,
|
||||||
|
"subject": "pve1.example.com",
|
||||||
|
"fingerprint": "D4:E5:...:F6",
|
||||||
|
"acme": False,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_timestamps_are_integers() -> None:
|
||||||
|
driver, _ = _pve([{**PVE_SSL, "notafter": "1765238400", "notbefore": None}])
|
||||||
|
|
||||||
|
(cert,) = driver.get_certificates()
|
||||||
|
|
||||||
|
assert cert["valid_to"] == 1765238400
|
||||||
|
assert cert["valid_from"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_a_custom_certificate_pveproxy_serves_pve_ssl() -> None:
|
||||||
|
driver, _ = _pve([ROOT_CA, PVE_SSL])
|
||||||
|
|
||||||
|
in_use = {c["name"]: c["in_use_by"] for c in driver.get_certificates()}
|
||||||
|
|
||||||
|
assert in_use == {"pve-root-ca.pem": 0, "pve-ssl.pem": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_renews_the_certificate_pveproxy_serves() -> None:
|
||||||
|
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL], ACME_CONFIG)
|
||||||
|
|
||||||
|
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
|
||||||
|
|
||||||
|
assert acme == {"pve-root-ca.pem": False, "pve-ssl.pem": False, "pveproxy-ssl.pem": True}
|
||||||
|
# One call more than the certificates: the node's config.
|
||||||
|
api.nodes.return_value.config.get.assert_called_once_with()
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_in_its_older_form_names_the_domains_in_acme() -> None:
|
||||||
|
config = {"acme": "account=default,domains=pve1.example.com"}
|
||||||
|
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], config)
|
||||||
|
|
||||||
|
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
|
||||||
|
|
||||||
|
assert acme == {"pve-ssl.pem": False, "pveproxy-ssl.pem": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_acme_account_without_domains_renews_nothing() -> None:
|
||||||
|
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], {"acme": "account=default"})
|
||||||
|
|
||||||
|
assert not any(c["acme"] for c in driver.get_certificates())
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_never_renews_pve_ssl() -> None:
|
||||||
|
# Without pveproxy-ssl.pem there is no ACME certificate yet, even with domains set.
|
||||||
|
driver, _ = _pve([ROOT_CA, PVE_SSL], ACME_CONFIG)
|
||||||
|
|
||||||
|
assert not any(c["acme"] for c in driver.get_certificates())
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unreadable_config_reads_as_no_acme() -> None:
|
||||||
|
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], ResourceException(403, "Forbidden", "no Sys.Audit"))
|
||||||
|
|
||||||
|
certs = driver.get_certificates()
|
||||||
|
|
||||||
|
assert [c["name"] for c in certs] == ["pve-ssl.pem", "pveproxy-ssl.pem"]
|
||||||
|
assert not any(c["acme"] for c in certs)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreadable_certificates_are_none_rather_than_a_failed_poll() -> None:
|
||||||
|
driver, api = _pve(ResourceException(403, "Forbidden", "no Sys.Audit"))
|
||||||
|
|
||||||
|
assert driver.get_certificates() == []
|
||||||
|
api.nodes.return_value.config.get.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
# -- Proxmox Backup Server ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_localhost() -> None:
|
||||||
|
driver, api = _pbs(
|
||||||
|
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": {}}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert driver.get_certificates() == [
|
||||||
|
{
|
||||||
|
"name": "proxy.pem",
|
||||||
|
"issuer": "pbs1.example.com",
|
||||||
|
"valid_from": 1702166400,
|
||||||
|
"valid_to": 2017526400,
|
||||||
|
"in_use_by": 1,
|
||||||
|
"subject": "pbs1.example.com",
|
||||||
|
"fingerprint": "0A:1B:...:2C",
|
||||||
|
"acme": False,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
assert ("GET", "nodes/localhost/certificates/info", {}) in api.calls
|
||||||
|
|
||||||
|
|
||||||
|
def test_acme_renews_the_backup_servers_proxy_certificate() -> None:
|
||||||
|
config = {"acme": "account=default", "acmedomain0": "domain=pbs1.example.com"}
|
||||||
|
driver, _ = _pbs(
|
||||||
|
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": config}
|
||||||
|
)
|
||||||
|
|
||||||
|
(cert,) = driver.get_certificates()
|
||||||
|
|
||||||
|
assert cert["acme"] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
|
||||||
|
def test_both_drivers_have_it(cls: type) -> None:
|
||||||
|
assert callable(getattr(cls, "get_certificates", None))
|
||||||
@@ -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,577 @@
|
|||||||
|
"""get_clusters(): the cluster a node belongs to, its nodes, storages and networks.
|
||||||
|
|
||||||
|
A Proxmox node can read its whole cluster: ``/cluster/status`` names the members
|
||||||
|
and the quorum, ``/cluster/resources`` their capacity and every storage per
|
||||||
|
node, ``/nodes/{node}/status`` the CPU, ``/nodes/{node}/network`` the bridges.
|
||||||
|
netOrk uses it to tell where a new VM may go (NetOrk/netork#484, #1822). The
|
||||||
|
payloads below follow PVE 8.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
|
||||||
|
GIB = 1024**3
|
||||||
|
|
||||||
|
CLUSTER_STATUS = [
|
||||||
|
{"type": "cluster", "id": "cluster", "name": "lab", "nodes": 3, "quorate": 1, "version": 7},
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"id": "node/pve1",
|
||||||
|
"name": "pve1",
|
||||||
|
"nodeid": 1,
|
||||||
|
"ip": "10.0.0.1",
|
||||||
|
"local": 1,
|
||||||
|
"online": 1,
|
||||||
|
"level": "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"id": "node/pve2",
|
||||||
|
"name": "pve2",
|
||||||
|
"nodeid": 2,
|
||||||
|
"ip": "10.0.0.2",
|
||||||
|
"local": 0,
|
||||||
|
"online": 1,
|
||||||
|
"level": "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"id": "node/pve3",
|
||||||
|
"name": "pve3",
|
||||||
|
"nodeid": 3,
|
||||||
|
"ip": "10.0.0.3",
|
||||||
|
"local": 0,
|
||||||
|
"online": 0,
|
||||||
|
"level": "",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _node_row(node: str, maxcpu: int, cpu: float, maxmem: int, mem: int) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": f"node/{node}",
|
||||||
|
"type": "node",
|
||||||
|
"node": node,
|
||||||
|
"status": "online",
|
||||||
|
"cpu": cpu,
|
||||||
|
"maxcpu": maxcpu,
|
||||||
|
"mem": mem,
|
||||||
|
"maxmem": maxmem,
|
||||||
|
"disk": 5 * GIB,
|
||||||
|
"maxdisk": 100 * GIB,
|
||||||
|
"uptime": 86400,
|
||||||
|
"level": "",
|
||||||
|
"cgroup-mode": 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _storage_row(
|
||||||
|
node: str,
|
||||||
|
storage: str,
|
||||||
|
plugintype: str,
|
||||||
|
shared: int,
|
||||||
|
content: str,
|
||||||
|
maxdisk: int,
|
||||||
|
disk: int,
|
||||||
|
status: str = "available",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": f"storage/{node}/{storage}",
|
||||||
|
"type": "storage",
|
||||||
|
"node": node,
|
||||||
|
"storage": storage,
|
||||||
|
"plugintype": plugintype,
|
||||||
|
"shared": shared,
|
||||||
|
"content": content,
|
||||||
|
"maxdisk": maxdisk,
|
||||||
|
"disk": disk,
|
||||||
|
"status": status,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
CLUSTER_RESOURCES = [
|
||||||
|
_node_row("pve1", 32, 0.25, 128 * GIB, 64 * GIB),
|
||||||
|
_node_row("pve2", 16, 0.5, 64 * GIB, 16 * GIB),
|
||||||
|
# An offline node keeps a row, with what PVE last knew of it.
|
||||||
|
{"id": "node/pve3", "type": "node", "node": "pve3", "status": "offline", "maxcpu": 8},
|
||||||
|
_storage_row("pve1", "local-lvm", "lvmthin", 0, "rootdir,images", 400 * GIB, 100 * GIB),
|
||||||
|
_storage_row("pve2", "local-lvm", "lvmthin", 0, "rootdir,images", 200 * GIB, 50 * GIB),
|
||||||
|
_storage_row("pve3", "local-lvm", "lvmthin", 0, "rootdir,images", 0, 0, status="unknown"),
|
||||||
|
_storage_row("pve1", "ceph-vm", "rbd", 1, "images,rootdir", 3000 * GIB, 1000 * GIB),
|
||||||
|
_storage_row("pve2", "ceph-vm", "rbd", 1, "images,rootdir", 3000 * GIB, 1000 * GIB),
|
||||||
|
_storage_row("pve1", "nfs-iso", "nfs", 1, "iso,vztmpl,snippets", 1000 * GIB, 10 * GIB),
|
||||||
|
# The NFS server cannot be reached from pve2.
|
||||||
|
_storage_row("pve2", "nfs-iso", "nfs", 1, "iso,vztmpl,snippets", 0, 0, status="unavailable"),
|
||||||
|
{"id": "qemu/100", "type": "qemu", "vmid": 100, "node": "pve1", "status": "running"},
|
||||||
|
{"id": "sdn/pve1/localnetwork", "type": "sdn", "sdn": "localnetwork", "node": "pve1"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _cpuinfo(cores: int, sockets: int, model: str, flags: str) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"cpuinfo": {
|
||||||
|
"cores": cores,
|
||||||
|
"sockets": sockets,
|
||||||
|
"cpus": cores * sockets * 2,
|
||||||
|
"model": model,
|
||||||
|
"flags": flags,
|
||||||
|
"mhz": "2100.000",
|
||||||
|
"hvm": "1",
|
||||||
|
"user_hz": 100,
|
||||||
|
},
|
||||||
|
"memory": {"total": 128 * GIB, "used": 64 * GIB, "free": 64 * GIB},
|
||||||
|
"uptime": 86400,
|
||||||
|
"pveversion": "pve-manager/8.2.4/faa83925c9641325",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
NODE_STATUS = {
|
||||||
|
"pve1": _cpuinfo(8, 2, "Intel(R) Xeon(R) Silver 4110 CPU @ 2.10GHz", "fpu vme sse4_2 avx2"),
|
||||||
|
"pve2": _cpuinfo(8, 1, "AMD EPYC 7302P 16-Core Processor", "fpu vme sse4_2"),
|
||||||
|
}
|
||||||
|
|
||||||
|
NODE_NETWORK = {
|
||||||
|
"pve1": [
|
||||||
|
{"iface": "eno1", "type": "eth", "active": 1},
|
||||||
|
{
|
||||||
|
"iface": "vmbr0",
|
||||||
|
"type": "bridge",
|
||||||
|
"active": 1,
|
||||||
|
"bridge_ports": "eno1",
|
||||||
|
"bridge_vlan_aware": 1,
|
||||||
|
},
|
||||||
|
{"iface": "vmbr9", "type": "bridge", "active": 1, "bridge_ports": "none"},
|
||||||
|
],
|
||||||
|
"pve2": [
|
||||||
|
{"iface": "eno1", "type": "eth", "active": 1},
|
||||||
|
# Same name, but not VLAN aware on this node.
|
||||||
|
{"iface": "vmbr0", "type": "bridge", "active": 1, "bridge_ports": "eno1"},
|
||||||
|
{"iface": "vmbr1", "type": "OVSBridge", "active": 1, "ovs_ports": ""},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
SDN_ZONES = [
|
||||||
|
{"zone": "edge", "type": "vlan", "bridge": "vmbr0", "nodes": "pve2", "digest": "x"},
|
||||||
|
{"zone": "fabric", "type": "vxlan", "peers": "10.0.0.1,10.0.0.2", "digest": "x"},
|
||||||
|
]
|
||||||
|
|
||||||
|
SDN_VNETS = [
|
||||||
|
{"vnet": "dmz", "zone": "edge", "tag": 30, "type": "vnet", "digest": "x"},
|
||||||
|
{"vnet": "overlay", "zone": "fabric", "tag": 100000, "type": "vnet", "digest": "x"},
|
||||||
|
]
|
||||||
|
|
||||||
|
# /cluster/config/nodes: corosync's nodelist; corosync.conf keeps every value a string.
|
||||||
|
CONFIG_NODES = [
|
||||||
|
{"node": "pve1", "name": "pve1", "nodeid": "1", "quorum_votes": "1", "ring0_addr": "10.0.0.1"},
|
||||||
|
{"node": "pve2", "name": "pve2", "nodeid": "2", "quorum_votes": "1", "ring0_addr": "10.0.0.2"},
|
||||||
|
{"node": "pve3", "name": "pve3", "nodeid": "3", "quorum_votes": "2", "ring0_addr": "10.0.0.3"},
|
||||||
|
]
|
||||||
|
|
||||||
|
HA_MANAGER_STATUS = {
|
||||||
|
"manager_status": {
|
||||||
|
"master_node": "pve1",
|
||||||
|
"node_status": {"pve1": "online", "pve2": "maintenance", "pve3": "unknown"},
|
||||||
|
"service_status": {},
|
||||||
|
"timestamp": 1730000000,
|
||||||
|
},
|
||||||
|
"quorum": {"node": "pve1", "quorate": "1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _api(
|
||||||
|
cluster_status: list[dict[str, Any]] | None = None,
|
||||||
|
resources: list[dict[str, Any]] | None = None,
|
||||||
|
node_status: dict[str, Any] | None = None,
|
||||||
|
node_network: dict[str, Any] | None = None,
|
||||||
|
zones: list[dict[str, Any]] | None = None,
|
||||||
|
vnets: list[dict[str, Any]] | None = None,
|
||||||
|
ha: dict[str, Any] | Exception | None = None,
|
||||||
|
) -> MagicMock:
|
||||||
|
api = _build_mock_api(cluster_status=cluster_status or CLUSTER_STATUS)
|
||||||
|
statuses = NODE_STATUS if node_status is None else node_status
|
||||||
|
networks = NODE_NETWORK if node_network is None else node_network
|
||||||
|
nodes: dict[str, MagicMock] = {}
|
||||||
|
|
||||||
|
def node_res(name: str) -> MagicMock:
|
||||||
|
if name not in nodes:
|
||||||
|
res = MagicMock()
|
||||||
|
if name in statuses:
|
||||||
|
res.status.get.return_value = statuses[name]
|
||||||
|
else:
|
||||||
|
res.status.get.side_effect = ConnectionError(f"{name} unreachable")
|
||||||
|
res.network.get.return_value = networks.get(name, [])
|
||||||
|
nodes[name] = res
|
||||||
|
return nodes[name]
|
||||||
|
|
||||||
|
api.nodes.side_effect = node_res
|
||||||
|
api.nodes.return_value = None
|
||||||
|
api.cluster.resources.get.return_value = CLUSTER_RESOURCES if resources is None else resources
|
||||||
|
api.cluster.sdn.zones.get.return_value = SDN_ZONES if zones is None else zones
|
||||||
|
api.cluster.sdn.vnets.get.return_value = SDN_VNETS if vnets is None else vnets
|
||||||
|
manager = api.cluster.ha.status.manager_status.get
|
||||||
|
if isinstance(ha, Exception):
|
||||||
|
manager.side_effect = ha
|
||||||
|
else:
|
||||||
|
manager.return_value = HA_MANAGER_STATUS if ha is None else ha
|
||||||
|
# Read for get_clusters' votes, HA resources and backups; see test_cluster_ha_backups.
|
||||||
|
api.cluster.config.nodes.get.return_value = CONFIG_NODES
|
||||||
|
api.cluster.ha.resources.get.return_value = []
|
||||||
|
api.cluster.ha.status.current.get.return_value = []
|
||||||
|
api.cluster.ha.rules.get.return_value = []
|
||||||
|
api.cluster.backup.get.return_value = []
|
||||||
|
api.storage.get.return_value = []
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
def _driver(api: MagicMock, node: str = "pve1") -> ProxmoxDriver:
|
||||||
|
drv = ProxmoxDriver(
|
||||||
|
hostname=f"{node}.example.com",
|
||||||
|
username="root",
|
||||||
|
password="secret",
|
||||||
|
optional_args={"verify_ssl": False, "node": node},
|
||||||
|
)
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||||
|
drv.open()
|
||||||
|
return drv
|
||||||
|
|
||||||
|
|
||||||
|
def _cluster(**kwargs: Any) -> dict[str, Any]:
|
||||||
|
clusters = _driver(_api(**kwargs)).get_clusters()
|
||||||
|
assert len(clusters) == 1
|
||||||
|
return dict(clusters[0])
|
||||||
|
|
||||||
|
|
||||||
|
def _by_name(items: list[Any]) -> dict[str, Any]:
|
||||||
|
return {item["name"]: item for item in items}
|
||||||
|
|
||||||
|
|
||||||
|
class TestCluster:
|
||||||
|
def test_name_and_quorum(self):
|
||||||
|
cluster = _cluster()
|
||||||
|
assert cluster["id"] is None
|
||||||
|
assert cluster["name"] == "lab"
|
||||||
|
assert cluster["quorate"] is True
|
||||||
|
|
||||||
|
def test_lost_quorum(self):
|
||||||
|
status = [dict(CLUSTER_STATUS[0], quorate=0), *CLUSTER_STATUS[1:]]
|
||||||
|
assert _cluster(cluster_status=status)["quorate"] is False
|
||||||
|
|
||||||
|
def test_every_member_listed_in_cluster_order(self):
|
||||||
|
assert [n["name"] for n in _cluster()["nodes"]] == ["pve1", "pve2", "pve3"]
|
||||||
|
|
||||||
|
def test_pve_9_3_names_the_cluster_by_its_id(self):
|
||||||
|
"""``cluster-id``: a random identifier, kept when the cluster is renamed."""
|
||||||
|
status = [dict(CLUSTER_STATUS[0], **{"cluster-id": "a1b2c3d4e5"}), *CLUSTER_STATUS[1:]]
|
||||||
|
assert _cluster(cluster_status=status)["id"] == "a1b2c3d4e5"
|
||||||
|
|
||||||
|
|
||||||
|
class TestNodes:
|
||||||
|
def test_online_node(self):
|
||||||
|
pve1 = _by_name(_cluster()["nodes"])["pve1"]
|
||||||
|
assert pve1 == {
|
||||||
|
"name": "pve1",
|
||||||
|
"status": "online",
|
||||||
|
"local": True,
|
||||||
|
"maintenance": False,
|
||||||
|
"cpu_threads": 32,
|
||||||
|
"cpu_cores": 16,
|
||||||
|
"cpu_model": "Intel(R) Xeon(R) Silver 4110 CPU @ 2.10GHz",
|
||||||
|
"cpu_flags": ["fpu", "vme", "sse4_2", "avx2"],
|
||||||
|
"cpu_usage": 0.25,
|
||||||
|
"memory_total": 128 * GIB,
|
||||||
|
"memory_used": 64 * GIB,
|
||||||
|
"votes": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_other_member_is_not_local(self):
|
||||||
|
pve2 = _by_name(_cluster()["nodes"])["pve2"]
|
||||||
|
assert pve2["local"] is False
|
||||||
|
assert pve2["cpu_cores"] == 8
|
||||||
|
assert pve2["cpu_threads"] == 16
|
||||||
|
|
||||||
|
def test_offline_node_is_listed_without_capacity(self):
|
||||||
|
api = _api()
|
||||||
|
pve3 = _by_name(_driver(api).get_clusters()[0]["nodes"])["pve3"]
|
||||||
|
assert pve3["status"] == "offline"
|
||||||
|
assert pve3["local"] is False
|
||||||
|
for key in (
|
||||||
|
"cpu_threads",
|
||||||
|
"cpu_cores",
|
||||||
|
"cpu_model",
|
||||||
|
"cpu_flags",
|
||||||
|
"cpu_usage",
|
||||||
|
"memory_total",
|
||||||
|
"memory_used",
|
||||||
|
):
|
||||||
|
assert pve3[key] is None, key
|
||||||
|
# An offline node is not asked: the request would only time out.
|
||||||
|
assert all(call.args != ("pve3",) for call in api.nodes.call_args_list)
|
||||||
|
|
||||||
|
def test_local_falls_back_to_the_resolved_node(self):
|
||||||
|
status = [dict(s, local=0) if s["type"] == "node" else s for s in CLUSTER_STATUS]
|
||||||
|
nodes = _by_name(
|
||||||
|
_driver(_api(cluster_status=status), node="pve2").get_clusters()[0]["nodes"]
|
||||||
|
)
|
||||||
|
assert nodes["pve2"]["local"] is True
|
||||||
|
assert nodes["pve1"]["local"] is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestStandalone:
|
||||||
|
STATUS = [
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"id": "node/pve1",
|
||||||
|
"name": "pve1",
|
||||||
|
"nodeid": 0,
|
||||||
|
"ip": "10.0.0.1",
|
||||||
|
"local": 1,
|
||||||
|
"online": 1,
|
||||||
|
"level": "",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
RESOURCES = [
|
||||||
|
_node_row("pve1", 32, 0.25, 128 * GIB, 64 * GIB),
|
||||||
|
_storage_row("pve1", "local", "dir", 0, "iso,vztmpl,backup", 100 * GIB, 5 * GIB),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_a_cluster_of_one_without_name(self):
|
||||||
|
cluster = _cluster(cluster_status=self.STATUS, resources=self.RESOURCES, ha=RuntimeError())
|
||||||
|
assert cluster["id"] is None
|
||||||
|
assert cluster["name"] is None
|
||||||
|
assert cluster["quorate"] is None
|
||||||
|
[node] = cluster["nodes"]
|
||||||
|
assert node["name"] == "pve1"
|
||||||
|
assert node["status"] == "online"
|
||||||
|
assert node["local"] is True
|
||||||
|
assert node["cpu_cores"] == 16
|
||||||
|
assert node["memory_total"] == 128 * GIB
|
||||||
|
assert _by_name(cluster["storages"])["local"]["nodes"] == ["pve1"]
|
||||||
|
|
||||||
|
def test_pve_9_3_names_a_standalone_node_by_its_own_id(self):
|
||||||
|
status = [dict(self.STATUS[0], **{"cluster-id": "f6e5d4c3b2"})]
|
||||||
|
cluster = _cluster(cluster_status=status, resources=self.RESOURCES, ha=RuntimeError())
|
||||||
|
assert cluster["id"] == "f6e5d4c3b2"
|
||||||
|
assert cluster["name"] is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestStorages:
|
||||||
|
def test_local_storage_grouped_over_its_nodes(self):
|
||||||
|
lvm = _by_name(_cluster()["storages"])["local-lvm"]
|
||||||
|
assert lvm == {
|
||||||
|
"name": "local-lvm",
|
||||||
|
"type": "lvmthin",
|
||||||
|
"shared": False,
|
||||||
|
"content": ["rootdir", "images"],
|
||||||
|
# pve3 is offline: its storage is "unknown", not available.
|
||||||
|
"nodes": ["pve1", "pve2"],
|
||||||
|
# Separate disks on each node: their sizes add up.
|
||||||
|
"total": 600 * GIB,
|
||||||
|
"used": 150 * GIB,
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_shared_storage_counted_once(self):
|
||||||
|
ceph = _by_name(_cluster()["storages"])["ceph-vm"]
|
||||||
|
assert ceph["shared"] is True
|
||||||
|
assert ceph["type"] == "rbd"
|
||||||
|
assert ceph["nodes"] == ["pve1", "pve2"]
|
||||||
|
assert ceph["total"] == 3000 * GIB
|
||||||
|
assert ceph["used"] == 1000 * GIB
|
||||||
|
|
||||||
|
def test_storage_unavailable_on_a_node_leaves_it_out(self):
|
||||||
|
nfs = _by_name(_cluster()["storages"])["nfs-iso"]
|
||||||
|
assert nfs["nodes"] == ["pve1"]
|
||||||
|
assert nfs["content"] == ["iso", "vztmpl", "snippets"]
|
||||||
|
assert nfs["total"] == 1000 * GIB
|
||||||
|
|
||||||
|
def test_storage_available_nowhere_has_no_size(self):
|
||||||
|
resources = [
|
||||||
|
*CLUSTER_RESOURCES[:3],
|
||||||
|
_storage_row("pve1", "nas", "cifs", 1, "backup", 0, 0, status="unavailable"),
|
||||||
|
]
|
||||||
|
nas = _by_name(_cluster(resources=resources)["storages"])["nas"]
|
||||||
|
assert nas["nodes"] == []
|
||||||
|
assert nas["total"] is None
|
||||||
|
assert nas["used"] is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestNetworks:
|
||||||
|
def test_bridge_merged_across_nodes_vlan_aware_only_if_everywhere(self):
|
||||||
|
vmbr0 = _by_name(_cluster()["networks"])["vmbr0"]
|
||||||
|
assert vmbr0 == {
|
||||||
|
"name": "vmbr0",
|
||||||
|
"kind": "bridge",
|
||||||
|
"vlan_aware": False,
|
||||||
|
"nodes": ["pve1", "pve2"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_bridge_on_one_node(self):
|
||||||
|
networks = _by_name(_cluster()["networks"])
|
||||||
|
assert networks["vmbr9"]["nodes"] == ["pve1"]
|
||||||
|
assert networks["vmbr1"] == {
|
||||||
|
"name": "vmbr1",
|
||||||
|
"kind": "bridge",
|
||||||
|
"vlan_aware": True,
|
||||||
|
"nodes": ["pve2"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_vlan_aware_on_every_node(self):
|
||||||
|
network = {
|
||||||
|
n: [dict(i, bridge_vlan_aware=1) for i in NODE_NETWORK["pve1"]] for n in NODE_NETWORK
|
||||||
|
}
|
||||||
|
assert _by_name(_cluster(node_network=network)["networks"])["vmbr0"]["vlan_aware"] is True
|
||||||
|
|
||||||
|
def test_vnet_on_its_zones_nodes(self):
|
||||||
|
dmz = _by_name(_cluster()["networks"])["dmz"]
|
||||||
|
assert dmz == {
|
||||||
|
"name": "dmz",
|
||||||
|
"kind": "vnet",
|
||||||
|
"vlan_aware": False,
|
||||||
|
"fixed_vlan_tag": 30,
|
||||||
|
"nodes": ["pve2"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_vnet_of_a_zone_without_nodes_is_everywhere(self):
|
||||||
|
overlay = _by_name(_cluster()["networks"])["overlay"]
|
||||||
|
assert overlay["nodes"] == ["pve1", "pve2", "pve3"]
|
||||||
|
assert overlay["fixed_vlan_tag"] == 100000
|
||||||
|
|
||||||
|
def test_get_network_targets_unchanged_for_the_own_node(self):
|
||||||
|
targets = _by_name(_driver(_api()).get_network_targets())
|
||||||
|
assert targets["vmbr0"] == {
|
||||||
|
"name": "vmbr0",
|
||||||
|
"kind": "bridge",
|
||||||
|
"vlan_aware": True,
|
||||||
|
"uplinks": [["eno1"]],
|
||||||
|
}
|
||||||
|
assert targets["dmz"]["fixed_vlan_tag"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
class TestMaintenance:
|
||||||
|
def test_ha_reports_maintenance(self):
|
||||||
|
nodes = _by_name(_cluster()["nodes"])
|
||||||
|
assert nodes["pve1"]["maintenance"] is False
|
||||||
|
assert nodes["pve2"]["maintenance"] is True
|
||||||
|
|
||||||
|
def test_ha_unreadable_leaves_maintenance_unknown(self):
|
||||||
|
nodes = _cluster(ha=RuntimeError("403 Forbidden: Permission check failed"))["nodes"]
|
||||||
|
assert [n["maintenance"] for n in nodes] == [None, None, None]
|
||||||
|
|
||||||
|
def test_node_the_ha_manager_does_not_track_is_unknown(self):
|
||||||
|
ha = {"manager_status": {"node_status": {"pve1": "online"}}, "quorum": {}}
|
||||||
|
nodes = _by_name(_cluster(ha=ha)["nodes"])
|
||||||
|
assert nodes["pve1"]["maintenance"] is False
|
||||||
|
assert nodes["pve2"]["maintenance"] is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestReadFailures:
|
||||||
|
def test_cluster_resources_unreadable_raises(self):
|
||||||
|
api = _api()
|
||||||
|
api.cluster.resources.get.side_effect = ConnectionError("pveproxy down")
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
_driver(api).get_clusters()
|
||||||
|
|
||||||
|
def test_cluster_status_unreadable_raises(self):
|
||||||
|
api = _api()
|
||||||
|
drv = _driver(api)
|
||||||
|
api.cluster.status.get.side_effect = ConnectionError("pveproxy down")
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
drv.get_clusters()
|
||||||
|
|
||||||
|
def test_own_node_status_unreadable_raises(self):
|
||||||
|
status = {"pve2": NODE_STATUS["pve2"]}
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
_driver(_api(node_status=status)).get_clusters()
|
||||||
|
|
||||||
|
def test_other_node_status_unreadable_leaves_its_cpu_unknown(self):
|
||||||
|
status = {"pve1": NODE_STATUS["pve1"]}
|
||||||
|
pve2 = _by_name(_cluster(node_status=status)["nodes"])["pve2"]
|
||||||
|
assert pve2["status"] == "online"
|
||||||
|
assert pve2["cpu_cores"] is None
|
||||||
|
assert pve2["cpu_model"] is None
|
||||||
|
assert pve2["cpu_flags"] is None
|
||||||
|
# What /cluster/resources says still stands.
|
||||||
|
assert pve2["cpu_threads"] == 16
|
||||||
|
|
||||||
|
|
||||||
|
class TestCreateOnAnotherNode:
|
||||||
|
def test_other_node_raises_before_anything_is_created(self):
|
||||||
|
api = _api()
|
||||||
|
drv = _driver(api)
|
||||||
|
with pytest.raises(ValueError, match="pve2"):
|
||||||
|
drv.create_vm_from_cloud_init(
|
||||||
|
"vm1",
|
||||||
|
image_url="https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2",
|
||||||
|
cpu=2,
|
||||||
|
memory=2048,
|
||||||
|
nics=[{"bridge": "vmbr0"}],
|
||||||
|
cloud_init_config={},
|
||||||
|
node="pve2",
|
||||||
|
)
|
||||||
|
api.cluster.nextid.get.assert_not_called()
|
||||||
|
for res in [api.nodes(n) for n in ("pve1", "pve2")]:
|
||||||
|
assert not [c for c in res.mock_calls if "post" in c[0]]
|
||||||
|
|
||||||
|
|
||||||
|
# /storage: what a pbs storage writes to (napalm-device-types 4.25, #55). The password
|
||||||
|
# and the encryption key are never in this answer's use.
|
||||||
|
PBS_ROW = _storage_row("pve1", "pbs-01", "pbs", 1, "backup", 1000 * GIB, 30 * GIB)
|
||||||
|
STORAGE_CONFIG = [
|
||||||
|
{"storage": "local", "type": "dir", "path": "/var/lib/vz", "content": "iso,backup"},
|
||||||
|
{
|
||||||
|
"storage": "pbs-01",
|
||||||
|
"type": "pbs",
|
||||||
|
"server": "192.0.2.80",
|
||||||
|
"port": 8007,
|
||||||
|
"datastore": "backup",
|
||||||
|
"namespace": "lab",
|
||||||
|
"fingerprint": "aa:bb",
|
||||||
|
"username": "root@pam",
|
||||||
|
"content": "backup",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestBackupServerRef:
|
||||||
|
def _storages(self, config):
|
||||||
|
api = _api(resources=[*CLUSTER_RESOURCES, PBS_ROW])
|
||||||
|
if isinstance(config, Exception):
|
||||||
|
api.storage.get.side_effect = config
|
||||||
|
else:
|
||||||
|
api.storage.get.return_value = config
|
||||||
|
return _by_name(_driver(api).get_clusters()[0]["storages"])
|
||||||
|
|
||||||
|
def test_a_pbs_storage_names_its_server(self):
|
||||||
|
assert self._storages(STORAGE_CONFIG)["pbs-01"]["backup_server"] == {
|
||||||
|
"server": "192.0.2.80",
|
||||||
|
"port": 8007,
|
||||||
|
"datastore": "backup",
|
||||||
|
"namespace": "lab",
|
||||||
|
"fingerprint": "aa:bb",
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_what_it_does_not_set_is_none(self):
|
||||||
|
bare = [{"storage": "pbs-01", "type": "pbs", "server": "pbs.example.com", "datastore": "b"}]
|
||||||
|
assert self._storages(bare)["pbs-01"]["backup_server"] == {
|
||||||
|
"server": "pbs.example.com",
|
||||||
|
"port": None,
|
||||||
|
"datastore": "b",
|
||||||
|
"namespace": None,
|
||||||
|
"fingerprint": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_other_storages_carry_no_reference(self):
|
||||||
|
storages = self._storages(STORAGE_CONFIG)
|
||||||
|
assert "backup_server" not in storages["local-lvm"]
|
||||||
|
assert "backup_server" not in storages["ceph-vm"]
|
||||||
|
|
||||||
|
def test_an_unreadable_storage_config_says_none(self):
|
||||||
|
storages = self._storages(PermissionError("403 Forbidden"))
|
||||||
|
assert storages["pbs-01"]["backup_server"] is None
|
||||||
|
assert "backup_server" not in storages["local-lvm"]
|
||||||
@@ -2,12 +2,13 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
from unittest.mock import patch
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
|
import pytest
|
||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
|
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
from tests.conftest import _build_mock_api, NODES_LIST
|
from tests.conftest import _build_mock_api
|
||||||
|
|
||||||
|
|
||||||
class TestOpen:
|
class TestOpen:
|
||||||
@@ -76,3 +77,74 @@ class TestIsAlive:
|
|||||||
def test_not_alive_when_api_fails(self, driver):
|
def test_not_alive_when_api_fails(self, driver):
|
||||||
driver._api.version.get.side_effect = Exception("timeout")
|
driver._api.version.get.side_effect = Exception("timeout")
|
||||||
assert driver.is_alive() == {"is_alive": False}
|
assert driver.is_alive() == {"is_alive": False}
|
||||||
|
|
||||||
|
|
||||||
|
# A four-node cluster as GET /cluster/status reports it. The node the API
|
||||||
|
# session landed on carries local=1 — here the third one, so taking the first
|
||||||
|
# entry of /nodes (the old behaviour) picks the wrong host.
|
||||||
|
CLUSTER_NODES = [
|
||||||
|
{"type": "node", "name": "pve-01", "ip": "172.22.8.101", "local": 0},
|
||||||
|
{"type": "node", "name": "pve-02", "ip": "172.22.8.102", "local": 0},
|
||||||
|
{"type": "node", "name": "pve-dual", "ip": "172.22.8.120", "local": 1},
|
||||||
|
{"type": "node", "name": "pve-garden", "ip": "172.22.8.5", "local": 0},
|
||||||
|
]
|
||||||
|
CLUSTER_STATUS = [{"type": "cluster", "name": "home", "nodes": 4}, *CLUSTER_NODES]
|
||||||
|
CLUSTER_NODES_LIST = [{"node": n["name"], "status": "online"} for n in CLUSTER_NODES]
|
||||||
|
|
||||||
|
|
||||||
|
def _open_with(hostname, **api_kwargs):
|
||||||
|
drv = ProxmoxDriver(hostname, "root", "secret")
|
||||||
|
mock_api = _build_mock_api(**api_kwargs)
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||||
|
drv.open()
|
||||||
|
return drv
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
assert drv._node_name == "pve-dual"
|
||||||
|
|
||||||
|
def test_matches_by_ip_without_local_flag(self):
|
||||||
|
status = [{**n, "local": 0} for n in CLUSTER_STATUS if n["type"] == "node"]
|
||||||
|
drv = _open_with("172.22.8.102", nodes=CLUSTER_NODES_LIST, cluster_status=status)
|
||||||
|
assert drv._node_name == "pve-02"
|
||||||
|
|
||||||
|
def test_matches_by_name_without_local_flag(self):
|
||||||
|
status = [{**n, "local": 0} for n in CLUSTER_STATUS if n["type"] == "node"]
|
||||||
|
drv = _open_with("pve-garden", nodes=CLUSTER_NODES_LIST, cluster_status=status)
|
||||||
|
assert drv._node_name == "pve-garden"
|
||||||
|
|
||||||
|
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)
|
||||||
|
assert drv._node_name == "pve-01"
|
||||||
|
|
||||||
|
def test_single_node_without_cluster_status(self):
|
||||||
|
drv = _open_with("10.0.0.9", nodes=[{"node": "solo", "status": "online"}])
|
||||||
|
assert drv._node_name == "solo"
|
||||||
|
|
||||||
|
def test_ambiguous_cluster_refuses_to_guess(self):
|
||||||
|
status = [{**n, "local": 0} for n in CLUSTER_STATUS if n["type"] == "node"]
|
||||||
|
with pytest.raises(ConnectionException, match="node"):
|
||||||
|
_open_with("10.9.9.9", nodes=CLUSTER_NODES_LIST, cluster_status=status)
|
||||||
|
|
||||||
|
def test_api_error_fails_open_instead_of_guessing(self):
|
||||||
|
# A TLS failure used to be swallowed here: the IP became the node
|
||||||
|
# name, open() succeeded and every later call failed quietly.
|
||||||
|
drv = ProxmoxDriver("172.22.8.120", "root", "secret")
|
||||||
|
mock_api = _build_mock_api()
|
||||||
|
mock_api.cluster.status.get.side_effect = Exception("CERTIFICATE_VERIFY_FAILED")
|
||||||
|
mock_api.nodes.get.side_effect = Exception("CERTIFICATE_VERIFY_FAILED")
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||||
|
with pytest.raises(ConnectionException, match="CERTIFICATE_VERIFY_FAILED"):
|
||||||
|
drv.open()
|
||||||
|
|
||||||
|
def test_explicit_node_skips_lookup(self):
|
||||||
|
drv = ProxmoxDriver("172.22.8.120", "root", "secret", optional_args={"node": "pve-dual"})
|
||||||
|
mock_api = _build_mock_api()
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=mock_api):
|
||||||
|
drv.open()
|
||||||
|
assert drv._node_name == "pve-dual"
|
||||||
|
mock_api.cluster.status.get.assert_not_called()
|
||||||
|
mock_api.nodes.get.assert_not_called()
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""When the credential the driver logs in with stops working (NetOrk/netork#2728).
|
||||||
|
|
||||||
|
PVE 9.3's datacenter ``token-policy`` can require an expiry on every API token;
|
||||||
|
the platform keeps one on every token and account anyway. A token is read with
|
||||||
|
``GET /access/users/{userid}/token/{tokenid}``; a token without an ``expire``
|
||||||
|
of its own expires with its user (``default: same as user``), read with
|
||||||
|
``GET /access/users/{userid}``, which is also where a password's account says
|
||||||
|
when it expires. ``0`` is never.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from proxmoxer.core import ResourceException
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
|
||||||
|
|
||||||
|
def _driver(**optional_args: Any) -> tuple[ProxmoxDriver, MagicMock]:
|
||||||
|
password = "" if optional_args else "secret"
|
||||||
|
drv = ProxmoxDriver("pve1", "netork", password, optional_args=optional_args)
|
||||||
|
api = _build_mock_api()
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||||
|
drv.open()
|
||||||
|
return drv, api
|
||||||
|
|
||||||
|
|
||||||
|
def _token_driver(token_name: str = "netork@pve!poll") -> tuple[ProxmoxDriver, MagicMock]:
|
||||||
|
return _driver(token_name=token_name, token_value="s3cret", realm="pve")
|
||||||
|
|
||||||
|
|
||||||
|
def _forbidden() -> ResourceException:
|
||||||
|
return ResourceException(403, "Forbidden", "Permission check failed (/access, User.Modify)")
|
||||||
|
|
||||||
|
|
||||||
|
class TestApiToken:
|
||||||
|
def test_the_tokens_own_expiry(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {
|
||||||
|
"expire": 1767225600,
|
||||||
|
"privsep": 1,
|
||||||
|
}
|
||||||
|
assert drv.get_credential_expiry() == {
|
||||||
|
"kind": "api-token",
|
||||||
|
"name": "netork@pve!poll",
|
||||||
|
"expires": 1767225600,
|
||||||
|
}
|
||||||
|
api.access.users.assert_called_with("netork@pve")
|
||||||
|
api.access.users.return_value.token.assert_called_once_with("poll")
|
||||||
|
|
||||||
|
def test_zero_never_expires(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||||
|
assert drv.get_credential_expiry()["expires"] is None
|
||||||
|
api.access.users.return_value.get.assert_not_called()
|
||||||
|
|
||||||
|
def test_a_token_without_expiry_expires_with_its_user(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {"privsep": 1}
|
||||||
|
api.access.users.return_value.get.return_value = {
|
||||||
|
"userid": "netork@pve",
|
||||||
|
"expire": 1798761600,
|
||||||
|
}
|
||||||
|
assert drv.get_credential_expiry()["expires"] == 1798761600
|
||||||
|
|
||||||
|
def test_a_token_name_without_user_is_the_login_users(self):
|
||||||
|
drv, api = _token_driver(token_name="poll")
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||||
|
assert drv.get_credential_expiry()["name"] == "netork@pve!poll"
|
||||||
|
api.access.users.assert_called_with("netork@pve")
|
||||||
|
|
||||||
|
def test_a_refused_read_is_a_permission_error(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError, match="User.Modify"):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
def test_a_refused_read_of_the_user_is_a_permission_error(self):
|
||||||
|
drv, api = _token_driver()
|
||||||
|
api.access.users.return_value.token.return_value.get.return_value = {}
|
||||||
|
api.access.users.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
|
||||||
|
class TestAccount:
|
||||||
|
def test_a_password_login_reads_its_account(self):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.return_value = {
|
||||||
|
"userid": "netork@pam",
|
||||||
|
"expire": 1767225600,
|
||||||
|
}
|
||||||
|
assert drv.get_credential_expiry() == {
|
||||||
|
"kind": "account",
|
||||||
|
"name": "netork@pam",
|
||||||
|
"expires": 1767225600,
|
||||||
|
}
|
||||||
|
api.access.users.assert_called_with("netork@pam")
|
||||||
|
|
||||||
|
def test_an_account_without_expiry_never_expires(self):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.return_value = {"userid": "netork@pam", "enable": 1}
|
||||||
|
assert drv.get_credential_expiry()["expires"] is None
|
||||||
|
|
||||||
|
def test_a_refused_read_is_a_permission_error(self):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.side_effect = _forbidden()
|
||||||
|
with pytest.raises(PermissionError):
|
||||||
|
drv.get_credential_expiry()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"error",
|
||||||
|
[
|
||||||
|
ResourceException(500, "Internal Server Error", "cfs lock timeout"),
|
||||||
|
ConnectionError("reset"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_another_failure_is_a_runtime_error(self, error):
|
||||||
|
drv, api = _driver()
|
||||||
|
api.access.users.return_value.get.side_effect = error
|
||||||
|
with pytest.raises(RuntimeError, match="netork@pam"):
|
||||||
|
drv.get_credential_expiry()
|
||||||
@@ -2,11 +2,12 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
|
||||||
from tests.conftest import _build_mock_api, NODE_STATUS
|
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
|
||||||
|
|
||||||
class TestGetEnvironment:
|
class TestGetEnvironment:
|
||||||
@@ -25,9 +26,6 @@ class TestGetEnvironment:
|
|||||||
assert isinstance(result["fans"], dict)
|
assert isinstance(result["fans"], dict)
|
||||||
|
|
||||||
def test_temperature_with_sensors(self):
|
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 = [
|
sensors_data = [
|
||||||
{"name": "CPU Package", "value": "55.0"},
|
{"name": "CPU Package", "value": "55.0"},
|
||||||
@@ -49,9 +47,6 @@ class TestGetEnvironment:
|
|||||||
assert result["temperature"]["GPU Core"]["is_critical"] is False
|
assert result["temperature"]["GPU Core"]["is_critical"] is False
|
||||||
|
|
||||||
def test_temperature_critical(self):
|
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"}]
|
sensors_data = [{"name": "NVMe", "value": "98.0"}]
|
||||||
mock_api = _build_mock_api(sensors=sensors_data)
|
mock_api = _build_mock_api(sensors=sensors_data)
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"""The PVE firewall, read only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall`` reads the datacenter level -- options, rules, security groups,
|
||||||
|
IP sets, aliases -- the node's options and rules, and every guest's on the node with
|
||||||
|
which of its NICs carry ``firewall=1``. Each rule says where it came from. A level
|
||||||
|
PVE refuses is None, not empty. ``get_host_firewall`` reads what the node has loaded
|
||||||
|
(``nft list ruleset`` / ``iptables-save``), as for any Linux host.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.firewall_mixin import nic_firewalls
|
||||||
|
|
||||||
|
DC_OPTIONS = {"enable": 1, "policy_in": "DROP", "policy_out": "ACCEPT"}
|
||||||
|
DC_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"macro": "SSH",
|
||||||
|
"source": "+dc/admins",
|
||||||
|
"enable": 1,
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
GROUP_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "proto": "tcp", "dport": "80,443", "enable": 1}
|
||||||
|
]
|
||||||
|
IPSET = [{"cidr": "198.51.100.0/24", "comment": "office"}, {"cidr": "198.51.100.7", "nomatch": 1}]
|
||||||
|
ALIASES = [{"name": "monitor", "cidr": "203.0.113.5/32", "comment": "zabbix"}]
|
||||||
|
NODE_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "dport": "8006", "proto": "tcp", "enable": 0}
|
||||||
|
]
|
||||||
|
GUEST_OPTIONS = {"enable": 1, "policy_in": "DROP"}
|
||||||
|
GUEST_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"enable": 1,
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _api() -> MagicMock:
|
||||||
|
api = MagicMock()
|
||||||
|
fw = api.cluster.firewall
|
||||||
|
fw.options.get.return_value = DC_OPTIONS
|
||||||
|
fw.rules.get.return_value = DC_RULES
|
||||||
|
fw.groups.get.return_value = [{"group": "web", "comment": "web servers"}]
|
||||||
|
fw.groups.return_value.get.return_value = GROUP_RULES
|
||||||
|
fw.ipset.get.return_value = [{"name": "admins"}]
|
||||||
|
fw.ipset.return_value.get.return_value = IPSET
|
||||||
|
fw.aliases.get.return_value = ALIASES
|
||||||
|
node = api.nodes.return_value
|
||||||
|
node.firewall.options.get.return_value = {"enable": 1}
|
||||||
|
node.firewall.rules.get.return_value = NODE_RULES
|
||||||
|
node.qemu.get.return_value = [{"vmid": 100, "name": "web-01"}]
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
vm.firewall.options.get.return_value = GUEST_OPTIONS
|
||||||
|
vm.firewall.rules.get.return_value = GUEST_RULES
|
||||||
|
vm.config.get.return_value = {
|
||||||
|
"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=1",
|
||||||
|
"net1": "virtio=AA:BB:CC:DD:EE:02,bridge=vmbr1",
|
||||||
|
"name": "web-01",
|
||||||
|
}
|
||||||
|
node.lxc.get.return_value = [{"vmid": 200, "name": "dns-01"}]
|
||||||
|
ct = node.lxc.return_value
|
||||||
|
ct.firewall.options.get.return_value = {}
|
||||||
|
ct.firewall.rules.get.return_value = []
|
||||||
|
ct.config.get.return_value = {"net0": "name=eth0,bridge=vmbr0,firewall=1,ip=dhcp"}
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fw_driver(driver):
|
||||||
|
driver._api = _api()
|
||||||
|
return driver
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheDatacenter:
|
||||||
|
def test_options_rules_groups_ipsets_aliases(self, fw_driver):
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["options"] == DC_OPTIONS
|
||||||
|
assert [
|
||||||
|
(r["origin"], r["type"], r.get("macro"), r["enable"]) for r in cluster["rules"]
|
||||||
|
] == [
|
||||||
|
("cluster", "in", "SSH", True),
|
||||||
|
("cluster", "group", None, True),
|
||||||
|
]
|
||||||
|
assert cluster["groups"] == {
|
||||||
|
"web": [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "80,443",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "group",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["ipsets"] == {
|
||||||
|
"admins": [
|
||||||
|
{"cidr": "198.51.100.0/24", "nomatch": False, "comment": "office"},
|
||||||
|
{"cidr": "198.51.100.7", "nomatch": True, "comment": None},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
def test_a_level_pve_refuses_is_none_not_empty(self, fw_driver):
|
||||||
|
fw_driver._api.cluster.firewall.ipset.get.side_effect = RuntimeError("403 Forbidden")
|
||||||
|
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["ipsets"] is None
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheNodeAndItsGuests:
|
||||||
|
def test_the_nodes_rules_keep_their_switch(self, fw_driver):
|
||||||
|
node = fw_driver.get_pve_firewall()["node"]
|
||||||
|
|
||||||
|
assert node["name"] == fw_driver._node_name
|
||||||
|
assert node["options"] == {"enable": 1}
|
||||||
|
assert node["rules"][0]["enable"] is False
|
||||||
|
assert node["rules"][0]["origin"] == "node"
|
||||||
|
|
||||||
|
def test_every_guest_with_its_rules_and_nics(self, fw_driver):
|
||||||
|
guests = fw_driver.get_pve_firewall()["guests"]
|
||||||
|
|
||||||
|
assert [(g["vmid"], g["type"], g["name"]) for g in guests] == [
|
||||||
|
("100", "vm", "web-01"),
|
||||||
|
("200", "container", "dns-01"),
|
||||||
|
]
|
||||||
|
vm = guests[0]
|
||||||
|
assert vm["options"] == GUEST_OPTIONS
|
||||||
|
assert vm["rules"][0] == {
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "guest",
|
||||||
|
}
|
||||||
|
assert vm["nics"] == [
|
||||||
|
{"name": "net0", "firewall": True},
|
||||||
|
{"name": "net1", "firewall": False},
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_a_guest_whose_config_is_refused_has_no_nics_reading(self, fw_driver):
|
||||||
|
fw_driver._api.nodes.return_value.qemu.return_value.config.get.side_effect = RuntimeError(
|
||||||
|
"403"
|
||||||
|
)
|
||||||
|
|
||||||
|
vm = fw_driver.get_pve_firewall()["guests"][0]
|
||||||
|
|
||||||
|
assert vm["nics"] is None
|
||||||
|
assert vm["rules"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_nic_without_the_flag_is_not_filtered():
|
||||||
|
assert nic_firewalls({"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=0"}) == [
|
||||||
|
{"name": "net0", "firewall": False}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheLoadedRuleset:
|
||||||
|
def test_the_node_reads_its_netfilter_rules_like_a_linux_host(self, driver):
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
def run(command: str) -> str:
|
||||||
|
seen.append(command)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
driver._exec_ssh_command = run # type: ignore[method-assign]
|
||||||
|
|
||||||
|
assert hasattr(driver, "get_host_firewall")
|
||||||
|
try:
|
||||||
|
driver.get_host_firewall()
|
||||||
|
except Exception:
|
||||||
|
pass # an empty answer is no report; the transport is what is tested here
|
||||||
|
assert seen and "nft" in seen[0] and "iptables-save" in seen[0]
|
||||||
@@ -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": ""}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
"""Proxmox VE says that "upgrade everything" must be a full upgrade on it.
|
||||||
|
|
||||||
|
A plain ``apt-get upgrade`` can leave a node half updated; Proxmox documents
|
||||||
|
``apt full-upgrade``. netOrk reads ``FULL_UPGRADE`` to choose.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_full_upgrade_is_declared():
|
||||||
|
assert ProxmoxDriver.FULL_UPGRADE is True
|
||||||
@@ -3,10 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
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
|
@pytest.fixture
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""`get_hardening`: how the node is hardened (NetOrk/netork#2776).
|
||||||
|
|
||||||
|
A hypervisor is where CPU vulnerabilities matter most: its guests share the CPU.
|
||||||
|
The command and its parse are napalm-device-types' (``HardeningMixin``); both
|
||||||
|
drivers carry the command over their own exec path, which is root's login, so
|
||||||
|
AppArmor's profiles per mode are read as well.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import HardeningMixin
|
||||||
|
|
||||||
|
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
WIRE = "\n".join(
|
||||||
|
[
|
||||||
|
"HARDENING_BEGIN",
|
||||||
|
"[lsm]",
|
||||||
|
"lockdown,capability,landlock,yama,apparmor,bpf",
|
||||||
|
"[cmdline]",
|
||||||
|
"BOOT_IMAGE=/boot/vmlinuz-6.8.12-4-pve root=/dev/mapper/pve-root ro mitigations=off",
|
||||||
|
"[fips]",
|
||||||
|
"0",
|
||||||
|
"[apparmor_enabled]",
|
||||||
|
"Y",
|
||||||
|
"[os]",
|
||||||
|
"ID=debian",
|
||||||
|
"[cpu_vulnerabilities]",
|
||||||
|
"/sys/devices/system/cpu/vulnerabilities/mds:Vulnerable; SMT vulnerable",
|
||||||
|
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected",
|
||||||
|
"HARDENING_END",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_declare_the_contract(cls):
|
||||||
|
assert issubclass(cls, HardeningMixin)
|
||||||
|
assert hasattr(cls, "get_hardening")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_node_runs_the_shared_command_over_its_exec_path(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
reading = driver.get_hardening()
|
||||||
|
|
||||||
|
exec_.assert_called_once()
|
||||||
|
assert "HARDENING_" in exec_.call_args.args[0]
|
||||||
|
assert reading["lsm"] == ["lockdown", "capability", "landlock", "yama", "apparmor", "bpf"]
|
||||||
|
assert reading["mitigations"] == "off"
|
||||||
|
assert reading["cpu_vulnerabilities"]["mds"] == "Vulnerable; SMT vulnerable"
|
||||||
|
assert reading["os_ids"] == ["debian"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_it_the_same_way():
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
|
||||||
|
with patch.object(drv, "_exec_ssh_command", return_value=WIRE):
|
||||||
|
reading = drv.get_hardening()
|
||||||
|
|
||||||
|
assert reading["cpu_vulnerabilities"]["meltdown"] == "Not affected"
|
||||||
|
|
||||||
|
|
||||||
|
def test_output_without_a_report_raises(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_hardening()
|
||||||
|
|
||||||
|
|
||||||
|
class TestCpuMicrocode:
|
||||||
|
"""``install_cpu_microcode`` (napalm-device-types ``CpuMicrocodeMixin``, NetOrk/netork#2838):
|
||||||
|
a node runs on its own CPU, and Proxmox's own install enables no ``non-free-firmware``."""
|
||||||
|
|
||||||
|
SOURCES = "/etc/apt/sources.list.d/debian.sources"
|
||||||
|
TEXT = (
|
||||||
|
"Types: deb\nURIs: http://deb.debian.org/debian/\nSuites: trixie trixie-updates\n"
|
||||||
|
"Components: main contrib\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _node(self, drv, *, virtualization="none"):
|
||||||
|
import base64
|
||||||
|
|
||||||
|
ran: list[str] = []
|
||||||
|
file_lines = "".join(f"|{line}\n" for line in self.TEXT.split("\n"))
|
||||||
|
report = (
|
||||||
|
"ARELEASE_BEGIN\n@@os\n|ID=debian\n|VERSION_CODENAME=trixie\n"
|
||||||
|
f"@@file {self.SOURCES}\n{file_lines}ARELEASE_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def exec_(command):
|
||||||
|
ran.append(command)
|
||||||
|
if command.startswith("base64 "):
|
||||||
|
return base64.b64encode(self.TEXT.encode()).decode()
|
||||||
|
if "ARELEASE_" in command:
|
||||||
|
return report
|
||||||
|
return "done\n__PVE_RC=0"
|
||||||
|
|
||||||
|
drv.get_hardening = lambda: {
|
||||||
|
"os_ids": ["debian"],
|
||||||
|
"virtualization": virtualization,
|
||||||
|
"cpu_vendor": "GenuineIntel",
|
||||||
|
}
|
||||||
|
drv.get_packages = lambda: []
|
||||||
|
drv.refresh_available_updates = lambda: pytest.fail("the API refresh does not wait")
|
||||||
|
drv._exec_ssh_command = exec_
|
||||||
|
return ran
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_carry_it(self, cls):
|
||||||
|
assert callable(getattr(cls, "install_cpu_microcode", None))
|
||||||
|
|
||||||
|
def test_the_component_then_apt_get_update_then_the_package(self, driver):
|
||||||
|
ran = self._node(driver)
|
||||||
|
|
||||||
|
result = driver.install_cpu_microcode()
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
assert result["sources_changed"] is True
|
||||||
|
written = next(c for c in ran if "install -m 644" in c)
|
||||||
|
assert self.SOURCES in written
|
||||||
|
update = next(i for i, c in enumerate(ran) if "apt-get update" in c)
|
||||||
|
install = next(i for i, c in enumerate(ran) if "apt-get install -y intel-microcode" in c)
|
||||||
|
assert ran.index(written) < update < install
|
||||||
|
|
||||||
|
def test_a_virtual_backup_server_installs_nothing(self):
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
ran = self._node(drv, virtualization="kvm")
|
||||||
|
|
||||||
|
result = drv.install_cpu_microcode()
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "its host does" in result["output"]
|
||||||
|
assert ran == []
|
||||||
@@ -2,11 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
from tests.conftest import NODE_NETWORK
|
||||||
from tests.conftest import _build_mock_api, NODE_NETWORK
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetInterfaces:
|
class TestGetInterfaces:
|
||||||
@@ -89,10 +85,18 @@ class TestGetInterfacesCounters:
|
|||||||
result = driver.get_interfaces_counters()
|
result = driver.get_interfaces_counters()
|
||||||
eth0 = result["eth0"]
|
eth0 = result["eth0"]
|
||||||
for field in (
|
for field in (
|
||||||
"tx_errors", "rx_errors", "tx_discards", "rx_discards",
|
"tx_errors",
|
||||||
"tx_octets", "rx_octets", "tx_unicast_packets", "rx_unicast_packets",
|
"rx_errors",
|
||||||
"tx_multicast_packets", "rx_multicast_packets",
|
"tx_discards",
|
||||||
"tx_broadcast_packets", "rx_broadcast_packets",
|
"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}"
|
assert field in eth0, f"Missing field: {field}"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""`get_kernel_facts`: what the node's kernel has built and loaded.
|
||||||
|
|
||||||
|
A Proxmox node runs its own kernel under every guest, which makes it the host
|
||||||
|
where a kernel CVE's preconditions matter most. The command and its parse are
|
||||||
|
napalm-device-types'; the driver only carries the command over its exec path.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
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 = (
|
||||||
|
"[release]\n6.8.12-4-pve\n[loaded]\nkvm_intel\n[builtin]\nkernel/net/ipv4/tcp_cubic.ko\n"
|
||||||
|
"[available]\nkernel/net/tipc/tipc.ko\n[config]\nCONFIG_TIPC=m\n"
|
||||||
|
)
|
||||||
|
WIRE = "KFACTS_BEGIN\n" + base64.encodebytes(gzip.compress(REPORT.encode())).decode() + "KFACTS_END"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_driver_declares_the_contract():
|
||||||
|
assert issubclass(ProxmoxDriver, KernelFactsMixin)
|
||||||
|
|
||||||
|
|
||||||
|
def test_it_runs_the_shared_command(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
facts = driver.get_kernel_facts()
|
||||||
|
|
||||||
|
exec_.assert_called_once_with(KERNEL_FACTS_COMMAND)
|
||||||
|
assert facts["release"] == "6.8.12-4-pve"
|
||||||
|
assert facts["loaded"] == ["kvm_intel"]
|
||||||
|
assert facts["builtin"] == ["tcp_cubic"]
|
||||||
|
assert facts["available"] == ["tipc"]
|
||||||
|
assert facts["config"] == {"CONFIG_TIPC": "m"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_output_without_a_report_raises(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_kernel_facts()
|
||||||
@@ -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")
|
||||||
|
]
|
||||||
+80
-77
@@ -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 __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
import pytest
|
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:
|
class TestGetNTPStats:
|
||||||
@@ -25,19 +14,19 @@ class TestGetNTPStats:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_synchronized_server(self, driver):
|
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()
|
stats = driver.get_ntp_stats()
|
||||||
synced = [s for s in stats if s["synchronized"]]
|
synced = [s for s in stats if s["synchronized"]]
|
||||||
assert len(synced) == 1
|
assert len(synced) == 1
|
||||||
assert synced[0]["remote"] == "192.168.1.1"
|
assert synced[0]["remote"] == "192.168.1.1"
|
||||||
|
|
||||||
def test_stratum(self, driver):
|
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()
|
stats = driver.get_ntp_stats()
|
||||||
assert stats[0]["stratum"] == 4
|
assert stats[0]["stratum"] == 4
|
||||||
|
|
||||||
def test_empty_when_no_ntp_command(self, driver):
|
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()
|
stats = driver.get_ntp_stats()
|
||||||
assert stats == []
|
assert stats == []
|
||||||
|
|
||||||
@@ -52,7 +41,7 @@ class TestGetSNMPInformation:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_communities(self, driver):
|
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()
|
result = driver.get_snmp_information()
|
||||||
assert "public" in result["community"]
|
assert "public" in result["community"]
|
||||||
assert result["community"]["public"]["mode"] == "ro"
|
assert result["community"]["public"]["mode"] == "ro"
|
||||||
@@ -60,39 +49,39 @@ class TestGetSNMPInformation:
|
|||||||
assert result["community"]["private"]["mode"] == "rw"
|
assert result["community"]["private"]["mode"] == "rw"
|
||||||
|
|
||||||
def test_location(self, driver):
|
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()
|
result = driver.get_snmp_information()
|
||||||
assert result["location"] == "Server Room A"
|
assert result["location"] == "Server Room A"
|
||||||
|
|
||||||
def test_contact(self, driver):
|
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()
|
result = driver.get_snmp_information()
|
||||||
assert result["contact"] == "admin@example.com"
|
assert result["contact"] == "admin@example.com"
|
||||||
|
|
||||||
def test_chassis_id_is_node_name(self, driver):
|
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()
|
result = driver.get_snmp_information()
|
||||||
assert result["chassis_id"] == "pve1"
|
assert result["chassis_id"] == "pve1"
|
||||||
|
|
||||||
|
|
||||||
class TestGetUsers:
|
class TestGetUsers:
|
||||||
def test_pve_users_returned(self, driver):
|
def test_pve_users_returned(self, driver):
|
||||||
driver._node_api().execute.post.return_value = {"data": ""}
|
driver._node_ssh().output = ""
|
||||||
result = driver.get_users()
|
result = driver.get_users()
|
||||||
assert "root@pam" in result
|
assert "root@pam" in result
|
||||||
assert "napalm@pam" in result
|
assert "napalm@pam" in result
|
||||||
|
|
||||||
def test_user_has_required_keys(self, driver):
|
def test_user_has_required_keys(self, driver):
|
||||||
driver._node_api().execute.post.return_value = {"data": ""}
|
driver._node_ssh().output = ""
|
||||||
result = driver.get_users()
|
result = driver.get_users()
|
||||||
for user, data in result.items():
|
for _user, data in result.items():
|
||||||
assert "level" in data
|
assert "level" in data
|
||||||
assert "password" in data
|
assert "password" in data
|
||||||
assert "sshkeys" in data
|
assert "sshkeys" in data
|
||||||
|
|
||||||
def test_root_local_user_from_passwd(self, driver):
|
def test_root_local_user_from_passwd(self, driver):
|
||||||
passwd_output = "root:x:0:0:root:/root:/bin/bash\n"
|
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()
|
result = driver.get_users()
|
||||||
assert "root" in result
|
assert "root" in result
|
||||||
assert result["root"]["level"] == 15
|
assert result["root"]["level"] == 15
|
||||||
@@ -135,14 +124,14 @@ class TestConfigManagement:
|
|||||||
assert diff == ""
|
assert diff == ""
|
||||||
|
|
||||||
def test_get_config_running(self, driver):
|
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")
|
result = driver.get_config(retrieve="running")
|
||||||
assert self.RUNNING in result["running"]
|
assert self.RUNNING in result["running"]
|
||||||
assert result["candidate"] == ""
|
assert result["candidate"] == ""
|
||||||
|
|
||||||
def test_get_config_sanitized_redacts_password(self, driver):
|
def test_get_config_sanitized_redacts_password(self, driver):
|
||||||
raw = "password mysecret\nauto eth0\n"
|
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)
|
result = driver.get_config(retrieve="running", sanitized=True)
|
||||||
assert "mysecret" not in result["running"]
|
assert "mysecret" not in result["running"]
|
||||||
assert "****" in result["running"]
|
assert "****" in result["running"]
|
||||||
@@ -167,20 +156,45 @@ class TestPing:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_success(self, driver):
|
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")
|
result = driver.ping("8.8.8.8")
|
||||||
assert "success" in result
|
assert "success" in result
|
||||||
assert result["success"]["probes_sent"] == 2
|
assert result["success"]["probes_sent"] == 2
|
||||||
assert result["success"]["packet_loss"] == 0
|
assert result["success"]["packet_loss"] == 0
|
||||||
assert result["success"]["rtt_min"] == pytest.approx(10.5, abs=0.01)
|
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):
|
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")
|
result = driver.ping("badhost")
|
||||||
assert "error" in result
|
assert "error" in result
|
||||||
|
|
||||||
def test_exec_unavailable(self, driver):
|
def test_no_output(self, driver):
|
||||||
driver._node_api().execute.post.return_value = {"data": ""}
|
driver._node_ssh().output = ""
|
||||||
result = driver.ping("8.8.8.8")
|
result = driver.ping("8.8.8.8")
|
||||||
assert "error" in result
|
assert "error" in result
|
||||||
|
|
||||||
@@ -194,44 +208,34 @@ class TestTraceroute:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_success_hops(self, driver):
|
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")
|
result = driver.traceroute("8.8.8.8")
|
||||||
assert "success" in result
|
assert "success" in result
|
||||||
assert 1 in result["success"]
|
assert 1 in result["success"]
|
||||||
assert 3 in result["success"]
|
assert 3 in result["success"]
|
||||||
|
|
||||||
def test_hop_rtt(self, driver):
|
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")
|
result = driver.traceroute("8.8.8.8")
|
||||||
hop1 = result["success"][1]["probes"]
|
hop1 = result["success"][1]["probes"]
|
||||||
assert hop1[1]["ip_address"] == "10.0.0.254"
|
assert hop1[1]["ip_address"] == "10.0.0.254"
|
||||||
|
|
||||||
def test_empty_returns_error(self, driver):
|
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")
|
result = driver.traceroute("8.8.8.8")
|
||||||
assert "error" in result
|
assert "error" in result
|
||||||
|
|
||||||
|
|
||||||
class TestCLI:
|
class TestCLI:
|
||||||
def test_cli_single_command(self, driver):
|
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"])
|
result = driver.cli(["echo hello world"])
|
||||||
assert result["echo hello world"] == "hello world"
|
assert result["echo hello world"] == "hello world"
|
||||||
|
|
||||||
def test_cli_multiple_commands(self, driver):
|
def test_cli_multiple_commands(self, driver):
|
||||||
responses = {"uptime": "up 2 days", "hostname": "pve1"}
|
driver._node_ssh().outputs = {"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
|
|
||||||
result = driver.cli(["uptime", "hostname"])
|
result = driver.cli(["uptime", "hostname"])
|
||||||
assert "uptime" in result
|
assert result == {"uptime": "up 2 days", "hostname": "pve1"}
|
||||||
assert "hostname" in result
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetRouteTo:
|
class TestGetRouteTo:
|
||||||
@@ -241,57 +245,49 @@ class TestGetRouteTo:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_returns_routes(self, driver):
|
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")
|
result = driver.get_route_to(destination="10.0.0.0/24")
|
||||||
assert "10.0.0.0/24" in result
|
assert "10.0.0.0/24" in result
|
||||||
|
|
||||||
def test_route_fields(self, driver):
|
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()
|
result = driver.get_route_to()
|
||||||
for prefix, routes in result.items():
|
for _prefix, routes in result.items():
|
||||||
for route in routes:
|
for route in routes:
|
||||||
assert "protocol" in route
|
assert "protocol" in route
|
||||||
assert "next_hop" in route
|
assert "next_hop" in route
|
||||||
assert "outgoing_interface" in route
|
assert "outgoing_interface" in route
|
||||||
|
|
||||||
def test_protocol_filter(self, driver):
|
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")
|
result = driver.get_route_to(protocol="dhcp")
|
||||||
for prefix, routes in result.items():
|
for _prefix, routes in result.items():
|
||||||
for route in routes:
|
for route in routes:
|
||||||
assert "dhcp" in route["protocol"].lower()
|
assert "dhcp" in route["protocol"].lower()
|
||||||
|
|
||||||
|
|
||||||
class TestLLDPNeighbors:
|
class TestLLDPNeighbors:
|
||||||
# Real `lldpcli show neighbors summary` output. The interface line carries
|
# ``lldpctl -f keyvalue`` with its exit status, as LLDPCTL_KEYVALUE_COMMAND prints
|
||||||
# ", via: LLDP, ..." after the name, which is what the parser matches on —
|
# it (the parse itself is covered in test_lldp.py).
|
||||||
# the previous fixture stopped at the name and matched nothing.
|
LLDP_KEYVALUE = (
|
||||||
LLDP_SUMMARY = (
|
"lldp.eth0.via=LLDP\n"
|
||||||
"LLDP neighbors:\n"
|
"lldp.eth0.chassis.name=sw01.example.com\n"
|
||||||
"-------------------------------------------------------------------------------\n"
|
"lldp.eth0.port.ifname=GigabitEthernet1/0/1\n"
|
||||||
"Interface: eth0, via: LLDP, RID: 1, Time: 0 day, 00:11:22\n"
|
"lldp.eth1.via=LLDP\n"
|
||||||
" Chassis:\n"
|
"lldp.eth1.chassis.name=sw02.example.com\n"
|
||||||
" SysName: sw01.example.com\n"
|
"lldp.eth1.port.ifname=GigabitEthernet1/0/2\n"
|
||||||
" Port:\n"
|
"__LLDPCTL_RC=0\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"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_neighbors_found(self, driver):
|
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()
|
result = driver.get_lldp_neighbors()
|
||||||
assert "eth0" in result
|
assert "eth0" in result
|
||||||
assert result["eth0"][0]["hostname"] == "sw01.example.com"
|
assert result["eth0"][0]["hostname"] == "sw01.example.com"
|
||||||
|
|
||||||
def test_empty_when_no_lldp(self, driver):
|
def test_empty_when_no_lldp_neighbour(self, driver):
|
||||||
driver._node_api().execute.post.return_value = {"data": ""}
|
with patch.object(driver, "_exec_ssh_command", return_value="__LLDPCTL_RC=0"):
|
||||||
result = driver.get_lldp_neighbors()
|
result = driver.get_lldp_neighbors()
|
||||||
assert result == {}
|
assert result == {}
|
||||||
|
|
||||||
|
|
||||||
@@ -303,22 +299,29 @@ class TestIPv6Neighbors:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_neighbors_parsed(self, driver):
|
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()
|
result = driver.get_ipv6_neighbors_table()
|
||||||
assert len(result) == 2 # FAILED entry excluded
|
assert len(result) == 2 # FAILED entry excluded
|
||||||
|
|
||||||
def test_mac_normalized(self, driver):
|
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()
|
result = driver.get_ipv6_neighbors_table()
|
||||||
macs = {e["mac"] for e in result}
|
macs = {e["mac"] for e in result}
|
||||||
assert "aa:bb:cc:dd:ee:ff" in macs
|
assert "aa:bb:cc:dd:ee:ff" in macs
|
||||||
|
|
||||||
def test_state_present(self, driver):
|
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()
|
result = driver.get_ipv6_neighbors_table()
|
||||||
states = {e["state"] for e in result}
|
states = {e["state"] for e in result}
|
||||||
assert "REACHABLE" in states
|
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:
|
class TestNotImplemented:
|
||||||
def test_get_bgp_config_raises(self, driver):
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from napalm_proxmox import utils
|
from napalm_proxmox import utils
|
||||||
|
|
||||||
|
|
||||||
PROC_NET_ARP = """\
|
PROC_NET_ARP = """\
|
||||||
IP address HW type Flags HW address Mask Device
|
IP address HW type Flags HW address Mask Device
|
||||||
10.0.0.254 0x1 0x2 aa:bb:cc:dd:ee:ff * eth0
|
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):
|
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()
|
result = driver.get_arp_table()
|
||||||
assert len(result) == 2 # 00:00:00:00:00:00 excluded
|
assert len(result) == 2 # 00:00:00:00:00:00 excluded
|
||||||
|
|
||||||
def test_mac_normalized(self, driver):
|
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()
|
result = driver.get_arp_table()
|
||||||
macs = {e["mac"] for e in result}
|
macs = {e["mac"] for e in result}
|
||||||
assert "aa:bb:cc:dd:ee:ff" in macs
|
assert "aa:bb:cc:dd:ee:ff" in macs
|
||||||
|
|
||||||
def test_vrf_filter(self, driver):
|
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")
|
result = driver.get_arp_table(vrf="vmbr0")
|
||||||
assert all(e["interface"] == "vmbr0" for e in result)
|
assert all(e["interface"] == "vmbr0" for e in result)
|
||||||
|
|
||||||
def test_empty_when_exec_unavailable(self, driver):
|
def test_empty_when_the_node_prints_nothing(self, driver):
|
||||||
driver._node_api().execute.post.return_value = {"data": ""}
|
driver._node_ssh().output = ""
|
||||||
result = driver.get_arp_table()
|
result = driver.get_arp_table()
|
||||||
assert result == []
|
assert result == []
|
||||||
|
|
||||||
@@ -137,10 +135,7 @@ class TestGetMACAddressTable:
|
|||||||
"cc:dd:ee:ff:00:11 dev eth0 vlan 20 master vmbr0\n"
|
"cc:dd:ee:ff:00:11 dev eth0 vlan 20 master vmbr0\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
OVS_APPCTL = (
|
OVS_APPCTL = " LOCAL 0 aa:bb:cc:dd:ee:03 0\n 1 10 11:22:33:44:55:66 100\n"
|
||||||
" 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 test_linux_bridge_entries(self, driver):
|
||||||
def _exec(cmd):
|
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."""
|
not, so no amount of parsing could have produced one."""
|
||||||
import inspect
|
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
|
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,46 @@
|
|||||||
|
"""Which Proxmox VE release the node runs, for what only newer releases offer.
|
||||||
|
|
||||||
|
``GET /version`` names the pve-manager package's version (``"9.3.0"``) and the
|
||||||
|
point release (``"9.3"``). PVE 9.3 added the REST calls of NetOrk/netork#2728;
|
||||||
|
the driver takes them only on a node that has them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("version", "expected"),
|
||||||
|
[
|
||||||
|
({"version": "9.3.0", "release": "9.3"}, True),
|
||||||
|
({"version": "9.3.2", "release": "9.3"}, True),
|
||||||
|
({"version": "10.0.1", "release": "10.0"}, True),
|
||||||
|
({"version": "9.2.4", "release": "9.2"}, False),
|
||||||
|
({"version": "8.4.1", "release": "8.4"}, False),
|
||||||
|
# No package version: the point release tells.
|
||||||
|
({"release": "9.3"}, True),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_at_least(driver, version, expected):
|
||||||
|
driver._api.version.get.return_value = version
|
||||||
|
assert driver._version_at_least(9, 3) is expected
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("version", [{}, {"version": "unknown", "release": ""}])
|
||||||
|
def test_a_version_it_cannot_read_counts_as_older(driver, version):
|
||||||
|
driver._api.version.get.return_value = version
|
||||||
|
assert driver._version_at_least(9, 3) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_api_error_propagates(driver):
|
||||||
|
driver._api.version.get.side_effect = ConnectionError("node unreachable")
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
driver._version_at_least(9, 3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_another_node_is_asked_for_its_own_version(driver):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
driver._api.nodes("pve2").version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
assert driver._version_at_least(9, 3, node="pve2") is False
|
||||||
|
driver._api.nodes.assert_called_with("pve2")
|
||||||
@@ -0,0 +1,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
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
from tests.conftest import _build_mock_api
|
||||||
from tests.conftest import _build_mock_api, SDN_ZONES, SDN_VNETS
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetVlans:
|
class TestGetVlans:
|
||||||
@@ -52,8 +51,8 @@ class TestGetVlans:
|
|||||||
|
|
||||||
def test_empty_sdn_returns_dict(self):
|
def test_empty_sdn_returns_dict(self):
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
from tests.conftest import _build_mock_api
|
|
||||||
|
|
||||||
mock_api = _build_mock_api(sdn_vnets=[], sdn_zones=[])
|
mock_api = _build_mock_api(sdn_vnets=[], sdn_zones=[])
|
||||||
drv = ProxmoxDriver("pve1", "root", "secret", optional_args={"verify_ssl": False})
|
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,68 @@
|
|||||||
|
"""Services on a Proxmox node: systemd, through napalm-device-types' mixin.
|
||||||
|
|
||||||
|
The listing used to read ``list-unit-files``' second column, which since
|
||||||
|
systemd 245 is followed by a preset column -- so ``enabled`` was false for
|
||||||
|
every service on every node (#6). An action ended in ``|| true`` and reported
|
||||||
|
success whatever happened. Both now come from the shared mixin; the driver
|
||||||
|
only carries the command over its exec path, as root.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import SystemdServicesMixin
|
||||||
|
from napalm_device_types.systemd import SYSTEMD_SERVICES_COMMAND, service_action_command
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
REPORT = (
|
||||||
|
"SVC_BEGIN\n[files]\npveproxy.service enabled enabled\n[units]\n"
|
||||||
|
"MainPID=1234\nId=pveproxy.service\nNames=pveproxy.service\nLoadState=loaded\n"
|
||||||
|
"ActiveState=active\nSubState=running\nUnitFileState=enabled\n"
|
||||||
|
"[generated]\nSVC_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_driver_uses_the_shared_mixin():
|
||||||
|
assert issubclass(ProxmoxDriver, SystemdServicesMixin)
|
||||||
|
assert ProxmoxDriver.get_services is SystemdServicesMixin.get_services
|
||||||
|
assert ProxmoxDriver.manage_service is SystemdServicesMixin.manage_service
|
||||||
|
|
||||||
|
|
||||||
|
def test_listing_runs_the_shared_command(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=REPORT) as exec_:
|
||||||
|
services = driver.get_services()
|
||||||
|
|
||||||
|
exec_.assert_called_once_with(SYSTEMD_SERVICES_COMMAND)
|
||||||
|
assert services == [{"name": "pveproxy", "running": True, "enabled": True, "pid": 1234}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unreadable_listing_raises_instead_of_reporting_no_services(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_services()
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_action_reports_its_real_outcome(driver):
|
||||||
|
failed = "Failed to restart nope.service: Unit nope.service not found.\n__SVC_RC=5"
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=failed) as exec_:
|
||||||
|
result = driver.manage_service("nope", "restart")
|
||||||
|
|
||||||
|
exec_.assert_called_once_with(service_action_command("nope", "restart"))
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "not found" in result["output"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_successful_action(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value="__SVC_RC=0"):
|
||||||
|
assert driver.manage_service("pveproxy", "restart") == {"success": True, "output": ""}
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_invalid_name_never_reaches_the_node(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command") as exec_:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.manage_service("pveproxy; reboot", "stop")
|
||||||
|
|
||||||
|
exec_.assert_not_called()
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""`get_services_need_restart`: the services on the node that still run replaced code.
|
||||||
|
|
||||||
|
An openssl or glibc update replaces the files on disk; every daemon that had them
|
||||||
|
loaded keeps the old code until it restarts (NetOrk/netork#2750). On a hypervisor that
|
||||||
|
is where a restart instead of a reboot matters most. The command and its parse are
|
||||||
|
napalm-device-types' (``ServicesRestartMixin``); the driver only carries the command
|
||||||
|
over its exec path, which runs as root. A login that is not root gets no reading: it
|
||||||
|
would see only its own processes and read as clean.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import ServicesRestartMixin
|
||||||
|
|
||||||
|
from napalm_proxmox import ProxmoxBackupDriver
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
#: A PVE node after an openssl update, read by the /proc scan (no needrestart):
|
||||||
|
#: pveproxy and a running VM's QEMU still map the old library, and so does a
|
||||||
|
#: container's own nginx, which the container updates itself.
|
||||||
|
WIRE = (
|
||||||
|
"RST_BEGIN\n[maps]\n"
|
||||||
|
"2101 pveproxy worker\n"
|
||||||
|
"3100 kvm\n"
|
||||||
|
"4100 nginx\n"
|
||||||
|
"[cgroups]\n"
|
||||||
|
"2101 0::/system.slice/pveproxy.service\n"
|
||||||
|
"3100 0::/qemu.slice/101.scope\n"
|
||||||
|
"4100 0::/lxc/200/ns/system.slice/nginx.service\n"
|
||||||
|
"RST_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("driver_class", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_declare_the_contract(driver_class):
|
||||||
|
assert issubclass(driver_class, ServicesRestartMixin)
|
||||||
|
|
||||||
|
|
||||||
|
def test_it_reads_as_root_over_the_exec_path(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
reading = driver.get_services_need_restart()
|
||||||
|
|
||||||
|
[command] = [c.args[0] for c in exec_.call_args_list]
|
||||||
|
assert command.startswith('[ "$(id -u)" = 0 ] && sh -c \'')
|
||||||
|
assert reading == {
|
||||||
|
"source": "maps",
|
||||||
|
"units": ["pveproxy"],
|
||||||
|
"processes": [{"pid": 3100, "name": "kvm"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_it_the_same_way():
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
wire = "RST_BEGIN\n[needrestart]\nNEEDRESTART-SVC: proxmox-backup-proxy.service\nRST_END\n"
|
||||||
|
|
||||||
|
with patch.object(drv, "_exec_ssh_command", return_value=wire):
|
||||||
|
reading = drv.get_services_need_restart()
|
||||||
|
|
||||||
|
assert reading["units"] == ["proxmox-backup-proxy"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_login_other_than_root_gets_no_reading(driver):
|
||||||
|
"""The guard runs nothing but as root, so no report comes back and the parse raises."""
|
||||||
|
|
||||||
|
def as_this_user(command: str) -> str:
|
||||||
|
return subprocess.run(["sh", "-c", command], capture_output=True, text=True).stdout
|
||||||
|
|
||||||
|
if subprocess.run(["id", "-u"], capture_output=True, text=True).stdout.strip() == "0":
|
||||||
|
pytest.skip("runs as root here")
|
||||||
|
with patch.object(driver, "_exec_ssh_command", side_effect=as_this_user):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_services_need_restart()
|
||||||
@@ -0,0 +1,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()
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""The node's past APT transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||||
|
|
||||||
|
PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
||||||
|
first. The payload below follows its schema: a transaction is identified by
|
||||||
|
``start-time`` with ``start-index`` (default 0) among those that started in the
|
||||||
|
same second; ``end-time`` is missing while it runs or after it was interrupted.
|
||||||
|
An older node has no such endpoint, and the driver parses no log over SSH.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
HISTORY = [
|
||||||
|
{
|
||||||
|
"start-time": 1764158400,
|
||||||
|
"start-index": 1,
|
||||||
|
"end-time": 1764158460,
|
||||||
|
"command-line": "apt-get -y dist-upgrade",
|
||||||
|
"requested-by": "admin",
|
||||||
|
"requested-by-uid": 1000,
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"package": "openssh-server",
|
||||||
|
"action": "upgrade",
|
||||||
|
"arch": "amd64",
|
||||||
|
"old-version": "1:10.0p1-7",
|
||||||
|
"new-version": "1:10.0p1-7+deb13u1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"package": "proxmox-kernel-6.17.2-1-pve-signed",
|
||||||
|
"action": "install",
|
||||||
|
"new-version": "6.17.2-1",
|
||||||
|
"automatic": 1,
|
||||||
|
},
|
||||||
|
{"package": "ifupdown", "action": "purge", "old-version": "0.8.44"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
# unattended-upgrades, interrupted: no end, no user, the error dpkg left.
|
||||||
|
"start-time": 1764072000,
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"package": "libssl3t64",
|
||||||
|
"action": "upgrade",
|
||||||
|
"old-version": "3.5.1-1",
|
||||||
|
"new-version": "3.5.1-1+deb13u1",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"error": "Sub-process /usr/bin/dpkg returned an error code (1)",
|
||||||
|
"running": 0,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def history(driver) -> MagicMock:
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
getter = driver._node_api().apt.history.get
|
||||||
|
getter.return_value = HISTORY
|
||||||
|
return getter
|
||||||
|
|
||||||
|
|
||||||
|
class TestUpdateHistory:
|
||||||
|
def test_transactions_newest_first(self, driver, history):
|
||||||
|
newest, older = driver.get_update_history()
|
||||||
|
assert newest == {
|
||||||
|
"id": "1764158400-1",
|
||||||
|
"start": 1764158400,
|
||||||
|
"end": 1764158460,
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"name": "openssh-server",
|
||||||
|
"action": "upgrade",
|
||||||
|
"old_version": "1:10.0p1-7",
|
||||||
|
"new_version": "1:10.0p1-7+deb13u1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "proxmox-kernel-6.17.2-1-pve-signed",
|
||||||
|
"action": "install",
|
||||||
|
"old_version": None,
|
||||||
|
"new_version": "6.17.2-1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ifupdown",
|
||||||
|
"action": "purge",
|
||||||
|
"old_version": "0.8.44",
|
||||||
|
"new_version": None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"requested_by": "admin",
|
||||||
|
"command": "apt-get -y dist-upgrade",
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
assert older["id"] == "1764072000-0"
|
||||||
|
history.assert_called_once_with()
|
||||||
|
|
||||||
|
def test_what_the_log_does_not_keep_is_none(self, driver, history):
|
||||||
|
older = driver.get_update_history()[1]
|
||||||
|
assert older["end"] is None
|
||||||
|
assert older["requested_by"] is None
|
||||||
|
assert older["command"] is None
|
||||||
|
assert older["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
|
||||||
|
|
||||||
|
def test_since_is_passed_on(self, driver, history):
|
||||||
|
driver.get_update_history(since=1764100000)
|
||||||
|
history.assert_called_once_with(since=1764100000)
|
||||||
|
|
||||||
|
def test_no_transaction_is_an_empty_list(self, driver, history):
|
||||||
|
history.return_value = []
|
||||||
|
assert driver.get_update_history() == []
|
||||||
|
|
||||||
|
def test_a_failed_read_raises(self, driver, history):
|
||||||
|
history.side_effect = Exception("596 Connection timed out")
|
||||||
|
with pytest.raises(RuntimeError, match="timed out"):
|
||||||
|
driver.get_update_history()
|
||||||
|
|
||||||
|
def test_an_older_node_has_no_history(self, driver, history):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
with pytest.raises(NotImplementedError):
|
||||||
|
driver.get_update_history()
|
||||||
|
history.assert_not_called()
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
"""Pending updates on a Proxmox node: from where, whether they are security fixes,
|
||||||
|
and whether the node needs a reboot.
|
||||||
|
|
||||||
|
The node's APT API names only an Origin ("Debian", "Proxmox"), the same for the
|
||||||
|
main and the security archive. ``apt list --upgradable`` over the exec path
|
||||||
|
names the suite (``trixie-security``), so that is read first; the API remains
|
||||||
|
the fallback, with the security status left unknown. A reader that cannot read
|
||||||
|
raises: an empty list would tell netOrk that nothing is pending.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import HostStatusMixin
|
||||||
|
from napalm_device_types.host_status import HOST_STATUS_COMMAND
|
||||||
|
from napalm_device_types.package_updates import APT_UPGRADABLE_COMMAND
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
APT = (
|
||||||
|
"libssl3t64/stable-security 3.5.1-1+deb13u2 amd64 [upgradable from: 3.5.1-1+deb13u1]\n"
|
||||||
|
"ceph-common/stable 20.2.4-pve5 amd64 [upgradable from: 20.2.4-pve4]\n"
|
||||||
|
)
|
||||||
|
API_ENTRY = {
|
||||||
|
"Package": "librados2",
|
||||||
|
"OldVersion": "20.2.4-pve4",
|
||||||
|
"Version": "20.2.4-pve5",
|
||||||
|
"Origin": "Proxmox",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _api_updates(driver, entries=None, error=None):
|
||||||
|
api = MagicMock()
|
||||||
|
getter = api.nodes.return_value.apt.update.get
|
||||||
|
if error:
|
||||||
|
getter.side_effect = error
|
||||||
|
else:
|
||||||
|
getter.return_value = entries or []
|
||||||
|
driver._api = api
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
class TestAvailableUpdates:
|
||||||
|
def test_apt_over_the_exec_path_names_the_suite(self, driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=APT + "__APT_RC=0\n") as exec_:
|
||||||
|
updates = {u["name"]: u for u in driver.get_available_updates()}
|
||||||
|
|
||||||
|
exec_.assert_called_once_with(APT_UPGRADABLE_COMMAND)
|
||||||
|
assert updates["libssl3t64"]["security"] is True
|
||||||
|
assert updates["ceph-common"]["security"] is False
|
||||||
|
assert updates["ceph-common"]["origin"] == "stable"
|
||||||
|
|
||||||
|
def test_the_api_is_the_fallback_with_security_unknown(self, driver):
|
||||||
|
_api_updates(driver, [API_ENTRY])
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
updates = driver.get_available_updates()
|
||||||
|
|
||||||
|
assert updates == [
|
||||||
|
{
|
||||||
|
"name": "librados2",
|
||||||
|
"current_version": "20.2.4-pve4",
|
||||||
|
"new_version": "20.2.4-pve5",
|
||||||
|
"origin": "Proxmox",
|
||||||
|
"security": None,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_a_failed_apt_falls_back_too(self, driver):
|
||||||
|
_api_updates(driver, [API_ENTRY])
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value="E: lock\n__APT_RC=100\n"):
|
||||||
|
assert [u["name"] for u in driver.get_available_updates()] == ["librados2"]
|
||||||
|
|
||||||
|
def test_nothing_readable_raises_instead_of_reporting_nothing(self, driver):
|
||||||
|
_api_updates(driver, error=RuntimeError("API timeout"))
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
driver.get_available_updates()
|
||||||
|
|
||||||
|
def test_nothing_pending_is_an_empty_list(self, driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value="__APT_RC=0\n"):
|
||||||
|
assert driver.get_available_updates() == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestRefresh:
|
||||||
|
def test_the_node_refreshes_its_index_through_the_api(self, driver):
|
||||||
|
api = _api_updates(driver)
|
||||||
|
api.nodes.return_value.apt.update.post.return_value = "UPID:pve1:0001"
|
||||||
|
|
||||||
|
result = driver.refresh_available_updates()
|
||||||
|
|
||||||
|
assert result["success"] is True
|
||||||
|
api.nodes.return_value.apt.update.post.assert_called_once()
|
||||||
|
|
||||||
|
def test_a_refused_refresh_says_why(self, driver):
|
||||||
|
api = _api_updates(driver)
|
||||||
|
api.nodes.return_value.apt.update.post.side_effect = RuntimeError(
|
||||||
|
"403 Permission check failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
result = driver.refresh_available_updates()
|
||||||
|
|
||||||
|
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 = (
|
||||||
|
"HSTAT_BEGIN\n[kernel]\n7.0.14-19-pve\n[modules]\n7.0.14-19-pve\n7.0.2-6-pve\n"
|
||||||
|
"[timers]\napt-daily-upgrade.timer enabled\nHSTAT_END\n"
|
||||||
|
)
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=report) as exec_:
|
||||||
|
status = driver.get_host_status()
|
||||||
|
|
||||||
|
exec_.assert_called_once_with(HOST_STATUS_COMMAND)
|
||||||
|
assert status["reboot_required"] is False
|
||||||
|
|
||||||
|
def test_the_driver_declares_the_contract(self):
|
||||||
|
assert issubclass(ProxmoxDriver, HostStatusMixin)
|
||||||
@@ -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
|
from __future__ import annotations
|
||||||
|
|
||||||
import pytest
|
|
||||||
from napalm_proxmox import utils
|
from napalm_proxmox import utils
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,90 @@ class TestGetVmsReportsStringIds:
|
|||||||
assert [vm["vmid"] for vm in driver.get_vms()] == ["99", "1000"]
|
assert [vm["vmid"] for vm in driver.get_vms()] == ["99", "1000"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetVmsGuestUid:
|
||||||
|
"""PVE 9.3 gives every guest a ``uid`` that survives a migration, a restore and a
|
||||||
|
changed vmid; only ``/cluster/resources`` reports it (NetOrk/netork#2728)."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def listed(self, driver, api):
|
||||||
|
driver.get_vm_interfaces = MagicMock(return_value=({}, False, False))
|
||||||
|
driver._get_vm_disk_and_boot = MagicMock(return_value=([], False))
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
return driver._api.cluster.resources.get
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _row(vmid, kind, uid=None, node="pve1"):
|
||||||
|
row = {"id": f"{kind}/{vmid}", "type": kind, "vmid": vmid, "node": node}
|
||||||
|
return {**row, "uid": uid} if uid else row
|
||||||
|
|
||||||
|
def test_each_guest_carries_its_uid_from_one_resources_call(self, driver, listed):
|
||||||
|
listed.return_value = [
|
||||||
|
self._row(100, "qemu", "abcdefghijklmnopqrst"),
|
||||||
|
self._row(200, "lxc", "bcdefghijklmnopqrstu"),
|
||||||
|
]
|
||||||
|
assert {vm["vmid"]: vm["uid"] for vm in driver.get_vms()} == {
|
||||||
|
"100": "abcdefghijklmnopqrst",
|
||||||
|
"200": "bcdefghijklmnopqrstu",
|
||||||
|
}
|
||||||
|
listed.assert_called_once_with(type="vm")
|
||||||
|
|
||||||
|
def test_a_guest_without_uid_has_no_key(self, driver, listed):
|
||||||
|
listed.return_value = [
|
||||||
|
self._row(100, "qemu"),
|
||||||
|
# The same vmid on another node is another guest.
|
||||||
|
self._row(200, "lxc", "bcdefghijklmnopqrstu", node="pve2"),
|
||||||
|
]
|
||||||
|
assert all("uid" not in vm for vm in driver.get_vms())
|
||||||
|
|
||||||
|
def test_unreadable_resources_leave_the_listing_without_uids(self, driver, listed):
|
||||||
|
listed.side_effect = Exception("403 Forbidden")
|
||||||
|
vms = driver.get_vms()
|
||||||
|
assert [vm["vmid"] for vm in vms] == ["100", "200"]
|
||||||
|
assert all("uid" not in vm for vm in vms)
|
||||||
|
|
||||||
|
def test_an_older_node_is_not_asked(self, driver, listed):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
assert all("uid" not in vm for vm in driver.get_vms())
|
||||||
|
listed.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetVmsTellsPausedFromRunning:
|
||||||
|
"""PVE reports a paused guest ``status: running``; only ``qmpstatus`` tells, and only
|
||||||
|
when the listing is asked for the full status (NetOrk/netork#2658)."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def listed(self, driver, api):
|
||||||
|
driver.get_vm_interfaces = MagicMock(return_value=({}, False, False))
|
||||||
|
driver._get_vm_disk_and_boot = MagicMock(return_value=([], False))
|
||||||
|
api.lxc.get.return_value = []
|
||||||
|
|
||||||
|
def statuses(*qemu):
|
||||||
|
api.qemu.get.return_value = [
|
||||||
|
{"vmid": 100 + i, "name": f"vm{i}", **row} for i, row in enumerate(qemu)
|
||||||
|
]
|
||||||
|
return {vm["vmid"]: vm["status"] for vm in driver.get_vms()}
|
||||||
|
|
||||||
|
return statuses
|
||||||
|
|
||||||
|
def test_the_listing_asks_for_the_full_status(self, listed, api):
|
||||||
|
listed({"status": "running", "qmpstatus": "running"})
|
||||||
|
api.qemu.get.assert_called_once_with(full=1)
|
||||||
|
|
||||||
|
def test_a_paused_guest_is_paused(self, listed):
|
||||||
|
assert listed({"status": "running", "qmpstatus": "paused"}) == {"100": "paused"}
|
||||||
|
|
||||||
|
def test_a_guest_asleep_in_s3_is_paused(self, listed):
|
||||||
|
"""Its QEMU process still holds its memory; ``status/resume`` wakes it."""
|
||||||
|
assert listed({"status": "running", "qmpstatus": "suspended"}) == {"100": "paused"}
|
||||||
|
|
||||||
|
def test_running_and_stopped_stay_as_they_are(self, listed):
|
||||||
|
assert listed(
|
||||||
|
{"status": "running", "qmpstatus": "running"},
|
||||||
|
{"status": "stopped", "qmpstatus": "stopped"},
|
||||||
|
{"status": "running"},
|
||||||
|
) == {"100": "running", "101": "stopped", "102": "running"}
|
||||||
|
|
||||||
|
|
||||||
class TestResolveVm:
|
class TestResolveVm:
|
||||||
def test_by_vmid_string(self, driver, api):
|
def test_by_vmid_string(self, driver, api):
|
||||||
assert driver._resolve_vm("100") == (100, "vm")
|
assert driver._resolve_vm("100") == (100, "vm")
|
||||||
@@ -84,6 +168,44 @@ class TestPowerActions:
|
|||||||
with pytest.raises(RuntimeError, match="container"):
|
with pytest.raises(RuntimeError, match="container"):
|
||||||
driver.suspend_vm("200")
|
driver.suspend_vm("200")
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||||
|
def test_resume_posts_status_resume_and_waits(self, driver, api, qmpstatus):
|
||||||
|
guest = api.qemu.return_value
|
||||||
|
guest.status.current.get.return_value = {"status": "running", "qmpstatus": qmpstatus}
|
||||||
|
guest.status.resume.post.return_value = "UPID:resume"
|
||||||
|
driver.resume_vm("web01")
|
||||||
|
guest.status.resume.post.assert_called_once()
|
||||||
|
driver._wait_for_task.assert_called_once_with("UPID:resume", timeout=120)
|
||||||
|
|
||||||
|
def test_resume_on_pve_9_3_sets_the_guests_clock(self, driver, api):
|
||||||
|
"""``sync-time-on-resume``: the guest agent sets the guest's clock (NetOrk/netork#2728)."""
|
||||||
|
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||||
|
guest = api.qemu.return_value
|
||||||
|
guest.status.current.get.return_value = {"status": "running", "qmpstatus": "paused"}
|
||||||
|
driver.resume_vm("100")
|
||||||
|
guest.status.resume.post.assert_called_once_with(**{"sync-time-on-resume": 1})
|
||||||
|
|
||||||
|
def test_resume_on_an_older_node_sends_no_clock_sync(self, driver, api):
|
||||||
|
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
guest = api.qemu.return_value
|
||||||
|
guest.status.current.get.return_value = {"status": "running", "qmpstatus": "paused"}
|
||||||
|
driver.resume_vm("100")
|
||||||
|
guest.status.resume.post.assert_called_once_with()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"current", [{"status": "running", "qmpstatus": "running"}, {"status": "stopped"}]
|
||||||
|
)
|
||||||
|
def test_resume_of_a_guest_that_is_not_paused_is_refused(self, driver, api, current):
|
||||||
|
api.qemu.return_value.status.current.get.return_value = current
|
||||||
|
with pytest.raises(RuntimeError, match="not paused"):
|
||||||
|
driver.resume_vm("100")
|
||||||
|
api.qemu.return_value.status.resume.post.assert_not_called()
|
||||||
|
|
||||||
|
def test_resume_of_a_container_is_refused(self, driver, api):
|
||||||
|
with pytest.raises(RuntimeError, match="container 200"):
|
||||||
|
driver.resume_vm("200")
|
||||||
|
api.lxc.return_value.status.resume.post.assert_not_called()
|
||||||
|
|
||||||
def test_api_error_becomes_runtime_error(self, driver, api):
|
def test_api_error_becomes_runtime_error(self, driver, api):
|
||||||
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
||||||
with pytest.raises(RuntimeError, match="locked"):
|
with pytest.raises(RuntimeError, match="locked"):
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""Which virtual CPU model a new VM gets.
|
||||||
|
|
||||||
|
Created without a ``cpu`` argument, a Proxmox VM falls back to ``kvm64``:
|
||||||
|
no AVX, no AES-NI. MongoDB 5.0 and later will not even start on it, which is
|
||||||
|
how a Graylog provisioned through netOrk failed (netOrk#494). The driver now
|
||||||
|
always names a model, defaulting to ``x86-64-v2-AES`` as the Proxmox GUI does,
|
||||||
|
and lists the alternatives with what each needs from the node's CPU.
|
||||||
|
|
||||||
|
The flag sets below are trimmed from real ``/nodes/{node}/status`` answers in a
|
||||||
|
mixed cluster: a Celeron J3455 (no AVX at all) and an i7-7700 (AVX2).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||||
|
|
||||||
|
CELERON_J3455 = (
|
||||||
|
"fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush "
|
||||||
|
"mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc pni pclmulqdq "
|
||||||
|
"ssse3 cx16 sse4_1 sse4_2 x2apic movbe popcnt aes rdrand lahf_lm 3dnowprefetch "
|
||||||
|
"erms mpx rdseed smap clflushopt sha_ni xsaveopt xsavec xgetbv1"
|
||||||
|
)
|
||||||
|
CORE_I7_7700 = (
|
||||||
|
"fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush "
|
||||||
|
"mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc pni pclmulqdq "
|
||||||
|
"ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand "
|
||||||
|
"lahf_lm abm 3dnowprefetch fsgsbase bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx "
|
||||||
|
"rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _mixin_on(flags: str) -> tuple[ProxmoxVMProvisionMixin, MagicMock, MagicMock]:
|
||||||
|
"""A mixin whose node reports `flags` and that can run a full create."""
|
||||||
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
mixin._node_name = "pve1"
|
||||||
|
|
||||||
|
api = MagicMock()
|
||||||
|
api.cluster.nextid.get.return_value = 120
|
||||||
|
api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
|
||||||
|
|
||||||
|
node = MagicMock()
|
||||||
|
node.status.get.return_value = {"cpuinfo": {"model": "test", "flags": flags}}
|
||||||
|
node.storage.get.return_value = [
|
||||||
|
{"storage": "local-lvm", "type": "lvmthin", "content": "images,rootdir", "enabled": 1},
|
||||||
|
{"storage": "snippets", "type": "dir", "content": "snippets", "enabled": 1},
|
||||||
|
]
|
||||||
|
vm = MagicMock()
|
||||||
|
vm.config.get.return_value = {
|
||||||
|
"unused0": "local-lvm:vm-120-disk-0",
|
||||||
|
"scsi0": "local-lvm:vm-120-disk-0",
|
||||||
|
}
|
||||||
|
vm.status.start.post.return_value = "UPID:pve1:1:start"
|
||||||
|
node.qemu.return_value = vm
|
||||||
|
task = MagicMock()
|
||||||
|
task.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
|
||||||
|
node.tasks.return_value = task
|
||||||
|
|
||||||
|
mixin._api = api
|
||||||
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
|
mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/template/x.qcow2")
|
||||||
|
mixin._run_node_command = MagicMock(return_value="")
|
||||||
|
return mixin, api, node
|
||||||
|
|
||||||
|
|
||||||
|
def _create(mixin: ProxmoxVMProvisionMixin, **kwargs):
|
||||||
|
with patch("time.sleep"):
|
||||||
|
return mixin.create_vm_from_cloud_init(
|
||||||
|
name="graylog-01",
|
||||||
|
image_url="https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img",
|
||||||
|
cpu=2,
|
||||||
|
memory=4096,
|
||||||
|
nics=[{"bridge": "vmbr0"}],
|
||||||
|
cloud_init_config={"hostname": "graylog-01"},
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _by_name(types):
|
||||||
|
return {t["name"]: t for t in types}
|
||||||
|
|
||||||
|
|
||||||
|
class TestListing:
|
||||||
|
def test_offers_the_three_models_in_order(self):
|
||||||
|
mixin, _, _ = _mixin_on(CORE_I7_7700)
|
||||||
|
assert [t["name"] for t in mixin.get_vm_cpu_types()] == [
|
||||||
|
"x86-64-v2-AES",
|
||||||
|
"x86-64-v3",
|
||||||
|
"host",
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_exactly_one_default_and_it_is_what_the_gui_uses(self):
|
||||||
|
mixin, _, _ = _mixin_on(CORE_I7_7700)
|
||||||
|
defaults = [t["name"] for t in mixin.get_vm_cpu_types() if t["default"]]
|
||||||
|
assert defaults == ["x86-64-v2-AES"]
|
||||||
|
|
||||||
|
def test_v3_gives_avx_and_runs_on_a_core_i7(self):
|
||||||
|
mixin, _, _ = _mixin_on(CORE_I7_7700)
|
||||||
|
v3 = _by_name(mixin.get_vm_cpu_types())["x86-64-v3"]
|
||||||
|
assert v3["available"] is True
|
||||||
|
assert {"avx", "avx2"} <= set(v3["features"])
|
||||||
|
|
||||||
|
def test_v3_is_unavailable_on_a_celeron_without_avx(self):
|
||||||
|
mixin, _, _ = _mixin_on(CELERON_J3455)
|
||||||
|
types = _by_name(mixin.get_vm_cpu_types())
|
||||||
|
assert types["x86-64-v3"]["available"] is False
|
||||||
|
assert types["x86-64-v2-AES"]["available"] is True
|
||||||
|
|
||||||
|
def test_v2_aes_has_no_avx(self):
|
||||||
|
mixin, _, _ = _mixin_on(CORE_I7_7700)
|
||||||
|
assert "avx" not in _by_name(mixin.get_vm_cpu_types())["x86-64-v2-AES"]["features"]
|
||||||
|
|
||||||
|
def test_host_passes_the_nodes_own_flags_through(self):
|
||||||
|
"""On a CPU without AVX, `host` gives none either -- a role that needs
|
||||||
|
AVX must not be told `host` would help there."""
|
||||||
|
mixin, _, _ = _mixin_on(CELERON_J3455)
|
||||||
|
host = _by_name(mixin.get_vm_cpu_types())["host"]
|
||||||
|
assert host["available"] is True
|
||||||
|
assert "avx" not in host["features"]
|
||||||
|
assert "aes" in host["features"]
|
||||||
|
|
||||||
|
def test_every_entry_explains_itself(self):
|
||||||
|
mixin, _, _ = _mixin_on(CORE_I7_7700)
|
||||||
|
assert all(t["description"] for t in mixin.get_vm_cpu_types())
|
||||||
|
|
||||||
|
|
||||||
|
class TestCreate:
|
||||||
|
def test_names_the_default_model_instead_of_leaving_kvm64(self):
|
||||||
|
mixin, _, node = _mixin_on(CORE_I7_7700)
|
||||||
|
_create(mixin)
|
||||||
|
assert node.qemu.post.call_args[1]["cpu"] == "x86-64-v2-AES"
|
||||||
|
|
||||||
|
def test_passes_a_chosen_model_through(self):
|
||||||
|
mixin, _, node = _mixin_on(CORE_I7_7700)
|
||||||
|
_create(mixin, cpu_type="host")
|
||||||
|
assert node.qemu.post.call_args[1]["cpu"] == "host"
|
||||||
|
|
||||||
|
def test_refuses_a_model_the_node_cannot_run_before_creating_anything(self):
|
||||||
|
mixin, api, node = _mixin_on(CELERON_J3455)
|
||||||
|
with pytest.raises(ValueError, match="avx"):
|
||||||
|
_create(mixin, cpu_type="x86-64-v3")
|
||||||
|
api.cluster.nextid.get.assert_not_called()
|
||||||
|
node.qemu.post.assert_not_called()
|
||||||
|
|
||||||
|
def test_refuses_an_unknown_model_before_creating_anything(self):
|
||||||
|
mixin, api, node = _mixin_on(CORE_I7_7700)
|
||||||
|
with pytest.raises(ValueError, match="kvm64"):
|
||||||
|
_create(mixin, cpu_type="kvm64")
|
||||||
|
api.cluster.nextid.get.assert_not_called()
|
||||||
|
node.qemu.post.assert_not_called()
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
"""Tests for provisioning through a storage with content type "import".
|
||||||
|
|
||||||
|
Proxmox (8.2+) can download a disk image into such a storage itself
|
||||||
|
(``download-url``, with checksum verification) and attach it to a VM with
|
||||||
|
``import-from``. When the node has one, provisioning uses it instead of
|
||||||
|
downloading over SSH into the node's root filesystem.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
_DEBIAN = "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2"
|
||||||
|
|
||||||
|
|
||||||
|
def _mixin_with_storages(storages: list[dict]) -> tuple[ProxmoxVMProvisionMixin, MagicMock]:
|
||||||
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
mixin._node_name = "pve1"
|
||||||
|
node = MagicMock()
|
||||||
|
node.storage.get.return_value = storages
|
||||||
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
|
return mixin, node
|
||||||
|
|
||||||
|
|
||||||
|
# ── which storage ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_import_storage_picks_a_storage_that_accepts_import():
|
||||||
|
mixin, _ = _mixin_with_storages(
|
||||||
|
[
|
||||||
|
{"storage": "local", "content": "iso,backup,vztmpl,snippets"},
|
||||||
|
{"storage": "software", "content": "import,iso", "active": 1},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert mixin._find_import_storage() == "software"
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_import_storage_does_not_mistake_images_for_import():
|
||||||
|
mixin, _ = _mixin_with_storages([{"storage": "local-zfs", "content": "images,rootdir"}])
|
||||||
|
assert mixin._find_import_storage() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_import_storage_skips_disabled_and_inactive_storages():
|
||||||
|
"""An inactive storage is typically an unmounted share; Proxmox cannot
|
||||||
|
download into it, and the SSH path still works without it."""
|
||||||
|
mixin, _ = _mixin_with_storages(
|
||||||
|
[
|
||||||
|
{"storage": "off", "content": "import", "enabled": 0},
|
||||||
|
{"storage": "unmounted", "content": "import", "active": 0},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert mixin._find_import_storage() is None
|
||||||
|
|
||||||
|
|
||||||
|
# ── what the file is called ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_volume_name_keeps_a_qcow2_extension():
|
||||||
|
name = _import_volume_name(_DEBIAN)
|
||||||
|
assert name is not None
|
||||||
|
assert name.endswith("-debian-12-genericcloud-amd64.qcow2")
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_volume_name_stores_an_img_as_qcow2():
|
||||||
|
"""Proxmox reads the format off the extension and does not accept .img.
|
||||||
|
Ubuntu's .img is qcow2; guessing qcow2 for a raw .img fails loudly at
|
||||||
|
import, while the opposite guess would import a qcow2 container as a raw
|
||||||
|
disk without complaint."""
|
||||||
|
name = _import_volume_name(_UBUNTU)
|
||||||
|
assert name is not None
|
||||||
|
assert name.endswith("-ubuntu-26.04-server-cloudimg-amd64.qcow2")
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_volume_name_is_none_for_types_proxmox_cannot_import():
|
||||||
|
assert _import_volume_name("https://example.org/image.qcow2.xz") is None
|
||||||
|
assert _import_volume_name("https://example.org/installer.iso") is None
|
||||||
|
assert _import_volume_name("https://example.org/noextension") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_volume_name_differs_for_the_same_basename_under_another_url():
|
||||||
|
"""Ubuntu publishes daily builds under one basename; a cache keyed on the
|
||||||
|
basename alone would serve yesterday's build."""
|
||||||
|
a = _import_volume_name("https://x/release-20260927/ubuntu-26.04-server-cloudimg-amd64.img")
|
||||||
|
b = _import_volume_name("https://x/release-20260928/ubuntu-26.04-server-cloudimg-amd64.img")
|
||||||
|
assert a != b
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_volume_name_uses_only_characters_proxmox_keeps():
|
||||||
|
name = _import_volume_name("https://x/My Image (beta)+1.qcow2")
|
||||||
|
assert name is not None
|
||||||
|
assert all(c.isalnum() or c in "-.+=_" for c in name)
|
||||||
|
|
||||||
|
|
||||||
|
# ── the download ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_cloud_image_reuses_a_file_already_in_the_storage():
|
||||||
|
mixin, node = _mixin_with_storages([])
|
||||||
|
name = _import_volume_name(_DEBIAN)
|
||||||
|
node.storage.return_value.content.get.return_value = [
|
||||||
|
{"volid": f"software:import/{name}", "content": "import"}
|
||||||
|
]
|
||||||
|
|
||||||
|
volid = mixin._import_cloud_image("software", name, _DEBIAN, None, timeout=300)
|
||||||
|
|
||||||
|
assert volid == f"software:import/{name}"
|
||||||
|
node.storage.return_value.return_value.post.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_cloud_image_has_proxmox_download_and_verify_it():
|
||||||
|
mixin, node = _mixin_with_storages([])
|
||||||
|
name = _import_volume_name(_UBUNTU)
|
||||||
|
node.storage.return_value.content.get.return_value = []
|
||||||
|
download = node.storage.return_value.return_value
|
||||||
|
download.post.return_value = "UPID:pve1:download"
|
||||||
|
mixin._wait_for_task = MagicMock()
|
||||||
|
|
||||||
|
volid = mixin._import_cloud_image("software", name, _UBUNTU, "sha256:abc123", timeout=300)
|
||||||
|
|
||||||
|
assert volid == f"software:import/{name}"
|
||||||
|
node.storage.assert_any_call("software")
|
||||||
|
node.storage.return_value.assert_called_with("download-url")
|
||||||
|
download.post.assert_called_once_with(
|
||||||
|
url=_UBUNTU,
|
||||||
|
content="import",
|
||||||
|
filename=name,
|
||||||
|
checksum="abc123",
|
||||||
|
**{"checksum-algorithm": "sha256"},
|
||||||
|
)
|
||||||
|
mixin._wait_for_task.assert_called_once_with("UPID:pve1:download", timeout=300)
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_cloud_image_without_checksum_sends_none():
|
||||||
|
mixin, node = _mixin_with_storages([])
|
||||||
|
name = _import_volume_name(_DEBIAN)
|
||||||
|
node.storage.return_value.content.get.return_value = []
|
||||||
|
mixin._wait_for_task = MagicMock()
|
||||||
|
|
||||||
|
mixin._import_cloud_image("software", name, _DEBIAN, None, timeout=300)
|
||||||
|
|
||||||
|
kwargs = node.storage.return_value.return_value.post.call_args.kwargs
|
||||||
|
assert "checksum" not in kwargs
|
||||||
|
assert "checksum-algorithm" not in kwargs
|
||||||
|
|
||||||
|
|
||||||
|
# ── provisioning end to end ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _provisioning_mixin(storages: list[dict]) -> tuple[ProxmoxVMProvisionMixin, MagicMock]:
|
||||||
|
mixin, node = _mixin_with_storages(storages)
|
||||||
|
api = MagicMock()
|
||||||
|
api.cluster.nextid.get.return_value = 101
|
||||||
|
api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
|
||||||
|
mixin._api = api
|
||||||
|
mixin._run_node_command = MagicMock(return_value="")
|
||||||
|
mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/template/x.qcow2")
|
||||||
|
vm = MagicMock()
|
||||||
|
node.qemu.return_value = vm
|
||||||
|
vm.config.get.return_value = {"unused0": "local-zfs:vm-101-disk-0"}
|
||||||
|
vm.config.post.return_value = None
|
||||||
|
node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
|
||||||
|
node.storage.return_value.content.get.return_value = []
|
||||||
|
return mixin, node
|
||||||
|
|
||||||
|
|
||||||
|
def _provision(mixin: ProxmoxVMProvisionMixin, image_url: str) -> None:
|
||||||
|
with patch("time.sleep"):
|
||||||
|
mixin.create_vm_from_cloud_init(
|
||||||
|
name="vm",
|
||||||
|
image_url=image_url,
|
||||||
|
cpu=1,
|
||||||
|
memory=1024,
|
||||||
|
nics=[{"bridge": "vmbr0"}],
|
||||||
|
cloud_init_config={"hostname": "vm"},
|
||||||
|
storage="local-zfs",
|
||||||
|
timeout=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_WITH_IMPORT = [
|
||||||
|
{"storage": "local", "content": "iso,backup,vztmpl,snippets"},
|
||||||
|
{"storage": "software", "content": "import,iso"},
|
||||||
|
{"storage": "local-zfs", "content": "images,rootdir"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_provisioning_downloads_through_the_import_storage_when_there_is_one():
|
||||||
|
mixin, node = _provisioning_mixin(_WITH_IMPORT)
|
||||||
|
name = _import_volume_name(_UBUNTU)
|
||||||
|
|
||||||
|
_provision(mixin, _UBUNTU)
|
||||||
|
|
||||||
|
mixin._download_cloud_image.assert_not_called()
|
||||||
|
assert not any("importdisk" in c.args[0] for c in mixin._run_node_command.call_args_list), (
|
||||||
|
"no SSH download/import when Proxmox can do it"
|
||||||
|
)
|
||||||
|
disk = next(
|
||||||
|
c.kwargs for c in node.qemu.return_value.config.post.call_args_list if "scsi0" in c.kwargs
|
||||||
|
)
|
||||||
|
assert disk["scsi0"] == f"local-zfs:0,import-from=software:import/{name},discard=on"
|
||||||
|
assert disk["boot"] == "order=scsi0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_provisioning_waits_for_the_import_task():
|
||||||
|
"""Attaching with import-from copies the image — a task, which has to
|
||||||
|
finish before the cloud-init drive and the resize touch the VM."""
|
||||||
|
mixin, node = _provisioning_mixin(_WITH_IMPORT)
|
||||||
|
node.qemu.return_value.config.post.side_effect = lambda **kw: (
|
||||||
|
"UPID:pve1:import" if "scsi0" in kw else None
|
||||||
|
)
|
||||||
|
mixin._wait_for_task = MagicMock()
|
||||||
|
|
||||||
|
_provision(mixin, _DEBIAN)
|
||||||
|
|
||||||
|
waited = [c.args[0] for c in mixin._wait_for_task.call_args_list]
|
||||||
|
assert "UPID:pve1:import" in waited
|
||||||
|
|
||||||
|
|
||||||
|
def test_provisioning_falls_back_to_ssh_without_an_import_storage():
|
||||||
|
mixin, _ = _provisioning_mixin([s for s in _WITH_IMPORT if s["storage"] != "software"])
|
||||||
|
|
||||||
|
_provision(mixin, _UBUNTU)
|
||||||
|
|
||||||
|
mixin._download_cloud_image.assert_called_once()
|
||||||
|
assert any("qm importdisk 101" in c.args[0] for c in mixin._run_node_command.call_args_list)
|
||||||
|
|
||||||
|
|
||||||
|
def test_provisioning_falls_back_to_ssh_for_an_image_type_proxmox_cannot_import():
|
||||||
|
mixin, _ = _provisioning_mixin(_WITH_IMPORT)
|
||||||
|
|
||||||
|
_provision(mixin, "https://example.org/image.qcow2.xz")
|
||||||
|
|
||||||
|
mixin._download_cloud_image.assert_called_once()
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
"""Moving a guest to another node: preflight, migration, HA maintenance mode.
|
||||||
|
|
||||||
|
Payloads: ``GET /nodes/{node}/qemu/{vmid}/migrate`` follows qemu-server's
|
||||||
|
``migrate_vm_precondition`` (PVE 9: ``not_allowed_nodes`` may name
|
||||||
|
``unavailable_storages``, ``unavailable-resources`` and
|
||||||
|
``blocking-ha-resources``); the task log follows ``/nodes/{node}/tasks/{upid}/log``
|
||||||
|
(``n``/``t`` rows). A guest that HA manages migrates through a ``hamigrate``
|
||||||
|
task that only hands the request to the HA manager.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.test_clusters import CLUSTER_RESOURCES, CLUSTER_STATUS, GIB, _api, _driver, _storage_row
|
||||||
|
|
||||||
|
QEMU_LIST = [
|
||||||
|
{"vmid": 100, "name": "web", "status": "running", "maxmem": 4 * GIB},
|
||||||
|
{"vmid": 102, "name": "idle", "status": "stopped", "maxmem": 2 * GIB},
|
||||||
|
]
|
||||||
|
LXC_LIST = [{"vmid": "101", "name": "dns", "status": "running", "type": "lxc"}]
|
||||||
|
|
||||||
|
PREFLIGHT_RUNNING = {
|
||||||
|
"running": 1,
|
||||||
|
"allowed_nodes": ["pve2", "pve3"],
|
||||||
|
"not_allowed_nodes": {},
|
||||||
|
"local_disks": [
|
||||||
|
{
|
||||||
|
"volid": "local-lvm:vm-100-disk-0",
|
||||||
|
"size": 32 * GIB,
|
||||||
|
"drivename": "scsi0",
|
||||||
|
"is_attached": 1,
|
||||||
|
"referenced_in_config": 1,
|
||||||
|
},
|
||||||
|
{"volid": "local:iso/debian-13.iso", "cdrom": 1, "size": 700 * 1024**2},
|
||||||
|
# Regenerated on the target: neither a disk to copy nor a blocker.
|
||||||
|
{"volid": "local-lvm:vm-100-cloudinit", "cdrom": 1, "size": 4 * 1024**2},
|
||||||
|
],
|
||||||
|
"local_resources": [],
|
||||||
|
"mapped-resources": [],
|
||||||
|
"mapped-resource-info": {},
|
||||||
|
"has-dbus-vmstate": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
PREFLIGHT_BLOCKED = {
|
||||||
|
"running": 0,
|
||||||
|
"allowed_nodes": [],
|
||||||
|
"not_allowed_nodes": {
|
||||||
|
"pve2": {"unavailable_storages": ["local-zfs"]},
|
||||||
|
"pve3": {
|
||||||
|
"blocking-ha-resources": [{"sid": "vm:101", "cause": "resource-affinity"}],
|
||||||
|
"unavailable-resources": ["gpu-a"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"local_disks": [],
|
||||||
|
"local_resources": ["hostpci0", "usb0"],
|
||||||
|
"mapped-resources": ["gpu-a"],
|
||||||
|
"mapped-resource-info": {"gpu-a": {"live-migration": 0}},
|
||||||
|
"has-dbus-vmstate": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
LXC_CONFIG = {
|
||||||
|
"hostname": "dns",
|
||||||
|
"rootfs": "local-lvm:vm-101-disk-0,size=8G",
|
||||||
|
"mp0": "ceph-vm:vm-101-disk-1,mp=/data,size=32G",
|
||||||
|
"mp1": "/srv/share,mp=/share",
|
||||||
|
"mp2": "/mnt/nfs,mp=/nfs,shared=1",
|
||||||
|
"unused0": "local-lvm:vm-101-disk-2",
|
||||||
|
"net0": "name=eth0,bridge=vmbr0,ip=dhcp",
|
||||||
|
"digest": "abc",
|
||||||
|
}
|
||||||
|
|
||||||
|
UPID_QEMU = "UPID:pve1:000ABCDE:0123ABCD:672AB000:qmigrate:100:root@pam:"
|
||||||
|
UPID_LXC = "UPID:pve1:000ABCDF:0123ABCE:672AB001:vzmigrate:101:root@pam:"
|
||||||
|
UPID_HA = "UPID:pve1:000ABCE0:0123ABCF:672AB002:hamigrate:100:root@pam:"
|
||||||
|
|
||||||
|
FAILED_LOG = [
|
||||||
|
{"n": 1, "t": "2026-11-01 10:00:00 starting migration of VM 100 to node 'pve2' (10.0.0.2)"},
|
||||||
|
{"n": 2, "t": "2026-11-01 10:00:01 starting VM 100 on remote node 'pve2'"},
|
||||||
|
{
|
||||||
|
"n": 3,
|
||||||
|
"t": "2026-11-01 10:00:02 ERROR: online migrate failure - remote command failed "
|
||||||
|
"with exit code 255",
|
||||||
|
},
|
||||||
|
{"n": 4, "t": "2026-11-01 10:00:02 aborting phase 2 - cleanup resources"},
|
||||||
|
{
|
||||||
|
"n": 5,
|
||||||
|
"t": "2026-11-01 10:00:03 ERROR: migration finished with problems (duration 00:00:03)",
|
||||||
|
},
|
||||||
|
{"n": 6, "t": "TASK ERROR: migration problems"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _migration_api(
|
||||||
|
preflight: dict[str, Any] | None = None,
|
||||||
|
task: dict[str, Any] | None = None,
|
||||||
|
log: list[dict[str, Any]] | None = None,
|
||||||
|
status: list[dict[str, Any]] | None = None,
|
||||||
|
) -> tuple[MagicMock, MagicMock]:
|
||||||
|
resources = [
|
||||||
|
*CLUSTER_RESOURCES,
|
||||||
|
_storage_row("pve1", "local", "dir", 0, "iso,vztmpl,backup", 100 * GIB, 20 * GIB),
|
||||||
|
]
|
||||||
|
api = _api(cluster_status=status, resources=resources)
|
||||||
|
node = api.nodes("pve1")
|
||||||
|
node.qemu.get.return_value = QEMU_LIST
|
||||||
|
node.lxc.get.return_value = LXC_LIST
|
||||||
|
node.qemu.return_value.migrate.get.return_value = preflight or PREFLIGHT_RUNNING
|
||||||
|
node.qemu.return_value.migrate.post.return_value = UPID_QEMU
|
||||||
|
node.lxc.return_value.migrate.post.return_value = UPID_LXC
|
||||||
|
node.lxc.return_value.status.current.get.return_value = {"status": "running", "vmid": 101}
|
||||||
|
node.lxc.return_value.config.get.return_value = LXC_CONFIG
|
||||||
|
node.tasks.return_value.status.get.return_value = task or {
|
||||||
|
"status": "stopped",
|
||||||
|
"exitstatus": "OK",
|
||||||
|
}
|
||||||
|
node.tasks.return_value.log.get.return_value = log or []
|
||||||
|
return api, node
|
||||||
|
|
||||||
|
|
||||||
|
class TestPreflightQemu:
|
||||||
|
def test_allowed_nodes_and_local_disks(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
result = _driver(api).get_vm_migration_preflight("web")
|
||||||
|
assert result == {
|
||||||
|
"running": True,
|
||||||
|
# pve3 is offline: the platform would allow it, it cannot take the VM now.
|
||||||
|
"allowed_nodes": ["pve2"],
|
||||||
|
"refused_nodes": {"pve3": "node offline"},
|
||||||
|
"local_disks": ["local-lvm:vm-100-disk-0"],
|
||||||
|
# A local ISO in a CD drive stops the migration.
|
||||||
|
"local_resources": ["cdrom=local:iso/debian-13.iso"],
|
||||||
|
}
|
||||||
|
node.qemu.assert_any_call(100)
|
||||||
|
|
||||||
|
def test_refusal_reasons_in_plain_words(self):
|
||||||
|
all_online = [dict(s, online=1) if s["type"] == "node" else s for s in CLUSTER_STATUS]
|
||||||
|
api, _ = _migration_api(preflight=PREFLIGHT_BLOCKED, status=all_online)
|
||||||
|
result = _driver(api).get_vm_migration_preflight("100")
|
||||||
|
assert result["running"] is False
|
||||||
|
assert result["allowed_nodes"] == []
|
||||||
|
assert result["refused_nodes"] == {
|
||||||
|
"pve2": "storage local-zfs is not available there",
|
||||||
|
"pve3": "HA resource vm:101 blocks it (resource-affinity rule); "
|
||||||
|
"mapped resource gpu-a is not available there",
|
||||||
|
}
|
||||||
|
assert result["local_resources"] == ["hostpci0", "usb0"]
|
||||||
|
|
||||||
|
def test_unknown_reason_is_passed_on(self):
|
||||||
|
preflight = {
|
||||||
|
"running": 0,
|
||||||
|
"allowed_nodes": [],
|
||||||
|
"not_allowed_nodes": {"pve2": {"some-future-check": ["x", "y"]}},
|
||||||
|
"local_disks": [],
|
||||||
|
"local_resources": [],
|
||||||
|
}
|
||||||
|
api, _ = _migration_api(preflight=preflight)
|
||||||
|
refused = _driver(api).get_vm_migration_preflight("web")["refused_nodes"]
|
||||||
|
assert refused["pve2"] == "some-future-check: x, y"
|
||||||
|
|
||||||
|
def test_unknown_guest(self):
|
||||||
|
api, _ = _migration_api()
|
||||||
|
with pytest.raises(ValueError, match="nope"):
|
||||||
|
_driver(api).get_vm_migration_preflight("nope")
|
||||||
|
|
||||||
|
|
||||||
|
class TestPreflightLxc:
|
||||||
|
def test_members_and_local_volumes(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
result = _driver(api).get_vm_migration_preflight("dns")
|
||||||
|
assert result == {
|
||||||
|
"running": True,
|
||||||
|
"allowed_nodes": ["pve2"],
|
||||||
|
"refused_nodes": {"pve3": "node offline"},
|
||||||
|
# ceph-vm is shared; local-lvm is not.
|
||||||
|
"local_disks": ["local-lvm:vm-101-disk-0", "local-lvm:vm-101-disk-2"],
|
||||||
|
# A bind mount that is not marked shared stops the migration.
|
||||||
|
"local_resources": ["mp1"],
|
||||||
|
}
|
||||||
|
node.qemu.return_value.migrate.get.assert_not_called()
|
||||||
|
|
||||||
|
def test_stopped_container(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
node.lxc.return_value.status.current.get.return_value = {"status": "stopped"}
|
||||||
|
assert _driver(api).get_vm_migration_preflight("101")["running"] is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestMigrateQemu:
|
||||||
|
def test_running_vm_moves_online_with_its_local_disks(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
node.qemu.return_value.migrate.post.assert_called_once_with(
|
||||||
|
target="pve2", online=1, **{"with-local-disks": 1}
|
||||||
|
)
|
||||||
|
node.tasks.assert_called_with(UPID_QEMU)
|
||||||
|
|
||||||
|
def test_target_storage_and_offline(self):
|
||||||
|
preflight = dict(PREFLIGHT_RUNNING, local_disks=[])
|
||||||
|
api, node = _migration_api(preflight=preflight)
|
||||||
|
_driver(api).migrate_vm("web", "pve2", online=False, target_storage="ceph-vm")
|
||||||
|
node.qemu.return_value.migrate.post.assert_called_once_with(
|
||||||
|
target="pve2", targetstorage="ceph-vm"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stopped_vm_is_not_moved_online(self):
|
||||||
|
preflight = dict(PREFLIGHT_RUNNING, running=0, local_disks=[])
|
||||||
|
api, node = _migration_api(preflight=preflight)
|
||||||
|
_driver(api).migrate_vm("idle", "pve2")
|
||||||
|
node.qemu.return_value.migrate.post.assert_called_once_with(target="pve2")
|
||||||
|
|
||||||
|
def test_failure_raises_with_the_task_logs_errors(self):
|
||||||
|
api, node = _migration_api(
|
||||||
|
task={"status": "stopped", "exitstatus": "migration problems"}, log=FAILED_LOG
|
||||||
|
)
|
||||||
|
with pytest.raises(RuntimeError) as exc:
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
message = str(exc.value)
|
||||||
|
assert "online migrate failure - remote command failed with exit code 255" in message
|
||||||
|
assert "migration finished with problems (duration 00:00:03)" in message
|
||||||
|
assert "starting VM 100" not in message
|
||||||
|
node.tasks.return_value.log.get.assert_called_once()
|
||||||
|
|
||||||
|
def test_failure_without_error_lines_keeps_the_task_status(self):
|
||||||
|
api, _ = _migration_api(
|
||||||
|
task={"status": "stopped", "exitstatus": "migration aborted"},
|
||||||
|
log=[{"n": 1, "t": "starting migration"}],
|
||||||
|
)
|
||||||
|
with pytest.raises(RuntimeError, match="migration aborted"):
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
|
||||||
|
def test_refused_request_raises(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
node.qemu.return_value.migrate.post.side_effect = RuntimeError(
|
||||||
|
"500 Internal Server Error: VM is locked (backup)"
|
||||||
|
)
|
||||||
|
with pytest.raises(RuntimeError, match="VM is locked"):
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
|
||||||
|
|
||||||
|
class TestMigrateLxc:
|
||||||
|
def test_running_container_moves_in_restart_mode(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
_driver(api).migrate_vm("dns", "pve2", target_storage="local-lvm")
|
||||||
|
node.lxc.return_value.migrate.post.assert_called_once_with(
|
||||||
|
target="pve2", restart=1, **{"target-storage": "local-lvm"}
|
||||||
|
)
|
||||||
|
node.tasks.assert_called_with(UPID_LXC)
|
||||||
|
|
||||||
|
def test_stopped_container(self):
|
||||||
|
api, node = _migration_api()
|
||||||
|
node.lxc.return_value.status.current.get.return_value = {"status": "stopped"}
|
||||||
|
_driver(api).migrate_vm("dns", "pve2")
|
||||||
|
node.lxc.return_value.migrate.post.assert_called_once_with(target="pve2")
|
||||||
|
|
||||||
|
|
||||||
|
class TestTargetRefusedBeforeTheApi:
|
||||||
|
@pytest.mark.parametrize("target", ["pve1", "pve9", "pve2; reboot"])
|
||||||
|
def test_not_another_member(self, target):
|
||||||
|
api, node = _migration_api()
|
||||||
|
with pytest.raises(ValueError, match="not another member"):
|
||||||
|
_driver(api).migrate_vm("web", target)
|
||||||
|
node.qemu.return_value.migrate.post.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def _ha_status(node: str, crm_state: str) -> list[dict[str, Any]]:
|
||||||
|
return [
|
||||||
|
{"id": "quorum", "type": "quorum", "node": "pve1", "quorate": 1, "status": "OK"},
|
||||||
|
{
|
||||||
|
"id": "service:vm:100",
|
||||||
|
"type": "service",
|
||||||
|
"sid": "vm:100",
|
||||||
|
"node": node,
|
||||||
|
"crm_state": crm_state,
|
||||||
|
"state": crm_state,
|
||||||
|
"status": f"vm:100 ({node}, {crm_state})",
|
||||||
|
"request_state": "started",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestMigrateHaManaged:
|
||||||
|
"""PVE hands an HA guest's migration to the HA manager: the hamigrate task only
|
||||||
|
queues the request, so the driver follows the HA manager until the guest is there."""
|
||||||
|
|
||||||
|
def _api(self, states: list[list[dict[str, Any]]]) -> tuple[MagicMock, MagicMock]:
|
||||||
|
api, node = _migration_api()
|
||||||
|
node.qemu.return_value.migrate.post.return_value = UPID_HA
|
||||||
|
api.cluster.ha.status.current.get.side_effect = states
|
||||||
|
return api, node
|
||||||
|
|
||||||
|
def test_waits_until_the_guest_runs_on_the_target(self):
|
||||||
|
api, _ = self._api(
|
||||||
|
[
|
||||||
|
_ha_status("pve1", "started"),
|
||||||
|
_ha_status("pve1", "migrate"),
|
||||||
|
_ha_status("pve2", "started"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
with patch("napalm_proxmox.vm_migrate_mixin.sleep") as sleep:
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
assert api.cluster.ha.status.current.get.call_count == 3
|
||||||
|
assert sleep.call_count == 2
|
||||||
|
|
||||||
|
def test_back_on_the_source_node_is_a_failure_with_the_migration_log(self):
|
||||||
|
api, node = self._api([_ha_status("pve1", "migrate"), _ha_status("pve1", "started")])
|
||||||
|
node.tasks.get.return_value = [
|
||||||
|
{
|
||||||
|
"upid": UPID_QEMU,
|
||||||
|
"type": "qmigrate",
|
||||||
|
"id": "100",
|
||||||
|
"starttime": 0x672AB002 + 12,
|
||||||
|
"status": "migration problems",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
node.tasks.return_value.log.get.return_value = FAILED_LOG
|
||||||
|
with patch("napalm_proxmox.vm_migrate_mixin.sleep"):
|
||||||
|
with pytest.raises(RuntimeError, match="online migrate failure"):
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
node.tasks.get.assert_called_once_with(vmid=100, typefilter="qmigrate", limit=1)
|
||||||
|
|
||||||
|
def test_error_state_raises(self):
|
||||||
|
api, node = self._api([_ha_status("pve1", "error")])
|
||||||
|
node.tasks.get.return_value = []
|
||||||
|
with patch("napalm_proxmox.vm_migrate_mixin.sleep"):
|
||||||
|
with pytest.raises(RuntimeError, match="error"):
|
||||||
|
_driver(api).migrate_vm("web", "pve2")
|
||||||
|
|
||||||
|
def test_times_out(self):
|
||||||
|
api, _ = self._api([_ha_status("pve1", "migrate")] * 50)
|
||||||
|
clock = iter(range(0, 10000, 30))
|
||||||
|
with (
|
||||||
|
patch("napalm_proxmox.vm_migrate_mixin.sleep"),
|
||||||
|
patch("napalm_proxmox.vm_migrate_mixin.monotonic", lambda: next(clock)),
|
||||||
|
):
|
||||||
|
with pytest.raises(RuntimeError, match="timed out"):
|
||||||
|
_driver(api).migrate_vm("web", "pve2", timeout=120)
|
||||||
|
|
||||||
|
|
||||||
|
class TestNodeMaintenance:
|
||||||
|
def _driver(self) -> tuple[Any, MagicMock]:
|
||||||
|
api, _ = _migration_api()
|
||||||
|
drv = _driver(api)
|
||||||
|
drv._node_ssh = MagicMock() # type: ignore[method-assign]
|
||||||
|
drv._run_node_command = MagicMock(return_value="") # type: ignore[method-assign]
|
||||||
|
return drv, drv._run_node_command
|
||||||
|
|
||||||
|
def test_enable(self):
|
||||||
|
drv, run = self._driver()
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
run.assert_called_once_with(
|
||||||
|
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_disable(self):
|
||||||
|
drv, run = self._driver()
|
||||||
|
drv.set_node_maintenance("pve3", False)
|
||||||
|
run.assert_called_once_with(
|
||||||
|
"ha-manager crm-command node-maintenance disable pve3", timeout=drv.timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("node", ["pve9", "pve2; reboot", "$(reboot)"])
|
||||||
|
def test_not_a_member_runs_nothing(self, node):
|
||||||
|
drv, run = self._driver()
|
||||||
|
with pytest.raises(ValueError, match="not a member"):
|
||||||
|
drv.set_node_maintenance(node, True)
|
||||||
|
run.assert_not_called()
|
||||||
|
|
||||||
|
def test_no_ssh(self):
|
||||||
|
drv, run = self._driver()
|
||||||
|
drv._node_ssh.side_effect = OSError("Authentication failed")
|
||||||
|
with pytest.raises(RuntimeError, match="SSH"):
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
run.assert_not_called()
|
||||||
|
|
||||||
|
def test_command_refused(self):
|
||||||
|
drv, run = self._driver()
|
||||||
|
run.side_effect = RuntimeError("Command failed (exit 255): ...\nno such node 'pve2'")
|
||||||
|
with pytest.raises(RuntimeError, match="no such node"):
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
|
||||||
|
|
||||||
|
class TestNodeMaintenanceOverRest:
|
||||||
|
"""PVE 9.3 has ``PUT /nodes/{node}/maintenance``: no SSH session at all."""
|
||||||
|
|
||||||
|
def _driver(self, version: str = "9.3.0") -> tuple[Any, MagicMock]:
|
||||||
|
api, _ = _migration_api()
|
||||||
|
api.version.get.return_value = {"version": version, "release": version[:3]}
|
||||||
|
api.nodes("pve2").version.get.return_value = {"version": version, "release": version[:3]}
|
||||||
|
drv = _driver(api)
|
||||||
|
drv._node_ssh = MagicMock() # type: ignore[method-assign]
|
||||||
|
drv._run_node_command = MagicMock(return_value="") # type: ignore[method-assign]
|
||||||
|
return drv, api
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("enabled", "mode"), [(True, "enable"), (False, "disable")])
|
||||||
|
def test_puts_the_mode_and_opens_no_ssh(self, enabled, mode):
|
||||||
|
drv, api = self._driver()
|
||||||
|
drv.set_node_maintenance("pve2", enabled)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_called_once_with(**{"maintenance-mode": mode})
|
||||||
|
drv._node_ssh.assert_not_called()
|
||||||
|
drv._run_node_command.assert_not_called()
|
||||||
|
|
||||||
|
def test_not_a_member_puts_nothing(self):
|
||||||
|
drv, api = self._driver()
|
||||||
|
with pytest.raises(ValueError, match="not a member"):
|
||||||
|
drv.set_node_maintenance("pve9", True)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
|
|
||||||
|
def test_refused(self):
|
||||||
|
drv, api = self._driver()
|
||||||
|
api.nodes("pve2").maintenance.put.side_effect = Exception(
|
||||||
|
"403 Forbidden: Permission check failed (/, Sys.Modify)"
|
||||||
|
)
|
||||||
|
with pytest.raises(RuntimeError, match="Sys.Modify"):
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
drv._node_ssh.assert_not_called()
|
||||||
|
|
||||||
|
def test_older_node_uses_ha_manager_over_ssh(self):
|
||||||
|
drv, api = self._driver("9.2.4")
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
drv._run_node_command.assert_called_once_with(
|
||||||
|
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||||
|
)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
|
|
||||||
|
def test_the_target_nodes_version_decides_mid_upgrade(self):
|
||||||
|
# A rolling upgrade: the node the driver is connected to runs 9.3 already,
|
||||||
|
# the one going into maintenance does not, and has no endpoint to proxy to.
|
||||||
|
drv, api = self._driver("9.3.0")
|
||||||
|
api.nodes("pve2").version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
drv._run_node_command.assert_called_once_with(
|
||||||
|
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||||
|
)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
|
|
||||||
|
def test_an_unreadable_target_version_is_a_runtime_error(self):
|
||||||
|
drv, api = self._driver()
|
||||||
|
api.nodes("pve2").version.get.side_effect = ConnectionError("pve2 unreachable")
|
||||||
|
with pytest.raises(RuntimeError, match="pve2"):
|
||||||
|
drv.set_node_maintenance("pve2", True)
|
||||||
|
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||||
@@ -3,12 +3,12 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from unittest.mock import MagicMock, patch
|
from napalm_device_types.provisioning import VMProvisionIncomplete
|
||||||
from napalm_proxmox.driver import ProxmoxDriver
|
|
||||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
|
||||||
|
|
||||||
|
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Tests
|
# Tests
|
||||||
@@ -221,7 +221,8 @@ def test_create_vm_from_cloud_init_dual_nic_trunk():
|
|||||||
|
|
||||||
|
|
||||||
def test_create_vm_missing_snippet_storage():
|
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 = ProxmoxVMProvisionMixin()
|
||||||
mixin._node_name = "pve1"
|
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_task.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
|
||||||
mock_node.tasks.return_value = mock_task
|
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"):
|
with patch("napalm_proxmox.vm_provision_mixin.time.sleep"):
|
||||||
mixin.create_vm_from_cloud_init(
|
mixin.create_vm_from_cloud_init(
|
||||||
name="test-vm",
|
name="test-vm",
|
||||||
@@ -261,6 +262,8 @@ def test_create_vm_missing_snippet_storage():
|
|||||||
nics=[{"bridge": "vmbr0"}],
|
nics=[{"bridge": "vmbr0"}],
|
||||||
cloud_init_config={},
|
cloud_init_config={},
|
||||||
)
|
)
|
||||||
|
assert isinstance(caught.value.__cause__, ValueError)
|
||||||
|
assert caught.value.vmid == "101"
|
||||||
|
|
||||||
|
|
||||||
def test_create_vm_with_disk_resize():
|
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 config
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0,tag=10"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
||||||
# reached via agent(...) as a callable resource, not dotted attribute
|
# reached via agent(...) as a callable resource, not dotted attribute
|
||||||
@@ -372,7 +375,7 @@ def test_get_vm_status_skips_loopback_interface():
|
|||||||
|
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
mock_agent_call = MagicMock()
|
mock_agent_call = MagicMock()
|
||||||
mock_vm.agent.return_value = mock_agent_call
|
mock_vm.agent.return_value = mock_agent_call
|
||||||
@@ -407,7 +410,7 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
|||||||
# Mock VM config
|
# Mock VM config
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
# Mock guest-agent that never returns IP
|
# Mock guest-agent that never returns IP
|
||||||
mock_agent_call = MagicMock()
|
mock_agent_call = MagicMock()
|
||||||
@@ -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)
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
||||||
|
|
||||||
|
|
||||||
|
_RUNNING = {"status": "running", "qmpstatus": "running"}
|
||||||
|
_ETH0 = {
|
||||||
|
"name": "eth0",
|
||||||
|
"hardware-address": "aa:bb:cc:dd:ee:00",
|
||||||
|
"ip-addresses": [{"ip-address": "10.0.0.100", "ip-address-type": "ipv4"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _status_of(current, interfaces=()):
|
||||||
|
"""A mixin whose VM 101 answers ``status/current`` with *current*."""
|
||||||
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
node = MagicMock()
|
||||||
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
if isinstance(current, list):
|
||||||
|
vm.status.current.get.side_effect = current
|
||||||
|
else:
|
||||||
|
vm.status.current.get.return_value = current
|
||||||
|
vm.agent.return_value.get.return_value = {"result": list(interfaces)}
|
||||||
|
return mixin, vm
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheStatusIsWhatProxmoxSays:
|
||||||
|
"""``status/current``, not whether the config reads (NAPALM/napalm-proxmox#72).
|
||||||
|
|
||||||
|
The guest agent is asked for an address only while the VM runs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_a_stopped_vm_is_stopped(self):
|
||||||
|
mixin, vm = _status_of({"status": "stopped", "qmpstatus": "stopped"})
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "stopped"}
|
||||||
|
vm.status.current.get.assert_called_once_with()
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||||
|
def test_a_paused_vm_is_paused(self, qmpstatus):
|
||||||
|
mixin, vm = _status_of({"status": "running", "qmpstatus": qmpstatus})
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "paused"}
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
def test_a_running_vm_is_running_with_its_address(self):
|
||||||
|
mixin, _vm = _status_of(_RUNNING, [_ETH0])
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {
|
||||||
|
"status": "running",
|
||||||
|
"ip_address": "10.0.0.100",
|
||||||
|
"hostname": "eth0",
|
||||||
|
"mac_address": "aa:bb:cc:dd:ee:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_a_running_vm_whose_agent_does_not_answer_is_running(self):
|
||||||
|
mixin, vm = _status_of(_RUNNING)
|
||||||
|
vm.agent.return_value.get.side_effect = Exception("QEMU guest agent is not running")
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "running"}
|
||||||
|
|
||||||
|
def test_a_vm_proxmox_does_not_have_is_unknown(self):
|
||||||
|
mixin, vm = _status_of({})
|
||||||
|
vm.status.current.get.side_effect = Exception("Configuration file does not exist")
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("999") == {"status": "unknown"}
|
||||||
|
|
||||||
|
def test_waiting_for_an_address_ends_when_the_vm_stops(self):
|
||||||
|
"""A VM that stopped will report no address: the wait ends with an error at once."""
|
||||||
|
mixin, vm = _status_of([_RUNNING, {"status": "stopped"}])
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="stopped"):
|
||||||
|
with patch("time.sleep"):
|
||||||
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
assert vm.agent.return_value.get.call_count == 1
|
||||||
|
|
||||||
|
def test_waiting_for_an_address_of_a_paused_vm_does_not_ask_the_agent(self):
|
||||||
|
mixin, vm = _status_of({"status": "running", "qmpstatus": "paused"})
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="paused"):
|
||||||
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
def test_waiting_reads_the_status_again_on_each_round(self):
|
||||||
|
mixin, vm = _status_of([_RUNNING, _RUNNING, _RUNNING])
|
||||||
|
vm.agent.return_value.get.side_effect = [
|
||||||
|
{"result": []},
|
||||||
|
{"result": []},
|
||||||
|
{"result": [_ETH0]},
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("time.sleep"):
|
||||||
|
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
|
||||||
|
assert result["ip_address"] == "10.0.0.100"
|
||||||
|
assert vm.status.current.get.call_count == 3
|
||||||
|
|
||||||
|
def test_a_status_that_does_not_read_while_waiting_keeps_the_wait_going(self):
|
||||||
|
mixin, vm = _status_of([_RUNNING, Exception("timed out"), _RUNNING])
|
||||||
|
vm.agent.return_value.get.side_effect = [
|
||||||
|
{"result": []},
|
||||||
|
{"result": []},
|
||||||
|
{"result": [_ETH0]},
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("time.sleep"):
|
||||||
|
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
|
||||||
|
assert result["ip_address"] == "10.0.0.100"
|
||||||
|
|
||||||
|
|
||||||
def test_destroy_vm_success():
|
def test_destroy_vm_success():
|
||||||
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
@@ -459,7 +570,13 @@ def test_destroy_vm_success():
|
|||||||
|
|
||||||
|
|
||||||
def test_destroy_vm_already_stopped():
|
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()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
|
||||||
mock_node = MagicMock()
|
mock_node = MagicMock()
|
||||||
@@ -468,6 +585,7 @@ def test_destroy_vm_already_stopped():
|
|||||||
# Mock VM operations
|
# Mock VM operations
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
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.config.get.return_value = {}
|
||||||
mock_vm.delete.return_value = None
|
mock_vm.delete.return_value = None
|
||||||
|
|
||||||
@@ -478,6 +596,42 @@ def test_destroy_vm_already_stopped():
|
|||||||
assert mock_vm.delete.called
|
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
|
# 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():
|
def test_run_node_command_success_returns_stdout():
|
||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
mixin._ssh_client = MagicMock()
|
ssh = MagicMock()
|
||||||
mixin._ssh_client.exec_command.return_value = _mock_ssh_exec(0, stdout_text="hello\n")
|
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)
|
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():
|
def test_run_node_command_nonzero_exit_raises():
|
||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
mixin._ssh_client = MagicMock()
|
ssh = MagicMock()
|
||||||
mixin._ssh_client.exec_command.return_value = _mock_ssh_exec(
|
ssh.exec_command.return_value = _mock_ssh_exec(1, stderr_text="No such file or directory")
|
||||||
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"):
|
with pytest.raises(RuntimeError, match="No such file or directory"):
|
||||||
mixin._run_node_command("cat /nonexistent", timeout=10)
|
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])
|
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]["ide2"] == "local-zfs:cloudinit"
|
||||||
assert cloud_init_call[1]["cicustom"].startswith("user=local:snippets/")
|
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