diff --git a/.env.example b/.env.example index 9f86684..ce13f74 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,14 @@ MASTER_KEY=change-me-to-a-random-string-of-at-least-32-characters CONTAINER_MEMORY_MB=512 CONTAINER_CPUS=1 +# Safeguards against a stuck upstream or a memory leak taking the host down (see docs/operations.md). +# Inactivity timeout (ms) on proxied MCP requests/streams +PROXY_TIMEOUT_MS=300000 +# Max simultaneous proxied requests; beyond this the proxy answers 503 +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 + # 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 e81c779..2f6c4f8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,4 +36,7 @@ authenticated requests to it. See `README.md` for the full flow and `docs/` for ## Gotchas - Builds run one at a time; no per-installation resource override (see README "Known limitations"). +- The manager enforces its own memory/socket limits (`docs/operations.md`); keep every new long-lived resource bounded. +- 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. diff --git a/Dockerfile b/Dockerfile index 389015f..a88dd6b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -41,5 +41,8 @@ COPY --from=build /repo/apps/web/dist apps/web/dist WORKDIR /repo/apps/server ENV NODE_ENV=production +# 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 EXPOSE 3000 CMD ["node", "dist/index.js"] diff --git a/LESSONS.md b/LESSONS.md index 216077c..cd58180 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -115,3 +115,18 @@ A short image name wasn't enough to remove an image via the Docker-compatible so Mounting only `apps/server` into a test container produced `node_modules not found` — the hoisted root `node_modules` wasn't mounted. **Avoid it:** mount the whole repo root when testing a workspace package, not just its subdirectory. + +## The manager itself needs hard limits — it shares the host with every MCP + +The manager ran with no timeouts, no concurrency cap, no heap ceiling and `MemoryStore` for +sessions. When it started to grow (~1.1 GiB of RAM + swap) and Docker slowed under the +pressure, every proxied request kept waiting on `docker inspect` and held its socket, ~70 +connections piled up on port 3000, the 3 GiB LXC swapped, and even `docker ps` hung — taking +every MCP down with it. The root cause of the growth was not proven (a feedback loop of +unbounded in-flight requests is the prime suspect); what was fixed is that nothing can grow +unbounded any more. See `docs/operations.md`. + +**Avoid it:** any long-lived or per-request resource (sockets, sessions, queues, in-flight +subprocesses) needs an explicit bound or timeout. Don't rely on a cgroup limit for the manager +on the OpenRC LXC (see the cgroup lesson above) — enforce limits inside the process. Local Node +24 cannot compile `better-sqlite3@11`, so run the test suite in a `node:20` container. diff --git a/README.md b/README.md index 5495167..f1d407c 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ a runner. - Every installed container gets the same memory/CPU caps (`CONTAINER_MEMORY_MB`, `CONTAINER_CPUS`), no per-installation override yet. - No multi-user support — single operator only. -- Builds run one at a time. +- Builds run one at a time (queued in the manager; a build is killed after 30 minutes). See `LESSONS.md` for operational gotchas found while building and running this (Nixpacks runtime-version mismatches, Podman networking, SELinux, etc.). diff --git a/apps/server/src/api/installations.ts b/apps/server/src/api/installations.ts index fad765a..207e6bc 100644 --- a/apps/server/src/api/installations.ts +++ b/apps/server/src/api/installations.ts @@ -13,6 +13,9 @@ import { buildInstallation, deployInstallation, redeployInstallation, + startInstallation, + stopInstallation, + restartInstallation, removeInstallationContainer, } from "../service/orchestrator.js"; import { buildLogPath } from "../build/nixpacks.js"; @@ -117,6 +120,24 @@ installationsRouter.post("/:id/redeploy", async (req, res) => { } }); +for (const [action, handler] of [ + ["start", startInstallation], + ["stop", stopInstallation], + ["restart", restartInstallation], +] as const) { + installationsRouter.post(`/:id/${action}`, async (req, res) => { + if (!getInstallationById(req.params.id)) { + res.status(404).json({ error: "not found" }); + return; + } + try { + res.json(toPublicJson(await handler(req.params.id))); + } catch (err) { + res.status(500).json({ error: (err as Error).message }); + } + }); +} + installationsRouter.get("/:id/logs", (req, res) => { const installation = getInstallationById(req.params.id); if (!installation) { diff --git a/apps/server/src/build/git.ts b/apps/server/src/build/git.ts index 46acbde..da3e647 100644 --- a/apps/server/src/build/git.ts +++ b/apps/server/src/build/git.ts @@ -2,10 +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 }); + 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())); diff --git a/apps/server/src/build/nixpacks.ts b/apps/server/src/build/nixpacks.ts index f71121e..6392a34 100644 --- a/apps/server/src/build/nixpacks.ts +++ b/apps/server/src/build/nixpacks.ts @@ -2,11 +2,15 @@ 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`); } +// A hung build would hold the (serialized) build queue forever. +const BUILD_TIMEOUT_MS = 30 * 60 * 1000; + export interface BuildResult { success: boolean; logPath: string; @@ -83,7 +87,8 @@ export function runNixpacksBuild( logStream.write(`[remote-mcp-manager] pinning NIXPACKS_NODE_VERSION=${nodeVersion}\n`); } - const child = spawn("nixpacks", args); + const child = spawn("nixpacks", args, { detached: true }); + killGroupAfter(child, BUILD_TIMEOUT_MS); child.stdout.pipe(logStream, { end: false }); child.stderr.pipe(logStream, { end: false }); diff --git a/apps/server/src/config/env.ts b/apps/server/src/config/env.ts index cc95ba5..e7589ee 100644 --- a/apps/server/src/config/env.ts +++ b/apps/server/src/config/env.ts @@ -17,4 +17,12 @@ export const config = { // Per-container resource caps, applied to every installation (no per-installation override in V1). containerMemoryMb: Number(process.env.CONTAINER_MEMORY_MB ?? 512), containerCpus: Number(process.env.CONTAINER_CPUS ?? 1), + // Safeguards so one stuck upstream or a runaway heap can't take the whole host down. + // Inactivity timeout for proxied MCP requests/streams; a stalled upstream is cut after this. + proxyTimeoutMs: Number(process.env.PROXY_TIMEOUT_MS ?? 300_000), + // Max simultaneous proxied requests; beyond this the proxy answers 503 instead of piling up. + maxProxyRequests: Number(process.env.MAX_PROXY_REQUESTS ?? 100), + // 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), }; diff --git a/apps/server/src/db/installations.test.ts b/apps/server/src/db/installations.test.ts index ed733ec..65f9daa 100644 --- a/apps/server/src/db/installations.test.ts +++ b/apps/server/src/db/installations.test.ts @@ -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"); + }); +}); diff --git a/apps/server/src/db/installations.ts b/apps/server/src/db/installations.ts index 929991a..044ed05 100644 --- a/apps/server/src/db/installations.ts +++ b/apps/server/src/db/installations.ts @@ -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); } diff --git a/apps/server/src/docker/containers.ts b/apps/server/src/docker/containers.ts index 45da4cf..31ff680 100644 --- a/apps/server/src/docker/containers.ts +++ b/apps/server/src/docker/containers.ts @@ -2,6 +2,8 @@ import net from "node:net"; import Docker from "dockerode"; import { config } from "../config/env.js"; import type { Installation } from "../db/installations.js"; +import { withTimeout } from "../util/withTimeout.js"; +import { isNotFoundError, isNotModifiedError } from "./errors.js"; const docker = new Docker({ socketPath: config.dockerSocketPath }); @@ -12,7 +14,17 @@ export async function ensureNetwork(name: string): Promise { } } +// Every proxied MCP request needs the container's IP. Asking Docker each time meant a slow +// daemon stalled every request at once (and each one held its socket while waiting); a short +// cache plus a call timeout keeps one wedged Docker daemon from snowballing into the proxy. +const IP_CACHE_TTL_MS = 5_000; +const DOCKER_CALL_TIMEOUT_MS = 10_000; +// stop/restart send SIGTERM and wait the daemon's grace period (10s) before SIGKILL. +const DOCKER_STOP_TIMEOUT_MS = 30_000; +const ipCache = new Map; expires: number }>(); + export async function removeContainerIfExists(containerName: string): Promise { + ipCache.delete(containerName); try { await docker.getContainer(containerName).remove({ force: true }); } catch { @@ -25,6 +37,7 @@ export async function runInstallationContainer(installation: Installation): Prom await ensureNetwork(config.mcpNetworkName); await removeContainerIfExists(installation.containerName); + ipCache.delete(installation.containerName); const env = { ...installation.env, @@ -69,7 +82,7 @@ export async function runInstallationContainer(installation: Installation): Prom export async function getImageId(imageTag: string): Promise { 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; @@ -79,7 +92,7 @@ export async function getImageId(imageTag: string): Promise /** 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 { 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 } @@ -89,9 +102,45 @@ export async function stopInstallationContainer(containerName: string): Promise< await removeContainerIfExists(containerName); } -export async function getContainerIp(containerName: string): Promise { - const container = docker.getContainer(containerName); - const info = await container.inspect(); +// Lifecycle actions on the EXISTING container (no remove/recreate, so the image and the +// config it was created with stay untouched). Resolves false when the container no longer +// exists, so the caller can fall back to a full deploy. The container's IP can change across a +// stop/start, hence the cache is dropped before and after. +async function actOnExistingContainer( + containerName: string, + what: string, + timeoutMs: number, + action: (container: Docker.Container) => Promise, +): Promise { + ipCache.delete(containerName); + try { + await withTimeout(action(docker.getContainer(containerName)), timeoutMs, `docker ${what} ${containerName}`); + return true; + } catch (err) { + if (isNotFoundError(err)) return false; + // start on a running container / stop on a stopped one: already where we want it. + if (isNotModifiedError(err)) return true; + throw err; + } finally { + ipCache.delete(containerName); + } +} + +export const stopContainer = (containerName: string) => + actOnExistingContainer(containerName, "stop", DOCKER_STOP_TIMEOUT_MS, (c) => c.stop()); + +export const startContainer = (containerName: string) => + actOnExistingContainer(containerName, "start", DOCKER_CALL_TIMEOUT_MS, (c) => c.start()); + +export const restartContainer = (containerName: string) => + actOnExistingContainer(containerName, "restart", DOCKER_STOP_TIMEOUT_MS, (c) => c.restart()); + +async function lookupContainerIp(containerName: string): Promise { + const info = await withTimeout( + docker.getContainer(containerName).inspect(), + DOCKER_CALL_TIMEOUT_MS, + `docker inspect ${containerName}`, + ); const network = info.NetworkSettings.Networks[config.mcpNetworkName]; if (!network?.IPAddress) { throw new Error(`Container ${containerName} has no IP on network ${config.mcpNetworkName}`); @@ -99,6 +148,19 @@ export async function getContainerIp(containerName: string): Promise { return network.IPAddress; } +export function getContainerIp(containerName: string): Promise { + const cached = ipCache.get(containerName); + if (cached && cached.expires > Date.now()) return cached.ip; + + // Concurrent callers share one in-flight lookup; failures aren't cached. + const ip = lookupContainerIp(containerName); + ipCache.set(containerName, { ip, expires: Date.now() + IP_CACHE_TTL_MS }); + ip.catch(() => { + if (ipCache.get(containerName)?.ip === ip) ipCache.delete(containerName); + }); + return ip; +} + export async function waitForContainerHealth( installation: Installation, timeoutMs = 20_000, diff --git a/apps/server/src/docker/errors.test.ts b/apps/server/src/docker/errors.test.ts new file mode 100644 index 0000000..b73c828 --- /dev/null +++ b/apps/server/src/docker/errors.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { isNotFoundError, isNotModifiedError } from "./errors.js"; + +describe("isNotFoundError", () => { + it("matches a Docker API 404", () => { + expect(isNotFoundError(Object.assign(new Error("no such container"), { statusCode: 404 }))).toBe(true); + }); + + it("does not match other Docker errors or non-errors", () => { + expect(isNotFoundError(Object.assign(new Error("server error"), { statusCode: 500 }))).toBe(false); + expect(isNotFoundError(new Error("docker inspect x timed out after 10000ms"))).toBe(false); + expect(isNotFoundError(undefined)).toBe(false); + expect(isNotFoundError("404")).toBe(false); + }); +}); + +describe("isNotModifiedError", () => { + it("matches the 304 docker-modem raises for already started/stopped containers", () => { + expect(isNotModifiedError(Object.assign(new Error("already started"), { statusCode: 304 }))).toBe(true); + expect(isNotModifiedError(Object.assign(new Error("boom"), { statusCode: 500 }))).toBe(false); + expect(isNotModifiedError(new Error("plain"))).toBe(false); + }); +}); diff --git a/apps/server/src/docker/errors.ts b/apps/server/src/docker/errors.ts new file mode 100644 index 0000000..acfeb7b --- /dev/null +++ b/apps/server/src/docker/errors.ts @@ -0,0 +1,9 @@ +/** True when a dockerode call failed because the target container (or image) doesn't exist. */ +export function isNotFoundError(err: unknown): boolean { + return typeof err === "object" && err !== null && (err as { statusCode?: unknown }).statusCode === 404; +} + +/** True for HTTP 304: docker-modem surfaces "already started/stopped" as an error, but it means the container is already in the wanted state. */ +export function isNotModifiedError(err: unknown): boolean { + return typeof err === "object" && err !== null && (err as { statusCode?: unknown }).statusCode === 304; +} diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index baca1ae..8240b54 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -2,20 +2,27 @@ import path from "node:path"; import express from "express"; import session from "express-session"; import { config } from "./config/env.js"; -import "./db/index.js"; -import { handleMcpProxyRequest } from "./proxy/mcpProxy.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"; import { requireAuth } from "./middleware/requireAuth.js"; +import { SqliteSessionStore } from "./session/sqliteStore.js"; +import { startMemoryGuard } from "./service/memoryGuard.js"; 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( session({ + store: new SqliteSessionStore(db), secret: config.sessionSecret, resave: false, saveUninitialized: false, @@ -32,7 +39,16 @@ app.use( }), ); -app.get("/health", (_req, res) => res.json({ ok: true })); +app.get("/health", (_req, res) => { + const mem = process.memoryUsage(); + res.json({ + ok: true, + uptimeSec: Math.round(process.uptime()), + rssMb: Math.round(mem.rss / 1048576), + heapUsedMb: Math.round(mem.heapUsed / 1048576), + activeProxyRequests: getActiveProxyRequests(), + }); +}); // Bearer-token-gated MCP reverse proxy, public (auth handled per-installation). app.all("/mcp/:slug", handleMcpProxyRequest); @@ -53,6 +69,27 @@ app.get(/^\/(?!api|mcp|health).*/, (_req, res) => { }); }); -app.listen(config.port, () => { +const server = app.listen(config.port, () => { console.log(`remote-mcp-manager listening on http://localhost:${config.port}`); }); + +function shutdown(code: number): void { + server.close(() => process.exit(code)); + server.closeAllConnections(); + setTimeout(() => process.exit(code), 5_000).unref(); +} + +process.on("SIGTERM", () => shutdown(0)); +process.on("SIGINT", () => shutdown(0)); + +// Exit before a leak drags the whole host into swap; the container's restart policy +// (`unless-stopped`) starts a fresh process. +startMemoryGuard({ + limitMb: config.memoryLimitMb, + onExceeded: (usedMb) => { + console.error( + `memory guard: heap+external at ${Math.round(usedMb)} MB exceeds MANAGER_MEMORY_LIMIT_MB=${config.memoryLimitMb}, restarting`, + ); + shutdown(1); + }, +}); diff --git a/apps/server/src/proxy/mcpProxy.ts b/apps/server/src/proxy/mcpProxy.ts index 142f481..22467c6 100644 --- a/apps/server/src/proxy/mcpProxy.ts +++ b/apps/server/src/proxy/mcpProxy.ts @@ -3,8 +3,17 @@ import type { Request, Response } from "express"; import httpProxy from "http-proxy"; import { getInstallationBySlug, type Installation } from "../db/installations.js"; import { getContainerIp } from "../docker/containers.js"; +import { config } from "../config/env.js"; -const proxy = httpProxy.createProxyServer(); +// proxyTimeout: inactivity timeout on the upstream socket; timeout: same on the client socket. +// Without them a stalled MCP container (or a client that vanished mid-stream) holds its +// sockets and buffers forever, and those pile up until the host runs out of memory. +const proxy = httpProxy.createProxyServer({ proxyTimeout: config.proxyTimeoutMs, timeout: config.proxyTimeoutMs }); +let activeProxyRequests = 0; + +export function getActiveProxyRequests(): number { + return activeProxyRequests; +} proxy.on("error", (err, _req, res) => { if (!(res as Response).headersSent) { (res as Response).status(502).json({ error: "proxy error", detail: err.message }); @@ -51,6 +60,16 @@ export async function handleMcpProxyRequest(req: Request, res: Response): Promis return; } + // Bounded concurrency: when upstreams or Docker stall, shed load rather than queue unboundedly. + if (activeProxyRequests >= config.maxProxyRequests) { + res.set("Retry-After", "5").status(503).json({ error: "too many concurrent requests" }); + return; + } + activeProxyRequests += 1; + res.once("close", () => { + activeProxyRequests -= 1; + }); + let targetIp: string; try { targetIp = await getContainerIp(installation.containerName); diff --git a/apps/server/src/service/memoryGuard.test.ts b/apps/server/src/service/memoryGuard.test.ts new file mode 100644 index 0000000..bd0ac7b --- /dev/null +++ b/apps/server/src/service/memoryGuard.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it, vi } from "vitest"; +import { isOverLimit, startMemoryGuard } from "./memoryGuard.js"; + +const MB = 1024 * 1024; + +describe("isOverLimit", () => { + it("counts heap + external against the limit", () => { + expect(isOverLimit({ heapUsed: 300 * MB, external: 250 * MB }, 512)).toBe(true); + expect(isOverLimit({ heapUsed: 300 * MB, external: 100 * MB }, 512)).toBe(false); + }); + + it("is disabled when the limit is 0", () => { + expect(isOverLimit({ heapUsed: 9999 * MB, external: 0 }, 0)).toBe(false); + }); +}); + +describe("startMemoryGuard", () => { + it("fires onExceeded exactly once after the limit is passed", async () => { + const onExceeded = vi.fn(); + const timer = startMemoryGuard({ + limitMb: 100, + intervalMs: 5, + sample: () => ({ heapUsed: 200 * MB, external: 0 }), + onExceeded, + }); + await new Promise((r) => setTimeout(r, 40)); + clearInterval(timer); + expect(onExceeded).toHaveBeenCalledTimes(1); + }); + + it("does not start when disabled", () => { + expect(startMemoryGuard({ limitMb: 0, onExceeded: () => {} })).toBeUndefined(); + }); +}); diff --git a/apps/server/src/service/memoryGuard.ts b/apps/server/src/service/memoryGuard.ts new file mode 100644 index 0000000..271ce41 --- /dev/null +++ b/apps/server/src/service/memoryGuard.ts @@ -0,0 +1,40 @@ +const MB = 1024 * 1024; + +export interface MemorySample { + heapUsed: number; + external: number; +} + +/** Heap + external, not RSS: RSS drops when the kernel swaps pages out, which hides a leak on a swapping host. */ +export function usedMb(sample: MemorySample): number { + return (sample.heapUsed + sample.external) / MB; +} + +export function isOverLimit(sample: MemorySample, limitMb: number): boolean { + return limitMb > 0 && usedMb(sample) > limitMb; +} + +/** + * Polls the process's own memory and calls `onExceeded` once it passes `limitMb`. The caller is + * expected to exit so the container restart policy replaces a bloated process with a fresh one + * *before* the host starts swapping and every other container on it degrades. + */ +export function startMemoryGuard(opts: { + limitMb: number; + intervalMs?: number; + sample?: () => MemorySample; + onExceeded: (usedMb: number) => void; +}): NodeJS.Timeout | undefined { + if (opts.limitMb <= 0) return undefined; + const sample = opts.sample ?? (() => process.memoryUsage()); + let fired = false; + const timer = setInterval(() => { + const current = sample(); + if (!fired && isOverLimit(current, opts.limitMb)) { + fired = true; + opts.onExceeded(usedMb(current)); + } + }, opts.intervalMs ?? 30_000); + timer.unref(); + return timer; +} diff --git a/apps/server/src/service/orchestrator.ts b/apps/server/src/service/orchestrator.ts index 04c1f55..a4ab18f 100644 --- a/apps/server/src/service/orchestrator.ts +++ b/apps/server/src/service/orchestrator.ts @@ -12,11 +12,19 @@ import { runNixpacksBuild } from "../build/nixpacks.js"; import { runInstallationContainer, stopInstallationContainer, + stopContainer, + startContainer, + restartContainer, waitForContainerHealth, getImageId, 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(); export interface DraftResult { installation: Installation; @@ -64,11 +72,28 @@ export function configureInstallation( return updateInstallation(id, patch); } +interface BuildOutcome { + installation: Installation; + ok: boolean; +} + export async function buildInstallation(id: string): Promise { + return (await enqueueBuild(() => runBuild(id))).installation; +} + +async function runBuild(id: string): Promise { 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 @@ -76,7 +101,7 @@ export async function buildInstallation(id: string): Promise { 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`; @@ -90,10 +115,7 @@ export async function buildInstallation(id: string): Promise { ); 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 @@ -105,7 +127,10 @@ export async function buildInstallation(id: string): Promise { } } - 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 { @@ -127,11 +152,60 @@ export async function deployInstallation(id: string): Promise { export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise { if (opts.rebuild) { - await buildInstallation(id); + // 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); } +// Start/restart act on the existing container, so they never apply changed env/config (that +// needs a deploy, which recreates it). If the container is gone (e.g. pruned after a host +// reboot) they fall back to a deploy from the built image. +async function resumeInstallation( + id: string, + act: (containerName: string) => Promise, +): Promise { + const installation = getInstallationById(id); + if (!installation) throw new Error("installation not found"); + + updateInstallation(id, { status: "starting", statusDetail: null }); + + try { + if (!(await act(installation.containerName))) { + if (!installation.imageTag) { + throw new Error("container does not exist and the installation has no built image — build it first"); + } + return await deployInstallation(id); + } + await waitForContainerHealth(installation); + + const bearerToken = installation.bearerToken ?? generateBearerToken(); + return updateInstallation(id, { status: "running", statusDetail: null, bearerToken }); + } catch (err) { + return updateInstallation(id, { status: "error", statusDetail: (err as Error).message }); + } +} + +export const startInstallation = (id: string) => resumeInstallation(id, startContainer); + +export const restartInstallation = (id: string) => resumeInstallation(id, restartContainer); + +/** Stops the container without removing it; it stays stopped (restart policy `unless-stopped`) until started again. */ +export async function stopInstallation(id: string): Promise { + const installation = getInstallationById(id); + if (!installation) throw new Error("installation not found"); + + try { + // A missing container is already stopped as far as the operator is concerned. + await stopContainer(installation.containerName); + return updateInstallation(id, { status: "stopped", statusDetail: null }); + } catch (err) { + return updateInstallation(id, { status: "error", statusDetail: (err as Error).message }); + } +} + export async function removeInstallationContainer(id: string): Promise { const installation = getInstallationById(id); if (!installation) return; diff --git a/apps/server/src/session/sqliteStore.test.ts b/apps/server/src/session/sqliteStore.test.ts new file mode 100644 index 0000000..929dbeb --- /dev/null +++ b/apps/server/src/session/sqliteStore.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import Database from "better-sqlite3"; +import type { SessionData } from "express-session"; +import { SqliteSessionStore } from "./sqliteStore.js"; + +function makeStore() { + return new SqliteSessionStore(new Database(":memory:"), 60_000); +} + +function sessionExpiringIn(ms: number): SessionData { + return { cookie: { expires: new Date(Date.now() + ms), originalMaxAge: ms }, authenticated: true } as SessionData; +} + +const get = (store: SqliteSessionStore, sid: string) => + new Promise((resolve, reject) => + store.get(sid, (err, sess) => (err ? reject(err) : resolve(sess))), + ); + +describe("SqliteSessionStore", () => { + it("round-trips a session and destroys it", async () => { + const store = makeStore(); + store.set("a", sessionExpiringIn(60_000)); + expect((await get(store, "a"))?.authenticated).toBe(true); + + await new Promise((resolve) => store.destroy("a", () => resolve())); + expect(await get(store, "a")).toBeNull(); + }); + + it("treats an expired session as missing", async () => { + const store = makeStore(); + store.set("old", sessionExpiringIn(-1_000)); + expect(await get(store, "old")).toBeNull(); + }); + + it("purges expired sessions that are never read again", () => { + const db = new Database(":memory:"); + const store = new SqliteSessionStore(db, 60_000); + store.set("old", sessionExpiringIn(-1_000)); + store.set("live", sessionExpiringIn(60_000)); + store.purgeExpired(); + expect(db.prepare("SELECT sid FROM sessions").all()).toEqual([{ sid: "live" }]); + }); +}); diff --git a/apps/server/src/session/sqliteStore.ts b/apps/server/src/session/sqliteStore.ts new file mode 100644 index 0000000..98aa676 --- /dev/null +++ b/apps/server/src/session/sqliteStore.ts @@ -0,0 +1,78 @@ +import session from "express-session"; +import type { Database } from "better-sqlite3"; + +const DEFAULT_TTL_MS = 12 * 60 * 60 * 1000; + +/** + * Session store backed by the manager's own SQLite DB. Replaces express-session's MemoryStore, + * which never evicts sessions that aren't read again (it warns it "will leak memory" in + * production) and loses every login on restart. + */ +export class SqliteSessionStore extends session.Store { + constructor(private readonly db: Database, purgeIntervalMs = 10 * 60 * 1000) { + super(); + db.exec( + "CREATE TABLE IF NOT EXISTS sessions (sid TEXT PRIMARY KEY, sess TEXT NOT NULL, expires INTEGER NOT NULL)", + ); + db.exec("CREATE INDEX IF NOT EXISTS sessions_expires ON sessions (expires)"); + const timer = setInterval(() => this.purgeExpired(), purgeIntervalMs); + timer.unref(); + } + + purgeExpired(): void { + this.db.prepare("DELETE FROM sessions WHERE expires <= ?").run(Date.now()); + } + + private expiryOf(sess: session.SessionData): number { + const expires = sess.cookie?.expires; + return expires ? new Date(expires).getTime() : Date.now() + DEFAULT_TTL_MS; + } + + get(sid: string, cb: (err?: unknown, sess?: session.SessionData | null) => void): void { + try { + const row = this.db.prepare("SELECT sess, expires FROM sessions WHERE sid = ?").get(sid) as + | { sess: string; expires: number } + | undefined; + if (!row || row.expires <= Date.now()) { + if (row) this.db.prepare("DELETE FROM sessions WHERE sid = ?").run(sid); + cb(null, null); + return; + } + cb(null, JSON.parse(row.sess) as session.SessionData); + } catch (err) { + cb(err); + } + } + + set(sid: string, sess: session.SessionData, cb?: (err?: unknown) => void): void { + try { + this.db + .prepare( + "INSERT INTO sessions (sid, sess, expires) VALUES (?, ?, ?) " + + "ON CONFLICT(sid) DO UPDATE SET sess = excluded.sess, expires = excluded.expires", + ) + .run(sid, JSON.stringify(sess), this.expiryOf(sess)); + cb?.(); + } catch (err) { + cb?.(err); + } + } + + touch(sid: string, sess: session.SessionData, cb?: () => void): void { + try { + this.db.prepare("UPDATE sessions SET expires = ? WHERE sid = ?").run(this.expiryOf(sess), sid); + } catch { + // best effort: a failed touch only means the session expires on its original schedule + } + cb?.(); + } + + destroy(sid: string, cb?: (err?: unknown) => void): void { + try { + this.db.prepare("DELETE FROM sessions WHERE sid = ?").run(sid); + cb?.(); + } catch (err) { + cb?.(err); + } + } +} diff --git a/apps/server/src/util/processTimeout.test.ts b/apps/server/src/util/processTimeout.test.ts new file mode 100644 index 0000000..52d31d7 --- /dev/null +++ b/apps/server/src/util/processTimeout.test.ts @@ -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); + }); +}); diff --git a/apps/server/src/util/processTimeout.ts b/apps/server/src/util/processTimeout.ts new file mode 100644 index 0000000..f129d4c --- /dev/null +++ b/apps/server/src/util/processTimeout.ts @@ -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)); +} diff --git a/apps/server/src/util/serialQueue.ts b/apps/server/src/util/serialQueue.ts new file mode 100644 index 0000000..087c7cb --- /dev/null +++ b/apps/server/src/util/serialQueue.ts @@ -0,0 +1,9 @@ +/** Runs async tasks strictly one after another, whether the previous one succeeded or failed. */ +export function createSerialQueue() { + let tail: Promise = Promise.resolve(); + return function enqueue(task: () => Promise): Promise { + const run = tail.then(task, task); + tail = run.catch(() => {}); + return run; + }; +} diff --git a/apps/server/src/util/withTimeout.test.ts b/apps/server/src/util/withTimeout.test.ts new file mode 100644 index 0000000..f3f7107 --- /dev/null +++ b/apps/server/src/util/withTimeout.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { withTimeout } from "./withTimeout.js"; +import { createSerialQueue } from "./serialQueue.js"; + +describe("withTimeout", () => { + it("resolves with the value when the promise settles in time", async () => { + await expect(withTimeout(Promise.resolve(42), 100, "x")).resolves.toBe(42); + }); + + it("rejects when the promise never settles", async () => { + await expect(withTimeout(new Promise(() => {}), 10, "docker inspect")).rejects.toThrow( + "docker inspect timed out after 10ms", + ); + }); +}); + +describe("createSerialQueue", () => { + it("never runs two tasks at once and keeps going after a failure", async () => { + const enqueue = createSerialQueue(); + let running = 0; + let maxRunning = 0; + const task = (fail = false) => async () => { + running += 1; + maxRunning = Math.max(maxRunning, running); + await new Promise((r) => setTimeout(r, 5)); + running -= 1; + if (fail) throw new Error("boom"); + return "ok"; + }; + + const results = await Promise.allSettled([enqueue(task()), enqueue(task(true)), enqueue(task())]); + + expect(maxRunning).toBe(1); + expect(results.map((r) => r.status)).toEqual(["fulfilled", "rejected", "fulfilled"]); + }); +}); diff --git a/apps/server/src/util/withTimeout.ts b/apps/server/src/util/withTimeout.ts new file mode 100644 index 0000000..7692c1a --- /dev/null +++ b/apps/server/src/util/withTimeout.ts @@ -0,0 +1,16 @@ +/** Rejects if `promise` hasn't settled within `ms` — for calls that can hang forever (e.g. a wedged Docker daemon). */ +export function withTimeout(promise: Promise, ms: number, what: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms}ms`)), ms); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (err) => { + clearTimeout(timer); + reject(err); + }, + ); + }); +} diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index 9cceb2b..afca352 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -53,6 +53,9 @@ export const api = { deploy: (id: string) => request(`/api/installations/${id}/deploy`, { method: "POST" }), redeploy: (id: string, rebuild: boolean) => request(`/api/installations/${id}/redeploy`, { method: "POST", body: JSON.stringify({ rebuild }) }), + start: (id: string) => request(`/api/installations/${id}/start`, { method: "POST" }), + stop: (id: string) => request(`/api/installations/${id}/stop`, { method: "POST" }), + restart: (id: string) => request(`/api/installations/${id}/restart`, { method: "POST" }), regenerateToken: (id: string) => request<{ bearerToken: string }>(`/api/installations/${id}/regenerate-token`, { method: "POST" }), remove: (id: string) => request(`/api/installations/${id}`, { method: "DELETE" }), diff --git a/apps/web/src/pages/InstallationDetail.tsx b/apps/web/src/pages/InstallationDetail.tsx index 2b2688e..d2c129e 100644 --- a/apps/web/src/pages/InstallationDetail.tsx +++ b/apps/web/src/pages/InstallationDetail.tsx @@ -91,6 +91,11 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void }) } const deployLocked = DEPLOY_LOCKED_STATUSES.has(installation.status); + const isRunning = installation.status === "running"; + // Start also covers "built"/"error" with an image: with no container yet it falls back to a deploy. + const canStart = + installation.status === "stopped" || + ((installation.status === "built" || installation.status === "error") && installation.imageTag !== null); return ( @@ -232,6 +237,54 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void }) + + + +

