mirror of
https://github.com/Dasemu/remote-mcp-manager.git
synced 2026-11-26 23:36:31 +00:00
fix: address review findings on the memory safeguards
- kill the whole process group on git/nixpacks timeout so a hung docker build cannot block the build queue - mark interrupted cloning/building/starting installations as error on boot - keep a running installation served while it rebuilds, including failed builds - time out Docker image calls inside the build queue - make session touch best-effort Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a999b8c694
commit
5fb1d6b0b4
12 files changed
+118
-23
No files matched your search
@@ -2,13 +2,15 @@ import fs from "node:fs";
|
||||
import { spawn } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { config } from "../config/env.js";
|
||||
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 }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(cmd, args, { cwd, timeout: GIT_TIMEOUT_MS });
|
||||
const child = spawn(cmd, args, { cwd, detached: true });
|
||||
killGroupAfter(child, GIT_TIMEOUT_MS);
|
||||
let output = "";
|
||||
child.stdout.on("data", (d) => (output += d.toString()));
|
||||
child.stderr.on("data", (d) => (output += d.toString()));
|
||||
|
||||
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { config } from "../config/env.js";
|
||||
import { killGroupAfter } from "../util/processTimeout.js";
|
||||
|
||||
export function buildLogPath(slug: string, buildId: string): string {
|
||||
return path.join(config.logsDir, slug, `${buildId}.log`);
|
||||
@@ -86,7 +87,8 @@ export function runNixpacksBuild(
|
||||
logStream.write(`[remote-mcp-manager] pinning NIXPACKS_NODE_VERSION=${nodeVersion}\n`);
|
||||
}
|
||||
|
||||
const child = spawn("nixpacks", args, { timeout: BUILD_TIMEOUT_MS });
|
||||
const child = spawn("nixpacks", args, { detached: true });
|
||||
killGroupAfter(child, BUILD_TIMEOUT_MS);
|
||||
child.stdout.pipe(logStream, { end: false });
|
||||
child.stderr.pipe(logStream, { end: false });
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ process.env.DATA_DIR = tmpDir;
|
||||
process.env.DB_PATH = path.join(tmpDir, "db.sqlite");
|
||||
process.env.MASTER_KEY = "test-master-key-at-least-32-characters-long";
|
||||
|
||||
const { createInstallation, updateInstallation, getInstallationById, slugify } = await import("./installations.js");
|
||||
const { createInstallation, updateInstallation, getInstallationById, slugify, reconcileInterruptedInstallations } =
|
||||
await import("./installations.js");
|
||||
|
||||
describe("slugify", () => {
|
||||
it("normalizes names into a URL/container-safe slug", () => {
|
||||
@@ -59,3 +60,18 @@ describe("installations repository", () => {
|
||||
expect(getInstallationById(installation.id)?.env).toEqual({ FOO: "bar", API_KEY: "shh" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileInterruptedInstallations", () => {
|
||||
it("turns statuses that only a live process can advance into errors, and leaves the rest alone", () => {
|
||||
const stuck = createInstallation({ name: "Stuck", slug: "stuck", repoUrl: "https://example.com/a.git" });
|
||||
const fine = createInstallation({ name: "Fine", slug: "fine", repoUrl: "https://example.com/b.git" });
|
||||
updateInstallation(stuck.id, { status: "starting" });
|
||||
updateInstallation(fine.id, { status: "running" });
|
||||
|
||||
expect(reconcileInterruptedInstallations()).toBeGreaterThanOrEqual(1);
|
||||
|
||||
expect(getInstallationById(stuck.id)?.status).toBe("error");
|
||||
expect(getInstallationById(stuck.id)?.statusDetail).toContain("interrupted");
|
||||
expect(getInstallationById(fine.id)?.status).toBe("running");
|
||||
});
|
||||
});
|
||||
@@ -229,6 +229,20 @@ export function updateInstallation(id: string, patch: InstallationUpdate): Insta
|
||||
return getInstallationById(id)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that only make sense while this process is working on the installation. After a
|
||||
* restart (including the memory guard's deliberate one) nothing is working on them any more, so
|
||||
* they would otherwise stay stuck forever, locking the UI buttons and gating the proxy.
|
||||
*/
|
||||
export function reconcileInterruptedInstallations(): number {
|
||||
return db
|
||||
.prepare(
|
||||
`UPDATE installations SET status = 'error', status_detail = ?, updated_at = ?
|
||||
WHERE status IN ('cloning', 'building', 'starting')`,
|
||||
)
|
||||
.run("interrupted by a manager restart — use Start or Redeploy to recover", new Date().toISOString()).changes;
|
||||
}
|
||||
|
||||
export function deleteInstallation(id: string): void {
|
||||
db.prepare("DELETE FROM installations WHERE id = ?").run(id);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ export async function runInstallationContainer(installation: Installation): Prom
|
||||
|
||||
export async function getImageId(imageTag: string): Promise<string | undefined> {
|
||||
try {
|
||||
const info = await docker.getImage(imageTag).inspect();
|
||||
const info = await withTimeout(docker.getImage(imageTag).inspect(), DOCKER_CALL_TIMEOUT_MS, `docker inspect ${imageTag}`);
|
||||
return info.Id;
|
||||
} catch {
|
||||
return undefined;
|
||||
@@ -92,7 +92,7 @@ export async function getImageId(imageTag: string): Promise<string | undefined>
|
||||
/** Best-effort removal: leaves the image alone if it's still referenced (e.g. by a running container). */
|
||||
export async function removeImageIfUnused(imageId: string): Promise<void> {
|
||||
try {
|
||||
await docker.getImage(imageId).remove({ force: false });
|
||||
await withTimeout(docker.getImage(imageId).remove({ force: false }), DOCKER_CALL_TIMEOUT_MS, "docker image rm");
|
||||
} catch {
|
||||
// still in use or already gone — nothing to do
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import express from "express";
|
||||
import session from "express-session";
|
||||
import { config } from "./config/env.js";
|
||||
import { db } from "./db/index.js";
|
||||
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";
|
||||
@@ -14,6 +15,9 @@ if (!config.sessionSecret) {
|
||||
throw new Error("SESSION_SECRET env var must be set");
|
||||
}
|
||||
|
||||
const interrupted = reconcileInterruptedInstallations();
|
||||
if (interrupted > 0) console.warn(`marked ${interrupted} interrupted installation(s) as error after restart`);
|
||||
|
||||
const app = express();
|
||||
app.set("trust proxy", 1);
|
||||
app.use(
|
||||
|
||||
@@ -72,15 +72,28 @@ export function configureInstallation(
|
||||
return updateInstallation(id, patch);
|
||||
}
|
||||
|
||||
export function buildInstallation(id: string): Promise<Installation> {
|
||||
return enqueueBuild(() => runBuild(id));
|
||||
interface BuildOutcome {
|
||||
installation: Installation;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
async function runBuild(id: string): Promise<Installation> {
|
||||
export async function buildInstallation(id: string): Promise<Installation> {
|
||||
return (await enqueueBuild(() => runBuild(id))).installation;
|
||||
}
|
||||
|
||||
async function runBuild(id: string): Promise<BuildOutcome> {
|
||||
const installation = getInstallationById(id);
|
||||
if (!installation) throw new Error("installation not found");
|
||||
|
||||
updateInstallation(id, { status: "building", statusDetail: null });
|
||||
// A build never touches the running container, so a running installation keeps its
|
||||
// "running" status (and keeps being served by the proxy) throughout, whether the build
|
||||
// succeeds or fails. Any other installation shows the build's progress/failure instead.
|
||||
const wasRunning = installation.status === "running";
|
||||
if (!wasRunning) updateInstallation(id, { status: "building", statusDetail: null });
|
||||
const fail = (detail: string): BuildOutcome => ({
|
||||
installation: updateInstallation(id, { status: wasRunning ? "running" : "error", statusDetail: detail }),
|
||||
ok: false,
|
||||
});
|
||||
|
||||
// The clone on disk is otherwise only ever made once, at draft creation — without this,
|
||||
// every "rebuild" silently reused that same stale checkout forever, never picking up new
|
||||
@@ -88,7 +101,7 @@ async function runBuild(id: string): Promise<Installation> {
|
||||
try {
|
||||
await cloneOrUpdateRepo(installation.slug, installation.repoUrl, installation.gitRef);
|
||||
} catch (err) {
|
||||
return updateInstallation(id, { status: "error", statusDetail: `git pull failed: ${(err as Error).message}` });
|
||||
return fail(`git pull failed: ${(err as Error).message}`);
|
||||
}
|
||||
|
||||
const imageTag = `mcpmgr/${installation.slug}:latest`;
|
||||
@@ -102,10 +115,7 @@ async function runBuild(id: string): Promise<Installation> {
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
return updateInstallation(id, {
|
||||
status: "error",
|
||||
statusDetail: `build failed, see log at ${result.logPath}`,
|
||||
});
|
||||
return fail(`build failed, see log at ${result.logPath}`);
|
||||
}
|
||||
|
||||
// Nixpacks moves the tag to the new image, leaving the previous one dangling — clean it up
|
||||
@@ -117,7 +127,10 @@ async function runBuild(id: string): Promise<Installation> {
|
||||
}
|
||||
}
|
||||
|
||||
return updateInstallation(id, { status: "built", statusDetail: null, imageTag });
|
||||
return {
|
||||
installation: updateInstallation(id, { status: wasRunning ? "running" : "built", statusDetail: null, imageTag }),
|
||||
ok: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function deployInstallation(id: string): Promise<Installation> {
|
||||
@@ -139,10 +152,10 @@ export async function deployInstallation(id: string): Promise<Installation> {
|
||||
|
||||
export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise<Installation> {
|
||||
if (opts.rebuild) {
|
||||
// A failed build must stop here: deploying anyway would silently run the previous image
|
||||
// and flip the status back to "running", hiding the failure.
|
||||
const built = await buildInstallation(id);
|
||||
if (built.status === "error") return built;
|
||||
// A failed build must stop here: deploying anyway would silently redeploy the previous image
|
||||
// and report success, hiding the failure.
|
||||
const built = await enqueueBuild(() => runBuild(id));
|
||||
if (!built.ok) return built.installation;
|
||||
}
|
||||
return deployInstallation(id);
|
||||
}
|
||||
|
||||
@@ -61,9 +61,10 @@ export class SqliteSessionStore extends session.Store {
|
||||
touch(sid: string, sess: session.SessionData, cb?: () => void): void {
|
||||
try {
|
||||
this.db.prepare("UPDATE sessions SET expires = ? WHERE sid = ?").run(this.expiryOf(sess), sid);
|
||||
} finally {
|
||||
cb?.();
|
||||
} catch {
|
||||
// best effort: a failed touch only means the session expires on its original schedule
|
||||
}
|
||||
cb?.();
|
||||
}
|
||||
|
||||
destroy(sid: string, cb?: (err?: unknown) => void): void {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { spawn } from "node:child_process";
|
||||
import { killGroupAfter } from "./processTimeout.js";
|
||||
|
||||
describe("killGroupAfter", () => {
|
||||
it("kills a hung grandchild so the child's 'close' event still fires", async () => {
|
||||
// The shell backgrounds `sleep` (a grandchild that inherits stdio) and waits on it.
|
||||
const child = spawn("sh", ["-c", "sleep 30 & wait"], { detached: true });
|
||||
killGroupAfter(child, 100);
|
||||
const started = Date.now();
|
||||
await new Promise((resolve) => child.on("close", resolve));
|
||||
expect(Date.now() - started).toBeLessThan(5_000);
|
||||
});
|
||||
|
||||
it("does nothing to a process that exits on its own", async () => {
|
||||
const child = spawn("sh", ["-c", "exit 0"], { detached: true });
|
||||
killGroupAfter(child, 60_000);
|
||||
const code = await new Promise((resolve) => child.on("close", resolve));
|
||||
expect(code).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
/**
|
||||
* Kills the child's whole process group (SIGKILL) after `ms`. Spawn the child with `detached: true`
|
||||
* so it leads its own group. Plain `spawn({ timeout })` only signals the direct child: a grandchild
|
||||
* (e.g. the `docker build` nixpacks runs, or `ssh` under git) survives holding the stdio pipes, so
|
||||
* the child's 'close' event never fires and whatever awaits it hangs forever.
|
||||
*/
|
||||
export function killGroupAfter(child: ChildProcess, ms: number): void {
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
process.kill(-child.pid!, "SIGKILL");
|
||||
} catch {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, ms);
|
||||
timer.unref();
|
||||
child.once("exit", () => clearTimeout(timer));
|
||||
}
|
||||
Reference in new issue
Block a user