From 0ad5b5f44f11729907da593c2848ce6b706cb7c0 Mon Sep 17 00:00:00 2001 From: Overlord Date: Tue, 13 Oct 2026 15:04:21 +0200 Subject: [PATCH] Add jobs service with script execution, configuration support, and control interface. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/images.yml | 17 ++ apps/backend/src/builtins.test.ts | 10 ++ apps/backend/src/builtins.ts | 5 + apps/backend/src/config.ts | 3 + apps/backend/src/jobs.ts | 44 +---- apps/backend/src/main.ts | 12 +- apps/backend/src/server.test.ts | 1 + apps/jobs/Dockerfile | 16 ++ apps/jobs/package.json | 12 ++ apps/jobs/src/config.ts | 29 ++++ apps/jobs/src/control.ts | 85 ++++++++++ apps/jobs/src/jobctl.ts | 61 +++++++ apps/jobs/src/main.ts | 21 +++ apps/jobs/src/runner.test.ts | 84 ++++++++++ apps/jobs/src/runner.ts | 95 +++++++++++ apps/jobs/src/service.test.ts | 140 ++++++++++++++++ apps/jobs/src/service.ts | 247 +++++++++++++++++++++++++++++ deploy.sh | 18 ++- deploy/compose.yml | 34 ++++ deploy/env.example | 4 + deploy/jobs.example.toml | 57 +++++++ packages/jobs/src/definition.ts | 15 +- packages/jobs/src/index.ts | 2 + packages/jobs/src/triggers.test.ts | 23 +++ packages/jobs/src/triggers.ts | 46 ++++++ packages/jobs/src/watch.ts | 63 ++++++++ pnpm-lock.yaml | 9 ++ 27 files changed, 1108 insertions(+), 45 deletions(-) create mode 100644 apps/jobs/Dockerfile create mode 100644 apps/jobs/package.json create mode 100644 apps/jobs/src/config.ts create mode 100644 apps/jobs/src/control.ts create mode 100644 apps/jobs/src/jobctl.ts create mode 100644 apps/jobs/src/main.ts create mode 100644 apps/jobs/src/runner.test.ts create mode 100644 apps/jobs/src/runner.ts create mode 100644 apps/jobs/src/service.test.ts create mode 100644 apps/jobs/src/service.ts create mode 100644 deploy/jobs.example.toml create mode 100644 packages/jobs/src/triggers.test.ts create mode 100644 packages/jobs/src/triggers.ts create mode 100644 packages/jobs/src/watch.ts diff --git a/.gitea/workflows/images.yml b/.gitea/workflows/images.yml index d89dc54..13ee1e0 100644 --- a/.gitea/workflows/images.yml +++ b/.gitea/workflows/images.yml @@ -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" diff --git a/apps/backend/src/builtins.test.ts b/apps/backend/src/builtins.test.ts index a2ebf74..dcbe533 100644 --- a/apps/backend/src/builtins.test.ts +++ b/apps/backend/src/builtins.test.ts @@ -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); diff --git a/apps/backend/src/builtins.ts b/apps/backend/src/builtins.ts index 01ca9b1..0f64fc0 100644 --- a/apps/backend/src/builtins.ts +++ b/apps/backend/src/builtins.ts @@ -21,6 +21,7 @@ const CONTENT_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 64 * 1024 * 1 export function createBuiltins(dependencies: BuiltinDependencies): Record { const { config, hub, spawner, log } = dependencies; + let lastHash = ''; let lastWarnings = ''; return { @@ -29,6 +30,10 @@ export function createBuiltins(dependencies: BuiltinDependencies): Record Promise; @@ -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, log: (message: string) => void) { @@ -31,27 +29,16 @@ export class BackendJobs async start(): Promise { 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; - } -} diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index c4f577b..c16e113 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -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 diff --git a/apps/backend/src/server.test.ts b/apps/backend/src/server.test.ts index 72ed689..50ed2c1 100644 --- a/apps/backend/src/server.test.ts +++ b/apps/backend/src/server.test.ts @@ -90,6 +90,7 @@ describe('backend', () => { frontendDir: '', contentDir: '', jobsFile: '', + triggerDir: '', siteUrl: 'https://security-command.org', legalPages: new Map(), statusDir: '', diff --git a/apps/jobs/Dockerfile b/apps/jobs/Dockerfile new file mode 100644 index 0000000..82041ba --- /dev/null +++ b/apps/jobs/Dockerfile @@ -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"] diff --git a/apps/jobs/package.json b/apps/jobs/package.json new file mode 100644 index 0000000..50bf6b2 --- /dev/null +++ b/apps/jobs/package.json @@ -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:*" + } +} diff --git a/apps/jobs/src/config.ts b/apps/jobs/src/config.ts new file mode 100644 index 0000000..01094b2 --- /dev/null +++ b/apps/jobs/src/config.ts @@ -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, + }; +} diff --git a/apps/jobs/src/control.ts b/apps/jobs/src/control.ts new file mode 100644 index 0000000..ff8b091 --- /dev/null +++ b/apps/jobs/src/control.ts @@ -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 +{ + 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 +{ + 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 +{ + 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 +{ + 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()); + }); + }); +} diff --git a/apps/jobs/src/jobctl.ts b/apps/jobs/src/jobctl.ts new file mode 100644 index 0000000..bd768b5 --- /dev/null +++ b/apps/jobs/src/jobctl.ts @@ -0,0 +1,61 @@ +import { request, type ControlRequest } from './control.ts'; +import type { JobState, RunRecord } from './service.ts'; + +const usage = 'usage: jobctl list | run | cancel '; + +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); diff --git a/apps/jobs/src/main.ts b/apps/jobs/src/main.ts new file mode 100644 index 0000000..8ded347 --- /dev/null +++ b/apps/jobs/src/main.ts @@ -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); + }); +} diff --git a/apps/jobs/src/runner.test.ts b/apps/jobs/src/runner.test.ts new file mode 100644 index 0000000..5c720d3 --- /dev/null +++ b/apps/jobs/src/runner.test.ts @@ -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 +{ + 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); + }); +}); diff --git a/apps/jobs/src/runner.ts b/apps/jobs/src/runner.ts new file mode 100644 index 0000000..e739e4b --- /dev/null +++ b/apps/jobs/src/runner.ts @@ -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; + 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 +{ + 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}`)); + }); + }); +} diff --git a/apps/jobs/src/service.test.ts b/apps/jobs/src/service.test.ts new file mode 100644 index 0000000..1e54f75 --- /dev/null +++ b/apps/jobs/src/service.test.ts @@ -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 = {}) +{ + 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'); + }); +}); diff --git a/apps/jobs/src/service.ts b/apps/jobs/src/service.ts new file mode 100644 index 0000000..699899f --- /dev/null +++ b/apps/jobs/src/service.ts @@ -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 +{ + 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(); + private definitions = new Map(); + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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(); + } + } +} diff --git a/deploy.sh b/deploy.sh index 55c74a7..65ddad6 100755 --- a/deploy.sh +++ b/deploy.sh @@ -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 <(['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): 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 }; } diff --git a/packages/jobs/src/index.ts b/packages/jobs/src/index.ts index 7a6c2f1..d578631 100644 --- a/packages/jobs/src/index.ts +++ b/packages/jobs/src/index.ts @@ -1,3 +1,5 @@ export * from './duration.ts'; export * from './definition.ts'; export * from './scheduler.ts'; +export * from './watch.ts'; +export * from './triggers.ts'; diff --git a/packages/jobs/src/triggers.test.ts b/packages/jobs/src/triggers.test.ts new file mode 100644 index 0000000..cb93675 --- /dev/null +++ b/packages/jobs/src/triggers.test.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']); + }); +}); diff --git a/packages/jobs/src/triggers.ts b/packages/jobs/src/triggers.ts new file mode 100644 index 0000000..895936e --- /dev/null +++ b/packages/jobs/src/triggers.ts @@ -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 +{ + 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(); + 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; + } +} diff --git a/packages/jobs/src/watch.ts b/packages/jobs/src/watch.ts new file mode 100644 index 0000000..100beb1 --- /dev/null +++ b/packages/jobs/src/watch.ts @@ -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); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 007cdfd..6d78f3f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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':