From 55948591dbed1e25f982ee7a3cf0f9d3233efc83 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 06:10:46 +0000 Subject: [PATCH] feat(automation): add Phase 4 DB meta migration, system/probe hooks, and TransferEngine --- src/server/automation/transfer-engine.ts | 451 ++++++++++++++++++++ src/server/db/database.ts | 7 +- src/server/db/migrations/003_phase4_meta.ts | 13 + src/server/monitoring/monitoring-service.ts | 20 + src/server/systems/systems-engine.ts | 207 +++++++-- src/shared/ws-protocol.ts | 10 + 6 files changed, 665 insertions(+), 43 deletions(-) create mode 100644 src/server/automation/transfer-engine.ts create mode 100644 src/server/db/migrations/003_phase4_meta.ts diff --git a/src/server/automation/transfer-engine.ts b/src/server/automation/transfer-engine.ts new file mode 100644 index 0000000..e913f3e --- /dev/null +++ b/src/server/automation/transfer-engine.ts @@ -0,0 +1,451 @@ +import crypto from 'node:crypto'; +import path from 'node:path'; +import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { SftpService } from '../ssh/sftp-service.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { posixSingleQuote } from '../ssh/sudo.js'; + +export interface TransferResult { + mode: 'hub-relayed' | 'direct'; + sourcePath: string; + destinationPath: string; + filesTransferred: number; + bytesTransferred: number; + durationMs: number; +} + +function isDirMode(mode: number): boolean { + return (mode & 0o170000) === 0o040000; +} + +function promisifySftp( + fn: (cb: (err: Error | undefined | null, result: T) => void) => void, +): Promise { + return new Promise((resolve, reject) => { + fn((err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); +} + +function promisifySftpVoid( + fn: (cb: (err?: Error | null) => void) => void, +): Promise { + return new Promise((resolve, reject) => { + fn((err) => { + if (err) reject(err); + else resolve(); + }); + }); +} + +export class TransferEngine { + constructor( + private readonly sshPool: SSHPool, + private readonly _sftpService: SftpService, + private readonly configManager: ConfigManager, + ) { + void this._sftpService; + } + + async transfer(opts: { + mode: 'hub-relayed' | 'direct'; + source: { serverId: string; path: string }; + destination: { serverId: string; path: string }; + sudo?: boolean; + timeoutMs?: number; + signal?: AbortSignal; + onProgress?: (msg: string) => void; + }): Promise { + if (opts.signal?.aborted) { + throw new Error('Transfer cancelled before start'); + } + + const srcServer = this.configManager.getServer(opts.source.serverId); + const dstServer = this.configManager.getServer(opts.destination.serverId); + if (!srcServer || !srcServer.enabled) { + throw new Error(`Source server "${opts.source.serverId}" not found or disabled`); + } + if (!dstServer || !dstServer.enabled) { + throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`); + } + + const started = Date.now(); + const timeoutMs = opts.timeoutMs ?? 600_000; + + if (opts.mode === 'direct') { + const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; + const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`; + opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`); + + const handle = await this.sshPool.execStream(srcServer.id, cmd, { + sudo: opts.sudo, + }); + + const errBuf: Buffer[] = []; + let errLen = 0; + handle.channel.stderr?.on('data', (chunk: Buffer) => { + if (errLen < 16_384) { + errBuf.push(chunk); + errLen += chunk.length; + } + opts.onProgress?.(chunk.toString('utf8')); + }); + + const result = await new Promise<{ exitCode: number | null }>((resolve, reject) => { + let settled = false; + const cleanup = () => { + if (timer) clearTimeout(timer); + if (opts.signal && onAbort) { + opts.signal.removeEventListener('abort', onAbort); + } + }; + const timer = setTimeout(() => { + handle.abort(); + if (!settled) { + settled = true; + cleanup(); + reject(new Error(`Direct transfer timed out after ${timeoutMs}ms`)); + } + }, timeoutMs); + timer.unref(); + + const onAbort = () => { + handle.abort(); + if (!settled) { + settled = true; + cleanup(); + reject(new Error('Direct transfer cancelled')); + } + }; + if (opts.signal) { + if (opts.signal.aborted) { + onAbort(); + return; + } + opts.signal.addEventListener('abort', onAbort, { once: true }); + } + + handle.done + .then((res) => { + if (!settled) { + settled = true; + cleanup(); + resolve(res); + } + }) + .catch((err) => { + if (!settled) { + settled = true; + cleanup(); + reject(err); + } + }); + }); + + if (result.exitCode !== 0) { + const stderr = Buffer.concat(errBuf).toString('utf8').trim(); + throw new Error( + `Direct rsync failed (exit=${result.exitCode})${stderr ? `: ${stderr}` : ''}`, + ); + } + + return { + mode: 'direct', + sourcePath: opts.source.path, + destinationPath: opts.destination.path, + filesTransferred: 1, + bytesTransferred: 0, + durationMs: Date.now() - started, + }; + } + + // hub-relayed SFTP stream + const srcSftp = await this.sshPool.openSftp(srcServer.id); + let dstSftp: SFTPWrapper | null = null; + try { + dstSftp = await this.sshPool.openSftp(dstServer.id); + } catch (err) { + try { + srcSftp.end(); + } catch { + // Ignore + } + throw err; + } + + const activeStreams = new Set<{ destroy: () => void }>(); + let timedOutOrAborted: Error | null = null; + const cancelAll = (err: Error) => { + if (!timedOutOrAborted) timedOutOrAborted = err; + for (const s of activeStreams) { + try { + s.destroy(); + } catch { + // Ignore destroy errors + } + } + }; + + const timer = setTimeout(() => { + cancelAll(new Error(`Hub-relayed SFTP transfer timed out after ${timeoutMs}ms`)); + }, timeoutMs); + timer.unref(); + + const onAbort = () => cancelAll(new Error('Hub-relayed SFTP transfer cancelled')); + opts.signal?.addEventListener('abort', onAbort, { once: true }); + + try { + const trimmedDest = opts.destination.path.trim(); + const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/'); + const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path); + const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path); + + const srcStat = await promisifySftp((cb) => srcSftp.stat(resolvedSrc, cb)); + let filesTransferred = 0; + let bytesTransferred = 0; + + if (isDirMode(srcStat.mode ?? 0)) { + const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( + () => null, + ); + const targetDir = + destEndsWithSlash && dstStat && isDirMode(dstStat.mode ?? 0) + ? path.posix.join(resolvedDest, path.posix.basename(resolvedSrc)) + : resolvedDest; + + const counts = await this.copyDirectoryRecursive( + srcSftp, + dstSftp, + resolvedSrc, + targetDir, + activeStreams, + () => timedOutOrAborted, + opts.onProgress, + ); + filesTransferred = counts.files; + bytesTransferred = counts.bytes; + + return { + mode: 'hub-relayed', + sourcePath: resolvedSrc, + destinationPath: targetDir, + filesTransferred, + bytesTransferred, + durationMs: Date.now() - started, + }; + } + + const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( + () => null, + ); + const targetFile = + destEndsWithSlash || (dstStat !== null && isDirMode(dstStat.mode ?? 0)) + ? path.posix.join(resolvedDest, path.posix.basename(resolvedSrc)) + : resolvedDest; + + bytesTransferred = await this.copySingleFile( + srcSftp, + dstSftp, + resolvedSrc, + targetFile, + srcStat.mode ?? 0o644, + activeStreams, + () => timedOutOrAborted, + opts.onProgress, + ); + filesTransferred = 1; + + return { + mode: 'hub-relayed', + sourcePath: resolvedSrc, + destinationPath: targetFile, + filesTransferred, + bytesTransferred, + durationMs: Date.now() - started, + }; + } finally { + clearTimeout(timer); + opts.signal?.removeEventListener('abort', onAbort); + for (const s of activeStreams) { + try { + s.destroy(); + } catch { + // Ignore + } + } + try { + srcSftp.end(); + } catch { + // Ignore + } + try { + dstSftp.end(); + } catch { + // Ignore + } + } + } + + private async resolveRemotePath(sftp: SFTPWrapper, requestedPath: string): Promise { + const trimmed = requestedPath.trim(); + if (!trimmed || trimmed === '.' || trimmed === '~') { + const home = await promisifySftp((cb) => sftp.realpath('.', cb)); + return path.posix.normalize(home || '/'); + } + if (trimmed.startsWith('~/')) { + const home = await promisifySftp((cb) => sftp.realpath('.', cb)); + return path.posix.normalize(path.posix.join(home || '/', trimmed.slice(2))); + } + if (!trimmed.startsWith('/')) { + const home = await promisifySftp((cb) => sftp.realpath('.', cb)); + return path.posix.normalize(path.posix.join(home || '/', trimmed)); + } + return path.posix.normalize(trimmed); + } + + private async ensureRemoteDir(sftp: SFTPWrapper, dirPath: string): Promise { + const normalized = path.posix.normalize(dirPath); + if (!normalized || normalized === '/' || normalized === '.') return; + + const stat = await promisifySftp((cb) => sftp.stat(normalized, cb)).catch(() => null); + if (stat) return; + + await this.ensureRemoteDir(sftp, path.posix.dirname(normalized)); + await promisifySftpVoid((cb) => sftp.mkdir(normalized, cb)).catch(async (err) => { + const again = await promisifySftp((cb) => sftp.stat(normalized, cb)).catch(() => null); + if (!again) throw err; + }); + } + + private async copyDirectoryRecursive( + srcSftp: SFTPWrapper, + dstSftp: SFTPWrapper, + srcDir: string, + dstDir: string, + activeStreams: Set<{ destroy: () => void }>, + getCancelError: () => Error | null, + onProgress?: (msg: string) => void, + ): Promise<{ files: number; bytes: number }> { + const cancelErr = getCancelError(); + if (cancelErr) throw cancelErr; + + await this.ensureRemoteDir(dstSftp, dstDir); + const entries = await promisifySftp((cb) => srcSftp.readdir(srcDir, cb)); + + let files = 0; + let bytes = 0; + for (const entry of entries) { + if (entry.filename === '.' || entry.filename === '..') continue; + const srcChild = path.posix.join(srcDir, entry.filename); + const dstChild = path.posix.join(dstDir, entry.filename); + const mode = entry.attrs.mode ?? 0; + + if (isDirMode(mode)) { + const sub = await this.copyDirectoryRecursive( + srcSftp, + dstSftp, + srcChild, + dstChild, + activeStreams, + getCancelError, + onProgress, + ); + files += sub.files; + bytes += sub.bytes; + } else { + const copied = await this.copySingleFile( + srcSftp, + dstSftp, + srcChild, + dstChild, + mode || 0o644, + activeStreams, + getCancelError, + onProgress, + ); + files += 1; + bytes += copied; + } + } + return { files, bytes }; + } + + private async copySingleFile( + srcSftp: SFTPWrapper, + dstSftp: SFTPWrapper, + srcFile: string, + dstFile: string, + srcMode: number, + activeStreams: Set<{ destroy: () => void }>, + getCancelError: () => Error | null, + onProgress?: (msg: string) => void, + ): Promise { + const cancelErr = getCancelError(); + if (cancelErr) throw cancelErr; + + const dstDir = path.posix.dirname(dstFile); + await this.ensureRemoteDir(dstSftp, dstDir); + const tmpFile = path.posix.join( + dstDir, + `.gcoord-xfer-${crypto.randomBytes(6).toString('hex')}`, + ); + onProgress?.(`Relaying ${srcFile} -> ${dstFile}`); + + const readStream = srcSftp.createReadStream(srcFile); + const writeStream = dstSftp.createWriteStream(tmpFile); + activeStreams.add(readStream); + activeStreams.add(writeStream); + + let bytes = 0; + try { + await new Promise((resolve, reject) => { + let settled = false; + const fail = (err: Error) => { + if (settled) return; + settled = true; + readStream.destroy(); + writeStream.destroy(); + reject(getCancelError() ?? err); + }; + + readStream.on('data', (chunk: Buffer) => { + bytes += chunk.length; + }); + readStream.on('error', fail); + writeStream.on('error', fail); + writeStream.on('close', () => { + if (settled) return; + settled = true; + const ce = getCancelError(); + if (ce) reject(ce); + else resolve(); + }); + + readStream.pipe(writeStream); + }); + + const perm = srcMode & 0o7777; + if (perm > 0) { + await promisifySftpVoid((cb) => dstSftp.chmod(tmpFile, perm, cb)).catch(() => undefined); + } + + try { + await promisifySftpVoid((cb) => dstSftp.ext_openssh_rename(tmpFile, dstFile, cb)); + } catch { + await promisifySftpVoid((cb) => dstSftp.unlink(dstFile, cb)).catch(() => undefined); + await promisifySftpVoid((cb) => dstSftp.rename(tmpFile, dstFile, cb)); + } + + return bytes; + } catch (err) { + await promisifySftpVoid((cb) => dstSftp.unlink(tmpFile, cb)).catch(() => undefined); + throw err; + } finally { + activeStreams.delete(readStream); + activeStreams.delete(writeStream); + } + } +} diff --git a/src/server/db/database.ts b/src/server/db/database.ts index d52c6eb..0e1fedc 100644 --- a/src/server/db/database.ts +++ b/src/server/db/database.ts @@ -3,8 +3,13 @@ import path from 'node:path'; import Database from 'better-sqlite3'; 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'; -const MIGRATIONS: Migration[] = [migration001Initial, migration002MultiAuth]; +const MIGRATIONS: Migration[] = [ + migration001Initial, + migration002MultiAuth, + migration003Phase4Meta, +]; export function openDatabase(dbPath: string): Database.Database { fs.mkdirSync(path.dirname(dbPath), { recursive: true }); diff --git a/src/server/db/migrations/003_phase4_meta.ts b/src/server/db/migrations/003_phase4_meta.ts new file mode 100644 index 0000000..d0440c7 --- /dev/null +++ b/src/server/db/migrations/003_phase4_meta.ts @@ -0,0 +1,13 @@ +import type Database from 'better-sqlite3'; +import type { Migration } from './001_initial.js'; + +export const migration003Phase4Meta: Migration = { + id: '003_phase4_meta', + up(db: Database.Database) { + db.exec(` + ALTER TABLE workflow_runs ADD COLUMN inputs_json TEXT; + ALTER TABLE alert_events ADD COLUMN incident_key TEXT; + CREATE INDEX IF NOT EXISTS idx_alert_events_state ON alert_events(state); + `); + }, +}; diff --git a/src/server/monitoring/monitoring-service.ts b/src/server/monitoring/monitoring-service.ts index 87ff228..1a69daa 100644 --- a/src/server/monitoring/monitoring-service.ts +++ b/src/server/monitoring/monitoring-service.ts @@ -49,6 +49,9 @@ export class MonitoringService { private readonly osCache = new Map(); private readonly latest = new Map(); private readonly tickListeners = new Set<(event: MonitoringTickEvent) => void>(); + private readonly probeListeners = new Set< + (event: { serverId: string; probe: ProbeSample }) => void + >(); private maintenanceTimer: NodeJS.Timeout | null = null; private stopped = false; @@ -67,6 +70,15 @@ export class MonitoringService { }; } + onProbe( + listener: (event: { serverId: string; probe: ProbeSample }) => void, + ): () => void { + this.probeListeners.add(listener); + return () => { + this.probeListeners.delete(listener); + }; + } + start(): void { this.stopped = false; this.hydrateLatestFromDb(); @@ -410,6 +422,14 @@ export class MonitoringService { }; prevLatest.probes[probe.id] = sample; this.latest.set(server.id, prevLatest); + + for (const listener of this.probeListeners) { + try { + listener({ serverId: server.id, probe: sample }); + } catch { + // Isolate probe listener errors + } + } } private hydrateLatestFromDb(): void { diff --git a/src/server/systems/systems-engine.ts b/src/server/systems/systems-engine.ts index a709d83..b6ff48a 100644 --- a/src/server/systems/systems-engine.ts +++ b/src/server/systems/systems-engine.ts @@ -265,6 +265,169 @@ export class CustomSystemsEngine { } } + private resolveActionContext(params: { + serverId: string; + systemId: string; + actionId: string; + itemName?: string; + subItemName?: string; + }) { + return (async () => { + const system = this.configManager.getSystem(params.systemId); + const server = this.configManager.getServer(params.serverId); + if (!system || !server) { + throw new Error(`Unknown server "${params.serverId}" or system "${params.systemId}"`); + } + const attachment = server.systems.find((a) => a.systemId === system.id); + if (!attachment) { + throw new Error(`System "${system.id}" is not attached to server "${server.id}"`); + } + const action = system.actions.find((a) => a.id === params.actionId); + if (!action) { + throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`); + } + + const resolvedParams = this.resolveParams(system, attachment.params); + let item: DiscoveredSystemItem | undefined; + + if (action.scope === 'item' || action.scope === 'subitem') { + if (!params.itemName) { + throw new Error(`Action "${action.id}" requires itemName`); + } + const snap = await this.getServerSystem(server.id, system.id); + item = snap.items.find((i) => i.name === params.itemName); + if (!item) { + throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); + } + if (action.scope === 'subitem' && !params.subItemName) { + throw new Error(`Action "${action.id}" requires subItemName`); + } + } + + const env = this.buildExecutionEnv( + server.id, + system.id, + resolvedParams, + item, + params.subItemName, + ); + + const execCmd = item?.dir + ? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}` + : action.command; + + return { system, server, action, item, env, execCmd }; + })(); + } + + async executeActionBlocking(params: { + serverId: string; + systemId: string; + actionId: string; + itemName?: string; + subItemName?: string; + timeoutMs?: number; + signal?: AbortSignal; + onChunk?: (stream: 'stdout' | 'stderr', text: string) => void; + }): Promise<{ + exitCode: number | null; + stdout: string; + stderr: string; + durationMs: number; + }> { + if (params.signal?.aborted) { + throw new Error('System action cancelled before start'); + } + + const { system, server, action, env, execCmd } = await this.resolveActionContext(params); + if (action.mode === 'interactive') { + throw new Error('Interactive PTY actions cannot run unattended in workflows'); + } + + const timeoutMs = params.timeoutMs ?? 300_000; + const started = Date.now(); + const handle = await this.sshPool.execStream(server.id, execCmd, { + env, + sudo: action.sudo, + }); + + const maxBytes = 256 * 1024; + const outChunks: Buffer[] = []; + const errChunks: Buffer[] = []; + let outBytes = 0; + let errBytes = 0; + + return new Promise((resolve, reject) => { + let settled = false; + const cleanup = () => { + if (timer) clearTimeout(timer); + if (params.signal && onAbort) { + params.signal.removeEventListener('abort', onAbort); + } + this.invalidateCache(server.id, system.id); + }; + + const fail = (err: Error) => { + if (settled) return; + settled = true; + cleanup(); + reject(err); + }; + + const timer = setTimeout(() => { + handle.abort(); + fail(new Error(`System action "${action.id}" timed out after ${timeoutMs}ms`)); + }, timeoutMs); + timer.unref(); + + const onAbort = () => { + handle.abort(); + fail(new Error(`System action "${action.id}" cancelled`)); + }; + if (params.signal) { + if (params.signal.aborted) { + onAbort(); + return; + } + params.signal.addEventListener('abort', onAbort, { once: true }); + } + + handle.channel.on('data', (chunk: Buffer) => { + if (outBytes < maxBytes) { + const slice = chunk.subarray(0, maxBytes - outBytes); + outChunks.push(slice); + outBytes += slice.length; + } + params.onChunk?.('stdout', chunk.toString('utf8')); + }); + + handle.channel.stderr?.on('data', (chunk: Buffer) => { + if (errBytes < maxBytes) { + const slice = chunk.subarray(0, maxBytes - errBytes); + errChunks.push(slice); + errBytes += slice.length; + } + params.onChunk?.('stderr', chunk.toString('utf8')); + }); + + void handle.done + .then(({ exitCode }) => { + if (settled) return; + settled = true; + cleanup(); + resolve({ + exitCode, + stdout: Buffer.concat(outChunks).toString('utf8'), + stderr: Buffer.concat(errChunks).toString('utf8'), + durationMs: Date.now() - started, + }); + }) + .catch((err) => { + fail(err instanceof Error ? err : new Error(String(err))); + }); + }); + } + async executeAction(params: { serverId: string; systemId: string; @@ -274,48 +437,8 @@ export class CustomSystemsEngine { cols?: number; rows?: number; }): Promise { - const system = this.configManager.getSystem(params.systemId); - const server = this.configManager.getServer(params.serverId); - if (!system || !server) { - throw new Error(`Unknown server "${params.serverId}" or system "${params.systemId}"`); - } - const attachment = server.systems.find((a) => a.systemId === system.id); - if (!attachment) { - throw new Error(`System "${system.id}" is not attached to server "${server.id}"`); - } - const action = system.actions.find((a) => a.id === params.actionId); - if (!action) { - throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`); - } - - const resolvedParams = this.resolveParams(system, attachment.params); - let item: DiscoveredSystemItem | undefined; - - if (action.scope === 'item' || action.scope === 'subitem') { - if (!params.itemName) { - throw new Error(`Action "${action.id}" requires itemName`); - } - const snap = await this.getServerSystem(server.id, system.id); - item = snap.items.find((i) => i.name === params.itemName); - if (!item) { - throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); - } - if (action.scope === 'subitem' && !params.subItemName) { - throw new Error(`Action "${action.id}" requires subItemName`); - } - } - - const env = this.buildExecutionEnv( - server.id, - system.id, - resolvedParams, - item, - params.subItemName, - ); - - const execCmd = item?.dir - ? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}` - : action.command; + const { system, server, action, item, env, execCmd } = + await this.resolveActionContext(params); if (action.mode === 'oneshot') { const res = await this.sshPool.exec(server.id, execCmd, { diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts index 7143633..66a596e 100644 --- a/src/shared/ws-protocol.ts +++ b/src/shared/ws-protocol.ts @@ -168,12 +168,22 @@ export type ServerWsFrame = event?: AlertEventSummary; hostKeyMismatch?: HostKeyAlert; } + | { + type: 'workflow:run'; + runId: string; + workflowId: string; + status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'skipped'; + triggerSource: string; + startedAt: number; + finishedAt?: number | null; + } | { type: 'ai:delta'; chatId: string; chunk: string; done?: boolean; error?: string }; export const WS_CHANNELS = { METRICS: 'metrics', ALERTS: 'alerts', CONFIG: 'config', + WORKFLOWS: 'workflows', pty: (sessionId: string) => `pty:${sessionId}`, stream: (jobId: string) => `stream:${jobId}`, ai: (chatId: string) => `ai:${chatId}`,