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

Handle non-existing backup file #5590

Merged
merged 7 commits into from
Jan 31, 2025
Merged

Conversation

agners
Copy link
Member

@agners agners commented Jan 30, 2025

Proposed change

Currently handling if the backup tar-file of a previously scanned tar file vanished is rather inconsistent. Most API's return with 400 error code, but error handling varies from simple error message in logs (e.g. when deleting) up to printing a stack trace (e.g. restoring with password).

This PR consistently uses error 404 when the backup file vanished.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (which adds functionality to the supervisor)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to cli pull request:
  • Link to client library pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • The code has been formatted using Ruff (ruff format supervisor tests)
  • Tests have been added to verify that the new code works.

If API endpoints or add-on configuration are added/changed:

Summary by CodeRabbit

  • New Features

    • Introduced a new BackupFileNotFoundError exception to improve error handling for backup operations.
  • Bug Fixes

    • Enhanced error reporting for scenarios involving missing backup files.
    • Improved API response for backup-related file not found errors.
  • Tests

    • Added new test cases to verify error handling for backup file removal and restore operations.

These updates enhance the robustness of backup functionalities by providing clearer error messages and improved handling of missing backup files.

@agners agners added the bugfix A bug fix label Jan 30, 2025
Copy link

coderabbitai bot commented Jan 30, 2025

Warning

Rate limit exceeded

@agners has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 38 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 a3a5413 and 03bd728.

📒 Files selected for processing (9)
  • supervisor/api/backups.py (1 hunks)
  • supervisor/api/utils.py (5 hunks)
  • supervisor/backups/backup.py (2 hunks)
  • supervisor/backups/manager.py (3 hunks)
  • supervisor/exceptions.py (1 hunks)
  • supervisor/misc/tasks.py (2 hunks)
  • supervisor/resolution/fixups/system_clear_full_backup.py (2 hunks)
  • tests/api/test_backups.py (3 hunks)
  • tests/backups/test_manager.py (3 hunks)
📝 Walkthrough

Walkthrough

The changes introduce a new exception BackupFileNotFoundError across multiple files in the supervisor project to improve error handling for backup-related operations. This exception provides more specific error reporting when backup files are missing during various tasks such as backup creation, restoration, and removal. The modifications enhance the granularity of error handling by allowing more precise tracking and reporting of file-related issues in backup processes.

Changes

File Change Summary
supervisor/exceptions.py Added new BackupFileNotFoundError exception class inheriting from BackupError
supervisor/api/backups.py Integrated BackupFileNotFoundError in backup and restore methods with improved error handling
supervisor/backups/backup.py Replaced generic BackupError with BackupFileNotFoundError in file opening logic
supervisor/backups/manager.py Modified backup removal method to raise BackupFileNotFoundError when file is not found; updated method signature
supervisor/misc/tasks.py Added import and error handling for BackupFileNotFoundError in backup cleanup
supervisor/resolution/fixups/system_clear_full_backup.py Added error handling for BackupFileNotFoundError during backup removal
tests/api/test_backups.py Added new test cases for handling missing backup files
tests/backups/test_manager.py Added test to verify BackupFileNotFoundError behavior

Sequence Diagram

sequenceDiagram
    participant API as Backup API
    participant Manager as Backup Manager
    participant Filesystem as File System

    API->>Manager: Remove Backup
    Manager->>Filesystem: Attempt to Unlink Backup File
    alt File Not Found
        Filesystem-->>Manager: FileNotFoundError
        Manager->>Manager: Raise BackupFileNotFoundError
        Manager-->>API: BackupFileNotFoundError
        API->>API: Generate 404 Error Response
    else File Successfully Removed
        Filesystem-->>Manager: File Removed Successfully
        Manager-->>API: Backup Removed
    end
Loading

This sequence diagram illustrates the new error handling flow when attempting to remove a backup file that does not exist, demonstrating how the BackupFileNotFoundError is propagated and handled.


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 or @coderabbitai title 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 (1)
supervisor/backups/manager.py (1)

Line range hint 1773-1774: Simplify error handling logic.

The error handling for OSError can be simplified by removing redundant error checks since the error is re-raised in both cases.

-    with pytest.raises(OSError):
-        coresys.backups.remove(backup)
-    assert coresys.core.healthy is True
-
-    err.errno = errno.EBADMSG
-    with pytest.raises(OSError):
-        coresys.backups.remove(backup)
+    err.errno = errno.EBADMSG
+    with pytest.raises(OSError):
+        coresys.backups.remove(backup)

Also applies to: 1778-1779

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d1d8446 and 6de2179.

