Files
headroom/modules/esxi/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

151 lines
5.8 KiB
Python

"""VMware ESXi / vCenter collector using pyVmomi (optional dependency)."""
from __future__ import annotations
from typing import Any, Dict
from app import sdk
def _connect(config: Dict[str, Any]):
try:
from pyVim.connect import SmartConnect
except ImportError:
raise sdk.ModuleError(
"pyvmomi is not installed. Run: .venv/bin/pip install pyvmomi (then restart Headroom)"
)
ssl_context = None
if not config.get("verify_tls", True):
import ssl
ssl_context = ssl._create_unverified_context()
try:
connection = SmartConnect(
host=config.get("host"),
user=config.get("username"),
pwd=config.get("password"),
port=sdk.free_port(config.get("port"), 443),
sslContext=ssl_context,
)
except Exception as exc:
raise sdk.ModuleError(f"vSphere connection failed: {exc}")
if not connection:
raise sdk.ModuleError("vSphere returned no session")
return connection
def collect(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host", "username", "password"]):
return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a vSphere endpoint"}
config = ctx["config"]
try:
from pyVmomi import vim
except ImportError:
raise sdk.ModuleError("pyvmomi is not installed. Run: .venv/bin/pip install pyvmomi")
connection = _connect(config)
assets = []
cluster_default = config.get("cluster_name") or "ESXi"
try:
content = connection.RetrieveContent()
host_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True)
try:
for host in host_view.view:
summary = host.summary
hardware = summary.hardware
quick = summary.quickStats
cores = float(getattr(hardware, "numCpuCores", 0) or 0)
cpu_mhz = float(getattr(hardware, "cpuMhz", 0) or 0) * cores
mem_bytes = float(getattr(hardware, "memorySize", 0) or 0)
cluster = cluster_default
try:
if host.parent is not None:
cluster = host.parent.name
except Exception:
pass
assets.append(
sdk.add_asset(
external_id=host.name,
name=host.name,
type_="hypervisor",
metrics={
"cpu_pct": sdk.percent(float(getattr(quick, "overallCpuUsage", 0) or 0), cpu_mhz),
"mem_pct": sdk.percent(
float(getattr(quick, "overallMemoryUsage", 0) or 0) * 1024 ** 2, mem_bytes
),
"uptime_days": round(float(getattr(quick, "uptime", 0) or 0) / 86400, 1),
"vm_count": len(getattr(host, "vm", []) or []),
},
capacity={"cpu_cores": cores, "mem_gb": round(mem_bytes / 1024 ** 3, 1)},
cluster=cluster,
tags=["esxi"],
meta={
"version": getattr(summary.config.product, "version", "") if summary.config else "",
"model": getattr(hardware, "model", ""),
},
)
)
finally:
host_view.Destroy()
datastore_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.Datastore], True)
try:
for datastore in datastore_view.view:
summary = datastore.summary
total = float(summary.capacity or 0)
free = float(summary.freeSpace or 0)
if total <= 0:
continue
cluster = cluster_default
try:
if datastore.parent is not None:
cluster = datastore.parent.name
except Exception:
pass
assets.append(
sdk.add_asset(
external_id=datastore.name,
name=datastore.name,
type_="storage",
metrics={
"storage_pct": sdk.percent(total - free, total),
"storage_used_gb": round((total - free) / 1024 ** 3, 1),
"storage_total_gb": round(total / 1024 ** 3, 1),
},
capacity={"storage_gb": round(total / 1024 ** 3, 1)},
cluster=cluster,
tags=[str(summary.type) if summary.type else "datastore"],
meta={"accessible": bool(summary.accessible)},
)
)
finally:
datastore_view.Destroy()
return {"assets": assets, "notes": f"Collected {len(assets)} assets from {config.get('host')}"}
finally:
try:
from pyVim.connect import Disconnect
Disconnect(connection)
except Exception:
pass
def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host", "username", "password"]):
return {"ok": True, "message": "Demo mode — no vSphere endpoint contacted."}
connection = _connect(ctx["config"])
try:
about = connection.content.about
return {
"ok": True,
"message": f"Connected to {about.fullName}",
"details": {"version": about.version, "build": about.build},
}
finally:
try:
from pyVim.connect import Disconnect
Disconnect(connection)
except Exception:
pass