Files
headroom/modules/proxmox/module.py
T
kristianwind 15bbe02277 Headroom: homelab capacity dashboard
- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json)
- Multi-instance support: flere instanser af samme modultype med adskilte assets
- Community/Enterprise licensing med admin enterprise-toggle
- Capacity forecasting, trends, what-if simulator, alert policies
- MCP server + LLM copilot integration
- Dockerfile + rune.yaml til Yggdrasil
2026-10-23 22:39:27 +02:00

120 lines
5.3 KiB
Python

"""Proxmox VE collector — API token (recommended) or ticket authentication."""
from __future__ import annotations
from typing import Any, Dict
from app import sdk
def _session(config: Dict[str, Any]):
base = sdk.base_url(config, "https", 8006)
session = sdk.http_session(config)
token_id = str(config.get("token_id", "")).strip()
token_secret = str(config.get("token_secret", "")).strip()
if token_id and token_secret:
session.headers["Authorization"] = f"PVEAPIToken={token_id}={token_secret}"
elif config.get("username") and config.get("password"):
response = session.post(
f"{base}/api2/json/access/ticket",
data={"username": config.get("username"), "password": config.get("password")},
timeout=15,
)
response.raise_for_status()
ticket = (response.json().get("data") or {}).get("ticket")
if not ticket:
raise sdk.ModuleError("Proxmox ticket authentication returned no ticket")
session.cookies.set("PVEAuthCookie", ticket)
else:
raise sdk.ModuleError("Configure an API token or username/password for Proxmox")
return base, session
def collect(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host"]):
return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a Proxmox endpoint"}
config = ctx["config"]
base, session = _session(config)
cluster = config.get("cluster_name") or "Proxmox"
try:
nodes = sdk.get_json(session, f"{base}/api2/json/nodes").get("data", [])
assets = []
for node in nodes[:100]:
name = node.get("node") or node.get("id") or "node"
if node.get("status") not in (None, "online"):
continue
maxmem = float(node.get("maxmem") or 0)
mem = float(node.get("mem") or 0)
maxcpu = float(node.get("maxcpu") or 0)
metrics = {
"cpu_pct": round(float(node.get("cpu") or 0) * 100, 2),
"mem_pct": sdk.percent(mem, maxmem),
"uptime_days": round(float(node.get("uptime") or 0) / 86400, 1),
}
try:
qemu = sdk.get_json(session, f"{base}/api2/json/nodes/{name}/qemu").get("data", [])
lxc = sdk.get_json(session, f"{base}/api2/json/nodes/{name}/lxc").get("data", [])
metrics["vm_count"] = len(qemu) + len(lxc)
except Exception as exc:
ctx["log"](f"guest inventory failed for {name}: {exc}")
assets.append(
sdk.add_asset(
external_id=name,
name=name,
type_="hypervisor",
metrics=metrics,
capacity={"cpu_cores": maxcpu, "mem_gb": round(maxmem / 1024 ** 3, 1)},
cluster=cluster,
tags=["pve"],
meta={"version": node.get("version") or "", "status": node.get("status") or ""},
)
)
try:
storages = sdk.get_json(session, f"{base}/api2/json/nodes/{name}/storage").get("data", [])
except Exception as exc:
ctx["log"](f"storage inventory failed for {name}: {exc}")
storages = []
for storage in storages:
if storage.get("active") == 0:
continue
total = float(storage.get("total") or 0)
used = float(storage.get("used") or 0)
if total <= 0:
continue
storage_name = str(storage.get("storage") or "storage")
shared = bool(storage.get("shared"))
external_id = storage_name if shared else f"{name}/{storage_name}"
display = storage_name if shared else f"{storage_name} ({name})"
assets.append(
sdk.add_asset(
external_id=external_id,
name=display,
type_="storage",
metrics={
"storage_pct": sdk.percent(used, total),
"storage_used_gb": round(used / 1024 ** 3, 1),
"storage_total_gb": round(total / 1024 ** 3, 1),
},
capacity={"storage_gb": round(total / 1024 ** 3, 1)},
cluster=cluster,
tags=["shared"] if shared else ["local"],
meta={"node": name, "type": storage.get("type") or "", "content": storage.get("content") or ""},
)
)
return {"assets": assets, "notes": f"Collected {len(assets)} assets from {base}"}
except Exception as exc:
raise sdk.ModuleError(f"Proxmox collection failed: {exc}")
def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host"]):
return {"ok": True, "message": "Demo mode — no Proxmox endpoint contacted."}
config = ctx["config"]
base, session = _session(config)
version = sdk.get_json(session, f"{base}/api2/json/version").get("data", {})
return {
"ok": True,
"message": f"Connected to Proxmox {version.get('version', '')} at {base}",
"details": {"version": version.get("version"), "release": version.get("release")},
}