Spaces:
Runtime error
Runtime error
Download app/api/v1/endpoints/telemetry.py from 12mhsssss/bimquery-api: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/api/v1/endpoints/telemetry.py
- Command line
-
hf download hf://spaces/12mhsssss/bimquery-api/app/api/v1/endpoints/telemetry.py
-
curl -L -o telemetry.py https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/api/v1/endpoints/telemetry.py
15.4 kB
| # Copyright (C) 2026 Mattia Zatelli | |
| # | |
| # This program is free software: you can redistribute it and/or modify | |
| # it under the terms of the GNU Affero General Public License as published by | |
| # the Free Software Foundation, either version 3 of the License, or | |
| # (at your option) any later version. | |
| # | |
| # This program is distributed in the hope that it will be useful, | |
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
| # GNU Affero General Public License for more details. | |
| # | |
| # You should have received a copy of the GNU Affero General Public License | |
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | |
| """ | |
| Telemetry and metrics endpoints for monitoring tiered storage | |
| """ | |
| import logging | |
| from typing import Optional, Dict, Any, List | |
| from datetime import datetime | |
| from fastapi import APIRouter, Depends, Request, Query as QueryParam | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from pydantic import BaseModel | |
| from app.core.database import get_async_session | |
| from app.services.metrics import metrics_collector | |
| from app.models import StorageTier, TieringOperationType | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter() | |
| class TierMetricsResponse(BaseModel): | |
| """Response model for tier metrics""" | |
| tier: str | |
| project_count: int | |
| total_size_bytes: int | |
| avg_days_inactive: float | |
| oldest_project_days: int | |
| newest_project_days: int | |
| class OperationMetricsResponse(BaseModel): | |
| """Response model for operation metrics""" | |
| operation_type: str | |
| total_operations: int | |
| successful_operations: int | |
| failed_operations: int | |
| avg_processing_time_ms: float | |
| total_bytes_moved: int | |
| success_rate: float | |
| class SystemMetricsResponse(BaseModel): | |
| """Response model for system metrics""" | |
| total_projects: int | |
| total_storage_bytes: int | |
| compression_ratio: float | |
| storage_cost_savings: float | |
| rehydration_hit_rate: float | |
| avg_tier_demotion_time_days: float | |
| class TelemetryOverviewResponse(BaseModel): | |
| """Complete telemetry overview""" | |
| system_metrics: SystemMetricsResponse | |
| tier_metrics: List[TierMetricsResponse] | |
| operation_metrics: List[OperationMetricsResponse] | |
| tier_distribution: Dict[str, Any] | |
| performance_metrics: Dict[str, Any] | |
| generated_at: datetime | |
| async def get_telemetry_overview( | |
| request: Request, | |
| days: int = QueryParam(7, description="Days to look back for operation metrics"), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get comprehensive telemetry overview for tiered storage system | |
| """ | |
| # Get authentication info for tenant filtering | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| logger.info(f"Generating telemetry overview for tenant {tenant_id or 'all'}") | |
| try: | |
| # Collect all metrics concurrently | |
| system_metrics = await metrics_collector.collect_system_metrics(tenant_id) | |
| tier_metrics = await metrics_collector.collect_tier_metrics(tenant_id) | |
| operation_metrics = await metrics_collector.collect_operation_metrics(days, tenant_id) | |
| tier_distribution = await metrics_collector.get_tier_distribution(tenant_id) | |
| performance_metrics = await metrics_collector.get_performance_metrics(tenant_id) | |
| # Convert dataclasses to response models | |
| system_response = SystemMetricsResponse( | |
| total_projects=system_metrics.total_projects, | |
| total_storage_bytes=system_metrics.total_storage_bytes, | |
| compression_ratio=system_metrics.compression_ratio, | |
| storage_cost_savings=system_metrics.storage_cost_savings, | |
| rehydration_hit_rate=system_metrics.rehydration_hit_rate, | |
| avg_tier_demotion_time_days=system_metrics.avg_tier_demotion_time_days | |
| ) | |
| tier_responses = [ | |
| TierMetricsResponse( | |
| tier=tm.tier, | |
| project_count=tm.project_count, | |
| total_size_bytes=tm.total_size_bytes, | |
| avg_days_inactive=tm.avg_days_inactive, | |
| oldest_project_days=tm.oldest_project_days, | |
| newest_project_days=tm.newest_project_days | |
| ) | |
| for tm in tier_metrics | |
| ] | |
| operation_responses = [ | |
| OperationMetricsResponse( | |
| operation_type=om.operation_type, | |
| total_operations=om.total_operations, | |
| successful_operations=om.successful_operations, | |
| failed_operations=om.failed_operations, | |
| avg_processing_time_ms=om.avg_processing_time_ms, | |
| total_bytes_moved=om.total_bytes_moved, | |
| success_rate=om.success_rate | |
| ) | |
| for om in operation_metrics | |
| ] | |
| return TelemetryOverviewResponse( | |
| system_metrics=system_response, | |
| tier_metrics=tier_responses, | |
| operation_metrics=operation_responses, | |
| tier_distribution=tier_distribution, | |
| performance_metrics=performance_metrics, | |
| generated_at=datetime.now() | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to generate telemetry overview: {e}") | |
| raise | |
| async def get_tier_metrics( | |
| request: Request, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get metrics for each storage tier | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| logger.info(f"Getting tier metrics for tenant {tenant_id or 'all'}") | |
| tier_metrics = await metrics_collector.collect_tier_metrics(tenant_id) | |
| return [ | |
| TierMetricsResponse( | |
| tier=tm.tier, | |
| project_count=tm.project_count, | |
| total_size_bytes=tm.total_size_bytes, | |
| avg_days_inactive=tm.avg_days_inactive, | |
| oldest_project_days=tm.oldest_project_days, | |
| newest_project_days=tm.newest_project_days | |
| ) | |
| for tm in tier_metrics | |
| ] | |
| async def get_operation_metrics( | |
| request: Request, | |
| days: int = QueryParam(7, description="Days to look back"), | |
| operation_type: Optional[TieringOperationType] = QueryParam(None, description="Filter by operation type"), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get metrics for tiering operations | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| logger.info(f"Getting operation metrics for tenant {tenant_id or 'all'}, days={days}") | |
| operation_metrics = await metrics_collector.collect_operation_metrics(days, tenant_id) | |
| # Filter by operation type if specified | |
| if operation_type: | |
| operation_metrics = [om for om in operation_metrics if om.operation_type == operation_type.value] | |
| return [ | |
| OperationMetricsResponse( | |
| operation_type=om.operation_type, | |
| total_operations=om.total_operations, | |
| successful_operations=om.successful_operations, | |
| failed_operations=om.failed_operations, | |
| avg_processing_time_ms=om.avg_processing_time_ms, | |
| total_bytes_moved=om.total_bytes_moved, | |
| success_rate=om.success_rate | |
| ) | |
| for om in operation_metrics | |
| ] | |
| async def get_system_metrics( | |
| request: Request, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get overall system metrics | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| logger.info(f"Getting system metrics for tenant {tenant_id or 'all'}") | |
| system_metrics = await metrics_collector.collect_system_metrics(tenant_id) | |
| return SystemMetricsResponse( | |
| total_projects=system_metrics.total_projects, | |
| total_storage_bytes=system_metrics.total_storage_bytes, | |
| compression_ratio=system_metrics.compression_ratio, | |
| storage_cost_savings=system_metrics.storage_cost_savings, | |
| rehydration_hit_rate=system_metrics.rehydration_hit_rate, | |
| avg_tier_demotion_time_days=system_metrics.avg_tier_demotion_time_days | |
| ) | |
| async def get_tier_distribution( | |
| request: Request, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get distribution of projects across tiers | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| logger.info(f"Getting tier distribution for tenant {tenant_id or 'all'}") | |
| return await metrics_collector.get_tier_distribution(tenant_id) | |
| async def get_performance_metrics( | |
| request: Request, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get performance-related metrics | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| logger.info(f"Getting performance metrics for tenant {tenant_id or 'all'}") | |
| return await metrics_collector.get_performance_metrics(tenant_id) | |
| async def get_tiering_health( | |
| request: Request, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get health status of tiering system | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| try: | |
| # Quick health checks | |
| tier_metrics = await metrics_collector.collect_tier_metrics(tenant_id) | |
| operation_metrics = await metrics_collector.collect_operation_metrics(1, tenant_id) # Last day | |
| # Calculate health indicators | |
| total_projects = sum(tm.project_count for tm in tier_metrics) | |
| hot_projects = next((tm.project_count for tm in tier_metrics if tm.tier == "hot"), 0) | |
| # Check if there are any failed operations in the last day | |
| failed_operations = sum(om.failed_operations for om in operation_metrics) | |
| total_operations = sum(om.total_operations for om in operation_metrics) | |
| overall_success_rate = 100.0 | |
| if total_operations > 0: | |
| overall_success_rate = ((total_operations - failed_operations) / total_operations) * 100 | |
| # Determine health status | |
| health_status = "healthy" | |
| issues = [] | |
| if overall_success_rate < 95.0: | |
| health_status = "degraded" | |
| issues.append(f"Low success rate: {overall_success_rate:.1f}%") | |
| if failed_operations > 10: | |
| health_status = "degraded" if health_status == "healthy" else "unhealthy" | |
| issues.append(f"High failure count: {failed_operations} failures in last day") | |
| # Check for projects stuck in processing | |
| processing_projects = 0 # Would need to query for this | |
| if processing_projects > 0: | |
| issues.append(f"{processing_projects} projects stuck in processing") | |
| return { | |
| "status": health_status, | |
| "timestamp": datetime.now(), | |
| "summary": { | |
| "total_projects": total_projects, | |
| "hot_tier_projects": hot_projects, | |
| "success_rate_24h": overall_success_rate, | |
| "failed_operations_24h": failed_operations, | |
| "total_operations_24h": total_operations | |
| }, | |
| "issues": issues, | |
| "uptime_indicators": { | |
| "tiering_service": "operational", | |
| "rehydration_service": "operational", | |
| "metrics_collection": "operational" | |
| } | |
| } | |
| except Exception as e: | |
| logger.error(f"Health check failed: {e}") | |
| return { | |
| "status": "unhealthy", | |
| "timestamp": datetime.now(), | |
| "issues": ["Health check failed"], | |
| "summary": {}, | |
| "uptime_indicators": { | |
| "tiering_service": "unknown", | |
| "rehydration_service": "unknown", | |
| "metrics_collection": "failed" | |
| } | |
| } | |
| async def get_tiering_alerts( | |
| request: Request, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get active alerts and warnings for tiering system | |
| """ | |
| tenant_id = getattr(request.state, "tenant_id", None) | |
| alerts = [] | |
| warnings = [] | |
| try: | |
| # Collect metrics for alert evaluation | |
| tier_metrics = await metrics_collector.collect_tier_metrics(tenant_id) | |
| operation_metrics = await metrics_collector.collect_operation_metrics(1, tenant_id) | |
| system_metrics = await metrics_collector.collect_system_metrics(tenant_id) | |
| # Check for alerts | |
| # Alert: High failure rate | |
| total_failures = sum(om.failed_operations for om in operation_metrics) | |
| total_operations = sum(om.total_operations for om in operation_metrics) | |
| if total_operations > 0: | |
| failure_rate = (total_failures / total_operations) * 100 | |
| if failure_rate > 10: | |
| alerts.append({ | |
| "type": "high_failure_rate", | |
| "severity": "critical", | |
| "message": f"High operation failure rate: {failure_rate:.1f}%", | |
| "threshold": "10%", | |
| "current_value": f"{failure_rate:.1f}%", | |
| "timestamp": datetime.now() | |
| }) | |
| # Alert: Very old projects in HOT tier | |
| hot_tier = next((tm for tm in tier_metrics if tm.tier == "hot"), None) | |
| if hot_tier and hot_tier.oldest_project_days > 90: | |
| alerts.append({ | |
| "type": "old_hot_projects", | |
| "severity": "warning", | |
| "message": f"Very old projects in HOT tier: {hot_tier.oldest_project_days} days", | |
| "threshold": "90 days", | |
| "current_value": f"{hot_tier.oldest_project_days} days", | |
| "timestamp": datetime.now() | |
| }) | |
| # Warning: Low compression ratio | |
| if system_metrics.compression_ratio > 0.8: | |
| warnings.append({ | |
| "type": "low_compression", | |
| "message": f"Low compression ratio: {system_metrics.compression_ratio:.2f}", | |
| "recommendation": "Check compression settings or file types", | |
| "timestamp": datetime.now() | |
| }) | |
| # Warning: No recent tiering activity | |
| recent_demotions = next((om for om in operation_metrics if om.operation_type == "demote"), None) | |
| if not recent_demotions or recent_demotions.total_operations == 0: | |
| warnings.append({ | |
| "type": "no_tiering_activity", | |
| "message": "No demotion operations in the last 24 hours", | |
| "recommendation": "Check if tiering job is running properly", | |
| "timestamp": datetime.now() | |
| }) | |
| return { | |
| "alerts": alerts, | |
| "warnings": warnings, | |
| "alert_count": len(alerts), | |
| "warning_count": len(warnings), | |
| "last_check": datetime.now() | |
| } | |
| except Exception as e: | |
| logger.error(f"Alert generation failed: {e}") | |
| return { | |
| "alerts": [{ | |
| "type": "system_error", | |
| "severity": "critical", | |
| "message": "Alert system failure", | |
| "timestamp": datetime.now() | |
| }], | |
| "warnings": [], | |
| "alert_count": 1, | |
| "warning_count": 0, | |
| "last_check": datetime.now() | |
| } |