Skip to content

Commit 2dd116f

Browse files
authored
Find an available port before starting event loop (#1136)
* find an available port before starting event loop * now warnings on pypy
1 parent f6e280b commit 2dd116f

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

.github/workflows/python-tests.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ jobs:
4242
run: hatch run cov:test --cov-fail-under 75 || hatch run test:test --lf
4343
- name: Run the tests on pypy
4444
if: ${{ startsWith(matrix.python-version, 'pypy') }}
45-
run: hatch run test:test || hatch run test:test --lf
45+
run: hatch run test:nowarn || hatch run test:nowarn --lf
4646
- name: Run the tests on windows
4747
if: ${{ startsWith(matrix.os, 'windows') }}
4848
run: hatch run cov:nowarn -s || hatch run cov:nowarn --lf

jupyter_server/serverapp.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2337,6 +2337,8 @@ def init_httpserver(self):
23372337
)
23382338

23392339
# binding sockets must be called from inside an event loop
2340+
if not self.sock:
2341+
self._find_http_port()
23402342
self.io_loop.add_callback(self._bind_http_server)
23412343

23422344
def _bind_http_server(self):
@@ -2371,10 +2373,16 @@ def _bind_http_server_unix(self):
23712373
return True
23722374

23732375
def _bind_http_server_tcp(self):
2376+
self.http_server.listen(self.port, self.ip)
2377+
return True
2378+
2379+
def _find_http_port(self):
23742380
success = None
23752381
for port in random_ports(self.port, self.port_retries + 1):
2382+
tmp_sock = socket.socket()
23762383
try:
2377-
self.http_server.listen(port, self.ip)
2384+
tmp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8)
2385+
tmp_sock.bind((self.ip, port))
23782386
except OSError as e:
23792387
if e.errno == errno.EADDRINUSE:
23802388
if self.port_retries:
@@ -2396,6 +2404,8 @@ def _bind_http_server_tcp(self):
23962404
self.port = port
23972405
success = True
23982406
break
2407+
finally:
2408+
tmp_sock.close()
23992409
if not success:
24002410
if self.port_retries:
24012411
self.log.critical(
@@ -2413,7 +2423,6 @@ def _bind_http_server_tcp(self):
24132423
% port
24142424
)
24152425
self.exit(1)
2416-
return success
24172426

24182427
@staticmethod
24192428
def _init_asyncio_patch():

0 commit comments

Comments
 (0)