-
Notifications
You must be signed in to change notification settings - Fork 2.6k
SentinelManagedConnection searches for new master upon connection failure (#3560) #3601
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
ManelCoutinhoSensei
wants to merge
3
commits into
redis:master
Choose a base branch
from
ManelCoutinhoSensei:sentinel-master-detection
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 |
---|---|---|
@@ -1,12 +1,18 @@ | ||
import random | ||
import socket | ||
import weakref | ||
from typing import Optional | ||
|
||
from redis.client import Redis | ||
from redis.commands import SentinelCommands | ||
from redis.connection import Connection, ConnectionPool, SSLConnection | ||
from redis.exceptions import ConnectionError, ReadOnlyError, ResponseError, TimeoutError | ||
from redis.utils import str_if_bytes | ||
from redis.exceptions import ( | ||
ConnectionError, | ||
ReadOnlyError, | ||
RedisError, | ||
ResponseError, | ||
TimeoutError, | ||
) | ||
|
||
|
||
class MasterNotFoundError(ConnectionError): | ||
|
@@ -35,11 +41,39 @@ def __repr__(self): | |
|
||
def connect_to(self, address): | ||
self.host, self.port = address | ||
super().connect() | ||
if self.connection_pool.check_connection: | ||
self.send_command("PING") | ||
if str_if_bytes(self.read_response()) != "PONG": | ||
raise ConnectionError("PING failed") | ||
|
||
if self._sock: | ||
return | ||
try: | ||
sock = self._connect() | ||
except socket.timeout: | ||
raise TimeoutError("Timeout connecting to server") | ||
except OSError as e: | ||
raise ConnectionError(self._error_message(e)) | ||
|
||
self._sock = sock | ||
try: | ||
if self.redis_connect_func is None: | ||
# Use the default on_connect function | ||
self.on_connect_check_health( | ||
check_health=self.connection_pool.check_connection | ||
) | ||
else: | ||
# Use the passed function redis_connect_func | ||
self.redis_connect_func(self) | ||
except RedisError: | ||
# clean up after any error in on_connect | ||
self.disconnect() | ||
raise | ||
|
||
# run any user callbacks. right now the only internal callback | ||
# is for pubsub channel/pattern resubscription | ||
# first, remove any dead weakrefs | ||
self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()] | ||
for ref in self._connect_callbacks: | ||
callback = ref() | ||
if callback: | ||
callback(self) | ||
|
||
def _connect_retry(self): | ||
if self._sock: | ||
|
@@ -305,13 +339,16 @@ def discover_master(self, service_name): | |
""" | ||
collected_errors = list() | ||
for sentinel_no, sentinel in enumerate(self.sentinels): | ||
# print(f"Sentinel: {sentinel_no}") | ||
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. Commented print statements should be removed. |
||
try: | ||
masters = sentinel.sentinel_masters() | ||
except (ConnectionError, TimeoutError) as e: | ||
collected_errors.append(f"{sentinel} - {e!r}") | ||
continue | ||
state = masters.get(service_name) | ||
# print(f"Found master: {state}") | ||
if state and self.check_master_state(state, service_name): | ||
# print("Valid state") | ||
# Put this sentinel at the top of the list | ||
self.sentinels[0], self.sentinels[sentinel_no] = ( | ||
sentinel, | ||
|
@@ -324,6 +361,7 @@ def discover_master(self, service_name): | |
else state["ip"] | ||
) | ||
return ip, state["port"] | ||
# print("Ignoring it") | ||
|
||
error_info = "" | ||
if len(collected_errors) > 0: | ||
|
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,34 @@ | ||
import socket | ||
|
||
from redis.retry import Retry | ||
from redis.sentinel import SentinelManagedConnection | ||
from redis.backoff import NoBackoff | ||
from unittest import mock | ||
|
||
|
||
def test_connect_retry_on_timeout_error(master_host): | ||
"""Test that the _connect function is retried in case of a timeout""" | ||
connection_pool = mock.Mock() | ||
connection_pool.get_master_address = mock.Mock( | ||
return_value=(master_host[0], master_host[1]) | ||
) | ||
conn = SentinelManagedConnection( | ||
retry_on_timeout=True, | ||
retry=Retry(NoBackoff(), 3), | ||
connection_pool=connection_pool, | ||
) | ||
origin_connect = conn._connect | ||
conn._connect = mock.Mock() | ||
|
||
def mock_connect(): | ||
# connect only on the last retry | ||
if conn._connect.call_count <= 2: | ||
raise socket.timeout | ||
else: | ||
return origin_connect() | ||
|
||
conn._connect.side_effect = mock_connect | ||
conn.connect() | ||
assert conn._connect.call_count == 3 | ||
assert connection_pool.get_master_address.call_count == 3 | ||
conn.disconnect() |
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.
That’s quite a bit of code duplication. Perhaps the approach with a flag would be preferable after all. Since
connect()
is part of the interface, I think it’s better not to modify it directly. Instead, you can use theconnect_with_health_check()
method from AbstractConnection. You could introduce an additional flag to enable or disableretry_socket_connect
, with a default value that preserves the current behaviour.