diff --git a/.env.example b/.env.example index ce13f74..d4c26a4 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,13 @@ MAX_PROXY_REQUESTS=100 # The manager exits (and is restarted by compose) when its heap + external memory passes this. 0 disables. MANAGER_MEMORY_LIMIT_MB=512 +# Enables the panel's "Update manager" button: the manager clones this repo at SELF_UPDATE_REF, +# builds a new image and replaces its own container (rolls back if the new one isn't healthy). +# Operator-set only, never taken from a request. Leave empty to disable the button. +# Needs SSH_DIR below if the URL is ssh://. See docs/operations.md. +SELF_UPDATE_REPO_URL= +SELF_UPDATE_REF=master + # Absolute path to an SSH dir (key + known_hosts) with clone access to the repos you'll # install, mounted read-only into the manager container so `git clone ssh://...` works for # private repos. Required only if you install from private/SSH repo URLs. diff --git a/CLAUDE.md b/CLAUDE.md index 2f6c4f8..5655328 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,3 +40,6 @@ authenticated requests to it. See `README.md` for the full flow and `docs/` for - Local Node 24 cannot compile `better-sqlite3@11`, so `npm test` fails on the host: run the suite in a `node:20` container (`podman run ... docker.io/library/node:20-slim`, repo copied without `node_modules`). - `.gitea/workflows/ci.yml` only runs if this repo's Gitea instance has Actions enabled with a runner. +- Self-update (panel button) needs `SELF_UPDATE_REPO_URL` and only works when the manager runs in a + container; the swap is done by a helper container (`system/selfUpdateHelper.ts`), not by the + manager itself. Keep the helper standalone (no config/db imports). See `docs/operations.md`. diff --git a/Dockerfile b/Dockerfile index a88dd6b..fa1f840 100644 --- a/Dockerfile +++ b/Dockerfile @@ -38,6 +38,8 @@ RUN npm ci --omit=dev --workspace apps/server COPY --from=build /repo/apps/server/dist apps/server/dist COPY --from=build /repo/apps/web/dist apps/web/dist +# Shown in the panel next to the self-update button. +COPY VERSION VERSION WORKDIR /repo/apps/server ENV NODE_ENV=production diff --git a/README.md b/README.md index f1d407c..6bdf86b 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,12 @@ docker compose up -d --build Put your own reverse proxy (nginx, etc.) in front of port 3000 for TLS and your public domain. +## Updating + +Set `SELF_UPDATE_REPO_URL` (and optionally `SELF_UPDATE_REF`) in `.env` and use the **Update manager** +button in the panel: it builds the latest source and swaps the manager's container, rolling back +if the new one isn't healthy. Details in [docs/operations.md](docs/operations.md). + ## Local development (Podman) Requires `nixpacks` and a `docker` CLI pointed at your Podman socket (e.g. via the diff --git a/apps/server/src/api/installations.ts b/apps/server/src/api/installations.ts index 207e6bc..cfecd7a 100644 --- a/apps/server/src/api/installations.ts +++ b/apps/server/src/api/installations.ts @@ -21,9 +21,20 @@ import { import { buildLogPath } from "../build/nixpacks.js"; import { generateBearerToken } from "../crypto/secrets.js"; import fs from "node:fs"; +import { isSelfUpdateInProgress } from "../system/selfUpdate.js"; export const installationsRouter = Router(); +// An update swaps the manager's own container; an installation build or start in flight would be +// killed by it, so changes wait until the update is over. +installationsRouter.use((req, res, next) => { + if (req.method !== "GET" && isSelfUpdateInProgress()) { + res.status(409).json({ error: "the manager is updating itself; try again in a minute" }); + return; + } + next(); +}); + // Not masked: this API sits behind single-operator session auth (requireAuth), and the // operator is the same person who owns these secrets — editing them requires seeing them. function toPublicJson(installation: Installation) { diff --git a/apps/server/src/api/system.ts b/apps/server/src/api/system.ts new file mode 100644 index 0000000..f4a791f --- /dev/null +++ b/apps/server/src/api/system.ts @@ -0,0 +1,17 @@ +import { Router } from "express"; +import { getSystemInfo, startSelfUpdate, SelfUpdateError } from "../system/selfUpdate.js"; + +export const systemRouter = Router(); + +systemRouter.get("/", async (_req, res) => { + res.json(await getSystemInfo()); +}); + +systemRouter.post("/update", async (_req, res) => { + try { + await startSelfUpdate(); + res.status(202).json({ ok: true }); + } catch (err) { + res.status(err instanceof SelfUpdateError ? err.status : 500).json({ error: (err as Error).message }); + } +}); diff --git a/apps/server/src/config/env.ts b/apps/server/src/config/env.ts index e7589ee..8d70e6a 100644 --- a/apps/server/src/config/env.ts +++ b/apps/server/src/config/env.ts @@ -25,4 +25,8 @@ export const config = { // The manager exits (and the container restart policy brings it back) once its own // heap + external memory exceeds this. 0 disables the guard. memoryLimitMb: Number(process.env.MANAGER_MEMORY_LIMIT_MB ?? 512), + // Self-update: git repo/ref the manager rebuilds itself from. Operator-set only (never taken + // from a request); without a repo URL the panel's "Update manager" button is disabled. + selfUpdateRepoUrl: process.env.SELF_UPDATE_REPO_URL || undefined, + selfUpdateRef: process.env.SELF_UPDATE_REF || "master", }; diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 8240b54..adf15d1 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -7,6 +7,8 @@ import { reconcileInterruptedInstallations } from "./db/installations.js"; import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js"; import { authRouter } from "./api/auth.js"; import { installationsRouter } from "./api/installations.js"; +import { systemRouter } from "./api/system.js"; +import { collectSelfUpdateResult } from "./system/selfUpdate.js"; import { requireAuth } from "./middleware/requireAuth.js"; import { SqliteSessionStore } from "./session/sqliteStore.js"; import { startMemoryGuard } from "./service/memoryGuard.js"; @@ -28,6 +30,8 @@ app.use( saveUninitialized: false, cookie: { httpOnly: true, + // Lax: a cross-site form POST must not carry the session (e.g. to trigger a manager update). + sameSite: "lax", // "auto": secure only if the request actually arrived over HTTPS (checks req.secure, // which respects "trust proxy" + X-Forwarded-Proto). A flat `NODE_ENV === "production"` // check meant the cookie was never stored at all when the admin panel is reached over @@ -60,6 +64,7 @@ app.all("/mcp/:slug", handleMcpProxyRequest); app.use("/api", express.json()); app.use("/api/auth", authRouter); app.use("/api/installations", requireAuth, installationsRouter); +app.use("/api/system", requireAuth, systemRouter); const webDist = path.resolve(import.meta.dirname, "../../web/dist"); app.use(express.static(webDist)); @@ -73,6 +78,9 @@ const server = app.listen(config.port, () => { console.log(`remote-mcp-manager listening on http://localhost:${config.port}`); }); +// If an updater container ran just before this boot, pick up its outcome for the panel. +void collectSelfUpdateResult(); + function shutdown(code: number): void { server.close(() => process.exit(code)); server.closeAllConnections(); diff --git a/apps/server/src/service/buildQueue.ts b/apps/server/src/service/buildQueue.ts new file mode 100644 index 0000000..74b0cf2 --- /dev/null +++ b/apps/server/src/service/buildQueue.ts @@ -0,0 +1,6 @@ +import { createSerialQueue } from "../util/serialQueue.js"; + +// Builds are the heaviest thing the host does (nixpacks + docker build); running several at +// once on a small host is what pushes it into swap. Serialize them — including the manager's +// own self-update build. +export const enqueueBuild = createSerialQueue(); diff --git a/apps/server/src/service/orchestrator.ts b/apps/server/src/service/orchestrator.ts index a4ab18f..84cf838 100644 --- a/apps/server/src/service/orchestrator.ts +++ b/apps/server/src/service/orchestrator.ts @@ -20,11 +20,7 @@ import { removeImageIfUnused, } from "../docker/containers.js"; import { generateBearerToken } from "../crypto/secrets.js"; -import { createSerialQueue } from "../util/serialQueue.js"; - -// Builds are the heaviest thing the host does (nixpacks + docker build); running several at -// once on a small host is what pushes it into swap. Serialize them. -const enqueueBuild = createSerialQueue(); +import { enqueueBuild } from "./buildQueue.js"; export interface DraftResult { installation: Installation; diff --git a/apps/server/src/system/containerSpec.test.ts b/apps/server/src/system/containerSpec.test.ts new file mode 100644 index 0000000..53cd75f --- /dev/null +++ b/apps/server/src/system/containerSpec.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; +import type { ContainerInspectInfo } from "dockerode"; +import { buildReplacementSpec } from "./containerSpec.js"; + +const old = { + Id: "0123456789abcdef0123", + Name: "/remote-mcp-manager-manager-1", + Config: { + Env: ["PATH=/usr/bin", "NODE_OPTIONS=--old", "ADMIN_PASSWORD=x", "PORT=3000"], + Labels: { "com.docker.compose.service": "manager" }, + ExposedPorts: { "3000/tcp": {} }, + User: "", + Hostname: "0123456789ab", + Cmd: ["node", "old.js"], + }, + HostConfig: { + NetworkMode: "mcp-net", + Binds: ["/var/run/docker.sock:/var/run/docker.sock", "./data:/repo/data"], + RestartPolicy: { Name: "unless-stopped" }, + }, + NetworkSettings: { Networks: { "mcp-net": { Aliases: ["manager", "0123456789ab"] } } }, +} as unknown as ContainerInspectInfo; + +describe("buildReplacementSpec", () => { + const spec = buildReplacementSpec(old, ["PATH=/usr/bin", "NODE_OPTIONS=--old"], "mcpmgr-manager:new"); + + it("keeps the name, host config and operator-set env, and runs the new image", () => { + expect(spec.name).toBe("remote-mcp-manager-manager-1"); + expect(spec.Image).toBe("mcpmgr-manager:new"); + expect(spec.HostConfig).toBe(old.HostConfig); + expect(spec.Env).toEqual(["ADMIN_PASSWORD=x", "PORT=3000"]); + }); + + it("does not pin the old image's Cmd or hostname", () => { + expect(spec.Cmd).toBeUndefined(); + expect(spec.Hostname).toBeUndefined(); + }); + + it("keeps network aliases except the old container's own id", () => { + expect(spec.NetworkingConfig?.EndpointsConfig?.["mcp-net"]?.Aliases).toEqual(["manager"]); + }); +}); diff --git a/apps/server/src/system/containerSpec.ts b/apps/server/src/system/containerSpec.ts new file mode 100644 index 0000000..c9bbb1d --- /dev/null +++ b/apps/server/src/system/containerSpec.ts @@ -0,0 +1,40 @@ +import type { ContainerCreateOptions, ContainerInspectInfo } from "dockerode"; + +/** + * Builds the create options for a container that replaces `old` but runs `newImage`, keeping + * everything the operator configured (name, bind mounts, port bindings, network + aliases, + * restart policy, user-supplied env) and nothing the image itself defines. + * + * `oldImageEnv` is the env baked into the OLD image: those entries are dropped, otherwise a + * `docker inspect`'d container pins the old image's ENV and a changed ENV in the new image + * (e.g. NODE_OPTIONS) would silently never apply. Cmd/Entrypoint/Hostname are likewise left + * out so the new image's defaults and a fresh hostname (= its own container id) apply. + */ +export function buildReplacementSpec( + old: ContainerInspectInfo, + oldImageEnv: string[], + newImage: string, +): ContainerCreateOptions { + const networkMode = old.HostConfig.NetworkMode ?? "default"; + const network = old.NetworkSettings.Networks[networkMode]; + const shortId = old.Id.slice(0, 12); + + return { + name: old.Name.replace(/^\//, ""), + Image: newImage, + Env: (old.Config.Env ?? []).filter((e) => !oldImageEnv.includes(e)), + Labels: old.Config.Labels ?? {}, + ExposedPorts: old.Config.ExposedPorts, + User: old.Config.User || undefined, + HostConfig: old.HostConfig, + ...(network + ? { + NetworkingConfig: { + EndpointsConfig: { + [networkMode]: { Aliases: ((network.Aliases ?? []) as string[]).filter((a) => a !== shortId) }, + }, + }, + } + : {}), + }; +} diff --git a/apps/server/src/system/dockerLogs.test.ts b/apps/server/src/system/dockerLogs.test.ts new file mode 100644 index 0000000..fe900be --- /dev/null +++ b/apps/server/src/system/dockerLogs.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { demuxLogs } from "./dockerLogs.js"; + +function frame(stream: number, text: string): Buffer { + const payload = Buffer.from(text); + const header = Buffer.alloc(8); + header[0] = stream; + header.writeUInt32BE(payload.length, 4); + return Buffer.concat([header, payload]); +} + +describe("demuxLogs", () => { + it("joins stdout and stderr frames in order", () => { + const buf = Buffer.concat([frame(1, "hello "), frame(2, "world\n")]); + expect(demuxLogs(buf)).toBe("hello world\n"); + }); + + it("returns an empty string for empty or header-only input", () => { + expect(demuxLogs(Buffer.alloc(0))).toBe(""); + expect(demuxLogs(Buffer.alloc(4))).toBe(""); + }); + + it("does not read past a truncated frame", () => { + const buf = frame(1, "abcdef").subarray(0, 8 + 3); + expect(demuxLogs(buf)).toBe("abc"); + }); +}); diff --git a/apps/server/src/system/dockerLogs.ts b/apps/server/src/system/dockerLogs.ts new file mode 100644 index 0000000..9824f17 --- /dev/null +++ b/apps/server/src/system/dockerLogs.ts @@ -0,0 +1,11 @@ +/** Demuxes Docker's non-tty log stream (8-byte frame headers) into plain text. */ +export function demuxLogs(buf: Buffer): string { + const out: string[] = []; + let offset = 0; + while (offset + 8 <= buf.length) { + const size = buf.readUInt32BE(offset + 4); + out.push(buf.subarray(offset + 8, offset + 8 + size).toString("utf8")); + offset += 8 + size; + } + return out.join(""); +} diff --git a/apps/server/src/system/selfUpdate.ts b/apps/server/src/system/selfUpdate.ts new file mode 100644 index 0000000..dfbaa73 --- /dev/null +++ b/apps/server/src/system/selfUpdate.ts @@ -0,0 +1,211 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import Docker from "dockerode"; +import { config } from "../config/env.js"; +import { listInstallations } from "../db/installations.js"; +import { cloneOrUpdateRepo, repoDir } from "../build/git.js"; +import { enqueueBuild } from "../service/buildQueue.js"; +import { killGroupAfter } from "../util/processTimeout.js"; +import { withTimeout } from "../util/withTimeout.js"; +import { demuxLogs } from "./dockerLogs.js"; +import { readVersion } from "./version.js"; + +const docker = new Docker({ socketPath: config.dockerSocketPath }); + +const HELPER_LABEL = "remote-mcp-manager.self-update-helper"; +const BUILD_TIMEOUT_MS = 30 * 60 * 1000; +// Updater: up to 90 s of health checks plus stop/create/rollback; this is only a backstop. +const HANDOVER_TIMEOUT_MS = 5 * 60 * 1000; +// The checkout lives under a name no installation slug can take (slugify strips underscores). +const CHECKOUT_SLUG = "_manager"; +const BUSY_STATUSES = new Set(["cloning", "building", "starting"]); + +type Phase = "idle" | "cloning" | "building" | "handing-over"; + +const state: { phase: Phase; error?: string; logPath?: string } = { phase: "idle" }; +let lastResult: { finishedAt: string; ok: boolean; log: string } | null = null; + +/** The container this process runs in (Docker sets the hostname to the container id), if any. */ +async function inspectSelf() { + try { + return await withTimeout(docker.getContainer(os.hostname()).inspect(), 10_000, "docker inspect self"); + } catch { + return undefined; + } +} + +function tailOfLog(maxLines = 200): string { + if (!state.logPath || !fs.existsSync(state.logPath)) return ""; + return fs.readFileSync(state.logPath, "utf8").split("\n").slice(-maxLines).join("\n"); +} + +export async function getSystemInfo() { + // The updater is usually still running when the new manager boots, so its result can only be + // collected later; polling this endpoint is what picks it up. + if (!lastResult && state.phase === "idle") await collectSelfUpdateResult(); + const self = await inspectSelf(); + return { + version: readVersion(), + uptimeSec: Math.round(process.uptime()), + canSelfUpdate: Boolean(config.selfUpdateRepoUrl && self), + unavailableReason: !config.selfUpdateRepoUrl + ? "SELF_UPDATE_REPO_URL is not set" + : !self + ? "the manager is not running inside a container it can inspect" + : null, + ref: config.selfUpdateRef, + phase: state.phase, + error: state.error ?? null, + log: state.phase === "idle" && !state.error ? "" : tailOfLog(), + lastUpdate: lastResult, + }; +} + +function runDockerBuild(contextDir: string, image: string, logPath: string): Promise { + return new Promise((resolve) => { + const logStream = fs.createWriteStream(logPath, { flags: "a" }); + const child = spawn("docker", ["build", "-t", image, contextDir], { detached: true }); + killGroupAfter(child, BUILD_TIMEOUT_MS); + child.stdout.pipe(logStream, { end: false }); + child.stderr.pipe(logStream, { end: false }); + child.on("close", (code) => { + logStream.end(); + resolve(code === 0); + }); + child.on("error", (err) => { + logStream.write(`\nfailed to spawn docker: ${err.message}\n`); + logStream.end(); + resolve(false); + }); + }); +} + +async function runUpdate(self: Docker.ContainerInspectInfo): Promise { + const url = config.selfUpdateRepoUrl!; + const image = `mcpmgr-manager:update-${Date.now()}`; + const logDir = path.join(config.logsDir, CHECKOUT_SLUG); + fs.mkdirSync(logDir, { recursive: true }); + state.logPath = path.join(logDir, `${Date.now()}.log`); + const note = (msg: string) => fs.appendFileSync(state.logPath!, `[self-update] ${msg}\n`); + + try { + // Same queue as installation builds: never two heavy builds at once on a small host. The + // hand-over below also happens inside it, so no queued build can start while the manager is + // about to be swapped out. + await enqueueBuild(async () => { + state.phase = "cloning"; + note(`cloning ${url} (${config.selfUpdateRef})`); + await cloneOrUpdateRepo(CHECKOUT_SLUG, url, config.selfUpdateRef); + + state.phase = "building"; + note(`building ${image}`); + if (!(await runDockerBuild(repoDir(CHECKOUT_SLUG), image, state.logPath!))) { + throw new Error(`image build failed, see ${state.logPath}`); + } + + state.phase = "handing-over"; + const socketBind = (self.HostConfig.Binds ?? []).find((b) => b.split(":")[1] === config.dockerSocketPath); + if (!socketBind) throw new Error(`no bind mount for ${config.dockerSocketPath} on the manager container`); + + note("starting the updater container; the manager will restart shortly"); + const helper = await docker.createContainer({ + Image: image, + Cmd: ["node", "dist/system/selfUpdateHelper.js"], + Env: [ + `OLD_CONTAINER_ID=${self.Id}`, + `NEW_IMAGE=${image}`, + `DOCKER_SOCKET_PATH=${config.dockerSocketPath}`, + ], + Labels: { [HELPER_LABEL]: "1" }, + HostConfig: { + Binds: [socketBind], + SecurityOpt: self.HostConfig.SecurityOpt ?? undefined, + NetworkMode: self.HostConfig.NetworkMode, + RestartPolicy: { Name: "no" }, + }, + }); + await helper.start(); + + // A successful hand-over kills this process, so getting past this wait means the updater + // ended without replacing us (crashed early, rolled back before stopping us) or hung. + const exit = (await withTimeout(helper.wait(), HANDOVER_TIMEOUT_MS, "updater container")) as { StatusCode: number }; + await collectSelfUpdateResult(); + throw new Error( + exit.StatusCode === 0 + ? "the updater finished but this manager is still running" + : `the updater exited with code ${exit.StatusCode}${lastResult ? `:\n${lastResult.log.split("\n").slice(-15).join("\n")}` : ""}`, + ); + }); + } catch (err) { + state.phase = "idle"; + state.error = (err as Error).message; + note(`failed: ${state.error}`); + } +} + +/** True from the moment an update is requested until it fails; a successful one ends this process. */ +export function isSelfUpdateInProgress(): boolean { + return state.phase !== "idle"; +} + +export class SelfUpdateError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message); + } +} + +/** Validates preconditions and starts the update in the background. Throws SelfUpdateError if it can't. */ +export async function startSelfUpdate(): Promise { + if (!config.selfUpdateRepoUrl) throw new SelfUpdateError("SELF_UPDATE_REPO_URL is not set", 400); + if (state.phase !== "idle") throw new SelfUpdateError("an update is already in progress", 409); + if (listInstallations().some((i) => BUSY_STATUSES.has(i.status))) { + throw new SelfUpdateError("an installation is building or starting; wait for it to finish", 409); + } + + // Claimed before the first await so two concurrent requests can't both start an update. + state.phase = "cloning"; + state.error = undefined; + const self = await inspectSelf(); + if (!self) { + state.phase = "idle"; + throw new SelfUpdateError("the manager is not running inside a container it can inspect", 400); + } + void runUpdate(self); +} + +/** + * Called once at boot: if an updater container left a result behind (this process is either the + * freshly updated manager or the one the updater rolled back to), record its log and clean it up. + */ +export async function collectSelfUpdateResult(): Promise { + try { + const helpers = await withTimeout( + docker.listContainers({ all: true, filters: { label: [HELPER_LABEL] } }), + 10_000, + "docker list updater", + ); + for (const h of helpers) { + if (h.State === "running") continue; + const container = docker.getContainer(h.Id); + const info = await withTimeout(container.inspect(), 10_000, "docker inspect updater"); + const logs = (await withTimeout( + container.logs({ stdout: true, stderr: true }), + 10_000, + "docker logs updater", + )) as unknown as Buffer; + lastResult = { + finishedAt: info.State.FinishedAt, + ok: info.State.ExitCode === 0, + log: demuxLogs(Buffer.from(logs)), + }; + await withTimeout(container.remove({ force: true }), 10_000, "docker rm updater"); + } + } catch { + // Best effort: no Docker access (e.g. local dev) just means there is nothing to report. + } +} diff --git a/apps/server/src/system/selfUpdateHelper.ts b/apps/server/src/system/selfUpdateHelper.ts new file mode 100644 index 0000000..5051d5d --- /dev/null +++ b/apps/server/src/system/selfUpdateHelper.ts @@ -0,0 +1,109 @@ +// Entry point of the short-lived "updater" container (the NEW image run with this script). +// The manager can't replace itself — stopping its own container kills the code doing it — so it +// hands over to this process, which swaps the manager container for one running NEW_IMAGE and +// rolls back to the old container if the new one never becomes healthy. +// Standalone on purpose: it doesn't import the app's config/db modules. +import http from "node:http"; +import Docker from "dockerode"; +import { buildReplacementSpec } from "./containerSpec.js"; + +const socketPath = process.env.DOCKER_SOCKET_PATH ?? "/var/run/docker.sock"; +const oldId = process.env.OLD_CONTAINER_ID; +const newImage = process.env.NEW_IMAGE; +const HEALTH_TIMEOUT_MS = 90_000; + +const docker = new Docker({ socketPath }); +const log = (msg: string) => console.log(`[self-update] ${msg}`); + +function checkHealth(ip: string, port: number): Promise { + return new Promise((resolve) => { + const req = http.get({ host: ip, port, path: "/health", timeout: 2_000 }, (res) => { + res.resume(); + resolve(res.statusCode === 200); + }); + req.on("error", () => resolve(false)); + req.on("timeout", () => { + req.destroy(); + resolve(false); + }); + }); +} + +async function waitUntilHealthy(containerId: string, network: string, port: number): Promise { + const deadline = Date.now() + HEALTH_TIMEOUT_MS; + while (Date.now() < deadline) { + const info = await docker.getContainer(containerId).inspect(); + if (!info.State.Running && info.State.Status !== "restarting") return false; + const ip = info.NetworkSettings.Networks[network]?.IPAddress; + if (ip && (await checkHealth(ip, port))) return true; + await new Promise((r) => setTimeout(r, 2_000)); + } + return false; +} + +async function main(): Promise { + if (!oldId || !newImage) throw new Error("OLD_CONTAINER_ID and NEW_IMAGE are required"); + + const oldContainer = docker.getContainer(oldId); + const old = await oldContainer.inspect(); + const name = old.Name.replace(/^\//, ""); + const oldImageEnv = (await docker.getImage(old.Image).inspect()).Config.Env ?? []; + const spec = buildReplacementSpec(old, oldImageEnv, newImage); + const network = old.HostConfig.NetworkMode ?? "default"; + const port = Number(old.Config.Env?.find((e) => e.startsWith("PORT="))?.slice(5) ?? 3000); + + // The old container holds the name and the published port, so it has to go first. It is only + // renamed and stopped (not removed) so it can be started again if the new one fails. Renaming + // comes first, while it is still running: if that fails, nothing has been touched yet. + const backupName = `${name}-pre-update`; + await docker.getContainer(backupName).remove({ force: true }).catch(() => {}); + await oldContainer.rename({ name: backupName }); + log(`stopping ${name} (${old.Id.slice(0, 12)})`); + try { + await oldContainer.stop({ t: 15 }); + } catch (err) { + if ((err as { statusCode?: number }).statusCode !== 304) { + await oldContainer.rename({ name }).catch(() => {}); + throw err; + } + } + + let created: Docker.Container | undefined; + let healthy = false; + try { + log(`starting new container from ${newImage}`); + created = await docker.createContainer(spec); + await created.start(); + healthy = await waitUntilHealthy(created.id, network, port); + if (!healthy) log(`new manager did not become healthy within ${HEALTH_TIMEOUT_MS / 1000}s`); + } catch (err) { + log(`failed to start the new container: ${(err as Error).message}`); + } + + if (healthy) { + // The update has succeeded; failing to tidy up must not undo it. + log("new manager is healthy, removing the old container"); + await oldContainer.remove({ force: true }).catch((err) => log(`could not remove the old container: ${err.message}`)); + await docker.getImage(old.Image).remove({ force: false }).catch(() => {}); + log("update complete"); + return 0; + } + + // Every rollback step is attempted on its own: the old container must be started again even if + // an earlier step failed. + log("rolling back to the previous manager"); + if (created) await created.remove({ force: true }).catch((err) => log(`could not remove the new container: ${err.message}`)); + await oldContainer.rename({ name }).catch((err) => log(`could not restore the name: ${err.message}`)); + await oldContainer.start().catch((err) => log(`could not start the old container: ${err.message}`)); + await docker.getImage(newImage).remove({ force: false }).catch(() => {}); + log("rollback complete"); + return 1; +} + +main().then( + (code) => process.exit(code), + (err) => { + log(`fatal: ${(err as Error).stack ?? err}`); + process.exit(2); + }, +); diff --git a/apps/server/src/system/version.ts b/apps/server/src/system/version.ts new file mode 100644 index 0000000..58ff796 --- /dev/null +++ b/apps/server/src/system/version.ts @@ -0,0 +1,14 @@ +import fs from "node:fs"; +import path from "node:path"; + +// VERSION sits at the repo root, four levels above this file in both the image and a checkout: +// /apps/server/{src,dist}/system/version.* +const versionFile = path.resolve(import.meta.dirname, "../../../../VERSION"); + +export function readVersion(): string { + try { + return fs.readFileSync(versionFile, "utf8").trim() || "unknown"; + } catch { + return "unknown"; + } +} diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index afca352..5fe54c4 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -19,6 +19,18 @@ export interface Installation { updatedAt: string; } +export interface SystemInfo { + version: string; + uptimeSec: number; + canSelfUpdate: boolean; + unavailableReason: string | null; + ref: string; + phase: "idle" | "cloning" | "building" | "handing-over"; + error: string | null; + log: string; + lastUpdate: { finishedAt: string; ok: boolean; log: string } | null; +} + async function request(path: string, init?: RequestInit): Promise { const res = await fetch(path, { ...init, @@ -60,4 +72,7 @@ export const api = { request<{ bearerToken: string }>(`/api/installations/${id}/regenerate-token`, { method: "POST" }), remove: (id: string) => request(`/api/installations/${id}`, { method: "DELETE" }), logs: (id: string) => request<{ log: string }>(`/api/installations/${id}/logs`), + + systemInfo: () => request("/api/system"), + updateManager: () => request<{ ok: true }>("/api/system/update", { method: "POST" }), }; diff --git a/apps/web/src/components/ManagerCard.tsx b/apps/web/src/components/ManagerCard.tsx new file mode 100644 index 0000000..10280fe --- /dev/null +++ b/apps/web/src/components/ManagerCard.tsx @@ -0,0 +1,123 @@ +import { useEffect, useState } from "react"; +import { api, type SystemInfo } from "../api/client"; + +// Stops waiting for a manager that never comes back (the updater itself gives up well before this). +const MAX_WAIT_MS = 10 * 60 * 1000; + +const PHASE_LABEL: Record = { + idle: "", + cloning: "Fetching the latest source…", + building: "Building the new image…", + "handing-over": "Handing over to the new version…", +}; + +export function ManagerCard() { + const [info, setInfo] = useState(null); + const [error, setError] = useState(null); + const [requested, setRequested] = useState(false); + const [unreachable, setUnreachable] = useState(false); + const [startedAt, setStartedAt] = useState(null); + const [gaveUp, setGaveUp] = useState(false); + + async function refresh() { + try { + setInfo(await api.systemInfo()); + setUnreachable(false); + } catch { + // Expected while the container is being swapped; keep polling until it answers again. + setUnreachable(true); + } + } + + useEffect(() => { + refresh(); + }, []); + + const updating = !gaveUp && (requested || (info !== null && info.phase !== "idle")); + + useEffect(() => { + if (!updating) return; + const timer = setInterval(() => { + if (startedAt !== null && Date.now() - startedAt > MAX_WAIT_MS) { + setGaveUp(true); + setRequested(false); + return; + } + refresh(); + }, 3000); + return () => clearInterval(timer); + }, [updating, startedAt]); + + // The update is over once the manager answers again with nothing in progress. + useEffect(() => { + // A restarted manager has a smaller uptime than the time since we asked. + const restarted = startedAt !== null && info !== null && info.uptimeSec * 1000 < Date.now() - startedAt; + if (requested && info && info.phase === "idle" && !unreachable && (info.lastUpdate || info.error || restarted)) { + setRequested(false); + } + }, [requested, info, unreachable, startedAt]); + + async function update() { + if (!info) return; + const msg = + `Update the manager from ${info.ref}? It builds a new image, then restarts itself ` + + "(a few seconds of downtime; MCP clients should reconnect). It rolls back if the new version isn't healthy."; + if (!window.confirm(msg)) return; + setError(null); + try { + await api.updateManager(); + setGaveUp(false); + setStartedAt(Date.now()); + setRequested(true); + refresh(); + } catch (err) { + setError((err as Error).message); + } + } + + if (!info && !unreachable) return null; + + const log = info?.log || info?.lastUpdate?.log || ""; + + return ( +
+
+ Manager + + {info ? `Version ${info.version} · ${info.ref}` : "Restarting…"} + +
+ + {updating && ( +

+ {unreachable ? "The manager is restarting, waiting for it to come back…" : PHASE_LABEL[info?.phase ?? "idle"]} +

+ )} + {error &&
{error}
} + {gaveUp &&
The manager did not come back in 10 minutes; check the host.
} + {info?.error &&
Update failed: {info.error}
} + {!updating && info?.lastUpdate && ( +

+ Last update {info.lastUpdate.ok ? "succeeded" : "did not complete (rolled back or failed; see the log)"} ({new Date(info.lastUpdate.finishedAt).toLocaleString()}). +

+ )} + {info && !info.canSelfUpdate && info.unavailableReason && ( +

Self-update unavailable: {info.unavailableReason}.

+ )} + +
+ +
+ + {log &&
{log}
} +
+ ); +} diff --git a/apps/web/src/pages/InstallationList.tsx b/apps/web/src/pages/InstallationList.tsx index 9d37fe8..1e5d81f 100644 --- a/apps/web/src/pages/InstallationList.tsx +++ b/apps/web/src/pages/InstallationList.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { api, type Installation } from "../api/client"; import { InstallWizard } from "./InstallWizard"; +import { ManagerCard } from "../components/ManagerCard"; import { Shell } from "../components/Shell"; import { StatusBadge } from "../components/StatusBadge"; @@ -71,6 +72,8 @@ export function InstallationList({ onLoggedOut }: { onLoggedOut: () => void }) { )} + + ); } diff --git a/docker-compose.yml b/docker-compose.yml index 33b9860..fa325e6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,6 +18,8 @@ services: PROXY_TIMEOUT_MS: ${PROXY_TIMEOUT_MS:-300000} MAX_PROXY_REQUESTS: ${MAX_PROXY_REQUESTS:-100} MANAGER_MEMORY_LIMIT_MB: ${MANAGER_MEMORY_LIMIT_MB:-512} + SELF_UPDATE_REPO_URL: ${SELF_UPDATE_REPO_URL:-} + SELF_UPDATE_REF: ${SELF_UPDATE_REF:-master} volumes: - /var/run/docker.sock:/var/run/docker.sock - ./data:/repo/data diff --git a/docs/architecture.md b/docs/architecture.md index dfaf92f..0f514e5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,3 +54,10 @@ manager can only reach sibling MCP containers (by IP on `mcp-net`) when it is it attached to that network — running it directly on the host only works for routes that don't need to reach a sibling container (e.g. `/health`, `/api/auth`). See the README's "Local development (Podman)" section and `LESSONS.md` for the operational detail. + +## Self-update + +`system/selfUpdate.ts` (state, clone + build in the shared build queue, hand-over) and +`system/selfUpdateHelper.ts` (the updater container's entry point: swap, health check, rollback) +implement the panel's *Update manager* button, exposed as `GET /api/system` and +`POST /api/system/update` behind `requireAuth`. See `docs/operations.md`. diff --git a/docs/operations.md b/docs/operations.md index 545d258..77e5232 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -29,3 +29,39 @@ yourself on hosts that support it. `activeProxyRequests`. A heap that keeps climbing between restarts, or an `activeProxyRequests` that stays high with no traffic, points at a leak. A line `memory guard: ... restarting` in the manager's log means the guard fired. + +## Updating the manager from the panel + +The **Manager** card on the installations page has an *Update manager* button. It is enabled when +`SELF_UPDATE_REPO_URL` is set (operator-only env var, never taken from a request) and the manager +runs in a container whose id it can inspect (production compose; not local `npm run dev`). + +Flow: + +1. In the serial build queue (so it never overlaps an installation build) the manager clones + `SELF_UPDATE_REPO_URL` at `SELF_UPDATE_REF` (default `master`) and runs `docker build` on it. + Refused with `409` if an installation is cloning/building/starting. +2. It starts a short-lived **updater container** from the *new* image + (`node dist/system/selfUpdateHelper.js`, label `remote-mcp-manager.self-update-helper`). A + manager cannot replace itself: stopping its own container kills the code doing it. +3. The updater stops the old manager, renames it `-pre-update`, creates a replacement with + the same name, bind mounts, port bindings, network aliases, restart policy, labels and operator + env (`buildReplacementSpec`), but the new image's own `Cmd` and image `ENV`, and polls + `/health` for up to 90 s. +4. Healthy: the old container and image are removed. Not healthy: the replacement is removed and + the old container is renamed back and started (rollback). Exit code 0 = updated, 1 = rolled + back, 2 = fatal. +5. The (new or restored) manager reads the exited updater's logs at the next `GET /api/system`, + shows the outcome in the card, and removes the updater container. + +Expect a few seconds of downtime while the containers swap; the panel keeps polling and reconnects +on its own. The sessions live in SQLite under `./data`, so the login survives. Compose still sees +the replacement as its `manager` service (labels are copied); a later `docker compose up -d --build` +works as usual. The checkout is kept in `data/repos/_manager` and logs in `data/logs/_manager/`. +Over `ssh://` the clone uses the mounted `SSH_DIR`, like installations do. + +Caveats: installation changes (build, deploy, start, stop...) answer `409` while an update is in +progress, and the hand-over runs inside the build queue, so no installation build overlaps it. The +updater removes the old manager image after a successful swap, so before running `docker compose +up -d --build` on the host again, `git pull` its checkout first or compose will rebuild (and +deploy) an older version than the one installed from the panel.