Skip to content

Commit 434b75e

Browse files
jackgerritsekzhusonichi
authored
Get unused port from jupyter kernel gateway not host (#1870)
Co-authored-by: Eric Zhu <[email protected]> Co-authored-by: Chi Wang <[email protected]>
1 parent a54b733 commit 434b75e

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

autogen/coding/jupyter/local_jupyter_server.py

+15-12
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,6 @@
1919
from .jupyter_client import JupyterClient
2020

2121

22-
def _get_free_port() -> int:
23-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
24-
s.bind(("", 0))
25-
return cast(int, s.getsockname()[1])
26-
27-
2822
class LocalJupyterServer(JupyterConnectable):
2923
class GenerateToken:
3024
pass
@@ -69,9 +63,6 @@ def __init__(
6963
)
7064

7165
self.ip = ip
72-
if port is None:
73-
port = _get_free_port()
74-
self.port = port
7566

7667
if isinstance(token, LocalJupyterServer.GenerateToken):
7768
token = secrets.token_hex(32)
@@ -98,8 +89,6 @@ def __init__(
9889
"kernelgateway",
9990
"--KernelGatewayApp.ip",
10091
ip,
101-
"--KernelGatewayApp.port",
102-
str(port),
10392
"--KernelGatewayApp.auth_token",
10493
token,
10594
"--JupyterApp.answer_yes",
@@ -109,6 +98,9 @@ def __init__(
10998
"--JupyterWebsocketPersonality.list_kernels",
11099
"true",
111100
]
101+
if port is not None:
102+
args.extend(["--KernelGatewayApp.port", str(port)])
103+
args.extend(["--KernelGatewayApp.port_retries", "0"])
112104
self._subprocess = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
113105

114106
# Satisfy mypy, we know this is not None because we passed PIPE
@@ -119,11 +111,22 @@ def __init__(
119111
result = self._subprocess.poll()
120112
if result is not None:
121113
stderr += self._subprocess.stderr.read()
122-
print(f"token=[[[[{token}]]]]")
123114
raise ValueError(f"Jupyter gateway server failed to start with exit code: {result}. stderr:\n{stderr}")
124115
line = self._subprocess.stderr.readline()
125116
stderr += line
117+
118+
if "ERROR:" in line:
119+
error_info = line.split("ERROR:")[1]
120+
raise ValueError(f"Jupyter gateway server failed to start. {error_info}")
121+
126122
if "is available at" in line:
123+
# We need to extract what port it settled on
124+
# Example output:
125+
# Jupyter Kernel Gateway 3.0.0 is available at http://127.0.0.1:8890
126+
if port is None:
127+
port = int(line.split(":")[-1])
128+
self.port = port
129+
127130
break
128131

129132
# Poll the subprocess to check if it is still running

0 commit comments

Comments
 (0)