diff --git a/ipykernel/heartbeat.py b/ipykernel/heartbeat.py index 3f0de81f4..b0ac259b7 100644 --- a/ipykernel/heartbeat.py +++ b/ipykernel/heartbeat.py @@ -107,7 +107,16 @@ 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 @@ -115,6 +124,9 @@ def run(self): self.socket.curve_server = True try: self._bind_socket() + except zmq.ContextTerminated: + self.socket.close() + return except Exception: self.socket.close() raise diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py index e093d5eb2..eeaf0e60e 100644 --- a/tests/test_heartbeat.py +++ b/tests/test_heartbeat.py @@ -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()