Add jobs service with script execution, configuration support, and control interface.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1f6d41ab06
commit
0ad5b5f44f
27 files changed
+1108
-45
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# Build context is the repository root.
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN corepack pnpm install --frozen-lockfile \
|
||||
&& corepack pnpm --filter @homepage/jobs-service build
|
||||
|
||||
FROM node:24-alpine
|
||||
# Tools job scripts can rely on.
|
||||
RUN apk add --no-cache bash coreutils curl git jq \
|
||||
&& printf '#!/bin/sh\nexec node /app/jobctl.js "$@"\n' > /usr/local/bin/jobctl \
|
||||
&& chmod 0755 /usr/local/bin/jobctl
|
||||
COPY --from=build /src/apps/jobs/dist/ /app/
|
||||
# Compose runs the service as the owner of the content directory instead.
|
||||
USER 10003:10003
|
||||
CMD ["node", "/app/main.js"]
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@homepage/jobs-service",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild src/main.ts src/jobctl.ts --bundle --platform=node --target=node24 --format=esm --outdir=dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"@homepage/jobs": "workspace:*",
|
||||
"@homepage/protocol": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export type JobsConfig = {
|
||||
jobsFile: string;
|
||||
/** Directory of the job scripts; relative script paths start here. */
|
||||
scriptsDir: string;
|
||||
contentDir: string;
|
||||
/** Read only view of /srv on the host. Watch paths are relative to it and must stay inside. */
|
||||
hostDir: string;
|
||||
/** Builtin jobs of the backend are triggered through files in this directory. */
|
||||
triggerDir: string;
|
||||
controlSocket: string;
|
||||
/** Time a cancelled script gets between SIGTERM and SIGKILL. */
|
||||
killGraceMs: number;
|
||||
};
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv): JobsConfig
|
||||
{
|
||||
const killGraceSeconds = Number(env.KILL_GRACE_SECONDS ?? 5);
|
||||
if (!Number.isInteger(killGraceSeconds) || killGraceSeconds < 0) throw new Error('KILL_GRACE_SECONDS must be a whole number');
|
||||
|
||||
return {
|
||||
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
|
||||
scriptsDir: env.SCRIPTS_DIR ?? '/jobs',
|
||||
contentDir: env.CONTENT_DIR ?? '/content',
|
||||
hostDir: env.HOST_DIR ?? '/host/srv',
|
||||
triggerDir: env.TRIGGER_DIR ?? '/run/jobs/triggers',
|
||||
controlSocket: env.CONTROL_SOCKET ?? '/run/jobs/control.sock',
|
||||
killGraceMs: killGraceSeconds * 1000,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { chmodSync, rmSync } from 'node:fs';
|
||||
import { connect, createServer, type Server, type Socket } from 'node:net';
|
||||
import { readLine } from '@homepage/protocol';
|
||||
import type { JobService, JobState } from './service.ts';
|
||||
|
||||
/** Requests jobctl sends to the jobs service, one JSON line per connection. */
|
||||
export type ControlRequest =
|
||||
| { op: 'list' }
|
||||
| { op: 'run' | 'cancel'; id: string };
|
||||
|
||||
export type ControlResponse =
|
||||
| { ok: true; message?: string; jobs?: JobState[] }
|
||||
| { ok: false; error: string };
|
||||
|
||||
const MAX_REQUEST_BYTES = 1024;
|
||||
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
|
||||
function parseRequest(line: string): ControlRequest
|
||||
{
|
||||
const request = JSON.parse(line) as Partial<{ op: unknown; id: unknown }>;
|
||||
if (request.op === 'list') return { op: 'list' };
|
||||
if ((request.op === 'run' || request.op === 'cancel') && typeof request.id === 'string') return { op: request.op, id: request.id };
|
||||
throw new Error('unknown request');
|
||||
}
|
||||
|
||||
async function answer(service: JobService, request: ControlRequest): Promise<ControlResponse>
|
||||
{
|
||||
switch (request.op)
|
||||
{
|
||||
case 'list': return { ok: true, jobs: service.list() };
|
||||
case 'run': return { ok: true, message: await service.run(request.id) };
|
||||
case 'cancel': return { ok: true, message: service.cancel(request.id) };
|
||||
}
|
||||
}
|
||||
|
||||
async function handle(connection: Socket, service: JobService): Promise<void>
|
||||
{
|
||||
let response: ControlResponse;
|
||||
try
|
||||
{
|
||||
const { line } = await readLine(connection, MAX_REQUEST_BYTES);
|
||||
response = await answer(service, parseRequest(line));
|
||||
}
|
||||
catch (error) { response = { ok: false, error: (error as Error).message }; }
|
||||
|
||||
connection.end(`${JSON.stringify(response)}\n`);
|
||||
}
|
||||
|
||||
/** Listens on a Unix socket only the service's own user may use. */
|
||||
export function listenControl(service: JobService, path: string): Promise<Server>
|
||||
{
|
||||
rmSync(path, { force: true });
|
||||
|
||||
const server = createServer((connection) =>
|
||||
{
|
||||
connection.on('error', () => connection.destroy());
|
||||
void handle(connection, service);
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) =>
|
||||
{
|
||||
server.once('error', reject);
|
||||
server.listen(path, () =>
|
||||
{
|
||||
chmodSync(path, 0o600);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function request(path: string, body: ControlRequest): Promise<ControlResponse>
|
||||
{
|
||||
return new Promise((resolve, reject) =>
|
||||
{
|
||||
const socket = connect(path);
|
||||
socket.once('error', reject);
|
||||
socket.once('connect', () =>
|
||||
{
|
||||
socket.write(`${JSON.stringify(body)}\n`);
|
||||
readLine(socket, MAX_RESPONSE_BYTES, 30_000)
|
||||
.then(({ line }) => resolve(JSON.parse(line) as ControlResponse), reject)
|
||||
.finally(() => socket.destroy());
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { request, type ControlRequest } from './control.ts';
|
||||
import type { JobState, RunRecord } from './service.ts';
|
||||
|
||||
const usage = 'usage: jobctl list | run <id> | cancel <id>';
|
||||
|
||||
function ago(time: number): string
|
||||
{
|
||||
const seconds = Math.round((Date.now() - time) / 1000);
|
||||
if (seconds < 120) return `${seconds}s ago`;
|
||||
if (seconds < 7200) return `${Math.round(seconds / 60)}m ago`;
|
||||
return `${Math.round(seconds / 3600)}h ago`;
|
||||
}
|
||||
|
||||
function describeRun(run: RunRecord | undefined): string
|
||||
{
|
||||
if (!run) return '';
|
||||
if (run.outcome === 'running') return `since ${ago(run.startedAt)}`;
|
||||
|
||||
const took = `${((run.finishedAt! - run.startedAt) / 1000).toFixed(1)}s`;
|
||||
return `${run.outcome} ${ago(run.finishedAt!)}, took ${took}${run.error ? `: ${run.error}` : ''}`;
|
||||
}
|
||||
|
||||
function state(job: JobState): string
|
||||
{
|
||||
if (!job.enabled) return 'disabled';
|
||||
if (job.kind === 'builtin') return 'backend';
|
||||
return job.running ? 'running' : 'idle';
|
||||
}
|
||||
|
||||
function table(jobs: JobState[]): string
|
||||
{
|
||||
const rows = [['ID', 'KIND', 'STATE', 'SCHEDULE', 'LAST RUN'], ...jobs.map((job) => [job.id, job.kind, state(job), job.schedule, describeRun(job.last)])];
|
||||
const widths = rows[0]!.map((_, column) => Math.max(...rows.map((row) => row[column]!.length)));
|
||||
return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column]!)).join(' ').trimEnd()).join('\n');
|
||||
}
|
||||
|
||||
const socket = process.env.CONTROL_SOCKET ?? '/run/jobs/control.sock';
|
||||
const [command, id] = process.argv.slice(2);
|
||||
|
||||
let body: ControlRequest;
|
||||
if (command === 'list') body = { op: 'list' };
|
||||
else if ((command === 'run' || command === 'cancel') && id) body = { op: command, id };
|
||||
else
|
||||
{
|
||||
console.error(usage);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const response = await request(socket, body).catch((error: Error) =>
|
||||
{
|
||||
console.error(`cannot reach the jobs service at ${socket}: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
if (!response.ok)
|
||||
{
|
||||
console.error(response.error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(response.jobs ? table(response.jobs) : response.message);
|
||||
@@ -0,0 +1,21 @@
|
||||
import { loadConfig } from './config.ts';
|
||||
import { listenControl } from './control.ts';
|
||||
import { JobService } from './service.ts';
|
||||
|
||||
const log = (message: string) => console.log(`[jobs] ${message}`);
|
||||
|
||||
const config = loadConfig(process.env);
|
||||
const service = new JobService(config, log);
|
||||
await service.start();
|
||||
|
||||
const control = await listenControl(service, config.controlSocket);
|
||||
log(`jobctl listens on ${config.controlSocket}`);
|
||||
|
||||
for (const signal of ['SIGTERM', 'SIGINT'] as const)
|
||||
{
|
||||
process.once(signal, async () => {
|
||||
control.close();
|
||||
await service.stop();
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { JobCancelledError, type JobDefinition } from '@homepage/jobs';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { runScript, ScriptError, type RunnerOptions } from './runner.ts';
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
function job(path: string, overrides: Partial<JobDefinition> = {}): JobDefinition
|
||||
{
|
||||
return { id: 'test', path, args: [], on: [], watch: [], then: [], timeout: 60_000, env: {}, enabled: true, parallel: false, ...overrides };
|
||||
}
|
||||
|
||||
describe('runScript', () => {
|
||||
let dir: string;
|
||||
let lines: string[];
|
||||
let options: RunnerOptions;
|
||||
|
||||
const script = (name: string, body: string) =>
|
||||
{
|
||||
writeFileSync(join(dir, name), `#!/bin/sh\n${body}\n`);
|
||||
chmodSync(join(dir, name), 0o755);
|
||||
};
|
||||
|
||||
beforeEach(() =>
|
||||
{
|
||||
dir = mkdtempSync(join(tmpdir(), 'runner-'));
|
||||
lines = [];
|
||||
options = { scriptsDir: dir, env: { CONTENT_DIR: '/content' }, killGraceMs: 300, output: (line) => lines.push(line) };
|
||||
});
|
||||
|
||||
it('passes arguments and environment and collects output', async () => {
|
||||
script('hello.sh', 'echo "$1 $JOB_ID $CONTENT_DIR $GREETING"; echo oops >&2');
|
||||
await runScript(job('hello.sh', { args: ['hi'], env: { GREETING: 'moin' } }), new AbortController().signal, options);
|
||||
|
||||
expect(lines.sort()).toEqual(['hi test /content moin', 'oops']);
|
||||
});
|
||||
|
||||
it('fails on a non zero exit code and on scripts that cannot start', async () => {
|
||||
script('fail.sh', 'exit 3');
|
||||
writeFileSync(join(dir, 'plain.sh'), 'echo');
|
||||
|
||||
await expect(runScript(job('fail.sh'), new AbortController().signal, options)).rejects.toThrow('exited with code 3');
|
||||
await expect(runScript(job('plain.sh'), new AbortController().signal, options)).rejects.toThrow('is not executable');
|
||||
await expect(runScript(job('missing.sh'), new AbortController().signal, options)).rejects.toBeInstanceOf(ScriptError);
|
||||
});
|
||||
|
||||
it('stops the whole process group when cancelled', async () => {
|
||||
const marker = join(dir, 'survived');
|
||||
script('tree.sh', `(sleep 1; touch ${marker}) & sleep 5`);
|
||||
|
||||
const controller = new AbortController();
|
||||
const run = runScript(job('tree.sh'), controller.signal, options);
|
||||
await sleep(100);
|
||||
controller.abort(new JobCancelledError('cancelled'));
|
||||
|
||||
await expect(run).rejects.toBeInstanceOf(JobCancelledError);
|
||||
await sleep(1200);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
it('kills scripts that ignore SIGTERM after the grace time', async () => {
|
||||
script('stubborn.sh', `trap '' TERM; while :; do sleep 0.05; done`);
|
||||
|
||||
const controller = new AbortController();
|
||||
const run = runScript(job('stubborn.sh'), controller.signal, options);
|
||||
await sleep(100);
|
||||
|
||||
const started = Date.now();
|
||||
controller.abort(new JobCancelledError('cancelled'));
|
||||
await expect(run).rejects.toBeInstanceOf(JobCancelledError);
|
||||
expect(Date.now() - started).toBeGreaterThanOrEqual(250);
|
||||
});
|
||||
|
||||
it('kills background processes left behind by a finished script', async () => {
|
||||
const marker = join(dir, 'survived');
|
||||
script('leaky.sh', `(sleep 0.5; touch ${marker}) &`);
|
||||
|
||||
await runScript(job('leaky.sh'), new AbortController().signal, options);
|
||||
await sleep(800);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
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}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { loadJobs } from '@homepage/jobs';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import type { JobsConfig } from './config.ts';
|
||||
import { listenControl, request } from './control.ts';
|
||||
import { JobService, prepareJobsFile } from './service.ts';
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
function setup(jobs: string, scripts: Record<string, string> = {})
|
||||
{
|
||||
const root = mkdtempSync(join(tmpdir(), 'jobs-'));
|
||||
const config: JobsConfig = {
|
||||
jobsFile: join(root, 'config', 'jobs.toml'),
|
||||
scriptsDir: join(root, 'jobs'),
|
||||
contentDir: join(root, 'content'),
|
||||
hostDir: join(root, 'srv'),
|
||||
triggerDir: join(root, 'triggers'),
|
||||
controlSocket: join(root, 'control.sock'),
|
||||
killGraceMs: 300,
|
||||
};
|
||||
for (const dir of ['config', 'jobs', 'content', 'srv/gitea', 'triggers']) mkdirSync(join(root, dir), { recursive: true });
|
||||
|
||||
writeFileSync(config.jobsFile, jobs);
|
||||
for (const [name, body] of Object.entries(scripts))
|
||||
{
|
||||
writeFileSync(join(config.scriptsDir, name), `#!/bin/sh\n${body}\n`);
|
||||
chmodSync(join(config.scriptsDir, name), 0o755);
|
||||
}
|
||||
|
||||
const logs: string[] = [];
|
||||
const service = new JobService(config, (line) => logs.push(line));
|
||||
return { root, config, logs, service };
|
||||
}
|
||||
|
||||
let current: JobService | undefined;
|
||||
afterEach(async () => { await current?.stop(); });
|
||||
|
||||
describe('prepareJobsFile', () => {
|
||||
it('creates the file with every system job', async () => {
|
||||
const file = join(mkdtempSync(join(tmpdir(), 'jobs-')), 'jobs.toml');
|
||||
await prepareJobsFile(file, () => {});
|
||||
|
||||
const text = readFileSync(file, 'utf8');
|
||||
expect(text).toContain('# Jobs of security-command.org');
|
||||
expect(loadJobs(text).missing).toBe('');
|
||||
});
|
||||
|
||||
it('appends only missing system jobs and keeps existing ones as written', async () => {
|
||||
const file = join(mkdtempSync(join(tmpdir(), 'jobs-')), 'jobs.toml');
|
||||
writeFileSync(file, '[[job]]\nid = "status"\nbuiltin = "status"\nenabled = false');
|
||||
await prepareJobsFile(file, () => {});
|
||||
|
||||
const { jobs, missing } = loadJobs(readFileSync(file, 'utf8'));
|
||||
expect(missing).toBe('');
|
||||
expect(jobs.filter((job) => job.id === 'status')).toEqual([expect.objectContaining({ enabled: false })]);
|
||||
});
|
||||
|
||||
it('leaves a broken file alone', async () => {
|
||||
const file = join(mkdtempSync(join(tmpdir(), 'jobs-')), 'jobs.toml');
|
||||
writeFileSync(file, '[[job]\n');
|
||||
await prepareJobsFile(file, () => {});
|
||||
|
||||
expect(readFileSync(file, 'utf8')).toBe('[[job]\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('JobService', () => {
|
||||
it('runs script jobs, triggers builtin targets through files and reports runs', async () => {
|
||||
const { config, service } = setup(
|
||||
'[[job]]\nid = "services"\npath = "services.sh"\non = ["start"]\nthen = ["index"]\n',
|
||||
{ 'services.sh': 'echo "gitea" > "$CONTENT_DIR/services.txt"' },
|
||||
);
|
||||
current = service;
|
||||
await service.start();
|
||||
await sleep(200);
|
||||
|
||||
expect(readFileSync(join(config.contentDir, 'services.txt'), 'utf8')).toBe('gitea\n');
|
||||
expect(existsSync(join(config.triggerDir, 'index'))).toBe(true);
|
||||
|
||||
const state = service.list().find((job) => job.id === 'services');
|
||||
expect(state).toMatchObject({ kind: 'script', running: false, schedule: 'on start', last: { outcome: 'ok' } });
|
||||
expect(service.list().find((job) => job.id === 'index')).toMatchObject({ kind: 'builtin', schedule: 'on start, on content-change' });
|
||||
});
|
||||
|
||||
it('runs a job when a watched host path changes', async () => {
|
||||
const { root, config, service } = setup(
|
||||
'[[job]]\nid = "watcher"\npath = "count.sh"\non = ["watch"]\nwatch = ["gitea/compose.yml"]\n',
|
||||
{ 'count.sh': 'echo run >> "$CONTENT_DIR/runs"' },
|
||||
);
|
||||
current = service;
|
||||
await service.start();
|
||||
|
||||
writeFileSync(join(root, 'srv/gitea/compose.yml'), 'services: {}');
|
||||
writeFileSync(join(root, 'srv/gitea/other.yml'), 'ignored');
|
||||
await sleep(2500);
|
||||
|
||||
expect(readFileSync(join(config.contentDir, 'runs'), 'utf8')).toBe('run\n');
|
||||
});
|
||||
|
||||
it('refuses watch paths outside the host directory', async () => {
|
||||
const { logs, service } = setup('[[job]]\nid = "loop"\npath = "x.sh"\non = ["watch"]\nwatch = ["../content"]\n');
|
||||
current = service;
|
||||
await service.start();
|
||||
|
||||
expect(logs.some((line) => line.includes('job "loop" cannot watch ../content'))).toBe(true);
|
||||
});
|
||||
|
||||
it('runs, restarts and cancels jobs over the control socket', async () => {
|
||||
const { config, service } = setup('[[job]]\nid = "slow"\npath = "slow.sh"\n', { 'slow.sh': 'sleep 5' });
|
||||
current = service;
|
||||
await service.start();
|
||||
const server = await listenControl(service, config.controlSocket);
|
||||
|
||||
expect(await request(config.controlSocket, { op: 'run', id: 'slow' })).toEqual({ ok: true, message: 'started job "slow"' });
|
||||
expect(await request(config.controlSocket, { op: 'run', id: 'slow' })).toEqual({ ok: true, message: 'restarting job "slow"' });
|
||||
await sleep(100);
|
||||
expect(await request(config.controlSocket, { op: 'cancel', id: 'slow' })).toEqual({ ok: true, message: 'cancelled job "slow"' });
|
||||
await sleep(100);
|
||||
|
||||
expect(service.list().find((job) => job.id === 'slow')?.last?.outcome).toBe('cancelled');
|
||||
expect(await request(config.controlSocket, { op: 'run', id: 'nope' })).toEqual({ ok: false, error: 'unknown job "nope"' });
|
||||
expect(await request(config.controlSocket, { op: 'cancel', id: 'index' })).toMatchObject({ ok: false });
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('applies edits to the job file without a restart', async () => {
|
||||
const { config, logs, service } = setup('');
|
||||
current = service;
|
||||
await service.start();
|
||||
|
||||
writeFileSync(config.jobsFile, `${readFileSync(config.jobsFile, 'utf8')}\n[[job]]\nid = "new"\npath = "new.sh"\nenabled = false\n`);
|
||||
await sleep(800);
|
||||
|
||||
expect(service.list().find((job) => job.id === 'new')).toMatchObject({ enabled: false });
|
||||
expect(logs).toContain('job "new" is disabled');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import type { FSWatcher } from 'node:fs';
|
||||
import { appendFile, readFile } from 'node:fs/promises';
|
||||
import { isAbsolute, relative, resolve } from 'node:path';
|
||||
import {
|
||||
JobCancelledError,
|
||||
JobTimeoutError,
|
||||
loadJobs,
|
||||
Scheduler,
|
||||
watchFile,
|
||||
watchPath,
|
||||
writeTrigger,
|
||||
type JobDefinition,
|
||||
} from '@homepage/jobs';
|
||||
import type { JobsConfig } from './config.ts';
|
||||
import { runScript } from './runner.ts';
|
||||
|
||||
export type Outcome = 'running' | 'ok' | 'failed' | 'cancelled' | 'timed out';
|
||||
|
||||
export type RunRecord = {
|
||||
startedAt: number;
|
||||
finishedAt?: number;
|
||||
outcome: Outcome;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type JobState = {
|
||||
id: string;
|
||||
kind: 'script' | 'builtin';
|
||||
enabled: boolean;
|
||||
running: boolean;
|
||||
schedule: string;
|
||||
last?: RunRecord;
|
||||
};
|
||||
|
||||
const RELOAD_DEBOUNCE_MS = 500;
|
||||
const WATCH_QUIET_MS = 2000;
|
||||
const STOP_POLL_MS = 100;
|
||||
|
||||
const FILE_HEADER = `# Jobs of security-command.org. The backend runs the builtin jobs, the jobs
|
||||
# service runs the scripts. Edits apply within a second; all options are
|
||||
# described in deploy/jobs.example.toml.
|
||||
`;
|
||||
|
||||
const UNITS: [string, number][] = [['d', 86_400_000], ['h', 3_600_000], ['m', 60_000], ['s', 1000]];
|
||||
|
||||
function formatDuration(ms: number): string
|
||||
{
|
||||
for (const [unit, size] of UNITS) if (ms % size === 0) return `${ms / size}${unit}`;
|
||||
return `${ms}ms`;
|
||||
}
|
||||
|
||||
function describeSchedule(job: JobDefinition): string
|
||||
{
|
||||
const parts: string[] = [];
|
||||
if (job.every !== undefined) parts.push(`every ${formatDuration(job.every)}`);
|
||||
if (job.cron !== undefined) parts.push(`cron ${job.cron}`);
|
||||
for (const event of job.on) if (event !== 'watch') parts.push(`on ${event}`);
|
||||
if (job.watch.length > 0) parts.push(`watch ${job.watch.join(' ')}`);
|
||||
return parts.join(', ') || 'manual';
|
||||
}
|
||||
|
||||
function inside(base: string, path: string): boolean
|
||||
{
|
||||
const rest = relative(base, path);
|
||||
return !rest.startsWith('..') && !isAbsolute(rest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the job file with the system jobs, or appends the system jobs it
|
||||
* lacks, so they can be switched off there. A file that is not valid TOML is
|
||||
* left alone.
|
||||
*/
|
||||
export async function prepareJobsFile(file: string, log: (message: string) => void): Promise<void>
|
||||
{
|
||||
const text = await readFile(file, 'utf8').catch((error: NodeJS.ErrnoException) =>
|
||||
{
|
||||
if (error.code === 'ENOENT') return '';
|
||||
throw error;
|
||||
});
|
||||
|
||||
const { parsed, missing } = loadJobs(text);
|
||||
if (!parsed || !missing) return;
|
||||
|
||||
const separator = text === '' ? FILE_HEADER : text.endsWith('\n') ? '' : '\n';
|
||||
await appendFile(file, separator + missing);
|
||||
log(text === '' ? `created ${file} with the system jobs` : `added missing system jobs to ${file}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the script jobs of the job file. Builtin jobs belong to the backend,
|
||||
* which this service triggers through trigger files when a script job names
|
||||
* one in "then" or jobctl runs one.
|
||||
*/
|
||||
export class JobService
|
||||
{
|
||||
private readonly config: JobsConfig;
|
||||
private readonly log: (message: string) => void;
|
||||
private readonly history = new Map<string, RunRecord>();
|
||||
private definitions = new Map<string, JobDefinition>();
|
||||
private scheduler?: Scheduler;
|
||||
private jobWatchers: FSWatcher[] = [];
|
||||
private fileWatcher?: FSWatcher;
|
||||
|
||||
constructor(config: JobsConfig, log: (message: string) => void)
|
||||
{
|
||||
this.config = config;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
async start(): Promise<void>
|
||||
{
|
||||
try { await prepareJobsFile(this.config.jobsFile, this.log); }
|
||||
catch (error) { this.log(`cannot write ${this.config.jobsFile}: ${(error as Error).message}`); }
|
||||
|
||||
await this.load();
|
||||
this.fileWatcher = watchFile(this.config.jobsFile, RELOAD_DEBOUNCE_MS, () => void this.load(), this.log);
|
||||
}
|
||||
|
||||
/** Starts a job, or triggers it in the backend when it is builtin. Returns what happened. */
|
||||
async run(id: string): Promise<string>
|
||||
{
|
||||
const job = this.definitions.get(id);
|
||||
if (!job) throw new Error(`unknown job "${id}"`);
|
||||
if (!job.enabled) throw new Error(`job "${id}" is disabled`);
|
||||
|
||||
if (job.builtin !== undefined)
|
||||
{
|
||||
await writeTrigger(this.config.triggerDir, id);
|
||||
return `triggered builtin job "${id}" in the backend`;
|
||||
}
|
||||
|
||||
const restart = !job.parallel && this.scheduler!.running().includes(id);
|
||||
this.scheduler!.trigger(id);
|
||||
return restart ? `restarting job "${id}"` : `started job "${id}"`;
|
||||
}
|
||||
|
||||
cancel(id: string): string
|
||||
{
|
||||
const job = this.definitions.get(id);
|
||||
if (!job) throw new Error(`unknown job "${id}"`);
|
||||
if (job.builtin !== undefined) throw new Error(`job "${id}" is builtin and runs in the backend, which cannot be cancelled from here`);
|
||||
|
||||
return this.scheduler!.cancel(id) ? `cancelled job "${id}"` : `job "${id}" is not running`;
|
||||
}
|
||||
|
||||
list(): JobState[]
|
||||
{
|
||||
const running = new Set(this.scheduler?.running());
|
||||
return [...this.definitions.values()].map((job) => ({
|
||||
id: job.id,
|
||||
kind: job.builtin === undefined ? 'script' : 'builtin',
|
||||
enabled: job.enabled,
|
||||
running: running.has(job.id),
|
||||
schedule: describeSchedule(job),
|
||||
...(this.history.has(job.id) ? { last: this.history.get(job.id)! } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Cancels all runs and waits until they ended, at most for the kill grace time and a bit. */
|
||||
async stop(): Promise<void>
|
||||
{
|
||||
this.fileWatcher?.close();
|
||||
this.stopJobs();
|
||||
|
||||
const deadline = Date.now() + this.config.killGraceMs + 1000;
|
||||
while ((this.scheduler?.running().length ?? 0) > 0 && Date.now() < deadline)
|
||||
{
|
||||
await new Promise((resolve) => setTimeout(resolve, STOP_POLL_MS));
|
||||
}
|
||||
}
|
||||
|
||||
private stopJobs(): void
|
||||
{
|
||||
for (const watcher of this.jobWatchers) watcher.close();
|
||||
this.jobWatchers = [];
|
||||
this.scheduler?.stop();
|
||||
}
|
||||
|
||||
private async load(): Promise<void>
|
||||
{
|
||||
let text = '';
|
||||
try { text = await readFile(this.config.jobsFile, 'utf8'); }
|
||||
catch { this.log(`${this.config.jobsFile} cannot be read, no script jobs run`); }
|
||||
|
||||
const { jobs, warnings } = loadJobs(text);
|
||||
for (const warning of warnings) this.log(warning);
|
||||
|
||||
this.stopJobs();
|
||||
this.definitions = new Map(jobs.map((job) => [job.id, job]));
|
||||
|
||||
const scripts = jobs.filter((job) => job.path !== undefined);
|
||||
this.scheduler = new Scheduler(scripts, (job, signal) => this.execute(job, signal), {
|
||||
log: this.log,
|
||||
triggerOther: (id) => void this.run(id).catch((error: Error) => this.log(`cannot trigger job "${id}": ${error.message}`)),
|
||||
});
|
||||
this.scheduler.start();
|
||||
|
||||
for (const job of scripts) if (job.enabled) this.watch(job);
|
||||
this.log(`loaded ${scripts.length} script job(s)`);
|
||||
}
|
||||
|
||||
/** Watch paths must lie in the read only host directory, so a job can never trigger itself by writing. */
|
||||
private watch(job: JobDefinition): void
|
||||
{
|
||||
for (const path of job.watch)
|
||||
{
|
||||
const target = resolve(this.config.hostDir, path);
|
||||
if (!inside(this.config.hostDir, target))
|
||||
{
|
||||
this.log(`job "${job.id}" cannot watch ${path}: watch paths are relative to ${this.config.hostDir} and must stay inside it`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const watcher = watchPath(target, WATCH_QUIET_MS, () => this.scheduler?.trigger(job.id), this.log);
|
||||
if (watcher) this.jobWatchers.push(watcher);
|
||||
}
|
||||
}
|
||||
|
||||
private async execute(job: JobDefinition, signal: AbortSignal): Promise<void>
|
||||
{
|
||||
const record: RunRecord = { startedAt: Date.now(), outcome: 'running' };
|
||||
this.history.set(job.id, record);
|
||||
|
||||
try
|
||||
{
|
||||
await runScript(job, signal, {
|
||||
scriptsDir: this.config.scriptsDir,
|
||||
env: { CONTENT_DIR: this.config.contentDir, HOST_DIR: this.config.hostDir },
|
||||
killGraceMs: this.config.killGraceMs,
|
||||
output: (line) => this.log(`${job.id}: ${line}`),
|
||||
});
|
||||
record.outcome = 'ok';
|
||||
}
|
||||
catch (error)
|
||||
{
|
||||
const reason = signal.aborted ? signal.reason : error;
|
||||
record.outcome = reason instanceof JobCancelledError ? 'cancelled' : reason instanceof JobTimeoutError ? 'timed out' : 'failed';
|
||||
record.error = reason instanceof Error ? reason.message : String(reason);
|
||||
if (record.outcome === 'cancelled') this.log(`job "${job.id}" ${record.error}`);
|
||||
throw error;
|
||||
}
|
||||
finally
|
||||
{
|
||||
record.finishedAt = Date.now();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user