import json import re import socket import ssl import sys import urllib.request import urllib.error from typing import Any, Dict, List, Optional from inventory_collector.collectors.base import BaseCollector from inventory_collector.models import HostRecord class ProxmoxCollector(BaseCollector): """Collects hypervisor nodes, virtual machines, and LXC containers from Proxmox VE API.""" def __init__( self, url: str, token_id: str, token_secret: str, verify_ssl: bool = False, timeout: int = 10, default_user: str = "lain", quiet: bool = False, resolve_dns: bool = True ) -> None: # Normalize base URL (strip trailing slashes and /api2/json if included) clean_url = url.rstrip("/") clean_url = re.sub(r"/api2/json/?$", "", clean_url) self.base_url = clean_url self.token_id = token_id self.token_secret = token_secret self.verify_ssl = verify_ssl self.timeout = timeout self.default_user = default_user self.quiet = quiet self.resolve_dns = resolve_dns self.wildcard_ip: Optional[str] = self._detect_wildcard_dns() if self.resolve_dns else None if not self.verify_ssl: self.ssl_context = ssl._create_unverified_context() else: self.ssl_context = ssl.create_default_context() def _api_get(self, endpoint: str) -> Any: url = f"{self.base_url}/api2/json{endpoint}" req = urllib.request.Request(url) req.add_header("Authorization", f"PVEAPIToken={self.token_id}={self.token_secret}") req.add_header("Accept", "application/json") try: with urllib.request.urlopen(req, context=self.ssl_context, timeout=self.timeout) as resp: data = json.loads(resp.read().decode("utf-8")) return data.get("data", {}) except urllib.error.HTTPError as e: # 500 often happens if guest agent is not running on VM return {} except Exception as e: if not self.quiet: sys.stderr.write(f"[WARN] Proxmox API request failed for '{endpoint}': {e}\n") return {} def _parse_tags(self, raw_tags: Optional[str]) -> List[str]: if not raw_tags: return [] cleaned = re.sub(r"[,;]", " ", str(raw_tags)) return [t.strip() for t in cleaned.split() if t.strip()] def _detect_wildcard_dns(self) -> Optional[str]: """Detect if local DNS environment resolves non-existent hostnames to a wildcard IP.""" try: import uuid test_host = f"nxdomain-probe-{uuid.uuid4().hex[:12]}" ip = socket.gethostbyname(test_host) if ip and not self.quiet: sys.stderr.write(f"[INFO] Detected DNS wildcard catch-all resolving to '{ip}'. Collision protection active.\n") return ip except Exception: return None def _resolve_dns_ip(self, name: str) -> Optional[str]: if not self.resolve_dns: return None try: resolved = socket.gethostbyname(name) if self.wildcard_ip and resolved == self.wildcard_ip: # Wildcard catch-all detected; not a genuine host-specific resolution return None return resolved except Exception: return None def _resolve_node_ip(self, node_name: str, node_info: Dict[str, Any]) -> str: # 1. From node info if present if node_info.get("ip"): return str(node_info["ip"]) # 2. Query /nodes/{node}/network for active physical bridge (vmbr0) or IP net_data = self._api_get(f"/nodes/{node_name}/network") if isinstance(net_data, list): # Prefer vmbr0 or interface with gateway for iface in net_data: addr = iface.get("address") if addr and not str(addr).startswith("127."): if iface.get("iface") == "vmbr0" or iface.get("gateway"): return str(addr) for iface in net_data: addr = iface.get("address") if addr and not str(addr).startswith("127."): return str(addr) # 3. Safe DNS fallback dns_ip = self._resolve_dns_ip(node_name) if dns_ip: return dns_ip # 4. Fallback if base_url contains IP m = re.search(r"://([^:/]+)", self.base_url) if m: host_part = m.group(1) if re.match(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$", host_part): return host_part return "" def _resolve_qemu_ip(self, node: str, vmid: int, vm_name: str) -> str: # 1. Try QEMU Guest Agent agent_data = self._api_get(f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces") if isinstance(agent_data, dict) and "result" in agent_data: interfaces = agent_data.get("result", []) for iface in interfaces: if iface.get("name") == "lo": continue for addr in iface.get("ip-addresses", []): if addr.get("ip-address-type") == "ipv4": ip = addr.get("ip-address", "").strip() if ip and not ip.startswith("127.") and not ip.startswith("169.254."): return ip # 2. Try VM hardware config config = self._api_get(f"/nodes/{node}/qemu/{vmid}/config") if isinstance(config, dict): for k in ("ipconfig0", "ipconfig1", "net0", "net1"): val = str(config.get(k, "")) m_ip = re.search(r"ip=([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", val) if m_ip: return m_ip.group(1) # 3. Try DNS resolution dns_ip = self._resolve_dns_ip(vm_name) if dns_ip: return dns_ip return "" def _resolve_lxc_ip(self, node: str, vmid: int, ct_name: str) -> str: # Check container config config = self._api_get(f"/nodes/{node}/lxc/{vmid}/config") if isinstance(config, dict): for k in ("net0", "net1", "net2"): val = str(config.get(k, "")) m_ip = re.search(r"ip=([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", val) if m_ip: return m_ip.group(1) # Try DNS resolution dns_ip = self._resolve_dns_ip(ct_name) if dns_ip: return dns_ip return "" def collect(self) -> List[HostRecord]: records: List[HostRecord] = [] nodes_data = self._api_get("/nodes") if not isinstance(nodes_data, list): return records for node_info in nodes_data: node_name = node_info.get("node") if not node_name: continue # Hypervisor physical node node_ip = self._resolve_node_ip(node_name, node_info) records.append(HostRecord( name=node_name, ansible_host=node_ip, ansible_user="root", groups=["proxmox_nodes"], tags=["hypervisor", "pve"], variables={"proxmox_node": node_name, "proxmox_status": node_info.get("status", "unknown")}, source="proxmox:node" )) # QEMU Virtual Machines qemu_list = self._api_get(f"/nodes/{node_name}/qemu") if isinstance(qemu_list, list): for vm in qemu_list: if vm.get("template") == 1: continue # Skip templates vmid = vm.get("vmid") vm_name = vm.get("name") or f"vm-{vmid}" status = vm.get("status", "unknown") tags = self._parse_tags(vm.get("tags")) ip = self._resolve_qemu_ip(node_name, vmid, vm_name) if not ip: tags.append("no-ip") if not self.quiet: sys.stderr.write(f"[WARN] No IP address discovered for VM '{vm_name}' (vmid: {vmid}, status: {status})\n") groups = ["proxmox_vms", f"pve_node_{node_name}", f"status_{status}"] for t in tags: if t != "no-ip": groups.append(t) groups.append(f"tag_{t}") records.append(HostRecord( name=vm_name, ansible_host=ip, ansible_user=self.default_user, groups=sorted(list(set(groups))), tags=sorted(list(set(tags))), variables={ "proxmox_vmid": vmid, "proxmox_node": node_name, "proxmox_type": "qemu", "proxmox_status": status }, source="proxmox:qemu" )) # LXC Containers lxc_list = self._api_get(f"/nodes/{node_name}/lxc") if isinstance(lxc_list, list): for ct in lxc_list: if ct.get("template") == 1: continue # Skip templates vmid = ct.get("vmid") ct_name = ct.get("name") or f"ct-{vmid}" status = ct.get("status", "unknown") tags = self._parse_tags(ct.get("tags")) ip = self._resolve_lxc_ip(node_name, vmid, ct_name) if not ip: tags.append("no-ip") if not self.quiet: sys.stderr.write(f"[WARN] No IP address discovered for LXC container '{ct_name}' (vmid: {vmid}, status: {status})\n") groups = ["proxmox_lxc", f"pve_node_{node_name}", f"status_{status}"] for t in tags: if t != "no-ip": groups.append(t) groups.append(f"tag_{t}") records.append(HostRecord( name=ct_name, ansible_host=ip, ansible_user=self.default_user, groups=sorted(list(set(groups))), tags=sorted(list(set(tags))), variables={ "proxmox_vmid": vmid, "proxmox_node": node_name, "proxmox_type": "lxc", "proxmox_status": status }, source="proxmox:lxc" )) return records