commit 15bbe022775c3946bcf43000b0155a2c8c1d7480 Author: kristianwind Date: Fri Oct 23 22:39:27 2026 +0200 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f078145 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.venv/ +data/ +__pycache__/ +*.pyc +.pytest_cache/ +.DS_Store +*.log +._* diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9c2f045 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.11-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + HEADROOM_DATA=/data \ + HEADROOM_MODULES=/app/modules + +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY app ./app +COPY modules ./modules +COPY ctlpanel-logo ./ctlpanel-logo + +RUN mkdir -p /data && chmod 777 /data 2>/dev/null || true + +EXPOSE 8787 + +CMD ["sh", "-c", "exec python -m uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-${WEB_PORT:-${HEADROOM_PORT:-8787}}} --workers 1"] diff --git a/HANDOFF_TO_OPENCODE.md b/HANDOFF_TO_OPENCODE.md new file mode 100644 index 0000000..85b09e0 --- /dev/null +++ b/HANDOFF_TO_OPENCODE.md @@ -0,0 +1,47 @@ +# Handoff: Headroom -> anden OpenCode + +Dato: 2026-10-23 + +## Status lige nu +- Headroom kører på http://127.0.0.1:8787 (login: admin / admin) +- **Multi-instance support TESTET OG VERIFIERET** — se testlog nederfor +- **Enterprise admin-toggle TESTET OG VERIFIERET** (admin_override=1, limits -1/400) +- rune.yaml + Dockerfile klar til Yggdrasil +- Server migreret til ny modules-schema +- Enterprise-mode er PÅ i settings (enterprise_mode=1) — slåes fra via UI eller `POST /api/license/enterprise {"enabled":false}` + +## Vigtige filer +- app/registry.py (multi-instance logik, `_generate_instance_id`, `delete_module`-guard) +- app/routes.py (POST /api/modules/instances, POST /api/license/enterprise) +- app/licensing.py (admin override) +- app/static/app.js (UI til flere instanser + enterprise toggle) +- rune.yaml +- Dockerfile +- HANDOFF_TO_OPENCODE.md + +## Testlog 2026-10-23 + +### Multi-instance (3 Proxmox-instanser) +- Oprettede `proxmox-cluster-1/2/3` via `POST /api/modules/instances` (demo=true) +- Alle 3 samlede OK: 7/7/4 assets (4. blev trunceret af Community 40-asset grænsen, warning i `last_limit_warning`) +- **Asset-adskillelse bekræftet**: samme `external_id` (f.eks. `ceph-atlas`) giver distinkte asset-rækker per instans: + `proxmox::ceph-atlas`, `proxmox-cluster-2::ceph-atlas`, `proxmox-cluster-3::ceph-atlas` +- Deaktivere en instans deaktivere kun dens egne assets + +### Delete-guard (bundled instanser) +- Slette en ikke-sidste bundled-instans: 200 OK +- Slette den sidste bundled-instans: **400 "Bundled module's last instance cannot be removed, disable it instead"** ✔ +- Slette ikke-eksisterende id: 400 "Module not found" ✔ + +### Enterprise-toggle +- `POST /api/license/enterprise {"enabled":true}` → `licensing.status()`: edition=enterprise, source=admin, admin_override=True, limits {assets:-1, retention_days:400}, alle ENTERPRISE_FEATURES +- `custom_modules: true`, `asset_limit: -1` i `/api/modules` + +## Bug fundet og rettet i sessionen +1. **Delete-guard-maskering**: `DELETE /api/modules/{id}` er bag `require_feature("custom_modules")` — i Community-mode gav det 402 i stedet for 400-guarden. Testet korrekt i Enterprise-mode. +2. **`_generate_instance_id` gren-rækkefølge**: oprindeligt matchede `slug.startswith(module_type + "-")` før `slug == module_type`, så et genoprettet bundled-type aldrig kunne få plain-id via API. Rettet: `slug == module_type` evalueres først, med timestamp-fallback hvis plain-id allerede er optaget. +3. **`delete_module` custom-comment**: tilføjet kommentar om at ekstra instanser af custom-typer er data-only og trygge at slette direkte. + +## Næste skridt +- [ ] UI-smoke-test: Add-instance modal / "Add another" clone-knap / `#enterprise-toggle` (kodelinjer læst og matcher API-opførsel — lav risiko) +- [ ] Bygge/pushe Docker image til `ghcr.io/kristianwind/headroom:latest` hvis du vil bruge rune i Yggdrasil diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..6893d9e --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,3 @@ +"""Headroom — a modular capacity management framework for homelabs.""" + +__version__ = "1.0.0" diff --git a/app/auth.py b/app/auth.py new file mode 100644 index 0000000..a2062d6 --- /dev/null +++ b/app/auth.py @@ -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"]) diff --git a/app/capacity.py b/app/capacity.py new file mode 100644 index 0000000..575d24e --- /dev/null +++ b/app/capacity.py @@ -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 diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..edb001c --- /dev/null +++ b/app/config.py @@ -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 diff --git a/app/copilot.py b/app/copilot.py new file mode 100644 index 0000000..69026b0 --- /dev/null +++ b/app/copilot.py @@ -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.", + ] diff --git a/app/db.py b/app/db.py new file mode 100644 index 0000000..3207b82 --- /dev/null +++ b/app/db.py @@ -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 diff --git a/app/demo_fleet.py b/app/demo_fleet.py new file mode 100644 index 0000000..4fd0cc2 --- /dev/null +++ b/app/demo_fleet.py @@ -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, [])) diff --git a/app/licensing.py b/app/licensing.py new file mode 100644 index 0000000..255d822 --- /dev/null +++ b/app/licensing.py @@ -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() diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..3e308c6 --- /dev/null +++ b/app/main.py @@ -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") diff --git a/app/mcp.py b/app/mcp.py new file mode 100644 index 0000000..cffebef --- /dev/null +++ b/app/mcp.py @@ -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}") diff --git a/app/metrics.py b/app/metrics.py new file mode 100644 index 0000000..d22b733 --- /dev/null +++ b/app/metrics.py @@ -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 + ], + } diff --git a/app/registry.py b/app/registry.py new file mode 100644 index 0000000..5dbe8fe --- /dev/null +++ b/app/registry.py @@ -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 "") diff --git a/app/routes.py b/app/routes.py new file mode 100644 index 0000000..d00ac07 --- /dev/null +++ b/app/routes.py @@ -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": "enterprise@headroom.local", + } + + +@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"'}, + ) diff --git a/app/runner.py b/app/runner.py new file mode 100644 index 0000000..9e7f127 --- /dev/null +++ b/app/runner.py @@ -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 ", 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() diff --git a/app/scheduler.py b/app/scheduler.py new file mode 100644 index 0000000..b60e4b1 --- /dev/null +++ b/app/scheduler.py @@ -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() diff --git a/app/sdk.py b/app/sdk.py new file mode 100644 index 0000000..dd8505f --- /dev/null +++ b/app/sdk.py @@ -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)) diff --git a/app/security.py b/app/security.py new file mode 100644 index 0000000..9bb96ed --- /dev/null +++ b/app/security.py @@ -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() diff --git a/app/seed.py b/app/seed.py new file mode 100644 index 0000000..c1a72bc --- /dev/null +++ b/app/seed.py @@ -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() diff --git a/app/static/app.js b/app/static/app.js new file mode 100644 index 0000000..20fa9a4 --- /dev/null +++ b/app/static/app.js @@ -0,0 +1,2731 @@ +/* ========================================================================== + Headroom frontend — no build step, ES modules only. + ========================================================================== */ +import { lineChart, ring, sparkline, bandColor } from './charts.js'; + +const app = document.getElementById('app'); +const bootEl = document.getElementById('boot'); +const modalRoot = document.getElementById('modal-root'); +const toastRoot = document.getElementById('toast-root'); + +/* -------------------------------------------------------------------------- + Icons + -------------------------------------------------------------------------- */ +const ICONS = { + dashboard: '', + server: '', + chart: '', + bell: '', + plug: '', + sparkles: '', + code: '', + settings: '', + search: '', + refresh: '', + plus: '', + x: '', + play: '', + check: '', + upload: '', + trash: '', + logout: '', + shield: '', + arrowRight: '', + arrowLeft: '', + arrowUp: '', + arrowDown: '', + menu: '', + alert: '', + info: '', + database: '', + layers: '', + network: '', + bolt: '', + box: '', + key: '', + clock: '', + copy: '', + download: '', + external: '', + cpu: '', + lock: '', + list: '', + cap: '', + chevronDown: '', + minus: '', + activity: '', + filter: '', + dollar: '', + mail: '', + git: '', + terminal: '', + spark: '', +}; + +const BRAND_SVG = ``; + +function icon(name, cls = 'ic') { + return ``; +} + +/* -------------------------------------------------------------------------- + Utilities + -------------------------------------------------------------------------- */ +const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + +const META = () => state.boot?.meta || { metrics: {}, asset_types: {}, util_metrics: [] }; +const METRICS = () => META().metrics || {}; +const TYPES = () => META().asset_types || {}; + +const BAND_LABELS = { healthy: 'Healthy', watch: 'Watch', tight: 'Tight', critical: 'Critical', unknown: 'No data' }; + +function band(value) { + if (value == null || Number.isNaN(Number(value))) return 'unknown'; + const n = Number(value); + if (n >= 90) return 'critical'; + if (n >= 80) return 'tight'; + if (n >= 60) return 'watch'; + return 'healthy'; +} + +function trimNum(value, digits = 1) { + if (value == null || Number.isNaN(Number(value))) return '—'; + const n = Number(value); + const fixed = n.toFixed(digits); + return fixed.replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1'); +} + +function pct(value, digits = 1) { + if (value == null || Number.isNaN(Number(value))) return '—'; + return `${trimNum(value, digits)}%`; +} + +function gb(value) { + if (value == null || Number.isNaN(Number(value))) return '—'; + const n = Number(value); + if (Math.abs(n) >= 1024) return `${trimNum(n / 1024, n >= 10240 ? 0 : 1)} TB`; + return `${trimNum(n, 0)} GB`; +} + +function days(value) { + if (value == null || Number.isNaN(Number(value))) return '—'; + const n = Number(value); + if (n < 1) return '<1 day'; + if (n < 45) return `${Math.round(n)} days`; + if (n < 365) return `${trimNum(n / 30.44, 1)} months`; + return `${trimNum(n / 365, 1)} years`; +} + +function timeAgo(value) { + if (!value) return 'never'; + const t = new Date(value).getTime(); + if (!Number.isFinite(t)) return '—'; + const seconds = Math.max(0, Math.round((Date.now() - t) / 1000)); + if (seconds < 60) return `${seconds}s ago`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; + if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; + if (seconds < 86400 * 30) return `${Math.floor(seconds / 86400)}d ago`; + return new Date(t).toLocaleDateString(); +} + +function fmtDate(value, withTime = false) { + if (!value) return '—'; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return String(value); + return date.toLocaleString([], withTime ? { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' } : { year: 'numeric', month: 'short', day: 'numeric' }); +} + +function metricMeta(key) { + return METRICS()[key] || { label: key, unit: '', kind: 'other' }; +} + +function metricValue(key, value) { + if (value == null) return '—'; + const meta = metricMeta(key); + const unit = meta.unit || ''; + const n = Number(value); + if (unit === '%') return `${trimNum(n, 1)}%`; + const formatted = Math.abs(n) >= 1000 ? Math.round(n).toLocaleString() : trimNum(n, 2); + return unit ? `${formatted} ${unit}` : formatted; +} + +function statusPill(status, label = '') { + const key = status || 'unknown'; + return `${esc(BAND_LABELS[key] || label || key)}`; +} + +const ASSET_ICON = { hypervisor: 'server', storage: 'database', nas: 'database', appliance: 'box', network: 'network', power: 'bolt', server: 'server', cluster: 'layers' }; +const MODULE_ICON = { proxmox: 'layers', esxi: 'server', splunk: 'chart', truenas: 'database', linux: 'terminal', windows: 'server', 'http-json': 'code' }; +const typeIcon = (type) => icon(ASSET_ICON[type] || 'server'); +const assetHref = (id) => `#/assets/${encodeURIComponent(id)}`; +const trendCell = (asset) => { + const slope = Number(asset?.slope_per_day || 0); + if (Math.abs(slope) < 0.02) return `${icon('minus')} stable`; + const up = slope > 0; + return `${icon(up ? 'arrowUp' : 'arrowDown')} ${trimNum(Math.abs(slope), 2)} pp/d`; +}; +const moduleName = (id) => (state.boot?.meta ? id : id); + +/* -------------------------------------------------------------------------- + State + -------------------------------------------------------------------------- */ +const state = { + boot: null, + route: { name: 'overview', id: null }, + windowDays: 7, + renderToken: 0, + assetFilters: { q: '', type: '', module: '' }, + alertResolved: false, + apiTab: 'rest', + settingsTab: 'general', + chat: [], + chatLoading: false, + simResult: null, + assetMetric: null, + pollTimer: null, +}; + +/* -------------------------------------------------------------------------- + API + -------------------------------------------------------------------------- */ +function parseError(data, status) { + const detail = data && data.detail; + if (detail && typeof detail === 'object') return { message: detail.message || `Request failed (${status})`, code: detail.code, feature: detail.feature, detail }; + return { message: typeof detail === 'string' ? detail : `Request failed (${status})`, code: null, feature: null, detail }; +} + +async function request(path, options = {}) { + const opts = { credentials: 'same-origin', ...options }; + const isForm = opts.body instanceof FormData; + opts.headers = { ...(isForm ? {} : { 'Content-Type': 'application/json' }), ...(options.headers || {}) }; + const response = await fetch(`/api${path}`, opts); + const type = response.headers.get('content-type') || ''; + const data = type.includes('json') ? await response.json().catch(() => null) : await response.text(); + if (!response.ok) { + const error = parseError(data, response.status); + if (response.status === 401 && state.boot) showLogin(); + if (response.status === 402) openUpgrade(error.feature); + const err = new Error(error.message); + err.status = response.status; + err.code = error.code; + err.feature = error.feature; + throw err; + } + return data; +} + +const get = (path) => request(path); +const post = (path, body) => request(path, { method: 'POST', body: body === undefined ? undefined : JSON.stringify(body) }); +const put = (path, body) => request(path, { method: 'PUT', body: JSON.stringify(body) }); +const del = (path) => request(path, { method: 'DELETE' }); + +function toastError(error) { + if (!error || error.status === 402) return; + toast(error.message || 'Something went wrong', 'error'); +} + +/* -------------------------------------------------------------------------- + Toasts / modal + -------------------------------------------------------------------------- */ +function toast(message, kind = 'ok', title = '') { + const icons = { ok: 'check', error: 'alert', warn: 'alert', info: 'info' }; + const el = document.createElement('div'); + el.className = `toast ${kind}`; + el.innerHTML = `${icon(icons[kind] || 'info')}
${title ? `${esc(title)}` : ''}${esc(message)}
`; + toastRoot.appendChild(el); + setTimeout(() => { + el.classList.add('leaving'); + setTimeout(() => el.remove(), 200); + }, kind === 'error' ? 6200 : 4200); +} + +let modalEscape = null; + +function closeModal() { + modalRoot.innerHTML = ''; + if (modalEscape) { + document.removeEventListener('keydown', modalEscape); + modalEscape = null; + } +} + +function openModal({ title, sub = '', body = '', footer = '', wide = false, narrow = false, onMount = null, onClose = null }) { + closeModal(); + const size = wide ? 'wide' : narrow ? 'narrow' : ''; + modalRoot.innerHTML = ` + `; + const backdrop = modalRoot.querySelector('[data-backdrop]'); + const close = () => { const callback = onClose; closeModal(); if (callback) callback(); }; + backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close(); }); + modalRoot.querySelectorAll('[data-close]').forEach((button) => button.addEventListener('click', close)); + modalEscape = (event) => { if (event.key === 'Escape') close(); }; + document.addEventListener('keydown', modalEscape); + if (onMount) onMount(modalRoot.querySelector('.modal'), close); + return modalRoot.querySelector('.modal'); +} + +function confirmDialog({ title, message, confirmLabel = 'Confirm', danger = false }) { + return new Promise((resolve) => { + let settled = false; + const finish = (value) => { if (settled) return; settled = true; closeModal(); resolve(value); }; + openModal({ + title: esc(title), + narrow: true, + body: `

${message}

`, + footer: ``, + onMount(modal) { + modal.querySelector('[data-cancel]').addEventListener('click', () => finish(false)); + modal.querySelector('[data-yes]').addEventListener('click', () => finish(true)); + }, + onClose() { if (!settled) { settled = true; resolve(false); } }, + }); + }); +} + +async function copyText(text) { + try { + await navigator.clipboard.writeText(text); + toast('Copied to clipboard'); + } catch { + const area = document.createElement('textarea'); + area.value = text; + document.body.appendChild(area); + area.select(); + document.execCommand('copy'); + area.remove(); + toast('Copied to clipboard'); + } +} + +/* -------------------------------------------------------------------------- + Boot / login + -------------------------------------------------------------------------- */ +async function init() { + try { + const data = await get('/bootstrap'); + state.boot = data; + startApp(); + } catch (error) { + if (error.status === 401) { + showLogin(); + } else { + showBootError(error.message); + } + } +} + +function showBootError(message) { + if (!bootEl) return; + bootEl.hidden = false; + app.hidden = true; + const sub = bootEl.querySelector('.boot-sub'); + if (sub) sub.textContent = message; + bootEl.classList.add('boot-failed'); + if (!bootEl.querySelector('.boot-error')) { + const div = document.createElement('div'); + div.className = 'boot-error'; + div.textContent = 'The API did not respond correctly. Verify the server log and reload.'; + bootEl.appendChild(div); + } +} + +function showLogin(message = '') { + state.boot = null; + state.renderToken += 1; + if (state.pollTimer) { clearInterval(state.pollTimer); state.pollTimer = null; } + if (bootEl) bootEl.hidden = true; + app.hidden = false; + document.title = 'Sign in — Headroom'; + app.innerHTML = ` + `; + const form = app.querySelector('#login-form'); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const button = app.querySelector('#login-submit'); + const error = app.querySelector('#login-error'); + error.textContent = ''; + button.disabled = true; + button.innerHTML = `${icon('refresh')} Signing in…`; + const payload = Object.fromEntries(new FormData(form).entries()); + try { + await post('/auth/login', payload); + await init(); + } catch (err) { + error.textContent = err.message; + button.disabled = false; + button.innerHTML = `Sign in ${icon('arrowRight')}`; + app.querySelector('#login-pass').focus(); + } + }); +} + +/* -------------------------------------------------------------------------- + Shell + -------------------------------------------------------------------------- */ +const NAV = [ + { section: 'Operations' }, + { key: 'overview', label: 'Overview', icon: 'dashboard', href: '#/overview' }, + { key: 'assets', label: 'Assets', icon: 'server', href: '#/assets' }, + { key: 'capacity', label: 'Capacity & forecast', icon: 'chart', href: '#/capacity' }, + { key: 'alerts', label: 'Alerts', icon: 'bell', href: '#/alerts' }, + { section: 'Platform' }, + { key: 'modules', label: 'Modules', icon: 'plug', href: '#/modules' }, + { key: 'copilot', label: 'Copilot', icon: 'sparkles', href: '#/copilot' }, + { key: 'api', label: 'API & MCP', icon: 'code', href: '#/api' }, + { section: 'System' }, + { key: 'settings', label: 'Settings', icon: 'settings', href: '#/settings' }, +]; + +function navKey(route) { + if (route.name === 'asset') return 'assets'; + return route.name; +} + +function startApp() { + if (!state.boot) return; + if (bootEl) bootEl.hidden = true; + app.hidden = false; + document.title = `${state.boot.site_name} — Headroom`; + const user = state.boot.user; + const initial = esc((user.username || '?').slice(0, 1).toUpperCase()); + app.innerHTML = ` +
+ +
+
+ +

Overview

+
+
Live
+ ${state.boot.edition.edition !== 'community' ? `${esc(state.boot.edition.label)}` : ''} + +
+ + +
+
+
+
+
+
`; + renderEditionCard(); + updateNav(); + bindShell(); + location.hash = location.hash && location.hash !== '#/' ? location.hash : '#/overview'; + renderRoute(); + startPolling(); +} + +function renderEditionCard() { + const slot = document.getElementById('edition-slot'); + if (!slot || !state.boot) return; + const edition = state.boot.edition; + const paid = edition.edition !== 'community'; + const p = paid + ? (edition.source === 'trial' ? `${edition.days_left ?? 0} days left in the Enterprise trial.` : `${esc(edition.customer || 'Licensed')} · ${edition.days_left ?? '—'} days remaining.`) + : 'Custom modules, LLM copilot, MCP server and 400-day retention.'; + slot.innerHTML = ` +
+
+ ${esc(edition.label)} + ${paid ? (edition.source === 'trial' ? 'TRIAL' : 'PRO') : 'FREE'} +
+

${p}

+ +
`; +} + +function updateNav() { + const key = navKey(state.route); + document.querySelectorAll('.nav-item').forEach((item) => item.classList.toggle('active', item.dataset.nav === key)); + const count = Number(state.boot?.open_alerts || 0); + const badge = document.getElementById('nav-alert-count'); + if (badge) { + badge.textContent = count > 99 ? '99+' : String(count); + badge.hidden = count === 0; + } + document.querySelectorAll('[data-lock]').forEach((lock) => { + const feature = lock.dataset.lock === 'copilot' ? 'llm_copilot' : 'mcp_server'; + const unlocked = state.boot?.features?.[feature] || lock.dataset.lock === 'copilot'; + lock.hidden = unlocked; + }); +} + +function setPage(title, sub = '') { + const titleEl = document.getElementById('tb-title'); + const subEl = document.getElementById('tb-sub'); + if (titleEl) titleEl.textContent = title; + if (subEl) subEl.textContent = sub; +} + +function bindShell() { + document.addEventListener('click', (event) => { + const menuToggle = event.target.closest('[data-menu-toggle]'); + if (menuToggle) { + document.getElementById('sidebar')?.classList.toggle('open'); + return; + } + if (event.target.closest('.sidebar .nav-item')) { + document.getElementById('sidebar')?.classList.remove('open'); + } + const userButton = event.target.closest('[data-user-menu]'); + if (userButton) { + document.getElementById('user-menu')?.toggleAttribute('hidden'); + return; + } + if (!event.target.closest('#user-menu')) { + document.getElementById('user-menu')?.setAttribute('hidden', ''); + } + if (event.target.closest('[data-logout]')) { + event.preventDefault(); + logout(); + } + if (event.target.closest('[data-open-settings]')) { + location.hash = '#/settings'; + } + const windowButton = event.target.closest('[data-window]'); + if (windowButton) { + state.windowDays = Number(windowButton.dataset.window) || 7; + renderRoute(); + } + if (event.target.closest('[data-refresh]')) { + renderRoute(); + } + if (event.target.closest('[data-upgrade]')) { + openUpgrade(event.target.closest('[data-upgrade]').dataset.upgrade || ''); + } + }); + window.addEventListener('hashchange', () => { + if (!state.boot) return; + renderRoute(); + window.scrollTo({ top: 0, behavior: 'smooth' }); + }); +} + +async function logout() { + try { await post('/auth/logout'); } catch { /* ignore */ } + state.chat = []; + showLogin(); + location.hash = ''; +} + +/* -------------------------------------------------------------------------- + Router + -------------------------------------------------------------------------- */ +function parseHash() { + const raw = (location.hash || '').replace(/^#\/?/, ''); + if (!raw) return { name: 'overview', id: null }; + const parts = raw.split('/'); + if (parts[0] === 'assets' && parts[1]) return { name: 'asset', id: decodeURIComponent(parts.slice(1).join('/')) }; + const name = parts[0]; + const known = ['overview', 'assets', 'capacity', 'alerts', 'modules', 'copilot', 'api', 'settings']; + return { name: known.includes(name) ? name : 'overview', id: null }; +} + +const VIEWS = {}; + +async function renderRoute(silent = false) { + if (!state.boot) return; + const route = parseHash(); + state.route = route; + updateNav(); + const token = ++state.renderToken; + const view = document.getElementById('view'); + if (!view) return; + if (!silent) view.innerHTML = loadingHtml(); + try { + const renderer = VIEWS[route.name]; + if (!renderer) throw new Error('Unknown view'); + await renderer({ route, view, token }); + } catch (error) { + if (token !== state.renderToken) return; + if (error.status === 401) return; + view.innerHTML = errorState(error); + } +} + +function loadingHtml() { + return `
`; +} + +function errorState(error) { + return `
+
${icon('alert')}
+ Could not load this view +

${esc(error?.message || 'Unexpected error')}

