Explorar el Código

refactor: enhance user grouping logic in connections.py and improve log line parsing in log.py

Manuel hace 1 año
padre
commit
5bb798c233
Se han modificado 3 ficheros con 35 adiciones y 15 borrados
  1. 15 13
      parsers/connections.py
  2. 19 2
      parsers/log.py
  3. 1 0
      services/fetch_data.py

+ 15 - 13
parsers/connections.py

@@ -84,23 +84,25 @@ def group_by_user(connections):
 
     for connection in connections:
         user = connection.get("username")
-
-        if user is None:
-            continue
         if not isinstance(user, str):
-            user = str(user)
-        user_normalized = user.strip().lower()
+            user = str(user) if user is not None else ""
+        user_normalized = user.strip().lower() if user else ""
+        if user_normalized == "n/a":
+            continue
         is_anonymous = not user_normalized or user_normalized in (
             indicator.lower()
             for indicator in ANONYMOUS_INDICATORS
             if indicator is not None
         )
-        if is_anonymous:
-            continue
-
-        if not grouped[user]["connections"]:
-            grouped[user]["client_ip"] = connection.get("client_ip", "Not found")
-
-        grouped[user]["connections"].append(connection)
-
+        if not is_anonymous:
+            key = user
+            client_ip = connection.get("client_ip", "Not found")
+        else:
+            raw_ip = connection.get("client_ip", "Not found")
+            ip_only = raw_ip.split(":")[0] if ":" in raw_ip else raw_ip
+            key = ip_only
+            client_ip = ip_only
+        if not grouped[key]["connections"]:
+            grouped[key]["client_ip"] = client_ip
+        grouped[key]["connections"].append(connection)
     return dict(grouped)

+ 19 - 2
parsers/log.py

@@ -108,8 +108,25 @@ def get_file_inode(filepath):
 def parse_log_line(line):
     if "|" in line:
         return parse_log_line_pipe_format(line)
-    else:
-        return parse_log_line_space_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 ("CONNECT", "GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE", "PATCH"):
+        try:
+            return {
+                "ip": parts[2],
+                "username": parts[2] if parts[2] != "-" else None,
+                "url": parts[6],
+                "response": int(parts[3].split("/")[-1]) if "/" in parts[3] and parts[3].split("/")[-1].isdigit() else 0,
+                "data_transmitted": int(parts[4]) if parts[4].isdigit() else 0,
+                "method": parts[5],
+                "status": parts[3],
+                "is_denied": "TCP_DENIED" in parts[3],
+            }
+        except Exception as e:
+            logger.error(f"Error parsing classic squid log line: {line.strip()} - {e}")
+            return None
+    # Si no es clásico, intenta el formato space
+    return parse_log_line_space_format(line)
 
 
 def parse_log_line_pipe_format(line):

+ 1 - 0
services/fetch_data.py

@@ -19,6 +19,7 @@ def fetch_squid_data():
             response = b""
             while chunk := s.recv(4096):
                 response += chunk
+        print(response.decode("utf-8"))  # Debugging line
         return response.decode("utf-8")
     except Exception as e:
         return str(e)