Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find an available port before starting event loop #1136

Merged
merged 2 commits into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/python-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
run: hatch run cov:test --cov-fail-under 75 || hatch run test:test --lf
- name: Run the tests on pypy
if: ${{ startsWith(matrix.python-version, 'pypy') }}
run: hatch run test:test || hatch run test:test --lf
run: hatch run test:nowarn || hatch run test:nowarn --lf
- name: Run the tests on windows
if: ${{ startsWith(matrix.os, 'windows') }}
run: hatch run cov:nowarn -s || hatch run cov:nowarn --lf
Expand Down
13 changes: 11 additions & 2 deletions jupyter_server/serverapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2337,6 +2337,8 @@ def init_httpserver(self):
)

# binding sockets must be called from inside an event loop
if not self.sock:
self._find_http_port()
self.io_loop.add_callback(self._bind_http_server)

def _bind_http_server(self):
Expand Down Expand Up @@ -2371,10 +2373,16 @@ def _bind_http_server_unix(self):
return True

def _bind_http_server_tcp(self):
self.http_server.listen(self.port, self.ip)
return True

def _find_http_port(self):
success = None
for port in random_ports(self.port, self.port_retries + 1):
tmp_sock = socket.socket()
try:
self.http_server.listen(port, self.ip)
tmp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8)
tmp_sock.bind((self.ip, port))
except OSError as e:
if e.errno == errno.EADDRINUSE:
if self.port_retries:
Expand All @@ -2396,6 +2404,8 @@ def _bind_http_server_tcp(self):
self.port = port
success = True
break
finally:
tmp_sock.close()
if not success:
if self.port_retries:
self.log.critical(
Expand All @@ -2413,7 +2423,6 @@ def _bind_http_server_tcp(self):
% port
)
self.exit(1)
return success

@staticmethod
def _init_asyncio_patch():
Expand Down