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

fix(e2e): use backup target API if settings are removed #2230

Merged
merged 1 commit into from
Dec 27, 2024

Conversation

mantissahz
Copy link
Contributor

@mantissahz mantissahz commented Dec 27, 2024

Which issue(s) this PR fixes:

Issue # ref: longhorn/longhorn#5411, longhorn/longhorn#10043

What this PR does / why we need it:

Special notes for your reviewer:

Additional documentation or context

Summary by CodeRabbit

  • New Features
    • Introduced methods for managing backup store configurations, including retrieving and updating backup target details.
    • Added a utility function to convert Kubernetes duration strings into total seconds.
  • Bug Fixes
    • Enhanced error handling for unsupported backup settings, providing fallback mechanisms to the BackupStore.
  • Documentation
    • Updated documentation to reflect new methods and constants related to backup store management.

Copy link

coderabbitai bot commented Dec 27, 2024

Walkthrough

This pull request introduces enhancements to backup store management in the Longhorn testing framework. The changes focus on adding utility methods for converting Kubernetes duration strings, managing backup target configurations, and improving error handling. The modifications span two files: e2e/libs/backupstore/base.py and e2e/libs/setting/setting.py, introducing new methods for retrieving, setting, and resetting backup store parameters with robust error handling mechanisms.

Changes

File Changes
e2e/libs/backupstore/base.py - Added from_k8s_duration_to_seconds() utility function
- Added methods for getting/setting backup store URL, secret, and poll interval
- Introduced update_backupstore() and reset_backupstore() methods
- Defined DEFAULT_BACKUPTARGET constant
e2e/libs/setting/setting.py - Added BackupStore class initialization
- Updated set_backupstore() and reset_backupstore() with error handling
- Modified get_backup_target() and get_secret() methods to handle unsupported settings

Sequence Diagram

sequenceDiagram
    participant Setting
    participant BackupStore
    participant LonghornClient

    Setting->>BackupStore: Initialize
    Setting->>LonghornClient: Attempt to set backup target
    alt Setting not supported
        LonghornClient-->>Setting: Error
        Setting->>BackupStore: Fallback to set URL/secret
    else Setting supported
        LonghornClient->>Setting: Update successful
    end
Loading

Possibly related PRs

Suggested reviewers

  • COLDTURNIP
  • chriscchien
  • roger-ryao

Poem

🐰 Backup Bunny's Ballad 🥕

In lines of code, a rabbit's might,
Backup targets now shine so bright!
Durations parsed with regex glee,
Settings dance with agility!
A testing tale of storage's art! 🚀


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.

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 (9)
e2e/libs/setting/setting.py (3)

17-22: Consider renaming to avoid repetition
SETTING_SETTING_BACKUPSTORE_POLL_INTERVAL_NOT_SUPPORTED has an extra “SETTING_” prefix. Consider renaming to maintain consistency (e.g. SETTING_BACKUPSTORE_POLL_INTERVAL_NOT_SUPPORTED).


58-80: Double-check exception handling flow
Currently, only exceptions containing SETTING_BACKUP_TARGET_NOT_SUPPORTED trigger a fallback to BackupStore. Other exceptions are just logged and swallowed. If upstream code throws different error shapes (e.g., no error.message), this may produce unhandled attribute errors.


107-115: Ensure robust exception checks
Like the prior method, any error unrelated to SETTING_BACKUP_TARGET_CREDENTIAL_SECRET_NOT_SUPPORTED is only logged. The code may benefit from an explicit check to avoid potential AttributeError on e.error.message.

e2e/libs/backupstore/base.py (6)

21-34: Regex-based duration parsing
This function properly converts K8s duration strings into seconds. Consider unit tests for edge cases or invalid suffixes.


67-79: Potential error handling improvement
All three getters rely on the default backup target object’s existence. If the default backup target is missing or invalid, you may want to handle that scenario more robustly.


80-87: Avoid partial update overhead
set_backupstore_url retrieves and reuses the poll interval and credential secret from the existing backup target. Consider factoring out common logic if additional set_ methods follow the same pattern.


88-95: Credential secret update logic
Similar to set_backupstore_url, a possible improvement is to unify these partial updates under one helper function.


106-114: Bulk backup store update
update_backupstore uses backupTargetUpdate with a default poll interval of 300. Consider referencing a shared constant or environment variable to avoid hardcoded values if requirements change later.


160-196: Partial implementations
All methods in BackupStore return NotImplemented, indicating placeholders for future extension. Ensure new functionalities are tested once implemented.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 57b5bc6 and be14dbb.

📒 Files selected for processing (2)
  • e2e/libs/backupstore/base.py (3 hunks)
  • e2e/libs/setting/setting.py (2 hunks)
🔇 Additional comments (10)
e2e/libs/setting/setting.py (3)

8-8: Import usage is valid
The BackupStore class is referenced below, so this import is appropriate and necessary.


26-26: Validate environment variable usage
BackupStore() is constructed directly here, but if the environment variable LONGHORN_BACKUPSTORE is not set or improperly formatted, this might cause unexpected errors. Consider adding fallback logic or warnings.


