Explorar o código

feat: add database overview and health check API routes

Manuel hai 8 meses
pai
achega
511ce2759c
Modificáronse 3 ficheiros con 148 adicións e 0 borrados
  1. 2 0
      routes/admin/__init__.py
  2. 27 0
      routes/admin/database.py
  3. 119 0
      services/database/db_info_service.py

+ 2 - 0
routes/admin/__init__.py

@@ -12,6 +12,7 @@ from . import (
     acls,
     backup,
     blacklist,
+    database,
     dashboard,
     delay_pools,
     http_access,
@@ -35,4 +36,5 @@ delay_pools.register_routes(admin_bp)
 quota.register_routes(admin_bp)
 logs.register_routes(admin_bp)
 backup.register_routes(admin_bp)
+database.register_routes(admin_bp)
 system_api.register_routes(admin_bp)

+ 27 - 0
routes/admin/database.py

@@ -0,0 +1,27 @@
+"""Admin database overview – health panel, integrity check API."""
+
+from flask import jsonify, render_template
+
+from services.auth.auth_service import admin_required, api_auth_required
+from services.database import backup_service
+from services.database.db_info_service import get_db_health, run_integrity_check
+
+
+def register_routes(bp):
+    @bp.route("/database")
+    @admin_required
+    def database_view():
+        cfg = backup_service.load_config()
+        return render_template("admin/database.html", current_config=cfg)
+
+    @bp.route("/api/db-health", methods=["GET"])
+    @api_auth_required
+    def db_health():
+        resp, code = get_db_health()
+        return jsonify(resp), code
+
+    @bp.route("/api/db-integrity", methods=["POST"])
+    @api_auth_required
+    def db_integrity():
+        resp, code = run_integrity_check()
+        return jsonify(resp), code

+ 119 - 0
services/database/db_info_service.py

@@ -1,4 +1,5 @@
 from loguru import logger
+from sqlalchemy import text
 
 from config import Config
 from database.database import get_engine, get_session
@@ -33,3 +34,121 @@ def get_tables_info():
     finally:
         if session:
             session.close()
+
+
+def get_db_health():
+    """Return a fast health snapshot of the database (no full table scans)."""
+    session = None
+    try:
+        engine = get_engine()
+        session = get_session()
+        db_type = Config.DATABASE_TYPE
+
+        stats = get_all_tables_stats(session, engine, db_type)
+        table_count = len(stats)
+        total_rows = sum(v["rows"] for v in stats.values())
+
+        health = {
+            "db_type": db_type,
+            "table_count": table_count,
+            "total_rows": total_rows,
+            "total_size_bytes": 0,
+            "extra": {},
+        }
+
+        if db_type == "SQLITE":
+            page_size = session.execute(text("PRAGMA page_size")).scalar() or 0
+            page_count = session.execute(text("PRAGMA page_count")).scalar() or 0
+            freelist_count = session.execute(text("PRAGMA freelist_count")).scalar() or 0
+            journal_mode = session.execute(text("PRAGMA journal_mode")).scalar() or "unknown"
+            auto_vacuum_val = session.execute(text("PRAGMA auto_vacuum")).scalar() or 0
+            _av = {0: "None", 1: "Full", 2: "Incremental"}
+            fragmentation_pct = round(freelist_count / page_count * 100, 2) if page_count else 0.0
+
+            health["total_size_bytes"] = page_size * page_count
+            health["extra"] = {
+                "page_size": page_size,
+                "page_count": page_count,
+                "freelist_count": freelist_count,
+                "journal_mode": journal_mode,
+                "auto_vacuum": _av.get(auto_vacuum_val, str(auto_vacuum_val)),
+                "fragmentation_pct": fragmentation_pct,
+            }
+
+        elif db_type in ("MYSQL", "MARIADB"):
+            size = session.execute(
+                text(
+                    "SELECT COALESCE(SUM(data_length + index_length), 0)"
+                    " FROM information_schema.tables WHERE table_schema = DATABASE()"
+                )
+            ).scalar() or 0
+            version = session.execute(text("SELECT VERSION()")).scalar() or "unknown"
+            health["total_size_bytes"] = int(size)
+            health["extra"] = {"version": version}
+
+        elif db_type in ("POSTGRES", "POSTGRESQL"):
+            size = session.execute(
+                text("SELECT pg_database_size(current_database())")
+            ).scalar() or 0
+            version = session.execute(text("SELECT version()")).scalar() or "unknown"
+            health["total_size_bytes"] = int(size)
+            health["extra"] = {"version": " ".join(version.split()[:2])}
+
+        return {"status": "success", "health": health}, 200
+
+    except Exception:
+        logger.exception("Error getting DB health")
+        return {"status": "error", "message": "Error interno del servidor"}, 500
+
+    finally:
+        if session:
+            session.close()
+
+
+def run_integrity_check():
+    """Run a quick integrity check. Uses PRAGMA quick_check for SQLite."""
+    session = None
+    try:
+        session = get_session()
+        db_type = Config.DATABASE_TYPE
+
+        errors = []
+
+        if db_type == "SQLITE":
+            rows = session.execute(text("PRAGMA quick_check")).fetchall()
+            errors = [r[0] for r in rows if r[0] != "ok"]
+
+        elif db_type in ("MYSQL", "MARIADB"):
+            tables = session.execute(
+                text(
+                    "SELECT table_name FROM information_schema.tables"
+                    " WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'"
+                )
+            ).fetchall()
+            for (t,) in tables:
+                rows = session.execute(
+                    text(f"CHECK TABLE `{t}` FAST QUICK")
+                ).fetchall()
+                for row in rows:
+                    if row[3] not in ("OK", "note"):
+                        errors.append(f"{t}: {row[3]}")
+
+        else:
+            session.execute(text("SELECT 1"))
+
+        return {
+            "status": "success",
+            "integrity": {
+                "ok": not errors,
+                "errors": errors[:10],
+                "error_count": len(errors),
+            },
+        }, 200
+
+    except Exception:
+        logger.exception("Error running integrity check")
+        return {"status": "error", "message": "Error al ejecutar la verificación"}, 500
+
+    finally:
+        if session:
+            session.close()