Download src/monitoring/api.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/monitoring/api.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/monitoring/api.py
-
curl -L -o api.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/monitoring/api.py
10.5 kB
| """ | |
| YAZ Care Platform - Monitoring API Endpoints | |
| Real-time access to performance metrics, query profiling, and cache statistics | |
| """ | |
| from typing import Any, Dict, Optional | |
| import structlog | |
| from fastapi import APIRouter, HTTPException, Query | |
| from monitoring.cache_optimizer import cache_optimizer | |
| from monitoring.prometheus_metrics import metrics_collector | |
| from monitoring.query_profiler import query_profiler | |
| logger = structlog.get_logger(__name__) | |
| router = APIRouter(prefix="/api/monitoring", tags=["monitoring"]) | |
| # ============================================ | |
| # PROMETHEUS METRICS | |
| # ============================================ | |
| async def get_prometheus_metrics() -> str: | |
| """Export metrics in Prometheus format""" | |
| try: | |
| return metrics_collector.export_metrics() | |
| except Exception as e: | |
| logger.error("Failed to export Prometheus metrics: %s", e) | |
| raise HTTPException(status_code=500, detail="Failed to export metrics") from e | |
| async def get_metrics_summary() -> dict[str, Any]: | |
| """Get summary of all platform metrics""" | |
| try: | |
| return { | |
| "prometheus": metrics_collector.get_summary(), | |
| "queries": query_profiler.get_statistics(), | |
| "cache": cache_optimizer.get_metrics(), | |
| "timestamp": metrics_collector.get_timestamp(), | |
| } | |
| except Exception as e: | |
| logger.error("Failed to get metrics summary: %s", e) | |
| raise HTTPException(status_code=500, detail="Failed to get metrics summary") from e | |
| # ============================================ | |
| # QUERY PROFILING | |
| # ============================================ | |
| async def get_slow_queries(limit: int = Query(10, ge=1, le=100)): | |
| """Get slowest queries by average execution time""" | |
| try: | |
| slow_queries = query_profiler.get_slow_queries(limit) | |
| return { | |
| "slow_queries": [ | |
| { | |
| "query_hash": q.query_hash, | |
| "query": q.query_text, | |
| "execution_count": q.execution_count, | |
| "avg_duration": f"{q.avg_duration:.3f}s", | |
| "min_duration": f"{q.min_duration:.3f}s", | |
| "max_duration": f"{q.max_duration:.3f}s", | |
| "p95_duration": f"{q.p95_duration:.3f}s", | |
| "p99_duration": f"{q.p99_duration:.3f}s", | |
| "error_count": q.error_count, | |
| "last_execution": q.last_execution.isoformat() if q.last_execution else None, | |
| } | |
| for q in slow_queries | |
| ], | |
| "count": len(slow_queries), | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to get slow queries: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to get slow queries") | |
| async def get_frequent_queries(limit: int = Query(10, ge=1, le=100)): | |
| """Get most frequently executed queries""" | |
| try: | |
| frequent_queries = query_profiler.get_frequent_queries(limit) | |
| return { | |
| "frequent_queries": [ | |
| { | |
| "query_hash": q.query_hash, | |
| "query": q.query_text, | |
| "execution_count": q.execution_count, | |
| "avg_duration": f"{q.avg_duration:.3f}s", | |
| "total_duration": f"{q.total_duration:.3f}s", | |
| "error_count": q.error_count, | |
| } | |
| for q in frequent_queries | |
| ], | |
| "count": len(frequent_queries), | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to get frequent queries: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to get frequent queries") | |
| async def get_query_statistics(): | |
| """Get overall query performance statistics""" | |
| try: | |
| return query_profiler.get_statistics() | |
| except Exception as e: | |
| logger.error(f"Failed to get query statistics: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to get query statistics") | |
| async def get_query_recommendations(): | |
| """Get query optimization recommendations""" | |
| try: | |
| recommendations = query_profiler.generate_recommendations() | |
| return { | |
| "recommendations": recommendations, | |
| "count": len(recommendations), | |
| "high_severity": len([r for r in recommendations if r["severity"] == "high"]), | |
| "medium_severity": len([r for r in recommendations if r["severity"] == "medium"]), | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to get recommendations: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to get recommendations") | |
| async def reset_query_statistics(): | |
| """Reset all query profiling statistics""" | |
| try: | |
| query_profiler.reset_statistics() | |
| return {"message": "Query statistics reset successfully"} | |
| except Exception as e: | |
| logger.error(f"Failed to reset query statistics: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to reset statistics") | |
| # ============================================ | |
| # CACHE MONITORING | |
| # ============================================ | |
| async def get_cache_metrics(): | |
| """Get cache performance metrics""" | |
| try: | |
| return cache_optimizer.get_metrics() | |
| except Exception as e: | |
| logger.error(f"Failed to get cache metrics: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to get cache metrics") | |
| async def invalidate_cache( | |
| namespace: str = Query(..., description="Cache namespace to invalidate"), | |
| pattern: str | None = Query(None, description="Pattern to match (optional)"), | |
| ): | |
| """Invalidate cache entries by namespace and optional pattern""" | |
| try: | |
| if pattern: | |
| await cache_optimizer.invalidate_pattern(namespace, pattern) | |
| return {"message": f"Invalidated cache for pattern: {namespace}:{pattern}"} | |
| else: | |
| await cache_optimizer.invalidate_pattern(namespace, "*") | |
| return {"message": f"Invalidated all cache for namespace: {namespace}"} | |
| except Exception as e: | |
| logger.error(f"Failed to invalidate cache: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to invalidate cache") | |
| async def reset_cache_metrics(): | |
| """Reset cache performance metrics""" | |
| try: | |
| cache_optimizer.reset_metrics() | |
| return {"message": "Cache metrics reset successfully"} | |
| except Exception as e: | |
| logger.error(f"Failed to reset cache metrics: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to reset cache metrics") | |
| async def cleanup_expired_cache(): | |
| """Remove expired entries from cache""" | |
| try: | |
| await cache_optimizer.cleanup_expired() | |
| return {"message": "Expired cache entries cleaned up successfully"} | |
| except Exception as e: | |
| logger.error(f"Failed to cleanup cache: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to cleanup cache") | |
| # ============================================ | |
| # HEALTH & STATUS | |
| # ============================================ | |
| async def monitoring_health(): | |
| """Check health of monitoring systems""" | |
| try: | |
| query_stats = query_profiler.get_statistics() | |
| cache_metrics = cache_optimizer.get_metrics() | |
| return { | |
| "status": "healthy", | |
| "systems": { | |
| "prometheus": { | |
| "status": "active", | |
| "uptime_seconds": metrics_collector._get_uptime(), | |
| }, | |
| "query_profiler": { | |
| "status": "active", | |
| "total_queries": query_stats["total_queries"], | |
| "uptime_seconds": query_stats["uptime_seconds"], | |
| }, | |
| "cache_optimizer": { | |
| "status": "active", | |
| "hit_rate": f"{cache_metrics['hit_rate']:.2f}%", | |
| "uptime_seconds": cache_metrics["uptime_seconds"], | |
| }, | |
| }, | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to get monitoring health: {e}") | |
| return {"status": "degraded", "error": str(e)} | |
| async def get_monitoring_dashboard(): | |
| """Get comprehensive monitoring dashboard data""" | |
| try: | |
| return { | |
| "metrics": { | |
| "http": { | |
| "total_requests": metrics_collector.http_requests_total._value.get(), | |
| "request_duration_avg": metrics_collector._get_avg_response_time(), | |
| "error_rate": metrics_collector._get_error_rate(), | |
| }, | |
| "database": { | |
| "total_queries": query_profiler.get_statistics()["total_queries"], | |
| "slow_queries": query_profiler.get_statistics()["slow_queries"], | |
| "avg_duration": query_profiler.get_statistics()["avg_duration"], | |
| }, | |
| "cache": { | |
| "hit_rate": cache_optimizer.get_metrics()["hit_rate"], | |
| "total_hits": cache_optimizer.get_metrics()["hits"], | |
| "total_misses": cache_optimizer.get_metrics()["misses"], | |
| }, | |
| }, | |
| "alerts": { | |
| "slow_queries": len(query_profiler.get_slow_queries(10)), | |
| "query_errors": len(query_profiler.get_error_queries()), | |
| "recommendations": len(query_profiler.generate_recommendations()), | |
| }, | |
| "timestamp": metrics_collector._get_timestamp(), | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to get dashboard data: {e}") | |
| raise HTTPException(status_code=500, detail="Failed to get dashboard data") | |
| __all__ = ["router"] | |