feat(cli): add stop command to shut down running daemon

This commit is contained in:
yuez committed 2026-10-27 18:37:21 +08:00
1 parent 2b8171cc37
commit 48411dccd2
8 files changed
+498 -19

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ Then:
```bash ```bash
pi2 daemon # foreground; the plugin/browser needs this running pi2 daemon # foreground; the plugin/browser needs this running
pi2 stop # stop a running daemon (or: pi2 daemon stop)
pi2 install-service --write # or run it at login: systemd --user / launchd pi2 install-service --write # or run it at login: systemd --user / launchd
pi2 status # daemon + instances + health pi2 status # daemon + instances + health
pi2 doctor # node/nvim/pi/curl/plugin/runtime/web-dist/protocol checks pi2 doctor # node/nvim/pi/curl/plugin/runtime/web-dist/protocol checks
+15
View File
@@ -275,6 +275,21 @@ The daemon is dispatched *inside* `pi2` (`src/cli/pi2.ts` → `src/cli/daemon.ts
it is not a separate executable, nothing is re-exec'd, and there is no detaching it is not a separate executable, nothing is re-exec'd, and there is no detaching
mode. Flags, stdout contract and startup order: [§3](#3-running-the-daemon). mode. Flags, stdout contract and startup order: [§3](#3-running-the-daemon).
### 8.0b `pi2 stop` / `pi2 daemon stop`
```bash
pi2 stop # stop a running daemon (SIGTERM, waits up to 5s)
pi2 daemon stop # alias for `pi2 stop`
pi2 stop --force # escalate to SIGKILL if SIGTERM times out
pi2 stop -t 10 # wait up to 10 seconds before failing / escalating
```
Locates the running daemon via `<runtime>/daemon.json` (or `daemon.lock`), verifies
that the PID belongs to this boot, sends `SIGTERM`, and waits for the process to exit.
If the daemon was already dead (stale lock/json), it cleans up the stale files and reports
that no daemon is running. With `--force`, it escalates to `SIGKILL` if the daemon does not
exit within the timeout.
### 8.1 `pi2 attach [path]` ### 8.1 `pi2 attach [path]`
```bash ```bash
+4 -8
View File
@@ -174,20 +174,16 @@ pass "GET /api/v1/workspaces without a token -> 401"
expect_status 401 GET /api/v1/workspaces -H "authorization: Bearer deadbeef" expect_status 401 GET /api/v1/workspaces -H "authorization: Bearer deadbeef"
pass "GET /api/v1/workspaces with a bogus token -> 401" pass "GET /api/v1/workspaces with a bogus token -> 401"
printf '==> stopping pi2 daemon (SIGTERM)\n' printf '==> stopping pi2 daemon (pi2 stop)\n'
kill -TERM "$DAEMON_PID" PI2_RUNTIME_DIR="$TMP/run" node "$ROOT/dist/cli/pi2.js" stop
for _ in $(seq 1 100); do pass "pi2 stop executed cleanly"
kill -0 "$DAEMON_PID" 2>/dev/null || break
sleep 0.05
done
kill -0 "$DAEMON_PID" 2>/dev/null && fail "pi2 daemon did not exit within 5s of SIGTERM"
set +e set +e
wait "$DAEMON_PID" wait "$DAEMON_PID"
EXIT_CODE=$? EXIT_CODE=$?
set -e set -e
[[ "$EXIT_CODE" -eq 0 ]] || fail "pi2 daemon exited with code $EXIT_CODE" [[ "$EXIT_CODE" -eq 0 ]] || fail "pi2 daemon exited with code $EXIT_CODE"
pass "SIGTERM -> clean exit (code 0)" pass "daemon process -> clean exit (code 0)"
[[ ! -f "$LOCK" ]] || fail "daemon.lock was not removed on shutdown" [[ ! -f "$LOCK" ]] || fail "daemon.lock was not removed on shutdown"
pass "daemon.lock removed" pass "daemon.lock removed"
+57 -11
View File
@@ -26,6 +26,7 @@ import { readDaemonJson, type DaemonLock } from "./lock.js";
import { cliTokenPath, readCliToken } from "./token.js"; import { cliTokenPath, readCliToken } from "./token.js";
import { import {
boolFlag, boolFlag,
CliError,
errorMessage, errorMessage,
formatBytes, formatBytes,
formatTable, formatTable,
@@ -44,11 +45,17 @@ import {
type ServicePlatform, type ServicePlatform,
} from "./service.js"; } from "./service.js";
import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js"; import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js";
import { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
export { CliError } from "./util.js";
export { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
export const USAGE = `pi2 — pi2 client export const USAGE = `pi2 — pi2 client
Usage: Usage:
pi2 daemon [start] [options] run the web-console daemon (foreground) pi2 daemon [start] [options] run the web-console daemon (foreground)
pi2 daemon stop [options] stop the running daemon
pi2 stop [options] stop the running daemon (alias for daemon stop)
pi2 attach [path] attach nvim to the workspace instance, else open nvim pi2 attach [path] attach nvim to the workspace instance, else open nvim
pi2 status [--json] daemon info, instances, resources, health pi2 status [--json] daemon info, instances, resources, health
pi2 open [--print] [--no-browser] open the web console signed in (local only) pi2 open [--print] [--no-browser] open the web console signed in (local only)
@@ -58,6 +65,8 @@ Usage:
pi2 uninstall-service [--dry-run|--write] remove the unit pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 --version | --help pi2 --version | --help
\`pi2 stop\` / \`pi2 daemon stop\` flags: -f, --force sends SIGKILL if the daemon
does not exit in time; -t, --timeout <sec> configures the wait timeout (default 5s).
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead \`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
of launching a browser (--print implies --no-browser). of launching a browser (--print implies --no-browser).
\`pi2 pairing\` flags: --base <url> pins the link to one of the addresses the \`pi2 pairing\` flags: --base <url> pins the link to one of the addresses the
@@ -69,17 +78,6 @@ The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`. $PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
See docs/deployment.md.`; See docs/deployment.md.`;
/** A user-facing failure: printed as-is, exits with `code`. */
export class CliError extends Error {
readonly code: number;
constructor(message: string, code = 1) {
super(message);
this.name = "CliError";
this.code = code;
}
}
export interface Endpoint { export interface Endpoint {
baseUrl: string; baseUrl: string;
token: string; token: string;
@@ -635,6 +633,44 @@ export function runUninstallService(options: ServiceCommandOptions): number {
return 0; return 0;
} }
async function handleStop(argv: readonly string[], options: Pi2Options, out: (line: string) => void): Promise<number> {
const parsed = parseArgs(argv, {
values: ["--timeout", "-t"],
booleans: ["--force", "--help"],
aliases: { "-h": "--help", "-f": "--force", "-t": "--timeout" },
});
if (boolFlag(parsed.flags, "--help")) {
out(STOP_USAGE);
return 0;
}
if (parsed.positionals.length > 0) {
throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, STOP_USAGE);
}
let timeoutSec: number | undefined;
const timeout = stringFlag(parsed.flags, "--timeout");
if (timeout !== undefined) {
if (!/^\d+$/.test(timeout.trim())) {
throw new UsageError(`--timeout must be a positive integer, got "${timeout}"`, STOP_USAGE);
}
const val = Number(timeout);
if (!Number.isSafeInteger(val) || val <= 0) {
throw new UsageError(`--timeout must be a positive integer, got "${timeout}"`, STOP_USAGE);
}
timeoutSec = val;
}
const runner = options.stopRunner ?? runStop;
return await runner({
runtime: options.runtime,
force: boolFlag(parsed.flags, "--force"),
...(timeoutSec === undefined ? {} : { timeoutSec }),
print: out,
...(options.isPidAlive === undefined ? {} : { isPidAlive: options.isPidAlive }),
...(options.kill === undefined ? {} : { kill: options.kill }),
...(options.sleep === undefined ? {} : { sleep: options.sleep }),
...(options.removeFile === undefined ? {} : { unlink: options.removeFile }),
});
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// main // main
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -654,6 +690,10 @@ export interface Pi2Options {
runtime?: string; runtime?: string;
/** Injected `pi2 daemon` runner (defaults to `src/cli/daemon.ts:main`). */ /** Injected `pi2 daemon` runner (defaults to `src/cli/daemon.ts:main`). */
daemonMain?: (argv: readonly string[], io: { out: (line: string) => void; err: (line: string) => void }) => Promise<number>; daemonMain?: (argv: readonly string[], io: { out: (line: string) => void; err: (line: string) => void }) => Promise<number>;
stopRunner?: (options: StopOptions) => Promise<number>;
isPidAlive?: (pid: number) => boolean;
kill?: (pid: number, signal: NodeJS.Signals) => void;
sleep?: (ms: number) => Promise<void>;
} }
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> { export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
@@ -673,12 +713,18 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
try { try {
switch (command) { switch (command) {
case "daemon": { case "daemon": {
if (rest[0] === "stop") {
return await handleStop(rest.slice(1), options, out);
}
// `pi2 daemon` and `pi2 daemon start` are the same thing; the // `pi2 daemon` and `pi2 daemon start` are the same thing; the
// optional `start` word is consumed here so the daemon parser // optional `start` word is consumed here so the daemon parser
// only ever sees flags. // only ever sees flags.
const argv = rest[0] === "start" ? rest.slice(1) : rest; const argv = rest[0] === "start" ? rest.slice(1) : rest;
return await (options.daemonMain ?? runDaemonMain)(argv, { out, err }); return await (options.daemonMain ?? runDaemonMain)(argv, { out, err });
} }
case "stop": {
return await handleStop(rest, options, out);
}
case "attach": { case "attach": {
const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } }); const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
if (boolFlag(parsed.flags, "--help")) { if (boolFlag(parsed.flags, "--help")) {
+159
View File
@@ -0,0 +1,159 @@
/**
* `pi2 stop` / `pi2 daemon stop` — stop a running pi2 web-console daemon.
*
* Locates the daemon via `<runtime>/daemon.json` (or `daemon.lock`), verifies
* the PID belongs to this boot, sends SIGTERM, and waits for it to exit.
* If --force is passed and SIGTERM times out, escalates to SIGKILL.
*/
import { rmSync } from "node:fs";
import { resolve } from "node:path";
import { runtimeDir } from "../core/paths.js";
import {
assessLock,
DAEMON_JSON_FILE,
LOCK_FILE,
readBootId,
readDaemonJson,
readLockFile,
isPidAlive as defaultIsPidAlive,
type DaemonLock,
} from "./lock.js";
import { CliError, errorMessage } from "./util.js";
export const STOP_USAGE = `pi2 stop — stop a running pi2 daemon
Usage:
pi2 stop [options]
pi2 daemon stop [options]
Options:
-f, --force force kill with SIGKILL if the daemon does not stop in time
-t, --timeout <sec> seconds to wait for the daemon to exit (default: 5)
-h, --help print this help and exit
Environment:
PI2_RUNTIME_DIR directory holding daemon.json and daemon.lock`;
export interface StopOptions {
runtime?: string;
force?: boolean;
timeoutSec?: number;
print?: (line: string) => void;
readDaemonJson?: (path: string) => DaemonLock | undefined;
readLockFile?: (path: string) => DaemonLock | undefined;
isPidAlive?: (pid: number) => boolean;
bootId?: () => string;
kill?: (pid: number, signal: NodeJS.Signals) => void;
sleep?: (ms: number) => Promise<void>;
unlink?: (path: string) => void;
now?: () => number;
}
export async function runStop(options: StopOptions = {}): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const runtime = options.runtime ?? runtimeDir();
const daemonJsonPath = resolve(runtime, DAEMON_JSON_FILE);
const lockPath = resolve(runtime, LOCK_FILE);
const readJson = options.readDaemonJson ?? readDaemonJson;
const readLock = options.readLockFile ?? readLockFile;
const lock = readJson(daemonJsonPath) ?? readLock(lockPath);
if (lock === undefined) {
throw new CliError(`no running pi2 daemon (${daemonJsonPath} missing)`);
}
const checkAlive = options.isPidAlive ?? defaultIsPidAlive;
const getBootId = options.bootId ?? readBootId;
const staleness = assessLock(lock, { isPidAlive: checkAlive, bootId: getBootId });
const doUnlink = options.unlink ?? ((p: string) => rmSync(p, { force: true }));
if (!staleness.live) {
doUnlink(daemonJsonPath);
doUnlink(lockPath);
throw new CliError(`no running pi2 daemon (cleaned up stale lock for pid ${lock.pid})`);
}
const killFn = options.kill ?? ((pid: number, sig: NodeJS.Signals) => process.kill(pid, sig));
const sleepFn = options.sleep ?? ((ms: number) => new Promise((res) => setTimeout(res, ms)));
const nowFn = options.now ?? Date.now;
const timeoutSec = options.timeoutSec ?? 5;
const timeoutMs = timeoutSec * 1000;
try {
killFn(lock.pid, "SIGTERM");
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ESRCH") {
doUnlink(daemonJsonPath);
doUnlink(lockPath);
print(`pi2 daemon (pid ${lock.pid}) stopped`);
return 0;
}
if (err.code === "EPERM") {
throw new CliError(`failed to stop pi2 daemon (pid ${lock.pid}): permission denied`);
}
throw new CliError(`failed to stop pi2 daemon (pid ${lock.pid}): ${errorMessage(error)}`);
}
const pollIntervalMs = 50;
const deadline = nowFn() + timeoutMs;
let exited = false;
while (nowFn() < deadline) {
if (!checkAlive(lock.pid)) {
exited = true;
break;
}
await sleepFn(Math.min(pollIntervalMs, Math.max(1, deadline - nowFn())));
}
if (!exited && !checkAlive(lock.pid)) {
exited = true;
}
if (exited) {
doUnlink(daemonJsonPath);
doUnlink(lockPath);
print(`pi2 daemon (pid ${lock.pid}) stopped`);
return 0;
}
if (options.force === true) {
try {
killFn(lock.pid, "SIGKILL");
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code !== "ESRCH") {
if (err.code === "EPERM") {
throw new CliError(`failed to kill pi2 daemon (pid ${lock.pid}): permission denied`);
}
throw new CliError(`failed to kill pi2 daemon (pid ${lock.pid}): ${errorMessage(error)}`);
}
}
const killDeadline = nowFn() + 1000;
while (nowFn() < killDeadline) {
if (!checkAlive(lock.pid)) {
exited = true;
break;
}
await sleepFn(50);
}
if (!exited && !checkAlive(lock.pid)) {
exited = true;
}
if (!exited) {
throw new CliError(`pi2 daemon (pid ${lock.pid}) could not be killed with SIGKILL`);
}
doUnlink(daemonJsonPath);
doUnlink(lockPath);
print(`pi2 daemon (pid ${lock.pid}) killed with SIGKILL`);
return 0;
}
throw new CliError(`pi2 daemon (pid ${lock.pid}) did not stop within ${timeoutSec}s; use --force to kill`);
}
+11
View File
@@ -13,6 +13,17 @@ export class UsageError extends Error {
} }
} }
/** A user-facing failure: printed as-is, exits with `code`. */
export class CliError extends Error {
readonly code: number;
constructor(message: string, code = 1) {
super(message);
this.name = "CliError";
this.code = code;
}
}
export type FlagValue = string | boolean; export type FlagValue = string | boolean;
export interface FlagSpec { export interface FlagSpec {
+59
View File
@@ -658,4 +658,63 @@ describe("pi2 main", () => {
checks: [{ name: "node", status: "fail", detail: "v18.0.0" }], checks: [{ name: "node", status: "fail", detail: "v18.0.0" }],
}); });
}); });
it("prints stop usage for `stop --help` and `daemon stop --help`", async () => {
const out1: string[] = [];
const code1 = await main(["stop", "--help"], { out: (line) => out1.push(line) });
expect(code1).toBe(0);
expect(out1.join("\n")).toContain("pi2 stop [options]");
expect(out1.join("\n")).toContain("-f, --force");
const out2: string[] = [];
const code2 = await main(["daemon", "stop", "--help"], { out: (line) => out2.push(line) });
expect(code2).toBe(0);
expect(out2.join("\n")).toContain("pi2 stop [options]");
});
it("routes `stop` and `daemon stop` to stopRunner with parsed flags", async () => {
const calls: unknown[] = [];
const code1 = await main(["stop", "--force", "-t", "10"], {
stopRunner: async (opts) => {
calls.push(opts);
return 0;
},
});
expect(code1).toBe(0);
expect(calls[0]).toMatchObject({ force: true, timeoutSec: 10 });
calls.length = 0;
const code2 = await main(["daemon", "stop", "-f"], {
stopRunner: async (opts) => {
calls.push(opts);
return 0;
},
});
expect(code2).toBe(0);
expect(calls[0]).toMatchObject({ force: true });
});
it("rejects invalid arguments for `stop` with exit 2", async () => {
const err: string[] = [];
const code1 = await main(["stop", "extra"], { err: (line) => err.push(line) });
expect(code1).toBe(2);
expect(err[0]).toContain('unexpected argument "extra"');
err.length = 0;
const code2 = await main(["stop", "--timeout", "nope"], { err: (line) => err.push(line) });
expect(code2).toBe(2);
expect(err[0]).toContain("--timeout must be a positive integer");
});
it("reports missing daemon on `stop` with exit 1", async () => {
const err: string[] = [];
const code = await main(["stop"], {
err: (line) => err.push(line),
stopRunner: async () => {
throw new CliError("no running pi2 daemon");
},
});
expect(code).toBe(1);
expect(err[0]).toBe("pi2: no running pi2 daemon");
});
}); });
+192
View File
@@ -0,0 +1,192 @@
import { describe, expect, it } from "vitest";
import { runStop, type StopOptions } from "../../src/cli/stop.js";
import { CliError } from "../../src/cli/util.js";
import type { DaemonLock } from "../../src/cli/lock.js";
function mockLock(overrides: Partial<DaemonLock> = {}): DaemonLock {
return {
pid: 12345,
bootId: "boot-1",
port: 7676,
daemonId: "d-test-1",
startedAt: 1700000000000,
protocolVersion: 1,
...overrides,
};
}
describe("runStop", () => {
it("throws CliError when neither daemon.json nor daemon.lock exists", async () => {
await expect(
runStop({
readDaemonJson: () => undefined,
readLockFile: () => undefined,
}),
).rejects.toThrow("no running pi2 daemon");
});
it("cleans up stale lock and throws CliError when PID is dead", async () => {
const unlinked: string[] = [];
const lock = mockLock({ pid: 99999 });
await expect(
runStop({
readDaemonJson: () => lock,
isPidAlive: () => false,
bootId: () => "boot-1",
unlink: (p) => unlinked.push(p),
}),
).rejects.toThrow("no running pi2 daemon (cleaned up stale lock for pid 99999)");
expect(unlinked.length).toBe(2);
});
it("cleans up stale lock and throws CliError when bootId has changed", async () => {
const unlinked: string[] = [];
const lock = mockLock({ pid: 12345, bootId: "boot-old" });
await expect(
runStop({
readDaemonJson: () => lock,
isPidAlive: () => true,
bootId: () => "boot-new",
unlink: (p) => unlinked.push(p),
}),
).rejects.toThrow("no running pi2 daemon (cleaned up stale lock for pid 12345)");
expect(unlinked.length).toBe(2);
});
it("sends SIGTERM, waits for daemon to exit, and returns 0", async () => {
const signals: { pid: number; signal: NodeJS.Signals }[] = [];
const lines: string[] = [];
const unlinked: string[] = [];
let alive = true;
const code = await runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => alive,
bootId: () => "boot-1",
kill: (pid, sig) => {
signals.push({ pid, signal: sig });
alive = false;
},
print: (line) => lines.push(line),
unlink: (p) => unlinked.push(p),
sleep: async () => {},
});
expect(code).toBe(0);
expect(signals).toEqual([{ pid: 12345, signal: "SIGTERM" }]);
expect(lines).toEqual(["pi2 daemon (pid 12345) stopped"]);
expect(unlinked.length).toBe(2);
});
it("handles ESRCH on SIGTERM cleanly as stopped", async () => {
const lines: string[] = [];
const unlinked: string[] = [];
const esrch = new Error("kill ESRCH") as NodeJS.ErrnoException;
esrch.code = "ESRCH";
const code = await runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {
throw esrch;
},
print: (line) => lines.push(line),
unlink: (p) => unlinked.push(p),
});
expect(code).toBe(0);
expect(lines).toEqual(["pi2 daemon (pid 12345) stopped"]);
expect(unlinked.length).toBe(2);
});
it("throws CliError when SIGTERM fails with EPERM", async () => {
const eperm = new Error("kill EPERM") as NodeJS.ErrnoException;
eperm.code = "EPERM";
await expect(
runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {
throw eperm;
},
}),
).rejects.toThrow("failed to stop pi2 daemon (pid 12345): permission denied");
});
it("throws CliError when daemon does not exit within timeout without force", async () => {
let fakeTime = 1000;
await expect(
runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {},
timeoutSec: 1,
now: () => fakeTime,
sleep: async (ms) => {
fakeTime += ms;
},
}),
).rejects.toThrow("pi2 daemon (pid 12345) did not stop within 1s; use --force to kill");
});
it("escalates to SIGKILL with --force when SIGTERM times out", async () => {
const signals: { pid: number; signal: NodeJS.Signals }[] = [];
const lines: string[] = [];
const unlinked: string[] = [];
let fakeTime = 1000;
let killedWithSigkill = false;
const code = await runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => !killedWithSigkill,
bootId: () => "boot-1",
kill: (pid, sig) => {
signals.push({ pid, signal: sig });
if (sig === "SIGKILL") killedWithSigkill = true;
},
force: true,
timeoutSec: 1,
now: () => fakeTime,
sleep: async (ms) => {
fakeTime += ms;
},
print: (line) => lines.push(line),
unlink: (p) => unlinked.push(p),
});
expect(code).toBe(0);
expect(signals).toEqual([
{ pid: 12345, signal: "SIGTERM" },
{ pid: 12345, signal: "SIGKILL" },
]);
expect(lines).toEqual(["pi2 daemon (pid 12345) killed with SIGKILL"]);
expect(unlinked.length).toBe(2);
});
it("throws CliError if daemon still alive after SIGKILL", async () => {
let fakeTime = 1000;
await expect(
runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {},
force: true,
timeoutSec: 1,
now: () => fakeTime,
sleep: async (ms) => {
fakeTime += ms;
},
}),
).rejects.toThrow("pi2 daemon (pid 12345) could not be killed with SIGKILL");
});
});