Skip to content

Commit 59d6d6a

Browse files
committed
Move all network connection IO into KafkaClient.poll()
1 parent 143afab commit 59d6d6a

File tree

4 files changed

+32
-18
lines changed

4 files changed

+32
-18
lines changed

kafka/client_async.py

+22-8
Original file line numberDiff line numberDiff line change
@@ -304,18 +304,21 @@ def _conn_state_change(self, node_id, conn):
304304
# SSL connections can enter this state 2x (second during Handshake)
305305
if node_id not in self._connecting:
306306
self._connecting.add(node_id)
307+
try:
307308
self._selector.register(conn._sock, selectors.EVENT_WRITE)
309+
except KeyError:
310+
self._selector.modify(conn._sock, selectors.EVENT_WRITE)
308311

309312
elif conn.connected():
310313
log.debug("Node %s connected", node_id)
311314
if node_id in self._connecting:
312315
self._connecting.remove(node_id)
313316

314317
try:
315-
self._selector.unregister(conn._sock)
318+
self._selector.modify(conn._sock, selectors.EVENT_READ, conn)
316319
except KeyError:
317-
pass
318-
self._selector.register(conn._sock, selectors.EVENT_READ, conn)
320+
self._selector.register(conn._sock, selectors.EVENT_READ, conn)
321+
319322
if self._sensors:
320323
self._sensors.connection_created.record()
321324

@@ -336,6 +339,7 @@ def _conn_state_change(self, node_id, conn):
336339
self._selector.unregister(conn._sock)
337340
except KeyError:
338341
pass
342+
339343
if self._sensors:
340344
self._sensors.connection_closed.record()
341345

@@ -348,6 +352,17 @@ def _conn_state_change(self, node_id, conn):
348352
log.warning("Node %s connection failed -- refreshing metadata", node_id)
349353
self.cluster.request_update()
350354

355+
def maybe_connect(self, node_id):
356+
"""Queues a node for asynchronous connection during the next .poll()"""
357+
if self._can_connect(node_id):
358+
self._connecting.add(node_id)
359+
# Wakeup signal is useful in case another thread is
360+
# blocked waiting for incoming network traffic while holding
361+
# the client lock in poll().
362+
self.wakeup()
363+
return True
364+
return False
365+
351366
def _maybe_connect(self, node_id):
352367
"""Idempotent non-blocking connection attempt to the given node id."""
353368
with self._lock:
@@ -397,7 +412,7 @@ def ready(self, node_id, metadata_priority=True):
397412
Returns:
398413
bool: True if we are ready to send to the given node
399414
"""
400-
self._maybe_connect(node_id)
415+
self.maybe_connect(node_id)
401416
return self.is_ready(node_id, metadata_priority=metadata_priority)
402417

403418
def connected(self, node_id):
@@ -520,8 +535,8 @@ def send(self, node_id, request):
520535
Future: resolves to Response struct or Error
521536
"""
522537
if not self._can_send_request(node_id):
523-
if not self._maybe_connect(node_id):
524-
return Future().failure(Errors.NodeNotReadyError(node_id))
538+
self.maybe_connect(node_id)
539+
return Future().failure(Errors.NodeNotReadyError(node_id))
525540

526541
# conn.send will queue the request internally
527542
# we will need to call send_pending_requests()
@@ -814,9 +829,8 @@ def refresh_done(val_or_error):
814829
# have such application level configuration, using request timeout instead.
815830
return self.config['request_timeout_ms']
816831

817-
if self._can_connect(node_id):
832+
if self.maybe_connect(node_id):
818833
log.debug("Initializing connection to node %s for metadata request", node_id)
819-
self._maybe_connect(node_id)
820834
return self.config['reconnect_backoff_ms']
821835

822836
# connected but can't send more, OR connecting

kafka/coordinator/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def ensure_coordinator_ready(self):
252252
if self.config['api_version'] < (0, 8, 2):
253253
self.coordinator_id = self._client.least_loaded_node()
254254
if self.coordinator_id is not None:
255-
self._client.ready(self.coordinator_id)
255+
self._client.maybe_connect(self.coordinator_id)
256256
continue
257257

258258
future = self.lookup_coordinator()
@@ -686,7 +686,7 @@ def _handle_group_coordinator_response(self, future, response):
686686
self.coordinator_id = response.coordinator_id
687687
log.info("Discovered coordinator %s for group %s",
688688
self.coordinator_id, self.group_id)
689-
self._client.ready(self.coordinator_id)
689+
self._client.maybe_connect(self.coordinator_id)
690690
self.heartbeat.reset_timeouts()
691691
future.success(self.coordinator_id)
692692

test/fixtures.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -405,10 +405,11 @@ def _failure(error):
405405
retries = 10
406406
while True:
407407
node_id = self._client.least_loaded_node()
408-
for ready_retry in range(40):
409-
if self._client.ready(node_id, False):
408+
for connect_retry in range(40):
409+
self._client.maybe_connect(node_id)
410+
if self._client.connected(node_id):
410411
break
411-
time.sleep(.1)
412+
self._client.poll(timeout_ms=100)
412413
else:
413414
raise RuntimeError('Could not connect to broker with node id %d' % (node_id,))
414415

test/test_client_async.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,7 @@ def test_conn_state_change(mocker, cli, conn):
125125
conn.state = ConnectionStates.CONNECTED
126126
cli._conn_state_change(node_id, conn)
127127
assert node_id not in cli._connecting
128-
sel.unregister.assert_called_with(conn._sock)
129-
sel.register.assert_called_with(conn._sock, selectors.EVENT_READ, conn)
128+
sel.modify.assert_called_with(conn._sock, selectors.EVENT_READ, conn)
130129

131130
# Failure to connect should trigger metadata update
132131
assert cli.cluster._need_update is False
@@ -145,7 +144,7 @@ def test_conn_state_change(mocker, cli, conn):
145144

146145

147146
def test_ready(mocker, cli, conn):
148-
maybe_connect = mocker.patch.object(cli, '_maybe_connect')
147+
maybe_connect = mocker.patch.object(cli, 'maybe_connect')
149148
node_id = 1
150149
cli.ready(node_id)
151150
maybe_connect.assert_called_with(node_id)
@@ -362,6 +361,7 @@ def test_maybe_refresh_metadata_cant_send(mocker, client):
362361
mocker.patch.object(client, 'least_loaded_node', return_value='foobar')
363362
mocker.patch.object(client, '_can_connect', return_value=True)
364363
mocker.patch.object(client, '_maybe_connect', return_value=True)
364+
mocker.patch.object(client, 'maybe_connect', return_value=True)
365365

366366
now = time.time()
367367
t = mocker.patch('time.time')
@@ -370,8 +370,7 @@ def test_maybe_refresh_metadata_cant_send(mocker, client):
370370
# first poll attempts connection
371371
client.poll(timeout_ms=12345678)
372372
client._poll.assert_called_with(2.222) # reconnect backoff
373-
client._can_connect.assert_called_once_with('foobar')
374-
client._maybe_connect.assert_called_once_with('foobar')
373+
client.maybe_connect.assert_called_once_with('foobar')
375374

376375
# poll while connecting should not attempt a new connection
377376
client._connecting.add('foobar')

0 commit comments

Comments
 (0)