Skip to content
Open
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
14 changes: 13 additions & 1 deletion ipykernel/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,26 @@ def _bind_socket(self):
def run(self):
"""Run the heartbeat thread."""
self.name = "Heartbeat"
self.socket = self.context.socket(zmq.ROUTER)
# The context can be terminated before this thread has finished
# starting, e.g. when the kernel closes right after starting the
# heartbeat. That's a normal shutdown, not an error.
try:
self.socket = self.context.socket(zmq.ROUTER)
except zmq.ZMQError as e:
# ETERM while it's being terminated, ENOTSUP once it's done
if e.errno == zmq.ETERM or self.context.closed:
return
raise
self.socket.linger = 1000
if self._curve_secretkey is not None:
self.socket.curve_secretkey = self._curve_secretkey
self.socket.curve_publickey = self._curve_publickey
self.socket.curve_server = True
try:
self._bind_socket()
except zmq.ContextTerminated:
self.socket.close()
return
except Exception:
self.socket.close()
raise
Expand Down
35 changes: 35 additions & 0 deletions tests/test_heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,38 @@ def test_port_bind_failure_gives_up_retries():
with pytest.raises(zmq.ZMQError):
heart._bind_socket()
assert mock_try_bind.call_count == 100


def _uncaught(monkeypatch):
"""Collect exceptions that escape a thread."""
errors = []
monkeypatch.setattr("threading.excepthook", lambda args: errors.append(args.exc_value))
return errors


def test_context_terminated_before_start(monkeypatch):
# e.g. the kernel closing right after it started the heartbeat
errors = _uncaught(monkeypatch)
hb = Heartbeat(zmq.Context(), ("tcp", "127.0.0.1", 0))
hb.context.term()
hb.start()
hb.join(5)
assert not hb.is_alive()
assert errors == []


def test_context_terminated_while_binding(monkeypatch):
errors = _uncaught(monkeypatch)
hb = Heartbeat(zmq.Context(), ("tcp", "127.0.0.1", 0))

def bind_after_close():
# the context is terminated between making the socket and binding it
raise zmq.ContextTerminated(zmq.ETERM)

with patch.object(hb, "_bind_socket", bind_after_close):
hb.start()
hb.join(5)
assert not hb.is_alive()
assert errors == []
assert hb.socket.closed
hb.context.term()
Loading