|
|
@@ -11,7 +11,7 @@ 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
|
|
|
+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,
|
|
|
@@ -73,7 +73,6 @@ def parse_log_line_pipe_format(line):
|
|
|
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]
|
|
|
@@ -85,24 +84,17 @@ def parse_log_line_pipe_format(line):
|
|
|
status_code = int(parts[8])
|
|
|
bytes_sent = int(parts[9])
|
|
|
squid_status = parts[13]
|
|
|
-
|
|
|
- # Filtrar registros irrelevantes
|
|
|
- if "TCP_DENIED" in squid_status:
|
|
|
- return None
|
|
|
-
|
|
|
- # Aquí puedes aplicar otros filtros si lo deseas (por método, por URL, etc.)
|
|
|
- # Ejemplo: excluir métodos distintos de GET/CONNECT
|
|
|
- if method not in ("GET", "CONNECT"):
|
|
|
- return None
|
|
|
-
|
|
|
+ is_denied = "TCP_DENIED" in squid_status
|
|
|
return {
|
|
|
'ip': client_ip,
|
|
|
'username': username,
|
|
|
'url': url,
|
|
|
'response': status_code,
|
|
|
- 'data_transmitted': bytes_sent
|
|
|
+ 'data_transmitted': bytes_sent,
|
|
|
+ 'method': method,
|
|
|
+ 'status': squid_status,
|
|
|
+ 'is_denied': is_denied
|
|
|
}
|
|
|
-
|
|
|
except Exception as e:
|
|
|
logger.error(f"Error parseando línea con formato pipe: {line.strip()} - {e}")
|
|
|
return None
|
|
|
@@ -113,34 +105,29 @@ def parse_log_line_space_format(line):
|
|
|
"""
|
|
|
try:
|
|
|
parts = line.split(" ")
|
|
|
-
|
|
|
- # Validar que tenga suficientes partes
|
|
|
if len(parts) < 11:
|
|
|
logger.warning(f"Línea ignorada (formato incompleto): {line.strip()}")
|
|
|
return None
|
|
|
-
|
|
|
- # Ignorar líneas con username "-"
|
|
|
if parts[3] == "-":
|
|
|
return None
|
|
|
-
|
|
|
- # Buscar TCP_DENIED en toda la línea
|
|
|
- if "TCP_DENIED" in line:
|
|
|
- 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
|
|
|
+ 'data_transmitted': int(data) if data.isdigit() else 0,
|
|
|
+ 'method': method,
|
|
|
+ 'status': squid_status,
|
|
|
+ 'is_denied': is_denied
|
|
|
}
|
|
|
-
|
|
|
except (IndexError, ValueError) as e:
|
|
|
logger.error(f"Error parseando línea con formato espacios: {line.strip()} - {e}")
|
|
|
return None
|
|
|
@@ -170,12 +157,9 @@ def detect_log_format(log_file, sample_lines=10):
|
|
|
|
|
|
def process_logs(log_file):
|
|
|
log_format = detect_log_format(log_file)
|
|
|
-
|
|
|
if not os.path.exists(log_file):
|
|
|
logger.error(f"Archivo no encontrado: {log_file}")
|
|
|
return
|
|
|
-
|
|
|
- # Comprobación de existencia de tablas dinámicas para la fecha actual
|
|
|
engine = get_engine()
|
|
|
user_table, log_table = get_dynamic_table_names()
|
|
|
if not (table_exists(engine, user_table) and table_exists(engine, log_table)):
|
|
|
@@ -186,21 +170,14 @@ def process_logs(log_file):
|
|
|
except Exception as e:
|
|
|
logger.error(f"Error al crear las tablas dinámicas: {e}")
|
|
|
return
|
|
|
-
|
|
|
try:
|
|
|
current_inode = get_file_inode(log_file)
|
|
|
file_size = os.path.getsize(log_file)
|
|
|
-
|
|
|
- # Obtener modelos dinámicos para la fecha actual
|
|
|
date_suffix = datetime.now().strftime("%Y%m%d")
|
|
|
DynamicUser, DynamicLog = get_dynamic_models(date_suffix)
|
|
|
-
|
|
|
with DatabaseManager() as session:
|
|
|
- # Obtener o crear metadatos
|
|
|
metadata = session.query(LogMetadata).first()
|
|
|
last_position = metadata.last_position if metadata else 0
|
|
|
-
|
|
|
- # Detectar rotación o truncamiento
|
|
|
if metadata:
|
|
|
if metadata.last_inode != current_inode:
|
|
|
logger.info(f"Rotación detectada (inodo: {metadata.last_inode} -> {current_inode})")
|
|
|
@@ -208,83 +185,85 @@ def process_logs(log_file):
|
|
|
elif file_size < last_position:
|
|
|
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
|
|
|
start_time = time.time()
|
|
|
-
|
|
|
def commit_batch():
|
|
|
- nonlocal inserted_logs, inserted_users
|
|
|
+ nonlocal inserted_logs, inserted_users, inserted_denied
|
|
|
retry_count = 0
|
|
|
- # Obtener nombres de tablas dinámicas
|
|
|
user_table, log_table = get_dynamic_table_names()
|
|
|
- logger.info(f"Guardando usuarios en la tabla: {user_table}, logs en la tabla: {log_table}")
|
|
|
- # Usar los modelos dinámicos ya obtenidos
|
|
|
+ logger.info(f"Guardando usuarios en la tabla: {user_table}, logs en la tabla: {log_table}, denied en denied_logs")
|
|
|
while retry_count < MAX_RETRIES:
|
|
|
try:
|
|
|
- # Insertar nuevos usuarios
|
|
|
if new_users_to_insert:
|
|
|
session.bulk_save_objects(new_users_to_insert)
|
|
|
- session.flush() # Asigna IDs
|
|
|
-
|
|
|
- # Actualizar caché con nuevos IDs
|
|
|
+ session.flush()
|
|
|
for user in new_users_to_insert:
|
|
|
user_cache[(user.username, user.ip)] = user.id
|
|
|
-
|
|
|
inserted_users += len(new_users_to_insert)
|
|
|
new_users_to_insert.clear()
|
|
|
-
|
|
|
- # Insertar logs
|
|
|
if logs_to_insert:
|
|
|
session.bulk_insert_mappings(DynamicLog, logs_to_insert)
|
|
|
inserted_logs += len(logs_to_insert)
|
|
|
logs_to_insert.clear()
|
|
|
-
|
|
|
+ if denied_to_insert:
|
|
|
+ session.bulk_save_objects(denied_to_insert)
|
|
|
+ inserted_denied += len(denied_to_insert)
|
|
|
+ denied_to_insert.clear()
|
|
|
session.commit()
|
|
|
- logger.debug(f"Batch commit: {inserted_users} usuarios, {inserted_logs} logs")
|
|
|
+ logger.debug(f"Batch commit: {inserted_users} usuarios, {inserted_logs} logs, {inserted_denied} denied")
|
|
|
return True
|
|
|
-
|
|
|
except IntegrityError as e:
|
|
|
- # Manejar usuarios duplicados (insertados concurrentemente)
|
|
|
logger.warning(f"Error de integridad (reintento {retry_count+1}): {e}")
|
|
|
session.rollback()
|
|
|
retry_count += 1
|
|
|
-
|
|
|
- # Limpiar caché y reintentar
|
|
|
if new_users_to_insert:
|
|
|
for user in new_users_to_insert:
|
|
|
key = (user.username, user.ip)
|
|
|
if key in user_cache:
|
|
|
del user_cache[key]
|
|
|
-
|
|
|
except SQLAlchemyError as e:
|
|
|
logger.error(f"Error de base de datos: {e}")
|
|
|
session.rollback()
|
|
|
break
|
|
|
-
|
|
|
return False
|
|
|
-
|
|
|
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'))
|
|
|
-
|
|
|
- # Parsear línea
|
|
|
log_data = parse_log_line(line)
|
|
|
if not log_data:
|
|
|
continue
|
|
|
-
|
|
|
+ if log_data.get('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()
|
|
|
+ )
|
|
|
+ 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():
|
|
|
+ logger.info(f"Batch denied_logs insertado exitosamente. Registros: {BATCH_SIZE}")
|
|
|
+ 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'])
|
|
|
|
|
|
@@ -345,24 +324,26 @@ def process_logs(log_file):
|
|
|
logger.error("Error en commit batch. Continuando con siguiente lote")
|
|
|
|
|
|
# Comitar último lote
|
|
|
- if new_users_to_insert or logs_to_insert:
|
|
|
- commit_batch()
|
|
|
-
|
|
|
- # 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}")
|
|
|
- logger.info(f"Tiempo: {elapsed:.2f}s, Velocidad: {processed_lines/elapsed:.2f} lps")
|
|
|
+ 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")
|
|
|
|
|
|
except Exception as e:
|
|
|
logger.critical(f"Error crítico en process_logs: {e}", exc_info=True)
|