Headroom: homelab capacity dashboard
- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json) - Multi-instance support: flere instanser af samme modultype med adskilte assets - Community/Enterprise licensing med admin enterprise-toggle - Capacity forecasting, trends, what-if simulator, alert policies - MCP server + LLM copilot integration - Dockerfile + rune.yaml til Yggdrasil
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user