+ +
`; +} + +function pageHead({ eyebrow = '', title, sub = '', actions = '' }) { + return `
+
${eyebrow ? `
${esc(eyebrow)}
` : ''}

${title}

${sub ? `

${sub}

` : ''}
+ ${actions ? `
${actions}
` : ''} +
`; +} + +function windowSeg() { + const options = [[1, '24h'], [7, '7d'], [30, '30d'], [90, '90d']]; + return `
${options.map(([value, label]) => ``).join('')}
`; +} + +function refreshButton() { + return ``; +} + +function startPolling() { + if (state.pollTimer) clearInterval(state.pollTimer); + state.pollTimer = setInterval(async () => { + if (document.hidden || !state.boot || document.querySelector('.modal-backdrop')) return; + const active = document.activeElement; + if (active && ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)) return; + await refreshBootstrap(); + if (['overview', 'assets'].includes(state.route.name)) renderRoute(true); + }, 45000); +} + +async function refreshBootstrap() { + try { + const data = await get('/bootstrap'); + state.boot = data; + renderEditionCard(); + updateNav(); + return data; + } catch { return null; } +} + +/* -------------------------------------------------------------------------- + Upgrade / trial + -------------------------------------------------------------------------- */ +async function openUpgrade(feature = '') { + let editions = null; + try { editions = await get('/editions'); } catch { /* ignore */ } + const labels = state.boot?.feature_labels || {}; + const enterpriseFeatures = []; + if (editions) { + for (const group of editions.matrix || []) { + for (const item of group.features) { + if (item.enterprise && !item.community) enterpriseFeatures.push(item.label); + } + } + } + const featureLabel = feature && labels[feature] ? labels[feature] : ''; + const trialAvailable = editions ? editions.trial_available : false; + const body = ` + ${featureLabel ? `
${icon('lock')}
${esc(featureLabel)} is an Enterprise capability.
` : ''} +

Enterprise adds the tooling you need when the lab stops being just a lab: upload your own modules, talk to your fleet through an LLM, expose capacity data over MCP, and keep a year of history.

+
+ ${(enterpriseFeatures.length ? enterpriseFeatures : ['Custom module uploads', 'LLM copilot', 'MCP server for AI agents', 'Unlimited assets', '400-day retention', 'Audit export and webhooks']).map((item) => `
${icon('check')}${esc(item)}
`).join('')} +
+ ${trialAvailable ? `
${icon('sparkles')}
30-day Enterprise trial — unlock everything now, no payment details.
` : `
${icon('info')}
A trial has already been used on this installation. Activate a license key to continue with Enterprise features.
`} +
+
+ + + Keys are signed and verified locally. Contact enterprise@headroom.local for a key. +
+
`; + openModal({ + title: 'Unlock Headroom Enterprise', + sub: 'Upgrade the edition of this installation', + wide: true, + body, + footer: ` + ${trialAvailable ? `` : ''} + + `, + onMount(modal, close) { + const trial = modal.querySelector('[data-trial]'); + if (trial) trial.addEventListener('click', async () => { + trial.disabled = true; + try { + await post('/license/trial'); + await refreshBootstrap(); + close(); + toast('Enterprise trial started — all features are unlocked', 'ok', 'Trial active'); + renderRoute(); + } catch (error) { trial.disabled = false; toastError(error); } + }); + modal.querySelector('[data-activate]').addEventListener('click', async () => { + const key = modal.querySelector('#license-key').value.trim(); + if (!key) { toast('Paste a license key first', 'warn'); return; } + try { + await post('/license/activate', { key }); + await refreshBootstrap(); + close(); + toast('License activated. Welcome to Enterprise.', 'ok', 'Edition upgraded'); + renderRoute(); + } catch (error) { toastError(error); } + }); + }, + }); +} + +/* -------------------------------------------------------------------------- + Shared components + -------------------------------------------------------------------------- */ +function emptyState(title, text, action = '') { + return `
${icon('database')}
${esc(title)}

${esc(text)}

${action}
`; +} + +function resourceCard(key, label, data, accent = 'accent') { + const util = data?.util; + const b = band(util); + const unit = key === 'storage' ? gb : key === 'cpu' ? (v) => `${trimNum(v, 0)} cores` : gb; + const total = unit(data?.total ?? 0); + const used = unit(data?.used ?? 0); + const growth = key === 'storage' ? gb(data?.growth_per_day ?? 0) : key === 'cpu' ? `${trimNum(data?.growth_per_day ?? 0, 2)} cores` : gb(data?.growth_per_day ?? 0); + return `
+
+
+
${esc(label)}
+
${used} / ${total}
+
${pct(util)} utilized
+
+ ${ring(util ?? 0, { size: 74, stroke: 7, band: b })} +
+
+
+
Free
${unit(data?.free ?? 0)}
+
Growth / day
${growth}
+
Runway
${days(data?.days_to_full)}
+
+
`; +} + +function alertRow(alert, options = {}) { + const open = alert.state === 'open'; + return `
+ +
+
${esc(alert.message)}
+
+ ${esc(alert.asset_name || alert.asset_id)} + ·${esc(alert.metric_label || alert.metric || '')} + ·${timeAgo(alert.created_at)} + ${open ? '' : 'resolved'} +
+
+ ${options.resolve && open ? `` : ''} +
`; +} + +function minModuleName(id) { + const modules = state.boot?.modules || []; + return modules.find((module) => module.id === id)?.name || id; +} + +/* -------------------------------------------------------------------------- + Overview + -------------------------------------------------------------------------- */ +VIEWS.overview = async ({ view, token }) => { + setPage('Fleet overview', 'Capacity posture across every integrated system'); + const data = await get(`/overview?window=${state.windowDays}`); + if (token !== state.renderToken) return; + const k = data.kpis; + const storage = data.resources.storage; + const nearest = k.nearest_exhaustion; + const storageBand = band(storage.util); + const pressureBand = band(k.avg_pressure); + const timeline = data.timeline || {}; + const series = [ + { key: 'cpu', label: 'CPU', color: 'var(--cyan)', points: timeline.cpu_pct || [] }, + { key: 'mem', label: 'Memory', color: 'var(--watch)', points: timeline.mem_pct || [] }, + { key: 'storage', label: 'Storage', color: 'var(--accent)', points: timeline.storage_pct || [], area: true }, + ].filter((item) => item.points.length); + const openAlerts = data.alerts || []; + const modules = data.modules || []; + + view.innerHTML = ` + ${pageHead({ + eyebrow: 'Operations', + title: 'Fleet overview', + sub: `Live headroom across ${k.asset_count} assets in ${k.module_count} modules. ${k.last_collection ? `Last collection ${timeAgo(k.last_collection)}.` : 'Waiting for the first collection.'}`, + actions: `${windowSeg()}${refreshButton()}`, + })} +
+
+
Managed assets${icon('server')}
+
${k.asset_count}assets
+
${k.modules_online} of ${k.module_count} modules online
+
${k.critical_assets} critical${k.warning_assets} warning
+
+
+
Average pressure${icon('activity')}
+
${Math.round(k.avg_pressure)}/ 100
+
${statusPill(pressureBand)}weighted utilization + growth
+
+
+
+
Storage headroom${icon('database')}
+
${pct(storage.util)}used
+
${gb(storage.used)} of ${gb(storage.total)} · ${gb(storage.free)} free
+
+
+
+
Needs attention${icon('bell')}
+
${k.open_alerts}open alerts
+
${nearest ? `Nearest exhaustion: ${esc(nearest.name)}` : 'No exhaustion projected'}
+
${nearest ? `${days(nearest.days_to_full)} to full` : 'Runway healthy'}
+
+
+ ${nearest ? `${icon('alert')} +
${esc(nearest.name)} runs out of ${esc((metricMeta(nearest.metric).label || '').toLowerCase())} in ${days(nearest.days_to_full)} (${fmtDate(nearest.eta_date)}). Currently ${pct(nearest.util)} used. Open asset →
+
` : ''} +
+
+
+

Fleet utilization

Average utilization across active assets · last ${state.windowDays === 1 ? '24 hours' : `${state.windowDays} days`}
+
+ CPU + Memory + Storage +
+
+
+
+
+

Pressure leaders

Highest risk first
+
+ ${(data.top_pressure || []).length ? data.top_pressure.map((asset) => ` + + ${typeIcon(asset.type)} +
+
${esc(asset.name)}
+
${esc(asset.module_name)} · ${esc(asset.type_label || asset.type)}
+
+
+
${pct(asset.util)}${statusPill(asset.status, asset.status_label)}
+
`).join('') : emptyState('No assets yet', 'Enable a module to begin collecting capacity data.')} +
+
+
+
+ ${resourceCard('storage', 'Storage pool', data.resources.storage)} + ${resourceCard('cpu', 'Compute pool', data.resources.cpu)} + ${resourceCard('mem', 'Memory pool', data.resources.mem)} +
+
+
+

Fastest movers

Largest utilization growth per day
+
+ + + + ${(data.movers || []).length ? data.movers.map((asset) => ` + + + + + + `).join('') : ``} + +
AssetUtilizationGrowthRunway
${typeIcon(asset.type)}
${esc(asset.name)}
${esc(asset.module_name)}
${pct(asset.util)}${trendCell(asset)}${days(asset.days_to_full)}
No growth detectedGrowth will appear here as utilization rises over time.
+
+
+
+

Open alerts

${k.open_alerts} unresolved
+
+ ${openAlerts.length ? openAlerts.map((alert) => alertRow(alert)).join('') : emptyState('No open alerts', 'Every policy is within its threshold.')} +
+
+
+
+

Integrations

Collection health
+
+ ${modules.map((module) => ` + + + ${esc(module.name)}${module.asset_count} + `).join('') || 'No modules installed.'} +
+
`; + if (series.length) { + lineChart(view.querySelector('#fleet-chart'), series, { height: 282, max: 100, valueFormat: (value) => `${Math.round(value)}%`, ariaLabel: 'Fleet utilization over time' }); + } else { + view.querySelector('#fleet-chart').innerHTML = '
No telemetry in this window yet.
'; + } + view.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; })); +}; + +/* -------------------------------------------------------------------------- + Assets + -------------------------------------------------------------------------- */ +function assetFilteredRows(items) { + const filter = state.assetFilters; + const needle = filter.q.trim().toLowerCase(); + return items.filter((asset) => { + if (filter.type && asset.type !== filter.type) return false; + if (filter.module && asset.module_id !== filter.module) return false; + if (!needle) return true; + return asset.name.toLowerCase().includes(needle) + || asset.module_name.toLowerCase().includes(needle) + || (asset.cluster || '').toLowerCase().includes(needle) + || (asset.site || '').toLowerCase().includes(needle) + || (asset.tags || []).some((tag) => tag.toLowerCase().includes(needle)); + }); +} + +function assetRow(asset) { + return ` +
+ ${typeIcon(asset.type)} +
${esc(asset.name)}
${esc(asset.module_name)}${asset.cluster ? ` · ${esc(asset.cluster)}` : ''}
+
+ ${esc(asset.type_label || asset.type)}${asset.site ? `
${esc(asset.site)}
` : ''} +
${pct(asset.util)}
+ ${statusPill(asset.status, asset.status_label)} + ${trendCell(asset)} + ${days(asset.days_to_full)} + ${timeAgo(asset.last_seen)} + `; +} + +VIEWS.assets = async ({ view, token }) => { + setPage('Asset inventory', 'Every monitored system in one list'); + const data = await get('/assets'); + if (token !== state.renderToken) return; + const items = data.items || []; + const types = TYPES(); + const modules = [...new Map(items.map((asset) => [asset.module_id, asset.module_name])).entries()]; + const filter = state.assetFilters; + + view.innerHTML = ` + ${pageHead({ + eyebrow: 'Inventory', + title: 'Assets', + sub: `${items.length} active assets reported by ${modules.length} module${modules.length === 1 ? '' : 's'}. Click any row for forecasts and recommendations.`, + actions: `${windowSeg()}${icon('download')} Export CSV${refreshButton()}`, + })} +
+ + + + + Showing ${assetFilteredRows(items).length} of ${items.length} + +
+
+
+ + + ${assetFilteredRows(items).map(assetRow).join('') || ``} +
AssetTypeUtilizationPressureTrendRunwayLast seen
No assets matchAdjust the filters or enable another module.
+
+
${items.length ? `Auto-refreshes every 45 seconds · last collection ${timeAgo(state.boot?.scheduler?.last_run || state.boot?.meta?.generated_at || '')}` : 'No active assets.'}
+
`; + + const tbody = view.querySelector('#asset-tbody'); + const count = view.querySelector('#asset-count'); + const refreshRows = () => { + const filtered = assetFilteredRows(items); + tbody.innerHTML = filtered.length ? filtered.map(assetRow).join('') : `No assets matchAdjust the filters or enable another module.`; + count.textContent = `Showing ${filtered.length} of ${items.length}`; + tbody.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; })); + }; + const bindRowClicks = () => tbody.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; })); + bindRowClicks(); + view.querySelector('#asset-search').addEventListener('input', (event) => { + state.assetFilters.q = event.target.value; + refreshRows(); + }); + view.querySelector('#filter-type').addEventListener('change', (event) => { + state.assetFilters.type = event.target.value; + refreshRows(); + }); + view.querySelector('#filter-module').addEventListener('change', (event) => { + state.assetFilters.module = event.target.value; + refreshRows(); + }); + view.querySelector('#clear-filters').addEventListener('click', () => { + state.assetFilters = { q: '', type: '', module: '' }; + view.querySelector('#asset-search').value = ''; + view.querySelector('#filter-type').value = ''; + view.querySelector('#filter-module').value = ''; + refreshRows(); + }); +}; + +/* -------------------------------------------------------------------------- + Asset detail + -------------------------------------------------------------------------- */ +VIEWS.asset = async ({ view, token, route }) => { + const data = await get(`/assets/${encodeURIComponent(route.id)}?window=30`); + if (token !== state.renderToken) return; + const asset = data.asset; + const analysis = data.analysis || {}; + const cards = data.cards || []; + const forecasts = data.forecasts || {}; + const reco = data.recommendation || {}; + const assetAlerts = data.alerts || []; + setPage(asset.name, `${asset.module_name} · ${asset.type_label}`); + + const capacity = asset.capacity || {}; + const capacityRows = [ + ['Primary metric', metricMeta(analysis.primary_metric).label || analysis.primary_metric], + ['Headroom', pct(analysis.headroom_pct)], + ['Growth', `${analysis.slope_per_day > 0 ? '+' : ''}${trimNum(analysis.slope_per_day, 2)} pp/day`], + ['Days to full', days(analysis.days_to_full)], + ['Projected full', analysis.eta_date ? fmtDate(analysis.eta_date) : '—'], + ['Last sample', timeAgo(asset.last_seen)], + ['First seen', fmtDate(asset.first_seen)], + ['Module status', data.module?.status ? `${data.module.status}${data.module.enabled ? '' : ' · disabled'}` : 'unknown'], + ]; + if (capacity.cpu_cores != null) capacityRows.push(['CPU cores', trimNum(capacity.cpu_cores, 0)]); + if (capacity.mem_gb != null) capacityRows.push(['Memory', gb(capacity.mem_gb)]); + if (capacity.storage_gb != null) capacityRows.push(['Storage', gb(capacity.storage_gb)]); + Object.entries(asset.meta || {}).slice(0, 8).forEach(([key, value]) => capacityRows.push([key.replace(/_/g, ' '), String(value)])); + + const selected = cards.some((card) => card.key === state.assetMetric) ? state.assetMetric : (cards[0]?.key || analysis.primary_metric); + const selectedCard = cards.find((card) => card.key === selected); + + view.innerHTML = ` + ${icon('arrowLeft')} All assets +
+ ${ring(analysis.pressure ?? 0, { size: 96, stroke: 9 })} +
+

${esc(asset.name)} ${statusPill(analysis.status, analysis.status_label)}

+
+ ${esc(asset.type_label || asset.type)} + ${esc(asset.module_name)} + ${asset.cluster ? `·${esc(asset.cluster)}` : ''} + ${asset.site ? `·${esc(asset.site)}` : ''} + ·Last seen ${timeAgo(asset.last_seen)} + ${analysis.stale ? 'stale telemetry' : ''} +
+
+ + ${icon('plug')} Module settings + ${icon('bell')} Alerts +
+
+
+ ${icon(analysis.trend === 'rising' ? 'arrowUp' : analysis.trend === 'falling' ? 'arrowDown' : 'minus')} ${esc(analysis.trend)} +
+
+
+
${esc(reco.level || 'info')}

${esc(reco.title || 'Capacity assessment')}

+

${esc(reco.detail || '')}

+ ${reco.action ? `
${icon('arrowRight')}${esc(reco.action)}
` : ''} +
+
+ ${cards.map((card) => { + const meta = metricMeta(card.key); + const delta = card.delta_24h; + const color = meta.kind === 'util' ? bandColor(band(card.value)) : 'var(--cyan)'; + return `
+
${esc(card.label)}${esc(meta.unit || '')}
+
${esc(metricValue(card.key, card.value))} ${delta != null && delta !== 0 ? `${delta > 0 ? '+' : ''}${trimNum(delta, 1)}` : ''}
+ ${sparkline(card.series, color)} +
`; + }).join('') || `
${icon('info')} No metric cards were reported for this asset.
`} +
+
+
+

Capacity & metadata

Declared capacity and collection state
+
+
${capacityRows.map(([label, value]) => `
${esc(label)}
${esc(value)}
`).join('')}
+ ${(asset.tags || []).length ? `
${asset.tags.map((tag) => `${esc(tag)}`).join('')}
` : ''} +
+ ${icon('download')} Export fleet CSV + +
+
+
+
+
+

Trend & forecast

Observed history plus projected trajectory
+
ObservedForecast
+
+
+ ${cards.map((card) => ``).join('')} +
+
+
+
+
+
+
+
+
+

Forecasts

Linear projection over the next 90 days
+ ${Object.keys(forecasts).length ? `
+ + ${Object.entries(forecasts).map(([key, forecast]) => ` + + + + + `).join('')} +
MetricCurrentGrowthDays to full
${esc(metricMeta(key).label || key)}${esc(metricValue(key, asset.metrics?.[key]))}${forecast.slope_per_day > 0 ? '+' : ''}${trimNum(forecast.slope_per_day, 2)} pp/d${days(forecast.days_to_full)}
` : `
${icon('info')} No upward trend detected in the current window, so no exhaustion forecast is available.
`} +
+
+

Alert history

${assetAlerts.filter((alert) => alert.state === 'open').length} open · ${assetAlerts.length} total
+
${assetAlerts.length ? assetAlerts.slice(0, 8).map((alert) => alertRow(alert)).join('') : emptyState('No alerts', 'This asset has never crossed a policy threshold.')}
+
+
`; + + const drawChart = (key) => { + const card = cards.find((item) => item.key === key); + const container = view.querySelector('#asset-chart'); + if (!card || !container) return; + const meta = metricMeta(key); + const series = [{ label: card.label, color: 'var(--accent)', points: card.series, area: true, dot: true }]; + const forecast = forecasts[key]; + if (forecast) series.push({ label: 'Forecast', color: 'var(--violet)', points: forecast.points, dashed: true }); + const isPct = meta.unit === '%'; + lineChart(container, series, { + height: 272, + max: isPct ? 100 : undefined, + valueFormat: (value) => (isPct ? `${Math.round(value)}%` : `${trimNum(value, 0)}${meta.unit ? ` ${meta.unit}` : ''}`), + ariaLabel: `${card.label} trend`, + }); + const callout = view.querySelector('#forecast-callout'); + callout.innerHTML = forecast + ? `
${icon('chart')}
${esc(card.label)} is growing ${forecast.slope_per_day > 0 ? '+' : ''}${trimNum(forecast.slope_per_day, 2)} ${isPct ? 'pp' : meta.unit || 'units'}/day${forecast.days_to_full ? ` and reaches capacity in ${days(forecast.days_to_full)}` : ''}. The dashed line projects 90 days at the current rate.
` + : `
${icon('info')}
No positive growth trend for this metric in the selected window.
`; + }; + drawChart(selected); + view.querySelectorAll('[data-metric-tab]').forEach((button) => button.addEventListener('click', () => { + state.assetMetric = button.dataset.metricTab; + view.querySelectorAll('[data-metric-tab]').forEach((tab) => tab.classList.toggle('on', tab === button)); + drawChart(button.dataset.metricTab); + })); + view.querySelectorAll('[data-run-module]').forEach((button) => button.addEventListener('click', async () => { + button.disabled = true; + button.classList.add('is-busy'); + try { + const result = await post(`/modules/${encodeURIComponent(button.dataset.runModule)}/run`); + toast(`${result.assets} assets refreshed in ${result.duration_ms} ms`, 'ok', 'Collection complete'); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + finally { button.disabled = false; button.classList.remove('is-busy'); } + })); +}; + +/* -------------------------------------------------------------------------- + Capacity & what-if + -------------------------------------------------------------------------- */ +VIEWS.capacity = async ({ view, token }) => { + setPage('Capacity & forecast', 'Pools, groups and upgrade planning'); + const [data, modulesData] = await Promise.all([get(`/capacity?window=${state.windowDays}`), get('/modules')]); + if (token !== state.renderToken) return; + const groups = data.groups || []; + const modules = (modulesData.items || []).filter((module) => module.enabled); + view.innerHTML = ` + ${pageHead({ + eyebrow: 'Planning', + title: 'Capacity & forecast', + sub: 'Aggregated pools, per-cluster pressure and a what-if simulator for the next hardware decision.', + actions: `${windowSeg()}${refreshButton()}`, + })} +
+ ${resourceCard('storage', 'Storage pool', data.totals.storage)} + ${resourceCard('cpu', 'Compute pool', data.totals.cpu)} + ${resourceCard('mem', 'Memory pool', data.totals.mem)} +
+
+

Clusters & groups

Grouped by cluster label, falling back to module
${groups.length} groups
+
+ + + + ${groups.length ? groups.map((group) => { + const storage = group.resources?.storage || {}; + return ` + + + + + + + + `; + }).join('') : ``} + +
GroupModuleAssetsPeak utilizationPressureStorage runwayStorage
${icon('layers')}
${esc(group.name)}
${esc(group.site || group.types.join(', '))}
${esc(group.module_name)}${group.asset_count}
${pct(group.util)}
${statusPill(group.status, group.status_label)}${days(group.days_to_full)}
${pct(storage.util)}
No groups yetEnable at least one module to build capacity groups.
+
+
+
+

What-if simulator

Model growth and added capacity before you buy hardware
${icon('sparkles')} local model
+
+
+
+ +
+
+ + 1 = current trend, 2 = twice as fast, 0 = no growth. +
+
+ +
+
+ +
+
+ +
+
+
+ ${modules.length ? modules.map((module) => ``).join('') : 'No enabled modules'} +
+
+
+ + + Uses linear growth from the selected window. Results are directional, not a purchase order. +
+
+
+
${icon('info')}
Set a horizon and growth assumption, add planned capacity, then run the model. The simulator also projects every resource pool at the end of the horizon.
+
+
+
`; + + const form = view.querySelector('#sim-form'); + const output = view.querySelector('#sim-output'); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const button = form.querySelector('button[type="submit"]'); + button.disabled = true; + button.classList.add('is-busy'); + const formData = new FormData(form); + const payload = { + horizon_days: Number(formData.get('horizon_days') || 90), + growth_multiplier: Number(formData.get('growth_multiplier') || 1), + add_storage_gb: Number(formData.get('add_storage_gb') || 0), + add_cpu_cores: Number(formData.get('add_cpu_cores') || 0), + add_mem_gb: Number(formData.get('add_mem_gb') || 0), + disable_modules: formData.getAll('disable_modules'), + }; + try { + const result = await post('/capacity/simulate', payload); + state.simResult = result; + renderSimulation(output, result); + } catch (error) { toastError(error); } + finally { button.disabled = false; button.classList.remove('is-busy'); } + }); + form.addEventListener('reset', () => { + setTimeout(() => { + output.innerHTML = `
${icon('info')}
Set a horizon and growth assumption, add planned capacity, then run the model.
`; + }, 0); + }); + if (state.simResult) renderSimulation(output, state.simResult); +}; + +function renderSimulation(output, result) { + const verdictMap = { + healthy: ['healthy', 'Comfortable headroom', 'The fleet stays below 60% on all modeled resources.'], + watch: ['watch', 'Keep watching', 'The plan keeps everything below 80%, but headroom is shrinking.'], + tight: ['tight', 'Tight after the plan', 'At least one resource exceeds 80% at the end of the horizon.'], + critical: ['critical', 'Exceeds safe capacity', 'At least one resource is projected above 90%. Add capacity or reduce growth.'], + }; + const [vClass, vTitle, vText] = verdictMap[result.verdict] || verdictMap.watch; + const resourceLabels = { storage: 'Storage', cpu: 'Compute', mem: 'Memory' }; + const resourceUnits = { storage: 'GB', cpu: 'cores', mem: 'GB' }; + output.innerHTML = ` +
+ ${ring(result.verdict === 'healthy' ? 42 : result.verdict === 'watch' ? 68 : result.verdict === 'tight' ? 85 : 96, { size: 58, stroke: 6, band: vClass })} +
${vTitle}${vText}
+ ${esc(result.verdict)} +
+
+ ${['storage', 'cpu', 'mem'].map((key) => { + const resource = result.resources[key]; + return `
+
${resourceLabels[key]}${pct(resource.util_after)} after
+
+
+
Before${pct(resource.util_before)}
+
After plan${pct(resource.util_after)}
+
Projected use${trimNum(resource.projected_used, 0)} ${resourceUnits[key]}
+
Headroom${trimNum(resource.headroom_after, 0)} ${resourceUnits[key]}
+
+
`; + }).join('')} +
+
+
+
${icon('info')}
${result.asset_count} assets included${result.disabled_modules.length ? ` · excluded: ${result.disabled_modules.map(esc).join(', ')}` : ''} · horizon ${result.horizon_days} days · growth ×${result.growth_multiplier}
+
    ${result.findings.map((finding) => `
  • ${icon('arrowRight')}${esc(finding)}
  • `).join('')}
