Files
UAV-CO2/src/gasflux/blueprints/stats.py

109 lines
3.5 KiB
Python

"""
Statistics Blueprintoutput_dir
Provides API statistics and monitoring endpoints.
"""
import time
from flask import Blueprint, current_app
from ..shared import _format_response, log_performance, logger, stats_collector
# Create blueprint
stats_bp = Blueprint('stats', __name__, url_prefix='/stats')
@stats_bp.route('', methods=['GET'])
@log_performance
def get_stats():
"""Get detailed API statistics and monitoring data."""
logger.debug("Statistics requested")
try:
# Get detailed statistics
stats_data = stats_collector.get_summary()
# Add current system information
try:
import psutil
memory = psutil.virtual_memory()
disk = psutil.disk_usage(str(current_app.config['OUTPUT_FOLDER']))
stats_data['system'] = {
'memory_usage_percent': memory.percent,
'memory_used_gb': round(memory.used / (1024**3), 2),
'memory_total_gb': round(memory.total / (1024**3), 2),
'disk_usage_percent': disk.percent,
'disk_used_gb': round(disk.used / (1024**3), 2),
'disk_total_gb': round(disk.total / (1024**3), 2)
}
except ImportError:
# psutil not available
stats_data['system'] = {
'note': 'System metrics unavailable - install psutil for detailed monitoring'
}
except Exception as e:
logger.warning(f"Failed to collect system metrics: {e}")
stats_data['system'] = {'error': str(e)}
# Add recent task information from database
recent_tasks = []
try:
from ..db import get_db
db = get_db()
current_time = time.time()
rows = db.execute("""
SELECT task_id, status, message, updated_at
FROM tasks
WHERE deleted_at IS NULL
ORDER BY updated_at DESC
LIMIT 20
""").fetchall()
for row in rows:
updated_at = row[3] if row[3] else 0
age = current_time - updated_at
recent_tasks.append({
'task_id': row[0], # task_id
'status': row[1], # status
'age_seconds': round(age, 1),
'message': (row[2] or '')[:100] # message, truncate long messages
})
except Exception as e:
logger.warning(f"Failed to get recent tasks from database: {e}")
recent_tasks = []
stats_data['recent_tasks'] = recent_tasks
return _format_response(200, "统计信息获取成功", stats_data)
except Exception as e:
logger.error(f"Failed to retrieve statistics: {str(e)}", exc_info=True)
return _format_response(500, "获取统计信息失败", {
"error_details": str(e)
})
@stats_bp.route('/reset', methods=['POST'])
@log_performance
def reset_stats():
"""Reset API statistics (admin function)."""
logger.warning("Statistics reset requested")
try:
# Reset statistics
stats_collector.reset_stats()
# Log the reset
logger.info("API statistics have been reset")
return _format_response(200, "统计信息重置成功", {
"timestamp": time.time()
})
except Exception as e:
logger.error(f"Failed to reset statistics: {str(e)}", exc_info=True)
return _format_response(500, "重置统计信息失败", {
"error_details": str(e)
})