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

feat(backup): add cleanup snapshot after backup test case #2288

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

mantissahz
Copy link
Contributor

@mantissahz mantissahz commented Jan 22, 2025

Which issue(s) this PR fixes:

Issue # longhorn/longhorn#9213

What this PR does / why we need it:

Special notes for your reviewer:

Additional documentation or context

Summary by CodeRabbit

Release Notes

  • Documentation

    • Minor grammatical correction in cluster restore documentation (removed hyphen in "reuses")
  • New Features

    • Added option to clean up snapshots after backup creation
    • Added ability to check snapshot existence for a specific backup
  • Tests

    • Added new test case to verify snapshot cleanup after backup completion

@mantissahz mantissahz self-assigned this Jan 22, 2025
Copy link

coderabbitai bot commented Jan 22, 2025

Warning

Rate limit exceeded

@mantissahz has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 53 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1e2ce91 and 5900681.

📒 Files selected for processing (5)
  • e2e/keywords/backup.resource (2 hunks)
  • e2e/libs/backup/backup.py (2 hunks)
  • e2e/libs/backup/rest.py (2 hunks)
  • e2e/libs/keywords/backup_keywords.py (2 hunks)
  • e2e/tests/regression/test_backup.robot (1 hunks)

Walkthrough

This pull request introduces enhancements to the backup functionality in Longhorn's testing framework. The changes include adding a new parameter cleanup_snapshot to backup-related methods, which allows controlling whether snapshots are cleaned up after backup creation. A new test case is added to verify this functionality, and corresponding keywords and methods are updated across multiple files to support the new feature.

Changes

File Change Summary
docs/content/manual/pre-release/... Minor grammatical correction: removed hyphen in "reuses"
e2e/keywords/backup.resource Added two new keywords:
- Create backup with cleanup snapshot
- Check snapshot for backup exists
e2e/libs/backup/backup.py Updated create method with cleanup_snapshot parameter
Added check_snapshot_exists_for_backup method
e2e/libs/backup/rest.py Updated create method to pass cleanup_snapshot to snapshotBackup
e2e/libs/keywords/backup_keywords.py Updated create_backup method with cleanup_snapshot parameter
Added check_snapshot_exists_for_backup method
e2e/tests/regression/test_backup.robot Added new test case "Test Cleanup Snapshot After Backup Completed"

Sequence Diagram

sequenceDiagram
    participant User
    participant BackupKeywords
    participant Backup
    participant Volume
    
    User->>BackupKeywords: create_backup(volume_name, backup_id, cleanup_snapshot)
    BackupKeywords->>Backup: create(volume_name, backup_id, cleanup_snapshot)
    Backup->>Volume: snapshotBackup(name, cleanupBackupSnapshot)
    alt cleanup_snapshot is True
        Volume-->>Backup: Delete snapshot after backup
    else cleanup_snapshot is False
        Volume-->>Backup: Keep snapshot
    end
Loading

Possibly related PRs

Suggested reviewers

  • yangchiu
  • chriscchien
  • roger-ryao

Poem

🐰 A Backup Bunny's Ballad 🥕

Snapshots dancing, clean or stay,
With a hop and a click, we pave the way,
Cleanup flag waving, tests in sight,
Longhorn's backup magic takes flight!
Hop-tastic testing, oh what a delight! 🚀


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. (Beta)
  • @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.

@mantissahz mantissahz marked this pull request as ready for review January 23, 2025 08:01
@mantissahz mantissahz requested a review from a team as a code owner January 23, 2025 08:01
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: 1

🧹 Nitpick comments (4)
e2e/tests/regression/test_backup.robot (1)

110-122: Consider adding more test cases for edge scenarios.

The test case effectively verifies the basic functionality. Consider adding tests for:

  1. Cleanup with empty volume (no data written)
  2. Cleanup with multiple existing snapshots
  3. Cleanup when snapshot is already removed

Example test structure:

Test Cleanup Snapshot After Backup With Empty Volume
    Given Create volume 0 with    dataEngine=${DATA_ENGINE}
    And Attach volume 0
    And Wait for volume 0 healthy
    When Create backup 0 for volume 0 with cleanup snapshot True
    Then Check snapshot for backup 0 of volume 0 exists False
e2e/libs/backup/rest.py (3)

27-28: Consider aligning parameter names for consistency.

The parameter name cleanup_snapshot in the method signature differs from cleanupBackupSnapshot in the API call. While functionally correct, consistent naming would improve code readability.

Also, the indentation appears to be using both spaces and tabs. Consider using consistent indentation (preferably spaces) throughout the file.

-        volume.snapshotBackup(name=snapshot.name,
-                              cleanupBackupSnapshot=cleanup_snapshot)
+        volume.snapshotBackup(
+            name=snapshot.name,
+            cleanupBackupSnapshot=cleanup_snapshot
+        )

48-49: Fix indentation for consistency.

The indentation in the set_data_checksum call is inconsistent with the rest of the file.

-        self.set_data_checksum(backup.name,
-                               self.volume.get_last_data_checksum(volume_name))
+        self.set_data_checksum(
+            backup.name,
+            self.volume.get_last_data_checksum(volume_name)
+        )

22-28: Consider adding error handling for cleanup failures.

The current implementation doesn't handle potential failures during snapshot cleanup. Consider:

  1. Adding error handling for cleanup failures
  2. Verifying successful cleanup
  3. Adding logging for cleanup operations

