Elffuss BraidHub

kikocis/java-driver public

Optimize connection use after reconnection (JAVA-505).
Changeset697b75f263875d9adc89ebca509587e0e87df37be22044d8a4def7accbc8dfcd
Authorolim7t <omichallat+github@gmail.com> · 2014-11-27 12:39 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-11-27 18:15 +01:00
Parents46bcf5126dc2

Browse the files at this changeset

6 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -8,6 +8,7 @@
88 - [improvement] Target schema refreshes more precisely (JAVA-543)
99 - [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
1010 - [bug] Don't check rpc_address for control host (JAVA-546)
11+- [improvement] Optimize connection use after reconnection (JAVA-505)
1112
1213
1314 2.0.8:
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +165 −162
@@ -1358,103 +1358,107 @@
13581358 return executor.submit(new ExceptionCatchingRunnable() {
13591359 @Override
13601360 public void runMayThrow() throws InterruptedException, ExecutionException {
1361- onUp(host);
1361+ onUp(host, null);
13621362 }
13631363 });
13641364 }
13651365
1366- private void onUp(final Host host) throws InterruptedException, ExecutionException {
1366+ private void onUp(final Host host, Connection preExistentConnection) throws InterruptedException, ExecutionException {
13671367 // Note that in generalize we can parallelize the pool creation on
13681368 // each session, but we shouldn't use executor since we're already
13691369 // running on it most probably (and so we could deadlock). Use the
13701370 // blockingExecutor instead, that's why it's for.
1371- onUp(host, blockingExecutor);
1371+ onUp(host, preExistentConnection, blockingExecutor);
13721372 }
13731373
13741374 // Use triggerOnUp unless you're sure you want to run this on the current thread.
1375- private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
1375+ private void onUp(final Host host, Connection preExistentConnection, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
13761376 logger.debug("Host {} is UP", host);
1377-
1378- if (isClosed())
1379- return;
1380-
1381- // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1382- if (host.state == Host.State.UP)
1383- return;
1384-
1385- if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1386- logUnsupportedVersionProtocol(host);
1387- return;
1388- }
1389-
1390- // If there is a reconnection attempt scheduled for that node, cancel it
1391- Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1392- if (scheduledAttempt != null) {
1393- logger.debug("Cancelling reconnection attempt since node is UP");
1394- scheduledAttempt.cancel(false);
1395- }
1396-
13971377 try {
1398- prepareAllQueries(host);
1399- } catch (InterruptedException e) {
1400- Thread.currentThread().interrupt();
1401- // Don't propagate because we don't want to prevent other listener to run
1402- } catch (UnsupportedProtocolVersionException e) {
1403- logUnsupportedVersionProtocol(host);
1404- return;
1405- } catch (ClusterNameMismatchException e) {
1406- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1407- return;
1408- }
1409-
1410- // Session#onUp() expects the load balancing policy to have been updated first, so that
1411- // Host distances are up to date. This mean the policy could return the node before the
1412- // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1413- // will ignore the node, but we do want to make sure there is no prior pool so we don't
1414- // query from a pool we will shutdown right away.
1415- for (SessionManager s : sessions)
1416- s.removePool(host);
1417- loadBalancingPolicy().onUp(host);
1418- controlConnection.onUp(host);
1419-
1420- logger.trace("Adding/renewing host pools for newly UP host {}", host);
1378+ if (isClosed())
1379+ return;
14211380
1422- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1423- for (SessionManager s : sessions)
1424- futures.add(s.forceRenewPool(host, poolCreationExecutor));
1425-
1426- // Only mark the node up once all session have re-added their pool (if the load-balancing
1427- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1428- // to the node.
1429- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1430- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1431- public void onSuccess(List<Boolean> poolCreationResults) {
1432- // If any of the creation failed, they will have signaled a connection failure
1433- // which will trigger a reconnection to the node. So don't bother marking UP.
1434- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1435- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1436- return;
1437- }
1381+ // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1382+ if (host.state == Host.State.UP)
1383+ return;
14381384
1439- host.setUp();
1385+ if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1386+ logUnsupportedVersionProtocol(host);
1387+ return;
1388+ }
14401389
1441- for (Host.StateListener listener : listeners)
1442- listener.onUp(host);
1390+ // If there is a reconnection attempt scheduled for that node, cancel it
1391+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1392+ if (scheduledAttempt != null) {
1393+ logger.debug("Cancelling reconnection attempt since node is UP");
1394+ scheduledAttempt.cancel(false);
14431395 }
14441396
1445- public void onFailure(Throwable t) {
1446- // That future is not really supposed to throw unexpected exceptions
1447- if (!(t instanceof InterruptedException))
1448- logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1397+ try {
1398+ prepareAllQueries(host);
1399+ } catch (InterruptedException e) {
1400+ Thread.currentThread().interrupt();
1401+ // Don't propagate because we don't want to prevent other listener to run
1402+ } catch (UnsupportedProtocolVersionException e) {
1403+ logUnsupportedVersionProtocol(host);
1404+ return;
1405+ } catch (ClusterNameMismatchException e) {
1406+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1407+ return;
14491408 }
1450- });
14511409
1452- f.get();
1410+ // Session#onUp() expects the load balancing policy to have been updated first, so that
1411+ // Host distances are up to date. This mean the policy could return the node before the
1412+ // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1413+ // will ignore the node, but we do want to make sure there is no prior pool so we don't
1414+ // query from a pool we will shutdown right away.
1415+ for (SessionManager s : sessions)
1416+ s.removePool(host);
1417+ loadBalancingPolicy().onUp(host);
1418+ controlConnection.onUp(host);
1419+
1420+ logger.trace("Adding/renewing host pools for newly UP host {}", host);
1421+
1422+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1423+ for (SessionManager s : sessions)
1424+ futures.add(s.forceRenewPool(host, preExistentConnection, poolCreationExecutor));
1425+
1426+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1427+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1428+ // to the node.
1429+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1430+ Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1431+ public void onSuccess(List<Boolean> poolCreationResults) {
1432+ // If any of the creation failed, they will have signaled a connection failure
1433+ // which will trigger a reconnection to the node. So don't bother marking UP.
1434+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1435+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1436+ return;
1437+ }
14531438
1454- // Now, check if there isn't pools to create/remove following the addition.
1455- // We do that now only so that it's not called before we've set the node up.
1456- for (SessionManager s : sessions)
1457- s.updateCreatedPools(blockingExecutor);
1439+ host.setUp();
1440+
1441+ for (Host.StateListener listener : listeners)
1442+ listener.onUp(host);
1443+ }
1444+
1445+ public void onFailure(Throwable t) {
1446+ // That future is not really supposed to throw unexpected exceptions
1447+ if (!(t instanceof InterruptedException))
1448+ logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1449+ }
1450+ });
1451+
1452+ f.get();
1453+
1454+ // Now, check if there isn't pools to create/remove following the addition.
1455+ // We do that now only so that it's not called before we've set the node up.
1456+ for (SessionManager s : sessions)
1457+ s.updateCreatedPools(blockingExecutor);
1458+ } finally {
1459+ if (preExistentConnection != null && !preExistentConnection.hasPool())
1460+ preExistentConnection.closeAsync();
1461+ }
14581462 }
14591463
14601464 public ListenableFuture<?> triggerOnDown(final Host host) {
@@ -1505,11 +1509,10 @@
15051509 @Override
15061510 public void runMayThrow() throws InterruptedException, ExecutionException {
15071511 try {
1508- // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection
1509- connectionFactory.open(host).closeAsync();
1512+ Connection connection = connectionFactory.open(host);
15101513 // Note that we want to do the pool creation on this thread because we want that
15111514 // when onUp return, the host is ready for querying
1512- onUp(host, MoreExecutors.sameThreadExecutor());
1515+ onUp(host, connection, MoreExecutors.sameThreadExecutor());
15131516 } catch (Exception e) {
15141517 onDown(host, false, true);
15151518 }
@@ -1573,7 +1576,6 @@
15731576 if (distance == HostDistance.IGNORED)
15741577 return;
15751578
1576- // Note: we basically waste the first successful reconnection, but it's probably not a big deal
15771579 logger.debug("{} is down, scheduling connection retries", host);
15781580 startPeriodicReconnectionAttempt(host, isHostAddition);
15791581 }
@@ -1586,19 +1588,16 @@
15861588 }
15871589
15881590 protected void onReconnection(Connection connection) {
1589- // We don't use that first connection so close it.
1590- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1591- // we use it for the first HostConnectionPool created
1592- connection.closeAsync();
15931591 // Make sure we have up-to-date infos on that host before adding it (so we typically
15941592 // catch that an upgraded node uses a new cassandra version).
15951593 if (controlConnection.refreshNodeInfo(host)) {
15961594 logger.debug("Successful reconnection to {}, setting host UP", host);
15971595 try {
1596+ // We pass the connection to onAdd/onUp so that it can be reused in a pool
15981597 if (isHostAddition)
1599- onAdd(host);
1598+ onAdd(host, connection);
16001599 else
1601- onUp(host);
1600+ onUp(host, connection);
16021601 } catch (InterruptedException e) {
16031602 Thread.currentThread().interrupt();
16041603 } catch (Exception e) {
@@ -1606,6 +1605,7 @@
16061605 }
16071606 } else {
16081607 logger.debug("Not enough info for {}, ignoring host", host);
1608+ connection.closeAsync();
16091609 }
16101610 }
16111611
@@ -1642,16 +1642,13 @@
16421642 }
16431643
16441644 protected void onReconnection(Connection connection) {
1645- // We don't use that first connection so close it.
1646- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1647- // we use it for the first HostConnectionPool created
1648- connection.closeAsync();
16491645 // Make sure we have up-to-date infos on that host before adding it (so we typically
16501646 // catch that an upgraded node uses a new cassandra version).
16511647 if (controlConnection.refreshNodeInfo(host)) {
16521648 logger.debug("Successful reconnection to {}, setting host UP", host);
16531649 try {
1654- onUp(host);
1650+ // We pass the connection so that it can be reused in a pool
1651+ onUp(host, connection);
16551652 } catch (InterruptedException e) {
16561653 Thread.currentThread().interrupt();
16571654 } catch (Exception e) {
@@ -1659,6 +1656,7 @@
16591656 }
16601657 } else {
16611658 logger.debug("Not enough info for {}, ignoring host", host);
1659+ connection.closeAsync();
16621660 }
16631661 }
16641662
@@ -1684,91 +1682,96 @@
16841682 return executor.submit(new ExceptionCatchingRunnable() {
16851683 @Override
16861684 public void runMayThrow() throws InterruptedException, ExecutionException {
1687- onAdd(host);
1685+ onAdd(host, null);
16881686 }
16891687 });
16901688 }
16911689
16921690 // Use triggerOnAdd unless you're sure you want to run this on the current thread.
1693- private void onAdd(final Host host) throws InterruptedException, ExecutionException {
1694- if (isClosed())
1695- return;
1696-
1697- logger.info("New Cassandra host {} added", host);
1698-
1699- if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1700- logUnsupportedVersionProtocol(host);
1701- return;
1702- }
1703-
1704- // Adds to the load balancing first and foremost, as doing so might change the decision
1705- // it will make for distance() on that node (not likely but we leave that possibility).
1706- // This does mean the policy may start returning that node for query plan, but as long
1707- // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1708- loadBalancingPolicy().onAdd(host);
1709-
1710- // Next, if the host should be ignored, well, ignore it.
1711- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1712- // We still mark the node UP though as it should be (and notifiy the listeners).
1713- // We'll mark it down if we have a notification anyway and we've documented that especially
1714- // for IGNORED hosts, the isUp() method was a best effort guess
1715- host.setUp();
1716- for (Host.StateListener listener : listeners)
1717- listener.onAdd(host);
1718- return;
1719- }
1720-
1691+ private void onAdd(final Host host, Connection preExistentConnection) throws InterruptedException, ExecutionException {
17211692 try {
1722- prepareAllQueries(host);
1723- } catch (InterruptedException e) {
1724- Thread.currentThread().interrupt();
1725- // Don't propagate because we don't want to prevent other listener to run
1726- } catch (UnsupportedProtocolVersionException e) {
1727- logUnsupportedVersionProtocol(host);
1728- return;
1729- } catch (ClusterNameMismatchException e) {
1730- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1731- return;
1732- }
1693+ if (isClosed())
1694+ return;
17331695
1734- controlConnection.onAdd(host);
1696+ logger.info("New Cassandra host {} added", host);
17351697
1736- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1737- for (SessionManager s : sessions)
1738- futures.add(s.maybeAddPool(host, blockingExecutor));
1739-
1740- // Only mark the node up once all session have added their pool (if the load-balancing
1741- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1742- // to the node.
1743- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1744- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1745- public void onSuccess(List<Boolean> poolCreationResults) {
1746- // If any of the creation failed, they will have signaled a connection failure
1747- // which will trigger a reconnection to the node. So don't bother marking UP.
1748- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1749- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1750- return;
1751- }
1698+ if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1699+ logUnsupportedVersionProtocol(host);
1700+ return;
1701+ }
17521702
1703+ // Adds to the load balancing first and foremost, as doing so might change the decision
1704+ // it will make for distance() on that node (not likely but we leave that possibility).
1705+ // This does mean the policy may start returning that node for query plan, but as long
1706+ // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1707+ loadBalancingPolicy().onAdd(host);
1708+
1709+ // Next, if the host should be ignored, well, ignore it.
1710+ if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1711+ // We still mark the node UP though as it should be (and notifiy the listeners).
1712+ // We'll mark it down if we have a notification anyway and we've documented that especially
1713+ // for IGNORED hosts, the isUp() method was a best effort guess
17531714 host.setUp();
1754-
17551715 for (Host.StateListener listener : listeners)
17561716 listener.onAdd(host);
1717+ return;
17571718 }
17581719
1759- public void onFailure(Throwable t) {
1760- // That future is not really supposed to throw unexpected exceptions
1761- if (!(t instanceof InterruptedException))
1762- logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1720+ try {
1721+ prepareAllQueries(host);
1722+ } catch (InterruptedException e) {
1723+ Thread.currentThread().interrupt();
1724+ // Don't propagate because we don't want to prevent other listener to run
1725+ } catch (UnsupportedProtocolVersionException e) {
1726+ logUnsupportedVersionProtocol(host);
1727+ return;
1728+ } catch (ClusterNameMismatchException e) {
1729+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1730+ return;
17631731 }
1764- });
17651732
1766- f.get();
1733+ controlConnection.onAdd(host);
1734+
1735+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1736+ for (SessionManager s : sessions)
1737+ futures.add(s.maybeAddPool(host, preExistentConnection, blockingExecutor));
1738+
1739+ // Only mark the node up once all session have added their pool (if the load-balancing
1740+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1741+ // to the node.
1742+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1743+ Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1744+ public void onSuccess(List<Boolean> poolCreationResults) {
1745+ // If any of the creation failed, they will have signaled a connection failure
1746+ // which will trigger a reconnection to the node. So don't bother marking UP.
1747+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1748+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1749+ return;
1750+ }
17671751
1768- // Now, check if there isn't pools to create/remove following the addition.
1769- // We do that now only so that it's not called before we've set the node up.
1770- for (SessionManager s : sessions)
1771- s.updateCreatedPools(blockingExecutor);
1752+ host.setUp();
1753+
1754+ for (Host.StateListener listener : listeners)
1755+ listener.onAdd(host);
1756+ }
1757+
1758+ public void onFailure(Throwable t) {
1759+ // That future is not really supposed to throw unexpected exceptions
1760+ if (!(t instanceof InterruptedException))
1761+ logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1762+ }
1763+ });
1764+
1765+ f.get();
1766+
1767+ // Now, check if there isn't pools to create/remove following the addition.
1768+ // We do that now only so that it's not called before we've set the node up.
1769+ for (SessionManager s : sessions)
1770+ s.updateCreatedPools(blockingExecutor);
1771+ } finally {
1772+ if (preExistentConnection != null && !preExistentConnection.hasPool())
1773+ preExistentConnection.closeAsync();
1774+ }
17721775 }
17731776
17741777 public ListenableFuture<?> triggerOnRemove(final Host host) {
@@ -1989,7 +1992,7 @@
19891992 // Make sure we have up-to-date infos on that host before adding it (so we typically
19901993 // catch that an upgraded node uses a new cassandra version).
19911994 if (controlConnection.refreshNodeInfo(newHost)) {
1992- onAdd(newHost);
1995+ onAdd(newHost, null);
19931996 } else {
19941997 logger.debug("Not enough info for {}, ignoring host", newHost);
19951998 }
@@ -2031,7 +2034,7 @@
20312034 // Make sure we have up-to-date infos on that host before adding it (so we typically
20322035 // catch that an upgraded node uses a new cassandra version).
20332036 if (controlConnection.refreshNodeInfo(h)) {
2034- onAdd(h);
2037+ onAdd(h, null);
20352038 } else {
20362039 logger.debug("Not enough info for {}, ignoring host", h);
20372040 }
@@ -2044,7 +2047,7 @@
20442047 // Make sure we have up-to-date infos on that host before adding it (so we typically
20452048 // catch that an upgraded node uses a new cassandra version).
20462049 if (controlConnection.refreshNodeInfo(hostUp)) {
2047- onUp(hostUp);
2050+ onUp(hostUp, null);
20482051 } else {
20492052 logger.debug("Not enough info for {}, ignoring host", hostUp);
20502053 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +10 −11
@@ -75,7 +75,7 @@
7575 private final Object terminationLock = new Object();
7676
7777
78- private volatile HostConnectionPool pool;
78+ private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
7979
8080 /** The instant when the connection should be trashed after being idle for too long */
8181 private volatile long trashTime = Long.MAX_VALUE;
@@ -131,7 +131,7 @@
131131 */
132132 Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
133133 this(name, address, factory);
134- this.pool = pool;
134+ this.poolRef.set(pool);
135135 }
136136
137137 private static String extractMessage(Throwable t) {
@@ -301,6 +301,7 @@
301301 }
302302
303303 protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
304+ HostConnectionPool pool = this.poolRef.get();
304305 if (pool == null)
305306 return;
306307
@@ -425,13 +426,12 @@
425426 }
426427
427428 boolean hasPool() {
428- return this.pool != null;
429+ return this.poolRef.get() != null;
429430 }
430431
431- void setPool(HostConnectionPool pool) {
432- if (hasPool())
433- throw new IllegalStateException("cannot move a connection from one pool to another");
434- this.pool = pool;
432+ /** @return whether the connection was already associated with a pool */
433+ boolean setPool(HostConnectionPool pool) {
434+ return poolRef.compareAndSet(null, pool);
435435 }
436436
437437 /**
@@ -439,10 +439,9 @@
439439 * The connection should generally not be reused after that.
440440 */
441441 void release() {
442- if (pool == null)
443- return;
444-
445- pool.returnConnection(this);
442+ HostConnectionPool pool = poolRef.get();
443+ if (pool != null)
444+ pool.returnConnection(this);
446445 }
447446
448447 long getTrashTime() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +12 −3
@@ -65,7 +65,12 @@
6565
6666 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
6767
68- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
68+ /**
69+ * @param preExistentConnection an existing connection (from a reconnection attempt) that we want to
70+ * reuse as part of this pool. Might be null or already used by another
71+ * pool.
72+ */
73+ public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager, Connection preExistentConnection) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
6974 assert hostDistance != HostDistance.IGNORED;
7075 this.host = host;
7176 this.hostDistance = hostDistance;
@@ -82,8 +87,12 @@
8287 // Create initial core connections
8388 List<Connection> l = new ArrayList<Connection>(options().getCoreConnectionsPerHost(hostDistance));
8489 try {
85- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
86- l.add(manager.connectionFactory().open(this));
90+ for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
91+ if (preExistentConnection != null && preExistentConnection.setPool(this))
92+ l.add(preExistentConnection);
93+ else
94+ l.add(manager.connectionFactory().open(this));
95+ }
8796 } catch (InterruptedException e) {
8897 Thread.currentThread().interrupt();
8998 // If asked to interrupt, we can skip opening core connections, the pool will still work.
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +10 −10
@@ -84,7 +84,7 @@
8484 List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size());
8585 for (Host host : hosts)
8686 if (host.state != Host.State.DOWN)
87- futures.add(maybeAddPool(host, executor()));
87+ futures.add(maybeAddPool(host, null, executor()));
8888 ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
8989 try {
9090 f.get();
@@ -100,7 +100,7 @@
100100 for (Host host : cluster.getMetadata().allHosts()) {
101101 try {
102102 if (host.state != Host.State.DOWN)
103- maybeAddPool(host, executor()).get();
103+ maybeAddPool(host, null, executor()).get();
104104 } catch (ExecutionException e) {
105105 // This is not supposed to happen
106106 throw new DriverInternalError(e);
@@ -214,7 +214,7 @@
214214 }
215215
216216 // Returns whether there was problem creating the pool
217- ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) {
217+ ListenableFuture<Boolean> forceRenewPool(final Host host, final Connection preExistentConnection, ListeningExecutorService executor) {
218218 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
219219 if (distance == HostDistance.IGNORED)
220220 return Futures.immediateFuture(true);
@@ -227,7 +227,7 @@
227227 if (isClosing)
228228 return true;
229229
230- HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
230+ HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this, preExistentConnection);
231231 HostConnectionPool previous = pools.put(host, newPool);
232232 if (previous == null) {
233233 logger.debug("Added connection pool for {}", host);
@@ -255,7 +255,7 @@
255255 // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools
256256 // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we
257257 // want to avoid
258- private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
258+ private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition, Connection preExistentConnection) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
259259 if (isClosing)
260260 return true;
261261
@@ -266,7 +266,7 @@
266266 if (previous != condition)
267267 return false;
268268
269- HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
269+ HostConnectionPool newPool = new HostConnectionPool(host, distance, this, preExistentConnection);
270270 pools.put(host, newPool);
271271
272272 // If we raced with a session shutdown, ensure that the pool will be closed.
@@ -280,7 +280,7 @@
280280 }
281281
282282 // Returns whether there was problem creating the pool
283- ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) {
283+ ListenableFuture<Boolean> maybeAddPool(final Host host, final Connection preExistentConnection, ListeningExecutorService executor) {
284284 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
285285 if (distance == HostDistance.IGNORED)
286286 return Futures.immediateFuture(true);
@@ -298,7 +298,7 @@
298298 if (previous != null && !previous.isClosed())
299299 return true;
300300
301- if (replacePool(host, distance, previous)) {
301+ if (replacePool(host, distance, previous, preExistentConnection)) {
302302 logger.debug("Added connection pool for {}", host);
303303 return true;
304304 }
@@ -346,7 +346,7 @@
346346
347347 if (pool == null) {
348348 if (dist != HostDistance.IGNORED && h.isUp())
349- poolCreationFutures.add(maybeAddPool(h, executor));
349+ poolCreationFutures.add(maybeAddPool(h, null, executor));
350350 } else if (dist != pool.hostDistance) {
351351 if (dist == HostDistance.IGNORED) {
352352 toRemove.add(h);
@@ -379,7 +379,7 @@
379379 try {
380380 if (pool == null) {
381381 if (dist != HostDistance.IGNORED && h.isUp())
382- maybeAddPool(h, executor).get();
382+ maybeAddPool(h, null, executor).get();
383383 } else if (dist != pool.hostDistance) {
384384 if (dist == HostDistance.IGNORED) {
385385 removePool(h).get();
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +117 −20
@@ -2,6 +2,7 @@
22
33 import java.io.IOException;
44 import java.net.InetSocketAddress;
5+import java.util.Collection;
56 import java.util.Collections;
67 import java.util.Iterator;
78 import java.util.Map;
@@ -12,8 +13,14 @@
1213
1314 import com.google.common.base.Charsets;
1415 import com.google.common.collect.ImmutableMap;
16+import org.mockito.Mockito;
1517 import org.testng.annotations.Test;
18+
1619 import static org.assertj.core.api.Assertions.assertThat;
20+import static org.mockito.Mockito.reset;
21+import static org.mockito.Mockito.spy;
22+import static org.mockito.Mockito.times;
23+import static org.mockito.Mockito.verify;
1724
1825 import com.datastax.driver.core.Host.State;
1926 import com.datastax.driver.core.policies.*;
@@ -33,9 +40,9 @@
3340 ccm = CCMBridge.create("test", 2);
3441 int reconnectionDelay = 1000;
3542 cluster = Cluster.builder()
36- .addContactPoint(CCMBridge.ipOfNode(1))
37- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
38- .build();
43+ .addContactPoint(CCMBridge.ipOfNode(1))
44+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
45+ .build();
3946 cluster.connect();
4047
4148 assertThat(cluster).usesControlHost(1);
@@ -78,11 +85,11 @@
7885 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
7986
8087 cluster = Cluster.builder()
81- .addContactPoint(CCMBridge.ipOfNode(1))
82- // Start with the correct auth so that we can initialize the server
83- .withAuthProvider(authProvider)
84- .withReconnectionPolicy(reconnectionPolicy)
85- .build();
88+ .addContactPoint(CCMBridge.ipOfNode(1))
89+ // Start with the correct auth so that we can initialize the server
90+ .withAuthProvider(authProvider)
91+ .withReconnectionPolicy(reconnectionPolicy)
92+ .build();
8693
8794 cluster.init();
8895 assertThat(cluster).usesControlHost(1);
@@ -122,15 +129,15 @@
122129 CCMBridge ccm = null;
123130 Cluster cluster = null;
124131
125- long reconnectionDelayMillis = 1 * 1000;
132+ long reconnectionDelayMillis = 1000;
126133 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
127134
128135 try {
129136 ccm = CCMBridge.create("test", 2);
130137 cluster = Cluster.builder()
131- .addContactPoint(CCMBridge.ipOfNode(1))
132- .withReconnectionPolicy(reconnectionPolicy)
133- .build();
138+ .addContactPoint(CCMBridge.ipOfNode(1))
139+ .withReconnectionPolicy(reconnectionPolicy)
140+ .build();
134141 cluster.connect();
135142
136143 // Stop a node and cancel the reconnection attempts to it
@@ -163,16 +170,16 @@
163170 CCMBridge ccm = null;
164171 Cluster cluster = null;
165172
166- long reconnectionDelayMillis = 1 * 1000;
173+ long reconnectionDelayMillis = 1000;
167174 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
168175
169176 try {
170177 ccm = CCMBridge.create("test", 1);
171178 cluster = Cluster.builder()
172- .addContactPoint(CCMBridge.ipOfNode(1))
173- .withLoadBalancingPolicy(loadBalancingPolicy)
174- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
175- .build();
179+ .addContactPoint(CCMBridge.ipOfNode(1))
180+ .withLoadBalancingPolicy(loadBalancingPolicy)
181+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
182+ .build();
176183 cluster.connect();
177184
178185 // Tweak the LBP so that the control connection never reconnects, otherwise
@@ -198,6 +205,7 @@
198205 // down for the driver.
199206 ccm.start(1);
200207 ccm.waitForUp(1);
208+ assertThat(cluster).host(1).hasState(State.DOWN);
201209
202210 TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
203211 assertThat(cluster).host(1).hasState(State.DOWN);
@@ -214,6 +222,64 @@
214222 }
215223 }
216224
225+ /**
226+ * The connection established by a successful reconnection attempt should be reused in one of the
227+ * connection pools (JAVA-505).
228+ */
229+ @Test(groups = "long")
230+ public void should_use_connection_from_reconnection_in_pool() {
231+ CCMBridge ccm = null;
232+ Cluster cluster = null;
233+
234+ TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
235+
236+ // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
237+ SocketOptions socketOptions = spy(new SocketOptions());
238+
239+ try {
240+ ccm = CCMBridge.create("test", 1);
241+ cluster = Cluster.builder()
242+ .addContactPoint(CCMBridge.ipOfNode(1))
243+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
244+ .withLoadBalancingPolicy(loadBalancingPolicy)
245+ .withSocketOptions(socketOptions)
246+ .build();
247+ // Create two sessions to have multiple pools
248+ cluster.connect();
249+ cluster.connect();
250+
251+ // Right after init, 1 connection has been opened by the control connection, and 2 (core size) for each pool.
252+ verify(socketOptions, times(5)).getKeepAlive();
253+
254+ // Tweak the LBP so that the control connection never reconnects. This makes it easier
255+ // to reason about the number of connection attempts.
256+ loadBalancingPolicy.returnEmptyQueryPlan = true;
257+
258+ // Stop the node and cancel the reconnection attempts to it
259+ ccm.stop(1);
260+ ccm.waitForDown(1);
261+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
262+ Host host1 = TestUtils.findHost(cluster, 1);
263+ host1.getReconnectionAttemptFuture().cancel(false);
264+
265+ ccm.start(1);
266+ ccm.waitForUp(1);
267+
268+ // Reset the spy and count the number of connections attempts for 1 reconnect
269+ reset(socketOptions);
270+ host1.tryReconnectOnce();
271+ assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
272+ // Expect 1 connection from the reconnection attempt + 3 for the pools (we need 4
273+ // but the one from the reconnection attempt gets reused).
274+ verify(socketOptions, times(4)).getKeepAlive();
275+ } finally {
276+ if (cluster != null)
277+ cluster.close();
278+ if (ccm != null)
279+ ccm.remove();
280+ }
281+ }
282+
217283 /**
218284 * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested.
219285 */
@@ -258,10 +324,9 @@
258324 // no-op, the server should send nothing anyway
259325 }
260326
261- @Override
262- Map<String, String> getCredentials() {
327+ @Override Map<String, String> getCredentials() {
263328 return ImmutableMap.of("username", username,
264- "password", password);
329+ "password", password);
265330 }
266331 }
267332 }
@@ -316,4 +381,36 @@
316381 return super.newQueryPlan(loggedKeyspace, statement);
317382 }
318383 }
384+
385+ public static class TryAllPolicy implements LoadBalancingPolicy {
386+
387+ private Cluster cluster;
388+
389+ @Override public void init(Cluster cluster, Collection<Host> hosts) {
390+ this.cluster = cluster;
391+ }
392+
393+ @Override public HostDistance distance(Host host) {
394+ return HostDistance.LOCAL;
395+ }
396+
397+ @Override public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
398+ return cluster.getMetadata().allHosts().iterator();
399+ }
400+
401+ @Override public void onAdd(Host host) {
402+ }
403+
404+ @Override public void onUp(Host host) {
405+ }
406+
407+ @Override public void onSuspected(Host host) {
408+ }
409+
410+ @Override public void onDown(Host host) {
411+ }
412+
413+ @Override public void onRemove(Host host) {
414+ }
415+ }
319416 }