mirror of
https://github.com/Dasemu/remote-mcp-manager.git
synced 2026-11-26 15:26:27 +00:00
Merge pull request 'feat: add a panel button to update the manager itself' (#3) from claude/remote-mcp-manager-memory-leak-204b11 into master
Reviewed-on: #3
This commit is contained in:
commit
c1f90b28c1
28 files changed
+1141
-8
No files matched your search
@@ -40,6 +40,16 @@ 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
|
||||
# Optional, read by docker compose at build time only (not by the app): the commit being built,
|
||||
# e.g. GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build
|
||||
# GIT_SHA=
|
||||
|
||||
# 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.
|
||||
|
||||
@@ -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`.
|
||||
@@ -38,9 +38,15 @@ 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
|
||||
# Commit this image was built from, shown in the panel. Passed with --build-arg GIT_SHA=<sha>
|
||||
# (compose: see docker-compose.yml; the panel's self-update does it itself).
|
||||
ARG GIT_SHA=unknown
|
||||
ENV GIT_SHA=$GIT_SHA
|
||||
# Hard V8 heap ceiling, above MANAGER_MEMORY_LIMIT_MB (the soft limit the app enforces itself):
|
||||
# a leak ends in a crash + restart by the compose restart policy instead of swapping the host.
|
||||
ENV NODE_OPTIONS=--max-old-space-size=768
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Router } from "express";
|
||||
import { getSystemInfo, refreshRemoteStatus, startSelfUpdate, SelfUpdateError } from "../system/selfUpdate.js";
|
||||
|
||||
export const systemRouter = Router();
|
||||
|
||||
systemRouter.get("/", async (_req, res) => {
|
||||
res.json(await getSystemInfo());
|
||||
});
|
||||
|
||||
systemRouter.post("/check", async (_req, res) => {
|
||||
await refreshRemoteStatus();
|
||||
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 });
|
||||
}
|
||||
});
|
||||
@@ -7,10 +7,15 @@ import { killGroupAfter } from "../util/processTimeout.js";
|
||||
// A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever.
|
||||
const GIT_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> {
|
||||
export function run(
|
||||
cmd: string,
|
||||
args: string[],
|
||||
cwd?: string,
|
||||
timeoutMs = GIT_TIMEOUT_MS,
|
||||
): Promise<{ code: number; output: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(cmd, args, { cwd, detached: true });
|
||||
killGroupAfter(child, GIT_TIMEOUT_MS);
|
||||
killGroupAfter(child, timeoutMs);
|
||||
let output = "";
|
||||
child.stdout.on("data", (d) => (output += d.toString()));
|
||||
child.stderr.on("data", (d) => (output += d.toString()));
|
||||
@@ -39,6 +44,13 @@ export async function cloneOrUpdateRepo(slug: string, repoUrl: string, gitRef?:
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** Full SHA of the checkout's HEAD, or undefined if it can't be read. */
|
||||
export async function readHeadSha(dir: string): Promise<string | undefined> {
|
||||
const { code, output } = await run("git", ["rev-parse", "HEAD"], dir).catch(() => ({ code: 1, output: "" }));
|
||||
const sha = output.trim();
|
||||
return code === 0 && /^[0-9a-f]{40}$/.test(sha) ? sha : undefined;
|
||||
}
|
||||
|
||||
export function readEnvExampleKeys(dir: string): string[] {
|
||||
const file = path.join(dir, ".env.example");
|
||||
if (!fs.existsSync(file)) return [];
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeSha, parseCommitLog } from "./commits.js";
|
||||
|
||||
describe("normalizeSha", () => {
|
||||
it("accepts hex shas and lowercases them", () => {
|
||||
expect(normalizeSha("ABCDEF1234567")).toBe("abcdef1234567");
|
||||
expect(normalizeSha(" 5fb1d6b\n")).toBe("5fb1d6b");
|
||||
});
|
||||
|
||||
it("rejects unknown, empty, too short and non-hex values", () => {
|
||||
for (const v of [undefined, "", "unknown", "abc12", "zzzzzzzz", "abc123; rm -rf /"]) {
|
||||
expect(normalizeSha(v)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCommitLog", () => {
|
||||
it("parses sha and subject, keeping tabs inside the subject", () => {
|
||||
const out = "a1b2c3d\tfeat: add thing\ne4f5a6b\tfix: a\tb\n";
|
||||
expect(parseCommitLog(out)).toEqual([
|
||||
{ sha: "a1b2c3d", subject: "feat: add thing" },
|
||||
{ sha: "e4f5a6b", subject: "fix: a\tb" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns nothing for empty output", () => {
|
||||
expect(parseCommitLog("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
export interface CommitSummary {
|
||||
sha: string;
|
||||
subject: string;
|
||||
}
|
||||
|
||||
const SHA_RE = /^[0-9a-f]{7,40}$/;
|
||||
|
||||
/** Accepts a baked-in/inspected SHA only if it is plain hex; "unknown" and junk become undefined. */
|
||||
export function normalizeSha(raw: string | undefined): string | undefined {
|
||||
const sha = raw?.trim().toLowerCase();
|
||||
return sha && SHA_RE.test(sha) ? sha : undefined;
|
||||
}
|
||||
|
||||
/** Parses `git log --format=%h%x09%s` output. */
|
||||
export function parseCommitLog(output: string): CommitSummary[] {
|
||||
return output
|
||||
.split("\n")
|
||||
.filter((line) => line.includes("\t"))
|
||||
.map((line) => {
|
||||
const [sha, ...rest] = line.split("\t");
|
||||
return { sha: sha!.trim(), subject: rest.join("\t").trim() };
|
||||
});
|
||||
}
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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) },
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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("");
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "remote-check-"));
|
||||
const origin = path.join(tmp, "origin");
|
||||
const shas: string[] = [];
|
||||
|
||||
function git(cwd: string, ...args: string[]) {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" },
|
||||
}).trim();
|
||||
}
|
||||
|
||||
async function load(ref = "main") {
|
||||
vi.resetModules();
|
||||
vi.stubEnv("DATA_DIR", path.join(tmp, "data"));
|
||||
vi.stubEnv("SELF_UPDATE_REPO_URL", origin);
|
||||
vi.stubEnv("SELF_UPDATE_REF", ref);
|
||||
return import("./remoteCheck.js");
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
fs.mkdirSync(origin);
|
||||
git(origin, "init", "-q", "-b", "main");
|
||||
for (const n of [1, 2, 3]) {
|
||||
fs.writeFileSync(path.join(origin, "f.txt"), String(n));
|
||||
git(origin, "add", ".");
|
||||
git(origin, "commit", "-q", "-m", `commit ${n}`);
|
||||
shas.push(git(origin, "rev-parse", "HEAD"));
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
vi.unstubAllEnvs();
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("checkRemote", () => {
|
||||
it("resolves an annotated tag to its commit", async () => {
|
||||
git(origin, "tag", "-a", "v1", "-m", "release", shas[2]!);
|
||||
const { checkRemote } = await load("v1");
|
||||
const status = await checkRemote(shas[0], true);
|
||||
expect(status.remoteSha).toBe(shas[2]);
|
||||
expect(status.behind).toBe(2);
|
||||
});
|
||||
|
||||
it("runs a fresh check after a forced refresh requested mid-flight", async () => {
|
||||
const { checkRemote } = await load();
|
||||
const first = checkRemote(shas[0]);
|
||||
const forced = checkRemote(shas[0], true);
|
||||
const [a, b] = await Promise.all([first, forced]);
|
||||
expect(b.checkedAt >= a.checkedAt).toBe(true);
|
||||
expect(b).not.toBe(a);
|
||||
});
|
||||
|
||||
it("counts the commits the installed sha is missing", async () => {
|
||||
const { checkRemote } = await load();
|
||||
const status = await checkRemote(shas[0], true);
|
||||
expect(status.error).toBeNull();
|
||||
expect(status.remoteSha).toBe(shas[2]);
|
||||
expect(status.behind).toBe(2);
|
||||
expect(status.commits.map((c) => c.subject)).toEqual(["commit 3", "commit 2"]);
|
||||
});
|
||||
|
||||
it("reports 0 when installed is the remote head", async () => {
|
||||
const { checkRemote } = await load();
|
||||
expect((await checkRemote(shas[2], true)).behind).toBe(0);
|
||||
});
|
||||
|
||||
it("reports the remote head only when the installed sha is unknown to it", async () => {
|
||||
const { checkRemote } = await load();
|
||||
const status = await checkRemote("deadbeefdeadbeef", true);
|
||||
expect(status.behind).toBeNull();
|
||||
expect(status.remoteSha).toBe(shas[2]);
|
||||
expect(status.error).toBeNull();
|
||||
});
|
||||
|
||||
it("reports an error instead of throwing when the remote is unreachable", async () => {
|
||||
await load();
|
||||
vi.stubEnv("SELF_UPDATE_REPO_URL", path.join(tmp, "does-not-exist"));
|
||||
vi.resetModules();
|
||||
const mod = await import("./remoteCheck.js");
|
||||
const status = await mod.checkRemote(shas[0], true);
|
||||
expect(status.error).toMatch(/git fetch failed/);
|
||||
expect(status.behind).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { config } from "../config/env.js";
|
||||
import { run } from "../build/git.js";
|
||||
import { type CommitSummary, parseCommitLog } from "./commits.js";
|
||||
|
||||
// A bare repo that only ever holds commit history (no blobs) of the update source, so counting
|
||||
// "how far behind" doesn't need a full clone. Name can't collide with an installation slug.
|
||||
const CHECK_DIR = "_manager-check";
|
||||
const OK_TTL_MS = 10 * 60 * 1000;
|
||||
const ERROR_TTL_MS = 60 * 1000;
|
||||
const MAX_LISTED = 20;
|
||||
// The panel waits on this, so it gets far less than the 5 min installs allow for a clone.
|
||||
const GIT_CHECK_TIMEOUT_MS = 60 * 1000;
|
||||
|
||||
export interface RemoteStatus {
|
||||
checkedAt: string;
|
||||
remoteSha: string | null;
|
||||
/** Commits on the remote that the installed build doesn't have; null when it can't be told. */
|
||||
behind: number | null;
|
||||
commits: CommitSummary[];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
let cached: { status: RemoteStatus; expires: number; forSha: string | undefined } | null = null;
|
||||
let inFlight: Promise<RemoteStatus> | null = null;
|
||||
let queuedForce: Promise<RemoteStatus> | null = null;
|
||||
|
||||
async function git(cwd: string, args: string[]) {
|
||||
return run("git", args, cwd, GIT_CHECK_TIMEOUT_MS).catch((err: Error) => ({ code: 1, output: err.message }));
|
||||
}
|
||||
|
||||
async function compute(installedSha: string | undefined): Promise<RemoteStatus> {
|
||||
const base: RemoteStatus = { checkedAt: new Date().toISOString(), remoteSha: null, behind: null, commits: [], error: null };
|
||||
const url = config.selfUpdateRepoUrl;
|
||||
if (!url) return { ...base, error: "SELF_UPDATE_REPO_URL is not set" };
|
||||
|
||||
const dir = path.join(config.reposDir, CHECK_DIR);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
if (!fs.existsSync(path.join(dir, "HEAD"))) {
|
||||
const init = await git(dir, ["init", "--bare", "--quiet"]);
|
||||
if (init.code !== 0) return { ...base, error: `git init failed: ${init.output.trim()}` };
|
||||
}
|
||||
|
||||
// Blobless fetch where the server supports it; plain fetch otherwise.
|
||||
const fetchTail = ["--quiet", "--no-tags", "--", url, config.selfUpdateRef];
|
||||
let fetched = await git(dir, ["fetch", "--filter=blob:none", ...fetchTail]);
|
||||
// Only a server that doesn't do partial clones warrants the retry; an unreachable one would
|
||||
// just make the panel wait twice as long.
|
||||
if (fetched.code !== 0 && /filter/i.test(fetched.output)) fetched = await git(dir, ["fetch", ...fetchTail]);
|
||||
if (fetched.code !== 0) return { ...base, error: `git fetch failed: ${fetched.output.trim().slice(-300)}` };
|
||||
|
||||
const head = await git(dir, ["rev-parse", "--verify", "FETCH_HEAD^{commit}"]);
|
||||
const remoteSha = head.output.trim();
|
||||
if (head.code !== 0 || !remoteSha) return { ...base, error: "could not read the fetched head" };
|
||||
if (!installedSha) return { ...base, remoteSha };
|
||||
if (remoteSha.startsWith(installedSha)) return { ...base, remoteSha, behind: 0 };
|
||||
|
||||
// The installed commit has to be an ancestor of the remote head to count what is new; if it
|
||||
// isn't (force-push, other branch, local build) we can only report the remote head.
|
||||
const isAncestor = await git(dir, ["merge-base", "--is-ancestor", installedSha, remoteSha]);
|
||||
if (isAncestor.code !== 0) return { ...base, remoteSha };
|
||||
|
||||
const range = `${installedSha}..${remoteSha}`;
|
||||
const count = await git(dir, ["rev-list", "--count", range]);
|
||||
const behind = Number.parseInt(count.output.trim(), 10);
|
||||
if (count.code !== 0 || Number.isNaN(behind)) {
|
||||
return { ...base, remoteSha, error: `git rev-list failed: ${count.output.trim().slice(-200)}` };
|
||||
}
|
||||
const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]);
|
||||
return { ...base, remoteSha, behind, commits: log.code === 0 ? parseCommitLog(log.output) : [] };
|
||||
}
|
||||
|
||||
function start(installedSha: string | undefined): Promise<RemoteStatus> {
|
||||
inFlight = compute(installedSha)
|
||||
.catch((err: Error): RemoteStatus => ({
|
||||
checkedAt: new Date().toISOString(),
|
||||
remoteSha: null,
|
||||
behind: null,
|
||||
commits: [],
|
||||
error: err.message,
|
||||
}))
|
||||
.then((status) => {
|
||||
cached = { status, expires: Date.now() + (status.error ? ERROR_TTL_MS : OK_TTL_MS), forSha: installedSha };
|
||||
return status;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached for a few minutes; concurrent callers share one fetch. `force` skips the cache, and if a
|
||||
* fetch is already running (it may have read the refs before a push) waits for it and runs a
|
||||
* fresh one after it — at most one is ever queued.
|
||||
*/
|
||||
export function checkRemote(installedSha: string | undefined, force = false): Promise<RemoteStatus> {
|
||||
if (!force && cached && cached.expires > Date.now() && cached.forSha === installedSha) {
|
||||
return Promise.resolve(cached.status);
|
||||
}
|
||||
if (!inFlight) return start(installedSha);
|
||||
if (!force) return inFlight;
|
||||
queuedForce ??= inFlight.then(() => {
|
||||
queuedForce = null;
|
||||
return start(installedSha);
|
||||
});
|
||||
return queuedForce;
|
||||
}
|
||||
|
||||
/** Last known result without triggering a fetch (null if none yet). */
|
||||
export function cachedRemoteStatus(): RemoteStatus | null {
|
||||
return cached?.status ?? null;
|
||||
}
|
||||
|
||||
export function isRemoteCheckStale(installedSha: string | undefined): boolean {
|
||||
return !cached || cached.expires <= Date.now() || cached.forSha !== installedSha;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
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, readHeadSha, 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 { cachedRemoteStatus, checkRemote, isRemoteCheckStale } from "./remoteCheck.js";
|
||||
import { readInstalledSha, 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();
|
||||
const installedSha = readInstalledSha();
|
||||
// Refresh in the background so this endpoint never waits on a git fetch.
|
||||
if (config.selfUpdateRepoUrl && state.phase === "idle" && isRemoteCheckStale(installedSha)) {
|
||||
void checkRemote(installedSha);
|
||||
}
|
||||
return {
|
||||
version: readVersion(),
|
||||
sha: installedSha ?? null,
|
||||
remote: cachedRemoteStatus(),
|
||||
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, sha: string | undefined): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const logStream = fs.createWriteStream(logPath, { flags: "a" });
|
||||
const child = spawn("docker", ["build", "-t", image, ...(sha ? ["--build-arg", `GIT_SHA=${sha}`] : []), 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<void> {
|
||||
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}`);
|
||||
const sha = await readHeadSha(repoDir(CHECKOUT_SLUG));
|
||||
note(`building commit ${sha ?? "unknown"}`);
|
||||
if (!(await runDockerBuild(repoDir(CHECKOUT_SLUG), image, state.logPath!, sha))) {
|
||||
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";
|
||||
}
|
||||
|
||||
/** Forces a fresh look at the remote (the panel's "Check now"). */
|
||||
export function refreshRemoteStatus() {
|
||||
return checkRemote(readInstalledSha(), true);
|
||||
}
|
||||
|
||||
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<void> {
|
||||
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<void> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -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<boolean> {
|
||||
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<boolean> {
|
||||
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<number> {
|
||||
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);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,36 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { normalizeSha } from "./commits.js";
|
||||
|
||||
// VERSION sits at the repo root, four levels above this file in both the image and a checkout:
|
||||
// <root>/apps/server/{src,dist}/system/version.*
|
||||
const repoRoot = path.resolve(import.meta.dirname, "../../../..");
|
||||
const versionFile = path.join(repoRoot, "VERSION");
|
||||
|
||||
export function readVersion(): string {
|
||||
try {
|
||||
return fs.readFileSync(versionFile, "utf8").trim() || "unknown";
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
let sha: string | undefined | null = null;
|
||||
|
||||
/**
|
||||
* Commit this build was made from. The image gets it as the GIT_SHA build arg (see the
|
||||
* Dockerfile); in a plain checkout (local dev) it is read from git instead.
|
||||
*/
|
||||
export function readInstalledSha(): string | undefined {
|
||||
if (sha !== null) return sha;
|
||||
sha = normalizeSha(process.env.GIT_SHA);
|
||||
if (!sha) {
|
||||
try {
|
||||
sha = normalizeSha(execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, timeout: 3000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }));
|
||||
} catch {
|
||||
sha = undefined;
|
||||
}
|
||||
}
|
||||
return sha;
|
||||
}
|
||||
@@ -19,6 +19,28 @@ export interface Installation {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface RemoteStatus {
|
||||
checkedAt: string;
|
||||
remoteSha: string | null;
|
||||
behind: number | null;
|
||||
commits: { sha: string; subject: string }[];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface SystemInfo {
|
||||
version: string;
|
||||
sha: string | null;
|
||||
remote: RemoteStatus | null;
|
||||
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<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(path, {
|
||||
...init,
|
||||
@@ -60,4 +82,8 @@ export const api = {
|
||||
request<{ bearerToken: string }>(`/api/installations/${id}/regenerate-token`, { method: "POST" }),
|
||||
remove: (id: string) => request<void>(`/api/installations/${id}`, { method: "DELETE" }),
|
||||
logs: (id: string) => request<{ log: string }>(`/api/installations/${id}/logs`),
|
||||
|
||||
systemInfo: () => request<SystemInfo>("/api/system"),
|
||||
checkManager: () => request<SystemInfo>("/api/system/check", { method: "POST" }),
|
||||
updateManager: () => request<{ ok: true }>("/api/system/update", { method: "POST" }),
|
||||
};
|
||||
@@ -0,0 +1,198 @@
|
||||
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<SystemInfo["phase"], string> = {
|
||||
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<SystemInfo | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [requested, setRequested] = useState(false);
|
||||
const [unreachable, setUnreachable] = useState(false);
|
||||
const [startedAt, setStartedAt] = useState<number | null>(null);
|
||||
const [gaveUp, setGaveUp] = useState(false);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [remoteGaveUp, setRemoteGaveUp] = 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]);
|
||||
|
||||
const repoConfigured = info !== null && info.unavailableReason !== "SELF_UPDATE_REPO_URL is not set";
|
||||
const waitingForRemote = repoConfigured && info !== null && info.remote === null && info.phase === "idle" && !remoteGaveUp;
|
||||
|
||||
// The first remote check runs in the background on the server; poll briefly until it lands.
|
||||
useEffect(() => {
|
||||
if (!waitingForRemote) return;
|
||||
let tries = 0;
|
||||
const timer = setInterval(() => {
|
||||
if (++tries > 10) {
|
||||
clearInterval(timer);
|
||||
setRemoteGaveUp(true);
|
||||
} else refresh();
|
||||
}, 3000);
|
||||
return () => clearInterval(timer);
|
||||
}, [waitingForRemote]);
|
||||
|
||||
async function checkNow() {
|
||||
setChecking(true);
|
||||
setRemoteGaveUp(false);
|
||||
setError(null);
|
||||
try {
|
||||
setInfo(await api.checkManager());
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="card section-gap">
|
||||
<div className="card-header">
|
||||
<span className="card-title">Manager</span>
|
||||
<span className="card-hint">
|
||||
{info ? `Version ${info.version} · ${info.sha ? info.sha.slice(0, 7) : "unknown commit"}` : "Restarting…"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{updating && (
|
||||
<p className="status-detail">
|
||||
{unreachable ? "The manager is restarting, waiting for it to come back…" : PHASE_LABEL[info?.phase ?? "idle"]}
|
||||
</p>
|
||||
)}
|
||||
{error && <div className="alert">{error}</div>}
|
||||
{gaveUp && <div className="alert">The manager did not come back in 10 minutes; check the host.</div>}
|
||||
{info?.error && <div className="alert">Update failed: {info.error}</div>}
|
||||
{!updating && info?.lastUpdate && (
|
||||
<p className="status-detail">
|
||||
Last update {info.lastUpdate.ok ? "succeeded" : "did not complete (rolled back or failed; see the log)"} ({new Date(info.lastUpdate.finishedAt).toLocaleString()}).
|
||||
</p>
|
||||
)}
|
||||
{!updating && info && repoConfigured && <RemoteLine info={info} checking={checking || waitingForRemote} />}
|
||||
{info && !info.canSelfUpdate && info.unavailableReason && (
|
||||
<p className="status-detail">Self-update unavailable: {info.unavailableReason}.</p>
|
||||
)}
|
||||
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn"
|
||||
disabled={!info?.canSelfUpdate || updating}
|
||||
onClick={update}
|
||||
title="Fetch the latest source, build a new image and replace this container"
|
||||
>
|
||||
{updating ? "Updating…" : "Update manager"}
|
||||
</button>
|
||||
{repoConfigured && (
|
||||
<button type="button" className="btn btn-ghost" disabled={checking || updating} onClick={checkNow}>
|
||||
{checking ? "Checking…" : "Check for updates"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{log && <pre className="log-pane">{log}</pre>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) {
|
||||
const remote = info.remote;
|
||||
if (!remote) {
|
||||
return <p className="status-detail">{checking ? "Checking the remote…" : "Not checked yet; use Check for updates."}</p>;
|
||||
}
|
||||
if (remote.error) return <p className="status-detail">Could not check the remote: {remote.error}</p>;
|
||||
|
||||
const head = remote.remoteSha?.slice(0, 7);
|
||||
const when = new Date(remote.checkedAt).toLocaleTimeString();
|
||||
if (remote.behind === 0) {
|
||||
return <p className="status-detail">Up to date with {info.ref} ({head}) · checked {when}</p>;
|
||||
}
|
||||
if (remote.behind === null) {
|
||||
return (
|
||||
<p className="status-detail">
|
||||
{info.sha
|
||||
? `The installed commit is not in the history of ${info.ref}; its head is ${head}.`
|
||||
: `The installed commit is unknown; ${info.ref} is at ${head}.`}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<p className="status-detail">
|
||||
{remote.behind} newer commit{remote.behind === 1 ? "" : "s"} on {info.ref} (head {head}) · checked {when}
|
||||
</p>
|
||||
<ul className="status-detail" style={{ margin: "4px 0 8px 18px" }}>
|
||||
{remote.commits.map((c) => (
|
||||
<li key={c.sha}>
|
||||
<code>{c.sha}</code> {c.subject}
|
||||
</li>
|
||||
))}
|
||||
{remote.behind > remote.commits.length && <li>…and {remote.behind - remote.commits.length} more</li>}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 }) {
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ManagerCard />
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
+8
-1
@@ -1,6 +1,11 @@
|
||||
services:
|
||||
manager:
|
||||
build: .
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
# export GIT_SHA=$(git rev-parse HEAD) before `docker compose up -d --build` so the panel
|
||||
# can show which commit is installed and how far behind the remote it is.
|
||||
GIT_SHA: ${GIT_SHA:-unknown}
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:3000:3000"
|
||||
@@ -18,6 +23,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
|
||||
|
||||
@@ -54,3 +54,12 @@ 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`.
|
||||
`system/remoteCheck.ts` compares the installed commit (`GIT_SHA`) with the remote head to show how many
|
||||
commits behind the manager is.
|
||||
@@ -29,3 +29,56 @@ 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 `<name>-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.
|
||||
|
||||
## Installed version and newer commits
|
||||
|
||||
The Manager card shows the version (`VERSION`) and the **commit SHA** the running image was built
|
||||
from, and how many commits `SELF_UPDATE_REF` has on `SELF_UPDATE_REPO_URL` that it doesn't (with
|
||||
the subjects of the latest 20). `Check for updates` forces a refresh; otherwise the result is
|
||||
cached for 10 minutes (1 minute after a failure) and refreshed in the background by
|
||||
`GET /api/system`, so the endpoint never waits on git.
|
||||
|
||||
- **Where the SHA comes from:** the `GIT_SHA` build arg (baked as an image `ENV`). The panel's
|
||||
self-update passes it itself. With compose, build with
|
||||
`GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build`; without it the card says
|
||||
"unknown commit" and can only show the remote head. In local dev it is read with `git rev-parse`.
|
||||
- **How it counts:** a history-only (blobless where the server allows it) fetch into the bare repo
|
||||
`data/repos/_manager-check`, then `git rev-list --count <installed>..<remote head>`. If the
|
||||
installed commit isn't an ancestor of the remote head (force-push, other branch) only the remote
|
||||
head is shown.
|
||||
Reference in new issue
Block a user