Files
napalm-proxmox/napalm_proxmox/pbs_host.py
T
Christian Manivong 2b2cd9b867
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m5s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m20s
driver / publish (pull_request) Skipped
feat(pbs): Proxmox Backup Server as entry point proxmox_backup (#52)
A second driver in this package, ProxmoxBackupDriver. Its API and web UI
are on 8007, not on PVE's 8006, and its node is always localhost; open()
proves the login with GET /version, so a bad token fails there.

Roles: BackupServerDriver (napalm-device-types 4.25.0) first, then
StorageDriver for the disks and ZFS pools the server manages. It reads
datastores, the backup groups of every namespace with their newest
snapshot, a group's snapshots, the GC, verify, prune, sync and tape jobs
with how their last run ended, and the remotes without their secrets;
it starts garbage collection and jobs, verifies, protects and deletes
snapshots, and follows the tasks. As a host it reports facts,
interfaces, CPU and memory, disks, pools, its pbs-subscription and the
same packages, updates, host readers and sshd hardening as a PVE node.

A privilege-separated token without an ACL entry gets an empty list from
PBS, not a refusal, so every read checks /access/permissions and raises
PermissionError. A removable datastore that is not mounted is reported
as unmounted and left out of the group listing.

The fixture is what a PBS 4.2 answered, sanitised; groups, snapshots and
jobs it did not have yet follow the API schema.
2026-11-02 22:29:21 +01:00

169 lines
6.8 KiB
Python

"""The Proxmox Backup Server as a host: facts, interfaces, environment, and the
disks and ZFS pools it manages (``StorageDriver``, its second role).
The API answers most of it; the shell over SSH adds what the API does not
carry (the host name, DMI, the interfaces' MAC addresses). Without an SSH login
those stay at what the API alone can say.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types.models import DiskPoolDict, PhysicalDiskDict
from napalm_proxmox import utils
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: Each interface's name and MAC address, one per line.
LINK_ADDRESSES_COMMAND = (
'for i in /sys/class/net/*; do echo "${i##*/} $(cat "$i/address" 2>/dev/null)"; done'
)
_HEALTH = {"passed": "healthy", "failed": "failed"}
_POOL_STATUS = {"online": "online", "degraded": "degraded", "faulted": "faulted"}
class ProxmoxPbsHostMixin:
"""Host getters of the PBS driver."""
hostname: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _exec_ssh_command(self, command: str) -> str: ...
def _node_api(self) -> Any: ...
def _hardware(self) -> tuple[str, str, str]: ...
def _get_node_status(self) -> _JsonDict: ...
def _get_node_network(self) -> list[_JsonDict]: ...
def _get_version_info(self) -> _JsonDict: ...
def _shell(self, command: str) -> str | None:
"""*command*'s output, or None where the server has no SSH login for us."""
try:
return self._exec_ssh_command(command)
except ConnectionException as exc:
logger.debug("%s: no shell for %r: %s", self.hostname, command, exc)
return None
def get_facts(self) -> _JsonDict:
"""Facts from the API, with the host name and DMI over SSH where it is open."""
status = self._get_node_status()
version = self._get_version_info().get("version", "")
fqdn = (self._shell("hostname -f") or "").strip() or self.hostname
vendor, model, serial = self._hardware()
return {
"uptime": float(status.get("uptime", 0)),
"vendor": vendor or "Proxmox Server Solutions GmbH",
"model": model or "Proxmox Backup Server",
"hostname": fqdn.split(".")[0] if fqdn != self.hostname else fqdn,
"fqdn": fqdn,
"os_version": f"Proxmox Backup Server {version}".strip(),
"serial_number": serial,
"interface_list": sorted(
i["iface"] for i in self._get_node_network() if i.get("iface")
),
"running_kernel": (status.get("current-kernel") or {}).get("release", ""),
}
def _link_macs(self) -> dict[str, str]:
out = self._shell(LINK_ADDRESSES_COMMAND) or ""
macs: dict[str, str] = {}
for line in out.splitlines():
name, _, mac = line.strip().partition(" ")
if name and mac:
macs[name] = utils.normalize_mac(mac.strip())
return macs
def get_interfaces(self) -> dict[str, _JsonDict]:
"""The interfaces the server's network configuration lists. The API carries
no MAC address; it is read over SSH, and empty without it."""
macs = self._link_macs()
result: dict[str, _JsonDict] = {}
for iface in self._get_node_network():
name = iface.get("iface", "")
if not name:
continue
result[name] = {
"is_up": bool(iface.get("active")),
"is_enabled": bool(iface.get("autostart")) or bool(iface.get("active")),
"description": (iface.get("comments") or "").strip(),
"last_flapped": -1.0,
"speed": utils.speed_mbps(iface),
"mtu": int(iface.get("mtu") or 1500),
"mac_address": macs.get(name, utils.normalize_mac(iface.get("hwaddr", ""))),
}
return result
def get_interfaces_ip(self) -> dict[str, _JsonDict]:
result: dict[str, _JsonDict] = {}
for iface in self._get_node_network():
addrs = utils.addresses_from_node_network(iface)
if iface.get("iface") and addrs:
result[iface["iface"]] = addrs
return result
def get_environment(self) -> _JsonDict:
"""CPU and memory from the node status; a PBS reports no sensors."""
status = self._get_node_status()
mem = status.get("memory") or {}
return {
"fans": {},
"temperature": {},
"power": {},
"cpu": {"0": {"%usage": round(float(status.get("cpu") or 0.0) * 100, 2)}},
"memory": {
"available_ram": int(mem.get("total") or 0),
"used_ram": int(mem.get("used") or 0),
},
}
# ------------------------------------------------------------------ #
# Storage role
# ------------------------------------------------------------------ #
def get_disks(self) -> list[PhysicalDiskDict]:
"""The server's disks (``/nodes/{node}/disks/list``), as it classifies them."""
disks: list[PhysicalDiskDict] = []
for raw in self._node_api().disks.list.get() or []:
kind = raw.get("disk-type")
disks.append(
{
"slot": raw.get("name") or raw.get("devpath", ""),
"model": raw.get("model") or "",
"serial": raw.get("serial") or "",
"vendor": raw.get("vendor") or "",
"type": kind if kind in ("ssd", "nvme") else "hdd",
"size": int(raw.get("size") or 0),
"rpm": int(raw.get("rpm") or 0),
"temperature": -1,
"health": _HEALTH.get(str(raw.get("status", "")).lower(), "unknown"),
"pool": "",
}
)
return disks
def get_disk_pools(self) -> dict[str, DiskPoolDict]:
"""The ZFS pools the server manages (``/nodes/{node}/disks/zfs``)."""
pools: dict[str, DiskPoolDict] = {}
for raw in self._node_api().disks.zfs.get() or []:
name = raw["name"]
pools[name] = {
"name": name,
"type": "zfs",
"level": "",
"status": _POOL_STATUS.get(str(raw.get("health", "")).lower(), "unknown"),
"total": int(raw.get("size") or 0),
"used": int(raw.get("alloc") or 0),
"available": int(raw.get("free") or 0),
"disks": [],
"auto_expand": False,
"dedup": float(raw.get("dedup") or 1.0) > 1.0,
"compression": "",
}
return pools