优化计算逻辑
This commit is contained in:
@@ -504,20 +504,18 @@ app.get('/api/metrics/overview', async (req, res) => {
|
||||
allServers = allServers.concat(m.servers);
|
||||
}
|
||||
|
||||
// --- 24h Traffic from DB ---
|
||||
// --- 24h Traffic from DB (Integrating Bandwidth) ---
|
||||
try {
|
||||
// Get the oldest record within 24h and the latest overall
|
||||
const [oldest] = await db.query('SELECT rx_bytes, tx_bytes, timestamp FROM traffic_stats WHERE timestamp >= NOW() - INTERVAL 1 DAY ORDER BY timestamp ASC LIMIT 1');
|
||||
const [latest] = await db.query('SELECT rx_bytes, tx_bytes, timestamp FROM traffic_stats ORDER BY timestamp DESC LIMIT 1');
|
||||
// Each record represents a 5-second interval
|
||||
const [sumRows] = await db.query('SELECT SUM(rx_bandwidth) as sumRx, SUM(tx_bandwidth) as sumTx FROM traffic_stats WHERE timestamp >= NOW() - INTERVAL 1 DAY');
|
||||
|
||||
if (oldest.length > 0 && latest.length > 0) {
|
||||
// Calculate difference. Handle counter resets (though unlikely for aggregated total)
|
||||
traffic24hRx = latest[0].rx_bytes > oldest[0].rx_bytes ? (latest[0].rx_bytes - oldest[0].rx_bytes) : 0;
|
||||
traffic24hTx = latest[0].tx_bytes > oldest[0].tx_bytes ? (latest[0].tx_bytes - oldest[0].tx_bytes) : 0;
|
||||
if (sumRows.length > 0 && sumRows[0].sumRx !== null) {
|
||||
// Total bytes = Sum of (bytes/sec) * 5 seconds
|
||||
traffic24hRx = sumRows[0].sumRx * 5;
|
||||
traffic24hTx = sumRows[0].sumTx * 5;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error calculating 24h traffic from DB:', err);
|
||||
// Fallback to what we got from Prometheus directly in each source if DB fails
|
||||
console.error('Error calculating 24h traffic from DB integration:', err);
|
||||
}
|
||||
|
||||
res.json({
|
||||
|
||||
Reference in New Issue
Block a user