Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -7,6 +7,103 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [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
|
## [0.9.0] - 2026-11-02
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ device = driver(
|
|||||||
| `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` |
|
||||||
@@ -126,6 +126,11 @@ device = driver(
|
|||||||
| `traceroute` | `traceroute -n` over SSH |
|
| `traceroute` | `traceroute -n` over SSH |
|
||||||
| `cli` | Arbitrary commands over SSH (stdout) |
|
| `cli` | Arbitrary commands over SSH (stdout) |
|
||||||
| `get_route_to` | `ip route show` over SSH |
|
| `get_route_to` | `ip route show` over SSH |
|
||||||
|
| `get_scheduled_jobs` | cron, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers, as root over SSH (napalm-device-types' `PosixScheduledJobsMixin`); `pve-*` units, `pvesr.timer` and `/etc/cron.d/vzdump` are `platform` |
|
||||||
|
| `manage_scheduled_job(key, action, digest=)` | enable, disable, run now; a `/etc/cron.d/vzdump` line only runs |
|
||||||
|
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
|
||||||
|
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
||||||
|
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
||||||
|
|
||||||
**Not implemented** (raise `NotImplementedError`):
|
**Not implemented** (raise `NotImplementedError`):
|
||||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||||
@@ -184,6 +189,8 @@ the disks and ZFS pools the server manages itself.
|
|||||||
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
||||||
| `get_licenses` | `pbs-subscription` |
|
| `get_licenses` | `pbs-subscription` |
|
||||||
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
||||||
|
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
||||||
|
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
||||||
|
|
||||||
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
||||||
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
||||||
@@ -237,7 +244,8 @@ 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_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from napalm_device_types import (
|
|||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
PortSpec,
|
PortSpec,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
@@ -40,6 +41,10 @@ from napalm_proxmox._base import ProxmoxBase
|
|||||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
|
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
|
||||||
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
||||||
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -50,17 +55,22 @@ PBS_NODE = "localhost"
|
|||||||
class ProxmoxBackupDriver(
|
class ProxmoxBackupDriver(
|
||||||
ProxmoxBase,
|
ProxmoxBase,
|
||||||
ProxmoxBackupServerMixin,
|
ProxmoxBackupServerMixin,
|
||||||
|
PbsRunningBackupsMixin,
|
||||||
ProxmoxPbsHostMixin,
|
ProxmoxPbsHostMixin,
|
||||||
ProxmoxHostMixin,
|
ProxmoxHostMixin,
|
||||||
|
ProxmoxTimeSyncMixin,
|
||||||
BackupServerDriver,
|
BackupServerDriver,
|
||||||
StorageDriver,
|
StorageDriver,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
|
ProxmoxScheduledJobsMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
|
ProxmoxZabbixAgentMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
@@ -76,6 +86,8 @@ class ProxmoxBackupDriver(
|
|||||||
#: A PBS upgrades like a PVE node: a plain ``apt-get upgrade`` holds back
|
#: A PBS upgrades like a PVE node: a plain ``apt-get upgrade`` holds back
|
||||||
#: what needs new or removed packages.
|
#: what needs new or removed packages.
|
||||||
FULL_UPGRADE = True
|
FULL_UPGRADE = True
|
||||||
|
#: The backup server's own timer is ``platform``.
|
||||||
|
PLATFORM_SOURCES = PBS_PLATFORM_SOURCES
|
||||||
PORT_SPECS = [
|
PORT_SPECS = [
|
||||||
PortSpec("https", 8007, weight=8.0),
|
PortSpec("https", 8007, weight=8.0),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ if TYPE_CHECKING:
|
|||||||
# Type-only: the cluster models are newer than the napalm_device_types floor
|
# Type-only: the cluster models are newer than the napalm_device_types floor
|
||||||
# in pyproject.toml, and nothing here needs them at runtime.
|
# in pyproject.toml, and nothing here needs them at runtime.
|
||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
|
BackupServerRefDict,
|
||||||
ClusterDict,
|
ClusterDict,
|
||||||
ClusterNetworkDict,
|
ClusterNetworkDict,
|
||||||
ClusterNodeDict,
|
ClusterNodeDict,
|
||||||
@@ -94,6 +95,35 @@ def _storages(resources: list[_JsonDict]) -> list[ClusterStorageDict]:
|
|||||||
return [_storage(name, rows) for name, rows in groups.items()]
|
return [_storage(name, rows) for name, rows in groups.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_server_ref(config: _JsonDict) -> BackupServerRefDict:
|
||||||
|
"""Which server and datastore a ``pbs`` storage writes to (``/storage``); never
|
||||||
|
its password or encryption key."""
|
||||||
|
port = config.get("port")
|
||||||
|
return {
|
||||||
|
"server": str(config.get("server") or ""),
|
||||||
|
"port": int(port) if port else None,
|
||||||
|
"datastore": str(config.get("datastore") or ""),
|
||||||
|
"namespace": config.get("namespace") or None,
|
||||||
|
"fingerprint": config.get("fingerprint") or None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _name_backup_servers(storages: list[ClusterStorageDict], api: Any) -> None:
|
||||||
|
"""Give each ``pbs`` storage in *storages* its ``backup_server`` (#55); None for
|
||||||
|
all of them when ``/storage`` cannot be read."""
|
||||||
|
pbs = [s for s in storages if s["type"] == "pbs"]
|
||||||
|
if not pbs:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
configs = {str(c.get("storage")): c for c in api.storage.get() or []}
|
||||||
|
except Exception:
|
||||||
|
logger.debug("/storage could not be read; the backup servers stay unnamed", exc_info=True)
|
||||||
|
configs = None
|
||||||
|
for storage in pbs:
|
||||||
|
config = configs.get(storage["name"]) if configs is not None else None
|
||||||
|
storage["backup_server"] = _backup_server_ref(config) if config else None
|
||||||
|
|
||||||
|
|
||||||
def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]:
|
def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]:
|
||||||
merged: dict[str, ClusterNetworkDict] = {}
|
merged: dict[str, ClusterNetworkDict] = {}
|
||||||
for node, network in per_node:
|
for node, network in per_node:
|
||||||
@@ -148,6 +178,7 @@ class ProxmoxClusterMixin:
|
|||||||
head = next((s for s in status if s.get("type") == "cluster"), None)
|
head = next((s for s in status if s.get("type") == "cluster"), None)
|
||||||
members = self._members(status if head else [])
|
members = self._members(status if head else [])
|
||||||
storages = _storages(resources)
|
storages = _storages(resources)
|
||||||
|
_name_backup_servers(storages, self._api)
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
"id": None,
|
"id": None,
|
||||||
|
|||||||
+14
-12
@@ -34,6 +34,7 @@ from napalm_device_types import (
|
|||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
PortSpec,
|
PortSpec,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
@@ -54,13 +55,17 @@ from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
|||||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||||
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.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.vm_contract_mixin import ProxmoxVMContractMixin
|
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
||||||
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||||
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
|
||||||
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
|
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
|
||||||
|
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -92,11 +97,16 @@ class ProxmoxDriver(
|
|||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
|
LogSourcesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
|
ProxmoxScheduledJobsMixin,
|
||||||
|
ProxmoxRunningBackupsMixin,
|
||||||
|
ProxmoxTimeSyncMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
|
ProxmoxZabbixAgentMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
@@ -115,6 +125,10 @@ class ProxmoxDriver(
|
|||||||
#: ``apt-get upgrade`` holds back what needs new or removed packages and can
|
#: ``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.
|
#: leave the node half updated. netOrk reads this when it upgrades the host.
|
||||||
FULL_UPGRADE = True
|
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),
|
||||||
]
|
]
|
||||||
@@ -188,18 +202,6 @@ class ProxmoxDriver(
|
|||||||
f"set the 'node' driver argument"
|
f"set the 'node' driver argument"
|
||||||
)
|
)
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
# Node info helpers (PVE only)
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
|
|
||||||
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
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|||||||
@@ -75,6 +75,11 @@ class ProxmoxHostMixin:
|
|||||||
the exec path, which runs as root either way."""
|
the exec path, which runs as root either way."""
|
||||||
return str(self._exec_ssh_command(command))
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``LogSourcesMixin.get_log_sources``: the exec path,
|
||||||
|
which runs as root either way."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
def get_packages(self) -> list[PackageDict]:
|
def get_packages(self) -> list[PackageDict]:
|
||||||
"""Return installed Debian packages with available-update info.
|
"""Return installed Debian packages with available-update info.
|
||||||
|
|
||||||
@@ -226,6 +231,17 @@ class ProxmoxHostMixin:
|
|||||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
return self._write_root_file(path, content)
|
return self._write_root_file(path, content)
|
||||||
|
|
||||||
|
def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict:
|
||||||
|
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
|
||||||
|
sources or no ufw -- pve-firewall's rules are the operator's."""
|
||||||
|
sources = [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(f"ufw allow from {s} to any port {port} proto {proto}" for s in sources)
|
||||||
|
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
|
||||||
|
|
||||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
||||||
encoded = base64.b64encode(content.encode()).decode()
|
encoded = base64.b64encode(content.encode()).decode()
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -23,6 +23,7 @@ from __future__ import annotations
|
|||||||
import ipaddress
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
import shlex
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm.base.exceptions import CommandErrorException
|
from napalm.base.exceptions import CommandErrorException
|
||||||
@@ -176,21 +177,9 @@ 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 chrony, or ntpd where chrony is missing."""
|
"""Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing."""
|
||||||
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND))
|
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND))
|
||||||
@@ -373,13 +362,7 @@ class ProxmoxSystemMixin:
|
|||||||
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
|
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
|
||||||
|
|
||||||
def _allow_snmp_sources(self, settings: dict) -> dict:
|
def _allow_snmp_sources(self, settings: dict) -> dict:
|
||||||
sources = [_net(s) for s in settings.get("allowed_sources", [])]
|
return dict(self._allow_sources(settings.get("allowed_sources", []), 161, "udp"))
|
||||||
if not sources:
|
|
||||||
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
|
||||||
if self._rc("command -v ufw")[1] != 0:
|
|
||||||
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
|
|
||||||
rules = " && ".join(f"ufw allow from {s} to any port 161 proto udp" for s in sources)
|
|
||||||
return self._step(rules, f"udp/161 open for {', '.join(sources)}")
|
|
||||||
|
|
||||||
def _start_snmp_agent(self) -> dict:
|
def _start_snmp_agent(self) -> dict:
|
||||||
return self._step(
|
return self._step(
|
||||||
@@ -453,9 +436,8 @@ class ProxmoxSystemMixin:
|
|||||||
hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain)
|
hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain)
|
||||||
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 ─────────────────────────────────────────────
|
||||||
@@ -465,12 +447,13 @@ class ProxmoxSystemMixin:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# ── 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 && postconf -e 'myhostname = {fqdn}' || true"
|
f"command -v postconf >/dev/null 2>&1 && postconf -e {postfix} || 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>/.
|
||||||
@@ -479,16 +462,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)
|
||||||
|
|||||||
@@ -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})"}
|
||||||
@@ -19,6 +19,8 @@ from napalm_device_types.models import (
|
|||||||
VMPassthroughDict,
|
VMPassthroughDict,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from napalm_proxmox.vm_mixin import qemu_status
|
||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
_POWER_TIMEOUT = 120
|
_POWER_TIMEOUT = 120
|
||||||
@@ -188,6 +190,25 @@ 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.
|
||||||
|
"""
|
||||||
|
vmid, vm_type = self._resolve_vm(name)
|
||||||
|
if vm_type != "vm":
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Proxmox cannot resume container {vmid}: only a paused VM can be resumed"
|
||||||
|
)
|
||||||
|
current = self._guest_api(vmid, vm_type).status.current.get() or {}
|
||||||
|
state = qemu_status(current)
|
||||||
|
if state != "paused":
|
||||||
|
raise RuntimeError(f"Cannot resume VM {vmid}: it is not paused ({state})")
|
||||||
|
self._run_power(vmid, vm_type, "resume")
|
||||||
|
|
||||||
def get_vm_config(self, name: str) -> VMConfigDict:
|
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 {}
|
||||||
|
|||||||
@@ -24,6 +24,20 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The QMP states of a guest whose QEMU process holds its memory but does not run it:
|
||||||
|
#: paused (``status/suspend``, the GUI's Pause) and asleep in S3. ``status/resume``
|
||||||
|
#: brings either back. PVE's ``status`` says ``running`` for both (NetOrk/netork#2658).
|
||||||
|
PAUSED_QMP_STATES = ("paused", "suspended")
|
||||||
|
|
||||||
|
|
||||||
|
def qemu_status(vm: _JsonDict) -> str:
|
||||||
|
"""A QEMU guest's status as the contract names it: ``paused`` where PVE's full
|
||||||
|
status (``qmpstatus``) says the running process does not execute the guest."""
|
||||||
|
status = str(vm.get("status", "unknown"))
|
||||||
|
if status == "running" and vm.get("qmpstatus") in PAUSED_QMP_STATES:
|
||||||
|
return "paused"
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxVMMixin:
|
class ProxmoxVMMixin:
|
||||||
"""Mixin providing VM and container NAPALM methods."""
|
"""Mixin providing VM and container NAPALM methods."""
|
||||||
@@ -215,7 +229,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)
|
||||||
@@ -227,12 +241,12 @@ class ProxmoxVMMixin:
|
|||||||
"""
|
"""
|
||||||
result: list[_JsonDict] = []
|
result: list[_JsonDict] = []
|
||||||
|
|
||||||
# QEMU VMs
|
# QEMU VMs; only the full status has ``qmpstatus``, which tells paused from running.
|
||||||
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)
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from napalm_device_types.provisioning import (
|
|||||||
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
||||||
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||||
from napalm_proxmox.utils import cpu_flags
|
from napalm_proxmox.utils import cpu_flags
|
||||||
|
from napalm_proxmox.vm_mixin import qemu_status
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
|
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
|
||||||
@@ -874,6 +875,11 @@ class ProxmoxVMProvisionMixin:
|
|||||||
"""
|
"""
|
||||||
Get the runtime status of a virtual machine.
|
Get the runtime status of a virtual machine.
|
||||||
|
|
||||||
|
The status is what ``GET /nodes/{node}/qemu/{vmid}/status/current`` says:
|
||||||
|
``running``, ``stopped``, or ``paused`` where its ``qmpstatus`` is paused or
|
||||||
|
suspended (``qemu_status``, as ``get_vms()`` lists it). Only a running VM's
|
||||||
|
guest agent is asked for an address (NAPALM/napalm-proxmox#72).
|
||||||
|
|
||||||
Optionally waits for the guest-agent to report an IP address on the
|
Optionally waits for the guest-agent to report an IP address on the
|
||||||
management NIC (net0), useful after provisioning.
|
management NIC (net0), useful after provisioning.
|
||||||
|
|
||||||
@@ -885,45 +891,69 @@ 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)
|
||||||
|
if address is not None:
|
||||||
|
return {"status": "running", **address}
|
||||||
|
if not wait_for_ip:
|
||||||
|
return {"status": "running"}
|
||||||
|
time.sleep(poll_interval)
|
||||||
|
# A status that does not read this round keeps the last one.
|
||||||
|
status = self._qemu_current_status(vm, vmid) or status
|
||||||
|
|
||||||
|
except RuntimeError:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
||||||
|
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _qemu_current_status(vm: Any, vmid: str) -> str | None:
|
||||||
|
"""The VM's status from ``status/current``; None when it does not read."""
|
||||||
try:
|
try:
|
||||||
# Query guest-agent network interfaces. Proxmox's REST path is
|
return qemu_status(vm.status.current.get() or {})
|
||||||
# "network-get-interfaces" (hyphens) — it must be passed as a
|
except Exception as e:
|
||||||
# resource id via __call__, not dotted attribute access (which
|
_logger.debug(f"Could not read the status of VM {vmid}: {e}")
|
||||||
# would silently build a non-existent "network_get_interfaces"
|
return None
|
||||||
# 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 —
|
@staticmethod
|
||||||
# loopback commonly comes first, named "lo" on Linux and
|
def _guest_agent_address(vm: Any, vmid: str) -> dict[str, str] | None:
|
||||||
# "lo0" on the BSDs. Skip loopback addresses, whatever the
|
"""The first non-loopback IPv4 address the guest agent reports, or None."""
|
||||||
# interface is called, and take the first IPv4 address.
|
try:
|
||||||
for iface in interfaces:
|
# Proxmox's REST path is "network-get-interfaces" (hyphens) — it must
|
||||||
|
# be passed as a resource id via __call__, not dotted attribute access
|
||||||
|
# (which would silently build a non-existent "network_get_interfaces"
|
||||||
|
# path and 404 on every poll).
|
||||||
|
agent_info = 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", "")
|
name = iface.get("name", "")
|
||||||
if not name:
|
if not name:
|
||||||
continue
|
continue
|
||||||
@@ -934,27 +964,11 @@ class ProxmoxVMProvisionMixin:
|
|||||||
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
||||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||||
return {
|
return {
|
||||||
"status": "running",
|
|
||||||
"ip_address": ip_addr,
|
"ip_address": ip_addr,
|
||||||
"hostname": name,
|
"hostname": name,
|
||||||
"mac_address": iface.get("hardware-address", ""),
|
"mac_address": iface.get("hardware-address", ""),
|
||||||
}
|
}
|
||||||
|
return None
|
||||||
except Exception as e:
|
|
||||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
|
||||||
|
|
||||||
if not wait_for_ip:
|
|
||||||
# Return immediate status without IP
|
|
||||||
return {"status": "running"}
|
|
||||||
|
|
||||||
# Wait before next poll
|
|
||||||
time.sleep(poll_interval)
|
|
||||||
|
|
||||||
except RuntimeError:
|
|
||||||
raise
|
|
||||||
except Exception as e:
|
|
||||||
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
|
||||||
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
|
||||||
|
|
||||||
def get_network_targets(self) -> list[NetworkTargetDict]:
|
def get_network_targets(self) -> list[NetworkTargetDict]:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""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 (
|
||||||
|
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")
|
||||||
|
|
||||||
|
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
|
||||||
|
) -> FixStepOutcomeDict: ...
|
||||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "napalm-proxmox"
|
name = "napalm-proxmox"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -21,7 +21,7 @@ classifiers = [
|
|||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"napalm>=5.0.0",
|
"napalm>=5.0.0",
|
||||||
"napalm_device_types>=4.25.0", # BackupServerDriver
|
"napalm_device_types>=4.40.0", # ZabbixAgentMixin
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||||
"proxmoxer>=2.0.0",
|
"proxmoxer>=2.0.0",
|
||||||
"netaddr>=0.9.0",
|
"netaddr>=0.9.0",
|
||||||
|
|||||||
@@ -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",
|
||||||
@@ -164,7 +162,6 @@ 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,
|
||||||
sensors=None,
|
sensors=None,
|
||||||
@@ -186,7 +183,6 @@ 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.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 = {}
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ class _Resource:
|
|||||||
def post(self, **params: Any) -> Any:
|
def post(self, **params: Any) -> Any:
|
||||||
return self._api.post(self._path, **params)
|
return self._api.post(self._path, **params)
|
||||||
|
|
||||||
|
def put(self, **params: Any) -> Any:
|
||||||
|
return self._api.put(self._path, **params)
|
||||||
|
|
||||||
|
|
||||||
class FakePbsApi:
|
class FakePbsApi:
|
||||||
"""``get``/``post``/``put``/``delete`` by path, like ``ProxmoxAPI.get("admin/gc")``,
|
"""``get``/``post``/``put``/``delete`` by path, like ``ProxmoxAPI.get("admin/gc")``,
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 37,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 37,
|
||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 21,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 21,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 18,
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 18,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 12
|
||||||
},
|
},
|
||||||
"function_lines": {
|
"function_lines": {
|
||||||
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
||||||
@@ -29,12 +29,12 @@
|
|||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 66,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 66,
|
||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 70,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 70,
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
|
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 114,
|
"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_vm_interfaces": 179,
|
||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 220,
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 220,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
|
||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 92
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 63
|
||||||
},
|
},
|
||||||
"mypy_relaxed": [
|
"mypy_relaxed": [
|
||||||
"napalm_proxmox.config_mixin",
|
"napalm_proxmox.config_mixin",
|
||||||
|
|||||||
@@ -226,6 +226,7 @@ def _api(
|
|||||||
api.cluster.ha.status.current.get.return_value = []
|
api.cluster.ha.status.current.get.return_value = []
|
||||||
api.cluster.ha.rules.get.return_value = []
|
api.cluster.ha.rules.get.return_value = []
|
||||||
api.cluster.backup.get.return_value = []
|
api.cluster.backup.get.return_value = []
|
||||||
|
api.storage.get.return_value = []
|
||||||
return api
|
return api
|
||||||
|
|
||||||
|
|
||||||
@@ -505,3 +506,61 @@ class TestCreateOnAnotherNode:
|
|||||||
api.cluster.nextid.get.assert_not_called()
|
api.cluster.nextid.get.assert_not_called()
|
||||||
for res in [api.nodes(n) for n in ("pve1", "pve2")]:
|
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]]
|
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"]
|
||||||
@@ -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")
|
||||||
|
]
|
||||||
+1
-13
@@ -1,4 +1,4 @@
|
|||||||
"""Tests for NTP, SNMP, users, config management, ping, traceroute, CLI."""
|
"""Tests for NTP statistics, SNMP, users, config management, ping, traceroute, CLI."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -7,18 +7,6 @@ from unittest.mock import patch
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
class TestGetNTPServers:
|
|
||||||
def test_returns_configured_servers(self, driver):
|
|
||||||
result = driver.get_ntp_servers()
|
|
||||||
assert "pool.ntp.org" in result
|
|
||||||
assert "time.cloudflare.com" in result
|
|
||||||
|
|
||||||
def test_empty_when_no_ntp(self, driver):
|
|
||||||
driver._node_api().ntp.get.return_value = {}
|
|
||||||
result = driver.get_ntp_servers()
|
|
||||||
assert result == {}
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetNTPStats:
|
class TestGetNTPStats:
|
||||||
NTP_OUTPUT = (
|
NTP_OUTPUT = (
|
||||||
"*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123\n"
|
"*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123\n"
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
import re
|
import re
|
||||||
|
import shlex
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from napalm.base.exceptions import CommandErrorException
|
from napalm.base.exceptions import CommandErrorException
|
||||||
@@ -41,8 +42,8 @@ class _Node:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
def written_hosts(self) -> str:
|
def written_hosts(self) -> str:
|
||||||
write = next(c for c in self.ran if c.rstrip().endswith("chmod 644 /etc/hosts"))
|
write = next(c for c in self.ran if "/etc/hosts" in c and "base64 -d" in c)
|
||||||
return base64.b64decode(re.match(r"echo (\S+) \| base64 -d", write).group(1)).decode()
|
return base64.b64decode(re.search(r"echo (\S+) \| base64 -d", write).group(1)).decode()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -105,3 +106,75 @@ def test_an_unreadable_cluster_check_refuses_too(driver, node):
|
|||||||
driver.set_hostname("new")
|
driver.set_hostname("new")
|
||||||
|
|
||||||
assert [c for c in node.ran if "corosync.conf" not in c] == []
|
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()
|
||||||
@@ -25,7 +25,8 @@ def test_it_runs_the_shared_command(driver):
|
|||||||
identity = driver.get_system_identity()
|
identity = driver.get_system_identity()
|
||||||
|
|
||||||
exec_.assert_called_once_with(SYSTEM_IDENTITY_COMMAND)
|
exec_.assert_called_once_with(SYSTEM_IDENTITY_COMMAND)
|
||||||
assert identity == {
|
# The identity's keys only: napalm-device-types reads more in the same round trip.
|
||||||
|
assert {k: identity[k] for k in ("system_uuid", "product_serial", "board_serial")} == {
|
||||||
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
|
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
|
||||||
"product_serial": "",
|
"product_serial": "",
|
||||||
"board_serial": "ZM155S026022",
|
"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()
|
||||||
@@ -41,6 +41,43 @@ 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 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 +121,29 @@ 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)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"current", [{"status": "running", "qmpstatus": "running"}, {"status": "stopped"}]
|
||||||
|
)
|
||||||
|
def test_resume_of_a_guest_that_is_not_paused_is_refused(self, driver, api, current):
|
||||||
|
api.qemu.return_value.status.current.get.return_value = current
|
||||||
|
with pytest.raises(RuntimeError, match="not paused"):
|
||||||
|
driver.resume_vm("100")
|
||||||
|
api.qemu.return_value.status.resume.post.assert_not_called()
|
||||||
|
|
||||||
|
def test_resume_of_a_container_is_refused(self, driver, api):
|
||||||
|
with pytest.raises(RuntimeError, match="container 200"):
|
||||||
|
driver.resume_vm("200")
|
||||||
|
api.lxc.return_value.status.resume.post.assert_not_called()
|
||||||
|
|
||||||
def test_api_error_becomes_runtime_error(self, driver, api):
|
def test_api_error_becomes_runtime_error(self, driver, api):
|
||||||
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
api.qemu.return_value.status.start.post.side_effect = Exception("locked")
|
||||||
with pytest.raises(RuntimeError, match="locked"):
|
with pytest.raises(RuntimeError, match="locked"):
|
||||||
|
|||||||
@@ -201,7 +201,7 @@ class TestLoopbackIsNeverTheVmsAddress:
|
|||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
node = MagicMock()
|
node = MagicMock()
|
||||||
mixin._node_api = MagicMock(return_value=node)
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
node.qemu.return_value.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
node.qemu.return_value.status.current.get.return_value = {"status": "running"}
|
||||||
node.qemu.return_value.agent.return_value.get.return_value = {"result": interfaces}
|
node.qemu.return_value.agent.return_value.get.return_value = {"result": interfaces}
|
||||||
with patch("time.sleep"):
|
with patch("time.sleep"):
|
||||||
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
|
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
|
||||||
|
|||||||
@@ -336,7 +336,7 @@ def test_get_vm_status_with_wait_for_ip():
|
|||||||
# Mock VM config
|
# Mock VM config
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0,tag=10"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
||||||
# reached via agent(...) as a callable resource, not dotted attribute
|
# reached via agent(...) as a callable resource, not dotted attribute
|
||||||
@@ -375,7 +375,7 @@ def test_get_vm_status_skips_loopback_interface():
|
|||||||
|
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
mock_agent_call = MagicMock()
|
mock_agent_call = MagicMock()
|
||||||
mock_vm.agent.return_value = mock_agent_call
|
mock_vm.agent.return_value = mock_agent_call
|
||||||
@@ -410,7 +410,7 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
|||||||
# Mock VM config
|
# Mock VM config
|
||||||
mock_vm = MagicMock()
|
mock_vm = MagicMock()
|
||||||
mock_node.qemu.return_value = mock_vm
|
mock_node.qemu.return_value = mock_vm
|
||||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
mock_vm.status.current.get.return_value = _RUNNING
|
||||||
|
|
||||||
# Mock guest-agent that never returns IP
|
# Mock guest-agent that never returns IP
|
||||||
mock_agent_call = MagicMock()
|
mock_agent_call = MagicMock()
|
||||||
@@ -424,6 +424,114 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
|||||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
||||||
|
|
||||||
|
|
||||||
|
_RUNNING = {"status": "running", "qmpstatus": "running"}
|
||||||
|
_ETH0 = {
|
||||||
|
"name": "eth0",
|
||||||
|
"hardware-address": "aa:bb:cc:dd:ee:00",
|
||||||
|
"ip-addresses": [{"ip-address": "10.0.0.100", "ip-address-type": "ipv4"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _status_of(current, interfaces=()):
|
||||||
|
"""A mixin whose VM 101 answers ``status/current`` with *current*."""
|
||||||
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
node = MagicMock()
|
||||||
|
mixin._node_api = MagicMock(return_value=node)
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
if isinstance(current, list):
|
||||||
|
vm.status.current.get.side_effect = current
|
||||||
|
else:
|
||||||
|
vm.status.current.get.return_value = current
|
||||||
|
vm.agent.return_value.get.return_value = {"result": list(interfaces)}
|
||||||
|
return mixin, vm
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheStatusIsWhatProxmoxSays:
|
||||||
|
"""``status/current``, not whether the config reads (NAPALM/napalm-proxmox#72).
|
||||||
|
|
||||||
|
The guest agent is asked for an address only while the VM runs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_a_stopped_vm_is_stopped(self):
|
||||||
|
mixin, vm = _status_of({"status": "stopped", "qmpstatus": "stopped"})
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "stopped"}
|
||||||
|
vm.status.current.get.assert_called_once_with()
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||||
|
def test_a_paused_vm_is_paused(self, qmpstatus):
|
||||||
|
mixin, vm = _status_of({"status": "running", "qmpstatus": qmpstatus})
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "paused"}
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
def test_a_running_vm_is_running_with_its_address(self):
|
||||||
|
mixin, _vm = _status_of(_RUNNING, [_ETH0])
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {
|
||||||
|
"status": "running",
|
||||||
|
"ip_address": "10.0.0.100",
|
||||||
|
"hostname": "eth0",
|
||||||
|
"mac_address": "aa:bb:cc:dd:ee:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_a_running_vm_whose_agent_does_not_answer_is_running(self):
|
||||||
|
mixin, vm = _status_of(_RUNNING)
|
||||||
|
vm.agent.return_value.get.side_effect = Exception("QEMU guest agent is not running")
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("101") == {"status": "running"}
|
||||||
|
|
||||||
|
def test_a_vm_proxmox_does_not_have_is_unknown(self):
|
||||||
|
mixin, vm = _status_of({})
|
||||||
|
vm.status.current.get.side_effect = Exception("Configuration file does not exist")
|
||||||
|
|
||||||
|
assert mixin.get_vm_status("999") == {"status": "unknown"}
|
||||||
|
|
||||||
|
def test_waiting_for_an_address_ends_when_the_vm_stops(self):
|
||||||
|
"""A VM that stopped will report no address: the wait ends with an error at once."""
|
||||||
|
mixin, vm = _status_of([_RUNNING, {"status": "stopped"}])
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="stopped"):
|
||||||
|
with patch("time.sleep"):
|
||||||
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
assert vm.agent.return_value.get.call_count == 1
|
||||||
|
|
||||||
|
def test_waiting_for_an_address_of_a_paused_vm_does_not_ask_the_agent(self):
|
||||||
|
mixin, vm = _status_of({"status": "running", "qmpstatus": "paused"})
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="paused"):
|
||||||
|
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
vm.agent.assert_not_called()
|
||||||
|
|
||||||
|
def test_waiting_reads_the_status_again_on_each_round(self):
|
||||||
|
mixin, vm = _status_of([_RUNNING, _RUNNING, _RUNNING])
|
||||||
|
vm.agent.return_value.get.side_effect = [
|
||||||
|
{"result": []},
|
||||||
|
{"result": []},
|
||||||
|
{"result": [_ETH0]},
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("time.sleep"):
|
||||||
|
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
|
||||||
|
assert result["ip_address"] == "10.0.0.100"
|
||||||
|
assert vm.status.current.get.call_count == 3
|
||||||
|
|
||||||
|
def test_a_status_that_does_not_read_while_waiting_keeps_the_wait_going(self):
|
||||||
|
mixin, vm = _status_of([_RUNNING, Exception("timed out"), _RUNNING])
|
||||||
|
vm.agent.return_value.get.side_effect = [
|
||||||
|
{"result": []},
|
||||||
|
{"result": []},
|
||||||
|
{"result": [_ETH0]},
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("time.sleep"):
|
||||||
|
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||||
|
|
||||||
|
assert result["ip_address"] == "10.0.0.100"
|
||||||
|
|
||||||
|
|
||||||
def test_destroy_vm_success():
|
def test_destroy_vm_success():
|
||||||
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
||||||
mixin = ProxmoxVMProvisionMixin()
|
mixin = ProxmoxVMProvisionMixin()
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""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_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] = []
|
||||||
|
|
||||||
|
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 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"
|
||||||
Reference in new issue
Block a user