feat(monitoring,inspector,metrics): fix rollup/probe bugs, add net/disk/probe history, TLS expiry & Prometheus /metrics
This commit is contained in:
parent
ca67c85fbf
commit
dbf7144c5d
11 changed files with 954 additions and 174 deletions
|
|
@ -1,8 +1,9 @@
|
||||||
|
import crypto from 'node:crypto';
|
||||||
import { Router, type RequestHandler } from 'express';
|
import { Router, type RequestHandler } from 'express';
|
||||||
import { ZodError, z } from 'zod';
|
import { ZodError, z } from 'zod';
|
||||||
import type { ConfigManager } from '../../config/config-manager.js';
|
import type { ConfigManager } from '../../config/config-manager.js';
|
||||||
import type { AuditService } from '../../security/audit.js';
|
import type { AuditService } from '../../security/audit.js';
|
||||||
import type { AuthService } from '../../security/auth.js';
|
import { sha256Hex, type AuthService } from '../../security/auth.js';
|
||||||
import {
|
import {
|
||||||
enforceSafeMode,
|
enforceSafeMode,
|
||||||
requireAuth,
|
requireAuth,
|
||||||
|
|
@ -237,5 +238,50 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/prometheus-token',
|
||||||
|
requireAuth(authService),
|
||||||
|
requireCsrf,
|
||||||
|
enforceSafeMode,
|
||||||
|
stepUpGuard,
|
||||||
|
(req, res) => {
|
||||||
|
const parsed = z
|
||||||
|
.object({ enable: z.boolean().optional() })
|
||||||
|
.safeParse(req.body ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const token = crypto.randomBytes(32).toString('base64url');
|
||||||
|
const tokenHash = sha256Hex(token);
|
||||||
|
const next = structuredClone(configManager.getSettings());
|
||||||
|
next.metrics.prometheusTokenHash = tokenHash;
|
||||||
|
if (parsed.data.enable !== undefined) {
|
||||||
|
next.metrics.prometheusEnabled = parsed.data.enable;
|
||||||
|
} else {
|
||||||
|
next.metrics.prometheusEnabled = true;
|
||||||
|
}
|
||||||
|
configManager.saveConfigText(
|
||||||
|
'settings.json',
|
||||||
|
JSON.stringify(next, null, 2),
|
||||||
|
'ui',
|
||||||
|
'Rotate Prometheus metrics Bearer token',
|
||||||
|
);
|
||||||
|
auditService.log({
|
||||||
|
action: 'metrics.prometheus_token_rotate',
|
||||||
|
actorIp: req.clientIp ?? 'unknown',
|
||||||
|
sessionIdHash: req.authSession!.idHash,
|
||||||
|
target: 'settings.json',
|
||||||
|
status: 'ok',
|
||||||
|
details: { prometheusEnabled: next.metrics.prometheusEnabled },
|
||||||
|
});
|
||||||
|
res.json({
|
||||||
|
token,
|
||||||
|
tokenHash,
|
||||||
|
prometheusEnabled: next.metrics.prometheusEnabled,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -548,23 +548,140 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/:id/inspect', requireAuth(authService), async (req, res) => {
|
router.get('/:id/inspect', requireAuth(authService), (req, res) => {
|
||||||
const id = String(req.params.id ?? '');
|
const id = String(req.params.id ?? '');
|
||||||
if (!configManager.getServer(id)) {
|
if (!configManager.getServer(id)) {
|
||||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
const sort = String(req.query.sort ?? 'cpu') === 'mem' ? 'mem' : 'cpu';
|
||||||
const result = await serverInspector.inspect(id);
|
const useSudo = req.query.sudo === 'true' || req.query.sudo === '1';
|
||||||
res.json(result);
|
|
||||||
} catch (err) {
|
const executeInspect = async () => {
|
||||||
res.status(502).json({
|
try {
|
||||||
error: 'INSPECT_FAILED',
|
const result = await serverInspector.inspect(id, { sort, useSudo });
|
||||||
message: err instanceof Error ? err.message : 'Server inspection failed',
|
res.json(result);
|
||||||
|
} catch (err) {
|
||||||
|
res.status(502).json({
|
||||||
|
error: 'INSPECT_FAILED',
|
||||||
|
message: err instanceof Error ? err.message : 'Server inspection failed',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (useSudo) {
|
||||||
|
stepUpGuard(req, res, () => {
|
||||||
|
void executeInspect();
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
void executeInspect();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/:id/processes/:pid/signal',
|
||||||
|
requireAuth(authService),
|
||||||
|
requireCsrf,
|
||||||
|
enforceSafeMode,
|
||||||
|
stepUpGuard,
|
||||||
|
async (req, res) => {
|
||||||
|
const id = String(req.params.id ?? '');
|
||||||
|
if (!configManager.getServer(id)) {
|
||||||
|
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rawPid = String(req.params.pid ?? '');
|
||||||
|
if (!/^[1-9][0-9]{0,7}$/.test(rawPid)) {
|
||||||
|
res.status(400).json({ error: 'INVALID_PID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const parsed = z
|
||||||
|
.object({
|
||||||
|
signal: z.enum(['SIGTERM', 'SIGKILL']).default('SIGTERM'),
|
||||||
|
sudo: z.boolean().optional(),
|
||||||
|
})
|
||||||
|
.safeParse(req.body ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const pid = Number(rawPid);
|
||||||
|
try {
|
||||||
|
const result = await serverInspector.signalProcess(id, pid, parsed.data.signal, {
|
||||||
|
useSudo: parsed.data.sudo,
|
||||||
|
});
|
||||||
|
auditService.log({
|
||||||
|
action: 'server.process_signal',
|
||||||
|
actorIp: req.clientIp ?? 'unknown',
|
||||||
|
sessionIdHash: req.authSession!.idHash,
|
||||||
|
target: `${id}:${pid}`,
|
||||||
|
status: result.ok ? 'ok' : 'error',
|
||||||
|
details: { signal: parsed.data.signal, sudo: Boolean(parsed.data.sudo) },
|
||||||
|
});
|
||||||
|
res.json(result);
|
||||||
|
} catch (err) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: 'SIGNAL_FAILED',
|
||||||
|
message: err instanceof Error ? err.message : 'Unable to send process signal',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
router.get('/:id/probes/history', requireAuth(authService), (req, res) => {
|
||||||
|
const id = String(req.params.id ?? '');
|
||||||
|
if (!configManager.getServer(id)) {
|
||||||
|
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rawRange = String(req.query.range ?? '24h') as MetricRange;
|
||||||
|
const hoursMap: Record<MetricRange, number> = {
|
||||||
|
'1h': 1,
|
||||||
|
'6h': 6,
|
||||||
|
'24h': 24,
|
||||||
|
'7d': 168,
|
||||||
|
'30d': 720,
|
||||||
|
};
|
||||||
|
const hours = hoursMap[rawRange] ?? 24;
|
||||||
|
const limit = Math.max(1, Math.min(1000, Number(req.query.limit) || 200));
|
||||||
|
const samples = monitoringService.queryProbeHistory(
|
||||||
|
id,
|
||||||
|
Date.now() - hours * 3600_000,
|
||||||
|
limit,
|
||||||
|
);
|
||||||
|
res.json({ serverId: id, samples });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/:id/probes/:probeId/run',
|
||||||
|
requireAuth(authService),
|
||||||
|
requireCsrf,
|
||||||
|
async (req, res) => {
|
||||||
|
const id = String(req.params.id ?? '');
|
||||||
|
const probeId = String(req.params.probeId ?? '');
|
||||||
|
if (!configManager.getServer(id)) {
|
||||||
|
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const sample = await monitoringService.runProbeNow(id, probeId);
|
||||||
|
auditService.log({
|
||||||
|
action: 'server.probe_run',
|
||||||
|
actorIp: req.clientIp ?? 'unknown',
|
||||||
|
sessionIdHash: req.authSession!.idHash,
|
||||||
|
target: `${id}:${probeId}`,
|
||||||
|
status: sample.ok ? 'ok' : 'error',
|
||||||
|
});
|
||||||
|
res.json({ serverId: id, sample });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(404).json({
|
||||||
|
error: 'PROBE_RUN_FAILED',
|
||||||
|
message: err instanceof Error ? err.message : 'Unable to run probe',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
router.get('/:id/keys', requireAuth(authService), async (req, res) => {
|
router.get('/:id/keys', requireAuth(authService), async (req, res) => {
|
||||||
const id = String(req.params.id ?? '');
|
const id = String(req.params.id ?? '');
|
||||||
if (!configManager.getServer(id)) {
|
if (!configManager.getServer(id)) {
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js';
|
||||||
import { ServerInspector } from './monitoring/inspector.js';
|
import { ServerInspector } from './monitoring/inspector.js';
|
||||||
import { MonitoringService } from './monitoring/monitoring-service.js';
|
import { MonitoringService } from './monitoring/monitoring-service.js';
|
||||||
import { ProbeRunner } from './monitoring/probes.js';
|
import { ProbeRunner } from './monitoring/probes.js';
|
||||||
|
import { createPrometheusHandler } from './monitoring/prometheus.js';
|
||||||
import { AuditService } from './security/audit.js';
|
import { AuditService } from './security/audit.js';
|
||||||
import { AuthService } from './security/auth.js';
|
import { AuthService } from './security/auth.js';
|
||||||
import { BackupScheduler } from './security/backup-scheduler.js';
|
import { BackupScheduler } from './security/backup-scheduler.js';
|
||||||
|
|
@ -195,13 +196,14 @@ export async function createGCoordinatorServer(
|
||||||
wsHub,
|
wsHub,
|
||||||
);
|
);
|
||||||
const serverInspector = new ServerInspector(sshPool, configManager);
|
const serverInspector = new ServerInspector(sshPool, configManager);
|
||||||
const probeRunner = new ProbeRunner(sshPool);
|
const probeRunner = new ProbeRunner(sshPool, configManager);
|
||||||
const monitoringService = new MonitoringService(
|
const monitoringService = new MonitoringService(
|
||||||
db,
|
db,
|
||||||
configManager,
|
configManager,
|
||||||
vaultService,
|
vaultService,
|
||||||
sshPool,
|
sshPool,
|
||||||
probeRunner,
|
probeRunner,
|
||||||
|
getRuntimeLimits,
|
||||||
);
|
);
|
||||||
const transferEngine = new TransferEngine(sshPool, sftpService, configManager);
|
const transferEngine = new TransferEngine(sshPool, sftpService, configManager);
|
||||||
const workflowEngine = new WorkflowEngine(
|
const workflowEngine = new WorkflowEngine(
|
||||||
|
|
@ -612,6 +614,17 @@ export async function createGCoordinatorServer(
|
||||||
createConfigRouter({ authService, configManager, auditService, stepUpGuard }),
|
createConfigRouter({ authService, configManager, auditService, stepUpGuard }),
|
||||||
);
|
);
|
||||||
app.use('/api/audit', createAuditRouter(authService, auditService));
|
app.use('/api/audit', createAuditRouter(authService, auditService));
|
||||||
|
app.get(
|
||||||
|
'/metrics',
|
||||||
|
createPrometheusHandler({
|
||||||
|
configManager,
|
||||||
|
vaultService,
|
||||||
|
sshPool,
|
||||||
|
monitoringService,
|
||||||
|
tunnelManager,
|
||||||
|
alertEngine,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
app.use('/api', (_req, res) => {
|
app.use('/api', (_req, res) => {
|
||||||
res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' });
|
res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' });
|
||||||
|
|
|
||||||
|
|
@ -56,20 +56,67 @@ export const LINUX_METRIC_CMD = [
|
||||||
].join('; ');
|
].join('; ');
|
||||||
|
|
||||||
export const BSD_METRIC_CMD = [
|
export const BSD_METRIC_CMD = [
|
||||||
'printf "===SYSCTL===\\n"; sysctl -n hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null',
|
'printf "===SYSCTL===\\n"; sysctl hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null || true',
|
||||||
'printf "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat',
|
'printf "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat',
|
||||||
'printf "===NET===\\n"; netstat -ibn 2>/dev/null',
|
'printf "===NET===\\n"; netstat -ibn 2>/dev/null',
|
||||||
'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP',
|
'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP',
|
||||||
].join('; ');
|
].join('; ');
|
||||||
|
|
||||||
export const MACOS_METRIC_CMD = [
|
export const MACOS_METRIC_CMD = [
|
||||||
'printf "===SYSCTL===\\n"; sysctl -n hw.memsize hw.pagesize vm.loadavg kern.boottime',
|
'printf "===SYSCTL===\\n"; sysctl hw.memsize hw.pagesize vm.loadavg kern.boottime 2>/dev/null || true',
|
||||||
'printf "===VMSTAT===\\n"; vm_stat',
|
'printf "===VMSTAT===\\n"; vm_stat',
|
||||||
'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true',
|
'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true',
|
||||||
'printf "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib',
|
'printf "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib',
|
||||||
'printf "===DF===\\n"; df -kP',
|
'printf "===DF===\\n"; df -kP',
|
||||||
].join('; ');
|
].join('; ');
|
||||||
|
|
||||||
|
const VIRTUAL_NIC_PREFIXES = [
|
||||||
|
'lo',
|
||||||
|
'veth',
|
||||||
|
'docker',
|
||||||
|
'br-',
|
||||||
|
'tun',
|
||||||
|
'tap',
|
||||||
|
'wg',
|
||||||
|
'virbr',
|
||||||
|
'dummy',
|
||||||
|
'cilium',
|
||||||
|
'flannel',
|
||||||
|
'cni',
|
||||||
|
'vxlan',
|
||||||
|
'ifb',
|
||||||
|
];
|
||||||
|
|
||||||
|
function isVirtualNic(iface: string): boolean {
|
||||||
|
const clean = iface.trim().replace(/:$/, '').toLowerCase();
|
||||||
|
return VIRTUAL_NIC_PREFIXES.some(
|
||||||
|
(p) => clean === p || (p.endsWith('-') ? clean.startsWith(p) : clean.startsWith(p)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse `sysctl` sections supporting both `key: val` / `key=val` (resilient to
|
||||||
|
* missing keys across BSD/macOS versions) and legacy unlabeled positional lines.
|
||||||
|
*/
|
||||||
|
function parseSysctlMap(rawText: string, positionalKeys: string[]): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
const lines = rawText
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((l) => l.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
let posIdx = 0;
|
||||||
|
for (const line of lines) {
|
||||||
|
const kv = /^([a-zA-Z][a-zA-Z0-9_.]*)\s*[:=]\s*(.+)$/.exec(line);
|
||||||
|
if (kv) {
|
||||||
|
out.set(kv[1]!, kv[2]!.trim());
|
||||||
|
} else if (posIdx < positionalKeys.length) {
|
||||||
|
out.set(positionalKeys[posIdx]!, line);
|
||||||
|
posIdx += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
function splitSections(stdout: string): Record<string, string> {
|
function splitSections(stdout: string): Record<string, string> {
|
||||||
const sections: Record<string, string> = {};
|
const sections: Record<string, string> = {};
|
||||||
let current = '';
|
let current = '';
|
||||||
|
|
@ -137,6 +184,7 @@ function parseDfLines(
|
||||||
if (
|
if (
|
||||||
fsName === 'devfs' ||
|
fsName === 'devfs' ||
|
||||||
fsName === 'map' ||
|
fsName === 'map' ||
|
||||||
|
fsName.startsWith('/dev/loop') ||
|
||||||
!Number.isFinite(totalKb) ||
|
!Number.isFinite(totalKb) ||
|
||||||
totalKb <= 0
|
totalKb <= 0
|
||||||
) {
|
) {
|
||||||
|
|
@ -205,9 +253,12 @@ export function parseLinuxOutput(
|
||||||
Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0),
|
Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Network RX/TX across non-loopback interfaces
|
// Network RX/TX prioritizing physical NICs and excluding loopback/virtual bridges
|
||||||
let netRxBytes = 0;
|
let physRxBytes = 0;
|
||||||
let netTxBytes = 0;
|
let physTxBytes = 0;
|
||||||
|
let hasPhys = false;
|
||||||
|
let fallbackRxBytes = 0;
|
||||||
|
let fallbackTxBytes = 0;
|
||||||
for (const line of (sec.NET ?? '').split(/\r?\n/)) {
|
for (const line of (sec.NET ?? '').split(/\r?\n/)) {
|
||||||
const colon = line.indexOf(':');
|
const colon = line.indexOf(':');
|
||||||
if (colon <= 0) continue;
|
if (colon <= 0) continue;
|
||||||
|
|
@ -215,10 +266,19 @@ export function parseLinuxOutput(
|
||||||
if (iface === 'lo' || iface.startsWith('lo:')) continue;
|
if (iface === 'lo' || iface.startsWith('lo:')) continue;
|
||||||
const cols = line.slice(colon + 1).trim().split(/\s+/);
|
const cols = line.slice(colon + 1).trim().split(/\s+/);
|
||||||
if (cols.length >= 9) {
|
if (cols.length >= 9) {
|
||||||
netRxBytes += Number(cols[0]) || 0;
|
const rx = Number(cols[0]) || 0;
|
||||||
netTxBytes += Number(cols[8]) || 0;
|
const tx = Number(cols[8]) || 0;
|
||||||
|
fallbackRxBytes += rx;
|
||||||
|
fallbackTxBytes += tx;
|
||||||
|
if (!isVirtualNic(iface)) {
|
||||||
|
hasPhys = true;
|
||||||
|
physRxBytes += rx;
|
||||||
|
physTxBytes += tx;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const netRxBytes = hasPhys ? physRxBytes : fallbackRxBytes;
|
||||||
|
const netTxBytes = hasPhys ? physTxBytes : fallbackTxBytes;
|
||||||
|
|
||||||
let netRxBps = 0;
|
let netRxBps = 0;
|
||||||
let netTxBps = 0;
|
let netTxBps = 0;
|
||||||
|
|
@ -267,25 +327,28 @@ export function parseBsdOutput(
|
||||||
nowMs = Date.now(),
|
nowMs = Date.now(),
|
||||||
): CollectOutput {
|
): CollectOutput {
|
||||||
const sec = splitSections(stdout);
|
const sec = splitSections(stdout);
|
||||||
const sysctlLines = (sec.SYSCTL ?? '')
|
const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [
|
||||||
.split(/\r?\n/)
|
'hw.physmem',
|
||||||
.map((l) => l.trim())
|
'hw.pagesize',
|
||||||
.filter(Boolean);
|
'vm.loadavg',
|
||||||
|
'kern.boottime',
|
||||||
|
'kern.cp_time',
|
||||||
|
]);
|
||||||
|
|
||||||
const physMemBytes = Number(sysctlLines[0]) || 0;
|
const physMemBytes = Number(sysctl.get('hw.physmem')) || 0;
|
||||||
const pageSize = Number(sysctlLines[1]) || 4096;
|
const pageSize = Number(sysctl.get('hw.pagesize')) || 4096;
|
||||||
const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0');
|
const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0');
|
||||||
const load1m = round2(Number(loadMatch?.[1] ?? 0));
|
const load1m = round2(Number(loadMatch?.[1] ?? 0));
|
||||||
|
|
||||||
let uptimeSec = 0;
|
let uptimeSec = 0;
|
||||||
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? '');
|
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? '');
|
||||||
if (bootSecMatch) {
|
if (bootSecMatch) {
|
||||||
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
|
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
|
||||||
}
|
}
|
||||||
|
|
||||||
let cpuTotal = 0;
|
let cpuTotal = 0;
|
||||||
let cpuIdle = 0;
|
let cpuIdle = 0;
|
||||||
const cpNums = (sysctlLines[4] ?? '')
|
const cpNums = (sysctl.get('kern.cp_time') ?? '')
|
||||||
.split(/\s+/)
|
.split(/\s+/)
|
||||||
.map((n) => Number(n) || 0);
|
.map((n) => Number(n) || 0);
|
||||||
if (cpNums.length >= 5) {
|
if (cpNums.length >= 5) {
|
||||||
|
|
@ -369,18 +432,20 @@ export function parseMacOsOutput(
|
||||||
nowMs = Date.now(),
|
nowMs = Date.now(),
|
||||||
): CollectOutput {
|
): CollectOutput {
|
||||||
const sec = splitSections(stdout);
|
const sec = splitSections(stdout);
|
||||||
const sysctlLines = (sec.SYSCTL ?? '')
|
const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [
|
||||||
.split(/\r?\n/)
|
'hw.memsize',
|
||||||
.map((l) => l.trim())
|
'hw.pagesize',
|
||||||
.filter(Boolean);
|
'vm.loadavg',
|
||||||
|
'kern.boottime',
|
||||||
|
]);
|
||||||
|
|
||||||
const memBytes = Number(sysctlLines[0]) || 0;
|
const memBytes = Number(sysctl.get('hw.memsize')) || 0;
|
||||||
const pageSize = Number(sysctlLines[1]) || 4096;
|
const pageSize = Number(sysctl.get('hw.pagesize')) || 4096;
|
||||||
const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0');
|
const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0');
|
||||||
const load1m = round2(Number(loadMatch?.[1] ?? 0));
|
const load1m = round2(Number(loadMatch?.[1] ?? 0));
|
||||||
|
|
||||||
let uptimeSec = 0;
|
let uptimeSec = 0;
|
||||||
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? '');
|
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? '');
|
||||||
if (bootSecMatch) {
|
if (bootSecMatch) {
|
||||||
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
|
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,25 +26,30 @@ export interface ServerInspectionResult {
|
||||||
serverId: string;
|
serverId: string;
|
||||||
os: OsType;
|
os: OsType;
|
||||||
collectedAt: number;
|
collectedAt: number;
|
||||||
|
sort: 'cpu' | 'mem';
|
||||||
processes: ProcessEntry[];
|
processes: ProcessEntry[];
|
||||||
ports: PortEntry[];
|
ports: PortEntry[];
|
||||||
thermals: ThermalEntry[];
|
thermals: ThermalEntry[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const LINUX_INSPECT_CMD = [
|
function buildLinuxInspectCmd(sort: 'cpu' | 'mem'): string {
|
||||||
'printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=-%cpu 2>/dev/null | head -n 26 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 26',
|
const linuxSort = sort === 'mem' ? '-rss' : '-%cpu';
|
||||||
'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true',
|
const bsdFlag = sort === 'mem' ? '-m' : '-r';
|
||||||
'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true',
|
return [
|
||||||
].join('; ');
|
`printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=${linuxSort} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args ${bsdFlag} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 41`,
|
||||||
|
'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true',
|
||||||
|
'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true',
|
||||||
|
].join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
const BSD_INSPECT_CMD = [
|
const BSD_INSPECT_CMD = [
|
||||||
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 26',
|
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 41',
|
||||||
'printf "===PORTS===\\n"; sockstat -l 2>/dev/null || netstat -an 2>/dev/null || true',
|
'printf "===PORTS===\\n"; sockstat -l 2>/dev/null || netstat -an 2>/dev/null || true',
|
||||||
'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true',
|
'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true',
|
||||||
].join('; ');
|
].join('; ');
|
||||||
|
|
||||||
const MACOS_INSPECT_CMD = [
|
const MACOS_INSPECT_CMD = [
|
||||||
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 26',
|
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 41',
|
||||||
'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true',
|
'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true',
|
||||||
'printf "===THERMAL===\\n"; true',
|
'printf "===THERMAL===\\n"; true',
|
||||||
].join('; ');
|
].join('; ');
|
||||||
|
|
@ -54,6 +59,7 @@ export function parseInspectorOutput(
|
||||||
os: OsType,
|
os: OsType,
|
||||||
stdout: string,
|
stdout: string,
|
||||||
collectedAt = Date.now(),
|
collectedAt = Date.now(),
|
||||||
|
sort: 'cpu' | 'mem' = 'cpu',
|
||||||
): ServerInspectionResult {
|
): ServerInspectionResult {
|
||||||
const sections: Record<string, string[]> = {};
|
const sections: Record<string, string[]> = {};
|
||||||
let current = '';
|
let current = '';
|
||||||
|
|
@ -85,6 +91,12 @@ export function parseInspectorOutput(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
processes.sort((a, b) =>
|
||||||
|
sort === 'mem'
|
||||||
|
? b.memPct - a.memPct || b.rssMb - a.rssMb || b.cpuPct - a.cpuPct
|
||||||
|
: b.cpuPct - a.cpuPct || b.memPct - a.memPct,
|
||||||
|
);
|
||||||
|
|
||||||
// Ports
|
// Ports
|
||||||
const ports: PortEntry[] = [];
|
const ports: PortEntry[] = [];
|
||||||
const portLines = sections.PORTS ?? [];
|
const portLines = sections.PORTS ?? [];
|
||||||
|
|
@ -98,7 +110,6 @@ export function parseInspectorOutput(
|
||||||
}
|
}
|
||||||
const cols = trimmed.split(/\s+/);
|
const cols = trimmed.split(/\s+/);
|
||||||
if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) {
|
if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) {
|
||||||
// ss -tulnp format: Netid State Recv-Q Send-Q Local Peer Process
|
|
||||||
if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) {
|
if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) {
|
||||||
ports.push({
|
ports.push({
|
||||||
proto: cols[0]!,
|
proto: cols[0]!,
|
||||||
|
|
@ -113,14 +124,12 @@ export function parseInspectorOutput(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') {
|
} else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') {
|
||||||
// lsof format
|
|
||||||
ports.push({
|
ports.push({
|
||||||
proto: cols[7] ?? 'TCP',
|
proto: cols[7] ?? 'TCP',
|
||||||
localAddress: cols[8] ?? '',
|
localAddress: cols[8] ?? '',
|
||||||
process: `${cols[0]}(${cols[1]})`,
|
process: `${cols[0]}(${cols[1]})`,
|
||||||
});
|
});
|
||||||
} else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) {
|
} else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) {
|
||||||
// sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN
|
|
||||||
ports.push({
|
ports.push({
|
||||||
proto: cols[4] ?? 'tcp',
|
proto: cols[4] ?? 'tcp',
|
||||||
localAddress: cols[5] ?? '',
|
localAddress: cols[5] ?? '',
|
||||||
|
|
@ -144,7 +153,7 @@ export function parseInspectorOutput(
|
||||||
thermals.push({ zone, tempC });
|
thermals.push({ zone, tempC });
|
||||||
}
|
}
|
||||||
|
|
||||||
return { serverId, os, collectedAt, processes, ports, thermals };
|
return { serverId, os, collectedAt, sort, processes, ports, thermals };
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ServerInspector {
|
export class ServerInspector {
|
||||||
|
|
@ -153,11 +162,15 @@ export class ServerInspector {
|
||||||
private readonly configManager: ConfigManager,
|
private readonly configManager: ConfigManager,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async inspect(serverId: string): Promise<ServerInspectionResult> {
|
async inspect(
|
||||||
|
serverId: string,
|
||||||
|
opts: { sort?: 'cpu' | 'mem'; useSudo?: boolean } = {},
|
||||||
|
): Promise<ServerInspectionResult> {
|
||||||
const server = this.configManager.getServer(serverId);
|
const server = this.configManager.getServer(serverId);
|
||||||
if (!server) {
|
if (!server) {
|
||||||
throw new Error(`Unknown server "${serverId}"`);
|
throw new Error(`Unknown server "${serverId}"`);
|
||||||
}
|
}
|
||||||
|
const sort = opts.sort === 'mem' ? 'mem' : 'cpu';
|
||||||
const runtime = this.sshPool.getState(serverId);
|
const runtime = this.sshPool.getState(serverId);
|
||||||
const os = await detectServerOs(this.sshPool, server, runtime?.osDetected);
|
const os = await detectServerOs(this.sshPool, server, runtime?.osDetected);
|
||||||
const cmd =
|
const cmd =
|
||||||
|
|
@ -165,9 +178,39 @@ export class ServerInspector {
|
||||||
? MACOS_INSPECT_CMD
|
? MACOS_INSPECT_CMD
|
||||||
: os === 'bsd'
|
: os === 'bsd'
|
||||||
? BSD_INSPECT_CMD
|
? BSD_INSPECT_CMD
|
||||||
: LINUX_INSPECT_CMD;
|
: buildLinuxInspectCmd(sort);
|
||||||
|
|
||||||
const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 });
|
const res = await this.sshPool.exec(serverId, cmd, {
|
||||||
return parseInspectorOutput(serverId, os, res.stdout);
|
timeoutMs: 15_000,
|
||||||
|
sudo: opts.useSudo,
|
||||||
|
});
|
||||||
|
return parseInspectorOutput(serverId, os, res.stdout, Date.now(), sort);
|
||||||
|
}
|
||||||
|
|
||||||
|
async signalProcess(
|
||||||
|
serverId: string,
|
||||||
|
pid: number,
|
||||||
|
signal: 'SIGTERM' | 'SIGKILL',
|
||||||
|
opts: { useSudo?: boolean } = {},
|
||||||
|
): Promise<{ ok: boolean; pid: number; signal: string; stderr: string }> {
|
||||||
|
const server = this.configManager.getServer(serverId);
|
||||||
|
if (!server) {
|
||||||
|
throw new Error(`Unknown server "${serverId}"`);
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(pid) || pid < 1 || pid > 99_999_999) {
|
||||||
|
throw new Error('Invalid PID');
|
||||||
|
}
|
||||||
|
const sigName = signal === 'SIGKILL' ? 'KILL' : 'TERM';
|
||||||
|
const res = await this.sshPool.exec(
|
||||||
|
serverId,
|
||||||
|
`kill -s ${sigName} ${pid}`,
|
||||||
|
{ timeoutMs: 10_000, sudo: opts.useSudo },
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
ok: res.exitCode === 0,
|
||||||
|
pid,
|
||||||
|
signal,
|
||||||
|
stderr: res.stderr.trim(),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import type {
|
||||||
ProbeSample,
|
ProbeSample,
|
||||||
} from '../../shared/ws-protocol.js';
|
} from '../../shared/ws-protocol.js';
|
||||||
import type { ConfigManager } from '../config/config-manager.js';
|
import type { ConfigManager } from '../config/config-manager.js';
|
||||||
|
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||||
import type { VaultService } from '../security/vault.js';
|
import type { VaultService } from '../security/vault.js';
|
||||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||||
import {
|
import {
|
||||||
|
|
@ -37,6 +38,7 @@ export interface MonitoringTickEvent {
|
||||||
interface ServerTimers {
|
interface ServerTimers {
|
||||||
metricTimer: NodeJS.Timeout | null;
|
metricTimer: NodeJS.Timeout | null;
|
||||||
warmupTimer: NodeJS.Timeout | null;
|
warmupTimer: NodeJS.Timeout | null;
|
||||||
|
staggerTimer: NodeJS.Timeout | null;
|
||||||
probeTimers: Map<string, NodeJS.Timeout>;
|
probeTimers: Map<string, NodeJS.Timeout>;
|
||||||
pollingMetrics: boolean;
|
pollingMetrics: boolean;
|
||||||
}
|
}
|
||||||
|
|
@ -54,6 +56,8 @@ export class MonitoringService {
|
||||||
>();
|
>();
|
||||||
private maintenanceTimer: NodeJS.Timeout | null = null;
|
private maintenanceTimer: NodeJS.Timeout | null = null;
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
|
private inFlightPolls = 0;
|
||||||
|
private readonly pollQueue: Array<() => void> = [];
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly db: Database.Database,
|
private readonly db: Database.Database,
|
||||||
|
|
@ -61,6 +65,7 @@ export class MonitoringService {
|
||||||
private readonly vaultService: VaultService,
|
private readonly vaultService: VaultService,
|
||||||
private readonly sshPool: SSHPool,
|
private readonly sshPool: SSHPool,
|
||||||
private readonly probeRunner: ProbeRunner,
|
private readonly probeRunner: ProbeRunner,
|
||||||
|
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
onTick(listener: (event: MonitoringTickEvent) => void): () => void {
|
onTick(listener: (event: MonitoringTickEvent) => void): () => void {
|
||||||
|
|
@ -96,6 +101,7 @@ export class MonitoringService {
|
||||||
for (const timers of this.serverTimers.values()) {
|
for (const timers of this.serverTimers.values()) {
|
||||||
if (timers.metricTimer) clearInterval(timers.metricTimer);
|
if (timers.metricTimer) clearInterval(timers.metricTimer);
|
||||||
if (timers.warmupTimer) clearTimeout(timers.warmupTimer);
|
if (timers.warmupTimer) clearTimeout(timers.warmupTimer);
|
||||||
|
if (timers.staggerTimer) clearTimeout(timers.staggerTimer);
|
||||||
for (const pt of timers.probeTimers.values()) clearInterval(pt);
|
for (const pt of timers.probeTimers.values()) clearInterval(pt);
|
||||||
}
|
}
|
||||||
this.serverTimers.clear();
|
this.serverTimers.clear();
|
||||||
|
|
@ -104,6 +110,9 @@ export class MonitoringService {
|
||||||
close(): void {
|
close(): void {
|
||||||
this.stopped = true;
|
this.stopped = true;
|
||||||
this.stopAll();
|
this.stopAll();
|
||||||
|
while (this.pollQueue.length > 0) {
|
||||||
|
this.pollQueue.shift()?.();
|
||||||
|
}
|
||||||
if (this.maintenanceTimer) {
|
if (this.maintenanceTimer) {
|
||||||
clearInterval(this.maintenanceTimer);
|
clearInterval(this.maintenanceTimer);
|
||||||
this.maintenanceTimer = null;
|
this.maintenanceTimer = null;
|
||||||
|
|
@ -119,10 +128,10 @@ export class MonitoringService {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const server of this.configManager.listServers()) {
|
const enabledServers = this.configManager.listServers().filter((s) => s.enabled);
|
||||||
if (!server.enabled) continue;
|
enabledServers.forEach((server, idx) => {
|
||||||
this.scheduleServer(server);
|
this.scheduleServer(server, idx);
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getLatest(serverId: string): LatestServerTelemetry | undefined {
|
getLatest(serverId: string): LatestServerTelemetry | undefined {
|
||||||
|
|
@ -138,45 +147,105 @@ export class MonitoringService {
|
||||||
return this.executeMetricPoll(server);
|
return this.executeMetricPoll(server);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async runProbeNow(serverId: string, probeId: string): Promise<ProbeSample> {
|
||||||
|
const server = this.configManager.getServer(serverId);
|
||||||
|
if (!server) {
|
||||||
|
throw new Error(`Unknown server "${serverId}"`);
|
||||||
|
}
|
||||||
|
const probe = server.probes.find((p) => p.id === probeId);
|
||||||
|
if (!probe) {
|
||||||
|
throw new Error(`Unknown probe "${probeId}" on server "${serverId}"`);
|
||||||
|
}
|
||||||
|
return this.runAndPersistProbe(server, probe);
|
||||||
|
}
|
||||||
|
|
||||||
runMaintenance(nowMs = Date.now()): void {
|
runMaintenance(nowMs = Date.now()): void {
|
||||||
const settings = this.configManager.getSettings();
|
const settings = this.configManager.getSettings();
|
||||||
const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000;
|
const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000;
|
||||||
const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000;
|
const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000;
|
||||||
|
const auditCutoff = nowMs - settings.auditRetentionDays * 86_400_000;
|
||||||
|
const workflowCutoff = nowMs - settings.workflowRunRetentionDays * 86_400_000;
|
||||||
|
const alertCutoff = nowMs - settings.alertEventRetentionDays * 86_400_000;
|
||||||
|
|
||||||
const tx = this.db.transaction(() => {
|
const tx = this.db.transaction(() => {
|
||||||
// Aggregate hourly rollups from raw metrics
|
// Stage 1: Aggregate 1h rollups preserving any partial bucket spanning rawCutoff
|
||||||
this.db
|
this.db
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max)
|
`INSERT INTO metrics_rollup (
|
||||||
|
bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max,
|
||||||
|
mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct
|
||||||
|
)
|
||||||
SELECT
|
SELECT
|
||||||
(ts / 3600000) * 3600000 AS bucket_ts,
|
(r.ts / 3600000) * 3600000 AS bucket_ts,
|
||||||
'1h' AS granularity,
|
'1h' AS granularity,
|
||||||
server_id,
|
r.server_id,
|
||||||
MIN(cpu_pct),
|
MIN(r.cpu_pct),
|
||||||
AVG(cpu_pct),
|
AVG(r.cpu_pct),
|
||||||
MAX(cpu_pct),
|
MAX(r.cpu_pct),
|
||||||
COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0),
|
COALESCE(AVG(CASE WHEN r.mem_total_mb > 0 THEN (r.mem_used_mb * 100.0 / r.mem_total_mb) ELSE 0 END), 0),
|
||||||
MAX(load_1m)
|
MAX(r.load_1m),
|
||||||
FROM metrics_raw
|
AVG(r.net_rx_bps),
|
||||||
GROUP BY server_id, (ts / 3600000) * 3600000`,
|
AVG(r.net_tx_bps),
|
||||||
|
COALESCE(MAX(d.max_disk_pct), 0)
|
||||||
|
FROM metrics_raw r
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT server_id, ts, MAX(used_pct) AS max_disk_pct
|
||||||
|
FROM metrics_disks
|
||||||
|
GROUP BY server_id, ts
|
||||||
|
) d ON d.server_id = r.server_id AND d.ts = r.ts
|
||||||
|
GROUP BY r.server_id, (r.ts / 3600000) * 3600000
|
||||||
|
ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET
|
||||||
|
cpu_min = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_min ELSE MIN(metrics_rollup.cpu_min, excluded.cpu_min) END,
|
||||||
|
cpu_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_max ELSE MAX(metrics_rollup.cpu_max, excluded.cpu_max) END,
|
||||||
|
load_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.load_max ELSE MAX(metrics_rollup.load_max, excluded.load_max) END,
|
||||||
|
disk_max_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.disk_max_pct ELSE MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct) END,
|
||||||
|
cpu_avg = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_avg ELSE metrics_rollup.cpu_avg END,
|
||||||
|
mem_avg_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.mem_avg_pct ELSE metrics_rollup.mem_avg_pct END,
|
||||||
|
net_rx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_rx_avg_bps ELSE metrics_rollup.net_rx_avg_bps END,
|
||||||
|
net_tx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_tx_avg_bps ELSE metrics_rollup.net_tx_avg_bps END`,
|
||||||
)
|
)
|
||||||
.run();
|
.run(
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
rawCutoff,
|
||||||
|
);
|
||||||
|
|
||||||
// Aggregate daily rollups
|
// Stage 2: Aggregate 1d rollups from complete 1h buckets so raw pruning never truncates a day
|
||||||
this.db
|
this.db
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max)
|
`INSERT INTO metrics_rollup (
|
||||||
|
bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max,
|
||||||
|
mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct
|
||||||
|
)
|
||||||
SELECT
|
SELECT
|
||||||
(ts / 86400000) * 86400000 AS bucket_ts,
|
(bucket_ts / 86400000) * 86400000 AS day_ts,
|
||||||
'1d' AS granularity,
|
'1d' AS granularity,
|
||||||
server_id,
|
server_id,
|
||||||
MIN(cpu_pct),
|
MIN(cpu_min),
|
||||||
AVG(cpu_pct),
|
AVG(cpu_avg),
|
||||||
MAX(cpu_pct),
|
MAX(cpu_max),
|
||||||
COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0),
|
AVG(mem_avg_pct),
|
||||||
MAX(load_1m)
|
MAX(load_max),
|
||||||
FROM metrics_raw
|
AVG(net_rx_avg_bps),
|
||||||
GROUP BY server_id, (ts / 86400000) * 86400000`,
|
AVG(net_tx_avg_bps),
|
||||||
|
MAX(disk_max_pct)
|
||||||
|
FROM metrics_rollup
|
||||||
|
WHERE granularity = '1h'
|
||||||
|
GROUP BY server_id, (bucket_ts / 86400000) * 86400000
|
||||||
|
ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET
|
||||||
|
cpu_min = MIN(metrics_rollup.cpu_min, excluded.cpu_min),
|
||||||
|
cpu_max = MAX(metrics_rollup.cpu_max, excluded.cpu_max),
|
||||||
|
load_max = MAX(metrics_rollup.load_max, excluded.load_max),
|
||||||
|
disk_max_pct = MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct),
|
||||||
|
cpu_avg = excluded.cpu_avg,
|
||||||
|
mem_avg_pct = excluded.mem_avg_pct,
|
||||||
|
net_rx_avg_bps = excluded.net_rx_avg_bps,
|
||||||
|
net_tx_avg_bps = excluded.net_tx_avg_bps`,
|
||||||
)
|
)
|
||||||
.run();
|
.run();
|
||||||
|
|
||||||
|
|
@ -184,16 +253,65 @@ export class MonitoringService {
|
||||||
this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff);
|
this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff);
|
||||||
this.db.prepare('DELETE FROM probe_results WHERE ts < ?').run(rawCutoff);
|
this.db.prepare('DELETE FROM probe_results WHERE ts < ?').run(rawCutoff);
|
||||||
this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff);
|
this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff);
|
||||||
|
this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(auditCutoff);
|
||||||
|
this.db
|
||||||
|
.prepare('DELETE FROM workflow_runs WHERE finished_at IS NOT NULL AND started_at < ?')
|
||||||
|
.run(workflowCutoff);
|
||||||
|
this.db
|
||||||
|
.prepare(
|
||||||
|
"DELETE FROM alert_events WHERE state = 'resolved' AND COALESCE(resolved_at, triggered_at) < ?",
|
||||||
|
)
|
||||||
|
.run(alertCutoff);
|
||||||
|
this.db.prepare('DELETE FROM alert_silences WHERE expires_at < ?').run(nowMs);
|
||||||
|
this.db
|
||||||
|
.prepare('DELETE FROM broadcast_jobs WHERE finished_at IS NOT NULL AND started_at < ?')
|
||||||
|
.run(workflowCutoff);
|
||||||
});
|
});
|
||||||
tx();
|
tx();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
queryProbeHistory(
|
||||||
|
serverId: string,
|
||||||
|
sinceMs = Date.now() - 24 * 3600_000,
|
||||||
|
limit = 200,
|
||||||
|
): Array<ProbeSample & { ts: number }> {
|
||||||
|
const safeLimit = Math.max(1, Math.min(1000, Math.floor(limit)));
|
||||||
|
const rows = this.db
|
||||||
|
.prepare(
|
||||||
|
`SELECT ts, probe_id AS probeId, ok AS okInt, status_code AS statusCode,
|
||||||
|
latency_ms AS latencyMs, error
|
||||||
|
FROM probe_results
|
||||||
|
WHERE server_id = ? AND ts >= ?
|
||||||
|
ORDER BY ts DESC
|
||||||
|
LIMIT ?`,
|
||||||
|
)
|
||||||
|
.all(serverId, sinceMs, safeLimit) as Array<{
|
||||||
|
ts: number;
|
||||||
|
probeId: string;
|
||||||
|
okInt: number;
|
||||||
|
statusCode: number | null;
|
||||||
|
latencyMs: number;
|
||||||
|
error: string | null;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
return rows.reverse().map((r) => ({
|
||||||
|
ts: r.ts,
|
||||||
|
probeId: r.probeId,
|
||||||
|
ok: r.okInt === 1,
|
||||||
|
statusCode: r.statusCode ?? undefined,
|
||||||
|
latencyMs: r.latencyMs,
|
||||||
|
error: r.error ?? undefined,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
queryHistory(serverId: string, range: MetricRange = '1h'): {
|
queryHistory(serverId: string, range: MetricRange = '1h'): {
|
||||||
range: MetricRange;
|
range: MetricRange;
|
||||||
granularity: 'raw' | '1h' | '1d';
|
granularity: 'raw' | '1h' | '1d';
|
||||||
points: Array<Record<string, unknown>>;
|
points: Array<Record<string, unknown>>;
|
||||||
latestDisks: DiskSample[];
|
latestDisks: DiskSample[];
|
||||||
latestProbes: Array<ProbeSample & { ts: number }>;
|
latestProbes: Array<ProbeSample & { ts: number }>;
|
||||||
|
probeHistory: Array<ProbeSample & { ts: number }>;
|
||||||
|
diskHistory: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>;
|
||||||
} {
|
} {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const rangeMs: Record<MetricRange, number> = {
|
const rangeMs: Record<MetricRange, number> = {
|
||||||
|
|
@ -223,7 +341,9 @@ export class MonitoringService {
|
||||||
points = this.db
|
points = this.db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax,
|
`SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax,
|
||||||
mem_avg_pct AS memAvgPct, load_max AS loadMax
|
mem_avg_pct AS memAvgPct, load_max AS loadMax,
|
||||||
|
net_rx_avg_bps AS netRxAvgBps, net_tx_avg_bps AS netTxAvgBps,
|
||||||
|
disk_max_pct AS diskMaxPct
|
||||||
FROM metrics_rollup
|
FROM metrics_rollup
|
||||||
WHERE server_id = ? AND granularity = ? AND bucket_ts >= ?
|
WHERE server_id = ? AND granularity = ? AND bucket_ts >= ?
|
||||||
ORDER BY bucket_ts ASC`,
|
ORDER BY bucket_ts ASC`,
|
||||||
|
|
@ -240,6 +360,22 @@ export class MonitoringService {
|
||||||
)
|
)
|
||||||
.all(serverId, serverId) as DiskSample[];
|
.all(serverId, serverId) as DiskSample[];
|
||||||
|
|
||||||
|
const diskHistory = this.db
|
||||||
|
.prepare(
|
||||||
|
`SELECT ts, mount_point AS mountPoint, used_pct AS usedPct, used_mb AS usedMb, total_mb AS totalMb
|
||||||
|
FROM metrics_disks
|
||||||
|
WHERE server_id = ? AND ts >= ?
|
||||||
|
ORDER BY ts ASC
|
||||||
|
LIMIT 500`,
|
||||||
|
)
|
||||||
|
.all(serverId, since) as Array<{
|
||||||
|
ts: number;
|
||||||
|
mountPoint: string;
|
||||||
|
usedPct: number;
|
||||||
|
usedMb: number;
|
||||||
|
totalMb: number;
|
||||||
|
}>;
|
||||||
|
|
||||||
const latestProbes = this.db
|
const latestProbes = this.db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode,
|
`SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode,
|
||||||
|
|
@ -262,6 +398,8 @@ export class MonitoringService {
|
||||||
ts: number;
|
ts: number;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
|
const probeHistory = this.queryProbeHistory(serverId, since, 200);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
range,
|
range,
|
||||||
granularity,
|
granularity,
|
||||||
|
|
@ -275,50 +413,88 @@ export class MonitoringService {
|
||||||
error: r.error ?? undefined,
|
error: r.error ?? undefined,
|
||||||
ts: r.ts,
|
ts: r.ts,
|
||||||
})),
|
})),
|
||||||
|
probeHistory,
|
||||||
|
diskHistory,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private scheduleServer(server: ServerConfig): void {
|
private async withPollSlot<T>(fn: () => Promise<T>): Promise<T> {
|
||||||
|
const limit = Math.max(1, this.getRuntimeLimits?.().maxConcurrentMetricPolls ?? 4);
|
||||||
|
if (this.inFlightPolls >= limit) {
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
this.pollQueue.push(resolve);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.inFlightPolls += 1;
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} finally {
|
||||||
|
this.inFlightPolls = Math.max(0, this.inFlightPolls - 1);
|
||||||
|
const next = this.pollQueue.shift();
|
||||||
|
if (next) next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleServer(server: ServerConfig, index: number): void {
|
||||||
const timers: ServerTimers = {
|
const timers: ServerTimers = {
|
||||||
metricTimer: null,
|
metricTimer: null,
|
||||||
warmupTimer: null,
|
warmupTimer: null,
|
||||||
|
staggerTimer: null,
|
||||||
probeTimers: new Map(),
|
probeTimers: new Map(),
|
||||||
pollingMetrics: false,
|
pollingMetrics: false,
|
||||||
};
|
};
|
||||||
this.serverTimers.set(server.id, timers);
|
this.serverTimers.set(server.id, timers);
|
||||||
|
|
||||||
// Kick initial poll asynchronously without delaying syncServers()
|
const limits = this.getRuntimeLimits?.();
|
||||||
const hadDelta = this.deltaStates.has(server.id);
|
const staggerMs =
|
||||||
void this.executeMetricPoll(server).then((ev) => {
|
limits?.staggerPolls && index > 0 ? Math.min(index * 120, 2_500) : 0;
|
||||||
if (
|
|
||||||
ev &&
|
|
||||||
!hadDelta &&
|
|
||||||
!this.stopped &&
|
|
||||||
this.serverTimers.get(server.id) === timers &&
|
|
||||||
server.pollIntervalSec >= 3
|
|
||||||
) {
|
|
||||||
const wt = setTimeout(() => {
|
|
||||||
timers.warmupTimer = null;
|
|
||||||
void this.executeMetricPoll(server);
|
|
||||||
}, 1000);
|
|
||||||
wt.unref();
|
|
||||||
timers.warmupTimer = wt;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
timers.metricTimer = setInterval(() => {
|
const kickInitialAndStartTimer = () => {
|
||||||
void this.executeMetricPoll(server);
|
if (this.stopped || this.serverTimers.get(server.id) !== timers) return;
|
||||||
}, server.pollIntervalSec * 1000);
|
|
||||||
timers.metricTimer.unref();
|
|
||||||
|
|
||||||
for (const probe of server.probes) {
|
const hadDelta = this.deltaStates.has(server.id);
|
||||||
if (!probe.enabled) continue;
|
void this.executeMetricPoll(server).then((ev) => {
|
||||||
void this.executeProbe(server, probe.id);
|
if (
|
||||||
const pt = setInterval(() => {
|
ev &&
|
||||||
|
!hadDelta &&
|
||||||
|
!this.stopped &&
|
||||||
|
this.serverTimers.get(server.id) === timers &&
|
||||||
|
server.pollIntervalSec >= 3
|
||||||
|
) {
|
||||||
|
const wt = setTimeout(() => {
|
||||||
|
timers.warmupTimer = null;
|
||||||
|
void this.executeMetricPoll(server);
|
||||||
|
}, 1000);
|
||||||
|
wt.unref();
|
||||||
|
timers.warmupTimer = wt;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
timers.metricTimer = setInterval(() => {
|
||||||
|
void this.executeMetricPoll(server);
|
||||||
|
}, server.pollIntervalSec * 1000);
|
||||||
|
timers.metricTimer.unref();
|
||||||
|
|
||||||
|
for (const probe of server.probes) {
|
||||||
|
if (!probe.enabled) continue;
|
||||||
void this.executeProbe(server, probe.id);
|
void this.executeProbe(server, probe.id);
|
||||||
}, probe.intervalSec * 1000);
|
const pt = setInterval(() => {
|
||||||
pt.unref();
|
void this.executeProbe(server, probe.id);
|
||||||
timers.probeTimers.set(probe.id, pt);
|
}, probe.intervalSec * 1000);
|
||||||
|
pt.unref();
|
||||||
|
timers.probeTimers.set(probe.id, pt);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (staggerMs > 0) {
|
||||||
|
const st = setTimeout(() => {
|
||||||
|
timers.staggerTimer = null;
|
||||||
|
kickInitialAndStartTimer();
|
||||||
|
}, staggerMs);
|
||||||
|
st.unref();
|
||||||
|
timers.staggerTimer = st;
|
||||||
|
} else {
|
||||||
|
kickInitialAndStartTimer();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -332,51 +508,55 @@ export class MonitoringService {
|
||||||
if (timerState) timerState.pollingMetrics = true;
|
if (timerState) timerState.pollingMetrics = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const os = await detectServerOs(
|
return await this.withPollSlot(async () => {
|
||||||
this.sshPool,
|
if (this.stopped || !this.vaultService.isRuntimeReady) return null;
|
||||||
server,
|
|
||||||
this.osCache.get(server.id),
|
|
||||||
);
|
|
||||||
this.osCache.set(server.id, os);
|
|
||||||
|
|
||||||
const collected = await collectServerMetrics(
|
const os = await detectServerOs(
|
||||||
this.sshPool,
|
this.sshPool,
|
||||||
server,
|
server,
|
||||||
os,
|
this.osCache.get(server.id),
|
||||||
this.deltaStates.get(server.id),
|
);
|
||||||
);
|
this.osCache.set(server.id, os);
|
||||||
this.deltaStates.set(server.id, collected.nextState);
|
|
||||||
|
|
||||||
this.persistMetricSample(server.id, collected.sample, collected.disks);
|
const collected = await collectServerMetrics(
|
||||||
|
this.sshPool,
|
||||||
|
server,
|
||||||
|
os,
|
||||||
|
this.deltaStates.get(server.id),
|
||||||
|
);
|
||||||
|
this.deltaStates.set(server.id, collected.nextState);
|
||||||
|
|
||||||
const prevLatest = this.latest.get(server.id) ?? {
|
this.persistMetricSample(server.id, collected.sample, collected.disks);
|
||||||
serverId: server.id,
|
|
||||||
disks: [],
|
|
||||||
probes: {},
|
|
||||||
};
|
|
||||||
this.latest.set(server.id, {
|
|
||||||
...prevLatest,
|
|
||||||
os,
|
|
||||||
sample: collected.sample,
|
|
||||||
disks: collected.disks,
|
|
||||||
lastError: undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
const probes = Object.values(this.latest.get(server.id)!.probes);
|
const prevLatest = this.latest.get(server.id) ?? {
|
||||||
const event: MonitoringTickEvent = {
|
serverId: server.id,
|
||||||
serverId: server.id,
|
disks: [],
|
||||||
sample: collected.sample,
|
probes: {},
|
||||||
disks: collected.disks,
|
};
|
||||||
probes,
|
this.latest.set(server.id, {
|
||||||
};
|
...prevLatest,
|
||||||
for (const listener of this.tickListeners) {
|
os,
|
||||||
try {
|
sample: collected.sample,
|
||||||
listener(event);
|
disks: collected.disks,
|
||||||
} catch {
|
lastError: undefined,
|
||||||
// Isolate listener errors
|
});
|
||||||
|
|
||||||
|
const probes = Object.values(this.latest.get(server.id)!.probes);
|
||||||
|
const event: MonitoringTickEvent = {
|
||||||
|
serverId: server.id,
|
||||||
|
sample: collected.sample,
|
||||||
|
disks: collected.disks,
|
||||||
|
probes,
|
||||||
|
};
|
||||||
|
for (const listener of this.tickListeners) {
|
||||||
|
try {
|
||||||
|
listener(event);
|
||||||
|
} catch {
|
||||||
|
// Isolate listener errors
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return event;
|
||||||
return event;
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const prevLatest = this.latest.get(server.id) ?? {
|
const prevLatest = this.latest.get(server.id) ?? {
|
||||||
serverId: server.id,
|
serverId: server.id,
|
||||||
|
|
@ -397,8 +577,16 @@ export class MonitoringService {
|
||||||
if (this.stopped || !this.vaultService.isRuntimeReady) return;
|
if (this.stopped || !this.vaultService.isRuntimeReady) return;
|
||||||
const probe = server.probes.find((p) => p.id === probeId);
|
const probe = server.probes.find((p) => p.id === probeId);
|
||||||
if (!probe || !probe.enabled) return;
|
if (!probe || !probe.enabled) return;
|
||||||
|
await this.runAndPersistProbe(server, probe);
|
||||||
|
}
|
||||||
|
|
||||||
const sample = await this.probeRunner.runProbe(server.id, probe);
|
private async runAndPersistProbe(
|
||||||
|
server: ServerConfig,
|
||||||
|
probe: ServerConfig['probes'][number],
|
||||||
|
): Promise<ProbeSample> {
|
||||||
|
const sample = await this.withPollSlot(() =>
|
||||||
|
this.probeRunner.runProbe(server.id, probe),
|
||||||
|
);
|
||||||
const ts = Date.now();
|
const ts = Date.now();
|
||||||
this.db
|
this.db
|
||||||
.prepare(
|
.prepare(
|
||||||
|
|
@ -430,6 +618,7 @@ export class MonitoringService {
|
||||||
// Isolate probe listener errors
|
// Isolate probe listener errors
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return sample;
|
||||||
}
|
}
|
||||||
|
|
||||||
private hydrateLatestFromDb(): void {
|
private hydrateLatestFromDb(): void {
|
||||||
|
|
|
||||||
|
|
@ -3,36 +3,93 @@ import tls from 'node:tls';
|
||||||
import type { Duplex } from 'node:stream';
|
import type { Duplex } from 'node:stream';
|
||||||
import type { ServerProbe } from '../../shared/schemas/server.schema.js';
|
import type { ServerProbe } from '../../shared/schemas/server.schema.js';
|
||||||
import type { ProbeSample } from '../../shared/ws-protocol.js';
|
import type { ProbeSample } from '../../shared/ws-protocol.js';
|
||||||
|
import type { ConfigManager } from '../config/config-manager.js';
|
||||||
|
import {
|
||||||
|
fetchWithEgressGuard,
|
||||||
|
resolveAllowedEgressIps,
|
||||||
|
} from '../security/egress-guard.js';
|
||||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||||
|
|
||||||
|
const MAX_PROBE_BODY_BYTES = 128 * 1024;
|
||||||
|
|
||||||
|
function decodeChunkedIfNeeded(head: string, body: string): string {
|
||||||
|
if (!/^transfer-encoding:\s*chunked\b/im.test(head)) return body;
|
||||||
|
let idx = 0;
|
||||||
|
let out = '';
|
||||||
|
while (idx < body.length) {
|
||||||
|
const lineEnd = body.indexOf('\r\n', idx);
|
||||||
|
if (lineEnd < 0) break;
|
||||||
|
const sizeHex = body.slice(idx, lineEnd).split(';')[0]!.trim();
|
||||||
|
const size = Number.parseInt(sizeHex, 16);
|
||||||
|
if (!Number.isFinite(size) || size <= 0) break;
|
||||||
|
idx = lineEnd + 2;
|
||||||
|
out += body.slice(idx, idx + size);
|
||||||
|
idx += size + 2;
|
||||||
|
}
|
||||||
|
return out || body;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readResponseTextCapped(
|
||||||
|
res: Response,
|
||||||
|
maxBytes = MAX_PROBE_BODY_BYTES,
|
||||||
|
): Promise<string> {
|
||||||
|
if (!res.body) return '';
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let total = 0;
|
||||||
|
try {
|
||||||
|
while (total < maxBytes) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done || !value) break;
|
||||||
|
const take = Math.min(value.byteLength, maxBytes - total);
|
||||||
|
chunks.push(Buffer.from(value.subarray(0, take)));
|
||||||
|
total += take;
|
||||||
|
if (total >= maxBytes) {
|
||||||
|
await reader.cancel().catch(() => undefined);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
return Buffer.concat(chunks).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
function readHttpFromStream(
|
function readHttpFromStream(
|
||||||
stream: Duplex,
|
stream: Duplex,
|
||||||
url: URL,
|
url: URL,
|
||||||
timeoutMs: number,
|
timeoutMs: number,
|
||||||
): Promise<{ statusCode: number; body: string }> {
|
tlsOpts: { rejectUnauthorized?: boolean } = {},
|
||||||
|
): Promise<{ statusCode: number; body: string; certExpiryDays?: number }> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let settled = false;
|
let settled = false;
|
||||||
|
let certExpiryDays: number | undefined;
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
settled = true;
|
settled = true;
|
||||||
stream.destroy();
|
stream.destroy();
|
||||||
reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`));
|
reject(new Error(`HTTP probe timed out after ${timeoutMs}ms`));
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
|
const servername = net.isIP(url.hostname) ? undefined : url.hostname;
|
||||||
const transport: Duplex =
|
const transport: Duplex =
|
||||||
url.protocol === 'https:'
|
url.protocol === 'https:'
|
||||||
? tls.connect({ socket: stream, servername: url.hostname })
|
? tls.connect({
|
||||||
|
socket: stream,
|
||||||
|
servername,
|
||||||
|
rejectUnauthorized: tlsOpts.rejectUnauthorized ?? true,
|
||||||
|
})
|
||||||
: stream;
|
: stream;
|
||||||
|
|
||||||
const chunks: Buffer[] = [];
|
const chunks: Buffer[] = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
const maxBytes = 256 * 1024;
|
|
||||||
|
|
||||||
const done = (err?: Error) => {
|
const done = (err?: Error) => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
transport.destroy();
|
transport.destroy();
|
||||||
|
stream.destroy();
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
return;
|
return;
|
||||||
|
|
@ -40,36 +97,53 @@ function readHttpFromStream(
|
||||||
const raw = Buffer.concat(chunks).toString('utf8');
|
const raw = Buffer.concat(chunks).toString('utf8');
|
||||||
const headerEnd = raw.indexOf('\r\n\r\n');
|
const headerEnd = raw.indexOf('\r\n\r\n');
|
||||||
const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw;
|
const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw;
|
||||||
const body = headerEnd >= 0 ? raw.slice(headerEnd + 4) : '';
|
const rawBody = headerEnd >= 0 ? raw.slice(headerEnd + 4) : '';
|
||||||
const statusLine = head.split('\r\n')[0] ?? '';
|
const statusLine = head.split('\r\n')[0] ?? '';
|
||||||
const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine);
|
const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine);
|
||||||
if (!m) {
|
if (!m) {
|
||||||
reject(new Error(`Invalid HTTP response line: ${statusLine}`));
|
reject(new Error(`Invalid HTTP response line: ${statusLine}`));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
resolve({ statusCode: Number(m[1]), body });
|
resolve({
|
||||||
|
statusCode: Number(m[1]),
|
||||||
|
body: decodeChunkedIfNeeded(head, rawBody),
|
||||||
|
certExpiryDays,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
transport.on('data', (chunk: Buffer) => {
|
transport.on('data', (chunk: Buffer) => {
|
||||||
if (total < maxBytes) {
|
if (total < MAX_PROBE_BODY_BYTES) {
|
||||||
chunks.push(chunk.subarray(0, maxBytes - total));
|
chunks.push(chunk.subarray(0, MAX_PROBE_BODY_BYTES - total));
|
||||||
total += chunk.length;
|
total += chunk.length;
|
||||||
|
} else {
|
||||||
|
transport.destroy();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
transport.once('end', () => done());
|
transport.once('end', () => done());
|
||||||
transport.once('close', () => done());
|
transport.once('close', () => done());
|
||||||
transport.once('error', (err) => done(err));
|
transport.once('error', (err) => done(err));
|
||||||
|
if (transport !== stream) {
|
||||||
|
stream.once('error', (err) => done(err));
|
||||||
|
}
|
||||||
|
|
||||||
const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`;
|
const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`;
|
||||||
const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
|
const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
|
||||||
const reqText =
|
const reqText =
|
||||||
`GET ${pathAndQuery} HTTP/1.1\r\n` +
|
`GET ${pathAndQuery} HTTP/1.1\r\n` +
|
||||||
`Host: ${hostHeader}\r\n` +
|
`Host: ${hostHeader}\r\n` +
|
||||||
`User-Agent: GCoordinator-Probe/1.0\r\n` +
|
`User-Agent: GCoordinator-Probe/1.1\r\n` +
|
||||||
|
`Accept-Encoding: identity\r\n` +
|
||||||
`Connection: close\r\n\r\n`;
|
`Connection: close\r\n\r\n`;
|
||||||
|
|
||||||
if (url.protocol === 'https:') {
|
if (url.protocol === 'https:') {
|
||||||
(transport as tls.TLSSocket).once('secureConnect', () => {
|
(transport as tls.TLSSocket).once('secureConnect', () => {
|
||||||
|
const cert = (transport as tls.TLSSocket).getPeerCertificate(false);
|
||||||
|
if (cert && typeof cert.valid_to === 'string') {
|
||||||
|
const expMs = Date.parse(cert.valid_to);
|
||||||
|
if (Number.isFinite(expMs)) {
|
||||||
|
certExpiryDays = Math.floor((expMs - Date.now()) / 86_400_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
transport.write(reqText);
|
transport.write(reqText);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -79,16 +153,26 @@ function readHttpFromStream(
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ProbeRunner {
|
export class ProbeRunner {
|
||||||
constructor(private readonly sshPool: SSHPool) {}
|
constructor(
|
||||||
|
private readonly sshPool: SSHPool,
|
||||||
|
private readonly configManager?: ConfigManager,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
runSingleProbe(serverId: string, probe: ServerProbe): Promise<ProbeSample> {
|
||||||
|
return this.runProbe(serverId, probe);
|
||||||
|
}
|
||||||
|
|
||||||
async runProbe(serverId: string, probe: ServerProbe): Promise<ProbeSample> {
|
async runProbe(serverId: string, probe: ServerProbe): Promise<ProbeSample> {
|
||||||
const started = Date.now();
|
const started = Date.now();
|
||||||
|
const allowedCidrs = this.configManager?.getSettings().security.egressAllowedCidrs ?? [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (probe.type === 'tcp') {
|
if (probe.type === 'tcp') {
|
||||||
if (probe.from === 'hub') {
|
if (probe.from === 'hub') {
|
||||||
|
const ips = await resolveAllowedEgressIps(probe.host, allowedCidrs);
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
const sock = net.createConnection({
|
const sock = net.createConnection({
|
||||||
host: probe.host,
|
host: ips[0]!,
|
||||||
port: probe.port,
|
port: probe.port,
|
||||||
});
|
});
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
|
|
@ -125,19 +209,35 @@ export class ProbeRunner {
|
||||||
}
|
}
|
||||||
|
|
||||||
// HTTP(S) probe
|
// HTTP(S) probe
|
||||||
|
const parsedUrl = new URL(probe.url);
|
||||||
let statusCode: number;
|
let statusCode: number;
|
||||||
let body: string;
|
let body: string;
|
||||||
|
let certExpiryDays: number | undefined;
|
||||||
|
|
||||||
if (probe.from === 'hub') {
|
if (probe.from === 'hub') {
|
||||||
const res = await fetch(probe.url, {
|
if (
|
||||||
method: 'GET',
|
parsedUrl.protocol === 'https:' &&
|
||||||
redirect: 'manual',
|
(probe.tlsRejectUnauthorized === false || probe.tlsCheckExpiryDays !== undefined)
|
||||||
signal: AbortSignal.timeout(probe.timeoutMs),
|
) {
|
||||||
});
|
const ips = await resolveAllowedEgressIps(parsedUrl.hostname, allowedCidrs);
|
||||||
statusCode = res.status;
|
const port = parsedUrl.port ? Number(parsedUrl.port) : 443;
|
||||||
body = await res.text();
|
const sock = net.createConnection({ host: ips[0]!, port });
|
||||||
|
const resp = await readHttpFromStream(sock, parsedUrl, probe.timeoutMs, {
|
||||||
|
rejectUnauthorized: probe.tlsRejectUnauthorized,
|
||||||
|
});
|
||||||
|
statusCode = resp.statusCode;
|
||||||
|
body = resp.body;
|
||||||
|
certExpiryDays = resp.certExpiryDays;
|
||||||
|
} else {
|
||||||
|
const res = await fetchWithEgressGuard(
|
||||||
|
probe.url,
|
||||||
|
{ method: 'GET', redirect: 'manual' },
|
||||||
|
{ allowedCidrs, timeoutMs: probe.timeoutMs },
|
||||||
|
);
|
||||||
|
statusCode = res.status;
|
||||||
|
body = await readResponseTextCapped(res, MAX_PROBE_BODY_BYTES);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const parsedUrl = new URL(probe.url);
|
|
||||||
const port = parsedUrl.port
|
const port = parsedUrl.port
|
||||||
? Number(parsedUrl.port)
|
? Number(parsedUrl.port)
|
||||||
: parsedUrl.protocol === 'https:'
|
: parsedUrl.protocol === 'https:'
|
||||||
|
|
@ -149,24 +249,40 @@ export class ProbeRunner {
|
||||||
port,
|
port,
|
||||||
probe.timeoutMs,
|
probe.timeoutMs,
|
||||||
);
|
);
|
||||||
const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs);
|
const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs, {
|
||||||
|
rejectUnauthorized: probe.tlsRejectUnauthorized,
|
||||||
|
});
|
||||||
statusCode = resp.statusCode;
|
statusCode = resp.statusCode;
|
||||||
body = resp.body;
|
body = resp.body;
|
||||||
|
certExpiryDays = resp.certExpiryDays;
|
||||||
}
|
}
|
||||||
|
|
||||||
const statusOk = statusCode === probe.expectedStatus;
|
const statusOk = statusCode === probe.expectedStatus;
|
||||||
const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true;
|
const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true;
|
||||||
const ok = statusOk && bodyOk;
|
const certOk =
|
||||||
|
probe.tlsCheckExpiryDays !== undefined && certExpiryDays !== undefined
|
||||||
|
? certExpiryDays >= probe.tlsCheckExpiryDays
|
||||||
|
: true;
|
||||||
|
const ok = statusOk && bodyOk && certOk;
|
||||||
|
|
||||||
|
let error: string | undefined;
|
||||||
|
if (!ok) {
|
||||||
|
if (!statusOk) {
|
||||||
|
error = `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`;
|
||||||
|
} else if (!bodyOk) {
|
||||||
|
error = `Response body missing substring "${probe.bodyIncludes}"`;
|
||||||
|
} else {
|
||||||
|
error = `TLS certificate expires in ${certExpiryDays}d (threshold ${probe.tlsCheckExpiryDays}d)`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
probeId: probe.id,
|
probeId: probe.id,
|
||||||
ok,
|
ok,
|
||||||
statusCode,
|
statusCode,
|
||||||
latencyMs: Date.now() - started,
|
latencyMs: Date.now() - started,
|
||||||
error: ok
|
certExpiryDays,
|
||||||
? undefined
|
error,
|
||||||
: !statusOk
|
|
||||||
? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`
|
|
||||||
: `Response body missing substring "${probe.bodyIncludes}"`,
|
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
180
src/server/monitoring/prometheus.ts
Normal file
180
src/server/monitoring/prometheus.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import type { Request, Response } from 'express';
|
||||||
|
import type { AlertEngine } from '../alerts/alert-engine.js';
|
||||||
|
import type { ConfigManager } from '../config/config-manager.js';
|
||||||
|
import { sha256Hex } from '../security/auth.js';
|
||||||
|
import type { VaultService } from '../security/vault.js';
|
||||||
|
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||||
|
import type { TunnelManager } from '../ssh/tunnel-manager.js';
|
||||||
|
import type { MonitoringService } from './monitoring-service.js';
|
||||||
|
|
||||||
|
export interface PrometheusHandlerDeps {
|
||||||
|
configManager: ConfigManager;
|
||||||
|
vaultService: VaultService;
|
||||||
|
sshPool: SSHPool;
|
||||||
|
monitoringService: MonitoringService;
|
||||||
|
tunnelManager: TunnelManager;
|
||||||
|
alertEngine: AlertEngine;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapePromLabel(val: string): string {
|
||||||
|
return val.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function labels(pairs: Record<string, string>): string {
|
||||||
|
const parts = Object.entries(pairs).map(
|
||||||
|
([k, v]) => `${k}="${escapePromLabel(v)}"`,
|
||||||
|
);
|
||||||
|
return parts.length > 0 ? `{${parts.join(',')}}` : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function constantTimeTokenMatch(provided: string, expectedSha256Hex: string): boolean {
|
||||||
|
if (!/^[a-f0-9]{64}$/i.test(expectedSha256Hex)) return false;
|
||||||
|
const providedDigest = Buffer.from(sha256Hex(provided), 'hex');
|
||||||
|
const expectedDigest = Buffer.from(expectedSha256Hex.toLowerCase(), 'hex');
|
||||||
|
if (providedDigest.length !== expectedDigest.length) return false;
|
||||||
|
return crypto.timingSafeEqual(providedDigest, expectedDigest);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPrometheusHandler(deps: PrometheusHandlerDeps) {
|
||||||
|
const {
|
||||||
|
configManager,
|
||||||
|
vaultService,
|
||||||
|
sshPool,
|
||||||
|
monitoringService,
|
||||||
|
tunnelManager,
|
||||||
|
alertEngine,
|
||||||
|
} = deps;
|
||||||
|
|
||||||
|
return (req: Request, res: Response): void => {
|
||||||
|
const settings = configManager.getSettings();
|
||||||
|
if (!settings.metrics.prometheusEnabled) {
|
||||||
|
res.status(404).json({ error: 'METRICS_DISABLED' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const authHeader = typeof req.headers.authorization === 'string' ? req.headers.authorization : '';
|
||||||
|
const bearerMatch = /^Bearer\s+(.+)$/i.exec(authHeader.trim());
|
||||||
|
const providedToken = bearerMatch?.[1]?.trim() ?? '';
|
||||||
|
|
||||||
|
let authorized = false;
|
||||||
|
if (providedToken) {
|
||||||
|
if (settings.metrics.prometheusSecretRef && vaultService.isRuntimeReady) {
|
||||||
|
const cred = vaultService.getRuntimeSecret(settings.metrics.prometheusSecretRef);
|
||||||
|
const rawSecret =
|
||||||
|
cred?.type === 'api-token'
|
||||||
|
? cred.token
|
||||||
|
: cred?.type === 'webhook-secret'
|
||||||
|
? cred.secret
|
||||||
|
: undefined;
|
||||||
|
if (rawSecret) {
|
||||||
|
authorized = constantTimeTokenMatch(providedToken, sha256Hex(rawSecret));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!authorized && settings.metrics.prometheusTokenHash) {
|
||||||
|
authorized = constantTimeTokenMatch(providedToken, settings.metrics.prometheusTokenHash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!authorized) {
|
||||||
|
res.setHeader('WWW-Authenticate', 'Bearer realm="GCoordinator"');
|
||||||
|
res.status(401).json({ error: 'METRICS_UNAUTHORIZED' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines: string[] = [];
|
||||||
|
const metric = (name: string, help: string, type: 'gauge' | 'counter', rows: string[]) => {
|
||||||
|
lines.push(`# HELP ${name} ${help}`);
|
||||||
|
lines.push(`# TYPE ${name} ${type}`);
|
||||||
|
lines.push(...rows);
|
||||||
|
};
|
||||||
|
|
||||||
|
const states = new Map(sshPool.getStates().map((s) => [s.serverId, s]));
|
||||||
|
const servers = configManager.listServers();
|
||||||
|
|
||||||
|
const upRows: string[] = [];
|
||||||
|
const cpuRows: string[] = [];
|
||||||
|
const memUsedRows: string[] = [];
|
||||||
|
const memTotalRows: string[] = [];
|
||||||
|
const load1Rows: string[] = [];
|
||||||
|
const uptimeRows: string[] = [];
|
||||||
|
const netRxRows: string[] = [];
|
||||||
|
const netTxRows: string[] = [];
|
||||||
|
const diskRows: string[] = [];
|
||||||
|
const probeUpRows: string[] = [];
|
||||||
|
const probeLatencyRows: string[] = [];
|
||||||
|
const probeTlsExpiryRows: string[] = [];
|
||||||
|
|
||||||
|
for (const srv of servers) {
|
||||||
|
const state = states.get(srv.id);
|
||||||
|
const isUp = state?.status === 'connected' ? 1 : 0;
|
||||||
|
const baseLabels = labels({ server_id: srv.id, name: srv.name });
|
||||||
|
upRows.push(`gcoordinator_server_up${baseLabels} ${isUp}`);
|
||||||
|
|
||||||
|
const latest = monitoringService.getLatest(srv.id);
|
||||||
|
if (latest?.sample) {
|
||||||
|
const s = latest.sample;
|
||||||
|
cpuRows.push(`gcoordinator_server_cpu_percent${baseLabels} ${s.cpuPct}`);
|
||||||
|
memUsedRows.push(
|
||||||
|
`gcoordinator_server_memory_used_bytes${baseLabels} ${Math.round(s.memUsedMb * 1024 * 1024)}`,
|
||||||
|
);
|
||||||
|
memTotalRows.push(
|
||||||
|
`gcoordinator_server_memory_total_bytes${baseLabels} ${Math.round(s.memTotalMb * 1024 * 1024)}`,
|
||||||
|
);
|
||||||
|
load1Rows.push(`gcoordinator_server_load1${baseLabels} ${s.load1m}`);
|
||||||
|
uptimeRows.push(`gcoordinator_server_uptime_seconds${baseLabels} ${s.uptimeSec}`);
|
||||||
|
netRxRows.push(`gcoordinator_server_net_rx_bytes_per_sec${baseLabels} ${s.netRxBps}`);
|
||||||
|
netTxRows.push(`gcoordinator_server_net_tx_bytes_per_sec${baseLabels} ${s.netTxBps}`);
|
||||||
|
}
|
||||||
|
if (latest?.disks) {
|
||||||
|
for (const d of latest.disks) {
|
||||||
|
const dl = labels({ server_id: srv.id, mount: d.mountPoint });
|
||||||
|
diskRows.push(`gcoordinator_server_disk_used_percent${dl} ${d.usedPct}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (latest?.probes) {
|
||||||
|
for (const p of Object.values(latest.probes)) {
|
||||||
|
const pl = labels({ server_id: srv.id, probe_id: p.probeId });
|
||||||
|
probeUpRows.push(`gcoordinator_probe_up${pl} ${p.ok ? 1 : 0}`);
|
||||||
|
probeLatencyRows.push(`gcoordinator_probe_latency_ms${pl} ${p.latencyMs}`);
|
||||||
|
if (typeof p.certExpiryDays === 'number') {
|
||||||
|
probeTlsExpiryRows.push(`gcoordinator_probe_tls_expiry_days${pl} ${p.certExpiryDays}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
metric('gcoordinator_server_up', 'Server SSH reachability (1=connected, 0=disconnected)', 'gauge', upRows);
|
||||||
|
metric('gcoordinator_server_cpu_percent', 'Latest sampled CPU utilization percentage', 'gauge', cpuRows);
|
||||||
|
metric('gcoordinator_server_memory_used_bytes', 'Latest sampled memory used in bytes', 'gauge', memUsedRows);
|
||||||
|
metric('gcoordinator_server_memory_total_bytes', 'Total RAM in bytes', 'gauge', memTotalRows);
|
||||||
|
metric('gcoordinator_server_load1', 'Latest 1-minute load average', 'gauge', load1Rows);
|
||||||
|
metric('gcoordinator_server_uptime_seconds', 'Server uptime in seconds', 'gauge', uptimeRows);
|
||||||
|
metric('gcoordinator_server_net_rx_bytes_per_sec', 'Network receive throughput B/s', 'gauge', netRxRows);
|
||||||
|
metric('gcoordinator_server_net_tx_bytes_per_sec', 'Network transmit throughput B/s', 'gauge', netTxRows);
|
||||||
|
metric('gcoordinator_server_disk_used_percent', 'Disk filesystem usage percentage', 'gauge', diskRows);
|
||||||
|
metric('gcoordinator_probe_up', 'Latest health probe result (1=ok, 0=fail)', 'gauge', probeUpRows);
|
||||||
|
metric('gcoordinator_probe_latency_ms', 'Latest health probe latency in ms', 'gauge', probeLatencyRows);
|
||||||
|
if (probeTlsExpiryRows.length > 0) {
|
||||||
|
metric('gcoordinator_probe_tls_expiry_days', 'Days remaining until TLS certificate expiry', 'gauge', probeTlsExpiryRows);
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeTunnels = tunnelManager.listTunnels().filter((t) => t.active).length;
|
||||||
|
metric('gcoordinator_tunnels_active', 'Number of currently active SSH tunnels', 'gauge', [
|
||||||
|
`gcoordinator_tunnels_active ${activeTunnels}`,
|
||||||
|
]);
|
||||||
|
metric('gcoordinator_alerts_active', 'Number of active unresolved alert incidents', 'gauge', [
|
||||||
|
`gcoordinator_alerts_active ${alertEngine.getActiveCount()}`,
|
||||||
|
]);
|
||||||
|
metric('gcoordinator_process_resident_memory_bytes', 'Hub Node.js resident set size bytes', 'gauge', [
|
||||||
|
`gcoordinator_process_resident_memory_bytes ${process.memoryUsage().rss}`,
|
||||||
|
]);
|
||||||
|
metric('gcoordinator_process_uptime_seconds', 'Hub Node.js process uptime in seconds', 'gauge', [
|
||||||
|
`gcoordinator_process_uptime_seconds ${Math.round(process.uptime())}`,
|
||||||
|
]);
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
|
||||||
|
res.setHeader('Cache-Control', 'no-store');
|
||||||
|
res.send(`${lines.join('\n')}\n`);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -86,6 +86,7 @@ export const SettingsSchema = z.object({
|
||||||
.object({
|
.object({
|
||||||
prometheusEnabled: z.boolean().default(false),
|
prometheusEnabled: z.boolean().default(false),
|
||||||
prometheusSecretRef: EntityIdSchema.optional(),
|
prometheusSecretRef: EntityIdSchema.optional(),
|
||||||
|
prometheusTokenHash: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
||||||
})
|
})
|
||||||
.default({ prometheusEnabled: false }),
|
.default({ prometheusEnabled: false }),
|
||||||
security: SecuritySettingsSchema.default({}),
|
security: SecuritySettingsSchema.default({}),
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,7 @@ export interface ProbeSample {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
statusCode?: number;
|
statusCode?: number;
|
||||||
latencyMs: number;
|
latencyMs: number;
|
||||||
|
certExpiryDays?: number;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -170,7 +170,7 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', ()
|
||||||
await cfg.init({ watch: false });
|
await cfg.init({ watch: false });
|
||||||
const knownHosts = new KnownHostsService(db, audit);
|
const knownHosts = new KnownHostsService(db, audit);
|
||||||
const sshPool = new SSHPool(cfg, vault, knownHosts);
|
const sshPool = new SSHPool(cfg, vault, knownHosts);
|
||||||
const probeRunner = new ProbeRunner(sshPool);
|
const probeRunner = new ProbeRunner(sshPool, cfg);
|
||||||
const inspector = new ServerInspector(sshPool, cfg);
|
const inspector = new ServerInspector(sshPool, cfg);
|
||||||
const monitoring = new MonitoringService(db, cfg, vault, sshPool, probeRunner);
|
const monitoring = new MonitoringService(db, cfg, vault, sshPool, probeRunner);
|
||||||
|
|
||||||
|
|
@ -222,6 +222,15 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', ()
|
||||||
);
|
);
|
||||||
|
|
||||||
const serverCfg = cfg.getServer('linux-01')!;
|
const serverCfg = cfg.getServer('linux-01')!;
|
||||||
|
// Hub loopback HTTP probe is blocked by default Zero-Trust egress policy until explicitly allowlisted
|
||||||
|
const hubProbe = serverCfg.probes.find((p) => p.id === 'hub-http')!;
|
||||||
|
const deniedSample = await probeRunner.runProbe('linux-01', hubProbe);
|
||||||
|
expect(deniedSample.ok).toBe(false);
|
||||||
|
|
||||||
|
const nextSettings = cfg.getSettings();
|
||||||
|
nextSettings.security.egressAllowedCidrs = ['127.0.0.1/32'];
|
||||||
|
cfg.saveConfigText('settings.json', JSON.stringify(nextSettings, null, 2));
|
||||||
|
|
||||||
for (const p of serverCfg.probes) {
|
for (const p of serverCfg.probes) {
|
||||||
const sample = await probeRunner.runProbe('linux-01', p);
|
const sample = await probeRunner.runProbe('linux-01', p);
|
||||||
expect(sample.ok).toBe(true);
|
expect(sample.ok).toBe(true);
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue