96 lines
3.1 KiB
TypeScript
96 lines
3.1 KiB
TypeScript
import { spawn } from 'node:child_process';
|
|
import { resolve } from 'node:path';
|
|
import { createInterface } from 'node:readline';
|
|
import type { JobDefinition } from '@homepage/jobs';
|
|
|
|
export type RunnerOptions = {
|
|
scriptsDir: string;
|
|
/** Variables every script gets on top of a minimal base environment; the job's own env wins. */
|
|
env: Record<string, string>;
|
|
killGraceMs: number;
|
|
/** Receives every line the script prints. */
|
|
output: (line: string) => void;
|
|
};
|
|
|
|
export class ScriptError extends Error {}
|
|
|
|
const MAX_LINE_CHARS = 4096;
|
|
const BASE_ENV = { PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', HOME: '/tmp', LANG: 'C.UTF-8' };
|
|
|
|
function spawnError(path: string, error: NodeJS.ErrnoException): string
|
|
{
|
|
switch (error.code)
|
|
{
|
|
case 'ENOENT': return `${path} does not exist`;
|
|
case 'EACCES': return `${path} is not executable`;
|
|
default: return `${path} cannot be started: ${error.message}`;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Runs a script job in its own process group, so cancelling it also stops
|
|
* everything the script started. Cancelling sends SIGTERM and, after the
|
|
* grace time, SIGKILL. Processes still left once the script exits are killed.
|
|
*/
|
|
export function runScript(job: JobDefinition, signal: AbortSignal, options: RunnerOptions): Promise<void>
|
|
{
|
|
return new Promise((done, fail) =>
|
|
{
|
|
signal.throwIfAborted();
|
|
|
|
const path = resolve(options.scriptsDir, job.path!);
|
|
const child = spawn(path, job.args, {
|
|
cwd: options.scriptsDir,
|
|
env: { ...BASE_ENV, ...options.env, JOB_ID: job.id, ...job.env },
|
|
detached: true,
|
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
});
|
|
|
|
const killGroup = (name: NodeJS.Signals) =>
|
|
{
|
|
if (child.pid === undefined) return;
|
|
try { process.kill(-child.pid, name); }
|
|
catch { /* The group is already gone. */ }
|
|
};
|
|
|
|
let killTimer: NodeJS.Timeout | undefined;
|
|
const onAbort = () =>
|
|
{
|
|
killGroup('SIGTERM');
|
|
killTimer = setTimeout(() => killGroup('SIGKILL'), options.killGraceMs);
|
|
};
|
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
|
|
for (const stream of [child.stdout, child.stderr])
|
|
{
|
|
createInterface({ input: stream, crlfDelay: Infinity }).on('line', (line) =>
|
|
{
|
|
options.output(line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)} [truncated]` : line);
|
|
});
|
|
}
|
|
|
|
let settled = false;
|
|
const finish = (error?: unknown) =>
|
|
{
|
|
if (settled) return;
|
|
settled = true;
|
|
|
|
clearTimeout(killTimer);
|
|
signal.removeEventListener('abort', onAbort);
|
|
|
|
if (error === undefined) done();
|
|
else fail(error);
|
|
};
|
|
|
|
// Leftover background processes would otherwise keep the output pipes open.
|
|
child.once('exit', () => killGroup('SIGKILL'));
|
|
child.once('error', (error) => finish(new ScriptError(spawnError(path, error))));
|
|
child.once('close', (code, name) =>
|
|
{
|
|
if (signal.aborted) finish(signal.reason);
|
|
else if (code === 0) finish();
|
|
else finish(new ScriptError(code === null ? `killed by ${name}` : `exited with code ${code}`));
|
|
});
|
|
});
|
|
}
|