Просмотр исходного кода

Merge pull request #90 from kaelthasmanu/squidConfDatabse

Squid conf databse
Manuel Gorrin 5 месяцев назад
Родитель
Сommit
c47d38b0a3

+ 93 - 0
alembic/versions/010_add_squid_config.py

@@ -0,0 +1,93 @@
+"""Add squid_config table
+
+Revision ID: 010_add_squid_config
+Revises: 009_add_telegram_config
+Create Date: 2026-06-18 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from sqlalchemy import inspect
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "010_add_squid_config"
+down_revision: str | None = "009_add_telegram_config"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+    """Create squid_config table."""
+    conn = op.get_bind()
+    inspector = inspect(conn)
+
+    if not inspector.has_table("squid_config"):
+        op.create_table(
+            "squid_config",
+            sa.Column("id", sa.Integer(), nullable=False),
+            sa.Column(
+                "squid_host",
+                sa.String(length=255),
+                nullable=False,
+                server_default="127.0.0.1",
+            ),
+            sa.Column(
+                "squid_port", sa.Integer(), nullable=False, server_default="3128"
+            ),
+            sa.Column(
+                "squid_hosts",
+                sa.String(length=512),
+                nullable=False,
+                server_default="",
+            ),
+            sa.Column(
+                "log_format",
+                sa.String(length=50),
+                nullable=False,
+                server_default="DEFAULT",
+            ),
+            sa.Column(
+                "squid_log",
+                sa.String(length=512),
+                nullable=False,
+                server_default="/var/log/squid/access.log",
+            ),
+            sa.Column(
+                "squid_cache_log",
+                sa.String(length=512),
+                nullable=False,
+                server_default="/var/log/squid/cache.log",
+            ),
+            sa.Column(
+                "squid_config_path",
+                sa.String(length=512),
+                nullable=False,
+                server_default="/etc/squid/squid.conf",
+            ),
+            sa.Column(
+                "acl_files_dir",
+                sa.String(length=512),
+                nullable=False,
+                server_default="",
+            ),
+            sa.Column("created_at", sa.DateTime(), nullable=False),
+            sa.Column("updated_at", sa.DateTime(), nullable=True),
+            sa.PrimaryKeyConstraint("id"),
+        )
+    else:
+        print("Skipping creation of 'squid_config' because it already exists")
+
+
+def downgrade() -> None:
+    """Drop squid_config table."""
+    conn = op.get_bind()
+    inspector = inspect(conn)
+
+    if inspector.has_table("squid_config"):
+        op.drop_table("squid_config")
+    else:
+        print("Skipping drop of 'squid_config' because it does not exist")

+ 5 - 3
app.py

@@ -78,14 +78,16 @@ def create_app():
         )
         # Continue anyway - the app might still work with existing schema
 
-    # Migrate legacy BLACKLIST_DOMAINS from .env into DB (non-interactive)
+    # Migrate legacy BLACKLIST_DOMAINS and Squid env vars from .env into DB (non-interactive)
     try:
-        from manage_db import migrate_env_blacklist
+        from manage_db import migrate_env_blacklist, migrate_env_squid_config
 
         logger.info("Checking for legacy BLACKLIST_DOMAINS to migrate into DB...")
         migrate_env_blacklist(auto_confirm=True)
+        logger.info("Checking for legacy Squid env vars to migrate into DB...")
+        migrate_env_squid_config(auto_confirm=True)
     except Exception as e:
-        logger.error(f"Error migrating BLACKLIST_DOMAINS into DB: {e}")
+        logger.error(f"Error migrating legacy environment configuration into DB: {e}")
 
     # Compile Babel translations from sources/ at startup
     try:

+ 4 - 0
config.py

@@ -142,6 +142,10 @@ class Config:
 
     # Squid configuration path
     SQUID_CONFIG_PATH = safe_get_env("SQUID_CONFIG_PATH", "/etc/squid/squid.conf")
+    ACL_FILES_DIR = safe_get_env(
+        "ACL_FILES_DIR",
+        os.path.join(os.path.dirname(SQUID_CONFIG_PATH), "squid.d"),
+    )
 
     # Internationalization (i18n)
     BABEL_DEFAULT_LOCALE = safe_get_env("BABEL_DEFAULT_LOCALE", "es")

+ 2 - 0
database/models/__init__.py

@@ -10,6 +10,7 @@ from .models import (
     QuotaGroup,
     QuotaRule,
     QuotaUser,
+    SquidConfig,
     SystemMetrics,
     User,
 )
@@ -24,6 +25,7 @@ __all__ = [
     "Notification",
     "AdminUser",
     "BackupConfig",
+    "SquidConfig",
     "QuotaUser",
     "QuotaGroup",
     "QuotaRule",

+ 22 - 0
database/models/models.py

@@ -232,6 +232,28 @@ class LdapConfig(Base):
     updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
 
 
+class SquidConfig(Base):
+    """Single-row table that stores Squid runtime configuration values."""
+
+    __tablename__ = "squid_config"
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    squid_host = Column(String(255), nullable=False, default="127.0.0.1")
+    squid_port = Column(Integer, nullable=False, default=3128)
+    squid_hosts = Column(String(512), nullable=False, default="")
+    log_format = Column(String(50), nullable=False, default="DEFAULT")
+    squid_log = Column(String(512), nullable=False, default="/var/log/squid/access.log")
+    squid_cache_log = Column(
+        String(512), nullable=False, default="/var/log/squid/cache.log"
+    )
+    squid_config_path = Column(
+        String(512), nullable=False, default="/etc/squid/squid.conf"
+    )
+    acl_files_dir = Column(String(512), nullable=False, default="")
+    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):
     """Factory to create dynamic user/log models bound to a fresh declarative base.
 

