""" Enhanced system resource monitoring with detailed metrics and thresholds. Provides comprehensive system health monitoring beyond basic metrics. """ import asyncio import logging from datetime import datetime, timedelta from typing import Dict, List, Optional, Any from dataclasses import dataclass import json # Optional dependencies try: import psutil PSUTIL_AVAILABLE = True except ImportError: PSUTIL_AVAILABLE = False try: import shutil SHUTIL_AVAILABLE = True except ImportError: SHUTIL_AVAILABLE = False from .config import settings from .monitoring import monitoring_system, get_logger logger = get_logger(__name__) @dataclass class SystemThresholds: """System resource thresholds for monitoring.""" cpu_warning: float = 70.0 cpu_critical: float = 90.0 memory_warning: float = 75.0 memory_critical: float = 90.0 disk_warning: float = 80.0 disk_critical: float = 95.0 load_warning: float = 2.0 load_critical: float = 5.0 @dataclass class SystemResourceStatus: """Current system resource status.""" cpu_percent: float memory_percent: float disk_percent: float load_average: Optional[float] available_memory_gb: float free_disk_gb: float network_connections: int process_count: int uptime_hours: float status: str # "healthy", "warning", "critical" warnings: List[str] timestamp: datetime class SystemResourceMonitor: """Enhanced system resource monitoring.""" def __init__(self, thresholds: Optional[SystemThresholds] = None): self.thresholds = thresholds or SystemThresholds() self.monitoring_active = False self.monitor_task: Optional[asyncio.Task] = None self.history: List[SystemResourceStatus] = [] self.max_history = 1000 async def start_monitoring(self, interval: float = 60.0): """Start system resource monitoring.""" if self.monitoring_active: return self.monitoring_active = True self.monitor_task = asyncio.create_task(self._monitoring_loop(interval)) logger.info("System resource monitoring started") async def stop_monitoring(self): """Stop system resource monitoring.""" self.monitoring_active = False if self.monitor_task: self.monitor_task.cancel() try: await self.monitor_task except asyncio.CancelledError: pass logger.info("System resource monitoring stopped") async def _monitoring_loop(self, interval: float): """Main monitoring loop.""" while self.monitoring_active: try: status = await self.get_current_status() self._add_to_history(status) await self._record_metrics(status) await asyncio.sleep(interval) except asyncio.CancelledError: break except Exception as e: logger.error(f"Error in system resource monitoring: {e}") await asyncio.sleep(interval) def _add_to_history(self, status: SystemResourceStatus): """Add status to history with size limit.""" self.history.append(status) if len(self.history) > self.max_history: self.history.pop(0) async def _record_metrics(self, status: SystemResourceStatus): """Record metrics to the monitoring system.""" monitoring_system.metrics_collector.record_metric( "system.resource_status.cpu_percent", status.cpu_percent ) monitoring_system.metrics_collector.record_metric( "system.resource_status.memory_percent", status.memory_percent ) monitoring_system.metrics_collector.record_metric( "system.resource_status.disk_percent", status.disk_percent ) monitoring_system.metrics_collector.record_metric( "system.resource_status.available_memory_gb", status.available_memory_gb ) monitoring_system.metrics_collector.record_metric( "system.resource_status.free_disk_gb", status.free_disk_gb ) monitoring_system.metrics_collector.record_metric( "system.resource_status.process_count", status.process_count ) monitoring_system.metrics_collector.record_metric( "system.resource_status.network_connections", status.network_connections ) if status.load_average is not None: monitoring_system.metrics_collector.record_metric( "system.resource_status.load_average", status.load_average ) async def get_current_status(self) -> SystemResourceStatus: """Get current system resource status.""" if not PSUTIL_AVAILABLE: return self._get_fallback_status() try: # CPU metrics cpu_percent = psutil.cpu_percent(interval=1) # Memory metrics memory = psutil.virtual_memory() memory_percent = memory.percent available_memory_gb = memory.available / (1024**3) # Disk metrics disk = psutil.disk_usage('/') disk_percent = (disk.used / disk.total) * 100 free_disk_gb = disk.free / (1024**3) # Load average (Unix-like systems) load_average = None try: load_avg = psutil.getloadavg() load_average = load_avg[0] # 1-minute load average except (AttributeError, OSError): pass # Not available on Windows # Process and connection counts process_count = len(psutil.pids()) try: network_connections = len(psutil.net_connections()) except (psutil.AccessDenied, OSError): network_connections = 0 # System uptime boot_time = psutil.boot_time() uptime_hours = (datetime.now().timestamp() - boot_time) / 3600 # Determine status and warnings warnings = [] status = "healthy" if cpu_percent >= self.thresholds.cpu_critical: warnings.append(f"Critical CPU usage: {cpu_percent:.1f}%") status = "critical" elif cpu_percent >= self.thresholds.cpu_warning: warnings.append(f"High CPU usage: {cpu_percent:.1f}%") if status != "critical": status = "warning" if memory_percent >= self.thresholds.memory_critical: warnings.append(f"Critical memory usage: {memory_percent:.1f}%") status = "critical" elif memory_percent >= self.thresholds.memory_warning: warnings.append(f"High memory usage: {memory_percent:.1f}%") if status != "critical": status = "warning" if disk_percent >= self.thresholds.disk_critical: warnings.append(f"Critical disk usage: {disk_percent:.1f}%") status = "critical" elif disk_percent >= self.thresholds.disk_warning: warnings.append(f"High disk usage: {disk_percent:.1f}%") if status != "critical": status = "warning" if load_average and load_average >= self.thresholds.load_critical: warnings.append(f"Critical system load: {load_average:.2f}") status = "critical" elif load_average and load_average >= self.thresholds.load_warning: warnings.append(f"High system load: {load_average:.2f}") if status != "critical": status = "warning" return SystemResourceStatus( cpu_percent=cpu_percent, memory_percent=memory_percent, disk_percent=disk_percent, load_average=load_average, available_memory_gb=available_memory_gb, free_disk_gb=free_disk_gb, network_connections=network_connections, process_count=process_count, uptime_hours=uptime_hours, status=status, warnings=warnings, timestamp=datetime.now() ) except Exception as e: logger.error(f"Error getting system status: {e}") return self._get_fallback_status() def _get_fallback_status(self) -> SystemResourceStatus: """Get fallback status when psutil is not available.""" return SystemResourceStatus( cpu_percent=0.0, memory_percent=0.0, disk_percent=0.0, load_average=None, available_memory_gb=0.0, free_disk_gb=0.0, network_connections=0, process_count=0, uptime_hours=0.0, status="unknown", warnings=["System monitoring unavailable (psutil not installed)"], timestamp=datetime.now() ) def get_status_history(self, hours: int = 24) -> List[SystemResourceStatus]: """Get system status history for the specified number of hours.""" cutoff_time = datetime.now() - timedelta(hours=hours) return [ status for status in self.history if status.timestamp >= cutoff_time ] def get_resource_trends(self, hours: int = 24) -> Dict[str, Any]: """Get resource usage trends over the specified time period.""" history = self.get_status_history(hours) if not history: return {"error": "No historical data available"} # Calculate trends cpu_values = [s.cpu_percent for s in history] memory_values = [s.memory_percent for s in history] disk_values = [s.disk_percent for s in history] return { "time_period_hours": hours, "data_points": len(history), "cpu": { "current": cpu_values[-1] if cpu_values else 0, "average": sum(cpu_values) / len(cpu_values) if cpu_values else 0, "max": max(cpu_values) if cpu_values else 0, "min": min(cpu_values) if cpu_values else 0 }, "memory": { "current": memory_values[-1] if memory_values else 0, "average": sum(memory_values) / len(memory_values) if memory_values else 0, "max": max(memory_values) if memory_values else 0, "min": min(memory_values) if memory_values else 0 }, "disk": { "current": disk_values[-1] if disk_values else 0, "average": sum(disk_values) / len(disk_values) if disk_values else 0, "max": max(disk_values) if disk_values else 0, "min": min(disk_values) if disk_values else 0 } } def get_system_summary(self) -> Dict[str, Any]: """Get comprehensive system summary.""" current_status = None try: import asyncio loop = asyncio.get_event_loop() current_status = loop.run_until_complete(self.get_current_status()) except Exception as e: logger.error(f"Error getting current status for summary: {e}") current_status = self._get_fallback_status() trends = self.get_resource_trends(24) return { "current_status": { "cpu_percent": current_status.cpu_percent, "memory_percent": current_status.memory_percent, "disk_percent": current_status.disk_percent, "load_average": current_status.load_average, "available_memory_gb": round(current_status.available_memory_gb, 2), "free_disk_gb": round(current_status.free_disk_gb, 2), "process_count": current_status.process_count, "network_connections": current_status.network_connections, "uptime_hours": round(current_status.uptime_hours, 1), "status": current_status.status, "warnings": current_status.warnings }, "trends_24h": trends, "thresholds": { "cpu_warning": self.thresholds.cpu_warning, "cpu_critical": self.thresholds.cpu_critical, "memory_warning": self.thresholds.memory_warning, "memory_critical": self.thresholds.memory_critical, "disk_warning": self.thresholds.disk_warning, "disk_critical": self.thresholds.disk_critical }, "monitoring_active": self.monitoring_active, "history_size": len(self.history), "timestamp": datetime.now().isoformat() } # Global system resource monitor system_monitor = SystemResourceMonitor() # Convenience functions async def get_system_resource_status() -> SystemResourceStatus: """Get current system resource status.""" return await system_monitor.get_current_status() async def start_system_monitoring(): """Start system resource monitoring.""" await system_monitor.start_monitoring() async def stop_system_monitoring(): """Stop system resource monitoring.""" await system_monitor.stop_monitoring() def get_system_summary() -> Dict[str, Any]: """Get system resource summary.""" return system_monitor.get_system_summary()