Procházet zdrojové kódy

feat: add BackupConfig model and integrate database backup configuration management

Manuel před 8 měsíci
rodič
revize
47d5112bcf

+ 2 - 0
database/models/__init__.py

@@ -1,5 +1,6 @@
 from .models import (
 from .models import (
     AdminUser,
     AdminUser,
+    BackupConfig,
     DailyBase,
     DailyBase,
     DeniedLog,
     DeniedLog,
     Log,
     Log,
@@ -22,6 +23,7 @@ __all__ = [
     "SystemMetrics",
     "SystemMetrics",
     "Notification",
     "Notification",
     "AdminUser",
     "AdminUser",
+    "BackupConfig",
     "QuotaUser",
     "QuotaUser",
     "QuotaGroup",
     "QuotaGroup",
     "QuotaRule",
     "QuotaRule",

+ 12 - 0
database/models/models.py

@@ -160,6 +160,18 @@ class QuotaEvent(Base):
     created_at = Column(DateTime, default=datetime.now, nullable=False)
     created_at = Column(DateTime, default=datetime.now, nullable=False)
 
 
 
 
+class BackupConfig(Base):
+    __tablename__ = "backup_config"
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    db_type = Column(String(50), nullable=False, default="sqlite")
+    frequency = Column(String(50), nullable=False, default="daily_weekly")
+    backup_dir = Column(String(512), nullable=False, default="/opt/SquidStats/backups")
+    enabled = Column(Integer, nullable=False, default=0)
+    created_at = Column(DateTime, default=datetime.now, nullable=False)
+    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
+
+
 def create_dynamic_models(engine, user_table_name: str, log_table_name: str):
 def create_dynamic_models(engine, user_table_name: str, log_table_name: str):
     """Factory to create dynamic user/log models bound to a fresh declarative base.
     """Factory to create dynamic user/log models bound to a fresh declarative base.
 
 

+ 84 - 46
services/database/backup_service.py

@@ -9,9 +9,7 @@ Planned (not yet implemented):
   - PostgreSQL
   - PostgreSQL
 """
 """
 
 
-import json
 import os
 import os
-import shutil
 import sqlite3
 import sqlite3
 from datetime import datetime
 from datetime import datetime
 from pathlib import Path
 from pathlib import Path
@@ -20,11 +18,13 @@ from urllib.parse import urlparse
 from loguru import logger
 from loguru import logger
 
 
 from config import Config
 from config import Config
+from database.database import get_session
+from database.models.models import BackupConfig
 
 
-# ─── Constants ────────────────────────────────────────────────────────────────
+# Constants
 
 
-_CONFIG_FILE = Path(os.path.dirname(os.path.abspath(__file__))) / "backup_config.json"
 _MAX_RETENTION = 3
 _MAX_RETENTION = 3
+_DEFAULT_BACKUP_DIR = "/opt/SquidStats/backups"
 
 
 FREQUENCY_CHOICES = {
 FREQUENCY_CHOICES = {
     "daily_weekly": "Diaria — máx. 3 por semana",
     "daily_weekly": "Diaria — máx. 3 por semana",
@@ -32,56 +32,90 @@ FREQUENCY_CHOICES = {
 }
 }
 
 
 
 
-# ─── Config helpers ───────────────────────────────────────────────────────────
+# Config helpers
 
 
 
 
 def _default_config() -> dict:
 def _default_config() -> dict:
     return {
     return {
         "db_type": "sqlite",
         "db_type": "sqlite",
         "frequency": "daily_weekly",
         "frequency": "daily_weekly",
-        "backup_dir": "/opt/SquidStats/backups",
+        "backup_dir": _DEFAULT_BACKUP_DIR,
         "enabled": False,
         "enabled": False,
     }
     }
 
 
 
 
 def load_config() -> dict:
 def load_config() -> dict:
-    if _CONFIG_FILE.exists():
-        try:
-            with open(_CONFIG_FILE) as f:
-                data = json.load(f)
-            cfg = _default_config()
-            cfg.update(data)
-            return cfg
-        except Exception as e:
-            logger.warning(f"Could not read backup config, using defaults: {e}")
-    return _default_config()
+    """Read backup configuration from the database. Returns defaults if no row exists."""
+    session = get_session()
+    try:
+        row = session.query(BackupConfig).first()
+        if row is None:
+            return _default_config()
+        return {
+            "db_type": row.db_type,
+            "frequency": row.frequency,
+            "backup_dir": row.backup_dir,
+            "enabled": bool(row.enabled),
+        }
+    except Exception as e:
+        logger.warning(f"Could not read backup config from DB, using defaults: {e}")
+        return _default_config()
+    finally:
+        session.close()
 
 
 
 
 def save_config(cfg: dict) -> None:
 def save_config(cfg: dict) -> None:
+    """Upsert backup configuration into the database (single-row table)."""
     allowed_keys = {"db_type", "frequency", "backup_dir", "enabled"}
     allowed_keys = {"db_type", "frequency", "backup_dir", "enabled"}
     safe = {k: v for k, v in cfg.items() if k in allowed_keys}
     safe = {k: v for k, v in cfg.items() if k in allowed_keys}
-    _CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
-    with open(_CONFIG_FILE, "w") as f:
-        json.dump(safe, f, indent=2)
+
+    session = get_session()
+    try:
+        row = session.query(BackupConfig).first()
+        if row is None:
+            row = BackupConfig(
+                db_type=safe.get("db_type", "sqlite"),
+                frequency=safe.get("frequency", "daily_weekly"),
+                backup_dir=safe.get("backup_dir", _DEFAULT_BACKUP_DIR),
+                enabled=int(bool(safe.get("enabled", False))),
+                created_at=datetime.now(),
+            )
+            session.add(row)
+        else:
+            if "db_type" in safe:
+                row.db_type = safe["db_type"]
+            if "frequency" in safe:
+                row.frequency = safe["frequency"]
+            if "backup_dir" in safe:
+                row.backup_dir = safe["backup_dir"]
+            if "enabled" in safe:
+                row.enabled = int(bool(safe["enabled"]))
+            row.updated_at = datetime.now()
+        session.commit()
+    except Exception as e:
+        session.rollback()
+        logger.exception(f"Error saving backup config: {e}")
+        raise
+    finally:
+        session.close()
 
 
 
 
-# ─── Backup directory helpers ─────────────────────────────────────────────────
+# Backup directory helpers
 
 
 
 
 def _backup_dir(cfg: dict) -> Path:
 def _backup_dir(cfg: dict) -> Path:
-    p = Path(cfg.get("backup_dir", "/opt/SquidStats/backups"))
+    p = Path(cfg.get("backup_dir", _DEFAULT_BACKUP_DIR))
     p.mkdir(parents=True, exist_ok=True)
     p.mkdir(parents=True, exist_ok=True)
     return p
     return p
 
 
 
 
 def _list_backup_files(backup_dir: Path) -> list[Path]:
 def _list_backup_files(backup_dir: Path) -> list[Path]:
     """Return backup files sorted newest-first."""
     """Return backup files sorted newest-first."""
-    files = sorted(
+    return sorted(
         backup_dir.glob("squidstats_backup_*.sqlite3"),
         backup_dir.glob("squidstats_backup_*.sqlite3"),
         key=lambda f: f.stat().st_mtime,
         key=lambda f: f.stat().st_mtime,
         reverse=True,
         reverse=True,
     )
     )
-    return files
 
 
 
 
 def _human_size(size_bytes: int) -> str:
 def _human_size(size_bytes: int) -> str:
@@ -101,7 +135,6 @@ def list_backups(cfg: dict | None = None) -> list[dict]:
     for f in _list_backup_files(bdir):
     for f in _list_backup_files(bdir):
         stat = f.stat()
         stat = f.stat()
         created = datetime.fromtimestamp(stat.st_mtime)
         created = datetime.fromtimestamp(stat.st_mtime)
-        # Detect type from filename suffix
         btype = "auto" if "_auto_" in f.name else "manual"
         btype = "auto" if "_auto_" in f.name else "manual"
         result.append(
         result.append(
             {
             {
@@ -115,14 +148,13 @@ def list_backups(cfg: dict | None = None) -> list[dict]:
     return result
     return result
 
 
 
 
-# ─── Retention enforcement ────────────────────────────────────────────────────
+# Retention enforcement
 
 
 
 
 def _enforce_retention(backup_dir: Path) -> None:
 def _enforce_retention(backup_dir: Path) -> None:
     """Delete oldest backups beyond _MAX_RETENTION."""
     """Delete oldest backups beyond _MAX_RETENTION."""
     files = _list_backup_files(backup_dir)
     files = _list_backup_files(backup_dir)
-    excess = files[_MAX_RETENTION:]
-    for f in excess:
+    for f in files[_MAX_RETENTION:]:
         try:
         try:
             f.unlink()
             f.unlink()
             logger.info(f"Backup retention: removed old backup {f.name}")
             logger.info(f"Backup retention: removed old backup {f.name}")
@@ -130,20 +162,18 @@ def _enforce_retention(backup_dir: Path) -> None:
             logger.warning(f"Could not remove old backup {f.name}: {e}")
             logger.warning(f"Could not remove old backup {f.name}: {e}")
 
 
 
 
-# ─── Period quota check ───────────────────────────────────────────────────────
+# Period quota check
 
 
 
 
 def _count_backups_in_period(backup_dir: Path, frequency: str) -> int:
 def _count_backups_in_period(backup_dir: Path, frequency: str) -> int:
     """Count how many auto-backups exist within the current period window."""
     """Count how many auto-backups exist within the current period window."""
-    files = _list_backup_files(backup_dir)
     now = datetime.now()
     now = datetime.now()
     count = 0
     count = 0
-    for f in files:
+    for f in _list_backup_files(backup_dir):
         if "_auto_" not in f.name:
         if "_auto_" not in f.name:
             continue
             continue
         mtime = datetime.fromtimestamp(f.stat().st_mtime)
         mtime = datetime.fromtimestamp(f.stat().st_mtime)
         if frequency == "daily_weekly":
         if frequency == "daily_weekly":
-            # Same ISO week
             if mtime.isocalendar()[1] == now.isocalendar()[1] and mtime.year == now.year:
             if mtime.isocalendar()[1] == now.isocalendar()[1] and mtime.year == now.year:
                 count += 1
                 count += 1
         else:  # daily_monthly
         else:  # daily_monthly
@@ -152,7 +182,7 @@ def _count_backups_in_period(backup_dir: Path, frequency: str) -> int:
     return count
     return count
 
 
 
 
-# ─── SQLite backup ────────────────────────────────────────────────────────────
+# SQLite backup
 
 
 
 
 def _sqlite_backup(backup_dir: Path, tag: str) -> Path:
 def _sqlite_backup(backup_dir: Path, tag: str) -> Path:
@@ -160,20 +190,31 @@ def _sqlite_backup(backup_dir: Path, tag: str) -> Path:
     db_url = Config.DATABASE_URL
     db_url = Config.DATABASE_URL
     parsed = urlparse(db_url)
     parsed = urlparse(db_url)
 
 
-    # urlparse: sqlite:///path  →  path='' netloc='', or path='/abs'
     db_path = parsed.path
     db_path = parsed.path
+
+    # sqlite:///relative/path.db -> path is '/relative/path.db' but it should be project-relative
+    if db_path.startswith("/") and not Path(db_path).exists():
+        project_root = Path(os.path.dirname(os.path.abspath(__file__))).parent.parent
+        rel_path = db_path.lstrip("/")
+        alt_path = project_root / rel_path
+        if alt_path.exists():
+            db_path = str(alt_path)
+
     if not db_path or db_path == "/":
     if not db_path or db_path == "/":
-        # Handle sqlite:///relative or sqlite:///opt/…
         db_path = db_url.replace("sqlite:///", "")
         db_path = db_url.replace("sqlite:///", "")
 
 
     db_path = Path(db_path)
     db_path = Path(db_path)
     if not db_path.is_absolute():
     if not db_path.is_absolute():
-        # Relative to the project root
         project_root = Path(os.path.dirname(os.path.abspath(__file__))).parent.parent
         project_root = Path(os.path.dirname(os.path.abspath(__file__))).parent.parent
         db_path = project_root / db_path
         db_path = project_root / db_path
 
 
     if not db_path.exists():
     if not db_path.exists():
-        raise FileNotFoundError(f"SQLite database not found: {db_path}")
+        # try fallback for sqlite:///filename.db
+        try_path = Path(os.path.dirname(os.path.abspath(__file__))).parent.parent / db_path.name
+        if try_path.exists():
+            db_path = try_path
+        else:
+            raise FileNotFoundError(f"SQLite database not found: {db_path}")
 
 
     timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
     timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
     dest = backup_dir / f"squidstats_backup_{tag}_{timestamp}.sqlite3"
     dest = backup_dir / f"squidstats_backup_{tag}_{timestamp}.sqlite3"
@@ -190,7 +231,7 @@ def _sqlite_backup(backup_dir: Path, tag: str) -> Path:
     return dest
     return dest
 
 
 
 
-# ─── MySQL / MariaDB backup (not yet implemented) ─────────────────────────────
+# MySQL / MariaDB backup (not yet implemented)
 
 
 
 
 def _mysql_backup(backup_dir: Path, tag: str) -> Path:
 def _mysql_backup(backup_dir: Path, tag: str) -> Path:
@@ -200,7 +241,7 @@ def _mysql_backup(backup_dir: Path, tag: str) -> Path:
     )
     )
 
 
 
 
-# ─── PostgreSQL backup (not yet implemented) ──────────────────────────────────
+# PostgreSQL backup (not yet implemented)
 
 
 
 
 def _postgresql_backup(backup_dir: Path, tag: str) -> Path:
 def _postgresql_backup(backup_dir: Path, tag: str) -> Path:
@@ -210,14 +251,14 @@ def _postgresql_backup(backup_dir: Path, tag: str) -> Path:
     )
     )
 
 
 
 
-# ─── Public API ───────────────────────────────────────────────────────────────
+# Public API
 
 
 
 
 def run_backup(is_auto: bool = False) -> dict:
 def run_backup(is_auto: bool = False) -> dict:
-    """
-    Execute a database backup according to the current configuration.
+    """Execute a database backup according to the current configuration.
 
 
-    Returns a dict with keys: status ('success'|'error'), message, filename (on success).
+    Returns a dict with keys: status ('success'|'error'|'skipped'), message,
+    and filename on success.
     """
     """
     cfg = load_config()
     cfg = load_config()
     db_type = cfg.get("db_type", "sqlite").lower()
     db_type = cfg.get("db_type", "sqlite").lower()
@@ -225,7 +266,6 @@ def run_backup(is_auto: bool = False) -> dict:
     bdir = _backup_dir(cfg)
     bdir = _backup_dir(cfg)
     tag = "auto" if is_auto else "manual"
     tag = "auto" if is_auto else "manual"
 
 
-    # For auto backups: respect the per-period quota before running
     if is_auto:
     if is_auto:
         current_in_period = _count_backups_in_period(bdir, frequency)
         current_in_period = _count_backups_in_period(bdir, frequency)
         if current_in_period >= _MAX_RETENTION:
         if current_in_period >= _MAX_RETENTION:
@@ -262,7 +302,6 @@ def run_backup(is_auto: bool = False) -> dict:
 
 
 def delete_backup(filename: str) -> dict:
 def delete_backup(filename: str) -> dict:
     """Delete a specific backup file by name."""
     """Delete a specific backup file by name."""
-    # Validate filename to prevent path traversal
     if not filename or "/" in filename or "\\" in filename or ".." in filename:
     if not filename or "/" in filename or "\\" in filename or ".." in filename:
         return {"status": "error", "message": "Nombre de archivo inválido"}
         return {"status": "error", "message": "Nombre de archivo inválido"}
 
 
@@ -273,7 +312,6 @@ def delete_backup(filename: str) -> dict:
     if not target.exists():
     if not target.exists():
         return {"status": "error", "message": "La salva no existe"}
         return {"status": "error", "message": "La salva no existe"}
 
 
-    # Ensure the target is strictly inside the backup directory
     try:
     try:
         target.resolve().relative_to(bdir.resolve())
         target.resolve().relative_to(bdir.resolve())
     except ValueError:
     except ValueError:
@@ -284,7 +322,7 @@ def delete_backup(filename: str) -> dict:
     return {"status": "success", "message": f"Salva eliminada: {filename}"}
     return {"status": "success", "message": f"Salva eliminada: {filename}"}
 
 
 
 
-def get_backup_file_path(filename: str):
+def get_backup_file_path(filename: str) -> Path | None:
     """Return the absolute Path for a backup file, or None if invalid/missing."""
     """Return the absolute Path for a backup file, or None if invalid/missing."""
     if not filename or "/" in filename or "\\" in filename or ".." in filename:
     if not filename or "/" in filename or "\\" in filename or ".." in filename:
         return None
         return None