Sfoglia il codice sorgente

feat: enhance quota management and backup handling in admin routes

Manuel 8 mesi fa
parent
commit
5feea745bc
2 ha cambiato i file con 70 aggiunte e 24 eliminazioni
  1. 19 10
      routes/admin/quota.py
  2. 51 14
      utils/admin.py

+ 19 - 10
routes/admin/quota.py

@@ -1,6 +1,7 @@
 """Admin quota management routes."""
 
 import os
+import re
 from datetime import datetime, timezone
 
 from flask import render_template, request
@@ -25,13 +26,10 @@ def is_quota_enabled() -> bool:
 
 def set_quota_enabled(enabled: bool) -> None:
     """Persist the quota enabled flag using a file marker."""
-    block_file = os.path.join(os.getcwd(), "blockUsersQuota")
     try:
         if enabled:
             if os.path.exists(QUOTA_DISABLED_FLAG):
                 os.remove(QUOTA_DISABLED_FLAG)
-            if os.path.exists(block_file):
-                os.remove(block_file)
         else:
             with open(QUOTA_DISABLED_FLAG, "w", encoding="utf-8") as f:
                 f.write("disabled\n")
@@ -124,20 +122,31 @@ def register_routes(bp):
             )
 
             blocked_users = []
-            block_file = os.path.join(os.getcwd(), "blockUsersQuota")
+            block_file = "/etc/squid/usuarios_bloqueados.txt"
             if os.path.exists(block_file):
                 with open(block_file, encoding="utf-8") as f:
                     for line in f:
                         raw = line.strip()
                         if not raw:
                             continue
-                        parts = [p.strip() for p in raw.split(" - ")]
-                        if len(parts) >= 2:
-                            username = parts[1]
-                            detail = " - ".join(parts[2:]) if len(parts) > 2 else ""
+                        # Format 1: acl usuarios_bloqueados src <IP>
+                        m = re.match(
+                            r"^acl\s+usuarios_bloqueados\s+src\s+(\S+)", raw
+                        )
+                        if m:
+                            username = m.group(1)
+                            detail = "Bloqueado por IP (src)"
                         else:
-                            username = raw
-                            detail = ""
+                            # Format 2: plain username or "detail - username"
+                            parts = [p.strip() for p in raw.split(" - ")]
+                            if len(parts) >= 2:
+                                username = parts[1]
+                                detail = (
+                                    " - ".join(parts[2:]) if len(parts) > 2 else ""
+                                )
+                            else:
+                                username = raw
+                                detail = ""
                         blocked_users.append(
                             {"username": username, "detail": detail, "raw": raw}
                         )

+ 51 - 14
utils/admin.py

@@ -118,6 +118,27 @@ class SquidConfigManager:
             self.is_valid = True
             logger.info("SquidConfigManager initialized successfully")
 
+    def _cleanup_modular_backups(self, filepath: str, suffix: str = ".bak"):
+        """Remove old backups for a modular config file, keeping only the newest one."""
+        base = os.path.basename(filepath)
+        directory = os.path.dirname(filepath)
+        prefix = base + suffix
+        try:
+            backups = sorted(
+                f
+                for f in os.listdir(directory)
+                if f.startswith(prefix) and f != base
+            )
+            # Remove all but the last (newest) backup
+            for old in backups[:-1]:
+                try:
+                    os.remove(os.path.join(directory, old))
+                    logger.debug(f"Removed old backup: {old}")
+                except Exception as e:
+                    logger.warning(f"Could not remove old backup {old}: {e}")
+        except Exception as e:
+            logger.warning(f"Error cleaning up backups for {base}: {e}")
+
     def load_config(self):
         if not self.is_valid:
             logger.error("Cannot load configuration: invalid environment")
@@ -151,6 +172,11 @@ class SquidConfigManager:
             return False
 
         try:
+            # Skip write if content hasn't changed
+            if self.config_content == content:
+                logger.debug("Main config unchanged, skipping write")
+                return True
+
             backup_created = self.create_backup()
             if not backup_created:
                 logger.warning("Could not create backup, but continuing with save...")
@@ -862,16 +888,24 @@ class SquidConfigManager:
             return False
 
         try:
-            # Backup creation disabled by user request
-            # if os.path.exists(filepath):
-            #     backup_path = (
-            #         f"{filepath}.bak{datetime.now().strftime('%Y%m%d_%H%M%S')}"
-            #     )
-            #     try:
-            #         shutil.copy2(filepath, backup_path)
-            #         logger.info(f"Backup created: {backup_path}")
-            #     except Exception as e:
-            #         logger.warning(f"Could not create backup: {e}")
+            # Skip write if content hasn't changed
+            if os.path.exists(filepath):
+                try:
+                    with open(filepath, encoding="utf-8") as f:
+                        existing = f.read()
+                    if existing == content:
+                        logger.debug(f"Modular config unchanged, skipping write: {filename}")
+                        return True
+                except Exception:
+                    pass  # If we can't read, proceed with write
+
+                # Create single backup before overwriting
+                backup_path = f"{filepath}.bak"
+                try:
+                    shutil.copy2(filepath, backup_path)
+                    logger.debug(f"Backup created: {backup_path}")
+                except Exception as e:
+                    logger.warning(f"Could not create backup for {filename}: {e}")
 
             with open(filepath, "w", encoding="utf-8") as f:
                 f.write(content)
@@ -900,10 +934,13 @@ class SquidConfigManager:
             return False
 
         try:
-            # Create backup before deleting
-            backup_path = (
-                f"{filepath}.deleted{datetime.now().strftime('%Y%m%d_%H%M%S')}"
-            )
+            # Keep a single .deleted backup, removing any previous one
+            backup_path = f"{filepath}.deleted"
+            if os.path.exists(backup_path):
+                try:
+                    os.remove(backup_path)
+                except Exception as e:
+                    logger.warning(f"Could not remove previous deleted backup: {e}")
             try:
                 shutil.move(filepath, backup_path)
                 logger.info(f"File moved to: {backup_path}")