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
+3
View File
@@ -0,0 +1,3 @@
"""Headroom — a modular capacity management framework for homelabs."""
__version__ = "1.0.0"
+151
View File
@@ -0,0 +1,151 @@
"""Authentication: local users, signed session cookies and API keys."""
from __future__ import annotations
import time
from typing import Any, Dict, Optional
from fastapi import Depends, HTTPException, Request, Response
from . import db, licensing
from .util import now_iso
from .security import (
SESSION_TTL,
api_key_prefix,
hash_api_key,
sign_session,
verify_password,
verify_session,
)
COOKIE_NAME = "hr_session"
LOGIN_WINDOW = 300
LOGIN_LIMIT = 15
_ATTEMPTS: Dict[str, list] = {}
def _client_ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
def login(username: str, password: str, request: Request, response: Response) -> Dict[str, Any]:
ip = _client_ip(request)
now = time.time()
attempts = [stamp for stamp in _ATTEMPTS.get(ip, []) if now - stamp < LOGIN_WINDOW]
if len(attempts) >= LOGIN_LIMIT:
raise HTTPException(status_code=429, detail="Too many login attempts. Wait a few minutes.")
row = db.query_one("SELECT * FROM users WHERE username=?", (username.strip(),))
if not row or not verify_password(password, row["password_hash"]):
attempts.append(now)
_ATTEMPTS[ip] = attempts
raise HTTPException(status_code=401, detail="Invalid username or password")
_ATTEMPTS.pop(ip, None)
token = sign_session(int(row["id"]))
response.set_cookie(
COOKIE_NAME,
token,
max_age=SESSION_TTL,
httponly=True,
samesite="lax",
path="/",
)
db.audit(row["username"], "login", target=ip)
return {"id": row["id"], "username": row["username"], "role": row["role"]}
def logout(response: Response) -> None:
response.delete_cookie(COOKIE_NAME, path="/")
def _api_key_user(request: Request) -> Optional[Dict[str, Any]]:
candidate = request.headers.get("x-api-key", "")
authorization = request.headers.get("authorization", "")
if not candidate and authorization.lower().startswith("bearer "):
token = authorization[7:].strip()
if token.startswith("hr_"):
candidate = token
if not candidate.startswith("hr_"):
return None
row = db.query_one("SELECT * FROM api_keys WHERE key_hash=?", (hash_api_key(candidate),))
if not row:
return None
db.execute("UPDATE api_keys SET last_used=? WHERE id=?", (now_iso(), row["id"]))
return {
"id": 0,
"username": f"api:{row['name']}",
"role": row["role"],
"auth": "api_key",
"api_key_id": row["id"],
}
def current_user(request: Request) -> Dict[str, Any]:
api_user = _api_key_user(request)
if api_user:
return api_user
token = request.cookies.get(COOKIE_NAME, "")
if not token:
authorization = request.headers.get("authorization", "")
if authorization.lower().startswith("bearer "):
token = authorization[7:].strip()
payload = verify_session(token) if token else None
if not payload:
raise HTTPException(status_code=401, detail="Authentication required")
row = db.query_one("SELECT * FROM users WHERE id=?", (payload["uid"],))
if not row:
raise HTTPException(status_code=401, detail="User no longer exists")
return {"id": row["id"], "username": row["username"], "role": row["role"], "auth": "session"}
def require_admin(user: Dict[str, Any] = Depends(current_user)) -> Dict[str, Any]:
if user.get("role") != "admin":
raise HTTPException(status_code=403, detail="Administrator role required")
return user
def require_operator(user: Dict[str, Any] = Depends(current_user)) -> Dict[str, Any]:
if user.get("role") not in ("admin", "operator"):
raise HTTPException(status_code=403, detail="Operator role required")
return user
def require_feature(feature: str, role: str = "viewer"):
def dependency(user: Dict[str, Any] = Depends(current_user)) -> Dict[str, Any]:
if role == "admin" and user.get("role") != "admin":
raise HTTPException(status_code=403, detail="Administrator role required")
if role == "operator" and user.get("role") not in ("admin", "operator"):
raise HTTPException(status_code=403, detail="Operator role required")
if not licensing.has_feature(feature):
raise HTTPException(
status_code=402,
detail={
"code": "upgrade_required",
"feature": feature,
"message": "This capability requires Headroom Enterprise. Start a trial or activate a license.",
},
)
return user
return dependency
def account(request: Request) -> Dict[str, Any]:
user = current_user(request)
status = licensing.status()
return {
"user": user,
"edition": status,
"site_name": db.get_setting("site_name", "Homelab HQ"),
"version": "1.0.0",
}
def change_password(user: Dict[str, Any], current_password: str, new_password: str) -> None:
if len(new_password) < 8:
raise HTTPException(status_code=400, detail="New password must be at least 8 characters")
row = db.query_one("SELECT * FROM users WHERE id=?", (user["id"],))
if not row or not verify_password(current_password, row["password_hash"]):
raise HTTPException(status_code=400, detail="Current password is incorrect")
from .security import hash_password
db.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(new_password), user["id"]))
db.audit(user["username"], "password.change", target=user["username"])
+935
View File
@@ -0,0 +1,935 @@
"""Capacity analytics: latest state, trends, forecasts, groups and what-if."""
from __future__ import annotations
import json
import math
import time
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Iterable, List, Optional, Tuple
from . import config, db, licensing
from .metrics import (
METRIC_CATALOG,
utilization_for_type,
primary_for_type,
status_for_pressure,
status_label,
metric_meta,
)
from .util import clamp, epoch_from_iso, iso_from_epoch, now_iso, utcnow
LATEST_WINDOW = 72 * 3600
STALE_AFTER = 1800
RESOURCES = ("storage", "cpu", "mem")
_MANIFEST_CACHE: Dict[str, Any] = {"at": 0.0, "names": {}}
# ---------------------------------------------------------------------------
# Loading
# ---------------------------------------------------------------------------
def module_names() -> Dict[str, Dict[str, str]]:
if time.time() - _MANIFEST_CACHE["at"] < 5:
return dict(_MANIFEST_CACHE["names"])
names: Dict[str, Dict[str, str]] = {}
try:
from . import db as _db
for row in _db.query("SELECT id, module_type, display_name FROM modules"):
mtype = row["module_type"] or row["id"]
manifest = None
path = config.MODULES_DIR / mtype / "manifest.json"
if path.exists():
try:
manifest = json.loads(path.read_text())
except Exception:
manifest = None
base_name = (manifest.get("name") if manifest else None) or mtype
display = row["display_name"] or base_name
names[str(row["id"])] = {
"name": display,
"type_name": base_name,
"module_type": mtype,
"category": str((manifest.get("category") if manifest else "") or ""),
}
except Exception:
pass
if not names:
for path in config.MODULES_DIR.glob("*/manifest.json"):
try:
manifest = json.loads(path.read_text())
names[str(manifest.get("id"))] = {
"name": str(manifest.get("name", manifest.get("id"))),
"category": str(manifest.get("category", "")),
}
except (OSError, ValueError):
continue
_MANIFEST_CACHE["names"] = names
_MANIFEST_CACHE["at"] = time.time()
return dict(names)
def row_asset(row: Any) -> Dict[str, Any]:
names = module_names()
module_id = row["module_id"]
capacity = json.loads(row["capacity"] or "{}")
asset = {
"id": row["id"],
"module_id": module_id,
"module_name": names.get(module_id, {}).get("name", module_id),
"external_id": row["external_id"],
"name": row["name"],
"type": row["type"],
"cluster": row["cluster"] or "",
"site": row["site"] or "",
"tags": json.loads(row["tags"] or "[]"),
"meta": json.loads(row["meta"] or "{}"),
"capacity": capacity,
"first_seen": row["first_seen"],
"last_seen": row["last_seen"],
"active": bool(row["active"]),
}
return asset
def list_assets(
include_inactive: bool = False,
module_id: Optional[str] = None,
type_filter: Optional[str] = None,
search: Optional[str] = None,
) -> List[Dict[str, Any]]:
sql = "SELECT * FROM assets"
clauses = []
params: List[Any] = []
if not include_inactive:
clauses.append("active=1")
if module_id:
clauses.append("module_id=?")
params.append(module_id)
if type_filter:
clauses.append("type=?")
params.append(type_filter)
if clauses:
sql += " WHERE " + " AND ".join(clauses)
sql += " ORDER BY name COLLATE NOCASE"
assets = [row_asset(row) for row in db.query(sql, params)]
if search:
needle = search.lower()
assets = [
a
for a in assets
if needle in a["name"].lower()
or needle in a["cluster"].lower()
or needle in a["module_name"].lower()
or any(needle in tag.lower() for tag in a["tags"])
]
return assets
def latest_values(cutoff: int = LATEST_WINDOW) -> Dict[str, Dict[str, float]]:
start = int(time.time()) - cutoff
rows = db.query(
"SELECT s.asset_id, s.metric, s.value, s.ts FROM samples s "
"JOIN (SELECT asset_id, metric, MAX(ts) AS mts FROM samples WHERE ts>=? "
" GROUP BY asset_id, metric) m "
" ON s.asset_id=m.asset_id AND s.metric=m.metric AND s.ts=m.mts",
(start,),
)
out: Dict[str, Dict[str, float]] = {}
for row in rows:
out.setdefault(row["asset_id"], {})[row["metric"]] = float(row["value"])
return out
def series(asset_id: str, metric: str, days: int = 7, max_points: int = 200) -> List[Dict[str, Any]]:
start = int(time.time()) - days * 86400
bucket = _bucket_for(days)
rows = db.query(
"SELECT (ts/?)*? AS t, AVG(value) AS v FROM samples "
"WHERE asset_id=? AND metric=? AND ts>=? GROUP BY t ORDER BY t",
(bucket, bucket, asset_id, metric, start),
)
points = [{"t": int(row["t"]) * 1000, "v": round(float(row["v"]), 2)} for row in rows]
if len(points) > max_points:
stride = int(math.ceil(len(points) / max_points))
points = points[::stride]
return points
def _bucket_for(days: int) -> int:
if days <= 2:
return 900
if days <= 7:
return 3600
if days <= 31:
return 21600
if days <= 120:
return 86400
return 604800
def slope_per_day(
asset_id: str,
metric: str,
days: int = 7,
cache: Optional[Dict[Tuple[str, str], float]] = None,
) -> float:
key = (asset_id, metric)
if cache is not None and key in cache:
return cache[key]
start = int(time.time()) - days * 86400
rows = db.query(
"SELECT (ts/3600)*3600 AS t, AVG(value) AS v FROM samples "
"WHERE asset_id=? AND metric=? AND ts>=? GROUP BY t ORDER BY t",
(asset_id, metric, start),
)
slope = 0.0
if len(rows) >= 6:
xs = [0.0]
ys = [float(rows[0]["v"])]
t0 = float(rows[0]["t"])
for row in rows[1:]:
xs.append((float(row["t"]) - t0) / 86400.0)
ys.append(float(row["v"]))
x_mean = sum(xs) / len(xs)
y_mean = sum(ys) / len(ys)
denom = sum((x - x_mean) ** 2 for x in xs)
if denom > 0:
slope = sum((x - x_mean) * (y - y_mean) for x, y in zip(xs, ys)) / denom
if cache is not None:
cache[key] = slope
return slope
# ---------------------------------------------------------------------------
# Analysis
# ---------------------------------------------------------------------------
def analyze(
asset: Dict[str, Any],
values: Dict[str, float],
slopes: Optional[Dict[Tuple[str, str], float]] = None,
) -> Dict[str, Any]:
util_keys = [m for m in utilization_for_type(asset["type"]) if values.get(m) is not None]
if not util_keys:
util_keys = [m for m in ("storage_pct", "cpu_pct", "mem_pct", "load_pct") if values.get(m) is not None]
primary = primary_for_type(asset["type"])
if primary not in values and util_keys:
primary = max(util_keys, key=lambda key: values[key])
util = max((values[key] for key in util_keys), default=None)
slope = slope_per_day(asset["id"], primary, cache=slopes) if util_keys else 0.0
pressure = None
if util is not None:
pressure = int(round(clamp(util + min(12.0, max(0.0, slope * 15.0)), 0, 100)))
eta: Optional[float] = None
if util is not None and slope > 0.03 and util < 100:
eta = round((100.0 - util) / slope, 1)
if eta > 3650:
eta = None
trend = "stable"
if slope > 0.15:
trend = "rising"
elif slope < -0.15:
trend = "falling"
last_seen_epoch = epoch_from_iso(asset.get("last_seen"))
stale = bool(last_seen_epoch and time.time() - last_seen_epoch > STALE_AFTER)
result = {
"primary_metric": primary,
"util": round(util, 1) if util is not None else None,
"pressure": pressure,
"status": status_for_pressure(pressure if pressure is not None else 0) if pressure is not None else "unknown",
"status_label": status_label(pressure if pressure is not None else 0) if pressure is not None else "No telemetry",
"trend": trend,
"slope_per_day": round(slope, 3),
"days_to_full": eta,
"eta_date": (utcnow() + timedelta(days=eta)).date().isoformat() if eta is not None else None,
"headroom_pct": round(100.0 - util, 1) if util is not None else None,
"stale": stale,
}
return result
def summary(asset: Dict[str, Any], values: Dict[str, float], analysis: Dict[str, Any]) -> Dict[str, Any]:
out = dict(asset)
out.update(analysis)
out.pop("meta", None)
out["metrics"] = values
out["type_label"] = str(asset.get("type", "")).replace("_", " ").title()
return out
def _analyses(assets: Iterable[Dict[str, Any]], latest: Dict[str, Dict[str, float]]):
slopes: Dict[Tuple[str, str], float] = {}
result = {}
for asset in assets:
values = latest.get(asset["id"], {})
result[asset["id"]] = analyze(asset, values, slopes)
return result, slopes
def _maybe_float(value: Any) -> Optional[float]:
try:
number = float(value)
return number if math.isfinite(number) else None
except (TypeError, ValueError):
return None
def resource_totals(
assets: Iterable[Dict[str, Any]],
latest: Dict[str, Dict[str, float]],
slopes: Dict[Tuple[str, str], float],
) -> Dict[str, Dict[str, Any]]:
totals = {
"storage": {"total": 0.0, "used": 0.0, "growth": 0.0},
"cpu": {"total": 0.0, "used": 0.0, "growth": 0.0},
"mem": {"total": 0.0, "used": 0.0, "growth": 0.0},
}
for asset in assets:
values = latest.get(asset["id"], {})
capacity = asset.get("capacity", {})
if values.get("storage_pct") is not None:
total = _maybe_float(capacity.get("storage_gb"))
if total:
totals["storage"]["total"] += total
totals["storage"]["used"] += total * values["storage_pct"] / 100.0
slope = slope_per_day(asset["id"], "storage_pct", cache=slopes)
totals["storage"]["growth"] += max(0.0, total * slope / 100.0)
if values.get("cpu_pct") is not None:
cores = _maybe_float(capacity.get("cpu_cores"))
if cores:
totals["cpu"]["total"] += cores
totals["cpu"]["used"] += cores * values["cpu_pct"] / 100.0
slope = slope_per_day(asset["id"], "cpu_pct", cache=slopes)
totals["cpu"]["growth"] += max(0.0, cores * slope / 100.0)
if values.get("mem_pct") is not None:
mem = _maybe_float(capacity.get("mem_gb"))
if mem:
totals["mem"]["total"] += mem
totals["mem"]["used"] += mem * values["mem_pct"] / 100.0
slope = slope_per_day(asset["id"], "mem_pct", cache=slopes)
totals["mem"]["growth"] += max(0.0, mem * slope / 100.0)
out: Dict[str, Dict[str, Any]] = {}
for resource, data in totals.items():
total = data["total"]
used = data["used"]
growth = data["growth"]
util = round(used / total * 100, 1) if total else None
eta = round((total - used) / growth, 1) if growth > 0.001 and total > used else None
out[resource] = {
"total": round(total, 1),
"used": round(used, 1),
"free": round(max(0.0, total - used), 1),
"util": util,
"growth_per_day": round(growth, 2),
"days_to_full": eta,
"headroom_pct": round(100 - util, 1) if util is not None else None,
}
return out
def recommendation(
asset: Dict[str, Any],
analysis: Dict[str, Any],
values: Dict[str, float],
) -> Dict[str, Any]:
name = asset["name"]
if analysis.get("stale"):
return {
"level": "info",
"title": "Telemetry is stale",
"detail": f"The last sample from {asset['module_name']} is older than 30 minutes. Check the module connection.",
}
pressure = analysis.get("pressure")
util = analysis.get("util")
if util is None:
return {
"level": "info",
"title": "No utilization metrics yet",
"detail": "The module reported the asset without a known utilization metric. Inspect the module logs and its metric mapping.",
}
eta = analysis.get("days_to_full")
primary = analysis.get("primary_metric", "cpu_pct")
slope = analysis.get("slope_per_day", 0.0)
capability = asset.get("capacity", {})
if eta is not None and eta <= 180:
total_gb = _maybe_float(capability.get("storage_gb"))
if primary == "storage_pct" and total_gb:
free_gb = total_gb * (100 - util) / 100
growth_gb = max(0.1, total_gb * slope / 100)
needed = max(0.0, (total_gb * util / 100 + growth_gb * 180) / 0.85 - total_gb)
reclaim = max(0.0, total_gb * util / 100 - total_gb * 0.85)
detail = (
f"{name} is at {util:.0f}% with {free_gb:.0f} GB free. At {slope:+.2f} pp/day "
f"({growth_gb:.1f} GB/day) it reaches 100% around {analysis.get('eta_date')}."
)
action = (
f"Add about {math.ceil(needed / 100) * 100:.0f} GB for six months at 85% target, "
f"or reclaim ~{reclaim:.0f} GB now."
)
return {"level": "critical" if eta <= 45 else "warning", "title": f"Storage runway: {int(eta)} days", "detail": detail, "action": action}
if primary in ("cpu_pct", "mem_pct"):
unit = "cores" if primary == "cpu_pct" else "GB RAM"
total = _maybe_float(capability.get("cpu_cores" if primary == "cpu_pct" else "mem_gb")) or 0
add = max(1, math.ceil(total * (85 - util) / 100)) if util else 0
return {
"level": "critical" if eta <= 45 else "warning",
"title": f"{'CPU' if primary == 'cpu_pct' else 'Memory'} saturation in {int(eta)} days",
"detail": f"{name} is at {util:.0f}% and growing {slope:+.2f} pp/day.",
"action": f"Add roughly {add} {unit} or rebalance guests before {analysis.get('eta_date')}.",
}
return {
"level": "warning" if pressure and pressure >= 80 else "info",
"title": f"{metric_meta(primary)['label']} trend needs attention",
"detail": f"{name} is at {util:.0f}%, projected to reach 100% in {int(eta)} days.",
"action": "Review the growth driver and plan additional capacity.",
}
if pressure is not None and pressure >= 85:
return {
"level": "warning",
"title": "Limited headroom",
"detail": f"{name} is running at {util:.0f}% sustained utilization with a {analysis.get('headroom_pct', 0):.0f}% buffer.",
"action": "Set a growth assumption in the simulator and validate the next capacity step.",
}
if analysis.get("trend") == "rising" and slope > 0.4:
return {
"level": "info",
"title": "Fastest-growing asset",
"detail": f"Growth is {slope:+.2f} pp/day, but there is still {analysis.get('headroom_pct', 0):.0f}% headroom.",
"action": "No action needed today — keep it on the monthly capacity review.",
}
return {
"level": "healthy",
"title": "Healthy headroom",
"detail": f"{name} has {analysis.get('headroom_pct', 0):.0f}% headroom and a stable trend.",
"action": "No action required.",
}
# ---------------------------------------------------------------------------
# Aggregations
# ---------------------------------------------------------------------------
def groups(days: int = 7) -> List[Dict[str, Any]]:
assets = list_assets()
latest = latest_values()
analyses, slopes = _analyses(assets, latest)
buckets: Dict[str, List[Dict[str, Any]]] = {}
for asset in assets:
key = asset["cluster"] or asset["module_name"]
buckets.setdefault(key, []).append(asset)
out = []
for key, members in buckets.items():
values = {a["id"]: latest.get(a["id"], {}) for a in members}
analyses_local = [summary(a, values[a["id"]], analyses[a["id"]]) for a in members]
resources = resource_totals(members, latest, slopes)
pressure = max((s["pressure"] or 0 for s in analyses_local), default=0)
util = max((s["util"] or 0 for s in analyses_local), default=0)
etas = [s["days_to_full"] for s in analyses_local if s.get("days_to_full")]
storage = resources["storage"]
out.append(
{
"key": key,
"name": key,
"module_id": members[0]["module_id"],
"module_name": members[0]["module_name"],
"site": members[0]["site"],
"asset_count": len(members),
"types": sorted({a["type"] for a in members}),
"resources": resources,
"pressure": pressure,
"util": round(util, 1),
"status": status_for_pressure(pressure),
"status_label": status_label(pressure),
"days_to_full": storage.get("days_to_full") or (min(etas) if etas else None),
"assets": [
{
"id": s["id"],
"name": s["name"],
"type": s["type"],
"pressure": s["pressure"],
"util": s["util"],
"status": s["status"],
"days_to_full": s["days_to_full"],
"primary_metric": s["primary_metric"],
}
for s in sorted(analyses_local, key=lambda item: item["pressure"] or 0, reverse=True)[:8]
],
}
)
out.sort(key=lambda group: group["pressure"], reverse=True)
return out
def fleet_timeline(days: int = 7) -> Dict[str, List[Dict[str, Any]]]:
bucket = _bucket_for(days)
start = int(time.time()) - days * 86400
rows = db.query(
"SELECT s.metric, (s.ts/?)*? AS t, AVG(s.value) AS v FROM samples s "
"JOIN assets a ON a.id=s.asset_id AND a.active=1 "
"WHERE s.metric IN ('cpu_pct','mem_pct','storage_pct') AND s.ts>=? "
"GROUP BY s.metric, t ORDER BY t",
(bucket, bucket, start),
)
out: Dict[str, List[Dict[str, Any]]] = {"cpu_pct": [], "mem_pct": [], "storage_pct": []}
for row in rows:
out.setdefault(row["metric"], []).append(
{"t": int(row["t"]) * 1000, "v": round(float(row["v"]), 2)}
)
return out
def alerts(include_resolved: bool = False, limit: int = 100) -> List[Dict[str, Any]]:
names = {row["id"]: row["name"] for row in db.query("SELECT id, name FROM assets")}
sql = (
"SELECT al.*, p.name AS policy_name FROM alerts al "
"LEFT JOIN policies p ON p.id=al.policy_id "
)
if not include_resolved:
sql += "WHERE al.state='open' "
sql += "ORDER BY CASE al.severity WHEN 'critical' THEN 0 WHEN 'warning' THEN 1 ELSE 2 END, al.created_at DESC LIMIT ?"
out = []
for row in db.query(sql, (limit,)):
item = dict(row)
item["asset_name"] = names.get(row["asset_id"], row["asset_id"] or "—")
item["metric_label"] = metric_meta(row["metric"]).get("label", row["metric"])
item["unit"] = metric_meta(row["metric"]).get("unit", "")
out.append(item)
return out
def overview(window_days: int = 7) -> Dict[str, Any]:
assets = list_assets()
latest = latest_values()
analyses, slopes = _analyses(assets, latest)
summaries = [summary(a, latest.get(a["id"], {}), analyses[a["id"]]) for a in assets]
summaries_with_data = [s for s in summaries if s.get("util") is not None]
storage = resource_totals(assets, latest, slopes)
open_alerts = alerts()
module_rows = db.query("SELECT * FROM modules ORDER BY id")
module_summary = []
for row in module_rows:
module_summary.append(
{
"id": row["id"],
"name": module_names().get(row["id"], {}).get("name", row["id"]),
"enabled": bool(row["enabled"]),
"status": row["status"],
"last_run": row["last_run"],
"message": row["message"],
"asset_count": sum(1 for a in assets if a["module_id"] == row["id"]),
}
)
last_runs = [row["last_run"] for row in module_rows if row["last_run"]]
nearest = None
for item in summaries:
if item.get("days_to_full") is not None:
if nearest is None or item["days_to_full"] < nearest["days_to_full"]:
nearest = {
"asset_id": item["id"],
"name": item["name"],
"days_to_full": item["days_to_full"],
"eta_date": item.get("eta_date"),
"metric": item["primary_metric"],
"util": item["util"],
}
top = sorted(summaries, key=lambda s: s.get("pressure") or 0, reverse=True)[:6]
movers = sorted(
[s for s in summaries if (s.get("slope_per_day") or 0) > 0],
key=lambda s: s.get("slope_per_day") or 0,
reverse=True,
)[:5]
storage_data = storage["storage"]
return {
"generated_at": now_iso(),
"window_days": window_days,
"kpis": {
"asset_count": len(assets),
"module_count": len(module_rows),
"modules_online": sum(1 for m in module_summary if m["enabled"] and m["status"] == "ok"),
"open_alerts": len(open_alerts),
"critical_assets": sum(1 for s in summaries if (s.get("pressure") or 0) >= 90),
"warning_assets": sum(1 for s in summaries if 80 <= (s.get("pressure") or 0) < 90),
"avg_pressure": round(
sum(s["pressure"] or 0 for s in summaries_with_data) / len(summaries_with_data), 0
) if summaries_with_data else 0,
"storage_total_gb": storage_data["total"],
"storage_used_gb": storage_data["used"],
"storage_free_gb": storage_data["free"],
"storage_util": storage_data["util"],
"nearest_exhaustion": nearest,
"last_collection": max(last_runs) if last_runs else None,
},
"resources": storage,
"top_pressure": [compact(s) for s in top],
"movers": [compact(s) for s in movers],
"alerts": open_alerts[:6],
"modules": module_summary,
"groups": groups(window_days)[:6],
"timeline": fleet_timeline(window_days),
}
def compact(asset: Dict[str, Any]) -> Dict[str, Any]:
keys = [
"id", "name", "type", "type_label", "module_id", "module_name", "cluster", "site",
"pressure", "util", "status", "status_label", "trend", "slope_per_day",
"days_to_full", "eta_date", "primary_metric", "headroom_pct", "stale", "last_seen",
]
out = {key: asset.get(key) for key in keys}
out["capacity"] = asset.get("capacity", {})
out["metrics"] = asset.get("metrics", {})
return out
def asset_detail(asset_id: str, window_days: int = 30) -> Optional[Dict[str, Any]]:
row = db.query_one("SELECT * FROM assets WHERE id=?", (asset_id,))
if not row:
return None
asset = row_asset(row)
latest = latest_values().get(asset_id, {})
slopes: Dict[Tuple[str, str], float] = {}
analysis = analyze(asset, latest, slopes)
util_keys = [m for m in utilization_for_type(asset["type"]) if m in latest]
interesting = util_keys + [
m for m in ("power_w", "temp_c", "net_rx_mbps", "net_tx_mbps", "latency_ms", "iops", "index_gb", "vm_count", "uptime_days")
if m in latest
]
seen = set()
cards = []
forecasts = {}
for metric in interesting:
if metric in seen:
continue
seen.add(metric)
points = series(asset_id, metric, window_days)
if not points:
continue
meta = metric_meta(metric)
delta = None
if len(points) >= 2:
target = int(time.time() * 1000) - 86400 * 1000
past = [p for p in points if p["t"] <= target]
if past:
delta = round(points[-1]["v"] - past[-1]["v"], 2)
cards.append(
{
"key": metric,
"label": meta.get("label", metric),
"unit": meta.get("unit", ""),
"kind": meta.get("kind", "other"),
"value": latest.get(metric),
"delta_24h": delta,
"series": points,
}
)
if metric in utilization_for_type(asset["type"]):
slope = slope_per_day(asset_id, metric, cache=slopes)
if latest.get(metric) is not None and slope > 0.03:
forecasts[metric] = {
"slope_per_day": round(slope, 3),
"points": forecast_points(asset_id, metric, latest[metric], slope, 90),
"days_to_full": analysis.get("days_to_full") if metric == analysis.get("primary_metric") else round((100 - latest[metric]) / slope, 1) if slope > 0.03 else None,
}
asset_alerts = [a for a in alerts(include_resolved=True, limit=200) if a["asset_id"] == asset_id]
module_row = db.query_one("SELECT * FROM modules WHERE id=?", (asset["module_id"],))
module_info = {
"id": asset["module_id"],
"name": asset["module_name"],
"status": module_row["status"] if module_row else "unknown",
"last_run": module_row["last_run"] if module_row else None,
"enabled": bool(module_row["enabled"]) if module_row else False,
}
return {
"asset": summary(asset, latest, analysis),
"cards": cards,
"forecasts": forecasts,
"analysis": analysis,
"recommendation": recommendation(asset, analysis, latest),
"alerts": asset_alerts,
"module": module_info,
"window_days": window_days,
}
def forecast_points(asset_id: str, metric: str, current: float, slope: float, horizon_days: int = 90) -> List[Dict[str, Any]]:
now = int(time.time())
points = []
step = max(1, horizon_days // 30)
for day in range(0, horizon_days + 1, step):
points.append(
{
"t": (now + day * 86400) * 1000,
"v": round(clamp(current + slope * day, 0, 100), 2),
}
)
return points
# ---------------------------------------------------------------------------
# Policy evaluation
# ---------------------------------------------------------------------------
def evaluate_policies() -> Dict[str, int]:
latest = latest_values()
active = {a["id"]: a for a in list_assets()}
policies = [dict(row) for row in db.query("SELECT * FROM policies WHERE enabled=1")]
open_rows = [dict(row) for row in db.query("SELECT * FROM alerts WHERE state='open'")]
open_map = {(row["asset_id"], row["metric"], row["policy_id"]): row for row in open_rows}
created = 0
updated = 0
resolved = 0
new_alerts: List[Dict[str, Any]] = []
handled = set()
for policy in policies:
for asset in active.values():
value = latest.get(asset["id"], {}).get(policy["metric"])
if value is None:
continue
handled.add((asset["id"], policy["metric"], policy["id"]))
existing = open_map.get((asset["id"], policy["metric"], policy["id"]))
severity = "critical" if value >= policy["crit"] else "warning" if value >= policy["warn"] else None
if severity:
threshold = policy["crit"] if severity == "critical" else policy["warn"]
label = metric_meta(policy["metric"]).get("label", policy["metric"])
unit = metric_meta(policy["metric"]).get("unit", "")
message = f"{asset['name']}: {label} at {value:.1f}{unit} (threshold {threshold:.0f}{unit})"
if existing:
db.execute(
"UPDATE alerts SET severity=?, value=?, threshold=?, message=? WHERE id=?",
(severity, value, threshold, message, existing["id"]),
)
updated += 1
else:
alert_id = db.execute(
"INSERT INTO alerts(asset_id, metric, policy_id, severity, value, threshold, message, state, created_at) "
"VALUES(?,?,?,?,?,?,?,'open',?)",
(asset["id"], policy["metric"], policy["id"], severity, value, threshold, message, now_iso()),
)
created += 1
new_alerts.append(
{"id": alert_id, "asset": asset["name"], "metric": policy["metric"], "severity": severity, "message": message}
)
elif existing:
db.execute(
"UPDATE alerts SET state='resolved', resolved_at=? WHERE id=?",
(now_iso(), existing["id"]),
)
resolved += 1
for key, existing in open_map.items():
if key not in handled:
db.execute(
"UPDATE alerts SET state='resolved', resolved_at=? WHERE id=?",
(now_iso(), existing["id"]),
)
resolved += 1
if new_alerts:
send_webhook(new_alerts)
return {"created": created, "updated": updated, "resolved": resolved}
def send_webhook(new_alerts: List[Dict[str, Any]]) -> None:
url = db.get_setting("alert_webhook", "").strip()
if not url or not licensing.has_feature("alert_webhooks"):
return
try:
import requests
critical = any(a["severity"] == "critical" for a in new_alerts)
lines = [f"{'🔴' if a['severity']=='critical' else '🟠'} {a['message']}" for a in new_alerts]
requests.post(
url,
json={"text": ("Headroom capacity alert\n" if not critical else "Headroom CRITICAL capacity alert\n") + "\n".join(lines), "alerts": new_alerts},
timeout=5,
)
except Exception:
pass
# ---------------------------------------------------------------------------
# What-if simulation
# ---------------------------------------------------------------------------
def simulate(payload: Dict[str, Any]) -> Dict[str, Any]:
horizon = int(clamp(float(payload.get("horizon_days", 90) or 90), 7, 365))
multiplier = clamp(float(payload.get("growth_multiplier", 1.0) or 1.0), 0, 5)
add_storage = max(0.0, float(payload.get("add_storage_gb", 0) or 0))
add_cpu = max(0.0, float(payload.get("add_cpu_cores", 0) or 0))
add_mem = max(0.0, float(payload.get("add_mem_gb", 0) or 0))
disabled = set(payload.get("disable_modules") or [])
assets = [a for a in list_assets() if a["module_id"] not in disabled]
latest = latest_values()
slopes: Dict[Tuple[str, str], float] = {}
pools = resource_totals(assets, latest, slopes)
adds = {"storage": add_storage, "cpu": add_cpu, "mem": add_mem}
results: Dict[str, Any] = {}
findings: List[str] = []
worst_after = 0.0
for resource in RESOURCES:
data = pools[resource]
total = data["total"]
used = data["used"]
growth = data["growth_per_day"] * multiplier * horizon
projected = used + growth
total_after = total + adds[resource]
util_before = round(projected / total * 100, 1) if total else None
util_after = round(projected / total_after * 100, 1) if total_after else None
if util_after is not None:
worst_after = max(worst_after, util_after)
results[resource] = {
"total": round(total, 1),
"total_after": round(total_after, 1),
"used": round(used, 1),
"projected_used": round(projected, 1),
"growth": round(growth, 1),
"util_before": util_before,
"util_after": util_after,
"headroom_before": round(max(0.0, total - projected), 1) if total else None,
"headroom_after": round(max(0.0, total_after - projected), 1) if total_after else None,
"add": round(adds[resource], 1),
"unit": {"storage": "GB", "cpu": "cores", "mem": "GB"}[resource],
}
if util_before is not None and util_before >= 90:
findings.append(
f"{resource.upper()} reaches {util_before:.0f}% within {horizon} days without changes."
)
if util_after is not None and util_after > 90:
findings.append(f"{resource.upper()} is still at {util_after:.0f}% after the plan.")
if util_before is not None and util_before > 90 and util_after is not None and util_after <= 75:
findings.append(f"Adding {adds[resource]:.0f} {results[resource]['unit']} brings {resource.upper()} back to a safe range.")
if not findings:
findings.append("The fleet stays below 80% on all modeled resources for the selected horizon.")
verdict = "healthy"
if worst_after >= 90:
verdict = "critical"
elif worst_after >= 80:
verdict = "tight"
elif worst_after >= 60:
verdict = "watch"
steps = 13
series = {"before": [], "after": []}
for index in range(steps):
day = round(horizon * index / (steps - 1))
before_vals = {}
after_vals = {}
for resource in RESOURCES:
data = pools[resource]
if not data["total"]:
continue
used = data["used"] + data["growth_per_day"] * multiplier * day
before_vals[resource] = round(used / data["total"] * 100, 2)
total_after = data["total"] + adds[resource]
after_vals[resource] = round(used / total_after * 100, 2) if total_after else None
stamp = (int(time.time()) + day * 86400) * 1000
series["before"].append({"t": stamp, "values": before_vals})
series["after"].append({"t": stamp, "values": after_vals})
return {
"horizon_days": horizon,
"growth_multiplier": multiplier,
"adds": adds,
"resources": results,
"findings": findings,
"verdict": verdict,
"series": series,
"disabled_modules": sorted(disabled),
"asset_count": len(assets),
"generated_at": now_iso(),
}
# ---------------------------------------------------------------------------
# Local insights + export
# ---------------------------------------------------------------------------
def local_insights() -> str:
data = overview(7)
kpis = data["kpis"]
lines = [
f"**Fleet snapshot** — {kpis['asset_count']} assets across {kpis['module_count']} modules. "
f"Average pressure {kpis['avg_pressure']:.0f}/100, {kpis['open_alerts']} open alert(s).",
"",
]
storage = data["resources"]["storage"]
lines.append(
f"**Storage** — {storage['util'] or 0:.0f}% used ({storage['used']:.0f} GB of {storage['total']:.0f} GB). "
f"{storage['free']:.0f} GB free, growth {storage['growth_per_day']:.1f} GB/day."
)
nearest = kpis.get("nearest_exhaustion")
if nearest:
lines.append(
f"Nearest exhaustion: **{nearest['name']}** in **{int(nearest['days_to_full'])} days** ({nearest['eta_date']})."
)
lines.append("")
lines.append("**Top pressure**")
for asset in data["top_pressure"][:4]:
eta = f", {int(asset['days_to_full'])} days to full" if asset.get("days_to_full") else ""
lines.append(
f"- {asset['name']} ({asset['module_name']}): {asset['util']:.0f}% used, "
f"{asset['slope_per_day']:+.2f} pp/day{eta}."
)
if data["alerts"]:
lines.append("")
lines.append("**Open alerts**")
for alert in data["alerts"][:4]:
lines.append(f"- {alert['message']}")
lines.append("")
lines.append(
"**Suggested next step** — Use the what-if simulator to model the next 90 days, "
"and verify the growth rate against your backup/retention policies before buying hardware."
)
return "\n".join(lines)
def export_assets_csv() -> str:
import csv
import io
assets = list_assets()
latest = latest_values()
analyses, _ = _analyses(assets, latest)
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(
["asset", "module", "type", "cluster", "site", "util_pct", "pressure", "status",
"slope_per_day", "days_to_full", "headroom_pct", "last_seen", "metrics"]
)
for asset in assets:
analysis = analyses[asset["id"]]
writer.writerow(
[
asset["name"], asset["module_name"], asset["type"], asset["cluster"], asset["site"],
analysis.get("util"), analysis.get("pressure"), analysis.get("status"),
analysis.get("slope_per_day"), analysis.get("days_to_full"),
analysis.get("headroom_pct"), asset["last_seen"],
json.dumps(latest.get(asset["id"], {}), sort_keys=True),
]
)
return buffer.getvalue()
def export_alerts_csv() -> str:
import csv
import io
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(["id", "created_at", "resolved_at", "severity", "state", "asset", "metric", "value", "threshold", "message"])
for alert in alerts(include_resolved=True, limit=10000):
writer.writerow(
[
alert["id"], alert["created_at"], alert["resolved_at"], alert["severity"],
alert["state"], alert["asset_name"], alert["metric"], alert["value"],
alert["threshold"], alert["message"],
]
)
return buffer.getvalue()
def prune_samples() -> int:
days = licensing.retention_days()
cutoff = int(time.time()) - days * 86400
with db.db() as conn:
cursor = conn.execute("DELETE FROM samples WHERE ts < ?", (cutoff,))
return cursor.rowcount
+52
View File
@@ -0,0 +1,52 @@
"""Runtime configuration. Everything has a sensible default for local use."""
from __future__ import annotations
import os
import secrets
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = Path(os.environ.get("HEADROOM_DATA", str(BASE_DIR / "data")))
MODULES_DIR = Path(os.environ.get("HEADROOM_MODULES", str(BASE_DIR / "modules")))
STATIC_DIR = BASE_DIR / "app" / "static"
DB_PATH = Path(os.environ.get("HEADROOM_DB", str(DATA_DIR / "headroom.db")))
SECRET_PATH = DATA_DIR / "secret.key"
APP_NAME = "Headroom"
APP_VERSION = "1.0.0"
API_VERSION = 1
MODULE_API_VERSION = 1
SCHEDULER_ENABLED = os.environ.get("HEADROOM_SCHEDULER", "1") not in ("0", "false", "no")
SEED_DAYS = int(os.environ.get("HEADROOM_SEED_DAYS", "30"))
SEED_DEMO = os.environ.get("HEADROOM_SEED_DEMO", "1") not in ("0", "false", "no")
ALLOW_DEV_LICENSE = os.environ.get("HEADROOM_ALLOW_DEV_LICENSE", "1") not in ("0", "false", "no")
ADMIN_USER = os.environ.get("HEADROOM_ADMIN_USER", "admin")
ADMIN_PASSWORD = os.environ.get("HEADROOM_ADMIN_PASSWORD", "admin")
MODULE_TIMEOUT_SECONDS = int(os.environ.get("HEADROOM_MODULE_TIMEOUT", "90"))
MAX_UPLOAD_BYTES = 2 * 1024 * 1024
MAX_PUSH_ASSETS = 2000
def ensure_dirs() -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
(DATA_DIR / "logs").mkdir(exist_ok=True)
MODULES_DIR.mkdir(parents=True, exist_ok=True)
def get_secret() -> str:
"""Stable per-install secret used for sessions and demo license signing."""
override = os.environ.get("HEADROOM_SECRET_KEY")
if override:
return override
ensure_dirs()
if SECRET_PATH.exists():
return SECRET_PATH.read_text().strip()
value = secrets.token_urlsafe(48)
SECRET_PATH.write_text(value)
try:
SECRET_PATH.chmod(0o600)
except OSError:
pass
return value
+160
View File
@@ -0,0 +1,160 @@
"""Capacity copilot: local insight always, LLM narrative on Enterprise."""
from __future__ import annotations
import json
from typing import Any, Dict, List, Optional
from . import capacity, db, licensing
from .registry import SECRET_MASK
SYSTEM_PROMPT = (
"You are Headroom Copilot, a senior infrastructure capacity engineer for a homelab. "
"Answer with concrete, quantified advice based on the supplied fleet context. "
"Be concise (max ~220 words), use short paragraphs or bullets, and never invent assets, "
"metrics or alerts that are not in the context. If data is missing, say what to configure. "
"Distinguish correlation from causation and include the top risk plus the next action."
)
def config() -> Dict[str, Any]:
settings = db.settings_map()
key = settings.get("ai_api_key", "")
return {
"base_url": settings.get("ai_base_url", ""),
"model": settings.get("ai_model", ""),
"api_key": SECRET_MASK if key else "",
"key_set": bool(key),
"configured": bool(settings.get("ai_base_url") and settings.get("ai_model")),
"available": licensing.has_feature("llm_copilot"),
"provider_hint": "Any OpenAI-compatible endpoint (OpenAI, Azure, Ollama, LM Studio, LiteLLM)",
}
def update_config(payload: Dict[str, Any]) -> Dict[str, Any]:
base_url = str(payload.get("base_url", "")).strip()[:500]
model = str(payload.get("model", "")).strip()[:200]
key = payload.get("api_key")
db.set_setting("ai_base_url", base_url)
db.set_setting("ai_model", model)
if isinstance(key, str) and key not in ("", SECRET_MASK):
db.set_setting("ai_api_key", key.strip()[:500])
elif key == "":
db.set_setting("ai_api_key", "")
return config()
def fleet_context() -> Dict[str, Any]:
data = capacity.overview(7)
return {
"generated_at": data["generated_at"],
"kpis": data["kpis"],
"resources": data["resources"],
"top_pressure": [
{
"name": asset["name"],
"type": asset["type"],
"module": asset["module_name"],
"util_pct": asset["util"],
"pressure": asset["pressure"],
"slope_pp_per_day": asset["slope_per_day"],
"days_to_full": asset["days_to_full"],
}
for asset in data["top_pressure"]
],
"movers": [
{
"name": asset["name"],
"slope_pp_per_day": asset["slope_per_day"],
"util_pct": asset["util"],
}
for asset in data["movers"]
],
"alerts": [alert["message"] for alert in data["alerts"]],
"modules": [
{"id": m["id"], "name": m["name"], "status": m["status"], "enabled": m["enabled"]}
for m in data["modules"]
],
}
def chat(messages: List[Dict[str, str]]) -> Dict[str, Any]:
cleaned = []
for message in messages[-12:]:
if not isinstance(message, dict):
continue
role = str(message.get("role", "user"))
if role not in ("user", "assistant", "system"):
continue
content = str(message.get("content", ""))[:6000].strip()
if content:
cleaned.append({"role": role, "content": content})
if not cleaned:
raise ValueError("A message is required")
local = capacity.local_insights()
cfg = config()
configured = bool(cfg["base_url"] and cfg["model"])
if not licensing.has_feature("llm_copilot"):
return {
"mode": "local",
"message": local,
"upgrade_required": True,
"note": "Local capacity analysis. Add an LLM provider with Headroom Enterprise for conversational answers.",
}
if not configured:
return {
"mode": "local",
"message": local,
"upgrade_required": False,
"note": "No LLM provider is configured yet. Showing the deterministic local analysis.",
}
try:
import requests
settings = db.settings_map()
base = cfg["base_url"].rstrip("/")
url = base if base.endswith("/chat/completions") else base + "/chat/completions"
headers = {"Content-Type": "application/json"}
if settings.get("ai_api_key"):
headers["Authorization"] = f"Bearer {settings['ai_api_key']}"
context = json.dumps(fleet_context(), default=str)
body = {
"model": cfg["model"],
"messages": [{"role": "system", "content": SYSTEM_PROMPT + "\n\nFleet context:\n" + context}] + cleaned,
"temperature": 0.2,
"max_tokens": 900,
}
response = requests.post(url, headers=headers, json=body, timeout=75)
if response.status_code >= 400:
raise RuntimeError(f"provider returned HTTP {response.status_code}: {response.text[:300]}")
payload = response.json()
choices = payload.get("choices") or []
if not choices:
raise RuntimeError("provider returned no choices")
content = choices[0].get("message", {}).get("content", "")
if not content:
raise RuntimeError("provider returned an empty answer")
return {
"mode": "llm",
"message": content,
"upgrade_required": False,
"model": cfg["model"],
"note": "Answer generated from live Headroom context.",
}
except Exception as exc:
return {
"mode": "local",
"message": local,
"upgrade_required": False,
"note": f"LLM provider unavailable, showing local analysis instead ({str(exc)[:180]}).",
}
def suggested_questions() -> List[str]:
return [
"Hvad bliver det næste kapacitetsproblem i mit lab?",
"Which assets should I upgrade first, and by how much?",
"Er der noget der er steget unormalt hurtigt den sidste uge?",
"Simulér 6 måneders vækst med 8 TB ekstra storage.",
]
+263
View File
@@ -0,0 +1,263 @@
"""SQLite storage layer. One connection per operation, WAL enabled."""
from __future__ import annotations
import json
import sqlite3
from contextlib import contextmanager
from typing import Any, Dict, Generator, Iterable, List, Optional
from . import config
from .security import hash_password
from .util import now_iso
SCHEMA = """
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'admin',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
prefix TEXT NOT NULL,
key_hash TEXT UNIQUE NOT NULL,
role TEXT NOT NULL DEFAULT 'operator',
created_at TEXT NOT NULL,
last_used TEXT
);
CREATE TABLE IF NOT EXISTS modules (
id TEXT PRIMARY KEY,
module_type TEXT,
display_name TEXT,
enabled INTEGER NOT NULL DEFAULT 1,
config TEXT NOT NULL DEFAULT '{}',
status TEXT NOT NULL DEFAULT 'pending',
message TEXT,
logs TEXT,
last_run TEXT,
last_duration_ms INTEGER,
installed_at TEXT,
source TEXT NOT NULL DEFAULT 'bundled',
version TEXT
);
CREATE INDEX IF NOT EXISTS idx_modules_type ON modules(module_type);
CREATE TABLE IF NOT EXISTS module_state (
module_id TEXT PRIMARY KEY,
state TEXT NOT NULL DEFAULT '{}',
updated_at TEXT
);
CREATE TABLE IF NOT EXISTS assets (
id TEXT PRIMARY KEY,
module_id TEXT NOT NULL,
external_id TEXT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'server',
cluster TEXT,
site TEXT,
tags TEXT NOT NULL DEFAULT '[]',
meta TEXT NOT NULL DEFAULT '{}',
capacity TEXT NOT NULL DEFAULT '{}',
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1,
UNIQUE(module_id, external_id)
);
CREATE INDEX IF NOT EXISTS idx_assets_module ON assets(module_id);
CREATE INDEX IF NOT EXISTS idx_assets_active ON assets(active);
CREATE TABLE IF NOT EXISTS samples (
asset_id TEXT NOT NULL,
metric TEXT NOT NULL,
ts INTEGER NOT NULL,
value REAL NOT NULL,
PRIMARY KEY (asset_id, metric, ts)
);
CREATE INDEX IF NOT EXISTS idx_samples_metric_ts ON samples(metric, ts);
CREATE INDEX IF NOT EXISTS idx_samples_asset_ts ON samples(asset_id, ts);
CREATE TABLE IF NOT EXISTS policies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
metric TEXT NOT NULL,
warn REAL NOT NULL,
crit REAL NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
asset_id TEXT,
metric TEXT NOT NULL,
policy_id INTEGER,
severity TEXT NOT NULL,
value REAL,
threshold REAL,
message TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'open',
created_at TEXT NOT NULL,
resolved_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_alerts_state ON alerts(state);
CREATE TABLE IF NOT EXISTS audit (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
actor TEXT NOT NULL,
action TEXT NOT NULL,
target TEXT,
detail TEXT
);
"""
DEFAULT_SETTINGS = {
"site_name": "Homelab HQ",
"retention_days": "30",
"seed_version": "",
"trial_started_at": "",
"license_key": "",
"license_activated_at": "",
"ai_base_url": "",
"ai_model": "",
"ai_api_key": "",
"alert_webhook": "",
"mcp_enabled": "1",
"enterprise_mode": "0",
}
DEFAULT_POLICIES = [
("Storage headroom", "storage_pct", 75, 85),
("CPU saturation", "cpu_pct", 80, 90),
("Memory pressure", "mem_pct", 80, 90),
("License consumption", "license_pct", 85, 95),
("Thermal ceiling", "temp_c", 70, 80),
]
@contextmanager
def db() -> Generator[sqlite3.Connection, None, None]:
config.ensure_dirs()
conn = sqlite3.connect(str(config.DB_PATH), timeout=20)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=20000")
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def _migrate_modules(conn: sqlite3.Connection) -> None:
try:
columns = {row["name"] for row in conn.execute("PRAGMA table_info(modules)").fetchall()}
if "module_type" not in columns:
conn.execute("ALTER TABLE modules ADD COLUMN module_type TEXT")
if "display_name" not in columns:
conn.execute("ALTER TABLE modules ADD COLUMN display_name TEXT")
conn.execute("UPDATE modules SET module_type=id WHERE module_type IS NULL OR module_type=''")
conn.execute("CREATE INDEX IF NOT EXISTS idx_modules_type ON modules(module_type)")
except Exception:
pass
def init_db() -> None:
config.ensure_dirs()
with db() as conn:
conn.executescript(SCHEMA)
_migrate_modules(conn)
for key, value in DEFAULT_SETTINGS.items():
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES(?, ?)", (key, value)
)
existing = conn.execute("SELECT COUNT(*) AS n FROM users").fetchone()["n"]
if not existing:
conn.execute(
"INSERT INTO users(username, password_hash, role, created_at) VALUES(?,?,?,?)",
(config.ADMIN_USER, hash_password(config.ADMIN_PASSWORD), "admin", now_iso()),
)
policies = conn.execute("SELECT COUNT(*) AS n FROM policies").fetchone()["n"]
if not policies:
for name, metric, warn, crit in DEFAULT_POLICIES:
conn.execute(
"INSERT INTO policies(name, metric, warn, crit, enabled, created_at) VALUES(?,?,?,?,1,?)",
(name, metric, warn, crit, now_iso()),
)
def query(sql: str, params: Iterable[Any] = ()) -> List[sqlite3.Row]:
with db() as conn:
return conn.execute(sql, tuple(params)).fetchall()
def query_one(sql: str, params: Iterable[Any] = ()) -> Optional[sqlite3.Row]:
rows = query(sql, params)
return rows[0] if rows else None
def execute(sql: str, params: Iterable[Any] = ()) -> int:
with db() as conn:
cur = conn.execute(sql, tuple(params))
return cur.lastrowid
def executemany(sql: str, rows: Iterable[Iterable[Any]]) -> None:
with db() as conn:
conn.executemany(sql, list(rows))
def get_setting(key: str, default: str = "") -> str:
row = query_one("SELECT value FROM settings WHERE key=?", (key,))
return row["value"] if row else default
def set_setting(key: str, value: Any) -> None:
with db() as conn:
conn.execute(
"INSERT INTO settings(key, value) VALUES(?, ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(key, str(value)),
)
invalidate_settings_cache()
_SETTINGS_CACHE: Dict[str, Any] = {"at": 0.0, "values": {}}
def settings_map() -> Dict[str, str]:
import time
if time.time() - _SETTINGS_CACHE["at"] < 2:
return dict(_SETTINGS_CACHE["values"])
rows = query("SELECT key, value FROM settings")
values = {row["key"]: row["value"] for row in rows}
_SETTINGS_CACHE["values"] = values
_SETTINGS_CACHE["at"] = time.time()
return dict(values)
def invalidate_settings_cache() -> None:
_SETTINGS_CACHE["at"] = 0.0
_SETTINGS_CACHE["values"] = {}
def audit(actor: str, action: str, target: str = "", detail: Any = "") -> None:
if not isinstance(detail, str):
detail = json.dumps(detail, default=str)[:2000]
execute(
"INSERT INTO audit(ts, actor, action, target, detail) VALUES(?,?,?,?,?)",
(now_iso(), actor, action, target, detail[:2000]),
)
def json_col(row: sqlite3.Row, key: str, default: Any) -> Any:
try:
raw = row[key]
return json.loads(raw) if raw else default
except (KeyError, TypeError, json.JSONDecodeError):
return default
+226
View File
@@ -0,0 +1,226 @@
"""Deterministic demo fleet.
The same definitions power both the 30-day seed history and the live demo
snapshots returned by the bundled modules, so the UI is consistent out of the
box while every collector module still implements a real API path.
"""
from __future__ import annotations
import hashlib
import math
from typing import Any, Dict, List, Optional
REFERENCE_METRICS = {"cpu_pct", "mem_pct", "storage_pct", "license_pct", "load_pct", "battery_pct"}
def _noise(key: str, ts: int, scale: float) -> float:
digest = hashlib.sha256(f"{key}:{ts // 3600}".encode()).digest()
return ((int.from_bytes(digest[:2], "big") / 65535.0) * 2 - 1) * scale
def _asset(
external_id: str,
name: str,
type_: str,
cluster: str,
site: str,
capacity: Dict[str, float],
metrics: Dict[str, float],
growth: Optional[Dict[str, float]] = None,
amp: Optional[Dict[str, float]] = None,
tags: Optional[List[str]] = None,
meta: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
return {
"external_id": external_id,
"name": name,
"type": type_,
"cluster": cluster,
"site": site,
"capacity": capacity,
"metrics": metrics,
"growth": growth or {},
"amp": amp or {},
"tags": tags or [],
"meta": meta or {},
}
FLEET: Dict[str, List[Dict[str, Any]]] = {
"proxmox": [
_asset("pve-01", "pve-01", "hypervisor", "Proxmox / Atlas", "Rack A",
{"cpu_cores": 16, "mem_gb": 64, "storage_gb": 2000},
{"cpu_pct": 46, "mem_pct": 64, "vm_count": 9, "power_w": 185, "uptime_days": 63},
{"cpu_pct": 0.15, "mem_pct": 0.22}, {"cpu_pct": 8, "mem_pct": 3},
["prod", "pve"], {"vendor": "Proxmox VE", "version": "8.2", "cpu": "AMD Ryzen 9 5950X"}),
_asset("pve-02", "pve-02", "hypervisor", "Proxmox / Atlas", "Rack A",
{"cpu_cores": 16, "mem_gb": 64, "storage_gb": 2000},
{"cpu_pct": 61, "mem_pct": 71, "vm_count": 11, "power_w": 212, "uptime_days": 91},
{"cpu_pct": 0.2, "mem_pct": 0.16}, {"cpu_pct": 9, "mem_pct": 3},
["prod", "pve"], {"vendor": "Proxmox VE", "version": "8.2"}),
_asset("pve-03", "pve-03", "hypervisor", "Proxmox / Atlas", "Rack A",
{"cpu_cores": 24, "mem_gb": 96, "storage_gb": 2000},
{"cpu_pct": 33, "mem_pct": 48, "vm_count": 7, "power_w": 168, "uptime_days": 34},
{"cpu_pct": 0.28, "mem_pct": 0.3}, {"cpu_pct": 6, "mem_pct": 2},
["lab", "pve"], {"vendor": "Proxmox VE", "version": "8.3"}),
_asset("ceph-atlas", "ceph-atlas", "storage", "Proxmox / Atlas", "Rack A",
{"storage_gb": 12288},
{"storage_pct": 71, "iops": 1850, "latency_ms": 3.4},
{"storage_pct": 0.32}, {"storage_pct": 0.4, "iops": 240, "latency_ms": 0.7},
["ceph", "ssd"], {"vendor": "Ceph", "pools": 3}),
_asset("local-lvm-01", "local-lvm (pve-01)", "storage", "Proxmox / Atlas", "Rack A",
{"storage_gb": 1900}, {"storage_pct": 58, "latency_ms": 1.9},
{"storage_pct": 0.18}, {"storage_pct": 0.3, "latency_ms": 0.3}, ["local", "nvme"]),
_asset("local-lvm-02", "local-lvm (pve-02)", "storage", "Proxmox / Atlas", "Rack A",
{"storage_gb": 1900}, {"storage_pct": 66, "latency_ms": 2.1},
{"storage_pct": 0.22}, {"storage_pct": 0.3, "latency_ms": 0.3}, ["local", "nvme"]),
_asset("nfs-vault", "nfs-vault", "storage", "Proxmox / Atlas", "Rack C",
{"storage_gb": 8192}, {"storage_pct": 82, "latency_ms": 6.2, "iops": 640},
{"storage_pct": 0.18}, {"storage_pct": 0.2, "latency_ms": 1.4},
["nfs", "backup"], {"vendor": "Synology", "mount": "/mnt/vault"}),
],
"esxi": [
_asset("esx-01", "esx-01.lab", "hypervisor", "ESXi / Edge", "Rack B",
{"cpu_cores": 32, "mem_gb": 256, "storage_gb": 960},
{"cpu_pct": 57, "mem_pct": 84, "vm_count": 24, "power_w": 412, "uptime_days": 122},
{"cpu_pct": 0.12, "mem_pct": 0.3}, {"cpu_pct": 10, "mem_pct": 2},
["prod", "esxi"], {"vendor": "VMware", "version": "8.0 U2"}),
_asset("esx-02", "esx-02.lab", "hypervisor", "ESXi / Edge", "Rack B",
{"cpu_cores": 32, "mem_gb": 256, "storage_gb": 960},
{"cpu_pct": 38, "mem_pct": 44, "vm_count": 18, "power_w": 355, "uptime_days": 118},
{"cpu_pct": 0.1, "mem_pct": 0.18}, {"cpu_pct": 8, "mem_pct": 2},
["prod", "esxi"], {"vendor": "VMware", "version": "8.0 U2"}),
_asset("vsan-edge", "vsan-edge", "storage", "ESXi / Edge", "Rack B",
{"storage_gb": 20480}, {"storage_pct": 74, "latency_ms": 2.8, "iops": 4200},
{"storage_pct": 0.25}, {"storage_pct": 0.3, "iops": 500, "latency_ms": 0.5},
["vsan", "ssd"], {"vendor": "VMware vSAN"}),
_asset("ds-scratch", "ds-scratch", "storage", "ESXi / Edge", "Rack B",
{"storage_gb": 4096}, {"storage_pct": 46, "latency_ms": 4.1},
{"storage_pct": 0.4}, {"storage_pct": 0.5, "latency_ms": 0.9}, ["scratch", "hdd"]),
],
"splunk": [
_asset("splunk-idx-01", "splunk-idx-01", "appliance", "Splunk / Observability", "Rack A",
{"cpu_cores": 16, "mem_gb": 64, "storage_gb": 4096},
{"cpu_pct": 52, "mem_pct": 67, "license_pct": 87, "index_gb": 2980,
"storage_pct": 73, "temp_c": 38, "uptime_days": 210},
{"license_pct": 0.35, "storage_pct": 0.3, "index_gb": 12},
{"cpu_pct": 6, "mem_pct": 3}, ["logging", "siem"],
{"vendor": "Splunk", "version": "9.2", "license": "Enterprise 50 GB/day"}),
],
"truenas": [
_asset("truenas-01", "truenas-01", "nas", "Storage / Vault", "Rack C",
{"cpu_cores": 12, "mem_gb": 96}, {"cpu_pct": 22, "mem_pct": 58, "temp_c": 41, "power_w": 238},
{"cpu_pct": 0.05, "mem_pct": 0.08}, {"cpu_pct": 4, "mem_pct": 2}, ["nas", "zfs"],
{"vendor": "TrueNAS SCALE", "version": "24.04", "disks": 12}),
_asset("tank-primary", "tank / primary", "storage", "Storage / Vault", "Rack C",
{"storage_gb": 40960}, {"storage_pct": 88, "latency_ms": 5.4, "iops": 980},
{"storage_pct": 0.5}, {"storage_pct": 0.4, "latency_ms": 1.1},
["zfs", "raidz2"], {"vendor": "TrueNAS SCALE", "pool": "tank/primary"}),
_asset("tank-backup", "tank / backup", "storage", "Storage / Vault", "Rack C",
{"storage_gb": 12288}, {"storage_pct": 48, "latency_ms": 7.8},
{"storage_pct": 0.2}, {"storage_pct": 0.3, "latency_ms": 1.2},
["zfs", "backup"], {"vendor": "TrueNAS SCALE", "pool": "tank/backup"}),
],
"linux": [
_asset("lnx-docker-01", "lnx-docker-01", "server", "Linux / Core", "Rack A",
{"cpu_cores": 16, "mem_gb": 64, "storage_gb": 1900},
{"cpu_pct": 39, "mem_pct": 55, "storage_pct": 62, "temp_c": 47, "uptime_days": 88},
{"cpu_pct": 0.22, "mem_pct": 0.25, "storage_pct": 0.3},
{"cpu_pct": 9, "mem_pct": 3}, ["docker", "prod"], {"os": "Ubuntu 24.04"}),
_asset("lnx-k8s-01", "lnx-k8s-01", "server", "Linux / Core", "Rack B",
{"cpu_cores": 24, "mem_gb": 128, "storage_gb": 3800},
{"cpu_pct": 66, "mem_pct": 73, "storage_pct": 69, "temp_c": 52, "uptime_days": 140},
{"cpu_pct": 0.45, "mem_pct": 0.4, "storage_pct": 0.35},
{"cpu_pct": 11, "mem_pct": 4}, ["kubernetes", "prod"], {"os": "Debian 12"}),
_asset("lnx-mon-01", "lnx-mon-01", "server", "Linux / Core", "Rack C",
{"cpu_cores": 8, "mem_gb": 32, "storage_gb": 950},
{"cpu_pct": 28, "mem_pct": 41, "storage_pct": 57, "temp_c": 43, "uptime_days": 67},
{"cpu_pct": 0.08, "mem_pct": 0.1, "storage_pct": 0.25},
{"cpu_pct": 5, "mem_pct": 2}, ["monitoring"], {"os": "Ubuntu 22.04"}),
],
"windows": [
_asset("win-ad-01", "win-ad-01", "server", "Windows / Core", "Rack A",
{"cpu_cores": 8, "mem_gb": 32, "storage_gb": 480},
{"cpu_pct": 21, "mem_pct": 46, "storage_pct": 64, "uptime_days": 55},
{"cpu_pct": 0.04, "mem_pct": 0.06, "storage_pct": 0.12},
{"cpu_pct": 3, "mem_pct": 2}, ["ad", "windows"], {"os": "Windows Server 2022"}),
_asset("win-files-01", "win-files-01", "server", "Windows / Core", "Rack B",
{"cpu_cores": 16, "mem_gb": 64, "storage_gb": 7600},
{"cpu_pct": 35, "mem_pct": 58, "storage_pct": 79},
{"cpu_pct": 0.1, "mem_pct": 0.15, "storage_pct": 0.3},
{"cpu_pct": 5, "mem_pct": 2}, ["files", "windows"], {"os": "Windows Server 2022"}),
],
"http-json": [
_asset("core-switch-01", "core-switch-01", "network", "Network / Facilities", "Rack C",
{}, {"load_pct": 47, "net_rx_mbps": 4230, "net_tx_mbps": 3120, "temp_c": 44, "uptime_days": 301},
{"load_pct": 0.12, "net_rx_mbps": 18, "net_tx_mbps": 14},
{"load_pct": 12, "net_rx_mbps": 420, "net_tx_mbps": 380, "temp_c": 2},
["network", "10g"], {"vendor": "UniFi", "model": "USW-Pro-48"}),
_asset("ups-rack-c", "ups-rack-c", "power", "Network / Facilities", "Rack C",
{}, {"load_pct": 62, "power_w": 1250, "battery_pct": 96, "temp_c": 32, "uptime_days": 200},
{}, {"load_pct": 4, "power_w": 80, "temp_c": 1},
["ups", "power"], {"vendor": "APC", "model": "Smart-UPS 3000"}),
],
}
MODULE_META = {
"proxmox": {"name": "Proxmox VE", "cluster": "Proxmox / Atlas"},
"esxi": {"name": "VMware ESXi", "cluster": "ESXi / Edge"},
"splunk": {"name": "Splunk", "cluster": "Splunk / Observability"},
"truenas": {"name": "TrueNAS", "cluster": "Storage / Vault"},
"linux": {"name": "Linux hosts", "cluster": "Linux / Core"},
"windows": {"name": "Windows hosts", "cluster": "Windows / Core"},
"http-json": {"name": "HTTP JSON bridge", "cluster": "Network / Facilities"},
}
def demo_value(spec: Dict[str, Any], metric: str, ts: int, reference_ts: int) -> float:
base = float(spec["metrics"].get(metric, 0))
growth = float(spec["growth"].get(metric, 0))
days_ago = (reference_ts - ts) / 86400.0
value = base - growth * days_ago
amp = float(spec["amp"].get(metric, 0))
if amp:
hour = (ts % 86400) / 3600.0
value += amp * math.sin(2 * math.pi * (hour - 8) / 24.0)
if metric == "uptime_days":
value = max(0.0, base - days_ago)
elif metric == "vm_count":
value = round(value + _noise(f"{spec['external_id']}:{metric}", ts, 0.5))
elif metric == "battery_pct":
value += _noise(f"{spec['external_id']}:{metric}", ts, 0.5)
elif growth:
value += _noise(f"{spec['external_id']}:{metric}", ts, 0.18)
else:
scale = {"power_w": 6.0, "temp_c": 1.0, "latency_ms": 0.2, "iops": 40.0}.get(metric, 0.9)
value += _noise(f"{spec['external_id']}:{metric}", ts, scale)
if metric in REFERENCE_METRICS:
value = max(0.0, min(99.5, value))
return round(value, 2)
def snapshot(module_id: str, now_ts: int) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
for spec in FLEET.get(module_id, []):
metrics = {
metric: demo_value(spec, metric, now_ts, now_ts)
for metric in spec["metrics"]
}
out.append(
{
"external_id": spec["external_id"],
"name": spec["name"],
"type": spec["type"],
"cluster": spec["cluster"],
"site": spec["site"],
"tags": list(spec["tags"]),
"capacity": dict(spec["capacity"]),
"metrics": metrics,
"meta": dict(spec["meta"]),
}
)
return out
def assets_for(module_id: str) -> List[Dict[str, Any]]:
return list(FLEET.get(module_id, []))
+284
View File
@@ -0,0 +1,284 @@
"""Edition / entitlement handling.
Community is free forever. Enterprise is unlocked by a signed license key or a
30-day trial. Keys are HMAC-signed for this reference implementation; swap the
signature for Ed25519 (public key in the app, private key in your license
service) when you ship commercially.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Iterable, List, Optional
from . import config, db
from .util import utcnow
TRIAL_DAYS = 30
COMMUNITY_FEATURES = {
"core",
"bundled_modules",
"rest_api",
"local_insights",
"forecasting",
"what_if",
"csv_export",
}
ENTERPRISE_FEATURES = COMMUNITY_FEATURES | {
"custom_modules",
"llm_copilot",
"mcp_server",
"unlimited_assets",
"long_retention",
"audit_export",
"alert_webhooks",
"priority_support",
}
FEATURE_LABELS = {
"core": "Capacity dashboard",
"bundled_modules": "All bundled integrations",
"rest_api": "REST API & push ingestion",
"local_insights": "Local capacity insights",
"forecasting": "Forecasting & days-to-full",
"what_if": "What-if simulator",
"csv_export": "CSV export",
"custom_modules": "Upload custom modules",
"llm_copilot": "LLM copilot (OpenAI-compatible)",
"mcp_server": "MCP server for AI agents",
"unlimited_assets": "Unlimited assets",
"long_retention": "400-day metric retention",
"audit_export": "Audit log export",
"alert_webhooks": "Alert webhooks",
"priority_support": "Priority support",
}
COMMUNITY_LIMITS = {"assets": 40, "retention_days": 30}
ENTERPRISE_LIMITS = {"assets": -1, "retention_days": 400}
def _b64e(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def _b64d(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
def _signing_key() -> bytes:
return hashlib.sha256(("license:" + config.get_secret()).encode()).digest()
def issue_key(
customer: str,
days: int = 365,
assets: int = -1,
features: Optional[Iterable[str]] = None,
edition: str = "enterprise",
) -> str:
payload = {
"v": 1,
"edition": edition,
"customer": customer,
"assets": int(assets),
"features": sorted(features or ENTERPRISE_FEATURES),
"issued": utcnow().isoformat(timespec="seconds"),
"expires": (utcnow() + timedelta(days=days)).isoformat(timespec="seconds"),
}
body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
sig = hmac.new(_signing_key(), body.encode(), hashlib.sha256).digest()
return f"HR1.{body}.{_b64e(sig)}"
def verify_key(key: str) -> Optional[Dict[str, Any]]:
try:
prefix, body, signature = key.strip().split(".")
if prefix != "HR1":
return None
expected = hmac.new(_signing_key(), body.encode(), hashlib.sha256).digest()
if not hmac.compare_digest(_b64d(signature), expected):
return None
payload = json.loads(_b64d(body))
expires = datetime.fromisoformat(payload["expires"])
if expires.tzinfo is None:
expires = expires.replace(tzinfo=timezone.utc)
if expires < utcnow():
payload["expired"] = True
return payload
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
return None
def activate(key: str) -> Dict[str, Any]:
payload = verify_key(key)
if not payload:
raise ValueError("Invalid license key")
if payload.get("expired"):
raise ValueError("This license key has expired")
if payload.get("edition") not in ("enterprise", "trial"):
raise ValueError("Unsupported license edition")
db.set_setting("license_key", key.strip())
db.set_setting("license_activated_at", utcnow().isoformat(timespec="seconds"))
return payload
def deactivate() -> None:
db.set_setting("license_key", "")
db.set_setting("license_activated_at", "")
def start_trial() -> Dict[str, Any]:
if db.get_setting("trial_started_at"):
raise ValueError("A trial has already been used on this installation")
db.set_setting("trial_started_at", utcnow().isoformat(timespec="seconds"))
return status()
def status() -> Dict[str, Any]:
settings = db.settings_map()
enterprise_mode = str(settings.get("enterprise_mode", "0") or "0").strip().lower()
if enterprise_mode in ("1", "true", "yes", "on"):
configured_retention = int(settings.get("retention_days", "30") or 30)
return {
"edition": "enterprise",
"label": "Enterprise",
"source": "admin",
"valid": True,
"admin_override": True,
"features": sorted(ENTERPRISE_FEATURES),
"limits": {
"assets": -1,
"retention_days": max(ENTERPRISE_LIMITS["retention_days"], configured_retention),
},
"customer": "Administrator unlock",
"expires": None,
"days_left": None,
}
key = settings.get("license_key", "")
trial_started = settings.get("trial_started_at", "")
result: Dict[str, Any] = {
"edition": "community",
"label": "Community",
"source": "community",
"valid": True,
"admin_override": False,
"features": sorted(COMMUNITY_FEATURES),
"limits": dict(COMMUNITY_LIMITS),
"customer": None,
"expires": None,
"days_left": None,
}
if key:
payload = verify_key(key)
if payload and not payload.get("expired"):
result.update(
edition="enterprise",
label="Enterprise",
source="license",
customer=payload.get("customer"),
expires=payload.get("expires"),
features=sorted(set(payload.get("features") or ENTERPRISE_FEATURES)),
limits={
"assets": int(payload.get("assets", -1)),
"retention_days": max(
ENTERPRISE_LIMITS["retention_days"],
int(settings.get("retention_days", "30") or 30),
),
},
)
expires = datetime.fromisoformat(payload["expires"])
if expires.tzinfo is None:
expires = expires.replace(tzinfo=timezone.utc)
result["days_left"] = max(0, (expires - utcnow()).days)
return result
result["invalid_license"] = True
if trial_started:
try:
started = datetime.fromisoformat(trial_started)
if started.tzinfo is None:
started = started.replace(tzinfo=timezone.utc)
ends = started + timedelta(days=TRIAL_DAYS)
left = (ends - utcnow()).days
if ends > utcnow():
result.update(
edition="trial",
label="Enterprise trial",
source="trial",
customer="Trial",
expires=ends.isoformat(timespec="seconds"),
days_left=max(0, left),
features=sorted(ENTERPRISE_FEATURES),
limits={
"assets": -1,
"retention_days": ENTERPRISE_LIMITS["retention_days"],
},
)
return result
result["trial_expired"] = True
except ValueError:
pass
return result
def has_feature(feature: str) -> bool:
return feature in status()["features"]
def retention_days() -> int:
st = status()
configured = int(db.get_setting("retention_days", "30") or 30)
limit = int(st["limits"].get("retention_days", 30))
return max(7, min(configured, limit))
def asset_limit() -> int:
return int(status()["limits"].get("assets", 40))
def edition_matrix() -> List[Dict[str, Any]]:
grouped = [
("Core capacity", ["core", "bundled_modules", "rest_api", "local_insights", "forecasting", "what_if", "csv_export"]),
("Scale & automation", ["custom_modules", "unlimited_assets", "long_retention", "alert_webhooks"]),
("AI & integration", ["mcp_server", "llm_copilot"]),
("Enterprise controls", ["audit_export", "priority_support"]),
]
out = []
for group, features in grouped:
out.append(
{
"group": group,
"features": [
{
"key": f,
"label": FEATURE_LABELS.get(f, f),
"community": f in COMMUNITY_FEATURES,
"enterprise": f in ENTERPRISE_FEATURES,
}
for f in features
],
}
)
return out
def _main() -> None:
import argparse
parser = argparse.ArgumentParser(description="Issue Headroom license keys")
parser.add_argument("customer", nargs="?", default="Homelab")
parser.add_argument("--days", type=int, default=365)
parser.add_argument("--assets", type=int, default=-1)
args = parser.parse_args()
print(issue_key(args.customer, days=args.days, assets=args.assets))
if __name__ == "__main__":
_main()
+64
View File
@@ -0,0 +1,64 @@
"""Headroom application entrypoint."""
from __future__ import annotations
from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncIterator
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import capacity, config, db, registry, seed
from .routes import router
from .scheduler import scheduler
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
config.ensure_dirs()
db.init_db()
registry.sync_modules()
if seed.seed_if_empty():
print(f"[headroom] seeded demo fleet ({config.SEED_DAYS} days of metrics)", flush=True)
try:
capacity.evaluate_policies()
except Exception as exc:
print(f"[headroom] initial policy evaluation failed: {exc}", flush=True)
if config.SCHEDULER_ENABLED:
await scheduler.start()
print(f"[headroom] ready — http://127.0.0.1:8787 (data: {config.DATA_DIR})", flush=True)
yield
await scheduler.stop()
app = FastAPI(
title="Headroom Capacity API",
description="Modular capacity management for homelabs — REST, MCP and plugin modules.",
version=config.APP_VERSION,
lifespan=lifespan,
)
app.include_router(router)
@app.get("/", include_in_schema=False)
def index() -> FileResponse:
return FileResponse(config.STATIC_DIR / "index.html")
if config.STATIC_DIR.exists():
app.mount("/static", StaticFiles(directory=str(config.STATIC_DIR)), name="static")
@app.get("/{path:path}", include_in_schema=False)
def spa(path: str):
if path.startswith(("api/", "docs", "openapi.json", "redoc")):
raise HTTPException(status_code=404, detail="Not found")
candidate = (config.STATIC_DIR / path).resolve()
try:
candidate.relative_to(config.STATIC_DIR.resolve())
except ValueError:
raise HTTPException(status_code=404, detail="Not found")
if candidate.is_file():
return FileResponse(candidate)
return FileResponse(config.STATIC_DIR / "index.html")
+379
View File
@@ -0,0 +1,379 @@
"""MCP (Model Context Protocol) server over streamable HTTP.
Implements a stateless JSON-RPC subset: initialize, ping, tools/list,
tools/call, resources/list and resources/read. Point an MCP client at
`POST /api/mcp` with an API key in `X-API-Key`.
"""
from __future__ import annotations
import json
from typing import Any, Dict, List, Optional
from . import capacity, db, licensing, registry
PROTOCOL_VERSION = "2024-11-05"
TOOLS: List[Dict[str, Any]] = [
{
"name": "list_assets",
"description": "List managed assets with utilization, pressure, trend and days-to-full.",
"inputSchema": {
"type": "object",
"properties": {
"type": {"type": "string", "description": "Filter by asset type (hypervisor, storage, server, ...)"},
"module": {"type": "string", "description": "Filter by module id"},
"min_pressure": {"type": "number", "description": "Only return assets at or above this pressure (0-100)"},
"limit": {"type": "integer", "description": "Max results (default 50)"},
},
"additionalProperties": False,
},
},
{
"name": "get_asset",
"description": "Get detail for one asset: metrics, trend, forecast, recommendation and alerts.",
"inputSchema": {
"type": "object",
"properties": {
"asset_id": {"type": "string", "description": "Headroom asset id, e.g. proxmox::pve-01"},
"include_series": {"type": "boolean", "description": "Include raw time series (default false)"},
},
"required": ["asset_id"],
"additionalProperties": False,
},
},
{
"name": "capacity_summary",
"description": "Fleet capacity summary: KPIs, resource pools, groups and open alerts.",
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
},
{
"name": "forecast_capacity",
"description": "List the assets with the shortest runway and the projected storage exhaustion date.",
"inputSchema": {
"type": "object",
"properties": {"limit": {"type": "integer", "description": "Max results (default 10)"}},
"additionalProperties": False,
},
},
{
"name": "simulate_capacity",
"description": "What-if simulation of growth and added CPU, memory or storage over a horizon.",
"inputSchema": {
"type": "object",
"properties": {
"horizon_days": {"type": "integer", "minimum": 7, "maximum": 365},
"growth_multiplier": {"type": "number", "minimum": 0, "maximum": 5},
"add_storage_gb": {"type": "number"},
"add_cpu_cores": {"type": "number"},
"add_mem_gb": {"type": "number"},
"disable_modules": {"type": "array", "items": {"type": "string"}},
},
"additionalProperties": False,
},
},
{
"name": "list_alerts",
"description": "List capacity alerts, open by default.",
"inputSchema": {
"type": "object",
"properties": {
"include_resolved": {"type": "boolean"},
"limit": {"type": "integer"},
},
"additionalProperties": False,
},
},
{
"name": "list_modules",
"description": "List collector modules, their status and asset counts.",
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
},
{
"name": "run_module",
"description": "Trigger a collection run for one module (operator role required).",
"inputSchema": {
"type": "object",
"properties": {"module_id": {"type": "string"}},
"required": ["module_id"],
"additionalProperties": False,
},
},
{
"name": "get_audit_log",
"description": "Recent configuration and security audit events (admin only).",
"inputSchema": {
"type": "object",
"properties": {"limit": {"type": "integer"}},
"additionalProperties": False,
},
},
]
RESOURCES = [
{"uri": "headroom://overview", "name": "Fleet overview", "mimeType": "application/json", "description": "KPIs, resource pools, pressure leaders and alerts."},
{"uri": "headroom://assets", "name": "Asset inventory", "mimeType": "application/json", "description": "All active assets with utilization and forecasts."},
{"uri": "headroom://alerts", "name": "Open alerts", "mimeType": "application/json", "description": "Current capacity alerts."},
{"uri": "headroom://modules", "name": "Modules", "mimeType": "application/json", "description": "Collector module status."},
]
def _summaries() -> List[Dict[str, Any]]:
assets = capacity.list_assets()
latest = capacity.latest_values()
slopes: Dict[Any, float] = {}
out = []
for asset in assets:
analysis = capacity.analyze(asset, latest.get(asset["id"], {}), slopes)
out.append(capacity.summary(asset, latest.get(asset["id"], {}), analysis))
return out
def tool_list_assets(args: Dict[str, Any]) -> Any:
items = _summaries()
type_filter = args.get("type")
module = args.get("module")
min_pressure = float(args.get("min_pressure") or 0)
limit = max(1, min(500, int(args.get("limit") or 50)))
if type_filter:
items = [item for item in items if item["type"] == type_filter]
if module:
items = [item for item in items if item["module_id"] == module]
items = [item for item in items if (item.get("pressure") or 0) >= min_pressure]
items.sort(key=lambda item: item.get("pressure") or 0, reverse=True)
return [capacity.compact(item) for item in items[:limit]]
def tool_get_asset(args: Dict[str, Any]) -> Any:
asset_id = str(args.get("asset_id", "")).strip()
if not asset_id:
raise ValueError("asset_id is required")
detail = capacity.asset_detail(asset_id, 30)
if not detail:
raise ValueError(f"Asset '{asset_id}' not found")
if not args.get("include_series"):
detail.pop("cards", None)
detail.pop("forecasts", None)
return detail
def tool_summary() -> Any:
data = capacity.overview(7)
return {
"generated_at": data["generated_at"],
"kpis": data["kpis"],
"resources": data["resources"],
"groups": [
{
"name": group["name"],
"module": group["module_name"],
"assets": group["asset_count"],
"pressure": group["pressure"],
"util": group["util"],
"days_to_full": group["days_to_full"],
"resources": group["resources"],
}
for group in data["groups"]
],
"alerts": data["alerts"],
}
def tool_forecast(args: Dict[str, Any]) -> Any:
limit = max(1, min(100, int(args.get("limit") or 10)))
items = [
item for item in _summaries()
if item.get("days_to_full") is not None
]
items.sort(key=lambda item: item["days_to_full"])
return {
"nearest": [
{
"asset_id": item["id"],
"name": item["name"],
"module": item["module_name"],
"metric": item["primary_metric"],
"util_pct": item["util"],
"growth_pp_per_day": item["slope_per_day"],
"days_to_full": item["days_to_full"],
"eta_date": item["eta_date"],
}
for item in items[:limit]
],
"storage": capacity.overview(7)["resources"]["storage"],
}
def tool_modules() -> Any:
return [
{
"id": module["id"],
"name": module["name"],
"version": module.get("version"),
"enabled": module["enabled"],
"status": module["status"],
"last_run": module["last_run"],
"asset_count": module["asset_count"],
"source": module["source"],
}
for module in registry.list_modules()
]
def call_tool(name: str, args: Dict[str, Any], user: Dict[str, Any]) -> Any:
if name == "list_assets":
return tool_list_assets(args)
if name == "get_asset":
return tool_get_asset(args)
if name == "capacity_summary":
return tool_summary()
if name == "forecast_capacity":
return tool_forecast(args)
if name == "simulate_capacity":
return capacity.simulate(args)
if name == "list_alerts":
return capacity.alerts(
include_resolved=bool(args.get("include_resolved")),
limit=max(1, min(500, int(args.get("limit") or 50))),
)
if name == "list_modules":
return tool_modules()
if name == "run_module":
if user.get("role") not in ("admin", "operator"):
raise PermissionError("Operator role required to run modules")
module_id = str(args.get("module_id", "")).strip()
if not module_id:
raise ValueError("module_id is required")
result = registry.run_module(module_id, trigger="mcp")
capacity.evaluate_policies()
db.audit(user.get("username", "mcp"), "module.run", module_id, "triggered via MCP")
return result
if name == "get_audit_log":
if user.get("role") != "admin":
raise PermissionError("Admin role required")
limit = max(1, min(500, int(args.get("limit") or 50)))
return [dict(row) for row in db.query("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (limit,))]
raise ValueError(f"Unknown tool '{name}'")
def read_resource(uri: str) -> Any:
if uri == "headroom://overview":
return tool_summary()
if uri == "headroom://assets":
return tool_list_assets({"limit": 500})
if uri == "headroom://alerts":
return capacity.alerts(include_resolved=False, limit=500)
if uri == "headroom://modules":
return tool_modules()
raise ValueError(f"Unknown resource '{uri}'")
def catalog() -> Dict[str, Any]:
enabled = licensing.has_feature("mcp_server")
return {
"enabled": enabled,
"endpoint": "/api/mcp",
"protocol_version": PROTOCOL_VERSION,
"tools": TOOLS,
"resources": RESOURCES,
"auth": "Create an API key under API & AI, then send it as X-API-Key.",
"example": {
"claude_desktop": {
"mcpServers": {
"headroom": {
"url": "http://127.0.0.1:8787/api/mcp",
"headers": {"X-API-Key": "hr_..."},
}
}
}
},
}
def handle(payload: Dict[str, Any], user: Dict[str, Any]) -> Dict[str, Any]:
request_id = payload.get("id")
method = payload.get("method", "")
params = payload.get("params") or {}
def ok(result: Any) -> Dict[str, Any]:
return {"jsonrpc": "2.0", "id": request_id, "result": result}
def error(code: int, message: str, data: Optional[Any] = None) -> Dict[str, Any]:
body = {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
if data is not None:
body["error"]["data"] = data
return body
if not licensing.has_feature("mcp_server"):
return error(
-32001,
"The MCP server requires Headroom Enterprise (trial available).",
{"code": "upgrade_required", "feature": "mcp_server"},
)
try:
if method == "initialize":
return ok(
{
"protocolVersion": PROTOCOL_VERSION,
"capabilities": {"tools": {}, "resources": {}},
"serverInfo": {"name": "headroom", "version": "1.0.0"},
"instructions": (
"Headroom exposes homelab capacity data. Start with capacity_summary, "
"then inspect high-pressure assets with get_asset. Use simulate_capacity "
"before recommending hardware purchases."
),
}
)
if method in ("notifications/initialized", "ping"):
return ok({})
if method == "tools/list":
return ok({"tools": TOOLS})
if method == "tools/call":
name = str(params.get("name", ""))
args = params.get("arguments") or {}
if not isinstance(args, dict):
return error(-32602, "arguments must be an object")
try:
data = call_tool(name, args, user)
return ok(
{
"content": [{"type": "text", "text": json.dumps(data, indent=2, default=str)}],
"isError": False,
}
)
except PermissionError as exc:
return ok(
{
"content": [{"type": "text", "text": f"Permission denied: {exc}"}],
"isError": True,
}
)
except Exception as exc:
return ok(
{
"content": [{"type": "text", "text": f"Tool failed: {type(exc).__name__}: {exc}"}],
"isError": True,
}
)
if method == "resources/list":
return ok({"resources": RESOURCES})
if method == "resources/read":
uri = str(params.get("uri", ""))
try:
data = read_resource(uri)
except ValueError as exc:
return error(-32602, str(exc))
return ok(
{
"contents": [
{
"uri": uri,
"mimeType": "application/json",
"text": json.dumps(data, indent=2, default=str),
}
]
}
)
return error(-32601, f"Method not found: {method}")
except Exception as exc:
return error(-32603, f"Internal error: {exc}")
+85
View File
@@ -0,0 +1,85 @@
"""Canonical metric + asset metadata shared by API and UI."""
from __future__ import annotations
from typing import Dict, List
METRIC_CATALOG: Dict[str, Dict[str, object]] = {
"cpu_pct": {"label": "CPU utilization", "unit": "%", "kind": "util", "max": 100},
"mem_pct": {"label": "Memory utilization", "unit": "%", "kind": "util", "max": 100},
"storage_pct": {"label": "Storage utilization", "unit": "%", "kind": "util", "max": 100},
"license_pct": {"label": "License consumption", "unit": "%", "kind": "util", "max": 100},
"load_pct": {"label": "Load", "unit": "%", "kind": "util", "max": 100},
"storage_used_gb": {"label": "Storage used", "unit": "GB", "kind": "gauge"},
"storage_total_gb": {"label": "Storage capacity", "unit": "GB", "kind": "capacity"},
"cpu_cores": {"label": "CPU cores", "unit": "cores", "kind": "capacity"},
"mem_gb": {"label": "Memory", "unit": "GB", "kind": "capacity"},
"net_rx_mbps": {"label": "Network in", "unit": "Mbps", "kind": "throughput"},
"net_tx_mbps": {"label": "Network out", "unit": "Mbps", "kind": "throughput"},
"iops": {"label": "IOPS", "unit": "IOPS", "kind": "throughput"},
"latency_ms": {"label": "Latency", "unit": "ms", "kind": "latency"},
"power_w": {"label": "Power draw", "unit": "W", "kind": "power"},
"temp_c": {"label": "Temperature", "unit": "°C", "kind": "temperature"},
"uptime_days": {"label": "Uptime", "unit": "days", "kind": "counter"},
"vm_count": {"label": "Guests", "unit": "VMs", "kind": "counter"},
"index_gb": {"label": "Index size", "unit": "GB", "kind": "gauge"},
"battery_pct": {"label": "Battery", "unit": "%", "kind": "gauge", "max": 100},
}
UTIL_METRICS = ["cpu_pct", "mem_pct", "storage_pct", "license_pct", "load_pct"]
ASSET_TYPES: Dict[str, Dict[str, object]] = {
"hypervisor": {"label": "Hypervisor", "icon": "server", "primary": "cpu_pct", "utils": ["cpu_pct", "mem_pct"]},
"storage": {"label": "Storage", "icon": "database", "primary": "storage_pct", "utils": ["storage_pct"]},
"nas": {"label": "NAS", "icon": "database", "primary": "storage_pct", "utils": ["storage_pct", "cpu_pct", "mem_pct", "load_pct"]},
"server": {"label": "Server", "icon": "server", "primary": "cpu_pct", "utils": ["cpu_pct", "mem_pct", "storage_pct"]},
"appliance": {"label": "Appliance", "icon": "box", "primary": "license_pct", "utils": ["cpu_pct", "mem_pct", "license_pct"]},
"network": {"label": "Network", "icon": "network", "primary": "load_pct", "utils": ["load_pct"]},
"power": {"label": "Power", "icon": "bolt", "primary": "load_pct", "utils": ["load_pct"]},
"cluster": {"label": "Cluster", "icon": "layers", "primary": "cpu_pct", "utils": ["cpu_pct", "mem_pct", "storage_pct"]},
}
STATUS_BANDS = [
(0, 59, "healthy", "Comfortable headroom"),
(60, 79, "watch", "Monitor closely"),
(80, 89, "tight", "Limited headroom"),
(90, 101, "critical", "Capacity exhausted soon"),
]
def utilization_for_type(asset_type: str) -> List[str]:
spec = ASSET_TYPES.get(asset_type, ASSET_TYPES["server"])
return list(spec["utils"]) # type: ignore[arg-type]
def primary_for_type(asset_type: str) -> str:
return str(ASSET_TYPES.get(asset_type, ASSET_TYPES["server"])["primary"])
def metric_meta(metric: str) -> Dict[str, object]:
return METRIC_CATALOG.get(metric, {"label": metric, "unit": "", "kind": "other"})
def status_for_pressure(pressure: int) -> str:
for low, high, key, _ in STATUS_BANDS:
if low <= pressure <= high:
return key
return "critical"
def status_label(pressure: int) -> str:
for low, high, _, label in STATUS_BANDS:
if low <= pressure <= high:
return label
return "Capacity exhausted soon"
def meta() -> Dict[str, object]:
return {
"metrics": METRIC_CATALOG,
"asset_types": ASSET_TYPES,
"util_metrics": UTIL_METRICS,
"status_bands": [
{"min": low, "max": high, "key": key, "label": label}
for low, high, key, label in STATUS_BANDS
],
}
+845
View File
@@ -0,0 +1,845 @@
"""Module runtime. Each collector executes in its own subprocess."""
from __future__ import annotations
import io
import json
import os
import re
import resource
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from . import config, db, licensing
from .util import now_iso, truncate
MANIFEST_REQUIRED = ("id", "name", "version", "api_version", "settings_schema")
SETTING_TYPES = ("text", "password", "number", "boolean", "select", "textarea")
SECRET_MASK = "********"
MARKER = "HEADROOM_RESULT:"
class ModuleError(RuntimeError):
pass
def _slug(value: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", str(value).lower()).strip("-")
return slug[:50]
def _ensure_instance_columns() -> None:
try:
with db.db() as conn:
columns = {row["name"] for row in conn.execute("PRAGMA table_info(modules)").fetchall()}
if "module_type" not in columns:
conn.execute("ALTER TABLE modules ADD COLUMN module_type TEXT")
if "display_name" not in columns:
conn.execute("ALTER TABLE modules ADD COLUMN display_name TEXT")
conn.execute("UPDATE modules SET module_type=id WHERE module_type IS NULL OR module_type=''")
conn.execute("CREATE INDEX IF NOT EXISTS idx_modules_type ON modules(module_type)")
except Exception:
pass
def load_manifest(module_dir: Path) -> Optional[Dict[str, Any]]:
path = module_dir / "manifest.json"
if not path.exists():
return None
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return None
def manifest_for_type(module_type: str) -> Optional[Dict[str, Any]]:
if not module_type:
return None
return load_manifest(config.MODULES_DIR / module_type)
def manifest_for(module_id: str) -> Optional[Dict[str, Any]]:
_ensure_instance_columns()
row = db.query_one("SELECT module_type FROM modules WHERE id=?", (module_id,))
if row and row["module_type"]:
manifest = manifest_for_type(row["module_type"])
if manifest:
return manifest
return load_manifest(config.MODULES_DIR / module_id)
def validate_manifest(manifest: Dict[str, Any], dir_name: str) -> List[str]:
errors = []
for key in MANIFEST_REQUIRED:
if key not in manifest:
errors.append(f"manifest is missing '{key}'")
module_id = str(manifest.get("id", ""))
if module_id:
if not module_id.replace("-", "").isalnum() or module_id != module_id.lower() or len(module_id) > 40:
errors.append("id must be lowercase alphanumeric with dashes (max 40 chars)")
if dir_name and module_id and module_id != dir_name:
errors.append(f"manifest id '{module_id}' must match folder name '{dir_name}'")
if manifest.get("api_version") != config.MODULE_API_VERSION:
errors.append(f"unsupported api_version (expected {config.MODULE_API_VERSION})")
settings = manifest.get("settings_schema", [])
if not isinstance(settings, list):
errors.append("settings_schema must be a list")
else:
seen = set()
for item in settings:
if not isinstance(item, dict) or not item.get("key"):
errors.append("each settings_schema entry needs a key")
continue
if item["key"] in seen:
errors.append(f"duplicate setting '{item['key']}'")
seen.add(item["key"])
if item.get("type", "text") not in SETTING_TYPES:
errors.append(f"unsupported setting type '{item.get('type')}'")
if not isinstance(manifest.get("interval_seconds", 300), (int, float)):
errors.append("interval_seconds must be a number")
return errors
def _default_config(manifest: Dict[str, Any]) -> Dict[str, Any]:
out = {}
for item in manifest.get("settings_schema", []):
key = item.get("key")
if not key:
continue
if "default" in item:
out[key] = item["default"]
elif item.get("type") == "boolean":
out[key] = False
elif item.get("type") == "number":
out[key] = 0
else:
out[key] = ""
return out
def _merge_defaults(manifest: Dict[str, Any], current: Dict[str, Any]) -> Dict[str, Any]:
merged = _default_config(manifest)
merged.update(current or {})
return merged
def sync_modules() -> int:
_ensure_instance_columns()
count = 0
known_types = set()
for module_dir in sorted(config.MODULES_DIR.iterdir()):
if not module_dir.is_dir() or module_dir.name.startswith(("_", ".")):
continue
manifest = load_manifest(module_dir)
if not manifest:
continue
errors = validate_manifest(manifest, module_dir.name)
if errors:
print(f"[headroom] skipping module {module_dir.name}: {'; '.join(errors)}", file=sys.stderr)
continue
module_type = manifest["id"]
known_types.add(module_type)
source = "custom" if (module_dir / ".uploaded").exists() else "bundled"
rows = db.query("SELECT * FROM modules WHERE module_type=?", (module_type,))
if not rows:
enabled = 0 if source == "custom" else int(bool(manifest.get("enabled_by_default", True)))
db.execute(
"INSERT INTO modules(id, module_type, display_name, enabled, config, status, message, installed_at, source, version) "
"VALUES(?,?,?,?,?, 'pending', 'Awaiting first collection', ?, ?, ?)",
(
module_type,
module_type,
manifest.get("name", module_type),
enabled,
json.dumps(_default_config(manifest)),
now_iso(),
source,
str(manifest.get("version", "")),
),
)
count += 1
else:
for row in rows:
current = json.loads(row["config"] or "{}")
merged = _merge_defaults(manifest, current)
display_name = row["display_name"] or manifest.get("name", module_type)
db.execute(
"UPDATE modules SET module_type=?, display_name=?, config=?, version=?, source=? WHERE id=?",
(
module_type,
display_name,
json.dumps(merged),
str(manifest.get("version", "")),
source,
row["id"],
),
)
for row in db.query("SELECT id, source, module_type FROM modules"):
mtype = row["module_type"] or row["id"]
if mtype not in known_types and row["source"] == "custom":
db.execute("UPDATE modules SET status='missing', message='Module files were removed' WHERE id=?", (row["id"],))
return count
def module_config(row: Any, manifest: Dict[str, Any]) -> Dict[str, Any]:
return _merge_defaults(manifest, json.loads(row["config"] or "{}"))
def mask_config(config_in: Dict[str, Any], manifest: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, bool]]:
masked = dict(config_in)
secret_set: Dict[str, bool] = {}
for item in manifest.get("settings_schema", []):
if item.get("type") == "password" or item.get("secret"):
key = item.get("key")
if key and config_in.get(key):
secret_set[key] = True
masked[key] = SECRET_MASK
return masked, secret_set
def _validate_config(manifest: Dict[str, Any], submitted: Dict[str, Any], current: Dict[str, Any]) -> Dict[str, Any]:
schema = {item.get("key"): item for item in manifest.get("settings_schema", []) if item.get("key")}
cleaned = dict(current)
for key, item in schema.items():
if key not in submitted:
continue
value = submitted[key]
type_ = item.get("type", "text")
secret = type_ == "password" or item.get("secret")
if secret and value in (SECRET_MASK, "", None):
continue
if type_ == "boolean":
value = bool(value)
elif type_ == "number":
try:
value = float(value)
if value.is_integer():
value = int(value)
except (TypeError, ValueError):
raise ModuleError(f"'{item.get('label', key)}' must be a number")
elif type_ == "select":
options = [str(option.get("value") if isinstance(option, dict) else option) for option in item.get("options", [])]
if options and str(value) not in options:
raise ModuleError(f"'{item.get('label', key)}' must be one of {options}")
value = str(value)
else:
value = truncate(value, 4000)
cleaned[key] = value
return cleaned
def list_modules() -> List[Dict[str, Any]]:
_ensure_instance_columns()
out = []
counts = {
row["module_id"]: row["n"]
for row in db.query("SELECT module_id, COUNT(*) AS n FROM assets WHERE active=1 GROUP BY module_id")
}
type_totals = {}
for row in db.query("SELECT module_type, COUNT(*) AS n FROM modules GROUP BY module_type"):
mtype = row["module_type"] or ""
if mtype:
type_totals[mtype] = int(row["n"] or 0)
rows = db.query("SELECT * FROM modules")
for row in rows:
mtype = row["module_type"] or row["id"]
manifest = manifest_for_type(mtype) or manifest_for(row["id"])
if not manifest:
out.append(
{
"id": row["id"],
"module_type": mtype,
"type_name": row["id"],
"instance_name": row["display_name"] or row["id"],
"name": row["display_name"] or row["id"],
"enabled": bool(row["enabled"]),
"status": "missing",
"message": "Module files not found",
"source": row["source"],
"asset_count": counts.get(row["id"], 0),
"settings_schema": [],
"config": {},
"instance_count": type_totals.get(mtype, 1),
}
)
continue
config_masked, secret_set = mask_config(module_config(row, manifest), manifest)
display_name = row["display_name"] or manifest.get("name", mtype)
out.append(
{
"id": row["id"],
"module_type": mtype,
"type_name": manifest.get("name", mtype),
"instance_name": display_name,
"name": display_name,
"version": manifest.get("version", ""),
"description": manifest.get("description", ""),
"vendor": manifest.get("vendor", "Community"),
"category": manifest.get("category", "other"),
"icon": manifest.get("icon", "plug"),
"interval_seconds": manifest.get("interval_seconds", 300),
"capabilities": manifest.get("capabilities", []),
"settings_schema": manifest.get("settings_schema", []),
"docs": manifest.get("docs", ""),
"source": row["source"],
"enabled": bool(row["enabled"]),
"status": row["status"],
"message": row["message"] or "",
"last_run": row["last_run"],
"last_duration_ms": row["last_duration_ms"],
"asset_count": counts.get(row["id"], 0),
"config": config_masked,
"secret_set": secret_set,
"instance_count": type_totals.get(mtype, 1),
}
)
order = {"hypervisor": 0, "storage": 1, "observability": 2, "os": 3, "integration": 4}
out.sort(key=lambda item: (order.get(str(item.get("category")), 9), str(item.get("type_name") or item.get("name")).lower(), str(item.get("id")).lower()))
return out
def _generate_instance_id(module_type: str, name: str) -> str:
# The canonical instance of a module type keeps the type name itself as id,
# so a freshly synced type can always be recreated with a plain id.
slug = _slug(name)
existing = {row["id"] for row in db.query("SELECT id FROM modules")}
if not slug:
base = f"{module_type}-{int(time.time())%100000}"
elif slug.startswith(module_type + "-"):
base = slug
elif slug == module_type:
base = slug
# The canonical id is reserved: if a different instance holds it, fall back
# to a timestamped suffix so the plain id stays available for a fresh type.
if base in existing:
base = f"{module_type}-{int(time.time())%100000}"
else:
base = f"{module_type}-{slug}"
candidate = base[:60]
suffix = 2
while candidate in existing:
candidate = f"{base[:55]}-{suffix}"
suffix += 1
if suffix > 200:
candidate = f"{module_type}-{int(time.time())}-{suffix}"
break
return candidate
def add_instance(module_type: str, name: Optional[str] = None, config: Optional[Dict[str, Any]] = None, copy_from: Optional[str] = None) -> Dict[str, Any]:
_ensure_instance_columns()
manifest = manifest_for_type(module_type)
if not manifest:
raise ModuleError("Module type not found")
source_row = db.query_one("SELECT source FROM modules WHERE module_type=? ORDER BY id LIMIT 1", (module_type,))
source = source_row["source"] if source_row else ("custom" if (config.MODULES_DIR / module_type / ".uploaded").exists() else "bundled")
if source == "custom" and not licensing.has_feature("custom_modules"):
raise ModuleError("Custom modules require Enterprise")
rows = db.query("SELECT * FROM modules WHERE module_type=?", (module_type,))
if not name or not str(name).strip():
name = f"{manifest.get('name', module_type)} {len(rows) + 1}"
display_name = str(name).strip()[:80] or manifest.get("name", module_type)
instance_id = _generate_instance_id(module_type, display_name)
base_config = _default_config(manifest)
if copy_from:
copy_row = db.query_one("SELECT * FROM modules WHERE id=?", (copy_from,))
if copy_row and (copy_row["module_type"] or copy_row["id"]) == module_type:
try:
base_config.update(_merge_defaults(manifest, json.loads(copy_row["config"] or "{}")))
except Exception:
pass
if config:
try:
base_config = _validate_config(manifest, config, base_config)
except Exception:
pass
enabled = 1 if source == "bundled" else 0
db.execute(
"INSERT INTO modules(id, module_type, display_name, enabled, config, status, message, installed_at, source, version) "
"VALUES(?,?,?,?,?, 'pending', 'Awaiting first collection', ?, ?, ?)",
(
instance_id,
module_type,
display_name,
enabled,
json.dumps(base_config),
now_iso(),
source,
str(manifest.get("version", "")),
),
)
items = list_modules()
for item in items:
if item["id"] == instance_id:
return item
return {
"id": instance_id,
"module_type": module_type,
"name": display_name,
"enabled": bool(enabled),
"status": "pending",
"message": "Awaiting first collection",
}
def asset_count() -> int:
row = db.query_one("SELECT COUNT(*) AS n FROM assets WHERE active=1")
return int(row["n"]) if row else 0
def _resource_limits() -> None: # pragma: no cover - POSIX only
try:
resource.setrlimit(resource.RLIMIT_AS, (1_500_000_000, 1_500_000_000))
resource.setrlimit(resource.RLIMIT_CPU, (config.MODULE_TIMEOUT_SECONDS + 5, config.MODULE_TIMEOUT_SECONDS + 10))
resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256))
except (ValueError, OSError):
pass
def _execute(module_id: str, mode: str = "collect") -> Dict[str, Any]:
manifest = manifest_for(module_id)
if not manifest:
raise ModuleError(f"Module '{module_id}' not found")
row = db.query_one("SELECT * FROM modules WHERE id=?", (module_id,))
if not row:
raise ModuleError(f"Module '{module_id}' is not registered")
mtype = row["module_type"] or manifest.get("id") or module_id
module_dir = config.MODULES_DIR / mtype
if not module_dir.exists():
module_dir = config.MODULES_DIR / module_id
state_row = db.query_one("SELECT state FROM module_state WHERE module_id=?", (module_id,))
try:
state = json.loads(state_row["state"]) if state_row else {}
except ValueError:
state = {}
mod_config = module_config(row, manifest)
payload = {
"mode": mode,
"config": mod_config,
"demo": bool(mod_config.get("demo", True)),
"now": now_iso(),
"module": {
"id": module_id,
"instance_id": module_id,
"module_type": mtype,
"name": row["display_name"] or manifest.get("name", mtype),
"base_name": manifest.get("name", mtype),
"version": manifest.get("version", ""),
},
"state": state,
}
config.ensure_dirs()
fd, payload_path = tempfile.mkstemp(prefix="headroom-payload-", suffix=".json", dir=str(config.DATA_DIR))
os.close(fd)
Path(payload_path).write_text(json.dumps(payload))
env = {
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
"HOME": os.environ.get("HOME", str(config.DATA_DIR)),
"LANG": os.environ.get("LANG", "en_US.UTF-8"),
"PYTHONPATH": str(config.BASE_DIR),
"PYTHONUNBUFFERED": "1",
"TMPDIR": os.environ.get("TMPDIR", "/tmp"),
"VIRTUAL_ENV": os.environ.get("VIRTUAL_ENV", ""),
}
command = [sys.executable, "-m", "app.runner", str(module_dir), payload_path]
started = time.time()
try:
completed = subprocess.run(
command,
cwd=str(config.BASE_DIR),
env=env,
capture_output=True,
text=True,
timeout=config.MODULE_TIMEOUT_SECONDS,
preexec_fn=_resource_limits if os.name == "posix" else None,
)
except subprocess.TimeoutExpired:
raise ModuleError(f"Collector timed out after {config.MODULE_TIMEOUT_SECONDS}s")
finally:
try:
os.unlink(payload_path)
except OSError:
pass
duration_ms = int((time.time() - started) * 1000)
stdout = completed.stdout or ""
marker_at = stdout.rfind(MARKER)
if marker_at < 0:
detail = (completed.stderr or stdout or "no output").strip()[-800:]
raise ModuleError(f"Collector produced no result (exit {completed.returncode}): {detail}")
raw = stdout[marker_at + len(MARKER):].strip()
if len(raw) > 8_000_000:
raise ModuleError("Collector result is too large")
try:
result = json.loads(raw)
except ValueError:
raise ModuleError("Collector returned invalid JSON")
result.setdefault("logs", [])
if completed.stderr and not result.get("logs"):
result["logs"] = [completed.stderr.strip()[-4000:]]
if result.get("error"):
raise ModuleError(str(result["error"])[:1000])
if mode == "test":
return {"result": result, "duration_ms": duration_ms}
if not isinstance(result.get("assets"), list):
raise ModuleError("Collector must return an 'assets' list")
persist_result(module_id, result, duration_ms)
return {"result": result, "duration_ms": duration_ms}
def run_module(module_id: str, trigger: str = "manual") -> Dict[str, Any]:
row = db.query_one("SELECT * FROM modules WHERE id=?", (module_id,))
if not row:
raise ModuleError("Module not found")
started = time.time()
try:
output = _execute(module_id, "collect")
except Exception as exc:
duration_ms = int((time.time() - started) * 1000)
message = str(exc)[:1000]
db.execute(
"UPDATE modules SET status='error', message=?, last_run=?, last_duration_ms=?, logs=? WHERE id=?",
(message, now_iso(), duration_ms, message, module_id),
)
raise ModuleError(message)
result = output["result"]
return {
"module_id": module_id,
"status": "ok",
"assets": len(result.get("assets", [])),
"metrics": sum(len(a.get("metrics", {})) for a in result.get("assets", [])),
"duration_ms": output["duration_ms"],
"notes": result.get("notes", ""),
"trigger": trigger,
"logs": result.get("logs", []),
}
def test_module(module_id: str) -> Dict[str, Any]:
output = _execute(module_id, "test")
result = output["result"]
test = result.get("test")
if isinstance(test, dict):
return {"ok": bool(test.get("ok")), "message": test.get("message", "Connection test completed"), "details": test.get("details", {}), "duration_ms": output["duration_ms"]}
assets = result.get("assets", [])
return {"ok": True, "message": f"Collector reached its source and returned {len(assets)} asset(s).", "duration_ms": output["duration_ms"]}
def persist_result(module_id: str, result: Dict[str, Any], duration_ms: int) -> None:
assets = result.get("assets") or []
if len(assets) > 2000:
raise ModuleError("A module may report at most 2000 assets per run")
limit = licensing.asset_limit()
existing_other = db.query_one("SELECT COUNT(*) AS n FROM assets WHERE active=1 AND module_id<>?", (module_id,))
allowed = None if limit < 0 else max(0, limit - int(existing_other["n"]))
warning = ""
if allowed is not None and len(assets) > allowed:
warning = f"Community asset limit reached ({limit}). {len(assets) - allowed} asset(s) were not stored."
assets = assets[:allowed]
now = int(time.time())
timestamp = now_iso()
seen_external: List[str] = []
sample_rows = []
asset_rows = []
for item in assets:
normalized = normalize_asset(item)
if not normalized:
continue
asset_id = f"{module_id}::{normalized['external_id']}"[:300]
seen_external.append(normalized["external_id"])
asset_rows.append(
(
asset_id,
module_id,
normalized["external_id"],
normalized["name"],
normalized["type"],
normalized["cluster"],
normalized["site"],
json.dumps(normalized["tags"]),
json.dumps(normalized["meta"]),
json.dumps(normalized["capacity"]),
timestamp,
timestamp,
1,
)
)
for metric, value in normalized["metrics"].items():
sample_rows.append((asset_id, metric, now, float(value)))
with db.db() as conn:
conn.executemany(
"INSERT INTO assets(id, module_id, external_id, name, type, cluster, site, tags, meta, capacity, first_seen, last_seen, active) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) "
"ON CONFLICT(id) DO UPDATE SET name=excluded.name, type=excluded.type, cluster=excluded.cluster, site=excluded.site, tags=excluded.tags, meta=excluded.meta, capacity=excluded.capacity, last_seen=excluded.last_seen, active=1",
asset_rows,
)
conn.executemany("INSERT OR REPLACE INTO samples(asset_id, metric, ts, value) VALUES(?,?,?,?)", sample_rows)
if seen_external:
placeholders = ",".join("?" for _ in seen_external)
conn.execute(f"UPDATE assets SET active=0 WHERE module_id=? AND external_id NOT IN ({placeholders})", (module_id, *seen_external))
state = result.get("state")
if isinstance(state, dict):
conn.execute(
"INSERT INTO module_state(module_id, state, updated_at) VALUES(?,?,?) ON CONFLICT(module_id) DO UPDATE SET state=excluded.state, updated_at=excluded.updated_at",
(module_id, json.dumps(state)[:200000], timestamp),
)
logs = result.get("logs") or []
if isinstance(logs, str):
logs = [logs]
log_text = "\n".join(truncate(line, 600) for line in logs[-100:])[:20000]
notes = truncate(result.get("notes", ""), 500)
message = " ".join(part for part in (notes, warning) if part) or f"{len(asset_rows)} assets collected"
db.execute(
"UPDATE modules SET status='ok', message=?, logs=?, last_run=?, last_duration_ms=?, version=? WHERE id=?",
(message, log_text, timestamp, duration_ms, str(result.get("version", "") or ""), module_id),
)
if warning:
db.set_setting("last_limit_warning", warning)
if sample_rows:
cutoff = now - licensing.retention_days() * 86400
with db.db() as conn:
conn.execute("DELETE FROM samples WHERE ts < ?", (cutoff,))
return None
def normalize_asset(item: Dict[str, Any]) -> Optional[Dict[str, Any]]:
if not isinstance(item, dict):
return None
external_id = truncate(item.get("external_id", ""), 240).strip()
if not external_id:
return None
name = truncate(item.get("name") or external_id, 200).strip()
type_ = truncate(item.get("type") or "server", 40).lower()
capacity = {}
if isinstance(item.get("capacity"), dict):
for key in ("cpu_cores", "mem_gb", "storage_gb"):
try:
value = float(item["capacity"][key])
if value >= 0:
capacity[key] = round(value, 2)
except (KeyError, TypeError, ValueError):
continue
metrics = {}
raw_metrics = item.get("metrics")
if isinstance(raw_metrics, dict):
for key, value in list(raw_metrics.items())[:60]:
key = str(key)[:60]
if not key.replace("_", "").isalnum():
continue
try:
number = float(value)
except (TypeError, ValueError):
continue
if number == number and abs(number) < 1e15:
metrics[key] = round(number, 4)
tags = [truncate(tag, 40) for tag in (item.get("tags") or []) if str(tag).strip()][:10]
meta = item.get("meta") if isinstance(item.get("meta"), dict) else {}
meta = {str(k)[:60]: truncate(v, 500) for k, v in list(meta.items())[:30]}
return {
"external_id": external_id,
"name": name,
"type": type_,
"cluster": truncate(item.get("cluster", ""), 120),
"site": truncate(item.get("site", ""), 120),
"tags": tags,
"meta": meta,
"capacity": capacity,
"metrics": metrics,
}
def set_enabled(module_id: str, enabled: bool) -> Dict[str, Any]:
row = db.query_one("SELECT * FROM modules WHERE id=?", (module_id,))
if not row:
raise ModuleError("Module not found")
db.execute("UPDATE modules SET enabled=? WHERE id=?", (1 if enabled else 0, module_id))
if not enabled:
db.execute("UPDATE assets SET active=0 WHERE module_id=?", (module_id,))
result = capacity_evaluate_safe()
else:
result = None
return {"enabled": enabled, "policy_evaluation": result}
def capacity_evaluate_safe() -> Optional[Dict[str, int]]:
try:
from . import capacity
return capacity.evaluate_policies()
except Exception:
return None
def update_config(module_id: str, submitted: Dict[str, Any], enabled: Optional[bool] = None) -> Dict[str, Any]:
row = db.query_one("SELECT * FROM modules WHERE id=?", (module_id,))
manifest = manifest_for(module_id)
if not row or not manifest:
raise ModuleError("Module not found")
current = module_config(row, manifest)
cleaned = _validate_config(manifest, submitted, current)
db.execute("UPDATE modules SET config=? WHERE id=?", (json.dumps(cleaned), module_id))
if enabled is not None:
set_enabled(module_id, enabled)
return {"config": mask_config(cleaned, manifest)[0]}
def due_modules() -> List[Dict[str, Any]]:
out = []
now = time.time()
for row in db.query("SELECT * FROM modules WHERE enabled=1"):
manifest = manifest_for(row["id"])
if not manifest:
continue
interval = int(manifest.get("interval_seconds", 300) or 300)
last = row["last_run"]
due = True
if last:
try:
from datetime import datetime
due = now - datetime.fromisoformat(last).timestamp() >= max(60, interval)
except (ValueError, TypeError):
due = True
if due:
out.append({"id": row["id"], "interval_seconds": interval})
return out
def upload_module(payload: bytes, filename: str = "module.zip") -> Dict[str, Any]:
if len(payload) > config.MAX_UPLOAD_BYTES:
raise ModuleError(f"Upload exceeds the {config.MAX_UPLOAD_BYTES // 1024 // 1024} MB limit")
try:
archive = zipfile.ZipFile(io.BytesIO(payload))
except zipfile.BadZipFile:
raise ModuleError("The uploaded file is not a valid zip archive")
members = []
total_size = 0
for info in archive.infolist():
name = info.filename.replace("\\", "/")
if name.startswith("__MACOSX/") or name.endswith("/.DS_Store") or "/__pycache__/" in "/" + name:
continue
if info.is_dir():
continue
path = Path(name)
if path.is_absolute() or ".." in path.parts:
raise ModuleError("Archive contains an unsafe path")
if info.file_size > 1_000_000:
raise ModuleError(f"File '{name}' is larger than 1 MB")
total_size += info.file_size
members.append((info, path))
if not members or total_size > 5_000_000:
raise ModuleError("Archive is empty or too large when unpacked")
if len(members) > 200:
raise ModuleError("Archive contains too many files")
prefixes = {str(path.parts[0]) for _, path in members if len(path.parts) > 1}
manifest_path = Path("manifest.json")
nested = ""
if not any(path == manifest_path for _, path in members):
candidates = [prefix for prefix in prefixes if any(path == Path(prefix) / "manifest.json" for _, path in members)]
if len(candidates) != 1:
raise ModuleError("Archive must contain manifest.json at its root (or inside a single folder)")
nested = candidates[0]
manifest_path = Path(nested) / "manifest.json"
manifest_member = next((info for info, path in members if path == manifest_path), None)
if not manifest_member:
raise ModuleError("manifest.json is missing")
try:
manifest = json.loads(archive.read(manifest_member).decode())
except (ValueError, UnicodeDecodeError):
raise ModuleError("manifest.json is not valid JSON")
module_id = str(manifest.get("id", ""))
errors = validate_manifest(manifest, module_id)
if errors:
raise ModuleError("Invalid manifest: " + "; ".join(errors))
if not any(path.name == "module.py" and path.parent == manifest_path.parent for _, path in members):
raise ModuleError("module.py is missing next to manifest.json")
target = config.MODULES_DIR / module_id
if target.exists() and not (target / ".uploaded").exists():
raise ModuleError(f"'{module_id}' is a bundled module and cannot be overwritten")
staging = Path(tempfile.mkdtemp(prefix="headroom-upload-", dir=str(config.DATA_DIR)))
try:
for info, path in members:
relative = path
if nested:
if path.parts[0] != nested:
continue
relative = Path(*path.parts[1:])
destination = staging / relative
destination.parent.mkdir(parents=True, exist_ok=True)
with archive.open(info) as source, open(destination, "wb") as handle:
handle.write(source.read(1_000_000))
(staging / ".uploaded").write_text(now_iso())
if target.exists():
shutil.rmtree(target)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(staging), str(target))
finally:
if staging.exists():
try:
shutil.rmtree(staging)
except Exception:
pass
sync_modules()
db.execute(
"UPDATE modules SET enabled=0, status='pending', message='Uploaded — configure and enable the module', source='custom' WHERE module_type=?",
(module_id,),
)
return {
"id": module_id,
"name": manifest.get("name", module_id),
"version": manifest.get("version"),
"source": "custom",
"filename": filename,
}
def delete_module(module_id: str) -> None:
row = db.query_one("SELECT * FROM modules WHERE id=?", (module_id,))
if not row:
raise ModuleError("Module not found")
mtype = row["module_type"] or row["id"]
source = row["source"]
rows = db.query("SELECT * FROM modules WHERE module_type=?", (mtype,))
if source != "custom":
if len(rows) <= 1:
raise ModuleError("Bundled module's last instance cannot be removed, disable it instead")
else:
# Last instance of an uploaded module: remove the uploaded files (with backup).
# Extra instances of the same custom type are data-only and safe to drop in place.
if len(rows) <= 1:
target = config.MODULES_DIR / mtype
if target.exists() and not (target / ".uploaded").exists():
raise ModuleError("Refusing to remove a module that was not uploaded")
if target.exists():
backup = config.DATA_DIR / "removed-modules"
backup.mkdir(exist_ok=True)
destination = backup / f"{mtype}-{int(time.time())}"
try:
if destination.exists():
shutil.rmtree(destination)
shutil.move(str(target), str(destination))
except OSError:
shutil.rmtree(target, ignore_errors=True)
with db.db() as conn:
conn.execute("DELETE FROM samples WHERE asset_id IN (SELECT id FROM assets WHERE module_id=?)", (module_id,))
conn.execute("DELETE FROM assets WHERE module_id=?", (module_id,))
conn.execute("DELETE FROM module_state WHERE module_id=?", (module_id,))
conn.execute("DELETE FROM alerts WHERE asset_id NOT IN (SELECT id FROM assets)")
conn.execute("DELETE FROM modules WHERE id=?", (module_id,))
capacity_evaluate_safe()
def logs_for(module_id: str) -> str:
row = db.query_one("SELECT logs, message FROM modules WHERE id=?", (module_id,))
if not row:
raise ModuleError("Module not found")
return (row["logs"] or "") or (row["message"] or "")
+636
View File
@@ -0,0 +1,636 @@
"""HTTP API."""
from __future__ import annotations
import csv
import io
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, BackgroundTasks, Body, Depends, File, HTTPException, Request, Response, UploadFile
from pydantic import BaseModel, Field
from . import auth, capacity, config, copilot, db, licensing, mcp, metrics, registry, scheduler, seed
from .util import now_iso
router = APIRouter(prefix="/api")
# ---------------------------------------------------------------------------
# Models
# ---------------------------------------------------------------------------
class LoginIn(BaseModel):
username: str
password: str
class PasswordIn(BaseModel):
current_password: str
new_password: str
class ModuleIn(BaseModel):
enabled: Optional[bool] = None
config: Optional[Dict[str, Any]] = None
class ModuleInstanceIn(BaseModel):
module_type: str = Field(min_length=1)
name: Optional[str] = None
config: Optional[Dict[str, Any]] = None
copy_from: Optional[str] = None
class EnterpriseModeIn(BaseModel):
enabled: bool = True
class PolicyIn(BaseModel):
name: str
metric: str
warn: float
crit: float
enabled: bool = True
class SettingsIn(BaseModel):
site_name: Optional[str] = None
retention_days: Optional[int] = None
alert_webhook: Optional[str] = None
class LicenseIn(BaseModel):
key: str
class DevLicenseIn(BaseModel):
customer: str = "Homelab"
days: int = 365
class ApiKeyIn(BaseModel):
name: str
role: str = "operator"
class AIConfigIn(BaseModel):
base_url: str = ""
model: str = ""
api_key: Optional[str] = None
class ChatIn(BaseModel):
messages: List[Dict[str, str]] = Field(default_factory=list)
# ---------------------------------------------------------------------------
# Public
# ---------------------------------------------------------------------------
@router.get("/health")
def health() -> Dict[str, Any]:
db_ok = True
try:
db.query_one("SELECT 1 AS ok")
except Exception:
db_ok = False
return {
"status": "ok" if db_ok else "degraded",
"version": config.APP_VERSION,
"database": db_ok,
"scheduler": scheduler.scheduler.stats(),
}
@router.post("/auth/login")
def login(payload: LoginIn, request: Request, response: Response) -> Dict[str, Any]:
user = auth.login(payload.username, payload.password, request, response)
return {
"user": user,
"edition": licensing.status(),
"site_name": db.get_setting("site_name", "Homelab HQ"),
}
@router.post("/auth/logout")
def logout(response: Response) -> Dict[str, bool]:
auth.logout(response)
return {"ok": True}
@router.get("/bootstrap")
def bootstrap(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return {
"user": user,
"edition": licensing.status(),
"site_name": db.get_setting("site_name", "Homelab HQ"),
"version": config.APP_VERSION,
"meta": metrics.meta(),
"feature_labels": licensing.FEATURE_LABELS,
"scheduler": scheduler.scheduler.stats(),
"features": {
"custom_modules": licensing.has_feature("custom_modules"),
"llm_copilot": licensing.has_feature("llm_copilot"),
"mcp_server": licensing.has_feature("mcp_server"),
"audit_export": licensing.has_feature("audit_export"),
},
"limits": licensing.status()["limits"],
"dev_license_enabled": config.ALLOW_DEV_LICENSE,
"asset_count": registry.asset_count(),
"open_alerts": db.query_one("SELECT COUNT(*) AS n FROM alerts WHERE state='open'")["n"],
}
@router.put("/auth/password")
def change_password(payload: PasswordIn, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, bool]:
auth.change_password(user, payload.current_password, payload.new_password)
return {"ok": True}
# ---------------------------------------------------------------------------
# Fleet
# ---------------------------------------------------------------------------
@router.get("/overview")
def overview(window: int = 7, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
window = max(1, min(365, window))
data = capacity.overview(window)
data["edition"] = licensing.status()
return data
@router.get("/assets")
def assets(
type: Optional[str] = None,
module: Optional[str] = None,
q: Optional[str] = None,
user: Dict[str, Any] = Depends(auth.current_user),
) -> Dict[str, Any]:
rows = capacity.list_assets(type_filter=type, module_id=module, search=q)
latest = capacity.latest_values()
analyses, _ = capacity._analyses(rows, latest)
items = [capacity.summary(row, latest.get(row["id"], {}), analyses[row["id"]]) for row in rows]
items.sort(key=lambda item: item.get("pressure") or 0, reverse=True)
return {"items": items, "count": len(items)}
@router.get("/assets/{asset_id:path}")
def asset_detail(
asset_id: str,
window: int = 30,
user: Dict[str, Any] = Depends(auth.current_user),
) -> Dict[str, Any]:
detail = capacity.asset_detail(asset_id, max(1, min(365, window)))
if not detail:
raise HTTPException(status_code=404, detail="Asset not found")
return detail
@router.get("/capacity")
def capacity_groups(window: int = 7, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
groups = capacity.groups(max(1, min(365, window)))
all_assets = capacity.list_assets()
latest = capacity.latest_values()
slopes: Dict[Any, float] = {}
totals = capacity.resource_totals(all_assets, latest, slopes)
return {"groups": groups, "totals": totals, "generated_at": now_iso()}
@router.post("/capacity/simulate")
def simulate(payload: Dict[str, Any] = Body(default={}), user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return capacity.simulate(payload)
@router.get("/alerts")
def alerts(include_resolved: bool = False, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
items = capacity.alerts(include_resolved=include_resolved, limit=500)
open_items = items if not include_resolved else capacity.alerts(include_resolved=False, limit=500)
return {
"items": items,
"open": len(open_items),
"critical": sum(1 for item in open_items if item["severity"] == "critical"),
"warning": sum(1 for item in open_items if item["severity"] == "warning"),
}
@router.post("/alerts/{alert_id}/resolve")
def resolve_alert(alert_id: int, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
row = db.query_one("SELECT * FROM alerts WHERE id=?", (alert_id,))
if not row:
raise HTTPException(status_code=404, detail="Alert not found")
db.execute("UPDATE alerts SET state='resolved', resolved_at=? WHERE id=?", (now_iso(), alert_id))
db.audit(user["username"], "alert.resolve", str(alert_id))
return {"ok": True}
@router.get("/policies")
def list_policies(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
rows = [dict(row) for row in db.query("SELECT * FROM policies ORDER BY id")]
return {"items": rows}
@router.post("/policies")
def create_policy(payload: PolicyIn, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
if payload.warn >= payload.crit:
raise HTTPException(status_code=400, detail="Warning threshold must be below the critical threshold")
policy_id = db.execute(
"INSERT INTO policies(name, metric, warn, crit, enabled, created_at) VALUES(?,?,?,?,?,?)",
(payload.name[:120], payload.metric[:60], payload.warn, payload.crit, 1 if payload.enabled else 0, now_iso()),
)
db.audit(user["username"], "policy.create", str(policy_id), payload.name)
capacity.evaluate_policies()
return {"id": policy_id}
@router.put("/policies/{policy_id}")
def update_policy(policy_id: int, payload: PolicyIn, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
if payload.warn >= payload.crit:
raise HTTPException(status_code=400, detail="Warning threshold must be below the critical threshold")
row = db.query_one("SELECT id FROM policies WHERE id=?", (policy_id,))
if not row:
raise HTTPException(status_code=404, detail="Policy not found")
db.execute(
"UPDATE policies SET name=?, metric=?, warn=?, crit=?, enabled=? WHERE id=?",
(payload.name[:120], payload.metric[:60], payload.warn, payload.crit, 1 if payload.enabled else 0, policy_id),
)
db.audit(user["username"], "policy.update", str(policy_id), payload.name)
capacity.evaluate_policies()
return {"ok": True}
@router.delete("/policies/{policy_id}")
def delete_policy(policy_id: int, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
row = db.query_one("SELECT id FROM policies WHERE id=?", (policy_id,))
if not row:
raise HTTPException(status_code=404, detail="Policy not found")
db.execute("DELETE FROM policies WHERE id=?", (policy_id,))
db.execute("UPDATE alerts SET state='resolved', resolved_at=? WHERE policy_id=? AND state='open'", (now_iso(), policy_id))
db.audit(user["username"], "policy.delete", str(policy_id))
return {"ok": True}
# ---------------------------------------------------------------------------
# Modules
# ---------------------------------------------------------------------------
def _module_or_404(module_id: str) -> Dict[str, Any]:
for module in registry.list_modules():
if module["id"] == module_id:
return module
raise HTTPException(status_code=404, detail="Module not found")
@router.get("/modules")
def modules(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return {
"items": registry.list_modules(),
"asset_limit": licensing.asset_limit(),
"custom_modules": licensing.has_feature("custom_modules"),
"multi_instance": True,
}
@router.post("/modules/instances")
def create_module_instance(
payload: ModuleInstanceIn,
background: BackgroundTasks,
user: Dict[str, Any] = Depends(auth.require_admin),
) -> Dict[str, Any]:
try:
result = registry.add_instance(
module_type=payload.module_type,
name=payload.name,
config=payload.config,
copy_from=payload.copy_from,
)
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
instance_id = result.get("id")
if instance_id:
background.add_task(_run_module_bg, instance_id)
db.audit(user["username"], "module.instance.create", instance_id or payload.module_type, result)
return result
@router.put("/modules/{module_id}")
def update_module(
module_id: str,
payload: ModuleIn,
background: BackgroundTasks,
user: Dict[str, Any] = Depends(auth.require_admin),
) -> Dict[str, Any]:
current = _module_or_404(module_id)
was_enabled = current["enabled"]
try:
if payload.config is not None:
registry.update_config(module_id, payload.config, enabled=payload.enabled)
elif payload.enabled is not None:
registry.set_enabled(module_id, payload.enabled)
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
updated = _module_or_404(module_id)
if payload.enabled and not was_enabled:
background.add_task(_run_module_bg, module_id)
db.audit(
user["username"],
"module.update",
module_id,
{"enabled": payload.enabled, "config_keys": sorted((payload.config or {}).keys())},
)
return updated
def _run_module_bg(module_id: str) -> None:
try:
registry.run_module(module_id, trigger="enable")
capacity.evaluate_policies()
except Exception:
pass
@router.post("/modules/{module_id}/run")
def run_module(module_id: str, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
_module_or_404(module_id)
try:
result = registry.run_module(module_id, trigger="manual")
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
capacity.evaluate_policies()
db.audit(user["username"], "module.run", module_id)
return result
@router.post("/modules/{module_id}/test")
def test_module(module_id: str, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
_module_or_404(module_id)
try:
result = registry.test_module(module_id)
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return result
@router.get("/modules/{module_id}/logs")
def module_logs(module_id: str, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
_module_or_404(module_id)
try:
logs = registry.logs_for(module_id)
except registry.ModuleError as exc:
raise HTTPException(status_code=404, detail=str(exc))
return {"module_id": module_id, "logs": logs}
@router.post("/modules/upload")
async def upload_module(
file: UploadFile = File(...),
user: Dict[str, Any] = Depends(auth.require_feature("custom_modules", "admin")),
) -> Dict[str, Any]:
payload = await file.read(config.MAX_UPLOAD_BYTES + 1)
try:
result = registry.upload_module(payload, filename=file.filename or "module.zip")
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
db.audit(user["username"], "module.upload", result["id"], result)
return result
@router.delete("/modules/{module_id}")
def delete_module(module_id: str, user: Dict[str, Any] = Depends(auth.require_feature("custom_modules", "admin"))) -> Dict[str, Any]:
try:
registry.delete_module(module_id)
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
db.audit(user["username"], "module.delete", module_id)
return {"ok": True}
# ---------------------------------------------------------------------------
# Licensing & settings
# ---------------------------------------------------------------------------
@router.get("/license")
def license_status(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
status = licensing.status()
status["trial_available"] = not bool(db.get_setting("trial_started_at"))
status["matrix"] = licensing.edition_matrix()
return status
@router.post("/license/activate")
def activate_license(payload: LicenseIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
try:
payload_data = licensing.activate(payload.key)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
db.audit(user["username"], "license.activate", payload_data.get("customer", ""))
return licensing.status()
@router.post("/license/trial")
def start_trial(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
try:
status = licensing.start_trial()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
db.audit(user["username"], "license.trial", "")
return status
@router.delete("/license")
def deactivate_license(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
licensing.deactivate()
db.audit(user["username"], "license.deactivate", "")
return licensing.status()
@router.post("/license/enterprise")
def set_enterprise_mode(payload: EnterpriseModeIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
db.set_setting("enterprise_mode", "1" if payload.enabled else "0")
db.audit(user["username"], "license.enterprise_mode", "enabled" if payload.enabled else "disabled")
return licensing.status()
@router.post("/license/dev-issue")
def issue_dev_license(payload: DevLicenseIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
if not config.ALLOW_DEV_LICENSE:
raise HTTPException(status_code=403, detail="Development license issuing is disabled")
key = licensing.issue_key(payload.customer, days=max(1, min(3650, payload.days)))
db.audit(user["username"], "license.dev_issue", payload.customer)
return {"key": key, "customer": payload.customer, "days": payload.days}
@router.get("/editions")
def editions(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return {
"status": licensing.status(),
"matrix": licensing.edition_matrix(),
"community_limits": licensing.COMMUNITY_LIMITS,
"enterprise_limits": licensing.ENTERPRISE_LIMITS,
"trial_days": licensing.TRIAL_DAYS,
"trial_available": not bool(db.get_setting("trial_started_at")),
"contact": "[email protected]",
}
@router.get("/settings")
def get_settings(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return {
"site_name": db.get_setting("site_name", "Homelab HQ"),
"retention_days": int(db.get_setting("retention_days", "30") or 30),
"effective_retention_days": licensing.retention_days(),
"alert_webhook": db.get_setting("alert_webhook", ""),
"scheduler": scheduler.scheduler.stats(),
"db_path": str(config.DB_PATH),
"modules_dir": str(config.MODULES_DIR),
"admin_user": config.ADMIN_USER,
}
@router.put("/settings")
def update_settings(payload: SettingsIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
if payload.site_name is not None:
name = payload.site_name.strip()[:80]
if not name:
raise HTTPException(status_code=400, detail="Site name cannot be empty")
db.set_setting("site_name", name)
if payload.retention_days is not None:
if not 7 <= payload.retention_days <= 400:
raise HTTPException(status_code=400, detail="Retention must be between 7 and 400 days")
db.set_setting("retention_days", payload.retention_days)
if payload.alert_webhook is not None:
url = payload.alert_webhook.strip()
if url and not (url.startswith("http://") or url.startswith("https://")):
raise HTTPException(status_code=400, detail="Webhook must be an http(s) URL")
db.set_setting("alert_webhook", url[:500])
db.audit(user["username"], "settings.update", "", payload.model_dump(exclude_none=True))
return get_settings(user)
@router.get("/audit")
def audit_log(limit: int = 100, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
limit = max(1, min(1000, limit))
rows = [dict(row) for row in db.query("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (limit,))]
return {"items": rows}
@router.get("/export/audit.csv")
def export_audit(user: Dict[str, Any] = Depends(auth.require_feature("audit_export", "admin"))) -> Response:
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(["id", "ts", "actor", "action", "target", "detail"])
for row in db.query("SELECT * FROM audit ORDER BY id"):
writer.writerow([row["id"], row["ts"], row["actor"], row["action"], row["target"], row["detail"]])
return Response(
content=buffer.getvalue(),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="headroom-audit.csv"'},
)
@router.post("/admin/reseed")
def reseed(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
seed.clear_all_data()
seed.seed()
capacity.evaluate_policies()
db.audit(user["username"], "demo.reseed", "")
return {"ok": True, "assets": len(capacity.list_assets()), "seeded_at": now_iso()}
# ---------------------------------------------------------------------------
# API keys, AI, MCP, ingestion
# ---------------------------------------------------------------------------
@router.get("/keys")
def list_keys(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
rows = db.query("SELECT id, name, prefix, role, created_at, last_used FROM api_keys ORDER BY id DESC")
return {"items": [dict(row) for row in rows]}
@router.post("/keys")
def create_key(payload: ApiKeyIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
if payload.role not in ("admin", "operator", "viewer"):
raise HTTPException(status_code=400, detail="Role must be admin, operator or viewer")
name = payload.name.strip()[:80] or "API key"
from .security import api_key_prefix, hash_api_key, new_api_key
key = new_api_key()
key_id = db.execute(
"INSERT INTO api_keys(name, prefix, key_hash, role, created_at) VALUES(?,?,?,?,?)",
(name, api_key_prefix(key), hash_api_key(key), payload.role, now_iso()),
)
db.audit(user["username"], "apikey.create", name, payload.role)
return {"id": key_id, "name": name, "role": payload.role, "key": key, "prefix": api_key_prefix(key)}
@router.delete("/keys/{key_id}")
def delete_key(key_id: int, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
row = db.query_one("SELECT name FROM api_keys WHERE id=?", (key_id,))
if not row:
raise HTTPException(status_code=404, detail="API key not found")
db.execute("DELETE FROM api_keys WHERE id=?", (key_id,))
db.audit(user["username"], "apikey.delete", row["name"])
return {"ok": True}
@router.get("/ai/config")
def ai_config(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return {"config": copilot.config(), "suggested_questions": copilot.suggested_questions()}
@router.put("/ai/config")
def update_ai_config(payload: AIConfigIn, user: Dict[str, Any] = Depends(auth.require_feature("llm_copilot", "admin"))) -> Dict[str, Any]:
data = copilot.update_config(payload.model_dump())
db.audit(user["username"], "ai.config", payload.base_url)
return data
@router.post("/ai/chat")
def ai_chat(payload: ChatIn, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
try:
return copilot.chat(payload.messages)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
@router.get("/mcp")
def mcp_catalog(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return mcp.catalog()
@router.post("/mcp")
def mcp_endpoint(payload: Dict[str, Any] = Body(...), user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
return mcp.handle(payload, user)
@router.post("/ingest/{module_id}")
def ingest(
module_id: str,
payload: Dict[str, Any] = Body(...),
user: Dict[str, Any] = Depends(auth.require_operator),
) -> Dict[str, Any]:
module = _module_or_404(module_id)
if not module["enabled"]:
raise HTTPException(status_code=400, detail="Enable the module before pushing data to it")
assets = payload.get("assets")
if not isinstance(assets, list):
raise HTTPException(status_code=400, detail="Payload must contain an 'assets' list")
if len(assets) > config.MAX_PUSH_ASSETS:
raise HTTPException(status_code=400, detail=f"Maximum {config.MAX_PUSH_ASSETS} assets per push")
try:
registry.persist_result(module_id, {"assets": assets, "notes": f"Push ingestion from {user['username']}"}, 0)
except registry.ModuleError as exc:
raise HTTPException(status_code=400, detail=str(exc))
evaluation = capacity.evaluate_policies()
db.audit(user["username"], "ingest.push", module_id, {"assets": len(assets)})
return {"ok": True, "assets": len(assets), "policy_evaluation": evaluation}
@router.get("/export/assets.csv")
def export_assets(user: Dict[str, Any] = Depends(auth.current_user)) -> Response:
return Response(
content=capacity.export_assets_csv(),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="headroom-assets.csv"'},
)
@router.get("/export/alerts.csv")
def export_alerts(user: Dict[str, Any] = Depends(auth.current_user)) -> Response:
return Response(
content=capacity.export_alerts_csv(),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="headroom-alerts.csv"'},
)
+92
View File
@@ -0,0 +1,92 @@
"""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()
+79
View File
@@ -0,0 +1,79 @@
"""Background collection scheduler."""
from __future__ import annotations
import asyncio
import time
import traceback
from typing import Dict, List, Optional
from . import capacity, db, registry
class Scheduler:
def __init__(self, interval: int = 20) -> None:
self.interval = interval
self.task: Optional[asyncio.Task] = None
self.last_prune = 0.0
self.last_tick_ms: Optional[int] = None
self.last_error: Optional[str] = None
self.runs = 0
async def start(self) -> None:
if self.task is None:
self.task = asyncio.create_task(self._loop())
async def stop(self) -> None:
if self.task:
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass
self.task = None
async def _loop(self) -> None:
await asyncio.sleep(2)
while True:
try:
await asyncio.to_thread(self.tick)
self.last_error = None
except asyncio.CancelledError:
raise
except Exception as exc:
self.last_error = f"{type(exc).__name__}: {exc}"
print(f"[headroom] scheduler error: {self.last_error}\n{traceback.format_exc()}", flush=True)
await asyncio.sleep(self.interval)
def tick(self) -> None:
started = time.time()
if time.time() - self.last_prune > 6 * 3600:
removed = capacity.prune_samples()
self.last_prune = time.time()
if removed:
print(f"[headroom] retention pruned {removed} samples", flush=True)
due = registry.due_modules()
ran = 0
errors = 0
for module in due:
try:
registry.run_module(module["id"], trigger="scheduler")
self.runs += 1
ran += 1
except Exception as exc:
errors += 1
print(f"[headroom] module {module['id']} failed: {exc}", flush=True)
if ran or errors:
capacity.evaluate_policies()
self.last_tick_ms = int((time.time() - started) * 1000)
def stats(self) -> Dict[str, object]:
return {
"running": bool(self.task and not self.task.done()),
"interval_seconds": self.interval,
"last_tick_ms": self.last_tick_ms,
"last_error": self.last_error,
"runs": self.runs,
}
scheduler = Scheduler()
+140
View File
@@ -0,0 +1,140 @@
"""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))
+75
View File
@@ -0,0 +1,75 @@
"""Password hashing, session tokens and API keys (stdlib only)."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import secrets
import time
from typing import Any, Dict, Optional
from .config import get_secret
PBKDF2_ROUNDS = 120_000
SESSION_TTL = 7 * 24 * 3600
def _b64e(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def _b64d(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, PBKDF2_ROUNDS)
return f"pbkdf2${PBKDF2_ROUNDS}${salt.hex()}${digest.hex()}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, rounds, salt, digest = stored.split("$")
if scheme != "pbkdf2":
return False
candidate = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), int(rounds)
)
return hmac.compare_digest(candidate.hex(), digest)
except (ValueError, TypeError):
return False
def sign_session(user_id: int, ttl: int = SESSION_TTL) -> str:
payload = {"uid": int(user_id), "exp": int(time.time()) + ttl, "n": secrets.token_hex(4)}
body = _b64e(json.dumps(payload, separators=(",", ":")).encode())
signature = hmac.new(get_secret().encode(), body.encode(), hashlib.sha256).digest()
return f"{body}.{_b64e(signature)}"
def verify_session(token: str) -> Optional[Dict[str, Any]]:
try:
body, signature = token.split(".", 1)
expected = hmac.new(get_secret().encode(), body.encode(), hashlib.sha256).digest()
if not hmac.compare_digest(_b64d(signature), expected):
return None
payload = json.loads(_b64d(body))
if int(payload.get("exp", 0)) < time.time():
return None
return payload
except (ValueError, TypeError, json.JSONDecodeError):
return None
def new_api_key() -> str:
return "hr_" + secrets.token_urlsafe(30)
def api_key_prefix(key: str) -> str:
return key[:12]
def hash_api_key(key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()
+99
View File
@@ -0,0 +1,99 @@
"""First-run demo seeding: 30 days of realistic hourly metrics.
Seeding only ever runs when the database has no assets (or the explicit reseed
endpoint is used), so real deployments are never mixed with demo data.
"""
from __future__ import annotations
import json
import time
from typing import Any, Dict, List
from . import config, db
from .demo_fleet import FLEET, demo_value
from .util import now_iso
SEED_VERSION = f"headroom-demo-v1-{config.SEED_DAYS}"
def is_seeded() -> bool:
if db.get_setting("seed_version") != SEED_VERSION:
return False
row = db.query_one("SELECT COUNT(*) AS n FROM assets")
return bool(row and row["n"] > 0)
def seed_if_empty() -> bool:
if not config.SEED_DEMO:
return False
if is_seeded():
return False
existing = db.query_one("SELECT COUNT(*) AS n FROM assets")
if existing and existing["n"] > 0:
return False
seed()
return True
def seed() -> None:
now = int(time.time())
now_hour = now - (now % 3600)
start = now_hour - config.SEED_DAYS * 86400
timestamp = now_iso()
asset_rows = []
sample_rows = []
for module_id, specs in FLEET.items():
for spec in specs:
external_id = str(spec["external_id"])
asset_id = f"{module_id}::{external_id}"
asset_rows.append(
(
asset_id,
module_id,
external_id,
spec["name"],
spec["type"],
spec.get("cluster", ""),
spec.get("site", ""),
json.dumps(spec.get("tags", [])),
json.dumps(spec.get("meta", {})),
json.dumps(spec.get("capacity", {})),
timestamp,
timestamp,
1,
)
)
metric_names = list(spec["metrics"].keys())
for ts in range(start, now_hour + 1, 3600):
for metric in metric_names:
sample_rows.append(
(asset_id, metric, ts, demo_value(spec, metric, ts, now_hour))
)
with db.db() as conn:
conn.executemany(
"INSERT OR REPLACE INTO assets(id, module_id, external_id, name, type, cluster, site, "
"tags, meta, capacity, first_seen, last_seen, active) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
asset_rows,
)
conn.executemany(
"INSERT OR REPLACE INTO samples(asset_id, metric, ts, value) VALUES(?,?,?,?)",
sample_rows,
)
conn.execute(
"INSERT INTO settings(key, value) VALUES('seed_version', ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(SEED_VERSION,),
)
db.invalidate_settings_cache()
def clear_all_data() -> None:
with db.db() as conn:
conn.execute("DELETE FROM samples")
conn.execute("DELETE FROM alerts")
conn.execute("DELETE FROM assets")
conn.execute("UPDATE modules SET last_run=NULL, status='pending', message='Awaiting first collection'")
conn.execute("UPDATE settings SET value='' WHERE key='seed_version'")
db.invalidate_settings_cache()
+2731
View File
File diff suppressed because it is too large Load Diff
+190
View File
@@ -0,0 +1,190 @@
/* Lightweight SVG charts — no external dependencies. */
let uid = 0;
const BAND_COLORS = {
healthy: 'var(--ok)',
watch: 'var(--watch)',
tight: 'var(--tight)',
critical: 'var(--crit)',
unknown: 'var(--muted)',
};
function esc(value) {
return String(value ?? '').replace(/[&<>"']/g, (character) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
}[character]));
}
function nearest(points, target) {
let best = null;
for (const point of points) {
if (!best || Math.abs(point.t - target) < Math.abs(best.t - target)) best = point;
}
return best;
}
export function bandColor(band) {
return BAND_COLORS[band] || BAND_COLORS.unknown;
}
export function lineChart(container, series, options = {}) {
if (!container) return;
const active = (series || []).filter((item) => item && item.points && item.points.length);
if (!active.length) {
container.innerHTML = '<div class="chart-empty">No telemetry in this window yet.</div>';
return;
}
const width = options.width || 920;
const height = options.height || 280;
const pad = { left: options.padLeft ?? 48, right: 18, top: 16, bottom: 30 };
const all = active.flatMap((item) => item.points);
let t0 = Math.min(...all.map((point) => point.t));
let t1 = Math.max(...all.map((point) => point.t));
if (t1 <= t0) t1 = t0 + 3600000;
let max = options.max;
if (!max) {
const peak = Math.max(...all.map((point) => point.v), 1);
max = peak * 1.15;
}
const plotW = width - pad.left - pad.right;
const plotH = height - pad.top - pad.bottom;
const x = (t) => pad.left + ((t - t0) / (t1 - t0)) * plotW;
const y = (v) => pad.top + plotH - (Math.max(0, Math.min(v, max)) / max) * plotH;
const span = t1 - t0;
const valueFormat = options.valueFormat || ((value) => `${Math.round(value)}`);
const timeFormat = (t) => {
const date = new Date(t);
if (span <= 2 * 86400000) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
};
const tooltipTime = (t) => {
const date = new Date(t);
if (span <= 2 * 86400000) {
return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}
return date.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
};
const parts = [];
parts.push(`<svg class="chart-svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="${esc(options.ariaLabel || 'Time series chart')}">`);
for (let index = 0; index <= 4; index += 1) {
const value = (max / 4) * index;
const yy = y(value);
parts.push(`<line class="chart-grid" x1="${pad.left}" x2="${width - pad.right}" y1="${yy}" y2="${yy}"></line>`);
parts.push(`<text class="chart-axis" x="${pad.left - 9}" y="${yy + 4}" text-anchor="end">${esc(valueFormat(value))}</text>`);
}
for (let index = 0; index <= 4; index += 1) {
const t = t0 + ((t1 - t0) * index) / 4;
parts.push(`<text class="chart-axis" x="${x(t)}" y="${height - 8}" text-anchor="${index === 0 ? 'start' : index === 4 ? 'end' : 'middle'}">${esc(timeFormat(t))}</text>`);
}
active.forEach((item) => {
if (!item.points.length) return;
const points = item.points;
const color = item.color || 'var(--accent)';
const d = points.map((point, index) => `${index === 0 ? 'M' : 'L'}${x(point.t).toFixed(2)},${y(point.v).toFixed(2)}`).join(' ');
if (item.area) {
const gradient = `chart-grad-${++uid}`;
const baseY = pad.top + plotH;
parts.push(`<defs><linearGradient id="${gradient}" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="${color}" stop-opacity="0.26"/><stop offset="100%" stop-color="${color}" stop-opacity="0"/></linearGradient></defs>`);
parts.push(`<path d="${d} L${x(points[points.length - 1].t).toFixed(2)},${baseY} L${x(points[0].t).toFixed(2)},${baseY} Z" fill="url(#${gradient})"></path>`);
}
parts.push(`<path d="${d}" fill="none" stroke="${color}" stroke-width="${item.width || 2.2}" stroke-linecap="round" stroke-linejoin="round" ${item.dashed ? 'stroke-dasharray="6 7"' : ''}></path>`);
if (item.dot) {
const last = points[points.length - 1];
parts.push(`<circle cx="${x(last.t)}" cy="${y(last.v)}" r="4" fill="${color}" stroke="var(--surface)" stroke-width="2"></circle>`);
}
});
parts.push(`<line class="chart-guide" x1="0" x2="0" y1="${pad.top}" y2="${pad.top + plotH}" opacity="0"></line>`);
parts.push(`<rect class="chart-hit" x="${pad.left}" y="${pad.top}" width="${plotW}" height="${plotH}" fill="transparent"></rect>`);
parts.push('</svg>');
const wrap = document.createElement('div');
wrap.className = 'chart-wrap';
wrap.innerHTML = parts.join('') + '<div class="chart-tip" hidden></div>';
container.replaceChildren(wrap);
const svg = wrap.querySelector('svg');
const tip = wrap.querySelector('.chart-tip');
const guide = wrap.querySelector('.chart-guide');
svg.addEventListener('pointermove', (event) => {
const rect = svg.getBoundingClientRect();
const px = ((event.clientX - rect.left) / rect.width) * width;
if (px < pad.left || px > width - pad.right) {
tip.hidden = true;
guide.setAttribute('opacity', '0');
return;
}
const t = t0 + ((px - pad.left) / plotW) * (t1 - t0);
const rows = active.map((item) => {
const point = nearest(item.points, t);
return { label: item.label || item.key || '', color: item.color || 'var(--accent)', point };
}).filter((row) => row.point);
if (!rows.length) return;
const reference = rows[0].point.t;
tip.innerHTML = `<div class="tip-time">${esc(tooltipTime(reference))}</div>` + rows.map((row) => (
`<div class="tip-row"><span><i style="background:${row.color}"></i>${esc(row.label)}</span><strong>${esc(valueFormat(row.point.v))}</strong></div>`
)).join('');
tip.hidden = false;
const guideX = x(reference);
guide.setAttribute('x1', guideX);
guide.setAttribute('x2', guideX);
guide.setAttribute('opacity', '1');
const left = (guideX / width) * 100;
tip.style.left = `${Math.max(2, Math.min(76, left))}%`;
});
svg.addEventListener('pointerleave', () => {
tip.hidden = true;
guide.setAttribute('opacity', '0');
});
}
export function ring(value, options = {}) {
const size = options.size || 104;
const stroke = options.stroke || 9;
const radius = (size - stroke) / 2;
const circumference = 2 * Math.PI * radius;
const safe = Math.max(0, Math.min(100, Number(value) || 0));
const band = options.band || (safe >= 90 ? 'critical' : safe >= 80 ? 'tight' : safe >= 60 ? 'watch' : 'healthy');
return `<div class="ring" data-band="${esc(band)}" style="width:${size}px;height:${size}px">
<svg viewBox="0 0 ${size} ${size}" aria-hidden="true">
<circle class="ring-track" cx="${size / 2}" cy="${size / 2}" r="${radius}" fill="none" stroke-width="${stroke}"/>
<circle class="ring-value" cx="${size / 2}" cy="${size / 2}" r="${radius}" fill="none" stroke-width="${stroke}"
stroke-linecap="round" stroke-dasharray="${circumference.toFixed(2)}"
stroke-dashoffset="${(circumference * (1 - safe / 100)).toFixed(2)}"
transform="rotate(-90 ${size / 2} ${size / 2})"/>
</svg>
<div class="ring-label"><strong>${Math.round(safe)}</strong><span>${esc(options.suffix || '/100')}</span></div>
</div>`;
}
export function sparkline(points, color = 'var(--accent)', options = {}) {
if (!points || points.length < 2) return '<span class="spark-empty"></span>';
const width = options.width || 116;
const height = options.height || 34;
const pad = 2;
let min = Math.min(...points.map((point) => point.v));
let max = Math.max(...points.map((point) => point.v));
if (max - min < 0.01) { max += 1; min -= 1; }
const t0 = points[0].t;
const t1 = points[points.length - 1].t || t0 + 1;
const x = (t) => pad + ((t - t0) / (t1 - t0 || 1)) * (width - pad * 2);
const y = (v) => pad + (1 - (v - min) / (max - min)) * (height - pad * 2);
const d = points.map((point, index) => `${index === 0 ? 'M' : 'L'}${x(point.t).toFixed(1)},${y(point.v).toFixed(1)}`).join(' ');
const area = `${d} L${x(points[points.length - 1].t).toFixed(1)},${height - pad} L${x(points[0].t).toFixed(1)},${height - pad} Z`;
return `<svg class="spark" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" aria-hidden="true">
<path d="${area}" fill="${color}" opacity="0.10"></path>
<path d="${d}" fill="none" stroke="${color}" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"></path>
</svg>`;
}
export function distributionBars(items, options = {}) {
const total = items.reduce((sum, item) => sum + item.value, 0) || 1;
return `<div class="dist">${items.map((item) => `
<div class="dist-bar" title="${esc(item.label)}: ${item.value}">
<span style="width:${(item.value / total) * 100}%;background:${item.color || 'var(--accent)'}"></span>
</div>`).join('')}</div>`;
}
+29
View File
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#070b0e">
<title>Headroom — Capacity Management</title>
<meta name="description" content="Modular capacity management for homelabs. Know your headroom before you run out.">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='16' fill='%230b1216'/%3E%3Cpath d='M16 42a16 16 0 0 1 32 0' fill='none' stroke='%2338e0a0' stroke-width='5' stroke-linecap='round'/%3E%3Cpath d='M32 42l9-12' stroke='%23e8f0f4' stroke-width='4' stroke-linecap='round'/%3E%3Ccircle cx='32' cy='42' r='4' fill='%23e8f0f4'/%3E%3C/svg%3E">
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<div id="app" hidden></div>
<div id="boot" class="boot">
<div class="boot-mark">
<svg viewBox="0 0 64 64" aria-hidden="true">
<path d="M12 44a20 20 0 0 1 40 0" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"/>
<path d="M32 44l11-15" stroke="#e8f0f4" stroke-width="4" stroke-linecap="round"/>
<circle cx="32" cy="44" r="4" fill="#e8f0f4"/>
</svg>
</div>
<div class="boot-text">HEADROOM</div>
<div class="boot-sub">Starting capacity engine…</div>
</div>
<div id="modal-root"></div>
<div id="toast-root" class="toast-root" aria-live="polite"></div>
<script type="module" src="/static/app.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+78
View File
@@ -0,0 +1,78 @@
"""Small shared helpers."""
from __future__ import annotations
import math
import re
from datetime import datetime, timezone
from typing import Any, Optional
_UNITS = [
(1024 ** 4, "PB"),
(1024 ** 3, "TB"),
(1024 ** 2, "GB"),
(1024, "MB"),
]
def utcnow() -> datetime:
return datetime.now(timezone.utc)
def now_iso() -> str:
return utcnow().isoformat(timespec="seconds")
def epoch() -> int:
return int(utcnow().timestamp())
def iso_from_epoch(ts: Optional[int]) -> Optional[str]:
if ts is None:
return None
return datetime.fromtimestamp(int(ts), timezone.utc).isoformat(timespec="seconds")
def epoch_from_iso(value: Optional[str]) -> Optional[int]:
if not value:
return None
try:
return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())
except (ValueError, TypeError):
return None
def clamp(value: float, low: float, high: float) -> float:
return max(low, min(high, value))
def finite(value: Any) -> Optional[float]:
try:
number = float(value)
except (TypeError, ValueError):
return None
if not math.isfinite(number) or abs(number) > 1e15:
return None
return number
def human_bytes(value: Optional[float]) -> str:
if value is None:
return "—"
number = float(value)
for factor, unit in _UNITS:
if abs(number) >= factor:
return f"{number / factor:.1f} {unit}"
return f"{number:.0f} B"
def slug(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
def truncate(value: Any, length: int = 200) -> str:
text = str(value if value is not None else "")
return text[:length]
def pct(value: Optional[float]) -> str:
return "—" if value is None else f"{value:.0f}%"