Parcourir la source

feat: Implement system metrics tracking and optimize data collection intervals

Manuel il y a 1 an
Parent
commit
56e81b8f9e
6 fichiers modifiés avec 488 ajouts et 130 suppressions
  1. 73 32
      app.py
  2. 8 54
      database/database.py
  3. 207 0
      services/metrics_service.py
  4. 37 17
      services/system_info.py
  5. 99 27
      templates/components/cache_stats.html
  6. 64 0
      test_optimization.py

+ 73 - 32
app.py

@@ -1,11 +1,11 @@
 from flask import Blueprint
-from datetime import date, timezone
+from datetime import date
 from services.fetch_data_logs import get_metrics_for_date
 from flask import Flask, render_template, request, redirect, jsonify
 from flask_socketio import SocketIO
 from flask_apscheduler import APScheduler
 from database.database import (
-    get_session, get_dynamic_models, get_dynamic_metrics_model
+    get_session, get_dynamic_models
 )
 from parsers.connections import parse_raw_data, group_by_user
 from services.fetch_data import fetch_squid_data
@@ -29,6 +29,7 @@ from services.auditoria_service import (
     get_daily_activity 
 )
 from services.get_reports import get_important_metrics
+from services.metrics_service import MetricsService
 from utils.colors import color_map
 from utils.updateSquid import update_squid
 from utils.updateSquidStats import updateSquidStats
@@ -149,6 +150,17 @@ def init_scheduler():
     else:
         process_logs(log_file)
 
+@scheduler.task('interval', id='cleanup_metrics', hours=1, misfire_grace_time=3600)
+def cleanup_old_metrics():
+    try:
+        success = MetricsService.cleanup_old_metrics()
+        if success:
+            logger.info("Limpieza de métricas antiguas completada exitosamente")
+        else:
+            logger.warning("Error durante la limpieza de métricas antiguas")
+    except Exception as e:
+        logger.error(f"Error en tarea de limpieza de métricas: {e}")
+
 @app.route('/get-logs-by-date', methods=['POST'])
 def get_logs_by_date():
     db = None
@@ -311,6 +323,8 @@ socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
 def realtime_data_thread():
     global realtime_cache_stats, realtime_system_info
     import time
+    data_collection_counter = 0
+    
     while True:
         try:
             cache_data = fetch_squid_cache_stats()
@@ -326,9 +340,41 @@ def realtime_data_thread():
                 'python_version': sys.version.split()[0],
                 'squid_version': get_squid_version(),
                 'timezone': get_timezone(),
-                'local_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+                'local_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
+                'timestamp_utc': datetime.now().isoformat()
             }
             network_stats = get_network_stats()
+            
+            # Guardar métricas en la base de datos solo cada 60 segundos (cada 4 iteraciones)
+            data_collection_counter += 1
+            if data_collection_counter % 4 == 0:  # Solo cada 4 iteraciones (60 segundos)
+                ram_info = get_ram_info()
+                swap_info = get_swap_info()
+                cpu_info = get_cpu_info()
+                
+                # Convertir información de RAM y SWAP a bytes para guardar en BD
+                def size_to_bytes(size_str):
+                    if not size_str:
+                        return 0
+                    parts = size_str.strip().split()
+                    if len(parts) != 2:
+                        return 0
+                    value, unit = float(parts[0]), parts[1].upper()
+                    multipliers = {'B': 1, 'KB': 1024, 'MB': 1024**2, 'GB': 1024**3, 'TB': 1024**4}
+                    return int(value * multipliers.get(unit, 1))
+                
+                ram_bytes = size_to_bytes(ram_info.get('used', '0 B'))
+                swap_bytes = size_to_bytes(swap_info.get('used', '0 B'))
+                
+                # Guardar en base de datos
+                MetricsService.save_system_metrics(
+                    cpu_usage=cpu_info.get('usage', '0%'),
+                    ram_usage_bytes=ram_bytes,
+                    swap_usage_bytes=swap_bytes,
+                    net_sent_bytes_sec=network_stats.get('bytes_sent_per_sec', 0) if network_stats else 0,
+                    net_recv_bytes_sec=network_stats.get('bytes_recv_per_sec', 0) if network_stats else 0
+                )
+            
             with realtime_data_lock:
                 realtime_cache_stats = cache_stats
                 realtime_system_info = system_info
@@ -339,7 +385,7 @@ def realtime_data_thread():
             })
         except Exception as e:
             logger.error(f"Error en hilo de datos en tiempo real: {str(e)}")
-        time.sleep(5)
+        time.sleep(15)  # Actualizar cada 15 segundos en lugar de 5
 
 @app.after_request
 def set_response_headers(response):
