"""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, 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.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, SystemIdentityMixin, SystemdServicesMixin, 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 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, }