#!/usr/bin/env python3 """ Performance Dashboard Generator for Claude-Flow Swarm Operations This script generates interactive HTML dashboards for performance monitoring: - Real-time performance metrics visualization - Historical trend analysis and charts - Performance regression tracking - Interactive charts and graphs - Automated report generation Author: Metrics Analyst Agent Version: 1.0.0 """ import json import os import sys from datetime import datetime, timedelta from pathlib import Path from typing import Dict, List, Any, Optional import statistics from dataclasses import asdict # Add local modules to path sys.path.insert(0, str(Path(__file__).parent)) try: from continuous_performance_monitor import PerformanceMonitor, MetricSnapshot except ImportError: print("Warning: Could not import performance monitor - dashboard will use sample data") class PerformanceDashboard: """Generates interactive performance dashboards.""" def __init__(self, output_dir: str = "dashboard_output"): self.output_dir = Path(output_dir) self.output_dir.mkdir(exist_ok=True) def generate_dashboard(self, data_source: str = "database") -> str: """Generate complete performance dashboard.""" print("š Generating Performance Dashboard...") # Collect data if data_source == "database": dashboard_data = self._collect_database_data() else: dashboard_data = self._generate_sample_data() # Generate HTML dashboard dashboard_file = self._generate_html_dashboard(dashboard_data) # Generate additional reports self._generate_csv_export(dashboard_data) self._generate_json_export(dashboard_data) print(f"ā Dashboard generated: {dashboard_file}") return str(dashboard_file) def _collect_database_data(self) -> Dict[str, Any]: """Collect data from performance database.""" try: monitor = PerformanceMonitor() # Get dashboard data for different time periods data = { "last_24h": monitor.get_performance_dashboard_data(24), "last_7d": monitor.get_performance_dashboard_data(168), "last_30d": monitor.get_performance_dashboard_data(720), "regression_report": monitor.generate_regression_report() } return data except Exception as e: print(f"Warning: Could not collect database data: {e}") return self._generate_sample_data() def _generate_sample_data(self) -> Dict[str, Any]: """Generate sample data for demonstration.""" import random # Generate sample time series data now = datetime.now() time_series = [] for i in range(100): timestamp = now - timedelta(hours=i) time_series.append({ "timestamp": timestamp.isoformat(), "swarm_init_time": random.uniform(1.0, 8.0), "agent_coordination_latency": random.uniform(50, 300), "memory_usage_mb": random.uniform(20, 80), "token_consumption_rate": random.uniform(80, 150), "mcp_response_time": random.uniform(0.2, 2.0), "neural_processing_time": random.uniform(100, 800), "active_agents": random.randint(0, 8), "cpu_usage_percent": random.uniform(10, 70) }) return { "last_24h": { "summary": { "total_samples": 100, "time_range_hours": 24, "last_update": now.isoformat() }, "swarm_performance": { "avg_init_time": 3.2, "max_init_time": 7.8, "avg_coordination_latency": 180.5, "max_coordination_latency": 295.2 }, "resource_usage": { "avg_memory_mb": 45.3, "peak_memory_mb": 78.9, "memory_trend": "stable" }, "time_series": time_series, "baselines": { "swarm_init_time": 5.0, "agent_coordination_latency": 200.0, "memory_usage_mb": 50.0 } }, "regression_report": { "analysis_period": { "recent_period_hours": 24, "historical_period_hours": 168 }, "regression_analysis": { "swarm_init_time": { "recent_avg": 3.2, "historical_avg": 3.5, "regression_percent": -8.6, "regression_detected": False }, "memory_usage": { "recent_avg": 45.3, "historical_avg": 42.1, "regression_percent": 7.6, "regression_detected": False } } } } def _generate_html_dashboard(self, data: Dict[str, Any]) -> Path: """Generate HTML dashboard file.""" dashboard_data = data.get("last_24h", {}) regression_data = data.get("regression_report", {}) html_content = self._create_html_template(dashboard_data, regression_data) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") dashboard_file = self.output_dir / f"performance_dashboard_{timestamp}.html" with open(dashboard_file, 'w') as f: f.write(html_content) # Also create a 'latest' version latest_file = self.output_dir / "performance_dashboard_latest.html" with open(latest_file, 'w') as f: f.write(html_content) return dashboard_file def _create_html_template(self, dashboard_data: Dict[str, Any], regression_data: Dict[str, Any]) -> str: """Create HTML template with embedded data and charts.""" summary = dashboard_data.get("summary", {}) swarm_perf = dashboard_data.get("swarm_performance", {}) resource_usage = dashboard_data.get("resource_usage", {}) time_series = dashboard_data.get("time_series", []) baselines = dashboard_data.get("baselines", {}) # Create JavaScript data for charts chart_data = { "timeSeries": time_series[-50:], # Last 50 data points "baselines": baselines, "summary": summary, "swarmPerf": swarm_perf, "resourceUsage": resource_usage, "regressionData": regression_data } html_template = f"""
Real-time monitoring and performance analytics
No regression data available.
" analysis = regression_data["regression_analysis"] html_parts = [] for metric_name, metric_data in analysis.items(): regression_percent = metric_data.get("regression_percent", 0) regression_detected = metric_data.get("regression_detected", False) recent_avg = metric_data.get("recent_avg", 0) historical_avg = metric_data.get("historical_avg", 0) # Determine status class if regression_percent < -5: status_class = "improvement" icon = "š" status_text = "Improvement" elif regression_percent > 15: status_class = "critical" icon = "šØ" status_text = "Critical Regression" elif regression_percent > 5: status_class = "warning" icon = "ā ļø" status_text = "Warning" else: status_class = "" icon = "ā " status_text = "Stable" html_parts.append(f"""Status: {status_text}
Change: {regression_percent:+.1f}%
Recent Average: {recent_avg:.2f}
Historical Average: {historical_avg:.2f}