Skip to content

cmd: add support for nested virtualization#327

Merged
openshift-merge-bot[bot] merged 1 commit intocrc-org:mainfrom
vyasgun:pr/nested-virt
Jun 25, 2025
Merged

cmd: add support for nested virtualization#327
openshift-merge-bot[bot] merged 1 commit intocrc-org:mainfrom
vyasgun:pr/nested-virt

Conversation

@vyasgun
Copy link
Copy Markdown
Contributor

@vyasgun vyasgun commented Jun 24, 2025

This commit adds a --nested (-n) flag to enable nested virtualization in vfkit. When enabled on macOS, it sets up a vz.GenericPlatformConfiguration with SetNestedVirtualizationEnabled(true).

Fixes: #279

Summary by Sourcery

Add support for nested virtualization by introducing a CLI flag, extending the VM config, and applying a generic platform configuration with nested virtualization enabled on macOS

New Features:

  • Introduce --nested-virtualization (-n) flag to the command-line interface
  • Add NestedVirtualization field to the VirtualMachine config structure

Enhancements:

  • Enable nested virtualization in NewVirtualMachine by configuring a vz.GenericPlatformConfiguration when the flag is set

Tests:

  • Update JSON stability tests to skip the new NestedVirtualization field

Summary by CodeRabbit

  • New Features
    • Added support for enabling nested virtualization via a new command-line flag.
    • Configuration files now support specifying nested virtualization.
  • Bug Fixes
    • Added validation to prevent nested virtualization when using the macOS bootloader.
  • Chores
    • Updated tests to accommodate the new nested virtualization field in configuration.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Jun 24, 2025

Reviewer's Guide

Adds nested virtualization support by introducing a CLI flag, extending the VM configuration, propagating the flag through the VM creation path, and implementing a helper that configures vz.GenericPlatformConfiguration with nested virtualization enabled.

Sequence diagram for VM creation with nested virtualization flag

sequenceDiagram
    actor User
    participant CLI as vfkit CLI
    participant Options
    participant Config as VirtualMachine Config
    participant VM as VirtualMachine
    participant VZ as vz.GenericPlatformConfiguration

    User->>CLI: Run vfkit with --nested-virtualization
    CLI->>Options: Parse flags
    Options->>Config: Set NestedVirtualization = true
    Config->>VM: NewVirtualMachine(config)
    VM->>VZ: setNestedVirtualization(vfConfig)
    VZ-->>VM: Platform config with nested virtualization enabled
    VM-->>Config: VirtualMachine instance created
Loading

Class diagram for updated VirtualMachine configuration

classDiagram
    class VirtualMachine {
        uint Vcpus
        strongunits.B Memory
        Bootloader Bootloader
        VirtioDevice[] Devices
        TimeSync* Timesync
        Ignition* Ignition
        bool NestedVirtualization
    }
Loading

Class diagram for Options struct with NestedVirtualization flag

classDiagram
    class Options {
        string IgnitionPath
        stringSliceValue CloudInitFiles
        bool NestedVirtualization
    }
Loading

File-Level Changes

Change Details Files
Extend VM config and CLI to support nested virtualization
  • add NestedVirtualization bool to VirtualMachine config
  • register --nested-virtualization (-n) flag in command-line options
  • update JSON stability tests to skip the new field
pkg/config/config.go
pkg/config/json_test.go
pkg/cmdline/cmdline.go
Propagate nested virtualization flag into VM creation
  • assign opts.NestedVirtualization to vmConfig in main
  • condition NewVirtualMachine to invoke setNestedVirtualization when enabled
cmd/vfkit/main.go
pkg/vf/vm.go
Implement nested virtualization setup helper
  • generate a GenericMachineIdentifier for vz
  • create a GenericPlatformConfiguration and set nested virtualization
  • attach the platform configuration to the VM configuration
pkg/vf/vm.go

Possibly linked issues

  • #0: The PR adds a flag to enable nested virtualization, directly addressing the issue's request to support this feature.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@openshift-ci openshift-ci bot requested review from baude and cfergeau June 24, 2025 06:17
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jun 24, 2025

