Files
napalm-proxmox/napalm_proxmox/driver.py
T
Christian Manivong 3877a5425a
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 54s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Successful in 2m10s
driver / publish (pull_request) Skipped
feat(running-backups): what a restart of a PVE node, a guest or a PBS would abort
netOrk holds a host's restart after patching while a backup runs on it, and
a guest's restart while its hypervisor is backing it up (NetOrk/netork#2318).
It asks right before the restart, so both drivers answer
get_running_backups() from napalm-device-types 4.34.0:

- PVE: the node's active vzdump tasks, each with the guests it is taking now
  (its own guest, or for a job the guests locked for their backup), and a
  guest locked without a task on its own, since the task list can lag and a
  lock can outlive its task.
- PBS: the running backup, sync, verify, gc, prune and tape tasks; a restore
  or housekeeping is no backup.

A failed read raises, so netOrk reads it as "not checked", never as "none".
2026-11-10 23:45:48 +01:00

260 lines
9.3 KiB
Python

"""NAPALM driver for Proxmox VE.
Supports:
- Classic Linux networking (/etc/network/interfaces via Proxmox API)
- Software-Defined Networking (SDN): zones, VNets, subnets
- Open vSwitch (OVS) bridges, bonds, and internal ports
Connection is made via the Proxmox REST API (``proxmoxer`` library).
The driver targets the *node* level: each Proxmox node is treated as a
network device. Cluster-wide SDN information is also exposed where the
NAPALM API allows it.
Optional args
-------------
The connection's are the shared base's (``napalm_proxmox._base``; the API port
defaults to 8006 here). In addition:
node : str
Override the target node name (default: auto-detected from hostname).
"""
from __future__ import annotations
import logging
from typing import Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types import (
AptProxyMixin,
EnsurePackageMixin,
FingerprintRule,
HostStatusMixin,
HypervisorDriver,
KernelFactsMixin,
LicenseMixin,
ListeningSocketsMixin,
LogSourcesMixin,
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
SnmpAgentMixin,
SystemdServicesMixin,
SystemIdentityMixin,
)
try:
from proxmoxer import ProxmoxAPI
except ImportError as exc:
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
from napalm_proxmox.running_backups import ProxmoxRunningBackupsMixin
from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
logger = logging.getLogger(__name__)
# --------------------------------------------------------------------------- #
# Type aliases
# --------------------------------------------------------------------------- #
_JsonDict = dict[str, Any]
# --------------------------------------------------------------------------- #
# Driver
# --------------------------------------------------------------------------- #
class ProxmoxDriver(
ProxmoxBase,
ProxmoxInterfaceMixin,
ProxmoxSDNMixin,
ProxmoxLLDPMixin,
ProxmoxConfigMixin,
ProxmoxVMMixin,
ProxmoxVMContractMixin,
ProxmoxVMSnapshotMixin,
ProxmoxVMProvisionMixin,
ProxmoxClusterMixin,
ProxmoxVMMigrateMixin,
ProxmoxRoutingMixin,
ProxmoxSystemMixin,
ProxmoxHostMixin,
KernelFactsMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
LogSourcesMixin,
SystemIdentityMixin,
SystemdServicesMixin,
ProxmoxScheduledJobsMixin,
ProxmoxRunningBackupsMixin,
HostStatusMixin,
LicenseMixin,
SnmpAgentMixin,
EnsurePackageMixin,
AptProxyMixin,
OpenSshServerMixin,
HypervisorDriver,
):
"""NAPALM driver for Proxmox VE nodes."""
VENDOR = "Proxmox"
DRIVER_NAME = "proxmox"
# netOrk reaches the node through the REST API and does not log in over SSH
# itself; the driver's own SSH session (_node_ssh) runs the node's shell.
USES_SSH = False
# A PVE node reboots through a full init sequence plus storage checks.
REBOOT_SETTLE_SECONDS = 90
#: "Upgrade everything" must be a full upgrade on Proxmox VE: a plain
#: ``apt-get upgrade`` holds back what needs new or removed packages and can
#: leave the node half updated. netOrk reads this when it upgrades the host.
FULL_UPGRADE = True
#: Proxmox VE's own timers and cron file are ``platform``.
PLATFORM_SOURCES = PVE_PLATFORM_SOURCES
#: ``/etc/cron.d/vzdump`` links into ``/etc/pve`` (pmxcfs); its lines are only run.
RUN_ONLY_SOURCES = ("/etc/cron.d/vzdump",)
PORT_SPECS = [
PortSpec("https", 8006, weight=8.0),
]
SSH_FINGERPRINT = [
FingerprintRule("debian", weight=3.0),
]
HTTP_FINGERPRINT = [
FingerprintRule("proxmox virtual environment", weight=9.0, mandatory=True),
FingerprintRule("proxmox", weight=5.0),
FingerprintRule("pve", weight=2.0),
]
platform = "proxmox"
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: _JsonDict | None = None,
) -> None:
super().__init__(hostname, username, password, timeout, optional_args)
self._node: str | None = self.optional_args.get("node")
# Candidate config (merge/replace)
self._candidate_config: str = ""
self._running_config: str = ""
# ------------------------------------------------------------------ #
# Connection management
# ------------------------------------------------------------------ #
def _proxmox_api(self, **kwargs: Any) -> Any:
return ProxmoxAPI(**kwargs)
def _resolve_node(self) -> str:
"""Resolve the PVE node this connection talks to.
In a cluster, ``GET /nodes`` lists every member, so its first entry is
just some node, not necessarily the one at ``self.hostname``. That used
to be taken blindly, and a device then reported another node's name and
VMs. ``GET /cluster/status`` marks the node the session landed on with
``local: 1``; failing that, the node is matched by IP or name.
API errors propagate so that ``open()`` fails with the real cause (e.g.
a TLS verification error) rather than succeeding on a guessed name.
"""
if self._node:
self._node_name = self._node
return self._node_name
members = [s for s in (self._api.cluster.status.get() or []) if s.get("type") == "node"]
short_host = self.hostname.split(".")[0]
for pick in (
lambda s: s.get("local"),
lambda s: s.get("ip") == self.hostname,
lambda s: s.get("name") in (self.hostname, short_host),
):
match = next((s for s in members if pick(s)), None)
if match:
self._node_name = match["name"]
return self._node_name
names = [n.get("node") for n in (self._api.nodes.get() or []) if n.get("node")]
if len(names) == 1:
self._node_name = names[0]
return self._node_name
raise ConnectionException(
f"Cannot tell which PVE node {self.hostname} is among {names}; "
f"set the 'node' driver argument"
)
# ------------------------------------------------------------------ #
# Node info helpers (PVE only)
# ------------------------------------------------------------------ #
def _get_node_ntp(self) -> _JsonDict:
"""Return NTP configuration for this node."""
try:
return self._node_api().ntp.get() or {}
except Exception as exc:
logger.debug("Failed to fetch node NTP: %s", exc)
return {}
# ------------------------------------------------------------------ #
# NAPALM getters kept in driver
# ------------------------------------------------------------------ #
def get_facts(self) -> _JsonDict:
"""Return basic facts about the Proxmox node.
Hardware vendor, model and serial are read from the Linux DMI sysfs
entries (``/sys/class/dmi/id/``) via SSH so they reflect the physical
machine, not the Proxmox software layer.
"""
status = self._get_node_status()
version = self._get_version_info()
network = self._get_node_network()
dns = self._get_node_dns()
uptime = float(status.get("uptime", 0))
dns_search = dns.get("search", "")
fqdn = f"{self._node_name}.{dns_search}" if dns_search else self.hostname
iface_list = sorted(iface["iface"] for iface in network if iface.get("iface"))
pve_version = version.get("version", "")
release = version.get("release", "")
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
vendor, model, serial = self._hardware()
# Currently-booted kernel release (uname -r) — distinct from any newer
# kernel that is merely installed and pending a reboot.
running_kernel = ""
try:
running_kernel = self._exec_ssh_command("uname -r").strip()
except Exception as exc:
logger.debug("Failed to read running kernel via SSH: %s", exc)
return {
"uptime": uptime,
"vendor": vendor or "Proxmox Server Solutions GmbH",
"model": model or status.get("model") or "Proxmox VE Node",
"hostname": self._node_name,
"fqdn": fqdn or self.hostname,
"os_version": os_version,
"serial_number": serial,
"interface_list": iface_list,
"running_kernel": running_kernel,
}