Parcourir la source

feat: Refactor install.sh and log.py for improved readability and maintainability

Manuel il y a 1 an
Parent
commit
c5e5eb7c09
2 fichiers modifiés avec 186 ajouts et 214 suppressions
  1. 80 76
      install.sh
  2. 106 138
      parsers/log.py

+ 80 - 76
install.sh

@@ -154,7 +154,7 @@ function moveDB() {
     current_version=$(grep -E '^VERSION\s*=' "$env_file" | cut -d= -f2 | tr -dc '0-9' || echo 0)
 
     if ! grep -qE '^VERSION\s*=' "$env_file"; then
-      echo "VERSION=2" >> "$env_file"
+        echo "VERSION=2" >>"$env_file"
         echo "Eliminando base de datos antigua por actualización..."
         rm -rf "$databaseSQlite"
         ok "Base de datos antigua eliminada"
@@ -181,7 +181,7 @@ function createEnvFile() {
         return 0
     else
         echo "Creando archivo de configuración .env..."
-        cat > "$env_file" << EOF
+        cat >"$env_file" <<EOF
 VERSION=2
 SQUID_HOST=127.0.0.1
 SQUID_PORT=3128
@@ -190,6 +190,7 @@ DATABASE_TYPE=SQLITE
 SQUID_LOG=/var/log/squid/access.log
 DATABASE_STRING_CONNECTION=/opt/SquidStats/squidstats.db
 REFRESH_INTERVAL=60
+BLACKLIST_DOMAINS="facebook.com,twitter.com,instagram.com,tiktok.com,youtube.com,netflix.com"
 EOF
         ok "Archivo .env creado correctamente en $env_file"
         return 0
@@ -205,7 +206,7 @@ function createService() {
     fi
 
     echo "Creando servicio en $service_file..."
-    cat > "$service_file" << EOF
+    cat >"$service_file" <<EOF
 [Unit]
 Description=SquidStats Web Application
 After=network.target
@@ -241,51 +242,50 @@ function configureDatabase() {
     while true; do
         read -p "Opción [1/2]: " choice
         case $choice in
-            1|"") break;;
-            2) break;;
-            *) error "Opción inválida. Intente nuevamente.";;
+        1 | "") break ;;
+        2) break ;;
+        *) error "Opción inválida. Intente nuevamente." ;;
         esac
     done
 
     case $choice in