@@ -391,38 +437,33 @@ def cache_stats_realtime():
 
 @app.route('/api/metrics/today')
 def get_today_metrics():
-    db = None
+    """Obtiene métricas del día actual usando el nuevo servicio"""
     try:
-        date_suffix = datetime.now().strftime('%Y%m%d')
-        MetricsModel = get_dynamic_metrics_model(date_suffix)
-        
-        if not MetricsModel:
-            logger.warning(f"No se encontró el modelo de métricas para {date_suffix}")
-            return jsonify([])
-
-        db = get_session()
-        metrics = db.query(MetricsModel).order_by(MetricsModel.timestamp.asc()).all()
+        results = MetricsService.get_metrics_today()
+        return jsonify(results)
+    except Exception as e:
+        logger.error(f"Error al obtener métricas del día: {e}")
+        return jsonify([])
 
-        results = []
-        for m in metrics:
-            aware_timestamp = m.timestamp.replace(tzinfo=timezone.utc)
-            
-            results.append({
-                "timestamp": aware_timestamp.isoformat(),
-                "cpu_usage": m.cpu_usage,
-                "ram_usage_bytes": m.ram_usage_bytes,
-                "swap_usage_bytes": m.swap_usage_bytes,
-                "net_sent_bytes_sec": m.net_sent_bytes_sec,
-                "net_recv_bytes_sec": m.net_recv_bytes_sec,
-            })
-            
+@app.route('/api/metrics/24hours')
+def get_24hours_metrics():
+    """Obtiene métricas de las últimas 24 horas"""
+    try:
+        results = MetricsService.get_metrics_last_24_hours()
         return jsonify(results)
     except Exception as e:
-        logger.error(f"Error en API de métricas: {e}", exc_info=True)
-        return jsonify({"error": "No se pudieron obtener las métricas"}), 500
-    finally:
-        if db:
-            db.close()
+        logger.error(f"Error al obtener métricas de 24 horas: {e}")
+        return jsonify([])
+
+@app.route('/api/metrics/latest')
+def get_latest_metric():
+    """Obtiene la métrica más reciente"""
+    try:
+        result = MetricsService.get_latest_metric()
+        return jsonify(result) if result else jsonify({})
+    except Exception as e:
+        logger.error(f"Error al obtener la métrica más reciente: {e}")
+        return jsonify({})
 
 @app.route('/auditoria', methods=['GET'])
 def auditoria_logs():

+ 8 - 54
database/database.py

@@ -70,15 +70,16 @@ class DeniedLog(Base):
     data_transmitted = Column(BigInteger, default=0)
     created_at = Column(DateTime, default=datetime.now)
 
-class Metrics(DailyBase):
-    __tablename__ = "metrics_base"
+class SystemMetrics(Base):
+    __tablename__ = "system_metrics"
     id = Column(Integer, primary_key=True)
-    timestamp = Column(DateTime, default=datetime.now, index=True)
-    cpu_usage = Column(Integer, nullable=False)
+    timestamp = Column(DateTime, default=datetime.now, nullable=False)
+    cpu_usage = Column(String(10), nullable=False)  # Ejemplo: "25.5%"
     ram_usage_bytes = Column(BigInteger, nullable=False)
     swap_usage_bytes = Column(BigInteger, nullable=False)
     net_sent_bytes_sec = Column(BigInteger, nullable=False)
     net_recv_bytes_sec = Column(BigInteger, nullable=False)
+    created_at = Column(DateTime, default=datetime.now)
 
 def get_database_url() -> str:
     db_type = os.getenv("DATABASE_TYPE", "SQLITE").upper()
@@ -116,20 +117,14 @@ def table_exists(engine, table_name: str) -> bool:
     inspector = inspect(engine)
     return inspector.has_table(table_name)
 
-def get_metrics_table_name(date_suffix: str = None) -> str:
-    """Devuelve el nombre de la tabla de métricas para un sufijo de fecha dado."""
-    if date_suffix is None:
-        date_suffix = get_table_suffix()
-    return f"metrics_{date_suffix}"
-
 def create_dynamic_tables(engine, date_suffix: str = None):
     """Crea las tablas principales y diarias si no existen."""
     LogMetadata.__table__.create(engine, checkfirst=True)
     DeniedLog.__table__.create(engine, checkfirst=True)
+    SystemMetrics.__table__.create(engine, checkfirst=True)  # Crear tabla de métricas del sistema
     
     # Si no se provee un sufijo, se usan las tablas del día actual.
     user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
