Skip to content

Commit d0a51cc

Browse files
committed
fix(gateway): harden unowned stop verification
Signed-off-by: sallyom <[email protected]>
1 parent 782ec44 commit d0a51cc

2 files changed

Lines changed: 44 additions & 45 deletions

File tree

‎src/cli/daemon-cli/lifecycle.test.ts‎

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const resolveGatewayServiceProbeHosts = vi.fn(
4242
["127.0.0.1"] as readonly string[],
4343
);
4444
const probePortUsage = vi.fn(
45-
async (_port: number, _hosts?: readonly string[]) => "free" as "free" | "busy",
45+
async (_port: number, _hosts?: readonly string[]) => "free" as "free" | "busy" | "unknown",
4646
);
4747
const formatGatewayPidList = vi.fn<(pids: number[]) => string>((pids) => pids.join(", "));
4848
const probeGateway =
@@ -57,7 +57,7 @@ const callGatewayCli = vi.fn();
5757
const isRestartEnabled = vi.fn<(config?: { commands?: unknown }) => boolean>(() => true);
5858
const loadConfig = vi.hoisted(() => vi.fn(() => ({})));
5959
const createConfigIO = vi.hoisted(() =>
60-
vi.fn((_opts?: { env?: Record<string, string | undefined> }) => ({
60+
vi.fn((_opts?: { env?: Record<string, string | undefined>; observe?: boolean }) => ({
6161
readBestEffortConfig: async () => loadConfig(),
6262
})),
6363
);
@@ -787,6 +787,7 @@ describe("runDaemonRestart health checks", () => {
787787
expect(appendGatewayLifecycleAudit).toHaveBeenCalledWith(
788788
expect.objectContaining({ action: "stop", mode: "sigterm", pid: 4200 }),
789789
);
790+
expect(service.readCommand).not.toHaveBeenCalled();
790791
expect(outcome).toEqual({
791792
result: "stopped",
792793
message: "Gateway stop signal sent to unmanaged process on port 18789: 4200.",
@@ -1094,50 +1095,46 @@ describe("runDaemonRestart health checks", () => {
10941095
expect(signalVerifiedGatewayPidSync).not.toHaveBeenCalled();
10951096
});
10961097

1097-
it("skips unmanaged signaling for pids that are not live gateway processes", async () => {
1098-
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([]);
1099-
readActiveGatewayLockIdentity.mockResolvedValue(undefined);
1100-
1101-
const outcome = await runUnmanagedStop();
1102-
1103-
expect(signalVerifiedGatewayPidSync).not.toHaveBeenCalled();
1104-
expect(appendGatewayLifecycleAudit).not.toHaveBeenCalled();
1105-
expect(probePortUsage).toHaveBeenCalledWith(18789, ["127.0.0.1"]);
1106-
expect(outcome).toBeNull();
1107-
});
1108-
1109-
it("throws when gateway-configured port is busy without an identified owner", async () => {
1110-
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([]);
1111-
readActiveGatewayLockIdentity.mockResolvedValue(undefined);
1112-
probePortUsage.mockResolvedValue("busy");
1113-
1114-
await expect(runUnmanagedStop()).rejects.toThrow(
1115-
/Port 18789 is in use but the owning process could not be identified/,
1116-
);
1117-
expect(probePortUsage).toHaveBeenCalledWith(18789, ["127.0.0.1"]);
1118-
expect(signalVerifiedGatewayPidSync).not.toHaveBeenCalled();
1119-
});
1098+
it.each([
1099+
["free", undefined],
1100+
["busy", "Port 18789 is in use but the owning process could not be identified"],
1101+
["unknown", "Could not determine whether port 18789 is still in use"],
1102+
] as const)(
1103+
"handles an unowned gateway port reported as %s",
1104+
async (portUsage, expectedError) => {
1105+
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([]);
1106+
readActiveGatewayLockIdentity.mockResolvedValue(undefined);
1107+
probePortUsage.mockResolvedValue(portUsage);
1108+
1109+
const outcome = runUnmanagedStop();
1110+
if (expectedError) {
1111+
await expect(outcome).rejects.toThrow(expectedError);
1112+
} else {
1113+
await expect(outcome).resolves.toBeNull();
1114+
}
1115+
},
1116+
);
11201117

11211118
it("resolves port and probe hosts from selected service config/env (no --port arg)", async () => {
11221119
const serviceCommand = {
11231120
programArguments: ["openclaw", "gateway"],
11241121
environment: { OPENCLAW_STATE_DIR: "/tmp/service-state" },
11251122
};
11261123
service.readCommand.mockResolvedValue(serviceCommand);
1127-
resolveGatewayPort.mockImplementation((_cfg, env) => {
1128-
const e = env as Record<string, string | undefined> | undefined;
1129-
return e?.OPENCLAW_STATE_DIR === "/tmp/service-state" ? 19000 : 18789;
1124+
loadConfig.mockReturnValue({ gateway: { port: 18789 } });
1125+
createConfigIO.mockImplementation((opts) => ({
1126+
readBestEffortConfig: async () => ({
1127+
gateway: { port: opts?.env?.OPENCLAW_STATE_DIR === "/tmp/service-state" ? 19000 : 18789 },
1128+
}),
1129+
}));
1130+
resolveGatewayPort.mockImplementation((cfg) => {
1131+
return (cfg as { gateway?: { port?: number } } | undefined)?.gateway?.port ?? 18789;
11301132
});
11311133
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([]);
11321134
readActiveGatewayLockIdentity.mockResolvedValue(undefined);
11331135
probePortUsage.mockResolvedValue("busy");
11341136

11351137
await expect(runUnmanagedStop()).rejects.toThrow(/Port 19000/);
1136-
expect(createConfigIO).toHaveBeenCalledWith(
1137-
expect.objectContaining({
1138-
env: expect.objectContaining({ OPENCLAW_STATE_DIR: "/tmp/service-state" }),
1139-
}),
1140-
);
11411138
expect(resolveGatewayServiceProbeHosts).toHaveBeenCalledWith(
11421139
expect.objectContaining({ command: serviceCommand }),
11431140
);

‎src/cli/daemon-cli/lifecycle.ts‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ async function resolveGatewayLifecycleContext(service = resolveGatewayService())
114114
const env = mergeGatewayServiceEnv(process.env, command);
115115
const config = await createConfigIO({
116116
env,
117+
observe: false,
117118
pluginValidation: "skip",
118119
suppressFutureVersionWarning: true,
119120
})
@@ -123,10 +124,9 @@ async function resolveGatewayLifecycleContext(service = resolveGatewayService())
123124
return { port, env, command };
124125
}
125126

126-
function resolveGatewayPortFallback(): Promise<number> {
127-
return readBestEffortConfig({ observe: false })
128-
.then((cfg) => resolveGatewayPort(cfg, process.env))
129-
.catch(() => resolveGatewayPort(undefined, process.env));
127+
async function resolveGatewayPortFallback(): Promise<number> {
128+
const config = await readBestEffortConfig({ observe: false }).catch(() => undefined);
129+
return resolveGatewayPort(config, process.env);
130130
}
131131

132132
async function resolveExplicitGatewayConfigPort(): Promise<number | undefined> {
@@ -135,8 +135,7 @@ async function resolveExplicitGatewayConfigPort(): Promise<number | undefined> {
135135

136136
async function assertUnmanagedGatewayRestartEnabled(port: number): Promise<void> {
137137
const cfg = await readBestEffortConfig({ observe: false }).catch(() => undefined);
138-
const tlsEnabled = Boolean(cfg?.gateway?.tls?.enabled);
139-
const scheme = tlsEnabled ? "wss" : "ws";
138+
const scheme = cfg?.gateway?.tls?.enabled ? "wss" : "ws";
140139
const probe = await probeGateway({
141140
url: `${scheme}://127.0.0.1:${port}`,
142141
auth: {
@@ -217,9 +216,12 @@ async function stopGatewayWithoutServiceManager(
217216
const pids = listenerPids.length > 0 ? listenerPids : lockOwnerPid ? [lockOwnerPid] : [];
218217
if (pids.length === 0) {
219218
const probeHosts = await resolveGatewayServiceProbeHosts(serviceContext ?? {});
220-
if ((await probePortUsage(port, probeHosts)) === "busy") {
219+
const portUsage = await probePortUsage(port, probeHosts);
220+
if (portUsage !== "free") {
221221
throw new Error(
222-
`Port ${port} is in use but the owning process could not be identified. Run ${formatCliCommand("openclaw gateway status --deep")} to diagnose.`,
222+
portUsage === "busy"
223+
? `Port ${port} is in use but the owning process could not be identified. Run ${formatCliCommand("openclaw gateway status --deep")} to diagnose.`
224+
: `Could not determine whether port ${port} is still in use, so the gateway cannot be confirmed stopped. Run ${formatCliCommand("openclaw gateway status --deep")} to diagnose.`,
223225
);
224226
}
225227
return null;
@@ -542,10 +544,10 @@ export async function runDaemonStop(opts: DaemonLifecycleOptions = {}) {
542544
// An unmanaged run loop keeps its lock port across config edits, so use it
543545
// for discovery the way restart already does; otherwise a valid port
544546
// override makes the running gateway look like it is already stopped.
545-
const lockIdentity = await readActiveGatewayLockIdentity().catch(() => undefined);
546-
const ctx = await resolveGatewayLifecycleContext(service).catch(() => null);
547-
const port = lockIdentity?.port ?? ctx?.port ?? (await resolveGatewayPortFallback());
548-
return await stopGatewayWithoutServiceManager(port, lockIdentity?.pid, ctx ?? undefined);
547+
const lock = await readActiveGatewayLockIdentity().catch(() => undefined);
548+
const ctx = lock ? null : await resolveGatewayLifecycleContext(service).catch(() => null);
549+
const port = lock?.port ?? ctx?.port ?? (await resolveGatewayPortFallback());
550+
return await stopGatewayWithoutServiceManager(port, lock?.pid, ctx ?? undefined);
549551
},
550552
});
551553
}

0 commit comments

Comments
 (0)