@@ -335,12 +335,17 @@ def return_connection(self, connection):
335335
336336 def _replace (self , connection ):
337337 log .debug ("Replacing connection (%s) to %s" , id (connection ), self .host )
338- conn = self ._session .cluster .connection_factory (self .host .address )
339- if self ._session .keyspace :
340- conn .set_keyspace_blocking (self ._session .keyspace )
341- self ._connection = conn
342- with self ._lock :
343- self ._is_replacing = False
338+ try :
339+ conn = self ._session .cluster .connection_factory (self .host .address )
340+ if self ._session .keyspace :
341+ conn .set_keyspace_blocking (self ._session .keyspace )
342+ self ._connection = conn
343+ except Exception :
344+ log .warning ("Failed reconnecting %s. Retrying." % (self .host .address ,))
345+ self ._session .submit (self ._replace , connection )
346+ else :
347+ with self ._lock :
348+ self ._is_replacing = False
344349
345350 def shutdown (self ):
346351 with self ._lock :
@@ -499,10 +504,10 @@ def _add_conn_if_under_max(self):
499504 max_conns = self ._session .cluster .get_max_connections_per_host (self .host_distance )
500505 with self ._lock :
501506 if self .is_shutdown :
502- return False
507+ return True
503508
504509 if self .open_count >= max_conns :
505- return False
510+ return True
506511
507512 self .open_count += 1
508513
@@ -646,17 +651,22 @@ def _replace(self, connection):
646651
647652 if should_replace :
648653 log .debug ("Replacing connection (%s) to %s" , id (connection ), self .host )
649-
650- def close_and_replace ():
651- connection .close ()
652- self ._add_conn_if_under_max ()
653-
654- self ._session .submit (close_and_replace )
654+ connection .close ()
655+ self ._session .submit (self ._retrying_replace )
655656 else :
656- # just close it
657657 log .debug ("Closing connection (%s) to %s" , id (connection ), self .host )
658658 connection .close ()
659659
660+ def _retrying_replace (self ):
661+ replaced = False
662+ try :
663+ replaced = self ._add_conn_if_under_max ()
664+ except Exception :
665+ log .exception ("Failed replacing connection to %s" , self .host )
666+ if not replaced :
667+ log .debug ("Failed replacing connection to %s. Retrying." , self .host )
668+ self ._session .submit (self ._retrying_replace )
669+
660670 def shutdown (self ):
661671 with self ._lock :
662672 if self .is_shutdown :
0 commit comments