Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Restart published apps that crash instead of serving 502s (#2220)

Regan Bell94c2d1cf3014
diff --git a/src/deploy/aws-deploy-provider.ts b/src/deploy/aws-deploy-provider.ts
index 887163cc1..0b181ac71 100644
--- a/src/deploy/aws-deploy-provider.ts
+++ b/src/deploy/aws-deploy-provider.ts
@@ -10,6 +10,7 @@ import { createNoopAdvisoryLock, type AdvisoryLock } from "../persistence/adviso
import { createKeyedQueue, sleep } from "../util/async.ts";
import { shq } from "../util/shell.ts";
import { swallow } from "../util/errors.ts";
+import { appGone, listeningOn, supervised, waitAppReady } from "./shared-deploy-provider.ts";
const AGENT_PORT_DEFAULT = 8080;
const APP_PORT_DEFAULT = 8081;
@@ -31,14 +32,9 @@ const READY_PATH = `${APP_DIR}/.qm-ready`;
const PID_PATH = "/tmp/qm-app.pid";
const LOG_PATH = "/tmp/qm-app.log";
const APP_READY_WINDOW_SEC = 60;
-const APP_READY_EXEC_TIMEOUT_SEC = 90;
const APP_PORT_RELEASE_TICKS = 40;
const APP_START_EXEC_TIMEOUT_SEC = 60;
const EXIT_APP_PORT_HELD = 97;
-const EXIT_APP_EXITED = 98;
-
-const LISTENING_ON_APP_PORT = (port: number): string =>
- `listening() { curl -s -o /dev/null --max-time 1 http://127.0.0.1:${port}/; [ "$?" != "7" ]; }`;
const LIVE_REPLICATOR_PIDS = `ls_pids() { for p in /proc/[0-9]*; do c=$(tr '\\0' ' ' < "$p/cmdline" 2>/dev/null); case "\${c%% *}" in litestream|*/litestream) case "$c" in *${LITESTREAM_CONFIG}*) echo "\${p#/proc/}";; esac;; esac; done; }`;
const ENDPOINT_PORT = 443;
@@ -435,7 +431,7 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
.join("; ");
const inner = `cd ${shq(APP_DIR)}; ${version.entrypoint}`;
const script = [
- LISTENING_ON_APP_PORT(appPort),
+ listeningOn(appPort),
`old=$(cat ${shq(PID_PATH)} 2>/dev/null || true)`,
`if [ -n "$old" ]; then kill -TERM "-$old" 2>/dev/null || true; sleep 0.5; kill -KILL "-$old" 2>/dev/null || true; fi`,
`rm -f ${shq(PID_PATH)}`,
@@ -446,7 +442,7 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
`export PORT=${appPort}`,
...(s3 ? [`export DATA_DIR=${shq(DATA_DIR)}`] : []),
...(envExports ? [envExports] : []),
- `setsid sh -c ${shq(inner)} > ${shq(LOG_PATH)} 2>&1 & echo $! > ${shq(PID_PATH)}`,
+ `setsid sh -c ${shq(supervised(inner, appPort, PID_PATH))} > ${shq(LOG_PATH)} 2>&1 & echo $! > ${shq(PID_PATH)}`,
].join("; ");
const r = await execRaw(id, endpoint, script, APP_START_EXEC_TIMEOUT_SEC);
if (r.code === EXIT_APP_PORT_HELD) {
@@ -455,27 +451,12 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
);
}
if (r.code !== 0) throw new Error(`aws deploy app start failed: ${r.stderr.slice(0, 300)}`);
- await waitAppReady(id, endpoint);
- }
-
- async function waitAppReady(id: string, endpoint: string): Promise<void> {
- const probe =
- `pid=$(cat ${shq(PID_PATH)} 2>/dev/null || true); died=0; ` +
- `end=$(( $(date +%s) + ${APP_READY_WINDOW_SEC} )); ` +
- `while [ "$(date +%s)" -lt "$end" ]; do ` +
- `curl -s --max-time 2 -o /dev/null http://127.0.0.1:${appPort}/ && exit 0; ` +
- `kill -0 -"$pid" 2>/dev/null || died=1; ` +
- `sleep 0.5; done; [ "$died" = 1 ] && exit ${EXIT_APP_EXITED}; exit 1`;
- const r = await execRaw(id, endpoint, probe, APP_READY_EXEC_TIMEOUT_SEC);
- if (r.code === 0) return;
- const log = await execRaw(id, endpoint, `tail -c 2000 ${shq(LOG_PATH)} 2>/dev/null || true`, 30)
- .then((out) => `${out.stdout}${out.stderr}`.trim())
- .catch(() => "");
- const why =
- r.code === EXIT_APP_EXITED
- ? `the version's entrypoint exited without binding port ${appPort}`
- : `app never listened on port ${appPort} within ${APP_READY_WINDOW_SEC}s`;
- throw new Error(why + (log ? `; last output from the entrypoint:\n${log}` : "; the entrypoint produced no output"));
+ await waitAppReady((script, timeoutSec) => execRaw(id, endpoint, script, timeoutSec), {
+ appPort,
+ windowSec: APP_READY_WINDOW_SEC,
+ pidPath: PID_PATH,
+ logPath: LOG_PATH,
+ });
}
async function materialize(
@@ -564,6 +545,9 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
)
return null;
await ensureRunning(stored.microvmId, stored.endpoint);
+ const exec = (script: string, timeoutSec: number) =>
+ execRaw(stored.microvmId, stored.endpoint, script, timeoutSec);
+ if (await appGone(exec, { appPort, pidPath: PID_PATH })) return null;
} catch (e) {
if (!(e instanceof AwsApiError && (e.status >= 500 || e.status === 429))) throw e;
}
diff --git a/src/deploy/docker-deploy-provider.ts b/src/deploy/docker-deploy-provider.ts
index 21239bec0..0db1576d3 100644
--- a/src/deploy/docker-deploy-provider.ts
+++ b/src/deploy/docker-deploy-provider.ts
@@ -111,6 +111,8 @@ export function createDockerDeployProvider(opts: DockerDeployProviderOptions = {
const r = await dexec([
"run",
"-d",
+ "--restart",
+ "unless-stopped",
"--name",
name(d),
"--network",
diff --git a/src/deploy/porter-deploy-provider.ts b/src/deploy/porter-deploy-provider.ts
index be0ade7fd..e86b26a88 100644
--- a/src/deploy/porter-deploy-provider.ts
+++ b/src/deploy/porter-deploy-provider.ts
@@ -3,7 +3,7 @@ import { LRUCache } from "lru-cache";
import { NotFoundError } from "porter-sandbox";
import type { Deployment, DeploymentVersion } from "./deploy-store.ts";
import type { DeployEndpoint, DeployProvider } from "./deploy-provider.ts";
-import { waitAppReady } from "./shared-deploy-provider.ts";
+import { appGone, supervised, waitAppReady } from "./shared-deploy-provider.ts";
import { normalizeRelPath, posixJoin, readTree } from "./deploy-fs.ts";
import { makeTar } from "../sandbox/tar.ts";
import {
@@ -147,7 +147,7 @@ export function createPorterDeployProvider(opts: PorterDeployProviderOptions): D
async function startApp(sandboxId: string, version: DeploymentVersion): Promise<void> {
const inner = `cd ${shq(APP_DIR)}; ${version.entrypoint}`;
- const launch = `sh -c ${shq(inner)} < /dev/null > ${shq(LOG_PATH)} 2>&1 & echo $! > ${shq(PID_PATH)}`;
+ const launch = `sh -c ${shq(supervised(inner, appPort, PID_PATH))} < /dev/null > ${shq(LOG_PATH)} 2>&1 & echo $! > ${shq(PID_PATH)}`;
const script = [
`mkdir -p ${shq(APP_DIR)} ${shq(DATA_DIR)}`,
`export HOME=${shq(HOME_DIR)} PORT=${appPort} DATA_DIR=${shq(DATA_DIR)}`,
@@ -251,6 +251,8 @@ export function createPorterDeployProvider(opts: PorterDeployProviderOptions): D
resolveCache.delete(d.id);
return null;
}
+ const exec = (script: string, timeoutSec: number) => execRaw(stored.sandboxId, script, timeoutSec);
+ if (await appGone(exec, { appPort, pidPath: PID_PATH })) return null;
const endpoint = endpointOf(stored);
if (resolveCacheMs > 0) resolveCache.set(d.id, endpoint);
return endpoint;
diff --git a/src/deploy/shared-deploy-provider.ts b/src/deploy/shared-deploy-provider.ts
index 12fd8681f..50c6a0756 100644
--- a/src/deploy/shared-deploy-provider.ts
+++ b/src/deploy/shared-deploy-provider.ts
@@ -1,8 +1,13 @@
import type { ExecResult } from "../sandbox/sandbox.ts";
import { shq } from "../util/shell.ts";
+import { swallow } from "../util/errors.ts";
const EXIT_APP_EXITED = 98;
+const EXIT_APP_GONE = 99;
const READY_EXEC_GRACE_SEC = 30;
+const APP_PROBE_TIMEOUT_SEC = 5;
+
+type Exec = (script: string, timeoutSec: number) => Promise<Pick<ExecResult, "stdout" | "stderr" | "code">>;
export interface AppReadyOptions {
appPort: number;
@@ -11,16 +16,41 @@ export interface AppReadyOptions {
logPath: string;
}
-export async function waitAppReady(
- exec: (script: string, timeoutSec: number) => Promise<ExecResult>,
- opts: AppReadyOptions,
-): Promise<void> {
+export const listeningOn = (port: number): string =>
+ `listening() { curl -s -o /dev/null --max-time 1 http://127.0.0.1:${port}/; [ "$?" != "7" ]; }`;
+
+const exitedPath = (pidPath: string): string => shq(`${pidPath}.exited`);
+
+export function supervised(inner: string, appPort: number, pidPath: string): string {
+ return [
+ listeningOn(appPort),
+ `rm -f ${exitedPath(pidPath)}`,
+ "n=1",
+ `while :; do s=$(date +%s); sh -c ${shq(inner)}; rc=$?; echo "$rc" >> ${exitedPath(pidPath)}`,
+ 'echo "qm: entrypoint exited with status $rc, restarting"',
+ "while listening; do sleep 5; done",
+ `[ $(( $(date +%s) - s )) -lt 60 ] || n=1; sleep "$n"; [ "$n" -ge 30 ] || n=$((n * 2)); done`,
+ ].join("; ");
+}
+
+export async function appGone(exec: Exec, opts: { appPort: number; pidPath: string }): Promise<boolean> {
+ const probe =
+ `${listeningOn(opts.appPort)}; listening && exit 0; pid=$(cat ${shq(opts.pidPath)} 2>/dev/null || true); ` +
+ `[ -n "$pid" ] && { kill -0 -"$pid" 2>/dev/null || kill -0 "$pid" 2>/dev/null; } && exit 0; exit ${EXIT_APP_GONE}`;
+ const r = await exec(probe, APP_PROBE_TIMEOUT_SEC).catch((e) => {
+ swallow("deploy: app liveness probe", e);
+ return null;
+ });
+ return r?.code === EXIT_APP_GONE;
+}
+
+export async function waitAppReady(exec: Exec, opts: AppReadyOptions): Promise<void> {
const probe =
`pid=$(cat ${shq(opts.pidPath)} 2>/dev/null || true); died=0; ` +
`end=$(( $(date +%s) + ${opts.windowSec} )); ` +
`while [ "$(date +%s)" -lt "$end" ]; do ` +
`curl -s --max-time 2 -o /dev/null http://127.0.0.1:${opts.appPort}/ && exit 0; ` +
- `kill -0 -"$pid" 2>/dev/null || kill -0 "$pid" 2>/dev/null || died=1; ` +
+ `{ kill -0 -"$pid" 2>/dev/null || kill -0 "$pid" 2>/dev/null; } && [ ! -f ${exitedPath(opts.pidPath)} ] || died=1; ` +
`sleep 0.5; done; [ "$died" = 1 ] && exit ${EXIT_APP_EXITED}; exit 1`;
const r = await exec(probe, opts.windowSec + READY_EXEC_GRACE_SEC);
if (r.code === 0) return;
diff --git a/test/aws-deploy-provider.test.ts b/test/aws-deploy-provider.test.ts
index 086bc23ed..3dcdca902 100644
--- a/test/aws-deploy-provider.test.ts
+++ b/test/aws-deploy-provider.test.ts
@@ -458,6 +458,20 @@ test("resolveEndpoint: destroy invalidates a hot resolve cache", async () => {
assert.equal(resolved, null, "a destroyed deployment must not serve a cached endpoint");
});
+test("resolveEndpoint: an app whose process and supervisor are both gone returns null, and the re-apply reuses the body", async () => {
+ const { api, counts } = fakeApi();
+ const appGoneProbe = (cmd: string): boolean => cmd.includes("listening && exit 0") && cmd.includes("qm-app.pid");
+ const { fetchImpl, execs } = fakeDaemon({ execCode: (cmd) => (appGoneProbe(cmd) ? 99 : 0) });
+ const p = provider(api, fetchImpl);
+ const d = deployment(ID);
+ await p.apply(d, version(localSnapshot("a", "1")));
+
+ assert.equal(await p.resolveEndpoint!(d, version("/unused")), null, "a dead app is not served as a live endpoint");
+ await p.apply(d, version(localSnapshot("a", "1")));
+ assert.equal(counts.run, 1, "the running body is reused, only the app is restarted");
+ assert.equal(execs.filter(appStartScript).length, 2, "the app was started again");
+});
+
test("resolveEndpoint (gone): a terminated body returns null (signal to re-apply) and clears the pointer", async () => {
const { api, vms } = fakeApi();
const { fetchImpl } = fakeDaemon();
diff --git a/test/porter-deploy-provider.test.ts b/test/porter-deploy-provider.test.ts
index c17c45239..75970b538 100644
--- a/test/porter-deploy-provider.test.ts
+++ b/test/porter-deploy-provider.test.ts
@@ -237,6 +237,34 @@ test("resolveEndpoint reports the live body and forgets a dead one", async () =>
assert.equal(await store.get("dep-5"), null);
});
+test("an app that crashes after publishing is restarted in place, and keeps resolving while it comes back", async () => {
+ const d = deployment("dep-5d", "crashy");
+ const crashy = SERVER.replace(
+ "if (q.url === '/data')",
+ "if (q.url === '/crash') process.exit(1); if (q.url === '/data')",
+ );
+ const v = version({ "server.js": crashy }, "node server.js");
+ const applied = await provider.apply(d, v);
+ await fetch(`http://127.0.0.1:${appPort}/crash`).catch(() => {});
+ assert.deepEqual(await provider.resolveEndpoint!({ ...d, endpoint: applied }, v), applied);
+ let body = "";
+ for (const end = Date.now() + 10_000; !body && Date.now() < end; await new Promise((r) => setTimeout(r, 200)))
+ body = await fetchText("/").catch(() => "");
+ assert.match(body, /^hello from/);
+ assert.match((await provider.logs!(d, { tailLines: 50 })) ?? "", /entrypoint exited with status 1/);
+});
+
+test("resolveEndpoint returns null when the app and its supervisor are both gone, so the service re-applies", async () => {
+ const d = deployment("dep-5e", "gone");
+ const v = version({ "server.js": SERVER }, "node server.js");
+ const applied = await provider.apply(d, v);
+ const { sandboxId } = (await store.get("dep-5e"))!;
+ await fake.client.sandboxes.raw.exec(sandboxId, { command: ["sh", "-c", 'kill -KILL -"$(cat /tmp/qm-app.pid)"'] });
+ for (const end = Date.now() + 5_000; Date.now() < end; await new Promise((r) => setTimeout(r, 100)))
+ if (!(await fetchText("/").catch(() => ""))) break;
+ assert.equal(await provider.resolveEndpoint!({ ...d, endpoint: applied }, v), null);
+});
+
test("resolveEndpoint caches the live answer instead of asking Porter on every request", async () => {
make({ resolveCacheMs: 60_000 });
const d = deployment("dep-5b", "cached");
diff --git a/test/support/fake-porter.ts b/test/support/fake-porter.ts
index 218af864e..7df4446b6 100644
--- a/test/support/fake-porter.ts
+++ b/test/support/fake-porter.ts
@@ -95,7 +95,10 @@ export function installFakePorter(opts: FakePorterOptions = {}): FakePorter {
if (!existsSync(pidFile)) return;
const pid = readFileSync(pidFile, "utf8").trim();
if (!/^\d+$/.test(pid)) return;
- spawnSync("sh", ["-c", `pkill -TERM -P ${pid} 2>/dev/null; kill -TERM ${pid} 2>/dev/null; true`]);
+ spawnSync("sh", [
+ "-c",
+ `kill -TERM -${pid} 2>/dev/null; pkill -TERM -P ${pid} 2>/dev/null; kill -TERM ${pid} 2>/dev/null; true`,
+ ]);
};
const retire = (b: BodyRecord): void => {