From 55eb5ce5f86b09a6a0b609c2399a64dd90dccef3 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 26 Oct 2026 11:52:03 +0000 Subject: [PATCH 1/4] fix(update): finish in-app updates under systemd and fail attempts whose worker died --- CHANGELOG.md | 9 +++ bin/omp-web-update-worker.js | 24 +++++++- bin/omp-web-update-worker.test.mjs | 60 +++++++++++++++++++ lib/self-update.test.mjs | 92 ++++++++++++++++++++++++++++++ lib/self-update.ts | 78 +++++++++++++++++++++++-- 5 files changed, 258 insertions(+), 5 deletions(-) create mode 100644 bin/omp-web-update-worker.test.mjs create mode 100644 lib/self-update.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 996a5f922..f25ddce22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f --- +## [Unreleased] + +### Fixes & Improvements + +- **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. +- **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. + +--- + ## [v0.6.0] - 2026-10-26 ### Added diff --git a/bin/omp-web-update-worker.js b/bin/omp-web-update-worker.js index c0151620e..b871678c4 100644 --- a/bin/omp-web-update-worker.js +++ b/bin/omp-web-update-worker.js @@ -28,6 +28,9 @@ const from = arg("--from"); const launcherPid = Number(arg("--launcher-pid")); const serverPid = Number(arg("--server-pid")); const kind = arg("--kind") || "app"; +// Set when the server runs as this systemd unit; systemd stops and starts it. +const systemdUnit = arg("--systemd-unit"); +const systemctlScope = arg("--systemd-user") === "1" ? ["--user"] : []; let descriptor; let managerPrefix; try { @@ -76,9 +79,20 @@ function isTrayActive() { return Boolean(data && data.pid); } catch { return false; } } +function systemctl(action) { + const result = cp.spawnSync("systemctl", [...systemctlScope, action, systemdUnit], { encoding: "utf8", timeout: 120000 }); + if (result.status !== 0) { + const detail = (result.stderr || (result.error && result.error.message) || "").trim().slice(0, 200); + throw new Error(`systemctl ${action} ${systemdUnit} failed${detail ? `: ${detail}` : ""}`); + } +} async function stopOriginalProcesses() { updateStatus({ stage: "stopping" }); + if (systemdUnit) { + systemctl("stop"); + return { systemd: true, launchd: false, tray: false }; + } // Detect services const launchd = isLaunchdActive(); const tray = isTrayActive(); @@ -158,6 +172,10 @@ async function runManagerGate() { async function restartServices(info) { updateStatus({ stage: "restarting" }); + if (info.systemd) { + systemctl("start"); + return; + } if (info.launchd) { try { const uid = typeof process.getuid === "function" ? process.getuid() : 501; @@ -228,7 +246,11 @@ async function main() { // write complete marker try { atomicWrite(markerFile("complete.json"), { attemptId, completedAt: new Date().toISOString() }); } catch {} } catch (e) { - const msg = e instanceof Error ? e.message : String(e); + let msg = e instanceof Error ? e.message : String(e); + // Never leave the service stopped after a failed install. + if (systemdUnit) { + try { systemctl("start"); } catch { msg = `${systemdUnit} is still stopped: ${msg}`; } + } updateStatus({ state: "failed", error: msg.slice(0, 240), finishedAt: new Date().toISOString(), cleanupReady: true }); } } diff --git a/bin/omp-web-update-worker.test.mjs b/bin/omp-web-update-worker.test.mjs new file mode 100644 index 000000000..d101efe2c --- /dev/null +++ b/bin/omp-web-update-worker.test.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { delimiter, join } from "node:path"; +import { tmpdir } from "node:os"; +import test from "node:test"; + +const WORKER = new URL("./omp-web-update-worker.js", import.meta.url).pathname; +const ATTEMPT = "11111111-2222-3333-4444-555555555555"; + +// Runs the worker for a systemd unit with stub `systemctl` and `npm` on PATH. +function runWorker(t, { npmExit = 0, startExit = 0 } = {}) { + const dir = mkdtempSync(join(tmpdir(), "update-worker-test-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const log = join(dir, "calls.log"); + writeFileSync(join(dir, "systemctl"), `#!/bin/sh\necho "systemctl $*" >> "${log}"\n[ "$2" = start ] && exit ${startExit}\nexit 0\n`, { mode: 0o755 }); + writeFileSync(join(dir, "npm"), `#!/bin/sh\necho "npm $*" >> "${log}"\nexit ${npmExit}\n`, { mode: 0o755 }); + writeFileSync(join(dir, "status.json"), JSON.stringify({ attemptId: ATTEMPT, state: "running" }), { mode: 0o600 }); + writeFileSync(join(dir, `${ATTEMPT}.go`), "{}", { mode: 0o600 }); + const result = spawnSync(process.execPath, [ + WORKER, + "--attempt", ATTEMPT, + "--root", dir, + "--package-dir", dir, + "--manager", "npm", + "--manager-path", "npm", + "--target", "0.6.0", + "--kind", "app", + "--systemd-unit", "ompweb.service", + "--systemd-user", "1", + ], { env: { ...process.env, PATH: `${dir}${delimiter}${process.env.PATH}` }, timeout: 20000 }); + assert.equal(result.status, 0, String(result.stderr)); + return { + calls: readFileSync(log, "utf8").trim().split("\n"), + status: JSON.parse(readFileSync(join(dir, "status.json"), "utf8")), + }; +} + +test("a systemd update stops the unit, installs, then starts it", { skip: process.platform === "win32" }, (t) => { + const { calls, status } = runWorker(t); + assert.deepEqual(calls, [ + "systemctl --user stop ompweb.service", + "npm install -g @kahme247/ompweb@0.6.0", + "systemctl --user start ompweb.service", + ]); + assert.equal(status.state, "succeeded"); +}); + +test("a failed install starts the unit again", { skip: process.platform === "win32" }, (t) => { + const { calls, status } = runWorker(t, { npmExit: 1 }); + assert.equal(calls.at(-1), "systemctl --user start ompweb.service"); + assert.equal(status.state, "failed"); + assert.match(status.error, /package install failed/); +}); + +test("a unit that will not start again is reported as stopped", { skip: process.platform === "win32" }, (t) => { + const { status } = runWorker(t, { startExit: 1 }); + assert.equal(status.state, "failed"); + assert.match(status.error, /^ompweb\.service is still stopped: /); +}); diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs new file mode 100644 index 000000000..34d050dda --- /dev/null +++ b/lib/self-update.test.mjs @@ -0,0 +1,92 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + alias: { + "@/": new URL("../", import.meta.url).pathname, + }, +}); +const { getSelfUpdateStatus, parseSystemdServiceCgroup, resolveSelfUpdateTempRoot } = await jiti.import("./self-update.ts"); + +test("parseSystemdServiceCgroup finds system and user services, and nothing outside one", () => { + assert.deepEqual(parseSystemdServiceCgroup("0::/system.slice/ompweb-api.service\n"), { unit: "ompweb-api.service", user: false }); + assert.deepEqual( + parseSystemdServiceCgroup("0::/user.slice/user-1000.slice/user@1000.service/app.slice/ompweb.service\n"), + { unit: "ompweb.service", user: true }, + ); + assert.deepEqual( + parseSystemdServiceCgroup("12:pids:/system.slice/x.service\n1:name=systemd:/system.slice/ompweb.service\n"), + { unit: "ompweb.service", user: false }, + ); + assert.deepEqual( + parseSystemdServiceCgroup("1:name=systemd:/system.slice/ompweb.service\n0::/\n"), + { unit: "ompweb.service", user: false }, + ); + assert.equal(parseSystemdServiceCgroup("0::/user.slice/user-1000.slice/session-3.scope\n"), null); + assert.equal(parseSystemdServiceCgroup("0::/user.slice/user-1000.slice/user@1000.service/app.slice/tmux-spawn-1.scope\n"), null); + assert.equal(parseSystemdServiceCgroup(""), null); +}); + +function withUpdateState(t, { workerPid, leaseExpiresAt }) { + const temporary = mkdtempSync(join(tmpdir(), "self-update-test-")); + const previous = process.env.TMPDIR; + process.env.TMPDIR = temporary; + t.after(() => { + if (previous === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previous; + rmSync(temporary, { recursive: true, force: true }); + }); + const root = resolveSelfUpdateTempRoot("app"); + mkdirSync(root, { mode: 0o700 }); + const attemptId = "2e4c6460-5a8f-4ef7-8d81-42cb688a8bdc"; + if (leaseExpiresAt !== null) { + writeFileSync(join(root, "lease.json"), JSON.stringify({ attemptId, kind: "app", expiresAt: leaseExpiresAt }), { mode: 0o600 }); + } + writeFileSync(join(root, "status.json"), JSON.stringify({ + attemptId, + state: "running", + stage: "stopping", + fromVersion: "0.5.2", + targetVersion: "0.6.0", + preparedAt: new Date().toISOString(), + workerPid, + }), { mode: 0o600 }); + return join(root, "status.json"); +} + +// A pid far above any pid_max, so it is never alive. +const DEAD_PID = 2 ** 30; + +test("a running update whose worker died is reported, and stored, as failed", (t) => { + const statusFile = withUpdateState(t, { workerPid: DEAD_PID, leaseExpiresAt: Date.now() + 60_000 }); + const status = getSelfUpdateStatus("app"); + assert.equal(status.state, "failed"); + assert.equal(status.cleanupReady, true); + assert.match(status.error, /worker stopped/); + assert.equal(JSON.parse(readFileSync(statusFile, "utf8")).state, "failed"); +}); + +test("a running update past its lease is failed even when its pid is alive (reused)", (t) => { + withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: Date.now() - 1 }); + assert.equal(getSelfUpdateStatus("app").state, "failed"); +}); + +test("a running update with a live worker inside its lease stays running", (t) => { + const statusFile = withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: Date.now() + 60_000 }); + assert.equal(getSelfUpdateStatus("app").state, "running"); + assert.equal(JSON.parse(readFileSync(statusFile, "utf8")).state, "running"); +}); + +test("a running update before its worker pid is recorded stays running", (t) => { + withUpdateState(t, { workerPid: undefined, leaseExpiresAt: Date.now() + 60_000 }); + assert.equal(getSelfUpdateStatus("app").state, "running"); +}); + +test("a running update without a lease is failed", (t) => { + withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: null }); + assert.equal(getSelfUpdateStatus("app").state, "failed"); +}); diff --git a/lib/self-update.ts b/lib/self-update.ts index c0582bff8..c6c00201d 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -12,7 +12,7 @@ import { writeFileSync, type Stats, } from "fs"; -import { spawn } from "child_process"; +import { spawn, spawnSync } from "child_process"; import { createChildProcessEnvironment } from "./project-command-env"; import { randomUUID } from "crypto"; import { tmpdir } from "os"; @@ -273,12 +273,63 @@ export function cleanupStaleSelfUpdate(now = Date.now(), kind: Kind = "app"): vo pruneEmptyRoot(kind); } +const WORKER_LOST_ERROR = "The update worker stopped before the update finished"; + +function isWorkerLost(status: StoredStatus, kind: Kind): boolean { + if (status.state !== "running") return false; + // The worker never outlives its lease, and a reused pid cannot keep an expired one alive. + if (!isActiveLease(readStateJson<{ expiresAt?: unknown }>(leasePath(kind)))) return true; + return status.workerPid !== undefined && !isProcessAlive(status.workerPid); +} + export function getSelfUpdateStatus(kind: Kind = "app"): SelfUpdateStatus | null { const s = readStateJson(statusPath(kind)); if (!s) return null; // minimal validation if (typeof s.attemptId !== "string" || typeof s.state !== "string") return null; - return s; + if (!isWorkerLost(s, kind)) return s; + // Re-read: the worker may have written its result just before it exited. + const latest = readStateJson(statusPath(kind)); + if (latest?.attemptId !== s.attemptId || latest.state !== "running") return latest; + const failed: StoredStatus = { ...latest, state: "failed", error: WORKER_LOST_ERROR, finishedAt: new Date().toISOString(), cleanupReady: true }; + // A read must not fail over the write; the next poll retries it. + try { + atomicWrite(statusPath(kind), JSON.stringify(failed)); + } catch {} + return failed; +} + +export interface SystemdService { + unit: string; + user: boolean; +} + +/** The systemd service named by `/proc//cgroup` content, or null outside one. */ +export function parseSystemdServiceCgroup(cgroup: string): SystemdService | null { + for (const line of cgroup.split("\n")) { + if (!line.startsWith("0::") && !line.includes(":name=systemd:")) continue; + const segments = line.split(":").slice(2).join(":").trim().split("/"); + const unit = segments.at(-1); + if (unit?.endsWith(".service")) { + return { unit, user: segments.some((segment) => /^user@\d+\.service$/.test(segment)) }; + } + } + return null; +} + +function detectSystemdService(launcherPid: number): SystemdService | null { + if (process.platform !== "linux") return null; + let service: SystemdService | null; + try { + service = parseSystemdServiceCgroup(readFileSync("/proc/self/cgroup", "utf8")); + } catch { + return null; + } + if (!service) return null; + // Only the unit this launcher is the main process of: a dev server started + // from a session inside another unit must never stop that unit. + const result = spawnSync("systemctl", [...(service.user ? ["--user"] : []), "show", "--property=MainPID", "--value", service.unit], { encoding: "utf8", timeout: 5000 }); + return result.status === 0 && Number(result.stdout.trim()) === launcherPid ? service : null; } export function getSelfUpdateSupport(): { supported: boolean; reason?: string; packageDir: string } { const packageDir = process.env.OMP_WEB_PACKAGE_DIR ?? resolve(join(import.meta ? dirname(new URL(import.meta.url).pathname) : process.cwd(), "..")); @@ -407,6 +458,7 @@ export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accep const { manager, managerPath, prefix } = detectManager(packageDir); const fromVersion = status.fromVersion; const targetVersion = status.targetVersion; + const launcherPid = Number(process.env.OMP_WEB_LAUNCHER_PID ?? process.pid); const descriptor = { launcherPath: join(resolve(packageDir), "bin", "omp-web.js"), hostname: process.env.OMP_WEB_HOSTNAME ?? process.env.HOSTNAME ?? "127.0.0.1", @@ -429,7 +481,7 @@ export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accep "--from", fromVersion, "--launcher-pid", - String(process.env.OMP_WEB_LAUNCHER_PID ?? process.pid), + String(launcherPid), "--server-pid", String(process.pid), JSON.stringify(descriptor), @@ -438,8 +490,26 @@ export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accep "--kind", kind, ]; + const systemd = kind === "app" ? detectSystemdService(launcherPid) : null; + if (systemd) args.push("--systemd-unit", systemd.unit, "--systemd-user", systemd.user ? "1" : "0"); + const workerArgs = workerPath ? [workerPath, ...args] : args; try { - const child = spawn(process.execPath, workerPath ? [workerPath, ...args] : args, { + let command = process.execPath; + let commandArgs = workerArgs; + if (systemd) { + // A worker left in the unit's cgroup is killed with the server it stops, + // so it runs in its own transient scope. + const systemdRun = [...(systemd.user ? ["--user"] : []), "--scope", "--quiet", "--collect", "--no-ask-password"]; + // The detached worker's own failure would be invisible; fail here instead + // (e.g. a non-root system service, which polkit refuses). + const probe = spawnSync("systemd-run", [...systemdRun, "true"], { encoding: "utf8", timeout: 10000 }); + if (probe.status !== 0) { + throw new Error(`systemd-run cannot start the update worker: ${(probe.stderr || probe.error?.message || "").trim()}`); + } + command = "systemd-run"; + commandArgs = [...systemdRun, process.execPath, ...workerArgs]; + } + const child = spawn(command, commandArgs, { detached: true, stdio: "ignore", windowsHide: true, From 6dff7748f6b5312f5fadde44afbb35c1dd59110a Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 26 Oct 2026 12:10:34 +0000 Subject: [PATCH 2/4] test(update): isolate the self-update temp root on Windows too --- lib/self-update.test.mjs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs index 34d050dda..dd07d29ce 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -33,11 +33,15 @@ test("parseSystemdServiceCgroup finds system and user services, and nothing outs function withUpdateState(t, { workerPid, leaseExpiresAt }) { const temporary = mkdtempSync(join(tmpdir(), "self-update-test-")); - const previous = process.env.TMPDIR; - process.env.TMPDIR = temporary; + // os.tmpdir() reads TMPDIR on POSIX and TEMP/TMP on Windows. + const names = ["TMPDIR", "TEMP", "TMP"]; + const previous = names.map((name) => process.env[name]); + for (const name of names) process.env[name] = temporary; t.after(() => { - if (previous === undefined) delete process.env.TMPDIR; - else process.env.TMPDIR = previous; + names.forEach((name, index) => { + if (previous[index] === undefined) delete process.env[name]; + else process.env[name] = previous[index]; + }); rmSync(temporary, { recursive: true, force: true }); }); const root = resolveSelfUpdateTempRoot("app"); From bc6fe32cb876383c2bdef214f084b51516357342 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 26 Oct 2026 12:13:01 +0000 Subject: [PATCH 3/4] fix(update): reject an expired lease at commit and renew it for the worker --- lib/self-update.test.mjs | 34 +++++++++++++++++++++++++++------- lib/self-update.ts | 6 +++++- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs index dd07d29ce..ec0841c94 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -10,7 +10,13 @@ const jiti = createJiti(import.meta.url, { "@/": new URL("../", import.meta.url).pathname, }, }); -const { getSelfUpdateStatus, parseSystemdServiceCgroup, resolveSelfUpdateTempRoot } = await jiti.import("./self-update.ts"); +const { + getSelfUpdateStatus, + markSelfUpdateStopping, + parseSystemdServiceCgroup, + resolveSelfUpdateTempRoot, + validateCommitSelfUpdate, +} = await jiti.import("./self-update.ts"); test("parseSystemdServiceCgroup finds system and user services, and nothing outside one", () => { assert.deepEqual(parseSystemdServiceCgroup("0::/system.slice/ompweb-api.service\n"), { unit: "ompweb-api.service", user: false }); @@ -31,7 +37,7 @@ test("parseSystemdServiceCgroup finds system and user services, and nothing outs assert.equal(parseSystemdServiceCgroup(""), null); }); -function withUpdateState(t, { workerPid, leaseExpiresAt }) { +function withUpdateState(t, { workerPid, leaseExpiresAt, state = "running" }) { const temporary = mkdtempSync(join(tmpdir(), "self-update-test-")); // os.tmpdir() reads TMPDIR on POSIX and TEMP/TMP on Windows. const names = ["TMPDIR", "TEMP", "TMP"]; @@ -50,23 +56,24 @@ function withUpdateState(t, { workerPid, leaseExpiresAt }) { if (leaseExpiresAt !== null) { writeFileSync(join(root, "lease.json"), JSON.stringify({ attemptId, kind: "app", expiresAt: leaseExpiresAt }), { mode: 0o600 }); } + writeFileSync(join(root, `${attemptId}.ready`), "{}", { mode: 0o600 }); writeFileSync(join(root, "status.json"), JSON.stringify({ attemptId, - state: "running", - stage: "stopping", + state, + ...(state === "running" ? { stage: "stopping" } : {}), fromVersion: "0.5.2", targetVersion: "0.6.0", preparedAt: new Date().toISOString(), workerPid, }), { mode: 0o600 }); - return join(root, "status.json"); + return { statusFile: join(root, "status.json"), leaseFile: join(root, "lease.json"), attemptId }; } // A pid far above any pid_max, so it is never alive. const DEAD_PID = 2 ** 30; test("a running update whose worker died is reported, and stored, as failed", (t) => { - const statusFile = withUpdateState(t, { workerPid: DEAD_PID, leaseExpiresAt: Date.now() + 60_000 }); + const { statusFile } = withUpdateState(t, { workerPid: DEAD_PID, leaseExpiresAt: Date.now() + 60_000 }); const status = getSelfUpdateStatus("app"); assert.equal(status.state, "failed"); assert.equal(status.cleanupReady, true); @@ -80,7 +87,7 @@ test("a running update past its lease is failed even when its pid is alive (reus }); test("a running update with a live worker inside its lease stays running", (t) => { - const statusFile = withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: Date.now() + 60_000 }); + const { statusFile } = withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: Date.now() + 60_000 }); assert.equal(getSelfUpdateStatus("app").state, "running"); assert.equal(JSON.parse(readFileSync(statusFile, "utf8")).state, "running"); }); @@ -94,3 +101,16 @@ test("a running update without a lease is failed", (t) => { withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: null }); assert.equal(getSelfUpdateStatus("app").state, "failed"); }); + +test("a prepared update whose lease expired cannot be committed", (t) => { + const { attemptId } = withUpdateState(t, { state: "prepared", leaseExpiresAt: Date.now() - 1 }); + assert.throws(() => validateCommitSelfUpdate(attemptId, "app"), { code: "lease_expired" }); +}); + +test("starting a commit renews the lease, so a late commit is not reported as lost", (t) => { + const { attemptId, leaseFile } = withUpdateState(t, { state: "prepared", leaseExpiresAt: Date.now() + 1_000 }); + assert.equal(validateCommitSelfUpdate(attemptId, "app"), "ready"); + markSelfUpdateStopping(attemptId, "app"); + assert.ok(JSON.parse(readFileSync(leaseFile, "utf8")).expiresAt > Date.now() + 10 * 60_000); + assert.equal(getSelfUpdateStatus("app").state, "running"); +}); diff --git a/lib/self-update.ts b/lib/self-update.ts index c6c00201d..c6e2e78e5 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -420,14 +420,18 @@ export function validateCommitSelfUpdate(attemptId: string, kind: Kind = "app"): if (!status || status.attemptId !== attemptId) throw new SelfUpdateError("attempt_not_found", "Update attempt not found", 404); if (status.state === "running") return "replay"; if (status.state !== "prepared") throw new SelfUpdateError("invalid_state", "Update attempt is not prepared", 409); - const lease = readStateJson<{ attemptId?: string }>(leasePath(kind)); + const lease = readStateJson<{ attemptId?: string; expiresAt?: unknown }>(leasePath(kind)); if (!lease || lease.attemptId !== attemptId) throw new SelfUpdateError("lease_mismatch", "Lease mismatch", 409); + if (!isActiveLease(lease)) throw new SelfUpdateError("lease_expired", "Update attempt expired; prepare it again", 409); if (!existsSync(markerPath(attemptId, "ready", kind))) throw new SelfUpdateError("not_ready", "Update attempt not ready", 409); return "ready"; } export function markSelfUpdateStopping(attemptId: string, kind: Kind = "app"): void { const status = readStateJson(statusPath(kind)); if (!status || status.attemptId !== attemptId) return; + // The worker gets a full lease from here: a running attempt past it counts as lost. + const lease = readStateJson>(leasePath(kind)); + atomicWrite(leasePath(kind), JSON.stringify({ ...lease, attemptId, expiresAt: Date.now() + LEASE_MS })); const next: StoredStatus = { ...status, state: "running", stage: "stopping", startedAt: new Date().toISOString() }; atomicWrite(statusPath(kind), JSON.stringify(next)); } From 9b0f1683f7dccd783abdee5079ebfd5c54c957f5 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 26 Oct 2026 12:48:40 +0000 Subject: [PATCH 4/4] fix(update): check the unit stays up, fail closed on a systemd query error, and keep the commit off the event loop --- app/api/app-update/route.ts | 2 +- app/api/omp-update/route.ts | 2 +- bin/omp-web-update-worker.js | 7 ++++- bin/omp-web-update-worker.test.mjs | 16 +++++++--- lib/self-update.ts | 49 ++++++++++++++++++++++-------- lib/update-policy.test.mjs | 2 +- 6 files changed, 58 insertions(+), 20 deletions(-) diff --git a/app/api/app-update/route.ts b/app/api/app-update/route.ts index 881a967a7..47ae0cb5b 100644 --- a/app/api/app-update/route.ts +++ b/app/api/app-update/route.ts @@ -27,7 +27,7 @@ async function commitAppUpdate(attemptId: string): Promise { if (commitState === "ready") markSelfUpdateStopping(attemptId); await armSelfUpdateLauncher(attemptId); launcherArmed = true; - return commitSelfUpdate(attemptId); + return await commitSelfUpdate(attemptId); } catch (error) { if (!launcherArmed) { const reason = error instanceof SelfUpdateError diff --git a/app/api/omp-update/route.ts b/app/api/omp-update/route.ts index d3f544d9a..632340ab5 100644 --- a/app/api/omp-update/route.ts +++ b/app/api/omp-update/route.ts @@ -50,7 +50,7 @@ export async function POST(request: Request) { const commitState = validateCommitSelfUpdate(body.attemptId, OMP_KIND); if (commitState !== "replay") { if (commitState === "ready") markSelfUpdateStopping(body.attemptId, OMP_KIND); - commitSelfUpdate(body.attemptId, OMP_KIND); + await commitSelfUpdate(body.attemptId, OMP_KIND); } return NextResponse.json({ accepted: true, attemptId: body.attemptId }, { status: 202 }); } diff --git a/bin/omp-web-update-worker.js b/bin/omp-web-update-worker.js index b871678c4..f02e577c7 100644 --- a/bin/omp-web-update-worker.js +++ b/bin/omp-web-update-worker.js @@ -82,7 +82,7 @@ function isTrayActive() { function systemctl(action) { const result = cp.spawnSync("systemctl", [...systemctlScope, action, systemdUnit], { encoding: "utf8", timeout: 120000 }); if (result.status !== 0) { - const detail = (result.stderr || (result.error && result.error.message) || "").trim().slice(0, 200); + const detail = (result.stderr || result.stdout || (result.error && result.error.message) || "").trim().slice(0, 200); throw new Error(`systemctl ${action} ${systemdUnit} failed${detail ? `: ${detail}` : ""}`); } } @@ -174,6 +174,11 @@ async function restartServices(info) { updateStatus({ stage: "restarting" }); if (info.systemd) { systemctl("start"); + // A Type=simple start returns once the process is forked; a release that + // crashes on startup shows up as not active a moment later. + // shortcut: one check after 3s, not a port probe; upgrade if slow-starting crashes slip through. + await sleep(3000); + systemctl("is-active"); return; } if (info.launchd) { diff --git a/bin/omp-web-update-worker.test.mjs b/bin/omp-web-update-worker.test.mjs index d101efe2c..3dc57d226 100644 --- a/bin/omp-web-update-worker.test.mjs +++ b/bin/omp-web-update-worker.test.mjs @@ -3,17 +3,18 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { delimiter, join } from "node:path"; import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; import test from "node:test"; -const WORKER = new URL("./omp-web-update-worker.js", import.meta.url).pathname; +const WORKER = fileURLToPath(new URL("./omp-web-update-worker.js", import.meta.url)); const ATTEMPT = "11111111-2222-3333-4444-555555555555"; // Runs the worker for a systemd unit with stub `systemctl` and `npm` on PATH. -function runWorker(t, { npmExit = 0, startExit = 0 } = {}) { +function runWorker(t, { npmExit = 0, startExit = 0, activeExit = 0 } = {}) { const dir = mkdtempSync(join(tmpdir(), "update-worker-test-")); t.after(() => rmSync(dir, { recursive: true, force: true })); const log = join(dir, "calls.log"); - writeFileSync(join(dir, "systemctl"), `#!/bin/sh\necho "systemctl $*" >> "${log}"\n[ "$2" = start ] && exit ${startExit}\nexit 0\n`, { mode: 0o755 }); + writeFileSync(join(dir, "systemctl"), `#!/bin/sh\necho "systemctl $*" >> "${log}"\n[ "$2" = start ] && exit ${startExit}\n[ "$2" = is-active ] && { echo failed; exit ${activeExit}; }\nexit 0\n`, { mode: 0o755 }); writeFileSync(join(dir, "npm"), `#!/bin/sh\necho "npm $*" >> "${log}"\nexit ${npmExit}\n`, { mode: 0o755 }); writeFileSync(join(dir, "status.json"), JSON.stringify({ attemptId: ATTEMPT, state: "running" }), { mode: 0o600 }); writeFileSync(join(dir, `${ATTEMPT}.go`), "{}", { mode: 0o600 }); @@ -36,12 +37,13 @@ function runWorker(t, { npmExit = 0, startExit = 0 } = {}) { }; } -test("a systemd update stops the unit, installs, then starts it", { skip: process.platform === "win32" }, (t) => { +test("a systemd update stops the unit, installs, starts it and checks it stayed up", { skip: process.platform === "win32" }, (t) => { const { calls, status } = runWorker(t); assert.deepEqual(calls, [ "systemctl --user stop ompweb.service", "npm install -g @kahme247/ompweb@0.6.0", "systemctl --user start ompweb.service", + "systemctl --user is-active ompweb.service", ]); assert.equal(status.state, "succeeded"); }); @@ -58,3 +60,9 @@ test("a unit that will not start again is reported as stopped", { skip: process. assert.equal(status.state, "failed"); assert.match(status.error, /^ompweb\.service is still stopped: /); }); + +test("a new release that does not stay up fails the update", { skip: process.platform === "win32" }, (t) => { + const { status } = runWorker(t, { activeExit: 3 }); + assert.equal(status.state, "failed"); + assert.match(status.error, /systemctl is-active ompweb\.service failed: failed/); +}); diff --git a/lib/self-update.ts b/lib/self-update.ts index c6e2e78e5..09c5c72d1 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -12,17 +12,19 @@ import { writeFileSync, type Stats, } from "fs"; -import { spawn, spawnSync } from "child_process"; +import { execFile, spawn } from "child_process"; import { createChildProcessEnvironment } from "./project-command-env"; import { randomUUID } from "crypto"; import { tmpdir } from "os"; import { dirname, join, posix, resolve, win32 } from "path"; +import { promisify } from "util"; import { checkNpmUpdate, detectInstallMethod } from "./npm-update"; import { checkOmpUpdate } from "./omp/updates"; import { DISABLE_AUTOUPDATE_ENV_VAR, isUpdateDisabled } from "./update-policy"; const LEASE_MS = 30 * 60 * 1000; const TERMINAL_STATUS_TTL_MS = 24 * 60 * 60 * 1000; +const execFileAsync = promisify(execFile); export type SelfUpdateState = "prepared" | "running" | "succeeded" | "failed"; export type SelfUpdateStage = "preparing" | "stopping" | "installing" | "restarting" | "finalizing"; @@ -317,7 +319,12 @@ export function parseSystemdServiceCgroup(cgroup: string): SystemdService | null return null; } -function detectSystemdService(launcherPid: number): SystemdService | null { +function commandError(error: unknown): string { + const stderr = (error as { stderr?: unknown } | null)?.stderr; + return (typeof stderr === "string" && stderr.trim()) || (error instanceof Error ? error.message : String(error)); +} + +async function detectSystemdService(launcherPid: number): Promise { if (process.platform !== "linux") return null; let service: SystemdService | null; try { @@ -328,8 +335,14 @@ function detectSystemdService(launcherPid: number): SystemdService | null { if (!service) return null; // Only the unit this launcher is the main process of: a dev server started // from a session inside another unit must never stop that unit. - const result = spawnSync("systemctl", [...(service.user ? ["--user"] : []), "show", "--property=MainPID", "--value", service.unit], { encoding: "utf8", timeout: 5000 }); - return result.status === 0 && Number(result.stdout.trim()) === launcherPid ? service : null; + let stdout: string; + try { + ({ stdout } = await execFileAsync("systemctl", [...(service.user ? ["--user"] : []), "show", "--property=MainPID", "--value", service.unit], { encoding: "utf8", timeout: 5000 })); + } catch (error) { + // Guessing "not systemd" would start a worker the unit's stop kills. + throw new Error(`Cannot check systemd unit ${service.unit}: ${commandError(error)}`); + } + return Number(stdout.trim()) === launcherPid ? service : null; } export function getSelfUpdateSupport(): { supported: boolean; reason?: string; packageDir: string } { const packageDir = process.env.OMP_WEB_PACKAGE_DIR ?? resolve(join(import.meta ? dirname(new URL(import.meta.url).pathname) : process.cwd(), "..")); @@ -431,7 +444,10 @@ export function markSelfUpdateStopping(attemptId: string, kind: Kind = "app"): v if (!status || status.attemptId !== attemptId) return; // The worker gets a full lease from here: a running attempt past it counts as lost. const lease = readStateJson>(leasePath(kind)); - atomicWrite(leasePath(kind), JSON.stringify({ ...lease, attemptId, expiresAt: Date.now() + LEASE_MS })); + // Never take over another attempt's lease. + if (lease?.attemptId === attemptId) { + atomicWrite(leasePath(kind), JSON.stringify({ ...lease, expiresAt: Date.now() + LEASE_MS })); + } const next: StoredStatus = { ...status, state: "running", stage: "stopping", startedAt: new Date().toISOString() }; atomicWrite(statusPath(kind), JSON.stringify(next)); } @@ -443,7 +459,7 @@ export async function armSelfUpdateLauncher(attemptId: string, kind: Kind = "app await new Promise((r) => setTimeout(r, 500)); } -export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accepted: true; attemptId: string } { +export async function commitSelfUpdate(attemptId: string, kind: Kind = "app"): Promise<{ accepted: true; attemptId: string }> { assertUpdatesEnabled(); const status = readStateJson(statusPath(kind)); if (!status || status.attemptId !== attemptId) throw new SelfUpdateError("attempt_not_found", "Update attempt not found", 404); @@ -494,10 +510,10 @@ export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accep "--kind", kind, ]; - const systemd = kind === "app" ? detectSystemdService(launcherPid) : null; - if (systemd) args.push("--systemd-unit", systemd.unit, "--systemd-user", systemd.user ? "1" : "0"); - const workerArgs = workerPath ? [workerPath, ...args] : args; try { + const systemd = kind === "app" ? await detectSystemdService(launcherPid) : null; + if (systemd) args.push("--systemd-unit", systemd.unit, "--systemd-user", systemd.user ? "1" : "0"); + const workerArgs = workerPath ? [workerPath, ...args] : args; let command = process.execPath; let commandArgs = workerArgs; if (systemd) { @@ -506,9 +522,10 @@ export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accep const systemdRun = [...(systemd.user ? ["--user"] : []), "--scope", "--quiet", "--collect", "--no-ask-password"]; // The detached worker's own failure would be invisible; fail here instead // (e.g. a non-root system service, which polkit refuses). - const probe = spawnSync("systemd-run", [...systemdRun, "true"], { encoding: "utf8", timeout: 10000 }); - if (probe.status !== 0) { - throw new Error(`systemd-run cannot start the update worker: ${(probe.stderr || probe.error?.message || "").trim()}`); + try { + await execFileAsync("systemd-run", [...systemdRun, "true"], { encoding: "utf8", timeout: 10000 }); + } catch (error) { + throw new Error(`systemd-run cannot start the update worker: ${commandError(error)}`); } command = "systemd-run"; commandArgs = [...systemdRun, process.execPath, ...workerArgs]; @@ -521,6 +538,14 @@ export function commitSelfUpdate(attemptId: string, kind: Kind = "app"): { accep // password hash must not be in it (issue #239). env: createChildProcessEnvironment(), }); + // A failed launch arrives as an event, after this function returned. + child.once("error", (error) => { + const current = readStateJson(statusPath(kind)); + if (current?.attemptId !== attemptId || current.state !== "running") return; + try { + atomicWrite(statusPath(kind), JSON.stringify({ ...current, state: "failed", error: error.message.slice(0, 240), finishedAt: new Date().toISOString(), cleanupReady: true })); + } catch {} + }); child.unref(); // record worker pid const updated: StoredStatus = { ...readStateJson(statusPath(kind))!, workerPid: child.pid }; diff --git a/lib/update-policy.test.mjs b/lib/update-policy.test.mjs index 7a9ea5e43..758a98711 100644 --- a/lib/update-policy.test.mjs +++ b/lib/update-policy.test.mjs @@ -105,7 +105,7 @@ test("update opt-out skips external checks and self-update actions", async (t) = assert.equal(error.httpStatus, 403); return true; }); - assert.throws(() => commitSelfUpdate("not-prepared"), (error) => { + await assert.rejects(() => commitSelfUpdate("not-prepared"), (error) => { assert.equal(error.code, "updates_disabled"); assert.equal(error.httpStatus, 403); return true;