feat(slice-3): implement Proxmox VE REST API collector with guest agent IP resolution
This commit is contained in:
1 parent
951be389a1
commit
ca9163530f
4 files changed
+361
-1
No files matched your search
@@ -8,7 +8,7 @@
|
||||
## Slices
|
||||
- [x] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output)
|
||||
- [x] Slice 2 — Robust static file collector (YAML & INI) and Ansible exporters (YAML & JSON --list)
|
||||
- [ ] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution
|
||||
- [x] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution
|
||||
- [ ] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings
|
||||
- [ ] Slice 5 — Extended exporters (linux-connector, Generic YAML, XML) and --sync flag
|
||||
- [ ] Slice 6 — Configuration file (config.yaml), CLI check mode (--check), and documentation
|
||||
|
||||
@@ -72,6 +72,26 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
for host in collector.collect():
|
||||
inv.add_host(host)
|
||||
|
||||
# Check for Proxmox environment variables
|
||||
import os
|
||||
from inventory_collector.collectors.proxmox import ProxmoxCollector
|
||||
|
||||
pve_url = os.getenv("PROXMOX_URL") or os.getenv("ANSIBLE_PROXMOX_URL")
|
||||
pve_token_id = os.getenv("PROXMOX_TOKEN_ID") or os.getenv("ANSIBLE_PROXMOX_TOKEN_ID")
|
||||
pve_token_secret = os.getenv("PROXMOX_TOKEN_SECRET") or os.getenv("ANSIBLE_PROXMOX_TOKEN_SECRET")
|
||||
verify_ssl = os.getenv("PROXMOX_VERIFY_SSL", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
if pve_url and pve_token_id and pve_token_secret:
|
||||
sys.stderr.write(f"[INFO] Querying Proxmox VE API at {pve_url}...\n")
|
||||
pve_collector = ProxmoxCollector(
|
||||
url=pve_url,
|
||||
token_id=pve_token_id,
|
||||
token_secret=pve_token_secret,
|
||||
verify_ssl=verify_ssl
|
||||
)
|
||||
for host in pve_collector.collect():
|
||||
inv.add_host(host)
|
||||
|
||||
# Tracer bullet fallback if no hosts loaded
|
||||
if not inv.hosts:
|
||||
inv.add_host(HostRecord(
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
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"
|
||||
) -> 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
|
||||
|
||||
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:
|
||||
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 _resolve_dns_ip(self, name: str) -> Optional[str]:
|
||||
try:
|
||||
return socket.gethostbyname(name)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
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 = node_info.get("ip") or self._resolve_dns_ip(node_name) or ""
|
||||
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")
|
||||
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")
|
||||
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
|
||||
@@ -0,0 +1,125 @@
|
||||
import unittest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from inventory_collector.collectors.proxmox import ProxmoxCollector
|
||||
|
||||
class TestProxmoxCollector(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.collector = ProxmoxCollector(
|
||||
url="https://pve-01.wired.intra:8006",
|
||||
token_id="root@pam!collector",
|
||||
token_secret="12345678-abcd-1234-abcd-123456789abc",
|
||||
verify_ssl=False
|
||||
)
|
||||
|
||||
@patch("inventory_collector.collectors.proxmox.urllib.request.urlopen")
|
||||
def test_collect_nodes_and_vms(self, mock_urlopen):
|
||||
# Mock responses for different API endpoints
|
||||
def mock_api_router(req, *args, **kwargs):
|
||||
url = req.full_url if hasattr(req, "full_url") else str(req)
|
||||
resp = MagicMock()
|
||||
resp.status = 200
|
||||
resp.__enter__.return_value = resp
|
||||
|
||||
if url.endswith("/api2/json/nodes"):
|
||||
# Node listing
|
||||
payload = {
|
||||
"data": [
|
||||
{"node": "node0", "status": "online", "ip": "192.168.0.101"}
|
||||
]
|
||||
}
|
||||
elif "/qemu" in url and not "/agent" in url and not "/config" in url:
|
||||
# QEMU listing on node0
|
||||
payload = {
|
||||
"data": [
|
||||
{
|
||||
"vmid": 100,
|
||||
"name": "k3s-master-0",
|
||||
"status": "running",
|
||||
"tags": "k3s_master;control-plane",
|
||||
"template": 0
|
||||
},
|
||||
{
|
||||
"vmid": 900,
|
||||
"name": "debian-12-template",
|
||||
"status": "stopped",
|
||||
"template": 1 # Should be skipped!
|
||||
}
|
||||
]
|
||||
}
|
||||
elif "/lxc" in url and not "/config" in url:
|
||||
# LXC listing on node0
|
||||
payload = {
|
||||
"data": [
|
||||
{
|
||||
"vmid": 200,
|
||||
"name": "pihole-ct",
|
||||
"status": "running",
|
||||
"tags": "dns;network",
|
||||
"template": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
elif "/agent/network-get-interfaces" in url:
|
||||
# Guest agent IP
|
||||
payload = {
|
||||
"data": {
|
||||
"result": [
|
||||
{
|
||||
"name": "lo",
|
||||
"ip-addresses": [{"ip-address-type": "ipv4", "ip-address": "127.0.0.1"}]
|
||||
},
|
||||
{
|
||||
"name": "eth0",
|
||||
"ip-addresses": [{"ip-address-type": "ipv4", "ip-address": "192.168.5.70"}]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
elif "/lxc/200/config" in url:
|
||||
# LXC config with IP
|
||||
payload = {
|
||||
"data": {
|
||||
"net0": "name=eth0,bridge=vmbr0,ip=192.168.5.20/24,gw=192.168.5.1"
|
||||
}
|
||||
}
|
||||
else:
|
||||
payload = {"data": {}}
|
||||
|
||||
import json
|
||||
resp.read.return_value = json.dumps(payload).encode("utf-8")
|
||||
return resp
|
||||
|
||||
mock_urlopen.side_effect = mock_api_router
|
||||
|
||||
hosts = self.collector.collect()
|
||||
hosts_by_name = {h.name: h for h in hosts}
|
||||
|
||||
# 1. Hypervisor node should be collected
|
||||
self.assertIn("node0", hosts_by_name)
|
||||
self.assertEqual(hosts_by_name["node0"].ansible_host, "192.168.0.101")
|
||||
self.assertEqual(hosts_by_name["node0"].ansible_user, "root")
|
||||
self.assertIn("proxmox_nodes", hosts_by_name["node0"].groups)
|
||||
|
||||
# 2. Template should be skipped
|
||||
self.assertNotIn("debian-12-template", hosts_by_name)
|
||||
|
||||
# 3. QEMU VM with Guest Agent IP
|
||||
self.assertIn("k3s-master-0", hosts_by_name)
|
||||
k3s = hosts_by_name["k3s-master-0"]
|
||||
self.assertEqual(k3s.ansible_host, "192.168.5.70")
|
||||
self.assertIn("k3s_master", k3s.groups)
|
||||
self.assertIn("tag_k3s_master", k3s.groups)
|
||||
self.assertIn("proxmox_vms", k3s.groups)
|
||||
self.assertIn("pve_node_node0", k3s.groups)
|
||||
self.assertIn("status_running", k3s.groups)
|
||||
self.assertEqual(k3s.variables.get("proxmox_vmid"), 100)
|
||||
|
||||
# 4. LXC container with net0 config IP
|
||||
self.assertIn("pihole-ct", hosts_by_name)
|
||||
pihole = hosts_by_name["pihole-ct"]
|
||||
self.assertEqual(pihole.ansible_host, "192.168.5.20")
|
||||
self.assertIn("proxmox_lxc", pihole.groups)
|
||||
self.assertIn("dns", pihole.groups)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user