Repository navigation
feat: add KVM pre-flight check and cleanup verification - #47
Conversation
Add /dev/kvm accessibility check to validateEnvironment() so vmsan create/start fails early with a clear error when KVM is unavailable. Add verifyCleanup() to detect leaked network resources (TAP devices, namespaces, veth pairs) after teardown in stop/remove flows, logging warnings for any orphaned resources.
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
📝 WalkthroughWalkthroughThe changes introduce KVM pre-flight validation during environment setup by checking read/write access to /dev/kvm, throwing an error if unavailable. Additionally, a cleanup verification function detects lingering network resources (TAP devices, network namespaces, veth interfaces) after VM stop/remove operations and logs any detected leaks. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/services/vm.ts (1)
791-797: Skip the second leak scan after a forced stop.When
remove()force-stops a running VM,stop()already emits the same cleanup warnings on Lines 659-662. Re-runningverifyCleanup()here duplicates warnings for the same leftovers.♻️ Minimal way to avoid duplicate warnings
- // Verify network cleanup - if (state.network) { + // `stop()` already verified cleanup for force-removes of running VMs. + if (state.status === "stopped" && state.network) { const leaks = verifyCleanup(state.network); for (const leak of leaks) { this.logger.warn(`[${vmId}] cleanup leak: ${leak}`); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/services/vm.ts` around lines 791 - 797, When remove() force-stops a VM it triggers stop() which already runs verifyCleanup() and logs warnings, so avoid duplicating them by setting a short-lived flag when remove() performs a forced stop (for example state.skipVerifyCleanup = true) and checking that flag before calling verifyCleanup() in the block that currently reads state.network / verifyCleanup(state.network); if the flag is set skip the verifyCleanup() call (and clear the flag afterward) so duplicate warnings for the same leftovers are not emitted; reference functions: remove(), stop(), verifyCleanup(), and the state.network / vmId identifiers.src/errors/setup.ts (1)
43-47: Fix suggestion is Intel-specific; consider adding AMD check.The diagnostic command
grep -c vmx /proc/cpuinfoonly works for Intel CPUs. AMD processors use thesvmflag for hardware virtualization. Users on AMD systems would incorrectly conclude their CPU lacks virtualization support.📝 Suggested improvement
export const kvmUnavailableError = (): SetupError => new SetupError("ERR_SETUP_KVM_UNAVAILABLE", { message: "/dev/kvm is not accessible — KVM virtualization is required.", - fix: "Ensure you're running on a KVM-capable host. Check: (1) CPU supports virtualization (grep -c vmx /proc/cpuinfo), (2) KVM module loaded (lsmod | grep kvm), (3) /dev/kvm is accessible", + fix: "Ensure you're running on a KVM-capable host. Check: (1) CPU supports virtualization (grep -Ec 'vmx|svm' /proc/cpuinfo), (2) KVM module loaded (lsmod | grep kvm), (3) /dev/kvm is accessible", });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/errors/setup.ts` around lines 43 - 47, The error message produced by kvmUnavailableError() is Intel-specific (it suggests checking for "vmx") and should include AMD's virtualization flag; update the message and the diagnostic command in the SetupError returned by kvmUnavailableError to suggest checking for either "vmx" (Intel) or "svm" (AMD) in /proc/cpuinfo and mention both in the troubleshooting steps (e.g., grep -E 'vmx|svm' /proc/cpuinfo), while keeping the existing KVM module and /dev/kvm accessibility checks intact so SetupError contains CPU-agnostic guidance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.changeset/kvm-preflight-cleanup.md:
- Line 5: Update the release note line to mention that the KVM pre-flight check
also runs on `vmsan start`: revise the changelog entry text (the line "Add KVM
pre-flight check to `vmsan create` and cleanup verification after `vmsan
stop`/`vmsan remove`") to include `vmsan start` and note that the gate is
invoked from `VMService.start()` via `validateEnvironment()`, so users see the
full user-visible change.
In `@src/services/vm.ts`:
- Around line 659-662: After calling safeKill(), add an explicit wait loop that
confirms the killed process(es) have actually exited before invoking
verifyCleanup(state.network); specifically, after safeKill() returns poll for
the PID(s) to disappear (e.g., check /proc/<pid> or use a non-blocking process
existence check) with a short sleep and an overall timeout, and only call
verifyCleanup() once the PID(s) are gone (or timeout); update the code paths
that call safeKill() so they perform this wait (referencing safeKill() and
verifyCleanup(state.network)) to avoid transient false-positive leak reports.
---
Nitpick comments:
In `@src/errors/setup.ts`:
- Around line 43-47: The error message produced by kvmUnavailableError() is
Intel-specific (it suggests checking for "vmx") and should include AMD's
virtualization flag; update the message and the diagnostic command in the
SetupError returned by kvmUnavailableError to suggest checking for either "vmx"
(Intel) or "svm" (AMD) in /proc/cpuinfo and mention both in the troubleshooting
steps (e.g., grep -E 'vmx|svm' /proc/cpuinfo), while keeping the existing KVM
module and /dev/kvm accessibility checks intact so SetupError contains
CPU-agnostic guidance.
In `@src/services/vm.ts`:
- Around line 791-797: When remove() force-stops a VM it triggers stop() which
already runs verifyCleanup() and logs warnings, so avoid duplicating them by
setting a short-lived flag when remove() performs a forced stop (for example
state.skipVerifyCleanup = true) and checking that flag before calling
verifyCleanup() in the block that currently reads state.network /
verifyCleanup(state.network); if the flag is set skip the verifyCleanup() call
(and clear the flag afterward) so duplicate warnings for the same leftovers are
not emitted; reference functions: remove(), stop(), verifyCleanup(), and the
state.network / vmId identifiers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3b40f24d-3fab-4605-9974-bc62d77ae341
📒 Files selected for processing (9)
.changeset/kvm-preflight-cleanup.mdsrc/commands/create/environment.tssrc/errors/codes.tssrc/errors/index.tssrc/errors/setup.tssrc/lib/network.tssrc/services/vm.tstests/unit/kvm-check.test.tstests/unit/network-cleanup.test.ts
| "vmsan": minor | ||
| --- | ||
|
|
||
| Add KVM pre-flight check to `vmsan create` and cleanup verification after `vmsan stop`/`vmsan remove` |
There was a problem hiding this comment.
Mention vmsan start in the release note.
The new KVM gate also runs from VMService.start() via validateEnvironment() on Line 412 of src/services/vm.ts, so this entry currently understates the user-visible change.
📝 Suggested wording
-Add KVM pre-flight check to `vmsan create` and cleanup verification after `vmsan stop`/`vmsan remove`
+Add KVM pre-flight check to `vmsan create`/`vmsan start` and cleanup verification after `vmsan stop`/`vmsan remove`📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| Add KVM pre-flight check to `vmsan create` and cleanup verification after `vmsan stop`/`vmsan remove` | |
| Add KVM pre-flight check to `vmsan create`/`vmsan start` and cleanup verification after `vmsan stop`/`vmsan remove` |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.changeset/kvm-preflight-cleanup.md at line 5, Update the release note line
to mention that the KVM pre-flight check also runs on `vmsan start`: revise the
changelog entry text (the line "Add KVM pre-flight check to `vmsan create` and
cleanup verification after `vmsan stop`/`vmsan remove`") to include `vmsan
start` and note that the gate is invoked from `VMService.start()` via
`validateEnvironment()`, so users see the full user-visible change.
| const leaks = verifyCleanup(state.network); | ||
| for (const leak of leaks) { | ||
| this.logger.warn(`[${vmId}] cleanup leak: ${leak}`); | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n=== safeKill definition ===\n'
fd 'utils.ts$' src --exec sed -n '/export function safeKill/,/^\}/p' {}
printf '\n=== stop() ordering around kill/teardown/verify ===\n'
sed -n '637,662p' src/services/vm.tsRepository: angelorc/vmsan
Length of output: 1577
Add explicit wait after safeKill() calls before running verifyCleanup().
safeKill() uses process.kill(), which is non-blocking—it sends the signal and returns immediately without waiting for the process to exit. Line 659 runs verifyCleanup() moments after the kill, but the kernel may not have finished reaping the process and cleaning up resource references yet. This creates a race window where the leak scanner could see transient resource state and report false positives.
Recommendation: Add an explicit wait (e.g., polling /proc/<pid> or waiting for the PID to disappear) between the safeKill() calls and verifyCleanup() to ensure the process has actually exited before checking for leaks.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/services/vm.ts` around lines 659 - 662, After calling safeKill(), add an
explicit wait loop that confirms the killed process(es) have actually exited
before invoking verifyCleanup(state.network); specifically, after safeKill()
returns poll for the PID(s) to disappear (e.g., check /proc/<pid> or use a
non-blocking process existence check) with a short sleep and an overall timeout,
and only call verifyCleanup() once the PID(s) are gone (or timeout); update the
code paths that call safeKill() so they perform this wait (referencing
safeKill() and verifyCleanup(state.network)) to avoid transient false-positive
leak reports.
Summary
/dev/kvmaccessibility check tovalidateEnvironment()with actionable error messageverifyCleanup()to detect orphaned TAP devices, network namespaces, and veth interfaces after teardownstop()andremove()flows (warns on leaks, doesn't throw)Changes
src/commands/create/environment.ts— KVM check in validateEnvironment()src/errors/codes.ts— newERR_SETUP_KVM_UNAVAILABLEerror codesrc/errors/setup.ts— newkvmUnavailableError()factorysrc/errors/index.ts— export new error factorysrc/lib/network.ts— newverifyCleanup()functionsrc/services/vm.ts— call verifyCleanup() after teardown in stop/removeTest plan
bun run test— 13 tests passbun run lint— cleanvmsan createon non-KVM machine shows clear errorvmsan stop+vmsan remove, no warnings about leaked resourcesSummary by CodeRabbit
New Features
Tests