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

104 lines
3.9 KiB
Python

"""TrueNAS SCALE collector — pools and system load."""
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", 443)
session = sdk.http_session(config)
key = str(config.get("api_key", "")).strip()
if not key:
raise sdk.ModuleError("Configure a TrueNAS API key")
session.headers["Authorization"] = f"Bearer {key}"
return base, session
def collect(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host", "api_key"]):
return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a TrueNAS endpoint"}
config = ctx["config"]
base, session = _session(config)
cluster = config.get("cluster_name") or "Storage"
try:
info = sdk.get_json(session, f"{base}/api/v2.0/system/info")
except Exception as exc:
raise sdk.ModuleError(f"TrueNAS system info failed: {exc}")
hostname = info.get("hostname") or config.get("host") or "truenas"
cores = float(info.get("cores") or 0)
physmem = float(info.get("physmem") or 0)
uptime = float(info.get("uptime_seconds") or 0)
metrics: Dict[str, float] = {"uptime_days": round(uptime / 86400, 1)}
loadavg = info.get("loadavg") or []
if cores and loadavg:
try:
metrics["load_pct"] = round(float(loadavg[0]) / cores * 100, 1)
except (TypeError, ValueError):
pass
assets = [
sdk.add_asset(
external_id=hostname,
name=hostname,
type_="nas",
metrics=metrics,
capacity={"cpu_cores": cores, "mem_gb": round(physmem / 1024 ** 3, 1)},
cluster=cluster,
tags=["truenas"],
meta={"version": str(info.get("version", "")), "model": str(info.get("system_product", ""))},
)
]
notes = []
try:
pools = sdk.get_json(session, f"{base}/api/v2.0/pool")
except Exception as exc:
raise sdk.ModuleError(f"TrueNAS pool inventory failed: {exc}")
pool_rows = pools if isinstance(pools, list) else []
for pool in pool_rows[:100]:
name = str(pool.get("name") or "pool")
total = float(pool.get("size") or 0)
allocated = float(pool.get("allocated") or pool.get("used") or 0)
if total <= 0:
notes.append(f"pool {name}: capacity not reported by this API version")
continue
assets.append(
sdk.add_asset(
external_id=f"pool-{name}",
name=f"{name} (pool)",
type_="storage",
metrics={
"storage_pct": sdk.percent(allocated, total),
"storage_used_gb": round(allocated / 1024 ** 3, 1),
"storage_total_gb": round(total / 1024 ** 3, 1),
},
capacity={"storage_gb": round(total / 1024 ** 3, 1)},
cluster=cluster,
tags=["zfs", str(pool.get("status", "")).lower()],
meta={
"pool": name,
"status": pool.get("status"),
"healthy": pool.get("healthy"),
"fragmentation": pool.get("fragmentation"),
},
)
)
note = f"Collected {len(assets)} assets from {base}"
if notes:
note += " — " + "; ".join(notes)
return {"assets": assets, "notes": note}
def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host", "api_key"]):
return {"ok": True, "message": "Demo mode — no TrueNAS endpoint contacted."}
base, session = _session(ctx["config"])
info = sdk.get_json(session, f"{base}/api/v2.0/system/info")
return {
"ok": True,
"message": f"Connected to {info.get('hostname', base)} (TrueNAS {info.get('version', '')})",
"details": {"version": info.get("version"), "hostname": info.get("hostname")},
}