-        2)
-            while true; do
-                read -p "Ingrese cadena de conexión (mysql+pymysql://user:clave@host:port/db): " conn_str
-
-                if [[ "$conn_str" != mysql+pymysql://* ]]; then
-                    error "Formato inválido. Debe comenzar con: mysql+pymysql://"
-                    continue
-                fi
-
-                validation_result=$(python3 /opt/SquidStats/utils/validateString.py "$conn_str" 2>&1)
-                exit_code=$?
-
-                if [[ $exit_code -eq 0 ]]; then
-                    sed -i "s|^DATABASE_TYPE=.*|DATABASE_TYPE=MARIADB|" "$env_file"
-
-                    # validation_result tiene la cadena codificada, escapamos para sed
-                    escaped_conn_str=$(printf '%s\n' "$validation_result" | sed -e 's/[\/&]/\\&/g')
-                    sed -i "s|^DATABASE_STRING_CONNECTION=.*|DATABASE_STRING_CONNECTION=$escaped_conn_str|" "$env_file"
-
-                    ok "Configuración MariaDB actualizada!"
-                    break
-                else
-                    error "Error en la cadena:\n${validation_result#ERROR: }"
-                fi
-            done
-            ;;
-        *)
-            sqlite_path="/opt/SquidStats/squidstats.db"
-            sed -i "s|^DATABASE_TYPE=.*|DATABASE_TYPE=SQLITE|" "$env_file"
-            sed -i "s|^DATABASE_STRING_CONNECTION=.*|DATABASE_STRING_CONNECTION=$sqlite_path|" "$env_file"
-            ok "Configuración SQLite establecida!"
-            ;;
+    2)
+        while true; do
+            read -p "Ingrese cadena de conexión (mysql+pymysql://user:clave@host:port/db): " conn_str
+
+            if [[ "$conn_str" != mysql+pymysql://* ]]; then
+                error "Formato inválido. Debe comenzar con: mysql+pymysql://"
+                continue
+            fi
+
+            validation_result=$(python3 /opt/SquidStats/utils/validateString.py "$conn_str" 2>&1)
+            exit_code=$?
+
+            if [[ $exit_code -eq 0 ]]; then
+                sed -i "s|^DATABASE_TYPE=.*|DATABASE_TYPE=MARIADB|" "$env_file"
+
+                # validation_result tiene la cadena codificada, escapamos para sed
+                escaped_conn_str=$(printf '%s\n' "$validation_result" | sed -e 's/[\/&]/\\&/g')
+                sed -i "s|^DATABASE_STRING_CONNECTION=.*|DATABASE_STRING_CONNECTION=$escaped_conn_str|" "$env_file"
+
+                ok "Configuración MariaDB actualizada!"
+                break
+            else
+                error "Error en la cadena:\n${validation_result#ERROR: }"
+            fi
+        done
+        ;;
+    *)
+        sqlite_path="/opt/SquidStats/squidstats.db"
+        sed -i "s|^DATABASE_TYPE=.*|DATABASE_TYPE=SQLITE|" "$env_file"
+        sed -i "s|^DATABASE_STRING_CONNECTION=.*|DATABASE_STRING_CONNECTION=$sqlite_path|" "$env_file"
+        ok "Configuración SQLite establecida!"
+        ;;
     esac
 }
 
-function patchSquidConf() {
+patchSquidConf() {
     local squid_conf=""
-
     if [ -f "/etc/squid/squid.conf" ]; then
         squid_conf="/etc/squid/squid.conf"
     elif [ -f "/etc/squid3/squid.conf" ]; then
@@ -295,13 +295,17 @@ function patchSquidConf() {
         return 1
     fi
 
-    cp "$squid_conf" "${squid_conf}.back"
-    ok "Backup realizado: ${squid_conf}.back"
+    # Backup solo si no existe
+    if [ ! -f "${squid_conf}.back" ]; then
+        cp "$squid_conf" "${squid_conf}.back"
+        ok "Backup realizado: ${squid_conf}.back"
+    else
+        echo "Backup previo ya existe: ${squid_conf}.back"
+    fi
 
-    # Añade logformat solo si no existe
+    # Añadir logformat detailed si no existe
     if ! grep -q '^logformat[[:space:]]\+detailed' "$squid_conf"; then
-        cat << 'EOF' >> "$squid_conf"
-
+        cat <<'EOF' >>"$squid_conf"
 logformat detailed %ts.%03tu %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st %rm %ru %>a %mt %<a %<rm %Ss/%Sh %<st
 EOF
         ok "Se agregó logformat detailed"
@@ -309,7 +313,7 @@ EOF
         echo "logformat detailed ya existe."
     fi
 
-    # Modificar access_log para asegurar que tenga detailed !manager
+    # Asegurar access_log con detailed !manager
     if grep -q '^access_log[[:space:]]\+/var/log/squid/access\.log' "$squid_conf"; then
         sed -i '/^access_log[[:space:]]\+\/var\/log\/squid\/access\.log/{
             s/detailed//g
@@ -318,7 +322,7 @@ EOF
         }' "$squid_conf"
         ok "access_log actualizado con detailed !manager"
     else
-        echo 'access_log /var/log/squid/access.log detailed !manager' >> "$squid_conf"
+        echo 'access_log /var/log/squid/access.log detailed !manager' >>"$squid_conf"
         ok "access_log agregado con detailed !manager"
     fi
 }
@@ -326,39 +330,39 @@ EOF
 function main() {
     checkSudo
 
-     if [ "$1" = "--update" ]; then
-      echo "Actualizando Servicio..."
-      updateOrCloneRepo
-      systemctl restart squidstats.service
+    if [ "$1" = "--update" ]; then
+        echo "Actualizando Servicio..."
+        updateOrCloneRepo
+        systemctl restart squidstats.service
 
-      ok "Actualizacion completada! Acceda en: \033[1;37mhttp://IP:5000\033[0m"
+        ok "Actualizacion completada! Acceda en: \033[1;37mhttp://IP:5000\033[0m"
     else
-      echo "Instalando aplicación web..."
-      checkPackages
-      updateOrCloneRepo
-      patchSquidConf
-      checkSquidLog
-      setupVenv
-      installDependencies
-      createEnvFile
-      configureDatabase
-      moveDB
-      createService
-
-      ok "Instalación completada! Acceda en: \033[1;37mhttp://IP:5000\033[0m"
+        echo "Instalando aplicación web..."
+        checkPackages
+        updateOrCloneRepo
+        patchSquidConf
+        checkSquidLog
+        setupVenv
+        installDependencies
+        createEnvFile
+        configureDatabase
+        moveDB
+        createService
+
+        ok "Instalación completada! Acceda en: \033[1;37mhttp://IP:5000\033[0m"
     fi
 }
 
 case "$1" in
-    "--update")
-        main "$1"
-        ;;
-    "")
-        main
-        ;;
-    *)
-        echo "Parámetro no reconocido: $1"
-        echo "Uso: $0 --update"
-        exit 1
-        ;;
+"--update")
+    main "$1"
+    ;;
+"")
+    main
+    ;;
+*)
+    echo "Parámetro no reconocido: $1"
+    echo "Uso: $0 --update"
+    exit 1
+    ;;
 esac