+ Start, Stop and Restart act on the existing container: fast, and the image and its configuration stay as they are. +

+
+
+

+ Build makes a new image from the repository. Deploy runs that image in a fresh container (Redeploy does the same + again). Rebuild & redeploy does both, to pick up new commits. +

diff --git a/docker-compose.yml b/docker-compose.yml index a798e34..33b9860 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -15,6 +15,9 @@ services: MASTER_KEY: ${MASTER_KEY} CONTAINER_MEMORY_MB: ${CONTAINER_MEMORY_MB:-512} CONTAINER_CPUS: ${CONTAINER_CPUS:-1} + PROXY_TIMEOUT_MS: ${PROXY_TIMEOUT_MS:-300000} + MAX_PROXY_REQUESTS: ${MAX_PROXY_REQUESTS:-100} + MANAGER_MEMORY_LIMIT_MB: ${MANAGER_MEMORY_LIMIT_MB:-512} volumes: - /var/run/docker.sock:/var/run/docker.sock - ./data:/repo/data diff --git a/docs/architecture.md b/docs/architecture.md index 36a29a3..dfaf92f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -24,6 +24,29 @@ (`apps/server/src/proxy/mcpProxy.ts`, constant-time comparison) and proxied to the container's IP on the shared network. +## Start / Stop / Restart vs Deploy + +Two families of actions, both in `apps/server/src/service/orchestrator.ts`: + +- **Build / Deploy** change what runs. Build re-clones the repo and produces a new image + (the running container is untouched). Deploy removes any existing container and creates a + new one from the built image, so it is the only way to apply changed env/config. + "Redeploy (env only)" is Deploy again with the current image; "Rebuild & redeploy" is Build + then Deploy (and stops before deploying if the build fails). +- **Start / Stop / Restart** only change whether the *existing* container runs + (`docker stop|start|restart`; nothing is removed or recreated, so they are fast and never + apply new env/config). Stop sets status `stopped`; the container's `unless-stopped` restart + policy keeps it stopped until started. Start and Restart set `starting`, wait for the + container to listen (same health check as Deploy), then `running` (or `error` with the + reason). If the container no longer exists they fall back to Deploy when the installation + has a built image, and report an error otherwise. + +A build never touches the running container, so an installation that is `running` stays +`running` (and served) during and after a build, even a failed one; the failure shows in the +status detail. The proxy only serves installations in status `running`, so a stopped or restarting +installation answers 404 until it is healthy again. The per-container IP cache is dropped on +every start/stop/restart because the IP can change. + ## Why the manager itself must run as a container Rootless Podman isolates the host network namespace from the container bridge, so the diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..545d258 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,31 @@ +# Operations + +## Memory and resource safeguards + +The manager runs on the same (often small) host as every MCP container, so a runaway manager +degrades all of them. After an incident where the manager's Node process grew to ~1.1 GiB +(RAM + swap), held ~70 stuck connections to port 3000 and pushed the host into swap, these +limits exist: + +| Safeguard | Where | Behaviour | +|---|---|---| +| Proxy inactivity timeout | `PROXY_TIMEOUT_MS` (default 300000) | A stalled upstream or vanished client is cut after this much silence, freeing its sockets and buffers. | +| Concurrent proxy cap | `MAX_PROXY_REQUESTS` (default 100) | Beyond it `/mcp/` answers `503` + `Retry-After` instead of queueing without bound. | +| Docker call timeout + IP cache | `docker/containers.ts` | `docker inspect` times out after 10 s and the container IP is cached for 5 s, so a wedged Docker daemon cannot stall every request at once. | +| Session store | `session/sqliteStore.ts` | Sessions live in the SQLite DB and expired ones are purged every 10 min. Replaces `MemoryStore`, which never evicts and warned it leaks in production. | +| Memory guard | `MANAGER_MEMORY_LIMIT_MB` (default 512, 0 = off) | Checked every 30 s on heap + external memory (not RSS, which hides swapped pages). When exceeded the process exits and `restart: unless-stopped` starts a fresh one. | +| V8 heap ceiling | `NODE_OPTIONS=--max-old-space-size=768` in the `Dockerfile` | Hard backstop above the soft limit. | +| Serialized builds | `service/orchestrator.ts` | One Nixpacks/Docker build at a time; git is killed after 5 min and a build after 30 min (the whole process group, so a hung `docker build` can't keep the queue blocked). | +| Restart reconciliation | `reconcileInterruptedInstallations` | On boot, `cloning`/`building`/`starting` installations are marked `error` (Start or Redeploy recovers them), since the process that was advancing them is gone. | + +A container-level cgroup limit on the manager (`mem_limit` in compose) would be the strongest +guard, but it fails outright on hosts that do not delegate cgroup controllers (see +`LESSONS.md`), so the limits above are enforced inside the process instead. Add `mem_limit` +yourself on hosts that support it. + +## Checking on it + +`GET /health` (unauthenticated) returns `ok`, `uptimeSec`, `rssMb`, `heapUsedMb` and +`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.