Files
headroom/app/capacity.py
T
kristianwind 15bbe02277 Headroom: homelab capacity dashboard
- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json)
- Multi-instance support: flere instanser af samme modultype med adskilte assets
- Community/Enterprise licensing med admin enterprise-toggle
- Capacity forecasting, trends, what-if simulator, alert policies
- MCP server + LLM copilot integration
- Dockerfile + rune.yaml til Yggdrasil
2026-10-23 22:39:27 +02:00

936 lines
38 KiB
Python

"""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