+ 106 - 138
parsers/log.py

@@ -11,18 +11,27 @@ current_dir = Path(__file__).resolve().parent
 project_root = current_dir.parent
 sys.path.append(str(project_root))
 
-from database.database import Base, get_session, User, Log, LogMetadata, get_engine, table_exists, get_dynamic_table_names, get_dynamic_models, DeniedLog
+from database.database import (
+    Base,
+    get_session,
+    User,
+    Log,
+    LogMetadata,
+    get_engine,
+    table_exists,
+    get_dynamic_table_names,
+    get_dynamic_models,
+    DeniedLog,
+)
 
 logging.basicConfig(
     level=logging.INFO,
-    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
-    handlers=[
-        logging.StreamHandler(),
-        logging.FileHandler('log_processor.log')
-    ]
+    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+    handlers=[logging.StreamHandler(), logging.FileHandler("log_processor.log")],
 )
 logger = logging.getLogger(__name__)
 
+
 class DatabaseManager:
     def __init__(self, engine=None, session=None):
         self.engine = engine if engine else get_engine()
@@ -46,11 +55,18 @@ class DatabaseManager:
         finally:
             self.session.close()
 
+
+# Constantes para campos y batch
+BATCH_SIZE = 500
+MAX_RETRIES = 3
+
+
 def get_table_names():
     """Obtiene nombres de tablas con fecha actual"""
     today = datetime.now().strftime("%Y%m%d")
     return f"user_{today}", f"log_{today}", "log_metadata"
 
+
 def get_file_inode(filepath):
     """Obtiene el inode del archivo para detectar rotaciones"""
     try:
@@ -62,98 +78,88 @@ def get_file_inode(filepath):
         logger.error(f"Error accediendo archivo: {e}")
         raise
 
+
 def parse_log_line(line):
-    if '|' in line:
+    if "|" in line:
         return parse_log_line_pipe_format(line)
     else:
         return parse_log_line_space_format(line)
 
+
 def parse_log_line_pipe_format(line):
-    parts = line.strip().split('|')
+    parts = line.strip().split("|")
     if len(parts) < 14:
         logger.warning(f"Línea ignorada (formato incompleto): {line.strip()}")
         return None
     try:
