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
@@ -69,3 +69,20 @@ jobs:
|
||||
image="$REGISTRY/homepage-backend"
|
||||
docker build -f apps/backend/Dockerfile --build-arg BUILD_SHA=${{ gitea.sha }} -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" .
|
||||
docker push --all-tags "$image"
|
||||
|
||||
jobs:
|
||||
needs: check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Log in to the registry
|
||||
run: >
|
||||
echo "${{ secrets.REGISTRY_TOKEN }}"
|
||||
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
|
||||
- name: Build and push
|
||||
run: |
|
||||
image="$REGISTRY/homepage-jobs"
|
||||
docker build -f apps/jobs/Dockerfile -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" .
|
||||
docker push --all-tags "$image"
|
||||
@@ -60,6 +60,16 @@ describe('builtin jobs', () => {
|
||||
expect(site()?.pages.has('/sitemap.xml')).toBe(true);
|
||||
});
|
||||
|
||||
it('index keeps the site when the content did not change', async () => {
|
||||
const { builtins, site, logs } = setup();
|
||||
await builtins.index!(new AbortController().signal);
|
||||
const first = site();
|
||||
await builtins.index!(new AbortController().signal);
|
||||
|
||||
expect(site()).toBe(first);
|
||||
expect(logs.filter((line) => line.startsWith('indexed'))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('status writes the status file', async () => {
|
||||
const { builtins, status } = setup();
|
||||
await builtins.status!(new AbortController().signal);
|
||||
|
||||
@@ -21,6 +21,7 @@ const CONTENT_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 64 * 1024 * 1
|
||||
export function createBuiltins(dependencies: BuiltinDependencies): Record<string, Builtin>
|
||||
{
|
||||
const { config, hub, spawner, log } = dependencies;
|
||||
let lastHash = '';
|
||||
let lastWarnings = '';
|
||||
|
||||
return {
|
||||
@@ -29,6 +30,10 @@ export function createBuiltins(dependencies: BuiltinDependencies): Record<string
|
||||
const index = await buildIndex(config.contentDir, { ...CONTENT_LIMITS, reserved: reservedNames(config.legalPages), signal });
|
||||
signal.throwIfAborted();
|
||||
|
||||
// Content changes often arrive twice, through "then" and the content watcher.
|
||||
if (index.hash === lastHash) return;
|
||||
lastHash = index.hash;
|
||||
|
||||
dependencies.setSite(buildSite(index, { siteUrl: config.siteUrl, legal: config.legalPages }));
|
||||
|
||||
// The same warnings come back on every rebuild, so they are only logged when they change.
|
||||
|
||||
@@ -7,6 +7,8 @@ export type BackendConfig = {
|
||||
frontendDir: string;
|
||||
contentDir: string;
|
||||
jobsFile: string;
|
||||
/** Directory the jobs service writes triggers for builtin jobs into; empty disables them. */
|
||||
triggerDir: string;
|
||||
/** Absolute URL of the site, for the sitemap. */
|
||||
siteUrl: string;
|
||||
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
|
||||
@@ -59,6 +61,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
||||
frontendDir: env.FRONTEND_DIR ?? '/app/public',
|
||||
contentDir: env.CONTENT_DIR ?? '/content',
|
||||
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
|
||||
triggerDir: env.TRIGGER_DIR ?? '',
|
||||
siteUrl: env.SITE_URL ?? 'https://security-command.org',
|
||||
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
|
||||
statusDir: env.STATUS_DIR ?? '',
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { watch, type FSWatcher } from 'node:fs';
|
||||
import type { FSWatcher } from 'node:fs';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { basename, dirname } from 'node:path';
|
||||
import { loadJobs, Scheduler, type JobDefinition, type JobEvent } from '@homepage/jobs';
|
||||
import { loadJobs, Scheduler, watchFile, type JobDefinition, type JobEvent } from '@homepage/jobs';
|
||||
|
||||
export type Builtin = (signal: AbortSignal) => Promise<void>;
|
||||
|
||||
@@ -19,7 +18,6 @@ export class BackendJobs
|
||||
private readonly log: (message: string) => void;
|
||||
private scheduler?: Scheduler;
|
||||
private watcher?: FSWatcher;
|
||||
private reloadTimer?: NodeJS.Timeout;
|
||||
|
||||
constructor(file: string, builtins: Record<string, Builtin>, log: (message: string) => void)
|
||||
{
|
||||
@@ -31,27 +29,16 @@ export class BackendJobs
|
||||
async start(): Promise<void>
|
||||
{
|
||||
await this.load();
|
||||
|
||||
// The directory is watched instead of the file, because editors and the
|
||||
// jobs service replace the file, which would end a watch on the old one.
|
||||
try
|
||||
{
|
||||
this.watcher = watch(dirname(this.file), (_event, name) =>
|
||||
{
|
||||
if (name !== basename(this.file)) return;
|
||||
clearTimeout(this.reloadTimer);
|
||||
this.reloadTimer = setTimeout(() => void this.load(), RELOAD_DEBOUNCE_MS);
|
||||
});
|
||||
}
|
||||
catch { this.log(`cannot watch ${this.file}, changes apply after a restart`); }
|
||||
this.watcher = watchFile(this.file, RELOAD_DEBOUNCE_MS, () => void this.load(), this.log);
|
||||
}
|
||||
|
||||
emit(event: JobEvent): void {
|
||||
this.scheduler?.emit(event);
|
||||
}
|
||||
|
||||
trigger(id: string): void {
|
||||
this.scheduler?.trigger(id);
|
||||
/** Starts a job. Returns false for unknown or disabled jobs. */
|
||||
trigger(id: string): boolean {
|
||||
return this.scheduler?.trigger(id) ?? false;
|
||||
}
|
||||
|
||||
stop(): void
|
||||
@@ -80,22 +67,3 @@ export class BackendJobs
|
||||
this.scheduler.start();
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls back once a directory tree has been quiet for the given time after a change. */
|
||||
export function watchTree(directory: string, quietMs: number, onChange: () => void, log: (message: string) => void): FSWatcher | undefined
|
||||
{
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try
|
||||
{
|
||||
return watch(directory, { recursive: true }, () =>
|
||||
{
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(onChange, quietMs);
|
||||
});
|
||||
}
|
||||
catch (error)
|
||||
{
|
||||
log(`cannot watch ${directory}: ${(error as Error).message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { Site } from '@homepage/indexer';
|
||||
import { watchTree, watchTriggers } from '@homepage/jobs';
|
||||
import { SpawnerClient } from '@homepage/protocol';
|
||||
import { loadAssets } from './assets.ts';
|
||||
import { createBuiltins } from './builtins.ts';
|
||||
import { loadConfig } from './config.ts';
|
||||
import { SessionHub } from './hub.ts';
|
||||
import { BackendJobs, watchTree } from './jobs.ts';
|
||||
import { BackendJobs } from './jobs.ts';
|
||||
import { createBackend, createMetricsServer } from './server.ts';
|
||||
|
||||
const log = (message: string) => console.log(`[backend] ${message}`);
|
||||
@@ -36,6 +37,15 @@ await jobs.start();
|
||||
|
||||
watchTree(config.contentDir, CONTENT_QUIET_MS, () => jobs?.emit('content-change'), log);
|
||||
|
||||
if (config.triggerDir)
|
||||
{
|
||||
watchTriggers(config.triggerDir, (id) =>
|
||||
{
|
||||
if (jobs?.trigger(id)) log(`job "${id}" triggered by the jobs service`);
|
||||
else log(`the jobs service triggered "${id}", which is no enabled builtin job`);
|
||||
}, log);
|
||||
}
|
||||
|
||||
// The public health check asks the spawner at most every few seconds, so it cannot be used to flood it.
|
||||
let health = { ok: true, checkedAt: 0 };
|
||||
async function healthy(): Promise<boolean>
|
||||
|
||||
@@ -90,6 +90,7 @@ describe('backend', () => {
|
||||
frontendDir: '',
|
||||
contentDir: '',
|
||||
jobsFile: '',
|
||||
triggerDir: '',
|
||||
siteUrl: 'https://security-command.org',
|
||||
legalPages: new Map(),
|
||||
statusDir: '',
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,13 @@ if [[ ! -d ${CONTENT_DIR:-} || ${CONTENT_DIR} != /* ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Jobs run as the owner of the content directory, which must not be root.
|
||||
jobs_user=$(stat -c %u:%g "$CONTENT_DIR")
|
||||
if [[ ${jobs_user%%:*} == 0 ]]; then
|
||||
echo "CONTENT_DIR is owned by root; give it to the user that maintains the content, jobs run as that user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
registry_host=${REGISTRY%%/*}
|
||||
if ! grep -qs "\"${registry_host}\"" ~/.docker/config.json; then
|
||||
echo "log in to the registry first: docker login ${registry_host} (token with read:package)" >&2
|
||||
@@ -75,20 +82,26 @@ commit=$(as_owner git rev-parse HEAD)
|
||||
sandbox_tag="${REGISTRY}/homepage-sandbox:${commit}"
|
||||
spawner_tag="${REGISTRY}/homepage-spawner:${commit}"
|
||||
backend_tag="${REGISTRY}/homepage-backend:${commit}"
|
||||
jobs_tag="${REGISTRY}/homepage-jobs:${commit}"
|
||||
pull_image sandbox_docker "$sandbox_tag"
|
||||
pull_image docker "$spawner_tag"
|
||||
pull_image docker "$backend_tag"
|
||||
pull_image docker "$jobs_tag"
|
||||
digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; }
|
||||
|
||||
# The spawner runs as 10001 and shares group 10100 with the backend, which
|
||||
# runs as 10002 and writes the status file that sandboxes read.
|
||||
install -d -m 0755 runtime config jobs
|
||||
# runs as 10002 and writes the status file that sandboxes read. The jobs
|
||||
# service writes the job file and the triggers the backend reads.
|
||||
install -d -m 0755 runtime
|
||||
install -d -o 10001 -g 10100 -m 0750 runtime/spawner
|
||||
install -d -o 10002 -g 10002 -m 0755 runtime/status
|
||||
install -d -o "${jobs_user%%:*}" -g "${jobs_user##*:}" -m 0755 config jobs runtime/jobs runtime/jobs/triggers
|
||||
cat > runtime/deploy.env <<EOF
|
||||
SANDBOX_IMAGE=$(digest sandbox_docker "$sandbox_tag")
|
||||
SPAWNER_IMAGE=$(digest docker "$spawner_tag")
|
||||
BACKEND_IMAGE=$(digest docker "$backend_tag")
|
||||
JOBS_IMAGE=$(digest docker "$jobs_tag")
|
||||
JOBS_USER=${jobs_user}
|
||||
SANDBOX_GROUP_ID=$(getent group sandbox-spawner | cut -d: -f3)
|
||||
STATUS_DIR=${PWD}/runtime/status
|
||||
EOF
|
||||
@@ -102,3 +115,4 @@ docker compose --project-directory "$PWD" -f deploy/compose.yml \
|
||||
--env-file .env --env-file runtime/deploy.env up -d --remove-orphans
|
||||
|
||||
echo "deployed ${commit}"
|
||||
echo "jobs: docker exec security-command-jobs-1 jobctl list"
|
||||
@@ -47,6 +47,7 @@ services:
|
||||
STATUS_DIR: /run/status
|
||||
CONTENT_DIR: /content
|
||||
JOBS_FILE: /config/jobs.toml
|
||||
TRIGGER_DIR: /run/jobs/triggers
|
||||
SITE_URL: ${SITE_URL:-https://security-command.org}
|
||||
LEGAL_PAGES: ${LEGAL_PAGES:-impressum:impressum.txt,datenschutz:datenschutz.txt}
|
||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://security-command.org}
|
||||
@@ -58,6 +59,39 @@ services:
|
||||
- ./runtime/status:/run/status
|
||||
- ${CONTENT_DIR}:/content:ro
|
||||
- ./config:/config:ro
|
||||
- ./runtime/jobs/triggers:/run/jobs/triggers:ro
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
|
||||
jobs:
|
||||
image: ${JOBS_IMAGE:?run deploy.sh}
|
||||
restart: unless-stopped
|
||||
# Jobs run as the owner of the content directory, so they can write into it.
|
||||
user: "${JOBS_USER:?run deploy.sh}"
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
mem_limit: 256m
|
||||
pids_limit: 128
|
||||
environment:
|
||||
JOBS_FILE: /config/jobs.toml
|
||||
SCRIPTS_DIR: /jobs
|
||||
CONTENT_DIR: /content
|
||||
HOST_DIR: /host/srv
|
||||
TRIGGER_DIR: /run/jobs/triggers
|
||||
CONTROL_SOCKET: /run/jobs/control.sock
|
||||
volumes:
|
||||
- ${CONTENT_DIR}:/content
|
||||
- ./config:/config
|
||||
- ./jobs:/jobs:ro
|
||||
- ${JOBS_HOST_DIR:-/srv}:/host/srv:ro
|
||||
- ./runtime/jobs:/run/jobs
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
# read it; jobs may write into it.
|
||||
CONTENT_DIR=
|
||||
|
||||
# Host directory job scripts see read only at /host/srv, for example to
|
||||
# describe the services running next to this one.
|
||||
JOBS_HOST_DIR=/srv
|
||||
|
||||
# Public address of the site, used by the sitemap.
|
||||
SITE_URL=https://security-command.org
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Reference for config/jobs.toml. The jobs service creates that file on its
|
||||
# first start with the system jobs, and adds system jobs it lacks on every
|
||||
# start. Edits apply within a second, which restarts all schedules as if the
|
||||
# services had just started.
|
||||
#
|
||||
# Each [[job]] needs exactly one of:
|
||||
# builtin a job implemented in the backend: index, status, reap-orphans
|
||||
# path a script in jobs/, run by the jobs service; it must be executable
|
||||
#
|
||||
# Options:
|
||||
# id lowercase letters, digits and dashes; unique
|
||||
# args list of arguments for the script
|
||||
# every run at a fixed interval: "30s", "15m", "1h", "1d"; at least 1s
|
||||
# cron run on a cron schedule in UTC: "0 4 * * *"
|
||||
# on events: "start", "content-change" (builtin jobs only) and "watch"
|
||||
# watch paths relative to /srv on the host; needs on = ["watch"]. A
|
||||
# directory is watched with everything inside it. The job runs
|
||||
# once things have been quiet for 2s.
|
||||
# then jobs to trigger after a successful run, builtin ones included
|
||||
# timeout run time after which the job is cancelled; default "5m"
|
||||
# env table of extra environment variables
|
||||
# enabled false switches the job off and logs a warning; default true
|
||||
# parallel true lets runs overlap. By default a new trigger cancels the
|
||||
# running run and starts the job over.
|
||||
#
|
||||
# Scripts run as the owner of the content directory with bash, coreutils, curl,
|
||||
# git and jq available, and get these variables:
|
||||
# JOB_ID the id of the job
|
||||
# CONTENT_DIR the content directory, writable
|
||||
# HOST_DIR /srv of the host, read only
|
||||
#
|
||||
# Cancelling sends SIGTERM to the script and everything it started, then
|
||||
# SIGKILL after 5s. Processes a script leaves behind are killed when it exits.
|
||||
#
|
||||
# Manage jobs with jobctl inside the jobs container:
|
||||
# docker exec security-command-jobs-1 jobctl list
|
||||
# docker exec security-command-jobs-1 jobctl run services
|
||||
# docker exec security-command-jobs-1 jobctl cancel services
|
||||
|
||||
# Describes the services next to this one in services/, whenever one of their
|
||||
# compose files changes, and rebuilds the static site right away.
|
||||
[[job]]
|
||||
id = "services"
|
||||
path = "services.sh"
|
||||
on = ["start", "watch"]
|
||||
watch = ["gitea/compose.yml", "nextcloud/compose.yml"]
|
||||
then = ["index"]
|
||||
|
||||
# Mirrors a public repository into the content once a night.
|
||||
[[job]]
|
||||
id = "mirror"
|
||||
path = "mirror.sh"
|
||||
args = ["https://example.org/notes.git", "notes"]
|
||||
cron = "0 4 * * *"
|
||||
timeout = "10m"
|
||||
env = { GIT_TERMINAL_PROMPT = "0" }
|
||||
enabled = false
|
||||
@@ -27,12 +27,14 @@ export type JobDefinition = {
|
||||
|
||||
export type LoadedJobs = {
|
||||
jobs: JobDefinition[];
|
||||
/** False when the file is not valid TOML; then nothing should be appended to it. */
|
||||
parsed: boolean;
|
||||
/** System jobs the file does not mention yet, as TOML ready to be appended. */
|
||||
missing: string;
|
||||
warnings: string[];
|
||||
};
|
||||
|
||||
const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
||||
export const JOB_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
||||
const EVENTS = new Set<JobEvent>(['start', 'content-change', 'watch']);
|
||||
const KEYS = new Set(['id', 'builtin', 'path', 'args', 'every', 'cron', 'on', 'watch', 'then', 'timeout', 'env', 'enabled', 'parallel']);
|
||||
const DEFAULT_TIMEOUT = '5m';
|
||||
@@ -78,7 +80,7 @@ function validate(raw: Record<string, unknown>): JobDefinition
|
||||
if (unknown.length > 0) fail(`unknown keys ${unknown.join(', ')}`);
|
||||
|
||||
const { id, builtin, path, every, cron, timeout, env, enabled, parallel } = raw;
|
||||
if (typeof id !== 'string' || !ID.test(id)) fail('id must be lowercase letters, digits and dashes');
|
||||
if (typeof id !== 'string' || !JOB_ID.test(id)) fail('id must be lowercase letters, digits and dashes');
|
||||
if ((builtin === undefined) === (path === undefined)) fail('needs exactly one of builtin or path');
|
||||
if (builtin !== undefined && typeof builtin !== 'string') fail('builtin must be a string');
|
||||
if (path !== undefined && typeof path !== 'string') fail('path must be a string');
|
||||
@@ -152,8 +154,13 @@ export function loadJobs(text: string): LoadedJobs
|
||||
const jobs: JobDefinition[] = [];
|
||||
|
||||
let raw: unknown[] = [];
|
||||
let parsed = true;
|
||||
try { raw = entries(text); }
|
||||
catch (error) { warnings.push(`the job file cannot be read, only system jobs run: ${(error as Error).message}`); }
|
||||
catch (error)
|
||||
{
|
||||
parsed = false;
|
||||
warnings.push(`the job file cannot be read, only system jobs run: ${(error as Error).message}`);
|
||||
}
|
||||
|
||||
for (const [index, entry] of raw.entries())
|
||||
{
|
||||
@@ -186,5 +193,5 @@ export function loadJobs(text: string): LoadedJobs
|
||||
for (const next of job.then) if (!jobs.some((other) => other.id === next)) warnings.push(`job "${job.id}" triggers unknown job "${next}"`);
|
||||
}
|
||||
|
||||
return { jobs, missing: missing.length > 0 ? `\n${missing.join('\n\n')}\n` : '', warnings };
|
||||
return { jobs, parsed, missing: missing.length > 0 ? `\n${missing.join('\n\n')}\n` : '', warnings };
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
export * from './duration.ts';
|
||||
export * from './definition.ts';
|
||||
export * from './scheduler.ts';
|
||||
export * from './watch.ts';
|
||||
export * from './triggers.ts';
|
||||
@@ -0,0 +1,23 @@
|
||||
import { mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { watchTriggers, writeTrigger } from './triggers.ts';
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
describe('triggers', () => {
|
||||
it('delivers each write once and ignores invalid names', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'triggers-'));
|
||||
const triggered: string[] = [];
|
||||
const watcher = watchTriggers(dir, (id) => triggered.push(id), () => {});
|
||||
|
||||
await writeTrigger(dir, 'index');
|
||||
await writeTrigger(dir, 'index');
|
||||
await expect(writeTrigger(dir, '../escape')).rejects.toThrow('invalid job id');
|
||||
await sleep(300);
|
||||
watcher?.close();
|
||||
|
||||
expect(triggered).toEqual(['index']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { watch, type FSWatcher } from 'node:fs';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { JOB_ID } from './definition.ts';
|
||||
import type { Log } from './watch.ts';
|
||||
|
||||
/**
|
||||
* Builtin jobs run in the backend and script jobs in the jobs service. The
|
||||
* jobs service triggers a builtin job by writing a file named after it into a
|
||||
* directory the backend watches, so neither needs a socket to the other.
|
||||
*/
|
||||
const TRIGGER_QUIET_MS = 100;
|
||||
|
||||
export async function writeTrigger(directory: string, id: string): Promise<void>
|
||||
{
|
||||
if (!JOB_ID.test(id)) throw new Error(`invalid job id "${id}"`);
|
||||
await writeFile(join(directory, id), `${Date.now()}\n`);
|
||||
}
|
||||
|
||||
export function watchTriggers(directory: string, onTrigger: (id: string) => void, log: Log): FSWatcher | undefined
|
||||
{
|
||||
const pending = new Map<string, NodeJS.Timeout>();
|
||||
try
|
||||
{
|
||||
const watcher = watch(directory, (_event, name) =>
|
||||
{
|
||||
if (!name || !JOB_ID.test(name)) return;
|
||||
|
||||
// One write raises several events, which count as one trigger.
|
||||
clearTimeout(pending.get(name));
|
||||
pending.set(name, setTimeout(() =>
|
||||
{
|
||||
pending.delete(name);
|
||||
onTrigger(name);
|
||||
}, TRIGGER_QUIET_MS));
|
||||
});
|
||||
watcher.on('error', (error) => log(`stopped watching ${directory} for triggers: ${error.message}`));
|
||||
watcher.on('close', () => { for (const timer of pending.values()) clearTimeout(timer); });
|
||||
return watcher;
|
||||
}
|
||||
catch (error)
|
||||
{
|
||||
log(`cannot watch ${directory} for triggers from the jobs service: ${(error as Error).message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { statSync, watch, type FSWatcher } from 'node:fs';
|
||||
import { basename, dirname } from 'node:path';
|
||||
|
||||
export type Log = (message: string) => void;
|
||||
|
||||
/** Calls back once a directory tree has been quiet for the given time after a change. */
|
||||
export function watchTree(directory: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
|
||||
{
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try
|
||||
{
|
||||
const watcher = watch(directory, { recursive: true }, () =>
|
||||
{
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(onChange, quietMs);
|
||||
});
|
||||
watcher.on('error', (error) => log(`stopped watching ${directory}: ${error.message}`));
|
||||
watcher.on('close', () => clearTimeout(timer));
|
||||
return watcher;
|
||||
}
|
||||
catch (error)
|
||||
{
|
||||
log(`cannot watch ${directory}: ${(error as Error).message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Watches a single file through its directory, because editors and atomic
|
||||
* writes replace files, which would end a watch on the old one. This also
|
||||
* notices a file that does not exist yet.
|
||||
*/
|
||||
export function watchFile(file: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
|
||||
{
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try
|
||||
{
|
||||
const watcher = watch(dirname(file), (_event, name) =>
|
||||
{
|
||||
if (name !== basename(file)) return;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(onChange, quietMs);
|
||||
});
|
||||
watcher.on('error', (error) => log(`stopped watching ${file}: ${error.message}`));
|
||||
watcher.on('close', () => clearTimeout(timer));
|
||||
return watcher;
|
||||
}
|
||||
catch (error)
|
||||
{
|
||||
log(`cannot watch ${file}: ${(error as Error).message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Watches a directory tree, or a file when the path is not a directory. */
|
||||
export function watchPath(path: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
|
||||
{
|
||||
let directory = false;
|
||||
try { directory = statSync(path).isDirectory(); }
|
||||
catch { /* A missing path is watched like a file, so its creation counts as a change. */ }
|
||||
|
||||
return directory ? watchTree(path, quietMs, onChange, log) : watchFile(path, quietMs, onChange, log);
|
||||
}
|
||||
Generated
+9
@@ -223,6 +223,15 @@ importers:
|
||||
specifier: ^8.3.4
|
||||
version: 8.3.4(@types/node@26.6.5)(esbuild@0.28.2)
|
||||
|
||||
apps/jobs:
|
||||
dependencies:
|
||||
'@homepage/jobs':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/jobs
|
||||
'@homepage/protocol':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/protocol
|
||||
|
||||
apps/spawner:
|
||||
dependencies:
|
||||
'@homepage/protocol':
|
||||
|
||||
Reference in new issue
Block a user