Skip to content

Commit 83b3e14

Browse files
committed
✨ Add hostname resolve when master host is not ip address
Fixes #1 Signed-off-by: Muhammed Hussein Karimi <[email protected]>
1 parent 7b8de59 commit 83b3e14

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

haproxy_redis_sentinel/handler.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
from socket import gethostbyname
12
from time import sleep
23
from typing import Any
34
from enum import StrEnum
4-
from utils import send_command, is_empty
5+
from utils import is_ipv4, send_command, is_empty
56
from redis import Redis
67
from redis.retry import Retry
78
from redis.backoff import FullJitterBackoff
@@ -131,6 +132,11 @@ def add_server(self, address: str):
131132
Add a new server to HAProxy (Used for initial sets).
132133
:param address: Address of the new server
133134
"""
135+
host = address.split(":")[0]
136+
port = address.split(":")[1]
137+
if not is_ipv4(host):
138+
host = gethostbyname(host)
139+
address = f"{host}:{port}"
134140
out = self.send_command(
135141
f"add server {self.haproxy_backend}/{self.haproxy_server_name} {address}" # noqa: E501
136142
)
@@ -146,6 +152,8 @@ def set_server_address(self, host: str, port: int):
146152
:param host: Host of the new server
147153
:param port: Port of the new server
148154
"""
155+
if not is_ipv4(host):
156+
host = gethostbyname(host)
149157
self.send_command(
150158
[
151159
f"set server {self.haproxy_backend}/{self.haproxy_server_name} addr {host}", # noqa: E501

haproxy_redis_sentinel/utils.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
11
import socket
2+
import re
23

3-
__all__ = ["send_command", "is_empty"]
4+
__all__ = ["send_command", "is_empty", "is_ipv4"]
5+
6+
7+
def is_ipv4(ip: str) -> bool:
8+
"""
9+
Check if a given string is a valid IP address.
10+
:param ip: IP address to check
11+
:return: True if valid, False otherwise
12+
"""
13+
pattern = re.compile(
14+
r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" # noqa: E501
15+
)
16+
return bool(pattern.match(ip))
417

518

619
def encode_command(command: str) -> bytes:

0 commit comments

Comments
 (0)