-        timestamp_str = parts[0]
-        client_ip = parts[1]
-        if parts[3] == '-':
-            return None  # Ignorar líneas con username "-"
         username = parts[3]
-        method = parts[5]
-        url = parts[6]
-        status_code = int(parts[8])
-        bytes_sent = int(parts[9])
-        squid_status = parts[13]
-        is_denied = "TCP_DENIED" in squid_status
+        if username == "-":
+            return None
         return {
-            'ip': client_ip,
-            'username': username,
-            'url': url,
-            'response': status_code,
-            'data_transmitted': bytes_sent,
-            'method': method,
-            'status': squid_status,
-            'is_denied': is_denied
+            "ip": parts[1],
+            "username": username,
+            "url": parts[6],
+            "response": int(parts[8]),
+            "data_transmitted": int(parts[9]),
+            "method": parts[5],
+            "status": parts[13],
+            "is_denied": "TCP_DENIED" in parts[13],
         }
     except Exception as e:
         logger.error(f"Error parseando línea con formato pipe: {line.strip()} - {e}")
         return None
 
+
 def parse_log_line_space_format(line):
-    """
-    Parsea línea con formato delimitado por espacios (formato estándar de Squid)
-    """
     try:
-        parts = line.split(" ")
-        if len(parts) < 11:
-            logger.warning(f"Línea ignorada (formato incompleto): {line.strip()}")
+        parts = line.split()
+        if len(parts) < 11 or parts[3] == "-":
+            logger.warning(f"Línea ignorada (formato incompleto o username '-'): {line.strip()}")
             return None
-        if parts[3] == "-":
-            return None
-        method = parts[5] if len(parts) > 5 else ""
-        squid_status = parts[6] if len(parts) > 6 else ""
-        is_denied = "TCP_DENIED" in line
-        ip = parts[1]
-        username = parts[3]
-        url = parts[7]
-        response = parts[9]
-        data = parts[10]
         return {
-            'ip': ip,
-            'username': username,
-            'url': url,
-            'response': int(response) if response.isdigit() else 0,
-            'data_transmitted': int(data) if data.isdigit() else 0,
-            'method': method,
-            'status': squid_status,
-            'is_denied': is_denied
+            "ip": parts[1],
+            "username": parts[3],
+            "url": parts[7],
+            "response": int(parts[9]) if parts[9].isdigit() else 0,
+            "data_transmitted": int(parts[10]) if parts[10].isdigit() else 0,
+            "method": parts[5] if len(parts) > 5 else "",
+            "status": parts[6] if len(parts) > 6 else "",
+            "is_denied": "TCP_DENIED" in line,
         }
     except (IndexError, ValueError) as e:
         logger.error(f"Error parseando línea con formato espacios: {line.strip()} - {e}")
         return None
 
+
 def detect_log_format(log_file, sample_lines=10):
     try:
-        with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
+        with open(log_file, "r", encoding="utf-8", errors="replace") as f:
             pipe_count = 0
             space_count = 0
-            
+
             for i, line in enumerate(f):
                 if i >= sample_lines:
                     break
-                    
-                if '|' in line and line.count('|') > 5:  # Formato pipe típicamente tiene muchos |
+
+                if (
+                    "|" in line and line.count("|") > 5
+                ):  # Formato pipe típicamente tiene muchos |
                     pipe_count += 1
-                elif len(line.split()) > 10:  # Formato space típicamente tiene muchos campos
+                elif (
+                    len(line.split()) > 10
+                ):  # Formato space típicamente tiene muchos campos
                     space_count += 1
-            
-            format_detected = 'pipe' if pipe_count > space_count else 'space'
-            logger.info(f"Formato detectado: {format_detected} (pipe: {pipe_count}, space: {space_count})")
+
+            format_detected = "pipe" if pipe_count > space_count else "space"
+            logger.info(
+                f"Formato detectado: {format_detected} (pipe: {pipe_count}, space: {space_count})"
+            )
             return format_detected
