feat(automation): add Phase 4 DB meta migration, system/probe hooks, and TransferEngine
This commit is contained in:
parent
7dac3d1261
commit
55948591db
6 changed files with 665 additions and 43 deletions
451
src/server/automation/transfer-engine.ts
Normal file
451
src/server/automation/transfer-engine.ts
Normal file
|
|
@ -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<T>(
|
||||
fn: (cb: (err: Error | undefined | null, result: T) => void) => void,
|
||||
): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
fn((err, result) => {
|
||||
if (err) reject(err);
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function promisifySftpVoid(
|
||||
fn: (cb: (err?: Error | null) => void) => void,
|
||||
): Promise<void> {
|
||||
return new Promise<void>((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<TransferResult> {
|
||||
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<Stats>((cb) => srcSftp.stat(resolvedSrc, cb));
|
||||
let filesTransferred = 0;
|
||||
let bytesTransferred = 0;
|
||||
|
||||
if (isDirMode(srcStat.mode ?? 0)) {
|
||||
const dstStat = await promisifySftp<Stats>((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<Stats>((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<string> {
|
||||
const trimmed = requestedPath.trim();
|
||||
if (!trimmed || trimmed === '.' || trimmed === '~') {
|
||||
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
|
||||
return path.posix.normalize(home || '/');
|
||||
}
|
||||
if (trimmed.startsWith('~/')) {
|
||||
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
|
||||
return path.posix.normalize(path.posix.join(home || '/', trimmed.slice(2)));
|
||||
}
|
||||
if (!trimmed.startsWith('/')) {
|
||||
const home = await promisifySftp<string>((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<void> {
|
||||
const normalized = path.posix.normalize(dirPath);
|
||||
if (!normalized || normalized === '/' || normalized === '.') return;
|
||||
|
||||
const stat = await promisifySftp<Stats>((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<Stats>((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<FileEntryWithStats[]>((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<number> {
|
||||
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<void>((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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue