Compare commits
13
Commits
5a5ed8eac7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2d9d7e75e | ||
|
|
685e995073 | ||
|
|
370aeed482 | ||
|
|
bc3eb86723 | ||
|
|
8159566ff4 | ||
|
|
b80a3950ac | ||
|
|
cae4859383 | ||
|
|
ad3b5b29a9 | ||
|
|
326527ddd5 | ||
|
|
f071c10cd1 | ||
|
|
93c974b8f0 | ||
|
|
449230c624 | ||
|
|
92108f0ff3 |
No files matched your search
+48
-1
@@ -7,7 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.13.0] - 2026-11-26
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
- An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run
|
||||||
|
(`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`,
|
||||||
|
NetOrk/netork#2693). ufw does not say who wrote a rule, so every rule the firewall step
|
||||||
|
adds -- the Zabbix agent's tcp/`listen_port`, SNMP's udp/161 -- is now recorded in
|
||||||
|
`/var/lib/netork/opened-ports` (napalm-device-types `opened_ports`), and only when ufw did
|
||||||
|
not have it before: an identical rule the operator wrote is never recorded. Closing removes
|
||||||
|
exactly the agent's recorded rules, whatever port they opened, and rewrites the record. It
|
||||||
|
reads the record only when it is root's alone, and reports the rules for the port it left
|
||||||
|
in place: the operator's, or ones opened before this version recorded them. pve-firewall's
|
||||||
|
rules stay the operator's.
|
||||||
|
|
||||||
|
## [0.12.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `get_vm_status(vmid)` reports the VM's real state (#72): it reads
|
||||||
|
`GET /nodes/{node}/qemu/{vmid}/status/current` and answers `running`, `stopped`, or
|
||||||
|
`paused` for a `qmpstatus` of paused or suspended, the same as `get_vms()`. It used to say
|
||||||
|
`running` for every VM whose config could be read, so a caller waiting for a clean shutdown
|
||||||
|
never saw the VM stop (NetOrk/netork's workflow step "Shut down Proxmox VM" always ran into
|
||||||
|
its timeout). The guest agent is asked for an address only while the VM runs, and
|
||||||
|
`wait_for_ip=True` ends with a `RuntimeError` at once when the VM is stopped or paused,
|
||||||
|
rather than waiting out its timeout for an address that cannot come.
|
||||||
|
|
||||||
|
## [0.11.0] - 2026-11-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `resume_vm(name)` (napalm-device-types' `HypervisorDriver`, NetOrk/netork#2658): a paused
|
||||||
|
VM continues where `suspend_vm` stopped it, through `status/resume`, and the driver waits
|
||||||
|
for its task. A VM that is not paused is refused (PVE answers a running one with success
|
||||||
|
and does nothing), and so is a container: the driver does not suspend one, PVE's
|
||||||
|
container suspend is experimental, and its listing does not tell a suspended container
|
||||||
|
from another.
|
||||||
|
- A native Zabbix agent on both drivers (napalm-device-types `ZabbixAgentMixin`,
|
||||||
|
NetOrk/netork#2571): a node runs no container engine. `configure_zabbix_agent(settings)`
|
||||||
|
installs Debian's `zabbix-agent`, and where Debian has none and the caller names the
|
||||||
|
server's release line, Zabbix's from its repository; writes the caller's values into
|
||||||
|
`/etc/zabbix/zabbix_agentd.conf` (the old file stays as `.bak`); opens tcp/`listen_port`
|
||||||
|
in ufw where the node has it (pve-firewall's rules are the operator's); enables and
|
||||||
|
restarts the service.
|
||||||
- Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types'
|
- 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
|
`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
|
servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's
|
||||||
@@ -46,7 +87,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
|
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Requires napalm-device-types 4.36.0.
|
- `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
|
### Fixed
|
||||||
- `set_hostname()` hands the name to the shell quoted (`shlex.quote`): to `hostname`, to
|
- `set_hostname()` hands the name to the shell quoted (`shlex.quote`): to `hostname`, to
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
|||||||
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
|
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
|
||||||
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||||
|
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -69,6 +70,7 @@ class ProxmoxBackupDriver(
|
|||||||
ProxmoxScheduledJobsMixin,
|
ProxmoxScheduledJobsMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
|
ProxmoxZabbixAgentMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ 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__)
|
||||||
|
|
||||||
@@ -105,6 +106,7 @@ class ProxmoxDriver(
|
|||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
|
ProxmoxZabbixAgentMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
|
|||||||
@@ -17,7 +17,18 @@ import re
|
|||||||
import shlex
|
import shlex
|
||||||
from typing import TYPE_CHECKING, Any, cast
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
|
from napalm_device_types import (
|
||||||
|
APT_UPGRADABLE_COMMAND,
|
||||||
|
OPENED_PORTS_RECORD,
|
||||||
|
OpenedRuleDict,
|
||||||
|
parse_apt_upgradable,
|
||||||
|
parse_opened_ports_record,
|
||||||
|
read_opened_ports_command,
|
||||||
|
revoke_recorded_rules,
|
||||||
|
revoked_output,
|
||||||
|
ufw_allow_recorded_command,
|
||||||
|
ufw_delete_command,
|
||||||
|
)
|
||||||
from napalm_device_types.models import (
|
from napalm_device_types.models import (
|
||||||
FixStepOutcomeDict,
|
FixStepOutcomeDict,
|
||||||
LicenseDict,
|
LicenseDict,
|
||||||
@@ -231,6 +242,58 @@ 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, purpose: str
|
||||||
|
) -> FixStepOutcomeDict:
|
||||||
|
"""Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no
|
||||||
|
sources or no ufw -- pve-firewall's rules are the operator's. Each rule ufw adds
|
||||||
|
is recorded under *purpose* (napalm-device-types ``opened_ports``,
|
||||||
|
NetOrk/netork#2693); one ufw had is not."""
|
||||||
|
sources = [str(ipaddress.ip_network(s.strip(), strict=False)) for s in allowed]
|
||||||
|
if not sources:
|
||||||
|
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
||||||
|
if self._rc("command -v ufw")[1] != 0:
|
||||||
|
return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"}
|
||||||
|
rules = " && ".join(ufw_allow_recorded_command(s, port, proto, purpose) for s in sources)
|
||||||
|
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
|
||||||
|
|
||||||
|
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict:
|
||||||
|
"""Remove the ufw rules recorded under *purpose*, whatever port they opened, and
|
||||||
|
nothing else; report what ufw has left for *proto*/*port*. Not ``ok`` where
|
||||||
|
the record may not be trusted -- nothing is removed then -- or a rule would not
|
||||||
|
go, which stays in the record."""
|
||||||
|
read, status = self._rc(read_opened_ports_command())
|
||||||
|
if status != 0:
|
||||||
|
return {"ok": False, "output": f"reading {OPENED_PORTS_RECORD}: {read[-300:]}"}
|
||||||
|
record = parse_opened_ports_record(read)
|
||||||
|
if record["problem"]:
|
||||||
|
return {"ok": False, "output": record["problem"]}
|
||||||
|
done = revoke_recorded_rules(record, purpose, self._remove_recorded_rule)
|
||||||
|
failed = done["failed"]
|
||||||
|
if done["removed"]:
|
||||||
|
written = self._write_root_file(OPENED_PORTS_RECORD, done["record"])
|
||||||
|
if not written["ok"]:
|
||||||
|
failed.append(f"writing {OPENED_PORTS_RECORD}: {written['output']}")
|
||||||
|
left = 0
|
||||||
|
if self._rc("command -v ufw")[1] == 0:
|
||||||
|
counted, _ = self._rc(
|
||||||
|
f"LC_ALL=C ufw show added"
|
||||||
|
f" | grep -cE '(port {port} proto {proto}| {port}/{proto})( |$)'"
|
||||||
|
)
|
||||||
|
last = counted.strip().splitlines()[-1:] or ["0"]
|
||||||
|
left = int(last[0]) if last[0].isdigit() else 0
|
||||||
|
output = revoked_output(
|
||||||
|
done["removed"], unknown=record["unknown"], left=left, proto=proto, port=port
|
||||||
|
)
|
||||||
|
if failed:
|
||||||
|
output = f"{output}; not removed: {'; '.join(failed)}"
|
||||||
|
return {"ok": not failed, "output": output}
|
||||||
|
|
||||||
|
def _remove_recorded_rule(self, rule: OpenedRuleDict) -> FixStepOutcomeDict:
|
||||||
|
if rule["backend"] != "ufw":
|
||||||
|
return {"ok": False, "output": f"a {rule['backend']} rule; a node's rules are ufw's"}
|
||||||
|
return self._step(ufw_delete_command(rule), "")
|
||||||
|
|
||||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
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()
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import shlex
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm.base.exceptions import CommandErrorException
|
from napalm.base.exceptions import CommandErrorException
|
||||||
|
from napalm_device_types import SNMP_PURPOSE
|
||||||
|
|
||||||
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
||||||
|
|
||||||
@@ -362,13 +363,9 @@ 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(
|
||||||
if not sources:
|
self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE)
|
||||||
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(
|
||||||
|
|||||||
@@ -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,70 +891,36 @@ class ProxmoxVMProvisionMixin:
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
||||||
(ip_address, hostname, mac_address only if VM is running and has network info)
|
(ip_address, hostname, mac_address only if VM is running and has network
|
||||||
|
info); {"status": "unknown"} when Proxmox gives no status for the vmid.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
RuntimeError: VM doesn't exist or wait_for_ip times out
|
RuntimeError: wait_for_ip times out, or the VM is not running while
|
||||||
|
waiting (a stopped or paused VM reports no address)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
vmid_int = int(vmid)
|
vm = self._node_api().qemu(int(vmid))
|
||||||
_logger.debug(f"Getting status for VM {vmid}")
|
_logger.debug(f"Getting status for VM {vmid}")
|
||||||
|
# The VM must exist / be readable before we start polling.
|
||||||
# VM must exist / be readable before we start polling.
|
status = self._qemu_current_status(vm, vmid)
|
||||||
try:
|
if status is None:
|
||||||
self._node_api().qemu(vmid_int).config.get()
|
|
||||||
except Exception:
|
|
||||||
# VM may not exist yet or config not readable
|
|
||||||
return {"status": "unknown"}
|
return {"status": "unknown"}
|
||||||
|
|
||||||
# Polling loop
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
while True:
|
while True:
|
||||||
elapsed = time.time() - start_time
|
if status != "running":
|
||||||
if wait_for_ip and elapsed > timeout:
|
if wait_for_ip:
|
||||||
|
raise RuntimeError(f"VM {vmid} is {status}: it reports no IP address")
|
||||||
|
return {"status": status}
|
||||||
|
if wait_for_ip and time.time() - start_time > timeout:
|
||||||
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
||||||
|
address = self._guest_agent_address(vm, vmid)
|
||||||
try:
|
if address is not None:
|
||||||
# Query guest-agent network interfaces. Proxmox's REST path is
|
return {"status": "running", **address}
|
||||||
# "network-get-interfaces" (hyphens) — it must be passed as a
|
|
||||||
# resource id via __call__, not dotted attribute access (which
|
|
||||||
# would silently build a non-existent "network_get_interfaces"
|
|
||||||
# path and 404 on every poll).
|
|
||||||
agent_info = (
|
|
||||||
self._node_api().qemu(vmid_int).agent("network-get-interfaces").get()
|
|
||||||
)
|
|
||||||
interfaces = (agent_info or {}).get("result", [])
|
|
||||||
|
|
||||||
# The guest agent does not report interfaces in a fixed order —
|
|
||||||
# loopback commonly comes first, named "lo" on Linux and
|
|
||||||
# "lo0" on the BSDs. Skip loopback addresses, whatever the
|
|
||||||
# interface is called, and take the first IPv4 address.
|
|
||||||
for iface in interfaces:
|
|
||||||
name = iface.get("name", "")
|
|
||||||
if not name:
|
|
||||||
continue
|
|
||||||
for addr in iface.get("ip-addresses", []):
|
|
||||||
if addr.get("ip-address-type") != "ipv4":
|
|
||||||
continue
|
|
||||||
ip_addr = addr.get("ip-address", "")
|
|
||||||
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
|
||||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
|
||||||
return {
|
|
||||||
"status": "running",
|
|
||||||
"ip_address": ip_addr,
|
|
||||||
"hostname": name,
|
|
||||||
"mac_address": iface.get("hardware-address", ""),
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
|
||||||
|
|
||||||
if not wait_for_ip:
|
if not wait_for_ip:
|
||||||
# Return immediate status without IP
|
|
||||||
return {"status": "running"}
|
return {"status": "running"}
|
||||||
|
|
||||||
# Wait before next poll
|
|
||||||
time.sleep(poll_interval)
|
time.sleep(poll_interval)
|
||||||
|
# A status that does not read this round keeps the last one.
|
||||||
|
status = self._qemu_current_status(vm, vmid) or status
|
||||||
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
raise
|
raise
|
||||||
@@ -956,6 +928,48 @@ class ProxmoxVMProvisionMixin:
|
|||||||
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
||||||
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _qemu_current_status(vm: Any, vmid: str) -> str | None:
|
||||||
|
"""The VM's status from ``status/current``; None when it does not read."""
|
||||||
|
try:
|
||||||
|
return qemu_status(vm.status.current.get() or {})
|
||||||
|
except Exception as e:
|
||||||
|
_logger.debug(f"Could not read the status of VM {vmid}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _guest_agent_address(vm: Any, vmid: str) -> dict[str, str] | None:
|
||||||
|
"""The first non-loopback IPv4 address the guest agent reports, or None."""
|
||||||
|
try:
|
||||||
|
# Proxmox's REST path is "network-get-interfaces" (hyphens) — it must
|
||||||
|
# be passed as a resource id via __call__, not dotted attribute access
|
||||||
|
# (which would silently build a non-existent "network_get_interfaces"
|
||||||
|
# path and 404 on every poll).
|
||||||
|
agent_info = vm.agent("network-get-interfaces").get()
|
||||||
|
except Exception as e:
|
||||||
|
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
||||||
|
return None
|
||||||
|
# The guest agent does not report interfaces in a fixed order — loopback
|
||||||
|
# commonly comes first, named "lo" on Linux and "lo0" on the BSDs. Skip
|
||||||
|
# loopback addresses, whatever the interface is called, and take the first
|
||||||
|
# IPv4 address.
|
||||||
|
for iface in (agent_info or {}).get("result", []):
|
||||||
|
name = iface.get("name", "")
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
for addr in iface.get("ip-addresses", []):
|
||||||
|
if addr.get("ip-address-type") != "ipv4":
|
||||||
|
continue
|
||||||
|
ip_addr = addr.get("ip-address", "")
|
||||||
|
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
||||||
|
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||||
|
return {
|
||||||
|
"ip_address": ip_addr,
|
||||||
|
"hostname": name,
|
||||||
|
"mac_address": iface.get("hardware-address", ""),
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
|
||||||
def get_network_targets(self) -> list[NetworkTargetDict]:
|
def get_network_targets(self) -> list[NetworkTargetDict]:
|
||||||
"""
|
"""
|
||||||
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""A native Zabbix agent on a Proxmox node: napalm-device-types' ``ZabbixAgentMixin``.
|
||||||
|
|
||||||
|
A node runs no container engine (NetOrk/netork#2571). The template installs Debian's
|
||||||
|
``zabbix-agent`` -- or, where Debian has none, Zabbix's from its repository -- and
|
||||||
|
enables and restarts it. This writes the caller's values into
|
||||||
|
``/etc/zabbix/zabbix_agentd.conf`` and opens tcp/``listen_port`` in ufw where the node
|
||||||
|
has it; pve-firewall's rules are the operator's, as for the SNMP agent. The node's
|
||||||
|
shell runs as root.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from napalm_device_types import (
|
||||||
|
ZABBIX_AGENT_PURPOSE,
|
||||||
|
FixStepOutcomeDict,
|
||||||
|
ZabbixAgentMixin,
|
||||||
|
ZabbixAgentSettingsDict,
|
||||||
|
zabbix_agent_config,
|
||||||
|
zabbix_repository_command,
|
||||||
|
)
|
||||||
|
|
||||||
|
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
|
||||||
|
"""``zabbix-agent`` from Debian, or else from Zabbix's repository."""
|
||||||
|
|
||||||
|
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
|
||||||
|
os_release, status = self._rc("cat /etc/os-release")
|
||||||
|
if status != 0:
|
||||||
|
return {"ok": False, "output": f"reading /etc/os-release: {os_release[-300:]}"}
|
||||||
|
try:
|
||||||
|
command = zabbix_repository_command(os_release, release)
|
||||||
|
except ValueError as exc:
|
||||||
|
return {"ok": False, "output": str(exc)}
|
||||||
|
return self._step(command, f"Zabbix {release} repository added")
|
||||||
|
|
||||||
|
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||||
|
text, status = self._rc(f"cat {CONFIG}")
|
||||||
|
if status != 0:
|
||||||
|
return {"ok": False, "output": f"reading {CONFIG}: {text[-300:]}"}
|
||||||
|
# _rc strips the output; the file ends with a newline.
|
||||||
|
new, changes = zabbix_agent_config(f"{text}\n", settings)
|
||||||
|
if not changes:
|
||||||
|
return {"ok": True, "output": f"{CONFIG} already says it"}
|
||||||
|
kept = self._step(f"cp -p {CONFIG} {CONFIG}.bak", "")
|
||||||
|
if not kept["ok"]:
|
||||||
|
return kept
|
||||||
|
written = self._write_root_file(CONFIG, new)
|
||||||
|
if not written["ok"]:
|
||||||
|
return written
|
||||||
|
return {"ok": True, "output": "; ".join(changes)}
|
||||||
|
|
||||||
|
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||||
|
return self._allow_sources(
|
||||||
|
settings["allowed_sources"], int(settings["listen_port"]), "tcp", ZABBIX_AGENT_PURPOSE
|
||||||
|
)
|
||||||
|
|
||||||
|
def _revoke_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||||
|
"""For an active-only agent: remove the ufw rules recorded for the agent on an
|
||||||
|
earlier passive run, whatever port they opened (NetOrk/netork#2693)."""
|
||||||
|
return self._revoke_sources(ZABBIX_AGENT_PURPOSE, int(settings["listen_port"]), "tcp")
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - ProxmoxHostMixin's
|
||||||
|
|
||||||
|
def _rc(self, command: str) -> tuple[str, int]: ...
|
||||||
|
|
||||||
|
def _step(self, command: str, done: str) -> FixStepOutcomeDict: ...
|
||||||
|
|
||||||
|
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
|
||||||
|
|
||||||
|
def _allow_sources(
|
||||||
|
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||||
|
) -> FixStepOutcomeDict: ...
|
||||||
|
|
||||||
|
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ...
|
||||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "napalm-proxmox"
|
name = "napalm-proxmox"
|
||||||
version = "0.10.0"
|
version = "0.13.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.36.0", # TimeSyncMixin, PosixTimeSyncMixin (DHCP's servers)
|
"napalm_device_types>=4.43.0", # ZabbixAgentMixin, opened_ports
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
"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",
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
"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",
|
||||||
|
|||||||
@@ -82,7 +82,8 @@ class TestSnmpAgent:
|
|||||||
def test_no_temp_file_with_an_application_name(self, driver, node):
|
def test_no_temp_file_with_an_application_name(self, driver, node):
|
||||||
driver.configure_snmp_agent(SETTINGS)
|
driver.configure_snmp_agent(SETTINGS)
|
||||||
|
|
||||||
assert not any("netork" in c for c in node.ran)
|
# The record of opened rules (/var/lib/netork, NetOrk/netork#2693) is no temp file.
|
||||||
|
assert not any(re.search(r"/tmp/\S*netork", c) for c in node.ran)
|
||||||
|
|
||||||
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
|
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
|
||||||
node.status["command -v ufw"] = 0
|
node.status["command -v ufw"] = 0
|
||||||
|
|||||||
@@ -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,243 @@
|
|||||||
|
"""configure_zabbix_agent on a Proxmox node (NetOrk/netork#2571).
|
||||||
|
|
||||||
|
A node runs no container engine, so the agent cannot run as a container there. The
|
||||||
|
template installs Debian's ``zabbix-agent`` -- or Zabbix's, where Debian has none -- and
|
||||||
|
enables and restarts it; the node writes the configuration and opens ufw where there is
|
||||||
|
one. pve-firewall's rules are the operator's.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import re
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import OPENED_PORTS_RECORD
|
||||||
|
|
||||||
|
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||||
|
|
||||||
|
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
|
||||||
|
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
|
||||||
|
DEBIAN = 'PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n'
|
||||||
|
SETTINGS = {
|
||||||
|
"server": "zabbix.example.com",
|
||||||
|
"server_active": "zabbix.example.com",
|
||||||
|
"listen_port": 10050,
|
||||||
|
"allowed_sources": ["10.40.100.254"],
|
||||||
|
"hostname": "pve-01",
|
||||||
|
"release": "7.4",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class _Node:
|
||||||
|
"""The node's root shell: files it reads, packages Debian has, what is refused."""
|
||||||
|
|
||||||
|
def __init__(self, *, config=STOCK, ufw=True, debian_has_it=True, refuse=""):
|
||||||
|
self.config = config
|
||||||
|
self.ufw = ufw
|
||||||
|
self.debian_has_it = debian_has_it
|
||||||
|
self.installed = False
|
||||||
|
self.refuse = refuse
|
||||||
|
self.ran: list[str] = []
|
||||||
|
#: What reading the record of opened rules prints (NetOrk/netork#2693).
|
||||||
|
self.record = ""
|
||||||
|
#: What counting the rules left for the port prints.
|
||||||
|
self.left = "0"
|
||||||
|
self.record_written: str | None = None
|
||||||
|
|
||||||
|
def __call__(self, command: str) -> str:
|
||||||
|
self.ran.append(command)
|
||||||
|
out, rc = self._answer(command)
|
||||||
|
for marker in ("__PVE_RC=", "__SVC_RC="):
|
||||||
|
if marker in command:
|
||||||
|
return f"{out}\n{marker}{rc}"
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _answer(self, command: str) -> tuple[str, int]:
|
||||||
|
if self.refuse and self.refuse in command:
|
||||||
|
return "E: refused", 1
|
||||||
|
if "stat -c" in command and OPENED_PORTS_RECORD in command:
|
||||||
|
return self.record, 0
|
||||||
|
if "grep -c" in command:
|
||||||
|
return self.left, 0
|
||||||
|
if "base64 -d" in command and OPENED_PORTS_RECORD in command:
|
||||||
|
written = re.search(r"echo (\S*) \|", command).group(1)
|
||||||
|
self.record_written = base64.b64decode(written).decode()
|
||||||
|
return "", 0
|
||||||
|
if command.startswith("dpkg-query"):
|
||||||
|
return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0
|
||||||
|
if f"cat {CONFIG}" in command:
|
||||||
|
return self.config, 0
|
||||||
|
if "cat /etc/os-release" in command:
|
||||||
|
return DEBIAN, 0
|
||||||
|
if "command -v ufw" in command:
|
||||||
|
return ("/usr/sbin/ufw", 0) if self.ufw else ("", 1)
|
||||||
|
if "repo.zabbix.com" in command:
|
||||||
|
self.debian_has_it = True
|
||||||
|
return "ok", 0
|
||||||
|
if "apt-get install" in command and "zabbix-agent" in command:
|
||||||
|
if not self.debian_has_it:
|
||||||
|
return "E: Unable to locate package zabbix-agent", 100
|
||||||
|
self.installed = True
|
||||||
|
return "ok", 0
|
||||||
|
if "base64 -d" in command and CONFIG in command:
|
||||||
|
self.config = base64.b64decode(re.search(r"echo (\S+) \|", command).group(1)).decode()
|
||||||
|
return "ok", 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def node():
|
||||||
|
return _Node()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(params=[ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
|
||||||
|
def driver(request, node):
|
||||||
|
d = request.param("pve", "root@pam", "pw")
|
||||||
|
d._exec_ssh_command = node
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def test_installs_writes_opens_and_starts(driver, node):
|
||||||
|
result = driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||||
|
assert any("apt-get install" in c and "zabbix-agent" in c for c in node.ran)
|
||||||
|
assert any("systemctl" in c and "restart" in c and "zabbix-agent" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, node):
|
||||||
|
driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert "Server=zabbix.example.com\n" in node.config
|
||||||
|
assert "Hostname=pve-01\n" in node.config
|
||||||
|
assert node.config.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
|
||||||
|
assert any(f"cp -p {CONFIG} {CONFIG}.bak" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_config_that_already_says_it_is_not_written(driver, node):
|
||||||
|
driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
node.ran.clear()
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert result["success"] is True
|
||||||
|
assert not any("base64 -d" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_debian_s_package_zabbix_s_repository_is_added(driver, node):
|
||||||
|
node.debian_has_it = False
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
repository = next(c for c in node.ran if "repo.zabbix.com" in c)
|
||||||
|
assert "zabbix-release_latest_7.4+debian13_all.deb" in repository
|
||||||
|
|
||||||
|
|
||||||
|
def test_ufw_opens_the_listen_port_for_the_sources(driver, node):
|
||||||
|
driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert any("ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_ufw_the_firewall_is_the_operator_s(driver, node):
|
||||||
|
node.ufw = False
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert result["success"] is True
|
||||||
|
assert "pve-firewall rules are the operator's" in result["output"]
|
||||||
|
assert not any("ufw allow" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_config_that_cannot_be_read_stops_the_fix(driver, node):
|
||||||
|
node.refuse = f"cat {CONFIG}"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert result["steps"][-1]["step"] == "configure"
|
||||||
|
|
||||||
|
|
||||||
|
# --- The record of the rules netOrk opened (NetOrk/netork#2693) ---------------------
|
||||||
|
|
||||||
|
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
|
||||||
|
ROOT = "0 755 directory\n0 644 regular file\n"
|
||||||
|
ZABBIX_UFW = "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
|
||||||
|
SNMP_UFW = "v1 snmp ufw udp 161 10.40.100.254/32"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ufw_records_the_rule_it_added_under_the_agent(driver, node):
|
||||||
|
driver.configure_zabbix_agent(SETTINGS)
|
||||||
|
|
||||||
|
opened = next(c for c in node.ran if "ufw allow" in c)
|
||||||
|
assert "*Skipping*) ;;" in opened
|
||||||
|
assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_snmp_rule_is_recorded_under_snmp(node):
|
||||||
|
driver = ProxmoxDriver("pve", "root@pam", "pw")
|
||||||
|
driver._exec_ssh_command = node
|
||||||
|
|
||||||
|
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.40.100.254"]})
|
||||||
|
|
||||||
|
assert any(f'"{SNMP_UFW}" >>' in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, node):
|
||||||
|
node.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\n"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
deletes = [c for c in node.ran if "ufw delete" in c]
|
||||||
|
assert len(deletes) == 1
|
||||||
|
assert "ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp" in deletes[0]
|
||||||
|
assert node.record_written == f"{SNMP_UFW}\n"
|
||||||
|
assert "removed" in result["steps"][2]["output"]
|
||||||
|
assert not any("ufw allow" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, node):
|
||||||
|
node.left = "1"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is True
|
||||||
|
assert not any("ufw delete" in c for c in node.ran)
|
||||||
|
assert node.record_written is None
|
||||||
|
firewall = result["steps"][2]["output"]
|
||||||
|
assert "netOrk recorded no rule" in firewall
|
||||||
|
assert "1 rule(s) for tcp/10050" in firewall
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_record_someone_else_could_write_is_not_acted_on(driver, node):
|
||||||
|
node.record = f"0 755 directory\n0 666 regular file\n{ZABBIX_UFW}\n"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "writable" in result["output"]
|
||||||
|
assert not any("ufw delete" in c for c in node.ran)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_rule_that_will_not_go_stays_in_the_record(driver, node):
|
||||||
|
node.record = ROOT + f"{ZABBIX_UFW}\n"
|
||||||
|
node.refuse = "ufw delete"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert node.record_written is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_recorded_rule_of_another_firewall_is_not_touched(driver, node):
|
||||||
|
"""A node's rules are ufw's; a firewalld line is not one this driver removes."""
|
||||||
|
node.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.40.100.254/32\n"
|
||||||
|
|
||||||
|
result = driver.configure_zabbix_agent(ACTIVE_ONLY)
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "iptables" in result["output"]
|
||||||
|
assert node.record_written is None
|
||||||
Reference in new issue
Block a user