Files
crawl4ai/deploy/docker/static/monitor/index.html
unclecode e2af031b09 feat(monitor): add real-time monitoring dashboard with Redis persistence
Complete observability solution for production deployments with terminal-style UI.

**Backend Implementation:**
- `monitor.py`: Stats manager tracking requests, browsers, errors, timeline data
- `monitor_routes.py`: REST API endpoints for all monitor functionality
  - GET /monitor/health - System health snapshot
  - GET /monitor/requests - Active & completed requests
  - GET /monitor/browsers - Browser pool details
  - GET /monitor/endpoints/stats - Aggregated endpoint analytics
  - GET /monitor/timeline - Time-series data (memory, requests, browsers)
  - GET /monitor/logs/{janitor,errors} - Event logs
  - POST /monitor/actions/{cleanup,kill_browser,restart_browser} - Control actions
  - POST /monitor/stats/reset - Reset counters
- Redis persistence for endpoint stats (survives restart)
- Timeline tracking (5min window, 5s resolution, 60 data points)

**Frontend Dashboard** (`/dashboard`):
- **System Health Bar**: CPU%, Memory%, Network I/O, Uptime
- **Pool Status**: Live counts (permanent/hot/cold browsers + memory)
- **Live Activity Tabs**:
  - Requests: Active (realtime) + recent completed (last 100)
  - Browsers: Detailed table with actions (kill/restart)
  - Janitor: Cleanup event log with timestamps
  - Errors: Recent errors with stack traces
- **Endpoint Analytics**: Count, avg latency, success%, pool hit%
- **Resource Timeline**: SVG charts (memory/requests/browsers) with terminal aesthetics
- **Control Actions**: Force cleanup, restart permanent, reset stats
- **Auto-refresh**: 5s polling (toggleable)

**Integration:**
- Janitor events tracked (close_cold, close_hot, promote)
- Crawler pool promotion events logged
- Timeline updater background task (5s interval)
- Lifespan hooks for monitor initialization

**UI Design:**
- Terminal vibe matching Crawl4AI theme
- Dark background, cyan/pink accents, monospace font
- Neon glow effects on charts
- Responsive layout, hover interactions
- Cross-navigation: Playground ↔ Monitor

**Key Features:**
- Zero-config: Works out of the box with existing Redis
- Real-time visibility into pool efficiency
- Manual browser management (kill/restart)
- Historical data persistence
- DevOps-friendly UX

Routes:
- API: `/monitor/*` (backend endpoints)
- UI: `/dashboard` (static HTML)
2025-10-17 21:36:25 +08:00

814 lines
37 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crawl4AI Monitor</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#4EFFFF',
primarydim: '#09b5a5',
accent: '#F380F5',
dark: '#070708',
light: '#E8E9ED',
secondary: '#D5CEBF',
codebg: '#1E1E1E',
surface: '#202020',
border: '#3F3F44',
},
fontFamily: {
mono: ['Fira Code', 'monospace'],
},
}
}
}
</script>
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
<style>
@keyframes pulse-slow {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.pulse-slow { animation: pulse-slow 2s ease-in-out infinite; }
@keyframes spin-slow {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spin-slow { animation: spin-slow 3s linear infinite; }
/* Progress bar animation */
.progress-bar {
transition: width 0.3s ease;
}
/* Sparkline styles */
.sparkline {
stroke-linecap: round;
stroke-linejoin: round;
}
/* Table hover */
tbody tr:hover {
background-color: rgba(78, 255, 255, 0.05);
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #070708;
}
::-webkit-scrollbar-thumb {
background: #3F3F44;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #4EFFFF;
}
</style>
</head>
<body class="bg-dark text-light font-mono min-h-screen flex flex-col" style="font-feature-settings: 'calt' 0;">
<!-- Header -->
<header class="border-b border-border px-4 py-2 flex items-center">
<h1 class="text-lg font-medium flex items-center space-x-4">
<span>📊 <span class="text-primary">Crawl4AI</span> Monitor</span>
<a href="https://github.com/unclecode/crawl4ai" target="_blank" class="flex space-x-1">
<img src="https://img.shields.io/github/stars/unclecode/crawl4ai?style=social" alt="GitHub stars" class="h-5">
</a>
</h1>
<div class="ml-auto flex items-center space-x-4">
<!-- Auto-refresh toggle -->
<div class="flex items-center space-x-2">
<label class="text-xs text-secondary">Auto-refresh:</label>
<button id="auto-refresh-toggle" class="px-2 py-1 rounded text-xs bg-primary text-dark">
ON ⚡5s
</button>
</div>
<!-- Navigation -->
<a href="/playground" class="text-xs text-secondary hover:text-primary underline">Playground</a>
</div>
</header>
<!-- Main Content -->
<main class="flex-1 overflow-auto p-4 space-y-4">
<!-- System Health Bar -->
<section class="bg-surface rounded-lg border border-border p-4">
<h2 class="text-sm font-medium mb-3 text-primary">System Health</h2>
<div class="grid grid-cols-4 gap-4 mb-4">
<!-- CPU -->
<div>
<div class="flex justify-between text-xs mb-1">
<span class="text-secondary">CPU</span>
<span id="cpu-percent" class="text-light">--%</span>
</div>
<div class="w-full bg-dark rounded-full h-2">
<div id="cpu-bar" class="progress-bar h-2 rounded-full bg-primary" style="width: 0%"></div>
</div>
</div>
<!-- Memory -->
<div>
<div class="flex justify-between text-xs mb-1">
<span class="text-secondary">Memory</span>
<span id="mem-percent" class="text-light">--%</span>
</div>
<div class="w-full bg-dark rounded-full h-2">
<div id="mem-bar" class="progress-bar h-2 rounded-full bg-accent" style="width: 0%"></div>
</div>
</div>
<!-- Network -->
<div>
<div class="flex justify-between text-xs mb-1">
<span class="text-secondary">Network</span>
<span id="net-io" class="text-light">--</span>
</div>
<div class="text-xs text-secondary"><span id="net-sent">0</span> MB / ⬇<span id="net-recv">0</span> MB</div>
</div>
<!-- Uptime -->
<div>
<div class="flex justify-between text-xs mb-1">
<span class="text-secondary">Uptime</span>
<span id="uptime" class="text-light">--</span>
</div>
<div class="text-xs text-secondary" id="last-update">Updated: never</div>
</div>
</div>
<!-- Pool Status -->
<div class="border-t border-border pt-3">
<div class="grid grid-cols-3 gap-4 text-xs">
<div>
<span class="text-secondary">🔥 Permanent:</span>
<span id="pool-perm" class="text-primary ml-2">INACTIVE (0MB)</span>
</div>
<div>
<span class="text-secondary">♨️ Hot:</span>
<span id="pool-hot" class="text-accent ml-2">0 (0MB)</span>
</div>
<div>
<span class="text-secondary">❄️ Cold:</span>
<span id="pool-cold" class="text-light ml-2">0 (0MB)</span>
</div>
</div>
<div class="mt-2 text-xs text-secondary">
<span>Janitor: </span><span id="janitor-status">adaptive</span> |
<span>Memory pressure: </span><span id="mem-pressure">LOW</span>
</div>
</div>
</section>
<!-- Live Activity (Tabbed) -->
<section class="bg-surface rounded-lg border border-border overflow-hidden flex flex-col" style="height: 400px;">
<div class="border-b border-border flex">
<button data-tab="requests" class="activity-tab px-4 py-2 border-r border-border bg-dark text-primary">Requests</button>
<button data-tab="browsers" class="activity-tab px-4 py-2 border-r border-border">Browsers</button>
<button data-tab="janitor" class="activity-tab px-4 py-2 border-r border-border">Janitor</button>
<button data-tab="errors" class="activity-tab px-4 py-2">Errors</button>
</div>
<div class="flex-1 overflow-auto p-3">
<!-- Requests Tab -->
<div id="tab-requests" class="activity-content">
<div class="mb-3 flex items-center justify-between">
<h3 class="text-sm font-medium">Active Requests (<span id="active-count">0</span>)</h3>
<select id="filter-requests" class="bg-dark border border-border rounded px-2 py-1 text-xs">
<option value="all">All</option>
<option value="success">Success Only</option>
<option value="error">Errors Only</option>
</select>
</div>
<div class="space-y-2">
<div id="active-requests-list" class="text-xs space-y-1">
<div class="text-secondary text-center py-4">No active requests</div>
</div>
<h4 class="text-xs font-medium text-secondary mt-4 mb-2">Recent Completed</h4>
<div id="completed-requests-list" class="text-xs space-y-1">
<div class="text-secondary text-center py-4">No completed requests</div>
</div>
</div>
</div>
<!-- Browsers Tab -->
<div id="tab-browsers" class="activity-content hidden">
<div class="mb-3">
<h3 class="text-sm font-medium mb-2">Browser Pool (<span id="browser-count">0</span> browsers, <span id="browser-mem">0</span> MB)</h3>
<div class="text-xs text-secondary">
Reuse rate: <span id="reuse-rate" class="text-primary">--%</span>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full text-xs">
<thead class="border-b border-border">
<tr class="text-secondary text-left">
<th class="py-2 pr-4">Type</th>
<th class="py-2 pr-4">Signature</th>
<th class="py-2 pr-4">Age</th>
<th class="py-2 pr-4">Last Used</th>
<th class="py-2 pr-4">Memory</th>
<th class="py-2 pr-4">Hits</th>
<th class="py-2">Actions</th>
</tr>
</thead>
<tbody id="browsers-table-body">
<tr><td colspan="7" class="text-center py-4 text-secondary">No browsers</td></tr>
</tbody>
</table>
</div>
</div>
<!-- Janitor Tab -->
<div id="tab-janitor" class="activity-content hidden">
<h3 class="text-sm font-medium mb-3">Cleanup Events (Last 100)</h3>
<div id="janitor-log" class="text-xs space-y-1 font-mono">
<div class="text-secondary text-center py-4">No events yet</div>
</div>
</div>
<!-- Errors Tab -->
<div id="tab-errors" class="activity-content hidden">
<h3 class="text-sm font-medium mb-3">Recent Errors (Last 100)</h3>
<div id="errors-log" class="text-xs space-y-2">
<div class="text-secondary text-center py-4">No errors</div>
</div>
</div>
</div>
</section>
<!-- Endpoint Analytics & Timeline (Side by side) -->
<div class="grid grid-cols-2 gap-4">
<!-- Endpoint Analytics -->
<section class="bg-surface rounded-lg border border-border p-4">
<h2 class="text-sm font-medium mb-3 text-primary">Endpoint Analytics</h2>
<div class="overflow-x-auto">
<table class="w-full text-xs">
<thead class="border-b border-border">
<tr class="text-secondary text-left">
<th class="py-2 pr-4">Endpoint</th>
<th class="py-2 pr-4 text-right">Count</th>
<th class="py-2 pr-4 text-right">Avg Latency</th>
<th class="py-2 pr-4 text-right">Success%</th>
<th class="py-2 pr-4 text-right">Pool%</th>
</tr>
</thead>
<tbody id="endpoints-table-body">
<tr><td colspan="5" class="text-center py-4 text-secondary">No data</td></tr>
</tbody>
</table>
</div>
</section>
<!-- Resource Timeline -->
<section class="bg-surface rounded-lg border border-border p-4">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-medium text-primary">Resource Timeline (5min)</h2>
<select id="timeline-metric" class="bg-dark border border-border rounded px-2 py-1 text-xs">
<option value="memory">Memory %</option>
<option value="requests">Requests/5s</option>
<option value="browsers">Browser Count</option>
</select>
</div>
<svg id="timeline-chart" class="w-full" style="height: 120px;" viewBox="0 0 400 120">
<!-- Chart will be drawn here -->
<text x="200" y="60" text-anchor="middle" fill="#D5CEBF" font-size="12">Loading...</text>
</svg>
</section>
</div>
<!-- Control Actions -->
<section class="bg-surface rounded-lg border border-accent p-4">
<h2 class="text-sm font-medium mb-3 text-accent">Control Actions</h2>
<div class="flex flex-wrap gap-2">
<button id="btn-force-cleanup" class="px-3 py-1 bg-accent text-dark rounded text-xs hover:opacity-90">
🧹 Force Cleanup
</button>
<button id="btn-restart-perm" class="px-3 py-1 bg-primary text-dark rounded text-xs hover:opacity-90">
🔄 Restart Permanent
</button>
<button id="btn-reset-stats" class="px-3 py-1 border border-border rounded text-xs hover:bg-dark">
📊 Reset Stats
</button>
<div class="ml-auto text-xs text-secondary" id="action-status"></div>
</div>
</section>
</main>
<script>
// ========== State Management ==========
let autoRefresh = true;
let refreshInterval;
const REFRESH_RATE = 5000; // 5 seconds
// ========== Tab Switching ==========
document.querySelectorAll('.activity-tab').forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
// Update tabs
document.querySelectorAll('.activity-tab').forEach(b => {
b.classList.remove('bg-dark', 'text-primary');
});
btn.classList.add('bg-dark', 'text-primary');
// Update content
document.querySelectorAll('.activity-content').forEach(c => c.classList.add('hidden'));
document.getElementById(`tab-${tab}`).classList.remove('hidden');
// Fetch specific data
if (tab === 'browsers') fetchBrowsers();
if (tab === 'janitor') fetchJanitorLog();
if (tab === 'errors') fetchErrors();
});
});
// ========== Auto-refresh Toggle ==========
document.getElementById('auto-refresh-toggle').addEventListener('click', function() {
autoRefresh = !autoRefresh;
this.textContent = autoRefresh ? 'ON ⚡5s' : 'OFF';
this.classList.toggle('bg-primary');
this.classList.toggle('bg-dark');
this.classList.toggle('text-dark');
this.classList.toggle('text-light');
if (autoRefresh) {
startAutoRefresh();
} else {
stopAutoRefresh();
}
});
function startAutoRefresh() {
fetchAll();
refreshInterval = setInterval(fetchAll, REFRESH_RATE);
}
function stopAutoRefresh() {
if (refreshInterval) clearInterval(refreshInterval);
}
// ========== Data Fetching ==========
async function fetchAll() {
await Promise.all([
fetchHealth(),
fetchRequests(),
fetchEndpointStats(),
fetchTimeline()
]);
}
async function fetchHealth() {
try {
const res = await fetch('/monitor/health');
const data = await res.json();
// Container metrics
const cpu = data.container.cpu_percent;
const mem = data.container.memory_percent;
document.getElementById('cpu-percent').textContent = cpu.toFixed(1) + '%';
document.getElementById('cpu-bar').style.width = Math.min(cpu, 100) + '%';
document.getElementById('cpu-bar').className = `progress-bar h-2 rounded-full ${cpu > 80 ? 'bg-red-500' : cpu > 60 ? 'bg-yellow-500' : 'bg-primary'}`;
document.getElementById('mem-percent').textContent = mem.toFixed(1) + '%';
document.getElementById('mem-bar').style.width = Math.min(mem, 100) + '%';
document.getElementById('mem-bar').className = `progress-bar h-2 rounded-full ${mem > 80 ? 'bg-red-500' : mem > 60 ? 'bg-yellow-500' : 'bg-accent'}`;
document.getElementById('net-sent').textContent = data.container.network_sent_mb.toFixed(1);
document.getElementById('net-recv').textContent = data.container.network_recv_mb.toFixed(1);
const uptime = formatUptime(data.container.uptime_seconds);
document.getElementById('uptime').textContent = uptime;
// Pool status
const perm = data.pool.permanent;
document.getElementById('pool-perm').textContent =
`${perm.active ? 'ACTIVE' : 'INACTIVE'} (${perm.memory_mb}MB)`;
document.getElementById('pool-perm').className = perm.active ? 'text-primary ml-2' : 'text-secondary ml-2';
document.getElementById('pool-hot').textContent =
`${data.pool.hot.count} (${data.pool.hot.memory_mb}MB)`;
document.getElementById('pool-cold').textContent =
`${data.pool.cold.count} (${data.pool.cold.memory_mb}MB)`;
// Janitor
document.getElementById('janitor-status').textContent = data.janitor.next_cleanup_estimate;
const pressure = data.janitor.memory_pressure;
const pressureEl = document.getElementById('mem-pressure');
pressureEl.textContent = pressure;
pressureEl.className = pressure === 'HIGH' ? 'text-red-500' : pressure === 'MEDIUM' ? 'text-yellow-500' : 'text-green-500';
document.getElementById('last-update').textContent = 'Updated: ' + new Date().toLocaleTimeString();
} catch (e) {
console.error('Failed to fetch health:', e);
}
}
async function fetchRequests() {
try {
const filter = document.getElementById('filter-requests')?.value || 'all';
const res = await fetch(`/monitor/requests?status=${filter}&limit=50`);
const data = await res.json();
// Active requests
const activeList = document.getElementById('active-requests-list');
document.getElementById('active-count').textContent = data.active.length;
if (data.active.length === 0) {
activeList.innerHTML = '<div class="text-secondary text-center py-2">No active requests</div>';
} else {
activeList.innerHTML = data.active.map(req => `
<div class="flex items-center justify-between p-2 bg-dark rounded border border-border">
<span class="text-primary">${req.id.substring(0, 8)}</span>
<span class="text-secondary">${req.endpoint}</span>
<span class="text-light truncate max-w-[200px]" title="${req.url}">${req.url}</span>
<span class="text-accent">${req.elapsed.toFixed(1)}s</span>
<span class="pulse-slow">⏳</span>
</div>
`).join('');
}
// Completed requests
const completedList = document.getElementById('completed-requests-list');
if (data.completed.length === 0) {
completedList.innerHTML = '<div class="text-secondary text-center py-2">No completed requests</div>';
} else {
completedList.innerHTML = data.completed.map(req => `
<div class="flex items-center justify-between p-2 bg-dark rounded">
<span class="text-secondary">${req.id.substring(0, 8)}</span>
<span class="text-secondary">${req.endpoint}</span>
<span class="text-light truncate max-w-[180px]" title="${req.url}">${req.url}</span>
<span>${req.elapsed.toFixed(2)}s</span>
<span class="text-secondary">${req.mem_delta > 0 ? '+' : ''}${req.mem_delta}MB</span>
<span>${req.success ? '✅' : '❌'} ${req.status_code}</span>
</div>
`).join('');
}
} catch (e) {
console.error('Failed to fetch requests:', e);
}
}
async function fetchBrowsers() {
try {
const res = await fetch('/monitor/browsers');
const data = await res.json();
document.getElementById('browser-count').textContent = data.summary.total_count;
document.getElementById('browser-mem').textContent = data.summary.total_memory_mb;
document.getElementById('reuse-rate').textContent = data.summary.reuse_rate_percent.toFixed(1) + '%';
const tbody = document.getElementById('browsers-table-body');
if (data.browsers.length === 0) {
tbody.innerHTML = '<tr><td colspan="7" class="text-center py-4 text-secondary">No browsers</td></tr>';
} else {
tbody.innerHTML = data.browsers.map(b => {
const typeIcon = b.type === 'permanent' ? '🔥' : b.type === 'hot' ? '♨️' : '❄️';
const typeColor = b.type === 'permanent' ? 'text-primary' : b.type === 'hot' ? 'text-accent' : 'text-light';
return `
<tr class="border-t border-border">
<td class="py-2 pr-4"><span class="${typeColor}">${typeIcon} ${b.type.toUpperCase()}</span></td>
<td class="py-2 pr-4 font-mono">${b.sig}</td>
<td class="py-2 pr-4">${formatSeconds(b.age_seconds)}</td>
<td class="py-2 pr-4">${formatSeconds(b.last_used_seconds)} ago</td>
<td class="py-2 pr-4">${b.memory_mb} MB</td>
<td class="py-2 pr-4">${b.hits}</td>
<td class="py-2">
${b.killable ? `
<button onclick="killBrowser('${b.sig}')"
class="text-red-500 hover:underline mr-2">Kill</button>
<button onclick="restartBrowser('${b.sig}')"
class="text-primary hover:underline">Restart</button>
` : `
<button onclick="restartBrowser('permanent')"
class="text-primary hover:underline">Restart</button>
`}
</td>
</tr>
`;
}).join('');
}
} catch (e) {
console.error('Failed to fetch browsers:', e);
}
}
async function fetchJanitorLog() {
try {
const res = await fetch('/monitor/logs/janitor?limit=100');
const data = await res.json();
const logEl = document.getElementById('janitor-log');
if (data.events.length === 0) {
logEl.innerHTML = '<div class="text-secondary text-center py-4">No events yet</div>';
} else {
logEl.innerHTML = data.events.reverse().map(evt => {
const time = new Date(evt.timestamp * 1000).toLocaleTimeString();
const icon = evt.type === 'close_cold' ? '🧹❄️' : evt.type === 'close_hot' ? '🧹♨️' : '⬆️';
const details = JSON.stringify(evt.details);
return `<div class="p-2 bg-dark rounded">
<span class="text-secondary">${time}</span>
<span>${icon}</span>
<span class="text-primary">${evt.type}</span>
<span class="text-secondary">sig=${evt.sig}</span>
<span class="text-xs text-secondary ml-2">${details}</span>
</div>`;
}).join('');
}
} catch (e) {
console.error('Failed to fetch janitor log:', e);
}
}
async function fetchErrors() {
try {
const res = await fetch('/monitor/logs/errors?limit=100');
const data = await res.json();
const logEl = document.getElementById('errors-log');
if (data.errors.length === 0) {
logEl.innerHTML = '<div class="text-secondary text-center py-4">No errors</div>';
} else {
logEl.innerHTML = data.errors.reverse().map(err => {
const time = new Date(err.timestamp * 1000).toLocaleTimeString();
return `<div class="p-2 bg-dark rounded border border-red-500">
<div class="flex justify-between">
<span class="text-secondary">${time}</span>
<span class="text-red-500">${err.endpoint}</span>
</div>
<div class="text-xs text-light mt-1">${err.url}</div>
<div class="text-xs text-red-400 mt-1 font-mono">${err.error}</div>
</div>`;
}).join('');
}
} catch (e) {
console.error('Failed to fetch errors:', e);
}
}
async function fetchEndpointStats() {
try {
const res = await fetch('/monitor/endpoints/stats');
const data = await res.json();
const tbody = document.getElementById('endpoints-table-body');
const endpoints = Object.entries(data);
if (endpoints.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4 text-secondary">No data</td></tr>';
} else {
tbody.innerHTML = endpoints.map(([endpoint, stats]) => `
<tr class="border-t border-border">
<td class="py-2 pr-4 text-primary">${endpoint}</td>
<td class="py-2 pr-4 text-right">${stats.count}</td>
<td class="py-2 pr-4 text-right">${stats.avg_latency_ms}ms</td>
<td class="py-2 pr-4 text-right ${stats.success_rate_percent >= 99 ? 'text-green-500' : 'text-yellow-500'}">
${stats.success_rate_percent.toFixed(1)}%
</td>
<td class="py-2 pr-4 text-right ${stats.pool_hit_rate_percent >= 90 ? 'text-green-500' : 'text-yellow-500'}">
${stats.pool_hit_rate_percent.toFixed(1)}%
</td>
</tr>
`).join('');
}
} catch (e) {
console.error('Failed to fetch endpoint stats:', e);
}
}
async function fetchTimeline() {
try {
const metric = document.getElementById('timeline-metric').value;
const res = await fetch(`/monitor/timeline?metric=${metric}`);
const data = await res.json();
drawTimeline(data, metric);
} catch (e) {
console.error('Failed to fetch timeline:', e);
}
}
function drawTimeline(data, metric) {
const svg = document.getElementById('timeline-chart');
const width = 400;
const height = 120;
const padding = 20;
// Clear previous chart
svg.innerHTML = '';
if (!data.values || data.values.length === 0) {
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', width / 2);
text.setAttribute('y', height / 2);
text.setAttribute('text-anchor', 'middle');
text.setAttribute('fill', '#D5CEBF');
text.setAttribute('font-size', '12');
text.textContent = 'No data';
svg.appendChild(text);
return;
}
// Handle browsers metric (nested data)
let values = data.values;
if (metric === 'browsers') {
// Sum all browser types
values = values.map(v => (v.permanent || 0) + (v.hot || 0) + (v.cold || 0));
}
const maxValue = Math.max(...values, 1);
const minValue = 0;
// Draw grid lines
for (let i = 0; i <= 4; i++) {
const y = padding + (height - 2 * padding) * (i / 4);
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', padding);
line.setAttribute('y1', y);
line.setAttribute('x2', width - padding);
line.setAttribute('y2', y);
line.setAttribute('stroke', '#3F3F44');
line.setAttribute('stroke-width', '1');
line.setAttribute('stroke-dasharray', '2,2');
svg.appendChild(line);
}
// Draw line
if (values.length > 1) {
const points = values.map((v, i) => {
const x = padding + (width - 2 * padding) * (i / (values.length - 1));
const y = height - padding - ((v - minValue) / (maxValue - minValue)) * (height - 2 * padding);
return `${x},${y}`;
}).join(' ');
const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
polyline.setAttribute('points', points);
polyline.setAttribute('fill', 'none');
polyline.setAttribute('stroke', '#4EFFFF');
polyline.setAttribute('stroke-width', '2');
polyline.classList.add('sparkline');
svg.appendChild(polyline);
// Add glow effect
const polylineGlow = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
polylineGlow.setAttribute('points', points);
polylineGlow.setAttribute('fill', 'none');
polylineGlow.setAttribute('stroke', '#4EFFFF');
polylineGlow.setAttribute('stroke-width', '4');
polylineGlow.setAttribute('opacity', '0.3');
polylineGlow.classList.add('sparkline');
svg.insertBefore(polylineGlow, polyline);
}
// Y-axis labels
const labelMax = document.createElementNS('http://www.w3.org/2000/svg', 'text');
labelMax.setAttribute('x', '5');
labelMax.setAttribute('y', padding);
labelMax.setAttribute('fill', '#D5CEBF');
labelMax.setAttribute('font-size', '10');
labelMax.textContent = maxValue.toFixed(0);
svg.appendChild(labelMax);
const labelMin = document.createElementNS('http://www.w3.org/2000/svg', 'text');
labelMin.setAttribute('x', '5');
labelMin.setAttribute('y', height - padding);
labelMin.setAttribute('fill', '#D5CEBF');
labelMin.setAttribute('font-size', '10');
labelMin.textContent = minValue.toFixed(0);
svg.appendChild(labelMin);
}
// Timeline metric selector
document.getElementById('timeline-metric').addEventListener('change', fetchTimeline);
// ========== Control Actions ==========
async function killBrowser(sig) {
if (!confirm(`Kill browser ${sig}?`)) return;
try {
const res = await fetch('/monitor/actions/kill_browser', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({sig})
});
const data = await res.json();
showActionStatus(data.success ? `✅ Killed ${sig}` : `❌ Failed to kill`, data.success);
if (data.success) fetchBrowsers();
} catch (e) {
showActionStatus('❌ Error: ' + e.message, false);
}
}
async function restartBrowser(sig) {
if (!confirm(`Restart browser ${sig}?`)) return;
try {
const res = await fetch('/monitor/actions/restart_browser', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({sig})
});
const data = await res.json();
showActionStatus(data.success ? `✅ Restarted ${sig}` : `❌ Failed to restart`, data.success);
if (data.success) fetchBrowsers();
} catch (e) {
showActionStatus('❌ Error: ' + e.message, false);
}
}
document.getElementById('btn-force-cleanup').addEventListener('click', async () => {
if (!confirm('Force cleanup all cold pool browsers?')) return;
try {
const res = await fetch('/monitor/actions/cleanup', {method: 'POST'});
const data = await res.json();
showActionStatus(`✅ Killed ${data.killed_browsers} browsers`, true);
fetchAll();
} catch (e) {
showActionStatus('❌ Error: ' + e.message, false);
}
});
document.getElementById('btn-restart-perm').addEventListener('click', async () => {
if (!confirm('Restart permanent browser? This will briefly interrupt service.')) return;
try {
const res = await fetch('/monitor/actions/restart_browser', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({sig: 'permanent'})
});
const data = await res.json();
showActionStatus(data.success ? '✅ Permanent browser restarted' : '❌ Failed', data.success);
fetchAll();
} catch (e) {
showActionStatus('❌ Error: ' + e.message, false);
}
});
document.getElementById('btn-reset-stats').addEventListener('click', async () => {
if (!confirm('Reset all endpoint statistics?')) return;
try {
const res = await fetch('/monitor/stats/reset', {method: 'POST'});
const data = await res.json();
showActionStatus('✅ Stats reset', true);
fetchEndpointStats();
} catch (e) {
showActionStatus('❌ Error: ' + e.message, false);
}
});
function showActionStatus(msg, success) {
const el = document.getElementById('action-status');
el.textContent = msg;
el.className = success ? 'ml-auto text-xs text-green-500' : 'ml-auto text-xs text-red-500';
setTimeout(() => el.textContent = '', 3000);
}
// ========== Utility Functions ==========
function formatUptime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
return `${h}h ${m}m`;
}
function formatSeconds(seconds) {
if (seconds < 60) return `${seconds}s`;
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}m ${s}s`;
}
// ========== Filter change handler ==========
document.getElementById('filter-requests')?.addEventListener('change', fetchRequests);
// ========== Initialize ==========
startAutoRefresh();
</script>
</body>
</html>