Walkthrough

This update introduces support for nested virtualization throughout the codebase. It adds a Nested flag to command-line options, configuration structures, and command-line generation logic. Runtime checks are implemented to verify nested virtualization support, and platform configuration logic is updated to enable or restrict nested virtualization as appropriate.

Changes

File(s) Change Summary
pkg/cmdline/cmdline.go Added Nested field to Options struct and introduced --nested/-n command-line flag.
pkg/config/config.go Added Nested field to VirtualMachine struct and updated ToCmdLine to include --nested if enabled.
pkg/config/json_test.go Updated JSON stability test to skip the Nested field for VirtualMachine.
cmd/vfkit/main.go Added runtime check for nested virtualization support in newVMConfiguration.
pkg/vf/vm.go Added error for nested virtualization with macOS bootloader, refactored platform config logic,
and introduced NewGenericPlatformConfiguration to handle nested virtualization setup.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Config
    participant VM
    participant Platform

    User->>CLI: Run vfkit with --nested flag
    CLI->>Config: Parse flags, set Options.Nested
    Config->>VM: Pass VirtualMachine config with Nested field
    VM->>Platform: Call NewGenericPlatformConfiguration (with Nested)
    Platform-->>VM: Return platform config (with nested enabled if supported)
    VM-->>CLI: Return VM instance or error if unsupported
Loading

Poem

In code we hop, a nested dream,
Virtual worlds within the stream.
A flag appears, a check is made,
If nested’s true, let none dissuade!
But if the bootloader says “no way,”
The bunny frowns, but hops away.
Onward to new virtual days! 🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ddc4518 and a881c3b.

📒 Files selected for processing (5)
  • cmd/vfkit/main.go (1 hunks)
  • pkg/cmdline/cmdline.go (2 hunks)
  • pkg/config/config.go (2 hunks)
  • pkg/config/json_test.go (1 hunks)
  • pkg/vf/vm.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • pkg/config/json_test.go
  • cmd/vfkit/main.go
  • pkg/config/config.go
  • pkg/cmdline/cmdline.go
  • pkg/vf/vm.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build (macOS-14)
  • GitHub Check: build (macOS-13)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @vyasgun - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
pkg/config/config.go (1)

35-35: Consider adding support for the new field in the ToCmdLine() method.

The new NestedVirtualization field is properly added to the struct, but the ToCmdLine() method (lines 84-117) doesn't handle serialization of this field back to command-line arguments. For consistency and completeness, consider adding support for the --nested-virtualization flag in the ToCmdLine() method.

 	if vm.Ignition != nil {
 		args = append(args, "--ignition", vm.Ignition.ConfigPath)
 	}
+
+	if vm.NestedVirtualization {
+		args = append(args, "--nested-virtualization")
+	}

 	return args, nil
pkg/vf/vm.go (1)

55-73: Consider adding host capability validation.

The setNestedVirtualization function is well-implemented with comprehensive error handling and clear error messages. However, consider adding validation to check if the host system actually supports nested virtualization before attempting to enable it.

#!/bin/bash
# Check if there are any existing validation patterns for virtualization capabilities in the codebase
rg -A 5 -B 5 "Support|Capabilit|Available" --type go
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f898496 and ba10333.

📒 Files selected for processing (5)
  • cmd/vfkit/main.go (1 hunks)
  • pkg/cmdline/cmdline.go (2 hunks)
  • pkg/config/config.go (1 hunks)
  • pkg/config/json_test.go (1 hunks)
  • pkg/vf/vm.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build (macOS-14)
  • GitHub Check: build (macOS-13)
🔇 Additional comments (5)
cmd/vfkit/main.go (1)

84-84: LGTM! Clean integration of the nested virtualization option.

The assignment correctly propagates the command-line option to the VM configuration and follows the established pattern used for other configuration fields.

pkg/config/json_test.go (1)

234-234: Correct test adjustment for the new optional field.

