Run multi-target commands in parallel #75

Merged
jared merged 1 commits from parallel-targets into main 2026-11-23 13:15:19 -05:00
4 changed files with 63 additions and 33 deletions

No files matched your search

+1 -1
View File
@@ -354,7 +354,7 @@ A workflow is a JSON definition with a list of steps, created on the **Workflows
| Step type | Fields | What it does |
|---|---|---|
| `execute` | `command`, `targets` (`["all"]` or worker names/ids; default all), `condition`, `timeout` (seconds, 5 to 600), `retries` (0 to 5), `retryDelayMs` | Runs the command on each target; a failure fails the workflow |
| `execute` | `command`, `targets` (`["all"]` or worker names/ids; default all), `condition`, `timeout` (seconds, 5 to 600), `retries` (0 to 5), `retryDelayMs`, `parallel` (default true) | Runs the command on all targets at once (`parallel: false`: one after another, stopping at the first failure); a failure on any target fails the workflow |
| `parse` | `condition` | Reads `KEY=VALUE` lines (key in capitals) from the last command's output into `state.key` (lower case) |
| `route` | `conditions`: `[{ "if", "goto", "label" }, { "default": true, "goto" }]` | Jumps to the first matching condition's step |
| `prompt` | `message`, `options`, `key`, `routes` (`{ "<option>": "<step id>" }`) | Waits for someone to answer in the UI (up to 60 min, never past the execution's time limit). An unanswered prompt fails the workflow |
+7 -9
View File
@@ -248,21 +248,19 @@
return;
}
renderExecuting(workerIds.length);
const results = [];
let successCount = 0;
let failCount = 0;
for (const workerId of workerIds) {
// Send to every selected worker at once (#26); results keep the selection order.
const results = await Promise.all(workerIds.map(async (workerId) => {
const worker = _workers.find(w => w.id === workerId);
const workerLabel = worker ? worker.name : workerId;
try {
const data = await Pulse.api.post('/api/workers/' + encodeURIComponent(workerId) + '/command', { command });
results.push({ worker: workerLabel, success: true, executionId: data && data.execution_id });
successCount++;
return { worker: workerLabel, success: true, executionId: data && data.execution_id };
} catch (e) {
results.push({ worker: workerLabel, success: false, error: e.message || 'Failed to execute' });
failCount++;
return { worker: workerLabel, success: false, error: e.message || 'Failed to execute' };
}
}
}));
const successCount = results.filter(r => r.success).length;
const failCount = results.length - successCount;
addToHistory(command, workerIds.length + ' workers');
renderMultiResult(results, successCount, failCount);
if (failCount === 0) Pulse.beep('success');
+26 -23
View File
@@ -1263,13 +1263,17 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
return false;
}
// Execute command on each target worker and wait for results
const results = [];
let sentCount = 0;
// Per-step timeout override: step.timeout (seconds) overrides global default
const stepTimeoutMs = step.timeout
? Math.min(Math.max(parseInt(step.timeout, 10) * 1000, 5000), 600000)
: COMMAND_TIMEOUT_MS;
// Per-step retry: step.retries (default 0) with step.retryDelayMs (default 2000)
const maxRetries = Math.min(parseInt(step.retries || 0, 10), 5);
const retryDelayMs = Math.min(parseInt(step.retryDelayMs || 2000, 10), 30000);
for (const workerId of targetWorkerIds) {
// Runs the command on one worker (with retries): { sent, success }.
const runOnWorker = async (workerId) => {
const workerWs = workers.get(workerId);
if (!workerWs || workerWs.readyState !== WebSocket.OPEN) {
await addExecutionLog(executionId, {
step: stepNumber,
@@ -1277,13 +1281,10 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
worker_id: workerId,
timestamp: new Date().toISOString()
});
continue;
return { sent: false, success: false };
}
sentCount++;
// Send command to worker
let commandId = crypto.randomUUID();
await addExecutionLog(executionId, {
step: stepNumber,
action: 'command_sent',
@@ -1292,12 +1293,6 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
command_id: commandId,
timestamp: new Date().toISOString()
});
// Per-step timeout override: step.timeout (seconds) overrides global default
const stepTimeoutMs = step.timeout
? Math.min(Math.max(parseInt(step.timeout, 10) * 1000, 5000), 600000)
: COMMAND_TIMEOUT_MS;
sendCommandToWorker(workerWs, {
type: 'execute_command',
execution_id: executionId,
@@ -1307,10 +1302,6 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
timeout: stepTimeoutMs
});
// Per-step retry: step.retries (default 0) with step.retryDelayMs (default 2000)
const maxRetries = Math.min(parseInt(step.retries || 0, 10), 5);
const retryDelayMs = Math.min(parseInt(step.retryDelayMs || 2000, 10), 30000);
let result;
let attempt = 0;
while (true) {
@@ -1340,13 +1331,25 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
});
commandId = retryCommandId; // update for next waitForCommandResult call
}
results.push(result);
return { sent: true, success: !!result.success };
};
if (!result.success) {
// Command failed after all retries, workflow should stop
return false;
// All targets at once (#26), so one slow or hung worker doesn't hold up the
// rest. `parallel: false` keeps the old one-at-a-time order for rolling changes,
// stopping at the first failure.
let outcomes;
if (step.parallel === false) {
outcomes = [];
for (const workerId of targetWorkerIds) {
const o = await runOnWorker(workerId);
outcomes.push(o);
if (o.sent && !o.success) return false;
}
} else {
outcomes = await Promise.all(targetWorkerIds.map(runOnWorker));
if (outcomes.some(o => o.sent && !o.success)) return false;
}
const sentCount = outcomes.filter(o => o.sent).length;
// If every target worker was offline, treat as step failure
if (sentCount === 0) {
+29
View File
@@ -227,3 +227,32 @@ test('the execution list marks runs waiting on a prompt (#3)', async () => {
await waitForExecution(id);
expect((await row()).waiting_for_input).toBe(false);
});
test('a step runs on all its targets at once (#26)', async () => {
const t0 = Date.now();
const ex = await waitForExecution(await start(await createWorkflow([
{ id: 'slow', type: 'execute', command: 'sleep 2; echo done', targets: ['all'] },
])));
expect(ex.status).toBe('completed');
expect(outputs(ex).filter(o => o === 'done')).toHaveLength(3);
expect(Date.now() - t0).toBeLessThan(5500); // in sequence it would take 6 s or more
});
test('parallel: false runs the targets one after another (#26)', async () => {
const t0 = Date.now();
const ex = await waitForExecution(await start(await createWorkflow([
{ id: 'slow', type: 'execute', command: 'sleep 2; echo done', targets: ['all'], parallel: false },
])), { timeout: 30_000 });
expect(ex.status).toBe('completed');
expect(Date.now() - t0).toBeGreaterThanOrEqual(6000);
});
test('a failure on one target fails the step, after every target has reported (#26)', async () => {
const ex = await waitForExecution(await start(await createWorkflow([
{ id: 'one-bad', type: 'execute', command: 'test "$WORKER_NAME" != node-02 && echo ok', targets: ['all'] },
{ id: 'after', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
])));
expect(ex.status).toBe('failed');
expect(outputs(ex).filter(o => o === 'ok')).toHaveLength(2);
expect(outputs(ex)).not.toContain('should-not-run');
});