Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
dbbasic_dashboard.py · 28.0 KB · 880 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | DBBasic Dashboard Service |
| 4 | Real-time dashboard with live metrics, system status, and operations overview |
| 5 | """ |
| 6 | |
| 7 | import asyncio |
| 8 | import json |
| 9 | import logging |
| 10 | import time |
| 11 | import psutil |
| 12 | import os |
| 13 | from typing import Dict, List, Any, Optional |
| 14 | from datetime import datetime, timedelta |
| 15 | from dataclasses import dataclass, asdict |
| 16 | from pathlib import Path |
| 17 | |
| 18 | import duckdb |
| 19 | from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException |
| 20 | from fastapi.responses import HTMLResponse, JSONResponse |
| 21 | from fastapi.staticfiles import StaticFiles |
| 22 | import uvicorn |
| 23 | |
| 24 | logger = logging.getLogger(__name__) |
| 25 | |
| 26 | @dataclass |
| 27 | class SystemMetrics: |
| 28 | cpu_percent: float |
| 29 | memory_percent: float |
| 30 | disk_usage_percent: float |
| 31 | uptime_seconds: int |
| 32 | active_connections: int |
| 33 | timestamp: str |
| 34 | |
| 35 | @dataclass |
| 36 | class DatabaseMetrics: |
| 37 | total_tables: int |
| 38 | total_records: int |
| 39 | queries_per_second: float |
| 40 | avg_query_time_ms: float |
| 41 | database_size_mb: float |
| 42 | timestamp: str |
| 43 | |
| 44 | @dataclass |
| 45 | class ServiceStatus: |
| 46 | name: str |
| 47 | status: str # running, stopped, error |
| 48 | port: Optional[int] |
| 49 | uptime_seconds: int |
| 50 | last_activity: str |
| 51 | |
| 52 | @dataclass |
| 53 | class RecentActivity: |
| 54 | timestamp: str |
| 55 | action: str |
| 56 | resource: str |
| 57 | user: str |
| 58 | details: str |
| 59 | |
| 60 | class DashboardService: |
| 61 | """Real-time dashboard service providing system and application metrics""" |
| 62 | |
| 63 | def __init__(self): |
| 64 | self.start_time = time.time() |
| 65 | self.websocket_connections: List[WebSocket] = [] |
| 66 | self.query_counter = 0 |
| 67 | self.query_times = [] |
| 68 | |
| 69 | # Initialize database connections for metrics |
| 70 | self.metrics_db = duckdb.connect("dashboard_metrics.db") |
| 71 | self._init_metrics_database() |
| 72 | |
| 73 | def _init_metrics_database(self): |
| 74 | """Initialize metrics database tables""" |
| 75 | self.metrics_db.execute(""" |
| 76 | CREATE TABLE IF NOT EXISTS system_metrics ( |
| 77 | timestamp TIMESTAMP PRIMARY KEY, |
| 78 | cpu_percent FLOAT, |
| 79 | memory_percent FLOAT, |
| 80 | disk_usage_percent FLOAT, |
| 81 | active_connections INTEGER |
| 82 | ) |
| 83 | """) |
| 84 | |
| 85 | self.metrics_db.execute(""" |
| 86 | CREATE TABLE IF NOT EXISTS database_metrics ( |
| 87 | timestamp TIMESTAMP PRIMARY KEY, |
| 88 | total_tables INTEGER, |
| 89 | total_records INTEGER, |
| 90 | queries_per_second FLOAT, |
| 91 | avg_query_time_ms FLOAT, |
| 92 | database_size_mb FLOAT |
| 93 | ) |
| 94 | """) |
| 95 | |
| 96 | self.metrics_db.execute(""" |
| 97 | CREATE TABLE IF NOT EXISTS activity_log ( |
| 98 | id INTEGER PRIMARY KEY, |
| 99 | timestamp TIMESTAMP, |
| 100 | action VARCHAR(100), |
| 101 | resource VARCHAR(100), |
| 102 | user_id VARCHAR(100), |
| 103 | details TEXT |
| 104 | ) |
| 105 | """) |
| 106 | |
| 107 | def get_system_metrics(self) -> SystemMetrics: |
| 108 | """Get current system performance metrics""" |
| 109 | cpu_percent = psutil.cpu_percent(interval=0.1) |
| 110 | memory = psutil.virtual_memory() |
| 111 | disk = psutil.disk_usage('/') |
| 112 | uptime = int(time.time() - self.start_time) |
| 113 | |
| 114 | metrics = SystemMetrics( |
| 115 | cpu_percent=cpu_percent, |
| 116 | memory_percent=memory.percent, |
| 117 | disk_usage_percent=disk.percent, |
| 118 | uptime_seconds=uptime, |
| 119 | active_connections=len(self.websocket_connections), |
| 120 | timestamp=datetime.now().isoformat() |
| 121 | ) |
| 122 | |
| 123 | # Store in database |
| 124 | self.metrics_db.execute(""" |
| 125 | INSERT INTO system_metrics |
| 126 | (timestamp, cpu_percent, memory_percent, disk_usage_percent, active_connections) |
| 127 | VALUES (?, ?, ?, ?, ?) |
| 128 | """, (metrics.timestamp, metrics.cpu_percent, metrics.memory_percent, |
| 129 | metrics.disk_usage_percent, metrics.active_connections)) |
| 130 | |
| 131 | return metrics |
| 132 | |
| 133 | def get_database_metrics(self) -> DatabaseMetrics: |
| 134 | """Get database performance metrics""" |
| 135 | try: |
| 136 | # Count tables and records across all DBBasic databases |
| 137 | total_tables = 0 |
| 138 | total_records = 0 |
| 139 | total_size_mb = 0 |
| 140 | |
| 141 | # Scan for database files |
| 142 | for db_file in Path('.').glob('*.db'): |
| 143 | try: |
| 144 | conn = duckdb.connect(str(db_file)) |
| 145 | |
| 146 | # Get table count |
| 147 | tables = conn.execute("SHOW TABLES").fetchall() |
| 148 | total_tables += len(tables) |
| 149 | |
| 150 | # Get record count |
| 151 | for table in tables: |
| 152 | table_name = table[0] |
| 153 | count = conn.execute(f"SELECT COUNT(*) FROM {table_name}").fetchone()[0] |
| 154 | total_records += count |
| 155 | |
| 156 | # Get file size |
| 157 | total_size_mb += db_file.stat().st_size / (1024 * 1024) |
| 158 | |
| 159 | conn.close() |
| 160 | except Exception: |
| 161 | continue |
| 162 | |
| 163 | # Calculate query performance |
| 164 | qps = self.query_counter / max(1, time.time() - self.start_time) |
| 165 | avg_query_time = sum(self.query_times) / max(1, len(self.query_times)) |
| 166 | |
| 167 | except Exception as e: |
| 168 | logger.error(f"Error getting database metrics: {e}") |
| 169 | total_tables = 0 |
| 170 | total_records = 0 |
| 171 | total_size_mb = 0 |
| 172 | qps = 0 |
| 173 | avg_query_time = 0 |
| 174 | |
| 175 | metrics = DatabaseMetrics( |
| 176 | total_tables=total_tables, |
| 177 | total_records=total_records, |
| 178 | queries_per_second=qps, |
| 179 | avg_query_time_ms=avg_query_time, |
| 180 | database_size_mb=total_size_mb, |
| 181 | timestamp=datetime.now().isoformat() |
| 182 | ) |
| 183 | |
| 184 | # Store in database |
| 185 | self.metrics_db.execute(""" |
| 186 | INSERT INTO database_metrics |
| 187 | (timestamp, total_tables, total_records, queries_per_second, avg_query_time_ms, database_size_mb) |
| 188 | VALUES (?, ?, ?, ?, ?, ?) |
| 189 | """, (metrics.timestamp, metrics.total_tables, metrics.total_records, |
| 190 | metrics.queries_per_second, metrics.avg_query_time_ms, metrics.database_size_mb)) |
| 191 | |
| 192 | return metrics |
| 193 | |
| 194 | def get_service_status(self) -> List[ServiceStatus]: |
| 195 | """Get status of DBBasic services""" |
| 196 | services = [] |
| 197 | |
| 198 | # Common DBBasic services and their expected ports |
| 199 | service_configs = [ |
| 200 | {"name": "CRUD Engine", "port": 8005, "process": "dbbasic_crud_engine.py"}, |
| 201 | {"name": "AI Service Builder", "port": 8003, "process": "dbbasic_ai_service_builder.py"}, |
| 202 | {"name": "Real-time Monitor", "port": 8004, "process": "realtime_monitor.py"}, |
| 203 | {"name": "Event Store", "port": 8006, "process": "dbbasic_event_store.py"}, |
| 204 | {"name": "Dashboard", "port": 8007, "process": "dbbasic_dashboard.py"}, |
| 205 | ] |
| 206 | |
| 207 | for config in service_configs: |
| 208 | try: |
| 209 | # Check if process is running |
| 210 | is_running = False |
| 211 | uptime = 0 |
| 212 | |
| 213 | for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'create_time']): |
| 214 | try: |
| 215 | cmdline = ' '.join(proc.info['cmdline'] or []) |
| 216 | if config['process'] in cmdline: |
| 217 | is_running = True |
| 218 | uptime = int(time.time() - proc.info['create_time']) |
| 219 | break |
| 220 | except (psutil.NoSuchProcess, psutil.AccessDenied): |
| 221 | continue |
| 222 | |
| 223 | status = ServiceStatus( |
| 224 | name=config['name'], |
| 225 | status='running' if is_running else 'stopped', |
| 226 | port=config['port'], |
| 227 | uptime_seconds=uptime, |
| 228 | last_activity=datetime.now().isoformat() |
| 229 | ) |
| 230 | services.append(status) |
| 231 | |
| 232 | except Exception as e: |
| 233 | logger.error(f"Error checking service {config['name']}: {e}") |
| 234 | services.append(ServiceStatus( |
| 235 | name=config['name'], |
| 236 | status='error', |
| 237 | port=config['port'], |
| 238 | uptime_seconds=0, |
| 239 | last_activity=datetime.now().isoformat() |
| 240 | )) |
| 241 | |
| 242 | return services |
| 243 | |
| 244 | def get_recent_activity(self, limit: int = 10) -> List[RecentActivity]: |
| 245 | """Get recent system activity""" |
| 246 | try: |
| 247 | activities = self.metrics_db.execute(""" |
| 248 | SELECT timestamp, action, resource, user_id, details |
| 249 | FROM activity_log |
| 250 | ORDER BY timestamp DESC |
| 251 | LIMIT ? |
| 252 | """, (limit,)).fetchall() |
| 253 | |
| 254 | return [RecentActivity( |
| 255 | timestamp=row[0], |
| 256 | action=row[1], |
| 257 | resource=row[2], |
| 258 | user=row[3] or "system", |
| 259 | details=row[4] or "" |
| 260 | ) for row in activities] |
| 261 | |
| 262 | except Exception as e: |
| 263 | logger.error(f"Error getting recent activity: {e}") |
| 264 | return [] |
| 265 | |
| 266 | def log_activity(self, action: str, resource: str, user_id: str = None, details: str = None): |
| 267 | """Log system activity""" |
| 268 | try: |
| 269 | self.metrics_db.execute(""" |
| 270 | INSERT INTO activity_log (timestamp, action, resource, user_id, details) |
| 271 | VALUES (?, ?, ?, ?, ?) |
| 272 | """, (datetime.now().isoformat(), action, resource, user_id, details)) |
| 273 | except Exception as e: |
| 274 | logger.error(f"Error logging activity: {e}") |
| 275 | |
| 276 | def record_query(self, query_time_ms: float): |
| 277 | """Record query execution time for performance metrics""" |
| 278 | self.query_counter += 1 |
| 279 | self.query_times.append(query_time_ms) |
| 280 | |
| 281 | # Keep only last 1000 query times to prevent memory growth |
| 282 | if len(self.query_times) > 1000: |
| 283 | self.query_times = self.query_times[-1000:] |
| 284 | |
| 285 | async def broadcast_metrics(self): |
| 286 | """Broadcast real-time metrics to all connected websockets""" |
| 287 | if not self.websocket_connections: |
| 288 | return |
| 289 | |
| 290 | try: |
| 291 | system_metrics = self.get_system_metrics() |
| 292 | database_metrics = self.get_database_metrics() |
| 293 | service_status = self.get_service_status() |
| 294 | recent_activity = self.get_recent_activity(5) |
| 295 | |
| 296 | dashboard_data = { |
| 297 | "type": "metrics_update", |
| 298 | "system_metrics": asdict(system_metrics), |
| 299 | "database_metrics": asdict(database_metrics), |
| 300 | "service_status": [asdict(s) for s in service_status], |
| 301 | "recent_activity": [asdict(a) for a in recent_activity], |
| 302 | "timestamp": datetime.now().isoformat() |
| 303 | } |
| 304 | |
| 305 | # Send to all connected clients |
| 306 | disconnected = [] |
| 307 | for websocket in self.websocket_connections: |
| 308 | try: |
| 309 | await websocket.send_text(json.dumps(dashboard_data)) |
| 310 | except Exception: |
| 311 | disconnected.append(websocket) |
| 312 | |
| 313 | # Remove disconnected clients |
| 314 | for ws in disconnected: |
| 315 | self.websocket_connections.remove(ws) |
| 316 | |
| 317 | except Exception as e: |
| 318 | logger.error(f"Error broadcasting metrics: {e}") |
| 319 | |
| 320 | async def add_websocket(self, websocket: WebSocket): |
| 321 | """Add new websocket connection""" |
| 322 | await websocket.accept() |
| 323 | self.websocket_connections.append(websocket) |
| 324 | |
| 325 | # Send initial data immediately |
| 326 | await self.broadcast_metrics() |
| 327 | |
| 328 | def remove_websocket(self, websocket: WebSocket): |
| 329 | """Remove websocket connection""" |
| 330 | if websocket in self.websocket_connections: |
| 331 | self.websocket_connections.remove(websocket) |
| 332 | |
| 333 | # Global dashboard service instance |
| 334 | dashboard_service = DashboardService() |
| 335 | |
| 336 | # FastAPI application |
| 337 | app = FastAPI(title="DBBasic Dashboard", version="1.0.0") |
| 338 | |
| 339 | # Mount static files |
| 340 | app.mount("/static", StaticFiles(directory="static"), name="static") |
| 341 | |
| 342 | @app.get("/", response_class=HTMLResponse) |
| 343 | async def dashboard_page(): |
| 344 | """Serve the main dashboard page""" |
| 345 | # Read the dashboard template and make it functional |
| 346 | dashboard_html = """ |
| 347 | <!DOCTYPE html> |
| 348 | <html lang="en"> |
| 349 | <head> |
| 350 | <meta charset="UTF-8"> |
| 351 | <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 352 | <title>DBBasic Dashboard - Live Metrics</title> |
| 353 | <style> |
| 354 | * { |
| 355 | margin: 0; |
| 356 | padding: 0; |
| 357 | box-sizing: border-box; |
| 358 | } |
| 359 | |
| 360 | body { |
| 361 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; |
| 362 | background: #f5f5f5; |
| 363 | color: #333; |
| 364 | } |
| 365 | |
| 366 | .header { |
| 367 | background: #fff; |
| 368 | border-bottom: 1px solid #e0e0e0; |
| 369 | padding: 1rem 2rem; |
| 370 | display: flex; |
| 371 | justify-content: space-between; |
| 372 | align-items: center; |
| 373 | position: sticky; |
| 374 | top: 0; |
| 375 | z-index: 100; |
| 376 | } |
| 377 | |
| 378 | .logo { |
| 379 | font-family: 'Times New Roman', Times, serif; |
| 380 | font-size: 24px; |
| 381 | font-weight: bold; |
| 382 | color: #2c3e50; |
| 383 | } |
| 384 | |
| 385 | .speed-badge { |
| 386 | background: #4CAF50; |
| 387 | color: white; |
| 388 | padding: 0.25rem 0.75rem; |
| 389 | border-radius: 20px; |
| 390 | font-size: 12px; |
| 391 | font-weight: bold; |
| 392 | } |
| 393 | |
| 394 | .nav { |
| 395 | display: flex; |
| 396 | gap: 2rem; |
| 397 | } |
| 398 | |
| 399 | .nav a { |
| 400 | color: #666; |
| 401 | text-decoration: none; |
| 402 | padding: 0.5rem 1rem; |
| 403 | border-radius: 8px; |
| 404 | transition: all 0.2s; |
| 405 | } |
| 406 | |
| 407 | .nav a:hover { |
| 408 | background: #f0f0f0; |
| 409 | color: #333; |
| 410 | } |
| 411 | |
| 412 | .nav a.active { |
| 413 | background: #4CAF50; |
| 414 | color: white; |
| 415 | } |
| 416 | |
| 417 | .main { |
| 418 | padding: 2rem; |
| 419 | max-width: 1400px; |
| 420 | margin: 0 auto; |
| 421 | } |
| 422 | |
| 423 | .metrics-grid { |
| 424 | display: grid; |
| 425 | grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); |
| 426 | gap: 1.5rem; |
| 427 | margin-bottom: 2rem; |
| 428 | } |
| 429 | |
| 430 | .metric-card { |
| 431 | background: white; |
| 432 | border-radius: 12px; |
| 433 | padding: 1.5rem; |
| 434 | box-shadow: 0 2px 10px rgba(0,0,0,0.1); |
| 435 | } |
| 436 | |
| 437 | .metric-header { |
| 438 | display: flex; |
| 439 | justify-content: space-between; |
| 440 | align-items: center; |
| 441 | margin-bottom: 1rem; |
| 442 | } |
| 443 | |
| 444 | .metric-title { |
| 445 | font-size: 14px; |
| 446 | color: #666; |
| 447 | text-transform: uppercase; |
| 448 | letter-spacing: 0.5px; |
| 449 | } |
| 450 | |
| 451 | .metric-value { |
| 452 | font-size: 32px; |
| 453 | font-weight: bold; |
| 454 | color: #2c3e50; |
| 455 | } |
| 456 | |
| 457 | .metric-unit { |
| 458 | font-size: 16px; |
| 459 | color: #666; |
| 460 | margin-left: 0.5rem; |
| 461 | } |
| 462 | |
| 463 | .status-indicator { |
| 464 | width: 12px; |
| 465 | height: 12px; |
| 466 | border-radius: 50%; |
| 467 | background: #4CAF50; |
| 468 | display: inline-block; |
| 469 | margin-right: 0.5rem; |
| 470 | } |
| 471 | |
| 472 | .status-indicator.warning { |
| 473 | background: #FF9800; |
| 474 | } |
| 475 | |
| 476 | .status-indicator.error { |
| 477 | background: #f44336; |
| 478 | } |
| 479 | |
| 480 | .progress-bar { |
| 481 | background: #e0e0e0; |
| 482 | height: 8px; |
| 483 | border-radius: 4px; |
| 484 | overflow: hidden; |
| 485 | margin-top: 0.5rem; |
| 486 | } |
| 487 | |
| 488 | .progress-fill { |
| 489 | height: 100%; |
| 490 | background: #4CAF50; |
| 491 | transition: width 0.3s; |
| 492 | } |
| 493 | |
| 494 | .services-grid { |
| 495 | display: grid; |
| 496 | grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); |
| 497 | gap: 1rem; |
| 498 | margin-bottom: 2rem; |
| 499 | } |
| 500 | |
| 501 | .service-card { |
| 502 | background: white; |
| 503 | border-radius: 8px; |
| 504 | padding: 1rem; |
| 505 | box-shadow: 0 2px 8px rgba(0,0,0,0.08); |
| 506 | display: flex; |
| 507 | align-items: center; |
| 508 | gap: 1rem; |
| 509 | } |
| 510 | |
| 511 | .service-info h3 { |
| 512 | font-size: 14px; |
| 513 | margin-bottom: 0.25rem; |
| 514 | } |
| 515 | |
| 516 | .service-details { |
| 517 | font-size: 12px; |
| 518 | color: #666; |
| 519 | } |
| 520 | |
| 521 | .activity-feed { |
| 522 | background: white; |
| 523 | border-radius: 12px; |
| 524 | padding: 1.5rem; |
| 525 | box-shadow: 0 2px 10px rgba(0,0,0,0.1); |
| 526 | } |
| 527 | |
| 528 | .activity-header { |
| 529 | font-size: 16px; |
| 530 | font-weight: bold; |
| 531 | margin-bottom: 1rem; |
| 532 | display: flex; |
| 533 | align-items: center; |
| 534 | gap: 0.5rem; |
| 535 | } |
| 536 | |
| 537 | .activity-item { |
| 538 | display: flex; |
| 539 | align-items: center; |
| 540 | gap: 1rem; |
| 541 | padding: 0.75rem 0; |
| 542 | border-bottom: 1px solid #f0f0f0; |
| 543 | } |
| 544 | |
| 545 | .activity-item:last-child { |
| 546 | border-bottom: none; |
| 547 | } |
| 548 | |
| 549 | .activity-time { |
| 550 | font-size: 12px; |
| 551 | color: #666; |
| 552 | min-width: 60px; |
| 553 | } |
| 554 | |
| 555 | .activity-text { |
| 556 | font-size: 14px; |
| 557 | } |
| 558 | |
| 559 | .live-indicator { |
| 560 | display: inline-flex; |
| 561 | align-items: center; |
| 562 | gap: 0.5rem; |
| 563 | font-size: 12px; |
| 564 | color: #4CAF50; |
| 565 | font-weight: bold; |
| 566 | } |
| 567 | |
| 568 | .pulse { |
| 569 | width: 8px; |
| 570 | height: 8px; |
| 571 | background: #4CAF50; |
| 572 | border-radius: 50%; |
| 573 | animation: pulse 2s infinite; |
| 574 | } |
| 575 | |
| 576 | @keyframes pulse { |
| 577 | 0% { opacity: 1; } |
| 578 | 50% { opacity: 0.5; } |
| 579 | 100% { opacity: 1; } |
| 580 | } |
| 581 | |
| 582 | .offline { |
| 583 | opacity: 0.6; |
| 584 | } |
| 585 | |
| 586 | .offline .live-indicator { |
| 587 | color: #f44336; |
| 588 | } |
| 589 | |
| 590 | .offline .pulse { |
| 591 | background: #f44336; |
| 592 | } |
| 593 | </style> |
| 594 | </head> |
| 595 | <body> |
| 596 | <header class="header"> |
| 597 | <div> |
| 598 | <div class="logo">DBBasic</div> |
| 599 | <div class="speed-badge">402M rows/sec</div> |
| 600 | </div> |
| 601 | <nav class="nav"> |
| 602 | <a href="#" class="active">Dashboard</a> |
| 603 | <a href="/">CRUD Engine</a> |
| 604 | <a href="/static/ai_service_builder.html">AI Services</a> |
| 605 | <a href="/static/mockups.html">Mockups</a> |
| 606 | <a href="/docs">API Docs</a> |
| 607 | </nav> |
| 608 | <div class="live-indicator"> |
| 609 | <div class="pulse"></div> |
| 610 | <span id="connection-status">LIVE</span> |
| 611 | </div> |
| 612 | </header> |
| 613 | |
| 614 | <main class="main"> |
| 615 | <div class="metrics-grid"> |
| 616 | <div class="metric-card"> |
| 617 | <div class="metric-header"> |
| 618 | <div class="metric-title">CPU Usage</div> |
| 619 | <div class="status-indicator" id="cpu-status"></div> |
| 620 | </div> |
| 621 | <div class="metric-value" id="cpu-value">0<span class="metric-unit">%</span></div> |
| 622 | <div class="progress-bar"> |
| 623 | <div class="progress-fill" id="cpu-progress"></div> |
| 624 | </div> |
| 625 | </div> |
| 626 | |
| 627 | <div class="metric-card"> |
| 628 | <div class="metric-header"> |
| 629 | <div class="metric-title">Memory Usage</div> |
| 630 | <div class="status-indicator" id="memory-status"></div> |
| 631 | </div> |
| 632 | <div class="metric-value" id="memory-value">0<span class="metric-unit">%</span></div> |
| 633 | <div class="progress-bar"> |
| 634 | <div class="progress-fill" id="memory-progress"></div> |
| 635 | </div> |
| 636 | </div> |
| 637 | |
| 638 | <div class="metric-card"> |
| 639 | <div class="metric-header"> |
| 640 | <div class="metric-title">Total Records</div> |
| 641 | <div class="status-indicator"></div> |
| 642 | </div> |
| 643 | <div class="metric-value" id="records-value">0</div> |
| 644 | </div> |
| 645 | |
| 646 | <div class="metric-card"> |
| 647 | <div class="metric-header"> |
| 648 | <div class="metric-title">Queries/Second</div> |
| 649 | <div class="status-indicator"></div> |
| 650 | </div> |
| 651 | <div class="metric-value" id="qps-value">0</div> |
| 652 | </div> |
| 653 | |
| 654 | <div class="metric-card"> |
| 655 | <div class="metric-header"> |
| 656 | <div class="metric-title">Active Tables</div> |
| 657 | <div class="status-indicator"></div> |
| 658 | </div> |
| 659 | <div class="metric-value" id="tables-value">0</div> |
| 660 | </div> |
| 661 | |
| 662 | <div class="metric-card"> |
| 663 | <div class="metric-header"> |
| 664 | <div class="metric-title">Database Size</div> |
| 665 | <div class="status-indicator"></div> |
| 666 | </div> |
| 667 | <div class="metric-value" id="db-size-value">0<span class="metric-unit">MB</span></div> |
| 668 | </div> |
| 669 | </div> |
| 670 | |
| 671 | <div class="services-grid" id="services-grid"> |
| 672 | <!-- Services will be populated dynamically --> |
| 673 | </div> |
| 674 | |
| 675 | <div class="activity-feed"> |
| 676 | <div class="activity-header"> |
| 677 | 🕐 Recent Activity |
| 678 | </div> |
| 679 | <div id="activity-list"> |
| 680 | <!-- Activity items will be populated dynamically --> |
| 681 | </div> |
| 682 | </div> |
| 683 | </main> |
| 684 | |
| 685 | <script> |
| 686 | let ws = null; |
| 687 | let reconnectTimeout = null; |
| 688 | |
| 689 | function connectWebSocket() { |
| 690 | const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; |
| 691 | const wsUrl = `${protocol}//${window.location.host}/ws`; |
| 692 | |
| 693 | ws = new WebSocket(wsUrl); |
| 694 | |
| 695 | ws.onopen = function(event) { |
| 696 | console.log('WebSocket connected'); |
| 697 | document.getElementById('connection-status').textContent = 'LIVE'; |
| 698 | document.body.classList.remove('offline'); |
| 699 | |
| 700 | if (reconnectTimeout) { |
| 701 | clearTimeout(reconnectTimeout); |
| 702 | reconnectTimeout = null; |
| 703 | } |
| 704 | }; |
| 705 | |
| 706 | ws.onmessage = function(event) { |
| 707 | const data = JSON.parse(event.data); |
| 708 | updateDashboard(data); |
| 709 | }; |
| 710 | |
| 711 | ws.onclose = function(event) { |
| 712 | console.log('WebSocket disconnected'); |
| 713 | document.getElementById('connection-status').textContent = 'OFFLINE'; |
| 714 | document.body.classList.add('offline'); |
| 715 | |
| 716 | // Attempt to reconnect after 3 seconds |
| 717 | reconnectTimeout = setTimeout(connectWebSocket, 3000); |
| 718 | }; |
| 719 | |
| 720 | ws.onerror = function(error) { |
| 721 | console.error('WebSocket error:', error); |
| 722 | }; |
| 723 | } |
| 724 | |
| 725 | function updateDashboard(data) { |
| 726 | if (data.type === 'metrics_update') { |
| 727 | // Update system metrics |
| 728 | const systemMetrics = data.system_metrics; |
| 729 | updateMetric('cpu', systemMetrics.cpu_percent); |
| 730 | updateMetric('memory', systemMetrics.memory_percent); |
| 731 | |
| 732 | // Update database metrics |
| 733 | const dbMetrics = data.database_metrics; |
| 734 | document.getElementById('records-value').textContent = dbMetrics.total_records.toLocaleString(); |
| 735 | document.getElementById('qps-value').textContent = dbMetrics.queries_per_second.toFixed(1); |
| 736 | document.getElementById('tables-value').textContent = dbMetrics.total_tables; |
| 737 | document.getElementById('db-size-value').innerHTML = dbMetrics.database_size_mb.toFixed(1) + '<span class="metric-unit">MB</span>'; |
| 738 | |
| 739 | // Update services |
| 740 | updateServices(data.service_status); |
| 741 | |
| 742 | // Update activity |
| 743 | updateActivity(data.recent_activity); |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | function updateMetric(name, value) { |
| 748 | const valueElement = document.getElementById(name + '-value'); |
| 749 | const progressElement = document.getElementById(name + '-progress'); |
| 750 | const statusElement = document.getElementById(name + '-status'); |
| 751 | |
| 752 | valueElement.innerHTML = Math.round(value) + '<span class="metric-unit">%</span>'; |
| 753 | progressElement.style.width = value + '%'; |
| 754 | |
| 755 | // Update status indicator color |
| 756 | if (value > 80) { |
| 757 | statusElement.className = 'status-indicator error'; |
| 758 | } else if (value > 60) { |
| 759 | statusElement.className = 'status-indicator warning'; |
| 760 | } else { |
| 761 | statusElement.className = 'status-indicator'; |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | function updateServices(services) { |
| 766 | const grid = document.getElementById('services-grid'); |
| 767 | grid.innerHTML = ''; |
| 768 | |
| 769 | services.forEach(service => { |
| 770 | const serviceCard = document.createElement('div'); |
| 771 | serviceCard.className = 'service-card'; |
| 772 | |
| 773 | const statusClass = service.status === 'running' ? '' : |
| 774 | service.status === 'error' ? 'error' : 'warning'; |
| 775 | |
| 776 | const uptime = service.uptime_seconds > 0 ? formatUptime(service.uptime_seconds) : 'Not running'; |
| 777 | |
| 778 | serviceCard.innerHTML = ` |
| 779 | <div class="status-indicator ${statusClass}"></div> |
| 780 | <div class="service-info"> |
| 781 | <h3>${service.name}</h3> |
| 782 | <div class="service-details"> |
| 783 | Port ${service.port} • ${uptime} |
| 784 | </div> |
| 785 | </div> |
| 786 | `; |
| 787 | |
| 788 | grid.appendChild(serviceCard); |
| 789 | }); |
| 790 | } |
| 791 | |
| 792 | function updateActivity(activities) { |
| 793 | const list = document.getElementById('activity-list'); |
| 794 | list.innerHTML = ''; |
| 795 | |
| 796 | activities.forEach(activity => { |
| 797 | const item = document.createElement('div'); |
| 798 | item.className = 'activity-item'; |
| 799 | |
| 800 | const time = new Date(activity.timestamp).toLocaleTimeString(); |
| 801 | |
| 802 | item.innerHTML = ` |
| 803 | <div class="activity-time">${time}</div> |
| 804 | <div class="activity-text"> |
| 805 | <strong>${activity.action}</strong> ${activity.resource} |
| 806 | ${activity.user ? 'by ' + activity.user : ''} |
| 807 | </div> |
| 808 | `; |
| 809 | |
| 810 | list.appendChild(item); |
| 811 | }); |
| 812 | } |
| 813 | |
| 814 | function formatUptime(seconds) { |
| 815 | const hours = Math.floor(seconds / 3600); |
| 816 | const minutes = Math.floor((seconds % 3600) / 60); |
| 817 | |
| 818 | if (hours > 0) { |
| 819 | return `${hours}h ${minutes}m`; |
| 820 | } else { |
| 821 | return `${minutes}m`; |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | // Initialize dashboard |
| 826 | connectWebSocket(); |
| 827 | </script> |
| 828 | </body> |
| 829 | </html> |
| 830 | """ |
| 831 | return dashboard_html |
| 832 | |
| 833 | @app.websocket("/ws") |
| 834 | async def websocket_endpoint(websocket: WebSocket): |
| 835 | """WebSocket endpoint for real-time dashboard updates""" |
| 836 | await dashboard_service.add_websocket(websocket) |
| 837 | try: |
| 838 | while True: |
| 839 | # Keep connection alive and listen for client messages |
| 840 | await websocket.receive_text() |
| 841 | except WebSocketDisconnect: |
| 842 | dashboard_service.remove_websocket(websocket) |
| 843 | |
| 844 | @app.get("/api/metrics") |
| 845 | async def get_metrics(): |
| 846 | """Get current dashboard metrics as JSON""" |
| 847 | system_metrics = dashboard_service.get_system_metrics() |
| 848 | database_metrics = dashboard_service.get_database_metrics() |
| 849 | service_status = dashboard_service.get_service_status() |
| 850 | recent_activity = dashboard_service.get_recent_activity() |
| 851 | |
| 852 | return { |
| 853 | "system_metrics": asdict(system_metrics), |
| 854 | "database_metrics": asdict(database_metrics), |
| 855 | "service_status": [asdict(s) for s in service_status], |
| 856 | "recent_activity": [asdict(a) for a in recent_activity] |
| 857 | } |
| 858 | |
| 859 | @app.post("/api/activity") |
| 860 | async def log_activity_endpoint(action: str, resource: str, user_id: str = None, details: str = None): |
| 861 | """Log system activity""" |
| 862 | dashboard_service.log_activity(action, resource, user_id, details) |
| 863 | return {"status": "logged"} |
| 864 | |
| 865 | # Background task to broadcast metrics periodically |
| 866 | async def periodic_metrics_broadcast(): |
| 867 | """Periodically broadcast metrics to connected clients""" |
| 868 | while True: |
| 869 | await dashboard_service.broadcast_metrics() |
| 870 | await asyncio.sleep(2) # Update every 2 seconds |
| 871 | |
| 872 | @app.on_event("startup") |
| 873 | async def startup_event(): |
| 874 | """Start background tasks when the application starts""" |
| 875 | asyncio.create_task(periodic_metrics_broadcast()) |
| 876 | logger.info("🏠 DBBasic Dashboard started on port 8007") |
| 877 | |
| 878 | if __name__ == "__main__": |
| 879 | logging.basicConfig(level=logging.INFO) |
| 880 | uvicorn.run(app, host="0.0.0.0", port=8007) |