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