ai_data_scientist / shared /monitoring.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
20.8 kB
"""
Comprehensive monitoring and logging system for MCP AI Data Scientist.
Provides centralized logging, metrics collection, and system health monitoring.
"""
import logging
import time
import json
import asyncio
from datetime import datetime, timezone
# Optional dependency
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
from typing import Dict, Any, Optional, List, Callable
from pathlib import Path
from dataclasses import dataclass, asdict
from contextlib import asynccontextmanager
import threading
from collections import defaultdict, deque
from .config import settings
@dataclass
class MetricPoint:
"""Individual metric data point."""
name: str
value: float
timestamp: datetime
tags: Dict[str, str] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"name": self.name,
"value": self.value,
"timestamp": self.timestamp.isoformat(),
"tags": self.tags or {}
}
@dataclass
class HealthStatus:
"""System health status."""
component: str
is_healthy: bool
status_message: str
last_check: datetime
metrics: Dict[str, float] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"component": self.component,
"is_healthy": self.is_healthy,
"status_message": self.status_message,
"last_check": self.last_check.isoformat(),
"metrics": self.metrics or {}
}
class MetricsCollector:
"""Collects and stores system metrics."""
def __init__(self, max_points: int = 10000):
self.max_points = max_points
self.metrics: Dict[str, deque] = defaultdict(lambda: deque(maxlen=max_points))
self.lock = threading.Lock()
def record_metric(self, name: str, value: float, tags: Dict[str, str] = None):
"""Record a metric point."""
point = MetricPoint(
name=name,
value=value,
timestamp=datetime.now(timezone.utc),
tags=tags
)
with self.lock:
self.metrics[name].append(point)
def get_metrics(self, name: str, limit: int = 100) -> List[MetricPoint]:
"""Get recent metrics for a given name."""
with self.lock:
if name in self.metrics:
return list(self.metrics[name])[-limit:]
return []
def get_all_metrics(self) -> Dict[str, List[Dict[str, Any]]]:
"""Get all metrics as serializable dictionary."""
with self.lock:
return {
name: [point.to_dict() for point in points]
for name, points in self.metrics.items()
}
def get_latest_values(self) -> Dict[str, float]:
"""Get latest value for each metric."""
with self.lock:
return {
name: points[-1].value if points else 0.0
for name, points in self.metrics.items()
}
class PerformanceMonitor:
"""Monitors system performance metrics."""
def __init__(self, metrics_collector: MetricsCollector):
self.metrics = metrics_collector
self.monitoring = False
self.monitor_task = None
self.process = psutil.Process() if PSUTIL_AVAILABLE else None
async def start_monitoring(self, interval: float = 30.0):
"""Start performance monitoring."""
if self.monitoring:
return
self.monitoring = True
self.monitor_task = asyncio.create_task(self._monitor_loop(interval))
async def stop_monitoring(self):
"""Stop performance monitoring."""
self.monitoring = False
if self.monitor_task:
self.monitor_task.cancel()
try:
await self.monitor_task
except asyncio.CancelledError:
pass
async def _monitor_loop(self, interval: float):
"""Main monitoring loop."""
while self.monitoring:
try:
await self._collect_system_metrics()
await asyncio.sleep(interval)
except asyncio.CancelledError:
break
except Exception as e:
logging.error(f"Error in performance monitoring: {e}")
await asyncio.sleep(interval)
async def _collect_system_metrics(self):
"""Collect system performance metrics."""
try:
if not PSUTIL_AVAILABLE:
# Record placeholder metrics when psutil is not available
self.metrics.record_metric("system.cpu_percent", 0.0)
self.metrics.record_metric("system.memory_rss_mb", 0.0)
return
# CPU metrics
cpu_percent = self.process.cpu_percent()
self.metrics.record_metric("system.cpu_percent", cpu_percent)
# Memory metrics
memory_info = self.process.memory_info()
self.metrics.record_metric("system.memory_rss_mb", memory_info.rss / 1024 / 1024)
self.metrics.record_metric("system.memory_vms_mb", memory_info.vms / 1024 / 1024)
# System-wide metrics
system_cpu = psutil.cpu_percent()
system_memory = psutil.virtual_memory()
self.metrics.record_metric("system.total_cpu_percent", system_cpu)
self.metrics.record_metric("system.total_memory_percent", system_memory.percent)
self.metrics.record_metric("system.available_memory_gb", system_memory.available / 1024 / 1024 / 1024)
# Disk usage
disk_usage = psutil.disk_usage('/')
self.metrics.record_metric("system.disk_usage_percent",
(disk_usage.used / disk_usage.total) * 100)
# Network I/O (if available)
try:
net_io = psutil.net_io_counters()
self.metrics.record_metric("system.network_bytes_sent", net_io.bytes_sent)
self.metrics.record_metric("system.network_bytes_recv", net_io.bytes_recv)
except:
pass # Network metrics not available on all systems
except Exception as e:
logging.error(f"Error collecting system metrics: {e}")
class ApplicationMonitor:
"""Monitors application-specific metrics."""
def __init__(self, metrics_collector: MetricsCollector):
self.metrics = metrics_collector
self.request_counts = defaultdict(int)
self.error_counts = defaultdict(int)
self.response_times = defaultdict(list)
def record_request(self, endpoint: str, method: str = "GET"):
"""Record an API request."""
key = f"{method}:{endpoint}"
self.request_counts[key] += 1
self.metrics.record_metric(
"app.requests_total",
self.request_counts[key],
tags={"endpoint": endpoint, "method": method}
)
def record_error(self, endpoint: str, error_type: str, method: str = "GET"):
"""Record an application error."""
key = f"{method}:{endpoint}:{error_type}"
self.error_counts[key] += 1
self.metrics.record_metric(
"app.errors_total",
self.error_counts[key],
tags={"endpoint": endpoint, "method": method, "error_type": error_type}
)
@asynccontextmanager
async def time_operation(self, operation_name: str, tags: Dict[str, str] = None):
"""Context manager to time operations."""
start_time = time.time()
try:
yield
finally:
duration = time.time() - start_time
self.metrics.record_metric(
f"app.operation_duration_seconds",
duration,
tags={**(tags or {}), "operation": operation_name}
)
def record_analysis_stage(self, stage: str, duration: float, success: bool):
"""Record analysis stage metrics."""
self.metrics.record_metric(
"app.analysis_stage_duration_seconds",
duration,
tags={"stage": stage, "success": str(success)}
)
self.metrics.record_metric(
"app.analysis_stage_count",
1,
tags={"stage": stage, "success": str(success)}
)
def record_mcp_call(self, server: str, tool: str, duration: float, success: bool):
"""Record MCP server call metrics."""
self.metrics.record_metric(
"app.mcp_call_duration_seconds",
duration,
tags={"server": server, "tool": tool, "success": str(success)}
)
self.metrics.record_metric(
"app.mcp_call_count",
1,
tags={"server": server, "tool": tool, "success": str(success)}
)
class HealthChecker:
"""Performs health checks on system components."""
def __init__(self):
self.health_status: Dict[str, HealthStatus] = {}
self.health_checks: Dict[str, Callable] = {}
def register_health_check(self, component: str, check_func: Callable):
"""Register a health check function for a component."""
self.health_checks[component] = check_func
async def check_component_health(self, component: str) -> HealthStatus:
"""Check health of a specific component."""
if component not in self.health_checks:
return HealthStatus(
component=component,
is_healthy=False,
status_message="No health check registered",
last_check=datetime.now(timezone.utc)
)
try:
check_func = self.health_checks[component]
if asyncio.iscoroutinefunction(check_func):
result = await check_func()
else:
result = check_func()
if isinstance(result, bool):
status = HealthStatus(
component=component,
is_healthy=result,
status_message="OK" if result else "Health check failed",
last_check=datetime.now(timezone.utc)
)
elif isinstance(result, dict):
status = HealthStatus(
component=component,
is_healthy=result.get("healthy", False),
status_message=result.get("message", "Unknown"),
last_check=datetime.now(timezone.utc),
metrics=result.get("metrics", {})
)
else:
status = HealthStatus(
component=component,
is_healthy=False,
status_message=f"Invalid health check result: {result}",
last_check=datetime.now(timezone.utc)
)
except Exception as e:
status = HealthStatus(
component=component,
is_healthy=False,
status_message=f"Health check error: {str(e)}",
last_check=datetime.now(timezone.utc)
)
self.health_status[component] = status
return status
async def check_all_health(self) -> Dict[str, HealthStatus]:
"""Check health of all registered components."""
tasks = [
self.check_component_health(component)
for component in self.health_checks.keys()
]
results = await asyncio.gather(*tasks, return_exceptions=True)
health_results = {}
for i, (component, result) in enumerate(zip(self.health_checks.keys(), results)):
if isinstance(result, Exception):
health_results[component] = HealthStatus(
component=component,
is_healthy=False,
status_message=f"Health check exception: {str(result)}",
last_check=datetime.now(timezone.utc)
)
else:
health_results[component] = result
self.health_status.update(health_results)
return health_results
def get_overall_health(self) -> bool:
"""Get overall system health status."""
if not self.health_status:
return False
return all(status.is_healthy for status in self.health_status.values())
class MonitoringSystem:
"""Central monitoring system that coordinates all monitoring components."""
def __init__(self):
self.metrics_collector = MetricsCollector()
self.performance_monitor = PerformanceMonitor(self.metrics_collector)
self.app_monitor = ApplicationMonitor(self.metrics_collector)
self.health_checker = HealthChecker()
# Setup logging
self.logger = self._setup_logging()
# Monitoring state
self.monitoring_active = False
def _setup_logging(self) -> logging.Logger:
"""Setup centralized logging."""
logger = logging.getLogger("mcp_data_scientist")
if not logger.handlers:
# Create formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# File handler
log_file = Path(settings.log_file)
log_file.parent.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(getattr(logging, settings.log_level.upper()))
# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.INFO)
# Add handlers
logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.setLevel(logging.DEBUG)
return logger
async def start_monitoring(self):
"""Start all monitoring components."""
if self.monitoring_active:
return
self.logger.info("Starting monitoring system...")
# Start performance monitoring
await self.performance_monitor.start_monitoring()
# Register default health checks
self._register_default_health_checks()
self.monitoring_active = True
self.logger.info("Monitoring system started successfully")
async def stop_monitoring(self):
"""Stop all monitoring components."""
if not self.monitoring_active:
return
self.logger.info("Stopping monitoring system...")
# Stop performance monitoring
await self.performance_monitor.stop_monitoring()
self.monitoring_active = False
self.logger.info("Monitoring system stopped")
def _register_default_health_checks(self):
"""Register default health checks."""
def database_health_check():
"""Check database connectivity."""
try:
# This would normally test database connection
# For now, return True as placeholder
return {
"healthy": True,
"message": "Database connection OK",
"metrics": {"connection_pool_size": 10}
}
except Exception as e:
return {
"healthy": False,
"message": f"Database error: {str(e)}"
}
def system_resources_health_check():
"""Check system resource usage."""
try:
if not PSUTIL_AVAILABLE:
return {
"healthy": True,
"message": "System resources check skipped (psutil not available)",
"metrics": {}
}
cpu_percent = psutil.cpu_percent()
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
# Define thresholds
cpu_threshold = 90.0
memory_threshold = 90.0
disk_threshold = 95.0
issues = []
if cpu_percent > cpu_threshold:
issues.append(f"High CPU usage: {cpu_percent:.1f}%")
if memory.percent > memory_threshold:
issues.append(f"High memory usage: {memory.percent:.1f}%")
if (disk.used / disk.total * 100) > disk_threshold:
issues.append(f"High disk usage: {disk.used / disk.total * 100:.1f}%")
return {
"healthy": len(issues) == 0,
"message": "System resources OK" if not issues else "; ".join(issues),
"metrics": {
"cpu_percent": cpu_percent,
"memory_percent": memory.percent,
"disk_percent": disk.used / disk.total * 100
}
}
except Exception as e:
return {
"healthy": False,
"message": f"System check error: {str(e)}"
}
# Register health checks
self.health_checker.register_health_check("database", database_health_check)
self.health_checker.register_health_check("system_resources", system_resources_health_check)
def get_monitoring_dashboard(self) -> Dict[str, Any]:
"""Get comprehensive monitoring dashboard data."""
return {
"timestamp": datetime.now(timezone.utc).isoformat(),
"monitoring_active": self.monitoring_active,
"metrics": {
"latest_values": self.metrics_collector.get_latest_values(),
"total_metrics": len(self.metrics_collector.metrics)
},
"health": {
component: status.to_dict()
for component, status in self.health_checker.health_status.items()
},
"overall_healthy": self.health_checker.get_overall_health()
}
def export_metrics(self, format: str = "json") -> str:
"""Export metrics in specified format."""
if format.lower() == "json":
return json.dumps(self.metrics_collector.get_all_metrics(), indent=2)
else:
raise ValueError(f"Unsupported export format: {format}")
# Global monitoring instance
monitoring_system = MonitoringSystem()
# Convenience functions for easy access
def record_metric(name: str, value: float, tags: Dict[str, str] = None):
"""Record a metric point."""
monitoring_system.metrics_collector.record_metric(name, value, tags)
def record_request(endpoint: str, method: str = "GET"):
"""Record an API request."""
monitoring_system.app_monitor.record_request(endpoint, method)
def record_error(endpoint: str, error_type: str, method: str = "GET"):
"""Record an application error."""
monitoring_system.app_monitor.record_error(endpoint, error_type, method)
def time_operation(operation_name: str, tags: Dict[str, str] = None):
"""Context manager to time operations."""
return monitoring_system.app_monitor.time_operation(operation_name, tags)
async def get_system_health() -> Dict[str, Any]:
"""Get current system health status."""
await monitoring_system.health_checker.check_all_health()
return monitoring_system.get_monitoring_dashboard()
def get_logger(name: str = None) -> logging.Logger:
"""Get a logger instance."""
if name:
return logging.getLogger(f"mcp_data_scientist.{name}")
return monitoring_system.logger