diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b3e80cdce8e..4ca95a53561 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1779,7 +1779,12 @@ NemoClaw preserves the per-gateway PID file and runtime marker so you can inspec Stop only the listener that matches the target gateway, then rerun `destroy` to converge cleanup. When the default-port gateway runs under the packaged OpenShell gateway service, gateway cleanup stops that service before it reaps host processes, so the gateway port is released instead of being rebound by the service manager. The service is stopped, not disabled or removed, and the next onboarding run starts it again. -If the service cannot be stopped, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal. +On headless Linux, the packaged service can exist while its `systemd` user manager is unavailable and the gateway runs through the standalone fallback. +For this recognized manager-unavailable failure only, `destroy` uses the per-gateway PID file when the service is not enabled for automatic activation. +If the recorded PID is live, its command line must match the exact gateway name and port before `destroy` stops it. +If the recorded process has exited, `destroy` continues only after it verifies that the gateway port is free. +If a live PID does not prove gateway ownership or the port remains occupied, `destroy` exits non-zero and preserves the runtime evidence for inspection. +For any other service stop failure, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal. If the OpenShell gateway is unreachable and the sandbox has no managed MCP ownership state, `--force` removes only NemoClaw's local registry entry and local artifacts. Gateway-side deletion remains unconfirmed, shared host-service and gateway teardown are skipped, and the sandbox and retained volume may still exist if the gateway returns. Start the gateway with `$$nemoclaw status` and retry destroy when you need a confirmed deletion. diff --git a/src/lib/actions/sandbox/destroy-gateway.test.ts b/src/lib/actions/sandbox/destroy-gateway.test.ts index 1560ac89951..1d72c56cf14 100644 --- a/src/lib/actions/sandbox/destroy-gateway.test.ts +++ b/src/lib/actions/sandbox/destroy-gateway.test.ts @@ -47,9 +47,10 @@ function packagedServiceOwner({ }; } -function serviceStopResult(stopped: boolean, reason?: string) { +function serviceStopResult(stopped: boolean, reason?: string, standaloneFallbackAllowed = false) { return { attempted: true, + standaloneFallbackAllowed, manager: "systemd" as const, serviceName: "nemoclaw-openshell-gateway", statusCommand: "systemctl --user status nemoclaw-openshell-gateway", @@ -344,6 +345,134 @@ describe("cleanupGatewayAfterLastSandbox", () => { expect(mocks.dockerRemoveVolumesByPrefix).not.toHaveBeenCalled(); }); + it("stops the recorded standalone gateway when the systemd user manager is unavailable", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner); + mocks.stopHostGatewayProcesses.mockReturnValueOnce({ + ...idleHostReaperResult(), + stopped: [4242], + }); + const clearGatewayRuntimeFiles = vi.fn(); + const isGatewayPortFree = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + + cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, { + clearGatewayRuntimeFiles, + isGatewayPortFree, + stopOpenShellGatewayUserService: () => + serviceStopResult( + false, + "systemctl --user stop failed: Failed to connect to bus: No medium found", + true, + ), + }); + + expect(mocks.stopHostGatewayProcesses).toHaveBeenCalledWith( + {}, + expect.objectContaining({ + clearRuntimeFiles: false, + openShellGatewayName: "nemoclaw", + openShellGatewayPort: 8080, + usePgrepFallback: false, + }), + ); + expect(isGatewayPortFree).toHaveBeenCalledWith(8080); + expect(clearGatewayRuntimeFiles).toHaveBeenCalledWith( + "/home/tester/.local/state/nemoclaw/openshell-docker-gateway", + "/home/tester/.local/state/nemoclaw/openshell-docker-gateway/openshell-gateway.pid", + ); + expect(runOpenshell).toHaveBeenCalledWith(["gateway", "remove", "nemoclaw"], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + }); + }); + + it("fails closed when a headless service stop has no recorded standalone owner", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner); + const isGatewayPortFree = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + + expect(() => + cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, { + isGatewayPortFree, + stopOpenShellGatewayUserService: () => + serviceStopResult(false, "Failed to connect to bus: No medium found", true), + }), + ).toThrow(/no recorded standalone gateway process proved ownership/); + expect(isGatewayPortFree).not.toHaveBeenCalled(); + expect(runOpenshell).not.toHaveBeenCalledWith( + ["gateway", "remove", "nemoclaw"], + expect.anything(), + ); + }); + + it("fails closed when the gateway port stays occupied after headless fallback cleanup", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner); + mocks.stopHostGatewayProcesses.mockReturnValueOnce({ + ...idleHostReaperResult(), + stopped: [4242], + }); + const clearGatewayRuntimeFiles = vi.fn(); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + + expect(() => + cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, { + clearGatewayRuntimeFiles, + isGatewayPortFree: () => false, + stopOpenShellGatewayUserService: () => + serviceStopResult(false, "Failed to connect to bus: No medium found", true), + }), + ).toThrow(/gateway port 8080 remains occupied/); + expect(clearGatewayRuntimeFiles).not.toHaveBeenCalled(); + expect(runOpenshell).not.toHaveBeenCalledWith( + ["gateway", "remove", "nemoclaw"], + expect.anything(), + ); + }); + + it("retries headless fallback cleanup after volume removal fails", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); + mocks.resolveGatewayTeardownAuthority.mockImplementation(packagedServiceOwner); + mocks.stopHostGatewayProcesses + .mockReturnValueOnce({ + ...idleHostReaperResult(), + stopped: [4242], + }) + .mockReturnValueOnce({ + ...idleHostReaperResult(), + skippedDeadPids: [4242], + }); + mocks.dockerRemoveVolumesByPrefix.mockImplementationOnce(() => { + throw new Error("injected volume cleanup failure"); + }); + const clearGatewayRuntimeFiles = vi.fn(); + const isGatewayPortFree = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + const deps = { + clearGatewayRuntimeFiles, + isGatewayPortFree, + stopOpenShellGatewayUserService: () => + serviceStopResult(false, "Failed to connect to bus: No medium found", true), + }; + + expect(() => cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, deps)).toThrow( + "injected volume cleanup failure", + ); + expect(clearGatewayRuntimeFiles).not.toHaveBeenCalled(); + + expect(() => cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, deps)).not.toThrow(); + expect(mocks.stopHostGatewayProcesses).toHaveBeenCalledTimes(2); + expect(isGatewayPortFree).toHaveBeenCalledTimes(2); + expect(clearGatewayRuntimeFiles).toHaveBeenCalledOnce(); + expect(mocks.dockerRemoveVolumesByPrefix).toHaveBeenCalledTimes(2); + }); + it("leaves the service manager alone for a standalone NemoClaw gateway (#7904)", () => { vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.spyOn(os, "homedir").mockReturnValue("/home/tester"); diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index dc1823dc724..48ce8809bc2 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -17,7 +17,11 @@ import { type GatewayTeardownAuthorityResolver, resolveGatewayTeardownAuthority, } from "../../onboard/gateway-teardown-authority"; -import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; +import { + clearHostGatewayRuntimeFiles, + isHostPortFree, + stopHostGatewayProcesses, +} from "../../onboard/host-gateway-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; export type DestroyRunOpenshell = ( @@ -28,6 +32,8 @@ export type DestroyRunOpenshell = ( const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); export interface CleanupGatewayDeps { + clearGatewayRuntimeFiles?: typeof clearHostGatewayRuntimeFiles; + isGatewayPortFree?: typeof isHostPortFree; resolveGatewayTeardownAuthority?: GatewayTeardownAuthorityResolver; stopOpenShellGatewayUserService?: typeof stopOpenShellGatewayUserService; } @@ -107,14 +113,19 @@ export function cleanupGatewayAfterLastSandbox( // ports the live openshell tracks; this catches orphans whose openshell // record was lost across upgrades or failed onboards. stopStaleDashboardListeners(); + let packagedServiceFallbackReason: string | null = null; if (!externallySupervised && owner.source === "packaged-service") { const stopService = deps.stopOpenShellGatewayUserService ?? stopOpenShellGatewayUserService; const serviceStop = stopService(); if (serviceStop.attempted && !serviceStop.stopped) { - throw new Error( - `Failed to stop the packaged OpenShell gateway service '${serviceStop.serviceName}' that owns gateway '${gatewayName}': ${serviceStop.reason}. ` + - `Check: ${serviceStop.statusCommand}. Stop the service, then rerun destroy.`, - ); + if (serviceStop.standaloneFallbackAllowed) { + packagedServiceFallbackReason = serviceStop.reason ?? "user service manager unavailable"; + } else { + throw new Error( + `Failed to stop the packaged OpenShell gateway service '${serviceStop.serviceName}' that owns gateway '${gatewayName}': ${serviceStop.reason}. ` + + `Check: ${serviceStop.statusCommand}. Stop the service, then rerun destroy.`, + ); + } } } if (!externallySupervised && (process.platform === "linux" || process.platform === "darwin")) { @@ -132,6 +143,7 @@ export function cleanupGatewayAfterLastSandbox( openShellGatewayPort?: number; preserveRuntimeFilesOnNonMatching: true; usePgrepFallback: false; + clearRuntimeFiles?: boolean; stateDir?: string; pidFile?: string; } = { @@ -142,6 +154,16 @@ export function cleanupGatewayAfterLastSandbox( stopOptions.pidFile = path.join(perGatewayState.stateDir, "openshell-gateway.pid"); stopOptions.openShellGatewayName = gatewayName; stopOptions.openShellGatewayPort = perGatewayState.port; + if (packagedServiceFallbackReason !== null) { + // A package can be installed even when its user manager is unavailable. + // Destroy cannot repair the missing systemd user session. Remove this + // branch when supported onboarding no longer starts a standalone gateway + // after this service-manager failure. + // In that exact start fallback, the standalone launcher wrote this + // per-gateway PID evidence. Preserve it until every later cleanup step + // succeeds so a retry can prove the same ownership again. + stopOptions.clearRuntimeFiles = false; + } const stopResult = stopHostGatewayProcesses({}, stopOptions); const unverifiablePids = [...new Set(stopResult.skippedNonMatchingPids)]; if (unverifiablePids.length > 0) { @@ -159,6 +181,23 @@ export function cleanupGatewayAfterLastSandbox( `Failed to stop the owned host gateway process(es) for '${gatewayName}': ${failedPids.join(", ")}.${remediation}`, ); } + if (packagedServiceFallbackReason !== null) { + const ownedStandalonePidProven = + stopResult.stopped.length > 0 || stopResult.skippedDeadPids.length > 0; + if (!ownedStandalonePidProven) { + throw new Error( + `Failed to stop the packaged OpenShell gateway service for '${gatewayName}' because ${packagedServiceFallbackReason}, and no recorded standalone gateway process proved ownership. ` + + "Restore the user service manager or stop the verified gateway listener, then rerun destroy.", + ); + } + const portFree = deps.isGatewayPortFree ?? isHostPortFree; + if (!portFree(perGatewayState.port)) { + throw new Error( + `Refusing cleanup because gateway port ${String(perGatewayState.port)} remains occupied after the recorded standalone gateway process for '${gatewayName}' exited or was stopped. ` + + "Inspect the remaining listener, stop only the matching gateway process, then rerun destroy.", + ); + } + } } /** * SOURCE_OF_TRUTH @@ -206,4 +245,11 @@ export function cleanupGatewayAfterLastSandbox( dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, { ignoreError: true, }); + if (packagedServiceFallbackReason !== null) { + const clearRuntimeFiles = deps.clearGatewayRuntimeFiles ?? clearHostGatewayRuntimeFiles; + clearRuntimeFiles( + perGatewayState.stateDir, + path.join(perGatewayState.stateDir, "openshell-gateway.pid"), + ); + } } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 0e9b7f66f41..505a2398e33 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -573,6 +573,7 @@ describe("docker-driver-gateway-service", () => { expect(result).toEqual({ attempted: true, + standaloneFallbackAllowed: false, manager: "systemd", serviceName: "nemoclaw-openshell-gateway", statusCommand: "systemctl --user status nemoclaw-openshell-gateway", @@ -626,6 +627,7 @@ describe("docker-driver-gateway-service", () => { expect(result).toEqual({ attempted: true, + standaloneFallbackAllowed: false, manager: "homebrew", serviceName: "openshell", statusCommand: "brew services info openshell", @@ -674,8 +676,54 @@ describe("docker-driver-gateway-service", () => { ])("reports nothing to stop when %s (#7904)", (_case, opts, reason) => { expect(stopOpenShellGatewayUserService({ commandExists: () => true, ...opts })).toEqual({ attempted: false, + standaloneFallbackAllowed: false, reason, stopped: false, }); }); + + it("reports standalone fallback eligibility when the systemd user manager is unavailable", () => { + const home = "/home/nvidia"; + const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`; + + const result = stopOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: { HOME: home }, + existsSync: (candidate) => candidate === servicePath, + home, + lstatSync: nonSymlinkStat, + platform: "linux", + readFileSync: () => `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}\n`, + spawnSyncImpl: vi.fn(() => spawnResult(1, "Failed to connect to bus: No medium found")), + }); + + expect(result).toMatchObject({ + attempted: true, + standaloneFallbackAllowed: true, + stopped: false, + }); + }); + + it("refuses standalone fallback when the systemd service can activate automatically", () => { + const home = "/home/nvidia"; + const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`; + const activationPath = `${home}/.config/systemd/user/default.target.wants/nemoclaw-openshell-gateway.service`; + + const result = stopOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: { HOME: home }, + existsSync: (candidate) => candidate === servicePath || candidate === activationPath, + home, + lstatSync: nonSymlinkStat, + platform: "linux", + readFileSync: () => `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}\n`, + spawnSyncImpl: vi.fn(() => spawnResult(1, "Failed to connect to bus: No medium found")), + }); + + expect(result).toMatchObject({ + attempted: true, + standaloneFallbackAllowed: false, + stopped: false, + }); + }); }); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 7e41084336b..96026ca3bdf 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -50,6 +50,7 @@ export interface OpenShellGatewayUserServiceStartResult { export interface OpenShellGatewayUserServiceStopResult { attempted: boolean; + standaloneFallbackAllowed: boolean; manager?: "homebrew" | "systemd"; reason?: string; serviceName?: string; @@ -360,6 +361,24 @@ function userManagerLooksUnavailable(reason: string): boolean { ); } +function hasSystemdUserServiceActivationLink( + service: OpenShellGatewayUserServiceTarget, + home: string, + env: NodeJS.ProcessEnv, + existsSync: (filePath: string) => boolean, +): boolean { + if (service.manager !== "systemd") return false; + return existsSync( + path.join( + getOpenShellUserConfigHome(home, env), + "systemd", + "user", + "default.target.wants", + `${service.serviceName}.service`, + ), + ); +} + function parseSystemctlShow(output: string): Record { return Object.fromEntries( output @@ -666,17 +685,35 @@ export function stopOpenShellGatewayUserService( ): OpenShellGatewayUserServiceStopResult { const platform = opts.platform ?? process.platform; if (platform !== "linux" && platform !== "darwin") { - return { attempted: false, stopped: false, reason: "unsupported platform" }; + return { + attempted: false, + standaloneFallbackAllowed: false, + stopped: false, + reason: "unsupported platform", + }; } const env = opts.env ?? process.env; const home = effectiveHome(opts.home, opts.env); + const existsSync = opts.existsSync ?? fs.existsSync; const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; const service = resolveOpenShellGatewayUserService({ ...opts, env, home }); - if (!service) return { attempted: false, stopped: false, reason: "service not installed" }; + if (!service) { + return { + attempted: false, + standaloneFallbackAllowed: false, + stopped: false, + reason: "service not installed", + }; + } const describe = (stopped: boolean, reason?: string): OpenShellGatewayUserServiceStopResult => ({ attempted: true, + standaloneFallbackAllowed: + !stopped && + service.manager === "systemd" && + userManagerLooksUnavailable(reason ?? "") && + !hasSystemdUserServiceActivationLink(service, home, env, existsSync), manager: service.manager, serviceName: service.serviceName, statusCommand: service.statusCommand, diff --git a/src/lib/onboard/host-gateway-process.test.ts b/src/lib/onboard/host-gateway-process.test.ts index 29c87ca9ffd..c07b4938548 100644 --- a/src/lib/onboard/host-gateway-process.test.ts +++ b/src/lib/onboard/host-gateway-process.test.ts @@ -8,8 +8,10 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { + clearHostGatewayRuntimeFiles, HOST_GATEWAY_PGREP_PATTERN, type HostGatewayProcessDeps, + isHostPortFree, type RunResult, stopHostGatewayProcesses, } from "./host-gateway-process"; @@ -66,6 +68,67 @@ function psResponses( ]; } +describe("host gateway cleanup boundaries", () => { + it.each([ + ["free", 0, true], + ["occupied", 1, false], + ["inconclusive", null, false], + ] as const)("reports a host port as %s from the bind probe", (_case, status, expected) => { + const spawnSyncImpl = vi.fn(() => ({ + status, + })) as unknown as typeof import("node:child_process").spawnSync; + + expect(isHostPortFree(8080, spawnSyncImpl)).toBe(expected); + expect(spawnSyncImpl).toHaveBeenCalledWith( + process.execPath, + ["-e", expect.stringContaining("server.listen(8080, '127.0.0.1'")], + { stdio: "ignore", timeout: 2_000 }, + ); + }); + + it("clears the exact gateway PID file and runtime marker", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-clear-")); + try { + const pidFile = path.join(stateDir, "openshell-gateway.pid"); + const markerFile = path.join(stateDir, "runtime.json"); + const unrelatedFile = path.join(stateDir, "unrelated.txt"); + fs.writeFileSync(pidFile, "4242\n"); + fs.writeFileSync(markerFile, "{}\n"); + fs.writeFileSync(unrelatedFile, "keep\n"); + + clearHostGatewayRuntimeFiles(stateDir, pidFile); + + expect(fs.existsSync(pidFile)).toBe(false); + expect(fs.existsSync(markerFile)).toBe(false); + expect(fs.existsSync(unrelatedFile)).toBe(true); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }); + + it("preserves the gateway PID file when runtime marker removal fails", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-clear-")); + const pidFile = path.join(stateDir, "openshell-gateway.pid"); + const markerFile = path.join(stateDir, "runtime.json"); + fs.writeFileSync(pidFile, "4242\n"); + fs.writeFileSync(markerFile, "{}\n"); + const rmSync = vi.spyOn(fs, "rmSync").mockImplementation((candidate) => { + expect(candidate).toBe(markerFile); + throw new Error("marker cleanup failed"); + }); + + try { + expect(() => clearHostGatewayRuntimeFiles(stateDir, pidFile)).toThrow( + "marker cleanup failed", + ); + expect(fs.existsSync(pidFile)).toBe(true); + } finally { + rmSync.mockRestore(); + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }); +}); + describe("stopHostGatewayProcesses", () => { it("uses pgrep fallback when the Docker-driver gateway PID file is missing", () => { const exited = new Set(); diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index af72f53fdde..eada983ec78 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -9,8 +9,8 @@ import path from "node:path"; import { waitUntil } from "../core/wait"; import { clearDockerDriverGatewayRuntimeMarker } from "./docker-driver-gateway-runtime-marker"; import { - hostGatewayCmdlineMatches as sharedHostGatewayCmdlineMatches, type OpenShellGatewayProcessTarget, + hostGatewayCmdlineMatches as sharedHostGatewayCmdlineMatches, } from "./gateway-process-identity"; export interface RunResult { @@ -194,9 +194,29 @@ function waitForExit( ); } -function clearRuntimeFiles(pidFile: string, stateDir: string): void { - fs.rmSync(pidFile, { force: true }); +export function clearHostGatewayRuntimeFiles(stateDir: string, pidFile: string): void { clearDockerDriverGatewayRuntimeMarker(stateDir); + fs.rmSync(pidFile, { force: true }); +} + +export function isHostPortFree(port: number, spawnSyncImpl: typeof spawnSync = spawnSync): boolean { + const script = + "const net = require('node:net');" + + "const server = net.createServer();" + + "let done = false;" + + "const finish = (code) => { if (!done) { done = true; process.exit(code); } };" + + "server.once('error', () => finish(1));" + + `server.listen(${String(port)}, '127.0.0.1', () => server.close(() => finish(0)));`; + try { + return ( + spawnSyncImpl(process.execPath, ["-e", script], { + stdio: "ignore", + timeout: 2_000, + }).status === 0 + ); + } catch { + return false; + } } function addPid(candidates: Map>, pid: number, source: string): void { @@ -274,7 +294,7 @@ export function stopHostGatewayProcesses( if (pidFromFile !== null) { addPid(candidates, pidFromFile, "pid-file"); } else if (clearRuntimeState && fs.existsSync(pidFile)) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); } } @@ -313,7 +333,7 @@ export function stopHostGatewayProcesses( if (!pidExists(pid, deps)) { result.skippedDeadPids.push(pid); if (clearRuntimeState && sources.has("pid-file") && !clearedRuntimeFiles) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); clearedRuntimeFiles = true; } continue; @@ -332,7 +352,7 @@ export function stopHostGatewayProcesses( sources.has("pid-file") && !clearedRuntimeFiles ) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); clearedRuntimeFiles = true; } continue; @@ -341,7 +361,7 @@ export function stopHostGatewayProcesses( if (tryStopPid(pid, deps, waitOptions) === "stopped") { result.stopped.push(pid); if (clearRuntimeState && !clearedRuntimeFiles) { - clearRuntimeFiles(pidFile, stateDir); + clearHostGatewayRuntimeFiles(stateDir, pidFile); clearedRuntimeFiles = true; } } else {