- 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
141 lines
4.2 KiB
Python
141 lines
4.2 KiB
Python
"""Helpers available to collector modules (stable module API v1).
|
|
|
|
Modules run in a separate, time-limited process. They receive a ``ctx`` dict:
|
|
|
|
{
|
|
"config": {...module settings...},
|
|
"demo": true|false,
|
|
"now": "2026-01-01T12:00:00+00:00",
|
|
"module": {"id": "...", "name": "...", "version": "..."},
|
|
"state": {...previous module state...}
|
|
}
|
|
|
|
and return::
|
|
|
|
{"assets": [ {external_id, name, type, cluster, site, tags, capacity, metrics, meta} ],
|
|
"state": {...optional...}, "notes": "optional"}
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
import requests
|
|
|
|
from .demo_fleet import snapshot as _demo_snapshot
|
|
|
|
|
|
class ModuleError(RuntimeError):
|
|
"""Raise with a human-readable message when a collector cannot continue."""
|
|
|
|
|
|
def demo_assets(ctx: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
now = int(time.time())
|
|
module = ctx.get("module") or {}
|
|
type_id = module.get("module_type") or module.get("base_name") or module.get("id")
|
|
instance_id = module.get("instance_id") or module.get("id")
|
|
config = ctx.get("config") or {}
|
|
assets = _demo_snapshot(type_id, now)
|
|
instance_label = str(config.get("cluster_name") or module.get("name") or "").strip()
|
|
if instance_label:
|
|
for asset in assets:
|
|
asset["cluster"] = instance_label
|
|
if instance_id and type_id and instance_id != type_id and instance_label:
|
|
for asset in assets:
|
|
asset["name"] = f"{asset.get('name')} · {instance_label}"
|
|
elif instance_id and type_id and instance_id != type_id:
|
|
label = instance_label or module.get("name") or instance_id
|
|
for asset in assets:
|
|
asset["name"] = f"{asset.get('name')} · {label}"
|
|
return assets
|
|
|
|
|
|
def use_demo(ctx: Dict[str, Any], required: Optional[List[str]] = None) -> bool:
|
|
config = ctx.get("config", {})
|
|
if bool(config.get("demo", True)):
|
|
return True
|
|
missing = [key for key in (required or []) if not str(config.get(key, "")).strip()]
|
|
return bool(missing)
|
|
|
|
|
|
def http_session(config: Dict[str, Any]) -> requests.Session:
|
|
session = requests.Session()
|
|
session.headers.update(
|
|
{
|
|
"User-Agent": "Headroom-Collector/1.0",
|
|
"Accept": "application/json",
|
|
}
|
|
)
|
|
if config.get("verify_tls") is False:
|
|
session.verify = False
|
|
try:
|
|
import urllib3
|
|
|
|
urllib3.disable_warnings()
|
|
except Exception:
|
|
pass
|
|
return session
|
|
|
|
|
|
def get_json(
|
|
session: requests.Session,
|
|
url: str,
|
|
timeout: int = 20,
|
|
**kwargs: Any,
|
|
) -> Any:
|
|
response = session.get(url, timeout=timeout, **kwargs)
|
|
response.raise_for_status()
|
|
if not response.content:
|
|
return {}
|
|
return response.json()
|
|
|
|
|
|
def free_port(value: Any, default: int) -> int:
|
|
try:
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def base_url(config: Dict[str, Any], scheme: str = "https", default_port: int = 443) -> str:
|
|
host = str(config.get("host", "")).strip().rstrip("/")
|
|
if host.startswith("http://") or host.startswith("https://"):
|
|
return host.rstrip("/")
|
|
port = free_port(config.get("port"), default_port)
|
|
suffix = "" if (scheme == "https" and port == 443) or (scheme == "http" and port == 80) else f":{port}"
|
|
return f"{scheme}://{host}{suffix}"
|
|
|
|
|
|
def add_asset(
|
|
external_id: str,
|
|
name: str,
|
|
type_: str,
|
|
metrics: Dict[str, Any],
|
|
capacity: Optional[Dict[str, Any]] = None,
|
|
cluster: str = "",
|
|
site: str = "",
|
|
tags: Optional[List[str]] = None,
|
|
meta: Optional[Dict[str, Any]] = None,
|
|
) -> Dict[str, Any]:
|
|
return {
|
|
"external_id": str(external_id),
|
|
"name": str(name),
|
|
"type": type_,
|
|
"cluster": cluster,
|
|
"site": site,
|
|
"tags": tags or [],
|
|
"capacity": capacity or {},
|
|
"metrics": {
|
|
key: float(value)
|
|
for key, value in metrics.items()
|
|
if isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
},
|
|
"meta": meta or {},
|
|
}
|
|
|
|
|
|
def percent(used: float, total: float) -> float:
|
|
if not total:
|
|
return 0.0
|
|
return max(0.0, min(100.0, used / total * 100.0))
|