-
Notifications
You must be signed in to change notification settings - Fork 3.5k
client: add Kubernetes-aware retry helpers #2634
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
Open
sttts
wants to merge
3
commits into
kubernetes-client:master
Choose a base branch
from
sttts:agent/kubernetes-retry-utils
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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 @@ | ||
| ../../base/retry.py |
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,113 @@ | ||
| # Copyright 2026 The Kubernetes Authors. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import asyncio | ||
| import random | ||
| from typing import Awaitable, Callable, TypeVar | ||
|
|
||
| from ._retry_base import ( | ||
| Backoff, | ||
| DEFAULT_BACKOFF, | ||
| DEFAULT_RETRY, | ||
| DEFAULT_RETRY_AFTER_BACKOFF, | ||
| _delay, | ||
| is_conflict, | ||
| is_retry_after_response, | ||
| is_too_many_requests, | ||
| retry_after_backoff, | ||
| retry_after_max_retries, | ||
| retry_after_seconds, | ||
| ) | ||
|
|
||
|
|
||
| T = TypeVar("T") | ||
|
|
||
|
|
||
| # The retry helpers in this module are async 1:1 Python implementations of the | ||
| # Kubernetes Go retry algorithms used by client-go: | ||
| # - https://github.com/kubernetes/client-go/blob/master/util/retry/util.go | ||
| # - https://github.com/kubernetes/client-go/blob/master/rest/with_retry.go | ||
| async def async_on_error( | ||
| backoff: Backoff, | ||
| retriable: Callable[[Exception], bool], | ||
| fn: Callable[[], Awaitable[T]], | ||
| sleep_func: Callable[[float], Awaitable[None]] = asyncio.sleep, | ||
| random_func: Callable[[], float] = random.random, | ||
| ) -> T: | ||
| """Async 1:1 implementation of client-go ``retry.OnError``.""" | ||
|
|
||
| steps = backoff.steps | ||
| duration = backoff.duration | ||
| last_error = None | ||
| while steps > 0: | ||
| try: | ||
| return await fn() | ||
| except Exception as error: | ||
| if not retriable(error): | ||
| raise | ||
| last_error = error | ||
|
|
||
| if steps == 1: | ||
| break | ||
|
|
||
| delay, duration, steps = _delay( | ||
| steps, duration, backoff, random_func) | ||
| await sleep_func(delay) | ||
|
|
||
| raise last_error | ||
|
|
||
|
|
||
| async def async_retry_on_conflict( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ditto |
||
| fn: Callable[[], Awaitable[T]], | ||
| backoff: Backoff = DEFAULT_RETRY, | ||
| sleep_func: Callable[[float], Awaitable[None]] = asyncio.sleep, | ||
| random_func: Callable[[], float] = random.random, | ||
| ) -> T: | ||
| """Async 1:1 implementation of client-go ``retry.RetryOnConflict``.""" | ||
|
|
||
| return await async_on_error( | ||
| backoff, is_conflict, fn, sleep_func, random_func) | ||
|
|
||
|
|
||
| async def async_on_retry_after_error( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ditto |
||
| backoff: Backoff, | ||
| retriable: Callable[[Exception], bool], | ||
| fn: Callable[[], Awaitable[T]], | ||
| sleep_func: Callable[[float], Awaitable[None]] = asyncio.sleep, | ||
| random_func: Callable[[], float] = random.random, | ||
| ) -> T: | ||
| """Async implementation of client-go REST Retry-After sleep semantics.""" | ||
|
|
||
| steps = backoff.steps | ||
| duration = backoff.duration | ||
| last_error = None | ||
| while steps > 0: | ||
| try: | ||
| return await fn() | ||
| except Exception as error: | ||
| if not retriable(error): | ||
| raise | ||
| last_error = error | ||
|
|
||
| if steps == 1: | ||
| break | ||
|
|
||
| delay, duration, steps = _delay( | ||
| steps, duration, backoff, random_func) | ||
| retry_after = retry_after_seconds(error) | ||
| if retry_after is not None and retry_after > delay: | ||
| delay = retry_after | ||
| await sleep_func(delay) | ||
|
|
||
| raise last_error | ||
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,124 @@ | ||
| # Copyright 2026 The Kubernetes Authors. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import unittest | ||
|
|
||
| from kubernetes.aio.utils.retry import ( | ||
| Backoff, | ||
| DEFAULT_RETRY, | ||
| async_on_error, | ||
| async_on_retry_after_error, | ||
| async_retry_on_conflict, | ||
| is_too_many_requests, | ||
| retry_after_seconds, | ||
| ) | ||
|
|
||
|
|
||
| class FakeError(Exception): | ||
|
|
||
| def __init__(self, status, headers=None): | ||
| super().__init__("status {0}".format(status)) | ||
| self.status = status | ||
| self.headers = headers or {} | ||
|
|
||
|
|
||
| class AioRetryTest(unittest.IsolatedAsyncioTestCase): | ||
|
|
||
| def test_default_retry_matches_client_go(self): | ||
| self.assertEqual( | ||
| DEFAULT_RETRY, | ||
| Backoff(steps=5, duration=0.01, factor=1.0, jitter=0.1), | ||
| ) | ||
|
|
||
| def test_retry_after_seconds_parses_delay_seconds(self): | ||
| error = FakeError(429, {"Retry-After": "7"}) | ||
|
|
||
| self.assertEqual(retry_after_seconds(error), 7.0) | ||
|
|
||
| async def test_async_on_error_retries_retriable_errors(self): | ||
| attempts = [] | ||
| sleeps = [] | ||
|
|
||
| async def fn(): | ||
| attempts.append(1) | ||
| if len(attempts) < 3: | ||
| raise FakeError(500) | ||
| return "ok" | ||
|
|
||
| async def sleep(delay): | ||
| sleeps.append(delay) | ||
|
|
||
| result = await async_on_error( | ||
| Backoff(steps=4, duration=1.0, factor=2.0), | ||
| lambda e: getattr(e, "status", None) == 500, | ||
| fn, | ||
| sleep_func=sleep, | ||
| random_func=lambda: 0.0, | ||
| ) | ||
|
|
||
| self.assertEqual(result, "ok") | ||
| self.assertEqual(len(attempts), 3) | ||
| self.assertEqual(sleeps, [1.0, 2.0]) | ||
|
|
||
| async def test_async_on_retry_after_error_honors_retry_after_for_429(self): | ||
| attempts = [] | ||
| sleeps = [] | ||
|
|
||
| async def fn(): | ||
| attempts.append(1) | ||
| if len(attempts) < 2: | ||
| raise FakeError(429, {"Retry-After": "3"}) | ||
| return "ok" | ||
|
|
||
| async def sleep(delay): | ||
| sleeps.append(delay) | ||
|
|
||
| result = await async_on_retry_after_error( | ||
| Backoff(steps=3, duration=1.0, factor=2.0), | ||
| is_too_many_requests, | ||
| fn, | ||
| sleep_func=sleep, | ||
| random_func=lambda: 0.0, | ||
| ) | ||
|
|
||
| self.assertEqual(result, "ok") | ||
| self.assertEqual(sleeps, [3.0]) | ||
|
|
||
| async def test_async_retry_on_conflict_retries(self): | ||
| attempts = [] | ||
| sleeps = [] | ||
|
|
||
| async def fn(): | ||
| attempts.append(1) | ||
| if len(attempts) < 3: | ||
| raise FakeError(409) | ||
| return "updated" | ||
|
|
||
| async def sleep(delay): | ||
| sleeps.append(delay) | ||
|
|
||
| result = await async_retry_on_conflict( | ||
| fn, | ||
| backoff=Backoff(steps=3, duration=1.0, factor=1.0), | ||
| sleep_func=sleep, | ||
| random_func=lambda: 0.0, | ||
| ) | ||
|
|
||
| self.assertEqual(result, "updated") | ||
| self.assertEqual(len(attempts), 3) | ||
| self.assertEqual(sleeps, [1.0, 1.0]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
do we need async_ prefix in the function name? the function is under aio/utils, so it should be async to users. WDYT?