Spaces:
Paused
Paused
File size: 14,115 Bytes
56c063a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | """
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() |