Integration tests for the workflow engine and the scheduler #59
No files matched your search
@@ -608,6 +608,11 @@ use it: Gandalf's submit-and-poll contract (`/api/internal/command`, `/api/inter
|
||||
SSO and worker-key auth on HTTP and on the WebSocket upgrade, forged results from a browser socket,
|
||||
and that executions always finish (a worker killed mid-command, a worker at capacity, an abort
|
||||
followed by a late result). Tests that need to kill or limit a worker start their own.
|
||||
The workflow engine (execute, parse, route, prompt, params, dry run, loop detection, abort) and the
|
||||
scheduler are covered too; the scheduler tests make a schedule due by setting `next_run` in the
|
||||
database, and the stack ticks the scheduler every second (`PULSE_SCHEDULER_TICK_MS`). Known bugs are
|
||||
written as `test.failing` with their issue number: when a fix lands, the test starts failing until
|
||||
the marker is removed.
|
||||
|
||||
```bash
|
||||
DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=... DB_NAME=pulse scripts/ci/ui-stack.sh start
|
||||
|
||||
@@ -25,6 +25,7 @@ export WORKER_API_KEY=ui-test-worker-key WORKER_AUTH_ENFORCE=1
|
||||
export GANDALF_API_KEY=ui-test-gandalf-key
|
||||
export SECRET_KEY=ui-test-secret EXECUTION_RETENTION_DAYS=30
|
||||
export PULSE_API_RATE_MAX=100000 PULSE_EXEC_RATE_MAX=100000 # one test client makes many requests
|
||||
export PULSE_SCHEDULER_TICK_MS=1000 # scheduler tests shouldn't wait a minute
|
||||
|
||||
stop() {
|
||||
for f in "$RUN"/*.pid; do
|
||||
|
||||
@@ -381,8 +381,9 @@ async function processScheduledCommands() {
|
||||
|
||||
|
||||
if (!DEV_READONLY) {
|
||||
// Run scheduler every minute
|
||||
setInterval(processScheduledCommands, 60 * 1000);
|
||||
// Run scheduler every minute (tests shorten it with PULSE_SCHEDULER_TICK_MS, minimum 1 s)
|
||||
const tick = parseInt(process.env.PULSE_SCHEDULER_TICK_MS, 10);
|
||||
setInterval(processScheduledCommands, Number.isInteger(tick) && tick >= 1000 ? tick : 60 * 1000);
|
||||
// Initial run on startup
|
||||
setTimeout(processScheduledCommands, 5000);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
'use strict';
|
||||
|
||||
// The scheduler (processScheduledCommands in server.js). The test stack ticks every
|
||||
// second (PULSE_SCHEDULER_TICK_MS); a schedule is made due at once by setting its
|
||||
// next_run in the database, the one place these tests reach past the API.
|
||||
const mysql = require('mysql2/promise');
|
||||
const { api, sso, SSO, waitFor, waitForExecution, workerByName, commandResult, startWorker, sleep } = require('./helpers');
|
||||
|
||||
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
let db;
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await mysql.createConnection({
|
||||
host: process.env.DB_HOST || '127.0.0.1',
|
||||
port: Number(process.env.DB_PORT || 3306),
|
||||
user: process.env.DB_USER || 'pulse',
|
||||
password: process.env.DB_PASSWORD || 'ci-only',
|
||||
database: process.env.DB_NAME || 'pulse',
|
||||
});
|
||||
});
|
||||
afterAll(() => db && db.end());
|
||||
|
||||
async function createSchedule(fields) {
|
||||
const r = await sso('POST', '/api/scheduled-commands', {
|
||||
name: `int ${unique()}`, schedule_type: 'interval', schedule_value: '60', ...fields,
|
||||
});
|
||||
return r;
|
||||
}
|
||||
const makeDue = id => db.query('UPDATE scheduled_commands SET next_run = NOW() - INTERVAL 1 SECOND WHERE id = ?', [id]);
|
||||
async function executionsOf(name) {
|
||||
const [rows] = await db.query('SELECT id, status FROM executions WHERE started_by = ? ORDER BY started_at', [`scheduler:${name}`]);
|
||||
return rows;
|
||||
}
|
||||
|
||||
test('a due schedule runs its command on its worker and moves next_run forward', async () => {
|
||||
const worker = await workerByName('node-02');
|
||||
const name = `int ${unique()}`;
|
||||
const created = await createSchedule({ name, command: 'echo scheduled-ok', worker_ids: [worker.id] });
|
||||
expect(created.status).toBe(200);
|
||||
await makeDue(created.json.id);
|
||||
|
||||
const [run] = await waitFor(async () => { const r = await executionsOf(name); return r.length ? r : null; },
|
||||
{ what: 'the scheduled execution' });
|
||||
const ex = await waitForExecution(run.id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(commandResult(ex).stdout.trim()).toBe('scheduled-ok');
|
||||
|
||||
const [[row]] = await db.query('SELECT next_run, last_run FROM scheduled_commands WHERE id = ?', [created.json.id]);
|
||||
expect(row.last_run).not.toBeNull();
|
||||
expect(new Date(row.next_run).getTime()).toBeGreaterThan(Date.now() + 50 * 60_000); // about 60 min ahead
|
||||
});
|
||||
|
||||
test('a disabled schedule does not run', async () => {
|
||||
const worker = await workerByName('node-02');
|
||||
const name = `int ${unique()}`;
|
||||
const created = await createSchedule({ name, command: 'echo nope', worker_ids: [worker.id] });
|
||||
const toggled = await sso('PUT', `/api/scheduled-commands/${created.json.id}/toggle`);
|
||||
expect(toggled.json.enabled).toBe(false);
|
||||
await makeDue(created.json.id);
|
||||
await sleep(3500); // several scheduler ticks
|
||||
expect(await executionsOf(name)).toEqual([]);
|
||||
});
|
||||
|
||||
test('only admins can create schedules, and bad input is refused', async () => {
|
||||
const worker = await workerByName('node-01');
|
||||
const asEmployee = await api('POST', '/api/scheduled-commands', {
|
||||
headers: { ...SSO, 'Remote-Groups': 'employee' },
|
||||
body: { name: 'x', command: 'true', worker_ids: [worker.id], schedule_type: 'interval', schedule_value: '5' },
|
||||
});
|
||||
expect(asEmployee.status).toBe(403);
|
||||
expect((await createSchedule({ command: 'true' })).status).toBe(400); // no workers
|
||||
expect((await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_value: '-5' })).status).toBe(400);
|
||||
});
|
||||
|
||||
// Known bug: calculateNextRun throws on a bad cron expression, and the route answers 500.
|
||||
test.failing('an invalid cron expression is a 400, not a server error', async () => {
|
||||
const worker = await workerByName('node-01');
|
||||
const r = await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_type: 'cron', schedule_value: 'not a cron' });
|
||||
expect(r.status).toBe(400);
|
||||
});
|
||||
|
||||
// Known bug #9: a schedule whose worker is offline is skipped silently, leaving no trace.
|
||||
test.failing('a schedule whose worker is offline records a failed run (#9)', async () => {
|
||||
const workerName = `int-sched-${unique()}`;
|
||||
const w = await startWorker(workerName);
|
||||
const name = `int ${unique()}`;
|
||||
try {
|
||||
const created = await createSchedule({ name, command: 'echo unreachable', worker_ids: [w.id] });
|
||||
w.child.kill('SIGKILL');
|
||||
await waitFor(async () => (await workerByName(workerName))?.status === 'offline', { what: 'the worker to go offline' });
|
||||
await makeDue(created.json.id);
|
||||
await sleep(3500);
|
||||
const runs = await executionsOf(name);
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0].status).toBe('failed');
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
'use strict';
|
||||
|
||||
// The workflow engine (executeWorkflowSteps in server.js), driven through the API
|
||||
// with real workers. Known bugs are written as test.failing: they document today's
|
||||
// behaviour and start failing (so the marker must be removed) once the bug is fixed.
|
||||
const { sso, waitFor, waitForExecution, sleep } = require('./helpers');
|
||||
|
||||
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
async function createWorkflow(steps, extra = {}) {
|
||||
const r = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps, ...extra } });
|
||||
expect(r.status).toBe(200);
|
||||
return r.json.id;
|
||||
}
|
||||
async function start(workflowId, body = {}) {
|
||||
const r = await sso('POST', '/api/executions', { workflow_id: workflowId, ...body });
|
||||
expect(r.status).toBe(200);
|
||||
return r.json.id;
|
||||
}
|
||||
const logs = (ex, action) => (ex.logs || []).filter(l => l.action === action);
|
||||
const outputs = ex => logs(ex, 'command_result').map(l => (l.stdout || '').trim());
|
||||
|
||||
test('an execute step on all workers runs everywhere and completes', async () => {
|
||||
const marker = `all-${unique()}`;
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'hello', name: 'Hello', type: 'execute', command: `echo ${marker}`, targets: ['all'] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(outputs(ex).filter(o => o === marker)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('a failing step fails the execution and stops the workflow', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'bad', type: 'execute', command: 'exit 3', targets: ['node-01'] },
|
||||
{ id: 'never', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('failed');
|
||||
expect(outputs(ex)).not.toContain('should-not-run');
|
||||
});
|
||||
|
||||
test('parse reads KEY=VALUE output and route jumps on it', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'probe', type: 'execute', command: 'echo STATUS=degraded', targets: ['node-01'] },
|
||||
{ id: 'parse', type: 'parse' },
|
||||
{ id: 'decide', type: 'route', conditions: [
|
||||
{ if: "state.status === 'degraded'", goto: 'fix', label: 'needs fixing' },
|
||||
{ default: true, goto: 'end' },
|
||||
] },
|
||||
{ id: 'skipped', type: 'execute', command: 'echo not-me', targets: ['node-01'] },
|
||||
{ id: 'fix', type: 'execute', command: 'echo fixed', targets: ['node-01'] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'parse_complete')[0].parsed).toEqual({ status: 'degraded' });
|
||||
expect(logs(ex, 'route_taken')[0]).toMatchObject({ goto: 'fix', label: 'needs fixing' });
|
||||
expect(outputs(ex)).toContain('fixed');
|
||||
expect(outputs(ex)).not.toContain('not-me');
|
||||
});
|
||||
|
||||
test('a false condition skips the step', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'prod-only', type: 'execute', command: 'echo prod', targets: ['node-01'], condition: "params.env === 'prod'" },
|
||||
{ id: 'always', type: 'execute', command: 'echo always', targets: ['node-01'] },
|
||||
], { params: [{ name: 'env' }] }), { params: { env: 'staging' } });
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'step_skipped')).toHaveLength(1);
|
||||
expect(outputs(ex)).toEqual(['always']);
|
||||
});
|
||||
|
||||
test('a prompt waits for an answer, rejects invalid options, and routes on the answer', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'ask', type: 'prompt', message: 'Restart?', options: ['Yes', 'No'], key: 'answer', routes: { No: 'end' } },
|
||||
{ id: 'restart', type: 'execute', command: 'echo restarted', targets: ['node-02'] },
|
||||
]));
|
||||
await waitFor(async () => logs((await sso('GET', `/api/executions/${id}`)).json || {}, 'prompt').length > 0,
|
||||
{ what: 'the prompt to be asked' });
|
||||
|
||||
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Maybe' })).status).toBe(400);
|
||||
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Yes' })).status).toBe(200);
|
||||
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'prompt_response')[0]).toMatchObject({ response: 'Yes', responded_by: 'int.tester' });
|
||||
expect(outputs(ex)).toEqual(['restarted']);
|
||||
});
|
||||
|
||||
test('parameters are substituted, and unsafe values are refused', async () => {
|
||||
const wf = await createWorkflow([
|
||||
{ id: 'greet', type: 'execute', command: 'echo host={{host}}', targets: ['node-03'] },
|
||||
], { params: [{ name: 'host', required: true }] });
|
||||
|
||||
expect((await sso('POST', '/api/executions', { workflow_id: wf })).status).toBe(400); // required
|
||||
|
||||
const ok = await waitForExecution(await start(wf, { params: { host: 'db-01.lan' } }));
|
||||
expect(ok.status).toBe('completed');
|
||||
expect(outputs(ok)).toEqual(['host=db-01.lan']);
|
||||
|
||||
const bad = await waitForExecution(await start(wf, { params: { host: 'x; reboot' } }));
|
||||
expect(bad.status).toBe('failed');
|
||||
expect(outputs(bad)).toEqual([]);
|
||||
});
|
||||
|
||||
test('a dry run logs the commands without running them', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'danger', type: 'execute', command: 'echo would-run', targets: ['all'] },
|
||||
]), { dry_run: true });
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'dry_run_skipped')).toHaveLength(1);
|
||||
expect(logs(ex, 'command_result')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('an endless goto loop is detected and fails the execution', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'loop', type: 'route', conditions: [{ default: true, goto: 'loop' }] },
|
||||
]));
|
||||
const ex = await waitForExecution(id, { timeout: 60_000 });
|
||||
expect(ex.status).toBe('failed');
|
||||
expect(logs(ex, 'workflow_error')[0].error).toMatch(/Infinite loop/);
|
||||
});
|
||||
|
||||
test('an aborted execution stays failed', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'pause', type: 'wait', duration: 2 },
|
||||
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
|
||||
]));
|
||||
await sleep(500);
|
||||
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
|
||||
await sleep(4000);
|
||||
const ex = (await sso('GET', `/api/executions/${id}`)).json;
|
||||
expect(ex.status).toBe('failed');
|
||||
});
|
||||
|
||||
// Known bug #8: abort marks the execution failed but the engine keeps going.
|
||||
test.failing('abort stops the workflow before its next step (#8)', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'pause', type: 'wait', duration: 2 },
|
||||
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
|
||||
]));
|
||||
await sleep(500);
|
||||
await sso('POST', `/api/executions/${id}/abort`);
|
||||
await sleep(5000);
|
||||
const ex = (await sso('GET', `/api/executions/${id}`)).json;
|
||||
expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]);
|
||||
});
|
||||
|
||||
// Known bug #20: a goto to a step that doesn't exist ends as 'completed'.
|
||||
test.failing('a goto to a missing step fails the execution (#20)', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'jump', type: 'route', conditions: [{ default: true, goto: 'no-such-step' }] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('failed');
|
||||
});
|
||||
Reference in new issue
Block a user