+ 94 - 1
manage_db.py

@@ -24,7 +24,7 @@ from sqlalchemy import inspect
 
 from alembic import command
 from database.database import get_engine
-from database.models.models import BlacklistDomain
+from database.models.models import BlacklistDomain, SquidConfig
 from services.security.blacklist_service import merge_and_save_blacklist
 
 # Delay import of project modules until runtime (project root added to sys.path above)
@@ -217,6 +217,97 @@ def migrate_env_blacklist(auto_confirm: bool = False):
         return
 
 
+def migrate_env_squid_config(auto_confirm: bool = False):
+    """Migrate Squid environment variables into the squid_config DB table."""
+
+    env_values = {}
+    raw_keys = {
+        "SQUID_HOST": "squid_host",
+        "SQUID_PORT": "squid_port",
+        "LOG_FORMAT": "log_format",
+        "SQUID_LOG": "squid_log",
+        "SQUID_CACHE_LOG": "squid_cache_log",
+        "SQUID_CONFIG_PATH": "squid_config_path",
+        "ACL_FILES_DIR": "acl_files_dir",
+    }
+
+    for env_key, field_name in raw_keys.items():
+        value = os.getenv(env_key)
+        if value is None:
+            continue
+        if (value.startswith('"') and value.endswith('"')) or (
+            value.startswith("'") and value.endswith("'")
+        ):
+            value = value[1:-1]
+        env_values[field_name] = value.strip()
+
+    if not env_values:
+        logger.info("No Squid environment variables found; nothing to migrate.")
+        return
+
+    engine = get_engine()
+    inspector = inspect(engine)
+    table_name = SquidConfig.__tablename__
+    if not inspector.has_table(table_name):
+        logger.error(
+            f"Table '{table_name}' does not exist in the database. Run migrations first."
+        )
+        return
+
+    if not auto_confirm:
+        logger.info(
+            "Squid config env values found. This will create a single row in squid_config."
+        )
+        ans = input("Proceed with migration? (yes/no): ").strip().lower()
+        if ans != "yes":
+            logger.info("Migration cancelled by user.")
+            return
+
+    from sqlalchemy.orm import sessionmaker
+
+    Session = sessionmaker(bind=engine)
+    session = Session()
+    try:
+        existing = session.query(SquidConfig).first()
+        if existing:
+            logger.info(
+                "squid_config already exists in the database; skipping migration."
+            )
+            return
+
+        squid_port = env_values.get("squid_port")
+        if squid_port is not None:
+            try:
+                env_values["squid_port"] = int(squid_port)
+            except ValueError:
+                logger.warning(
+                    f"Invalid SQUID_PORT value '{squid_port}'; using default 3128."
+                )
+                env_values["squid_port"] = 3128
+
+        row = SquidConfig(
+            squid_host=env_values.get("squid_host", "127.0.0.1"),
+            squid_port=env_values.get("squid_port", 3128),
+            log_format=env_values.get("log_format", "DEFAULT"),
+            squid_log=env_values.get("squid_log", "/var/log/squid/access.log"),
+            squid_cache_log=env_values.get(
+                "squid_cache_log", "/var/log/squid/cache.log"
+            ),
+            squid_config_path=env_values.get(
+                "squid_config_path", "/etc/squid/squid.conf"
+            ),
+            acl_files_dir=env_values.get("acl_files_dir", ""),
+        )
+        session.add(row)
+        session.commit()
+        logger.info("✓ SQUID environment config migrated into database successfully.")
+    except Exception:
+        session.rollback()
+        logger.exception("Failed migrating Squid config env values into DB")
+    finally:
+        session.close()
+
+
 def show_help():
     """Show help message."""
     help_text = """
@@ -238,6 +329,7 @@ Examples:
   python manage_db.py create "add user email field"  # Create new migration
 
   python manage_db.py migrate-env-blacklist   # Migrate BLACKLIST_DOMAINS from .env to DB
+  python manage_db.py migrate-env-squid-config   # Migrate Squid env vars from .env to DB
 
 For more information, see the Alembic documentation:
 https://alembic.sqlalchemy.org/
@@ -261,6 +353,7 @@ def main():
         "history": show_history,
         "create": lambda: create_migration(sys.argv[2] if len(sys.argv) > 2 else None),
         "migrate-env-blacklist": migrate_env_blacklist,
+        "migrate-env-squid-config": migrate_env_squid_config,
         "help": show_help,
     }
 

+ 39 - 2
routes/admin/squid_config.py

@@ -19,6 +19,11 @@ from services.squid.split_config_service import (
 from services.squid.split_config_service import (
     split_config as service_split_config,
 )
+from services.squid.squid_config_db_service import (
+    SQUID_ENV_KEYS,
+    load_squid_config_from_db,
+    save_squid_env_vars_to_db,
+)
 from services.squid.squid_config_splitter import SquidConfigSplitter
 
 from .helpers import (
@@ -39,6 +44,13 @@ def register_routes(bp):
     def view_config():
         cm = get_config_manager()
         env_vars = load_env_vars()
+
+        # Fill missing Squid env vars from DB when the key is absent or empty in .env
+        squid_db_values = load_squid_config_from_db()
+        for key in SQUID_ENV_KEYS:
+            if not env_vars.get(key):
+                env_vars[key] = squid_db_values.get(key, "")
+
         cfg = load_telegram_config()
         cfg["has_api_hash"] = bool(cfg.get("api_hash"))
         cfg["has_bot_token"] = bool(cfg.get("bot_token"))
@@ -79,15 +91,40 @@ def register_routes(bp):
         sensitive_vars = {"VERSION"}
 
         env_vars = {}
+        squid_env_vars = {}
         for key in request.form:
-            if key != "csrf_token" and key not in sensitive_vars:
-                env_vars[key] = request.form[key]
+            if key == "csrf_token" or key in sensitive_vars:
+                continue
+            value = request.form[key]
+            if key in SQUID_ENV_KEYS:
+                squid_env_vars[key] = value
+            else:
+                env_vars[key] = value
 
         existing_vars = load_env_vars()
+        # Preserve non-Squid vars normally, and update only existing Squid vars in .env
         for key, value in env_vars.items():
             existing_vars[key] = value
 
+        for key, value in squid_env_vars.items():
+            if key in existing_vars:
+                existing_vars[key] = value
+
         save_env_vars(existing_vars)
+
+        try:
+            save_squid_env_vars_to_db(squid_env_vars)
+        except Exception as e:
+            logger.exception("Error saving Squid env vars to DB")
+            flash(
+                _(
+                    "Las variables de Squid se guardaron en .env, pero no se pudieron guardar en la base de datos: %(error)s"
+                )
+                % {"error": str(e)},
+                "error",
+            )
+            return redirect(url_for("admin.view_config"))
+
         flash(_("Variables de entorno guardadas exitosamente"), "success")
         return redirect(url_for("admin.view_config"))
 

+ 3 - 3
routes/main_routes.py

@@ -82,9 +82,9 @@ def _get_dashboard_context() -> tuple[dict[str, Any] | None, tuple[Any, int] | N
             except Exception:
                 logger.exception(f"Error parsing connections from proxy {label}")
 
-        if not all_connections and all(not p["ok"] for p in proxy_results):
-            logger.error("All Squid proxies returned errors")
-            return None, _build_error_page("No data from any Squid proxy", 502)
+        # if not all_connections and all(not p["ok"] for p in proxy_results):
+        # logger.error("All Squid proxies returned errors")
+        # return None, _build_error_page("No data from any Squid proxy", 502)
 
         connections = all_connections
 

+ 96 - 0
services/squid/squid_config_db_service.py

@@ -0,0 +1,96 @@
+from database.database import get_session
+from database.models.models import SquidConfig
+
+SQUID_ENV_KEYS = {
+    "SQUID_HOST",
+    "SQUID_PORT",
+    "SQUID_HOSTS",
+    "LOG_FORMAT",
+    "SQUID_LOG",
+    "SQUID_CACHE_LOG",
+    "SQUID_CONFIG_PATH",
+    "ACL_FILES_DIR",
+}
+
+SQUID_ENV_TO_DB_FIELD = {
+    "SQUID_HOST": "squid_host",
+    "SQUID_PORT": "squid_port",
+    "SQUID_HOSTS": "squid_hosts",
+    "LOG_FORMAT": "log_format",
+    "SQUID_LOG": "squid_log",
+    "SQUID_CACHE_LOG": "squid_cache_log",
+    "SQUID_CONFIG_PATH": "squid_config_path",
+    "ACL_FILES_DIR": "acl_files_dir",
+}
+
+
+def save_squid_env_vars_to_db(env_vars: dict[str, str]) -> None:
+    """Save Squid-related environment variables into the squid_config DB row."""
+    if not env_vars:
+        return
+
+    session = get_session()
+    try:
+        row = session.query(SquidConfig).first()
+        if row is None:
+            row = SquidConfig()
+            session.add(row)
+
+        changed = False
+        for env_key, value in env_vars.items():
+            if env_key not in SQUID_ENV_KEYS:
+                continue
+
+            db_field = SQUID_ENV_TO_DB_FIELD.get(env_key)
+            if db_field is None:
+                continue
+
+            if env_key == "SQUID_PORT":
+                try:
+                    cast_value = int(value)
+                except (TypeError, ValueError):
+                    cast_value = 3128
+                if getattr(row, db_field) != cast_value:
+                    setattr(row, db_field, cast_value)
+                    changed = True
+            else:
+                if getattr(row, db_field) != value:
+                    setattr(row, db_field, value)
+                    changed = True
+
+        if changed:
+            session.commit()
+        else:
+            session.rollback()
+    except Exception:
+        session.rollback()
+        raise
+    finally:
+        session.close()
+
+
+def load_squid_config_from_db() -> dict[str, str]:
+    """Load Squid-related configuration values from the squid_config DB row."""
+    session = get_session()
+    try:
+        row = session.query(SquidConfig).first()
+        if not row:
+            return {}
+
+        return {
+            "SQUID_HOST": str(row.squid_host or ""),
+            "SQUID_PORT": str(row.squid_port or ""),
+            "SQUID_HOSTS": str(row.squid_hosts or ""),
+            "LOG_FORMAT": str(row.log_format or ""),
+            "SQUID_LOG": str(row.squid_log or ""),
+            "SQUID_CACHE_LOG": str(row.squid_cache_log or ""),
+            "SQUID_CONFIG_PATH": str(row.squid_config_path or ""),
+            "ACL_FILES_DIR": str(row.acl_files_dir or ""),
+        }
+    finally:
+        session.close()
+
+
+def filter_squid_env_keys(env_vars: dict[str, str]) -> dict[str, str]:
+    """Return only Squid-related env vars from the provided mapping."""
+    return {k: v for k, v in env_vars.items() if k in SQUID_ENV_KEYS}

+ 2 - 2
templates/admin/config.html

@@ -85,7 +85,7 @@
         <form method="POST" action="{{ url_for('admin.save_env') }}" x-show="editing" class="grid grid-cols-1 md:grid-cols-2 gap-6">
             <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
             {% set sensitive_vars = ['VERSION', 'JWT_SECRET_KEY', 'FIRST_PASSWORD', 'DATABASE_STRING_CONNECTION'] %}
-            {% for key in ['SQUID_HOST', 'SQUID_PORT', 'LOG_FORMAT', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}
+            {% for key in ['SQUID_HOST', 'SQUID_PORT', 'SQUID_HOSTS', 'LOG_FORMAT', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}
             {% set value = env_vars.get(key, '') %}
             <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                 <label class="block text-sm font-semibold text-gray-700 mb-2">{{ key }}</label>
@@ -101,7 +101,7 @@
         </form>
         
         <div x-show="!editing" class="bg-gray-900 rounded-lg p-4 overflow-x-auto">
-            <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap">{% for key in ['SQUID_HOST', 'SQUID_PORT', 'LOG_FORMAT', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}{{ key }}="{{ env_vars.get(key, '') }}"
+            <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap">{% for key in ['SQUID_HOST', 'SQUID_PORT', 'SQUID_HOSTS', 'LOG_FORMAT', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}{{ key }}="{{ env_vars.get(key, '') }}"
 {% endfor %}</pre>
         </div>
     </div>

+ 1 - 1
utils/admin.py

@@ -13,7 +13,7 @@ from utils.types import ACL_TYPES_INFO, PREDEFINED_ACLS
 load_dotenv()
 
 SQUID_CONFIG_PATH = Config.SQUID_CONFIG_PATH or "/etc/squid/squid.conf"
-ACL_FILES_DIR = os.getenv("ACL_FILES_DIR") or os.path.join(
+ACL_FILES_DIR = Config.ACL_FILES_DIR or os.path.join(
     os.path.dirname(SQUID_CONFIG_PATH), "squid.d", ""
 )