Skip to content

fix: Update virtual_machine.py example #2376

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 1 commit into from
Apr 7, 2025
Merged

Conversation

phoracek
Copy link
Contributor

@phoracek phoracek commented Apr 7, 2025

Short description:

The original example did not work. This patch replaces it with one that does, using the body attribute to provide a clear self-contained example.

More details:
What this PR does / why we need it:

Old example does not work, this one does.

Which issue(s) this PR fixes:
Special notes for reviewer:
Bug:

Summary by CodeRabbit

  • New Features

    • Introduced a streamlined workflow for managing virtual machines in Kubernetes, featuring explicit steps for creation, startup, and readiness verification with a 180-second timeout.
  • Refactor

    • Updated the virtual machine instantiation process for enhanced clarity and control, ensuring a more robust and predictable lifecycle management approach.

@phoracek phoracek changed the title Update virtual_machine example Update virtual_machine.py example Apr 7, 2025
@redhat-qe-bot
Copy link
Contributor

Report bugs in Issues

The following are automatically added:

  • Add reviewers from OWNER file (in the root of the repository) under reviewers section.
  • Set PR size label.
  • New issue is created for the PR. (Closed when PR is merged/closed)
  • Run pre-commit if .pre-commit-config.yaml exists in the repo.

Available user actions:

  • To mark PR as WIP comment /wip to the PR, To remove it from the PR comment /wip cancel to the PR.
  • To block merging of PR comment /hold, To un-block merging of PR comment /hold cancel.
  • To mark PR as verified comment /verified to the PR, to un-verify comment /verified cancel to the PR.
    verified label removed on each new commit push.
  • To cherry pick a merged PR comment /cherry-pick <target branch to cherry-pick to> in the PR.
    • Multiple target branches can be cherry-picked, separated by spaces. (/cherry-pick branch1 branch2)
    • Cherry-pick will be started when PR is merged
  • To build and push container image command /build-and-push-container in the PR (tag will be the PR number).
    • You can add extra args to the Podman build command
      • Example: /build-and-push-container --build-arg OPENSHIFT_PYTHON_WRAPPER_COMMIT=<commit_hash>
  • To add a label by comment use /<label name>, to remove, use /<label name> cancel
  • To assign reviewers based on OWNERS file use /assign-reviewers
  • To check if PR can be merged use /check-can-merge
  • to assign reviewer to PR use /assign-reviewer @<reviewer>
Supported /retest check runs
  • /retest tox: Retest tox
  • /retest python-module-install: Retest python-module-install
  • /retest conventional-title: Retest conventional-title
  • /retest all: Retest all
Supported labels
  • hold
  • verified
  • wip
  • lgtm

Copy link

coderabbitai bot commented Apr 7, 2025

Walkthrough

The changes modify the process of creating and managing a Virtual Machine (VM) in the example. The context manager approach for VM instantiation has been replaced with a direct assignment to a variable vm. The load_kube_config() method is now called for Kubernetes client configuration before defining the VM. The VM is instantiated with a detailed body parameter, and explicit calls to vm.create() and vm.start() are introduced, along with a wait for the Virtual Machine Instance (VMI) to be running, with a timeout of 180 seconds. Previous operations for stopping and restarting the VM have been removed, and the method signature has been updated.

Changes

File Summary
examples/virtual_machine.py Removed context manager for VM instantiation; introduced direct creation with detailed body specification; added explicit calls to create(), start(), and waiting for VMI; removed VM restart logic and command execution on the virt launcher Pod; updated method signature from with VirtualMachine(...) to vm = VirtualMachine(...).
✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

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

@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 (1)
examples/virtual_machine.py (1)

6-38: Consider adding error handling and documentation.

While the example is much improved, consider enhancing it further with:

  1. Error handling for potential failures during VM operations
  2. Comments explaining key configuration options
  3. Making hardcoded values like VM name and namespace more generic or explaining their significance
-# Define a VM
+# Define a VM with a basic CirrOS image and minimal resources
 vm = VirtualMachine(
     name="vm-example5",
     namespace="phoracek",
     body={
         "spec": {
-            "runStrategy": "Halted",
+            "runStrategy": "Halted",  # Start in halted state to allow explicit start
             "template": {
                 "spec": {
                     "domain": {
                         "devices": {
                             "disks": [{"name": "disk0", "disk": {"bus": "virtio"}}]
                         },
                         "resources": {"requests": {"memory": "64Mi"}},
                     },
                     "volumes": [
                         {
                             "name": "disk0",
                             "containerDisk": {
                                 "image": "kubevirt/cirros-container-disk-demo"
                             },
                         }
                     ],
                 },
             },
         }
     },
 )

 # VM operations
-vm.create()
-vm.start()
-vm.vmi.wait_until_running(timeout=180)
+try:
+    vm.create()
+    vm.start()
+    vm.vmi.wait_until_running(timeout=180)
+    # Example continues with stop operation
+except Exception as e:
+    print(f"Error during VM operations: {e}")
+    # Cleanup resources if needed
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7339e54 and 1127da0.

📒 Files selected for processing (1)
  • examples/virtual_machine.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: python-module-install
  • GitHub Check: tox
  • GitHub Check: conventional-title
🔇 Additional comments (3)
examples/virtual_machine.py (3)

1-5: Good addition of Kubernetes configuration loading.

Adding the explicit import and loading of Kubernetes configuration is a good practice as it ensures the example works correctly by having proper access to the cluster. This makes the example more self-contained and functional.


6-33: Excellent improvement to VM definition with detailed specification.

