refactor: share connection and Debian host code for a second product (#52)
Proxmox Backup Server speaks the same REST dialect, logs in the same way and runs on Debian too, so what a second driver needs moves out of ProxmoxDriver first: - napalm_proxmox._base: the connection (proxmoxer service PVE or PBS, each with its port), the token split, the SSH session, run_command, the node helpers and the DMI read. - napalm_proxmox.host_mixin: packages and APT updates, the subscription, restart and shutdown through the API, root file writes and the transports of the host readers (kernel, listening sockets, identity, systemd, host status, apt's proxy). The PVE driver behaves as before; what it hands proxmoxer is pinned by tests first, and it now names service="PVE" explicitly. get_packages is split so the dpkg line parser stands alone; get_facts and get_packages leave the quality baseline.
This commit is contained in:
1 parent
a4c220d2e3
commit
0b5f82cc02
8 files changed
+786
-593
No files matched your search
@@ -0,0 +1,408 @@
|
|||||||
|
"""What the Proxmox VE and the Proxmox Backup Server drivers share.
|
||||||
|
|
||||||
|
Both products speak the same REST dialect (``/api2/json``, ``/nodes/{node}/...``),
|
||||||
|
authenticate the same way (``user@realm`` with a password, or an API token
|
||||||
|
``user@realm!name``) and run on Debian, where the driver opens its own SSH
|
||||||
|
session as root for what the API does not offer. They differ in the service
|
||||||
|
proxmoxer talks to, its port (PVE 8006, PBS 8007) and how the node is found.
|
||||||
|
|
||||||
|
Optional args
|
||||||
|
-------------
|
||||||
|
verify_ssl : bool
|
||||||
|
Verify TLS certificates (default: True). ``ssl_verify`` and ``verify`` are
|
||||||
|
accepted as well.
|
||||||
|
port : int
|
||||||
|
API port (default: the service's, 8006 for PVE, 8007 for PBS).
|
||||||
|
realm : str
|
||||||
|
Realm a bare username logs in to (default: ``pam``).
|
||||||
|
token_name : str
|
||||||
|
API token name (e.g. ``root@pam!netork``).
|
||||||
|
token_value : str
|
||||||
|
API token secret. With both token_name and token_value, the token is used
|
||||||
|
instead of the password.
|
||||||
|
ssh_username, ssh_password, ssh_private_key_str : str
|
||||||
|
The node's SSH login; the API login's username and password otherwise.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from napalm.base.exceptions import ConnectionException
|
||||||
|
from napalm_device_types import CommandResult
|
||||||
|
from napalm_device_types.channel import run_on_transport
|
||||||
|
from napalm_device_types.ssh_host_keys import HostKeyCheck
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The API port of each proxmoxer service this package drives.
|
||||||
|
DEFAULT_PORTS = {"PVE": 8006, "PBS": 8007}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxBase:
|
||||||
|
"""Connection, SSH session and node helpers of a Proxmox product's driver.
|
||||||
|
|
||||||
|
A concrete driver sets :attr:`SERVICE`, says how it finds its node
|
||||||
|
(:meth:`_resolve_node`) and constructs the proxmoxer client
|
||||||
|
(:meth:`_proxmox_api`), so its own module names the client class.
|
||||||
|
"""
|
||||||
|
|
||||||
|
#: The proxmoxer service: ``"PVE"`` or ``"PBS"``.
|
||||||
|
SERVICE = "PVE"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hostname: str,
|
||||||
|
username: str,
|
||||||
|
password: str,
|
||||||
|
timeout: int = 60,
|
||||||
|
optional_args: _JsonDict | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.hostname = hostname
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
self.timeout = timeout
|
||||||
|
self.optional_args: _JsonDict = optional_args or {}
|
||||||
|
|
||||||
|
self._port: int = self.optional_args.get("port", DEFAULT_PORTS[self.SERVICE])
|
||||||
|
verify: Any = self.optional_args.get(
|
||||||
|
"verify_ssl",
|
||||||
|
self.optional_args.get("ssl_verify", self.optional_args.get("verify", True)),
|
||||||
|
)
|
||||||
|
self._verify_ssl: bool = verify
|
||||||
|
self._realm: str = self.optional_args.get("realm", "pam")
|
||||||
|
self._token_name: str | None = self.optional_args.get("token_name")
|
||||||
|
self._token_value: str | None = self.optional_args.get("token_value")
|
||||||
|
|
||||||
|
self._ssh_username: str | None = self.optional_args.get("ssh_username")
|
||||||
|
self._ssh_password: str | None = self.optional_args.get("ssh_password")
|
||||||
|
self._ssh_key: str | None = self.optional_args.get("ssh_private_key_str")
|
||||||
|
|
||||||
|
self._api: Any = None # proxmoxer.ProxmoxAPI
|
||||||
|
self._node_name: str = ""
|
||||||
|
# paramiko.SSHClient; paramiko is imported lazily (see _node_ssh).
|
||||||
|
self._ssh_client: Any = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Connection management
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def _proxmox_api(self, **kwargs: Any) -> Any:
|
||||||
|
"""The proxmoxer client for *kwargs*; the concrete driver's module names the class."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _resolve_node(self) -> str:
|
||||||
|
"""Find the node this connection talks to and set ``_node_name``.
|
||||||
|
|
||||||
|
API errors propagate, so that ``open()`` fails with the real cause.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _api_kwargs(self) -> _JsonDict:
|
||||||
|
# Use the HTTPS backend for proper REST API support.
|
||||||
|
# The openssh backend tunnels all kwargs through to
|
||||||
|
# openssh_wrapper.CommandBaseSession, which does not
|
||||||
|
# accept password/verify_ssl/token params.
|
||||||
|
# Proxmox authenticates against "<user>@<realm>" and rejects a bare
|
||||||
|
# username outright. A caller who typed a realm keeps it; one who
|
||||||
|
# did not gets self._realm, which is what the documented `realm`
|
||||||
|
# optional_arg is for -- it was read in __init__ and then never
|
||||||
|
# used, so the option had no effect and a bare username failed.
|
||||||
|
user = self.username or ""
|
||||||
|
if user and "@" not in user:
|
||||||
|
user = f"{user}@{self._realm}"
|
||||||
|
|
||||||
|
kwargs: _JsonDict = {
|
||||||
|
"host": self.hostname,
|
||||||
|
"user": user,
|
||||||
|
"password": self.password,
|
||||||
|
"port": self._port,
|
||||||
|
"verify_ssl": self._verify_ssl,
|
||||||
|
"backend": "https",
|
||||||
|
"service": self.SERVICE,
|
||||||
|
}
|
||||||
|
|
||||||
|
if self._token_name and self._token_value:
|
||||||
|
kwargs.pop("password", None)
|
||||||
|
kwargs["token_value"] = self._token_value
|
||||||
|
# token_name may be in "<user>!<tokenid>" format (e.g.
|
||||||
|
# "root@pam!netork"). proxmoxer expects them split:
|
||||||
|
# user="root@pam", token_name="netork"
|
||||||
|
user_part, _, token_id = self._token_name.partition("!")
|
||||||
|
if token_id:
|
||||||
|
kwargs["user"] = user_part
|
||||||
|
kwargs["token_name"] = token_id
|
||||||
|
else:
|
||||||
|
kwargs["token_name"] = self._token_name
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
def open(self) -> None:
|
||||||
|
"""Open the connection to the Proxmox API."""
|
||||||
|
try:
|
||||||
|
self._api = self._proxmox_api(**self._api_kwargs())
|
||||||
|
# Validate the connection: finding the node needs a working login.
|
||||||
|
self._resolve_node()
|
||||||
|
except Exception as exc:
|
||||||
|
raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""Close the connection."""
|
||||||
|
self._api = None
|
||||||
|
if self._ssh_client:
|
||||||
|
try:
|
||||||
|
self._ssh_client.close()
|
||||||
|
except Exception:
|
||||||
|
logger.debug("%s: closing the SSH session: ignored", self.hostname, exc_info=True)
|
||||||
|
self._ssh_client = None
|
||||||
|
|
||||||
|
def is_alive(self) -> _JsonDict:
|
||||||
|
"""Return connection liveness.
|
||||||
|
|
||||||
|
Probes ``GET /version``, the cheapest endpoint that proves the session
|
||||||
|
still authenticates. It used to call ``_resolve_node()``, which returns
|
||||||
|
early without touching the API whenever a node was configured via
|
||||||
|
optional_args — so a dead connection reported itself alive.
|
||||||
|
"""
|
||||||
|
alive = False
|
||||||
|
if self._api:
|
||||||
|
try:
|
||||||
|
self._api.version.get()
|
||||||
|
alive = True
|
||||||
|
except Exception:
|
||||||
|
logger.debug("%s: liveness probe failed", self.hostname, exc_info=True)
|
||||||
|
return {"is_alive": alive}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Internal API helpers
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def _node_api(self) -> Any:
|
||||||
|
"""Return the API resource for the current node."""
|
||||||
|
return self._api.nodes(self._node_name)
|
||||||
|
|
||||||
|
def _get_node_network(self) -> list[_JsonDict]:
|
||||||
|
"""Return the node's network interface list from the Proxmox API."""
|
||||||
|
try:
|
||||||
|
return self._node_api().network.get() or []
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node network: %s", exc)
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _exec_ssh_command(self, command: str) -> str:
|
||||||
|
"""Run *command* in the node's shell over SSH and return what it printed.
|
||||||
|
|
||||||
|
Stdout only: stderr is not output (a command that wants it says
|
||||||
|
``2>&1``). The exit status is not checked; a caller that needs it asks
|
||||||
|
for it (``_rc``). The node has no API endpoint that runs a shell command
|
||||||
|
(``/nodes/{node}/execute`` runs a batch of API calls), so this is the
|
||||||
|
one way, the same session ``_run_node_command`` uses (see
|
||||||
|
NAPALM/napalm-device-types#35 for the shared transport).
|
||||||
|
|
||||||
|
:raises ConnectionException: when the command could not run: no SSH
|
||||||
|
credential, a refused login or host key (``SshHostKeyMismatch``),
|
||||||
|
an unreachable node, a timeout.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=self.timeout)
|
||||||
|
out: str = stdout.read().decode(errors="replace")
|
||||||
|
err: str = stderr.read().decode(errors="replace").strip()
|
||||||
|
except ConnectionException:
|
||||||
|
raise
|
||||||
|
except _ssh_errors() as exc:
|
||||||
|
raise ConnectionException(
|
||||||
|
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
||||||
|
) from exc
|
||||||
|
if err:
|
||||||
|
logger.debug("%s: stderr of a node command: %s", self.hostname, err[-300:])
|
||||||
|
return out.strip()
|
||||||
|
|
||||||
|
def run_command(
|
||||||
|
self,
|
||||||
|
command: str,
|
||||||
|
*,
|
||||||
|
privileged: bool = False,
|
||||||
|
timeout: float = 60,
|
||||||
|
stdin: bytes | None = None,
|
||||||
|
) -> CommandResult:
|
||||||
|
"""Run *command* on an exec channel of the node's SSH session (``CommandChannelMixin``).
|
||||||
|
|
||||||
|
stdout, stderr and the exit status come back apart; *stdin*, if given, is
|
||||||
|
written and then closed. *privileged* needs nothing more: the node is
|
||||||
|
logged in as root, as for every other command this driver runs there.
|
||||||
|
|
||||||
|
:raises ConnectionException: when the command could not run, or did not
|
||||||
|
finish within *timeout* seconds.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
transport = self._node_ssh().get_transport()
|
||||||
|
return run_on_transport(transport, command, stdin=stdin, timeout=timeout)
|
||||||
|
except ConnectionException:
|
||||||
|
raise
|
||||||
|
except _ssh_errors() as exc:
|
||||||
|
raise ConnectionException(
|
||||||
|
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
|
||||||
|
"""The SSH session to the node on port 22, opened once.
|
||||||
|
|
||||||
|
Its host key is the one the caller expects for port 22, or on first use
|
||||||
|
whichever the node presents; either way it is reported (netork#1167).
|
||||||
|
|
||||||
|
:raises ConnectionException: without a password or a usable key.
|
||||||
|
"""
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
if self._ssh_client is None:
|
||||||
|
# A key is tried first; paramiko falls back to the password. Only
|
||||||
|
# these: not the keys in the process's own ~/.ssh, nor an agent.
|
||||||
|
connect_kwargs: _JsonDict = {
|
||||||
|
"username": self._ssh_username or self.username,
|
||||||
|
"timeout": self.timeout,
|
||||||
|
"look_for_keys": False,
|
||||||
|
"allow_agent": False,
|
||||||
|
}
|
||||||
|
password = self._ssh_password or self.password
|
||||||
|
if password:
|
||||||
|
connect_kwargs["password"] = password
|
||||||
|
pkey = _load_private_key(self._ssh_key) if self._ssh_key else None
|
||||||
|
if pkey is not None:
|
||||||
|
connect_kwargs["pkey"] = pkey
|
||||||
|
if not password and pkey is None:
|
||||||
|
# An API-token-only node: nothing to log in with, so no connection.
|
||||||
|
raise ConnectionException(
|
||||||
|
f"no SSH credential for {self.hostname}: set ssh_password or "
|
||||||
|
"ssh_private_key_str"
|
||||||
|
)
|
||||||
|
client = paramiko.SSHClient()
|
||||||
|
try:
|
||||||
|
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
|
||||||
|
client, **connect_kwargs
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
client.close()
|
||||||
|
raise
|
||||||
|
self._ssh_client = client
|
||||||
|
return self._ssh_client
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# Node info helpers
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def _get_version_info(self) -> _JsonDict:
|
||||||
|
"""Return the product's version info from the API."""
|
||||||
|
try:
|
||||||
|
return self._api.version.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch version info: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_status(self) -> _JsonDict:
|
||||||
|
"""Return the node's status from the Proxmox API."""
|
||||||
|
try:
|
||||||
|
return self._node_api().status.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node status: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_subscription(self) -> _JsonDict:
|
||||||
|
"""Return subscription status for this node."""
|
||||||
|
try:
|
||||||
|
return self._node_api().subscription.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node subscription: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_dns(self) -> _JsonDict:
|
||||||
|
"""Return DNS configuration for this node."""
|
||||||
|
try:
|
||||||
|
return self._node_api().dns.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node DNS: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_node_time(self) -> _JsonDict:
|
||||||
|
"""Return time configuration for this node."""
|
||||||
|
try:
|
||||||
|
return self._node_api().time.get() or {}
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch node time: %s", exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _hardware(self) -> tuple[str, str, str]:
|
||||||
|
"""The physical machine's vendor, model and serial number, from the Linux DMI
|
||||||
|
sysfs entries over SSH; empty strings where they cannot be read."""
|
||||||
|
# Physical hardware info from Linux DMI sysfs.
|
||||||
|
# Read each field separately to avoid shell quoting issues with printf.
|
||||||
|
# Field priority for model:
|
||||||
|
# product_name — human-readable name on most vendors (e.g. "NUC6CAYH",
|
||||||
|
# "ThinkCentre M910x")
|
||||||
|
# product_version — sometimes the marketing name on Lenovo; on Intel NUC
|
||||||
|
# it is the board part number (less useful as model name)
|
||||||
|
# We prefer product_name; fall back to product_version only when
|
||||||
|
# product_name looks like a raw type code (all uppercase + digits, no spaces).
|
||||||
|
vendor = ""
|
||||||
|
model = ""
|
||||||
|
serial = ""
|
||||||
|
try:
|
||||||
|
dmi_cmd = (
|
||||||
|
"v=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null); "
|
||||||
|
"n=$(cat /sys/class/dmi/id/product_name 2>/dev/null); "
|
||||||
|
"r=$(cat /sys/class/dmi/id/product_version 2>/dev/null); "
|
||||||
|
"s=$(cat /sys/class/dmi/id/product_serial 2>/dev/null); "
|
||||||
|
'printf \'%s\\n%s\\n%s\\n%s\\n\' "$v" "$n" "$r" "$s"'
|
||||||
|
)
|
||||||
|
lines = self._exec_ssh_command(dmi_cmd).splitlines()
|
||||||
|
if len(lines) >= 4:
|
||||||
|
vendor = lines[0].strip()
|
||||||
|
product_name = lines[1].strip()
|
||||||
|
product_version = lines[2].strip()
|
||||||
|
serial = lines[3].strip()
|
||||||
|
|
||||||
|
_bad = {"none", "n/a", "not specified", "to be filled by o.e.m."}
|
||||||
|
pv_usable = (
|
||||||
|
product_version
|
||||||
|
and product_version.lower() not in _bad
|
||||||
|
and product_version != product_name
|
||||||
|
# Only prefer product_version when it contains a space —
|
||||||
|
# that indicates a human-readable marketing name like
|
||||||
|
# "ThinkCentre M910x" rather than a part code like "J26843-409".
|
||||||
|
and " " in product_version
|
||||||
|
)
|
||||||
|
model = product_version if pv_usable else product_name
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to read DMI info via SSH: %s", exc)
|
||||||
|
return vendor, model, serial
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
# CLI passthrough
|
||||||
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
|
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
|
||||||
|
"""Execute a list of shell commands and return their outputs."""
|
||||||
|
return {cmd: self._exec_ssh_command(cmd) for cmd in commands}
|
||||||
|
|
||||||
|
|
||||||
|
def _load_private_key(text: str) -> Any: # paramiko.PKey; paramiko is imported lazily
|
||||||
|
"""The SSH private key in *text*, whatever its type, or None when it cannot be read."""
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
for key_class in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
|
||||||
|
try:
|
||||||
|
return key_class.from_private_key(io.StringIO(text))
|
||||||
|
except (paramiko.SSHException, ValueError):
|
||||||
|
continue
|
||||||
|
logger.warning("The SSH private key could not be read; logging in with the password")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _ssh_errors() -> tuple[type[Exception], ...]:
|
||||||
|
"""What a command that could not run raises: the socket's errors, timeouts
|
||||||
|
included, and paramiko's (a refused login, a closed session)."""
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
return (OSError, paramiko.SSHException)
|
||||||
+12
-334
@@ -12,19 +12,11 @@ NAPALM API allows it.
|
|||||||
|
|
||||||
Optional args
|
Optional args
|
||||||
-------------
|
-------------
|
||||||
verify_ssl : bool
|
The connection's are the shared base's (``napalm_proxmox._base``; the API port
|
||||||
Verify TLS certificates (default: True).
|
defaults to 8006 here). In addition:
|
||||||
port : int
|
|
||||||
Proxmox API port (default: 8006).
|
|
||||||
node : str
|
node : str
|
||||||
Override the target node name (default: auto-detected from hostname).
|
Override the target node name (default: auto-detected from hostname).
|
||||||
realm : str
|
|
||||||
PAM realm (default: ``pam``).
|
|
||||||
token_name : str
|
|
||||||
API token name (e.g. ``napalm@pam!mytoken``).
|
|
||||||
token_value : str
|
|
||||||
API token secret. When both token_name and token_value are provided,
|
|
||||||
token-based auth is used instead of password auth.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -35,7 +27,6 @@ from typing import Any
|
|||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
CommandResult,
|
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
FingerprintRule,
|
FingerprintRule,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
@@ -50,16 +41,16 @@ from napalm_device_types import (
|
|||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
)
|
)
|
||||||
from napalm_device_types.channel import run_on_transport
|
|
||||||
from napalm_device_types.ssh_host_keys import HostKeyCheck
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from proxmoxer import ProxmoxAPI
|
from proxmoxer import ProxmoxAPI
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
raise ImportError("proxmoxer is required: pip install proxmoxer") from 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.cluster_mixin import ProxmoxClusterMixin
|
||||||
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
||||||
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||||
from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
|
from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
|
||||||
@@ -84,6 +75,7 @@ _JsonDict = dict[str, Any]
|
|||||||
|
|
||||||
|
|
||||||
class ProxmoxDriver(
|
class ProxmoxDriver(
|
||||||
|
ProxmoxBase,
|
||||||
ProxmoxInterfaceMixin,
|
ProxmoxInterfaceMixin,
|
||||||
ProxmoxSDNMixin,
|
ProxmoxSDNMixin,
|
||||||
ProxmoxLLDPMixin,
|
ProxmoxLLDPMixin,
|
||||||
@@ -96,6 +88,7 @@ class ProxmoxDriver(
|
|||||||
ProxmoxVMMigrateMixin,
|
ProxmoxVMMigrateMixin,
|
||||||
ProxmoxRoutingMixin,
|
ProxmoxRoutingMixin,
|
||||||
ProxmoxSystemMixin,
|
ProxmoxSystemMixin,
|
||||||
|
ProxmoxHostMixin,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
@@ -143,31 +136,9 @@ class ProxmoxDriver(
|
|||||||
timeout: int = 60,
|
timeout: int = 60,
|
||||||
optional_args: _JsonDict | None = None,
|
optional_args: _JsonDict | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.hostname = hostname
|
super().__init__(hostname, username, password, timeout, optional_args)
|
||||||
self.username = username
|
|
||||||
self.password = password
|
|
||||||
self.timeout = timeout
|
|
||||||
self.optional_args: _JsonDict = optional_args or {}
|
|
||||||
|
|
||||||
self._port: int = self.optional_args.get("port", 8006)
|
|
||||||
self._verify_ssl: bool = self.optional_args.get(
|
|
||||||
"verify_ssl",
|
|
||||||
self.optional_args.get("ssl_verify", self.optional_args.get("verify", True)),
|
|
||||||
)
|
|
||||||
self._realm: str = self.optional_args.get("realm", "pam")
|
|
||||||
self._token_name: str | None = self.optional_args.get("token_name")
|
|
||||||
self._token_value: str | None = self.optional_args.get("token_value")
|
|
||||||
self._node: str | None = self.optional_args.get("node")
|
self._node: str | None = self.optional_args.get("node")
|
||||||
|
|
||||||
self._ssh_username: str | None = self.optional_args.get("ssh_username")
|
|
||||||
self._ssh_password: str | None = self.optional_args.get("ssh_password")
|
|
||||||
self._ssh_key: str | None = self.optional_args.get("ssh_private_key_str")
|
|
||||||
|
|
||||||
self._api: ProxmoxAPI | None = None
|
|
||||||
self._node_name: str = ""
|
|
||||||
# paramiko.SSHClient; paramiko is imported lazily (see _node_ssh).
|
|
||||||
self._ssh_client: Any = None
|
|
||||||
|
|
||||||
# Candidate config (merge/replace)
|
# Candidate config (merge/replace)
|
||||||
self._candidate_config: str = ""
|
self._candidate_config: str = ""
|
||||||
self._running_config: str = ""
|
self._running_config: str = ""
|
||||||
@@ -176,51 +147,8 @@ class ProxmoxDriver(
|
|||||||
# Connection management
|
# Connection management
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def open(self) -> None:
|
def _proxmox_api(self, **kwargs: Any) -> Any:
|
||||||
"""Open the connection to the Proxmox API."""
|
return ProxmoxAPI(**kwargs)
|
||||||
try:
|
|
||||||
# Use the HTTPS backend for proper REST API support.
|
|
||||||
# The openssh backend tunnels all kwargs through to
|
|
||||||
# openssh_wrapper.CommandBaseSession, which does not
|
|
||||||
# accept password/verify_ssl/token params.
|
|
||||||
# Proxmox authenticates against "<user>@<realm>" and rejects a bare
|
|
||||||
# username outright. A caller who typed a realm keeps it; one who
|
|
||||||
# did not gets self._realm, which is what the documented `realm`
|
|
||||||
# optional_arg is for -- it was read in __init__ and then never
|
|
||||||
# used, so the option had no effect and a bare username failed.
|
|
||||||
user = self.username or ""
|
|
||||||
if user and "@" not in user:
|
|
||||||
user = f"{user}@{self._realm}"
|
|
||||||
|
|
||||||
kwargs: _JsonDict = {
|
|
||||||
"host": self.hostname,
|
|
||||||
"user": user,
|
|
||||||
"password": self.password,
|
|
||||||
"port": self._port,
|
|
||||||
"verify_ssl": self._verify_ssl,
|
|
||||||
"backend": "https",
|
|
||||||
}
|
|
||||||
|
|
||||||
if self._token_name and self._token_value:
|
|
||||||
kwargs.pop("password", None)
|
|
||||||
kwargs["token_value"] = self._token_value
|
|
||||||
# token_name may be in "<user>!<tokenid>" format (e.g.
|
|
||||||
# "root@pam!netork"). proxmoxer expects them split:
|
|
||||||
# user="root@pam", token_name="netork"
|
|
||||||
user_part, _, token_id = self._token_name.partition("!")
|
|
||||||
if token_id:
|
|
||||||
kwargs["user"] = user_part
|
|
||||||
kwargs["token_name"] = token_id
|
|
||||||
else:
|
|
||||||
kwargs["token_name"] = self._token_name
|
|
||||||
|
|
||||||
self._api = ProxmoxAPI(**kwargs)
|
|
||||||
|
|
||||||
# Validate connection by fetching node status
|
|
||||||
self._resolve_node()
|
|
||||||
|
|
||||||
except Exception as exc:
|
|
||||||
raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
|
|
||||||
|
|
||||||
def _resolve_node(self) -> str:
|
def _resolve_node(self) -> str:
|
||||||
"""Resolve the PVE node this connection talks to.
|
"""Resolve the PVE node this connection talks to.
|
||||||
@@ -260,190 +188,10 @@ class ProxmoxDriver(
|
|||||||
f"set the 'node' driver argument"
|
f"set the 'node' driver argument"
|
||||||
)
|
)
|
||||||
|
|
||||||
def close(self) -> None:
|
|
||||||
"""Close the connection."""
|
|
||||||
self._api = None
|
|
||||||
if self._ssh_client:
|
|
||||||
try:
|
|
||||||
self._ssh_client.close()
|
|
||||||
except Exception:
|
|
||||||
logger.debug("%s: closing the SSH session: ignored", self.hostname, exc_info=True)
|
|
||||||
self._ssh_client = None
|
|
||||||
|
|
||||||
def is_alive(self) -> _JsonDict:
|
|
||||||
"""Return connection liveness.
|
|
||||||
|
|
||||||
Probes ``GET /version``, the cheapest endpoint that proves the session
|
|
||||||
still authenticates. It used to call ``_resolve_node()``, which returns
|
|
||||||
early without touching the API whenever a node was configured via
|
|
||||||
optional_args — so a dead connection reported itself alive.
|
|
||||||
"""
|
|
||||||
alive = False
|
|
||||||
if self._api:
|
|
||||||
try:
|
|
||||||
self._api.version.get()
|
|
||||||
alive = True
|
|
||||||
except Exception:
|
|
||||||
logger.debug("%s: liveness probe failed", self.hostname, exc_info=True)
|
|
||||||
return {"is_alive": alive}
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Internal API helpers
|
# Node info helpers (PVE only)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def _node_api(self):
|
|
||||||
"""Return the API resource for the current node."""
|
|
||||||
return self._api.nodes(self._node_name)
|
|
||||||
|
|
||||||
def _get_node_network(self) -> list[_JsonDict]:
|
|
||||||
"""Return the node's network interface list from the Proxmox API."""
|
|
||||||
try:
|
|
||||||
return self._node_api().network.get() or []
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch node network: %s", exc)
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _exec_ssh_command(self, command: str) -> str:
|
|
||||||
"""Run *command* in the node's shell over SSH and return what it printed.
|
|
||||||
|
|
||||||
Stdout only: stderr is not output (a command that wants it says
|
|
||||||
``2>&1``). The exit status is not checked; a caller that needs it asks
|
|
||||||
for it (``_rc``). The node has no API endpoint that runs a shell command
|
|
||||||
(``/nodes/{node}/execute`` runs a batch of API calls), so this is the
|
|
||||||
one way, the same session ``_run_node_command`` uses (see
|
|
||||||
NAPALM/napalm-device-types#35 for the shared transport).
|
|
||||||
|
|
||||||
:raises ConnectionException: when the command could not run: no SSH
|
|
||||||
credential, a refused login or host key (``SshHostKeyMismatch``),
|
|
||||||
an unreachable node, a timeout.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=self.timeout)
|
|
||||||
out = stdout.read().decode(errors="replace")
|
|
||||||
err = stderr.read().decode(errors="replace").strip()
|
|
||||||
except ConnectionException:
|
|
||||||
raise
|
|
||||||
except _ssh_errors() as exc:
|
|
||||||
raise ConnectionException(
|
|
||||||
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
|
||||||
) from exc
|
|
||||||
if err:
|
|
||||||
logger.debug("%s: stderr of a node command: %s", self.hostname, err[-300:])
|
|
||||||
return out.strip()
|
|
||||||
|
|
||||||
def run_command(
|
|
||||||
self,
|
|
||||||
command: str,
|
|
||||||
*,
|
|
||||||
privileged: bool = False,
|
|
||||||
timeout: float = 60,
|
|
||||||
stdin: bytes | None = None,
|
|
||||||
) -> CommandResult:
|
|
||||||
"""Run *command* on an exec channel of the node's SSH session (``CommandChannelMixin``).
|
|
||||||
|
|
||||||
stdout, stderr and the exit status come back apart; *stdin*, if given, is
|
|
||||||
written and then closed. *privileged* needs nothing more: the node is
|
|
||||||
logged in as root, as for every other command this driver runs there.
|
|
||||||
|
|
||||||
:raises ConnectionException: when the command could not run, or did not
|
|
||||||
finish within *timeout* seconds.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
transport = self._node_ssh().get_transport()
|
|
||||||
return run_on_transport(transport, command, stdin=stdin, timeout=timeout)
|
|
||||||
except ConnectionException:
|
|
||||||
raise
|
|
||||||
except _ssh_errors() as exc:
|
|
||||||
raise ConnectionException(
|
|
||||||
f"Cannot run a command on {self.hostname} over SSH: {exc}"
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
|
|
||||||
"""The SSH session to the node on port 22, opened once.
|
|
||||||
|
|
||||||
Its host key is the one the caller expects for port 22, or on first use
|
|
||||||
whichever the node presents; either way it is reported (netork#1167).
|
|
||||||
|
|
||||||
:raises ConnectionException: without a password or a usable key.
|
|
||||||
"""
|
|
||||||
import paramiko
|
|
||||||
|
|
||||||
if self._ssh_client is None:
|
|
||||||
# A key is tried first; paramiko falls back to the password. Only
|
|
||||||
# these: not the keys in the process's own ~/.ssh, nor an agent.
|
|
||||||
connect_kwargs: _JsonDict = {
|
|
||||||
"username": self._ssh_username or self.username,
|
|
||||||
"timeout": self.timeout,
|
|
||||||
"look_for_keys": False,
|
|
||||||
"allow_agent": False,
|
|
||||||
}
|
|
||||||
password = self._ssh_password or self.password
|
|
||||||
if password:
|
|
||||||
connect_kwargs["password"] = password
|
|
||||||
pkey = _load_private_key(self._ssh_key) if self._ssh_key else None
|
|
||||||
if pkey is not None:
|
|
||||||
connect_kwargs["pkey"] = pkey
|
|
||||||
if not password and pkey is None:
|
|
||||||
# An API-token-only node: nothing to log in with, so no connection.
|
|
||||||
raise ConnectionException(
|
|
||||||
f"no SSH credential for {self.hostname}: set ssh_password or "
|
|
||||||
"ssh_private_key_str"
|
|
||||||
)
|
|
||||||
client = paramiko.SSHClient()
|
|
||||||
try:
|
|
||||||
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
|
|
||||||
client, **connect_kwargs
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
client.close()
|
|
||||||
raise
|
|
||||||
self._ssh_client = client
|
|
||||||
return self._ssh_client
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
# Node info helpers
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
|
|
||||||
def _get_version_info(self) -> _JsonDict:
|
|
||||||
"""Return Proxmox VE version info from the API."""
|
|
||||||
try:
|
|
||||||
return self._api.version.get() or {}
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch version info: %s", exc)
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_node_status(self) -> _JsonDict:
|
|
||||||
"""Return the node's status from the Proxmox API."""
|
|
||||||
try:
|
|
||||||
return self._node_api().status.get() or {}
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch node status: %s", exc)
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_node_subscription(self) -> _JsonDict:
|
|
||||||
"""Return subscription status for this node."""
|
|
||||||
try:
|
|
||||||
return self._node_api().subscription.get() or {}
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch node subscription: %s", exc)
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_node_dns(self) -> _JsonDict:
|
|
||||||
"""Return DNS configuration for this node."""
|
|
||||||
try:
|
|
||||||
return self._node_api().dns.get() or {}
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch node DNS: %s", exc)
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_node_time(self) -> _JsonDict:
|
|
||||||
"""Return time configuration for this node."""
|
|
||||||
try:
|
|
||||||
return self._node_api().time.get() or {}
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch node time: %s", exc)
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_node_ntp(self) -> _JsonDict:
|
def _get_node_ntp(self) -> _JsonDict:
|
||||||
"""Return NTP configuration for this node."""
|
"""Return NTP configuration for this node."""
|
||||||
try:
|
try:
|
||||||
@@ -478,46 +226,7 @@ class ProxmoxDriver(
|
|||||||
release = version.get("release", "")
|
release = version.get("release", "")
|
||||||
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
|
os_version = f"Proxmox VE {pve_version}" if pve_version else f"Proxmox VE {release}"
|
||||||
|
|
||||||
# Physical hardware info from Linux DMI sysfs.
|
vendor, model, serial = self._hardware()
|
||||||
# Read each field separately to avoid shell quoting issues with printf.
|
|
||||||
# Field priority for model:
|
|
||||||
# product_name — human-readable name on most vendors (e.g. "NUC6CAYH",
|
|
||||||
# "ThinkCentre M910x")
|
|
||||||
# product_version — sometimes the marketing name on Lenovo; on Intel NUC
|
|
||||||
# it is the board part number (less useful as model name)
|
|
||||||
# We prefer product_name; fall back to product_version only when
|
|
||||||
# product_name looks like a raw type code (all uppercase + digits, no spaces).
|
|
||||||
vendor = ""
|
|
||||||
model = ""
|
|
||||||
serial = ""
|
|
||||||
try:
|
|
||||||
dmi_cmd = (
|
|
||||||
"v=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null); "
|
|
||||||
"n=$(cat /sys/class/dmi/id/product_name 2>/dev/null); "
|
|
||||||
"r=$(cat /sys/class/dmi/id/product_version 2>/dev/null); "
|
|
||||||
"s=$(cat /sys/class/dmi/id/product_serial 2>/dev/null); "
|
|
||||||
'printf \'%s\\n%s\\n%s\\n%s\\n\' "$v" "$n" "$r" "$s"'
|
|
||||||
)
|
|
||||||
lines = self._exec_ssh_command(dmi_cmd).splitlines()
|
|
||||||
if len(lines) >= 4:
|
|
||||||
vendor = lines[0].strip()
|
|
||||||
product_name = lines[1].strip()
|
|
||||||
product_version = lines[2].strip()
|
|
||||||
serial = lines[3].strip()
|
|
||||||
|
|
||||||
_bad = {"none", "n/a", "not specified", "to be filled by o.e.m."}
|
|
||||||
pv_usable = (
|
|
||||||
product_version
|
|
||||||
and product_version.lower() not in _bad
|
|
||||||
and product_version != product_name
|
|
||||||
# Only prefer product_version when it contains a space —
|
|
||||||
# that indicates a human-readable marketing name like
|
|
||||||
# "ThinkCentre M910x" rather than a part code like "J26843-409".
|
|
||||||
and " " in product_version
|
|
||||||
)
|
|
||||||
model = product_version if pv_usable else product_name
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to read DMI info via SSH: %s", exc)
|
|
||||||
|
|
||||||
# Currently-booted kernel release (uname -r) — distinct from any newer
|
# Currently-booted kernel release (uname -r) — distinct from any newer
|
||||||
# kernel that is merely installed and pending a reboot.
|
# kernel that is merely installed and pending a reboot.
|
||||||
@@ -538,34 +247,3 @@ class ProxmoxDriver(
|
|||||||
"interface_list": iface_list,
|
"interface_list": iface_list,
|
||||||
"running_kernel": running_kernel,
|
"running_kernel": running_kernel,
|
||||||
}
|
}
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
# CLI passthrough
|
|
||||||
# ------------------------------------------------------------------ #
|
|
||||||
|
|
||||||
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
|
|
||||||
"""Execute a list of shell commands and return their outputs."""
|
|
||||||
return {cmd: self._exec_ssh_command(cmd) for cmd in commands}
|
|
||||||
|
|
||||||
|
|
||||||
def _load_private_key(text: str) -> Any: # paramiko.PKey; paramiko is imported lazily
|
|
||||||
"""The SSH private key in *text*, whatever its type, or None when it cannot be read."""
|
|
||||||
import io
|
|
||||||
|
|
||||||
import paramiko
|
|
||||||
|
|
||||||
for key_class in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
|
|
||||||
try:
|
|
||||||
return key_class.from_private_key(io.StringIO(text))
|
|
||||||
except (paramiko.SSHException, ValueError):
|
|
||||||
continue
|
|
||||||
logger.warning("The SSH private key could not be read; logging in with the password")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _ssh_errors() -> tuple[type[Exception], ...]:
|
|
||||||
"""What a command that could not run raises: the socket's errors, timeouts
|
|
||||||
included, and paramiko's (a refused login, a closed session)."""
|
|
||||||
import paramiko
|
|
||||||
|
|
||||||
return (OSError, paramiko.SSHException)
|
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
|
||||||
|
|
||||||
|
The transports for napalm-device-types' host readers (kernel facts, service
|
||||||
|
packages, system identity, listening sockets, systemd services, host status,
|
||||||
|
apt's proxy), packages and APT updates, the subscription, root file writes,
|
||||||
|
and restarting or shutting the host down. All of it is the same on both
|
||||||
|
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status``
|
||||||
|
endpoints, and root's shell over the driver's own SSH session.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import ipaddress
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
|
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
|
||||||
|
from napalm_device_types.models import (
|
||||||
|
FixStepOutcomeDict,
|
||||||
|
LicenseDict,
|
||||||
|
LicenseStatus,
|
||||||
|
PackageDict,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The subscription API's status (lower-cased) as a napalm-device-types
|
||||||
|
#: ``LicenseStatus``; "new" and "suspended" have none of their own.
|
||||||
|
_SUBSCRIPTION_STATUS: dict[str, LicenseStatus] = {
|
||||||
|
"notfound": "none",
|
||||||
|
"active": "active",
|
||||||
|
"invalid": "invalid",
|
||||||
|
"expired": "expired",
|
||||||
|
}
|
||||||
|
|
||||||
|
_PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.+:~-]*$")
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxHostMixin:
|
||||||
|
"""The Debian host under a Proxmox product."""
|
||||||
|
|
||||||
|
#: ``source`` of every package ``get_packages`` reports.
|
||||||
|
PACKAGE_SOURCE = "pve"
|
||||||
|
#: ``name`` of the subscription ``get_licenses`` reports.
|
||||||
|
SUBSCRIPTION_LICENSE = "pve-subscription"
|
||||||
|
|
||||||
|
_node_name: 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 _get_node_subscription(self) -> _JsonDict: ...
|
||||||
|
|
||||||
|
def _run_kernel_facts_command(self, command: str) -> str:
|
||||||
|
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
||||||
|
return self._exec_ssh_command(command)
|
||||||
|
|
||||||
|
def _run_service_packages_command(self, command: str) -> str:
|
||||||
|
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_system_identity_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``SystemIdentityMixin.get_system_identity``: the exec path,
|
||||||
|
which runs as root either way."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``ListeningSocketsMixin.get_listening_sockets``:
|
||||||
|
the exec path, which runs as root either way."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def get_packages(self) -> list[PackageDict]:
|
||||||
|
"""Return installed Debian packages with available-update info.
|
||||||
|
|
||||||
|
Installed list comes from ``dpkg-query`` via SSH (the Proxmox API
|
||||||
|
``/apt/installed`` endpoint is not implemented on PVE 8.x).
|
||||||
|
Available updates come from the Proxmox API ``/apt/update``.
|
||||||
|
"""
|
||||||
|
upgradable = self._upgradable_versions()
|
||||||
|
# Installed packages via SSH dpkg-query
|
||||||
|
raw = self._exec_ssh_command(
|
||||||
|
"dpkg-query -W -f="
|
||||||
|
"'${Package}\\t${Version}\\t${db:Status-Status}\\t${Installed-Size}"
|
||||||
|
"\\t${source:Package}\\t${source:Version}\\n'"
|
||||||
|
" 2>/dev/null"
|
||||||
|
)
|
||||||
|
result = []
|
||||||
|
for line in raw.splitlines():
|
||||||
|
pkg = parse_dpkg_line(line, self.PACKAGE_SOURCE)
|
||||||
|
if pkg is not None:
|
||||||
|
pkg["upgrade_version"] = upgradable.get(pkg["name"], "")
|
||||||
|
result.append(pkg)
|
||||||
|
# PackageDict has no source_package, source_version and upgrade_version
|
||||||
|
# yet (NAPALM/napalm-device-types#85); every reader of these
|
||||||
|
# packages relies on them, so they stay.
|
||||||
|
return cast(list[PackageDict], result)
|
||||||
|
|
||||||
|
def _upgradable_versions(self) -> dict[str, str]:
|
||||||
|
"""The candidate version of every upgradable package, from ``/apt/update``."""
|
||||||
|
upgradable: dict[str, str] = {}
|
||||||
|
try:
|
||||||
|
for upd in self._node_api().apt.update.get():
|
||||||
|
pkg = upd.get("Package", "")
|
||||||
|
if pkg:
|
||||||
|
upgradable[pkg] = upd.get("Version", "")
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Failed to fetch available APT updates: %s", exc)
|
||||||
|
return upgradable
|
||||||
|
|
||||||
|
def get_licenses(self) -> list[LicenseDict]:
|
||||||
|
"""The node's subscription, as the API reports it.
|
||||||
|
|
||||||
|
A fact for the caller: whether running without one is a problem is not
|
||||||
|
the driver's to say. An unreadable subscription reports nothing.
|
||||||
|
"""
|
||||||
|
sub = self._get_node_subscription()
|
||||||
|
raw = str(sub.get("status", ""))
|
||||||
|
if not raw:
|
||||||
|
return []
|
||||||
|
lic: LicenseDict = {
|
||||||
|
"name": self.SUBSCRIPTION_LICENSE,
|
||||||
|
"status": _SUBSCRIPTION_STATUS.get(raw.lower(), "unknown"),
|
||||||
|
"detail": str(sub.get("message") or raw),
|
||||||
|
}
|
||||||
|
if sub.get("productname"):
|
||||||
|
lic["edition"] = sub["productname"]
|
||||||
|
if sub.get("nextduedate"):
|
||||||
|
lic["expires"] = sub["nextduedate"]
|
||||||
|
return [lic]
|
||||||
|
|
||||||
|
def _run_service_command(self, command: str, *, privileged: bool, timeout: int) -> str:
|
||||||
|
"""The transport for ``SystemdServicesMixin``: the exec path, as root.
|
||||||
|
|
||||||
|
*privileged* needs nothing more on a node the driver reaches as root, and
|
||||||
|
the exec path keeps its own timeout.
|
||||||
|
"""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def get_available_updates(self) -> list[_JsonDict]:
|
||||||
|
"""Return the node's upgradable packages, with origin and security status.
|
||||||
|
|
||||||
|
``apt list --upgradable`` over the exec path names each candidate's suite
|
||||||
|
(``trixie-security``); the APT API names only an Origin ("Debian",
|
||||||
|
"Proxmox") and is the fallback, with the security status unknown.
|
||||||
|
|
||||||
|
:raises Exception: when neither answers -- never an empty list for
|
||||||
|
"could not read".
|
||||||
|
"""
|
||||||
|
updates: list[_JsonDict]
|
||||||
|
try:
|
||||||
|
raw = self._exec_ssh_command(APT_UPGRADABLE_COMMAND) or ""
|
||||||
|
updates = [dict(u) for u in parse_apt_upgradable(raw)]
|
||||||
|
except ValueError as exc:
|
||||||
|
logger.debug("apt list over the exec path failed, using the API: %s", exc)
|
||||||
|
updates = self._updates_from_api()
|
||||||
|
return sorted(updates, key=lambda u: u["name"])
|
||||||
|
|
||||||
|
def _updates_from_api(self) -> list[_JsonDict]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": upd["Package"],
|
||||||
|
"current_version": upd.get("OldVersion", ""),
|
||||||
|
"new_version": upd.get("Version", ""),
|
||||||
|
"origin": upd.get("Origin"),
|
||||||
|
"security": None,
|
||||||
|
}
|
||||||
|
for upd in self._node_api().apt.update.get()
|
||||||
|
if upd.get("Package")
|
||||||
|
]
|
||||||
|
|
||||||
|
def refresh_available_updates(self) -> _JsonDict:
|
||||||
|
"""Resynchronise the node's package index (``POST nodes/{n}/apt/update``)."""
|
||||||
|
try:
|
||||||
|
task = self._node_api().apt.update.post()
|
||||||
|
except Exception as exc:
|
||||||
|
return {"success": False, "output": str(exc)}
|
||||||
|
return {"success": True, "output": f"Package index refresh started ({task})"}
|
||||||
|
|
||||||
|
def _run_host_status_command(self, command: str) -> str:
|
||||||
|
"""The transport for ``HostStatusMixin.get_host_status``: the exec path."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def apply_updates(self, packages: list[str]) -> _JsonDict:
|
||||||
|
"""Upgrade the given packages via ``apt-get install`` over SSH."""
|
||||||
|
for pkg in packages:
|
||||||
|
if not re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
|
||||||
|
raise ValueError(f"Invalid package name: {pkg!r}")
|
||||||
|
pkg_args = " ".join(packages)
|
||||||
|
output, status = self._rc(
|
||||||
|
f"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y {pkg_args}"
|
||||||
|
)
|
||||||
|
if status == 0:
|
||||||
|
return {"success": True, "output": output}
|
||||||
|
error = (
|
||||||
|
f"apt-get exited with status {status}"
|
||||||
|
if status >= 0
|
||||||
|
else "apt-get's exit status could not be read"
|
||||||
|
)
|
||||||
|
return {"success": False, "output": output, "error": error}
|
||||||
|
|
||||||
|
def _rc(self, command: str) -> tuple[str, int]:
|
||||||
|
"""Run *command* and return its output and exit status (-1 when unknown)."""
|
||||||
|
out = self._exec_ssh_command(f"{{ {command}; }} 2>&1; echo __PVE_RC=$?")
|
||||||
|
text, _, tail = out.rpartition("__PVE_RC=")
|
||||||
|
try:
|
||||||
|
return text.strip(), int(tail.strip())
|
||||||
|
except ValueError:
|
||||||
|
return out.strip(), -1
|
||||||
|
|
||||||
|
def _step(self, command: str, done: str) -> FixStepOutcomeDict:
|
||||||
|
output, status = self._rc(command)
|
||||||
|
return {"ok": status == 0, "output": done if status == 0 else output[-300:]}
|
||||||
|
|
||||||
|
def _run_apt_command(self, command: str) -> str:
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_apt_root_command(self, command: str, done: str) -> FixStepOutcomeDict:
|
||||||
|
return self._step(command, done)
|
||||||
|
|
||||||
|
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
|
return self._write_root_file(path, content)
|
||||||
|
|
||||||
|
def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
|
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
||||||
|
encoded = base64.b64encode(content.encode()).decode()
|
||||||
|
# No ``exit`` here: it would end the shell before ``_rc`` reads the status.
|
||||||
|
return self._step(
|
||||||
|
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
|
||||||
|
f'install -m 644 -o root -g root "$t" {shlex.quote(path)}; '
|
||||||
|
's=$?; rm -f "$t"; [ "$s" -eq 0 ]',
|
||||||
|
f"wrote {path}",
|
||||||
|
)
|
||||||
|
|
||||||
|
def install_package(self, name: str, version: str = "") -> None:
|
||||||
|
"""apt-get install *name* (``PackageManagementMixin``); raises when apt fails."""
|
||||||
|
if not _PACKAGE_NAME.match(name) or (version and not _PACKAGE_NAME.match(version)):
|
||||||
|
raise ValueError(f"not a package name: {name!r}")
|
||||||
|
target = f"{name}={version}" if version else name
|
||||||
|
output, status = self._rc(f"DEBIAN_FRONTEND=noninteractive apt-get install -y {target}")
|
||||||
|
if status != 0:
|
||||||
|
raise RuntimeError(f"apt-get install {target} failed: {output[-300:]}")
|
||||||
|
|
||||||
|
def get_management_peer(self) -> str | None:
|
||||||
|
"""The address the node sees the SSH connection come from (``SSH_CONNECTION``)."""
|
||||||
|
out = self._exec_ssh_command('printf "%s\\n" "$SSH_CONNECTION"').split()
|
||||||
|
try:
|
||||||
|
return str(ipaddress.ip_address(out[0])) if out else None
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def reboot_host(self) -> None:
|
||||||
|
"""Restart the node through the API (no SSH involved)."""
|
||||||
|
try:
|
||||||
|
self._node_api().status.post(command="reboot")
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Reboot of node {self._node_name!r} refused: {exc}") from exc
|
||||||
|
|
||||||
|
def shutdown_host(self) -> None:
|
||||||
|
"""Shut the node down through the API; on PVE its guests stop as on any shutdown."""
|
||||||
|
try:
|
||||||
|
self._node_api().status.post(command="shutdown")
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"Shutdown of node {self._node_name!r} refused: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def parse_dpkg_line(line: str, source: str) -> _JsonDict | None:
|
||||||
|
"""One installed package from a line of the ``dpkg-query`` format above, or
|
||||||
|
None for a line that is not an installed package."""
|
||||||
|
parts = line.strip().split("\t")
|
||||||
|
if len(parts) < 2 or not parts[0]:
|
||||||
|
return None
|
||||||
|
name, version = parts[0], parts[1]
|
||||||
|
status = parts[2] if len(parts) > 2 else "installed"
|
||||||
|
if status != "installed":
|
||||||
|
return None
|
||||||
|
size_kb, source_package_field, source_version_field = (parts[3:] + ["", "", ""])[:3]
|
||||||
|
# Debian source package (differs from the binary for split packages,
|
||||||
|
# e.g. openssh-server → openssh). Needed for accurate OSV matching.
|
||||||
|
source_package = source_package_field or name
|
||||||
|
# And its version, which is a different number from this package's.
|
||||||
|
#
|
||||||
|
# OSV states Debian ranges in *source* versions, so a consumer given
|
||||||
|
# the source package and only the binary version compares two
|
||||||
|
# unrelated numbers: libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while
|
||||||
|
# its source, samba, is 2:4.22.11+dfsg-…. Reporting the source
|
||||||
|
# without its version is worse than reporting neither, because it
|
||||||
|
# looks usable. Every package on all three Proxmox nodes was in that
|
||||||
|
# state — the format string never asked for the field.
|
||||||
|
#
|
||||||
|
# dpkg leaves it empty when it equals `Version`, and so does an
|
||||||
|
# older dpkg that does not know the field at all.
|
||||||
|
source_version = source_version_field or version
|
||||||
|
return {
|
||||||
|
"name": name,
|
||||||
|
"version": version,
|
||||||
|
"installed": True,
|
||||||
|
"description": "",
|
||||||
|
"size": int(size_kb) * 1024 if size_kb.isdigit() else 0,
|
||||||
|
"source": source,
|
||||||
|
"source_package": source_package,
|
||||||
|
"source_version": source_version,
|
||||||
|
}
|
||||||
@@ -14,20 +14,18 @@
|
|||||||
|
|
||||||
"""System-level NAPALM getters for Proxmox VE nodes.
|
"""System-level NAPALM getters for Proxmox VE nodes.
|
||||||
|
|
||||||
Environment, NTP, SNMP, users, packages, services, updates and disk SMART.
|
Environment, NTP, SNMP, users, hostname and disk SMART. What a PVE node shares
|
||||||
|
with a Proxmox Backup Server as a Debian host is in ``host_mixin``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
import shlex
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from napalm.base.exceptions import CommandErrorException
|
from napalm.base.exceptions import CommandErrorException
|
||||||
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
|
|
||||||
|
|
||||||
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
|
||||||
|
|
||||||
@@ -35,17 +33,6 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
_JsonDict = dict[str, Any]
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
#: The subscription API's status (lower-cased) as a napalm-device-types
|
|
||||||
#: ``LicenseStatus``; "new" and "suspended" have none of their own.
|
|
||||||
_SUBSCRIPTION_STATUS = {
|
|
||||||
"notfound": "none",
|
|
||||||
"active": "active",
|
|
||||||
"invalid": "invalid",
|
|
||||||
"expired": "expired",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
_PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.+:~-]*$")
|
|
||||||
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
||||||
_SNMP_WORD = re.compile(r'^[^\s"#]+$')
|
_SNMP_WORD = re.compile(r'^[^\s"#]+$')
|
||||||
#: The net-snmp agent's configuration file.
|
#: The net-snmp agent's configuration file.
|
||||||
@@ -303,200 +290,26 @@ class ProxmoxSystemMixin:
|
|||||||
# Kernel facts (KernelFactsMixin supplies get_kernel_facts)
|
# Kernel facts (KernelFactsMixin supplies get_kernel_facts)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def _run_kernel_facts_command(self, command: str) -> str:
|
|
||||||
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
|
||||||
return self._exec_ssh_command(command)
|
|
||||||
|
|
||||||
def _run_service_packages_command(self, command: str) -> str:
|
|
||||||
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
|
||||||
return str(self._exec_ssh_command(command))
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Listening sockets (ListeningSocketsMixin supplies get_listening_sockets)
|
# Listening sockets (ListeningSocketsMixin supplies get_listening_sockets)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def _run_system_identity_command(self, command: str, *, privileged: bool) -> str:
|
|
||||||
"""The transport for ``SystemIdentityMixin.get_system_identity``: the exec path,
|
|
||||||
which runs as root either way."""
|
|
||||||
return str(self._exec_ssh_command(command))
|
|
||||||
|
|
||||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
|
||||||
"""The transport for ``ListeningSocketsMixin.get_listening_sockets``:
|
|
||||||
the exec path, which runs as root either way."""
|
|
||||||
return str(self._exec_ssh_command(command))
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Packages (Debian APT)
|
# Packages (Debian APT)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def get_packages(self) -> list[_JsonDict]:
|
|
||||||
"""Return installed Debian packages with available-update info.
|
|
||||||
|
|
||||||
Installed list comes from ``dpkg-query`` via SSH (the Proxmox API
|
|
||||||
``/apt/installed`` endpoint is not implemented on PVE 8.x).
|
|
||||||
Available updates come from the Proxmox API ``/apt/update``.
|
|
||||||
"""
|
|
||||||
# Available updates from Proxmox API (keyed by package name)
|
|
||||||
upgradable: dict[str, str] = {}
|
|
||||||
try:
|
|
||||||
for upd in self._api.nodes(self._node_name).apt.update.get():
|
|
||||||
pkg = upd.get("Package", "")
|
|
||||||
if pkg:
|
|
||||||
upgradable[pkg] = upd.get("Version", "")
|
|
||||||
except Exception as exc:
|
|
||||||
logger.debug("Failed to fetch available APT updates: %s", exc)
|
|
||||||
|
|
||||||
# Installed packages via SSH dpkg-query
|
|
||||||
raw = self._exec_ssh_command(
|
|
||||||
"dpkg-query -W -f="
|
|
||||||
"'${Package}\\t${Version}\\t${db:Status-Status}\\t${Installed-Size}"
|
|
||||||
"\\t${source:Package}\\t${source:Version}\\n'"
|
|
||||||
" 2>/dev/null"
|
|
||||||
)
|
|
||||||
result: list[_JsonDict] = []
|
|
||||||
for line in raw.splitlines():
|
|
||||||
parts = line.strip().split("\t")
|
|
||||||
if len(parts) < 2:
|
|
||||||
continue
|
|
||||||
name = parts[0]
|
|
||||||
version = parts[1] if len(parts) > 1 else ""
|
|
||||||
status = parts[2] if len(parts) > 2 else "installed"
|
|
||||||
size_kb = parts[3] if len(parts) > 3 else "0"
|
|
||||||
# Debian source package (differs from the binary for split packages,
|
|
||||||
# e.g. openssh-server → openssh). Needed for accurate OSV matching.
|
|
||||||
source_package = parts[4] if len(parts) > 4 and parts[4] else name
|
|
||||||
# And its version, which is a different number from this package's.
|
|
||||||
#
|
|
||||||
# OSV states Debian ranges in *source* versions, so a consumer given
|
|
||||||
# the source package and only the binary version compares two
|
|
||||||
# unrelated numbers: libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while
|
|
||||||
# its source, samba, is 2:4.22.11+dfsg-…. Reporting the source
|
|
||||||
# without its version is worse than reporting neither, because it
|
|
||||||
# looks usable. Every package on all three Proxmox nodes was in that
|
|
||||||
# state — the format string never asked for the field.
|
|
||||||
#
|
|
||||||
# dpkg leaves it empty when it equals `Version`, and so does an
|
|
||||||
# older dpkg that does not know the field at all.
|
|
||||||
source_version = parts[5] if len(parts) > 5 and parts[5] else version
|
|
||||||
if not name or status != "installed":
|
|
||||||
continue
|
|
||||||
size_bytes = int(size_kb) * 1024 if size_kb.isdigit() else 0
|
|
||||||
result.append(
|
|
||||||
{
|
|
||||||
"name": name,
|
|
||||||
"version": version,
|
|
||||||
"installed": True,
|
|
||||||
"description": "",
|
|
||||||
"size": size_bytes,
|
|
||||||
"source": "pve",
|
|
||||||
"source_package": source_package,
|
|
||||||
"source_version": source_version,
|
|
||||||
"upgrade_version": upgradable.get(name, ""),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return result
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Licenses (napalm-device-types' LicenseMixin)
|
# Licenses (napalm-device-types' LicenseMixin)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def get_licenses(self) -> list[_JsonDict]:
|
|
||||||
"""The node's subscription, as the API reports it.
|
|
||||||
|
|
||||||
A fact for the caller: whether running without one is a problem is not
|
|
||||||
the driver's to say. An unreadable subscription reports nothing.
|
|
||||||
"""
|
|
||||||
sub = self._get_node_subscription()
|
|
||||||
raw = str(sub.get("status", ""))
|
|
||||||
if not raw:
|
|
||||||
return []
|
|
||||||
lic: _JsonDict = {
|
|
||||||
"name": "pve-subscription",
|
|
||||||
"status": _SUBSCRIPTION_STATUS.get(raw.lower(), "unknown"),
|
|
||||||
"detail": sub.get("message") or raw,
|
|
||||||
}
|
|
||||||
if sub.get("productname"):
|
|
||||||
lic["edition"] = sub["productname"]
|
|
||||||
if sub.get("nextduedate"):
|
|
||||||
lic["expires"] = sub["nextduedate"]
|
|
||||||
return [lic]
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Services (systemd, through napalm-device-types' SystemdServicesMixin)
|
# Services (systemd, through napalm-device-types' SystemdServicesMixin)
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def _run_service_command(self, command: str, *, privileged: bool, timeout: int) -> str:
|
|
||||||
"""The transport for ``SystemdServicesMixin``: the exec path, as root.
|
|
||||||
|
|
||||||
*privileged* needs nothing more on a node the driver reaches as root, and
|
|
||||||
the exec path keeps its own timeout.
|
|
||||||
"""
|
|
||||||
return str(self._exec_ssh_command(command))
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Available updates
|
# Available updates
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
|
|
||||||
def get_available_updates(self) -> list[_JsonDict]:
|
|
||||||
"""Return the node's upgradable packages, with origin and security status.
|
|
||||||
|
|
||||||
``apt list --upgradable`` over the exec path names each candidate's suite
|
|
||||||
(``trixie-security``); the APT API names only an Origin ("Debian",
|
|
||||||
"Proxmox") and is the fallback, with the security status unknown.
|
|
||||||
|
|
||||||
:raises Exception: when neither answers -- never an empty list for
|
|
||||||
"could not read".
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
updates = parse_apt_upgradable(self._exec_ssh_command(APT_UPGRADABLE_COMMAND) or "")
|
|
||||||
except ValueError as exc:
|
|
||||||
logger.debug("apt list over the exec path failed, using the API: %s", exc)
|
|
||||||
updates = self._updates_from_api()
|
|
||||||
return sorted(updates, key=lambda u: u["name"])
|
|
||||||
|
|
||||||
def _updates_from_api(self) -> list[_JsonDict]:
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
"name": upd["Package"],
|
|
||||||
"current_version": upd.get("OldVersion", ""),
|
|
||||||
"new_version": upd.get("Version", ""),
|
|
||||||
"origin": upd.get("Origin"),
|
|
||||||
"security": None,
|
|
||||||
}
|
|
||||||
for upd in self._api.nodes(self._node_name).apt.update.get() # type: ignore[union-attr]
|
|
||||||
if upd.get("Package")
|
|
||||||
]
|
|
||||||
|
|
||||||
def refresh_available_updates(self) -> _JsonDict:
|
|
||||||
"""Resynchronise the node's package index (``POST nodes/{n}/apt/update``)."""
|
|
||||||
try:
|
|
||||||
task = self._api.nodes(self._node_name).apt.update.post() # type: ignore[union-attr]
|
|
||||||
except Exception as exc:
|
|
||||||
return {"success": False, "output": str(exc)}
|
|
||||||
return {"success": True, "output": f"Package index refresh started ({task})"}
|
|
||||||
|
|
||||||
def _run_host_status_command(self, command: str) -> str:
|
|
||||||
"""The transport for ``HostStatusMixin.get_host_status``: the exec path."""
|
|
||||||
return str(self._exec_ssh_command(command))
|
|
||||||
|
|
||||||
def apply_updates(self, packages: list[str]) -> _JsonDict:
|
|
||||||
"""Upgrade the given packages via ``apt-get install`` over SSH."""
|
|
||||||
for pkg in packages:
|
|
||||||
if not re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
|
|
||||||
raise ValueError(f"Invalid package name: {pkg!r}")
|
|
||||||
pkg_args = " ".join(packages)
|
|
||||||
output, status = self._rc(
|
|
||||||
f"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y {pkg_args}"
|
|
||||||
)
|
|
||||||
if status == 0:
|
|
||||||
return {"success": True, "output": output}
|
|
||||||
error = (
|
|
||||||
f"apt-get exited with status {status}"
|
|
||||||
if status >= 0
|
|
||||||
else "apt-get's exit status could not be read"
|
|
||||||
)
|
|
||||||
return {"success": False, "output": output, "error": error}
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# SNMP / Health
|
# SNMP / Health
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
@@ -548,59 +361,9 @@ class ProxmoxSystemMixin:
|
|||||||
# caller's values. The node's shell runs as root.
|
# caller's values. The node's shell runs as root.
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def _rc(self, command: str) -> tuple[str, int]:
|
|
||||||
"""Run *command* and return its output and exit status (-1 when unknown)."""
|
|
||||||
out = self._exec_ssh_command(f"{{ {command}; }} 2>&1; echo __PVE_RC=$?")
|
|
||||||
text, _, tail = out.rpartition("__PVE_RC=")
|
|
||||||
try:
|
|
||||||
return text.strip(), int(tail.strip())
|
|
||||||
except ValueError:
|
|
||||||
return out.strip(), -1
|
|
||||||
|
|
||||||
def _step(self, command: str, done: str) -> dict:
|
|
||||||
output, status = self._rc(command)
|
|
||||||
return {"ok": status == 0, "output": done if status == 0 else output[-300:]}
|
|
||||||
|
|
||||||
# apt's proxy (napalm-device-types AptProxyMixin): the transports. The node
|
# apt's proxy (napalm-device-types AptProxyMixin): the transports. The node
|
||||||
# is logged in as root, so every command runs as root.
|
# is logged in as root, so every command runs as root.
|
||||||
|
|
||||||
def _run_apt_command(self, command: str) -> str:
|
|
||||||
return str(self._exec_ssh_command(command))
|
|
||||||
|
|
||||||
def _run_apt_root_command(self, command: str, done: str) -> dict:
|
|
||||||
return self._step(command, done)
|
|
||||||
|
|
||||||
def _write_apt_file(self, path: str, content: str) -> dict:
|
|
||||||
return self._write_root_file(path, content)
|
|
||||||
|
|
||||||
def _write_root_file(self, path: str, content: str) -> dict:
|
|
||||||
"""Write *content* to *path* as root, mode 644, through a temporary file."""
|
|
||||||
encoded = base64.b64encode(content.encode()).decode()
|
|
||||||
# No ``exit`` here: it would end the shell before ``_rc`` reads the status.
|
|
||||||
return self._step(
|
|
||||||
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
|
|
||||||
f'install -m 644 -o root -g root "$t" {shlex.quote(path)}; '
|
|
||||||
's=$?; rm -f "$t"; [ "$s" -eq 0 ]',
|
|
||||||
f"wrote {path}",
|
|
||||||
)
|
|
||||||
|
|
||||||
def install_package(self, name: str, version: str = "") -> None:
|
|
||||||
"""apt-get install *name* (``PackageManagementMixin``); raises when apt fails."""
|
|
||||||
if not _PACKAGE_NAME.match(name) or (version and not _PACKAGE_NAME.match(version)):
|
|
||||||
raise ValueError(f"not a package name: {name!r}")
|
|
||||||
target = f"{name}={version}" if version else name
|
|
||||||
output, status = self._rc(f"DEBIAN_FRONTEND=noninteractive apt-get install -y {target}")
|
|
||||||
if status != 0:
|
|
||||||
raise RuntimeError(f"apt-get install {target} failed: {output[-300:]}")
|
|
||||||
|
|
||||||
def get_management_peer(self) -> str | None:
|
|
||||||
"""The address the node sees the SSH connection come from (``SSH_CONNECTION``)."""
|
|
||||||
out = self._exec_ssh_command('printf "%s\\n" "$SSH_CONNECTION"').split()
|
|
||||||
try:
|
|
||||||
return str(ipaddress.ip_address(out[0])) if out else None
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _install_snmp_agent(self) -> dict:
|
def _install_snmp_agent(self) -> dict:
|
||||||
return self._step(
|
return self._step(
|
||||||
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp", "net-snmp installed"
|
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp", "net-snmp installed"
|
||||||
|
|||||||
@@ -194,17 +194,3 @@ class ProxmoxVMContractMixin:
|
|||||||
return parse_vm_config(str(vmid), vm_type, cfg)
|
return parse_vm_config(str(vmid), vm_type, cfg)
|
||||||
|
|
||||||
# -- the node itself --------------------------------------------------------
|
# -- the node itself --------------------------------------------------------
|
||||||
|
|
||||||
def reboot_host(self) -> None:
|
|
||||||
"""Restart this Proxmox node through the API (no SSH involved)."""
|
|
||||||
try:
|
|
||||||
self._node_api().status.post(command="reboot")
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError(f"Reboot of node {self._node_name!r} refused: {exc}") from exc
|
|
||||||
|
|
||||||
def shutdown_host(self) -> None:
|
|
||||||
"""Shut this Proxmox node down through the API; its guests stop as on any shutdown."""
|
|
||||||
try:
|
|
||||||
self._node_api().status.post(command="shutdown")
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError(f"Shutdown of node {self._node_name!r} refused: {exc}") from exc
|
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
"coverage_floor": 68.0,
|
"coverage_floor": 68.0,
|
||||||
"function_complexity": {
|
"function_complexity": {
|
||||||
"napalm_proxmox/driver.py::ProxmoxDriver._resolve_node": 13,
|
"napalm_proxmox/driver.py::ProxmoxDriver._resolve_node": 13,
|
||||||
"napalm_proxmox/driver.py::ProxmoxDriver.get_facts": 16,
|
|
||||||
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_interfaces_counters": 14,
|
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_interfaces_counters": 14,
|
||||||
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 22,
|
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 22,
|
||||||
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.get_route_to": 13,
|
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.get_route_to": 13,
|
||||||
@@ -15,7 +14,6 @@
|
|||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 16,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 16,
|
||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 13,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 13,
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 22,
|
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 22,
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 16,
|
|
||||||
"napalm_proxmox/utils.py::addresses_from_node_network": 15,
|
"napalm_proxmox/utils.py::addresses_from_node_network": 15,
|
||||||
"napalm_proxmox/vm_contract_mixin.py::parse_vm_config": 16,
|
"napalm_proxmox/vm_contract_mixin.py::parse_vm_config": 16,
|
||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin._get_vm_disk_and_boot": 16,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin._get_vm_disk_and_boot": 16,
|
||||||
@@ -25,14 +23,12 @@
|
|||||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
|
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
|
||||||
},
|
},
|
||||||
"function_lines": {
|
"function_lines": {
|
||||||
"napalm_proxmox/driver.py::ProxmoxDriver.get_facts": 82,
|
|
||||||
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
||||||
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.ping": 78,
|
"napalm_proxmox/routing_mixin.py::ProxmoxRoutingMixin.ping": 78,
|
||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._get_vm_vlan_tags": 54,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin._get_vm_vlan_tags": 54,
|
||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 66,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.get_vlans": 66,
|
||||||
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 70,
|
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 70,
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
|
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 66,
|
|
||||||
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 114,
|
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 114,
|
||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179,
|
||||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""What the PVE driver hands proxmoxer, pinned before the connection moved into a
|
||||||
|
base it shares with the Proxmox Backup Server driver (#52)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
from tests.conftest import _build_mock_api
|
||||||
|
|
||||||
|
|
||||||
|
def _kwargs(username: str = "root", password: str = "secret", **optional_args) -> dict:
|
||||||
|
drv = ProxmoxDriver("pve1", username, password, optional_args=optional_args)
|
||||||
|
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=_build_mock_api()) as api:
|
||||||
|
drv.open()
|
||||||
|
return api.call_args.kwargs
|
||||||
|
|
||||||
|
|
||||||
|
def test_password_login_on_the_pve_port():
|
||||||
|
assert _kwargs() == {
|
||||||
|
"host": "pve1",
|
||||||
|
"user": "root@pam",
|
||||||
|
"password": "secret",
|
||||||
|
"port": 8006,
|
||||||
|
"verify_ssl": True,
|
||||||
|
"backend": "https",
|
||||||
|
"service": "PVE",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_port_and_realm_from_the_arguments():
|
||||||
|
kwargs = _kwargs(port=443, realm="pve")
|
||||||
|
assert (kwargs["port"], kwargs["user"]) == (443, "root@pve")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_username_with_a_realm_keeps_it():
|
||||||
|
assert _kwargs("admin@ldap")["user"] == "admin@ldap"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("arg", ["verify_ssl", "ssl_verify", "verify"])
|
||||||
|
def test_tls_verification_under_each_name(arg):
|
||||||
|
assert _kwargs(**{arg: False})["verify_ssl"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_without_a_user_part_is_passed_as_given():
|
||||||
|
kwargs = _kwargs(token_name="mytoken", token_value="s3cret")
|
||||||
|
assert (kwargs["user"], kwargs["token_name"], kwargs["token_value"]) == (
|
||||||
|
"root@pam",
|
||||||
|
"mytoken",
|
||||||
|
"s3cret",
|
||||||
|
)
|
||||||
|
assert "password" not in kwargs
|
||||||
@@ -60,8 +60,8 @@ def test_the_query_asks_for_the_field():
|
|||||||
not, so no amount of parsing could have produced one."""
|
not, so no amount of parsing could have produced one."""
|
||||||
import inspect
|
import inspect
|
||||||
|
|
||||||
from napalm_proxmox import system_mixin
|
from napalm_proxmox import host_mixin
|
||||||
|
|
||||||
source = inspect.getsource(system_mixin.ProxmoxSystemMixin.get_packages)
|
source = inspect.getsource(host_mixin.ProxmoxHostMixin.get_packages)
|
||||||
|
|
||||||
assert "source:Version" in source
|
assert "source:Version" in source
|
||||||
Reference in new issue
Block a user