"""HypervisorDriver.get_clusters() for Proxmox VE: the cluster this node belongs to. Every PVE node can read its whole cluster, so the getter always reports exactly one cluster, the one the connected node is a member of (a standalone node is a cluster of one, without a name). Read from: - ``GET /cluster/status``: the cluster's name and quorum, and every member with ``online`` and ``local``; - ``GET /cluster/resources``: per node ``maxcpu``, ``cpu``, ``maxmem``, ``mem``; per node and storage one row with ``plugintype``, ``shared``, ``content``, ``maxdisk``, ``disk`` and ``status``; - ``GET /nodes/{node}/status`` of each online node: ``cpuinfo``; - ``GET /nodes/{node}/network`` of each online node: its bridges; - ``GET /cluster/sdn/vnets`` and ``/cluster/sdn/zones``: the vnets, on the nodes of their zone; - ``GET /cluster/ha/status/manager_status``: which node is in maintenance. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, NamedTuple from napalm_proxmox.network_targets import bridge_targets, vnet_target from napalm_proxmox.utils import cpu_flags if TYPE_CHECKING: # Type-only: the cluster models are newer than the napalm_device_types floor # in pyproject.toml, and nothing here needs them at runtime. from napalm_device_types import ( ClusterDict, ClusterNetworkDict, ClusterNodeDict, ClusterStorageDict, ) logger = logging.getLogger(__name__) _JsonDict = dict[str, Any] class _Member(NamedTuple): name: str online: bool local: bool class _Cpu(NamedTuple): cores: int | None = None model: str | None = None flags: list[str] | None = None def _int(value: Any) -> int | None: return None if value is None else int(value) def _float(value: Any) -> float | None: return None if value is None else float(value) def _flag(value: Any) -> bool: return bool(int(value or 0)) def _list(value: Any) -> list[str]: return [part.strip() for part in str(value or "").split(",") if part.strip()] def _size(rows: list[_JsonDict], key: str, shared: bool) -> int | None: """One storage's size over the nodes in *rows*: summed unless it is shared.""" values = [row.get(key) for row in rows] if not values or any(value is None for value in values): return None sizes = [int(value) for value in values if value is not None] return sizes[0] if shared else sum(sizes) def _storage(name: str, rows: list[_JsonDict]) -> ClusterStorageDict: shared = any(_flag(row.get("shared")) for row in rows) available = [row for row in rows if row.get("status") == "available"] return { "name": name, "type": str(rows[0].get("plugintype") or ""), "shared": shared, "content": _list(rows[0].get("content")), "nodes": [str(row.get("node")) for row in available], "total": _size(available, "maxdisk", shared), "used": _size(available, "disk", shared), } def _storages(resources: list[_JsonDict]) -> list[ClusterStorageDict]: groups: dict[str, list[_JsonDict]] = {} for row in resources: if row.get("type") == "storage" and row.get("storage"): groups.setdefault(str(row["storage"]), []).append(row) return [_storage(name, rows) for name, rows in groups.items()] def _merge_bridges(per_node: list[tuple[str, list[_JsonDict]]]) -> list[ClusterNetworkDict]: merged: dict[str, ClusterNetworkDict] = {} for node, network in per_node: for target in bridge_targets(network): entry = merged.setdefault( target["name"], {"name": target["name"], "kind": "bridge", "vlan_aware": True, "nodes": []}, ) entry["vlan_aware"] = entry["vlan_aware"] and target["vlan_aware"] entry["nodes"].append(node) return list(merged.values()) class ProxmoxClusterMixin: """Relies on ``_api``/``_node_name`` from the driver and the SDN readers.""" _api: Any _node_name: str _get_sdn_vnets: Any _get_sdn_zones: Any def get_clusters(self) -> list[ClusterDict]: """ Return the one cluster this node belongs to, its nodes, storages and networks. - ``id`` is 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. - Every member is listed. An offline node has ``status`` ``"offline"`` and no capacity values: its own API cannot be asked. ``local`` marks the node ``/cluster/status`` calls local, or else the node this driver talks to. ``maintenance`` comes from the HA manager; when that cannot be read (no HA stack, no permission) or does not track a node, it is None. If another node's status cannot be read although the cluster calls it online, its CPU fields are None and its bridges are not listed; the own node's must be readable. - A storage is one entry per name, with the nodes it is ``available`` on. ``total``/``used``: a shared storage is the same space on every node, so it is one node's figure; a local storage of that name is a separate disk on each node, so the figures of its nodes add up — the room any single node has is less. None when no node reports it. - Networks: each bridge once, with every online node that has one of that name; ``vlan_aware`` only if it is on all of them. A vnet is on the nodes of its zone, all members when the zone names none. Raises: Whatever the API raises for ``/cluster/status``, ``/cluster/resources`` or the own node: a getter that cannot read does not report less. """ status = self._api.cluster.status.get() or [] resources = self._api.cluster.resources.get() or [] head = next((s for s in status if s.get("type") == "cluster"), None) members = self._members(status if head else []) return [ { "id": None, "name": (head.get("name") or None) if head else None, "quorate": _flag(head.get("quorate")) if head else None, "nodes": self._cluster_nodes(members, resources), "storages": _storages(resources), "networks": self._networks(members), } ] def _cluster_nodes( self, members: list[_Member], resources: list[_JsonDict] ) -> list[ClusterNodeDict]: rows = {r.get("node"): r for r in resources if r.get("type") == "node"} maintenance = self._maintenance() return [self._cluster_node(m, rows.get(m.name, {}), maintenance) for m in members] def _networks(self, members: list[_Member]) -> list[ClusterNetworkDict]: online = [m for m in members if m.online] return [ *_merge_bridges([(m.name, self._node_network(m)) for m in online]), *self._vnets([m.name for m in members]), ] def _members(self, status: list[_JsonDict]) -> list[_Member]: entries = [s for s in status if s.get("type") == "node" and s.get("name")] if not entries: return [_Member(self._node_name, online=True, local=True)] any_local = any(_flag(s.get("local")) for s in entries) return [ _Member( str(s["name"]), online=_flag(s.get("online")), local=_flag(s.get("local")) if any_local else s["name"] == self._node_name, ) for s in entries ] def _maintenance(self) -> dict[str, bool] | None: try: status = self._api.cluster.ha.status.manager_status.get() or {} except Exception as exc: logger.debug("Cannot read the HA manager status: %s", exc) return None node_status = (status.get("manager_status") or {}).get("node_status") or {} return {str(node): state == "maintenance" for node, state in node_status.items()} def _read_node(self, member: _Member, path: str) -> Any: """``GET /nodes/{node}/{path}``; None for another node that does not answer.""" try: return getattr(self._api.nodes(member.name), path).get() except Exception as exc: if member.local: raise logger.warning("Cannot read %s of cluster node %s: %s", path, member.name, exc) return None def _node_network(self, member: _Member) -> list[_JsonDict]: return self._read_node(member, "network") or [] def _cpu(self, member: _Member) -> _Cpu: status = self._read_node(member, "status") if status is None: return _Cpu() info = status.get("cpuinfo") or {} cores, sockets = info.get("cores"), info.get("sockets") return _Cpu( cores=int(cores) * int(sockets) if cores and sockets else None, model=info.get("model") or None, flags=cpu_flags(status), ) def _cluster_node( self, member: _Member, row: _JsonDict, maintenance: dict[str, bool] | None ) -> ClusterNodeDict: if not member.online: row, cpu = {}, _Cpu() else: cpu = self._cpu(member) return { "name": member.name, "status": "online" if member.online else "offline", "local": member.local, "maintenance": None if maintenance is None else maintenance.get(member.name), "cpu_threads": _int(row.get("maxcpu")), "cpu_cores": cpu.cores, "cpu_model": cpu.model, "cpu_flags": cpu.flags, "cpu_usage": _float(row.get("cpu")), "memory_total": _int(row.get("maxmem")), "memory_used": _int(row.get("mem")), } def _vnets(self, members: list[str]) -> list[ClusterNetworkDict]: vnets = self._get_sdn_vnets() zones = {z.get("zone"): z for z in self._get_sdn_zones()} if vnets else {} networks: list[ClusterNetworkDict] = [] for vnet in vnets: target, zone = vnet_target(vnet), zones.get(vnet.get("zone")) if target is None or zone is None: continue only = set(_list(zone.get("nodes"))) networks.append( { "name": target["name"], "kind": "vnet", "vlan_aware": False, "fixed_vlan_tag": target.get("fixed_vlan_tag"), "nodes": [n for n in members if not only or n in only], } ) return networks