258 lines
9.2 KiB
Python
258 lines
9.2 KiB
Python
"""Proxmox VE API client: guest discovery and IP address resolution."""
|
|||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import ipaddress
|
||
|
|
from dataclasses import dataclass, field
|
||
|
|
from typing import Iterable
|
||
|
|
|
||
|
|
from .config import ProxmoxConfig
|
||
|
|
from .errors import ApiError, ProxdomainError
|
||
|
|
from .http import JsonClient, Transport, UrllibTransport
|
||
|
|
|
||
|
|
|
||
|
|
@dataclass(frozen=True)
|
||
|
|
class Guest:
|
||
|
|
vmid: int
|
||
|
|
node: str
|
||
|
|
name: str
|
||
|
|
kind: str # "qemu" | "lxc"
|
||
|
|
status: str = "unknown"
|
||
|
|
tags: tuple[str, ...] = field(default_factory=tuple)
|
||
|
|
|
||
|
|
@property
|
||
|
|
def ref(self) -> str:
|
||
|
|
return f"{self.kind}/{self.vmid}"
|
||
|
|
|
||
|
|
@property
|
||
|
|
def label(self) -> str:
|
||
|
|
return f"{self.name or 'unnamed'} ({self.kind} {self.vmid} on {self.node})"
|
||
|
|
|
||
|
|
@property
|
||
|
|
def is_running(self) -> bool:
|
||
|
|
return self.status == "running"
|
||
|
|
|
||
|
|
|
||
|
|
class ProxmoxClient:
|
||
|
|
def __init__(
|
||
|
|
self,
|
||
|
|
config: ProxmoxConfig,
|
||
|
|
*,
|
||
|
|
http: JsonClient | None = None,
|
||
|
|
transport: Transport | None = None,
|
||
|
|
) -> None:
|
||
|
|
self.config = config
|
||
|
|
if http is None:
|
||
|
|
http = JsonClient(
|
||
|
|
config.api_url,
|
||
|
|
transport=transport or UrllibTransport(verify_tls=config.verify_tls),
|
||
|
|
timeout=config.timeout,
|
||
|
|
retries=1,
|
||
|
|
)
|
||
|
|
self.http = http
|
||
|
|
self._excluded = _parse_networks(config.exclude_networks)
|
||
|
|
self.http.default_headers["Authorization"] = (
|
||
|
|
f"PVEAPIToken={config.token_id}={config.resolve_secret()}"
|
||
|
|
)
|
||
|
|
|
||
|
|
# -- inventory ------------------------------------------------------
|
||
|
|
def list_guests(self) -> list[Guest]:
|
||
|
|
data = self.http.get("/cluster/resources", {"type": "vm"})
|
||
|
|
guests: list[Guest] = []
|
||
|
|
for item in _data_list(data):
|
||
|
|
if not isinstance(item, dict) or "vmid" not in item:
|
||
|
|
continue
|
||
|
|
kind = str(item.get("type") or "")
|
||
|
|
if kind not in ("qemu", "lxc"):
|
||
|
|
continue
|
||
|
|
guests.append(
|
||
|
|
Guest(
|
||
|
|
vmid=int(item["vmid"]),
|
||
|
|
node=str(item.get("node") or ""),
|
||
|
|
name=str(item.get("name") or ""),
|
||
|
|
kind=kind,
|
||
|
|
status=str(item.get("status") or "unknown"),
|
||
|
|
tags=_split_tags(item.get("tags")),
|
||
|
|
)
|
||
|
|
)
|
||
|
|
guests.sort(key=lambda g: (g.node, g.vmid))
|
||
|
|
return guests
|
||
|
|
|
||
|
|
def find_guest(
|
||
|
|
self, *, vmid: int | None = None, name: str | None = None
|
||
|
|
) -> Guest:
|
||
|
|
if vmid is None and not name:
|
||
|
|
raise ProxdomainError("specify a guest by --vmid or --name")
|
||
|
|
guests = self.list_guests()
|
||
|
|
if vmid is not None:
|
||
|
|
matches = [g for g in guests if g.vmid == vmid]
|
||
|
|
else:
|
||
|
|
needle = (name or "").strip().lower()
|
||
|
|
matches = [g for g in guests if g.name.lower() == needle]
|
||
|
|
if not matches:
|
||
|
|
matches = [g for g in guests if needle and needle in g.name.lower()]
|
||
|
|
if not matches:
|
||
|
|
target = f"vmid {vmid}" if vmid is not None else f"name {name!r}"
|
||
|
|
raise ProxdomainError(f"no guest found for {target}; check the PVE token permissions")
|
||
|
|
if len(matches) > 1:
|
||
|
|
listing = ", ".join(f"{g.kind}/{g.vmid} ({g.name})" for g in matches)
|
||
|
|
raise ProxdomainError(f"{name!r} matches several guests: {listing}; use --vmid")
|
||
|
|
return matches[0]
|
||
|
|
|
||
|
|
def new_guests(self, known_vmids: Iterable[int], *, tag: str = "") -> list[Guest]:
|
||
|
|
known = set(known_vmids)
|
||
|
|
result = []
|
||
|
|
for guest in self.list_guests():
|
||
|
|
if guest.vmid in known:
|
||
|
|
continue
|
||
|
|
if tag and tag not in guest.tags:
|
||
|
|
continue
|
||
|
|
result.append(guest)
|
||
|
|
return result
|
||
|
|
|
||
|
|
# -- addressing -----------------------------------------------------
|
||
|
|
def guest_ip(self, guest: Guest) -> str | None:
|
||
|
|
want = self.config.ip_preference
|
||
|
|
candidates: list[str] = []
|
||
|
|
|
||
|
|
if guest.kind == "qemu":
|
||
|
|
candidates.extend(self._agent_ips(guest))
|
||
|
|
else:
|
||
|
|
candidates.extend(self._lxc_runtime_ips(guest))
|
||
|
|
candidates.extend(self._config_ips(guest))
|
||
|
|
|
||
|
|
unique: list[str] = []
|
||
|
|
for address in candidates:
|
||
|
|
if address and address not in unique:
|
||
|
|
unique.append(address)
|
||
|
|
|
||
|
|
v4 = [a for a in unique if _version(a) == 4 and self._usable(a)]
|
||
|
|
v6 = [a for a in unique if _version(a) == 6 and self._usable(a)]
|
||
|
|
if want == "ipv4":
|
||
|
|
return (v4 or v6 or [None])[0]
|
||
|
|
if want == "ipv6":
|
||
|
|
return (v6 or v4 or [None])[0]
|
||
|
|
return (unique and next((a for a in unique if self._usable(a)), None)) or None
|
||
|
|
|
||
|
|
def _usable(self, address: str) -> bool:
|
||
|
|
try:
|
||
|
|
ip = ipaddress.ip_address(address)
|
||
|
|
except ValueError:
|
||
|
|
return False
|
||
|
|
if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified:
|
||
|
|
return False
|
||
|
|
return not any(ip in network for network in self._excluded)
|
||
|
|
|
||
|
|
def _agent_ips(self, guest: Guest) -> list[str]:
|
||
|
|
path = f"/nodes/{guest.node}/qemu/{guest.vmid}/agent/network-get-interfaces"
|
||
|
|
try:
|
||
|
|
data = self.http.get(path)
|
||
|
|
except ApiError as exc:
|
||
|
|
if exc.is_auth_error:
|
||
|
|
raise
|
||
|
|
return [] # qemu-guest-agent not installed/running: fall back to config
|
||
|
|
payload = data
|
||
|
|
if isinstance(payload, dict) and isinstance(payload.get("data"), (dict, list)):
|
||
|
|
payload = payload["data"]
|
||
|
|
if isinstance(payload, dict) and isinstance(payload.get("result"), list):
|
||
|
|
payload = payload["result"]
|
||
|
|
found: list[str] = []
|
||
|
|
if isinstance(payload, list):
|
||
|
|
for iface in payload:
|
||
|
|
if not isinstance(iface, dict) or iface.get("name") == "lo":
|
||
|
|
continue
|
||
|
|
for addr in iface.get("ip-addresses") or []:
|
||
|
|
if not isinstance(addr, dict):
|
||
|
|
continue
|
||
|
|
value = addr.get("ip-address")
|
||
|
|
kind = addr.get("ip-address-type")
|
||
|
|
if value and kind in ("ipv4", "ipv6", 4, 6):
|
||
|
|
found.append(str(value))
|
||
|
|
return found
|
||
|
|
|
||
|
|
def _lxc_runtime_ips(self, guest: Guest) -> list[str]:
|
||
|
|
path = f"/nodes/{guest.node}/lxc/{guest.vmid}/interfaces"
|
||
|
|
try:
|
||
|
|
data = self.http.get(path)
|
||
|
|
except ApiError as exc:
|
||
|
|
if exc.is_auth_error:
|
||
|
|
raise
|
||
|
|
return []
|
||
|
|
found: list[str] = []
|
||
|
|
for item in _data_list(data):
|
||
|
|
if not isinstance(item, dict):
|
||
|
|
continue
|
||
|
|
for key in ("inet", "inet6"):
|
||
|
|
value = str(item.get(key) or "").split("/")[0].strip()
|
||
|
|
if value and value != "127.0.0.1":
|
||
|
|
found.append(value)
|
||
|
|
return found
|
||
|
|
|
||
|
|
def _config_ips(self, guest: Guest) -> list[str]:
|
||
|
|
endpoint = "qemu" if guest.kind == "qemu" else "lxc"
|
||
|
|
try:
|
||
|
|
data = self.http.get(f"/nodes/{guest.node}/{endpoint}/{guest.vmid}/config")
|
||
|
|
except ApiError as exc:
|
||
|
|
if exc.is_auth_error:
|
||
|
|
raise
|
||
|
|
return []
|
||
|
|
config = data if isinstance(data, dict) else {}
|
||
|
|
if "data" in config and isinstance(config["data"], dict):
|
||
|
|
config = config["data"]
|
||
|
|
found: list[str] = []
|
||
|
|
for key, value in sorted(config.items()):
|
||
|
|
if not (key.startswith("net") or key.startswith("ipconfig")):
|
||
|
|
continue
|
||
|
|
if not isinstance(value, str):
|
||
|
|
continue
|
||
|
|
for option in value.split(","):
|
||
|
|
option = option.strip()
|
||
|
|
if "=" not in option:
|
||
|
|
continue
|
||
|
|
name, _, raw = option.partition("=")
|
||
|
|
if name.strip() not in ("ip", "ip6"):
|
||
|
|
continue
|
||
|
|
address = raw.split("/")[0].strip()
|
||
|
|
if address and address.lower() != "dhcp" and address.lower() != "auto":
|
||
|
|
found.append(address)
|
||
|
|
return found
|
||
|
|
|
||
|
|
|
||
|
|
# ---------------------------------------------------------------------------
|
||
|
|
def _parse_networks(values: Iterable[str]) -> tuple[ipaddress._BaseNetwork, ...]:
|
||
|
|
networks = []
|
||
|
|
for value in values:
|
||
|
|
try:
|
||
|
|
networks.append(ipaddress.ip_network(value, strict=False))
|
||
|
|
except ValueError as exc:
|
||
|
|
raise ProxdomainError(
|
||
|
|
f"proxmox.exclude_networks contains an invalid network {value!r}: {exc}"
|
||
|
|
) from exc
|
||
|
|
return tuple(networks)
|
||
|
|
|
||
|
|
|
||
|
|
def _data_list(data: object) -> list:
|
||
|
|
if isinstance(data, dict):
|
||
|
|
inner = data.get("data")
|
||
|
|
if isinstance(inner, list):
|
||
|
|
return inner
|
||
|
|
if inner is None:
|
||
|
|
return []
|
||
|
|
return [inner]
|
||
|
|
if isinstance(data, list):
|
||
|
|
return data
|
||
|
|
return []
|
||
|
|
|
||
|
|
|
||
|
|
def _split_tags(value: object) -> tuple[str, ...]:
|
||
|
|
if not isinstance(value, str):
|
||
|
|
return ()
|
||
|
|
normalized = value.replace(",", ";")
|
||
|
|
return tuple(tag.strip() for tag in normalized.split(";") if tag.strip())
|
||
|
|
|
||
|
|
|
||
|
|
def _version(address: str) -> int:
|
||
|
|
try:
|
||
|
|
return ipaddress.ip_address(address).version
|
||
|
|
except ValueError:
|
||
|
|
return 0
|