-    metrics_table_name = get_metrics_table_name(date_suffix)
     
     # Se genera un logger específico para la fecha, para evitar mensajes duplicados.
     creation_logger = logging.getLogger(f"TableCreation_{date_suffix or 'today'}")
@@ -140,8 +135,8 @@ def create_dynamic_tables(engine, date_suffix: str = None):
         handler.setFormatter(formatter)
         creation_logger.addHandler(handler)
 
-    if not table_exists(engine, user_table_name) or not table_exists(engine, log_table_name) or not table_exists(engine, metrics_table_name):
-        creation_logger.info(f"Creando tablas dinámicas para la fecha del sufijo '{date_suffix}': {user_table_name}, {log_table_name}, {metrics_table_name}")
+    if not table_exists(engine, user_table_name) or not table_exists(engine, log_table_name):
+        creation_logger.info(f"Creando tablas dinámicas para la fecha del sufijo '{date_suffix}': {user_table_name}, {log_table_name}")
         DynamicBase = declarative_base()
 
         class DynamicUser(DynamicBase):
@@ -160,16 +155,6 @@ def create_dynamic_tables(engine, date_suffix: str = None):
             request_count = Column(Integer, default=1)
             data_transmitted = Column(BigInteger, default=0)
             created_at = Column(DateTime, default=datetime.now)
-
-        class DynamicMetrics(DynamicBase):
-            __tablename__ = metrics_table_name
-            id = Column(Integer, primary_key=True)
-            timestamp = Column(DateTime, default=datetime.now, index=True)
-            cpu_usage = Column(Integer, nullable=False)
-            ram_usage_bytes = Column(BigInteger, nullable=False)
-            swap_usage_bytes = Column(BigInteger, nullable=False)
-            net_sent_bytes_sec = Column(BigInteger, nullable=False)
-            net_recv_bytes_sec = Column(BigInteger, nullable=False)
             
         DynamicBase.metadata.create_all(engine, checkfirst=True)
 
@@ -179,37 +164,6 @@ def get_dynamic_table_names(date_suffix: str = None) -> Tuple[str, str]:
         date_suffix = get_table_suffix()
     return f"user_{date_suffix}", f"log_{date_suffix}"
 
-def get_dynamic_metrics_model(date_suffix: str):
-    """Devuelve el modelo dinámico de métricas para el sufijo de fecha dado."""
-    cache_key = f"metrics_{date_suffix}"
-    if cache_key in dynamic_model_cache:
-        return dynamic_model_cache[cache_key]
-
-    engine = get_engine()
-    metrics_table_name = get_metrics_table_name(date_suffix)
-
-    if not table_exists(engine, metrics_table_name):
-        logger.warning(f"La tabla de métricas '{metrics_table_name}' no existe. Intentando recrearla...")
-        create_dynamic_tables(engine, date_suffix=date_suffix)
-        if not table_exists(engine, metrics_table_name):
-             logger.error(f"No se pudo crear o encontrar la tabla de métricas: {metrics_table_name}")
-             return None
-
-    DynamicBase = declarative_base()
-    class DynamicMetrics(DynamicBase):
-        __tablename__ = metrics_table_name
-        __table_args__ = {'extend_existing': True}
-        id = Column(Integer, primary_key=True)
-        timestamp = Column(DateTime, default=datetime.now, index=True)
-        cpu_usage = Column(Integer, nullable=False)
-        ram_usage_bytes = Column(BigInteger, nullable=False)
-        swap_usage_bytes = Column(BigInteger, nullable=False)
-        net_sent_bytes_sec = Column(BigInteger, nullable=False)
-        net_recv_bytes_sec = Column(BigInteger, nullable=False)
-
-    dynamic_model_cache[cache_key] = DynamicMetrics
-    return DynamicMetrics
-
 def get_dynamic_models(date_suffix: str):
     """Devuelve modelos dinámicos de usuario y log para el sufijo de fecha dado."""
     cache_key = f"user_log_{date_suffix}"

+ 207 - 0
services/metrics_service.py

