feat: Proxmox VE 9.3 API additions (NetOrk/netork#2728)
On a node running 9.3: HA maintenance over PUT /nodes/{node}/maintenance
(the target node's version decides, SSH below it), the guest uid in
get_vms, the cluster-id as ClusterDict.id, sync-time-on-resume on resume.
get_credential_expiry reads the expiry of the token or account the driver
logged in with; get_update_history lists the node's APT transactions.
Needs napalm-device-types 4.44.0.
This commit is contained in:
1 parent
c2d9d7e75e
commit
fddf8af680
17 files changed
+718
-17
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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+$")
|
||||
|
||||
Reference in new issue
Block a user