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/docker/containers.ts b/apps/server/src/docker/containers.ts index 4683de6..565285f 100644 --- a/apps/server/src/docker/containers.ts +++ b/apps/server/src/docker/containers.ts @@ -3,6 +3,7 @@ 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 }); @@ -18,6 +19,8 @@ export async function ensureNetwork(name: string): Promise { // 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 { @@ -99,6 +102,39 @@ export async function stopInstallationContainer(containerName: string): Promise< await removeContainerIfExists(containerName); } +// 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(), 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/service/orchestrator.ts b/apps/server/src/service/orchestrator.ts index 2cee38e..f5bd0f8 100644 --- a/apps/server/src/service/orchestrator.ts +++ b/apps/server/src/service/orchestrator.ts @@ -12,6 +12,9 @@ import { runNixpacksBuild } from "../build/nixpacks.js"; import { runInstallationContainer, stopInstallationContainer, + stopContainer, + startContainer, + restartContainer, waitForContainerHealth, getImageId, removeImageIfUnused, @@ -144,6 +147,52 @@ export async function redeployInstallation(id: string, opts: { rebuild?: boolean 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/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/docs/architecture.md b/docs/architecture.md index 36a29a3..a80d221 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -24,6 +24,27 @@ (`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. + +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