-            
+
     except Exception as e:
         logger.warning(f"Error detectando formato, usando detección por línea: {e}")
-        return 'auto'  # Fallback a detección automática por línea
+        return "auto"  # Fallback a detección automática por línea
+
 
 def process_logs(log_file):
     log_format = detect_log_format(log_file)
@@ -186,17 +192,11 @@ def process_logs(log_file):
                     logger.warning(f"Archivo truncado (tamaño: {file_size} < posición: {last_position})")
                     last_position = 0
             logger.info(f"Leyendo desde posición: {last_position}")
-            BATCH_SIZE = 500
-            MAX_RETRIES = 3
             user_cache = {}
-            logs_to_insert = []
-            new_users_to_insert = []
-            denied_to_insert = []
-            processed_lines = 0
-            inserted_logs = 0
-            inserted_users = 0
-            inserted_denied = 0
+            logs_to_insert, new_users_to_insert, denied_to_insert = [], [], []
+            processed_lines = inserted_logs = inserted_users = inserted_denied = 0
             start_time = time.time()
+
             def commit_batch():
                 nonlocal inserted_logs, inserted_users, inserted_denied
                 retry_count = 0
@@ -217,6 +217,7 @@ def process_logs(log_file):
                             logs_to_insert.clear()
                         if denied_to_insert:
                             session.bulk_save_objects(denied_to_insert)
+                            logger.info(f"Enviando a denied_logs: {[d.__dict__ for d in denied_to_insert]}")
                             inserted_denied += len(denied_to_insert)
                             denied_to_insert.clear()
                         session.commit()
@@ -236,27 +237,27 @@ def process_logs(log_file):
                         session.rollback()
                         break
                 return False
-            with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
+
+            with open(log_file, "r", encoding="utf-8", errors="replace") as f:
                 f.seek(last_position)
                 current_position = last_position
                 for line in f:
                     processed_lines += 1
-                    current_position += len(line.encode('utf-8'))
+                    current_position += len(line.encode("utf-8"))
                     log_data = parse_log_line(line)
                     if not log_data:
                         continue
-                    if log_data.get('is_denied'):
+                    if log_data["is_denied"]:
                         denied_entry = DeniedLog(
-                            username=log_data['username'],
-                            ip=log_data['ip'],
-                            url=log_data['url'],
-                            method=log_data.get('method', ''),
-                            status=log_data.get('status', ''),
-                            response=log_data.get('response'),
-                            data_transmitted=log_data.get('data_transmitted', 0),
-                            created_at=datetime.now()
+                            username=log_data["username"],
+                            ip=log_data["ip"],
+                            url=log_data["url"],
+                            method=log_data.get("method", ""),
+                            status=log_data.get("status", ""),
+                            response=log_data.get("response"),
+                            data_transmitted=log_data.get("data_transmitted", 0),
+                            created_at=datetime.now(),
                         )
-                        logger.info(f"Enviando a denied_logs: {denied_entry.__dict__}")
                         denied_to_insert.append(denied_entry)
                         if len(denied_to_insert) >= BATCH_SIZE:
                             if commit_batch():
@@ -264,88 +265,55 @@ def process_logs(log_file):
                             else:
                                 logger.error("Error en commit batch denied. Continuando con siguiente lote")
                         continue
-                    # Identificador único usuario-ip
-                    user_key = (log_data['username'], log_data['ip'])
-                    
-                    # Buscar en caché o preparar para inserción
-                    if user_key in user_cache:
-                        user_id = user_cache[user_key]
-                    else:
-                        # Buscar en base de datos usando modelo dinámico
-                        existing_user = session.query(DynamicUser).filter_by(
-                            username=log_data['username'],
-                            ip=log_data['ip']
-                        ).first()
+                    user_key = (log_data["username"], log_data["ip"])
+                    user_id = user_cache.get(user_key)
+                    if user_id is None:
+                        existing_user = session.query(DynamicUser).filter_by(username=log_data["username"], ip=log_data["ip"]).first()
                         if existing_user:
                             user_id = existing_user.id
                             user_cache[user_key] = user_id
                         else:
