优化时间范围选择

This commit is contained in:
CN-JS-HuiBai
2026-04-04 22:27:35 +08:00
parent 4f04227976
commit 75736c0c4c
6 changed files with 662 additions and 68 deletions

View File

@@ -448,6 +448,85 @@ async function getServerDetails(baseUrl, instance, job) {
return results;
}
/**
* Get historical metrics for a specific server (node)
*/
async function getServerHistory(baseUrl, instance, job, metric, range = '1h', start = null, end = null) {
const url = normalizeUrl(baseUrl);
const node = instance;
// Map metric keys to Prometheus expressions
const metricMap = {
cpuBusy: `100 * (1 - avg(rate(node_cpu_seconds_total{mode="idle", instance="${node}"}[1m])))`,
sysLoad: `node_load1{instance="${node}",job="${job}"} * 100 / count(count(node_cpu_seconds_total{instance="${node}",job="${job}"}) by (cpu))`,
memUsedPct: `(1 - (node_memory_MemAvailable_bytes{instance="${node}", job="${job}"} / node_memory_MemTotal_bytes{instance="${node}", job="${job}"})) * 100`,
swapUsedPct: `((node_memory_SwapTotal_bytes{instance="${node}",job="${job}"} - node_memory_SwapFree_bytes{instance="${node}",job="${job}"}) / (node_memory_SwapTotal_bytes{instance="${node}",job="${job}"})) * 100`,
rootFsUsedPct: `100 - ((node_filesystem_avail_bytes{instance="${node}",job="${job}",mountpoint="/",fstype!="rootfs"} * 100) / node_filesystem_size_bytes{instance="${node}",job="${job}",mountpoint="/",fstype!="rootfs"})`,
netRx: `sum(rate(node_network_receive_bytes_total{instance="${node}",job="${job}",device!~'tap.*|veth.*|br.*|docker.*|virbr*|podman.*|lo.*|vmbr.*|fwbr.|ip.*|gre.*|virbr.*|vnet.*'}[1m]))`,
netTx: `sum(rate(node_network_transmit_bytes_total{instance="${node}",job="${job}",device!~'tap.*|veth.*|br.*|docker.*|virbr*|podman.*|lo.*|vmbr.*|fwbr.|ip.*|gre.*|virbr.*|vnet.*'}[1m]))`
};
const expr = metricMap[metric];
if (!expr) throw new Error('Invalid metric for history');
let duration, step, queryStart, queryEnd;
if (start && end) {
queryStart = Math.floor(new Date(start).getTime() / 1000);
queryEnd = Math.floor(new Date(end).getTime() / 1000);
duration = queryEnd - queryStart;
if (duration <= 0) throw new Error('End time must be after start time');
// Reasonable step for fixed range
step = Math.max(15, Math.floor(duration / 100));
} else {
// Relative range logic
const rangeMap = {
'15m': { duration: 900, step: 15 },
'30m': { duration: 1800, step: 30 },
'1h': { duration: 3600, step: 60 },
'6h': { duration: 21600, step: 300 },
'12h': { duration: 43200, step: 600 },
'24h': { duration: 86400, step: 900 },
'2d': { duration: 172800, step: 1800 },
'7d': { duration: 604800, step: 3600 }
};
if (rangeMap[range]) {
duration = rangeMap[range].duration;
step = rangeMap[range].step;
} else {
// Try to parse relative time string like "2h", "30m", "1d"
const match = range.match(/^(\d+)([smhd])$/);
if (match) {
const val = parseInt(match[1]);
const unit = match[2];
const multipliers = { s: 1, m: 60, h: 3600, d: 86400 };
duration = val * (multipliers[unit] || 3600);
// Calculate a reasonable step for ~60-120 data points
step = Math.max(15, Math.floor(duration / 100));
} else {
duration = 3600;
step = 60;
}
}
queryEnd = Math.floor(Date.now() / 1000);
queryStart = queryEnd - duration;
}
try {
const result = await queryRange(url, expr, queryStart, queryEnd, step);
if (!result || result.length === 0) return { timestamps: [], values: [] };
return {
timestamps: result[0].values.map(v => v[0] * 1000),
values: result[0].values.map(v => parseFloat(v[1]))
};
} catch (err) {
console.error(`[Prometheus] Error fetching history for ${metric} on ${node}:`, err.message);
throw err;
}
}
module.exports = {
testConnection,
query,
@@ -457,5 +536,6 @@ module.exports = {
mergeNetworkHistories,
getCpuHistory,
mergeCpuHistories,
getServerDetails
getServerDetails,
getServerHistory
};