def _create_sockets(self): import zmq import socket from ipykernel.heartbeat import Heartbeat context = zmq.Context() # or existing? zmq.Context.instance() ip = socket.gethostbyname(socket.gethostname()) transport = "tcp" addr = "%s://%s" % (transport, ip) shell_socket = context.socket(zmq.ROUTER) shell_port = shell_socket.bind_to_random_port(addr) iopub_socket = context.socket(zmq.PUB) iopub_port = iopub_socket.bind_to_random_port(addr) control_socket = context.socket(zmq.ROUTER) control_port = control_socket.bind_to_random_port(addr) # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() heartbeat = Heartbeat(hb_ctx, (transport, ip, 0)) hb_port = heartbeat.port heartbeat.start() self._connection_info = dict(ip=ip, shell_port=shell_port, iopub_port=iopub_port, control_port=control_port, hb_port=hb_port) self._shell_socket = shell_socket self._control_socket = control_socket self._iopub_socket = iopub_socket
def test_port_bind_failure_gives_up_retries(): heart = Heartbeat(None) with patch.object(heart, "_try_bind_socket") as mock_try_bind: mock_try_bind.side_effect = zmq.ZMQError(errno.EADDRINUSE, "fails for non-bind") with pytest.raises(zmq.ZMQError): heart._bind_socket() assert mock_try_bind.call_count == 100
def test_port_bind_failure_raises(): heart = Heartbeat(None) with patch.object(heart, "_try_bind_socket") as mock_try_bind: mock_try_bind.side_effect = zmq.ZMQError( -100, "fails for unknown error types") with pytest.raises(zmq.ZMQError): heart._bind_socket() assert mock_try_bind.call_count == 1
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port) self.heartbeat.start()
def test_port_bind_failure_recovery(): try: errno.WSAEADDRINUSE except AttributeError: # Fake windows address in-use code errno.WSAEADDRINUSE = 12345 try: heart = Heartbeat(None) with patch.object(heart, '_try_bind_socket') as mock_try_bind: mock_try_bind.side_effect = [ zmq.ZMQError(errno.EADDRINUSE, "fails for non-bind unix"), zmq.ZMQError(errno.WSAEADDRINUSE, "fails for non-bind windows") ] + [0] * 100 # Shouldn't raise anything as retries will kick in heart._bind_socket() finally: # Cleanup fake assignment if errno.WSAEADDRINUSE == 12345: del errno.WSAEADDRINUSE
def test_port_bind_success(): heart = Heartbeat(None) with patch.object(heart, "_try_bind_socket") as mock_try_bind: heart._bind_socket() assert mock_try_bind.call_count == 1