Files
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

83 lines
2.9 KiB
Python

"""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)."}