Adding NestedVirtualization to skipFields is appropriate since the field has an omitempty JSON tag and should maintain its default false value in stability tests, rather than being automatically filled with true by the fillStruct function.

pkg/cmdline/cmdline.go (2)

31-31: LGTM! Clean addition of the nested virtualization option.

The new boolean field integrates well with the existing Options struct.


61-61: Well-designed command-line flag.

The flag implementation follows established patterns with a descriptive name, reasonable short form (-n), appropriate default value (false), and clear description.

pkg/vf/vm.go (1)

42-47: Well-integrated nested virtualization support for Linux VMs.

The conditional logic correctly applies nested virtualization only to Linux platform VMs and includes proper error handling. The placement within the platform configuration section is logical.

Copy link
Copy Markdown

@gbraad gbraad left a comment

Choose a reason for hiding this comment

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

Not a big one, but the enable flag says this is 'use' instead.

@vyasgun vyasgun force-pushed the pr/nested-virt branch 2 times, most recently from 95488cc to c47b50f Compare June 24, 2025 08:01
@vyasgun vyasgun requested a review from gbraad June 24, 2025 08:02
Copy link
Copy Markdown
Collaborator

@cfergeau cfergeau left a comment

Choose a reason for hiding this comment

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

Can you add a

Fixes: https://github.com/crc-org/vfkit/issues/279

to the commit log?

I’ll test this on a machine without nested support to see if we need to use https://github.com/Code-Hex/vz/blob/5bbaec6daefb962461fdf7fb33b27aff8e939cff/platform.go#L44-L51

pkg/vf/vm.go Outdated
} else {
PlatformType = "linux"
if vmConfig.NestedVirtualization {
err := setNestedVirtualization(vfConfig)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we take a similar approach to the macosBootloader branch and introduce a NewGenericPlatformConfiguration function? At the moment, nested virtualization won’t be enabled with macOS guests.

Copy link
Copy Markdown
Contributor Author

@vyasgun vyasgun Jun 24, 2025

Choose a reason for hiding this comment

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

do you mean replace NewMacPlatformConfiguration with NewGenericPlatformConfiguration?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The macOSBootloader branch has to keep using NewMacPlatformConfiguration, but the linux codepath could make use of NewGenericPlatformConfiguration to have some kind of symmetry between the 2.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ah, okay got it. I'll add the function

@cfergeau
Copy link
Copy Markdown
Collaborator

I’ll test this on a machine without nested support

This fails with this message which should be ok

INFO[0000] Adding virtio-rng device
Error: Error Domain=VZErrorDomain Code=2 Description="Invalid virtual
machine configuration. Nested virtualization is not available on this
hardware." UserInfo={
     NSLocalizedFailure = "Invalid virtual machine configuration.";
     NSLocalizedFailureReason = "Nested virtualization is not available
on this hardware.";

@gbraad
Copy link
Copy Markdown

gbraad commented Jun 24, 2025

Lot of duplication in that error (INFO) message. Does it have a specific error code, or a static message that can be interpreted? If vfkit is started in the background, this would otherwise not be recorded by the calling application.

@cfergeau
Copy link
Copy Markdown
Collaborator

Lot of duplication in that error (INFO) message. Does it have a specific error code, or a static message that can be interpreted? If vfkit is started in the background, this would otherwise not be recorded by the calling application.

Nested virtualization is not available on this hardware can be used as a static string for a match. Otherwise we can come up with our own error message by using https://github.com/Code-Hex/vz/blob/5bbaec6daefb962461fdf7fb33b27aff8e939cff/platform.go#L44-L51

@gbraad
Copy link
Copy Markdown

gbraad commented Jun 24, 2025

by using ...

This is merely based on the macOS version, so not a hardware limitation? Does this mean 15 on an M1 would support this?

@cfergeau
Copy link
Copy Markdown
Collaborator

by using ...

This is merely based on the macOS version, so not a hardware limitation? Does this mean 15 on an M1 would support this?

It’s not merely based on the macOS version. If you have macOS < 15, then nested virt is not supported. Otherwise, on a M1,  this would return false:

	return (bool)(C.isNestedVirtualizationSupported())

@vyasgun
Copy link
Copy Markdown
Contributor Author

vyasgun commented Jun 24, 2025

I added a check for availability of nested virtualization like this:

if opts.Nested && !vz.IsNestedVirtualizationSupported() {
		return nil, fmt.Errorf("nested virtualization is not supported")
	}

@gbraad
Copy link
Copy Markdown

gbraad commented Jun 24, 2025

When requested, but not available, would you error out or only inform the user (but continue)?

If have an opinion, but WDYT?

@vyasgun
Copy link
Copy Markdown
Contributor Author

vyasgun commented Jun 24, 2025

@gbraad would it be correct to continue with the --nested flag if it's not going to be supported inside the VM?

@gbraad
Copy link
Copy Markdown

gbraad commented Jun 24, 2025

@cfergeau WDYS?

@cfergeau
Copy link
Copy Markdown
Collaborator

@cfergeau WDYS?

If someone requested nested virtualization when it’s not available, this should be an error.
If that causes problems in some use cases, we can add a way to check if it’s available from the commandline, or a flag to ignore the error, … But by default, it’s an error to ask for nested virt and not to get it.

@gbraad
Copy link
Copy Markdown

gbraad commented Jun 24, 2025

Agree, fail early... error out hard. You can not continue when something you requested is not available.

}

func NewGenericPlatformConfiguration(vmConfig config.VirtualMachine) (vz.PlatformConfiguration, error) {
return nil, fmt.Errorf("running generic platform configuration is only supported on ARM devices")
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Won’t this prevent us from starting VMs on intel? The "platform" API seems available on intel, was there a problem with having NewGenericPlatformConfiguration in vm.go?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried on an Intel machine and virtualization was not available on it so I thought it's only there on arm64 machines. I will put the function in vm.go as that's better


if vmConfig.Nested {
err = platformConfig.SetNestedVirtualizationEnabled(true)
if err != nil {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can this part be moved out of NewGenericPlatformConfiguration so that we can enable nested virt both for mac and linux VMs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure how to do this since the method SetNestedVirtualizationEnabled is only available in GenericPlatformConfiguration

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Oh indeed, I missed that! We probably should return an error in the macos code path if nested virt was requested.
Apparently no nested virt with macos guests? utmapp/UTM#6700 (comment) this is unexpected!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Returning an error for macOS when nested virt is requested sounds like the right thing to do. Made the change.

Also, I didn’t expect nested virt to be unsupported for macOS guests either. That UTM issue was helpful, thanks for linking it!

Copy link
Copy Markdown

@gbraad gbraad Jun 25, 2025

Choose a reason for hiding this comment

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

maybe implied, always possible... or not? would be good to verify/look into further. at least something to describe as I am sure this will come up as a question

Edit: read the issue, and.seems clear; no virt inside nested macos. documentation issue in that case and I would say; either error out when requested on mac or, in this case an INFO as there is nothing you can do about this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried with tart and it gives an error that nested virtualization is unsupported on macOS guests.

Copy link
Copy Markdown

@gbraad gbraad Jun 26, 2025

Choose a reason for hiding this comment

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

This is important to also note on https://github.com/crc-org/crc-internal/issues/123, as that would conclude it; the idea was to use macOS to run nested virtualization to test vfkit in a 'clean host'. Done

This commit adds a --nested (-n) flag to enable nested virtualization in vfkit.
When enabled on macOS, it sets up a vz.GenericPlatformConfiguration with SetNestedVirtualizationEnabled(true).

Fixes: crc-org#279
Copy link
Copy Markdown
Collaborator

@cfergeau cfergeau left a comment

Choose a reason for hiding this comment

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

/lgtm
/approve

@openshift-ci
Copy link
Copy Markdown

openshift-ci bot commented Jun 25, 2025

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: cfergeau

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-merge-bot openshift-merge-bot bot merged commit d196497 into crc-org:main Jun 25, 2025
6 checks passed
@pkpbynum pkpbynum mentioned this pull request Dec 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for nested virtualization

3 participants