The new approach of directly instantiating the VM with a detailed specification using the body parameter is much clearer and more instructive than the previous context manager approach. This provides a complete example of VM configuration including:

  • Run strategy configuration
  • Domain specification with devices and resources
  • Volume configuration with container disk image

This makes the example much more valuable for users trying to understand how to properly configure VMs.


36-38: Good explicit VM lifecycle management.

The explicit calls to create(), start(), and waiting for the VM to be running with a timeout provide a clear demonstration of VM lifecycle management. This approach is more transparent than using a context manager and shows users the exact sequence of operations required.

Copy link

@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 (1)
examples/virtual_machine.py (1)

1-40: Consider adding error handling and cleanup.

While the example effectively demonstrates VM creation and basic operations, it could be further improved with:

  1. Error handling for potential failures during VM creation or operations
  2. Cleanup code to delete the VM after the example completes
  3. Additional comments explaining key configuration choices
 from kubernetes import config
 from ocp_resources.virtual_machine import VirtualMachine
+import time
 
 config.load_kube_config()
 
 # Define a VM
 vm = VirtualMachine(
     name="vm-example",
     namespace="namespace-example",
     body={
         "spec": {
             "runStrategy": "Halted",
             "template": {
                 "spec": {
                     "domain": {
                         "devices": {
                             "disks": [{"name": "disk0", "disk": {"bus": "virtio"}}]
                         },
                         "resources": {"requests": {"memory": "64Mi"}},
                     },
                     "volumes": [
                         {
                             "name": "disk0",
                             "containerDisk": {
                                 "image": "kubevirt/cirros-container-disk-demo"
                             },
                         }
                     ],
                 },
             },
         }
     },
 )
 
 # VM operations
+try:
     vm.create()
     vm.start()
     vm.vmi.wait_until_running(timeout=180)
-vm.stop()
+    vm.stop()
+    
+    # Your additional operations with the VM would go here
+    
+    # Uncomment to clean up the VM
+    # print("Cleaning up VM...")
+    # vm.delete()
+    # vm.wait_for_delete()
+except Exception as e:
+    print(f"An error occurred: {e}")
+finally:
+    # Ensure VM is stopped even if an exception occurs
+    if vm.exists:
+        vm.stop()
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1127da0 and ec78c48.

📒 Files selected for processing (1)
  • examples/virtual_machine.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: python-module-install
  • GitHub Check: tox
  • GitHub Check: conventional-title
🔇 Additional comments (3)
examples/virtual_machine.py (3)

1-5: Configuration setup improves example usability.

Adding the explicit Kubernetes configuration loading makes the example self-contained and immediately executable for users. This is an essential improvement for demonstration purposes.


6-33: Clear VM definition with comprehensive configuration.

The direct VM instantiation with a detailed body parameter provides a more explicit and practical example than the previous context manager approach. The configuration includes all essential elements for a functional VM:

  • Appropriate runStrategy
  • Domain configuration with device specifications
  • Resource requirements
  • Container disk volume definition

This approach makes it easier for users to understand the required structure and adapt it to their needs.


36-38: VM lifecycle operations are now explicit and robust.

The explicit calls to create() and start() followed by waiting for the VM to be running provide a clearer demonstration of VM lifecycle management than the previous approach. The timeout value of 180 seconds is reasonable for this example.

@phoracek phoracek changed the title Update virtual_machine.py example fix: Update virtual_machine.py example Apr 7, 2025
dbasunag
dbasunag previously approved these changes Apr 7, 2025
myakove
myakove previously approved these changes Apr 7, 2025
@myakove
Copy link
Collaborator

myakove commented Apr 7, 2025

/retest conventional-title

The original example did not work. This patch replaces it with one that
does, using the body attribute to provide a clear self-contained
example.

Signed-off-by: Petr Horacek <phoracek@redhat.com>
@myakove myakove enabled auto-merge (squash) April 7, 2025 14:04
@myakove
Copy link
Collaborator

myakove commented Apr 7, 2025

/verified

@myakove myakove merged commit 106e999 into RedHatQE:main Apr 7, 2025
6 of 7 checks passed
Copy link

@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 (1)
examples/virtual_machine.py (1)

32-35: Consider adding cleanup example for completeness.

While the example now effectively demonstrates creating, starting, and stopping a VM, it might be beneficial to also show how to clean up resources by deleting the VM when done.

vm.create()
vm.start()
vm.vmi.wait_until_running(timeout=180)
vm.stop()
+
+# Clean up resources when done
+vm.delete()
+vm.wait_until_deleted()
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec78c48 and 2eb8afb.

📒 Files selected for processing (1)
  • examples/virtual_machine.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: tox
  • GitHub Check: python-module-install
  • GitHub Check: conventional-title
🔇 Additional comments (3)
examples/virtual_machine.py (3)

1-5: Good addition of explicit Kubernetes configuration.

The addition of config.load_kube_config() is essential for a functional example as it ensures the Kubernetes client is properly configured before attempting to interact with the cluster.


6-29: Well-structured VM definition with comprehensive body parameter.

The detailed body parameter effectively demonstrates how to configure a VM with proper specifications including:

  • Run strategy set to "Halted" (VM won't start automatically upon creation)
  • Domain specifications with device configuration
  • Resource requirements for memory
  • Volume definitions using a container disk image

This provides a much clearer, functional example compared to the previous implementation.


32-34: Clear demonstration of VM lifecycle operations.

The explicit calls to create(), start(), and waiting for the VM instance to be running provide a clear, step-by-step demonstration of the VM lifecycle management, which is more instructive than the previous context manager approach.

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants