Skip to content

Commit

Permalink
ctdb: improve hostname lookup for ctdb nodes
Browse files Browse the repository at this point in the history
Fixes: #136
Signed-off-by: Avan Thakkar <[email protected]>
  • Loading branch information
avanthakkar committed Sep 2, 2024
1 parent 7b361bf commit ac89c7d
Showing 1 changed file with 42 additions and 6 deletions.
48 changes: 42 additions & 6 deletions sambacc/commands/ctdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,12 +261,48 @@ def ctdb_migrate(ctx: Context) -> None:
ctdb.archive_tdb(ctx.instance_config, ctx.cli.archive)


def _lookup_hostname(hostname):
# XXX this is a nasty little hack.
ips = socket.gethostbyname_ex(hostname)[2]
addr = [ip for ip in ips if ip != "127.0.0.1"][0]
_logger.info(f"Determined address for {hostname}: {addr}")
return addr
def _lookup_hostname(hostname: str) -> str:
try:
addrinfo = socket.getaddrinfo(
hostname, None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
)
ipv4_addresses = []
ipv6_addresses = []

for entry in addrinfo:
family, _, _, _, sockaddr = entry
ip_address = sockaddr[0]

if ip_address.startswith("127.") or ip_address == "::1":
continue

if family == socket.AF_INET:
ipv4_addresses.append(ip_address)
elif family == socket.AF_INET6:
ipv6_addresses.append(ip_address)

preferred_address = ipv4_addresses[0] if ipv4_addresses else (
ipv6_addresses[0] if ipv6_addresses else None
)

if preferred_address:
_logger.info(
f"Determined address for {hostname}: {preferred_address}"
)
return preferred_address
else:
raise ValueError(
f"No valid IP address found for hostname '{hostname}'."
)

except socket.gaierror as e:
_logger.error(f"Failed to resolve hostname '{hostname}': {e}")
raise

except IndexError:
raise ValueError(
f"No valid IP address found for hostname '{hostname}'."
)


@commands.command(name="ctdb-set-node", arg_func=_ctdb_set_node_args)
Expand Down

0 comments on commit ac89c7d

Please sign in to comment.