98-104: Improve fallback scenario
When an exception is caught, only backup target unsupported errors are handled. If the exception is raised for another reason, it is silently logged. Consider re-throwing or providing a clearer error response.

e2e/libs/backupstore/base.py (7)

4-4: Regex import is valid
import re is required by the duration-parsing function below.


8-8: Client import is appropriate
get_longhorn_client is used throughout for retrieving and updating backup targets.


10-12: Readable time units
Defining SECOND, MINUTE, and HOUR is clean and self-documenting.


14-18: Clear mapping for units
The duration_u dict design is straightforward. Just ensure no future expansions (e.g., days) are needed.


38-39: Default target setting
DEFAULT_BACKUPTARGET is set to "default". Ensure it matches the desired initial fallback behavior of the system.


96-102: Poll interval usage
poll_interval is expected in seconds here rather than a raw K8s duration. Confirm that calling code is adequately documented or validated so users pass a numeric value.


103-105: Reset method
reset_backupstore sets everything to defaults via update_backupstore(). This is straightforward and consistent with other logic.

Comment on lines +83 to +95
try:
self.update_setting(self.SETTING_BACKUP_TARGET, "", retry=False)
self.update_setting(self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET,
"",
retry=False)
self.update_setting(self.SETTING_BACKUPSTORE_POLL_INTERVAL,
"300",
retry=False)
except Exception as e:
if self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in e.error.message:
self.backupstore.reset_backupstore()
else:
logging(e)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fallback logic might need expansion
The reset_backupstore method handles only the backup target not supported scenario. If the credential secret or poll interval settings are also not supported, they might not reset properly here.

Copy link
Contributor

@roger-ryao roger-ryao left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@derekbit derekbit left a comment

Choose a reason for hiding this comment

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

LGTM

ref: longhorn/longhorn 5411, 10043

Signed-off-by: James Lu <[email protected]>
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/libs/backupstore/base.py (2)

21-33: Enhance duration conversion edge case handling

The duration conversion utility works for basic formats but could be improved to handle edge cases:

  1. Negative durations (e.g., "-1h")
  2. Decimal values (e.g., "1.5h")
  3. Empty string input
  4. Multiple occurrences of same unit (e.g., "1h2h")
 def from_k8s_duration_to_seconds(duration_s):
+    if not duration_s:
+        raise ValueError("Empty duration string")
+    if duration_s.startswith("-"):
+        raise ValueError("Negative durations not supported")
+
     total = 0
     pattern_str = r'([0-9]+)([smh]+)'
     pattern = re.compile(pattern_str)
     matches = pattern.findall(duration_s)
     if not len(matches):
-        raise Exception("Invalid duration {}".format(duration_s))
+        raise ValueError(f"Invalid duration format: {duration_s}")
+
+    seen_units = set()
     for v, u in matches:
+        if u in seen_units:
+            raise ValueError(f"Duplicate unit '{u}' in duration")
+        seen_units.add(u)
         total += int(v) * duration_u[u]
 
     return total

67-70: Add error handling for backup target operations

The backup target URL operations should include error handling to gracefully handle API failures.

     def get_backupstore_url(self):
-        return get_longhorn_client().by_id_backupTarget(
-                            self.DEFAULT_BACKUPTARGET).backupTargetURL
+        try:
+            return get_longhorn_client().by_id_backupTarget(
+                                self.DEFAULT_BACKUPTARGET).backupTargetURL
+        except Exception as e:
+            raise ValueError(f"Failed to get backup target URL: {str(e)}")

     def set_backupstore_url(self, url):
-        bt = get_longhorn_client().by_id_backupTarget(
-                            self.DEFAULT_BACKUPTARGET)
-        p_interval = from_k8s_duration_to_seconds(bt.pollInterval)
-        self.update_backupstore(url=url,
-                                credential_secret=bt.credentialSecret,
-                                poll_interval=p_interval)
+        try:
+            bt = get_longhorn_client().by_id_backupTarget(
+                                self.DEFAULT_BACKUPTARGET)
+            p_interval = from_k8s_duration_to_seconds(bt.pollInterval)
+            self.update_backupstore(url=url,
+                                    credential_secret=bt.credentialSecret,
+                                    poll_interval=p_interval)
+        except Exception as e:
+            raise ValueError(f"Failed to set backup target URL: {str(e)}")

Also applies to: 80-87

e2e/libs/setting/setting.py (2)

58-80: Improve error handling granularity

The error handling could be more specific to handle different types of settings separately and provide better error messages.

     try:
         self.update_setting(self.SETTING_BACKUP_TARGET,
                             backupsettings[0],
                             retry=False)
         if len(backupsettings) > 1:
             self.update_setting(
                 self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET,
                 backupsettings[1],
                 retry=False)

         self.update_setting(self.SETTING_BACKUPSTORE_POLL_INTERVAL,
                             poll_interval,
                             retry=False)
     except Exception as e:
