فهرست منبع

feat: implement ICAP service module for fetching ICAP stats and handling connections

Manuel 1 سال پیش
والد
کامیت
7b803d5b45
4فایلهای تغییر یافته به همراه118 افزوده شده و 4 حذف شده
  1. 31 4
      parsers/connections.py
  2. 13 0
      routes/stats_routes.py
  3. 36 0
      services/icap_service.py
  4. 38 0
      templates/partials/conexiones.html

+ 31 - 4
parsers/connections.py

@@ -8,12 +8,13 @@ REGEX_MAP = {
     "logType": re.compile(r"logType (.+)"),
     "start": re.compile(r"start ([\d.]+)"),
     "elapsed_time": re.compile(r"start .*?\(([\d.]+) seconds ago\)"),
-    "client_ip": re.compile(r"remote: ([\d.]+:\d+)"),  # IP del cliente
-    "proxy_local_ip": re.compile(r"local: ([\d.]+:\d+)"),  # IP del proxy
+    "client_ip": re.compile(r"remote: ([\d.]+:\d+)"),
+    "proxy_local_ip": re.compile(r"local: ([\d.]+:\d+)"),
     "fd_read": re.compile(r"read (\d+)"),
     "fd_wrote": re.compile(r"wrote (\d+)"),
     "nrequests": re.compile(r"nrequests: (\d+)"),
     "delay_pool": re.compile(r"delay_pool (\d+)"),
+    "out_size": re.compile(r"out\.size (\d+)"),
 }
 
 
@@ -26,7 +27,6 @@ def parse_raw_data(raw_data):
             connection = parse_connection_block(block)
             connections.append(connection)
         except Exception as e:
-            # Imprime un error pero permite que el script continúe
             print(f"Error parseando bloque: {e}\n{block[:100]}...")
 
     return connections
@@ -36,7 +36,14 @@ def parse_connection_block(block):
     conn = {}
 
     for key, regex in REGEX_MAP.items():
-        if key not in ["fd_read", "fd_wrote", "nrequests", "delay_pool", "fd_total"]:
+        if key not in [
+            "fd_read",
+            "fd_wrote",
+            "nrequests",
+            "delay_pool",
+            "fd_total",
+            "out_size",
+        ]:
             match = regex.search(block)
             conn[key] = match.group(1) if match else "N/A"
 
@@ -62,6 +69,21 @@ def parse_connection_block(block):
         if REGEX_MAP["delay_pool"].search(block)
         else "N/A"
     )
+
+    out_size_match = REGEX_MAP["out_size"].search(block)
+    conn["out_size"] = int(out_size_match.group(1)) if out_size_match else 0
+
+    elapsed_match = REGEX_MAP["elapsed_time"].search(block)
+    elapsed_time = float(elapsed_match.group(1)) if elapsed_match else 0
+    conn["elapsed_time"] = elapsed_time
+
+    if conn["out_size"] > 0 and elapsed_time > 0:
+        conn["bandwidth_bps"] = round((conn["out_size"] * 8) / elapsed_time, 2)
+        conn["bandwidth_kbps"] = round(conn["bandwidth_bps"] / 1000, 2)
+    else:
+        conn["bandwidth_bps"] = 0
+        conn["bandwidth_kbps"] = 0
+
     return conn
 
 
@@ -87,13 +109,16 @@ def group_by_user(connections):
         if not isinstance(user, str):
             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 not is_anonymous:
             key = user
             client_ip = connection.get("client_ip", "Not found")
@@ -102,7 +127,9 @@ def group_by_user(connections):
             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)

+ 13 - 0
routes/stats_routes.py

@@ -5,6 +5,7 @@ from threading import Lock
 
 from flask import Blueprint, render_template
 
+# from services.icap_service import fetch_cicap_stats
 from config import logger
 from parsers.cache import fetch_squid_cache_stats
 from services.metrics_service import MetricsService
@@ -72,6 +73,18 @@ def cache_stats_realtime():
         ), 500
 
 
+""" @stats_bp.route("/print_icap_service")
+def print_icap_service():
+    try:
+        print(fetch_cicap_stats())
+        print("--- END OF ICAP SERVICE MODULE ---")
+        return "ICAP service module content printed to console.", 200
+    except Exception as e:
+        print(f"Error printing icap_service.py: {e}")
+        return f"Error printing icap_service.py: {e}", 500
+ """
+
+
 def realtime_data_thread(socketio):
     global realtime_cache_stats, realtime_system_info
     import time

+ 36 - 0
services/icap_service.py

@@ -0,0 +1,36 @@
+import os
+import socket
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+ICAP_HOST = os.getenv("ICAP_HOST", os.getenv("SQUID_HOST"))
+ICAP_PORT = int(os.getenv("ICAP_PORT", 1344))
+
+
+def fetch_cicap_stats(host="10.34.8.15", port=1344):
+    http_req = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
+
+    # Construimos la solicitud ICAP completa
+    icap_req = (
+        f"REQMOD icap://{host}:{port}/info?view=text ICAP/1.0\r\n"
+        f"Host: {host}\r\n"
+        f"Allow: 204\r\n"
+        f"Encapsulated: req-hdr=0, null-body={len(http_req)}\r\n"
+        "\r\n"
+        f"{http_req}"
+    )
+
+    try:
+        with socket.create_connection((host, port), timeout=5) as s:
+            s.sendall(icap_req.encode())
+            resp = b""
+            while True:
+                chunk = s.recv(4096)
+                if not chunk:
+                    break
+                resp += chunk
+        return resp.decode("utf-8", errors="ignore")
+    except Exception as e:
+        return f"Error connecting to ICAP server: {e}"

+ 38 - 0
templates/partials/conexiones.html

@@ -231,6 +231,7 @@ valid_users.update({user: user_data}) %} {% endif %} {% endfor %}
               <span>{{ client_ip }}</span>
             </div>
 
+
             <div
               class="flex items-center text-sm text-gray-600"
               title="Conexiones totales de este usuario"
@@ -239,6 +240,26 @@ valid_users.update({user: user_data}) %} {% endif %} {% endfor %}
               <span>{{ connections|length }} conexiones</span>
             </div>
 
+            {# Total de velocidad del usuario #}
+            {% set user_bw = namespace(value=0) %}
+            {% for connection in connections %}
+              {% if connection.bandwidth_kbps is defined %}
+                {% set user_bw.value = user_bw.value + (connection.bandwidth_kbps|float) %}
+              {% endif %}
+            {% endfor %}
+            <div class="flex items-center text-sm text-gray-600" title="Total de velocidad del usuario">
+              <i class="fas fa-tachometer-alt mr-1.5 text-teal-500"></i>
+              <span>
+                {% if user_bw.value >= 1000000 %}
+                  {{ (user_bw.value / 1000000)|round(2) }} Gbps
+                {% elif user_bw.value >= 1000 %}
+                  {{ (user_bw.value / 1000)|round(2) }} Mbps
+                {% else %}
+                  {{ user_bw.value|round(2) }} kbps
+                {% endif %}
+              </span>
+            </div>
+
             {% set total_data = namespace(value=0) %} {% set total_requests =
             namespace(value=0) %} {% for connection in connections %} {% if
             connection.fd_total != "N/A" %} {% set total_data.value =
@@ -295,6 +316,11 @@ valid_users.update({user: user_data}) %} {% endif %} {% endfor %}
                 >
                   Datos
                 </th>
+                <th
+                  class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase"
+                >
+                  Velocidad
+                </th>
                 <th
                   class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase"
                 >
@@ -343,6 +369,18 @@ valid_users.update({user: user_data}) %} {% endif %} {% endfor %}
                   {% if connection.fd_total != "N/A" %}{{ (connection.fd_total /
                   1024 / 1024)|round(2) }} MB {% else %}N/A{% endif %}
                 </td>
+                <td class="px-4 py-3 whitespace-nowrap text-sm">
+                  {% if connection.bandwidth_kbps is defined %}
+                    {% set bw = connection.bandwidth_kbps|float %}
+                    {% if bw >= 1000000 %}
+                      {{ (bw / 1000000)|round(2) }} Gbps
+                    {% elif bw >= 1000 %}
+                      {{ (bw / 1000)|round(2) }} Mbps
+                    {% else %}
+                      {{ bw|round(2) }} kbps
+                    {% endif %}
+                  {% else %}0 kbps{% endif %}
+                </td>
                 <td class="px-4 py-3 whitespace-nowrap">
                   {% if connection.delay_pool != "N/A" %} {% set pool =
                   connection.delay_pool|string %}