ソースを参照

fix: enhance error handling with logging in various services and configurations

Manuel 8 ヶ月 前
親
コミット
eb928d66e1

+ 1 - 1
config.py

@@ -106,7 +106,7 @@ class Config:
 
     # Flask settings
     DEBUG = safe_get_env("FLASK_DEBUG", False, var_type=bool)
-    LISTEN_HOST = safe_get_env("LISTEN_HOST") or safe_get_env("FLASK_HOST") or "0.0.0.0"
+    LISTEN_HOST = safe_get_env("LISTEN_HOST") or safe_get_env("FLASK_HOST") or "0.0.0.0"  # nosec B104
     LISTEN_PORT = safe_get_env(
         "LISTEN_PORT", safe_get_env("FLASK_PORT", 5000, var_type=int), var_type=int
     )

+ 2 - 2
parsers/log.py

@@ -111,8 +111,8 @@ def parse_log_line(line):
             or "error:invalid-request" in line_lower
         ):
             return None
-    except Exception:
-        pass
+    except Exception as e:
+        logger.debug("Unexpected error pre-filtering log line: %s", e)
 
     if LOG_FORMAT == "DEFAULT":
         return parse_log_line_default(line)

+ 13 - 7
services/notifications/notifications.py

@@ -1,6 +1,7 @@
 import hashlib
 import os
-import subprocess
+import shutil
+import subprocess  # nosec B404
 import threading
 from contextlib import contextmanager
 from datetime import datetime, timedelta
