|
|
@@ -5,6 +5,7 @@ from datetime import datetime
|
|
|
|
|
|
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
|
|
|
|
|
|
+from config import Config
|
|
|
from database.database import (
|
|
|
Base,
|
|
|
DeniedLog,
|
|
|
@@ -51,6 +52,9 @@ class DatabaseManager:
|
|
|
BATCH_SIZE = 500
|
|
|
MAX_RETRIES = 3
|
|
|
|
|
|
+# Modo de parseo de logs controlado por .env LOG_FORMAT: 'DETAILED' o 'DEFAULT'
|
|
|
+LOG_FORMAT = getattr(Config, "LOG_FORMAT", "DETAILED").upper()
|
|
|
+
|
|
|
|
|
|
def find_last_parent_proxy(log_file: str, lines_to_check: int = 5000) -> str | None:
|
|
|
if not os.path.exists(log_file):
|
|
|
@@ -106,13 +110,22 @@ def get_file_inode(filepath):
|
|
|
|
|
|
|
|
|
def parse_log_line(line):
|
|
|
+ """Parse a log line based on configured LOG_FORMAT.
|
|
|
+
|
|
|
+ - DETAILED: mantiene el comportamiento actual (pipe/space/autodetección clásica)
|
|
|
+ - DEFAULT: usa un parser fijo del formato clásico de Squid
|
|
|
+ """
|
|
|
+ if LOG_FORMAT == "DEFAULT":
|
|
|
+ return parse_log_line_default(line)
|
|
|
+
|
|
|
+ # DETAILED (comportamiento actual)
|
|
|
if "cache_object://" in line:
|
|
|
return None
|
|
|
if "|" in line:
|
|
|
return parse_log_line_pipe_format(line)
|
|
|
parts = line.split()
|
|
|
# Formato clásico de Squid: timestamp elapsed ip code/status bytes method url rfc931 peerstatus/peerhost type
|
|
|
- if len(parts) >= 10 and parts[5] in (
|
|
|
+ if len(parts) >= 10 and (len(parts) > 5 and parts[5] in (
|
|
|
"CONNECT",
|
|
|
"GET",
|
|
|
"POST",
|
|
|
@@ -122,10 +135,11 @@ def parse_log_line(line):
|
|
|
"OPTIONS",
|
|
|
"TRACE",
|
|
|
"PATCH",
|
|
|
- ):
|
|
|
+ )):
|
|
|
try:
|
|
|
return {
|
|
|
"ip": parts[2],
|
|
|
+ # Mantener comportamiento actual: si '-', dejar None
|
|
|
"username": parts[2] if parts[2] != "-" else None,
|
|
|
"url": parts[6],
|
|
|
"response": int(parts[3].split("/")[-1])
|
|
|
@@ -143,6 +157,54 @@ def parse_log_line(line):
|
|
|
return parse_log_line_space_format(line)
|
|
|
|
|
|
|
|
|
+def parse_log_line_default(line: str):
|
|
|
+ """Parser del formato por defecto de Squid (access.log nativo).
|
|
|
+
|
|
|
+ Ejemplo:
|
|
|
+ ts elapsed ip status bytes method url user hierarchy type
|
|
|
+ 1755283778.165 1 172.17.0.1 TCP_MISS/200 11185 GET http://... - HIER_NONE/- text/plain
|
|
|
+ """
|
|
|
+ try:
|
|
|
+ parts = line.split()
|
|
|
+ # Debe tener al menos: 10 campos; evitamos líneas internas de cache_object
|
|
|
+ if len(parts) < 7:
|
|
|
+ return None
|
|
|
+ # Localiza URL (puede contener espacios sólo en casos raros, asumimos estándar)
|
|
|
+ # En el formato típico, url está en parts[6]
|
|
|
+ url = parts[6] if len(parts) > 6 else None
|
|
|
+ if not url or "cache_object://" in url:
|
|
|
+ return None
|
|
|
+
|
|
|
+ ip = parts[2] if len(parts) > 2 else None
|
|
|
+ status = parts[3] if len(parts) > 3 else ""
|
|
|
+ bytes_str = parts[4] if len(parts) > 4 else "0"
|
|
|
+ method = parts[5] if len(parts) > 5 else ""
|
|
|
+ # Campo user suele ir en parts[7]; si es '-', usamos la IP como username
|
|
|
+ user_field = parts[7] if len(parts) > 7 else "-"
|
|
|
+ username = user_field if user_field != "-" else (ip or "-")
|
|
|
+
|
|
|
+ response = 0
|
|
|
+ if "/" in status:
|
|
|
+ code = status.split("/")[-1]
|
|
|
+ response = int(code) if code.isdigit() else 0
|
|
|
+
|
|
|
+ data_transmitted = int(bytes_str) if bytes_str.isdigit() else 0
|
|
|
+
|
|
|
+ return {
|
|
|
+ "ip": ip,
|
|
|
+ "username": username,
|
|
|
+ "url": url,
|
|
|
+ "response": response,
|
|
|
+ "data_transmitted": data_transmitted,
|
|
|
+ "method": method,
|
|
|
+ "status": status,
|
|
|
+ "is_denied": "TCP_DENIED" in status,
|
|
|
+ }
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"Error parsing DEFAULT format line: {line.strip()} - {e}")
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
def parse_log_line_pipe_format(line):
|
|
|
parts = line.strip().split("|")
|
|
|
if len(parts) < 14:
|
|
|
@@ -369,7 +431,7 @@ def process_logs(log_file):
|
|
|
"response": log_data["response"],
|
|
|
"request_count": 1,
|
|
|
"data_transmitted": log_data["data_transmitted"],
|
|
|
- "timestamp": datetime.now(),
|
|
|
+ "created_at": datetime.now(),
|
|
|
}
|
|
|
)
|
|
|
if len(logs_to_insert) >= BATCH_SIZE:
|
|
|
@@ -377,12 +439,17 @@ def process_logs(log_file):
|
|
|
logger.error(
|
|
|
"Error committing batch. Continuing with next batch"
|
|
|
)
|
|
|
+ # Commit any remaining items that didn't fill a full batch
|
|
|
+ if logs_to_insert or new_users_to_insert or denied_to_insert:
|
|
|
+ if not commit_batch():
|
|
|
+ logger.error("Final commit_batch failed for remaining items")
|
|
|
if not metadata:
|
|
|
metadata = LogMetadata()
|
|
|
session.add(metadata)
|
|
|
metadata.last_position = current_position
|
|
|
metadata.last_inode = current_inode
|
|
|
- metadata.last_processed = datetime.now()
|
|
|
+ # Align with LogMetadata model's column
|
|
|
+ metadata.updated_at = datetime.now()
|
|
|
session.commit()
|
|
|
elapsed = time.time() - start_time
|
|
|
logger.info(f"Processing completed. Lines: {processed_lines}")
|