Files
headroom/app/runner.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

93 lines
3.1 KiB
Python

"""Collector subprocess entrypoint.
Reads a JSON payload, imports ``module.py`` from the module directory, executes
the collector and prints exactly one machine-readable result line on stdout.
Module prints are redirected to stderr so they cannot corrupt the protocol.
"""
from __future__ import annotations
import importlib.util
import io
import json
import sys
import time
import traceback
import warnings
from pathlib import Path
MARKER = "HEADROOM_RESULT:"
MAX_LOG_LINES = 200
warnings.filterwarnings("ignore")
def main() -> None:
if len(sys.argv) < 3:
print("usage: python -m app.runner <module_dir> <payload.json>", file=sys.stderr)
raise SystemExit(2)
module_dir = Path(sys.argv[1])
payload = json.loads(Path(sys.argv[2]).read_text())
logs = []
def log(message) -> None:
stamp = time.strftime("%H:%M:%S")
logs.append(f"{stamp} {str(message)[:600]}")
if len(logs) > MAX_LOG_LINES:
del logs[0]
real_stdout = sys.stdout
sys.stdout = sys.stderr
result = {}
try:
module_path = module_dir / "module.py"
if not module_path.exists():
raise RuntimeError("module.py not found")
spec = importlib.util.spec_from_file_location("headroom_collector", str(module_path))
if spec is None or spec.loader is None:
raise RuntimeError("could not load module.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
ctx = {
"config": payload.get("config", {}),
"demo": bool(payload.get("demo", True)),
"now": payload.get("now", ""),
"module": payload.get("module", {}),
"state": payload.get("state", {}),
"log": log,
}
mode = payload.get("mode", "collect")
if mode == "test":
if hasattr(module, "test_connection"):
result = {"test": module.test_connection(ctx)}
else:
collected = module.collect(ctx)
result = {
"assets": collected.get("assets", []),
"notes": collected.get("notes", ""),
"test": {
"ok": True,
"message": f"Collector returned {len(collected.get('assets', []))} asset(s) (no dedicated test implemented).",
},
}
else:
if not hasattr(module, "collect"):
raise RuntimeError("module.py must define collect(ctx)")
result = module.collect(ctx) or {}
if not isinstance(result, dict):
raise RuntimeError("collector must return a dict")
except Exception as exc: # reported back to the parent process
result = {
"error": f"{type(exc).__name__}: {exc}",
"traceback": traceback.format_exc()[-5000:],
}
finally:
sys.stdout = real_stdout
result["logs"] = logs + ([result["traceback"]] if result.get("traceback") else [])
result.pop("traceback", None)
encoded = json.dumps(result, default=str, separators=(",", ":"))
print(MARKER + encoded)
if __name__ == "__main__":
main()