feat(server): request updates through a systemd trigger (#15)
The service stays unprivileged: POST /api/settings/update only writes the update-request file in the data directory, which a root-owned path unit watches. Status comes from systemctl show and the root-owned update log; the check fetches the tracked branch into FETCH_HEAD and lists new commits.
This commit is contained in:
@@ -10,6 +10,7 @@ import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
import { chatPlugin } from "./chat";
|
||||
import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
@@ -26,6 +27,8 @@ export interface AppOptions {
|
||||
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
|
||||
watchNotebooks?: boolean;
|
||||
terminal?: Omit<TerminalOptions, "workspaceDir">;
|
||||
/** Overrides for the self-update trigger (tests). */
|
||||
update?: Partial<UpdateOptions>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,7 +36,7 @@ export interface AppOptions {
|
||||
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
|
||||
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
|
||||
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
|
||||
* src/static/ built web app with SPA fallback
|
||||
* src/static/ built web app with SPA fallback; src/update/ self-update trigger (root runs it via systemd)
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = loadConfig(options.config);
|
||||
@@ -41,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await registerSettings(app, config);
|
||||
await registerUpdate(app, { ...defaultUpdateOptions(config.dataDir), ...options.update });
|
||||
await app.register(websocket);
|
||||
const builtins = () => builtinValues(config);
|
||||
await app.register(workspacePlugin, { config, builtins });
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, mkdir, open, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type {
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateState,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* Self-update from the web UI (#15). The service never gains privileges: it only writes
|
||||
* a request file. A root-owned systemd path unit (deploy/install.sh) watches that file
|
||||
* and starts `shellbook-update.service`, which runs the fixed root-owned updater and
|
||||
* writes its output to a root-owned log. Here we only read that state back.
|
||||
*/
|
||||
export interface UpdateOptions {
|
||||
/** Written to request an update; watched by shellbook-update.path. */
|
||||
requestFile: string;
|
||||
/** Present when the trigger units are installed. */
|
||||
triggerUnit: string;
|
||||
/** Output of the last update run (StandardOutput of the update unit). */
|
||||
logFile: string;
|
||||
/** The git checkout the server runs from. */
|
||||
repoDir: string;
|
||||
/** Runs a program with argv (no shell) and returns stdout; rejects on failure. */
|
||||
run(file: string, args: string[], timeoutMs: number): Promise<string>;
|
||||
}
|
||||
|
||||
const UNIT = "shellbook-update.service";
|
||||
const LOG_BYTES = 64 * 1024;
|
||||
const LOG_LINES = 200;
|
||||
|
||||
function run(file: string, args: string[], timeoutMs: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
file,
|
||||
args,
|
||||
// Never wait for credentials on a terminal that is not there.
|
||||
{ timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
|
||||
(error, stdout) => (error ? reject(error) : resolve(stdout)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function defaultUpdateOptions(dataDir: string): UpdateOptions {
|
||||
return {
|
||||
requestFile: join(dataDir, "update-request"),
|
||||
triggerUnit: "/etc/systemd/system/shellbook-update.path",
|
||||
logFile: "/var/log/shellbook-update.log",
|
||||
// systemd starts the service in the checkout (WorkingDirectory=/opt/shellbook).
|
||||
repoDir: process.cwd(),
|
||||
run,
|
||||
};
|
||||
}
|
||||
|
||||
/** `--timestamp=unix` prints `@<seconds>`; empty or `n/a` means never. */
|
||||
function timestamp(value: string | undefined): string | null {
|
||||
const match = value?.match(/^@(\d+)$/);
|
||||
return match ? new Date(Number(match[1]) * 1000).toISOString() : null;
|
||||
}
|
||||
|
||||
/** The last lines of the log, reading at most LOG_BYTES from its end. */
|
||||
async function logTail(path: string): Promise<string> {
|
||||
let file;
|
||||
try {
|
||||
file = await open(path, "r");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
const length = Math.min(size, LOG_BYTES);
|
||||
const buffer = Buffer.alloc(length);
|
||||
await file.read(buffer, 0, length, size - length);
|
||||
const lines = buffer.toString("utf8").split("\n");
|
||||
// Drop a partial first line when the read started mid-file.
|
||||
if (length < size) lines.shift();
|
||||
if (lines.at(-1) === "") lines.pop();
|
||||
return lines.slice(-LOG_LINES).join("\n");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function createUpdater(options: UpdateOptions) {
|
||||
const git = (args: string[], timeoutMs = 5000) =>
|
||||
options.run("git", ["-C", options.repoDir, ...args], timeoutMs).then((out) => out.trim());
|
||||
const current = () => git(["rev-parse", "--short", "HEAD"]).catch(() => null);
|
||||
const available = () => access(options.triggerUnit).then(() => true, () => false);
|
||||
|
||||
async function unitState(): Promise<Pick<UpdateStatusResponse, "state" | "startedAt" | "finishedAt">> {
|
||||
let output: string;
|
||||
try {
|
||||
output = await options.run(
|
||||
"systemctl",
|
||||
["show", UNIT, "--timestamp=unix", "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp"],
|
||||
5000,
|
||||
);
|
||||
} catch {
|
||||
return { state: "unknown", startedAt: null, finishedAt: null };
|
||||
}
|
||||
const props: Record<string, string> = Object.fromEntries(
|
||||
output.split("\n").filter((line) => line.includes("=")).map((line) => {
|
||||
const at = line.indexOf("=");
|
||||
return [line.slice(0, at), line.slice(at + 1).trim()];
|
||||
}),
|
||||
);
|
||||
const startedAt = timestamp(props.ExecMainStartTimestamp);
|
||||
const finishedAt = timestamp(props.ExecMainExitTimestamp);
|
||||
let state: UpdateState;
|
||||
if (["activating", "active", "reloading", "deactivating"].includes(props.ActiveState ?? "")) state = "running";
|
||||
else if (props.ActiveState === "failed" || (startedAt && props.Result !== "success")) state = "failed";
|
||||
else state = startedAt ? "succeeded" : "idle";
|
||||
return { state, startedAt, finishedAt: state === "running" ? null : finishedAt };
|
||||
}
|
||||
|
||||
return {
|
||||
async status(): Promise<UpdateStatusResponse> {
|
||||
const [isAvailable, commit] = await Promise.all([available(), current()]);
|
||||
if (!isAvailable)
|
||||
return { available: false, state: "idle", current: commit, startedAt: null, finishedAt: null, log: "" };
|
||||
return { available: true, current: commit, ...(await unitState()), log: await logTail(options.logFile) };
|
||||
},
|
||||
|
||||
/** Fetches the tracked branch (FETCH_HEAD only) and lists the commits an update would bring. */
|
||||
async check(): Promise<UpdateCheckResponse> {
|
||||
const commit = await current();
|
||||
const branch = await git(["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null);
|
||||
// A detached HEAD is a pinned SHELLBOOK_REF: the installer never pulls it.
|
||||
if (!branch) return { current: commit, latest: null, pinned: true, changes: [] };
|
||||
const upstream = await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
|
||||
const slash = upstream.indexOf("/");
|
||||
if (slash <= 0) throw new Error(`Unexpected upstream: ${upstream}`);
|
||||
await git(["fetch", "--quiet", "--no-tags", "--", upstream.slice(0, slash), upstream.slice(slash + 1)], 30_000);
|
||||
const latest = await git(["rev-parse", "--short", "FETCH_HEAD"]);
|
||||
const log = await git(["log", "--format=%h%x09%s", "-n", "50", "HEAD..FETCH_HEAD"]);
|
||||
const changes = log
|
||||
? log.split("\n").map((line) => {
|
||||
const tab = line.indexOf("\t");
|
||||
return { commit: line.slice(0, tab), subject: line.slice(tab + 1) };
|
||||
})
|
||||
: [];
|
||||
return { current: commit, latest, pinned: false, changes };
|
||||
},
|
||||
|
||||
/** Requests an update; systemd runs it as root. Returns null when it cannot start. */
|
||||
async start(): Promise<{ ok: true; response: UpdateStartResponse } | { ok: false; error: string }> {
|
||||
if (!(await available())) return { ok: false, error: "Updating from the web UI is not installed here. Run shellbook-update as root." };
|
||||
if ((await unitState()).state === "running") return { ok: false, error: "An update is already running." };
|
||||
const requestedAt = new Date().toISOString();
|
||||
await mkdir(dirname(options.requestFile), { recursive: true });
|
||||
// Closing the written file is what triggers the path unit (PathChanged=).
|
||||
await writeFile(options.requestFile, requestedAt + "\n", { mode: 0o600 });
|
||||
return { ok: true, response: { requestedAt } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function registerUpdate(app: FastifyInstance, options: UpdateOptions): Promise<void> {
|
||||
const updater = createUpdater(options);
|
||||
app.get("/api/settings/update", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await updater.status()),
|
||||
);
|
||||
app.post("/api/settings/update/check", async (_request, reply) => {
|
||||
if ((await updater.status()).state === "running")
|
||||
return reply.code(409).send({ error: "An update is running." });
|
||||
try {
|
||||
return reply.header("Cache-Control", "no-store").send(await updater.check());
|
||||
} catch (error) {
|
||||
app.log.warn({ err: error }, "update check failed");
|
||||
return reply.code(502).send({ error: "Could not check the repository for updates." });
|
||||
}
|
||||
});
|
||||
app.post("/api/settings/update", async (_request, reply) => {
|
||||
const result = await updater.start();
|
||||
return result.ok ? reply.code(202).send(result.response) : reply.code(409).send({ error: result.error });
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user