Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b423220bf | ||
|
|
75818c3f09 | ||
|
|
fddf8af680 | ||
|
|
c2d9d7e75e | ||
|
|
685e995073 | ||
|
|
370aeed482 |
No files matched your search
@@ -7,6 +7,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.14.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- Proxmox VE 9.3's API additions (NetOrk/netork#2728), each taken only on a node whose
|
||||
`GET /version` says 9.3 or later (`_version_at_least`); an older node does what it did.
|
||||
- `get_vms()`: each guest carries PVE 9.3's `uid`, an identity that survives a migration, a
|
||||
restore and a changed vmid, from one `GET /cluster/resources?type=vm` per call, joined by
|
||||
node and vmid (napalm-device-types `VMDict.uid`). A guest without one, an older node and a
|
||||
listing that cannot be read leave the key out; the guests are listed as before.
|
||||
- `get_clusters()`: `id` is the cluster's `cluster-id` from `GET /cluster/status`, or a
|
||||
standalone node's own on its node entry; None on an older node.
|
||||
- `get_credential_expiry()` (napalm-device-types `CredentialExpiryMixin`): the API token
|
||||
(`GET /access/users/{userid}/token/{tokenid}`) or the password's account
|
||||
(`GET /access/users/{userid}`) the driver logged in with, and when it expires; a token
|
||||
without an `expire` of its own expires with its user. A 403 is a `PermissionError`, any
|
||||
other failure a `RuntimeError`.
|
||||
- `get_update_history(since)` (napalm-device-types `UpdateMixin`): the node's APT
|
||||
transactions from `GET /nodes/{node}/apt/history`, newest first, with `id`
|
||||
`"{start-time}-{start-index}"`. A failed read raises; before 9.3 it is
|
||||
`NotImplementedError` (no log is parsed over SSH).
|
||||
|
||||
### Changed
|
||||
- `set_node_maintenance()` uses `PUT /nodes/{node}/maintenance` when the node going into
|
||||
maintenance runs PVE 9.3, and opens no SSH session; that node's own version decides,
|
||||
since a rolling upgrade leaves the members on different releases. An older node still
|
||||
takes `ha-manager crm-command node-maintenance` over SSH.
|
||||
- `resume_vm()` sets the guest's clock to the host's time on PVE 9.3
|
||||
(`sync-time-on-resume=1`, through the guest agent where it runs).
|
||||
- Needs napalm-device-types 4.44.0 or later (`CredentialExpiryMixin`, `UpdateHistoryDict`,
|
||||
`VMDict.uid`).
|
||||
|
||||
## [0.13.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run
|
||||
(`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`,
|
||||
NetOrk/netork#2693). ufw does not say who wrote a rule, so every rule the firewall step
|
||||
adds -- the Zabbix agent's tcp/`listen_port`, SNMP's udp/161 -- is now recorded in
|
||||
`/var/lib/netork/opened-ports` (napalm-device-types `opened_ports`), and only when ufw did
|
||||
not have it before: an identical rule the operator wrote is never recorded. Closing removes
|
||||
exactly the agent's recorded rules, whatever port they opened, and rewrites the record. It
|
||||
reads the record only when it is root's alone, and reports the rules for the port it left
|
||||
in place: the operator's, or ones opened before this version recorded them. pve-firewall's
|
||||
rules stay the operator's.
|
||||
|
||||
## [0.12.0] - 2026-11-26
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -28,6 +28,7 @@ from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
@@ -39,6 +40,9 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: The release at the start of a product version, ``"9.3"`` of ``"9.3.0"``.
|
||||
_RELEASE = re.compile(r"^(\d+)\.(\d+)")
|
||||
|
||||
#: The API port of each proxmoxer service this package drives.
|
||||
DEFAULT_PORTS = {"PVE": 8006, "PBS": 8007}
|
||||
|
||||
@@ -301,6 +305,24 @@ class ProxmoxBase:
|
||||
logger.debug("Failed to fetch version info: %s", exc)
|
||||
return {}
|
||||
|
||||
def _version_at_least(self, major: int, minor: int, node: str | None = None) -> bool:
|
||||
"""Whether the product on the node is release *major*.*minor* or newer.
|
||||
|
||||
Read from ``GET /version`` of the node the driver is connected to, or with
|
||||
*node* from ``GET /nodes/{node}/version``: during a rolling upgrade the
|
||||
cluster's members run different releases. The package ``version``
|
||||
(``"9.3.0"``) decides, else the point ``release`` (``"9.3"``). A version it
|
||||
cannot parse counts as older, so the caller takes the path every release
|
||||
has. An API error propagates.
|
||||
"""
|
||||
source = self._api.nodes(node).version if node else self._api.version
|
||||
info = source.get() or {}
|
||||
for raw in (info.get("version"), info.get("release")):
|
||||
match = _RELEASE.match(str(raw or ""))
|
||||
if match:
|
||||
return (int(match[1]), int(match[2])) >= (major, minor)
|
||||
return False
|
||||
|
||||
def _get_node_status(self) -> _JsonDict:
|
||||
"""Return the node's status from the Proxmox API."""
|
||||
try:
|
||||
|
||||
@@ -4,8 +4,8 @@ Every PVE node can read its whole cluster, so the getter always reports exactly
|
||||
one cluster, the one the connected node is a member of (a standalone node is a
|
||||
cluster of one, without a name). Read from:
|
||||
|
||||
- ``GET /cluster/status``: the cluster's name and quorum, and every member with
|
||||
``online`` and ``local``;
|
||||
- ``GET /cluster/status``: the cluster's name, quorum and (PVE 9.3) ``cluster-id``,
|
||||
and every member with ``online`` and ``local``;
|
||||
- ``GET /cluster/resources``: per node ``maxcpu``, ``cpu``, ``maxmem``, ``mem``;
|
||||
per node and storage one row with ``plugintype``, ``shared``, ``content``,
|
||||
``maxdisk``, ``disk`` and ``status``;
|
||||
@@ -124,6 +124,12 @@ def _name_backup_servers(storages: list[ClusterStorageDict], api: Any) -> None:
|
||||
storage["backup_server"] = _backup_server_ref(config) if config else None
|
||||
|
||||
|
||||
def _cluster_id(head: _JsonDict | None, status: list[_JsonDict]) -> str | None:
|
||||
"""``cluster-id`` (PVE 9.3) of the cluster entry, or of a standalone node's own entry."""
|
||||
entry = head or next((s for s in status if s.get("type") == "node"), {})
|
||||
return str(entry.get("cluster-id") or "") or None
|
||||
|
||||
|
||||
def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]:
|
||||
merged: dict[str, ClusterNetworkDict] = {}
|
||||
for node, network in per_node:
|
||||
@@ -149,9 +155,10 @@ class ProxmoxClusterMixin:
|
||||
"""
|
||||
Return the one cluster this node belongs to, its nodes, storages and networks.
|
||||
|
||||
- ``id`` is always None: PVE gives a cluster no identity beyond its name.
|
||||
``name`` and ``quorate`` are None on a standalone node, which reports
|
||||
itself as a cluster of one.
|
||||
- ``id`` is the ``cluster-id`` of PVE 9.3, a random identifier the cluster
|
||||
keeps when it is renamed; a standalone node reports its own on its node
|
||||
entry. None on an older node. ``name`` and ``quorate`` are None on a
|
||||
standalone node, which reports itself as a cluster of one.
|
||||
- Every member is listed. An offline node has ``status`` ``"offline"`` and
|
||||
no capacity values: its own API cannot be asked. ``local`` marks the
|
||||
node ``/cluster/status`` calls local, or else the node this driver
|
||||
@@ -181,7 +188,7 @@ class ProxmoxClusterMixin:
|
||||
_name_backup_servers(storages, self._api)
|
||||
return [
|
||||
{
|
||||
"id": None,
|
||||
"id": _cluster_id(head, status),
|
||||
"name": (head.get("name") or None) if head else None,
|
||||
"quorate": _flag(head.get("quorate")) if head else None,
|
||||
"nodes": self._cluster_nodes(members, resources),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""When the credential the Proxmox VE driver logs in with expires (NetOrk/netork#2728).
|
||||
|
||||
``CredentialExpiryMixin`` of napalm-device-types. The driver logs in either with
|
||||
an API token (``user@realm!tokenid``) or with a user's password:
|
||||
|
||||
- a token: ``GET /access/users/{userid}/token/{tokenid}``, its ``expire``. A token
|
||||
without one of its own expires with its user (the schema's default, "same as
|
||||
user"), read as for a password;
|
||||
- a password: ``GET /access/users/{userid}``, the account's ``expire``.
|
||||
|
||||
``0`` or no value is never. PVE 9.3's datacenter ``token-policy`` can require an
|
||||
expiry on every token; the fields themselves are older, so every release is read.
|
||||
PVE lets a user read itself and its tokens; a privilege-separated token may be
|
||||
refused its user (``User.Modify`` or ``Sys.Audit`` on the user's group), and a
|
||||
403 is a ``PermissionError``, as the contract says.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import CredentialExpiryDict, CredentialExpiryMixin
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
|
||||
def _expires(value: Any) -> int | None:
|
||||
"""PVE's ``expire``: unix seconds, ``0`` or none for never."""
|
||||
return int(value or 0) or None
|
||||
|
||||
|
||||
def _read(get: Callable[[], Any], what: str) -> _JsonDict:
|
||||
"""``get()``'s answer; a refusal as ``PermissionError``, another failure as
|
||||
``RuntimeError``."""
|
||||
try:
|
||||
answer = get()
|
||||
except ResourceException as exc:
|
||||
if exc.status_code == 403:
|
||||
raise PermissionError(f"Proxmox VE will not tell {what}'s expiry: {exc}") from exc
|
||||
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Cannot read the expiry of {what}: {exc}") from exc
|
||||
return dict(answer or {})
|
||||
|
||||
|
||||
class ProxmoxCredentialExpiryMixin(CredentialExpiryMixin):
|
||||
"""Relies on the driver's ``_api`` and its login (``_api_kwargs``)."""
|
||||
|
||||
_api: Any
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||
|
||||
def _api_kwargs(self) -> _JsonDict: ...
|
||||
|
||||
def get_credential_expiry(self) -> CredentialExpiryDict:
|
||||
"""The API token or the account this connection logged in with, and its expiry."""
|
||||
login = self._api_kwargs()
|
||||
userid = str(login["user"])
|
||||
if "token_value" not in login:
|
||||
return {"kind": "account", "name": userid, "expires": self._user_expiry(userid)}
|
||||
name = f"{userid}!{login['token_name']}"
|
||||
token = _read(lambda: self._api.access.users(userid).token(login["token_name"]).get(), name)
|
||||
expire = token.get("expire")
|
||||
return {
|
||||
"kind": "api-token",
|
||||
"name": name,
|
||||
"expires": self._user_expiry(userid) if expire is None else _expires(expire),
|
||||
}
|
||||
|
||||
def _user_expiry(self, userid: str) -> int | None:
|
||||
return _expires(_read(lambda: self._api.access.users(userid).get(), userid).get("expire"))
|
||||
@@ -51,6 +51,7 @@ except ImportError as exc:
|
||||
from napalm_proxmox._base import ProxmoxBase
|
||||
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
||||
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
||||
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||
@@ -60,6 +61,7 @@ from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduled
|
||||
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
||||
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
from napalm_proxmox.update_history import ProxmoxUpdateHistoryMixin
|
||||
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
||||
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||
@@ -103,6 +105,8 @@ class ProxmoxDriver(
|
||||
ProxmoxScheduledJobsMixin,
|
||||
ProxmoxRunningBackupsMixin,
|
||||
ProxmoxTimeSyncMixin,
|
||||
ProxmoxCredentialExpiryMixin,
|
||||
ProxmoxUpdateHistoryMixin,
|
||||
HostStatusMixin,
|
||||
LicenseMixin,
|
||||
SnmpAgentMixin,
|
||||
|
||||
@@ -17,7 +17,18 @@ import re
|
||||
import shlex
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
|
||||
from napalm_device_types import (
|
||||
APT_UPGRADABLE_COMMAND,
|
||||
OPENED_PORTS_RECORD,
|
||||
OpenedRuleDict,
|
||||
parse_apt_upgradable,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
revoke_recorded_rules,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
from napalm_device_types.models import (
|
||||
FixStepOutcomeDict,
|
||||
LicenseDict,
|
||||
@@ -231,17 +242,58 @@ class ProxmoxHostMixin:
|
||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
return self._write_root_file(path, content)
|
||||
|
||||
def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict:
|
||||
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."""
|
||||
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(f"ufw allow from {s} to any port {port} proto {proto}" for s in sources)
|
||||
rules = " && ".join(ufw_allow_recorded_command(s, port, proto, purpose) for s in sources)
|
||||
return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}")
|
||||
|
||||
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict:
|
||||
"""Remove the ufw rules recorded under *purpose*, whatever port they opened, and
|
||||
nothing else; report what ufw has left for *proto*/*port*. Not ``ok`` where
|
||||
the record may not be trusted -- nothing is removed then -- or a rule would not
|
||||
go, which stays in the record."""
|
||||
read, status = self._rc(read_opened_ports_command())
|
||||
if status != 0:
|
||||
return {"ok": False, "output": f"reading {OPENED_PORTS_RECORD}: {read[-300:]}"}
|
||||
record = parse_opened_ports_record(read)
|
||||
if record["problem"]:
|
||||
return {"ok": False, "output": record["problem"]}
|
||||
done = revoke_recorded_rules(record, purpose, self._remove_recorded_rule)
|
||||
failed = done["failed"]
|
||||
if done["removed"]:
|
||||
written = self._write_root_file(OPENED_PORTS_RECORD, done["record"])
|
||||
if not written["ok"]:
|
||||
failed.append(f"writing {OPENED_PORTS_RECORD}: {written['output']}")
|
||||
left = 0
|
||||
if self._rc("command -v ufw")[1] == 0:
|
||||
counted, _ = self._rc(
|
||||
f"LC_ALL=C ufw show added"
|
||||
f" | grep -cE '(port {port} proto {proto}| {port}/{proto})( |$)'"
|
||||
)
|
||||
last = counted.strip().splitlines()[-1:] or ["0"]
|
||||
left = int(last[0]) if last[0].isdigit() else 0
|
||||
output = revoked_output(
|
||||
done["removed"], unknown=record["unknown"], left=left, proto=proto, port=port
|
||||
)
|
||||
if failed:
|
||||
output = f"{output}; not removed: {'; '.join(failed)}"
|
||||
return {"ok": not failed, "output": output}
|
||||
|
||||
def _remove_recorded_rule(self, rule: OpenedRuleDict) -> FixStepOutcomeDict:
|
||||
if rule["backend"] != "ufw":
|
||||
return {"ok": False, "output": f"a {rule['backend']} rule; a node's rules are ufw's"}
|
||||
return self._step(ufw_delete_command(rule), "")
|
||||
|
||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
||||
encoded = base64.b64encode(content.encode()).decode()
|
||||
|
||||
@@ -8,6 +8,10 @@ from typing import Any
|
||||
|
||||
_LIST_SEPARATORS = re.compile(r"[\s,;\0]+")
|
||||
|
||||
#: The first release with node maintenance over REST, guest uids, the cluster id,
|
||||
#: clock sync on resume and the APT history (NetOrk/netork#2728).
|
||||
PVE_9_3 = (9, 3)
|
||||
|
||||
|
||||
def to_int(value: Any) -> int | None:
|
||||
return None if value is None else int(value)
|
||||
|
||||
@@ -27,6 +27,7 @@ import shlex
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import SNMP_PURPOSE
|
||||
|
||||
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
||||
|
||||
@@ -362,7 +363,9 @@ class ProxmoxSystemMixin:
|
||||
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
|
||||
|
||||
def _allow_snmp_sources(self, settings: dict) -> dict:
|
||||
return dict(self._allow_sources(settings.get("allowed_sources", []), 161, "udp"))
|
||||
return dict(
|
||||
self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE)
|
||||
)
|
||||
|
||||
def _start_snmp_agent(self) -> dict:
|
||||
return self._step(
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""The node's past APT transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||
|
||||
PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
||||
first, also the transactions netOrk did not start (an operator's ``apt``,
|
||||
unattended-upgrades). A transaction is named by its ``start-time`` and its
|
||||
``start-index`` among those that started in the same second of the same log
|
||||
file. An older node has no such endpoint: the driver raises
|
||||
``NotImplementedError`` and parses no log over SSH.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from napalm_device_types import UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict
|
||||
|
||||
from napalm_proxmox.pve_values import PVE_9_3
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def _package(row: _JsonDict) -> UpdateHistoryPackageDict:
|
||||
return {
|
||||
"name": str(row.get("package") or ""),
|
||||
"action": cast(UpdateHistoryAction, row.get("action")),
|
||||
"old_version": _text(row.get("old-version")),
|
||||
"new_version": _text(row.get("new-version")),
|
||||
}
|
||||
|
||||
|
||||
def _transaction(row: _JsonDict) -> UpdateHistoryDict:
|
||||
start = int(row["start-time"])
|
||||
end = row.get("end-time")
|
||||
return {
|
||||
"id": f"{start}-{int(row.get('start-index') or 0)}",
|
||||
"start": start,
|
||||
"end": None if end is None else int(end),
|
||||
"packages": [_package(p) for p in row.get("packages") or []],
|
||||
"requested_by": _text(row.get("requested-by")),
|
||||
"command": _text(row.get("command-line")),
|
||||
"error": _text(row.get("error")),
|
||||
}
|
||||
|
||||
|
||||
class ProxmoxUpdateHistoryMixin:
|
||||
"""Relies on the driver's ``_node_api`` and ``_version_at_least``."""
|
||||
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||
|
||||
def _node_api(self) -> Any: ...
|
||||
def _version_at_least(self, major: int, minor: int) -> bool: ...
|
||||
|
||||
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
"""The node's APT transactions, newest first, from ``since`` (unix seconds) on.
|
||||
|
||||
:raises NotImplementedError: before PVE 9.3, which has no history endpoint.
|
||||
:raises RuntimeError: the history could not be read; never an empty list.
|
||||
"""
|
||||
if not self._version_at_least(*PVE_9_3):
|
||||
raise NotImplementedError(
|
||||
f"Proxmox VE on {self._node_name} keeps no APT history its API reports "
|
||||
"(from 9.3 on)"
|
||||
)
|
||||
params = {} if since is None else {"since": since}
|
||||
try:
|
||||
rows = self._node_api().apt.history.get(**params) or []
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Cannot read the APT history of {self._node_name}: {exc}") from exc
|
||||
return [_transaction(row) for row in rows]
|
||||
@@ -19,6 +19,7 @@ from napalm_device_types.models import (
|
||||
VMPassthroughDict,
|
||||
)
|
||||
|
||||
from napalm_proxmox.pve_values import PVE_9_3
|
||||
from napalm_proxmox.vm_mixin import qemu_status
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
@@ -152,9 +153,9 @@ class ProxmoxVMContractMixin:
|
||||
node = self._node_api()
|
||||
return node.qemu(vmid) if vm_type == "vm" else node.lxc(vmid)
|
||||
|
||||
def _run_power(self, vmid: int, vm_type: str, action: str) -> None:
|
||||
def _run_power(self, vmid: int, vm_type: str, action: str, **params: Any) -> None:
|
||||
try:
|
||||
upid = getattr(self._guest_api(vmid, vm_type).status, action).post()
|
||||
upid = getattr(self._guest_api(vmid, vm_type).status, action).post(**params)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"{action} of {vm_type} {vmid} failed: {exc}") from exc
|
||||
if upid:
|
||||
@@ -197,6 +198,10 @@ class ProxmoxVMContractMixin:
|
||||
suspend is experimental (CRIU), and its listing does not tell a suspended
|
||||
container from another. A guest that is not paused is refused too: PVE would
|
||||
answer a running one with success and do nothing.
|
||||
|
||||
From PVE 9.3 the guest agent sets the guest's clock to the host's time after
|
||||
it resumes (``sync-time-on-resume``); PVE skips that where the guest has no
|
||||
agent enabled and running.
|
||||
"""
|
||||
vmid, vm_type = self._resolve_vm(name)
|
||||
if vm_type != "vm":
|
||||
@@ -207,7 +212,8 @@ class ProxmoxVMContractMixin:
|
||||
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")
|
||||
params = {"sync-time-on-resume": 1} if self._version_at_least(*PVE_9_3) else {}
|
||||
self._run_power(vmid, vm_type, "resume", **params)
|
||||
|
||||
def get_vm_config(self, name: str) -> VMConfigDict:
|
||||
vmid, vm_type = self._resolve_vm(name)
|
||||
|
||||
@@ -12,9 +12,10 @@ on the node the driver is connected to (``_resolve_vm``).
|
||||
manages migrates through a ``hamigrate`` task that only hands the request to
|
||||
the HA manager; the driver then follows ``/cluster/ha/status/current`` until
|
||||
the guest is on the target, and on a failure reads the migration task's log.
|
||||
- ``set_node_maintenance``: PVE has no REST endpoint for it; it runs
|
||||
``ha-manager crm-command node-maintenance`` over the driver's SSH session.
|
||||
The HA manager moves the node's HA guests away after the command returned.
|
||||
- ``set_node_maintenance``: from PVE 9.3 ``PUT /nodes/{node}/maintenance``; an
|
||||
older node has no REST endpoint for it, and the driver runs
|
||||
``ha-manager crm-command node-maintenance`` over its SSH session. Either way the
|
||||
HA manager moves the node's HA guests away after the request returned.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,7 +26,7 @@ from time import monotonic, sleep
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_proxmox.migration import lxc_local, qemu_local, refusal, task_errors, upid_field
|
||||
from napalm_proxmox.pve_values import to_flag
|
||||
from napalm_proxmox.pve_values import PVE_9_3, to_flag
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
|
||||
@@ -57,6 +58,7 @@ class ProxmoxVMMigrateMixin:
|
||||
_wait_for_task: Any
|
||||
_node_ssh: Any
|
||||
_run_node_command: Any
|
||||
_version_at_least: Any
|
||||
|
||||
# -- cluster membership -------------------------------------------------------
|
||||
|
||||
@@ -232,13 +234,30 @@ class ProxmoxVMMigrateMixin:
|
||||
# -- HA maintenance -----------------------------------------------------------
|
||||
|
||||
def set_node_maintenance(self, node: str, enabled: bool) -> None:
|
||||
"""Switch HA maintenance mode of a cluster node, over SSH (no REST endpoint)."""
|
||||
"""Switch HA maintenance mode of a cluster node: over REST from PVE 9.3, else
|
||||
with ``ha-manager`` over SSH."""
|
||||
names = [m.name for m in self._cluster_members()]
|
||||
if node not in names:
|
||||
raise ValueError(
|
||||
f"{node!r} is not a member of the cluster (members: {', '.join(names)})"
|
||||
)
|
||||
action = "enable" if enabled else "disable"
|
||||
# The request is served by *node* itself, which may not run 9.3 yet mid-upgrade.
|
||||
try:
|
||||
over_rest = self._version_at_least(*PVE_9_3, node=node)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Cannot read the Proxmox VE version of {node!r}: {exc}") from exc
|
||||
if over_rest:
|
||||
try:
|
||||
self._api.nodes(node).maintenance.put(**{"maintenance-mode": action})
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"Proxmox VE refused to {action} maintenance of {node!r}: {exc}"
|
||||
) from exc
|
||||
return
|
||||
self._ha_manager_maintenance(node, action)
|
||||
|
||||
def _ha_manager_maintenance(self, node: str, action: str) -> None:
|
||||
try:
|
||||
self._node_ssh()
|
||||
except Exception as exc:
|
||||
|
||||
@@ -20,6 +20,8 @@ import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm_proxmox.pve_values import PVE_9_3
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
@@ -238,9 +240,9 @@ class ProxmoxVMMixin:
|
||||
* node (str) - cluster node name
|
||||
* interfaces (dict) - network interfaces (NAPALM format + ipv4 field)
|
||||
* ipv4 (str) - primary IPv4 address (empty string if unknown)
|
||||
* uid (str) - PVE 9.3's identity of the guest (``_with_uids``); absent before
|
||||
"""
|
||||
result: list[_JsonDict] = []
|
||||
|
||||
# QEMU VMs; only the full status has ``qmpstatus``, which tells paused from running.
|
||||
try:
|
||||
for vm in self._node_api().qemu.get(full=1) or []:
|
||||
@@ -335,7 +337,36 @@ class ProxmoxVMMixin:
|
||||
except Exception as exc:
|
||||
logger.warning("get_vms: failed to list LXC containers: %s", exc)
|
||||
|
||||
return sorted(result, key=lambda x: int(x["vmid"]))
|
||||
return self._with_uids(sorted(result, key=lambda x: int(x["vmid"])))
|
||||
|
||||
def _with_uids(self, vms: list[_JsonDict]) -> list[_JsonDict]:
|
||||
"""Give each guest in *vms* its ``uid``, joined by node and vmid.
|
||||
|
||||
PVE 9.3 gives every guest a random identifier that survives a migration, a
|
||||
restore and a changed vmid; only ``GET /cluster/resources?type=vm`` reports
|
||||
it. A guest without one, an older node and a listing that cannot be read
|
||||
leave the key out: the guest is still listed, known by its vmid alone.
|
||||
"""
|
||||
try:
|
||||
uids = self._guest_uids()
|
||||
except Exception as exc:
|
||||
logger.debug("get_vms: cannot read the guests' uids: %s", exc)
|
||||
return vms
|
||||
for vm in vms:
|
||||
uid = uids.get((vm["node"], vm["vmid"]))
|
||||
if uid:
|
||||
vm["uid"] = uid
|
||||
return vms
|
||||
|
||||
def _guest_uids(self) -> dict[tuple[str, str], str]:
|
||||
if not self._version_at_least(*PVE_9_3):
|
||||
return {}
|
||||
rows = self._api.cluster.resources.get(type="vm") or []
|
||||
return {
|
||||
(str(row.get("node")), str(row.get("vmid"))): str(row["uid"])
|
||||
for row in rows
|
||||
if row.get("uid")
|
||||
}
|
||||
|
||||
# Disk-key prefixes for QEMU: scsi, virtio, ide, sata (exclude cdrom/none entries)
|
||||
_DISK_KEYS_VM = re.compile(r"^(scsi|virtio|ide|sata)\d+$")
|
||||
|
||||
@@ -13,6 +13,7 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import (
|
||||
ZABBIX_AGENT_PURPOSE,
|
||||
FixStepOutcomeDict,
|
||||
ZabbixAgentMixin,
|
||||
ZabbixAgentSettingsDict,
|
||||
@@ -53,7 +54,14 @@ class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
|
||||
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")
|
||||
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
|
||||
|
||||
@@ -64,5 +72,7 @@ class ProxmoxZabbixAgentMixin(ZabbixAgentMixin):
|
||||
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _allow_sources(
|
||||
self, allowed: list[str], port: int, proto: str
|
||||
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]
|
||||
name = "napalm-proxmox"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
@@ -21,7 +21,7 @@ classifiers = [
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"napalm>=5.0.0",
|
||||
"napalm_device_types>=4.40.0", # ZabbixAgentMixin
|
||||
"napalm_device_types>=4.44.0", # CredentialExpiryMixin, UpdateHistoryDict, VMDict.uid
|
||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||
"proxmoxer>=2.0.0",
|
||||
"netaddr>=0.9.0",
|
||||
|
||||
@@ -266,6 +266,11 @@ class TestCluster:
|
||||
def test_every_member_listed_in_cluster_order(self):
|
||||
assert [n["name"] for n in _cluster()["nodes"]] == ["pve1", "pve2", "pve3"]
|
||||
|
||||
def test_pve_9_3_names_the_cluster_by_its_id(self):
|
||||
"""``cluster-id``: a random identifier, kept when the cluster is renamed."""
|
||||
status = [dict(CLUSTER_STATUS[0], **{"cluster-id": "a1b2c3d4e5"}), *CLUSTER_STATUS[1:]]
|
||||
assert _cluster(cluster_status=status)["id"] == "a1b2c3d4e5"
|
||||
|
||||
|
||||
class TestNodes:
|
||||
def test_online_node(self):
|
||||
@@ -349,6 +354,12 @@ class TestStandalone:
|
||||
assert node["memory_total"] == 128 * GIB
|
||||
assert _by_name(cluster["storages"])["local"]["nodes"] == ["pve1"]
|
||||
|
||||
def test_pve_9_3_names_a_standalone_node_by_its_own_id(self):
|
||||
status = [dict(self.STATUS[0], **{"cluster-id": "f6e5d4c3b2"})]
|
||||
cluster = _cluster(cluster_status=status, resources=self.RESOURCES, ha=RuntimeError())
|
||||
assert cluster["id"] == "f6e5d4c3b2"
|
||||
assert cluster["name"] is None
|
||||
|
||||
|
||||
class TestStorages:
|
||||
def test_local_storage_grouped_over_its_nodes(self):
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""When the credential the driver logs in with stops working (NetOrk/netork#2728).
|
||||
|
||||
PVE 9.3's datacenter ``token-policy`` can require an expiry on every API token;
|
||||
the platform keeps one on every token and account anyway. A token is read with
|
||||
``GET /access/users/{userid}/token/{tokenid}``; a token without an ``expire``
|
||||
of its own expires with its user (``default: same as user``), read with
|
||||
``GET /access/users/{userid}``, which is also where a password's account says
|
||||
when it expires. ``0`` is never.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
from napalm_proxmox.driver import ProxmoxDriver
|
||||
from tests.conftest import _build_mock_api
|
||||
|
||||
|
||||
def _driver(**optional_args: Any) -> tuple[ProxmoxDriver, MagicMock]:
|
||||
password = "" if optional_args else "secret"
|
||||
drv = ProxmoxDriver("pve1", "netork", password, optional_args=optional_args)
|
||||
api = _build_mock_api()
|
||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||
drv.open()
|
||||
return drv, api
|
||||
|
||||
|
||||
def _token_driver(token_name: str = "netork@pve!poll") -> tuple[ProxmoxDriver, MagicMock]:
|
||||
return _driver(token_name=token_name, token_value="s3cret", realm="pve")
|
||||
|
||||
|
||||
def _forbidden() -> ResourceException:
|
||||
return ResourceException(403, "Forbidden", "Permission check failed (/access, User.Modify)")
|
||||
|
||||
|
||||
class TestApiToken:
|
||||
def test_the_tokens_own_expiry(self):
|
||||
drv, api = _token_driver()
|
||||
api.access.users.return_value.token.return_value.get.return_value = {
|
||||
"expire": 1767225600,
|
||||
"privsep": 1,
|
||||
}
|
||||
assert drv.get_credential_expiry() == {
|
||||
"kind": "api-token",
|
||||
"name": "netork@pve!poll",
|
||||
"expires": 1767225600,
|
||||
}
|
||||
api.access.users.assert_called_with("netork@pve")
|
||||
api.access.users.return_value.token.assert_called_once_with("poll")
|
||||
|
||||
def test_zero_never_expires(self):
|
||||
drv, api = _token_driver()
|
||||
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||
assert drv.get_credential_expiry()["expires"] is None
|
||||
api.access.users.return_value.get.assert_not_called()
|
||||
|
||||
def test_a_token_without_expiry_expires_with_its_user(self):
|
||||
drv, api = _token_driver()
|
||||
api.access.users.return_value.token.return_value.get.return_value = {"privsep": 1}
|
||||
api.access.users.return_value.get.return_value = {
|
||||
"userid": "netork@pve",
|
||||
"expire": 1798761600,
|
||||
}
|
||||
assert drv.get_credential_expiry()["expires"] == 1798761600
|
||||
|
||||
def test_a_token_name_without_user_is_the_login_users(self):
|
||||
drv, api = _token_driver(token_name="poll")
|
||||
api.access.users.return_value.token.return_value.get.return_value = {"expire": 0}
|
||||
assert drv.get_credential_expiry()["name"] == "netork@pve!poll"
|
||||
api.access.users.assert_called_with("netork@pve")
|
||||
|
||||
def test_a_refused_read_is_a_permission_error(self):
|
||||
drv, api = _token_driver()
|
||||
api.access.users.return_value.token.return_value.get.side_effect = _forbidden()
|
||||
with pytest.raises(PermissionError, match="User.Modify"):
|
||||
drv.get_credential_expiry()
|
||||
|
||||
def test_a_refused_read_of_the_user_is_a_permission_error(self):
|
||||
drv, api = _token_driver()
|
||||
api.access.users.return_value.token.return_value.get.return_value = {}
|
||||
api.access.users.return_value.get.side_effect = _forbidden()
|
||||
with pytest.raises(PermissionError):
|
||||
drv.get_credential_expiry()
|
||||
|
||||
|
||||
class TestAccount:
|
||||
def test_a_password_login_reads_its_account(self):
|
||||
drv, api = _driver()
|
||||
api.access.users.return_value.get.return_value = {
|
||||
"userid": "netork@pam",
|
||||
"expire": 1767225600,
|
||||
}
|
||||
assert drv.get_credential_expiry() == {
|
||||
"kind": "account",
|
||||
"name": "netork@pam",
|
||||
"expires": 1767225600,
|
||||
}
|
||||
api.access.users.assert_called_with("netork@pam")
|
||||
|
||||
def test_an_account_without_expiry_never_expires(self):
|
||||
drv, api = _driver()
|
||||
api.access.users.return_value.get.return_value = {"userid": "netork@pam", "enable": 1}
|
||||
assert drv.get_credential_expiry()["expires"] is None
|
||||
|
||||
def test_a_refused_read_is_a_permission_error(self):
|
||||
drv, api = _driver()
|
||||
api.access.users.return_value.get.side_effect = _forbidden()
|
||||
with pytest.raises(PermissionError):
|
||||
drv.get_credential_expiry()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
ResourceException(500, "Internal Server Error", "cfs lock timeout"),
|
||||
ConnectionError("reset"),
|
||||
],
|
||||
)
|
||||
def test_another_failure_is_a_runtime_error(self, error):
|
||||
drv, api = _driver()
|
||||
api.access.users.return_value.get.side_effect = error
|
||||
with pytest.raises(RuntimeError, match="netork@pam"):
|
||||
drv.get_credential_expiry()
|
||||
@@ -82,7 +82,8 @@ class TestSnmpAgent:
|
||||
def test_no_temp_file_with_an_application_name(self, driver, node):
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert not any("netork" in c for c in node.ran)
|
||||
# The record of opened rules (/var/lib/netork, NetOrk/netork#2693) is no temp file.
|
||||
assert not any(re.search(r"/tmp/\S*netork", c) for c in node.ran)
|
||||
|
||||
def test_ufw_opens_only_for_the_allowed_sources(self, driver, node):
|
||||
node.status["command -v ufw"] = 0
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Which Proxmox VE release the node runs, for what only newer releases offer.
|
||||
|
||||
``GET /version`` names the pve-manager package's version (``"9.3.0"``) and the
|
||||
point release (``"9.3"``). PVE 9.3 added the REST calls of NetOrk/netork#2728;
|
||||
the driver takes them only on a node that has them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "expected"),
|
||||
[
|
||||
({"version": "9.3.0", "release": "9.3"}, True),
|
||||
({"version": "9.3.2", "release": "9.3"}, True),
|
||||
({"version": "10.0.1", "release": "10.0"}, True),
|
||||
({"version": "9.2.4", "release": "9.2"}, False),
|
||||
({"version": "8.4.1", "release": "8.4"}, False),
|
||||
# No package version: the point release tells.
|
||||
({"release": "9.3"}, True),
|
||||
],
|
||||
)
|
||||
def test_at_least(driver, version, expected):
|
||||
driver._api.version.get.return_value = version
|
||||
assert driver._version_at_least(9, 3) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [{}, {"version": "unknown", "release": ""}])
|
||||
def test_a_version_it_cannot_read_counts_as_older(driver, version):
|
||||
driver._api.version.get.return_value = version
|
||||
assert driver._version_at_least(9, 3) is False
|
||||
|
||||
|
||||
def test_an_api_error_propagates(driver):
|
||||
driver._api.version.get.side_effect = ConnectionError("node unreachable")
|
||||
with pytest.raises(ConnectionError):
|
||||
driver._version_at_least(9, 3)
|
||||
|
||||
|
||||
def test_another_node_is_asked_for_its_own_version(driver):
|
||||
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||
driver._api.nodes("pve2").version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||
assert driver._version_at_least(9, 3, node="pve2") is False
|
||||
driver._api.nodes.assert_called_with("pve2")
|
||||
@@ -0,0 +1,124 @@
|
||||
"""The node's past APT transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||
|
||||
PVE 9.3 reads apt's history log for ``GET /nodes/{node}/apt/history``, newest
|
||||
first. The payload below follows its schema: a transaction is identified by
|
||||
``start-time`` with ``start-index`` (default 0) among those that started in the
|
||||
same second; ``end-time`` is missing while it runs or after it was interrupted.
|
||||
An older node has no such endpoint, and the driver parses no log over SSH.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
HISTORY = [
|
||||
{
|
||||
"start-time": 1764158400,
|
||||
"start-index": 1,
|
||||
"end-time": 1764158460,
|
||||
"command-line": "apt-get -y dist-upgrade",
|
||||
"requested-by": "admin",
|
||||
"requested-by-uid": 1000,
|
||||
"packages": [
|
||||
{
|
||||
"package": "openssh-server",
|
||||
"action": "upgrade",
|
||||
"arch": "amd64",
|
||||
"old-version": "1:10.0p1-7",
|
||||
"new-version": "1:10.0p1-7+deb13u1",
|
||||
},
|
||||
{
|
||||
"package": "proxmox-kernel-6.17.2-1-pve-signed",
|
||||
"action": "install",
|
||||
"new-version": "6.17.2-1",
|
||||
"automatic": 1,
|
||||
},
|
||||
{"package": "ifupdown", "action": "purge", "old-version": "0.8.44"},
|
||||
],
|
||||
},
|
||||
{
|
||||
# unattended-upgrades, interrupted: no end, no user, the error dpkg left.
|
||||
"start-time": 1764072000,
|
||||
"packages": [
|
||||
{
|
||||
"package": "libssl3t64",
|
||||
"action": "upgrade",
|
||||
"old-version": "3.5.1-1",
|
||||
"new-version": "3.5.1-1+deb13u1",
|
||||
}
|
||||
],
|
||||
"error": "Sub-process /usr/bin/dpkg returned an error code (1)",
|
||||
"running": 0,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def history(driver) -> MagicMock:
|
||||
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||
getter = driver._node_api().apt.history.get
|
||||
getter.return_value = HISTORY
|
||||
return getter
|
||||
|
||||
|
||||
class TestUpdateHistory:
|
||||
def test_transactions_newest_first(self, driver, history):
|
||||
newest, older = driver.get_update_history()
|
||||
assert newest == {
|
||||
"id": "1764158400-1",
|
||||
"start": 1764158400,
|
||||
"end": 1764158460,
|
||||
"packages": [
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"action": "upgrade",
|
||||
"old_version": "1:10.0p1-7",
|
||||
"new_version": "1:10.0p1-7+deb13u1",
|
||||
},
|
||||
{
|
||||
"name": "proxmox-kernel-6.17.2-1-pve-signed",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "6.17.2-1",
|
||||
},
|
||||
{
|
||||
"name": "ifupdown",
|
||||
"action": "purge",
|
||||
"old_version": "0.8.44",
|
||||
"new_version": None,
|
||||
},
|
||||
],
|
||||
"requested_by": "admin",
|
||||
"command": "apt-get -y dist-upgrade",
|
||||
"error": None,
|
||||
}
|
||||
assert older["id"] == "1764072000-0"
|
||||
history.assert_called_once_with()
|
||||
|
||||
def test_what_the_log_does_not_keep_is_none(self, driver, history):
|
||||
older = driver.get_update_history()[1]
|
||||
assert older["end"] is None
|
||||
assert older["requested_by"] is None
|
||||
assert older["command"] is None
|
||||
assert older["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
|
||||
|
||||
def test_since_is_passed_on(self, driver, history):
|
||||
driver.get_update_history(since=1764100000)
|
||||
history.assert_called_once_with(since=1764100000)
|
||||
|
||||
def test_no_transaction_is_an_empty_list(self, driver, history):
|
||||
history.return_value = []
|
||||
assert driver.get_update_history() == []
|
||||
|
||||
def test_a_failed_read_raises(self, driver, history):
|
||||
history.side_effect = Exception("596 Connection timed out")
|
||||
with pytest.raises(RuntimeError, match="timed out"):
|
||||
driver.get_update_history()
|
||||
|
||||
def test_an_older_node_has_no_history(self, driver, history):
|
||||
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||
with pytest.raises(NotImplementedError):
|
||||
driver.get_update_history()
|
||||
history.assert_not_called()
|
||||
@@ -41,6 +41,53 @@ class TestGetVmsReportsStringIds:
|
||||
assert [vm["vmid"] for vm in driver.get_vms()] == ["99", "1000"]
|
||||
|
||||
|
||||
class TestGetVmsGuestUid:
|
||||
"""PVE 9.3 gives every guest a ``uid`` that survives a migration, a restore and a
|
||||
changed vmid; only ``/cluster/resources`` reports it (NetOrk/netork#2728)."""
|
||||
|
||||
@pytest.fixture
|
||||
def listed(self, driver, api):
|
||||
driver.get_vm_interfaces = MagicMock(return_value=({}, False, False))
|
||||
driver._get_vm_disk_and_boot = MagicMock(return_value=([], False))
|
||||
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||
return driver._api.cluster.resources.get
|
||||
|
||||
@staticmethod
|
||||
def _row(vmid, kind, uid=None, node="pve1"):
|
||||
row = {"id": f"{kind}/{vmid}", "type": kind, "vmid": vmid, "node": node}
|
||||
return {**row, "uid": uid} if uid else row
|
||||
|
||||
def test_each_guest_carries_its_uid_from_one_resources_call(self, driver, listed):
|
||||
listed.return_value = [
|
||||
self._row(100, "qemu", "abcdefghijklmnopqrst"),
|
||||
self._row(200, "lxc", "bcdefghijklmnopqrstu"),
|
||||
]
|
||||
assert {vm["vmid"]: vm["uid"] for vm in driver.get_vms()} == {
|
||||
"100": "abcdefghijklmnopqrst",
|
||||
"200": "bcdefghijklmnopqrstu",
|
||||
}
|
||||
listed.assert_called_once_with(type="vm")
|
||||
|
||||
def test_a_guest_without_uid_has_no_key(self, driver, listed):
|
||||
listed.return_value = [
|
||||
self._row(100, "qemu"),
|
||||
# The same vmid on another node is another guest.
|
||||
self._row(200, "lxc", "bcdefghijklmnopqrstu", node="pve2"),
|
||||
]
|
||||
assert all("uid" not in vm for vm in driver.get_vms())
|
||||
|
||||
def test_unreadable_resources_leave_the_listing_without_uids(self, driver, listed):
|
||||
listed.side_effect = Exception("403 Forbidden")
|
||||
vms = driver.get_vms()
|
||||
assert [vm["vmid"] for vm in vms] == ["100", "200"]
|
||||
assert all("uid" not in vm for vm in vms)
|
||||
|
||||
def test_an_older_node_is_not_asked(self, driver, listed):
|
||||
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||
assert all("uid" not in vm for vm in driver.get_vms())
|
||||
listed.assert_not_called()
|
||||
|
||||
|
||||
class TestGetVmsTellsPausedFromRunning:
|
||||
"""PVE reports a paused guest ``status: running``; only ``qmpstatus`` tells, and only
|
||||
when the listing is asked for the full status (NetOrk/netork#2658)."""
|
||||
@@ -130,6 +177,21 @@ class TestPowerActions:
|
||||
guest.status.resume.post.assert_called_once()
|
||||
driver._wait_for_task.assert_called_once_with("UPID:resume", timeout=120)
|
||||
|
||||
def test_resume_on_pve_9_3_sets_the_guests_clock(self, driver, api):
|
||||
"""``sync-time-on-resume``: the guest agent sets the guest's clock (NetOrk/netork#2728)."""
|
||||
driver._api.version.get.return_value = {"version": "9.3.0", "release": "9.3"}
|
||||
guest = api.qemu.return_value
|
||||
guest.status.current.get.return_value = {"status": "running", "qmpstatus": "paused"}
|
||||
driver.resume_vm("100")
|
||||
guest.status.resume.post.assert_called_once_with(**{"sync-time-on-resume": 1})
|
||||
|
||||
def test_resume_on_an_older_node_sends_no_clock_sync(self, driver, api):
|
||||
driver._api.version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||
guest = api.qemu.return_value
|
||||
guest.status.current.get.return_value = {"status": "running", "qmpstatus": "paused"}
|
||||
driver.resume_vm("100")
|
||||
guest.status.resume.post.assert_called_once_with()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"current", [{"status": "running", "qmpstatus": "running"}, {"status": "stopped"}]
|
||||
)
|
||||
|
||||
@@ -380,3 +380,65 @@ class TestNodeMaintenance:
|
||||
run.side_effect = RuntimeError("Command failed (exit 255): ...\nno such node 'pve2'")
|
||||
with pytest.raises(RuntimeError, match="no such node"):
|
||||
drv.set_node_maintenance("pve2", True)
|
||||
|
||||
|
||||
class TestNodeMaintenanceOverRest:
|
||||
"""PVE 9.3 has ``PUT /nodes/{node}/maintenance``: no SSH session at all."""
|
||||
|
||||
def _driver(self, version: str = "9.3.0") -> tuple[Any, MagicMock]:
|
||||
api, _ = _migration_api()
|
||||
api.version.get.return_value = {"version": version, "release": version[:3]}
|
||||
api.nodes("pve2").version.get.return_value = {"version": version, "release": version[:3]}
|
||||
drv = _driver(api)
|
||||
drv._node_ssh = MagicMock() # type: ignore[method-assign]
|
||||
drv._run_node_command = MagicMock(return_value="") # type: ignore[method-assign]
|
||||
return drv, api
|
||||
|
||||
@pytest.mark.parametrize(("enabled", "mode"), [(True, "enable"), (False, "disable")])
|
||||
def test_puts_the_mode_and_opens_no_ssh(self, enabled, mode):
|
||||
drv, api = self._driver()
|
||||
drv.set_node_maintenance("pve2", enabled)
|
||||
api.nodes("pve2").maintenance.put.assert_called_once_with(**{"maintenance-mode": mode})
|
||||
drv._node_ssh.assert_not_called()
|
||||
drv._run_node_command.assert_not_called()
|
||||
|
||||
def test_not_a_member_puts_nothing(self):
|
||||
drv, api = self._driver()
|
||||
with pytest.raises(ValueError, match="not a member"):
|
||||
drv.set_node_maintenance("pve9", True)
|
||||
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||
|
||||
def test_refused(self):
|
||||
drv, api = self._driver()
|
||||
api.nodes("pve2").maintenance.put.side_effect = Exception(
|
||||
"403 Forbidden: Permission check failed (/, Sys.Modify)"
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="Sys.Modify"):
|
||||
drv.set_node_maintenance("pve2", True)
|
||||
drv._node_ssh.assert_not_called()
|
||||
|
||||
def test_older_node_uses_ha_manager_over_ssh(self):
|
||||
drv, api = self._driver("9.2.4")
|
||||
drv.set_node_maintenance("pve2", True)
|
||||
drv._run_node_command.assert_called_once_with(
|
||||
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||
)
|
||||
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||
|
||||
def test_the_target_nodes_version_decides_mid_upgrade(self):
|
||||
# A rolling upgrade: the node the driver is connected to runs 9.3 already,
|
||||
# the one going into maintenance does not, and has no endpoint to proxy to.
|
||||
drv, api = self._driver("9.3.0")
|
||||
api.nodes("pve2").version.get.return_value = {"version": "9.2.4", "release": "9.2"}
|
||||
drv.set_node_maintenance("pve2", True)
|
||||
drv._run_node_command.assert_called_once_with(
|
||||
"ha-manager crm-command node-maintenance enable pve2", timeout=drv.timeout
|
||||
)
|
||||
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||
|
||||
def test_an_unreadable_target_version_is_a_runtime_error(self):
|
||||
drv, api = self._driver()
|
||||
api.nodes("pve2").version.get.side_effect = ConnectionError("pve2 unreachable")
|
||||
with pytest.raises(RuntimeError, match="pve2"):
|
||||
drv.set_node_maintenance("pve2", True)
|
||||
api.nodes("pve2").maintenance.put.assert_not_called()
|
||||
@@ -12,6 +12,7 @@ import base64
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import OPENED_PORTS_RECORD
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||
|
||||
@@ -38,6 +39,11 @@ class _Node:
|
||||
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)
|
||||
@@ -50,6 +56,14 @@ class _Node:
|
||||
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:
|
||||
@@ -144,3 +158,86 @@ def test_a_config_that_cannot_be_read_stops_the_fix(driver, node):
|
||||
|
||||
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