Skip to content

Commit ee2e6ce

Browse files
committed
Improve robustness of get_pod_ip() function
In cases where single-stack IPv6 is used, it's possible that an unhandled exception is raised since we first attempt to verify ipv4 connectivity and fail before checking ipv6. This change makes the get_pod_ip() function more robust by ensuring that both are checked before raising an error. Fixes #478 Jira: https://issues.redhat.com/browse/OSPRH-19216 Signed-off-by: Brendan Shephard <[email protected]>
1 parent 26ea0fc commit ee2e6ce

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

templates/horizon/config/local_settings.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -63,25 +63,25 @@
6363
# retrieve the IP address, which we will then in turn add to the ALLOWED_HOSTS list.
6464
def get_pod_ip():
6565
import socket
66-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
67-
hostport = (
68-
"{{ .horizonEndpointHost }}",
69-
{{- if .isPublicHTTPS }}
70-
443
71-
{{- else }}
72-
80
73-
{{- end }}
74-
)
75-
try:
76-
s.connect(hostport)
77-
return s.getsockname()[0]
78-
except socket.gaierror:
79-
s.close()
80-
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
81-
s.connect(hostport)
82-
return "[{}]".format(s.getsockname()[0])
83-
finally:
84-
s.close()
66+
67+
ipstacks = [socket.AF_INET, socket.AF_INET6]
68+
last_error = None
69+
70+
host = "{{ .horizonEndpointHost }}"
71+
port = 443 if {{ .isPublicHTTPS }} else 80
72+
73+
for ipstack in ipstacks:
74+
try:
75+
s = socket.socket(ipstack, socket.SOCK_DGRAM)
76+
s.settimeout(2)
77+
s.connect((host, port))
78+
ip = s.getsockname()[0]
79+
s.close()
80+
return ip if ipstack == socket.AF_INET else f"[{ip}]"
81+
except Exception as e:
82+
last_error = e
83+
84+
raise RuntimeError(f"Could not determine pod IP: {last_error}")
8585

8686
ALLOWED_HOSTS = [get_pod_ip(), "{{ .horizonEndpointHost }}"]
8787

0 commit comments

Comments
 (0)