+
+
+

Projected utilization

Current plan vs. added capacity
+
+ ${['storage', 'cpu', 'mem'].map((key) => ``).join('')} +
+
+
Current planWith additions
+
+
`; + + const drawSim = (resource) => { + const before = result.series.before.map((point) => ({ t: point.t, v: point.values[resource] ?? 0 })); + const after = result.series.after.map((point) => ({ t: point.t, v: point.values[resource] ?? 0 })); + lineChart(output.querySelector('#sim-chart'), [ + { label: 'Current plan', color: 'var(--crit)', points: before, dashed: true }, + { label: 'With additions', color: 'var(--accent)', points: after, area: true, dot: true }, + ], { height: 240, max: 100, valueFormat: (value) => `${Math.round(value)}%`, ariaLabel: 'Projected utilization' }); + }; + drawSim('storage'); + output.querySelectorAll('[data-sim-resource]').forEach((button) => button.addEventListener('click', () => { + output.querySelectorAll('[data-sim-resource]').forEach((item) => item.classList.toggle('on', item === button)); + drawSim(button.dataset.simResource); + })); +} + +/* -------------------------------------------------------------------------- + Alerts & policies + -------------------------------------------------------------------------- */ +VIEWS.alerts = async ({ view, token }) => { + setPage('Alerts', 'Policy breaches and threshold history'); + const [data, policiesData] = await Promise.all([get(`/alerts?include_resolved=${state.alertResolved}`), get('/policies')]); + if (token !== state.renderToken) return; + const items = data.items || []; + const policies = policiesData.items || []; + const canOperate = ['admin', 'operator'].includes(state.boot.user.role); + const utilMetrics = META().util_metrics || ['cpu_pct', 'mem_pct', 'storage_pct']; + view.innerHTML = ` + ${pageHead({ + eyebrow: 'Operations', + title: 'Alerts', + sub: `${data.open} open · ${data.critical} critical · ${data.warning} warning`, + actions: `${icon('download')} Export${refreshButton()}`, + })} +
+
+

${state.alertResolved ? 'Alert history' : 'Open alerts'}

Ordered by severity, then newest first
${data.critical} critical
+
${items.length ? items.map((alert) => alertRow(alert, { resolve: canOperate })).join('') : emptyState('No alerts', state.alertResolved ? 'No alerts have been recorded yet.' : 'Everything is within policy thresholds.')}
+
+
+

Policy coverage

Thresholds evaluated after every collection
+
+
+

How it works

+

Each enabled policy is evaluated against every asset that reports the metric. Crossing the warning threshold opens a warning; crossing critical updates it. Values below warning resolve it automatically.

+
  • Warning and critical are percentages.
  • One open alert per asset, metric and policy.
  • Resolve manually to close it without waiting for the next collection.
+
+
+ ${canOperate ? `` : ''} + ${icon('bell')} Webhook settings +
+
+
+
+
+

Policies

