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
This commit is contained in:
kristianwind
2026-10-23 22:39:27 +02:00
commit 15bbe02277
49 changed files with 9984 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
{
"id": "esxi",
"name": "VMware ESXi / vCenter",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "hypervisor",
"icon": "vmware",
"interval_seconds": 300,
"enabled_by_default": true,
"description": "Hosts and datastores via the vSphere API. Install the optional pyvmomi package to collect live host statistics.",
"capabilities": ["assets", "metrics", "capacity"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true},
{"key": "host", "label": "vCenter / ESXi host", "type": "text", "default": "", "placeholder": "vcenter.lab.local"},
{"key": "port", "label": "Port", "type": "number", "default": 443},
{"key": "username", "label": "Username", "type": "text", "default": "", "placeholder": "[email protected]"},
{"key": "password", "label": "Password", "type": "password", "default": ""},
{"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false},
{"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "ESXi"}
]
}
+150
View File
@@ -0,0 +1,150 @@
"""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
+23
View File
@@ -0,0 +1,23 @@
{
"id": "http-json",
"name": "HTTP JSON bridge",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "integration",
"icon": "api",
"interval_seconds": 300,
"enabled_by_default": true,
"description": "Pull a normalized asset/metric payload from any HTTP API, or push to /api/ingest/http-json. Ideal for UPS, switches and custom scripts.",
"capabilities": ["assets", "metrics", "push"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true},
{"key": "url", "label": "JSON endpoint", "type": "text", "default": "", "placeholder": "https://api.example.net/capacity"},
{"key": "token", "label": "Bearer token", "type": "password", "default": ""},
{"key": "headers", "label": "Extra headers (JSON)", "type": "textarea", "default": "", "placeholder": "{\"X-Api-Key\": \"...\"}"},
{"key": "assets_path", "label": "Assets path", "type": "text", "default": "assets", "help": "Dot path to the asset list, e.g. data.hosts"},
{"key": "cluster_name", "label": "Default cluster label", "type": "text", "default": "External API"},
{"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": true}
]
}
+82
View File
@@ -0,0 +1,82 @@
"""Generic HTTP JSON bridge.
Pull mode expects::
{"assets": [{"external_id": "...", "name": "...", "type": "server",
"capacity": {"cpu_cores": 8},
"metrics": {"cpu_pct": 42}}]}
Configure ``assets_path`` if the list is nested (e.g. ``data.hosts``).
Push mode is served by the core at ``POST /api/ingest/http-json``.
"""
from __future__ import annotations
import json
from typing import Any, Dict
from app import sdk
def _fetch(ctx: Dict[str, Any]):
config = ctx["config"]
url = str(config.get("url", "")).strip()
if not url:
raise sdk.ModuleError("Configure the JSON endpoint URL")
session = sdk.http_session(config)
token = str(config.get("token", "")).strip()
if token:
session.headers["Authorization"] = f"Bearer {token}"
raw_headers = str(config.get("headers", "") or "").strip()
if raw_headers:
try:
extra = json.loads(raw_headers)
if isinstance(extra, dict):
session.headers.update({str(k): str(v) for k, v in extra.items()})
except ValueError:
raise sdk.ModuleError("Extra headers must be a JSON object")
response = session.get(url, timeout=30)
response.raise_for_status()
return response.json()
def _extract(payload: Any, path: str):
node = payload
for part in (path or "assets").split("."):
if not part:
continue
if not isinstance(node, dict) or part not in node:
raise sdk.ModuleError(f"Assets path '{path}' not found in the response")
node = node[part]
if isinstance(node, dict) and "external_id" in node:
return [node]
if not isinstance(node, list):
raise sdk.ModuleError(f"Assets path '{path}' did not resolve to a list")
return node
def collect(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["url"]):
return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — no external API contacted"}
config = ctx["config"]
payload = _fetch(ctx)
items = _extract(payload, str(config.get("assets_path") or "assets"))
cluster = str(config.get("cluster_name") or "").strip()
assets = []
for item in items[:2000]:
if not isinstance(item, dict):
continue
item = dict(item)
item.setdefault("type", "server")
if cluster and not item.get("cluster"):
item["cluster"] = cluster
assets.append(item)
return {"assets": assets, "notes": f"Fetched {len(assets)} assets from {config.get('url')}"}
def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["url"]):
return {"ok": True, "message": "Demo mode — no external API contacted."}
payload = _fetch(ctx)
items = _extract(payload, str(ctx["config"].get("assets_path") or "assets"))
return {"ok": True, "message": f"Endpoint reachable — found {len(items)} asset(s)."}
+22
View File
@@ -0,0 +1,22 @@
{
"id": "linux",
"name": "Linux hosts (SSH)",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "os",
"icon": "linux",
"interval_seconds": 300,
"enabled_by_default": true,
"description": "Agentless Linux host metrics over SSH using /proc and df. Key-based authentication only.",
"capabilities": ["assets", "metrics", "capacity"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true},
{"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "lnx-01.lab.local"},
{"key": "port", "label": "SSH port", "type": "number", "default": 22},
{"key": "username", "label": "SSH username", "type": "text", "default": "headroom"},
{"key": "key_path", "label": "Private key path", "type": "text", "default": "", "placeholder": "~/.ssh/id_ed25519"},
{"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Linux"}
]
}
+140
View File
@@ -0,0 +1,140 @@
"""Agentless Linux host collector over SSH (key authentication)."""
from __future__ import annotations
import subprocess
from pathlib import Path
from typing import Any, Dict
from app import sdk
SCRIPT = r"""
set -e
echo "__NPROC__"
nproc
echo "__MEM__"
awk '/MemTotal/{t=$2} /MemAvailable/{a=$2} /MemFree/{f=$2} END{if(!a)a=f; print t, a}' /proc/meminfo
echo "__DISK__"
df -P -B1 / | awk 'NR==2 {print $2, $3}'
echo "__UPTIME__"
awk '{print $1}' /proc/uptime
echo "__LOAD__"
awk '{print $1}' /proc/loadavg
echo "__OS__"
uname -sr
echo "__CPU1__"
awk '/^cpu / {s=0; for(i=2;i<=NF;i++) s+=$i; print s, $5+$6}' /proc/stat
sleep 1
echo "__CPU2__"
awk '/^cpu / {s=0; for(i=2;i<=NF;i++) s+=$i; print s, $5+$6}' /proc/stat
"""
def _ssh(config: Dict[str, Any], command: str, timeout: int = 40) -> str:
host = str(config.get("host", "")).strip()
user = str(config.get("username", "")).strip()
if not host or not user:
raise sdk.ModuleError("Configure host and SSH username")
key_path = str(config.get("key_path", "")).strip()
if not key_path:
key_path = "~/.ssh/id_ed25519"
key = Path(key_path).expanduser()
if not key.exists():
raise sdk.ModuleError(f"SSH private key not found: {key}")
command_line = [
"ssh",
"-i", str(key),
"-p", str(sdk.free_port(config.get("port"), 22)),
"-o", "BatchMode=yes",
"-o", "StrictHostKeyChecking=accept-new",
"-o", "ConnectTimeout=10",
"-o", "LogLevel=ERROR",
f"{user}@{host}",
command,
]
try:
result = subprocess.run(command_line, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
raise sdk.ModuleError("SSH command timed out")
except FileNotFoundError:
raise sdk.ModuleError("The 'ssh' client is not available on the Headroom host")
if result.returncode != 0:
detail = (result.stderr or result.stdout or "").strip()[-500:]
raise sdk.ModuleError(f"SSH failed (exit {result.returncode}): {detail}")
return result.stdout
def _parse_markers(output: str) -> Dict[str, str]:
values: Dict[str, str] = {}
current = None
buffer = []
for line in output.splitlines():
if line.startswith("__") and line.endswith("__"):
if current:
values[current] = "\n".join(buffer).strip()
current = line.strip("_")
buffer = []
elif current:
buffer.append(line)
if current:
values[current] = "\n".join(buffer).strip()
return values
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 an SSH endpoint"}
config = ctx["config"]
output = _ssh(config, SCRIPT)
data = _parse_markers(output)
try:
nproc = max(1, int(float(data.get("NPROC", "1"))))
mem_parts = data.get("MEM", "0 0").split()
mem_total_kb = float(mem_parts[0])
mem_avail_kb = float(mem_parts[1]) if len(mem_parts) > 1 else 0.0
disk_parts = data.get("DISK", "0 0").split()
disk_total = float(disk_parts[0])
disk_used = float(disk_parts[1])
uptime_seconds = float(data.get("UPTIME", "0").split()[0])
load1 = float(data.get("LOAD", "0").split()[0])
cpu1 = [float(x) for x in data.get("CPU1", "0 0").split()]
cpu2 = [float(x) for x in data.get("CPU2", "0 0").split()]
total_delta = cpu2[0] - cpu1[0]
idle_delta = cpu2[1] - cpu1[1]
cpu_pct = (1 - idle_delta / total_delta) * 100 if total_delta > 0 else 0.0
mem_total_bytes = mem_total_kb * 1024
mem_used_bytes = max(0.0, mem_total_bytes - mem_avail_kb * 1024)
metrics = {
"cpu_pct": round(max(0.0, min(100.0, cpu_pct)), 2),
"mem_pct": round(sdk.percent(mem_used_bytes, mem_total_bytes), 2),
"storage_pct": round(sdk.percent(disk_used, disk_total), 2),
"storage_used_gb": round(disk_used / 1024 ** 3, 1),
"storage_total_gb": round(disk_total / 1024 ** 3, 1),
"load_pct": round(load1 / nproc * 100, 1),
"uptime_days": round(uptime_seconds / 86400, 1),
}
except (ValueError, IndexError) as exc:
raise sdk.ModuleError(f"Could not parse Linux telemetry: {exc}")
host = str(config.get("host"))
asset = sdk.add_asset(
external_id=host,
name=host.split(".")[0],
type_="server",
metrics=metrics,
capacity={
"cpu_cores": nproc,
"mem_gb": round(mem_total_bytes / 1024 ** 3, 1),
"storage_gb": round(disk_total / 1024 ** 3, 1),
},
cluster=config.get("cluster_name") or "Linux",
tags=["linux"],
meta={"os": data.get("OS", ""), "host": host},
)
return {"assets": [asset], "notes": f"Collected Linux telemetry from {host}"}
def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host"]):
return {"ok": True, "message": "Demo mode — no SSH endpoint contacted."}
output = _ssh(ctx["config"], "echo connected; uname -sr", timeout=25)
return {"ok": True, "message": f"SSH connection OK — {output.strip()[:120]}"}
+25
View File
@@ -0,0 +1,25 @@
{
"id": "proxmox",
"name": "Proxmox VE",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "hypervisor",
"icon": "proxmox",
"interval_seconds": 300,
"enabled_by_default": true,
"description": "Nodes, storage and guest counts from the Proxmox VE API. Uses API tokens (recommended) or ticket auth.",
"capabilities": ["assets", "metrics", "capacity"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true, "help": "Generate realistic local data without contacting a Proxmox host."},
{"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "pve.lab.local"},
{"key": "port", "label": "API port", "type": "number", "default": 8006},
{"key": "token_id", "label": "API token ID", "type": "text", "default": "", "placeholder": "root@pam!headroom"},
{"key": "token_secret", "label": "API token secret", "type": "password", "default": ""},
{"key": "username", "label": "Username (fallback)", "type": "text", "default": "", "placeholder": "root@pam"},
{"key": "password", "label": "Password (fallback)", "type": "password", "default": ""},
{"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false},
{"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Proxmox"}
]
}
+119
View File
@@ -0,0 +1,119 @@
"""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")},
}
+24
View File
@@ -0,0 +1,24 @@
{
"id": "splunk",
"name": "Splunk",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "observability",
"icon": "splunk",
"interval_seconds": 600,
"enabled_by_default": true,
"description": "Index storage, license consumption and indexer health from the Splunk management API.",
"capabilities": ["assets", "metrics", "capacity"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true},
{"key": "host", "label": "Search head / indexer", "type": "text", "default": "", "placeholder": "splunk.lab.local"},
{"key": "port", "label": "Management port", "type": "number", "default": 8089},
{"key": "token", "label": "Bearer token", "type": "password", "default": ""},
{"key": "username", "label": "Username (fallback)", "type": "text", "default": ""},
{"key": "password", "label": "Password (fallback)", "type": "password", "default": ""},
{"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false},
{"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Splunk"}
]
}
+137
View File
@@ -0,0 +1,137 @@
"""Splunk collector — storage, license consumption and index sizes."""
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", 8089)
session = sdk.http_session(config)
token = str(config.get("token", "")).strip()
if token:
session.headers["Authorization"] = f"Bearer {token}"
elif config.get("username") and config.get("password"):
session.auth = (config.get("username"), config.get("password"))
else:
raise sdk.ModuleError("Configure a Splunk bearer token or username/password")
return base, session
def _entries(payload: Any):
if isinstance(payload, dict):
return payload.get("entry") or []
return []
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 Splunk endpoint"}
config = ctx["config"]
base, session = _session(config)
cluster = config.get("cluster_name") or "Splunk"
metrics: Dict[str, float] = {}
capacity: Dict[str, float] = {}
meta: Dict[str, Any] = {}
notes = []
try:
info = sdk.get_json(session, f"{base}/services/server/info?output_mode=json")
content = (_entries(info) or [{}])[0].get("content", {})
hostname = content.get("host") or config.get("host")
meta["version"] = content.get("version", "")
meta["server_name"] = hostname
cores = content.get("numberOfCores") or content.get("numberOfVirtualCores")
if cores:
capacity["cpu_cores"] = float(cores)
memory_mb = content.get("physicalMemoryMB") or content.get("memory")
if memory_mb:
capacity["mem_gb"] = round(float(memory_mb) / 1024, 1)
except Exception as exc:
raise sdk.ModuleError(f"Splunk server info failed: {exc}")
hostname = meta.get("server_name") or "splunk"
try:
partitions = sdk.get_json(session, f"{base}/services/server/status/partitions-space?output_mode=json")
chosen = None
for entry in _entries(partitions):
content = entry.get("content", {})
if str(content.get("mount_point")) in ("/", "/opt", "/opt/splunk"):
chosen = content
if content.get("mount_point") == "/":
break
if chosen is None:
entries = _entries(partitions)
chosen = entries[0].get("content", {}) if entries else None
if chosen:
total_mb = float(chosen.get("capacity") or 0)
free_mb = float(chosen.get("available") or 0)
if total_mb > 0:
used_mb = float(chosen.get("used") or (total_mb - free_mb))
metrics["storage_pct"] = sdk.percent(used_mb, total_mb)
metrics["storage_used_gb"] = round(used_mb / 1024, 1)
metrics["storage_total_gb"] = round(total_mb / 1024, 1)
capacity["storage_gb"] = round(total_mb / 1024, 1)
meta["mount"] = chosen.get("mount_point")
except Exception as exc:
notes.append(f"partition data unavailable ({exc})")
try:
usage = sdk.get_json(session, f"{base}/services/license/usage?output_mode=json")
used = 0.0
quota = 0.0
for entry in _entries(usage):
content = entry.get("content", {})
try:
used += float(content.get("used") or 0)
quota += float(content.get("quota") or 0)
except (TypeError, ValueError):
continue
if quota > 0:
metrics["license_pct"] = sdk.percent(used, quota)
meta["license_quota_gb"] = round(quota / 1024 ** 3, 1)
except Exception as exc:
notes.append(f"license data unavailable ({exc})")
try:
indexes = sdk.get_json(session, f"{base}/services/data/indexes?output_mode=json")
index_mb = 0.0
for entry in _entries(indexes):
try:
index_mb += float(entry.get("content", {}).get("currentDBSizeMB") or 0)
except (TypeError, ValueError):
continue
if index_mb:
metrics["index_gb"] = round(index_mb / 1024, 1)
except Exception as exc:
notes.append(f"index data unavailable ({exc})")
asset = sdk.add_asset(
external_id=hostname,
name=hostname,
type_="appliance",
metrics=metrics,
capacity=capacity,
cluster=cluster,
tags=["splunk"],
meta=meta,
)
note = f"Collected Splunk telemetry from {base}"
if notes:
note += " — " + "; ".join(notes)
return {"assets": [asset], "notes": note}
def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]:
if sdk.use_demo(ctx, ["host"]):
return {"ok": True, "message": "Demo mode — no Splunk endpoint contacted."}
base, session = _session(ctx["config"])
info = sdk.get_json(session, f"{base}/services/server/info?output_mode=json")
content = (_entries(info) or [{}])[0].get("content", {})
return {
"ok": True,
"message": f"Connected to Splunk {content.get('version', '')} at {base}",
"details": {"version": content.get("version"), "host": content.get("host")},
}
+22
View File
@@ -0,0 +1,22 @@
{
"id": "truenas",
"name": "TrueNAS / NAS",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "storage",
"icon": "truenas",
"interval_seconds": 600,
"enabled_by_default": true,
"description": "Pools, capacity and system load from the TrueNAS SCALE REST API. Works with TrueNAS 24.04+.",
"capabilities": ["assets", "metrics", "capacity"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true},
{"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "truenas.lab.local"},
{"key": "port", "label": "API port", "type": "number", "default": 443},
{"key": "api_key", "label": "API key", "type": "password", "default": ""},
{"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false},
{"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Storage"}
]
}
+103
View File
@@ -0,0 +1,103 @@
"""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")},
}
+23
View File
@@ -0,0 +1,23 @@
{
"id": "windows",
"name": "Windows hosts (WinRM)",
"version": "1.0.0",
"api_version": 1,
"vendor": "Headroom",
"category": "os",
"icon": "windows",
"interval_seconds": 300,
"enabled_by_default": true,
"description": "Windows Server CPU, memory, disk and uptime via WinRM/PowerShell. Requires the optional pywinrm package.",
"capabilities": ["assets", "metrics", "capacity"],
"docs": "docs/MODULE_SDK.md",
"settings_schema": [
{"key": "demo", "label": "Demo mode", "type": "boolean", "default": true},
{"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "win-01.lab.local"},
{"key": "port", "label": "WinRM port", "type": "number", "default": 5985},
{"key": "username", "label": "Username", "type": "text", "default": "", "placeholder": "LAB\\headroom"},
{"key": "password", "label": "Password", "type": "password", "default": ""},
{"key": "transport", "label": "Transport", "type": "select", "default": "ntlm", "options": ["ntlm", "basic", "credssp"]},
{"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Windows"}
]
}
+117
View File
@@ -0,0 +1,117 @@
"""Windows Server collector over WinRM (optional pywinrm dependency)."""
from __future__ import annotations
import json
from typing import Any, Dict
from app import sdk
PS_SCRIPT = r"""
$ErrorActionPreference = 'Stop'
$os = Get-CimInstance Win32_OperatingSystem
$cs = Get-CimInstance Win32_ComputerSystem
$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average
$disks = @(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3")
$size = ($disks | Measure-Object -Property Size -Sum).Sum
$free = ($disks | Measure-Object -Property FreeSpace -Sum).Sum
$memTotal = [double]$os.TotalVisibleMemorySize * 1KB
$memFree = [double]$os.FreePhysicalMemory * 1KB
$up = ((Get-Date) - $os.LastBootUpTime).TotalDays
[pscustomobject]@{
name = $env:COMPUTERNAME
cpu_pct = [math]::Round([double]$cpu, 1)
mem_pct = [math]::Round((($memTotal - $memFree) / $memTotal) * 100, 1)
storage_pct = if ($size -gt 0) { [math]::Round((($size - $free) / $size) * 100, 1) } else { 0 }
storage_total_gb = [math]::Round($size / 1GB, 1)
storage_used_gb = [math]::Round(($size - $free) / 1GB, 1)
uptime_days = [math]::Round($up, 1)
cores = [int]$cs.NumberOfLogicalProcessors
mem_total_gb = [math]::Round($memTotal / 1GB, 1)
os = $os.Caption
version = $os.Version
} | ConvertTo-Json -Compress
"""
def _session(config: Dict[str, Any]):
try:
import winrm
except ImportError:
raise sdk.ModuleError(
"pywinrm is not installed. Run: .venv/bin/pip install pywinrm (then restart Headroom)"
)
host = str(config.get("host", "")).strip()
if not host or not config.get("username") or not config.get("password"):
raise sdk.ModuleError("Configure host, username and password for WinRM")
port = sdk.free_port(config.get("port"), 5985)
scheme = "https" if port == 5986 else "http"
transport = str(config.get("transport") or "ntlm")
try:
return winrm.Session(
f"{scheme}://{host}:{port}/wsman",
auth=(str(config.get("username")), str(config.get("password"))),
transport=transport,
server_cert_validation="ignore",
)
except Exception as exc:
raise sdk.ModuleError(f"WinRM session failed: {exc}")
def _run(session, script: str):
result = session.run_ps(script)
stdout = result.std_out.decode(errors="replace") if isinstance(result.std_out, bytes) else str(result.std_out)
stderr = result.std_err.decode(errors="replace") if isinstance(result.std_err, bytes) else str(result.std_err)
if result.status_code != 0:
raise sdk.ModuleError(f"PowerShell failed: {(stderr or stdout).strip()[:500]}")
return stdout.strip()
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 WinRM endpoint"}
config = ctx["config"]
session = _session(config)
try:
raw = _run(session, PS_SCRIPT)
data = json.loads(raw)
if isinstance(data, list):
data = data[0]
except json.JSONDecodeError:
raise sdk.ModuleError("Could not parse PowerShell output as JSON")
except Exception as exc:
if isinstance(exc, sdk.ModuleError):
raise
raise sdk.ModuleError(f"WinRM collection failed: {exc}")
name = str(data.get("name") or config.get("host"))
metrics = {
key: float(data[key])
for key in ("cpu_pct", "mem_pct", "storage_pct", "storage_used_gb", "storage_total_gb", "uptime_days")
if isinstance(data.get(key), (int, float))
}
asset = sdk.add_asset(
external_id=name,
name=name,
type_="server",
metrics=metrics,
capacity={
"cpu_cores": float(data.get("cores") or 0),
"mem_gb": float(data.get("mem_total_gb") or 0),
"storage_gb": float(data.get("storage_total_gb") or 0),
},
cluster=config.get("cluster_name") or "Windows",
tags=["windows"],
meta={"os": str(data.get("os", "")), "version": str(data.get("version", ""))},
)
return {"assets": [asset], "notes": f"Collected Windows telemetry from {name}"}
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 WinRM endpoint contacted."}
session = _session(ctx["config"])
try:
output = _run(session, "hostname")
except Exception as exc:
raise sdk.ModuleError(f"WinRM test failed: {exc}")
return {"ok": True, "message": f"WinRM connection OK — {output.strip()[:120]}"}