@@ -325,31 +325,37 @@ def _conn_state_change(self, node_id, conn):
325
325
def _maybe_connect (self , node_id ):
326
326
"""Idempotent non-blocking connection attempt to the given node id."""
327
327
broker = self .cluster .broker_metadata (node_id )
328
+ conn = self ._conns .get (node_id )
328
329
329
- # If broker metadata indicates that a node's host/port has changed, remove it
330
- if node_id in self ._conns and broker is not None :
331
- conn = self ._conns [node_id ]
332
- host , _ , __ = get_ip_port_afi (broker .host )
333
- if conn .host != host or conn .port != broker .port :
334
- log .debug ("Closing connection to decommissioned node %s at %s:%s" ,
335
- node_id , conn .host , conn .port )
336
- conn .close ()
337
- self ._conns .pop (node_id )
338
-
339
- if node_id not in self ._conns :
330
+ if conn is None :
340
331
assert broker , 'Broker id %s not in current metadata' % node_id
341
332
342
333
log .debug ("Initiating connection to node %s at %s:%s" ,
343
334
node_id , broker .host , broker .port )
344
335
host , port , afi = get_ip_port_afi (broker .host )
345
336
cb = functools .partial (self ._conn_state_change , node_id )
346
- self ._conns [node_id ] = BrokerConnection (host , broker .port , afi ,
347
- state_change_callback = cb ,
348
- node_id = node_id ,
349
- ** self .config )
350
- conn = self ._conns [node_id ]
351
- if conn .connected ():
337
+ conn = BrokerConnection (host , broker .port , afi ,
338
+ state_change_callback = cb ,
339
+ node_id = node_id ,
340
+ ** self .config )
341
+ self ._conns [node_id ] = conn
342
+
343
+ # Check if existing connection should be recreated because host/port changed
344
+ elif conn .disconnected () and broker is not None :
345
+ host , _ , __ = get_ip_port_afi (broker .host )
346
+ if conn .host != host or conn .port != broker .port :
347
+ log .info ("Broker metadata change detected for node %s"
348
+ " from %s:%s to %s:%s" , node_id , conn .host , conn .port ,
349
+ broker .host , broker .port )
350
+
351
+ # Drop old connection object.
352
+ # It will be recreated on next _maybe_connect
353
+ self ._conns .pop (node_id )
354
+ return False
355
+
356
+ elif conn .connected ():
352
357
return True
358
+
353
359
conn .connect ()
354
360
return conn .connected ()
355
361
0 commit comments