Skip to content

Commit 7367d13

Browse files
authored
Semi-deterministic port in order to use persistence (equinor#243)
1 parent d691787 commit 7367d13

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

webviz_config/templates/webviz_template.py.jinja2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ if __name__ == "__main__":
114114
# It is used only when directly running this script with Python,
115115
# which will then initialize a localhost server.
116116

117-
port = webviz_config.utils.get_available_port()
117+
port = webviz_config.utils.get_available_port(preferred_port=5000)
118118

119119
token = webviz_config.LocalhostToken(app.server, port).one_time_token
120120
webviz_config.utils.LocalhostOpenBrowser(port, token)

webviz_config/utils/_available_port.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,38 @@
11
import os
22
import socket
3+
from typing import Optional
34

45

5-
def get_available_port() -> int:
6+
def get_available_port(preferred_port: Optional[int] = None) -> int:
67
"""Finds an available port for use in webviz on localhost. If a reload process,
78
it will reuse the same port as found in the parent process by using an inherited
89
environment variable.
10+
11+
If preferred_port is given, ports in the range [preferred_port, preferred_port + 20)
12+
will be tried first, before an OS provided random port is used as fallback.
913
"""
1014

15+
def is_available(port: int) -> bool:
16+
with socket.socket() as sock:
17+
try:
18+
sock.bind(("localhost", port))
19+
return True
20+
except OSError:
21+
return False
22+
1123
if os.environ.get("WEBVIZ_PORT") is None:
12-
sock = socket.socket()
13-
sock.bind(("localhost", 0))
14-
port = sock.getsockname()[1]
15-
sock.close()
24+
port = None
25+
26+
if preferred_port is not None:
27+
for port_to_test in range(preferred_port, preferred_port + 20):
28+
if is_available(port_to_test):
29+
port = port_to_test
30+
break
31+
32+
if port is None:
33+
with socket.socket() as sock:
34+
sock.bind(("localhost", 0))
35+
port = sock.getsockname()[1]
1636

1737
os.environ["WEBVIZ_PORT"] = str(port)
1838
return port

0 commit comments

Comments
 (0)