266 lines
9.6 KiB
JavaScript
266 lines
9.6 KiB
JavaScript
"use strict";
|
|
/**
|
|
* Read-only VPS metrics via Prometheus (allowlisted PromQL only).
|
|
* Never executes shell/Docker commands; never mounts docker.sock.
|
|
*/
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getOverview = getOverview;
|
|
exports.getTimeseries = getTimeseries;
|
|
exports.getContainers = getContainers;
|
|
exports.getServices = getServices;
|
|
exports.parseMetric = parseMetric;
|
|
exports.parseRange = parseRange;
|
|
const config_1 = require("../config");
|
|
const METRIC_QUERIES = {
|
|
cpu: '100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)',
|
|
mem: '(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100',
|
|
disk: '(1 - (sum(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs"}) / sum(node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs"}))) * 100',
|
|
net_in: 'sum(rate(node_network_receive_bytes_total{device!~"lo|veth.*|br-.*|docker.*|tunl.*"}[5m]))',
|
|
net_out: 'sum(rate(node_network_transmit_bytes_total{device!~"lo|veth.*|br-.*|docker.*|tunl.*"}[5m]))',
|
|
load1: 'node_load1',
|
|
};
|
|
const RANGE_SECONDS = {
|
|
'1h': 3600,
|
|
'6h': 6 * 3600,
|
|
'24h': 24 * 3600,
|
|
'7d': 7 * 24 * 3600,
|
|
};
|
|
function baseUrl() {
|
|
return config_1.config.vpsMonitor.prometheusUrl.replace(/\/$/, '');
|
|
}
|
|
async function promGet(path, search) {
|
|
const url = new URL(path, `${baseUrl()}/`);
|
|
for (const [k, v] of Object.entries(search))
|
|
url.searchParams.set(k, v);
|
|
const ctrl = new AbortController();
|
|
const timer = setTimeout(() => ctrl.abort(), config_1.config.vpsMonitor.timeoutMs);
|
|
try {
|
|
const res = await fetch(url, {
|
|
method: 'GET',
|
|
signal: ctrl.signal,
|
|
headers: { Accept: 'application/json' },
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`Prometheus HTTP ${res.status}`);
|
|
}
|
|
return (await res.json());
|
|
}
|
|
finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
async function queryInstant(query) {
|
|
const body = await promGet('/api/v1/query', { query });
|
|
if (body.status !== 'success')
|
|
return null;
|
|
const v = body.data?.result?.[0]?.value?.[1];
|
|
if (v == null)
|
|
return null;
|
|
const n = Number(v);
|
|
return Number.isFinite(n) ? n : null;
|
|
}
|
|
async function queryRange(query, range) {
|
|
const end = Math.floor(Date.now() / 1000);
|
|
const start = end - RANGE_SECONDS[range];
|
|
const step = range === '7d' ? 900 : range === '24h' ? 120 : range === '6h' ? 60 : 30;
|
|
const body = await promGet('/api/v1/query_range', {
|
|
query,
|
|
start: String(start),
|
|
end: String(end),
|
|
step: String(step),
|
|
});
|
|
if (body.status !== 'success')
|
|
return [];
|
|
const values = body.data?.result?.[0]?.values ?? [];
|
|
return values
|
|
.map(([ts, raw]) => ({ t: Number(ts) * 1000, v: Number(raw) }))
|
|
.filter((p) => Number.isFinite(p.t) && Number.isFinite(p.v));
|
|
}
|
|
function classify(value, warn, critical, higherIsWorse = true) {
|
|
if (value == null || !Number.isFinite(value))
|
|
return 'unknown';
|
|
if (higherIsWorse) {
|
|
if (value >= critical)
|
|
return 'critical';
|
|
if (value >= warn)
|
|
return 'warning';
|
|
return 'ok';
|
|
}
|
|
return 'ok';
|
|
}
|
|
async function getOverview() {
|
|
const th = config_1.config.vpsMonitor.thresholds;
|
|
const empty = (reachable) => ({
|
|
checkedAt: new Date().toISOString(),
|
|
prometheusReachable: reachable,
|
|
cpuPercent: null,
|
|
memPercent: null,
|
|
memUsedBytes: null,
|
|
memTotalBytes: null,
|
|
diskPercent: null,
|
|
diskUsedBytes: null,
|
|
diskTotalBytes: null,
|
|
load1: null,
|
|
load5: null,
|
|
load15: null,
|
|
netReceiveBps: null,
|
|
netTransmitBps: null,
|
|
status: { cpu: 'unknown', mem: 'unknown', disk: 'unknown', load: 'unknown' },
|
|
thresholds: {
|
|
cpuWarn: th.cpuWarn,
|
|
cpuCritical: th.cpuCritical,
|
|
memWarn: th.memWarn,
|
|
memCritical: th.memCritical,
|
|
diskWarn: th.diskWarn,
|
|
diskCritical: th.diskCritical,
|
|
loadWarn: th.loadWarn,
|
|
loadCritical: th.loadCritical,
|
|
},
|
|
});
|
|
try {
|
|
const [cpuPercent, memPercent, memAvail, memTotal, diskPercent, diskAvail, diskSize, load1, load5, load15, netIn, netOut,] = await Promise.all([
|
|
queryInstant(METRIC_QUERIES.cpu),
|
|
queryInstant(METRIC_QUERIES.mem),
|
|
queryInstant('node_memory_MemAvailable_bytes'),
|
|
queryInstant('node_memory_MemTotal_bytes'),
|
|
queryInstant(METRIC_QUERIES.disk),
|
|
queryInstant('sum(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs"})'),
|
|
queryInstant('sum(node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs"})'),
|
|
queryInstant('node_load1'),
|
|
queryInstant('node_load5'),
|
|
queryInstant('node_load15'),
|
|
queryInstant(METRIC_QUERIES.net_in),
|
|
queryInstant(METRIC_QUERIES.net_out),
|
|
]);
|
|
const memUsed = memTotal != null && memAvail != null ? Math.max(0, memTotal - memAvail) : null;
|
|
const diskUsed = diskSize != null && diskAvail != null ? Math.max(0, diskSize - diskAvail) : null;
|
|
return {
|
|
checkedAt: new Date().toISOString(),
|
|
prometheusReachable: true,
|
|
cpuPercent,
|
|
memPercent,
|
|
memUsedBytes: memUsed,
|
|
memTotalBytes: memTotal,
|
|
diskPercent,
|
|
diskUsedBytes: diskUsed,
|
|
diskTotalBytes: diskSize,
|
|
load1,
|
|
load5,
|
|
load15,
|
|
netReceiveBps: netIn,
|
|
netTransmitBps: netOut,
|
|
status: {
|
|
cpu: classify(cpuPercent, th.cpuWarn, th.cpuCritical),
|
|
mem: classify(memPercent, th.memWarn, th.memCritical),
|
|
disk: classify(diskPercent, th.diskWarn, th.diskCritical),
|
|
load: classify(load1, th.loadWarn, th.loadCritical),
|
|
},
|
|
thresholds: {
|
|
cpuWarn: th.cpuWarn,
|
|
cpuCritical: th.cpuCritical,
|
|
memWarn: th.memWarn,
|
|
memCritical: th.memCritical,
|
|
diskWarn: th.diskWarn,
|
|
diskCritical: th.diskCritical,
|
|
loadWarn: th.loadWarn,
|
|
loadCritical: th.loadCritical,
|
|
},
|
|
};
|
|
}
|
|
catch {
|
|
return empty(false);
|
|
}
|
|
}
|
|
async function getTimeseries(metric, range) {
|
|
const query = METRIC_QUERIES[metric];
|
|
if (!query)
|
|
throw new Error('Unknown metric');
|
|
try {
|
|
const points = await queryRange(query, range);
|
|
return { metric, range, points };
|
|
}
|
|
catch (e) {
|
|
throw new Error(e instanceof Error ? e.message : 'Prometheus query failed');
|
|
}
|
|
}
|
|
async function getContainers(limit = 20) {
|
|
const safeLimit = Math.min(50, Math.max(1, Math.floor(limit)));
|
|
try {
|
|
const [cpuBody, memBody] = await Promise.all([
|
|
promGet('/api/v1/query', {
|
|
query: `topk(${safeLimit}, sum by (name) (rate(container_cpu_usage_seconds_total{name!=""}[5m])) * 100)`,
|
|
}),
|
|
promGet('/api/v1/query', {
|
|
query: `topk(${safeLimit}, sum by (name) (container_memory_working_set_bytes{name!=""}))`,
|
|
}),
|
|
]);
|
|
const cpuMap = new Map();
|
|
for (const row of cpuBody.data?.result ?? []) {
|
|
const name = (row.metric?.name || '').trim();
|
|
if (!name || name === '/')
|
|
continue;
|
|
const v = Number(row.value?.[1]);
|
|
if (Number.isFinite(v))
|
|
cpuMap.set(name, v);
|
|
}
|
|
const memMap = new Map();
|
|
for (const row of memBody.data?.result ?? []) {
|
|
const name = (row.metric?.name || '').trim();
|
|
if (!name || name === '/')
|
|
continue;
|
|
const v = Number(row.value?.[1]);
|
|
if (Number.isFinite(v))
|
|
memMap.set(name, v);
|
|
}
|
|
const names = new Set([...cpuMap.keys(), ...memMap.keys()]);
|
|
const containers = [...names]
|
|
.map((name) => ({
|
|
name,
|
|
cpuPercent: cpuMap.get(name) ?? null,
|
|
memBytes: memMap.get(name) ?? null,
|
|
}))
|
|
.sort((a, b) => (b.cpuPercent ?? 0) - (a.cpuPercent ?? 0))
|
|
.slice(0, safeLimit);
|
|
return { containers };
|
|
}
|
|
catch (e) {
|
|
throw new Error(e instanceof Error ? e.message : 'Container metrics unavailable');
|
|
}
|
|
}
|
|
async function getServices() {
|
|
try {
|
|
const url = new URL('/api/v1/targets', `${baseUrl()}/`);
|
|
const ctrl = new AbortController();
|
|
const timer = setTimeout(() => ctrl.abort(), config_1.config.vpsMonitor.timeoutMs);
|
|
let res;
|
|
try {
|
|
res = await fetch(url, { signal: ctrl.signal, headers: { Accept: 'application/json' } });
|
|
}
|
|
finally {
|
|
clearTimeout(timer);
|
|
}
|
|
if (!res.ok)
|
|
throw new Error(`Prometheus HTTP ${res.status}`);
|
|
const body = (await res.json());
|
|
const targets = (body.data?.activeTargets ?? []).map((t) => ({
|
|
job: t.labels?.job || 'unknown',
|
|
health: t.health || 'unknown',
|
|
lastError: t.lastError ? String(t.lastError).slice(0, 200) : null,
|
|
}));
|
|
return { prometheusReachable: true, targets };
|
|
}
|
|
catch {
|
|
return { prometheusReachable: false, targets: [] };
|
|
}
|
|
}
|
|
function parseMetric(raw) {
|
|
if (typeof raw !== 'string')
|
|
return null;
|
|
return raw in METRIC_QUERIES ? raw : null;
|
|
}
|
|
function parseRange(raw) {
|
|
if (typeof raw !== 'string')
|
|
return null;
|
|
return raw in RANGE_SECONDS ? raw : null;
|
|
}
|
|
//# sourceMappingURL=vpsMonitorService.js.map
|