进一步优化算法 引入Websocket

This commit is contained in:
CN-JS-HuiBai
2026-04-05 22:45:23 +08:00
parent d7d650c5f9
commit 2a8cb32d47
6 changed files with 226 additions and 206 deletions

24
package-lock.json generated
View File

@@ -13,7 +13,8 @@
"dotenv": "^16.4.0", "dotenv": "^16.4.0",
"express": "^4.21.0", "express": "^4.21.0",
"ioredis": "^5.10.1", "ioredis": "^5.10.1",
"mysql2": "^3.11.0" "mysql2": "^3.11.0",
"ws": "^8.20.0"
} }
}, },
"node_modules/@ioredis/commands": { "node_modules/@ioredis/commands": {
@@ -1215,6 +1216,27 @@
"engines": { "engines": {
"node": ">= 0.8" "node": ">= 0.8"
} }
},
"node_modules/ws": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
"integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
} }
} }
} }

View File

@@ -14,6 +14,7 @@
"dotenv": "^16.4.0", "dotenv": "^16.4.0",
"express": "^4.21.0", "express": "^4.21.0",
"ioredis": "^5.10.1", "ioredis": "^5.10.1",
"mysql2": "^3.11.0" "mysql2": "^3.11.0",
"ws": "^8.20.0"
} }
} }

View File

