diff --git a/src/server/monitoring/collectors.ts b/src/server/monitoring/collectors.ts new file mode 100644 index 0000000..b1a7220 --- /dev/null +++ b/src/server/monitoring/collectors.ts @@ -0,0 +1,506 @@ +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { DiskSample, MetricSample } from '../../shared/ws-protocol.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; + +export type OsType = 'linux' | 'bsd' | 'macos'; + +export interface CollectorDeltaState { + ts: number; + cpuTotal?: number; + cpuIdle?: number; + netRxBytes?: number; + netTxBytes?: number; +} + +export interface CollectOutput { + sample: MetricSample; + disks: DiskSample[]; + nextState: CollectorDeltaState; +} + +const VIRTUAL_FS_TYPES = new Set([ + 'tmpfs', + 'devtmpfs', + 'squashfs', + 'overlay', + 'proc', + 'sysfs', + 'cgroup', + 'cgroup2', + 'devpts', + 'efivarfs', + 'nsfs', + 'autofs', + 'mqueue', + 'hugetlbfs', + 'tracefs', + 'debugfs', + 'fusectl', + 'pstore', + 'bpf', + 'securityfs', + 'ramfs', + 'udev', + 'devfs', + 'fdescfs', + 'procfs', +]); + +export const LINUX_METRIC_CMD = [ + 'printf "===STAT===\\n"; head -n 1 /proc/stat', + 'printf "===MEM===\\n"; grep -E "^(MemTotal|MemAvailable|MemFree|Buffers|Cached):" /proc/meminfo', + 'printf "===LOAD===\\n"; cat /proc/loadavg', + 'printf "===UPTIME===\\n"; cat /proc/uptime', + 'printf "===NET===\\n"; cat /proc/net/dev', + 'printf "===DF===\\n"; df -PT -k 2>/dev/null || df -P -k', +].join('; '); + +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 "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat', + 'printf "===NET===\\n"; netstat -ibn 2>/dev/null', + 'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP', +].join('; '); + +export const MACOS_METRIC_CMD = [ + 'printf "===SYSCTL===\\n"; sysctl -n hw.memsize hw.pagesize vm.loadavg kern.boottime', + 'printf "===VMSTAT===\\n"; vm_stat', + '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 "===DF===\\n"; df -kP', +].join('; '); + +function splitSections(stdout: string): Record { + const sections: Record = {}; + let current = ''; + for (const line of stdout.split(/\r?\n/)) { + const m = /^===([A-Z0-9_]+)===$/.exec(line.trim()); + if (m) { + current = m[1]!; + sections[current] = ''; + } else if (current) { + sections[current] = sections[current] + ? `${sections[current]}\n${line}` + : line; + } + } + return sections; +} + +function clamp(v: number, min: number, max: number): number { + return Math.max(min, Math.min(max, v)); +} + +function round2(n: number): number { + return Math.round(n * 100) / 100; +} + +function parseDfLines( + dfText: string, + hasTypeColumn: boolean, + mountFilter?: string[], +): DiskSample[] { + const disks: DiskSample[] = []; + const seenMounts = new Set(); + const lines = dfText.split(/\r?\n/).filter((l) => l.trim().length > 0); + if (lines.length < 2) return disks; + + // Detect whether output actually includes Type column (7 cols) or POSIX df (6 cols) + const headerCols = lines[0]!.trim().split(/\s+/); + const detectedTypeCol = + hasTypeColumn && headerCols.some((c) => c.toLowerCase() === 'type'); + + for (let i = 1; i < lines.length; i++) { + const cols = lines[i]!.trim().split(/\s+/); + if (detectedTypeCol && cols.length >= 7) { + const fsType = cols[1]!; + const totalKb = Number(cols[2]); + const usedKb = Number(cols[3]); + const mountPoint = cols.slice(6).join(' '); + if (VIRTUAL_FS_TYPES.has(fsType) || !Number.isFinite(totalKb) || totalKb <= 0) { + continue; + } + if (mountFilter && mountFilter.length > 0 && !mountFilter.includes(mountPoint)) { + continue; + } + if (seenMounts.has(mountPoint)) continue; + seenMounts.add(mountPoint); + const totalMb = round2(totalKb / 1024); + const usedMb = round2(usedKb / 1024); + const usedPct = round2(clamp((usedKb / totalKb) * 100, 0, 100)); + disks.push({ mountPoint, fsType, usedMb, totalMb, usedPct }); + } else if (!detectedTypeCol && cols.length >= 6) { + const fsName = cols[0]!; + const totalKb = Number(cols[1]); + const usedKb = Number(cols[2]); + const mountPoint = cols.slice(5).join(' '); + if ( + fsName === 'devfs' || + fsName === 'map' || + !Number.isFinite(totalKb) || + totalKb <= 0 + ) { + continue; + } + if (mountFilter && mountFilter.length > 0 && !mountFilter.includes(mountPoint)) { + continue; + } + if (seenMounts.has(mountPoint)) continue; + seenMounts.add(mountPoint); + const totalMb = round2(totalKb / 1024); + const usedMb = round2(usedKb / 1024); + const usedPct = round2(clamp((usedKb / totalKb) * 100, 0, 100)); + disks.push({ mountPoint, fsType: 'disk', usedMb, totalMb, usedPct }); + } + } + return disks; +} + +export function parseLinuxOutput( + stdout: string, + prevState?: CollectorDeltaState, + mountFilter?: string[], + nowMs = Date.now(), +): CollectOutput { + const sec = splitSections(stdout); + + // CPU from /proc/stat + let cpuTotal = 0; + let cpuIdle = 0; + const statLine = (sec.STAT ?? '').trim().split(/\s+/); + if (statLine[0] === 'cpu' && statLine.length >= 5) { + const nums = statLine.slice(1).map((n) => Number(n) || 0); + cpuTotal = nums.reduce((a, b) => a + b, 0); + cpuIdle = (nums[3] ?? 0) + (nums[4] ?? 0); // idle + iowait + } + + let cpuPct = 0; + if (prevState?.cpuTotal !== undefined && prevState.cpuIdle !== undefined) { + const totalDelta = cpuTotal - prevState.cpuTotal; + const idleDelta = cpuIdle - prevState.cpuIdle; + if (totalDelta > 0) { + cpuPct = round2(clamp(((totalDelta - idleDelta) / totalDelta) * 100, 0, 100)); + } + } + + // Memory from /proc/meminfo (values in kB) + const memMap = new Map(); + for (const line of (sec.MEM ?? '').split(/\r?\n/)) { + const m = /^(\w+):\s+(\d+)/.exec(line.trim()); + if (m) memMap.set(m[1]!, Number(m[2]!)); + } + const memTotalKb = memMap.get('MemTotal') ?? 0; + const memAvailKb = + memMap.get('MemAvailable') ?? + (memMap.get('MemFree') ?? 0) + + (memMap.get('Buffers') ?? 0) + + (memMap.get('Cached') ?? 0); + const memTotalMb = round2(memTotalKb / 1024); + const memUsedMb = round2(Math.max(0, memTotalKb - memAvailKb) / 1024); + + // Load average & uptime + const load1m = round2(Number((sec.LOAD ?? '0').trim().split(/\s+/)[0]) || 0); + const uptimeSec = Math.max( + 0, + Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0), + ); + + // Network RX/TX across non-loopback interfaces + let netRxBytes = 0; + let netTxBytes = 0; + for (const line of (sec.NET ?? '').split(/\r?\n/)) { + const colon = line.indexOf(':'); + if (colon <= 0) continue; + const iface = line.slice(0, colon).trim(); + if (iface === 'lo' || iface.startsWith('lo:')) continue; + const cols = line.slice(colon + 1).trim().split(/\s+/); + if (cols.length >= 9) { + netRxBytes += Number(cols[0]) || 0; + netTxBytes += Number(cols[8]) || 0; + } + } + + let netRxBps = 0; + let netTxBps = 0; + if ( + prevState?.netRxBytes !== undefined && + prevState.netTxBytes !== undefined && + nowMs > prevState.ts + ) { + const dtSec = (nowMs - prevState.ts) / 1000; + if (netRxBytes >= prevState.netRxBytes) { + netRxBps = Math.round((netRxBytes - prevState.netRxBytes) / dtSec); + } + if (netTxBytes >= prevState.netTxBytes) { + netTxBps = Math.round((netTxBytes - prevState.netTxBytes) / dtSec); + } + } + + const disks = parseDfLines(sec.DF ?? '', true, mountFilter); + + return { + sample: { + ts: nowMs, + cpuPct, + memUsedMb, + memTotalMb, + netRxBps, + netTxBps, + load1m, + uptimeSec, + }, + disks, + nextState: { + ts: nowMs, + cpuTotal, + cpuIdle, + netRxBytes, + netTxBytes, + }, + }; +} + +export function parseBsdOutput( + stdout: string, + prevState?: CollectorDeltaState, + mountFilter?: string[], + nowMs = Date.now(), +): CollectOutput { + const sec = splitSections(stdout); + const sysctlLines = (sec.SYSCTL ?? '') + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + + const physMemBytes = Number(sysctlLines[0]) || 0; + const pageSize = Number(sysctlLines[1]) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); + const load1m = round2(Number(loadMatch?.[1] ?? 0)); + + let uptimeSec = 0; + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); + if (bootSecMatch) { + uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); + } + + let cpuTotal = 0; + let cpuIdle = 0; + const cpNums = (sysctlLines[4] ?? '') + .split(/\s+/) + .map((n) => Number(n) || 0); + if (cpNums.length >= 5) { + cpuTotal = cpNums.reduce((a, b) => a + b, 0); + cpuIdle = cpNums[4]!; + } + + let cpuPct = 0; + if (prevState?.cpuTotal !== undefined && prevState.cpuIdle !== undefined) { + const td = cpuTotal - prevState.cpuTotal; + const id = cpuIdle - prevState.cpuIdle; + if (td > 0) cpuPct = round2(clamp(((td - id) / td) * 100, 0, 100)); + } + + // Free memory from vmstat last line column 5 (fre) in KB or pages + const vmLines = (sec.VMSTAT ?? '') + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + let memFreeBytes = 0; + if (vmLines.length > 0) { + const lastCols = vmLines[vmLines.length - 1]!.split(/\s+/); + const freeVal = Number(lastCols[4]) || 0; + // FreeBSD vmstat -H reports bytes with suffixes or pages without; heuristic if < physmem/pageSize + memFreeBytes = + freeVal * pageSize <= physMemBytes ? freeVal * pageSize : freeVal * 1024; + } + const memTotalMb = round2(physMemBytes / (1024 * 1024)); + const memUsedMb = round2(Math.max(0, physMemBytes - memFreeBytes) / (1024 * 1024)); + + let netRxBytes = 0; + let netTxBytes = 0; + for (const line of (sec.NET ?? '').split(/\r?\n/)) { + const cols = line.trim().split(/\s+/); + if (cols.length >= 11 && cols[2]?.startsWith(' prevState.ts + ) { + const dtSec = (nowMs - prevState.ts) / 1000; + if (netRxBytes >= prevState.netRxBytes) { + netRxBps = Math.round((netRxBytes - prevState.netRxBytes) / dtSec); + } + if (netTxBytes >= prevState.netTxBytes) { + netTxBps = Math.round((netTxBytes - prevState.netTxBytes) / dtSec); + } + } + + const disks = parseDfLines(sec.DF ?? '', true, mountFilter); + + return { + sample: { + ts: nowMs, + cpuPct, + memUsedMb, + memTotalMb, + netRxBps, + netTxBps, + load1m, + uptimeSec, + }, + disks, + nextState: { ts: nowMs, cpuTotal, cpuIdle, netRxBytes, netTxBytes }, + }; +} + +export function parseMacOsOutput( + stdout: string, + prevState?: CollectorDeltaState, + mountFilter?: string[], + nowMs = Date.now(), +): CollectOutput { + const sec = splitSections(stdout); + const sysctlLines = (sec.SYSCTL ?? '') + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + + const memBytes = Number(sysctlLines[0]) || 0; + const pageSize = Number(sysctlLines[1]) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); + const load1m = round2(Number(loadMatch?.[1] ?? 0)); + + let uptimeSec = 0; + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); + if (bootSecMatch) { + uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); + } + + let cpuPct = 0; + const idleMatch = /([\d.]+)%\s*idle/i.exec(sec.TOP ?? ''); + if (idleMatch) { + cpuPct = round2(clamp(100 - Number(idleMatch[1]), 0, 100)); + } + + // Parse vm_stat active + wired + compressor pages + let activePages = 0; + let wiredPages = 0; + let compressedPages = 0; + for (const line of (sec.VMSTAT ?? '').split(/\r?\n/)) { + const m = /^(.+?):\s+(\d+)\./.exec(line.trim()); + if (!m) continue; + const label = m[1]!.toLowerCase(); + const pages = Number(m[2]!) || 0; + if (label === 'pages active') activePages = pages; + else if (label === 'pages wired down') wiredPages = pages; + else if (label === 'pages occupied by compressor') compressedPages = pages; + } + const usedBytes = (activePages + wiredPages + compressedPages) * pageSize; + const memTotalMb = round2(memBytes / (1024 * 1024)); + const memUsedMb = round2(Math.min(memBytes, usedBytes) / (1024 * 1024)); + + let netRxBytes = 0; + let netTxBytes = 0; + for (const line of (sec.NET ?? '').split(/\r?\n/)) { + const cols = line.trim().split(/\s+/); + if (cols.length >= 10 && cols[2]?.startsWith(' prevState.ts + ) { + const dtSec = (nowMs - prevState.ts) / 1000; + if (netRxBytes >= prevState.netRxBytes) { + netRxBps = Math.round((netRxBytes - prevState.netRxBytes) / dtSec); + } + if (netTxBytes >= prevState.netTxBytes) { + netTxBps = Math.round((netTxBytes - prevState.netTxBytes) / dtSec); + } + } + + const disks = parseDfLines(sec.DF ?? '', false, mountFilter); + + return { + sample: { + ts: nowMs, + cpuPct, + memUsedMb, + memTotalMb, + netRxBps, + netTxBps, + load1m, + uptimeSec, + }, + disks, + nextState: { ts: nowMs, netRxBytes, netTxBytes }, + }; +} + +export async function detectServerOs( + sshPool: SSHPool, + server: ServerConfig, + cachedOs?: OsType, +): Promise { + if (server.osHint !== 'auto') { + sshPool.setOsDetected(server.id, server.osHint); + return server.osHint; + } + if (cachedOs) return cachedOs; + + const res = await sshPool.exec(server.id, 'uname -s'); + const raw = res.stdout.trim().toLowerCase(); + let detected: OsType = 'linux'; + if (raw.includes('darwin')) detected = 'macos'; + else if (raw.includes('bsd')) detected = 'bsd'; + + sshPool.setOsDetected(server.id, detected); + return detected; +} + +export async function collectServerMetrics( + sshPool: SSHPool, + server: ServerConfig, + osType: OsType, + prevState?: CollectorDeltaState, +): Promise { + const cmd = + osType === 'macos' + ? MACOS_METRIC_CMD + : osType === 'bsd' + ? BSD_METRIC_CMD + : LINUX_METRIC_CMD; + + const res = await sshPool.exec(server.id, cmd, { timeoutMs: 15_000 }); + if (res.exitCode !== 0 && res.stdout.trim().length === 0) { + throw new Error( + `Metric collection failed (exit=${res.exitCode}): ${res.stderr.trim()}`, + ); + } + + const nowMs = Date.now(); + if (osType === 'macos') { + return parseMacOsOutput(res.stdout, prevState, server.diskMountFilter, nowMs); + } + if (osType === 'bsd') { + return parseBsdOutput(res.stdout, prevState, server.diskMountFilter, nowMs); + } + return parseLinuxOutput(res.stdout, prevState, server.diskMountFilter, nowMs); +} diff --git a/src/server/monitoring/inspector.ts b/src/server/monitoring/inspector.ts new file mode 100644 index 0000000..518de1a --- /dev/null +++ b/src/server/monitoring/inspector.ts @@ -0,0 +1,173 @@ +import type { ConfigManager } from '../config/config-manager.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { detectServerOs, type OsType } from './collectors.js'; + +export interface ProcessEntry { + pid: number; + user: string; + cpuPct: number; + memPct: number; + rssMb: number; + command: string; +} + +export interface PortEntry { + proto: string; + localAddress: string; + process: string; +} + +export interface ThermalEntry { + zone: string; + tempC: number; +} + +export interface ServerInspectionResult { + serverId: string; + os: OsType; + collectedAt: number; + processes: ProcessEntry[]; + ports: PortEntry[]; + thermals: ThermalEntry[]; +} + +const LINUX_INSPECT_CMD = [ + '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', + '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 = [ + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 26', + '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', +].join('; '); + +const MACOS_INSPECT_CMD = [ + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 26', + 'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true', + 'printf "===THERMAL===\\n"; true', +].join('; '); + +export function parseInspectorOutput( + serverId: string, + os: OsType, + stdout: string, + collectedAt = Date.now(), +): ServerInspectionResult { + const sections: Record = {}; + let current = ''; + for (const line of stdout.split(/\r?\n/)) { + const m = /^===([A-Z]+)===$/.exec(line.trim()); + if (m) { + current = m[1]!; + sections[current] = []; + } else if (current && line.trim().length > 0) { + sections[current]!.push(line); + } + } + + // Processes + const processes: ProcessEntry[] = []; + const procLines = sections.PROCS ?? []; + for (let i = 1; i < procLines.length; i++) { + const cols = procLines[i]!.trim().split(/\s+/); + if (cols.length < 6) continue; + const pid = Number(cols[0]); + if (!Number.isFinite(pid)) continue; + processes.push({ + pid, + user: cols[1]!, + cpuPct: Number(cols[2]) || 0, + memPct: Number(cols[3]) || 0, + rssMb: Math.round(((Number(cols[4]) || 0) / 1024) * 10) / 10, + command: cols.slice(5).join(' '), + }); + } + + // Ports + const ports: PortEntry[] = []; + const portLines = sections.PORTS ?? []; + for (const line of portLines) { + const trimmed = line.trim(); + if ( + /^(Netid|Proto|USER|Active)/i.test(trimmed) || + trimmed.startsWith('Command') + ) { + continue; + } + const cols = trimmed.split(/\s+/); + 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')) { + ports.push({ + proto: cols[0]!, + localAddress: cols[4]!, + process: cols.slice(6).join(' ') || '—', + }); + } else if (cols.length >= 4) { + ports.push({ + proto: cols[0]!, + localAddress: cols[3]!, + process: cols[cols.length - 1] ?? '—', + }); + } + } else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') { + // lsof format + ports.push({ + proto: cols[7] ?? 'TCP', + localAddress: cols[8] ?? '', + process: `${cols[0]}(${cols[1]})`, + }); + } else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) { + // sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN + ports.push({ + proto: cols[4] ?? 'tcp', + localAddress: cols[5] ?? '', + process: `${cols[1]}(${cols[2]})`, + }); + } + } + + // Thermals + const thermals: ThermalEntry[] = []; + for (const line of sections.THERMAL ?? []) { + const colon = line.indexOf(':'); + if (colon <= 0) continue; + const zone = line.slice(0, colon).trim(); + const rawVal = line.slice(colon + 1).trim(); + const numMatch = /(-?[\d.]+)/.exec(rawVal); + if (!numMatch) continue; + const val = Number(numMatch[1]); + // Linux /sys/class/thermal reports millidegrees Celsius + const tempC = val > 1000 ? Math.round((val / 1000) * 10) / 10 : Math.round(val * 10) / 10; + thermals.push({ zone, tempC }); + } + + return { serverId, os, collectedAt, processes, ports, thermals }; +} + +export class ServerInspector { + constructor( + private readonly sshPool: SSHPool, + private readonly configManager: ConfigManager, + ) {} + + async inspect(serverId: string): Promise { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + const runtime = this.sshPool.getState(serverId); + const os = await detectServerOs(this.sshPool, server, runtime?.osDetected); + const cmd = + os === 'macos' + ? MACOS_INSPECT_CMD + : os === 'bsd' + ? BSD_INSPECT_CMD + : LINUX_INSPECT_CMD; + + const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 }); + return parseInspectorOutput(serverId, os, res.stdout); + } +} diff --git a/src/server/monitoring/monitoring-service.ts b/src/server/monitoring/monitoring-service.ts new file mode 100644 index 0000000..7f40111 --- /dev/null +++ b/src/server/monitoring/monitoring-service.ts @@ -0,0 +1,436 @@ +import type Database from 'better-sqlite3'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { + DiskSample, + MetricSample, + ProbeSample, +} from '../../shared/ws-protocol.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { VaultService } from '../security/vault.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { + collectServerMetrics, + detectServerOs, + type CollectorDeltaState, + type OsType, +} from './collectors.js'; +import { ProbeRunner } from './probes.js'; + +export type MetricRange = '1h' | '6h' | '24h' | '7d' | '30d'; + +export interface LatestServerTelemetry { + serverId: string; + os?: OsType; + sample?: MetricSample; + disks: DiskSample[]; + probes: Record; + lastError?: string; +} + +export interface MonitoringTickEvent { + serverId: string; + sample: MetricSample; + disks: DiskSample[]; + probes: ProbeSample[]; +} + +interface ServerTimers { + metricTimer: NodeJS.Timeout | null; + probeTimers: Map; + pollingMetrics: boolean; +} + +const MAINTENANCE_INTERVAL_MS = 15 * 60 * 1000; + +export class MonitoringService { + private readonly serverTimers = new Map(); + private readonly deltaStates = new Map(); + private readonly osCache = new Map(); + private readonly latest = new Map(); + private readonly tickListeners = new Set<(event: MonitoringTickEvent) => void>(); + private maintenanceTimer: NodeJS.Timeout | null = null; + private stopped = false; + + constructor( + private readonly db: Database.Database, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly sshPool: SSHPool, + private readonly probeRunner: ProbeRunner, + ) {} + + onTick(listener: (event: MonitoringTickEvent) => void): () => void { + this.tickListeners.add(listener); + return () => { + this.tickListeners.delete(listener); + }; + } + + start(): void { + this.stopped = false; + this.syncServers(); + if (!this.maintenanceTimer) { + this.runMaintenance(); + this.maintenanceTimer = setInterval(() => { + this.runMaintenance(); + }, MAINTENANCE_INTERVAL_MS); + this.maintenanceTimer.unref(); + } + } + + stopAll(): void { + for (const timers of this.serverTimers.values()) { + if (timers.metricTimer) clearInterval(timers.metricTimer); + for (const pt of timers.probeTimers.values()) clearInterval(pt); + } + this.serverTimers.clear(); + } + + close(): void { + this.stopped = true; + this.stopAll(); + if (this.maintenanceTimer) { + clearInterval(this.maintenanceTimer); + this.maintenanceTimer = null; + } + } + + syncServers(): void { + if (this.stopped) return; + this.stopAll(); + this.sshPool.syncWithConfig(); + + if (this.vaultService.state !== 'unlocked') { + return; + } + + for (const server of this.configManager.listServers()) { + if (!server.enabled) continue; + this.scheduleServer(server); + } + } + + getLatest(serverId: string): LatestServerTelemetry | undefined { + const entry = this.latest.get(serverId); + return entry ? structuredClone(entry) : undefined; + } + + async pollServerNow(serverId: string): Promise { + const server = this.configManager.getServer(serverId); + if (!server || !server.enabled || this.vaultService.state !== 'unlocked') { + return null; + } + return this.executeMetricPoll(server); + } + + runMaintenance(nowMs = Date.now()): void { + const settings = this.configManager.getSettings(); + const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000; + const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000; + + const tx = this.db.transaction(() => { + // Aggregate hourly rollups from raw metrics + this.db + .prepare( + `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) + SELECT + (ts / 3600000) * 3600000 AS bucket_ts, + '1h' AS granularity, + server_id, + MIN(cpu_pct), + AVG(cpu_pct), + MAX(cpu_pct), + COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), + MAX(load_1m) + FROM metrics_raw + GROUP BY server_id, (ts / 3600000) * 3600000`, + ) + .run(); + + // Aggregate daily rollups + this.db + .prepare( + `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) + SELECT + (ts / 86400000) * 86400000 AS bucket_ts, + '1d' AS granularity, + server_id, + MIN(cpu_pct), + AVG(cpu_pct), + MAX(cpu_pct), + COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), + MAX(load_1m) + FROM metrics_raw + GROUP BY server_id, (ts / 86400000) * 86400000`, + ) + .run(); + + this.db.prepare('DELETE FROM metrics_raw 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 metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff); + }); + tx(); + } + + queryHistory(serverId: string, range: MetricRange = '1h'): { + range: MetricRange; + granularity: 'raw' | '1h' | '1d'; + points: Array>; + latestDisks: DiskSample[]; + latestProbes: Array; + } { + const now = Date.now(); + const rangeMs: Record = { + '1h': 3600_000, + '6h': 6 * 3600_000, + '24h': 24 * 3600_000, + '7d': 7 * 86_400_000, + '30d': 30 * 86_400_000, + }; + const since = now - rangeMs[range]; + + let granularity: 'raw' | '1h' | '1d' = 'raw'; + let points: Array>; + + if (range === '1h' || range === '6h' || range === '24h') { + points = this.db + .prepare( + `SELECT ts, cpu_pct AS cpuPct, mem_used_mb AS memUsedMb, mem_total_mb AS memTotalMb, + net_rx_bps AS netRxBps, net_tx_bps AS netTxBps, load_1m AS load1m, uptime_sec AS uptimeSec + FROM metrics_raw + WHERE server_id = ? AND ts >= ? + ORDER BY ts ASC`, + ) + .all(serverId, since) as Array>; + } else { + granularity = range === '7d' ? '1h' : '1d'; + points = this.db + .prepare( + `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 + FROM metrics_rollup + WHERE server_id = ? AND granularity = ? AND bucket_ts >= ? + ORDER BY bucket_ts ASC`, + ) + .all(serverId, granularity, since) as Array>; + } + + const latestDisks = this.db + .prepare( + `SELECT mount_point AS mountPoint, fs_type AS fsType, used_mb AS usedMb, total_mb AS totalMb, used_pct AS usedPct + FROM metrics_disks + WHERE server_id = ? AND ts = (SELECT MAX(ts) FROM metrics_disks WHERE server_id = ?) + ORDER BY mount_point ASC`, + ) + .all(serverId, serverId) as DiskSample[]; + + const latestProbes = this.db + .prepare( + `SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode, + p.latency_ms AS latencyMs, p.error AS error, p.ts AS ts + FROM probe_results p + INNER JOIN ( + SELECT probe_id, MAX(ts) AS max_ts + FROM probe_results + WHERE server_id = ? + GROUP BY probe_id + ) latest ON latest.probe_id = p.probe_id AND latest.max_ts = p.ts + WHERE p.server_id = ?`, + ) + .all(serverId, serverId) as Array<{ + probeId: string; + okInt: number; + statusCode: number | null; + latencyMs: number; + error: string | null; + ts: number; + }>; + + return { + range, + granularity, + points, + latestDisks, + latestProbes: latestProbes.map((r) => ({ + probeId: r.probeId, + ok: r.okInt === 1, + statusCode: r.statusCode ?? undefined, + latencyMs: r.latencyMs, + error: r.error ?? undefined, + ts: r.ts, + })), + }; + } + + private scheduleServer(server: ServerConfig): void { + const timers: ServerTimers = { + metricTimer: null, + probeTimers: new Map(), + pollingMetrics: false, + }; + this.serverTimers.set(server.id, timers); + + // Kick initial poll asynchronously without delaying syncServers() + void this.executeMetricPoll(server); + + 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); + const pt = setInterval(() => { + void this.executeProbe(server, probe.id); + }, probe.intervalSec * 1000); + pt.unref(); + timers.probeTimers.set(probe.id, pt); + } + } + + private async executeMetricPoll( + server: ServerConfig, + ): Promise { + if (this.stopped || this.vaultService.state !== 'unlocked') return null; + + const timerState = this.serverTimers.get(server.id); + if (timerState?.pollingMetrics) return null; + if (timerState) timerState.pollingMetrics = true; + + try { + const os = await detectServerOs( + this.sshPool, + server, + this.osCache.get(server.id), + ); + this.osCache.set(server.id, os); + + const collected = await collectServerMetrics( + this.sshPool, + server, + os, + this.deltaStates.get(server.id), + ); + this.deltaStates.set(server.id, collected.nextState); + + this.persistMetricSample(server.id, collected.sample, collected.disks); + + const prevLatest = this.latest.get(server.id) ?? { + 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 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; + } catch (err) { + const prevLatest = this.latest.get(server.id) ?? { + serverId: server.id, + disks: [], + probes: {}, + }; + this.latest.set(server.id, { + ...prevLatest, + lastError: err instanceof Error ? err.message : String(err), + }); + return null; + } finally { + if (timerState) timerState.pollingMetrics = false; + } + } + + private async executeProbe(server: ServerConfig, probeId: string): Promise { + if (this.stopped || this.vaultService.state !== 'unlocked') return; + const probe = server.probes.find((p) => p.id === probeId); + if (!probe || !probe.enabled) return; + + const sample = await this.probeRunner.runProbe(server.id, probe); + const ts = Date.now(); + this.db + .prepare( + `INSERT OR REPLACE INTO probe_results (ts, server_id, probe_id, ok, status_code, latency_ms, error) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + ts, + server.id, + probe.id, + sample.ok ? 1 : 0, + sample.statusCode ?? null, + sample.latencyMs, + sample.error ?? null, + ); + + const prevLatest = this.latest.get(server.id) ?? { + serverId: server.id, + disks: [], + probes: {}, + }; + prevLatest.probes[probe.id] = sample; + this.latest.set(server.id, prevLatest); + } + + private persistMetricSample( + serverId: string, + sample: MetricSample, + disks: DiskSample[], + ): void { + const tx = this.db.transaction(() => { + this.db + .prepare( + `INSERT OR REPLACE INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + sample.ts, + serverId, + sample.cpuPct, + sample.memUsedMb, + sample.memTotalMb, + sample.netRxBps, + sample.netTxBps, + sample.load1m, + sample.uptimeSec, + ); + + const diskStmt = this.db.prepare( + `INSERT OR REPLACE INTO metrics_disks (ts, server_id, mount_point, fs_type, used_mb, total_mb, used_pct) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ); + for (const d of disks) { + diskStmt.run( + sample.ts, + serverId, + d.mountPoint, + d.fsType, + d.usedMb, + d.totalMb, + d.usedPct, + ); + } + }); + tx(); + } +} diff --git a/src/server/monitoring/probes.ts b/src/server/monitoring/probes.ts new file mode 100644 index 0000000..02d5bed --- /dev/null +++ b/src/server/monitoring/probes.ts @@ -0,0 +1,180 @@ +import net from 'node:net'; +import tls from 'node:tls'; +import type { Duplex } from 'node:stream'; +import type { ServerProbe } from '../../shared/schemas/server.schema.js'; +import type { ProbeSample } from '../../shared/ws-protocol.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; + +function readHttpFromStream( + stream: Duplex, + url: URL, + timeoutMs: number, +): Promise<{ statusCode: number; body: string }> { + return new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + stream.destroy(); + reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`)); + }, timeoutMs); + + const transport: Duplex = + url.protocol === 'https:' + ? tls.connect({ socket: stream, servername: url.hostname }) + : stream; + + const chunks: Buffer[] = []; + let total = 0; + const maxBytes = 256 * 1024; + + const done = (err?: Error) => { + if (settled) return; + settled = true; + clearTimeout(timer); + transport.destroy(); + if (err) { + reject(err); + return; + } + const raw = Buffer.concat(chunks).toString('utf8'); + const headerEnd = raw.indexOf('\r\n\r\n'); + const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw; + const body = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; + const statusLine = head.split('\r\n')[0] ?? ''; + const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine); + if (!m) { + reject(new Error(`Invalid HTTP response line: ${statusLine}`)); + return; + } + resolve({ statusCode: Number(m[1]), body }); + }; + + transport.on('data', (chunk: Buffer) => { + if (total < maxBytes) { + chunks.push(chunk.subarray(0, maxBytes - total)); + total += chunk.length; + } + }); + transport.once('end', () => done()); + transport.once('close', () => done()); + transport.once('error', (err) => done(err)); + + const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`; + const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname; + const reqText = + `GET ${pathAndQuery} HTTP/1.1\r\n` + + `Host: ${hostHeader}\r\n` + + `User-Agent: GCoordinator-Probe/1.0\r\n` + + `Connection: close\r\n\r\n`; + + if (url.protocol === 'https:') { + (transport as tls.TLSSocket).once('secureConnect', () => { + transport.write(reqText); + }); + } else { + transport.write(reqText); + } + }); +} + +export class ProbeRunner { + constructor(private readonly sshPool: SSHPool) {} + + async runProbe(serverId: string, probe: ServerProbe): Promise { + const started = Date.now(); + try { + if (probe.type === 'tcp') { + if (probe.from === 'hub') { + await new Promise((resolve, reject) => { + const sock = net.createConnection({ + host: probe.host, + port: probe.port, + }); + const timer = setTimeout(() => { + sock.destroy(); + reject(new Error(`TCP connect timed out after ${probe.timeoutMs}ms`)); + }, probe.timeoutMs); + + sock.once('connect', () => { + clearTimeout(timer); + sock.destroy(); + resolve(); + }); + sock.once('error', (err) => { + clearTimeout(timer); + sock.destroy(); + reject(err); + }); + }); + } else { + const stream = await this.sshPool.forwardOutStream( + serverId, + probe.host, + probe.port, + probe.timeoutMs, + ); + stream.destroy(); + } + + return { + probeId: probe.id, + ok: true, + latencyMs: Date.now() - started, + }; + } + + // HTTP(S) probe + let statusCode: number; + let body: string; + + if (probe.from === 'hub') { + const res = await fetch(probe.url, { + method: 'GET', + redirect: 'manual', + signal: AbortSignal.timeout(probe.timeoutMs), + }); + statusCode = res.status; + body = await res.text(); + } else { + const parsedUrl = new URL(probe.url); + const port = parsedUrl.port + ? Number(parsedUrl.port) + : parsedUrl.protocol === 'https:' + ? 443 + : 80; + const stream = await this.sshPool.forwardOutStream( + serverId, + parsedUrl.hostname, + port, + probe.timeoutMs, + ); + const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs); + statusCode = resp.statusCode; + body = resp.body; + } + + const statusOk = statusCode === probe.expectedStatus; + const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true; + const ok = statusOk && bodyOk; + return { + probeId: probe.id, + ok, + statusCode, + latencyMs: Date.now() - started, + error: ok + ? undefined + : !statusOk + ? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}` + : `Response body missing substring "${probe.bodyIncludes}"`, + }; + } catch (err) { + return { + probeId: probe.id, + ok: false, + latencyMs: Date.now() - started, + error: err instanceof Error ? err.message : String(err), + }; + } + } +}