Skip to content

Commit 6621eac

Browse files
Schimuneckcursoragentsallyom
authored
fix: gateway stop throws when port is busy without identified owner (#126085)
* fix: gateway stop throws when port is busy without identified owner When `openclaw gateway stop` cannot find the owning process via lsof or the lock file, probe the port using gateway-configured bind hosts (resolveGatewayServiceProbeHosts) before reporting success. If the port is provably busy on a configured interface, throw with actionable guidance (`openclaw gateway status --deep`) instead of silently returning. Uses gateway-scoped probe hosts to avoid false positives from unrelated listeners on different interfaces (e.g. another process on 127.0.0.2 does not trigger an error when the gateway binds 127.0.0.1). Co-authored-by: Cursor <[email protected]> * fix: thread selected service context into gateway stop port probe The port probe in stopGatewayWithoutServiceManager passed an empty object to resolveGatewayServiceProbeHosts, causing it to read the caller's process.env instead of the selected service's command environment. A gateway running under a different profile or state directory was probed against the wrong bind configuration. Inline the probe logic from the deleted lifecycle-port-probe.ts wrapper into the lifecycle caller, which already resolves the service command and merged environment. Add regression coverage for the differing-context case. Production LOC: -19 (lifecycle.ts -1, deleted wrapper -18). Co-authored-by: Cursor <[email protected]> * fix: load gateway port from selected service config for stop probe resolveGatewayLifecycleContext used readBestEffortConfig() which always reads config from process.env. When the selected service has a different state directory with its own gateway.port, the stop path would probe the caller's port instead, producing false "not loaded" results. Use createConfigIO({ env: mergedEnv }) to load config through the merged service environment — the same pattern resolveGatewayServiceProbeHosts already uses for bind host resolution. Compress mock infrastructure to stay within max-lines limits. Production: net -3 lines. Tests: net +27 lines. Co-authored-by: Cursor <[email protected]> * fix(gateway): harden unowned stop verification Signed-off-by: sallyom <[email protected]> --------- Signed-off-by: sallyom <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: sallyom <[email protected]>
1 parent ee7fe7b commit 6621eac

2 files changed

Lines changed: 142 additions & 119 deletions

File tree

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

Lines changed: 101 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -37,40 +37,40 @@ const findVerifiedGatewayListenerPidsOnPortSync = vi.fn<(port: number) => number
3737
const signalVerifiedGatewayPidSync = vi.fn<(pid: number, signal: "SIGTERM" | "SIGUSR1") => void>();
3838
const writeGatewayRestartIntentSync = vi.fn();
3939
const clearGatewayRestartIntentSync = vi.fn();
40+
const resolveGatewayServiceProbeHosts = vi.fn(
41+
async (_params: { env?: Record<string, string | undefined>; command?: unknown }) =>
42+
["127.0.0.1"] as readonly string[],
43+
);
44+
const probePortUsage = vi.fn(
45+
async (_port: number, _hosts?: readonly string[]) => "free" as "free" | "busy" | "unknown",
46+
);
4047
const formatGatewayPidList = vi.fn<(pids: number[]) => string>((pids) => pids.join(", "));
41-
const probeGateway = vi.fn<
42-
(opts: {
43-
url: string;
44-
auth?: { token?: string; password?: string };
45-
timeoutMs: number;
46-
}) => Promise<{
47-
ok: boolean;
48-
configSnapshot: unknown;
49-
}>
50-
>();
48+
const probeGateway =
49+
vi.fn<
50+
(opts: {
51+
url: string;
52+
auth?: { token?: string; password?: string };
53+
timeoutMs: number;
54+
}) => Promise<{ ok: boolean; configSnapshot: unknown }>
55+
>();
5156
const callGatewayCli = vi.fn();
5257
const isRestartEnabled = vi.fn<(config?: { commands?: unknown }) => boolean>(() => true);
5358
const loadConfig = vi.hoisted(() => vi.fn(() => ({})));
59+
const createConfigIO = vi.hoisted(() =>
60+
vi.fn((_opts?: { env?: Record<string, string | undefined>; observe?: boolean }) => ({
61+
readBestEffortConfig: async () => loadConfig(),
62+
})),
63+
);
5464
const readActiveGatewayLockPort = vi.hoisted(() => vi.fn<() => Promise<number | undefined>>());
65+
type LockIdentity = { pid: number; ownerId?: string; createdAt: string; port: number };
5566
const readActiveGatewayLockIdentity = vi.hoisted(() =>
56-
vi.fn<
57-
() => Promise<
58-
| {
59-
pid: number;
60-
ownerId?: string;
61-
createdAt: string;
62-
port: number;
63-
}
64-
| undefined
65-
>
66-
>(),
67+
vi.fn<() => Promise<LockIdentity | undefined>>(),
6768
);
6869
const recoverInstalledLaunchAgent = vi.hoisted(() => vi.fn());
6970
const repairLoadedGatewayServiceForStart = vi.hoisted(() => vi.fn());
71+
type SystemdScope = { scope: "user" | "system"; unitName: string; unitPath: string };
7072
const findInstalledSystemdGatewayScope = vi.hoisted(() =>
71-
vi.fn<() => Promise<{ scope: "user" | "system"; unitName: string; unitPath: string } | null>>(
72-
async () => null,
73-
),
73+
vi.fn<() => Promise<SystemdScope | null>>(async () => null),
7474
);
7575
const restartSystemdService = vi.hoisted(() =>
7676
vi.fn<() => Promise<{ outcome: "completed" }>>(async () => ({ outcome: "completed" })),
@@ -94,6 +94,8 @@ vi.mock("../../config/config.js", () => ({
9494
resolveGatewayPort: (cfg?: unknown, env?: unknown) => resolveGatewayPort(cfg, env),
9595
}));
9696

97+
vi.mock("../../config/io.js", () => ({ createConfigIO }));
98+
9799
vi.mock("../../config/paths.js", () => ({
98100
isDefaultInstallIdentity: () => isDefaultInstallIdentity(),
99101
resolveNativeServiceProfileConflict: () => null,
@@ -106,32 +108,24 @@ vi.mock("../../infra/gateway-processes.js", () => ({
106108
formatGatewayPidList: (pids: number[]) => formatGatewayPidList(pids),
107109
}));
108110

109-
vi.mock("../../infra/gateway-lock.js", () => ({
110-
readActiveGatewayLockPort: () => readActiveGatewayLockPort(),
111-
readActiveGatewayLockIdentity: () => readActiveGatewayLockIdentity(),
112-
isSameGatewayLockIdentity: (
113-
previous: { ownerId?: string; pid: number; createdAt: string; startTime?: number },
114-
current: { ownerId?: string; pid: number; createdAt: string; startTime?: number },
115-
) =>
116-
previous.ownerId && current.ownerId
117-
? previous.ownerId === current.ownerId
118-
: previous.pid === current.pid &&
119-
previous.createdAt === current.createdAt &&
120-
previous.startTime === current.startTime,
121-
}));
111+
vi.mock("../../infra/gateway-lock.js", () => {
112+
type I = { ownerId?: string; pid: number; createdAt: string; startTime?: number };
113+
return {
114+
readActiveGatewayLockPort: () => readActiveGatewayLockPort(),
115+
readActiveGatewayLockIdentity: () => readActiveGatewayLockIdentity(),
116+
isSameGatewayLockIdentity: (a: I, b: I) =>
117+
a.ownerId && b.ownerId
118+
? a.ownerId === b.ownerId
119+
: a.pid === b.pid && a.createdAt === b.createdAt && a.startTime === b.startTime,
120+
};
121+
});
122122

123123
vi.mock("../../infra/restart-intent.js", () => ({
124124
writeGatewayRestartIntentSync: (params: unknown) => writeGatewayRestartIntentSync(params),
125125
clearGatewayRestartIntentSync: () => clearGatewayRestartIntentSync(),
126126
}));
127127

128-
vi.mock("../../gateway/probe.js", () => ({
129-
probeGateway: (opts: {
130-
url: string;
131-
auth?: { token?: string; password?: string };
132-
timeoutMs: number;
133-
}) => probeGateway(opts),
134-
}));
128+
vi.mock("../../gateway/probe.js", () => ({ probeGateway }));
135129

136130
vi.mock("../../gateway/call.js", () => ({
137131
callGatewayCli: (opts: unknown) => callGatewayCli(opts),
@@ -172,6 +166,10 @@ vi.mock("./lifecycle-audit.js", () => ({
172166
createGatewayLifecycleMutationAudit(params),
173167
}));
174168

169+
vi.mock("../../daemon/gateway-service-probe-hosts.js", () => ({ resolveGatewayServiceProbeHosts }));
170+
171+
vi.mock("../../infra/ports-probe.js", () => ({ probePortUsage }));
172+
175173
vi.mock("./restart-health.js", () => ({
176174
DEFAULT_RESTART_HEALTH_ATTEMPTS: 120,
177175
DEFAULT_RESTART_HEALTH_DELAY_MS: 500,
@@ -265,13 +263,18 @@ describe("runDaemonRestart health checks", () => {
265263
callGatewayCli.mockReset();
266264
isRestartEnabled.mockReset();
267265
loadConfig.mockReset();
266+
createConfigIO
267+
.mockReset()
268+
.mockImplementation(() => ({ readBestEffortConfig: async () => loadConfig() }));
268269
readActiveGatewayLockPort.mockReset().mockResolvedValue(undefined);
269270
readActiveGatewayLockIdentity.mockReset();
270271
recoverInstalledLaunchAgent.mockReset().mockResolvedValue(null);
271272
repairLoadedGatewayServiceForStart.mockReset();
272273
isTerminalInteractive.mockReset().mockReturnValue(true);
273274
appendGatewayLifecycleAudit.mockClear();
274275
createGatewayLifecycleMutationAudit.mockClear();
276+
resolveGatewayServiceProbeHosts.mockReset().mockResolvedValue(["127.0.0.1"]);
277+
probePortUsage.mockReset().mockResolvedValue("free");
275278
isDefaultInstallIdentity.mockReset().mockReturnValue(true);
276279

277280
service.readCommand.mockResolvedValue({
@@ -784,6 +787,7 @@ describe("runDaemonRestart health checks", () => {
784787
expect(appendGatewayLifecycleAudit).toHaveBeenCalledWith(
785788
expect.objectContaining({ action: "stop", mode: "sigterm", pid: 4200 }),
786789
);
790+
expect(service.readCommand).not.toHaveBeenCalled();
787791
expect(outcome).toEqual({
788792
result: "stopped",
789793
message: "Gateway stop signal sent to unmanaged process on port 18789: 4200.",
@@ -802,7 +806,6 @@ describe("runDaemonRestart health checks", () => {
802806

803807
expect(findVerifiedGatewayListenerPidsOnPortSync).toHaveBeenCalledWith(39_471);
804808
expect(signalVerifiedGatewayPidSync).toHaveBeenCalledWith(4300, "SIGTERM");
805-
expect(service.readCommand).not.toHaveBeenCalled();
806809
});
807810

808811
it("signals a single unmanaged gateway process on restart", async () => {
@@ -1029,15 +1032,19 @@ describe("runDaemonRestart health checks", () => {
10291032
);
10301033
});
10311034

1032-
it("delegates system-scope restart to systemctl without unmanaged signaling when root (openclaw#87577)", async () => {
1035+
function mockSystemdScope(unit: string) {
10331036
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
10341037
findInstalledSystemdGatewayScope.mockResolvedValue({
1035-
scope: "system",
1036-
unitName: "openclaw.service",
1037-
unitPath: "/etc/systemd/system/openclaw.service",
1038+
scope: "system" as const,
1039+
unitName: unit,
1040+
unitPath: `/etc/systemd/system/${unit}`,
10381041
});
1039-
restartSystemdService.mockResolvedValue({ outcome: "completed" });
10401042
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([4200]);
1043+
}
1044+
1045+
it("delegates system-scope restart to systemctl without unmanaged signaling when root (openclaw#87577)", async () => {
1046+
mockSystemdScope("openclaw.service");
1047+
restartSystemdService.mockResolvedValue({ outcome: "completed" });
10411048
mockUnmanagedRestart();
10421049

10431050
await expect(runDaemonRestart({ json: true })).resolves.toBe(true);
@@ -1048,18 +1055,12 @@ describe("runDaemonRestart health checks", () => {
10481055
});
10491056

10501057
it("surfaces systemd sudo guidance and never signals when restarting a system-scope unit as non-root (openclaw#87577)", async () => {
1051-
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
1052-
findInstalledSystemdGatewayScope.mockResolvedValue({
1053-
scope: "system",
1054-
unitName: "openclaw.service",
1055-
unitPath: "/etc/systemd/system/openclaw.service",
1056-
});
1058+
mockSystemdScope("openclaw.service");
10571059
restartSystemdService.mockRejectedValue(
10581060
new Error(
10591061
"openclaw.service is a system-scope unit (/etc/systemd/system/openclaw.service); run `sudo systemctl restart openclaw.service` to restart it",
10601062
),
10611063
);
1062-
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([4200]);
10631064
mockUnmanagedRestart();
10641065

10651066
await expect(runDaemonRestart({ json: true })).rejects.toThrow(
@@ -1071,14 +1072,8 @@ describe("runDaemonRestart health checks", () => {
10711072
});
10721073

10731074
it("delegates system-scope stop to systemctl without unmanaged signaling when root (openclaw#87577)", async () => {
1074-
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
1075-
findInstalledSystemdGatewayScope.mockResolvedValue({
1076-
scope: "system",
1077-
unitName: "openclaw-gateway.service",
1078-
unitPath: "/etc/systemd/system/openclaw-gateway.service",
1079-
});
1075+
mockSystemdScope("openclaw-gateway.service");
10801076
stopSystemdService.mockResolvedValue(undefined);
1081-
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([4200]);
10821077
await expect(runUnmanagedStop()).resolves.toEqual(
10831078
expect.objectContaining({ result: "stopped" }),
10841079
);
@@ -1087,33 +1082,62 @@ describe("runDaemonRestart health checks", () => {
10871082
});
10881083

10891084
it("surfaces systemd sudo guidance and never signals when stopping a system-scope unit as non-root (openclaw#87577)", async () => {
1090-
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
1091-
findInstalledSystemdGatewayScope.mockResolvedValue({
1092-
scope: "system",
1093-
unitName: "openclaw-gateway.service",
1094-
unitPath: "/etc/systemd/system/openclaw-gateway.service",
1095-
});
1085+
mockSystemdScope("openclaw-gateway.service");
10961086
stopSystemdService.mockRejectedValue(
10971087
new Error(
10981088
"openclaw-gateway.service is a system-scope unit (/etc/systemd/system/openclaw-gateway.service); run `sudo systemctl stop openclaw-gateway.service` to stop it",
10991089
),
11001090
);
1101-
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([4200]);
11021091
await expect(runUnmanagedStop()).rejects.toThrow(
11031092
/sudo systemctl stop openclaw-gateway\.service/,
11041093
);
11051094
expect(stopSystemdService).toHaveBeenCalled();
11061095
expect(signalVerifiedGatewayPidSync).not.toHaveBeenCalled();
11071096
});
11081097

1109-
it("skips unmanaged signaling for pids that are not live gateway processes", async () => {
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+
);
1117+
1118+
it("resolves port and probe hosts from selected service config/env (no --port arg)", async () => {
1119+
const serviceCommand = {
1120+
programArguments: ["openclaw", "gateway"],
1121+
environment: { OPENCLAW_STATE_DIR: "/tmp/service-state" },
1122+
};
1123+
service.readCommand.mockResolvedValue(serviceCommand);
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;
1132+
});
11101133
findVerifiedGatewayListenerPidsOnPortSync.mockReturnValue([]);
11111134
readActiveGatewayLockIdentity.mockResolvedValue(undefined);
1135+
probePortUsage.mockResolvedValue("busy");
11121136

1113-
const outcome = await runUnmanagedStop();
1114-
1115-
expect(signalVerifiedGatewayPidSync).not.toHaveBeenCalled();
1116-
expect(appendGatewayLifecycleAudit).not.toHaveBeenCalled();
1117-
expect(outcome).toBeNull();
1137+
await expect(runUnmanagedStop()).rejects.toThrow(/Port 19000/);
1138+
expect(resolveGatewayServiceProbeHosts).toHaveBeenCalledWith(
1139+
expect.objectContaining({ command: serviceCommand }),
1140+
);
1141+
expect(probePortUsage).toHaveBeenCalledWith(19000, ["127.0.0.1"]);
11181142
});
11191143
});

0 commit comments

Comments
 (0)