@@ -0,0 +1,207 @@
+import logging
+from datetime import datetime, timedelta
+from typing import List, Dict, Any, Optional
+from sqlalchemy import desc
+from database.database import get_session, SystemMetrics
+
+logger = logging.getLogger(__name__)
+
+class MetricsService:
+    @staticmethod
+    def save_system_metrics(
+        cpu_usage: str,
+        ram_usage_bytes: int,
+        swap_usage_bytes: int,
+        net_sent_bytes_sec: int,
+        net_recv_bytes_sec: int
+    ) -> bool:
+        try:
+            session = get_session()
+            
+            # Crear nueva métrica con timestamp local
+            local_tz = datetime.now().astimezone().tzinfo
+            metric = SystemMetrics(
+                timestamp=datetime.now(local_tz),
+                cpu_usage=cpu_usage,
+                ram_usage_bytes=ram_usage_bytes,
+                swap_usage_bytes=swap_usage_bytes,
+                net_sent_bytes_sec=net_sent_bytes_sec,
+                net_recv_bytes_sec=net_recv_bytes_sec
+            )
+            
+            session.add(metric)
+            session.commit()
+            session.close()
+            
+            # Limpiar métricas antiguas (más de 24 horas)
+            MetricsService.cleanup_old_metrics()
+            
+            logger.info("Métricas del sistema guardadas correctamente")
+            return True
+            
+        except Exception as e:
+            logger.error(f"Error al guardar métricas del sistema: {e}")
+            if session:
+                session.rollback()
+                session.close()
+            return False
+    
+    @staticmethod
+    def get_metrics_last_24_hours() -> List[Dict[str, Any]]:
+        try:
+            session = get_session()
+            
+            # Calcular timestamp de 24 horas atrás con zona horaria local
+            local_tz = datetime.now().astimezone().tzinfo
+            twenty_four_hours_ago = datetime.now(local_tz) - timedelta(hours=24)
+            
+            # Consultar métricas de las últimas 24 horas
+            metrics = session.query(SystemMetrics)\
+                .filter(SystemMetrics.timestamp >= twenty_four_hours_ago)\
+                .order_by(SystemMetrics.timestamp)\
+                .all()
+            
+            session.close()
+            
+            # Convertir a lista de diccionarios con timestamps en zona horaria local
+            result = []
+            for metric in metrics:
+                # Asegurar que el timestamp tenga información de zona horaria
+                if metric.timestamp.tzinfo is None:
+                    # Si no tiene zona horaria, asumir que es local
+                    local_timestamp = metric.timestamp.replace(tzinfo=local_tz)
+                else:
+                    local_timestamp = metric.timestamp
+                
+                result.append({
+                    'id': metric.id,
+                    'timestamp': local_timestamp.isoformat(),
+                    'cpu_usage': metric.cpu_usage,
+                    'ram_usage_bytes': metric.ram_usage_bytes,
+                    'swap_usage_bytes': metric.swap_usage_bytes,
+                    'net_sent_bytes_sec': metric.net_sent_bytes_sec,
+                    'net_recv_bytes_sec': metric.net_recv_bytes_sec
+                })
+            
+            logger.info(f"Recuperadas {len(result)} métricas de las últimas 24 horas")
+            return result
+            
+        except Exception as e:
+            logger.error(f"Error al obtener métricas de las últimas 24 horas: {e}")
+            if session:
+                session.close()
+            return []
+    
+    @staticmethod
+    def get_metrics_today() -> List[Dict[str, Any]]:
+        try:
+            session = get_session()
+            
+            # Obtener inicio del día actual con zona horaria local
+            local_tz = datetime.now().astimezone().tzinfo
+            today_start = datetime.now(local_tz).replace(hour=0, minute=0, second=0, microsecond=0)
+            
+            # Consultar métricas del día actual
+            metrics = session.query(SystemMetrics)\
+                .filter(SystemMetrics.timestamp >= today_start)\
+                .order_by(SystemMetrics.timestamp)\
+                .all()
+            
+            session.close()
+            
+            # Convertir a lista de diccionarios con timestamps en zona horaria local
+            result = []
+            for metric in metrics:
+                # Asegurar que el timestamp tenga información de zona horaria
+                if metric.timestamp.tzinfo is None:
+                    # Si no tiene zona horaria, asumir que es local
+                    local_timestamp = metric.timestamp.replace(tzinfo=local_tz)
+                else:
+                    local_timestamp = metric.timestamp
+                
+                result.append({
+                    'id': metric.id,
+                    'timestamp': local_timestamp.isoformat(),
+                    'cpu_usage': metric.cpu_usage,
+                    'ram_usage_bytes': metric.ram_usage_bytes,
+                    'swap_usage_bytes': metric.swap_usage_bytes,
+                    'net_sent_bytes_sec': metric.net_sent_bytes_sec,
+                    'net_recv_bytes_sec': metric.net_recv_bytes_sec
+                })
+            
+            logger.info(f"Recuperadas {len(result)} métricas del día actual")
+            return result
+            
+        except Exception as e:
+            logger.error(f"Error al obtener métricas del día actual: {e}")
+            if session:
+                session.close()
+            return []
+    
+    @staticmethod
+    def cleanup_old_metrics() -> bool:
+        try:
+            session = get_session()
+            
+            # Calcular timestamp de 24 horas atrás con zona horaria local
+            local_tz = datetime.now().astimezone().tzinfo
+            twenty_four_hours_ago = datetime.now(local_tz) - timedelta(hours=24)
+            
+            # Eliminar métricas antiguas
+            deleted_count = session.query(SystemMetrics)\
+                .filter(SystemMetrics.timestamp < twenty_four_hours_ago)\
+                .delete()
+            
+            session.commit()
+            session.close()
+            
+            if deleted_count > 0:
+                logger.info(f"Eliminadas {deleted_count} métricas antiguas")
+            
+            return True
+            
+        except Exception as e:
+            logger.error(f"Error al limpiar métricas antiguas: {e}")
+            if session:
+                session.rollback()
+                session.close()
+            return False
+    
+    @staticmethod
+    def get_latest_metric() -> Optional[Dict[str, Any]]:
+        try:
+            session = get_session()
+            
+            # Obtener la métrica más reciente
+            metric = session.query(SystemMetrics)\
+                .order_by(desc(SystemMetrics.timestamp))\
+                .first()
+            
+            session.close()
+            
+            if metric:
+                # Asegurar que el timestamp tenga información de zona horaria
+                local_tz = datetime.now().astimezone().tzinfo
+                if metric.timestamp.tzinfo is None:
+                    # Si no tiene zona horaria, asumir que es local
+                    local_timestamp = metric.timestamp.replace(tzinfo=local_tz)
+                else:
+                    local_timestamp = metric.timestamp
+                
+                return {
+                    'id': metric.id,
+                    'timestamp': local_timestamp.isoformat(),
+                    'cpu_usage': metric.cpu_usage,
+                    'ram_usage_bytes': metric.ram_usage_bytes,
+                    'swap_usage_bytes': metric.swap_usage_bytes,
+                    'net_sent_bytes_sec': metric.net_sent_bytes_sec,
+                    'net_recv_bytes_sec': metric.net_recv_bytes_sec
+                }
+            
+            return None
+            
+        except Exception as e:
+            logger.error(f"Error al obtener la métrica más reciente: {e}")
+            if session:
+                session.close()
+            return None