@@ -477,17 +478,22 @@ def has_remote_commits_with_messages(
             env["http_proxy"] = http_proxy
             env["https_proxy"] = http_proxy
 
-        subprocess.run(
-            ["git", "fetch"],
+        git_bin = shutil.which("git")
+        if git_bin is None:
+            logger.warning("'git' executable not found in PATH")
+            return False, []
+
+        subprocess.run(  # nosec B603
+            [git_bin, "fetch"],
             cwd=repo_path,
             check=True,
             stdout=subprocess.DEVNULL,
             stderr=subprocess.DEVNULL,
             env=env,
         )
-        result = subprocess.run(
+        result = subprocess.run(  # nosec B603
             [
-                "git",
+                git_bin,
                 "rev-list",
                 "--left-right",
                 "--count",
@@ -503,8 +509,8 @@ def has_remote_commits_with_messages(
         remote_ahead = int(ahead_behind[0])
 
         if remote_ahead > 0:
-            log_result = subprocess.run(
-                ["git", "log", f"{branch}..origin/{branch}", "--pretty=format:%s"],
+            log_result = subprocess.run(  # nosec B603
+                [git_bin, "log", f"{branch}..origin/{branch}", "--pretty=format:%s"],
                 cwd=repo_path,
                 capture_output=True,
                 text=True,

+ 2 - 2
services/notifications/telegram_integration.py

@@ -43,8 +43,8 @@ def run_async(coro):
                 task.cancel()
             # Run loop until all tasks are cancelled
             loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
-        except Exception:
-            pass
+        except Exception as e:
+            logger.debug("Error while cancelling pending async tasks: %s", e)
         finally:
             loop.close()
 

+ 4 - 4
services/notifications/telegram_service.py

@@ -197,8 +197,8 @@ class TelegramService:
                 if self._client:
                     try:
                         await self._client.disconnect()
-                    except Exception:
-                        pass
+                    except Exception as e:
+                        logger.debug("Error disconnecting previous Telegram client: %s", e)
 
                 self._client = TelegramClient(
                     self.session_name, self.api_id, self.api_hash, proxy=self.proxy
@@ -432,8 +432,8 @@ class TelegramService:
                 # Try to disconnect gracefully
                 if self._event_loop and self._event_loop.is_running():
                     asyncio.create_task(self.disconnect())
-            except Exception:
-                pass
+            except Exception as e:
+                logger.debug("Error scheduling disconnect in __del__: %s", e)
 
 
 # Singleton instance

+ 4 - 4
services/quota/quota_scheduler.py

@@ -281,13 +281,13 @@ def register_quota_scheduler_tasks(scheduler):
             logger.error(f"Error en check_quota_users: {e}")
             try:
                 session.rollback()
-            except Exception:
-                pass
+            except Exception as e:
+                logger.warning("Error rolling back session after quota check failure: %s", e)
         finally:
             try:
                 session.close()
-            except Exception:
-                pass
+            except Exception as e:
+                logger.warning("Error closing session after quota check: %s", e)
 
     @scheduler.task(
         "interval",

+ 18 - 13
services/quota/quota_service.py

@@ -1,6 +1,7 @@
 import os
 import re
-import subprocess
+import shutil
+import subprocess  # nosec B404
 
 from loguru import logger
 
@@ -23,23 +24,28 @@ def _ensure_blocked_file(blocked_path: str):
             "No se pudo crear/ajustar permisos locales de %s: %s", blocked_path, e
         )
 
+    docker_bin = shutil.which("docker")
+    if docker_bin is None:
+        logger.debug("Docker no disponible, omitiendo creación en contenedor")
+        return
+
     try:
-        subprocess.run(
-            ["docker", "exec", "squid_proxy", "test", "-f", blocked_path],
+        subprocess.run(  # nosec B603
+            [docker_bin, "exec", "squid_proxy", "test", "-f", blocked_path],
             check=True,
             capture_output=True,
             timeout=10,
         )
     except subprocess.CalledProcessError:
         try:
-            subprocess.run(
-                ["docker", "exec", "squid_proxy", "touch", blocked_path],
+            subprocess.run(  # nosec B603
+                [docker_bin, "exec", "squid_proxy", "touch", blocked_path],
                 check=True,
                 capture_output=True,
                 timeout=10,
             )
-            subprocess.run(
-                ["docker", "exec", "squid_proxy", "chmod", "640", blocked_path],
+            subprocess.run(  # nosec B603
+                [docker_bin, "exec", "squid_proxy", "chmod", "640", blocked_path],
                 check=True,
                 capture_output=True,
                 timeout=10,
@@ -49,23 +55,22 @@ def _ensure_blocked_file(blocked_path: str):
             logger.warning(
                 "No se pudo crear %s en contenedor Docker: %s", blocked_path, e
             )
-    except FileNotFoundError:
-        logger.debug("Docker no disponible, omitiendo creación en contenedor")
     except Exception as e:
         logger.debug("Error verificando archivo en contenedor: %s", e)
 
 
 def _sync_blocked_file_to_docker(blocked_path: str):
     """Copia el archivo de bloqueados al contenedor Docker si está disponible."""
+    docker_bin = shutil.which("docker")
+    if docker_bin is None:
+        return
     try:
-        subprocess.run(
-            ["docker", "cp", blocked_path, f"squid_proxy:{blocked_path}"],
+        subprocess.run(  # nosec B603
+            [docker_bin, "cp", blocked_path, f"squid_proxy:{blocked_path}"],
             check=True,
             capture_output=True,
             timeout=10,
         )
-    except FileNotFoundError:
-        pass
     except Exception as e:
         logger.debug("No se pudo sincronizar %s a Docker: %s", blocked_path, e)
 

+ 2 - 2
services/squid/squid_config_splitter.py

@@ -1,7 +1,7 @@
 import os
 import re
 import shutil
-import subprocess
+import subprocess  # nosec B404
 from dataclasses import dataclass
 from datetime import datetime
 
@@ -372,7 +372,7 @@ class SquidConfigSplitter:
         def _run_command(cmd: list[str]) -> dict:
             """Run a validation command and return a result dict."""
             try:
-                result = subprocess.run(
+                result = subprocess.run(  # nosec B603
                     cmd,
                     capture_output=True,
                     text=True,

+ 30 - 25
services/system/system_info.py

@@ -1,8 +1,9 @@
 import os
 import platform
 import re
+import shutil
 import socket
-import subprocess
+import subprocess  # nosec B404
 import time
 
 import psutil
@@ -201,10 +202,12 @@ def get_timezone():
         tz_path = os.path.realpath("/etc/localtime")
         if "zoneinfo" in tz_path:
             return tz_path.split("zoneinfo/")[-1]
-        result = subprocess.run(["timedatectl"], stdout=subprocess.PIPE, text=True)
-        match = re.search(r"Time zone: (\S+)\s+(\S+/\S+)", result.stdout)
-        if match:
-            return f"{match.group(1)} {match.group(2)}"
+        timedatectl_bin = shutil.which("timedatectl")
+        if timedatectl_bin:
+            result = subprocess.run([timedatectl_bin], stdout=subprocess.PIPE, text=True)  # nosec B603
+            match = re.search(r"Time zone: (\S+)\s+(\S+/\S+)", result.stdout)
+            if match:
+                return f"{match.group(1)} {match.group(2)}"
         return "Unknown"
     except Exception:
         logger.exception("Error getting timezone")
@@ -224,30 +227,32 @@ def get_system_type():
                         ):
                             value = value[1:-1]
                         return value
-        except Exception:
-            pass
+        except Exception as e:
+            logger.debug("Error reading /etc/os-release: %s", e)
 
     # Check for macOS
-    try:
-        result = subprocess.run(
-            ["sw_vers", "-productName"], capture_output=True, text=True, timeout=5
-        )
-        if result.returncode == 0:
-            name = result.stdout.strip()
-            result = subprocess.run(
-                ["sw_vers", "-productVersion"],
-                capture_output=True,
-                text=True,
-                timeout=5,
+    sw_vers_bin = shutil.which("sw_vers")
+    if sw_vers_bin is not None:
+        try:
+            result = subprocess.run(  # nosec B603 B607
+                [sw_vers_bin, "-productName"], capture_output=True, text=True, timeout=5
             )
-            version = result.stdout.strip()
-            return f"{name} {version}"
-    except Exception:
-        pass
+            if result.returncode == 0:
+                name = result.stdout.strip()
+                result = subprocess.run(  # nosec B603 B607
+                    [sw_vers_bin, "-productVersion"],
+                    capture_output=True,
+                    text=True,
+                    timeout=5,
+                )
+                version = result.stdout.strip()
+                return f"{name} {version}"
+        except Exception as e:
+            logger.debug("Error calling sw_vers: %s", e)
 
     # Check for Windows
     try:
-        result = subprocess.run(
+        result = subprocess.run(  # nosec B602 B607
             'systeminfo | findstr /B /C:"OS Name" /B /C:"OS Version"',
             shell=True,
             capture_output=True,
@@ -267,7 +272,7 @@ def get_system_type():
                 return f"{os_name} {os_version}"
             elif os_name:
                 return os_name
-    except Exception:
-        pass
+    except Exception as e:
+        logger.debug("Error calling systeminfo: %s", e)
 
     return "Unknown"

+ 39 - 27
services/system/system_service.py

@@ -1,12 +1,21 @@
-import subprocess
+import shutil
+import subprocess  # nosec B404
 
 from loguru import logger
 
 
+def _get_bin(name: str) -> str | None:
+    """Return the absolute path of *name* in PATH, or None if not found."""
+    return shutil.which(name)
+
+
 def _docker_reconfigure() -> tuple[bool, str]:
+    docker_bin = _get_bin("docker")
+    if docker_bin is None:
+        return False, "Docker no encontrado"
     try:
-        subprocess.run(
-            ["docker", "exec", "squid_proxy", "squid", "-k", "reconfigure"],
+        subprocess.run(  # nosec B603
+            [docker_bin, "exec", "squid_proxy", "squid", "-k", "reconfigure"],
             check=True,
             capture_output=True,
             text=True,
@@ -28,9 +37,12 @@ def _docker_reconfigure() -> tuple[bool, str]:
 
 
 def _local_reconfigure() -> tuple[bool, str]:
+    squid_bin = _get_bin("squid")
+    if squid_bin is None:
+        return False, "Squid no encontrado"
     try:
-        subprocess.run(
-            ["squid", "-k", "reconfigure"],
+        subprocess.run(  # nosec B603
+            [squid_bin, "-k", "reconfigure"],
             check=True,
             capture_output=True,
             text=True,
@@ -51,17 +63,17 @@ def _local_reconfigure() -> tuple[bool, str]:
 
 
 def restart_squid() -> tuple[bool, str, str]:
-    try:
-        subprocess.run(["systemctl", "restart", "squid"], check=True)
-        return True, "Squid restarted successfully", None
-    except subprocess.CalledProcessError as e:
-        logger.warning(
-            "systemctl restart squid falló con estado %s: %s", e.returncode, e
-        )
-    except FileNotFoundError as e:
-        logger.warning("systemctl no encontrado: %s", e)
-    except Exception as e:
-        logger.warning("Error systemctl restart squid: %s", e)
+    systemctl_bin = _get_bin("systemctl")
+    if systemctl_bin:
+        try:
+            subprocess.run([systemctl_bin, "restart", "squid"], check=True)  # nosec B603
+            return True, "Squid restarted successfully", None
+        except subprocess.CalledProcessError as e:
+            logger.warning(
+                "systemctl restart squid falló con estado %s: %s", e.returncode, e
+            )
+        except Exception as e:
+            logger.warning("Error systemctl restart squid: %s", e)
 
     # Fallback docker si existe, y luego local
     success, msg = _docker_reconfigure()
@@ -76,17 +88,17 @@ def restart_squid() -> tuple[bool, str, str]:
 
 
 def reload_squid() -> tuple[bool, str, str]:
-    try:
-        subprocess.run(["systemctl", "reload", "squid"], check=True)
-        return True, "Configuration reloaded successfully", None
-    except subprocess.CalledProcessError as e:
-        logger.warning(
-            "systemctl reload squid falló con estado %s: %s", e.returncode, e
-        )
-    except FileNotFoundError as e:
-        logger.warning("systemctl no encontrado: %s", e)
-    except Exception as e:
-        logger.warning("Error systemctl reload squid: %s", e)
+    systemctl_bin = _get_bin("systemctl")
+    if systemctl_bin:
+        try:
+            subprocess.run([systemctl_bin, "reload", "squid"], check=True)  # nosec B603
+            return True, "Configuration reloaded successfully", None
+        except subprocess.CalledProcessError as e:
+            logger.warning(
+                "systemctl reload squid falló con estado %s: %s", e.returncode, e
+            )
+        except Exception as e:
+            logger.warning("Error systemctl reload squid: %s", e)
 
     # Fallback docker si existe, y luego local
     success, msg = _docker_reconfigure()

+ 2 - 2
utils/admin.py

@@ -896,8 +896,8 @@ class SquidConfigManager:
                             f"Modular config unchanged, skipping write: {filename}"
                         )
                         return True
-                except Exception:
-                    pass  # If we can't read, proceed with write
+                except Exception as e:
+                    logger.debug("Could not read existing config for comparison, proceeding with write: %s", e)
 
                 # Create single backup before overwriting
                 backup_path = f"{filepath}.bak"