${policies.length} configured
${canOperate ? `` : ''}
+
+ + + + ${policies.length ? policies.map((policy) => ` + + + + + + + `).join('') : ``} + +
PolicyMetricWarningCriticalEnabledActions
${esc(policy.name)}
created ${fmtDate(policy.created_at)}
${esc(metricMeta(policy.metric).label || policy.metric)}${trimNum(policy.warn, 0)}%${trimNum(policy.crit, 0)}%${canOperate ? `` : '—'}
No policiesAdd a threshold to start generating alerts.
+
+
`; + + view.querySelector('#show-resolved').addEventListener('change', (event) => { + state.alertResolved = event.target.checked; + renderRoute(); + }); + + const policyById = (id) => policies.find((policy) => String(policy.id) === String(id)); + view.querySelectorAll('[data-resolve]').forEach((button) => button.addEventListener('click', async () => { + button.disabled = true; + try { + await post(`/alerts/${button.dataset.resolve}/resolve`); + toast('Alert resolved'); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); button.disabled = false; } + })); + view.querySelectorAll('[data-new-policy]').forEach((button) => button.addEventListener('click', () => openPolicyModal(null, utilMetrics))); + view.querySelectorAll('[data-policy-edit]').forEach((button) => button.addEventListener('click', () => openPolicyModal(policyById(button.dataset.policyEdit), utilMetrics))); + view.querySelectorAll('[data-policy-toggle]').forEach((input) => input.addEventListener('change', async () => { + const policy = policyById(input.dataset.policyToggle); + if (!policy) return; + try { + await put(`/policies/${policy.id}`, { name: policy.name, metric: policy.metric, warn: policy.warn, crit: policy.crit, enabled: input.checked }); + toast(`Policy ${input.checked ? 'enabled' : 'disabled'}`); + renderRoute(); + } catch (error) { toastError(error); input.checked = !input.checked; } + })); + view.querySelectorAll('[data-policy-delete]').forEach((button) => button.addEventListener('click', async () => { + const policy = policyById(button.dataset.policyDelete); + if (!policy) return; + if (!(await confirmDialog({ title: 'Delete policy', message: `Delete ${esc(policy.name)}? Open alerts from this policy will be resolved.`, confirmLabel: 'Delete policy', danger: true }))) return; + try { + await del(`/policies/${policy.id}`); + toast('Policy deleted'); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + })); +}; + +function openPolicyModal(policy, utilMetrics) { + const isEdit = Boolean(policy); + const metricOptions = [...new Set([...(utilMetrics || []), ...(policy ? [policy.metric] : [])])]; + openModal({ + title: isEdit ? 'Edit policy' : 'New capacity policy', + sub: isEdit ? esc(policy.name) : 'Alerts are evaluated after every module run', + body: `
+
+
+ +
+
+
+
+
`, + footer: ``, + onMount(modal, close) { + const form = modal.querySelector('#policy-form'); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(form); + const payload = { + name: String(formData.get('name') || '').trim(), + metric: String(formData.get('metric') || 'storage_pct'), + warn: Number(formData.get('warn')), + crit: Number(formData.get('crit')), + enabled: formData.get('enabled') === 'on', + }; + if (payload.warn >= payload.crit) { toast('Warning must be below critical', 'warn'); return; } + try { + if (isEdit) await put(`/policies/${policy.id}`, payload); + else await post('/policies', payload); + close(); + toast(isEdit ? 'Policy updated' : 'Policy created'); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + }); + }, + }); +} + +/* -------------------------------------------------------------------------- + Modules + -------------------------------------------------------------------------- */ +function moduleStatusText(module) { + if (!module.enabled) return 'Disabled'; + if (module.status === 'ok') return 'Connected'; + if (module.status === 'error') return 'Collection failed'; + if (module.status === 'pending') return 'Awaiting first run'; + if (module.status === 'missing') return 'Files missing'; + return module.status || 'Unknown'; +} + +function moduleDot(module) { + if (!module.enabled) return 'disabled'; + if (module.status === 'ok') return 'ok'; + if (module.status === 'error') return 'error'; + if (module.status === 'pending') return 'pending'; + return 'disabled'; +} + +VIEWS.modules = async ({ view, token }) => { + setPage('Modules', 'Integrations, collector health and custom plugins'); + const data = await get('/modules'); + if (token !== state.renderToken) return; + const modules = data.items || []; + const isAdmin = state.boot.user.role === 'admin'; + const canOperate = ['admin', 'operator'].includes(state.boot.user.role); + const customAllowed = Boolean(state.boot.features.custom_modules); + const limit = Number(state.boot.limits?.assets ?? -1); + const limitWarning = limit > 0 && state.boot.asset_count >= limit; + const types = [...new Map(modules.map((m) => [m.module_type, m])).values()]; + view.innerHTML = ` + ${pageHead({ + eyebrow: 'Platform', + title: 'Modules', + sub: 'Toggle collectors, tune connections and upload your own integrations. Multiple instances of the same module type are supported.', + actions: `${isAdmin ? `` : ''}${customAllowed ? `` : ``}${refreshButton()}`, + })} + ${limitWarning ? `
${icon('alert')}
Community asset limit reached (${limit}). New assets will not be stored until the limit is raised.
` : ''} +
+ ${modules.length} instances · ${types.length} types · ${modules.filter((module) => module.enabled).length} enabled · ${modules.reduce((sum, module) => sum + (module.asset_count || 0), 0)} assets + + ${modules.filter((module) => module.source === 'bundled').length} bundled instances + ${modules.filter((module) => module.source === 'custom').length} custom instances + ${!isAdmin ? `${icon('lock')} read-only` : ''} +
+
+ ${modules.map((module) => { + const isCustom = module.source === 'custom'; + const instanceCount = module.instance_count || 1; + const canDelete = isAdmin && (isCustom || instanceCount > 1); + return `
+
+ ${icon(MODULE_ICON[module.icon] || MODULE_ICON[module.module_type] || MODULE_ICON[module.id] || 'plug')} +
+

${esc(module.name || module.instance_name)} ${isCustom ? 'custom' : 'bundled'}${instanceCount > 1 ? ` x${instanceCount}` : ''}

+
${esc(module.type_name || module.vendor || 'Community')} · ${esc(module.module_type || module.id)} · v${esc(module.version || '—')} · ${esc(module.category || 'other')}
+
+ +
+

${esc(module.description || 'No description provided.')}

+
${esc(moduleStatusText(module))}${module.message ? `· ${esc(module.message.length > 62 ? `${module.message.slice(0, 62)}…` : module.message)}` : ''}
+
+
Assets
${module.asset_count || 0}
+
Interval
${module.interval_seconds || 300}s
+
Last run
${timeAgo(module.last_run)}
+
Instance
${esc(module.id)}
+
+
+ + + + + ${isAdmin ? `` : ''} + ${canDelete ? `` : ''} +
+
`; + }).join('')} +
+ ${modules.length ? '' : `
${emptyState('No modules installed', 'Add an instance or upload a module package.', customAllowed ? `` : '')}
`}`; + + const moduleById = (id) => modules.find((module) => module.id === id); + view.querySelectorAll('[data-module-toggle]').forEach((input) => input.addEventListener('change', async () => { + const module = moduleById(input.dataset.moduleToggle); + if (!module) return; + input.disabled = true; + try { + await put(`/modules/${encodeURIComponent(module.id)}`, { enabled: input.checked }); + toast(`${module.name} ${input.checked ? 'enabled — first collection is starting' : 'disabled'}`); + await refreshBootstrap(); + renderRoute(); + if (input.checked) setTimeout(() => { if (state.route.name === 'modules') renderRoute(true); }, 3200); + } catch (error) { toastError(error); input.checked = !input.checked; input.disabled = false; } + })); + + view.querySelectorAll('[data-module-run]').forEach((button) => button.addEventListener('click', async () => { + const module = moduleById(button.dataset.moduleRun); + button.disabled = true; + button.classList.add('is-busy'); + try { + const result = await post(`/modules/${encodeURIComponent(module.id)}/run`); + toast(`${result.assets} assets · ${result.metrics} metrics · ${result.duration_ms} ms`, 'ok', `${module.name} collected`); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + finally { button.disabled = false; button.classList.remove('is-busy'); } + })); + + view.querySelectorAll('[data-module-test]').forEach((button) => button.addEventListener('click', async () => { + const module = moduleById(button.dataset.moduleTest); + button.disabled = true; + button.classList.add('is-busy'); + try { + const result = await post(`/modules/${encodeURIComponent(module.id)}/test`); + toast(result.message || 'Connection test completed', result.ok ? 'ok' : 'warn', `${module.name} test`); + } catch (error) { toastError(error); } + finally { button.disabled = false; button.classList.remove('is-busy'); } + })); + + view.querySelectorAll('[data-module-config]').forEach((button) => button.addEventListener('click', () => openModuleConfig(moduleById(button.dataset.moduleConfig)))); + view.querySelectorAll('[data-module-logs]').forEach((button) => button.addEventListener('click', () => openModuleLogs(moduleById(button.dataset.moduleLogs)))); + view.querySelectorAll('[data-module-delete]').forEach((button) => button.addEventListener('click', async () => { + const module = moduleById(button.dataset.moduleDelete); + if (!module) return; + if (!(await confirmDialog({ title: 'Delete instance', message: `Delete instance ${esc(module.name)} and remove its assets and metric history? This cannot be undone.`, confirmLabel: 'Delete instance', danger: true }))) return; + try { + await del(`/modules/${encodeURIComponent(module.id)}`); + toast(`${module.name} removed`); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + })); + + view.querySelectorAll('[data-module-clone]').forEach((button) => button.addEventListener('click', async () => { + const module = moduleById(button.dataset.moduleClone); + if (!module || !(state.boot.user && state.boot.user.role === 'admin')) return; + try { + const label = prompt(`Name for new ${module.type_name || module.name} instance`, `${module.name} 2`); + if (label === null) return; + await post('/modules/instances', { module_type: module.module_type, name: label, copy_from: module.id }); + toast('Instance added', 'ok'); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + })); + + const addInstance = view.querySelector('#add-module-instance'); + if (addInstance) { + addInstance.addEventListener('click', async () => { + if (!(state.boot.user && state.boot.user.role === 'admin')) return; + const choices = types.map((m) => ``).join(''); + openModal({ + title: 'Add module instance', + sub: 'Create another collector instance for the same module type', + body: `
+
+
+
`, + footer: ``, + onMount(modal, close) { + const form = modal.querySelector('#add-instance-form'); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(form); + try { + await post('/modules/instances', { module_type: String(formData.get('module_type') || ''), name: String(formData.get('name') || '') }); + close(); + toast('Instance added', 'ok'); + await refreshBootstrap(); + renderRoute(); + } catch (error) { toastError(error); } + }); + }, + }); + }); + } + + const upload = view.querySelector('#upload-module'); + if (upload) upload.addEventListener('click', openUploadModal); + const uploadAgain = view.querySelector('[data-upload-again]'); + if (uploadAgain) uploadAgain.addEventListener('click', openUploadModal); +}; + +function openModuleConfig(module) { + if (!module) return; + if (state.boot.user.role !== 'admin') { toast('Administrator role required', 'warn'); return; } + const config = module.config || {}; + const secretSet = module.secret_set || {}; + const fields = (module.settings_schema || []).map((item) => { + const key = item.key; + const label = item.label || key; + const type = item.type || 'text'; + const value = config[key]; + const help = item.help ? `${esc(item.help)}` : ''; + if (type === 'boolean') { + return `
${help}
`; + } + if (type === 'select') { + const options = (item.options || []).map((option) => { + const optionValue = typeof option === 'object' ? option.value : option; + const optionLabel = typeof option === 'object' ? (option.label || option.value) : option; + return ``; + }).join(''); + return `
${help}
`; + } + if (type === 'textarea') { + return `
${help}
`; + } + if (type === 'password') { + const placeholder = secretSet[key] ? 'Saved — leave blank to keep the current value' : (item.placeholder || ''); + return `
${help}
`; + } + const inputType = type === 'number' ? 'number' : 'text'; + const step = type === 'number' ? ' step="any"' : ''; + return `
${help}
`; + }).join(''); + const demo = config.demo; + openModal({ + title: `Configure ${module.name}`, + sub: `${module.source} module · v${esc(module.version || '—')}`, + wide: true, + body: `
+ ${demo ? `
${icon('info')}
Demo mode is on. The module generates realistic local data. Turn it off and add connection details to collect from the real system.
` : ''} + ${fields || `
${icon('info')}
This module exposes no configurable settings.
`} +
+
${icon('shield')}
Secrets are masked in the UI and stored in the local SQLite database. Module code runs in an isolated subprocess with a 90-second timeout.
`, + footer: ``, + onMount(modal, close) { + const form = modal.querySelector('#module-config-form'); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const payload = {}; + for (const item of module.settings_schema || []) { + const element = form.elements.namedItem(item.key); + if (!element) continue; + if ((item.type || 'text') === 'boolean') payload[item.key] = element.checked; + else if ((item.type || 'text') === 'number') payload[item.key] = element.value === '' ? (config[item.key] ?? 0) : Number(element.value); + else payload[item.key] = element.value; + } + try { + await put(`/modules/${encodeURIComponent(module.id)}`, { config: payload }); + close(); + toast(`${module.name} configuration saved`); + renderRoute(); + } catch (error) { toastError(error); } + }); + }, + }); +} + +function openModuleLogs(module) { + if (!module) return; + openModal({ + title: `${module.name} logs`, + sub: 'Most recent collector output', + wide: true, + body: `
${icon('refresh')}
Loading logs…
`, + footer: ``, + onMount(modal) { + const load = async () => { + const body = modal.querySelector('#module-logs-body'); + body.innerHTML = `
${icon('refresh')}
Loading logs…
`; + try { + const data = await get(`/modules/${encodeURIComponent(module.id)}/logs`); + body.innerHTML = data.logs ? `
${esc(data.logs)}
` : `
${icon('info')}
No log output yet. Run the module once to collect diagnostics.
`; + } catch (error) { + body.innerHTML = `
${icon('alert')}
${esc(error.message)}
`; + } + }; + load(); + modal.querySelector('#reload-logs').addEventListener('click', load); + }, + }); +} + +function openUploadModal() { + if (!state.boot.features.custom_modules) { openUpgrade('custom_modules'); return; } + openModal({ + title: 'Upload a module', + sub: 'Signed-out-of-the-box: a zip with manifest.json and module.py', + wide: true, + body: `
+ ${icon('upload')} + Drop a module zip here + or click to choose a file · max 2 MB + +
+
+
${icon('shield')}
Uploads are validated: manifest schema, module id, package paths and size. Module code executes in a subprocess with resource limits. Review third-party code before enabling it.
+
${icon('code')}
The package must contain manifest.json and module.py at the root (or inside one top-level folder).
`, + footer: ``, + onMount(modal, close) { + let file = null; + const drop = modal.querySelector('#upload-drop'); + const input = modal.querySelector('#upload-file'); + const selected = modal.querySelector('#upload-selected'); + const submit = modal.querySelector('#upload-submit'); + const choose = (chosen) => { + if (!chosen) return; + file = chosen; + selected.innerHTML = `
${icon('box')}${esc(chosen.name)}${(chosen.size / 1024).toFixed(1)} KB
`; + submit.disabled = false; + }; + drop.addEventListener('click', () => input.click()); + input.addEventListener('change', () => choose(input.files[0])); + drop.addEventListener('dragover', (event) => { event.preventDefault(); drop.style.borderColor = 'var(--accent)'; }); + drop.addEventListener('dragleave', () => { drop.style.borderColor = ''; }); + drop.addEventListener('drop', (event) => { + event.preventDefault(); + drop.style.borderColor = ''; + choose(event.dataTransfer.files[0]); + }); + submit.addEventListener('click', async () => { + if (!file) return; + submit.disabled = true; + submit.classList.add('is-busy'); + const formData = new FormData(); + formData.append('file', file); + try { + const result = await request('/modules/upload', { method: 'POST', body: formData }); + close(); + toast(`${result.name} v${result.version} registered. Configure and enable it to collect.`, 'ok', 'Module uploaded'); + renderRoute(); + } catch (error) { + toastError(error); + submit.disabled = false; + submit.classList.remove('is-busy'); + } + }); + }, + }); +} + +/* -------------------------------------------------------------------------- + Copilot + -------------------------------------------------------------------------- */ +function inlineMarkdown(text) { + return text + .replace(/\*\*(.+?)\*\*/g, '$1') + .replace(/`([^`]+)`/g, '$1'); +} + +function markdown(text) { + const lines = esc(text || '').split('\n'); + const out = []; + let inList = false; + for (const raw of lines) { + const line = raw.trimEnd(); + if (/^\s*[-*]\s+/.test(line)) { + if (!inList) { out.push('
    '); inList = true; } + out.push(`
  • ${inlineMarkdown(line.replace(/^\s*[-*]\s+/, ''))}
  • `); + continue; + } + if (inList) { out.push('
'); inList = false; } + if (!line.trim()) continue; + out.push(`

${inlineMarkdown(line)}

`); + } + if (inList) out.push(''); + return out.join(''); +} + +VIEWS.copilot = async ({ view, token }) => { + setPage('Copilot', 'Capacity analysis and conversational planning'); + let aiConfig = { config: {}, suggested_questions: [] }; + try { aiConfig = await get('/ai/config'); } catch { /* ignore */ } + if (token !== state.renderToken) return; + const features = state.boot.features || {}; + const config = aiConfig.config || {}; + const suggestions = aiConfig.suggested_questions || []; + const edition = state.boot.edition; + const llm = features.llm_copilot; + view.innerHTML = ` + ${pageHead({ + eyebrow: 'AI operations', + title: 'Capacity copilot', + sub: 'Ask about risk, growth or the next upgrade. Local analysis works on every edition; conversational answers unlock with Enterprise.', + actions: `${llm ? (config.configured ? 'LLM connected' : 'LLM not configured') : 'Local analysis'}`, + })} +
+
+

Ask Headroom

Grounded in your live fleet data
${llm && config.configured ? 'live context' : 'deterministic insights'}
+
+
+ ${suggestions.map((question) => ``).join('')} +
+
+ + +
+
+ +
`; + + const log = view.querySelector('#chat-log'); + const form = view.querySelector('#chat-form'); + const input = view.querySelector('#chat-text'); + const send = view.querySelector('#chat-send'); + + const renderLog = () => { + log.innerHTML = ` + ${state.chat.map((message) => { + const isUser = message.role === 'user'; + return `
+
${icon(isUser ? 'server' : 'sparkles')}
+
+
${markdown(message.content)}
+ ${message.note ? `
${esc(message.note)}
` : ''} + ${message.upgrade ? `
${icon('lock')}
Enterprise unlocks conversational answers with your own LLM provider.
` : ''} + ${message.mode ? `
${message.mode === 'llm' ? icon('sparkles') : icon('activity')} ${message.mode === 'llm' ? 'LLM narrative' : 'Local analysis'}
` : ''} +
+
`; + }).join('')} + ${state.chatLoading ? `
${icon('sparkles')}
` : ''}`; + log.scrollTop = log.scrollHeight; + }; + + const appendError = (error) => { + state.chat.push({ role: 'assistant', content: `I could not complete that request: ${error.message}`, error: true }); + }; + + const ask = async (text, { hidden = false } = {}) => { + if (state.chatLoading) return; + if (!hidden) state.chat.push({ role: 'user', content: text }); + state.chatLoading = true; + renderLog(); + send.disabled = true; + try { + const messages = state.chat.filter((message) => !message.hidden && !message.error && message.role !== 'system').map((message) => ({ role: message.role, content: message.content })); + const response = await post('/ai/chat', { messages }); + state.chat.push({ + role: 'assistant', + content: response.message || 'No response', + note: response.note, + mode: response.mode, + upgrade: Boolean(response.upgrade_required), + }); + } catch (error) { + appendError(error); + } finally { + state.chatLoading = false; + send.disabled = false; + renderLog(); + } + }; + + renderLog(); + if (!state.chat.length && !state.chatLoading) { + ask('Give me a capacity briefing for this fleet.', { hidden: true }); + } + + form.addEventListener('submit', (event) => { + event.preventDefault(); + const text = input.value.trim(); + if (!text || state.chatLoading) return; + input.value = ''; + input.style.height = '42px'; + ask(text); + }); + input.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + form.requestSubmit(); + } + }); + input.addEventListener('input', () => { + input.style.height = '42px'; + input.style.height = `${Math.min(150, input.scrollHeight)}px`; + }); + view.querySelectorAll('[data-question]').forEach((button) => button.addEventListener('click', () => ask(button.dataset.question))); + view.querySelector('[data-clear-chat]').addEventListener('click', () => { + state.chat = []; + renderLog(); + ask('Give me a capacity briefing for this fleet.', { hidden: true }); + }); + const configButton = view.querySelector('[data-ai-config]'); + if (configButton) configButton.addEventListener('click', () => openAiConfigModal(config)); + if (llm && !config.configured) { + // Keep the local briefing visible and make configuration discoverable. + if (!state.chat.some((message) => message.note)) { + // no-op: response note will explain the fallback + } + } +}; + +function openAiConfigModal(config) { + if (!state.boot.features.llm_copilot) { openUpgrade('llm_copilot'); return; } + openModal({ + title: 'LLM provider', + sub: 'Any OpenAI-compatible chat completions endpoint', + wide: true, + body: `
+
+ + Headroom appends /chat/completions. Works with OpenAI, Azure, Ollama, LM Studio and LiteLLM. +
+
+
+
${icon('shield')}
The key is stored server-side in SQLite and never returned to the browser. Only fleet aggregates and alert messages are sent to the provider — no credentials.
+
`, + footer: ``, + onMount(modal, close) { + const form = modal.querySelector('#ai-config-form'); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(form); + const payload = { base_url: String(formData.get('base_url') || ''), model: String(formData.get('model') || '') }; + const key = String(formData.get('api_key') || ''); + if (key) payload.api_key = key; + try { + await put('/ai/config', payload); + close(); + toast('LLM provider saved'); + renderRoute(); + } catch (error) { toastError(error); } + }); + }, + }); +} + +/* -------------------------------------------------------------------------- + API & MCP + -------------------------------------------------------------------------- */ +const API_ENDPOINTS = [ + ['GET', '/api/overview', 'Fleet KPIs, pools, leaders and timeline'], + ['GET', '/api/assets', 'Asset inventory with pressure and forecasts'], + ['GET', '/api/assets/{id}', 'Timeseries, forecast and recommendation'], + ['GET', '/api/capacity', 'Groups and aggregated resource pools'], + ['POST', '/api/capacity/simulate', 'What-if simulation'], + ['GET', '/api/alerts', 'Open or resolved alerts'], + ['GET', '/api/modules', 'Collector health and configuration'], + ['POST', '/api/modules/{id}/run', 'Trigger a collection'], + ['POST', '/api/ingest/{module_id}', 'Push assets and metrics'], + ['POST', '/api/mcp', 'MCP JSON-RPC endpoint'], +]; + +VIEWS.api = async ({ view, token }) => { + setPage('API & MCP', 'Automation surface for scripts and AI agents'); + const [mcpCatalog, keysData, aiConfig] = await Promise.all([ + get('/mcp').catch(() => null), + state.boot.user.role === 'admin' ? get('/keys').catch(() => null) : Promise.resolve(null), + get('/ai/config').catch(() => null), + ]); + if (token !== state.renderToken) return; + const tab = state.apiTab; + const base = location.origin; + const keys = keysData?.items || []; + const cat = mcpCatalog || { enabled: false, tools: [], resources: [], example: {} }; + const config = aiConfig?.config || {}; + const tabs = [['rest', 'REST API'], ['keys', 'API keys'], ['mcp', 'MCP server'], ['ai', 'AI provider']]; + + const restPanel = ` +
+
+

Authenticate

Two supported methods
+
+
${icon('shield')}
Session cookie — used by this UI. X-API-Key — create a key for scripts and agents. Keys inherit the role you assign.
+
+
Base URL
${esc(base)}
+
Auth header
X-API-Key: hr_…
+
OpenAPI
/docs
+
+
+
+
+

Endpoints

${API_ENDPOINTS.length} commonly used routes
+
${API_ENDPOINTS.map(([method, path, desc]) => `
${method}${path}${desc}
`).join('')}
+
+
+
+

Quick start

Read the fleet with an API key
+
curl -s ${esc(base)}/api/overview \\
+  -H "X-API-Key: hr_your_key_here"
+
+curl -s ${esc(base)}/api/assets \\
+  -H "X-API-Key: hr_your_key_here"
+
${icon('code')}
Push custom telemetry into an enabled module: POST /api/ingest/http-json with {"assets":[{ "external_id":"ups-1", "name":"UPS", "type":"power", "metrics":{"load_pct":42} }]}.
+
`; + + const keysPanel = keysData === null + ? `
${icon('lock')}
Administrator role required to manage API keys.
` + : `
+
+

API keys

${keys.length} active
+
+ + ${keys.length ? keys.map((key) => ` + + + + + + `).join('') : ``} +
NamePrefixRoleLast usedActions
${esc(key.name)}
created ${fmtDate(key.created_at)}
${esc(key.prefix)}…${esc(key.role)}${key.last_used ? timeAgo(key.last_used) : 'never'}
No API keysCreate one to automate Headroom.
+
+
+

Create a key

Shown once, stored hashed
+
+
+
+
+ +
+
${icon('shield')}
Revoke unused keys regularly. The plaintext key is never stored and cannot be recovered.
+
+
+
`; + + const mcpPanel = ` + ${cat.enabled ? '' : `
+

MCP server is an Enterprise capability

+

Give Claude Desktop, Cursor or a custom agent read access to capacity data and the ability to run collectors. Uses the same signed API keys as the REST API.

+ +
`} +
+
+

Connection

Streamable HTTP · JSON-RPC 2.0
${cat.enabled ? 'enabled' : 'locked'}
+
+
+
Endpoint
${esc(base)}/api/mcp
+
Protocol
${esc(cat.protocol_version || '2024-11-05')}
+
Auth
X-API-Key
+
Tools
${cat.tools?.length || 0}
+
+
+ + +
+ +
+
+
+

Client config

Claude Desktop example
+
${esc(JSON.stringify(cat.example || {}, null, 2))}
+
+
+
+
+

Resources

Read-only context objects
+
+ ${(cat.resources || []).map((resource) => ``).join('')} +
URIDescription
${esc(resource.uri)}${esc(resource.description || resource.name)}
+
+
+

Tools

${cat.tools?.length || 0} capabilities
+
+ ${(cat.tools || []).map((tool) => ``).join('')} +
ToolDescription
${esc(tool.name)}${esc(tool.description)}
+
+
`; + + const aiPanel = ` +
+
+

Provider configuration

${state.boot.features.llm_copilot ? 'Enterprise enabled' : 'Enterprise capability'}
+
+ ${state.boot.features.llm_copilot + ? `
+
+
+
+
+
` + : `
${icon('lock')}
LLM copilot requires Enterprise. The local deterministic analysis remains available in the copilot view.
`} +
+
+
+

Provider status

OpenAI-compatible
+
+
+
Configured
${config.configured ? 'yes' : 'no'}
+
Base URL
${esc(config.base_url || '—')}
+
Model
${esc(config.model || '—')}
+
Key
${config.key_set ? 'saved' : 'not set'}
+
+
${icon('info')}
${esc(config.provider_hint || 'Any OpenAI-compatible chat completions endpoint.')}
+ ${icon('sparkles')} Open copilot +
+
+
`; + + const panels = { rest: restPanel, keys: keysPanel, mcp: mcpPanel, ai: aiPanel }; + view.innerHTML = ` + ${pageHead({ eyebrow: 'Platform', title: 'API & MCP', sub: 'Everything in Headroom is available over the REST API. Enterprise adds an MCP server, API keys with roles and an LLM provider.', actions: `${icon('external')} API docs${refreshButton()}` })} +
+ ${tabs.map(([key, label]) => ``).join('')} +
+ ${panels[tab] || restPanel}`; + + view.querySelectorAll('[data-api-tab]').forEach((button) => button.addEventListener('click', () => { + state.apiTab = button.dataset.apiTab; + renderRoute(); + })); + view.querySelectorAll('[data-copy-target]').forEach((button) => button.addEventListener('click', () => { + const target = view.querySelector(`#${button.dataset.copyTarget}`); + if (target) copyText(target.textContent); + })); + + if (tab === 'keys' && keysData !== null) { + view.querySelectorAll('[data-key-delete]').forEach((button) => button.addEventListener('click', async () => { + if (!(await confirmDialog({ title: 'Revoke API key', message: 'Any client using this key will lose access immediately.', confirmLabel: 'Revoke key', danger: true }))) return; + try { + await del(`/keys/${button.dataset.keyDelete}`); + toast('API key revoked'); + renderRoute(); + } catch (error) { toastError(error); } + })); + const form = view.querySelector('#key-form'); + form?.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(form); + try { + const result = await post('/keys', { name: String(formData.get('name') || ''), role: String(formData.get('role') || 'viewer') }); + openModal({ + title: 'API key created', + sub: 'Copy it now — it is shown only once', + body: `
${icon('key')}
${esc(result.name)} · ${esc(result.role)}
+
${esc(result.key)}
`, + footer: ``, + onMount(modal, close) { + modal.querySelector('[data-copy-key]').addEventListener('click', () => copyText(result.key)); + modal.querySelector('[data-close]').addEventListener('click', () => { close(); renderRoute(); }); + }, + }); + } catch (error) { toastError(error); } + }); + } + + if (tab === 'mcp') { + const ping = view.querySelector('#mcp-ping'); + ping?.addEventListener('click', async () => { + const output = view.querySelector('#mcp-result'); + output.hidden = false; + output.textContent = 'Calling initialize…'; + try { + const result = await post('/mcp', { jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }); + output.textContent = JSON.stringify(result, null, 2); + if (result.error) toast(result.error.message || 'MCP call returned an error', 'warn'); + else toast('MCP server responded', 'ok'); + } catch (error) { + output.textContent = error.message; + toastError(error); + } + }); + } + + if (tab === 'ai') { + const form = view.querySelector('#ai-page-form'); + form?.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(form); + const payload = { base_url: String(formData.get('base_url') || ''), model: String(formData.get('model') || '') }; + const key = String(formData.get('api_key') || ''); + if (key) payload.api_key = key; + try { + await put('/ai/config', payload); + toast('LLM provider saved'); + renderRoute(); + } catch (error) { toastError(error); } + }); + } +}; + +/* -------------------------------------------------------------------------- + Settings + -------------------------------------------------------------------------- */ +VIEWS.settings = async ({ view, token }) => { + setPage('Settings', 'Edition, security and platform configuration'); + const isAdmin = state.boot.user.role === 'admin'; + const [settings, license, editions, auditData] = await Promise.all([ + get('/settings'), + get('/license'), + get('/editions').catch(() => null), + isAdmin ? get('/audit?limit=100').catch(() => null) : Promise.resolve(null), + ]); + if (token !== state.renderToken) return; + + const tabs = [['general', 'General'], ['license', 'Edition & license'], ['security', 'Security'], ['audit', 'Audit log'], ['about', 'About']]; + const tab = tabs.some(([key]) => key === state.settingsTab) ? state.settingsTab : 'general'; + const paid = license.edition !== 'community'; + const matrix = editions?.matrix || []; + const audit = auditData?.items || []; + const sched = settings.scheduler || {}; + const assetLimit = Number(license.limits?.assets ?? 40); + const assetCount = Number(state.boot.asset_count || 0); + const assetUsage = assetLimit > 0 ? Math.min(100, Math.round((assetCount / assetLimit) * 100)) : 0; + const maxRetention = Number(license.limits?.retention_days || 30); + const trialAvailable = Boolean(license.trial_available) && !paid; + const canModify = isAdmin; + const disabled = canModify ? '' : 'disabled'; + + const currentLicense = paid + ? `
+ ${license.source === 'trial' + ? ring(Math.max(0, Math.min(100, ((Number(license.days_left) || 0) / 30) * 100)), { size: 62, stroke: 7, suffix: 'days' }) + : `${icon('shield')}`} +
+ ${esc(license.label)} + ${license.customer ? `${esc(license.customer)} · ` : ''}${license.expires ? `Valid until ${fmtDate(license.expires)}` : 'Open-ended license'}${license.days_left != null ? ` · ${license.days_left} days left` : ''} +
+ ${license.source === 'trial' ? 'TRIAL' : 'ACTIVE'} +
` + : `
+ ${icon('layers')} +
+ Community edition + Free forever · ${license.limits?.assets ?? 40} assets · ${license.limits?.retention_days ?? 30}-day retention · bundled modules only +
+ +
`; + + const matrixRows = matrix.map((group) => ` + ${esc(group.group)} + ${group.features.map((feature) => ` + ${esc(feature.label)} + ${feature.community ? icon('check') : icon('minus')} + ${icon('check')} + `).join('')} + `).join(''); + + const generalPanel = ` +
+
+

Site & retention

Applied to dashboards, exports and the API
${canModify ? '' : 'read only'}
+
+ ${canModify ? '' : `
${icon('lock')}
Administrator role required to change these settings.
`} +
+
+ + + Shown in the browser title, sign-in screen and reports. +
+
+ + + Effective retention: ${settings.effective_retention_days} days.${paid ? '' : ' Enterprise extends this to 400 days.'} +
+
+ + + ${state.boot.features.alert_webhooks ? 'New alerts are POSTed as JSON.' : 'Enterprise feature — the URL is stored now and used after an upgrade.'} +
+
+
+
+
+
+

Runtime

This installation
${sched.running ? 'scheduler running' : 'scheduler stopped'}
+
+
+
Tick interval
${esc(String(sched.interval_seconds ?? '—'))}s
+
Collections run
${esc(String(sched.runs ?? 0))}
+
Last tick duration
${sched.last_tick_ms != null ? `${esc(String(sched.last_tick_ms))} ms` : '—'}
+
Database
${esc(settings.db_path)}
+
Modules directory
${esc(settings.modules_dir)}
+
Admin account
${esc(settings.admin_user)}
+
+ ${sched.last_error ? `
${icon('alert')}
Last scheduler error
${esc(sched.last_error)}
` : ''} +
+
+
+
+
+

Asset allowance

${assetLimit > 0 ? 'Community cap' : 'Enterprise — unlimited'}
${assetCount}${assetLimit > 0 ? ` / ${assetLimit}` : ''}
+
+
+
+ ${assetLimit > 0 + ? `${Math.max(0, assetLimit - assetCount)} asset slot${assetLimit - assetCount === 1 ? '' : 's'} remaining. The oldest idle assets are never evicted automatically.` + : `No hard limit. ${assetCount} assets are currently tracked across ${state.boot.edition.features?.length || 0} enabled capabilities.`} +
+
+
+
+

Maintenance

Destructive operations
+
+

Re-seed the installation with the realistic demo fleet. This clears assets, telemetry, alerts and the audit trail before loading a fresh dataset.

+
+ + ${icon('activity')} Health check +
+
+
+
`; + + const licensePanel = ` + ${currentLicense} + ${license.invalid_license ? `
${icon('alert')}
Stored license could not be verified. It may have been issued by another installation or has been tampered with. Activate a valid key to restore Enterprise features.
` : ''} + ${license.trial_expired ? `
${icon('clock')}
The 30-day trial has ended. Your data is intact; Enterprise capabilities are locked until you activate a license.
` : ''} +
+

Administrator unlock

Enable Enterprise features without a license key
${license.admin_override ? 'ENABLED' : 'DISABLED'}
+
+
+
+
Enterprise mode
+
Unlock all Enterprise features across this installation (paid service toggle).
+
+ +
+
+
+
+
+

Activate a license

Signed locally with HMAC — no phone home
+
+
+
+ + + Paste the key exactly as issued. ${canModify ? 'Activation takes effect immediately.' : 'Administrator role required.'} +
+ +
+ ${trialAvailable ? `
${icon('sparkles')}
30-day Enterprise trial — no payment details, no phone home. One trial per installation.
+ ` : ''} + ${paid ? `` : ''} +
+
+
+

Plan comparison

${matrix.reduce((sum, group) => sum + group.features.length, 0)} capabilities
+
+ + + ${matrixRows || ``} +
CapabilityCommunityEnterprise
Could not load the edition matrix.
+
+
+
+ ${state.boot.dev_license_enabled ? `
+

Development license issuer

Visible because HEADROOM_ALLOW_DEV_LICENSE is enabled
DEV
+
+
${icon('alert')}
Never enable this on a shared installation. Keys are signed with this installation's secret; revoke the environment variable afterwards.
+
+
+
+
+
+
+
` : ''}`; + + const securityPanel = ` +
+
+

Change password

${esc(state.boot.user.username)} · ${esc(state.boot.user.role)}
+
+
+
+
At least 8 characters.
+
+
+
+
${icon('shield')}
Passwords are stored as salted PBKDF2 hashes. Existing API keys are not affected by a password change.
+
+
+
+

Access

Session and credentials
+
+
+
Signed in as
${esc(state.boot.user.username)}
+
Role
${esc(state.boot.user.role)}
+
Session
HttpOnly cookie
+
API keys
${isAdmin ? 'manageable' : 'admin only'}
+
Edition
${esc(license.label)}
+
+
+ + +
+
+
+
`; + + const auditPanel = !isAdmin + ? `
${icon('lock')}
The audit trail is visible to administrators only.
` + : `
+
+

Audit trail

Latest ${audit.length} recorded actions
+
+ ${state.boot.features.audit_export + ? `` + : ``} + ${refreshButton()} +
+
+
+ + ${audit.length ? audit.map((item) => ` + + + + + + `).join('') : ``} +
WhenActorActionTargetDetail
${esc(fmtDate(item.ts, true))}${esc(item.actor)}${esc(item.action)}${esc(item.target || '—')}${esc(item.detail || '—')}
No audit entries yetAdministrative actions will appear here.
+
`; + + const enabledFeatures = state.boot.edition.features || []; + const aboutPanel = ` +
+
+

About Headroom

Know your headroom. Before you run out.
v${esc(state.boot.version)}
+
+

Headroom is a modular capacity-management console for homelabs and small fleets. It collects utilisation from hypervisors, storage, log platforms and bare-metal hosts, forecasts exhaustion, evaluates policies and lets you simulate upgrades before you buy hardware.

+
+
Edition
${esc(license.label)}
+
Source
${esc(license.source)}
+
Assets tracked
${assetCount}
+
Open alerts
${state.boot.open_alerts ?? 0}
+
API version
v1
+
Storage
SQLite (WAL)
+
+
+
+
+

Resources

Documentation and integration points
+
+ +
${icon('info')}
MCI / AI integration is implemented as MCP (JSON-RPC over HTTP) plus an OpenAI-compatible copilot provider, so agents and local LLMs can read capacity data with the same API keys.
+
${icon('terminal')}
The installation is fully self-hosted. No telemetry leaves this machine; the only outbound calls are to the integrations and LLM provider you configure yourself.
+
+
+
+ ${paid ? '' : `
+

Ready for the next rack?

+

Enterprise removes the 40-asset cap, keeps 400 days of history, unlocks custom module uploads, webhooks, audit export and the MCP server.

+
+
${icon('check')}Unlimited assets
+
${icon('check')}Custom modules
+
${icon('check')}LLM copilot
+
${icon('check')}MCP server
+
+ +
`}`; + + const panels = { general: generalPanel, license: licensePanel, security: securityPanel, audit: auditPanel, about: aboutPanel }; + + view.innerHTML = ` + ${pageHead({ eyebrow: 'System', title: 'Settings', sub: 'Edition, security, retention and platform maintenance.', actions: refreshButton() })} +
+ ${tabs.map(([key, label]) => ``).join('')} +
+ ${panels[tab] || generalPanel}`; + + view.querySelectorAll('[data-settings-tab]').forEach((button) => button.addEventListener('click', () => { + state.settingsTab = button.dataset.settingsTab; + renderRoute(); + })); + + const refreshAll = async () => { + await refreshBootstrap(); + renderRoute(); + }; + + if (tab === 'general' && canModify) { + view.querySelector('#settings-form')?.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(event.target); + const retention = Number(formData.get('retention_days')); + if (!Number.isFinite(retention)) { toast('Enter a retention period', 'warn'); return; } + try { + await put('/settings', { + site_name: String(formData.get('site_name') || ''), + retention_days: retention, + alert_webhook: String(formData.get('alert_webhook') || ''), + }); + toast('Settings saved'); + await refreshAll(); + } catch (error) { toastError(error); } + }); + view.querySelector('[data-reseed]')?.addEventListener('click', async () => { + const ok = await confirmDialog({ + title: 'Re-seed demo data', + message: 'This deletes every asset, sample, alert, policy and audit entry, then installs the demo fleet again. API keys and users are preserved. Continue?', + confirmLabel: 'Re-seed installation', + danger: true, + }); + if (!ok) return; + try { + const result = await post('/admin/reseed'); + toast(`${result.assets} assets restored`, 'ok', 'Demo data re-seeded'); + await refreshAll(); + } catch (error) { toastError(error); } + }); + } + + if (tab === 'license') { + view.querySelector('#enterprise-toggle')?.addEventListener('change', async (event) => { + if (!(state.boot.user && state.boot.user.role === 'admin')) { + event.target.checked = !event.target.checked; + return; + } + try { + await post('/license/enterprise', { enabled: event.target.checked }); + toast(event.target.checked ? 'Enterprise mode enabled' : 'Enterprise mode disabled', 'ok'); + await refreshAll(); + } catch (error) { + toastError(error); + await refreshAll(); + } + }); + view.querySelector('#license-form')?.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(event.target); + const key = String(formData.get('key') || '').trim(); + if (!key) { toast('Paste a license key first', 'warn'); return; } + try { + await post('/license/activate', { key }); + toast('License activated. Enterprise features are unlocked.', 'ok', 'Edition upgraded'); + await refreshAll(); + } catch (error) { toastError(error); } + }); + view.querySelector('[data-start-trial]')?.addEventListener('click', async (event) => { + const button = event.currentTarget; + button.disabled = true; + try { + await post('/license/trial'); + toast('30-day Enterprise trial started', 'ok', 'Trial active'); + await refreshAll(); + } catch (error) { button.disabled = false; toastError(error); } + }); + view.querySelector('[data-deactivate-license]')?.addEventListener('click', async () => { + const ok = await confirmDialog({ + title: 'Deactivate license', + message: 'The installation returns to the Community edition. Existing data stays, but Enterprise features become unavailable immediately.', + confirmLabel: 'Deactivate', + danger: true, + }); + if (!ok) return; + try { + await del('/license'); + toast('License deactivated'); + await refreshAll(); + } catch (error) { toastError(error); } + }); + view.querySelector('#dev-license-form')?.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(event.target); + try { + const result = await post('/license/dev-issue', { + customer: String(formData.get('customer') || 'Homelab'), + days: Number(formData.get('days') || 365), + }); + openModal({ + title: 'Development license issued', + sub: `${esc(result.customer)} · ${esc(String(result.days))} days`, + body: `
${icon('key')}
This key is signed for this installation only.
+
${esc(result.key)}
`, + footer: ``, + onMount(modal, close) { + modal.querySelector('[data-copy-dev-key]').addEventListener('click', () => copyText(result.key)); + modal.querySelector('[data-activate-dev-key]').addEventListener('click', async () => { + try { + await post('/license/activate', { key: result.key }); + close(); + toast('Development license activated', 'ok', 'Enterprise'); + await refreshAll(); + } catch (error) { toastError(error); } + }); + }, + }); + } catch (error) { toastError(error); } + }); + } + + if (tab === 'security') { + view.querySelector('#password-form')?.addEventListener('submit', async (event) => { + event.preventDefault(); + const formData = new FormData(event.target); + const next = String(formData.get('new_password') || ''); + if (next !== String(formData.get('confirm_password') || '')) { + toast('New passwords do not match', 'warn'); + return; + } + try { + await put('/auth/password', { + current_password: String(formData.get('current_password') || ''), + new_password: next, + }); + event.target.reset(); + toast('Password updated'); + } catch (error) { toastError(error); } + }); + view.querySelector('[data-goto-api-keys]')?.addEventListener('click', () => { + state.apiTab = 'keys'; + location.hash = '#/api'; + }); + } + + if (tab === 'audit' && isAdmin) { + view.querySelector('[data-audit-export]')?.addEventListener('click', async () => { + try { + const csv = await request('/export/audit.csv'); + const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = 'headroom-audit.csv'; + document.body.appendChild(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); + toast('Audit log exported'); + } catch (error) { toastError(error); } + }); + } +}; + +init(); diff --git a/app/static/charts.js b/app/static/charts.js new file mode 100644 index 0000000..04f3b56 --- /dev/null +++ b/app/static/charts.js @@ -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) => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', + }[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 = '
No telemetry in this window yet.
'; + 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(``); + for (let index = 0; index <= 4; index += 1) { + const value = (max / 4) * index; + const yy = y(value); + parts.push(``); + parts.push(`${esc(valueFormat(value))}`); + } + for (let index = 0; index <= 4; index += 1) { + const t = t0 + ((t1 - t0) * index) / 4; + parts.push(`${esc(timeFormat(t))}`); + } + + 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(``); + parts.push(``); + } + parts.push(``); + if (item.dot) { + const last = points[points.length - 1]; + parts.push(``); + } + }); + parts.push(``); + parts.push(``); + parts.push(''); + + const wrap = document.createElement('div'); + wrap.className = 'chart-wrap'; + wrap.innerHTML = parts.join('') + ''; + 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 = `
${esc(tooltipTime(reference))}
` + rows.map((row) => ( + `
${esc(row.label)}${esc(valueFormat(row.point.v))}
` + )).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 `
+ +
${Math.round(safe)}${esc(options.suffix || '/100')}
+
`; +} + +export function sparkline(points, color = 'var(--accent)', options = {}) { + if (!points || points.length < 2) return ''; + 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 ``; +} + +export function distributionBars(items, options = {}) { + const total = items.reduce((sum, item) => sum + item.value, 0) || 1; + return `
${items.map((item) => ` +
+ +
`).join('')}
`; +} diff --git a/app/static/index.html b/app/static/index.html new file mode 100644 index 0000000..cd90617 --- /dev/null +++ b/app/static/index.html @@ -0,0 +1,29 @@ + + + + + + + Headroom — Capacity Management + + + + + + +
+
+ +
+
HEADROOM
+
Starting capacity engine…
+
+ +
+ + + diff --git a/app/static/styles.css b/app/static/styles.css new file mode 100644 index 0000000..d1c29a6 --- /dev/null +++ b/app/static/styles.css @@ -0,0 +1,1126 @@ +/* ========================================================================== + Headroom — capacity operations console + ========================================================================== */ + +:root { + --bg: #060a0d; + --bg-soft: #081015; + --surface: #0c151a; + --surface-2: #101c22; + --surface-3: #16252c; + --line: #1c2c34; + --line-strong: #2a414b; + --text: #e8f0f4; + --text-2: #c2d2da; + --muted: #7f95a0; + --faint: #5a6e78; + --accent: #3ce6a4; + --accent-soft: rgba(60, 230, 164, 0.12); + --accent-line: rgba(60, 230, 164, 0.28); + --cyan: #4ec9f5; + --ok: #3ce6a4; + --watch: #f2c45c; + --tight: #ffa04d; + --crit: #ff6b7a; + --violet: #b69cff; + --radius: 14px; + --radius-sm: 10px; + --shadow: 0 18px 50px rgba(0, 0, 0, 0.38); + --mono: "SFMono-Regular", "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; + --sans: "Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; +} + +* { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +body { + margin: 0; + min-height: 100vh; + background: var(--bg); + color: var(--text); + font-family: var(--sans); + font-size: 14px; + line-height: 1.5; + letter-spacing: 0.005em; + -webkit-font-smoothing: antialiased; +} + +body::before { + content: ""; + position: fixed; + inset: 0; + z-index: -1; + background: + radial-gradient(900px 500px at 8% -10%, rgba(60, 230, 164, 0.10), transparent 60%), + radial-gradient(800px 600px at 100% 0%, rgba(78, 201, 245, 0.06), transparent 55%), + linear-gradient(180deg, #070c10 0%, #060a0d 60%); + pointer-events: none; +} + +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +button, input, select, textarea { font: inherit; color: inherit; } +h1, h2, h3, h4, p { margin: 0; } +[hidden] { display: none !important; } +::selection { background: rgba(60, 230, 164, 0.28); } + +/* Scrollbars */ +* { scrollbar-width: thin; scrollbar-color: #24404a transparent; } +::-webkit-scrollbar { width: 10px; height: 10px; } +::-webkit-scrollbar-thumb { background: #1f353e; border: 3px solid transparent; background-clip: content-box; border-radius: 10px; } +::-webkit-scrollbar-thumb:hover { background: #2c4b56; background-clip: content-box; } +::-webkit-scrollbar-track { background: transparent; } + +/* -------------------------------------------------------------------------- + Boot + -------------------------------------------------------------------------- */ +.boot { + position: fixed; + inset: 0; + display: grid; + place-content: center; + justify-items: center; + gap: 14px; + background: var(--bg); + z-index: 60; +} +.boot-mark { + width: 64px; + height: 64px; + color: var(--accent); + filter: drop-shadow(0 0 22px rgba(60, 230, 164, 0.35)); + animation: bootPulse 1.6s ease-in-out infinite; +} +.boot-mark svg { width: 100%; height: 100%; } +.boot-text { font-weight: 700; letter-spacing: 0.42em; font-size: 15px; color: var(--text); } +.boot-sub { color: var(--muted); font-size: 12.5px; letter-spacing: 0.04em; } +.boot-error { color: var(--crit); font-size: 12.5px; max-width: 420px; text-align: center; } +@keyframes bootPulse { 0%, 100% { opacity: 0.7; transform: scale(0.98); } 50% { opacity: 1; transform: scale(1); } } + +/* -------------------------------------------------------------------------- + Login + -------------------------------------------------------------------------- */ +.login-screen { + min-height: 100vh; + display: grid; + grid-template-columns: minmax(0, 1.15fr) minmax(380px, 0.85fr); +} +.login-art { + position: relative; + display: flex; + flex-direction: column; + justify-content: space-between; + padding: 48px clamp(32px, 5vw, 76px); + overflow: hidden; + border-right: 1px solid var(--line); + background: + radial-gradient(600px 400px at 20% 20%, rgba(60, 230, 164, 0.14), transparent 65%), + radial-gradient(500px 400px at 90% 90%, rgba(78, 201, 245, 0.10), transparent 60%), + #071014; +} +.login-art::after { + content: ""; + position: absolute; + inset: 0; + background-image: + linear-gradient(rgba(90, 140, 160, 0.055) 1px, transparent 1px), + linear-gradient(90deg, rgba(90, 140, 160, 0.055) 1px, transparent 1px); + background-size: 44px 44px; + mask-image: radial-gradient(circle at 35% 40%, #000 20%, transparent 78%); + pointer-events: none; +} +.login-brand { display: flex; align-items: center; gap: 12px; position: relative; z-index: 1; } +.login-brand .brand-mark { width: 38px; height: 38px; } +.login-brand strong { font-size: 16px; letter-spacing: 0.34em; font-weight: 700; } +.login-hero { position: relative; z-index: 1; max-width: 520px; } +.login-hero h1 { + font-size: clamp(30px, 4vw, 50px); + line-height: 1.06; + letter-spacing: -0.035em; + font-weight: 700; + margin-bottom: 18px; +} +.login-hero h1 em { font-style: normal; color: var(--accent); } +.login-hero p { color: var(--text-2); font-size: 15px; max-width: 460px; } +.login-points { display: grid; gap: 14px; margin-top: 34px; } +.login-point { display: flex; gap: 12px; align-items: flex-start; color: var(--text-2); font-size: 13.5px; } +.login-point .dot { width: 26px; height: 26px; border-radius: 8px; display: grid; place-items: center; background: var(--accent-soft); color: var(--accent); flex: 0 0 auto; } +.login-point .dot svg { width: 14px; height: 14px; } +.login-foot { position: relative; z-index: 1; color: var(--faint); font-size: 12px; display: flex; gap: 18px; flex-wrap: wrap; } +.login-panel { display: grid; place-items: center; padding: 40px 26px; background: #080d11; } +.login-card { + width: min(400px, 100%); + padding: 34px; + border-radius: 18px; + border: 1px solid var(--line); + background: linear-gradient(180deg, #0e181e, #0a1216); + box-shadow: var(--shadow); +} +.login-card .eyebrow { margin-bottom: 10px; } +.login-card h2 { font-size: 22px; letter-spacing: -0.02em; } +.login-card > p { color: var(--muted); font-size: 13px; margin-top: 6px; margin-bottom: 24px; } +.login-card .field { margin-bottom: 16px; } +.login-card .btn { width: 100%; margin-top: 6px; } +.login-hint { + margin-top: 20px; + padding: 11px 13px; + border-radius: 10px; + border: 1px dashed var(--line-strong); + background: rgba(78, 201, 245, 0.05); + color: var(--muted); + font-size: 12px; + display: flex; + gap: 8px; + align-items: center; +} +.login-hint code { color: var(--text-2); font-family: var(--mono); font-size: 11.5px; } +.login-error { color: var(--crit); font-size: 12.5px; margin-top: 12px; min-height: 18px; } + +/* -------------------------------------------------------------------------- + Shell + -------------------------------------------------------------------------- */ +.shell { + display: grid; + grid-template-columns: 250px minmax(0, 1fr); + min-height: 100vh; +} + +.sidebar { + position: sticky; + top: 0; + height: 100vh; + display: flex; + flex-direction: column; + gap: 4px; + padding: 20px 14px 16px; + border-right: 1px solid var(--line); + background: linear-gradient(180deg, rgba(11, 18, 23, 0.96), rgba(7, 12, 16, 0.98)); + backdrop-filter: blur(12px); + z-index: 30; +} +.brand { + display: flex; + align-items: center; + gap: 11px; + padding: 4px 10px 18px; + color: var(--text); +} +.brand:hover { text-decoration: none; } +.brand-mark { width: 33px; height: 33px; color: var(--accent); flex: 0 0 auto; filter: drop-shadow(0 0 12px rgba(60, 230, 164, 0.28)); } +.brand-mark svg { width: 100%; height: 100%; } +.brand-word { font-size: 13.5px; font-weight: 700; letter-spacing: 0.33em; } +.brand-sub { display: block; font-size: 9.5px; letter-spacing: 0.16em; color: var(--faint); font-weight: 600; margin-top: 2px; text-transform: uppercase; } + +.nav-section { padding: 14px 12px 6px; color: var(--faint); font-size: 10px; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; } +.nav-item { + display: flex; + align-items: center; + gap: 11px; + padding: 9px 11px; + border-radius: 9px; + color: var(--muted); + font-size: 13.5px; + font-weight: 500; + border: 1px solid transparent; + transition: background 0.15s, color 0.15s, border-color 0.15s; +} +.nav-item:hover { background: var(--surface-2); color: var(--text); text-decoration: none; } +.nav-item.active { background: linear-gradient(90deg, rgba(60, 230, 164, 0.13), rgba(60, 230, 164, 0.03)); color: var(--text); border-color: var(--accent-line); } +.nav-item.active .ic { color: var(--accent); } +.nav-item .ic { width: 17px; height: 17px; color: var(--faint); flex: 0 0 auto; } +.nav-item .nav-count { + margin-left: auto; + min-width: 20px; + height: 18px; + padding: 0 6px; + border-radius: 20px; + background: rgba(255, 107, 122, 0.14); + color: var(--crit); + font-size: 10.5px; + font-weight: 700; + display: grid; + place-items: center; + font-family: var(--mono); +} +.nav-item .nav-lock { margin-left: auto; color: var(--faint); width: 13px; height: 13px; } +.sidebar-foot { margin-top: auto; padding: 12px 4px 0; } +.edition-card { + border: 1px solid var(--line); + border-radius: 12px; + padding: 13px; + background: + radial-gradient(180px 100px at 100% 0%, rgba(60, 230, 164, 0.12), transparent 70%), + var(--surface); +} +.edition-card .row { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.edition-card .label { font-size: 12.5px; font-weight: 600; } +.edition-card p { color: var(--muted); font-size: 11px; line-height: 1.45; margin: 7px 0 11px; } +.edition-card .btn { width: 100%; } + +.main { min-width: 0; display: flex; flex-direction: column; } +.topbar { + position: sticky; + top: 0; + z-index: 25; + display: flex; + align-items: center; + gap: 16px; + height: 63px; + padding: 0 26px; + border-bottom: 1px solid var(--line); + background: rgba(7, 12, 16, 0.82); + backdrop-filter: blur(14px); +} +.topbar-title { min-width: 0; } +.topbar-title h1 { font-size: 15px; font-weight: 650; letter-spacing: -0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.topbar-title span { display: block; color: var(--faint); font-size: 11px; margin-top: 1px; } +.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 10px; } +.topbar-status { display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: 11.5px; padding-right: 6px; } +.live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 0 rgba(60, 230, 164, 0.5); animation: live 2.4s ease-out infinite; } +@keyframes live { 0% { box-shadow: 0 0 0 0 rgba(60, 230, 164, 0.45); } 70% { box-shadow: 0 0 0 7px rgba(60, 230, 164, 0); } 100% { box-shadow: 0 0 0 0 rgba(60, 230, 164, 0); } } +.user-chip { + display: flex; + align-items: center; + gap: 9px; + padding: 5px 9px 5px 5px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--surface); + cursor: pointer; + color: var(--text-2); + font-size: 12px; +} +.user-chip:hover { border-color: var(--line-strong); } +.avatar { width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; background: linear-gradient(135deg, var(--accent), #1a9c74); color: #04120c; font-weight: 800; font-size: 11px; } +.menu { + position: absolute; + top: 58px; + right: 22px; + width: 208px; + border: 1px solid var(--line-strong); + border-radius: 11px; + background: var(--surface-2); + box-shadow: var(--shadow); + padding: 6px; + z-index: 50; +} +.menu-item { display: flex; align-items: center; gap: 9px; width: 100%; padding: 8px 10px; border: 0; background: none; border-radius: 7px; color: var(--text-2); font-size: 12.5px; text-align: left; cursor: pointer; } +.menu-item:hover { background: var(--surface-3); color: var(--text); } +.menu-item .ic { width: 14px; height: 14px; color: var(--muted); } +.menu-sep { height: 1px; background: var(--line); margin: 5px 4px; } +.menu-meta { padding: 8px 10px 4px; color: var(--faint); font-size: 10.5px; } + +.view { padding: 26px clamp(18px, 2.6vw, 34px) 56px; width: 100%; max-width: 1620px; margin: 0 auto; } +.mobile-menu-btn { display: none; } + +/* -------------------------------------------------------------------------- + Page head + toolbars + -------------------------------------------------------------------------- */ +.page-head { + display: flex; + align-items: flex-end; + gap: 18px; + flex-wrap: wrap; + margin-bottom: 22px; +} +.page-head .eyebrow { margin-bottom: 5px; } +.page-head h2 { font-size: clamp(22px, 2.2vw, 28px); line-height: 1.15; letter-spacing: -0.025em; font-weight: 700; } +.page-head p { color: var(--muted); font-size: 13px; margin-top: 5px; max-width: 760px; } +.page-actions { margin-left: auto; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.eyebrow { color: var(--accent); font-size: 10.5px; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; } + +.back-link { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; margin-bottom: 13px; } +.back-link:hover { color: var(--text); text-decoration: none; } +.back-link .ic { width: 13px; height: 13px; } + +.toolbar { + display: flex; + align-items: center; + gap: 9px; + flex-wrap: wrap; + padding: 12px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + margin-bottom: 16px; +} +.toolbar .spacer { flex: 1; } +.toolbar-label { color: var(--muted); font-size: 11.5px; } + +/* -------------------------------------------------------------------------- + Buttons / inputs + -------------------------------------------------------------------------- */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + height: 34px; + padding: 0 13px; + border-radius: 8px; + border: 1px solid var(--line-strong); + background: var(--surface-2); + color: var(--text-2); + font-size: 12.5px; + font-weight: 600; + cursor: pointer; + white-space: nowrap; + transition: background 0.15s, border-color 0.15s, color 0.15s, transform 0.05s; +} +.btn:hover { background: var(--surface-3); border-color: #37535e; color: var(--text); text-decoration: none; } +.btn:active { transform: translateY(1px); } +.btn .ic { width: 14px; height: 14px; } +.btn.primary { + background: linear-gradient(180deg, #46eab0, #28c48c); + border-color: rgba(60, 230, 164, 0.55); + color: #04140d; + box-shadow: 0 6px 20px rgba(60, 230, 164, 0.16); +} +.btn.primary:hover { background: linear-gradient(180deg, #55f2bc, #30d49a); color: #04140d; } +.btn.danger { border-color: rgba(255, 107, 122, 0.3); color: #ff9aa5; background: rgba(255, 107, 122, 0.07); } +.btn.danger:hover { background: rgba(255, 107, 122, 0.14); border-color: rgba(255, 107, 122, 0.5); color: #ffc0c6; } +.btn.ghost { background: transparent; border-color: transparent; color: var(--muted); } +.btn.ghost:hover { background: var(--surface-2); color: var(--text); border-color: var(--line); } +.btn.sm { height: 28px; padding: 0 9px; font-size: 11.5px; border-radius: 7px; } +.btn.sm .ic { width: 12px; height: 12px; } +.btn:disabled, .btn.is-busy { opacity: 0.55; cursor: progress; } +.btn.is-busy .ic { animation: spin 1s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } +.icon-btn { + display: inline-grid; + place-items: center; + width: 30px; + height: 30px; + border-radius: 7px; + border: 1px solid transparent; + background: transparent; + color: var(--muted); + cursor: pointer; +} +.icon-btn:hover { background: var(--surface-2); color: var(--text); border-color: var(--line); } +.icon-btn .ic { width: 15px; height: 15px; } +.icon-btn.danger:hover { color: var(--crit); border-color: rgba(255, 107, 122, 0.3); } + +.input, .select, .textarea { + width: 100%; + height: 36px; + padding: 0 11px; + border-radius: 8px; + border: 1px solid var(--line-strong); + background: #0a1317; + color: var(--text); + font-size: 13px; + outline: none; + transition: border-color 0.15s, box-shadow 0.15s; +} +.textarea { height: auto; min-height: 84px; padding: 9px 11px; resize: vertical; line-height: 1.55; } +.input::placeholder, .textarea::placeholder { color: var(--faint); } +.input:focus, .select:focus, .textarea:focus { border-color: rgba(60, 230, 164, 0.55); box-shadow: 0 0 0 3px rgba(60, 230, 164, 0.08); } +.select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237f95a0' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 11px center; padding-right: 30px; } +.input.sm, .select.sm { height: 30px; font-size: 12px; } +.search { position: relative; flex: 1 1 220px; max-width: 340px; } +.search .ic { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--faint); pointer-events: none; } +.search .input { padding-left: 32px; } +.field { display: flex; flex-direction: column; gap: 6px; } +.field > label { color: var(--muted); font-size: 11.5px; font-weight: 600; letter-spacing: 0.02em; } +.field .help { color: var(--faint); font-size: 11px; line-height: 1.45; } +.field-error { color: var(--crit); font-size: 11.5px; } +.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } +.form-grid .span-2 { grid-column: 1 / -1; } +.check { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 12.5px; cursor: pointer; } +.check input { width: 15px; height: 15px; accent-color: var(--accent); } +.switch { position: relative; display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--muted); font-size: 11.5px; user-select: none; } +.switch input { position: absolute; opacity: 0; pointer-events: none; } +.switch .track { width: 32px; height: 18px; border-radius: 20px; background: #24343c; border: 1px solid #2c424c; position: relative; transition: background 0.15s; flex: 0 0 auto; } +.switch .track::after { content: ""; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%; background: #8ba0a9; transition: transform 0.15s, background 0.15s; } +.switch input:checked + .track { background: rgba(60, 230, 164, 0.28); border-color: rgba(60, 230, 164, 0.5); } +.switch input:checked + .track::after { transform: translateX(14px); background: var(--accent); } +.seg { display: inline-flex; padding: 3px; gap: 2px; border-radius: 8px; border: 1px solid var(--line); background: #081115; } +.seg button { border: 0; background: transparent; color: var(--muted); font-size: 11.5px; font-weight: 600; padding: 5px 9px; border-radius: 6px; cursor: pointer; } +.seg button:hover { color: var(--text); } +.seg button.on { background: var(--surface-3); color: var(--text); box-shadow: inset 0 0 0 1px var(--line-strong); } + +/* -------------------------------------------------------------------------- + Cards, grids, KPIs + -------------------------------------------------------------------------- */ +.grid { display: grid; gap: 16px; } +.kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 16px; } +.cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.cols-main { grid-template-columns: minmax(0, 1.65fr) minmax(0, 1fr); } +.cols-main-rev { grid-template-columns: minmax(0, 1fr) minmax(0, 1.6fr); } +.mb-16 { margin-bottom: 16px; } +.mt-8 { margin-top: 8px; } +.mt-16 { margin-top: 16px; } +.metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(158px, 1fr)); gap: 10px; margin-bottom: 16px; } + +.panel { + min-width: 0; + border: 1px solid var(--line); + border-radius: var(--radius); + background: linear-gradient(180deg, rgba(15, 25, 31, 0.96), rgba(10, 17, 21, 0.96)); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.025); + overflow: hidden; +} +.panel-head { + display: flex; + align-items: center; + gap: 12px; + padding: 14px 16px; + border-bottom: 1px solid var(--line); + min-height: 52px; +} +.panel-head h3 { font-size: 13.5px; font-weight: 650; letter-spacing: -0.005em; } +.panel-head .sub { color: var(--faint); font-size: 11px; margin-top: 1px; } +.panel-head .actions { margin-left: auto; display: flex; align-items: center; gap: 6px; } +.panel-body { padding: 16px; } +.panel-body.flush { padding: 0; } +.panel-foot { padding: 11px 16px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11.5px; display: flex; align-items: center; gap: 8px; } + +.kpi { + position: relative; + border: 1px solid var(--line); + border-radius: var(--radius); + background: + radial-gradient(240px 130px at 100% 0%, rgba(60, 230, 164, 0.06), transparent 70%), + linear-gradient(180deg, rgba(15, 25, 31, 0.97), rgba(10, 17, 21, 0.97)); + padding: 16px; + min-height: 132px; + display: flex; + flex-direction: column; + overflow: hidden; +} +.kpi::after { content: ""; position: absolute; inset: 0 0 auto; height: 1px; background: linear-gradient(90deg, transparent, rgba(60, 230, 164, 0.32), transparent); opacity: 0.5; } +.kpi-top { display: flex; align-items: center; gap: 8px; } +.kpi-label { color: var(--muted); font-size: 11.5px; font-weight: 600; letter-spacing: 0.03em; text-transform: uppercase; } +.kpi-icon { margin-left: auto; width: 26px; height: 26px; border-radius: 7px; display: grid; place-items: center; background: var(--surface-2); border: 1px solid var(--line); color: var(--muted); } +.kpi-icon .ic { width: 13px; height: 13px; } +.kpi-value { font-family: var(--mono); font-size: 30px; font-weight: 600; letter-spacing: -0.04em; line-height: 1.1; margin-top: 11px; display: flex; align-items: baseline; gap: 6px; } +.kpi-value small { font-family: var(--sans); font-size: 12.5px; font-weight: 500; color: var(--muted); letter-spacing: 0; } +.kpi-sub { color: var(--muted); font-size: 11.5px; margin-top: 6px; display: flex; align-items: center; gap: 7px; flex-wrap: wrap; } +.kpi-foot { margin-top: auto; display: flex; align-items: center; gap: 10px; padding-top: 10px; } +.kpi .bar { flex: 1; } +.kpi.crit { border-color: rgba(255, 107, 122, 0.26); background: radial-gradient(240px 130px at 100% 0%, rgba(255, 107, 122, 0.09), transparent 70%), linear-gradient(180deg, rgba(28, 17, 21, 0.97), rgba(13, 13, 17, 0.97)); } +.kpi.tight { border-color: rgba(255, 160, 77, 0.24); } + +.resource-card { + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; + background: linear-gradient(180deg, rgba(15, 25, 31, 0.96), rgba(10, 17, 21, 0.96)); +} +.resource-card .rc-top { display: flex; align-items: flex-start; gap: 12px; } +.resource-card .rc-label { color: var(--muted); font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; } +.resource-card .rc-value { font-family: var(--mono); font-size: 25px; font-weight: 600; letter-spacing: -0.03em; margin-top: 4px; } +.resource-card .rc-value small { font-size: 11.5px; color: var(--muted); font-weight: 500; } +.resource-card .rc-meta { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--line); } +.resource-card .rc-meta dt { color: var(--faint); font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600; } +.resource-card .rc-meta dd { margin: 3px 0 0; font-family: var(--mono); font-size: 12px; color: var(--text-2); } +.resource-card .ring { margin-left: auto; } + +.bar { height: 6px; border-radius: 20px; background: #1a2a32; overflow: hidden; position: relative; } +.bar > span { display: block; height: 100%; border-radius: 20px; background: var(--ok); transition: width 0.5s ease; } +.bar[data-band="watch"] > span { background: var(--watch); } +.bar[data-band="tight"] > span { background: var(--tight); } +.bar[data-band="critical"] > span { background: var(--crit); } +.bar[data-band="unknown"] > span { background: var(--muted); } +.bar.lg { height: 8px; } +.bar.xs { height: 4px; } + +/* -------------------------------------------------------------------------- + Pills, badges, status + -------------------------------------------------------------------------- */ +.pill { + display: inline-flex; + align-items: center; + gap: 5px; + height: 21px; + padding: 0 8px; + border-radius: 20px; + border: 1px solid var(--line-strong); + font-size: 10.5px; + font-weight: 650; + letter-spacing: 0.02em; + white-space: nowrap; + color: var(--muted); + background: rgba(255, 255, 255, 0.02); +} +.pill::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; } +.pill.plain::before { display: none; } +.pill.healthy, .pill.ok { color: var(--ok); border-color: rgba(60, 230, 164, 0.26); background: rgba(60, 230, 164, 0.07); } +.pill.watch { color: var(--watch); border-color: rgba(242, 196, 92, 0.26); background: rgba(242, 196, 92, 0.07); } +.pill.tight { color: var(--tight); border-color: rgba(255, 160, 77, 0.28); background: rgba(255, 160, 77, 0.08); } +.pill.critical, .pill.crit { color: var(--crit); border-color: rgba(255, 107, 122, 0.3); background: rgba(255, 107, 122, 0.08); } +.pill.info { color: var(--cyan); border-color: rgba(78, 201, 245, 0.26); background: rgba(78, 201, 245, 0.07); } +.pill.accent { color: var(--accent); border-color: var(--accent-line); background: var(--accent-soft); } +.pill.violet { color: var(--violet); border-color: rgba(182, 156, 255, 0.28); background: rgba(182, 156, 255, 0.08); } +.pill.muted { color: var(--muted); } +.badge { display: inline-flex; align-items: center; gap: 5px; padding: 2px 7px; border-radius: 5px; font-size: 9.5px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; border: 1px solid var(--line-strong); color: var(--muted); } +.badge.custom { color: var(--violet); border-color: rgba(182, 156, 255, 0.3); background: rgba(182, 156, 255, 0.07); } +.badge.bundled { color: var(--cyan); border-color: rgba(78, 201, 245, 0.24); background: rgba(78, 201, 245, 0.06); } +.badge.enterprise { color: var(--accent); border-color: var(--accent-line); background: var(--accent-soft); } +.badge.community { color: var(--muted); } +.dot-status { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--muted); flex: 0 0 auto; } +.dot-status.ok { background: var(--ok); box-shadow: 0 0 8px rgba(60, 230, 164, 0.55); } +.dot-status.error { background: var(--crit); box-shadow: 0 0 8px rgba(255, 107, 122, 0.5); } +.dot-status.pending { background: var(--watch); } +.dot-status.disabled { background: var(--faint); } +.trend { display: inline-flex; align-items: center; gap: 4px; font-family: var(--mono); font-size: 11.5px; color: var(--muted); } +.trend.up { color: var(--tight); } +.trend.down { color: var(--ok); } +.trend .ic { width: 11px; height: 11px; } +.mono { font-family: var(--mono); } +.muted { color: var(--muted); } +.faint { color: var(--faint); } +.crit-text { color: var(--crit); } +.ok-text { color: var(--ok); } +.nowrap { white-space: nowrap; } +.right { text-align: right; } + +/* -------------------------------------------------------------------------- + Tables + -------------------------------------------------------------------------- */ +.table-wrap { overflow-x: auto; } +table.data { width: 100%; border-collapse: collapse; font-size: 12.5px; } +table.data th { + text-align: left; + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--faint); + padding: 10px 14px; + border-bottom: 1px solid var(--line); + background: rgba(255, 255, 255, 0.012); + white-space: nowrap; +} +table.data td { padding: 11px 14px; border-bottom: 1px solid rgba(28, 44, 52, 0.65); vertical-align: middle; } +table.data tbody tr { transition: background 0.12s; } +table.data tbody tr:hover { background: rgba(60, 230, 164, 0.028); } +table.data tbody tr.clickable { cursor: pointer; } +table.data tbody tr:last-child td { border-bottom: 0; } +table.data td.num, table.data th.num { text-align: right; font-family: var(--mono); font-variant-numeric: tabular-nums; } +table.data .cell-main { display: flex; align-items: center; gap: 10px; min-width: 190px; } +table.data .cell-main .name { font-weight: 600; color: var(--text); font-size: 12.5px; } +table.data .cell-main .sub { color: var(--faint); font-size: 10.5px; margin-top: 1px; } +.table-empty { padding: 38px 18px; text-align: center; color: var(--muted); } +.table-empty strong { display: block; color: var(--text-2); margin-bottom: 4px; font-size: 13px; } + +.type-icon { + width: 32px; + height: 32px; + border-radius: 8px; + display: grid; + place-items: center; + flex: 0 0 auto; + border: 1px solid var(--line); + background: var(--surface-2); + color: var(--muted); +} +.type-icon .ic { width: 15px; height: 15px; } +.type-icon.t-hypervisor { color: var(--cyan); background: rgba(78, 201, 245, 0.07); border-color: rgba(78, 201, 245, 0.2); } +.type-icon.t-storage, .type-icon.t-nas { color: var(--accent); background: rgba(60, 230, 164, 0.07); border-color: rgba(60, 230, 164, 0.2); } +.type-icon.t-appliance { color: var(--watch); background: rgba(242, 196, 92, 0.07); border-color: rgba(242, 196, 92, 0.2); } +.type-icon.t-network { color: var(--violet); background: rgba(182, 156, 255, 0.07); border-color: rgba(182, 156, 255, 0.2); } +.type-icon.t-server { color: #9db5c0; } +.type-icon.t-power { color: var(--tight); } + +.util-cell { display: flex; align-items: center; gap: 9px; min-width: 120px; } +.util-cell .bar { width: 64px; flex: 0 0 auto; } +.util-cell strong { font-family: var(--mono); font-size: 11.5px; font-weight: 500; min-width: 38px; text-align: right; } +.mini-metric { font-family: var(--mono); font-size: 11.5px; color: var(--text-2); } + +/* -------------------------------------------------------------------------- + Lists (pressure leaders, alerts, modules) + -------------------------------------------------------------------------- */ +.list { display: flex; flex-direction: column; } +.list-row { + display: flex; + align-items: center; + gap: 11px; + padding: 11px 16px; + border-bottom: 1px solid rgba(28, 44, 52, 0.6); + min-width: 0; +} +.list-row:last-child { border-bottom: 0; } +a.list-row { color: inherit; } +a.list-row:hover { background: rgba(60, 230, 164, 0.03); text-decoration: none; } +.list-row .lr-main { min-width: 0; flex: 1; } +.list-row .lr-main .name { font-size: 12.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.list-row .lr-main .sub { color: var(--faint); font-size: 10.5px; margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.list-row .lr-value { text-align: right; flex: 0 0 auto; } +.list-row .lr-value strong { font-family: var(--mono); font-size: 12.5px; font-weight: 500; display: block; } +.list-row .lr-value span { color: var(--faint); font-size: 10px; } +.list-row .bar { margin-top: 7px; } + +.severity-dot { width: 8px; height: 8px; border-radius: 50%; flex: 0 0 auto; background: var(--watch); } +.severity-dot.critical { background: var(--crit); box-shadow: 0 0 8px rgba(255, 107, 122, 0.55); } +.severity-dot.warning { background: var(--watch); } +.severity-dot.info { background: var(--cyan); } + +.alert-row { display: flex; gap: 11px; padding: 12px 16px; border-bottom: 1px solid rgba(28, 44, 52, 0.6); align-items: flex-start; } +.alert-row:last-child { border-bottom: 0; } +.alert-row .a-main { min-width: 0; flex: 1; } +.alert-row .a-msg { font-size: 12.5px; color: var(--text-2); line-height: 1.4; } +.alert-row .a-msg a { color: var(--text); font-weight: 600; } +.alert-row .a-meta { display: flex; align-items: center; gap: 8px; margin-top: 5px; color: var(--faint); font-size: 10.5px; flex-wrap: wrap; } +.alert-row.resolved { opacity: 0.58; } + +/* -------------------------------------------------------------------------- + Charts + -------------------------------------------------------------------------- */ +.chart-wrap { position: relative; width: 100%; } +.chart-svg { display: block; width: 100%; height: auto; overflow: visible; } +.chart-grid { stroke: rgba(120, 160, 175, 0.11); stroke-width: 1; } +.chart-axis { fill: var(--faint); font-size: 10px; font-family: var(--mono); } +.chart-guide { stroke: rgba(60, 230, 164, 0.5); stroke-width: 1; stroke-dasharray: 3 3; } +.chart-tip { + position: absolute; + top: 8px; + min-width: 150px; + padding: 8px 10px; + border-radius: 8px; + border: 1px solid var(--line-strong); + background: rgba(10, 19, 24, 0.96); + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); + pointer-events: none; + z-index: 4; +} +.chart-tip .tip-time { color: var(--faint); font-size: 10px; margin-bottom: 5px; } +.chart-tip .tip-row { display: flex; align-items: center; justify-content: space-between; gap: 14px; font-size: 11px; padding: 2px 0; } +.chart-tip .tip-row span { display: flex; align-items: center; gap: 6px; color: var(--muted); } +.chart-tip .tip-row i { width: 7px; height: 7px; border-radius: 50%; display: inline-block; } +.chart-tip .tip-row strong { font-family: var(--mono); font-weight: 500; color: var(--text); } +.chart-empty { display: grid; place-items: center; min-height: 160px; color: var(--faint); font-size: 12px; border: 1px dashed var(--line); border-radius: 10px; } +.legend { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; color: var(--muted); font-size: 11px; } +.legend span { display: inline-flex; align-items: center; gap: 6px; } +.legend i { width: 8px; height: 8px; border-radius: 2px; display: inline-block; } + +.ring { position: relative; display: grid; place-items: center; flex: 0 0 auto; } +.ring svg { position: absolute; inset: 0; width: 100%; height: 100%; } +.ring-track { stroke: #1a2b33; } +.ring-value { stroke: var(--ok); transition: stroke-dashoffset 0.7s ease; } +.ring[data-band="watch"] .ring-value { stroke: var(--watch); } +.ring[data-band="tight"] .ring-value { stroke: var(--tight); } +.ring[data-band="critical"] .ring-value { stroke: var(--crit); } +.ring[data-band="unknown"] .ring-value { stroke: var(--muted); } +.ring-label { position: relative; text-align: center; line-height: 1; } +.ring-label strong { display: block; font-family: var(--mono); font-size: 21px; font-weight: 600; letter-spacing: -0.04em; } +.ring-label span { display: block; color: var(--faint); font-size: 9px; margin-top: 4px; letter-spacing: 0.04em; } +.ring.sm .ring-label strong { font-size: 15px; } +.ring.sm .ring-label span { font-size: 8px; margin-top: 2px; } + +.spark { width: 100%; height: 34px; display: block; overflow: visible; } +.spark-empty { display: block; height: 34px; } +.dist { display: flex; gap: 2px; height: 7px; border-radius: 20px; overflow: hidden; background: #16242b; } +.dist-bar { flex: 1; background: #1a2a32; overflow: hidden; } +.dist-bar span { display: block; height: 100%; } + +.metric-card { border: 1px solid var(--line); border-radius: 12px; background: var(--surface); padding: 13px 14px; min-width: 0; } +.metric-card .mc-top { display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; } +.metric-card .mc-value { font-family: var(--mono); font-size: 21px; font-weight: 600; margin-top: 5px; letter-spacing: -0.02em; } +.metric-card .mc-value small { color: var(--faint); font-size: 10.5px; font-weight: 500; margin-left: 2px; } +.metric-card .mc-delta { font-family: var(--mono); font-size: 10.5px; color: var(--faint); } +.metric-card .mc-delta.up { color: var(--tight); } +.metric-card .mc-delta.down { color: var(--ok); } +.metric-card .spark { margin-top: 7px; height: 28px; } + +/* -------------------------------------------------------------------------- + Hero (asset detail) + -------------------------------------------------------------------------- */ +.hero { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + gap: 20px; + align-items: center; + padding: 18px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: + radial-gradient(420px 180px at 0% 0%, rgba(60, 230, 164, 0.07), transparent 70%), + linear-gradient(180deg, rgba(15, 25, 31, 0.97), rgba(10, 17, 21, 0.97)); + margin-bottom: 16px; +} +.hero .hero-main { min-width: 0; } +.hero h2 { font-size: 23px; letter-spacing: -0.025em; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.hero .hero-sub { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 7px; color: var(--muted); font-size: 11.5px; } +.hero .hero-actions { display: flex; gap: 7px; align-items: center; flex-wrap: wrap; justify-content: flex-end; } + +.reco { + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; + background: linear-gradient(180deg, rgba(15, 25, 31, 0.96), rgba(10, 17, 21, 0.96)); + border-left: 3px solid var(--accent); +} +.reco.critical { border-left-color: var(--crit); } +.reco.warning { border-left-color: var(--watch); } +.reco.info { border-left-color: var(--cyan); } +.reco.healthy { border-left-color: var(--ok); } +.reco .reco-head { display: flex; align-items: center; gap: 8px; margin-bottom: 7px; } +.reco h3 { font-size: 14px; letter-spacing: -0.01em; } +.reco p { color: var(--text-2); font-size: 12.5px; line-height: 1.55; } +.reco .action { margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11.5px; display: flex; gap: 8px; } +.reco .action .ic { width: 13px; height: 13px; color: var(--accent); flex: 0 0 auto; margin-top: 2px; } + +.kv { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } +.kv > div { padding: 9px 12px; border-bottom: 1px solid var(--line); min-width: 0; } +.kv > div:nth-child(odd) { border-right: 1px solid var(--line); } +.kv > div:nth-last-child(-n+2) { border-bottom: 0; } +.kv dt { color: var(--faint); font-size: 9.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; } +.kv dd { margin: 3px 0 0; font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; } + +.tabs { display: flex; gap: 3px; border-bottom: 1px solid var(--line); padding: 0 16px; overflow-x: auto; } +.tab { border: 0; background: none; color: var(--muted); font-size: 12px; font-weight: 600; padding: 11px 10px; cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; white-space: nowrap; } +.tab:hover { color: var(--text); } +.tab.on { color: var(--accent); border-bottom-color: var(--accent); } +.tab-panel { padding: 16px; } + +/* -------------------------------------------------------------------------- + Modules + -------------------------------------------------------------------------- */ +.modules-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(310px, 1fr)); gap: 16px; } +.module-card { + display: flex; + flex-direction: column; + border: 1px solid var(--line); + border-radius: var(--radius); + background: linear-gradient(180deg, rgba(15, 25, 31, 0.96), rgba(10, 17, 21, 0.96)); + padding: 16px; + min-width: 0; + transition: border-color 0.15s, transform 0.15s; +} +.module-card:hover { border-color: var(--line-strong); } +.module-card.disabled { opacity: 0.68; } +.module-card.disabled:hover { opacity: 0.9; } +.module-top { display: flex; align-items: flex-start; gap: 11px; } +.module-icon { width: 36px; height: 36px; border-radius: 9px; display: grid; place-items: center; background: var(--surface-2); border: 1px solid var(--line-strong); color: var(--cyan); flex: 0 0 auto; } +.module-icon .ic { width: 18px; height: 18px; } +.module-title { min-width: 0; flex: 1; } +.module-title h3 { font-size: 14px; letter-spacing: -0.01em; display: flex; align-items: center; gap: 7px; flex-wrap: wrap; } +.module-title .sub { color: var(--faint); font-size: 10.5px; margin-top: 2px; } +.module-desc { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 11px 0 13px; min-height: 36px; } +.module-stats { display: flex; gap: 16px; flex-wrap: wrap; padding: 10px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); margin-bottom: 12px; } +.module-stats div { min-width: 0; } +.module-stats dt { color: var(--faint); font-size: 9px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600; } +.module-stats dd { margin: 2px 0 0; font-family: var(--mono); font-size: 11px; color: var(--text-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 118px; } +.module-foot { display: flex; align-items: center; gap: 5px; margin-top: auto; } +.module-foot .switch { margin-left: auto; } +.module-status { display: flex; align-items: center; gap: 5px; color: var(--muted); font-size: 10.5px; margin-top: 7px; } + +.upload-drop { + border: 1.5px dashed var(--line-strong); + border-radius: 12px; + padding: 26px 18px; + text-align: center; + background: rgba(78, 201, 245, 0.025); + cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} +.upload-drop:hover { border-color: var(--accent-line); background: rgba(60, 230, 164, 0.04); } +.upload-drop .ic { width: 26px; height: 26px; color: var(--accent); margin-bottom: 8px; } +.upload-drop strong { display: block; font-size: 13px; } +.upload-drop span { display: block; color: var(--muted); font-size: 11.5px; margin-top: 3px; } +.upload-file { display: flex; align-items: center; gap: 9px; margin-top: 12px; padding: 9px 11px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); font-family: var(--mono); font-size: 11.5px; } + +.log-box { + max-height: 380px; + overflow: auto; + margin: 0; + padding: 14px; + border-radius: 10px; + border: 1px solid var(--line); + background: #060c0f; + color: #a9c0ca; + font-family: var(--mono); + font-size: 11px; + line-height: 1.6; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +/* -------------------------------------------------------------------------- + Simulator + -------------------------------------------------------------------------- */ +.sim-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; } +.sim-form .span-3 { grid-column: 1 / -1; } +.sim-results { display: grid; gap: 12px; } +.sim-resource { border: 1px solid var(--line); border-radius: 10px; padding: 12px; background: rgba(255, 255, 255, 0.012); } +.sim-resource .sr-head { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; } +.sim-resource .sr-head strong { font-size: 12px; } +.sim-resource .sr-head .pill { margin-left: auto; } +.sim-compare { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; } +.sim-compare div { color: var(--muted); font-size: 10.5px; } +.sim-compare strong { display: block; font-family: var(--mono); font-size: 14px; color: var(--text-2); margin-top: 2px; font-weight: 500; } +.sim-compare .after strong { color: var(--accent); } +.sim-compare .warn strong { color: var(--crit); } +.findings { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; } +.findings li { display: flex; gap: 8px; color: var(--text-2); font-size: 12px; line-height: 1.45; } +.findings li .ic { width: 13px; height: 13px; color: var(--accent); flex: 0 0 auto; margin-top: 2px; } +.verdict { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface-2); } +.verdict strong { display: block; font-size: 13.5px; } +.verdict span { color: var(--muted); font-size: 11.5px; } + +/* -------------------------------------------------------------------------- + Copilot + -------------------------------------------------------------------------- */ +.chat-panel { display: flex; flex-direction: column; min-height: 560px; } +.chat-log { flex: 1; padding: 16px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; max-height: 60vh; } +.msg { display: flex; gap: 10px; max-width: 88%; } +.msg.user { margin-left: auto; flex-direction: row-reverse; } +.msg .msg-avatar { width: 26px; height: 26px; border-radius: 7px; flex: 0 0 auto; display: grid; place-items: center; border: 1px solid var(--line-strong); background: var(--surface-2); color: var(--accent); } +.msg.user .msg-avatar { color: var(--cyan); } +.msg .msg-avatar .ic { width: 13px; height: 13px; } +.msg .bubble { padding: 10px 13px; border-radius: 11px; border: 1px solid var(--line); background: var(--surface-2); color: var(--text-2); font-size: 12.5px; line-height: 1.6; overflow-wrap: anywhere; } +.msg.user .bubble { background: rgba(78, 201, 245, 0.09); border-color: rgba(78, 201, 245, 0.22); color: var(--text); } +.msg .bubble p { margin: 0 0 8px; } +.msg .bubble p:last-child { margin-bottom: 0; } +.msg .bubble ul { margin: 4px 0 8px; padding-left: 18px; } +.msg .bubble li { margin: 3px 0; } +.msg .bubble code { font-family: var(--mono); font-size: 11px; background: rgba(255, 255, 255, 0.06); padding: 1px 4px; border-radius: 4px; } +.msg .bubble strong { color: var(--text); } +.msg-note { color: var(--faint); font-size: 10px; margin-top: 5px; } +.typing { display: inline-flex; gap: 4px; align-items: center; } +.typing i { width: 5px; height: 5px; border-radius: 50%; background: var(--muted); animation: typing 1.2s infinite; } +.typing i:nth-child(2) { animation-delay: 0.15s; } +.typing i:nth-child(3) { animation-delay: 0.3s; } +@keyframes typing { 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-2px); } } +.chat-input { display: flex; gap: 9px; padding: 12px 14px; border-top: 1px solid var(--line); align-items: flex-end; } +.chat-input textarea { flex: 1; height: 42px; min-height: 42px; max-height: 150px; resize: none; } +.chat-input .btn { height: 42px; } +.chat-suggest { display: flex; flex-wrap: wrap; gap: 6px; } +.chat-suggest button { border: 1px solid var(--line-strong); background: var(--surface-2); color: var(--muted); border-radius: 20px; padding: 5px 10px; font-size: 11px; cursor: pointer; text-align: left; } +.chat-suggest button:hover { border-color: var(--accent-line); color: var(--text); } + +/* -------------------------------------------------------------------------- + API / settings + -------------------------------------------------------------------------- */ +.code-block { + position: relative; + margin: 0; + padding: 14px; + border-radius: 10px; + border: 1px solid var(--line); + background: #060c0f; + color: #a9c0ca; + font-family: var(--mono); + font-size: 11px; + line-height: 1.65; + overflow-x: auto; + white-space: pre; +} +.code-block .copy-btn { position: absolute; top: 8px; right: 8px; } +.endpoint-list { display: flex; flex-direction: column; } +.endpoint { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 0; + border-bottom: 1px solid rgba(28, 44, 52, 0.55); + font-size: 12px; +} +.endpoint:last-child { border-bottom: 0; } +.method { font-family: var(--mono); font-size: 9.5px; font-weight: 700; width: 42px; text-align: center; padding: 2px 0; border-radius: 4px; flex: 0 0 auto; background: rgba(60, 230, 164, 0.09); color: var(--accent); } +.method.post { background: rgba(78, 201, 245, 0.09); color: var(--cyan); } +.method.put { background: rgba(242, 196, 92, 0.09); color: var(--watch); } +.method.delete { background: rgba(255, 107, 122, 0.09); color: var(--crit); } +.endpoint code { font-family: var(--mono); font-size: 11.5px; color: var(--text-2); } +.endpoint span { color: var(--faint); font-size: 11px; margin-left: auto; text-align: right; } + +.matrix { width: 100%; border-collapse: collapse; font-size: 12px; } +.matrix th { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--line); color: var(--faint); font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.09em; } +.matrix td { padding: 8px 12px; border-bottom: 1px solid rgba(28, 44, 52, 0.55); } +.matrix tr:last-child td { border-bottom: 0; } +.matrix td:not(:first-child), .matrix th:not(:first-child) { text-align: center; width: 100px; } +.matrix .yes { color: var(--accent); } +.matrix .no { color: var(--faint); } +.matrix .group-row td { background: rgba(255, 255, 255, 0.018); color: var(--muted); font-size: 9.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; padding: 6px 12px; } + +.license-current { + display: flex; + align-items: center; + gap: 14px; + padding: 14px; + border-radius: 10px; + border: 1px solid var(--line); + background: var(--surface-2); +} +.license-current .lc-main { flex: 1; min-width: 0; } +.license-current strong { display: block; font-size: 14px; } +.license-current span { color: var(--muted); font-size: 11.5px; } +.license-current .ring { margin-left: auto; } + +.kv-list { display: flex; flex-direction: column; gap: 0; } +.kv-list > div { display: flex; justify-content: space-between; gap: 14px; padding: 8px 0; border-bottom: 1px solid rgba(28, 44, 52, 0.55); font-size: 12px; } +.kv-list > div:last-child { border-bottom: 0; } +.kv-list dt { color: var(--muted); } +.kv-list dd { margin: 0; font-family: var(--mono); font-size: 11.5px; text-align: right; overflow-wrap: anywhere; } + +.danger-zone { border-color: rgba(255, 107, 122, 0.22); } +.danger-zone .panel-head h3 { color: #ff9aa5; } + +/* -------------------------------------------------------------------------- + Empty / insight / CTA + -------------------------------------------------------------------------- */ +.empty { display: grid; place-items: center; text-align: center; padding: 44px 20px; color: var(--muted); } +.empty .empty-icon { width: 44px; height: 44px; border-radius: 12px; display: grid; place-items: center; background: var(--surface-2); border: 1px solid var(--line); color: var(--faint); margin-bottom: 12px; } +.empty .empty-icon .ic { width: 20px; height: 20px; } +.empty strong { display: block; color: var(--text-2); font-size: 13.5px; margin-bottom: 4px; } +.empty p { font-size: 12px; max-width: 340px; } +.empty .btn { margin-top: 14px; } + +.upgrade-cta { + border: 1px solid var(--accent-line); + border-radius: var(--radius); + padding: 20px; + background: + radial-gradient(400px 200px at 0% 0%, rgba(60, 230, 164, 0.12), transparent 70%), + linear-gradient(180deg, rgba(15, 27, 31, 0.98), rgba(10, 17, 21, 0.98)); +} +.upgrade-cta h3 { font-size: 16px; letter-spacing: -0.015em; margin-bottom: 4px; } +.upgrade-cta p { color: var(--muted); font-size: 12.5px; max-width: 620px; } +.upgrade-features { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; margin: 16px 0; } +.upgrade-feature { display: flex; gap: 8px; align-items: flex-start; color: var(--text-2); font-size: 12px; } +.upgrade-feature .ic { width: 13px; height: 13px; color: var(--accent); flex: 0 0 auto; margin-top: 2px; } + +.insight { border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); padding: 13px; font-size: 12.5px; line-height: 1.6; color: var(--text-2); } +.insight h4 { font-size: 11px; color: var(--accent); text-transform: uppercase; letter-spacing: 0.09em; margin-bottom: 7px; } +.insight ul { margin: 5px 0; padding-left: 16px; } +.insight p { margin: 0 0 8px; } +.insight p:last-child { margin-bottom: 0; } + +.notice { display: flex; gap: 9px; padding: 10px 12px; border-radius: 9px; border: 1px solid var(--line-strong); background: var(--surface-2); font-size: 11.5px; color: var(--muted); line-height: 1.5; } +.notice .ic { width: 14px; height: 14px; flex: 0 0 auto; color: var(--cyan); margin-top: 1px; } +.notice.warn { border-color: rgba(242, 196, 92, 0.28); background: rgba(242, 196, 92, 0.05); } +.notice.warn .ic { color: var(--watch); } +.notice.crit { border-color: rgba(255, 107, 122, 0.28); background: rgba(255, 107, 122, 0.05); } +.notice.crit .ic { color: var(--crit); } +.notice.ok { border-color: var(--accent-line); background: var(--accent-soft); } +.notice.ok .ic { color: var(--accent); } + +/* -------------------------------------------------------------------------- + Modal + -------------------------------------------------------------------------- */ +.modal-backdrop { + position: fixed; + inset: 0; + z-index: 80; + display: grid; + place-items: center; + padding: 20px; + background: rgba(3, 7, 9, 0.72); + backdrop-filter: blur(4px); + animation: fadeIn 0.14s ease; +} +@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } +.modal { + width: min(560px, 100%); + max-height: min(86vh, 860px); + display: flex; + flex-direction: column; + border: 1px solid var(--line-strong); + border-radius: 16px; + background: linear-gradient(180deg, #111d23, #0a1216); + box-shadow: 0 30px 90px rgba(0, 0, 0, 0.65); + animation: modalIn 0.16s ease; + overflow: hidden; +} +.modal.wide { width: min(780px, 100%); } +.modal.narrow { width: min(430px, 100%); } +@keyframes modalIn { from { opacity: 0; transform: translateY(8px) scale(0.99); } to { opacity: 1; transform: none; } } +.modal-head { display: flex; align-items: flex-start; gap: 12px; padding: 17px 20px; border-bottom: 1px solid var(--line); } +.modal-head h3 { font-size: 15px; letter-spacing: -0.01em; } +.modal-head .sub { color: var(--muted); font-size: 11.5px; margin-top: 3px; } +.modal-head .icon-btn { margin-left: auto; margin-top: -4px; margin-right: -6px; } +.modal-body { padding: 20px; overflow-y: auto; } +.modal-foot { display: flex; align-items: center; gap: 8px; justify-content: flex-end; padding: 13px 20px; border-top: 1px solid var(--line); background: rgba(0, 0, 0, 0.1); } +.modal-foot .left { margin-right: auto; } +.modal-foot .spacer { flex: 1; } + +/* -------------------------------------------------------------------------- + Toasts + -------------------------------------------------------------------------- */ +.toast-root { position: fixed; right: 18px; bottom: 18px; z-index: 100; display: flex; flex-direction: column; gap: 8px; max-width: min(380px, calc(100vw - 36px)); } +.toast { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 11px 13px; + border-radius: 10px; + border: 1px solid var(--line-strong); + background: rgba(16, 28, 34, 0.98); + box-shadow: var(--shadow); + color: var(--text-2); + font-size: 12.5px; + line-height: 1.45; + animation: toastIn 0.2s ease; +} +.toast.leaving { animation: toastOut 0.18s ease forwards; } +@keyframes toastIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } +@keyframes toastOut { to { opacity: 0; transform: translateY(6px); } } +.toast .ic { width: 15px; height: 15px; flex: 0 0 auto; margin-top: 1px; color: var(--accent); } +.toast.error .ic { color: var(--crit); } +.toast.warn .ic { color: var(--watch); } +.toast.info .ic { color: var(--cyan); } +.toast strong { display: block; color: var(--text); font-size: 12.5px; margin-bottom: 1px; } + +/* -------------------------------------------------------------------------- + Loading skeleton + -------------------------------------------------------------------------- */ +.skeleton { position: relative; overflow: hidden; background: #101b20; border-radius: 6px; color: transparent !important; } +.skeleton::after { content: ""; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.045), transparent); animation: shimmer 1.4s infinite; } +@keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } } +.view-loading { display: grid; gap: 16px; } +.view-loading .bar-block { height: 120px; border-radius: var(--radius); } + +/* -------------------------------------------------------------------------- + Responsive + -------------------------------------------------------------------------- */ +@media (max-width: 1280px) { + .kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .cols-main, .cols-main-rev { grid-template-columns: minmax(0, 1fr); } +} +@media (max-width: 980px) { + .shell { grid-template-columns: minmax(0, 1fr); } + .sidebar { + position: fixed; + left: 0; + top: 0; + width: 262px; + transform: translateX(-100%); + transition: transform 0.22s ease; + box-shadow: var(--shadow); + } + .sidebar.open { transform: none; } + .sidebar-backdrop { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.5); z-index: 29; } + .mobile-menu-btn { display: inline-grid; } + .topbar { padding: 0 16px; } + .view { padding: 20px 16px 48px; } + .login-screen { grid-template-columns: 1fr; } + .login-art { display: none; } + .login-panel { min-height: 100vh; } + .cols-2, .cols-3 { grid-template-columns: minmax(0, 1fr); } + .hero { grid-template-columns: auto minmax(0, 1fr); } + .hero .hero-actions { grid-column: 1 / -1; justify-content: flex-start; } +} +@media (max-width: 680px) { + .kpis { grid-template-columns: minmax(0, 1fr); gap: 10px; } + .form-grid { grid-template-columns: minmax(0, 1fr); } + .form-grid .span-2 { grid-column: auto; } + .sim-form { grid-template-columns: minmax(0, 1fr); } + .sim-form .span-3 { grid-column: auto; } + .page-head { align-items: flex-start; } + .page-actions { margin-left: 0; width: 100%; } + .topbar-status { display: none; } + .topbar-title span { display: none; } + .hero { grid-template-columns: minmax(0, 1fr); } + .hero .ring { display: none; } + .modal { max-height: 92vh; } + .login-card { padding: 26px 22px; } + .kv { grid-template-columns: minmax(0, 1fr); } + .kv > div:nth-child(odd) { border-right: 0; } + .kv > div:nth-last-child(-n+2) { border-bottom: 1px solid var(--line); } + .kv > div:last-child { border-bottom: 0; } + table.data th, table.data td { padding: 9px 10px; } +} diff --git a/app/util.py b/app/util.py new file mode 100644 index 0000000..614a751 --- /dev/null +++ b/app/util.py @@ -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}%" diff --git a/ctlpanel-logo/ctlpanel-logo-horizontal.svg b/ctlpanel-logo/ctlpanel-logo-horizontal.svg new file mode 100644 index 0000000..5f7f87e --- /dev/null +++ b/ctlpanel-logo/ctlpanel-logo-horizontal.svg @@ -0,0 +1,22 @@ + + ctlpanel logo + + + + + + + + + + + + + + + + + + ctlpanel + HOMELAB CONTROL + diff --git a/ctlpanel-logo/ctlpanel-logo-light.svg b/ctlpanel-logo/ctlpanel-logo-light.svg new file mode 100644 index 0000000..799bd89 --- /dev/null +++ b/ctlpanel-logo/ctlpanel-logo-light.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + ctlpanel + diff --git a/ctlpanel-logo/ctlpanel-logo-solid-white.svg b/ctlpanel-logo/ctlpanel-logo-solid-white.svg new file mode 100644 index 0000000..5a499a4 --- /dev/null +++ b/ctlpanel-logo/ctlpanel-logo-solid-white.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + ctlpanel + diff --git a/ctlpanel-logo/ctlpanel-mark-1024.svg b/ctlpanel-logo/ctlpanel-mark-1024.svg new file mode 100644 index 0000000..f647917 --- /dev/null +++ b/ctlpanel-logo/ctlpanel-mark-1024.svg @@ -0,0 +1,14 @@ + + ctlpanel logomark 1024 + + + + + + + + + + + + diff --git a/ctlpanel-logo/ctlpanel-mark-512.svg b/ctlpanel-logo/ctlpanel-mark-512.svg new file mode 100644 index 0000000..9b6e70d --- /dev/null +++ b/ctlpanel-logo/ctlpanel-mark-512.svg @@ -0,0 +1,14 @@ + + ctlpanel logomark + + + + + + + + + + + + diff --git a/ctlpanel-logo/ctlpanel-mark.svg b/ctlpanel-logo/ctlpanel-mark.svg new file mode 100644 index 0000000..957b52a --- /dev/null +++ b/ctlpanel-logo/ctlpanel-mark.svg @@ -0,0 +1,12 @@ + + ctlpanel icon + + + + + + + + + + diff --git a/modules/esxi/manifest.json b/modules/esxi/manifest.json new file mode 100644 index 0000000..2f9f8bb --- /dev/null +++ b/modules/esxi/manifest.json @@ -0,0 +1,23 @@ +{ + "id": "esxi", + "name": "VMware ESXi / vCenter", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "hypervisor", + "icon": "vmware", + "interval_seconds": 300, + "enabled_by_default": true, + "description": "Hosts and datastores via the vSphere API. Install the optional pyvmomi package to collect live host statistics.", + "capabilities": ["assets", "metrics", "capacity"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true}, + {"key": "host", "label": "vCenter / ESXi host", "type": "text", "default": "", "placeholder": "vcenter.lab.local"}, + {"key": "port", "label": "Port", "type": "number", "default": 443}, + {"key": "username", "label": "Username", "type": "text", "default": "", "placeholder": "headroom@vsphere.local"}, + {"key": "password", "label": "Password", "type": "password", "default": ""}, + {"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false}, + {"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "ESXi"} + ] +} diff --git a/modules/esxi/module.py b/modules/esxi/module.py new file mode 100644 index 0000000..1922be8 --- /dev/null +++ b/modules/esxi/module.py @@ -0,0 +1,150 @@ +"""VMware ESXi / vCenter collector using pyVmomi (optional dependency).""" +from __future__ import annotations + +from typing import Any, Dict + +from app import sdk + + +def _connect(config: Dict[str, Any]): + try: + from pyVim.connect import SmartConnect + except ImportError: + raise sdk.ModuleError( + "pyvmomi is not installed. Run: .venv/bin/pip install pyvmomi (then restart Headroom)" + ) + ssl_context = None + if not config.get("verify_tls", True): + import ssl + + ssl_context = ssl._create_unverified_context() + try: + connection = SmartConnect( + host=config.get("host"), + user=config.get("username"), + pwd=config.get("password"), + port=sdk.free_port(config.get("port"), 443), + sslContext=ssl_context, + ) + except Exception as exc: + raise sdk.ModuleError(f"vSphere connection failed: {exc}") + if not connection: + raise sdk.ModuleError("vSphere returned no session") + return connection + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host", "username", "password"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a vSphere endpoint"} + + config = ctx["config"] + try: + from pyVmomi import vim + except ImportError: + raise sdk.ModuleError("pyvmomi is not installed. Run: .venv/bin/pip install pyvmomi") + + connection = _connect(config) + assets = [] + cluster_default = config.get("cluster_name") or "ESXi" + try: + content = connection.RetrieveContent() + host_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True) + try: + for host in host_view.view: + summary = host.summary + hardware = summary.hardware + quick = summary.quickStats + cores = float(getattr(hardware, "numCpuCores", 0) or 0) + cpu_mhz = float(getattr(hardware, "cpuMhz", 0) or 0) * cores + mem_bytes = float(getattr(hardware, "memorySize", 0) or 0) + cluster = cluster_default + try: + if host.parent is not None: + cluster = host.parent.name + except Exception: + pass + assets.append( + sdk.add_asset( + external_id=host.name, + name=host.name, + type_="hypervisor", + metrics={ + "cpu_pct": sdk.percent(float(getattr(quick, "overallCpuUsage", 0) or 0), cpu_mhz), + "mem_pct": sdk.percent( + float(getattr(quick, "overallMemoryUsage", 0) or 0) * 1024 ** 2, mem_bytes + ), + "uptime_days": round(float(getattr(quick, "uptime", 0) or 0) / 86400, 1), + "vm_count": len(getattr(host, "vm", []) or []), + }, + capacity={"cpu_cores": cores, "mem_gb": round(mem_bytes / 1024 ** 3, 1)}, + cluster=cluster, + tags=["esxi"], + meta={ + "version": getattr(summary.config.product, "version", "") if summary.config else "", + "model": getattr(hardware, "model", ""), + }, + ) + ) + finally: + host_view.Destroy() + + datastore_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.Datastore], True) + try: + for datastore in datastore_view.view: + summary = datastore.summary + total = float(summary.capacity or 0) + free = float(summary.freeSpace or 0) + if total <= 0: + continue + cluster = cluster_default + try: + if datastore.parent is not None: + cluster = datastore.parent.name + except Exception: + pass + assets.append( + sdk.add_asset( + external_id=datastore.name, + name=datastore.name, + type_="storage", + metrics={ + "storage_pct": sdk.percent(total - free, total), + "storage_used_gb": round((total - free) / 1024 ** 3, 1), + "storage_total_gb": round(total / 1024 ** 3, 1), + }, + capacity={"storage_gb": round(total / 1024 ** 3, 1)}, + cluster=cluster, + tags=[str(summary.type) if summary.type else "datastore"], + meta={"accessible": bool(summary.accessible)}, + ) + ) + finally: + datastore_view.Destroy() + return {"assets": assets, "notes": f"Collected {len(assets)} assets from {config.get('host')}"} + finally: + try: + from pyVim.connect import Disconnect + + Disconnect(connection) + except Exception: + pass + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host", "username", "password"]): + return {"ok": True, "message": "Demo mode — no vSphere endpoint contacted."} + connection = _connect(ctx["config"]) + try: + about = connection.content.about + return { + "ok": True, + "message": f"Connected to {about.fullName}", + "details": {"version": about.version, "build": about.build}, + } + finally: + try: + from pyVim.connect import Disconnect + + Disconnect(connection) + except Exception: + pass diff --git a/modules/http-json/manifest.json b/modules/http-json/manifest.json new file mode 100644 index 0000000..f8cbcf1 --- /dev/null +++ b/modules/http-json/manifest.json @@ -0,0 +1,23 @@ +{ + "id": "http-json", + "name": "HTTP JSON bridge", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "integration", + "icon": "api", + "interval_seconds": 300, + "enabled_by_default": true, + "description": "Pull a normalized asset/metric payload from any HTTP API, or push to /api/ingest/http-json. Ideal for UPS, switches and custom scripts.", + "capabilities": ["assets", "metrics", "push"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true}, + {"key": "url", "label": "JSON endpoint", "type": "text", "default": "", "placeholder": "https://api.example.net/capacity"}, + {"key": "token", "label": "Bearer token", "type": "password", "default": ""}, + {"key": "headers", "label": "Extra headers (JSON)", "type": "textarea", "default": "", "placeholder": "{\"X-Api-Key\": \"...\"}"}, + {"key": "assets_path", "label": "Assets path", "type": "text", "default": "assets", "help": "Dot path to the asset list, e.g. data.hosts"}, + {"key": "cluster_name", "label": "Default cluster label", "type": "text", "default": "External API"}, + {"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": true} + ] +} diff --git a/modules/http-json/module.py b/modules/http-json/module.py new file mode 100644 index 0000000..d7323e3 --- /dev/null +++ b/modules/http-json/module.py @@ -0,0 +1,82 @@ +"""Generic HTTP JSON bridge. + +Pull mode expects:: + + {"assets": [{"external_id": "...", "name": "...", "type": "server", + "capacity": {"cpu_cores": 8}, + "metrics": {"cpu_pct": 42}}]} + +Configure ``assets_path`` if the list is nested (e.g. ``data.hosts``). +Push mode is served by the core at ``POST /api/ingest/http-json``. +""" +from __future__ import annotations + +import json +from typing import Any, Dict + +from app import sdk + + +def _fetch(ctx: Dict[str, Any]): + config = ctx["config"] + url = str(config.get("url", "")).strip() + if not url: + raise sdk.ModuleError("Configure the JSON endpoint URL") + session = sdk.http_session(config) + token = str(config.get("token", "")).strip() + if token: + session.headers["Authorization"] = f"Bearer {token}" + raw_headers = str(config.get("headers", "") or "").strip() + if raw_headers: + try: + extra = json.loads(raw_headers) + if isinstance(extra, dict): + session.headers.update({str(k): str(v) for k, v in extra.items()}) + except ValueError: + raise sdk.ModuleError("Extra headers must be a JSON object") + response = session.get(url, timeout=30) + response.raise_for_status() + return response.json() + + +def _extract(payload: Any, path: str): + node = payload + for part in (path or "assets").split("."): + if not part: + continue + if not isinstance(node, dict) or part not in node: + raise sdk.ModuleError(f"Assets path '{path}' not found in the response") + node = node[part] + if isinstance(node, dict) and "external_id" in node: + return [node] + if not isinstance(node, list): + raise sdk.ModuleError(f"Assets path '{path}' did not resolve to a list") + return node + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["url"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — no external API contacted"} + + config = ctx["config"] + payload = _fetch(ctx) + items = _extract(payload, str(config.get("assets_path") or "assets")) + cluster = str(config.get("cluster_name") or "").strip() + assets = [] + for item in items[:2000]: + if not isinstance(item, dict): + continue + item = dict(item) + item.setdefault("type", "server") + if cluster and not item.get("cluster"): + item["cluster"] = cluster + assets.append(item) + return {"assets": assets, "notes": f"Fetched {len(assets)} assets from {config.get('url')}"} + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["url"]): + return {"ok": True, "message": "Demo mode — no external API contacted."} + payload = _fetch(ctx) + items = _extract(payload, str(ctx["config"].get("assets_path") or "assets")) + return {"ok": True, "message": f"Endpoint reachable — found {len(items)} asset(s)."} diff --git a/modules/linux/manifest.json b/modules/linux/manifest.json new file mode 100644 index 0000000..b9f77e7 --- /dev/null +++ b/modules/linux/manifest.json @@ -0,0 +1,22 @@ +{ + "id": "linux", + "name": "Linux hosts (SSH)", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "os", + "icon": "linux", + "interval_seconds": 300, + "enabled_by_default": true, + "description": "Agentless Linux host metrics over SSH using /proc and df. Key-based authentication only.", + "capabilities": ["assets", "metrics", "capacity"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true}, + {"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "lnx-01.lab.local"}, + {"key": "port", "label": "SSH port", "type": "number", "default": 22}, + {"key": "username", "label": "SSH username", "type": "text", "default": "headroom"}, + {"key": "key_path", "label": "Private key path", "type": "text", "default": "", "placeholder": "~/.ssh/id_ed25519"}, + {"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Linux"} + ] +} diff --git a/modules/linux/module.py b/modules/linux/module.py new file mode 100644 index 0000000..7b592a5 --- /dev/null +++ b/modules/linux/module.py @@ -0,0 +1,140 @@ +"""Agentless Linux host collector over SSH (key authentication).""" +from __future__ import annotations + +import subprocess +from pathlib import Path +from typing import Any, Dict + +from app import sdk + +SCRIPT = r""" +set -e +echo "__NPROC__" +nproc +echo "__MEM__" +awk '/MemTotal/{t=$2} /MemAvailable/{a=$2} /MemFree/{f=$2} END{if(!a)a=f; print t, a}' /proc/meminfo +echo "__DISK__" +df -P -B1 / | awk 'NR==2 {print $2, $3}' +echo "__UPTIME__" +awk '{print $1}' /proc/uptime +echo "__LOAD__" +awk '{print $1}' /proc/loadavg +echo "__OS__" +uname -sr +echo "__CPU1__" +awk '/^cpu / {s=0; for(i=2;i<=NF;i++) s+=$i; print s, $5+$6}' /proc/stat +sleep 1 +echo "__CPU2__" +awk '/^cpu / {s=0; for(i=2;i<=NF;i++) s+=$i; print s, $5+$6}' /proc/stat +""" + + +def _ssh(config: Dict[str, Any], command: str, timeout: int = 40) -> str: + host = str(config.get("host", "")).strip() + user = str(config.get("username", "")).strip() + if not host or not user: + raise sdk.ModuleError("Configure host and SSH username") + key_path = str(config.get("key_path", "")).strip() + if not key_path: + key_path = "~/.ssh/id_ed25519" + key = Path(key_path).expanduser() + if not key.exists(): + raise sdk.ModuleError(f"SSH private key not found: {key}") + command_line = [ + "ssh", + "-i", str(key), + "-p", str(sdk.free_port(config.get("port"), 22)), + "-o", "BatchMode=yes", + "-o", "StrictHostKeyChecking=accept-new", + "-o", "ConnectTimeout=10", + "-o", "LogLevel=ERROR", + f"{user}@{host}", + command, + ] + try: + result = subprocess.run(command_line, capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + raise sdk.ModuleError("SSH command timed out") + except FileNotFoundError: + raise sdk.ModuleError("The 'ssh' client is not available on the Headroom host") + if result.returncode != 0: + detail = (result.stderr or result.stdout or "").strip()[-500:] + raise sdk.ModuleError(f"SSH failed (exit {result.returncode}): {detail}") + return result.stdout + + +def _parse_markers(output: str) -> Dict[str, str]: + values: Dict[str, str] = {} + current = None + buffer = [] + for line in output.splitlines(): + if line.startswith("__") and line.endswith("__"): + if current: + values[current] = "\n".join(buffer).strip() + current = line.strip("_") + buffer = [] + elif current: + buffer.append(line) + if current: + values[current] = "\n".join(buffer).strip() + return values + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without an SSH endpoint"} + + config = ctx["config"] + output = _ssh(config, SCRIPT) + data = _parse_markers(output) + try: + nproc = max(1, int(float(data.get("NPROC", "1")))) + mem_parts = data.get("MEM", "0 0").split() + mem_total_kb = float(mem_parts[0]) + mem_avail_kb = float(mem_parts[1]) if len(mem_parts) > 1 else 0.0 + disk_parts = data.get("DISK", "0 0").split() + disk_total = float(disk_parts[0]) + disk_used = float(disk_parts[1]) + uptime_seconds = float(data.get("UPTIME", "0").split()[0]) + load1 = float(data.get("LOAD", "0").split()[0]) + cpu1 = [float(x) for x in data.get("CPU1", "0 0").split()] + cpu2 = [float(x) for x in data.get("CPU2", "0 0").split()] + total_delta = cpu2[0] - cpu1[0] + idle_delta = cpu2[1] - cpu1[1] + cpu_pct = (1 - idle_delta / total_delta) * 100 if total_delta > 0 else 0.0 + mem_total_bytes = mem_total_kb * 1024 + mem_used_bytes = max(0.0, mem_total_bytes - mem_avail_kb * 1024) + metrics = { + "cpu_pct": round(max(0.0, min(100.0, cpu_pct)), 2), + "mem_pct": round(sdk.percent(mem_used_bytes, mem_total_bytes), 2), + "storage_pct": round(sdk.percent(disk_used, disk_total), 2), + "storage_used_gb": round(disk_used / 1024 ** 3, 1), + "storage_total_gb": round(disk_total / 1024 ** 3, 1), + "load_pct": round(load1 / nproc * 100, 1), + "uptime_days": round(uptime_seconds / 86400, 1), + } + except (ValueError, IndexError) as exc: + raise sdk.ModuleError(f"Could not parse Linux telemetry: {exc}") + host = str(config.get("host")) + asset = sdk.add_asset( + external_id=host, + name=host.split(".")[0], + type_="server", + metrics=metrics, + capacity={ + "cpu_cores": nproc, + "mem_gb": round(mem_total_bytes / 1024 ** 3, 1), + "storage_gb": round(disk_total / 1024 ** 3, 1), + }, + cluster=config.get("cluster_name") or "Linux", + tags=["linux"], + meta={"os": data.get("OS", ""), "host": host}, + ) + return {"assets": [asset], "notes": f"Collected Linux telemetry from {host}"} + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host"]): + return {"ok": True, "message": "Demo mode — no SSH endpoint contacted."} + output = _ssh(ctx["config"], "echo connected; uname -sr", timeout=25) + return {"ok": True, "message": f"SSH connection OK — {output.strip()[:120]}"} diff --git a/modules/proxmox/manifest.json b/modules/proxmox/manifest.json new file mode 100644 index 0000000..02625c9 --- /dev/null +++ b/modules/proxmox/manifest.json @@ -0,0 +1,25 @@ +{ + "id": "proxmox", + "name": "Proxmox VE", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "hypervisor", + "icon": "proxmox", + "interval_seconds": 300, + "enabled_by_default": true, + "description": "Nodes, storage and guest counts from the Proxmox VE API. Uses API tokens (recommended) or ticket auth.", + "capabilities": ["assets", "metrics", "capacity"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true, "help": "Generate realistic local data without contacting a Proxmox host."}, + {"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "pve.lab.local"}, + {"key": "port", "label": "API port", "type": "number", "default": 8006}, + {"key": "token_id", "label": "API token ID", "type": "text", "default": "", "placeholder": "root@pam!headroom"}, + {"key": "token_secret", "label": "API token secret", "type": "password", "default": ""}, + {"key": "username", "label": "Username (fallback)", "type": "text", "default": "", "placeholder": "root@pam"}, + {"key": "password", "label": "Password (fallback)", "type": "password", "default": ""}, + {"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false}, + {"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Proxmox"} + ] +} diff --git a/modules/proxmox/module.py b/modules/proxmox/module.py new file mode 100644 index 0000000..370ea13 --- /dev/null +++ b/modules/proxmox/module.py @@ -0,0 +1,119 @@ +"""Proxmox VE collector — API token (recommended) or ticket authentication.""" +from __future__ import annotations + +from typing import Any, Dict + +from app import sdk + + +def _session(config: Dict[str, Any]): + base = sdk.base_url(config, "https", 8006) + session = sdk.http_session(config) + token_id = str(config.get("token_id", "")).strip() + token_secret = str(config.get("token_secret", "")).strip() + if token_id and token_secret: + session.headers["Authorization"] = f"PVEAPIToken={token_id}={token_secret}" + elif config.get("username") and config.get("password"): + response = session.post( + f"{base}/api2/json/access/ticket", + data={"username": config.get("username"), "password": config.get("password")}, + timeout=15, + ) + response.raise_for_status() + ticket = (response.json().get("data") or {}).get("ticket") + if not ticket: + raise sdk.ModuleError("Proxmox ticket authentication returned no ticket") + session.cookies.set("PVEAuthCookie", ticket) + else: + raise sdk.ModuleError("Configure an API token or username/password for Proxmox") + return base, session + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a Proxmox endpoint"} + + config = ctx["config"] + base, session = _session(config) + cluster = config.get("cluster_name") or "Proxmox" + try: + nodes = sdk.get_json(session, f"{base}/api2/json/nodes").get("data", []) + assets = [] + for node in nodes[:100]: + name = node.get("node") or node.get("id") or "node" + if node.get("status") not in (None, "online"): + continue + maxmem = float(node.get("maxmem") or 0) + mem = float(node.get("mem") or 0) + maxcpu = float(node.get("maxcpu") or 0) + metrics = { + "cpu_pct": round(float(node.get("cpu") or 0) * 100, 2), + "mem_pct": sdk.percent(mem, maxmem), + "uptime_days": round(float(node.get("uptime") or 0) / 86400, 1), + } + try: + qemu = sdk.get_json(session, f"{base}/api2/json/nodes/{name}/qemu").get("data", []) + lxc = sdk.get_json(session, f"{base}/api2/json/nodes/{name}/lxc").get("data", []) + metrics["vm_count"] = len(qemu) + len(lxc) + except Exception as exc: + ctx["log"](f"guest inventory failed for {name}: {exc}") + assets.append( + sdk.add_asset( + external_id=name, + name=name, + type_="hypervisor", + metrics=metrics, + capacity={"cpu_cores": maxcpu, "mem_gb": round(maxmem / 1024 ** 3, 1)}, + cluster=cluster, + tags=["pve"], + meta={"version": node.get("version") or "", "status": node.get("status") or ""}, + ) + ) + try: + storages = sdk.get_json(session, f"{base}/api2/json/nodes/{name}/storage").get("data", []) + except Exception as exc: + ctx["log"](f"storage inventory failed for {name}: {exc}") + storages = [] + for storage in storages: + if storage.get("active") == 0: + continue + total = float(storage.get("total") or 0) + used = float(storage.get("used") or 0) + if total <= 0: + continue + storage_name = str(storage.get("storage") or "storage") + shared = bool(storage.get("shared")) + external_id = storage_name if shared else f"{name}/{storage_name}" + display = storage_name if shared else f"{storage_name} ({name})" + assets.append( + sdk.add_asset( + external_id=external_id, + name=display, + type_="storage", + metrics={ + "storage_pct": sdk.percent(used, total), + "storage_used_gb": round(used / 1024 ** 3, 1), + "storage_total_gb": round(total / 1024 ** 3, 1), + }, + capacity={"storage_gb": round(total / 1024 ** 3, 1)}, + cluster=cluster, + tags=["shared"] if shared else ["local"], + meta={"node": name, "type": storage.get("type") or "", "content": storage.get("content") or ""}, + ) + ) + return {"assets": assets, "notes": f"Collected {len(assets)} assets from {base}"} + except Exception as exc: + raise sdk.ModuleError(f"Proxmox collection failed: {exc}") + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host"]): + return {"ok": True, "message": "Demo mode — no Proxmox endpoint contacted."} + config = ctx["config"] + base, session = _session(config) + version = sdk.get_json(session, f"{base}/api2/json/version").get("data", {}) + return { + "ok": True, + "message": f"Connected to Proxmox {version.get('version', '')} at {base}", + "details": {"version": version.get("version"), "release": version.get("release")}, + } diff --git a/modules/splunk/manifest.json b/modules/splunk/manifest.json new file mode 100644 index 0000000..7296894 --- /dev/null +++ b/modules/splunk/manifest.json @@ -0,0 +1,24 @@ +{ + "id": "splunk", + "name": "Splunk", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "observability", + "icon": "splunk", + "interval_seconds": 600, + "enabled_by_default": true, + "description": "Index storage, license consumption and indexer health from the Splunk management API.", + "capabilities": ["assets", "metrics", "capacity"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true}, + {"key": "host", "label": "Search head / indexer", "type": "text", "default": "", "placeholder": "splunk.lab.local"}, + {"key": "port", "label": "Management port", "type": "number", "default": 8089}, + {"key": "token", "label": "Bearer token", "type": "password", "default": ""}, + {"key": "username", "label": "Username (fallback)", "type": "text", "default": ""}, + {"key": "password", "label": "Password (fallback)", "type": "password", "default": ""}, + {"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false}, + {"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Splunk"} + ] +} diff --git a/modules/splunk/module.py b/modules/splunk/module.py new file mode 100644 index 0000000..1b8cf50 --- /dev/null +++ b/modules/splunk/module.py @@ -0,0 +1,137 @@ +"""Splunk collector — storage, license consumption and index sizes.""" +from __future__ import annotations + +from typing import Any, Dict + +from app import sdk + + +def _session(config: Dict[str, Any]): + base = sdk.base_url(config, "https", 8089) + session = sdk.http_session(config) + token = str(config.get("token", "")).strip() + if token: + session.headers["Authorization"] = f"Bearer {token}" + elif config.get("username") and config.get("password"): + session.auth = (config.get("username"), config.get("password")) + else: + raise sdk.ModuleError("Configure a Splunk bearer token or username/password") + return base, session + + +def _entries(payload: Any): + if isinstance(payload, dict): + return payload.get("entry") or [] + return [] + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a Splunk endpoint"} + + config = ctx["config"] + base, session = _session(config) + cluster = config.get("cluster_name") or "Splunk" + metrics: Dict[str, float] = {} + capacity: Dict[str, float] = {} + meta: Dict[str, Any] = {} + notes = [] + + try: + info = sdk.get_json(session, f"{base}/services/server/info?output_mode=json") + content = (_entries(info) or [{}])[0].get("content", {}) + hostname = content.get("host") or config.get("host") + meta["version"] = content.get("version", "") + meta["server_name"] = hostname + cores = content.get("numberOfCores") or content.get("numberOfVirtualCores") + if cores: + capacity["cpu_cores"] = float(cores) + memory_mb = content.get("physicalMemoryMB") or content.get("memory") + if memory_mb: + capacity["mem_gb"] = round(float(memory_mb) / 1024, 1) + except Exception as exc: + raise sdk.ModuleError(f"Splunk server info failed: {exc}") + hostname = meta.get("server_name") or "splunk" + + try: + partitions = sdk.get_json(session, f"{base}/services/server/status/partitions-space?output_mode=json") + chosen = None + for entry in _entries(partitions): + content = entry.get("content", {}) + if str(content.get("mount_point")) in ("/", "/opt", "/opt/splunk"): + chosen = content + if content.get("mount_point") == "/": + break + if chosen is None: + entries = _entries(partitions) + chosen = entries[0].get("content", {}) if entries else None + if chosen: + total_mb = float(chosen.get("capacity") or 0) + free_mb = float(chosen.get("available") or 0) + if total_mb > 0: + used_mb = float(chosen.get("used") or (total_mb - free_mb)) + metrics["storage_pct"] = sdk.percent(used_mb, total_mb) + metrics["storage_used_gb"] = round(used_mb / 1024, 1) + metrics["storage_total_gb"] = round(total_mb / 1024, 1) + capacity["storage_gb"] = round(total_mb / 1024, 1) + meta["mount"] = chosen.get("mount_point") + except Exception as exc: + notes.append(f"partition data unavailable ({exc})") + + try: + usage = sdk.get_json(session, f"{base}/services/license/usage?output_mode=json") + used = 0.0 + quota = 0.0 + for entry in _entries(usage): + content = entry.get("content", {}) + try: + used += float(content.get("used") or 0) + quota += float(content.get("quota") or 0) + except (TypeError, ValueError): + continue + if quota > 0: + metrics["license_pct"] = sdk.percent(used, quota) + meta["license_quota_gb"] = round(quota / 1024 ** 3, 1) + except Exception as exc: + notes.append(f"license data unavailable ({exc})") + + try: + indexes = sdk.get_json(session, f"{base}/services/data/indexes?output_mode=json") + index_mb = 0.0 + for entry in _entries(indexes): + try: + index_mb += float(entry.get("content", {}).get("currentDBSizeMB") or 0) + except (TypeError, ValueError): + continue + if index_mb: + metrics["index_gb"] = round(index_mb / 1024, 1) + except Exception as exc: + notes.append(f"index data unavailable ({exc})") + + asset = sdk.add_asset( + external_id=hostname, + name=hostname, + type_="appliance", + metrics=metrics, + capacity=capacity, + cluster=cluster, + tags=["splunk"], + meta=meta, + ) + note = f"Collected Splunk telemetry from {base}" + if notes: + note += " — " + "; ".join(notes) + return {"assets": [asset], "notes": note} + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host"]): + return {"ok": True, "message": "Demo mode — no Splunk endpoint contacted."} + base, session = _session(ctx["config"]) + info = sdk.get_json(session, f"{base}/services/server/info?output_mode=json") + content = (_entries(info) or [{}])[0].get("content", {}) + return { + "ok": True, + "message": f"Connected to Splunk {content.get('version', '')} at {base}", + "details": {"version": content.get("version"), "host": content.get("host")}, + } diff --git a/modules/truenas/manifest.json b/modules/truenas/manifest.json new file mode 100644 index 0000000..2b85d3f --- /dev/null +++ b/modules/truenas/manifest.json @@ -0,0 +1,22 @@ +{ + "id": "truenas", + "name": "TrueNAS / NAS", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "storage", + "icon": "truenas", + "interval_seconds": 600, + "enabled_by_default": true, + "description": "Pools, capacity and system load from the TrueNAS SCALE REST API. Works with TrueNAS 24.04+.", + "capabilities": ["assets", "metrics", "capacity"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true}, + {"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "truenas.lab.local"}, + {"key": "port", "label": "API port", "type": "number", "default": 443}, + {"key": "api_key", "label": "API key", "type": "password", "default": ""}, + {"key": "verify_tls", "label": "Verify TLS certificate", "type": "boolean", "default": false}, + {"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Storage"} + ] +} diff --git a/modules/truenas/module.py b/modules/truenas/module.py new file mode 100644 index 0000000..753f4dc --- /dev/null +++ b/modules/truenas/module.py @@ -0,0 +1,103 @@ +"""TrueNAS SCALE collector — pools and system load.""" +from __future__ import annotations + +from typing import Any, Dict + +from app import sdk + + +def _session(config: Dict[str, Any]): + base = sdk.base_url(config, "https", 443) + session = sdk.http_session(config) + key = str(config.get("api_key", "")).strip() + if not key: + raise sdk.ModuleError("Configure a TrueNAS API key") + session.headers["Authorization"] = f"Bearer {key}" + return base, session + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host", "api_key"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a TrueNAS endpoint"} + + config = ctx["config"] + base, session = _session(config) + cluster = config.get("cluster_name") or "Storage" + try: + info = sdk.get_json(session, f"{base}/api/v2.0/system/info") + except Exception as exc: + raise sdk.ModuleError(f"TrueNAS system info failed: {exc}") + hostname = info.get("hostname") or config.get("host") or "truenas" + cores = float(info.get("cores") or 0) + physmem = float(info.get("physmem") or 0) + uptime = float(info.get("uptime_seconds") or 0) + metrics: Dict[str, float] = {"uptime_days": round(uptime / 86400, 1)} + loadavg = info.get("loadavg") or [] + if cores and loadavg: + try: + metrics["load_pct"] = round(float(loadavg[0]) / cores * 100, 1) + except (TypeError, ValueError): + pass + assets = [ + sdk.add_asset( + external_id=hostname, + name=hostname, + type_="nas", + metrics=metrics, + capacity={"cpu_cores": cores, "mem_gb": round(physmem / 1024 ** 3, 1)}, + cluster=cluster, + tags=["truenas"], + meta={"version": str(info.get("version", "")), "model": str(info.get("system_product", ""))}, + ) + ] + + notes = [] + try: + pools = sdk.get_json(session, f"{base}/api/v2.0/pool") + except Exception as exc: + raise sdk.ModuleError(f"TrueNAS pool inventory failed: {exc}") + pool_rows = pools if isinstance(pools, list) else [] + for pool in pool_rows[:100]: + name = str(pool.get("name") or "pool") + total = float(pool.get("size") or 0) + allocated = float(pool.get("allocated") or pool.get("used") or 0) + if total <= 0: + notes.append(f"pool {name}: capacity not reported by this API version") + continue + assets.append( + sdk.add_asset( + external_id=f"pool-{name}", + name=f"{name} (pool)", + type_="storage", + metrics={ + "storage_pct": sdk.percent(allocated, total), + "storage_used_gb": round(allocated / 1024 ** 3, 1), + "storage_total_gb": round(total / 1024 ** 3, 1), + }, + capacity={"storage_gb": round(total / 1024 ** 3, 1)}, + cluster=cluster, + tags=["zfs", str(pool.get("status", "")).lower()], + meta={ + "pool": name, + "status": pool.get("status"), + "healthy": pool.get("healthy"), + "fragmentation": pool.get("fragmentation"), + }, + ) + ) + note = f"Collected {len(assets)} assets from {base}" + if notes: + note += " — " + "; ".join(notes) + return {"assets": assets, "notes": note} + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host", "api_key"]): + return {"ok": True, "message": "Demo mode — no TrueNAS endpoint contacted."} + base, session = _session(ctx["config"]) + info = sdk.get_json(session, f"{base}/api/v2.0/system/info") + return { + "ok": True, + "message": f"Connected to {info.get('hostname', base)} (TrueNAS {info.get('version', '')})", + "details": {"version": info.get("version"), "hostname": info.get("hostname")}, + } diff --git a/modules/windows/manifest.json b/modules/windows/manifest.json new file mode 100644 index 0000000..b1f3441 --- /dev/null +++ b/modules/windows/manifest.json @@ -0,0 +1,23 @@ +{ + "id": "windows", + "name": "Windows hosts (WinRM)", + "version": "1.0.0", + "api_version": 1, + "vendor": "Headroom", + "category": "os", + "icon": "windows", + "interval_seconds": 300, + "enabled_by_default": true, + "description": "Windows Server CPU, memory, disk and uptime via WinRM/PowerShell. Requires the optional pywinrm package.", + "capabilities": ["assets", "metrics", "capacity"], + "docs": "docs/MODULE_SDK.md", + "settings_schema": [ + {"key": "demo", "label": "Demo mode", "type": "boolean", "default": true}, + {"key": "host", "label": "Host / IP", "type": "text", "default": "", "placeholder": "win-01.lab.local"}, + {"key": "port", "label": "WinRM port", "type": "number", "default": 5985}, + {"key": "username", "label": "Username", "type": "text", "default": "", "placeholder": "LAB\\headroom"}, + {"key": "password", "label": "Password", "type": "password", "default": ""}, + {"key": "transport", "label": "Transport", "type": "select", "default": "ntlm", "options": ["ntlm", "basic", "credssp"]}, + {"key": "cluster_name", "label": "Cluster label", "type": "text", "default": "Windows"} + ] +} diff --git a/modules/windows/module.py b/modules/windows/module.py new file mode 100644 index 0000000..5285fd1 --- /dev/null +++ b/modules/windows/module.py @@ -0,0 +1,117 @@ +"""Windows Server collector over WinRM (optional pywinrm dependency).""" +from __future__ import annotations + +import json +from typing import Any, Dict + +from app import sdk + +PS_SCRIPT = r""" +$ErrorActionPreference = 'Stop' +$os = Get-CimInstance Win32_OperatingSystem +$cs = Get-CimInstance Win32_ComputerSystem +$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average +$disks = @(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3") +$size = ($disks | Measure-Object -Property Size -Sum).Sum +$free = ($disks | Measure-Object -Property FreeSpace -Sum).Sum +$memTotal = [double]$os.TotalVisibleMemorySize * 1KB +$memFree = [double]$os.FreePhysicalMemory * 1KB +$up = ((Get-Date) - $os.LastBootUpTime).TotalDays +[pscustomobject]@{ + name = $env:COMPUTERNAME + cpu_pct = [math]::Round([double]$cpu, 1) + mem_pct = [math]::Round((($memTotal - $memFree) / $memTotal) * 100, 1) + storage_pct = if ($size -gt 0) { [math]::Round((($size - $free) / $size) * 100, 1) } else { 0 } + storage_total_gb = [math]::Round($size / 1GB, 1) + storage_used_gb = [math]::Round(($size - $free) / 1GB, 1) + uptime_days = [math]::Round($up, 1) + cores = [int]$cs.NumberOfLogicalProcessors + mem_total_gb = [math]::Round($memTotal / 1GB, 1) + os = $os.Caption + version = $os.Version +} | ConvertTo-Json -Compress +""" + + +def _session(config: Dict[str, Any]): + try: + import winrm + except ImportError: + raise sdk.ModuleError( + "pywinrm is not installed. Run: .venv/bin/pip install pywinrm (then restart Headroom)" + ) + host = str(config.get("host", "")).strip() + if not host or not config.get("username") or not config.get("password"): + raise sdk.ModuleError("Configure host, username and password for WinRM") + port = sdk.free_port(config.get("port"), 5985) + scheme = "https" if port == 5986 else "http" + transport = str(config.get("transport") or "ntlm") + try: + return winrm.Session( + f"{scheme}://{host}:{port}/wsman", + auth=(str(config.get("username")), str(config.get("password"))), + transport=transport, + server_cert_validation="ignore", + ) + except Exception as exc: + raise sdk.ModuleError(f"WinRM session failed: {exc}") + + +def _run(session, script: str): + result = session.run_ps(script) + stdout = result.std_out.decode(errors="replace") if isinstance(result.std_out, bytes) else str(result.std_out) + stderr = result.std_err.decode(errors="replace") if isinstance(result.std_err, bytes) else str(result.std_err) + if result.status_code != 0: + raise sdk.ModuleError(f"PowerShell failed: {(stderr or stdout).strip()[:500]}") + return stdout.strip() + + +def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host", "username", "password"]): + return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without a WinRM endpoint"} + + config = ctx["config"] + session = _session(config) + try: + raw = _run(session, PS_SCRIPT) + data = json.loads(raw) + if isinstance(data, list): + data = data[0] + except json.JSONDecodeError: + raise sdk.ModuleError("Could not parse PowerShell output as JSON") + except Exception as exc: + if isinstance(exc, sdk.ModuleError): + raise + raise sdk.ModuleError(f"WinRM collection failed: {exc}") + name = str(data.get("name") or config.get("host")) + metrics = { + key: float(data[key]) + for key in ("cpu_pct", "mem_pct", "storage_pct", "storage_used_gb", "storage_total_gb", "uptime_days") + if isinstance(data.get(key), (int, float)) + } + asset = sdk.add_asset( + external_id=name, + name=name, + type_="server", + metrics=metrics, + capacity={ + "cpu_cores": float(data.get("cores") or 0), + "mem_gb": float(data.get("mem_total_gb") or 0), + "storage_gb": float(data.get("storage_total_gb") or 0), + }, + cluster=config.get("cluster_name") or "Windows", + tags=["windows"], + meta={"os": str(data.get("os", "")), "version": str(data.get("version", ""))}, + ) + return {"assets": [asset], "notes": f"Collected Windows telemetry from {name}"} + + +def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: + if sdk.use_demo(ctx, ["host", "username", "password"]): + return {"ok": True, "message": "Demo mode — no WinRM endpoint contacted."} + session = _session(ctx["config"]) + try: + output = _run(session, "hostname") + except Exception as exc: + raise sdk.ModuleError(f"WinRM test failed: {exc}") + return {"ok": True, "message": f"WinRM connection OK — {output.strip()[:120]}"} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d83e34d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +# Core runtime +fastapi>=0.110,<1 +uvicorn[standard]>=0.29 +requests>=2.31 +python-multipart>=0.0.9 + +# Optional integrations (install when you connect the real systems) +# pyvmomi>=8.0 # VMware ESXi / vCenter deep metrics +# pywinrm>=0.4 # Windows hosts over WinRM + +# Development / tests +pytest>=8.0 +httpx>=0.27 diff --git a/run.sh b/run.sh new file mode 100644 index 0000000..2db50b8 --- /dev/null +++ b/run.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" + +if [ ! -d .venv ]; then + echo "Creating virtual environment..." + python3 -m venv .venv +fi +./.venv/bin/pip install --disable-pip-version-check -q -r requirements.txt + +PORT="${HEADROOM_PORT:-8787}" +echo "" +echo " Headroom is starting on http://127.0.0.1:${PORT}" +echo " Login: admin / admin (change it in Settings)" +echo "" +exec ./.venv/bin/python -m uvicorn app.main:app --host "${HEADROOM_HOST:-127.0.0.1}" --port "$PORT" "$@" diff --git a/rune.yaml b/rune.yaml new file mode 100644 index 0000000..22deac9 --- /dev/null +++ b/rune.yaml @@ -0,0 +1,55 @@ +gameskill: + id: headroom + name: "Headroom" + category: "Apps" + description: "Know your headroom. Before you run out. Capacity management for homelabs with collectors and insights." + author: "Netic" + version: 1 + icon: "chart" + + docker: + image: "ghcr.io/kristianwind/headroom:latest" + data_path: /data + env: + HEADROOM_DATA: /data + HEADROOM_MODULES: /app/modules + + variables: + - key: ADMIN_USER + name: "Admin username" + type: string + default: "admin" + required: true + - key: ADMIN_PASSWORD + name: "Admin password" + type: string + default: "admin" + required: true + secret: true + - key: PUBLIC_URL + name: "Public address (leave blank to use the panel's)" + type: string + default: "{{PUBLIC_URL}}" + pattern: '^$|^https?://\S+$' + hint: "Full URL, e.g. https://headroom.example.com" + - key: SEED_DEMO + name: "Seed demo data on first run" + type: bool + default: true + - key: ALLOW_DEV_LICENSE + name: "Allow development license issuer" + type: bool + default: true + + startup: + command: "exec python -m uvicorn app.main:app --host 0.0.0.0 --port :8080 --workers 1" + done_regex: "Application startup complete" + stop_timeout: 30 + + ports: + - name: web + default: 8787 + protocol: tcp + + backup: + include: ["."]