+ 37 - 17
services/system_info.py

@@ -140,37 +140,57 @@ def get_squid_version():
     except Exception as e:
         return f"Error: {str(e)}"
 
+# Variables globales para el cálculo de estadísticas de red
+_last_net_io = None
+_last_net_time = None
+
 def get_network_stats():
     """Obtiene estadísticas de uso de red (ancho de banda)"""
+    global _last_net_io, _last_net_time
+    
     try:
-        net_io_1 = psutil.net_io_counters()
-        # Usar asyncio.sleep si se llama desde una función async, si no, usar time.sleep
-        try:
-            loop = asyncio.get_running_loop()
-            # Si hay un loop, usar asyncio.sleep
-            async def async_sleep():
-                await asyncio.sleep(1)
-            loop.run_until_complete(async_sleep())
-        except RuntimeError:
-            # Si no hay loop, usar time.sleep
+        current_time = time.time()
+        current_net_io = psutil.net_io_counters()
+        
+        # Si es la primera vez, inicializar y esperar 1 segundo
+        if _last_net_io is None:
+            _last_net_io = current_net_io
+            _last_net_time = current_time
             time.sleep(1)
-        net_io_2 = psutil.net_io_counters()
-        bytes_sent_per_sec = net_io_2.bytes_sent - net_io_1.bytes_sent
-        bytes_recv_per_sec = net_io_2.bytes_recv - net_io_1.bytes_recv
+            current_time = time.time()
+            current_net_io = psutil.net_io_counters()
+        
+        # Calcular tiempo transcurrido
+        time_diff = current_time - _last_net_time
+        
+        # Calcular bytes por segundo
+        bytes_sent_per_sec = int((current_net_io.bytes_sent - _last_net_io.bytes_sent) / time_diff)
+        bytes_recv_per_sec = int((current_net_io.bytes_recv - _last_net_io.bytes_recv) / time_diff)
+        
+        # Convertir a Mbps
         up_mbps = round((bytes_sent_per_sec * 8) / 1_000_000, 2)
         down_mbps = round((bytes_recv_per_sec * 8) / 1_000_000, 2)
