Skip to content

Commit 7bf3b9c

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 1a0c8d3 commit 7bf3b9c

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

templates/horizon/config/local_settings.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,10 @@
6464
# retrieve the IP address, which we will then in turn add to the ALLOWED_HOSTS list.
6565
def get_pod_ip():
6666
import socket
67-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
67+
68+
ipstacks = [socket.AF_INET, socket.AF_INET6]
69+
last_error = None
70+
6871
hostport = (
6972
"{{ .horizonEndpointHost }}",
7073
{{- if .isPublicHTTPS }}
@@ -73,16 +76,21 @@ def get_pod_ip():
7376
80
7477
{{- end }}
7578
)
76-
try:
77-
s.connect(hostport)
78-
return s.getsockname()[0]
79-
except socket.gaierror:
80-
s.close()
81-
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
82-
s.connect(hostport)
83-
return "[{}]".format(s.getsockname()[0])
84-
finally:
85-
s.close()
79+
80+
for ipstack in ipstacks:
81+
try:
82+
s = socket.socket(ipstack, socket.SOCK_DGRAM)
83+
s.settimeout(2)
84+
s.connect((hostport))
85+
ip = s.getsockname()[0]
86+
s.close()
87+
return ip if ipstack == socket.AF_INET else f"[{ip}]"
88+
# Broad exception handling here since we will collect and return
89+
# any exceptions after checking each ipstack.
90+
except Exception as e:
91+
last_error = e
92+
93+
raise RuntimeError(f"Could not determine pod IP: {last_error}")
8694

8795
ALLOWED_HOSTS = [get_pod_ip(), "{{ .horizonEndpointHost }}"]
8896

0 commit comments

Comments
 (0)