Skip to content

Commit bb07757

Browse files
committed
Only try resolving the docker gateway IP once per server startup and add some diagnostics
Closes django-commons#2113.
1 parent 11e28f7 commit bb07757

File tree

1 file changed

+28
-14
lines changed

1 file changed

+28
-14
lines changed

debug_toolbar/middleware.py

+28-14
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,32 @@
1919
from debug_toolbar.toolbar import DebugToolbar
2020
from debug_toolbar.utils import clear_stack_trace_caches, is_processable_html_response
2121

22+
_resolved_gateway_ip = None
23+
24+
25+
def _gateway_ip():
26+
global _resolved_gateway_ip
27+
if _resolved_gateway_ip is None:
28+
print(
29+
"[django-debug-toolbar] Trying to configure determine the Docker gateay address for autoconfiguration... ",
30+
end="",
31+
)
32+
try:
33+
# This is a hack for docker installations. It attempts to look
34+
# up the IP address of the docker host.
35+
# This is not guaranteed to work.
36+
_resolved_gateway_ip = (
37+
# Convert the last segment of the IP address to be .1
38+
".".join(socket.gethostbyname("host.docker.internal").rsplit(".")[:-1])
39+
+ ".1"
40+
)
41+
print("Success.")
42+
except socket.gaierror:
43+
# It's fine if the lookup errored since they may not be using docker
44+
_resolved_gateway_ip = "unresolvable"
45+
print("Not resolvable.")
46+
return _resolved_gateway_ip
47+
2248

2349
def show_toolbar(request):
2450
"""
@@ -32,20 +58,8 @@ def show_toolbar(request):
3258
return True
3359

3460
# Test: Docker
35-
try:
36-
# This is a hack for docker installations. It attempts to look
37-
# up the IP address of the docker host.
38-
# This is not guaranteed to work.
39-
docker_ip = (
40-
# Convert the last segment of the IP address to be .1
41-
".".join(socket.gethostbyname("host.docker.internal").rsplit(".")[:-1])
42-
+ ".1"
43-
)
44-
if request.META.get("REMOTE_ADDR") == docker_ip:
45-
return True
46-
except socket.gaierror:
47-
# It's fine if the lookup errored since they may not be using docker
48-
pass
61+
if request.META.get("REMOTE_ADDR") == _gateway_ip():
62+
return True
4963

5064
# No test passed
5165
return False

0 commit comments

Comments
 (0)