-        if self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in e.error.message:
+        error_msg = getattr(e, 'error', e).message
+        if self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in error_msg:
             self.backupstore.set_backupstore_url(backupsettings[0])
             if len(backupsettings) > 1:
                 self.backupstore.set_backupstore_secret(
                     backupsettings[1])
             self.backupstore.set_backupstore_poll_interval(
                 poll_interval)
+        elif self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET_NOT_SUPPORTED in error_msg:
+            logging(f"Warning: Credential secret setting not supported: {error_msg}")
+            if len(backupsettings) > 1:
+                self.backupstore.set_backupstore_secret(backupsettings[1])
         else:
-            logging(e)
+            logging(f"Error setting backup store: {str(e)}")

97-115: Enhance error handling and logging in getter methods

The getter methods could benefit from more informative logging and consistent error handling.

     def get_backup_target(self):
         try:
-            return self.get_setting(self.SETTING_BACKUP_TARGET)
+            value = self.get_setting(self.SETTING_BACKUP_TARGET)
+            logging(f"Retrieved backup target from settings: {value}")
+            return value
         except Exception as e:
-            if self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in e.error.message:
-                return self.backupstore.get_backupstore_url()
+            error_msg = getattr(e, 'error', e).message
+            if self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in error_msg:
+                value = self.backupstore.get_backupstore_url()
+                logging(f"Retrieved backup target from backup store: {value}")
+                return value
             else:
-                logging(e)
+                logging(f"Error getting backup target: {str(e)}")
+                raise

     def get_secret(self):
         try:
-            return self.get_setting(
+            value = self.get_setting(
                 self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)
+            logging(f"Retrieved secret from settings")
+            return value
         except Exception as e:
-            if (self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET_NOT_SUPPORTED
-                    in e.error.message):
-                return self.backupstore.get_backupstore_secret()
+            error_msg = getattr(e, 'error', e).message
+            if (self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET_NOT_SUPPORTED
+                    in error_msg):
+                value = self.backupstore.get_backupstore_secret()
+                logging(f"Retrieved secret from backup store")
+                return value
             else:
-                logging(e)
+                logging(f"Error getting secret: {str(e)}")
+                raise
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between be14dbb and bfc6ee5.

📒 Files selected for processing (2)
  • e2e/libs/backupstore/base.py (3 hunks)
  • e2e/libs/setting/setting.py (2 hunks)
🔇 Additional comments (1)
e2e/libs/setting/setting.py (1)

83-95: Expand fallback logic for all unsupported settings

The reset_backupstore method only handles the backup target not supported scenario. Consider handling cases where credential secret or poll interval settings are not supported.

     try:
         self.update_setting(self.SETTING_BACKUP_TARGET, "", retry=False)
         self.update_setting(self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET,
                             "",
                             retry=False)
         self.update_setting(self.SETTING_BACKUPSTORE_POLL_INTERVAL,
                             "300",
                             retry=False)
     except Exception as e:
-        if self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in e.error.message:
+        error_msg = getattr(e, 'error', e).message
+        if (self.SETTING_BACKUP_TARGET_NOT_SUPPORTED in error_msg or
+            self.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET_NOT_SUPPORTED in error_msg or
+            self.SETTING_SETTING_BACKUPSTORE_POLL_INTERVAL_NOT_SUPPORTED in error_msg):
             self.backupstore.reset_backupstore()
         else:
             logging(e)

Comment on lines +160 to +196
class BackupStore(Base):

def __init__(self):
super().__init__()

def get_backup_volume_prefix(self, volume_name):
return NotImplemented

def get_backup_cfg_file_path(self, volume_name, backup_name):
return NotImplemented

def get_volume_cfg_file_path(self, volume_name):
return NotImplemented

def get_backup_blocks_dir(self, volume_name):
return NotImplemented

def create_file_in_backupstore(self):
return NotImplemented

def write_backup_cfg_file(self, volume_name, backup_name, data):
return NotImplemented

def delete_file_in_backupstore(self):
return NotImplemented

def delete_backup_cfg_file(self):
return NotImplemented

def delete_volume_cfg_file(self):
return NotImplemented

def delete_random_backup_block(self):
return NotImplemented

def count_backup_block_files(self):
return NotImplemented
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix abstract method implementations

The BackupStore class incorrectly uses NotImplemented constant instead of raising NotImplementedError. When implementing abstract methods, you should either provide a concrete implementation or raise NotImplementedError.

     def get_backup_volume_prefix(self, volume_name):
-        return NotImplemented
+        raise NotImplementedError("Method not implemented")

     def get_backup_cfg_file_path(self, volume_name, backup_name):
-        return NotImplemented
+        raise NotImplementedError("Method not implemented")

     # Apply similar changes to other methods...

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

@derekbit derekbit merged commit e23e21e into longhorn:master Dec 27, 2024
8 of 10 checks passed
@derekbit
Copy link
Member

@mergify backport v1.8.x

Copy link

mergify bot commented Dec 27, 2024

backport v1.8.x

✅ Backports have been created

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.

3 participants