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

CU-86bzu8m1g - Increase Lease in Dgraph while restoring Backup using API #326

Conversation

sushantpatil1214
Copy link
Collaborator

@sushantpatil1214 sushantpatil1214 commented Sep 26, 2024

Summary by CodeRabbit

  • New Features
    • Introduced functions to manage lease values for the Dgraph database, enhancing the lease management process.
    • Added functionality to retrieve and increase lease values as needed before processing records.

@rcrichton
Copy link
Member

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes introduce two new functions in the Dgraph restore API: get_current_lease and increase_lease. The get_current_lease function retrieves the current maximum leased UID from the Dgraph Zero /state endpoint, while increase_lease adjusts the lease value if necessary. These functions are integrated into the existing workflow to enhance lease management for Dgraph databases.

Changes

File Path Change Summary
devops/linux/docker/backup_restore/dgraph-restore-api.py - Added get_current_lease(endpoint) to retrieve the current max leased UID.
- Added increase_lease(endpoint, new_value) to adjust the lease value if below the specified new value.

Possibly related PRs

Poem

🐇 In the land of code where the Dgraph plays,
New functions hop in, brightening our days.
Leases managed with care, oh what a delight,
With get and increase, everything feels right!
So let’s cheer for the changes, a joyful parade,
In the world of backups, our progress is made! 🎉


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 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
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
devops/linux/docker/backup_restore/dgraph-restore-api.py (2)

15-31: LGTM with a minor suggestion

The get_current_lease function is well-implemented with proper error handling and clear output. Good job on using requests.raise_for_status() to handle HTTP errors.

A minor suggestion for improvement:
Consider using a logging library instead of print statements for better control over output in different environments.

Replace print statements with logging:

+import logging
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)

 def get_current_lease(endpoint):
     """Fetches the current maxLeasedUid from the Dgraph Zero /state endpoint."""
     try:
         response = requests.get(f"{endpoint}/state")
         response.raise_for_status()  # Raise an exception for HTTP errors
         data = response.json()
         # Extracting the maxLeasedUid from the JSON response
         max_leased_uid = data.get('maxUID', None)
         if max_leased_uid is not None:
-            print(f"Current maxLeasedUid: {max_leased_uid}")
+            logger.info(f"Current maxLeasedUid: {max_leased_uid}")
             return max_leased_uid
         else:
-            print("Error: maxLeasedUid not found in the response.")
+            logger.error("maxLeasedUid not found in the response.")
             return None
     except requests.RequestException as e:
-        print(f"Error fetching current lease: {e}")
+        logger.error(f"Error fetching current lease: {e}")
         return None

Line range hint 1-116: Summary of review for dgraph-restore-api.py

The changes introduced in this file align well with the PR objective of increasing the lease in Dgraph while restoring backup using API. The new functions get_current_lease and increase_lease provide the necessary functionality to manage leases effectively.

Key points for improvement:

  1. Consider using a logging library instead of print statements for better output control.
  2. In the increase_lease function:
    • Use POST instead of GET for the /assign endpoint to adhere to RESTful principles.
    • Implement more specific exception handling.
    • Avoid logging potentially sensitive response content.
  3. Add error handling for the increase_lease call in the process_json_data function.
  4. Make the new_lease_value configurable through environment variables for flexibility.

These improvements will enhance the robustness, security, and maintainability of the code. Overall, the changes are on the right track and with these refinements, the implementation will be solid.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8927d25 and 5b7954a.

📒 Files selected for processing (1)
  • devops/linux/docker/backup_restore/dgraph-restore-api.py (3 hunks)
🔇 Additional comments (3)
devops/linux/docker/backup_restore/dgraph-restore-api.py (3)

33-52: ⚠️ Potential issue

Improve HTTP method, error handling, and security in increase_lease function

While the overall logic of the increase_lease function is sound, there are several areas for improvement:

  1. HTTP Method: Using a GET request for an operation that modifies server state (increasing the lease) is not RESTful. Consider using a POST or PUT request instead.

  2. Error Handling: The current error handling is too broad. Consider catching more specific exceptions and handling them accordingly.

  3. Security: Printing the entire response content on error could potentially leak sensitive information. It's better to log a sanitized version of the error.

  4. Type Conversion: The type conversion of current_value to int is done after the None check, which could lead to a TypeError if get_current_lease returns None.

Here's a suggested refactor addressing these points:

def increase_lease(endpoint, new_value):
    """Increases the lease value if it's below the new_value."""
    current_value = get_current_lease(endpoint)
    if current_value is None:
        logger.error("Unable to fetch the current lease value. Exiting.")
        return

    try:
        current_value = int(current_value)
    except ValueError:
        logger.error(f"Invalid current lease value: {current_value}")
        return

    if current_value < new_value:
        try:
            data = {'what': 'uids', 'num': new_value}
            response = requests.post(f"{endpoint}/assign", json=data)
            response.raise_for_status()
            logger.info(f"Lease increased to {new_value}.")
        except requests.exceptions.HTTPError as e:
            logger.error(f"HTTP error occurred while increasing lease: {e}")
        except requests.exceptions.RequestException as e:
            logger.error(f"Error occurred while increasing lease: {e}")
    else:
        logger.info(f"Current lease ({current_value}) is already greater than or equal to {new_value}. No action taken.")

This refactored version:

  1. Uses POST instead of GET for the /assign endpoint.
  2. Handles type conversion of current_value more safely.
  3. Uses more specific exception handling.
  4. Avoids logging potentially sensitive response content.
  5. Uses logging instead of print statements for consistency with earlier suggestions.
#!/bin/bash
# Check if the /assign endpoint is used with POST method elsewhere in the codebase
rg --type python "requests\.post.*?/assign" -g '!dgraph-restore-api.py'

105-105: ⚠️ Potential issue

Add error handling for increase_lease call

The addition of increase_lease(endpoint, new_lease_value) at the beginning of process_json_data is a good approach to ensure sufficient lease before processing. However, there's currently no error handling if this operation fails.

Consider adding error handling to ensure the process doesn't continue if the lease increase fails. Here's a suggested modification:

def process_json_data(golden_records):
    if not increase_lease(endpoint, new_lease_value):
        logger.error("Failed to increase lease. Aborting process.")
        return

    for golden_record in golden_records:
        # ... rest of the function ...

This change assumes that you modify the increase_lease function to return a boolean indicating success or failure. If you prefer not to modify increase_lease, you could wrap the call in a try-except block instead.

#!/bin/bash
# Check if increase_lease is used elsewhere in the codebase and if it's consistently handled
rg --type python "increase_lease\(.*?\)" -g '!dgraph-restore-api.py'

12-14: Verify endpoint change and consider new_lease_value implications

  1. The endpoint has been changed to use port 6080. Please confirm if this is the correct port for communicating with the Dgraph Zero node.

  2. The new_lease_value is set to a very large number (50 trillion). While this may be necessary for your use case, consider the following:

    • Ensure this value aligns with your system's capacity and expected data growth.
    • Document the reasoning behind this specific value for future reference.
    • Consider making this value configurable (e.g., through environment variables) for easier adjustments in different environments.

Copy link
Collaborator

@MatthewErispe MatthewErispe left a comment

Choose a reason for hiding this comment

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

LGTM

@MatthewErispe MatthewErispe merged commit 76b7f24 into dev Oct 15, 2024
6 checks passed
@MatthewErispe MatthewErispe deleted the CU-86bzu8m1g_Increase-Lease-in-Dgraph-while-restoring-Backup-using-API branch October 15, 2024 11:59
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