Skip to content

fix(gateway): exit 0 on EADDRINUSE when healthy OpenClaw gateway is already running - #44476

Closed
hydro13 wants to merge 1 commit into
openclaw:mainfrom
hydro13:fix/gateway-eaddrinuse-exit-code
Closed

hydro13 wants to merge 1 commit into
openclaw:mainfrom
hydro13:fix/gateway-eaddrinuse-exit-code

Conversation

@hydro13

@hydro13 hydro13 commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When openclaw gateway run hits EADDRINUSE, it exits with code 1. Under systemd/launchd with Restart=on-failure, this creates a tight crash-loop.

Root Cause

GatewayLockError on port conflict always exited non-zero, even when an already-healthy OpenClaw gateway was listening on that port.

Fix

On EADDRINUSE, probe the gateway using the correct bind/TLS-aware URL with resolved auth credentials. Exit 0 only when a healthy OpenClaw instance is confirmed. Exit 1 for foreign processes or failed probes.

Probe handles all auth modes:

  • shared-secret (token/password): forwarded directly
  • trusted-proxy: synthetic proxy headers derived from config instead of shared-secret credentials
  • TLS with self-signed cert: fingerprint loaded from loadGatewayTlsRuntime and pinned for the probe

Also fixes a pre-existing type error in src/cli/update-cli.test.ts.

Supersedes #29499 — thanks @BlueBirdBack for identifying the issue.


AI-assisted

  • Built with Claude (Kees/OpenClaw) + Codex
  • Fully tested: VM gates (pnpm build + check + vitest gateway-cli + probe)
  • Author understands what the code does
  • Codex review findings addressed and resolved

@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Mar 13, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Mar 13, 2026
@hydro13
hydro13 force-pushed the fix/gateway-eaddrinuse-exit-code branch from 1223e1f to 2349043 Compare March 13, 2026 00:24

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1223e1fe8f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/cli/gateway-cli/run.ts Resolved
@greptile-apps

greptile-apps Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a systemd/launchd crash-loop problem where openclaw gateway run would exit with code 1 on EADDRINUSE, even when the port was already held by a healthy OpenClaw gateway. The fix adds a live probe before deciding the exit code: on EADDRINUSE, the new probeHealthyExistingGateway function generates TLS/bind-mode-aware WebSocket URLs (respecting GatewayClient's plaintext ws:// security policy via isSecureWebSocketUrl), then attempts a credentialed probeGateway call against each candidate URL. Exit 0 is returned only when a probe confirms ok: true; all other cases (foreign process, probe timeout, no reachable URL) continue to exit 1.

Key points:

  • The EADDRINUSE detection relies on (err as GatewayLockError).cause.code, which is correctly set by src/gateway/server/http-listen.ts when bind retries are exhausted — the code path is valid.
  • Security is preserved: private-IP plaintext ws:// URLs are filtered out unless the OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1 break-glass env var is set.
  • The loopback address is always appended as a fallback probe target, so bind: "loopback" and bind: "lan"/"custom" without TLS all have at least one probe candidate.
  • Four new targeted tests cover TLS+custom-bind, loopback fallback, plaintext skip, and break-glass override scenarios.
  • src/cli/update-cli.test.ts contains an unexplained deletion: the entire "uses OPENCLAW_UPDATE_PACKAGE_SPEC for package updates" test is removed alongside the null-guard type fix. The deleted test covers an important env-var-driven package spec override and its removal is not mentioned in the PR description.

Confidence Score: 4/5

  • The gateway fix is safe to merge; the unexplained deletion of a test in update-cli.test.ts should be clarified before merging.
  • The core EADDRINUSE probe logic is correct, well-tested, and secure. The cause detection aligns with how http-listen.ts actually constructs GatewayLockError. The security filter (non-loopback plaintext ws:// blocked by default) is properly enforced. The only concern lowering the score is the silent deletion of the OPENCLAW_UPDATE_PACKAGE_SPEC test in update-cli.test.ts — it removes behavioral coverage for an unrelated feature with no stated justification.
  • src/cli/update-cli.test.ts — deletion of the OPENCLAW_UPDATE_PACKAGE_SPEC test needs explanation or restoration.

Comments Outside Diff (1)

  1. src/cli/update-cli.test.ts, line 513-530 (link)

    Unrelated test deleted without explanation

    This PR removes the entire "uses OPENCLAW_UPDATE_PACKAGE_SPEC for package updates" test block as part of a "type error fix", but the actual TypeScript fix is confined to the null-guard change above (updateCall && typeof updateCall[1]). The deleted test independently verifies that setting OPENCLAW_UPDATE_PACKAGE_SPEC overrides the npm package spec — an important behavioral contract with no other coverage.

    If OPENCLAW_UPDATE_PACKAGE_SPEC handling was intentionally removed from the implementation, the removal should be documented in the PR description. If not, the test should be kept (the type error is not inside this test block).

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/cli/update-cli.test.ts
Line: 513-530

Comment:
**Unrelated test deleted without explanation**

This PR removes the entire `"uses OPENCLAW_UPDATE_PACKAGE_SPEC for package updates"` test block as part of a "type error fix", but the actual TypeScript fix is confined to the null-guard change above (`updateCall && typeof updateCall[1]`). The deleted test independently verifies that setting `OPENCLAW_UPDATE_PACKAGE_SPEC` overrides the npm package spec — an important behavioral contract with no other coverage.

If `OPENCLAW_UPDATE_PACKAGE_SPEC` handling was intentionally removed from the implementation, the removal should be documented in the PR description. If not, the test should be kept (the type error is not inside this test block).

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 3b40222

@hydro13

hydro13 commented Mar 13, 2026

Copy link
Copy Markdown
Contributor Author

CI failures are pre-existing upstream issues, not caused by this PR:

  • compat-node22: plugin version mismatch (@openclaw/ollama-provider 2026.3.12 vs release base 2026.3.11) — exists on main before this PR
  • checks-windows: wrapWebContent export missing in vitest mock for isolated-agent/run.payload-fallbacks.test.ts — pre-existing test infrastructure issue

This PR only touches src/cli/gateway-cli/run.ts, src/cli/gateway-cli.coverage.test.ts, and src/cli/update-cli.test.ts. All gateway-cli focused tests pass (10/10).

@hydro13
hydro13 force-pushed the fix/gateway-eaddrinuse-exit-code branch from 2349043 to 869537e Compare March 13, 2026 01:35
@hydro13

hydro13 commented Mar 13, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 869537edd4: resolveGatewayLockProbeUrls() now filters candidate URLs through isSecureWebSocketUrl() with the same OPENCLAW_ALLOW_INSECURE_PRIVATE_WS break-glass policy as GatewayClient. Non-loopback plaintext ws:// URLs are no longer enqueued by default, so probes stay consistent with the client's security model.

@hydro13 hydro13 closed this Mar 13, 2026
@hydro13
hydro13 force-pushed the fix/gateway-eaddrinuse-exit-code branch from 869537e to e951a42 Compare March 13, 2026 01:38

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 869537edd4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/cli/gateway-cli/run.ts Resolved
@hydro13 hydro13 reopened this Mar 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b402228e5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/cli/gateway-cli/run.ts Resolved
@hydro13

hydro13 commented Mar 13, 2026

Copy link
Copy Markdown
Contributor Author

The 3 remaining CI failures all point to the same test: src/hooks/loader.test.ts > sanitizes control characters in loader error logs (ANSI escape code assertion). This file is not touched by this PR. Looks like a flaky environment-dependent test — upstream/main at e951a42bcb passes clean with 0 failures on the same runners. Requesting a re-run.

@hydro13
hydro13 force-pushed the fix/gateway-eaddrinuse-exit-code branch 2 times, most recently from 3bd9ba0 to 272898c Compare March 13, 2026 08:17
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L and removed size: M labels Mar 13, 2026
@hydro13
hydro13 force-pushed the fix/gateway-eaddrinuse-exit-code branch from 272898c to 3fe3862 Compare March 13, 2026 08:25

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3fe3862f3c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +559 to +562
token: resolvedAuthMode === "trusted-proxy" ? undefined : tokenValue,
password: resolvedAuthMode === "trusted-proxy" ? undefined : passwordValue,
tlsFingerprint: await resolveGatewayLockProbeTlsFingerprint({ cfg, tlsEnabled }),
headers: resolveTrustedProxyProbeHeaders(resolvedAuth),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Probe trusted-proxy listeners through a trusted source

This probe path still dials the gateway directly from the local process and only injects headers, but trusted-proxy auth also enforces source IP trust (authorizeTrustedProxy rejects when req.socket.remoteAddress is not in gateway.trustedProxies in src/gateway/auth.ts:337-339). In deployments where the trusted proxy is a different host (common with bind=lan/custom), these probes will always return ok: false, so openclaw gateway run still exits 1 on EADDRINUSE and supervised restart loops continue.

Useful? React with 👍 / 👎.

pickLanHost: () => pickPrimaryLanIPv4() ?? null,
});
if (bindUrl && "url" in bindUrl) {
addProbeUrl(bindUrl.url);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize IPv6 custom bind URLs before probing

The bind-aware probe takes resolveGatewayBindUrl output as-is, but for gateway.bind=custom with an IPv6 host (for example ::1) that helper emits ws://::1:<port> (src/shared/gateway-bind-url.ts:23), which is not a valid URL and gets filtered out by isSecureWebSocketUrl. In that setup the probe falls back to 127.0.0.1 only, so an already-healthy gateway bound to IPv6 loopback is treated as unhealthy and startup still exits 1 on port conflict.

Useful? React with 👍 / 👎.

@hydro13
hydro13 force-pushed the fix/gateway-eaddrinuse-exit-code branch from 3fe3862 to cf517c9 Compare March 13, 2026 08:36
@frankekn frankekn self-assigned this Mar 13, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jul 8, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thanks @hydro13. Closing as superseded by the shipped fix in 9289a50.

Current main handles the same lock and EADDRINUSE restart-loop failure with bounded, supervisor-aware /healthz probing and focused tests. Healthy launchd or unmanaged duplicates keep the existing gateway in control, while systemd deliberately exits 78 to match RestartPreventExitStatus=78 and stop Restart=always loops. This behavior shipped in v2026.5.2.

The conflicting branch would now regress that systemd contract. Its generic WebSocket probe also synthesizes trusted-proxy identity headers and carries unrelated update-test deletion. If a current release still loops, please open a focused issue with the supervisor or unit configuration and redacted startup logs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants