- worker: commands run with spawn in their own process group (same timeout, 10 MB output limit and result fields as exec). A new cancel_command message (by command_id, or every command of an execution) sends SIGTERM to the group, then SIGKILL after 5 s; the result reports cancelled: true. Old workers ignore the message. - server: the abort route sends cancel_command to the worker running each of the execution's commands. - Tests: the whole process tree dies on cancel (a background child too), execution-wide cancel leaves other executions alone, and end to end an aborted quick command's process is gone from the worker. Liveness checks treat zombies as dead (an orphan waits to be reaped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
347 lines
11 KiB
JavaScript
347 lines
11 KiB
JavaScript
const axios = require('axios');
|
|
const WebSocket = require('ws');
|
|
const { spawn } = require('child_process');
|
|
const os = require('os');
|
|
const crypto = require('crypto');
|
|
require('dotenv').config();
|
|
|
|
const MAX_OUTPUT = 10 * 1024 * 1024; // per stream, like exec's maxBuffer
|
|
const KILL_GRACE_MS = 5000; // SIGTERM, then SIGKILL after this
|
|
|
|
// Runs a shell command in its own process group, so a timeout or a cancel can stop
|
|
// the whole tree (sh and everything it started). Resolves with the outcome; the
|
|
// error message matches what child_process.exec reported.
|
|
function runCommand(command, { timeout = 300000, onSpawn } = {}) {
|
|
return new Promise(resolve => {
|
|
const child = spawn('/bin/sh', ['-c', command], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
let stdout = '';
|
|
let stderr = '';
|
|
let timedOut = false;
|
|
let cancelled = false;
|
|
let overflow = false;
|
|
let killTimer = null;
|
|
const kill = () => {
|
|
try { process.kill(-child.pid, 'SIGTERM'); } catch { /* already gone */ }
|
|
killTimer = setTimeout(() => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ } }, KILL_GRACE_MS);
|
|
killTimer.unref();
|
|
};
|
|
const collect = which => chunk => {
|
|
if (which === 'out') stdout += chunk; else stderr += chunk;
|
|
if (!overflow && (stdout.length > MAX_OUTPUT || stderr.length > MAX_OUTPUT)) { overflow = true; kill(); }
|
|
};
|
|
child.stdout.setEncoding('utf8').on('data', collect('out'));
|
|
child.stderr.setEncoding('utf8').on('data', collect('err'));
|
|
const timer = setTimeout(() => { timedOut = true; kill(); }, timeout);
|
|
if (onSpawn) onSpawn({ cancel: () => { cancelled = true; kill(); } });
|
|
child.on('error', err => {
|
|
clearTimeout(timer);
|
|
resolve({ ok: false, stdout, stderr, code: undefined, signal: undefined, timedOut, cancelled, message: err.message });
|
|
});
|
|
child.on('close', (code, signal) => {
|
|
clearTimeout(timer);
|
|
if (killTimer) clearTimeout(killTimer);
|
|
const ok = code === 0 && !timedOut && !cancelled && !overflow;
|
|
let message;
|
|
if (cancelled) message = 'Cancelled';
|
|
else if (overflow) message = 'Output exceeded 10 MB';
|
|
else if (!ok) message = `Command failed: ${command}\n${stderr}`;
|
|
resolve({ ok, stdout, stderr, code, signal: signal || undefined, timedOut, cancelled, message });
|
|
});
|
|
});
|
|
}
|
|
|
|
// The commit this worker runs (#40): the VERSION file written by
|
|
// deploy/pulse_worker_deploy.sh, or the git checkout it runs from.
|
|
function detectVersion(dir = __dirname) {
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
try {
|
|
const v = fs.readFileSync(path.join(dir, 'VERSION'), 'utf8').trim();
|
|
if (/^[0-9a-f]{40}$/.test(v)) return v;
|
|
} catch { /* no VERSION file */ }
|
|
try {
|
|
return require('child_process')
|
|
.execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
|
|
.toString().trim();
|
|
} catch {
|
|
return 'unknown';
|
|
}
|
|
}
|
|
|
|
class PulseWorker {
|
|
constructor() {
|
|
this.workerId = crypto.randomUUID();
|
|
this.workerName = process.env.WORKER_NAME || os.hostname();
|
|
this.serverUrl = process.env.PULSE_SERVER || 'http://localhost:8080';
|
|
this.wsUrl = process.env.PULSE_WS || 'ws://localhost:8080';
|
|
this.apiKey = process.env.WORKER_API_KEY;
|
|
this.heartbeatInterval = parseInt(process.env.HEARTBEAT_INTERVAL || '30') * 1000;
|
|
this.maxConcurrentTasks = parseInt(process.env.MAX_CONCURRENT_TASKS || '5');
|
|
this.version = detectVersion();
|
|
this.activeTasks = 0;
|
|
this.running = new Map(); // command_id (or execution_id) -> { execution_id, cancel }
|
|
this.ws = null;
|
|
this.heartbeatTimer = null;
|
|
}
|
|
|
|
async start() {
|
|
console.log(`[PULSE Worker] Starting worker: ${this.workerName}`);
|
|
console.log(`[PULSE Worker] Worker ID: ${this.workerId}`);
|
|
console.log(`[PULSE Worker] Version: ${this.version}`);
|
|
console.log(`[PULSE Worker] Server: ${this.serverUrl}`);
|
|
|
|
// Send initial heartbeat
|
|
await this.sendHeartbeat();
|
|
|
|
// Start heartbeat timer
|
|
this.startHeartbeat();
|
|
|
|
// Connect to WebSocket for real-time commands
|
|
this.connectWebSocket();
|
|
|
|
console.log(`[PULSE Worker] Worker started successfully`);
|
|
}
|
|
|
|
startHeartbeat() {
|
|
this.heartbeatTimer = setInterval(async () => {
|
|
try {
|
|
await this.sendHeartbeat();
|
|
} catch (error) {
|
|
console.error('[PULSE Worker] Heartbeat failed:', error.message);
|
|
}
|
|
}, this.heartbeatInterval);
|
|
}
|
|
|
|
async sendHeartbeat() {
|
|
const metadata = {
|
|
hostname: os.hostname(),
|
|
platform: os.platform(),
|
|
arch: os.arch(),
|
|
cpus: os.cpus().length,
|
|
totalMem: os.totalmem(),
|
|
freeMem: os.freemem(),
|
|
uptime: os.uptime(),
|
|
loadavg: os.loadavg(),
|
|
activeTasks: this.activeTasks,
|
|
maxConcurrentTasks: this.maxConcurrentTasks,
|
|
version: this.version
|
|
};
|
|
|
|
try {
|
|
const response = await axios.post(
|
|
`${this.serverUrl}/api/workers/heartbeat`,
|
|
{
|
|
worker_id: this.workerId,
|
|
name: this.workerName,
|
|
metadata: metadata
|
|
},
|
|
{
|
|
headers: {
|
|
'X-API-Key': this.apiKey,
|
|
'Content-Type': 'application/json'
|
|
}
|
|
}
|
|
);
|
|
|
|
console.log(`[PULSE Worker] Heartbeat sent - Status: online`);
|
|
return response.data;
|
|
} catch (error) {
|
|
console.error('[PULSE Worker] Heartbeat error:', error.message);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
connectWebSocket() {
|
|
console.log(`[PULSE Worker] Connecting to WebSocket...`);
|
|
|
|
// The server authenticates the WebSocket upgrade with the worker key (issue #38).
|
|
const headers = this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {};
|
|
this.ws = new WebSocket(this.wsUrl, { headers });
|
|
|
|
this.ws.on('open', () => {
|
|
console.log('[PULSE Worker] WebSocket connected');
|
|
// Identify this worker
|
|
this.ws.send(JSON.stringify({
|
|
type: 'worker_connect',
|
|
worker_id: this.workerId,
|
|
worker_name: this.workerName,
|
|
api_key: this.apiKey,
|
|
version: this.version
|
|
}));
|
|
});
|
|
|
|
this.ws.on('message', async (data) => {
|
|
try {
|
|
const message = JSON.parse(data.toString());
|
|
await this.handleMessage(message);
|
|
} catch (error) {
|
|
console.error('[PULSE Worker] Message handling error:', error);
|
|
}
|
|
});
|
|
|
|
this.ws.on('close', () => {
|
|
console.log('[PULSE Worker] WebSocket disconnected, reconnecting...');
|
|
setTimeout(() => this.connectWebSocket(), 5000);
|
|
});
|
|
|
|
this.ws.on('error', (error) => {
|
|
console.error('[PULSE Worker] WebSocket error:', error.message);
|
|
});
|
|
}
|
|
|
|
async handleMessage(message) {
|
|
console.log(`[PULSE Worker] Received message:`, message.type);
|
|
|
|
switch (message.type) {
|
|
case 'execute_command':
|
|
await this.executeCommand(message);
|
|
break;
|
|
case 'execute_workflow':
|
|
await this.executeWorkflow(message);
|
|
break;
|
|
case 'cancel_command':
|
|
this.cancelCommand(message);
|
|
break;
|
|
case 'ping':
|
|
this.sendPong();
|
|
break;
|
|
default:
|
|
console.log(`[PULSE Worker] Unknown message type: ${message.type}`);
|
|
}
|
|
}
|
|
|
|
async executeCommand(message) {
|
|
const { command, execution_id, command_id, timeout = 300000 } = message;
|
|
|
|
if (this.activeTasks >= this.maxConcurrentTasks) {
|
|
console.log(`[PULSE Worker] Max concurrent tasks reached, rejecting command`);
|
|
// Tell the server, or the execution would wait for a result that never comes (#7).
|
|
this.sendResult({
|
|
type: 'command_result',
|
|
execution_id,
|
|
worker_id: this.workerId,
|
|
command_id,
|
|
success: false,
|
|
error: `Worker at capacity (${this.maxConcurrentTasks} commands already running)`,
|
|
stdout: '',
|
|
stderr: '',
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
return;
|
|
}
|
|
|
|
this.activeTasks++;
|
|
console.log(`[PULSE Worker] Executing command (active tasks: ${this.activeTasks})`);
|
|
const key = command_id || execution_id;
|
|
const startTime = Date.now();
|
|
try {
|
|
const r = await runCommand(command, {
|
|
timeout,
|
|
onSpawn: handle => this.running.set(key, { execution_id, ...handle }),
|
|
});
|
|
const duration = Date.now() - startTime;
|
|
const base = { type: 'command_result', execution_id, worker_id: this.workerId, command_id, timestamp: new Date().toISOString() };
|
|
if (r.ok) {
|
|
this.sendResult({ ...base, success: true, stdout: r.stdout, stderr: r.stderr, duration });
|
|
console.log(`[PULSE Worker] Command completed in ${duration}ms`);
|
|
} else {
|
|
this.sendResult({
|
|
...base,
|
|
success: false,
|
|
error: r.message,
|
|
exit_code: typeof r.code === 'number' ? r.code : undefined,
|
|
signal: r.signal,
|
|
timed_out: r.timedOut || undefined,
|
|
cancelled: r.cancelled || undefined,
|
|
stdout: r.stdout,
|
|
stderr: r.stderr,
|
|
});
|
|
console.error('[PULSE Worker] Command failed:', r.message.split('\n')[0]);
|
|
}
|
|
} finally {
|
|
this.running.delete(key);
|
|
this.activeTasks--;
|
|
}
|
|
}
|
|
|
|
// Stops a running command and everything it started (#8): by command_id, or every
|
|
// command of an execution. Its result is then reported with cancelled: true.
|
|
cancelCommand(message) {
|
|
const { execution_id, command_id } = message;
|
|
let n = 0;
|
|
for (const [key, run] of this.running) {
|
|
if ((command_id && key === command_id) || (!command_id && run.execution_id === execution_id)) {
|
|
run.cancel();
|
|
n++;
|
|
}
|
|
}
|
|
console.log(`[PULSE Worker] Cancel for ${command_id || execution_id}: ${n} command(s) stopped`);
|
|
}
|
|
|
|
async executeWorkflow(message) {
|
|
const { workflow, execution_id } = message;
|
|
|
|
console.log(`[PULSE Worker] Executing workflow: ${workflow.name}`);
|
|
|
|
// Workflow execution will be implemented in phase 2
|
|
// For now, just acknowledge receipt
|
|
this.sendResult({
|
|
type: 'workflow_result',
|
|
execution_id,
|
|
worker_id: this.workerId,
|
|
success: true,
|
|
message: 'Workflow execution not yet implemented',
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
}
|
|
|
|
sendResult(result) {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify(result));
|
|
}
|
|
}
|
|
|
|
sendPong() {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify({ type: 'pong', worker_id: this.workerId }));
|
|
}
|
|
}
|
|
|
|
async stop() {
|
|
console.log('[PULSE Worker] Shutting down...');
|
|
|
|
if (this.heartbeatTimer) {
|
|
clearInterval(this.heartbeatTimer);
|
|
}
|
|
|
|
if (this.ws) {
|
|
this.ws.close();
|
|
}
|
|
|
|
console.log('[PULSE Worker] Shutdown complete');
|
|
}
|
|
}
|
|
|
|
module.exports = { PulseWorker, detectVersion, runCommand };
|
|
|
|
// Start only when run directly (node worker.js), so tests can load the class.
|
|
if (require.main === module) {
|
|
const worker = new PulseWorker();
|
|
|
|
// Handle graceful shutdown
|
|
process.on('SIGTERM', async () => {
|
|
await worker.stop();
|
|
process.exit(0);
|
|
});
|
|
|
|
process.on('SIGINT', async () => {
|
|
await worker.stop();
|
|
process.exit(0);
|
|
});
|
|
|
|
worker.start().catch((error) => {
|
|
console.error('[PULSE Worker] Fatal error:', error);
|
|
process.exit(1);
|
|
});
|
|
}
|