Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

test(robot): wait for pvc and volume deleted when cleaning up statefulset #2187

Merged
merged 2 commits into from
Dec 13, 2024

Conversation

yangchiu
Copy link
Member

@yangchiu yangchiu commented Dec 11, 2024

Which issue(s) this PR fixes:

Issue N/A

What this PR does / why we need it:

wait for pvc and volume deleted when cleaning up statefulset

Special notes for your reviewer:

Additional documentation or context

Summary by CodeRabbit

  • New Features

    • Enhanced deletion process for stateful sets, including management of associated persistent volume claims and volumes.
    • Improved logging and checks during the deletion of stateful sets and related resources.
  • Bug Fixes

    • Updated logging statements to accurately reflect counts of persistent volume claims and volumes being cleaned up.
  • Documentation

    • Clarified method outputs to return only relevant items from API responses instead of full response objects.
  • Chores

    • Simplified iteration and data extraction processes in various methods for better clarity and efficiency.

@yangchiu yangchiu self-assigned this Dec 11, 2024
@yangchiu yangchiu requested a review from a team as a code owner December 11, 2024 03:34
Copy link

coderabbitai bot commented Dec 11, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several modifications to improve the handling of persistent volume claims and volumes within the codebase. Key changes include updating logging statements to accurately reflect the counts of cleaned-up resources, simplifying iteration over claims and volumes, and altering the return values of list methods to provide only the relevant items. Additionally, enhancements have been made to the deletion process of stateful sets, ensuring associated resources are properly managed and logged during deletion.

Changes

File Path Change Summary
e2e/libs/keywords/persistentvolumeclaim_keywords.py Updated logging in cleanup_persistentvolumeclaims to reflect the correct count and simplified iteration.
e2e/libs/keywords/volume_keywords.py Modified logging in cleanup_volumes to reflect the correct count and simplified iteration.
e2e/libs/persistentvolumeclaim/crd.py Changed list method to return only items from the API response instead of the full response.
e2e/libs/volume/crd.py Modified list method to return only items from the API response instead of the full response.
e2e/libs/volume/rest.py Enhanced wait_for_replica_count and wait_for_replica_rebuilding_complete methods with new logic and logging.
e2e/libs/volume/volume.py Updated list_names method to directly return items from the list method without accessing the 'items' key.
e2e/libs/workload/statefulset.py Enhanced delete_statefulset function to manage deletion of associated resources with logging and assertions.

Possibly related PRs

Suggested reviewers

  • chriscchien
  • khushboo-rancher

Poem

🐰 In the garden where volumes bloom,
Cleanup dances, dispelling gloom.
Claims and states, all in a row,
With logs that tell how counts do grow.
Hopping through code, we tidy and clear,
A world of volumes, we hold so dear! 🌼


📜 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 70c989c and 73c16c5.

📒 Files selected for processing (2)
  • e2e/libs/volume/crd.py (1 hunks)
  • e2e/libs/volume/volume.py (1 hunks)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Experiment)
  • @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

@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: 2

🧹 Outside diff range and nitpick comments (4)
e2e/libs/workload/statefulset.py (2)

Line range hint 85-97: Ensure Consistent Logic in Deletion Loops

In the loop waiting for the stateful set deletion, the deleted variable is initialized to True and set to False if the stateful set still exists. In the subsequent loops for PVC and volume deletion, deleted is initialized to False and set to True when the items are deleted. For consistency and clarity, consider using the same approach to initializing and updating the deleted variable across all loops.


Line range hint 85-123: Refactor Repetitive Deletion Waiting Loops into a Helper Function

The loops for waiting on the deletion of the stateful set, PVCs, and volumes have similar structures and logic. Consider refactoring this repeated code into a reusable helper function to improve maintainability and reduce code duplication.

Suggested Change:

Create a helper function, for example, wait_for_resource_deletion(resource_list_function, resource_name, label_selector), which encapsulates the deletion waiting logic.

e2e/libs/persistentvolumeclaim/crd.py (1)

25-25: Update Method Documentation to Reflect Changed Return Type

The list method now returns only the .items from the API response, which is a list of PersistentVolumeClaim objects. To prevent confusion and potential misuse, consider updating the method's docstring or adding a comment to indicate that the method returns a list of items rather than the full API response.

e2e/libs/volume/volume.py (1)

37-37: Ensure Consistency with Updated List Method

The list_names method assumes that self.list(label_selector) returns a list of volume objects directly. Verify that all other usages of self.list() in the codebase are updated accordingly to handle the new return type, preventing potential attribute errors or misuses.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between caaa648 and 70c989c.

📒 Files selected for processing (7)
  • e2e/libs/keywords/persistentvolumeclaim_keywords.py (1 hunks)
  • e2e/libs/keywords/volume_keywords.py (1 hunks)
  • e2e/libs/persistentvolumeclaim/crd.py (1 hunks)
  • e2e/libs/volume/crd.py (1 hunks)
  • e2e/libs/volume/rest.py (2 hunks)
  • e2e/libs/volume/volume.py (1 hunks)
  • e2e/libs/workload/statefulset.py (3 hunks)
