8000 feat: add KVM pre-flight check and cleanup verification by angelorc · Pull Request #47 · angelorc/vmsan · GitHub
[go: up one dir, main page]

Skip to content

feat: add KVM pre-flight check and cleanup verification - #47

Merged
angelorc merged 1 commit into
mainfrom
feat/kvm-preflight-cleanup-verify
Mar 7, 2026
Merged

angelorc merged 1 commit into
mainfrom
feat/kvm-preflight-cleanup-verify

Conversation

@angelorc
@angelorc angelorc commented Mar 7, 2026 •
Copy link
Copy Markdown
Owner

Summary

  • Add /dev/kvm accessibility check to validateEnvironment() with actionable error message
  • Add verifyCleanup() to detect orphaned TAP devices, network namespaces, and veth interfaces after teardown
  • Wire cleanup verification into stop() and remove() flows (warns on leaks, doesn't throw)

Changes

  • src/commands/create/environment.ts — KVM check in validateEnvironment()
  • src/errors/codes.ts — new ERR_SETUP_KVM_UNAVAILABLE error code
  • src/errors/setup.ts — new kvmUnavailableError() factory
  • src/errors/index.ts — export new error factory
  • src/lib/network.ts — new verifyCleanup() function
  • src/services/vm.ts — call verifyCleanup() after teardown in stop/remove

Test plan

  • bun run test — 13 tests pass
  • bun run lint — clean
  • vmsan create on non-KVM machine shows clear error
  • After vmsan stop + vmsan remove, no warnings about leaked resources

Summary by CodeRabbit

  • New Features

    • Added KVM environment validation during setup with helpful troubleshooting guidance if KVM is unavailable on the system.
    • Implemented detection of residual network resources after VM stop and removal operations, with warnings logged for any cleanup issues.
  • Tests

    • Added unit test coverage for KVM availability checks and network cleanup detection.

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.
@vercel
vercel Bot commented Mar 7, 2026
Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
vmsan Ignored Ignored Mar 7, 2026 3:18pm

Request Review

@coderabbitai
coderabbitai Bot commented Mar 7, 2026 •
Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
KVM Availability Validation
src/commands/create/environment.ts, src/errors/codes.ts, src/errors/index.ts, src/errors/setup.ts
Adds runtime KVM capability check validating read/write access to /dev/kvm. Introduces new error code ERR_SETUP_KVM_UNAVAILABLE with factory function providing diagnostic guidance on CPU virtualization and KVM module requirements.
Network Cleanup Verification
src/lib/network.ts, src/services/vm.ts
Adds verifyCleanup() function to detect orphaned TAP devices, network namespaces, and veth interfaces. Integrated into VM service stop/remove flows to log cleanup leaks as warnings without disrupting normal operation.
Changeset & Tests
.changeset/kvm-preflight-cleanup.md, tests/unit/kvm-check.test.ts, tests/unit/network-cleanup.test.ts
Adds changeset documentation for minor release. Introduces comprehensive unit test coverage for KVM validation and network cleanup verification with mocked filesystem operations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A KVM check hops in first,
Network cleanup quenches its thirst,
TAP devices no longer hide,
Resources leak? We catch 'em wide,
VMs are tidy, bunny-approved! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add KVM pre-flight check and cleanup verification' directly and accurately describes the two main changes: introducing a KVM pre-flight check and adding cleanup verification functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/kvm-preflight-cleanup-verify

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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-running verifyCleanup() 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/cpuinfo only works for Intel CPUs. AMD processors use the svm flag 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d39364 and 7a23f0a.

📒 Files selected for processing (9)
  • .changeset/kvm-preflight-cleanup.md
  • src/commands/create/environment.ts
  • src/errors/codes.ts
  • src/errors/index.ts
  • src/errors/setup.ts
  • src/lib/network.ts
  • src/services/vm.ts
  • tests/unit/kvm-check.test.ts
  • tests/unit/network-cleanup.test.ts

"vmsan": minor
---

Add KVM pre-flight check to `vmsan create` and cleanup verification after `vmsan stop`/`vmsan remove`
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Comment thread src/services/vm.ts
Comment on lines +659 to +662
const leaks = verifyCleanup(state.network);
for (const leak of leaks) {
this.logger.warn(`[${vmId}] cleanup leak: ${leak}`);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 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.ts

Repository: 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.

@angelorc
angelorc merged commit bfc12a7 into main Mar 7, 2026
4 checks passed
This was referenced Mar 7, 2026
This was referenced Mar 7, 2026
@angelorc
angelorc deleted the feat/kvm-preflight-cleanup-verify branch March 14, 2026 10:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0