This would improve the robustness of the test automation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 958d54b and 1e2ce91.

📒 Files selected for processing (6)
  • docs/content/manual/pre-release/cluster-restore/restore-to-an-old-cluster.md (1 hunks)
  • e2e/keywords/backup.resource (2 hunks)
  • e2e/libs/backup/backup.py (2 hunks)
  • e2e/libs/backup/rest.py (2 hunks)
  • e2e/libs/keywords/backup_keywords.py (2 hunks)
  • e2e/tests/regression/test_backup.robot (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/content/manual/pre-release/cluster-restore/restore-to-an-old-cluster.md
🧰 Additional context used
🪛 Ruff (0.8.2)
e2e/libs/backup/backup.py

76-76: Use not ... instead of False if ... else True

Replace with not ...

(SIM211)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (7)
e2e/libs/backup/backup.py (1)

18-19: LGTM!

The addition of the cleanup_snapshot parameter with a default value of False maintains backward compatibility while adding new functionality.

e2e/libs/keywords/backup_keywords.py (2)

12-13: LGTM!

Clean implementation that properly delegates to the backup implementation layer.


61-65: LGTM!

Good separation of concerns with proper delegation to the backup implementation.

e2e/keywords/backup.resource (2)

18-21: LGTM!

Good reuse of existing helper keyword generate_name_with_suffix and maintains consistency with existing keyword patterns.


61-63: LGTM!

Clean implementation that follows the established pattern of other similar keywords.

e2e/libs/backup/rest.py (2)

22-22: LGTM! Method signature change looks good.

The new parameter cleanup_snapshot with default value False maintains backward compatibility while adding the new cleanup functionality.


22-28: Verify test coverage for cleanup functionality.

Please ensure there are test cases that cover:

  1. Successful snapshot cleanup
  2. Failed snapshot cleanup
  3. Cleanup with various volume states
✅ Verification successful

Test coverage for cleanup functionality is verified

The cleanup functionality is well-covered by the "Test Cleanup Snapshot After Backup Completed" test case in e2e/tests/regression/test_backup.robot, which verifies:

  • Successful snapshot cleanup
  • Normal backup without cleanup
  • Volume state handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases covering the new cleanup functionality
rg -l "cleanup.*snapshot" --type py --type robot

Length of output: 295


Script:

#!/bin/bash
# Check content of the robot test file and integration test
echo "=== Robot Framework Test ==="
cat e2e/tests/regression/test_backup.robot
echo -e "\n=== Integration Test ==="
cat manager/integration/tests/test_snapshot.py

Length of output: 33742

Comment on lines +70 to +78
def check_snapshot_exists_for_backup(self, volume_name, backup_id,
exists=True):
backup = self.backup.get(backup_id, volume_name)
snap_name = backup.snapshotName
snapshot_id = self.backup.snapshot.get_snapshot_id(snap_name)
snap = self.backup.snapshot.get(volume_name, snapshot_id)
snap_exists = False if snap.removed else True
assert snap_exists == exists, \
f"Snapshot {snap_name} exists: {snap_exists}, expected: {exists}"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null check and simplify boolean expression.

The implementation should handle cases where backup.snapshotName might be None, and the boolean expression can be simplified.

Apply this diff to improve the implementation:

     def check_snapshot_exists_for_backup(self, volume_name, backup_id,
                                          exists=True):
         backup = self.backup.get(backup_id, volume_name)
+        if not backup or not backup.snapshotName:
+            raise ValueError(f"Backup {backup_id} not found or missing snapshot name")
         snap_name = backup.snapshotName
         snapshot_id = self.backup.snapshot.get_snapshot_id(snap_name)
         snap = self.backup.snapshot.get(volume_name, snapshot_id)
-        snap_exists = False if snap.removed else True
+        snap_exists = not snap.removed
         assert snap_exists == exists, \
             f"Snapshot {snap_name} exists: {snap_exists}, expected: {exists}"
📝 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.

Suggested change
def check_snapshot_exists_for_backup(self, volume_name, backup_id,
exists=True):
backup = self.backup.get(backup_id, volume_name)
snap_name = backup.snapshotName
snapshot_id = self.backup.snapshot.get_snapshot_id(snap_name)
snap = self.backup.snapshot.get(volume_name, snapshot_id)
snap_exists = False if snap.removed else True
assert snap_exists == exists, \
f"Snapshot {snap_name} exists: {snap_exists}, expected: {exists}"
def check_snapshot_exists_for_backup(self, volume_name, backup_id,
exists=True):
backup = self.backup.get(backup_id, volume_name)
if not backup or not backup.snapshotName:
raise ValueError(f"Backup {backup_id} not found or missing snapshot name")
snap_name = backup.snapshotName
snapshot_id = self.backup.snapshot.get_snapshot_id(snap_name)
snap = self.backup.snapshot.get(volume_name, snapshot_id)
snap_exists = not snap.removed
assert snap_exists == exists, \
f"Snapshot {snap_name} exists: {snap_exists}, expected: {exists}"
🧰 Tools
🪛 Ruff (0.8.2)

76-76: Use not ... instead of False if ... else True

Replace with not ...

(SIM211)

ref: longhorn/longhorn 9213

Signed-off-by: James Lu <[email protected]>
@mantissahz mantissahz marked this pull request as draft January 23, 2025 08:28
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