From 5933727a01e362e0d02be4eeb59d1596bc8485f8 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 16:18:15 +0000 Subject: [PATCH] fix(monitoring,db,proxy): cap/dedupe shared-host disk mounts, index metrics_disks, defer startup maintenance & bind split proxy port --- How/AGENTS.md | 4 +- src/server/config/config-manager.ts | 15 +- src/server/db/database.ts | 2 + .../migrations/005_metrics_disks_indexes.ts | 24 ++++ src/server/monitoring/collectors.ts | 135 ++++++++++++++++-- src/server/monitoring/monitoring-service.ts | 20 ++- src/server/ssh/tunnel-manager.ts | 5 +- tests/monitoring-and-probes.test.ts | 106 ++++++++++++++ 8 files changed, 292 insertions(+), 19 deletions(-) create mode 100644 src/server/db/migrations/005_metrics_disks_indexes.ts diff --git a/How/AGENTS.md b/How/AGENTS.md index e824fae..5b3728c 100644 --- a/How/AGENTS.md +++ b/How/AGENTS.md @@ -111,7 +111,7 @@ GCoordinator/ │ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock, /metrics │ │ ├── db/ │ │ │ ├── database.ts # SQLite WAL connection, throttle PRAGMAs & ordered migration runner -│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts, 004_v1_1.ts +│ │ │ └── migrations/ # 001_initial.ts .. 005_metrics_disks_indexes.ts │ │ ├── security/ │ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, seal(), Ed25519) │ │ │ ├── auth.ts # AuthService (Argon2id queue, multi-password, encrypted TOTP, idle TTL, WebAuthn) @@ -228,7 +228,7 @@ GCoordinator/ ### 5. Config Hot-Reload, Symlink Safety & SQLite Migrations (`config-manager.ts`, `database.ts`) - Every config write uses atomic staging (`tmp -> fsync -> rename`), rejects symlinks across config/backup/CLI file operations, validates against Zod schemas, and records `config_revisions`. Invalid hand-edited config files stay isolated without crashing the hub. -- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`, `004_v1_1.ts`) destructively; add new schema changes as `005_*.ts` and register them in `src/server/db/database.ts`. +- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`, `004_v1_1.ts`, `005_metrics_disks_indexes.ts`) destructively; add new schema changes as `006_*.ts` and register them in `src/server/db/database.ts`. ### 6. SSH, Shell Quoting, Egress Guard & Dual-Mode Isolated Proxy (`egress-guard.ts`, `tunnel-manager.ts`) - **Zero-Trust Egress Guard (`egress-guard.ts`)**: All outbound hub HTTP calls (HTTP probes, webhook deliveries, BYO AI requests, workflow `http` steps) must go through `fetchWithEgressGuard()` / `assertSafeEgressUrl()`, which default-denies loopback, private, link-local, carrier-grade NAT, and cloud-metadata IPs/DNS resolutions, disables automatic redirects (`redirect: 'error'`), and honors explicit `settings.security.egressAllowedCidrs` opt-ins. diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index c23a4ba..d349252 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -645,9 +645,22 @@ export class ConfigManager { this.watcher.on('add', (p) => scheduleReload(p, 'upsert')); this.watcher.on('change', (p) => scheduleReload(p, 'upsert')); this.watcher.on('unlink', (p) => scheduleReload(p, 'unlink')); + this.watcher.on('error', () => { + // Isolate watcher errors so corrupted/unreadable paths cannot crash or hang boot + }); return new Promise((resolve) => { - this.watcher!.once('ready', () => resolve()); + let settled = false; + const done = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(); + }; + const timer = setTimeout(done, 5_000); + timer.unref(); + this.watcher!.once('ready', done); + this.watcher!.once('error', done); }); } diff --git a/src/server/db/database.ts b/src/server/db/database.ts index b9f2fd5..a2bfbd1 100644 --- a/src/server/db/database.ts +++ b/src/server/db/database.ts @@ -6,12 +6,14 @@ import { migration001Initial, type Migration } from './migrations/001_initial.js import { migration002MultiAuth } from './migrations/002_multi_auth.js'; import { migration003Phase4Meta } from './migrations/003_phase4_meta.js'; import { migration004V11 } from './migrations/004_v1_1.js'; +import { migration005MetricsDisksIndexes } from './migrations/005_metrics_disks_indexes.js'; const MIGRATIONS: Migration[] = [ migration001Initial, migration002MultiAuth, migration003Phase4Meta, migration004V11, + migration005MetricsDisksIndexes, ]; function chmodBestEffort(targetPath: string, mode: number): void { diff --git a/src/server/db/migrations/005_metrics_disks_indexes.ts b/src/server/db/migrations/005_metrics_disks_indexes.ts new file mode 100644 index 0000000..2d28a4e --- /dev/null +++ b/src/server/db/migrations/005_metrics_disks_indexes.ts @@ -0,0 +1,24 @@ +import type Database from 'better-sqlite3'; +import type { Migration } from './001_initial.js'; + +export const RUNAWAY_METRICS_DISKS_THRESHOLD = 100_000; + +export const migration005MetricsDisksIndexes: Migration = { + id: '005_metrics_disks_indexes', + up(db: Database.Database) { + const row = db + .prepare('SELECT COUNT(*) AS n FROM metrics_disks') + .get() as { n: number }; + if (row.n > RUNAWAY_METRICS_DISKS_THRESHOLD) { + // Unconditional DELETE uses SQLite's fast B-tree truncate without spilling into /tmp + db.exec('DELETE FROM metrics_disks;'); + } + + db.exec(` + CREATE INDEX IF NOT EXISTS idx_metrics_disks_server_ts ON metrics_disks(server_id, ts DESC); + CREATE INDEX IF NOT EXISTS idx_metrics_disks_ts ON metrics_disks(ts); + CREATE INDEX IF NOT EXISTS idx_metrics_raw_ts ON metrics_raw(ts); + CREATE INDEX IF NOT EXISTS idx_probe_results_ts ON probe_results(ts); + `); + }, +}; diff --git a/src/server/monitoring/collectors.ts b/src/server/monitoring/collectors.ts index 5faee22..53561f9 100644 --- a/src/server/monitoring/collectors.ts +++ b/src/server/monitoring/collectors.ts @@ -18,11 +18,22 @@ export interface CollectOutput { nextState: CollectorDeltaState; } +export const MAX_AUTO_DISCOVERED_MOUNTS = 24; +export const MAX_EXPLICIT_FILTER_MOUNTS = 64; + const VIRTUAL_FS_TYPES = new Set([ 'tmpfs', 'devtmpfs', 'squashfs', 'overlay', + 'overlayfs', + 'iso9660', + 'rpc_pipefs', + 'nfsd', + 'binfmt_misc', + 'configfs', + 'selinuxfs', + 'systemd-1', 'proc', 'sysfs', 'cgroup', @@ -44,8 +55,50 @@ const VIRTUAL_FS_TYPES = new Set([ 'devfs', 'fdescfs', 'procfs', + 'fuse.lxcfs', + 'fuse.gvfsd-fuse', + 'fuse.portal', + 'fuse.snapfuse', + 'fuse.squashfuse', + 'fuse.revokefs-fuse', + 'fuse.appimage', + 'fuse.encfs', + 'fuse.docker-mount', + 'fuse.overlayfs', ]); +const NOISY_MOUNT_PREFIXES = [ + '/proc', + '/sys', + '/dev', + '/run', + '/snap', + '/var/snap', + '/var/lib/docker', + '/var/lib/containerd', + '/var/lib/kubelet', + '/var/lib/lxc', + '/var/lib/lxd', + '/home/virtfs', + '/var/cagefs', + '/usr/share/cagefs-skeleton', + '/cagefs', + '/mnt/wsl', +]; + +function isNoisyMountPath(mountPoint: string): boolean { + return NOISY_MOUNT_PREFIXES.some( + (prefix) => mountPoint === prefix || mountPoint.startsWith(`${prefix}/`), + ); +} + +function isPreferredMount(candidate: string, current: string): boolean { + if (candidate === '/') return true; + if (current === '/') return false; + if (candidate.length !== current.length) return candidate.length < current.length; + return candidate < current; +} + 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', @@ -147,10 +200,16 @@ function parseDfLines( hasTypeColumn: boolean, mountFilter?: string[], ): DiskSample[] { - const disks: DiskSample[] = []; + interface DiskCandidate { + fsName: string; + disk: DiskSample; + } + + const candidates: DiskCandidate[] = []; const seenMounts = new Set(); + const hasExplicitFilter = Boolean(mountFilter && mountFilter.length > 0); const lines = dfText.split(/\r?\n/).filter((l) => l.trim().length > 0); - if (lines.length < 2) return disks; + if (lines.length < 2) return []; // Detect whether output actually includes Type column (7 cols) or POSIX df (6 cols) const headerCols = lines[0]!.trim().split(/\s+/); @@ -160,14 +219,23 @@ function parseDfLines( for (let i = 1; i < lines.length; i++) { const cols = lines[i]!.trim().split(/\s+/); if (detectedTypeCol && cols.length >= 7) { + const fsName = cols[0]!; 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) { + if (!Number.isFinite(totalKb) || totalKb <= 0) { continue; } - if (mountFilter && mountFilter.length > 0 && !mountFilter.includes(mountPoint)) { + if ( + !hasExplicitFilter && + (VIRTUAL_FS_TYPES.has(fsType) || + fsName.startsWith('/dev/loop') || + isNoisyMountPath(mountPoint)) + ) { + continue; + } + if (hasExplicitFilter && !mountFilter!.includes(mountPoint)) { continue; } if (seenMounts.has(mountPoint)) continue; @@ -175,22 +243,25 @@ function parseDfLines( 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 }); + candidates.push({ fsName, disk: { 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 (!Number.isFinite(totalKb) || totalKb <= 0) { + continue; + } if ( - fsName === 'devfs' || - fsName === 'map' || - fsName.startsWith('/dev/loop') || - !Number.isFinite(totalKb) || - totalKb <= 0 + !hasExplicitFilter && + (fsName === 'devfs' || + fsName === 'map' || + fsName.startsWith('/dev/loop') || + isNoisyMountPath(mountPoint)) ) { continue; } - if (mountFilter && mountFilter.length > 0 && !mountFilter.includes(mountPoint)) { + if (hasExplicitFilter && !mountFilter!.includes(mountPoint)) { continue; } if (seenMounts.has(mountPoint)) continue; @@ -198,10 +269,48 @@ function parseDfLines( 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 }); + candidates.push({ fsName, disk: { mountPoint, fsType: 'disk', usedMb, totalMb, usedPct } }); } } - return disks; + + if (hasExplicitFilter) { + return candidates.slice(0, MAX_EXPLICIT_FILTER_MOUNTS).map((c) => c.disk); + } + + // Collapse bind mounts sharing the same backing block/network device + const byDevice = new Map(); + const deduped: DiskCandidate[] = []; + for (const cand of candidates) { + if (cand.fsName.startsWith('/') || cand.fsName.includes(':/')) { + const prev = byDevice.get(cand.fsName); + if (!prev) { + byDevice.set(cand.fsName, cand); + deduped.push(cand); + } else if (isPreferredMount(cand.disk.mountPoint, prev.disk.mountPoint)) { + prev.disk = cand.disk; + } + } else { + deduped.push(cand); + } + } + + if (deduped.length <= MAX_AUTO_DISCOVERED_MOUNTS) { + return deduped.map((c) => c.disk); + } + + deduped.sort((a, b) => { + const am = a.disk.mountPoint; + const bm = b.disk.mountPoint; + if (am === '/' && bm !== '/') return -1; + if (bm === '/' && am !== '/') return 1; + const depthDiff = + am.split('/').filter(Boolean).length - bm.split('/').filter(Boolean).length; + if (depthDiff !== 0) return depthDiff; + if (b.disk.totalMb !== a.disk.totalMb) return b.disk.totalMb - a.disk.totalMb; + return am < bm ? -1 : am > bm ? 1 : 0; + }); + + return deduped.slice(0, MAX_AUTO_DISCOVERED_MOUNTS).map((c) => c.disk); } export function parseLinuxOutput( diff --git a/src/server/monitoring/monitoring-service.ts b/src/server/monitoring/monitoring-service.ts index 29a02b1..a94b423 100644 --- a/src/server/monitoring/monitoring-service.ts +++ b/src/server/monitoring/monitoring-service.ts @@ -44,6 +44,8 @@ interface ServerTimers { } const MAINTENANCE_INTERVAL_MS = 15 * 60 * 1000; +const INITIAL_MAINTENANCE_DELAY_MS = 10_000; +const MAX_PERSISTED_DISKS = 64; export class MonitoringService { private readonly serverTimers = new Map(); @@ -55,6 +57,7 @@ export class MonitoringService { (event: { serverId: string; probe: ProbeSample }) => void >(); private maintenanceTimer: NodeJS.Timeout | null = null; + private initialMaintenanceTimer: NodeJS.Timeout | null = null; private stopped = false; private inFlightPolls = 0; private readonly pollQueue: Array<() => void> = []; @@ -89,7 +92,15 @@ export class MonitoringService { this.hydrateLatestFromDb(); this.syncServers(); if (!this.maintenanceTimer) { - this.runMaintenance(); + // Defer initial rollup/retention work so HTTP/healthcheck comes up immediately after boot + this.initialMaintenanceTimer = setTimeout(() => { + this.initialMaintenanceTimer = null; + if (!this.stopped) { + this.runMaintenance(); + } + }, INITIAL_MAINTENANCE_DELAY_MS); + this.initialMaintenanceTimer.unref(); + this.maintenanceTimer = setInterval(() => { this.runMaintenance(); }, MAINTENANCE_INTERVAL_MS); @@ -113,6 +124,10 @@ export class MonitoringService { while (this.pollQueue.length > 0) { this.pollQueue.shift()?.(); } + if (this.initialMaintenanceTimer) { + clearTimeout(this.initialMaintenanceTimer); + this.initialMaintenanceTimer = null; + } if (this.maintenanceTimer) { clearInterval(this.maintenanceTimer); this.maintenanceTimer = null; @@ -191,6 +206,7 @@ export class MonitoringService { LEFT JOIN ( SELECT server_id, ts, MAX(used_pct) AS max_disk_pct FROM metrics_disks + WHERE ts >= (SELECT COALESCE(MIN(ts), 0) FROM metrics_raw) 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 @@ -715,7 +731,7 @@ export class MonitoringService { `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) { + for (const d of disks.slice(0, MAX_PERSISTED_DISKS)) { diskStmt.run( sample.ts, serverId, diff --git a/src/server/ssh/tunnel-manager.ts b/src/server/ssh/tunnel-manager.ts index 993feb5..b335193 100644 --- a/src/server/ssh/tunnel-manager.ts +++ b/src/server/ssh/tunnel-manager.ts @@ -277,7 +277,10 @@ export class TunnelManager { this.handleDedicatedProxyPortWs(req, socket, head); }); - const bindHost = this.allowLanTunnels ? '0.0.0.0' : '127.0.0.1'; + const bindHost = + this.allowLanTunnels || this.trustCloudflare || Boolean(this.proxyPublicOrigin) + ? '0.0.0.0' + : '127.0.0.1'; await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(this.configuredProxyPort!, bindHost, () => { diff --git a/tests/monitoring-and-probes.test.ts b/tests/monitoring-and-probes.test.ts index c15573e..b2d204d 100644 --- a/tests/monitoring-and-probes.test.ts +++ b/tests/monitoring-and-probes.test.ts @@ -6,6 +6,11 @@ import { afterEach, describe, expect, it } from 'vitest'; import { ConfigManager } from '../src/server/config/config-manager.js'; import { openDatabase } from '../src/server/db/database.js'; import { + migration005MetricsDisksIndexes, + RUNAWAY_METRICS_DISKS_THRESHOLD, +} from '../src/server/db/migrations/005_metrics_disks_indexes.js'; +import { + MAX_AUTO_DISCOVERED_MOUNTS, parseBsdOutput, parseLinuxOutput, parseMacOsOutput, @@ -253,4 +258,105 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () expect(history7d.granularity).toBe('1h'); expect(history7d.points.length).toBeGreaterThanOrEqual(1); }); + + it('deduplicates bind mounts, filters shared-host/container noise, caps auto-discovered mounts, and honors explicit filters', () => { + const bindLines = Array.from( + { length: 30 }, + (_, i) => `/dev/sda1 ext4 104857600 41943040 62914560 40% /home/virtfs/user${i + 1}/usr`, + ); + const nvmeLines = Array.from( + { length: 35 }, + (_, i) => `/dev/nvme0n1p${i + 1} ext4 ${10485760 + i * 1024} 5242880 5242880 50% /srv/vol${i + 1}`, + ); + + const sharedHostOut = [ + '===STAT===', + 'cpu 1000 0 200 8800 0 0 0 0 0 0', + '===MEM===', + 'MemTotal: 8192000 kB', + 'MemAvailable: 4096000 kB', + '===LOAD===', + '0.50 0.40 0.30 1/120 55', + '===UPTIME===', + '12000.00 24000.00', + '===NET===', + ' eth0: 1000 10 0 0 0 0 0 0 2000 10', + '===DF===', + 'Filesystem Type 1024-blocks Used Available Capacity Mounted on', + ...bindLines, + '/dev/sda1 ext4 104857600 41943040 62914560 40% /', + '/dev/loop0 ext4 102400 102400 0 100% /snap/core/1', + '/dev/sdb1 ext4 104857600 41943040 62914560 40% /var/lib/docker/overlay2/abc/merged', + '/dev/sdc1 ext4 104857600 41943040 62914560 40% /var/cagefs/u1', + 'lxcfs fuse.lxcfs 1024 0 1024 0% /proc/cpuinfo', + ...nvmeLines, + ].join('\n'); + + const autoParsed = parseLinuxOutput(sharedHostOut, undefined, undefined, 20_000); + expect(autoParsed.disks.length).toBe(MAX_AUTO_DISCOVERED_MOUNTS); + const mounts = autoParsed.disks.map((d) => d.mountPoint); + expect(mounts[0]).toBe('/'); + expect(mounts.some((m) => m.startsWith('/home/virtfs'))).toBe(false); + expect(mounts.some((m) => m.startsWith('/snap'))).toBe(false); + expect(mounts.some((m) => m.startsWith('/var/lib/docker'))).toBe(false); + expect(mounts.some((m) => m.startsWith('/var/cagefs'))).toBe(false); + expect(mounts.some((m) => m.startsWith('/proc'))).toBe(false); + + // Explicit filter overrides noisy-path suppression when user selects a specific mount + const filtered = parseLinuxOutput(sharedHostOut, undefined, ['/home/virtfs/user5/usr'], 20_000); + expect(filtered.disks.map((d) => d.mountPoint)).toEqual(['/home/virtfs/user5/usr']); + }); + + it('creates metric indexes in migration 005 and truncates runaway metrics_disks rows above threshold', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-mig005-test-')); + const db = openDatabase(path.join(dir, 'gcoord.db')); + cleanups.push(() => { + db.close(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + const indexes = ( + db + .prepare("SELECT name FROM sqlite_master WHERE type = 'index'") + .all() as Array<{ name: string }> + ).map((r) => r.name); + expect(indexes).toContain('idx_metrics_disks_server_ts'); + expect(indexes).toContain('idx_metrics_disks_ts'); + expect(indexes).toContain('idx_metrics_raw_ts'); + expect(indexes).toContain('idx_probe_results_ts'); + + // Below threshold: preserves existing metrics_disks rows + db.prepare( + 'INSERT 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(1000, 's1', 10, 100, 1000, 0, 0, 0.1, 60); + const insDisk = db.prepare( + 'INSERT INTO metrics_disks (ts, server_id, mount_point, fs_type, used_mb, total_mb, used_pct) VALUES (?, ?, ?, ?, ?, ?, ?)', + ); + for (let i = 0; i < 5; i++) { + insDisk.run(1000, 's1', `/m${i}`, 'ext4', 10, 100, 10); + } + migration005MetricsDisksIndexes.up(db); + expect( + (db.prepare('SELECT COUNT(*) AS n FROM metrics_disks').get() as { n: number }).n, + ).toBe(5); + + // Above threshold: truncates runaway metrics_disks while preserving metrics_raw + db.transaction(() => { + const target = RUNAWAY_METRICS_DISKS_THRESHOLD + 1; + for (let i = 5; i < target; i++) { + insDisk.run(2000 + Math.floor(i / 500), 's1', `/m${i}`, 'ext4', 10, 100, 10); + } + })(); + expect( + (db.prepare('SELECT COUNT(*) AS n FROM metrics_disks').get() as { n: number }).n, + ).toBe(RUNAWAY_METRICS_DISKS_THRESHOLD + 1); + + migration005MetricsDisksIndexes.up(db); + expect( + (db.prepare('SELECT COUNT(*) AS n FROM metrics_disks').get() as { n: number }).n, + ).toBe(0); + expect( + (db.prepare('SELECT COUNT(*) AS n FROM metrics_raw').get() as { n: number }).n, + ).toBe(1); + }); });