🔇 Additional comments (4)
e2e/libs/keywords/persistentvolumeclaim_keywords.py (1)

19-20: Confirm Correct Logging of PersistentVolumeClaim Count

The logging statement now correctly reflects the number of persistent volume claims being cleaned up by using len(claims). Ensure that claims is always a list to prevent any unexpected issues.

e2e/libs/keywords/volume_keywords.py (1)

29-30: LGTM: Simplified volume iteration

The change improves code readability by directly iterating over volumes while maintaining the same functionality. This aligns well with the changes in the CRD class where list() now returns items directly.

e2e/libs/volume/rest.py (1)

Line range hint 241-258: LGTM: Improved replica count verification

The changes enhance reliability and debuggability by:

  1. Adding explicit condition tracking
  2. Providing more detailed logging
  3. Including descriptive assertion messages
🧰 Tools
🪛 Ruff (0.8.0)

251-256: Combine if branches using logical or operator

Combine if branches

(SIM114)

e2e/libs/volume/crd.py (1)

181-181: Verify all callers of the list method

The change to return only items is a breaking change that could affect callers expecting the full response object. While this simplifies the API, we should ensure all callers have been updated.

✅ Verification successful

Breaking change verified - callers already handle items-only response

Based on the search results, the main callers of the volume CRD list method are:

  • e2e/libs/volume/volume.py: Uses the list results directly to extract names or process items
  • e2e/libs/keywords/volume_keywords.py: Uses the results to iterate through volumes
  • e2e/libs/workload/statefulset.py: Only checks length and iterates through volumes

All identified callers are already treating the response as a list of items, either by iterating directly or checking the length. No callers are accessing other properties of the response object.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all callers of the CRD.list method to verify they handle the new return value

# Search for direct method calls
rg -A 3 "\.list\(" --type python

# Search for variable assignments from list calls
rg -A 3 "=.*\.list\(" --type python

Length of output: 134


Script:

#!/bin/bash
# Search for direct method calls and variable assignments using list method
# Note: Using ripgrep without file type filtering since python type is not recognized
rg -A 3 "\.list\(" 

# Also search for potential imports of the CRD class to identify files that might use it
rg "from.*volume.*crd.*import"

Length of output: 8315

Comment on lines +98 to +109
claim = PersistentVolumeClaim()
volume_name = None
for i in range(retry_count):
time.sleep(retry_interval)
logging(f"Waiting for pvc of statefulset {name} deleted ... ({i})")
claims = claim.list(label_selector=f"app={name}")
deleted = False
if len(claims) == 0:
deleted = True
break
else:
volume_name = claims[0].spec.volume_name
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Handle Multiple PersistentVolumeClaims and Associated Volumes

Currently, the code retrieves the volume_name from only the first PersistentVolumeClaim (claims[0].spec.volume_name). If the stateful set has multiple replicas, there may be multiple PVCs and associated volumes. Consider iterating over all claims to handle multiple PVCs and their volumes properly.

Suggested Change:

Modify the loop to handle all PVCs and collect their associated volume names:

 volume_names = []
 for i in range(retry_count):
     time.sleep(retry_interval)
     logging(f"Waiting for PVCs of statefulset {name} to be deleted... ({i})")
     claims = claim.list(label_selector=f"app={name}")
     if len(claims) == 0:
         deleted = True
         break
     else:
-        volume_name = claims[0].spec.volume_name
+        volume_names = [c.spec.volume_name for c in claims]
 assert deleted

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +112 to +123
if volume_name:
volume = Volume()
for i in range(retry_count):
time.sleep(retry_interval)
logging(f"Waiting for volume {volume_name} deleted ... ({i})")
volumes = volume.list(label_selector=f"longhornvolume={volume_name}")
deleted = False
if len(volumes) == 0:
deleted = True
break
assert deleted

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Handle Multiple Volumes During Deletion

Similar to the PVC deletion logic, the code is currently checking for the deletion of a single volume. If there are multiple volumes associated with the stateful set, they should all be checked and waited upon during the deletion process. Consider modifying the code to handle deletion checks for all relevant volumes.

Suggested Change:

Iterate over all collected volume_names to ensure each is deleted:

-if volume_name:
+if volume_names:
     volume = Volume()
     for volume_name in volume_names:
         for i in range(retry_count):
             time.sleep(retry_interval)
             logging(f"Waiting for volume {volume_name} to be deleted... ({i})")
             volumes = volume.list(label_selector=f"longhornvolume={volume_name}")
             if len(volumes) == 0:
                 deleted = True
                 break
             else:
                 deleted = False
         assert deleted

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@chriscchien chriscchien left a comment

Choose a reason for hiding this comment

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

LGTM

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.

2 participants