@@ -127,7 +127,9 @@ html {
body { body {
font-family: var(--font-sans); font-family: var(--font-sans);
background: var(--bg-primary); background: radial-gradient(circle at 0% 0%, #1a1e2e 0%, #0a0e1a 45%),
radial-gradient(circle at 100% 100%, #151a2e 0%, #0a0e1a 45%);
background-attachment: fixed;
color: var(--text-primary); color: var(--text-primary);
min-height: 100vh; min-height: 100vh;
overflow-x: hidden; overflow-x: hidden;
@@ -146,65 +148,7 @@ body {
pointer-events: none; pointer-events: none;
} }
.bg-glow { /* ---- Animated Background Classes Removed for Performance ---- */
position: fixed;
border-radius: 50%;
filter: blur(120px);
opacity: 0.4;
z-index: 0;
pointer-events: none;
animation: glowFloat 20s ease-in-out infinite;
will-change: transform, opacity;
transform: translateZ(0);
}
.bg-glow-1 {
width: 600px;
height: 600px;
background: radial-gradient(circle, rgba(99, 102, 241, 0.15), transparent 70%);
top: -200px;
left: -100px;
animation-delay: 0s;
}
.bg-glow-2 {
width: 500px;
height: 500px;
background: radial-gradient(circle, rgba(6, 182, 212, 0.12), transparent 70%);
bottom: -150px;
right: -100px;
animation-delay: -7s;
}
.bg-glow-3 {
width: 400px;
height: 400px;
background: radial-gradient(circle, rgba(168, 85, 247, 0.1), transparent 70%);
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
animation-delay: -14s;
}
@keyframes glowFloat {
0%,
100% {
transform: translate3d(0, 0, 0) scale(1);
}
25% {
transform: translate3d(30px, -30px, 0) scale(1.05);
}
50% {
transform: translate3d(-20px, 20px, 0) scale(0.95);
}
75% {
transform: translate3d(25px, 15px, 0) scale(1.02);
}
}
/* ---- App Container ---- */ /* ---- App Container ---- */
#app { #app {
@@ -223,9 +167,7 @@ body {
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 0 28px; padding: 0 28px;
background: rgba(10, 14, 26, 0.85); background: rgba(10, 14, 26, 0.95); /* More opaque, no filter */
backdrop-filter: blur(12px) saturate(150%);
-webkit-backdrop-filter: blur(12px) saturate(150%);
border-bottom: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color);
} }
@@ -455,8 +397,9 @@ input:checked+.slider:before {
background: var(--bg-card); background: var(--bg-card);
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
backdrop-filter: blur(8px); /* backdrop-filter: blur(8px); */
-webkit-backdrop-filter: blur(8px); /* -webkit-backdrop-filter: blur(8px); */
background: rgba(15, 22, 50, 0.9); /* More solid background for readability without blur */
transform: translateZ(0); transform: translateZ(0);
transition: all 0.3s ease; transition: all 0.3s ease;
overflow: hidden; overflow: hidden;
@@ -624,8 +567,9 @@ input:checked+.slider:before {
background: var(--bg-card); background: var(--bg-card);
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
backdrop-filter: blur(8px); /* backdrop-filter: blur(8px); */
-webkit-backdrop-filter: blur(8px); /* -webkit-backdrop-filter: blur(8px); */
background: rgba(15, 22, 50, 0.9); /* More solid background for readability without blur */
transform: translateZ(0); transform: translateZ(0);
overflow: hidden; overflow: hidden;
transition: all 0.3s ease; transition: all 0.3s ease;

View File

@@ -38,11 +38,8 @@
</head> </head>
<body> <body>
<!-- Animated Background --> <!-- Optimized Background -->
<div class="bg-grid"></div> <div class="bg-grid"></div>
<div class="bg-glow bg-glow-1"></div>
<div class="bg-glow bg-glow-2"></div>
<div class="bg-glow bg-glow-3"></div>
<!-- App Container --> <!-- App Container -->
<div id="app"> <div id="app">

View File

@@ -305,10 +305,40 @@
loadSiteSettings(); loadSiteSettings();
setInterval(fetchMetrics, REFRESH_INTERVAL); // setInterval(fetchMetrics, REFRESH_INTERVAL); - Now using WebSockets
initWebSocket();
setInterval(fetchNetworkHistory, NETWORK_HISTORY_INTERVAL); setInterval(fetchNetworkHistory, NETWORK_HISTORY_INTERVAL);
} }
// ---- Real-time WebSocket ----
function initWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}`;
const ws = new WebSocket(wsUrl);
ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data);
if (msg.type === 'overview') {
allServersData = msg.data.servers || [];
updateDashboard(msg.data);
}
} catch (err) {
console.error('WS Message Error:', err);
}
};
ws.onclose = () => {
console.log('WS connection closed. Reconnecting in 5s...');
setTimeout(initWebSocket, 5000);
};
ws.onerror = (err) => {
// Small silent error here to not alert the user constantly if server is down during maintenance
ws.close();
};
}
// ---- Theme Switching ---- // ---- Theme Switching ----
function toggleTheme() { function toggleTheme() {
const theme = dom.themeToggle.checked ? 'light' : 'dark'; const theme = dom.themeToggle.checked ? 'light' : 'dark';
@@ -507,11 +537,9 @@
} }
}, },
series: [{ series: [{
type: 'effectScatter', type: 'scatter',
coordinateSystem: 'geo', coordinateSystem: 'geo',
geoIndex: 0, geoIndex: 0,
showEffectOn: 'render',
rippleEffect: { brushType: 'stroke', scale: 3, period: 6 },
symbolSize: 5, symbolSize: 5,
itemStyle: { itemStyle: {
color: '#06b6d4', color: '#06b6d4',

View File

@@ -7,6 +7,8 @@ const prometheusService = require('./prometheus-service');
const cache = require('./cache'); const cache = require('./cache');
const geoService = require('./geo-service'); const geoService = require('./geo-service');
const checkAndFixDatabase = require('./db-integrity-check'); const checkAndFixDatabase = require('./db-integrity-check');
const http = require('http');
const WebSocket = require('ws');
const app = express(); const app = express();
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
@@ -570,20 +572,20 @@ app.post('/api/settings', requireAuth, async (req, res) => {
// ==================== Metrics Aggregation ==================== // ==================== Metrics Aggregation ====================
// Get all aggregated metrics from all Prometheus sources // Reusable function to get overview metrics
app.get('/api/metrics/overview', async (req, res) => { async function getOverview() {
try {
const [sources] = await db.query('SELECT * FROM prometheus_sources'); const [sources] = await db.query('SELECT * FROM prometheus_sources');
if (sources.length === 0) { if (sources.length === 0) {
return res.json({ return {
totalServers: 0, totalServers: 0,
activeServers: 0,
cpu: { used: 0, total: 0, percent: 0 }, cpu: { used: 0, total: 0, percent: 0 },
memory: { used: 0, total: 0, percent: 0 }, memory: { used: 0, total: 0, percent: 0 },
disk: { used: 0, total: 0, percent: 0 }, disk: { used: 0, total: 0, percent: 0 },
network: { total: 0, rx: 0, tx: 0 }, network: { total: 0, rx: 0, tx: 0 },
traffic24h: { rx: 0, tx: 0, total: 0 }, traffic24h: { rx: 0, tx: 0, total: 0 },
servers: [] servers: []
}); };
} }
const allMetrics = await Promise.all(sources.map(async (source) => { const allMetrics = await Promise.all(sources.map(async (source) => {
@@ -593,6 +595,8 @@ app.get('/api/metrics/overview', async (req, res) => {
try { try {
const metrics = await prometheusService.getOverviewMetrics(source.url, source.name); const metrics = await prometheusService.getOverviewMetrics(source.url, source.name);
// Don't set cache here if we want real-time WS push to be fresh,
// but keeping it for REST API performance is fine.
await cache.set(cacheKey, metrics, 15); // Cache for 15s await cache.set(cacheKey, metrics, 15); // Cache for 15s
return metrics; return metrics;
} catch (err) { } catch (err) {
@@ -615,7 +619,7 @@ app.get('/api/metrics/overview', async (req, res) => {
for (const m of validMetrics) { for (const m of validMetrics) {
totalServers += m.totalServers; totalServers += m.totalServers;
activeServers += m.activeServers || m.totalServers; // Default if missing activeServers += (m.activeServers !== undefined ? m.activeServers : m.totalServers);
cpuUsed += m.cpu.used; cpuUsed += m.cpu.used;
cpuTotal += m.cpu.total; cpuTotal += m.cpu.total;
memUsed += m.memory.used; memUsed += m.memory.used;
@@ -629,8 +633,6 @@ app.get('/api/metrics/overview', async (req, res) => {
allServers = allServers.concat(m.servers); allServers = allServers.concat(m.servers);
} }
const overview = { const overview = {
totalServers, totalServers,
activeServers, activeServers,
@@ -664,28 +666,20 @@ app.get('/api/metrics/overview', async (req, res) => {
// --- Add Geo Information to Servers --- // --- Add Geo Information to Servers ---
const geoServers = await Promise.all(overview.servers.map(async (server) => { const geoServers = await Promise.all(overview.servers.map(async (server) => {
// Use originalInstance if available for correct location lookup
const realInstance = server.originalInstance || prometheusService.resolveToken(server.instance); const realInstance = server.originalInstance || prometheusService.resolveToken(server.instance);
const cleanIp = realInstance.split(':')[0]; const cleanIp = realInstance.split(':')[0];
let geoData = null; let geoData = null;
// Try to get from DB cache only (fast)
try { try {
const [rows] = await db.query('SELECT * FROM server_locations WHERE ip = ?', [cleanIp]); const [rows] = await db.query('SELECT * FROM server_locations WHERE ip = ?', [cleanIp]);
if (rows.length > 0) { if (rows.length > 0) {
geoData = rows[0]; geoData = rows[0];
} else { } else {
// Trigger background resolution for future requests
geoService.getLocation(cleanIp).catch(() => {}); geoService.getLocation(cleanIp).catch(() => {});
} }
} catch (e) { } catch (e) {}
// DB error, skip geo for now
}
// Prepare the server object without sensitive originalInstance
const { originalInstance, ...safeServer } = server; const { originalInstance, ...safeServer } = server;
if (geoData) { if (geoData) {
return { return {
...safeServer, ...safeServer,
@@ -700,6 +694,13 @@ app.get('/api/metrics/overview', async (req, res) => {
})); }));
overview.servers = geoServers; overview.servers = geoServers;
return overview;
}
// Get all aggregated metrics from all Prometheus sources
app.get('/api/metrics/overview', async (req, res) => {
try {
const overview = await getOverview();
res.json(overview); res.json(overview);
} catch (err) { } catch (err) {
console.error('Error fetching overview metrics:', err); console.error('Error fetching overview metrics:', err);
@@ -820,11 +821,38 @@ app.get('*', (req, res, next) => {
}); });
// ==================== WebSocket Server ====================
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
function broadcast(data) {
const message = JSON.stringify(data);
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
// Broadcast loop
async function broadcastMetrics() {
try {
const overview = await getOverview();
broadcast({ type: 'overview', data: overview });
} catch (err) {
// console.error('WS Broadcast error:', err.message);
}
}
// Check and fix database integrity on startup // Check and fix database integrity on startup
checkAndFixDatabase(); checkAndFixDatabase();
app.listen(PORT, HOST, () => { const REFRESH_INT = parseInt(process.env.REFRESH_INTERVAL) || 5000;
console.log(`\n 🚀 Data Visualization Display Wall`); setInterval(broadcastMetrics, REFRESH_INT);
server.listen(PORT, HOST, () => {
console.log(`\n 🚀 Data Visualization Display Wall (WebSocket Enabled)`);
console.log(` 📊 Server running at http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}`); console.log(` 📊 Server running at http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}`);
console.log(` ⚙️ Configure Prometheus sources at http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}/settings\n`); console.log(` ⚙️ Configure Prometheus sources at http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}/settings\n`);
}); });