+        
+        # Actualizar valores para la próxima medición
+        _last_net_io = current_net_io
+        _last_net_time = current_time
+        
         return {
             'up_mbps': up_mbps,
             'down_mbps': down_mbps,
-            'bytes_sent_total': net_io_2.bytes_sent,
-            'bytes_recv_total': net_io_2.bytes_recv,
-            'packets_sent': net_io_2.packets_sent,
-            'packets_recv': net_io_2.packets_recv
+            'bytes_sent_per_sec': bytes_sent_per_sec,
+            'bytes_recv_per_sec': bytes_recv_per_sec,
+            'bytes_sent_total': current_net_io.bytes_sent,
+            'bytes_recv_total': current_net_io.bytes_recv,
+            'packets_sent': current_net_io.packets_sent,
+            'packets_recv': current_net_io.packets_recv
         }
     except Exception as e:
         return {
             'up_mbps': 0.0,
             'down_mbps': 0.0,
+            'bytes_sent_per_sec': 0,
+            'bytes_recv_per_sec': 0,
             'bytes_sent_total': 0,
             'bytes_recv_total': 0,
             'packets_sent': 0,

+ 99 - 27
templates/components/cache_stats.html

@@ -47,6 +47,10 @@
         @keyframes underline { from { transform: scaleX(0); } to { transform: scaleX(1); } }
         .value-change { animation: pulse 1s; }
         @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
+        .time-range-btn { transition: all 0.3s ease; }
+        .time-range-btn.active { background-color: white; color: #2563eb; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); }
+        .time-range-btn:not(.active) { background-color: transparent; color: #6b7280; }
+        .time-range-btn:not(.active):hover { color: #2563eb; }
     </style>
 </head>
 
@@ -129,6 +133,13 @@
             </section>
 
             <section class="bg-white rounded-xl shadow-lg p-6 mb-12">
+                <div class="flex items-center justify-between mb-6">
+                    <h2 class="text-xl font-bold text-gray-800">Gráficas del Sistema</h2>
+                    <div class="flex bg-gray-100 rounded-lg p-1">
+                        <button id="todayBtn" class="time-range-btn active px-4 py-2 rounded-md text-sm font-medium text-blue-600 bg-white shadow">Hoy</button>
+                        <button id="24hoursBtn" class="time-range-btn px-4 py-2 rounded-md text-sm font-medium text-gray-500 hover:text-blue-600">24 Horas</button>
+                    </div>
+                </div>
                 <div class="flex border-b mb-6">
                     <button class="tab-btn active py-3 px-6 font-medium border-b-2 border-blue-600 text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100">CPU</button>
                     <button class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100">RAM</button>
@@ -179,9 +190,19 @@
         Chart.register(ChartDataLabels);
 
         let maxRamBytes = 0, maxSwapBytes = 0;
-        const historySize = 720; 
+        const historySize = 240; // Reducido de 720 a 240 (4 horas de datos con intervalos de 1 minuto)
+        let liveDataCounter = 0; // Contador para manejar datos en vivo 
         
         // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
+        function getLocalTimeString() {
+            const now = new Date();
+            let hours = now.getHours();
+            const minutes = now.getMinutes().toString().padStart(2, '0');
+            const ampm = hours >= 12 ? 'PM' : 'AM';
+            hours = hours % 12 || 12;
+            return `${hours}:${minutes} ${ampm}`;
+        }
+        
         function formatTime(date) {
             let hours = date.getHours();
             const minutes = date.getMinutes().toString().padStart(2, '0');
@@ -235,15 +256,29 @@
         function updateCard(statId, value, isSize = false) { const element = document.querySelector(`[data-stat="${statId}"]`); if (!element) return; let formattedValue = value; if (isSize) { const bytes = parseFloat(value); formattedValue = (bytes / (1024 * 1024) < 1) ? `${Math.round(bytes / 1024)} MB` : `${(bytes / (1024 * 1024)).toFixed(2)} GB`; } if (element.textContent !== formattedValue.toString()) { element.textContent = formattedValue; element.classList.add('value-change'); setTimeout(() => element.classList.remove('value-change'), 1000); } }
         function updateCacheStats(stats) { updateCard('entradas_almacenadas', stats.store_entries); updateCard('uso_de_capacidad', stats.capacity_used); updateCard('espacio_total', stats.fs_space_total, true); updateCard('espacio_usado', stats.fs_space_used, true); updateCard('eliminación', stats.removal_policy); updateCard('edad_lru', `${stats.lru_age_days} días`); }
 
-        // --- AÑADIDO: Carga de datos históricos desde la API ---
-        function loadHistoricData() {
-            fetch('/api/metrics/today')
+        // --- AÑADIDO: Carga de datos históricos desde la API con sampling optimizado ---
+        function loadHistoricData(endpoint = '/api/metrics/24hours') {
+            fetch(endpoint)
                 .then(response => response.json())
                 .then(data => {
-                    if (!data || data.length === 0) { console.log("No hay historial de métricas para hoy."); return; }
+                    if (!data || data.length === 0) { 
+                        console.log(`No hay historial de métricas para el endpoint: ${endpoint}`); 
+                        return; 
+                    }
+                    
+                    // Implementar sampling inteligente para evitar sobrecarga
+                    let sampledData = data;
+                    if (data.length > 288) { // Si hay más de 288 puntos (4.8 horas con intervalos de 1 minuto)
+                        const sampleRate = Math.ceil(data.length / 288);
+                        sampledData = data.filter((_, index) => index % sampleRate === 0);
+                        console.log(`Aplicado sampling: ${data.length} → ${sampledData.length} puntos`);
+                    }
+                    
                     const labels = [], cpuData = [], ramData = [], swapData = [], netUpData = [], netDownData = [];
-                    data.forEach(metric => {
-                        labels.push(formatTime(new Date(metric.timestamp)));
+                    sampledData.forEach(metric => {
+                        // Crear fecha local desde el timestamp del servidor (ya incluye timezone)
+                        const localDate = new Date(metric.timestamp);
+                        labels.push(formatTime(localDate));
                         cpuData.push(parseFloat(metric.cpu_usage).toFixed(1));
                         ramData.push(metric.ram_usage_bytes);
                         swapData.push(metric.swap_usage_bytes);
@@ -266,34 +301,66 @@
                 .catch(error => console.error('Error al cargar historial de métricas:', error));
         }
 
+        // --- AÑADIDO: Funcionalidad para alternar entre vistas de tiempo ---
+        function setupTimeRangeButtons() {
+            const todayBtn = document.getElementById('todayBtn');
+            const hoursBtn = document.getElementById('24hoursBtn');
+            
+            todayBtn.addEventListener('click', () => {
+                setActiveTimeRange(todayBtn, hoursBtn);
+                loadHistoricData('/api/metrics/today');
+            });
+            
+            hoursBtn.addEventListener('click', () => {
+                setActiveTimeRange(hoursBtn, todayBtn);
+                loadHistoricData('/api/metrics/24hours');
+            });
+        }
+        
+        function setActiveTimeRange(activeBtn, inactiveBtn) {
+            activeBtn.classList.add('active');
+            activeBtn.classList.remove('text-gray-500');
+            activeBtn.classList.add('text-blue-600', 'bg-white', 'shadow');
+            
+            inactiveBtn.classList.remove('active');
+            inactiveBtn.classList.add('text-gray-500');
+            inactiveBtn.classList.remove('text-blue-600', 'bg-white', 'shadow');
+        }
+
         const socket = io();
         socket.on('system_update', function (data) {
             updateRings(data.system_info);
             updateSystemInfo(data.system_info);
             updateCacheStats(data.cache_stats);
 
-            // --- MODIFICADO: Lógica para añadir datos en vivo a las gráficas ---
-            function appendLiveData(chart, label, newData) {
-                chart.data.labels.push(label);
-                chart.data.datasets.forEach((dataset, index) => {
-                    const dataPoint = Array.isArray(newData) ? newData[index] : newData;
-                    dataset.data.push(dataPoint);
-                });
-                while (chart.data.labels.length > historySize) {
-                    chart.data.labels.shift();
-                    chart.data.datasets.forEach(dataset => dataset.data.shift());
+            // Incrementar contador de datos en vivo
+            liveDataCounter++;
+            
+            // Solo actualizar gráficas cada 4 actualizaciones (1 minuto) para evitar sobrecarga
+            if (liveDataCounter % 4 === 0) {
+                // --- MODIFICADO: Lógica para añadir datos en vivo a las gráficas ---
+                function appendLiveData(chart, label, newData) {
+                    chart.data.labels.push(label);
+                    chart.data.datasets.forEach((dataset, index) => {
+                        const dataPoint = Array.isArray(newData) ? newData[index] : newData;
+                        dataset.data.push(dataPoint);
+                    });
+                    while (chart.data.labels.length > historySize) {
+                        chart.data.labels.shift();
+                        chart.data.datasets.forEach(dataset => dataset.data.shift());
+                    }
+                    chart.update('none');
                 }
-                chart.update('none');
-            }
 
-            // --- CORREGIDO: Se usa el timestamp del servidor para la etiqueta en vivo ---
-            const newLabel = formatTime(new Date(data.system_info.timestamp_utc));
+                // --- CORREGIDO: Se usa la hora local del cliente para la etiqueta en vivo ---
+                const newLabel = getLocalTimeString();
 
-            appendLiveData(cpuChart, newLabel, parseFloat(data.system_info.cpu.usage.replace('%','')));
-            appendLiveData(ramChart, newLabel, sizeToBytes(data.system_info.ram.used));
-            appendLiveData(swapChart, newLabel, sizeToBytes(data.system_info.swap.used));
-            if (data.network_stats) {
-                appendLiveData(networkChart, newLabel, [ data.network_stats.up_mbps, data.network_stats.down_mbps ]);
+                appendLiveData(cpuChart, newLabel, parseFloat(data.system_info.cpu.usage.replace('%','')));
+                appendLiveData(ramChart, newLabel, sizeToBytes(data.system_info.ram.used));
+                appendLiveData(swapChart, newLabel, sizeToBytes(data.system_info.swap.used));
+                if (data.network_stats) {
+                    appendLiveData(networkChart, newLabel, [ data.network_stats.up_mbps, data.network_stats.down_mbps ]);
+                }
             }
         });
 
@@ -307,7 +374,12 @@
                 ram: { used: "{{ system_info.ram.used }}", percent: "{{ system_info.ram.percent }}" },
                 swap: { used: "{{ system_info.swap.used }}", percent: "{{ system_info.swap.percent }}" }
             });
-            loadHistoricData();
+            
+            // Inicializar botones de rango de tiempo
+            setupTimeRangeButtons();
+            
+            // Cargar datos históricos (por defecto 24 horas)
+            loadHistoricData('/api/metrics/24hours');
         });
     </script>
 </body>

+ 64 - 0
test_optimization.py

@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""
+Script para probar las optimizaciones de intervalos de recolección de datos.
+"""
+
+import time
+from datetime import datetime
+
+def test_intervals():
+    """Simula los nuevos intervalos de recolección de datos"""
+    print("🧪 Probando nuevos intervalos de recolección de datos")
+    print("=" * 60)
+    
+    # Simular el comportamiento del nuevo sistema
+    data_collection_counter = 0
+    
+    print("⏱️  Intervalos configurados:")
+    print("   • WebSocket (tiempo real): 15 segundos")
+    print("   • Base de datos: 60 segundos (cada 4 actualizaciones)")
+    print("   • Gráficas en vivo: 60 segundos (cada 4 actualizaciones)")
+    print("   • Historial: Sampling inteligente para >288 puntos")
+    print()
+    
+    # Calcular métricas de rendimiento
+    old_websocket_per_hour = 60 * 60 / 5  # 720 actualizaciones por hora
+    new_websocket_per_hour = 60 * 60 / 15  # 240 actualizaciones por hora
+    
+    old_db_per_day = 24 * 60 * 60 / 5  # 17,280 inserciones por día
+    new_db_per_day = 24 * 60 * 60 / 60  # 1,440 inserciones por día
+    
+    print("📊 Mejoras de rendimiento:")
+    print(f"   • WebSocket: {old_websocket_per_hour:.0f} → {new_websocket_per_hour:.0f} mensajes/hora ({((old_websocket_per_hour - new_websocket_per_hour) / old_websocket_per_hour * 100):.1f}% menos)")
+    print(f"   • Base de datos: {old_db_per_day:.0f} → {new_db_per_day:.0f} inserciones/día ({((old_db_per_day - new_db_per_day) / old_db_per_day * 100):.1f}% menos)")
+    print("   • Gráficas: Misma reducción + sampling inteligente")
+    print()
+    
+    # Simular 5 iteraciones para mostrar el comportamiento
+    print("🔄 Simulando comportamiento del sistema (5 iteraciones de 15s):")
+    print("   [R] = Tiempo Real  [BD] = Base de Datos  [G] = Gráficas")
+    print()
+    
+    for i in range(1, 6):
+        data_collection_counter += 1
+        current_time = datetime.now().strftime("%H:%M:%S")
+        
+        actions = ["[R]"]  # Siempre hay actualización en tiempo real
+        
+        if data_collection_counter % 4 == 0:
+            actions.extend(["[BD]", "[G]"])
+        
+        print(f"   {current_time} - Iteración {i}: {' '.join(actions)}")
+        
+        if i < 5:  # No esperar en la última iteración
+            time.sleep(1)  # Simular con 1 segundo en lugar de 15 para la demo
+    
+    print()
+    print("✅ Test completado. Los nuevos intervalos están optimizados para:")
+    print("   • Menor carga del servidor")
+    print("   • Menor uso de base de datos")
+    print("   • Gráficas más fluidas")
+    print("   • Mejor experiencia de usuario")
+
+if __name__ == "__main__":
+    test_intervals()