-
Notifications
You must be signed in to change notification settings - Fork 77
Provide a @retry decorator to automatically retry Python functions in Checkbox jobs (new) #1453
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5dbb5c0
Add a retry decorator for easier retries in Checkbox jobs
pieqq 16a2728
Modify the networking_http.py script to use the @retry decorator
pieqq ae74ca7
Max feedback and more
pieqq 7ae34dd
Modify networking HTTP script following retry decorator refactoring
pieqq 2937c82
black formatting
pieqq 73481d7
Handle negative attempts and delay
pieqq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # This file is part of Checkbox. | ||
| # | ||
| # Copyright 2024 Canonical Ltd. | ||
| # Written by: | ||
| # Pierre Equoy <pierre.equoy@canonical.com> | ||
| # | ||
| # Checkbox is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License version 3, | ||
| # as published by the Free Software Foundation. | ||
| # | ||
| # Checkbox is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with Checkbox. If not, see <http://www.gnu.org/licenses/>. | ||
| """ | ||
| checkbox_support.helpers.retry | ||
| ============================================= | ||
|
|
||
| Utility class providing functionalities to let functions retry with a | ||
| delay, backoff and jitter. | ||
| """ | ||
| import functools | ||
| import random | ||
| import time | ||
| from unittest.mock import patch | ||
|
|
||
|
|
||
| def run_with_retry(f, max_attempts, delay, *args, **kwargs): | ||
| """ | ||
| Run the f function. If it fails, retry for up to max_attempts times, adding | ||
| a backoff and a jitter on top of a delay (in seconds). If none of the runs | ||
| succeed, raise the encountered exception. | ||
| """ | ||
| initial_delay = 1 | ||
| backoff_factor = 2 | ||
| if max_attempts < 1: | ||
| raise ValueError( | ||
| "max_attempts should be at least 1 ({} was used)".format( | ||
| max_attempts | ||
| ) | ||
| ) | ||
| if delay < 1: | ||
| raise ValueError( | ||
| "delay should be at least 1 ({} was used)".format(delay) | ||
| ) | ||
| for attempt in range(1, max_attempts + 1): | ||
| attempt_string = "Attempt {}/{}".format(attempt, max_attempts) | ||
| print() | ||
| print("=" * len(attempt_string)) | ||
| print(attempt_string) | ||
| print("=" * len(attempt_string)) | ||
| try: | ||
| result = f(*args, **kwargs) | ||
| return result | ||
| except BaseException as e: | ||
| print("Attempt {} failed:".format(attempt)) | ||
| print(e) | ||
| print() | ||
| if attempt >= max_attempts: | ||
| print("All the attempts have failed!") | ||
| raise | ||
| min_delay = min( | ||
| initial_delay * (backoff_factor**attempt), | ||
| delay, | ||
| ) | ||
| jitter = random.uniform( | ||
| 0, delay * 0.5 | ||
| ) # Jitter: up to 50% of the delay | ||
| total_delay = min_delay + jitter | ||
| print( | ||
| "Waiting {:.2f} seconds before retrying...".format(total_delay) | ||
| ) | ||
| time.sleep(total_delay) | ||
|
|
||
|
|
||
| def retry(max_attempts, delay): | ||
| """ | ||
| Run the decorated function. If it fails, retry for up to max_attempts | ||
| times, adding a backoff and a jitter on top of a delay (in seconds). | ||
| If none of the runs succeed, raise the encountered exception. | ||
| """ | ||
|
|
||
| def decorator_retry(f): | ||
| @functools.wraps(f) | ||
| def _f(*args, **kwargs): | ||
| return run_with_retry(f, max_attempts, delay, *args, **kwargs) | ||
|
|
||
| return _f | ||
|
|
||
| return decorator_retry | ||
|
|
||
|
|
||
| def fake_run_with_retry(f, max_attempts, delay, *args, **kwargs): | ||
| return f(*args, **kwargs) | ||
|
|
||
|
|
||
| mock_timeout = functools.partial( | ||
| patch, | ||
| "checkbox_support.helpers.retry.run_with_retry", | ||
| new=fake_run_with_retry, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # This file is part of Checkbox. | ||
| # | ||
| # Copyright 2024 Canonical Ltd. | ||
| # Written by: | ||
| # Pierre Equoy <pierre.equoy@canonical.com> | ||
| # | ||
| # Checkbox is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License version 3, | ||
| # as published by the Free Software Foundation. | ||
| # | ||
| # Checkbox is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with Checkbox. If not, see <http://www.gnu.org/licenses/>. | ||
|
|
||
| from unittest import TestCase | ||
| from unittest.mock import patch | ||
| from io import StringIO | ||
|
|
||
| from checkbox_support.helpers.retry import fake_run_with_retry, retry | ||
|
|
||
|
|
||
| class TestRetry(TestCase): | ||
| @patch("time.sleep") | ||
| def test_decorator_ok(self, mock_sleep): | ||
| @retry(5, 10) | ||
| def f(first, second, third): | ||
| return (first, second, third) | ||
|
|
||
| self.assertEqual(f(1, 2, 3), (1, 2, 3)) | ||
|
|
||
| @patch("time.sleep") | ||
| def test_decorator_fail(self, mock_sleep): | ||
| @retry(3, 10) | ||
| def f(): | ||
| return 1 / 0 | ||
|
|
||
| with self.assertRaises(ZeroDivisionError): | ||
| f() | ||
|
|
||
| @patch("time.sleep") | ||
| @patch("sys.stdout", new_callable=StringIO) | ||
| def test_decorator_max_attempts(self, mock_stdout, mock_sleep): | ||
| @retry(max_attempts=7, delay=10) | ||
| def f(): | ||
| return 1 / 0 | ||
|
|
||
| with self.assertRaises(ZeroDivisionError): | ||
| f() | ||
| self.assertIn("Attempt 7 failed", mock_stdout.getvalue()) | ||
| self.assertNotIn("Attempt 8 failed", mock_stdout.getvalue()) | ||
|
|
||
| def test_decorator_wrong_max_attempts(self): | ||
| @retry(-1, 10) | ||
| def f(): | ||
| return 1 / 0 | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| f() | ||
|
|
||
| def test_decorator_wrong_delay(self): | ||
| @retry(2, -1) | ||
| def f(): | ||
| return 1 / 0 | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| f() | ||
|
|
||
| def test_identity(self): | ||
| def k(*args, **kwargs): | ||
| return (args, kwargs) | ||
|
|
||
| self.assertEqual( | ||
| k(1, 2, 3, abc=10), fake_run_with_retry(k, 5, 10, 1, 2, 3, abc=10) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.