Files
napalm-proxmox/napalm_proxmox/driver.py
T
Christian Manivong 410d34bdee
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / test (3.13) (pull_request) Successful in 59s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 31s
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Successful in 2m41s
driver / publish (pull_request) Skipped
feat(time-sync): servers and zone on Proxmox VE and Backup Server
netOrk keeps one list of NTP servers and a time zone per site and aligns
a device that differs (NetOrk/netork#2360, #2365). Both drivers now
implement napalm-device-types' TimeSyncMixin (4.35.0) and write both
values.

Neither API keeps time servers: /nodes/{node}/time knows only the zone,
and both products run chrony on Debian. The servers are therefore
PosixTimeSyncMixin's, over the driver's existing SSH session
(run_command, root): read from chrony's configuration, written to
/etc/chrony/sources.d/netork.sources with every other source commented
out, then a reload or a restart of chrony.

The zone is read with them from the host (timedatectl: the zone the
clock really runs in), and from GET /nodes/{node}/time only where the
host names none. It is written through PUT /nodes/{node}/time rather
than timedatectl set-timezone: Proxmox's own call validates the name and
keeps /etc/timezone, which its web UI and API show, in step with
/etc/localtime.

One device is one node: in a PVE cluster every node has its own clock,
and only the node this connection resolved is read and written.

get_ntp_servers() read GET /nodes/{node}/ntp, a path Proxmox VE does not
have, so it always reported no servers. It now reports what
get_time_sync() reads, on the backup server too.
2026-11-11 15:18:08 +01:00

250 lines
8.9 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.time_sync import ProxmoxTimeSyncMixin
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,
ProxmoxTimeSyncMixin,
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"
)
# ------------------------------------------------------------------ #
# 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,
}