📒 Files selected for processing (8)
  • supervisor/api/backups.py (5 hunks)
  • supervisor/backups/backup.py (2 hunks)
  • supervisor/backups/manager.py (3 hunks)
  • supervisor/exceptions.py (1 hunks)
  • supervisor/misc/tasks.py (2 hunks)
  • supervisor/resolution/fixups/system_clear_full_backup.py (2 hunks)
  • tests/api/test_backups.py (2 hunks)
  • tests/backups/test_manager.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
supervisor/exceptions.py (6)

Pattern */**(html|markdown|md): - For instructional content in documentation, use a direct and authoritative tone. Avoid expressions of politeness such as 'may' or 'please', and ensure the goal of the instruction is fronted.

  • Apply the Microsoft Style Guide to ensure documentation maintains clarity and conciseness.
  • In step-by-step instructions, front the location phrase in the instructional sentence.
  • In step-by-step instructions, front the 'goal' in the instructional sentence.
  • In step-by-step instructions, if in doubt what to front, front the 'goal' before the location phrase in the instructional sentence.
  • do not hyphenate terms like 'top-right' or 'bottom-left' with 'corner'

Pattern */**(html|markdown|md): - Use bold to mark UI strings.

  • If "" are used to mark UI strings, replace them by bold.

Pattern */**(html|markdown|md): - Be brief in your replies and don't add fluff like "thank you for..." and "Please let me know if"


Pattern */**(html|markdown|md): - Use sentence-style capitalization also in headings.


Pattern */**(html|markdown|md): do not comment on HTML used for icons


Pattern */**(html|markdown|md): Avoid flagging inline HTML for embedding videos in future reviews for this repository.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build i386 supervisor
  • GitHub Check: Build amd64 supervisor
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
  • GitHub Check: Run tests Python 3.13.1
🔇 Additional comments (8)
supervisor/exceptions.py (1)

662-664: LGTM! Well-structured exception class.

The new BackupFileNotFoundError exception is appropriately placed in the hierarchy and follows the established pattern.

supervisor/api/backups.py (1)

324-325: LGTM! Consistent error handling.

The error handling in _background_backup_task and remove methods is well-implemented and consistent, properly converting BackupFileNotFoundError to appropriate API errors.

Also applies to: 467-470

supervisor/resolution/fixups/system_clear_full_backup.py (1)

36-39: LGTM! Appropriate error handling for cleanup task.

The error handling is well-implemented:

  • Catches BackupFileNotFoundError without interrupting the cleanup process
  • Uses debug level logging which is appropriate for this scenario
supervisor/misc/tasks.py (1)

372-375: LGTM! Well-implemented error handling.

The error handling in the cleanup task is appropriate:

  • Properly catches BackupFileNotFoundError
  • Uses debug level logging
  • Allows the cleanup process to continue
supervisor/backups/backup.py (1)

Line range hint 521-525: LGTM! Improved error handling specificity.

Good change to use a dedicated BackupFileNotFoundError exception for better error handling when a backup file is missing. This makes the error more specific and easier to handle by consumers.

supervisor/backups/manager.py (1)

296-304: LGTM! Consistent error handling for missing backup files.

Good change to use BackupFileNotFoundError when a backup file is missing during removal. This aligns with the error handling in the open method.

tests/api/test_backups.py (1)

506-513: LGTM! Good test coverage for missing backup file.

The test case properly verifies that attempting to remove a non-existent backup file returns a 404 status code and includes the correct error message.

tests/backups/test_manager.py (1)

2080-2099: LGTM! Comprehensive test for file not found error.

Good test case that verifies the BackupFileNotFoundError is raised when attempting to remove a non-existent backup file. The test properly mocks the file system error and checks the exception.

supervisor/api/backups.py Outdated Show resolved Hide resolved
Copy link
Contributor

@mdegat01 mdegat01 left a comment

Choose a reason for hiding this comment

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

Main change is that we should only raise exceptions that extend from HassioError once we catch a system one like OSError in an except block to denote to the upstream that its been handled. Also I think extending from APINotFound is a bit cleaner.

supervisor/backups/manager.py Outdated Show resolved Hide resolved
supervisor/exceptions.py Show resolved Hide resolved
@home-assistant
Copy link

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant home-assistant bot marked this pull request as draft January 30, 2025 16:28
@agners agners requested a review from mdegat01 January 30, 2025 16:53
tests/api/test_backups.py Outdated Show resolved Hide resolved
@agners agners force-pushed the handle-non-existing-backup-file branch from 314c7d3 to 55d01f9 Compare January 31, 2025 10:32
@agners agners force-pushed the handle-non-existing-backup-file branch from 55d01f9 to 03bd728 Compare January 31, 2025 10:33
@agners agners marked this pull request as ready for review January 31, 2025 10:35
@home-assistant home-assistant bot requested a review from mdegat01 January 31, 2025 10:35
@agners agners merged commit 30cbb03 into main Jan 31, 2025
20 checks passed
@agners agners deleted the handle-non-existing-backup-file branch January 31, 2025 13:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants