feat(cli): add stop command to shut down running daemon
This commit is contained in:
1 parent
2b8171cc37
commit
48411dccd2
8 files changed
+498
-19
No files matched your search
+57
-11
@@ -26,6 +26,7 @@ import { readDaemonJson, type DaemonLock } from "./lock.js";
|
||||
import { cliTokenPath, readCliToken } from "./token.js";
|
||||
import {
|
||||
boolFlag,
|
||||
CliError,
|
||||
errorMessage,
|
||||
formatBytes,
|
||||
formatTable,
|
||||
@@ -44,11 +45,17 @@ import {
|
||||
type ServicePlatform,
|
||||
} from "./service.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
|
||||
|
||||
Usage:
|
||||
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 status [--json] daemon info, instances, resources, health
|
||||
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 --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
|
||||
of launching a browser (--print implies --no-browser).
|
||||
\`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\`.
|
||||
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 {
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
@@ -635,6 +633,44 @@ export function runUninstallService(options: ServiceCommandOptions): number {
|
||||
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
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -654,6 +690,10 @@ export interface Pi2Options {
|
||||
runtime?: string;
|
||||
/** 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>;
|
||||
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> {
|
||||
@@ -673,12 +713,18 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
||||
try {
|
||||
switch (command) {
|
||||
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
|
||||
// optional `start` word is consumed here so the daemon parser
|
||||
// only ever sees flags.
|
||||
const argv = rest[0] === "start" ? rest.slice(1) : rest;
|
||||
return await (options.daemonMain ?? runDaemonMain)(argv, { out, err });
|
||||
}
|
||||
case "stop": {
|
||||
return await handleStop(rest, options, out);
|
||||
}
|
||||
case "attach": {
|
||||
const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
|
||||
+159
@@ -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`);
|
||||
}
|
||||
@@ -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 interface FlagSpec {
|
||||
|
||||
Reference in new issue
Block a user