-                            # Preparar nuevo usuario con modelo dinámico
-                            new_user = DynamicUser(
-                                username=log_data['username'],
-                                ip=log_data['ip']
-                            )
+                            new_user = DynamicUser(username=log_data["username"], ip=log_data["ip"])
                             new_users_to_insert.append(new_user)
-                            user_cache[user_key] = None  # Marcador temporal
+                            user_cache[user_key] = None
                             user_id = None
-
-                    # Si el usuario es nuevo y no tiene ID aún
                     if user_id is None:
                         if not commit_batch():
                             logger.error("Error crítico en commit batch. Abortando lote")
                             continue
-
-                        # 🔁 FIX: reconsultar desde la base de datos usando modelo dinámico
-                        existing_user = session.query(DynamicUser).filter_by(
-                            username=log_data['username'],
-                            ip=log_data['ip']
-                        ).first()
-
+                        existing_user = session.query(DynamicUser).filter_by(username=log_data["username"], ip=log_data["ip"]).first()
                         if existing_user:
                             user_id = existing_user.id
                             user_cache[user_key] = user_id
                         else:
                             logger.error(f"Usuario no creado: {user_key}. Saltando línea")
                             continue
-
-                    # Preparar log para inserción
                     logs_to_insert.append({
-                        'user_id': user_id,
-                        'url': log_data['url'],
-                        'response': log_data['response'],
-                        'request_count': 1,
-                        'data_transmitted': log_data['data_transmitted'],
-                        'timestamp': datetime.now()
+                        "user_id": user_id,
+                        "url": log_data["url"],
+                        "response": log_data["response"],
+                        "request_count": 1,
+                        "data_transmitted": log_data["data_transmitted"],
+                        "timestamp": datetime.now(),
                     })
-
-                    # Comitar por lotes
                     if len(logs_to_insert) >= BATCH_SIZE:
                         if not commit_batch():
                             logger.error("Error en commit batch. Continuando con siguiente lote")
-            
-            # Comitar último lote
             if new_users_to_insert or logs_to_insert or denied_to_insert:
                 if commit_batch():
                     if denied_to_insert:
                         logger.info(f"Batch denied_logs insertado exitosamente. Registros: {len(denied_to_insert)}")
-                # ...existing code...
-                # Actualizar metadatos de posición
-                if not metadata:
-                    metadata = LogMetadata()
-                    session.add(metadata)
-                
-                metadata.last_position = current_position
-                metadata.last_inode = current_inode
-                metadata.last_processed = datetime.now()
-                session.commit()
-
-                # Estadísticas finales
-                elapsed = time.time() - start_time
-                logger.info(f"Procesamiento completado. Líneas: {processed_lines}")
-                logger.info(f"Logs insertados: {inserted_logs}, Usuarios nuevos: {inserted_users}, Denied: {inserted_denied}")
-                logger.info(f"Tiempo: {elapsed:.2f}s, Velocidad: {processed_lines/elapsed:.2f} lps")
-
+            if not metadata:
+                metadata = LogMetadata()
+                session.add(metadata)
+            metadata.last_position = current_position
+            metadata.last_inode = current_inode
+            metadata.last_processed = datetime.now()
+            session.commit()
+            elapsed = time.time() - start_time
+            logger.info(f"Procesamiento completado. Líneas: {processed_lines}")
+            logger.info(f"Logs insertados: {inserted_logs}, Usuarios nuevos: {inserted_users}, Denied: {inserted_denied}")
+            logger.info(f"Tiempo: {elapsed:.2f}s, Velocidad: {processed_lines/elapsed:.2f} lps")
     except Exception as e:
         logger.critical(f"Error crítico en process_logs: {e}", exc_info=True)
         raise
-