Repository navigation
fix: clean up Docker volumes after failed gateway start - #337
Conversation
Closes #17. When openshell gateway start fails, it leaves behind a Docker volume (openshell-cluster-nemoclaw) in a corrupted state. Rerunning onboard hits "Corrupted cluster state" because openshell gateway destroy doesn't remove the volume. Extracts a destroyGateway() helper that removes both the gateway and its Docker volumes. Called before start (pre-cleanup), after start failure, and after health check failure. Adds the same volume cleanup to uninstall.sh and scripts/setup.sh.
Static analysis tests that verify Docker volume cleanup exists in all three code paths (onboard.js, uninstall.sh, setup.sh) and that destroyGateway() is called on pre-start, start failure, and health check failure. Will catch regressions in CI. Refs: #17
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughIntroduces Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@bin/lib/onboard.js`:
- Around line 125-130: The destroyGateway function currently calls run(...) with
xargs -r (GNU-only) and swallows all errors via { ignoreError: true } and ||
true; remove the -r flag so xargs is portable on BSD/macOS, and change
destroyGateway (and its two run invocations that reference GATEWAY_NAME) to
propagate success/failure (e.g., return boolean or throw) instead of always
ignoring errors so callers can detect cleanup failures and show the manual
recovery command; update call sites that assume cleanup always succeeded to
check destroyGateway's result and display the manual docker volume rm
instruction when it fails.
In `@scripts/setup.sh`:
- Around line 77-97: The script uses the GNU-only xargs -r flag in the docker
volume removal pipelines (the commands that start with "docker volume ls -q
--filter \"name=openshell-cluster-nemoclaw\" | xargs -r docker volume rm ...")
which breaks on macOS/BSD; remove the -r flag so the pipeline becomes portable,
keeping the surrounding stderr redirection and the existing cleanup flow that
calls openshell gateway destroy -g nemoclaw, docker volume rm, warn and fail
unchanged to preserve behavior when cleanup is needed.
- Around line 80-85: The current check uses the exit of grep on the piped output
to decide success; instead run the openshell gateway start command and capture
both its exit code and output (e.g., capture output into a variable or tee it to
a temp log), then use the actual exit code of openshell (saved into a variable
like start_status or via PIPESTATUS[0]) to decide whether to run the cleanup;
you may still grep the captured output for logging/diagnostics but ensure the
cleanup block (the openshell gateway destroy and docker volume rm calls) is
executed only when the openshell gateway start exit status indicates failure.
In `@test/gateway-cleanup.test.js`:
- Around line 17-62: Tests only check source text and call counts; add an
integration-style test that actually exercises a failed gateway
start/health-check and asserts the cleanup command runs. Create a new test that
launches the real onboarding process (bin/lib/onboard.js or the bin script) via
child_process.spawn or fork with an env var that forces startGateway to fail (or
put a fake docker binary early in PATH that records invocations), wait for the
failure path, and then assert that destroyGateway was invoked by checking
captured stdout/stderr for the docker volume removal command (or that the fake
docker binary was called with "volume rm openshell-cluster") and/or that
remove_related_docker_volumes / uninstall.sh cleanup logic was executed;
reference startGateway, destroyGateway, remove_related_docker_volumes,
onboard.js, uninstall.sh, and scripts/setup.sh so the test locates and exercises
the real cleanup code rather than just matching strings.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 4efde2a0-67a9-4d4b-bfca-02f5d15477fe
📒 Files selected for processing (4)
bin/lib/onboard.jsscripts/setup.shtest/gateway-cleanup.test.jsuninstall.sh
cv
left a comment
There was a problem hiding this comment.
LGTM — clean fix for the corrupted volume problem. destroyGateway() extracts the cleanup well, all failure paths covered, and the regression tests verify it.
cv
left a comment
There was a problem hiding this comment.
Consistent fix across all three code paths, tests verify the right invariants.
xargs -r is not portable to macOS
The volume cleanup command uses xargs -r (GNU extension — don't run if stdin is empty). macOS xargs doesn't support -r. On macOS with no matching volumes, xargs will call docker volume rm with no arguments, which prints a usage error. Harmless due to || true, but noisy. This applies to onboard.js, setup.sh, and uninstall.sh — all three run on macOS.
Options: pipe through grep . first, use an if guard, or use xargs without -r and accept the usage noise (already suppressed by 2>/dev/null || true).
Minor: possible double-cleanup in uninstall.sh
The new explicit calls to remove_related_docker_containers, remove_related_docker_volumes, and remove_related_docker_images (lines 570-578) run immediately after remove_docker_resources (line 568). If remove_docker_resources already handles some of these, this results in redundant cleanup attempts. Not harmful, but worth verifying there's no overlap.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
scripts/setup.sh (2)
115-120:⚠️ Potential issue | 🟠 MajorGate cleanup on
openshell gateway startexit status, not grep match.Line 115 currently ties failure handling to
grepoutput. Withset -o pipefail, a successful start can still enter cleanup if output stops matching"Gateway|✓|Error|error".Suggested patch
-if ! openshell gateway start "${GATEWAY_ARGS[@]}" 2>&1 | grep -E "Gateway|✓|Error|error"; then +set +e +START_OUTPUT="$(openshell gateway start "${GATEWAY_ARGS[@]}" 2>&1)" +START_RC=$? +set -e +printf '%s\n' "$START_OUTPUT" | grep -E "Gateway|✓|Error|error" || true +if [ "$START_RC" -ne 0 ]; then warn "Gateway start failed. Cleaning up stale state..." openshell gateway destroy -g nemoclaw >/dev/null 2>&1 || true - docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs -r docker volume rm 2>/dev/null || true + docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs docker volume rm 2>/dev/null || true fail "Stale state removed. Please rerun: nemoclaw onboard" fi#!/usr/bin/env bash set -euo pipefail echo "Case 1: command succeeds, grep misses => currently treated as failure" if ! (echo "Starting gateway..." && exit 0) 2>&1 | grep -E "Gateway|✓|Error|error"; then echo "cleanup branch entered" else echo "no cleanup" fi🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@scripts/setup.sh` around lines 115 - 120, The cleanup branch currently triggers based on the grep match rather than the actual exit status of the starts command; change the logic so you run openshell gateway start "${GATEWAY_ARGS[@]}" and check its exit code (e.g., if ! openshell gateway start ...; then cleanup) instead of relying on the pipe to grep for "Gateway|✓|Error|error". If you still need to inspect stdout/stderr for error patterns, capture the command output into a variable (or a temp file), examine that with grep to log or decide additional actions, but always use the process exit status of openshell gateway start as the primary condition for running the cleanup steps that reference openshell gateway destroy and docker volume rm.
112-112:⚠️ Potential issue | 🟠 MajorUse portable
xargsinvocation for volume cleanup.Line 112, Line 118, and Line 130 use GNU-only
xargs -r. On macOS/BSD this can fail silently here (stderr redirected +|| true), leaving stale volumes behind.Suggested patch
-docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs -r docker volume rm 2>/dev/null || true +docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs docker volume rm 2>/dev/null || trueIs `xargs -r` supported on macOS/BSD `xargs`, and is removing `-r` the portable fix when input may be empty?Also applies to: 118-118, 130-130
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@scripts/setup.sh` at line 112, The xargs -r usage in the docker volume cleanup commands (the lines invoking "docker volume ls -q --filter \"name=openshell-cluster-nemoclaw\" | xargs -r docker volume rm") is GNU-only and not portable to macOS/BSD; replace the pipeline with a portability-safe check: capture the output of docker volume ls -q --filter "...", test if it's non-empty (e.g. ids="$(docker volume ls -q --filter 'name=...')" and if [ -n "$ids" ]; then echo "$ids" | xargs docker volume rm; fi) for each occurrence (the three lines that currently use xargs -r) so you avoid relying on -r and don't attempt to remove when there are no volumes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@scripts/setup.sh`:
- Around line 117-119: The script currently runs best-effort cleanup commands
(openshell gateway destroy, docker volume rm via docker volume ls | xargs) with
"|| true" then unconditionally calls fail("Stale state removed. Please rerun:
nemoclaw onboard"), which falsely claims success; update the cleanup blocks
around the openshell gateway destroy / docker volume ls | xargs sequences and
the duplicate block later (same pattern) to detect failures instead of
swallowing them: capture each command's exit status (or run them without "||
true"), aggregate any failures, and only emit a success message if all cleanup
steps succeeded — otherwise print a clear "Attempted to remove stale state;
manual recovery steps:" message listing the exact commands that failed (or the
full commands to run manually) and avoid calling fail with the misleading "Stale
state removed..." text.
---
Duplicate comments:
In `@scripts/setup.sh`:
- Around line 115-120: The cleanup branch currently triggers based on the grep
match rather than the actual exit status of the starts command; change the logic
so you run openshell gateway start "${GATEWAY_ARGS[@]}" and check its exit code
(e.g., if ! openshell gateway start ...; then cleanup) instead of relying on the
pipe to grep for "Gateway|✓|Error|error". If you still need to inspect
stdout/stderr for error patterns, capture the command output into a variable (or
a temp file), examine that with grep to log or decide additional actions, but
always use the process exit status of openshell gateway start as the primary
condition for running the cleanup steps that reference openshell gateway destroy
and docker volume rm.
- Line 112: The xargs -r usage in the docker volume cleanup commands (the lines
invoking "docker volume ls -q --filter \"name=openshell-cluster-nemoclaw\" |
xargs -r docker volume rm") is GNU-only and not portable to macOS/BSD; replace
the pipeline with a portability-safe check: capture the output of docker volume
ls -q --filter "...", test if it's non-empty (e.g. ids="$(docker volume ls -q
--filter 'name=...')" and if [ -n "$ids" ]; then echo "$ids" | xargs docker
volume rm; fi) for each occurrence (the three lines that currently use xargs -r)
so you avoid relying on -r and don't attempt to remove when there are no
volumes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3aa03a49-975d-4e56-826f-886a576f758b
📒 Files selected for processing (3)
bin/lib/onboard.jsscripts/setup.shuninstall.sh
🚧 Files skipped from review as they are similar to previous changes (2)
- uninstall.sh
- bin/lib/onboard.js
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
test/gateway-cleanup.test.js (1)
17-22: Assertion is weak—strings could appear anywhere in the file.The test passes if
"docker volume"and"openshell-cluster"appear anywhere inonboard.js, not necessarily withindestroyGateway(). Consider tightening the assertion to match within the actual function body.♻️ Suggested improvement
it("onboard.js: destroyGateway() removes Docker volumes", () => { const content = fs.readFileSync(path.join(ROOT, "bin/lib/onboard.js"), "utf-8"); - expect( - content.includes("docker volume") && content.includes("openshell-cluster"), - ).toBe(true); + // Extract destroyGateway function and verify volume cleanup is inside it + const destroyGwMatch = content.match(/(?:async\s+)?function\s+destroyGateway[\s\S]*?^}/m); + expect(destroyGwMatch).toBeTruthy(); + expect(destroyGwMatch[0]).toMatch(/docker volume/); + expect(destroyGwMatch[0]).toMatch(/openshell-cluster/); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/gateway-cleanup.test.js` around lines 17 - 22, The current test checks for literal strings anywhere in the file which is too broad; update the test in gateway-cleanup.test.js to assert those strings appear inside the destroyGateway function body specifically by extracting that function (e.g., locate the function declaration/assignment for destroyGateway and capture its source via a regex or an AST parse) and then assert the captured body contains "docker volume" and "openshell-cluster"; ensure the test fails if the function body does not include both strings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/gateway-cleanup.test.js`:
- Around line 24-36: The regex used to extract the async function startGateway
is brittle and can stop at the first unindented closing brace, truncating the
function and missing destroyGateway() calls; replace the regex with a more
robust parser approach (or a balanced-brace search) to reliably capture the
entire startGateway function body when scanning onboard.js, then recount
destroyGateway() occurrences inside that full body; also avoid reading
onboard.js twice by reusing the previously read content variable (content)
instead of calling fs.readFileSync a second time.
---
Nitpick comments:
In `@test/gateway-cleanup.test.js`:
- Around line 17-22: The current test checks for literal strings anywhere in the
file which is too broad; update the test in gateway-cleanup.test.js to assert
those strings appear inside the destroyGateway function body specifically by
extracting that function (e.g., locate the function declaration/assignment for
destroyGateway and capture its source via a regex or an AST parse) and then
assert the captured body contains "docker volume" and "openshell-cluster";
ensure the test fails if the function body does not include both strings.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e48ef391-c346-438c-a8b6-6b90f1b1a31c
📒 Files selected for processing (1)
test/gateway-cleanup.test.js
Merge origin/main and resolve conflicts in bin/lib/onboard.js. Replace xargs -r (GNU-only) with a macOS-compatible pattern that guards against empty stdin: grep . && ... | xargs docker volume rm. Remove duplicate remove_related_docker_volumes definition and calls from uninstall.sh that conflicted with main's implementation.
There was a problem hiding this comment.
♻️ Duplicate comments (2)
bin/lib/onboard.js (2)
1346-1350:⚠️ Potential issue | 🟡 MinorSame concern as gateway start failure path.
This health-check failure branch also prints "Stale state removed" unconditionally. The same fix (checking cleanup success or showing the manual recovery command) applies here.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@bin/lib/onboard.js` around lines 1346 - 1350, The health-check failure branch unconditionally prints "Stale state removed" after calling destroyGateway(); change it to check the result or catch errors from destroyGateway (or inspect a boolean/throwing behavior) and only print "Stale state removed. Please rerun: nemoclaw onboard" when cleanup actually succeeded; if destroyGateway fails, log the error and instead print a clear manual recovery command (e.g., rerun or specific cleanup instructions). Locate the block using the variables i (equal to 4) and the function destroyGateway to implement a try/catch or conditional around the cleanup and adjust the console.error messages accordingly.
1331-1337:⚠️ Potential issue | 🟡 MinorUnconditional "Stale state removed" message may mislead users if cleanup fails.
Since
destroyGateway()suppresses errors and returns void, line 1335 claims cleanup succeeded even when it may not have. If Docker volumes couldn't be removed (e.g., in use by another process), the user will retry and encounter the same "Corrupted cluster state" error.Per the PR's acceptance criteria: "If automatic cleanup cannot be performed, the error message must include the exact recovery command."
Consider having
destroyGateway()return a boolean or checking for remaining volumes, then conditionally printing the manual command:docker volume rm openshell-cluster-nemoclaw🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@bin/lib/onboard.js` around lines 1331 - 1337, The cleanup message is unconditional even though destroyGateway() currently suppresses errors; change destroyGateway() to return a success boolean (or throw on failure) and update the startup error path that uses startResult to check that return value (or catch the thrown error) before printing "Stale state removed"; if destroyGateway() reports failure, print a clear recovery instruction including the exact docker command (e.g., docker volume rm openshell-cluster-nemoclaw) and any relevant guidance, otherwise print the success message and exit as before — update references in this block that call destroyGateway(), runOpenshell, startResult, and gatewayEnv accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@bin/lib/onboard.js`:
- Around line 1346-1350: The health-check failure branch unconditionally prints
"Stale state removed" after calling destroyGateway(); change it to check the
result or catch errors from destroyGateway (or inspect a boolean/throwing
behavior) and only print "Stale state removed. Please rerun: nemoclaw onboard"
when cleanup actually succeeded; if destroyGateway fails, log the error and
instead print a clear manual recovery command (e.g., rerun or specific cleanup
instructions). Locate the block using the variables i (equal to 4) and the
function destroyGateway to implement a try/catch or conditional around the
cleanup and adjust the console.error messages accordingly.
- Around line 1331-1337: The cleanup message is unconditional even though
destroyGateway() currently suppresses errors; change destroyGateway() to return
a success boolean (or throw on failure) and update the startup error path that
uses startResult to check that return value (or catch the thrown error) before
printing "Stale state removed"; if destroyGateway() reports failure, print a
clear recovery instruction including the exact docker command (e.g., docker
volume rm openshell-cluster-nemoclaw) and any relevant guidance, otherwise print
the success message and exit as before — update references in this block that
call destroyGateway(), runOpenshell, startResult, and gatewayEnv accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a9403e57-95b6-40d6-a526-f3b6d5a4c470
📒 Files selected for processing (2)
bin/lib/onboard.jsscripts/setup.sh
🚧 Files skipped from review as they are similar to previous changes (1)
- scripts/setup.sh
The e2e gateway isolation test used head -21 to source the PATH export from nemoclaw-start.sh. The capsh fix (#929) added lines, pushing PATH past line 21. Use grep to find the export line dynamically.
…com/NVIDIA/NemoClaw into fix/issue-17-gateway-volume-cleanup
* fix: clean up Docker volumes after failed gateway start Closes NVIDIA#17. When openshell gateway start fails, it leaves behind a Docker volume (openshell-cluster-nemoclaw) in a corrupted state. Rerunning onboard hits "Corrupted cluster state" because openshell gateway destroy doesn't remove the volume. Extracts a destroyGateway() helper that removes both the gateway and its Docker volumes. Called before start (pre-cleanup), after start failure, and after health check failure. Adds the same volume cleanup to uninstall.sh and scripts/setup.sh. * test: add regression tests for gateway volume cleanup Static analysis tests that verify Docker volume cleanup exists in all three code paths (onboard.js, uninstall.sh, setup.sh) and that destroyGateway() is called on pre-start, start failure, and health check failure. Will catch regressions in CI. Refs: NVIDIA#17 * fix: convert assert.ok to vitest expect in policies.test.js * fix: convert node:test to vitest in gateway-cleanup.test.js * fix(test): use grep instead of hardcoded line count for PATH check The e2e gateway isolation test used head -21 to source the PATH export from nemoclaw-start.sh. The capsh fix (NVIDIA#929) added lines, pushing PATH past line 21. Use grep to find the export line dynamically. --------- Co-authored-by: Carlos Villela <[email protected]>
Closes #17.
Summary
destroyGateway()helper that removes both the gateway and its Docker volumes (openshell-cluster-nemoclaw)uninstall.shandscripts/setup.shProblem
When
openshell gateway startfails, it leaves behind a Docker volume (openshell-cluster-nemoclaw) in a corrupted state.openshell gateway destroydoesn't remove volumes. Rerunning onboard hits "Corrupted cluster state" with no guidance — users must manually rundocker volume rm openshell-cluster-nemoclaw.Fix
destroyGateway()callsopenshell gateway destroythen removes matching Docker volumes viadocker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs -r docker volume rm. On failure, it prints "Stale state removed. Please rerun: nemoclaw onboard".Test plan
uninstall.sh: volume cleanup worksSummary by CodeRabbit