82 lines
6.4 KiB
JavaScript
82 lines
6.4 KiB
JavaScript
import { spawn, execFile } from 'node:child_process';
|
|
import { createHash } from 'node:crypto';
|
|
import { StringDecoder } from 'node:string_decoder';
|
|
import { readOwnedProcessTree } from './owned-process-tree.mjs';
|
|
|
|
// Both checks and dependency preparation use this direct, shell-free process
|
|
// owner. Callers choose fixed invocations and interpret their own evidence.
|
|
export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn = null, input = null, timeoutMs = 180000, unlimitedOutput = false, onOutput = null } = {}) {
|
|
const started = Date.now(), at = () => new Date().toISOString();
|
|
if (signal.aborted) return { status: 'cancelled', exitCode: null, durationMs: 0, stdout: '', stderr: '', process: null };
|
|
return new Promise(resolve => {
|
|
const child = spawn(invocation.executable, invocation.args, { cwd, env, windowsHide: true,
|
|
detached: process.platform !== 'win32', stdio: [input === null ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
|
|
const streams = Object.fromEntries(['stdout', 'stderr'].map(name => [name, { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') }]));
|
|
let settled = false, timedOut = false, terminating = false, killTimer, ownershipError = null, treeKill = null, closedResult = null, rootClosed = false, treeTimer = null, treePending = null;
|
|
const processInfo = { pid: child.pid ?? null, hostPid: process.pid, executable: invocation.executable,
|
|
argsSha256: createHash('sha256').update(JSON.stringify(invocation.args)).digest('hex'), cwd, startedAt: at() };
|
|
const append = (name, text) => { const value = streams[name]; value.characters += text.length;
|
|
value.head = unlimitedOutput ? value.head + text : (value.head + text).slice(0, 240000); value.tail = unlimitedOutput ? '' : (value.tail + text).slice(-240000);
|
|
if (onOutput && !settled) { try { onOutput(name, text); } catch (error) { ownershipError = error; terminate(); } }
|
|
};
|
|
const captured = name => { const value = streams[name]; return unlimitedOutput || value.characters <= 240000 ? value.head
|
|
: value.characters <= 480000 ? value.head + value.tail.slice(value.head.length - value.characters)
|
|
: value.head + '\n[中间日志超出保存上限,保留开头和结尾]\n' + value.tail; };
|
|
const captureTree = async (publish = true) => {
|
|
const snapshot = await readOwnedProcessTree(processInfo);
|
|
if (!snapshot.supported) return snapshot;
|
|
if (snapshot.root) processInfo.rootCreatedAt ??= snapshot.root.createdAt;
|
|
const known = new Map((processInfo.descendants ?? []).map(value => [value.pid + ':' + value.createdAt, value]));
|
|
for (const value of snapshot.processes) if (value.pid !== processInfo.pid) known.set(value.pid + ':' + value.createdAt, value);
|
|
processInfo.descendants = [...known.values()].sort((a, b) => a.pid - b.pid);
|
|
processInfo.treeObservedAt = at(); processInfo.treeRemainingPids = snapshot.processes.map(value => value.pid);
|
|
if (publish && !settled) onSpawn?.(processInfo);
|
|
return snapshot;
|
|
};
|
|
const monitorTree = () => { if (settled || treePending) return;
|
|
treePending = captureTree().catch(error => { ownershipError = error; processInfo.treeObservationError = error.message; terminate(); }).finally(() => { treePending = null; }); };
|
|
const finish = async (code, error, unknown = false) => {
|
|
if (onSpawn && terminating && treeKill && !treeKill.done && !unknown) { closedResult = { code, error }; return; }
|
|
if (onSpawn && treeKill?.error) unknown = true;
|
|
if (settled) return; settled = true; clearTimeout(timeout); clearTimeout(killTimer); clearInterval(treeTimer); signal.removeEventListener('abort', terminate);
|
|
if (onSpawn && process.platform === 'win32' && processInfo.pid) {
|
|
await treePending;
|
|
try { const snapshot = await captureTree(false); if (snapshot.processes.length) unknown = true; }
|
|
catch (failure) { ownershipError = failure; processInfo.treeObservationError = failure.message; unknown = true; }
|
|
}
|
|
resolve({ status: unknown ? 'unknown' : signal.aborted ? 'cancelled' : timedOut || error || ownershipError || code !== 0 ? 'failed' : 'passed',
|
|
exitCode: code, durationMs: Date.now() - started, stdout: captured('stdout'),
|
|
stderr: captured('stderr') + (error ? '\n' + error.message : '') + (ownershipError ? '\n' + ownershipError.message : ''),
|
|
timedOut, truncated: !unlimitedOutput && (streams.stdout.characters > 480000 || streams.stderr.characters > 480000),
|
|
...(onSpawn ? { process: { ...processInfo, rootExited: rootClosed, treeTermination: terminating ? unknown ? 'unknown' : 'confirmed' : 'not_requested' } } : {}),
|
|
reason: unknown ? '进程结束未得到确认,需要核对实际副作用。' : timedOut ? '命令超过时间上限,已请求终止所属进程树。' : error?.message ?? ownershipError?.message ?? null });
|
|
};
|
|
const terminate = () => {
|
|
if (settled || terminating) return; terminating = true;
|
|
if (child.pid) {
|
|
if (process.platform === 'win32') {
|
|
if (onSpawn) treeKill = { done: false, error: null };
|
|
execFile('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, error => {
|
|
if (!treeKill) return; treeKill.done = true; treeKill.error = error;
|
|
if (closedResult) void finish(closedResult.code, closedResult.error);
|
|
});
|
|
} else { try { process.kill(-child.pid, 'SIGTERM'); } catch { child.kill('SIGTERM'); } }
|
|
}
|
|
killTimer = setTimeout(() => { void finish(null, null, true); }, 5000);
|
|
};
|
|
const timeout = timeoutMs > 0 ? setTimeout(() => { timedOut = true; terminate(); }, timeoutMs) : null;
|
|
signal.addEventListener('abort', terminate, { once: true });
|
|
for (const name of ['stdout', 'stderr']) {
|
|
child[name].on('data', bytes => append(name, streams[name].decoder.write(bytes)));
|
|
child[name].on('end', () => append(name, streams[name].decoder.end()));
|
|
}
|
|
child.once('error', error => { void finish(null, error); }); child.once('close', code => { rootClosed = true; void finish(code); });
|
|
if (onSpawn) child.once('spawn', () => { processInfo.pid = child.pid;
|
|
try { onSpawn(processInfo); if (process.platform === 'win32') { monitorTree(); treeTimer = setInterval(monitorTree, 1200); } }
|
|
catch (error) { ownershipError = error; terminate(); }
|
|
});
|
|
if (input !== null) { child.stdin.on('error', () => {}); child.stdin.end(input); }
|
|
if (signal.aborted) terminate();
|
|
});
|
|
}
|