Elffuss BraidHub

kikocis/java-driver public

Merge pull request #321 from datastax/java505

Make connection and pool creation fully async (JAVA-692),
and optimize connection use on reconnection (JAVA-505)
Changeset0af82488f2070915f2d3b7b869d6be04237a6d4aace81d0f74830e6acc99bd99
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-04-17 22:49 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-04-17 22:49 +02:00
Parentsa5bd5b316c2f, e646d782bb18

Browse the files at this changeset

25 files changed

modified driver-core/CHANGELOG.rst +2 −0
@@ -38,6 +38,8 @@
3838 (JAVA-619)
3939 - [new feature] Expose an API to check for schema agreement after a
4040 schema-altering statement (JAVA-669)
41+- [improvement] Make connection and pool creation fully async (JAVA-692)
42+- [improvement] Optimize connection use after reconnection (JAVA-505)
4143
4244 Merged from 2.0.9_fixes branch:
4345
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +3 −3
@@ -21,7 +21,6 @@
2121 import java.util.concurrent.ExecutionException;
2222 import java.util.concurrent.LinkedBlockingDeque;
2323
24-import com.google.common.util.concurrent.Futures;
2524 import com.google.common.util.concurrent.ListenableFuture;
2625 import com.google.common.util.concurrent.SettableFuture;
2726 import com.google.common.util.concurrent.Uninterruptibles;
@@ -29,6 +28,7 @@
2928 import org.slf4j.LoggerFactory;
3029
3130 import com.datastax.driver.core.exceptions.DriverInternalError;
31+import com.datastax.driver.core.utils.MoreFutures;
3232
3333 /**
3434 * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
@@ -178,7 +178,7 @@
178178 }
179179
180180 public ListenableFuture<Void> fetchMoreResults() {
181- return Futures.immediateFuture(null);
181+ return MoreFutures.VOID_SUCCESS;
182182 }
183183
184184 public ExecutionInfo getExecutionInfo() {
@@ -287,7 +287,7 @@
287287
288288 private ListenableFuture<Void> fetchMoreResults(FetchingState fetchState) {
289289 if (fetchState == null)
290- return Futures.immediateFuture(null);
290+ return MoreFutures.VOID_SUCCESS;
291291
292292 if (fetchState.inProgress != null)
293293 return fetchState.inProgress;
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +194 −185
@@ -1404,21 +1404,13 @@
14041404 return executor.submit(new ExceptionCatchingRunnable() {
14051405 @Override
14061406 public void runMayThrow() throws InterruptedException, ExecutionException {
1407- onUp(host);
1407+ onUp(host, null);
14081408 }
14091409 });
14101410 }
14111411
1412- private void onUp(final Host host) throws InterruptedException, ExecutionException {
1413- // Note that in generalize we can parallelize the pool creation on
1414- // each session, but we shouldn't use executor since we're already
1415- // running on it most probably (and so we could deadlock). Use the
1416- // blockingExecutor instead, that's why it's for.
1417- onUp(host, blockingExecutor);
1418- }
1419-
14201412 // Use triggerOnUp unless you're sure you want to run this on the current thread.
1421- private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
1413+ private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
14221414 logger.debug("Host {} is UP", host);
14231415
14241416 if (isClosed())
@@ -1429,59 +1421,61 @@
14291421 return;
14301422 }
14311423
1432- boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1433- if (!locked) {
1434- logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1435- return;
1436- }
14371424 try {
14381425
1439- // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1440- if (host.state == Host.State.UP)
1426+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1427+ if (!locked) {
1428+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
14411429 return;
1442-
1443- // If there is a reconnection attempt scheduled for that node, cancel it
1444- Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1445- if (scheduledAttempt != null) {
1446- logger.debug("Cancelling reconnection attempt since node is UP");
1447- scheduledAttempt.cancel(false);
14481430 }
1449-
14501431 try {
1451- prepareAllQueries(host);
1452- } catch (InterruptedException e) {
1453- Thread.currentThread().interrupt();
1454- // Don't propagate because we don't want to prevent other listener to run
1455- } catch (UnsupportedProtocolVersionException e) {
1456- logUnsupportedVersionProtocol(host);
1457- return;
1458- } catch (ClusterNameMismatchException e) {
1459- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1460- return;
1461- }
14621432
1463- // Session#onUp() expects the load balancing policy to have been updated first, so that
1464- // Host distances are up to date. This mean the policy could return the node before the
1465- // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1466- // will ignore the node, but we do want to make sure there is no prior pool so we don't
1467- // query from a pool we will shutdown right away.
1468- for (SessionManager s : sessions)
1469- s.removePool(host);
1470- loadBalancingPolicy().onUp(host);
1471- controlConnection.onUp(host);
1433+ // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1434+ if (host.state == Host.State.UP)
1435+ return;
1436+
1437+ // If there is a reconnection attempt scheduled for that node, cancel it
1438+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1439+ if (scheduledAttempt != null) {
1440+ logger.debug("Cancelling reconnection attempt since node is UP");
1441+ scheduledAttempt.cancel(false);
1442+ }
14721443
1473- logger.trace("Adding/renewing host pools for newly UP host {}", host);
1444+ try {
1445+ reusedConnection = prepareAllQueries(host, reusedConnection);
1446+ } catch (InterruptedException e) {
1447+ Thread.currentThread().interrupt();
1448+ // Don't propagate because we don't want to prevent other listener to run
1449+ } catch (UnsupportedProtocolVersionException e) {
1450+ logUnsupportedVersionProtocol(host);
1451+ return;
1452+ } catch (ClusterNameMismatchException e) {
1453+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1454+ return;
1455+ }
1456+
1457+ // Session#onUp() expects the load balancing policy to have been updated first, so that
1458+ // Host distances are up to date. This mean the policy could return the node before the
1459+ // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1460+ // will ignore the node, but we do want to make sure there is no prior pool so we don't
1461+ // query from a pool we will shutdown right away.
1462+ for (SessionManager s : sessions)
1463+ s.removePool(host);
1464+ loadBalancingPolicy().onUp(host);
1465+ controlConnection.onUp(host);
1466+
1467+ logger.trace("Adding/renewing host pools for newly UP host {}", host);
1468+
1469+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1470+ for (SessionManager s : sessions)
1471+ futures.add(s.forceRenewPool(host, reusedConnection));
1472+
1473+ try {
1474+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1475+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1476+ // to the node.
1477+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
14741478
1475- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1476- for (SessionManager s : sessions)
1477- futures.add(s.forceRenewPool(host, poolCreationExecutor));
1478-
1479- // Only mark the node up once all session have re-added their pool (if the load-balancing
1480- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1481- // to the node.
1482- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1483- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1484- public void onSuccess(List<Boolean> poolCreationResults) {
14851479 // If any of the creation failed, they will have signaled a connection failure
14861480 // which will trigger a reconnection to the node. So don't bother marking UP.
14871481 if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
@@ -1493,24 +1487,26 @@
14931487
14941488 for (Host.StateListener listener : listeners)
14951489 listener.onUp(host);
1496- }
14971490
1498- public void onFailure(Throwable t) {
1491+ } catch (ExecutionException e) {
1492+ Throwable t = e.getCause();
14991493 // That future is not really supposed to throw unexpected exceptions
15001494 if (!(t instanceof InterruptedException))
15011495 logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
15021496 }
1503- });
15041497
1505- f.get();
1498+ // Now, check if there isn't pools to create/remove following the addition.
1499+ // We do that now only so that it's not called before we've set the node up.
1500+ for (SessionManager s : sessions)
1501+ s.updateCreatedPools();
15061502
1507- // Now, check if there isn't pools to create/remove following the addition.
1508- // We do that now only so that it's not called before we've set the node up.
1509- for (SessionManager s : sessions)
1510- s.updateCreatedPools(blockingExecutor);
1503+ } finally {
1504+ host.notificationsLock.unlock();
1505+ }
15111506
15121507 } finally {
1513- host.notificationsLock.unlock();
1508+ if (reusedConnection != null && !reusedConnection.hasPool())
1509+ reusedConnection.closeAsync();
15141510 }
15151511 }
15161512
@@ -1563,11 +1559,10 @@
15631559 public void runMayThrow() throws InterruptedException, ExecutionException {
15641560 boolean success;
15651561 try {
1566- // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection
1567- connectionFactory.open(host).closeAsync();
1562+ Connection connection = connectionFactory.open(host);
15681563 // Note that we want to do the pool creation on this thread because we want that
15691564 // when onUp return, the host is ready for querying
1570- onUp(host, MoreExecutors.sameThreadExecutor());
1565+ onUp(host, connection);
15711566 // If one of the connections in onUp failed, it signaled the error and triggerd onDown,
15721567 // but onDown aborted because this reconnection attempt was in progress (JAVA-577).
15731568 // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was
@@ -1649,7 +1644,6 @@
16491644 if (distance == HostDistance.IGNORED || !startReconnection)
16501645 return;
16511646
1652- // Note: we basically waste the first successful reconnection, but it's probably not a big deal
16531647 logger.debug("{} is down, scheduling connection retries", host);
16541648 startPeriodicReconnectionAttempt(host, isHostAddition);
16551649 } finally {
@@ -1665,19 +1659,15 @@
16651659 }
16661660
16671661 protected void onReconnection(Connection connection) {
1668- // We don't use that first connection so close it.
1669- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1670- // we use it for the first HostConnectionPool created
1671- connection.closeAsync();
16721662 // Make sure we have up-to-date infos on that host before adding it (so we typically
16731663 // catch that an upgraded node uses a new cassandra version).
16741664 if (controlConnection.refreshNodeInfo(host)) {
16751665 logger.debug("Successful reconnection to {}, setting host UP", host);
16761666 try {
16771667 if (isHostAddition)
1678- onAdd(host);
1668+ onAdd(host, connection);
16791669 else
1680- onUp(host);
1670+ onUp(host, connection);
16811671 } catch (InterruptedException e) {
16821672 Thread.currentThread().interrupt();
16831673 } catch (Exception e) {
@@ -1685,6 +1675,7 @@
16851675 }
16861676 } else {
16871677 logger.debug("Not enough info for {}, ignoring host", host);
1678+ connection.closeAsync();
16881679 }
16891680 }
16901681
@@ -1721,16 +1712,12 @@
17211712 }
17221713
17231714 protected void onReconnection(Connection connection) {
1724- // We don't use that first connection so close it.
1725- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1726- // we use it for the first HostConnectionPool created
1727- connection.closeAsync();
17281715 // Make sure we have up-to-date infos on that host before adding it (so we typically
17291716 // catch that an upgraded node uses a new cassandra version).
17301717 if (controlConnection.refreshNodeInfo(host)) {
17311718 logger.debug("Successful reconnection to {}, setting host UP", host);
17321719 try {
1733- onUp(host);
1720+ onUp(host, connection);
17341721 } catch (InterruptedException e) {
17351722 Thread.currentThread().interrupt();
17361723 } catch (Exception e) {
@@ -1738,6 +1725,7 @@
17381725 }
17391726 } else {
17401727 logger.debug("Not enough info for {}, ignoring host", host);
1728+ connection.closeAsync();
17411729 }
17421730 }
17431731
@@ -1763,13 +1751,13 @@
17631751 return executor.submit(new ExceptionCatchingRunnable() {
17641752 @Override
17651753 public void runMayThrow() throws InterruptedException, ExecutionException {
1766- onAdd(host);
1754+ onAdd(host, null);
17671755 }
17681756 });
17691757 }
17701758
17711759 // Use triggerOnAdd unless you're sure you want to run this on the current thread.
1772- private void onAdd(final Host host) throws InterruptedException, ExecutionException {
1760+ private void onAdd(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
17731761 if (isClosed())
17741762 return;
17751763
@@ -1780,55 +1768,57 @@
17801768 return;
17811769 }
17821770
1783- boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1784- if (!locked) {
1785- logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1786- return;
1787- }
17881771 try {
17891772
1790- // Adds to the load balancing first and foremost, as doing so might change the decision
1791- // it will make for distance() on that node (not likely but we leave that possibility).
1792- // This does mean the policy may start returning that node for query plan, but as long
1793- // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1794- loadBalancingPolicy().onAdd(host);
1795-
1796- // Next, if the host should be ignored, well, ignore it.
1797- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1798- // We still mark the node UP though as it should be (and notifiy the listeners).
1799- // We'll mark it down if we have a notification anyway and we've documented that especially
1800- // for IGNORED hosts, the isUp() method was a best effort guess
1801- host.setUp();
1802- for (Host.StateListener listener : listeners)
1803- listener.onAdd(host);
1773+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1774+ if (!locked) {
1775+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
18041776 return;
18051777 }
1806-
18071778 try {
1808- prepareAllQueries(host);
1809- } catch (InterruptedException e) {
1810- Thread.currentThread().interrupt();
1811- // Don't propagate because we don't want to prevent other listener to run
1812- } catch (UnsupportedProtocolVersionException e) {
1813- logUnsupportedVersionProtocol(host);
1814- return;
1815- } catch (ClusterNameMismatchException e) {
1816- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1817- return;
1818- }
18191779
1820- controlConnection.onAdd(host);
1780+ // Adds to the load balancing first and foremost, as doing so might change the decision
1781+ // it will make for distance() on that node (not likely but we leave that possibility).
1782+ // This does mean the policy may start returning that node for query plan, but as long
1783+ // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1784+ loadBalancingPolicy().onAdd(host);
1785+
1786+ // Next, if the host should be ignored, well, ignore it.
1787+ if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1788+ // We still mark the node UP though as it should be (and notifiy the listeners).
1789+ // We'll mark it down if we have a notification anyway and we've documented that especially
1790+ // for IGNORED hosts, the isUp() method was a best effort guess
1791+ host.setUp();
1792+ for (Host.StateListener listener : listeners)
1793+ listener.onAdd(host);
1794+ return;
1795+ }
1796+
1797+ try {
1798+ reusedConnection = prepareAllQueries(host, reusedConnection);
1799+ } catch (InterruptedException e) {
1800+ Thread.currentThread().interrupt();
1801+ // Don't propagate because we don't want to prevent other listener to run
1802+ } catch (UnsupportedProtocolVersionException e) {
1803+ logUnsupportedVersionProtocol(host);
1804+ return;
1805+ } catch (ClusterNameMismatchException e) {
1806+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1807+ return;
1808+ }
1809+
1810+ controlConnection.onAdd(host);
1811+
1812+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1813+ for (SessionManager s : sessions)
1814+ futures.add(s.maybeAddPool(host, reusedConnection));
1815+
1816+ try {
1817+ // Only mark the node up once all session have added their pool (if the load-balancing
1818+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1819+ // to the node.
1820+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
18211821
1822- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1823- for (SessionManager s : sessions)
1824- futures.add(s.maybeAddPool(host, blockingExecutor));
1825-
1826- // Only mark the node up once all session have added their pool (if the load-balancing
1827- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1828- // to the node.
1829- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1830- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1831- public void onSuccess(List<Boolean> poolCreationResults) {
18321822 // If any of the creation failed, they will have signaled a connection failure
18331823 // which will trigger a reconnection to the node. So don't bother marking UP.
18341824 if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
@@ -1840,24 +1830,26 @@
18401830
18411831 for (Host.StateListener listener : listeners)
18421832 listener.onAdd(host);
1843- }
18441833
1845- public void onFailure(Throwable t) {
1834+ } catch (ExecutionException e) {
1835+ Throwable t = e.getCause();
18461836 // That future is not really supposed to throw unexpected exceptions
18471837 if (!(t instanceof InterruptedException))
18481838 logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
18491839 }
1850- });
18511840
1852- f.get();
1841+ // Now, check if there isn't pools to create/remove following the addition.
1842+ // We do that now only so that it's not called before we've set the node up.
1843+ for (SessionManager s : sessions)
1844+ s.updateCreatedPools();
18531845
1854- // Now, check if there isn't pools to create/remove following the addition.
1855- // We do that now only so that it's not called before we've set the node up.
1856- for (SessionManager s : sessions)
1857- s.updateCreatedPools(blockingExecutor);
1846+ } finally {
1847+ host.notificationsLock.unlock();
1848+ }
18581849
18591850 } finally {
1860- host.notificationsLock.unlock();
1851+ if (reusedConnection != null && !reusedConnection.hasPool())
1852+ reusedConnection.closeAsync();
18611853 }
18621854 }
18631855
@@ -1956,69 +1948,85 @@
19561948 return stmt;
19571949 }
19581950
1959- private void prepareAllQueries(Host host) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
1951+ /**
1952+ * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
1953+ * reuse to prepare the statements (might be null).
1954+ * @return a connection that the rest of the initialization process can use (it will be made part
1955+ * of a connection pool). Can be reusedConnection, or one that was open in the method.
1956+ */
1957+ private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
19601958 if (preparedQueries.isEmpty())
1961- return;
1959+ return reusedConnection;
19621960
19631961 logger.debug("Preparing {} prepared queries on newly up node {}", preparedQueries.size(), host);
1962+ Connection connection = null;
19641963 try {
1965- Connection connection = connectionFactory.open(host);
1964+ connection = (reusedConnection == null)
1965+ ? connectionFactory.open(host)
1966+ : reusedConnection;
19661967
1967- try
1968- {
1969- try {
1970- ControlConnection.waitForSchemaAgreement(connection, this);
1971- } catch (ExecutionException e) {
1972- // As below, just move on
1973- }
1968+ try {
1969+ ControlConnection.waitForSchemaAgreement(connection, this);
1970+ } catch (ExecutionException e) {
1971+ // As below, just move on
1972+ }
19741973
1975- // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation
1976- // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the
1977- // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is
1978- // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed.
1979-
1980- // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally
1981- // used for preparing it. However, since we are likely that all prepared query belong to only a handful
1982- // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed,
1983- // we first sort the query per keyspace.
1984- SetMultimap<String, String> perKeyspace = HashMultimap.create();
1985- for (PreparedStatement ps : preparedQueries.values()) {
1986- // It's possible for a query to not have a current keyspace. But since null doesn't work well as
1987- // map keys, we use the empty string instead (that is not a valid keyspace name).
1988- String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace();
1989- perKeyspace.put(keyspace, ps.getQueryString());
1990- }
1974+ // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation
1975+ // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the
1976+ // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is
1977+ // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed.
1978+
1979+ // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally
1980+ // used for preparing it. However, since we are likely that all prepared query belong to only a handful
1981+ // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed,
1982+ // we first sort the query per keyspace.
1983+ SetMultimap<String, String> perKeyspace = HashMultimap.create();
1984+ for (PreparedStatement ps : preparedQueries.values()) {
1985+ // It's possible for a query to not have a current keyspace. But since null doesn't work well as
1986+ // map keys, we use the empty string instead (that is not a valid keyspace name).
1987+ String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace();
1988+ perKeyspace.put(keyspace, ps.getQueryString());
1989+ }
19911990
1992- for (String keyspace : perKeyspace.keySet())
1993- {
1994- // Empty string mean no particular keyspace to set
1995- if (!keyspace.isEmpty())
1996- connection.setKeyspace(keyspace);
1997-
1998- List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size());
1999- for (String query : perKeyspace.get(keyspace)) {
2000- futures.add(connection.write(new Requests.Prepare(query)));
2001- }
2002- for (Connection.Future future : futures) {
2003- try {
2004- future.get();
2005- } catch (ExecutionException e) {
2006- // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do
2007- // currently). It's not a big deal however as if it's a more serious problem it'll show up later when
2008- // the query is tried for execution.
2009- logger.debug("Unexpected error while preparing queries on new/newly up host", e);
2010- }
1991+ for (String keyspace : perKeyspace.keySet()) {
1992+ // Empty string mean no particular keyspace to set
1993+ if (!keyspace.isEmpty())
1994+ connection.setKeyspace(keyspace);
1995+
1996+ List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size());
1997+ for (String query : perKeyspace.get(keyspace)) {
1998+ futures.add(connection.write(new Requests.Prepare(query)));
1999+ }
2000+ for (Connection.Future future : futures) {
2001+ try {
2002+ future.get();
2003+ } catch (ExecutionException e) {
2004+ // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do
2005+ // currently). It's not a big deal however as if it's a more serious problem it'll show up later when
2006+ // the query is tried for execution.
2007+ logger.debug("Unexpected error while preparing queries on new/newly up host", e);
20112008 }
20122009 }
2013- } finally {
2014- connection.closeAsync();
20152010 }
2011+
2012+ return connection;
20162013 } catch (ConnectionException e) {
20172014 // Ignore, not a big deal
2015+ if (connection != null)
2016+ connection.closeAsync();
2017+ return null;
20182018 } catch (AuthenticationException e) {
20192019 // That's a bad news, but ignore at this point
2020+ if (connection != null)
2021+ connection.closeAsync();
2022+ return null;
20202023 } catch (BusyConnectionException e) {
20212024 // Ignore, not a big deal
2025+ // In theory the problem is transient so the connection could be reused later, but if the core pool size is 1
2026+ // it's better to close this one so that we start with a fresh connection.
2027+ if (connection != null)
2028+ connection.closeAsync();
2029+ return null;
20222030 }
20232031 }
20242032
@@ -2107,7 +2115,7 @@
21072115 // Make sure we have up-to-date infos on that host before adding it (so we typically
21082116 // catch that an upgraded node uses a new cassandra version).
21092117 if (controlConnection.refreshNodeInfo(newHost)) {
2110- onAdd(newHost);
2118+ onAdd(newHost, null);
21112119 } else {
21122120 logger.debug("Not enough info for {}, ignoring host", newHost);
21132121 }
@@ -2149,7 +2157,7 @@
21492157 // Make sure we have up-to-date infos on that host before adding it (so we typically
21502158 // catch that an upgraded node uses a new cassandra version).
21512159 if (controlConnection.refreshNodeInfo(h)) {
2152- onAdd(h);
2160+ onAdd(h, null);
21532161 } else {
21542162 logger.debug("Not enough info for {}, ignoring host", h);
21552163 }
@@ -2162,7 +2170,7 @@
21622170 // Make sure we have up-to-date infos on that host before adding it (so we typically
21632171 // catch that an upgraded node uses a new cassandra version).
21642172 if (controlConnection.refreshNodeInfo(hostUp)) {
2165- onUp(hostUp);
2173+ onUp(hostUp, null);
21662174 } else {
21672175 logger.debug("Not enough info for {}, ignoring host", hostUp);
21682176 }
@@ -2221,7 +2229,7 @@
22212229 controlConnection.reconnect();
22222230
22232231 for (SessionManager s : sessions)
2224- s.updateCreatedPools(executor);
2232+ s.updateCreatedPools();
22252233 }
22262234
22272235 void refreshConnectedHost(Host host) {
@@ -2231,7 +2239,7 @@
22312239 controlConnection.reconnect();
22322240
22332241 for (SessionManager s : sessions)
2234- s.updateCreatedPools(host, executor);
2242+ s.updateCreatedPools(host);
22352243 }
22362244
22372245 private class ClusterCloseFuture extends CloseFuture.Forwarding {
@@ -2311,7 +2319,8 @@
23112319 private static final int INTERVAL_MS = 15000;
23122320
23132321 private final ScheduledExecutorService executor;
2314- private final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
2322+ @VisibleForTesting
2323+ final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
23152324
23162325 private volatile boolean shutdown;
23172326
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +329 −152
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.lang.ref.WeakReference;
1819 import java.net.InetSocketAddress;
1920 import java.util.HashSet;
2021 import java.util.Iterator;
@@ -26,8 +27,8 @@
2627 import java.util.concurrent.atomic.AtomicReference;
2728
2829 import com.google.common.collect.Lists;
29-import com.google.common.util.concurrent.AbstractFuture;
30-import com.google.common.util.concurrent.Uninterruptibles;
30+import com.google.common.collect.MapMaker;
31+import com.google.common.util.concurrent.*;
3132 import io.netty.bootstrap.Bootstrap;
3233 import io.netty.channel.*;
3334 import io.netty.channel.group.ChannelGroup;
@@ -47,7 +48,8 @@
4748 import static io.netty.handler.timeout.IdleState.ALL_IDLE;
4849
4950 import com.datastax.driver.core.exceptions.AuthenticationException;
50-import com.datastax.driver.core.exceptions.DriverInternalError;
51+import com.datastax.driver.core.exceptions.DriverException;
52+import com.datastax.driver.core.utils.MoreFutures;
5153
5254 // For LoggingHandler
5355 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -63,10 +65,16 @@
6365
6466 private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false);
6567
68+ enum State {OPEN, TRASHED, RESURRECTING, GONE }
69+
70+ final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
71+
72+ volatile long maxIdleTime;
73+
6674 public final InetSocketAddress address;
6775 private final String name;
6876
69- private final Channel channel;
77+ private volatile Channel channel;
7078 private final Factory factory;
7179
7280 private final Dispatcher dispatcher = new Dispatcher();
@@ -82,23 +90,42 @@
8290
8391 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
8492
93+ private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
94+
8595 /**
86- * Create a new connection to a Cassandra node.
87- *
88- * The connection is open and initialized by the constructor.
96+ /**
97+ * Create a new connection to a Cassandra node and associate it with the given pool.
8998 *
90- * @throws ConnectionException if the connection attempts fails or is
91- * refused by the server.
99+ * @param name the connection name
100+ * @param address the remote address
101+ * @param factory the connection factory to use
102+ * @param pool the pool this connection belongs to. May be null if this connection does not belong to a pool.
103+ * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}.
92104 */
93- protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
105+ protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
94106 this.address = address;
95107 this.factory = factory;
96108 this.name = name;
109+ this.poolRef.set(pool);
110+ }
111+
112+ /**
113+ * Create a new connection to a Cassandra node.
114+ */
115+ Connection(String name, InetSocketAddress address, Factory factory) {
116+ this(name, address, factory, null);
117+ }
118+
119+ public ListenableFuture<Void> initAsync() {
120+ if (factory.isShutdown)
121+ return Futures.immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down"));
122+
123+ int protocolVersion = factory.protocolVersion == 1 ? 1 : 2;
124+ final SettableFuture<Void> channelReadyFuture = SettableFuture.create();
97125
98126 try {
99127 Bootstrap bootstrap = factory.newBootstrap();
100128 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
101- int protocolVersion = factory.protocolVersion == 1 ? 1 : 2;
102129 bootstrap.handler(
103130 new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
104131 factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
@@ -107,41 +134,81 @@
107134 ChannelFuture future = bootstrap.connect(address);
108135
109136 writer.incrementAndGet();
110- try {
111- // Wait until the connection attempt succeeds or fails.
112- this.channel = future.awaitUninterruptibly().channel();
113- this.factory.allChannels.add(this.channel);
114- if (!future.isSuccess()) {
115- if (logger.isDebugEnabled())
116- logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.cause())));
117- throw defunct(new TransportException(address, "Cannot connect", future.cause()));
137+ future.addListener(new ChannelFutureListener() {
138+ @Override
139+ public void operationComplete(ChannelFuture future) throws Exception {
140+ writer.decrementAndGet();
141+ channel = future.channel();
142+ if (isClosed()) {
143+ channel.close().addListener(new ChannelFutureListener() {
144+ @Override
145+ public void operationComplete(ChannelFuture future) throws Exception {
146+ channelReadyFuture.setException(new TransportException(Connection.this.address, "Connection closed during initialization."));
147+ }
148+ });
149+ } else {
150+ Connection.this.factory.allChannels.add(channel);
151+ if (!future.isSuccess()) {
152+ if (logger.isDebugEnabled())
153+ logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause())));
154+ channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause()));
155+ } else {
156+ logger.debug("{} Connection opened successfully", Connection.this);
157+ channel.closeFuture().addListener(new ChannelCloseListener());
158+ channelReadyFuture.set(null);
159+ }
160+ }
118161 }
119- channel.closeFuture().addListener(new ChannelCloseListener());
120- } finally {
121- writer.decrementAndGet();
122- }
123-
124- logger.trace("{} Connection opened successfully", this);
125- initializeTransport(protocolVersion, factory.manager.metadata.clusterName);
126- logger.debug("{} Transport initialized and ready", this);
127- isInitialized = true;
128-
129- } catch (ConnectionException e) {
130- closeAsync().force();
131- throw e;
132- } catch (ClusterNameMismatchException e) {
133- closeAsync().force();
134- throw e;
135- } catch (UnsupportedProtocolVersionException e) {
136- closeAsync().force();
137- throw e;
138- } catch (InterruptedException e) {
139- closeAsync().force();
140- throw e;
162+ });
141163 } catch (RuntimeException e) {
142164 closeAsync().force();
143165 throw e;
144166 }
167+
168+ Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();
169+
170+ ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
171+ onChannelReady(protocolVersion, initExecutor), initExecutor);
172+
173+ // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
174+ ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() {
175+ @Override
176+ public ListenableFuture<Void> create(Throwable t) throws Exception {
177+ SettableFuture<Void> future = SettableFuture.create();
178+ // Make sure the connection gets properly closed.
179+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
180+ // These exceptions cause the node to be ignored, so just propagate
181+ closeAsync().force();
182+ future.setException(t);
183+ } else {
184+ // Defunct to ensure that the error will be signaled (marking the host down)
185+ ConnectionException ce = (t instanceof ConnectionException)
186+ ? (ConnectionException)t
187+ : new ConnectionException(Connection.this.address,
188+ String.format("Unexpected error during transport initialization (%s)", t),
189+ t);
190+ future.setException(defunct(ce));
191+ }
192+ return future;
193+ }
194+ }, initExecutor);
195+
196+ // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel.
197+ Futures.addCallback(initFuture, new FutureCallback<Void>() {
198+ @Override
199+ public void onSuccess(Void result) {
200+ isInitialized = true;
201+ }
202+
203+ @Override
204+ public void onFailure(Throwable t) {
205+ if (!isClosed()) {
206+ closeAsync().force();
207+ }
208+ }
209+ }, initExecutor);
210+
211+ return initFuture;
145212 }
146213
147214 private static String extractMessage(Throwable t) {
@@ -153,119 +220,157 @@
153220 return " (" + msg + ')';
154221 }
155222
156- private void initializeTransport(int version, String clusterName) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
157- try {
158- ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
159- Message.Response response = write(new Requests.Startup(compression)).get();
160- switch (response.type) {
161- case READY:
162- break;
163- case ERROR:
164- Responses.Error error = (Responses.Error)response;
165- // Testing for a specific string is a tad fragile but well, we don't have much choice
166- if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
167- throw unsupportedProtocolVersionException(version);
168- throw defunct(new TransportException(address, String.format("Error initializing connection: %s", error.message)));
169- case AUTHENTICATE:
170- Authenticator authenticator = factory.authProvider.newAuthenticator(address);
171- if (version == 1)
172- {
173- if (authenticator instanceof ProtocolV1Authenticator)
174- authenticateV1(authenticator);
175- else
176- // DSE 3.x always uses SASL authentication backported from protocol v2
177- authenticateV2(authenticator);
178- }
179- else
180- authenticateV2(authenticator);
181- break;
182- default:
183- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
223+ private AsyncFunction<Void, Void> onChannelReady(final int protocolVersion, final Executor initExecutor) {
224+ return new AsyncFunction<Void, Void>() {
225+ @Override
226+ public ListenableFuture<Void> apply(Void input) throws Exception {
227+ ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
228+ Future startupResponseFuture = write(new Requests.Startup(compression));
229+ return Futures.transform(startupResponseFuture,
230+ onStartupResponse(protocolVersion, initExecutor), initExecutor);
184231 }
232+ };
233+ }
185234
186- checkClusterName(clusterName);
187- } catch (BusyConnectionException e) {
188- throw defunct(new DriverInternalError("Newly created connection should not be busy"));
189- } catch (ExecutionException e) {
190- throw defunct(new ConnectionException(address, String.format("Unexpected error during transport initialization (%s)", e.getCause()), e.getCause()));
191- }
235+ private AsyncFunction<Message.Response, Void> onStartupResponse(final int protocolVersion, final Executor initExecutor) {
236+ return new AsyncFunction<Message.Response, Void>() {
237+ @Override
238+ public ListenableFuture<Void> apply(Message.Response response) throws Exception {
239+ switch (response.type) {
240+ case READY:
241+ return checkClusterName(initExecutor);
242+ case ERROR:
243+ Responses.Error error = (Responses.Error)response;
244+ // Testing for a specific string is a tad fragile but well, we don't have much choice
245+ if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
246+ throw unsupportedProtocolVersionException(protocolVersion);
247+ throw new TransportException(address, String.format("Error initializing connection: %s", error.message));
248+ case AUTHENTICATE:
249+ Authenticator authenticator = factory.authProvider.newAuthenticator(address);
250+ if (protocolVersion == 1)
251+ {
252+ if (authenticator instanceof ProtocolV1Authenticator)
253+ return authenticateV1(authenticator, initExecutor);
254+ else
255+ // DSE 3.x always uses SASL authentication backported from protocol v2
256+ return authenticateV2(authenticator, initExecutor);
257+ }
258+ else
259+ return authenticateV2(authenticator, initExecutor);
260+ default:
261+ throw new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type));
262+ }
263+ }
264+ };
192265 }
193266
194- private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) {
195- logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion);
196- return new UnsupportedProtocolVersionException(address, triedVersion);
267+ // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
268+ // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
269+ // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
270+ private ListenableFuture<Void> checkClusterName(final Executor executor) {
271+ final String expected = factory.manager.metadata.clusterName;
272+
273+ // At initialization, the cluster is not known yet
274+ if (expected == null)
275+ return MoreFutures.VOID_SUCCESS;
276+
277+ DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
278+ try {
279+ write(clusterNameFuture);
280+ return Futures.transform(clusterNameFuture,
281+ new AsyncFunction<ResultSet, Void>() {
282+ @Override
283+ public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
284+ Row row = rs.one();
285+ String actual = row.getString("cluster_name");
286+ if (!expected.equals(actual))
287+ throw new ClusterNameMismatchException(address, actual, expected);
288+ return MoreFutures.VOID_SUCCESS;
289+ }
290+ }, executor);
291+ } catch (Exception e) {
292+ return Futures.immediateFailedFuture(e);
293+ }
197294 }
198295
199- private void authenticateV1(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
296+ private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final Executor executor) {
200297 Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
201- Message.Response authResponse = write(creds).get();
202- switch (authResponse.type) {
203- case READY:
204- break;
205- case ERROR:
206- throw defunct(new AuthenticationException(address, ((Responses.Error)authResponse).message));
207- default:
208- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
298+ try {
299+ Future authResponseFuture = write(creds);
300+ return Futures.transform(authResponseFuture,
301+ new AsyncFunction<Message.Response, Void>() {
302+ @Override
303+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
304+ switch (authResponse.type) {
305+ case READY:
306+ return checkClusterName(executor);
307+ case ERROR:
308+ throw new AuthenticationException(address, ((Responses.Error)authResponse).message);
309+ default:
310+ throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
311+ }
312+ }
313+ }, executor);
314+ } catch (Exception e) {
315+ return Futures.immediateFailedFuture(e);
209316 }
210317 }
211318
212- private void authenticateV2(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
319+ private ListenableFuture<Void> authenticateV2(final Authenticator authenticator, final Executor executor) {
213320 byte[] initialResponse = authenticator.initialResponse();
214321 if (null == initialResponse)
215322 initialResponse = EMPTY_BYTE_ARRAY;
216323
217- Message.Response authResponse = write(new Requests.AuthResponse(initialResponse)).get();
218- waitForAuthCompletion(authResponse, authenticator);
219- }
220-
221- private void waitForAuthCompletion(Message.Response authResponse, Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
222- switch (authResponse.type) {
223- case AUTH_SUCCESS:
224- logger.trace("{} Authentication complete", this);
225- authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
226- break;
227- case AUTH_CHALLENGE:
228- byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
229- if (responseToServer == null) {
230- // If we generate a null response, then authentication has completed, return without
231- // sending a further response back to the server.
232- logger.trace("{} Authentication complete (No response to server)", this);
233- return;
234- } else {
235- // Otherwise, send the challenge response back to the server
236- logger.trace("{} Sending Auth response to challenge", this);
237- waitForAuthCompletion(write(new Requests.AuthResponse(responseToServer)).get(), authenticator);
238- }
239- break;
240- case ERROR:
241- // This is not very nice, but we're trying to identify if we
242- // attempted v2 auth against a server which only supports v1
243- // The AIOOBE indicates that the server didn't recognise the
244- // initial AuthResponse message
245- String message = ((Responses.Error)authResponse).message;
246- if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
247- message = String.format("Cannot use authenticator %s with protocol version 1, "
248- + "only plain text authentication is supported with this protocol version", authenticator);
249- throw defunct(new AuthenticationException(address, message));
250- default:
251- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type)));
324+ try {
325+ Future authResponseFuture = write(new Requests.AuthResponse(initialResponse));
326+ return Futures.transform(authResponseFuture, onV2AuthResponse(authenticator, executor), executor);
327+ } catch (Exception e) {
328+ return Futures.immediateFailedFuture(e);
252329 }
253330 }
254331
255- // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
256- // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
257- // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
258- private void checkClusterName(String expected) throws ClusterNameMismatchException, ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
259- // At initialization, the cluster is not known yet
260- if (expected == null)
261- return;
332+ private AsyncFunction<Message.Response, Void> onV2AuthResponse(final Authenticator authenticator, final Executor executor) {
333+ return new AsyncFunction<Message.Response, Void>() {
334+ @Override
335+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
336+ switch (authResponse.type) {
337+ case AUTH_SUCCESS:
338+ logger.trace("{} Authentication complete", this);
339+ authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
340+ return checkClusterName(executor);
341+ case AUTH_CHALLENGE:
342+ byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
343+ if (responseToServer == null) {
344+ // If we generate a null response, then authentication has completed, proceed without
345+ // sending a further response back to the server.
346+ logger.trace("{} Authentication complete (No response to server)", this);
347+ return checkClusterName(executor);
348+ } else {
349+ // Otherwise, send the challenge response back to the server
350+ logger.trace("{} Sending Auth response to challenge", this);
351+ Future nextResponseFuture = write(new Requests.AuthResponse(responseToServer));
352+ return Futures.transform(nextResponseFuture, onV2AuthResponse(authenticator, executor), executor);
353+ }
354+ case ERROR:
355+ // This is not very nice, but we're trying to identify if we
356+ // attempted v2 auth against a server which only supports v1
357+ // The AIOOBE indicates that the server didn't recognise the
358+ // initial AuthResponse message
359+ String message = ((Responses.Error)authResponse).message;
360+ if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
361+ message = String.format("Cannot use authenticator %s with protocol version 1, "
362+ + "only plain text authentication is supported with this protocol version", authenticator);
363+ throw new AuthenticationException(address, message);
364+ default:
365+ throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
366+ }
367+ }
368+ };
369+ }
262370
263- DefaultResultSetFuture future = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
264- write(future);
265- Row row = future.get().one();
266- String actual = row.getString("cluster_name");
267- if (!expected.equals(actual))
268- throw new ClusterNameMismatchException(address, actual, expected);
371+ private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) {
372+ logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion);
373+ return new UnsupportedProtocolVersionException(address, triedVersion);
269374 }
270375
271376 public boolean isDefunct() {
@@ -293,9 +398,9 @@
293398 // If the host was reconnecting, and this error happens right after we opened a connection pool, but
294399 // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can
295400 // lead to a race condition that leaves the node UP with a closed pool.
401+ HostConnectionPool pool = this.poolRef.get();
296402 boolean belongsToReconnectingPool = host.state != Host.State.UP &&
297- this instanceof PooledConnection &&
298- (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed());
403+ (pool == null || !pool.isClosed());
299404
300405 boolean markSuspected = isInitialized && !belongsToReconnectingPool;
301406
@@ -314,6 +419,19 @@
314419 }
315420
316421 protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
422+ // If an error happens during initialization, the owner will detect it and take appropriate action
423+ if (!isInitialized)
424+ return;
425+
426+ HostConnectionPool pool = this.poolRef.get();
427+ if (pool == null)
428+ return;
429+
430+ if (hostIsDown) {
431+ pool.closeAsync().force();
432+ } else {
433+ pool.replaceDefunctConnection(this);
434+ }
317435 }
318436
319437 public String keyspace() {
@@ -462,6 +580,25 @@
462580 };
463581 }
464582
583+ boolean hasPool() {
584+ return this.poolRef.get() != null;
585+ }
586+
587+ /** @return whether the connection was already associated with a pool */
588+ boolean setPool(HostConnectionPool pool) {
589+ return poolRef.compareAndSet(null, pool);
590+ }
591+
592+ /**
593+ * If the connection is part of a pool, return it to the pool.
594+ * The connection should generally not be reused after that.
595+ */
596+ void release() {
597+ HostConnectionPool pool = poolRef.get();
598+ if (pool != null)
599+ pool.returnConnection(this);
600+ }
601+
465602 public boolean isClosed() {
466603 return closeFuture.get() != null;
467604 }
@@ -585,20 +722,53 @@
585722 throw new ConnectionException(address, "Connection factory is shut down");
586723
587724 String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement();
588- return new Connection(name, address, this);
725+ Connection connection = new Connection(name, address, this);
726+ // This method opens the connection synchronously, so wait until it's initialized
727+ try {
728+ connection.initAsync().get();
729+ return connection;
730+ } catch (ExecutionException e) {
731+ throw launderAsyncInitException(e);
732+ }
589733 }
590734
591735 /**
592736 * Same as open, but associate the created connection to the provided connection pool.
593737 */
594- public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
738+ public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
739+ try {
740+ Connection connection = newConnection(pool);
741+ connection.initAsync().get();
742+ return connection;
743+ } catch (ExecutionException e) {
744+ throw launderAsyncInitException(e);
745+ }
746+ }
747+
748+ /**
749+ * Creates a new connection and associates it to the provided connection pool, but does not start it.
750+ */
751+ public Connection newConnection(HostConnectionPool pool) {
595752 InetSocketAddress address = pool.host.getSocketAddress();
753+ String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
596754
597- if (isShutdown)
598- throw new ConnectionException(address, "Connection factory is shut down");
755+ return new Connection(name, address, this, pool);
756+ }
599757
600- String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
601- return new PooledConnection(name, address, this, pool);
758+ static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
759+ Throwable t = e.getCause();
760+ if (t instanceof ConnectionException)
761+ throw (ConnectionException)t;
762+ if (t instanceof InterruptedException)
763+ throw (InterruptedException)t;
764+ if (t instanceof UnsupportedProtocolVersionException)
765+ throw (UnsupportedProtocolVersionException)t;
766+ if (t instanceof ClusterNameMismatchException)
767+ throw (ClusterNameMismatchException)t;
768+ if (t instanceof DriverException)
769+ throw (DriverException)t;
770+
771+ return new RuntimeException("Unexpected exception during connection initialization", t);
602772 }
603773
604774 private AtomicInteger getIdGenerator(Host host) {
@@ -665,7 +835,7 @@
665835 }
666836
667837 private static final class Flusher implements Runnable {
668- final EventLoop eventLoop;
838+ final WeakReference<EventLoop> eventLoopRef;
669839 final Queue<FlushItem> queued = new ConcurrentLinkedQueue<FlushItem>();
670840 final AtomicBoolean running = new AtomicBoolean(false);
671841 final HashSet<Channel> channels = new HashSet<Channel>();
@@ -674,12 +844,14 @@
674844 int runsWithNoWork = 0;
675845
676846 private Flusher(EventLoop eventLoop) {
677- this.eventLoop = eventLoop;
847+ this.eventLoopRef = new WeakReference<EventLoop>(eventLoop);
678848 }
679849
680850 void start() {
681851 if (!running.get() && running.compareAndSet(false, true)) {
682- this.eventLoop.execute(this);
852+ EventLoop eventLoop = eventLoopRef.get();
853+ if (eventLoop != null)
854+ eventLoop.execute(this);
683855 }
684856 }
685857
@@ -717,11 +889,17 @@
717889 }
718890 }
719891
720- eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
892+ EventLoop eventLoop = eventLoopRef.get();
893+ if(eventLoop != null) {
894+ eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
895+ }
721896 }
722897 }
723898
724- private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new ConcurrentHashMap<EventLoop, Flusher>();
899+ private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
900+ .concurrencyLevel(16)
901+ .weakKeys()
902+ .makeMap();
725903
726904 private static class FlushItem {
727905 final Channel channel;
@@ -925,7 +1103,7 @@
9251103 public ConnectionCloseFuture force() {
9261104 // Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared
9271105
928- // This method can be thrown during Connection ctor, at which point channel is not yet set. This is ok.
1106+ // This method can be thrown during initialization, at which point channel is not yet set. This is ok.
9291107 if (channel == null) {
9301108 set(null);
9311109 return this;
@@ -1056,8 +1234,7 @@
10561234 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
10571235 // of its own answer, and we would have no way to detect that.
10581236 connection.dispatcher.removeHandler(this, false);
1059- if (connection instanceof PooledConnection)
1060- ((PooledConnection)connection).release();
1237+ connection.release();
10611238 }
10621239
10631240 private TimerTask onTimeoutTask() {
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +3 −1
@@ -249,7 +249,9 @@
249249 if (!super.cancel(mayInterruptIfRunning))
250250 return false;
251251
252- handler.cancel();
252+ if(handler != null) {
253+ handler.cancel();
254+ }
253255 return true;
254256 }
255257
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +3 −1
@@ -27,6 +27,8 @@
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
30+import com.datastax.driver.core.utils.MoreFutures;
31+
3032 /**
3133 * A Cassandra node.
3234 *
@@ -48,7 +50,7 @@
4850 private final Cluster.Manager manager;
4951
5052 // Tracks the first "immediate" reconnection attempt when a node get suspected.
51- final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null));
53+ final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(MoreFutures.VOID_SUCCESS);
5254
5355 // Tracks later reconnection attempts to that host so we avoid adding multiple tasks.
5456 final AtomicReference<ListenableFuture<?>> reconnectionAttempt = new AtomicReference<ListenableFuture<?>>();
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +101 −64
@@ -15,14 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-
1918 import java.util.ArrayList;
2019 import java.util.List;
2120 import java.util.Set;
22-import java.util.concurrent.CopyOnWriteArrayList;
23-import java.util.concurrent.CopyOnWriteArraySet;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
21+import java.util.concurrent.*;
2622 import java.util.concurrent.atomic.AtomicInteger;
2723 import java.util.concurrent.atomic.AtomicReference;
2824 import java.util.concurrent.locks.Condition;
@@ -30,13 +26,17 @@
3026 import java.util.concurrent.locks.ReentrantLock;
3127
3228 import com.google.common.collect.Lists;
33-import com.google.common.util.concurrent.MoreExecutors;
29+import com.google.common.util.concurrent.*;
3430 import org.slf4j.Logger;
3531 import org.slf4j.LoggerFactory;
3632
3733 import com.datastax.driver.core.exceptions.AuthenticationException;
34+import com.datastax.driver.core.utils.MoreFutures;
3835
39-import static com.datastax.driver.core.PooledConnection.State.*;
36+import static com.datastax.driver.core.Connection.State.GONE;
37+import static com.datastax.driver.core.Connection.State.OPEN;
38+import static com.datastax.driver.core.Connection.State.RESURRECTING;
39+import static com.datastax.driver.core.Connection.State.TRASHED;
4040
4141 class HostConnectionPool {
4242
@@ -53,13 +53,13 @@
5353 public volatile HostDistance hostDistance;
5454 private final SessionManager manager;
5555
56- final List<PooledConnection> connections;
56+ final List<Connection> connections;
5757 private final AtomicInteger open;
5858 /** The total number of in-flight requests on all connections of this pool. */
5959 final AtomicInteger totalInFlight = new AtomicInteger();
6060 /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
6161 private final AtomicInteger maxTotalInFlight = new AtomicInteger();
62- final Set<PooledConnection> trash = new CopyOnWriteArraySet<PooledConnection>();
62+ final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
6363
6464 private volatile int waiter = 0;
6565 private final Lock waitLock = new ReentrantLock(true);
@@ -69,10 +69,12 @@
6969
7070 private final AtomicInteger scheduledForCreation = new AtomicInteger();
7171
72- private volatile boolean isClosing;
7372 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
7473
75- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
74+ private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
75+ private volatile Phase phase = Phase.INITIALIZING;
76+
77+ public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager){
7678 assert hostDistance != HostDistance.IGNORED;
7779 this.host = host;
7880 this.hostDistance = hostDistance;
@@ -86,37 +88,70 @@
8688 }
8789 };
8890
91+ this.connections = new CopyOnWriteArrayList<Connection>();
92+ this.open = new AtomicInteger();
93+ }
94+
95+ /**
96+ * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
97+ * reuse as part of this pool. Might be null or already used by another
98+ * pool.
99+ */
100+ public ListenableFuture<Void> initAsync(Connection reusedConnection) {
89101 // Create initial core connections
90- List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance));
91- try {
92- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
93- l.add(manager.connectionFactory().open(this));
94- } catch (InterruptedException e) {
95- Thread.currentThread().interrupt();
96- // If asked to interrupt, we can skip opening core connections, the pool will still work.
97- // But we ignore otherwise cause I'm not sure we can do much better currently.
98- } catch (ConnectionException e) {
99- forceClose(l);
100- throw e;
101- } catch (UnsupportedProtocolVersionException e) {
102- forceClose(l);
103- throw e;
104- } catch (ClusterNameMismatchException e) {
105- forceClose(l);
106- throw e;
107- } catch (RuntimeException e) {
108- forceClose(l);
109- throw e;
102+ int capacity = options().getCoreConnectionsPerHost(hostDistance);
103+ final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
104+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
105+ for (int i = 0; i < capacity; i++) {
106+ Connection connection;
107+ ListenableFuture<Void> connectionFuture;
108+ // reuse the existing connection only once
109+ if (reusedConnection != null && reusedConnection.setPool(this)) {
110+ connection = reusedConnection;
111+ connectionFuture = MoreFutures.VOID_SUCCESS;
112+ } else {
113+ connection = manager.connectionFactory().newConnection(this);
114+ connectionFuture = connection.initAsync();
115+ }
116+ reusedConnection = null;
117+ connections.add(connection);
118+ connectionFutures.add(connectionFuture);
110119 }
111- this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
112- this.open = new AtomicInteger(connections.size());
113120
114- logger.trace("Created connection pool to host {}", host);
121+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
122+
123+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
124+
125+ final SettableFuture<Void> initFuture = SettableFuture.create();
126+ Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
127+ @Override
128+ public void onSuccess(List<Void> l) {
129+ HostConnectionPool.this.connections.addAll(connections);
130+ open.set(l.size());
131+ if (isClosed()) {
132+ initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
133+ // we're not sure if closeAsync() saw the connections, so ensure they get closed
134+ forceClose(connections);
135+ } else {
136+ logger.trace("Created connection pool to host {}", host);
137+ phase = Phase.READY;
138+ initFuture.set(null);
139+ }
140+ }
141+
142+ @Override
143+ public void onFailure(Throwable t) {
144+ phase = Phase.INIT_FAILED;
145+ forceClose(connections);
146+ initFuture.setException(t);
147+ }
148+ }, initExecutor);
149+ return initFuture;
115150 }
116151
117152 // Clean up if we got an error at construction time but still created part of the core connections
118- private void forceClose(List<PooledConnection> l) {
119- for (PooledConnection connection : l) {
153+ private void forceClose(List<Connection> connections) {
154+ for (Connection connection : connections) {
120155 connection.closeAsync().force();
121156 }
122157 }
@@ -125,11 +160,14 @@
125160 return manager.configuration().getPoolingOptions();
126161 }
127162
128- public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
129- if (isClosed())
163+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
164+ if (phase == Phase.INITIALIZING)
165+ throw new ConnectionException(host.getSocketAddress(), "Pool is initializing.");
166+
167+ if (phase != Phase.READY)
130168 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
131169 // That being said, maybe having a specific exception could be cleaner.
132- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
170+ throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
133171
134172 if (connections.isEmpty()) {
135173 for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
@@ -138,15 +176,15 @@
138176 scheduledForCreation.incrementAndGet();
139177 manager.blockingExecutor().submit(newConnectionTask);
140178 }
141- PooledConnection c = waitForConnection(timeout, unit);
179+ Connection c = waitForConnection(timeout, unit);
142180 totalInFlight.incrementAndGet();
143181 c.setKeyspace(manager.poolsState.keyspace);
144182 return c;
145183 }
146184
147185 int minInFlight = Integer.MAX_VALUE;
148- PooledConnection leastBusy = null;
149- for (PooledConnection connection : connections) {
186+ Connection leastBusy = null;
187+ for (Connection connection : connections) {
150188 int inFlight = connection.inFlight.get();
151189 if (inFlight < minInFlight) {
152190 minInFlight = inFlight;
@@ -234,7 +272,7 @@
234272 }
235273 }
236274
237- private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
275+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
238276 if (timeout == 0)
239277 throw new TimeoutException();
240278
@@ -253,8 +291,8 @@
253291 throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
254292
255293 int minInFlight = Integer.MAX_VALUE;
256- PooledConnection leastBusy = null;
257- for (PooledConnection connection : connections) {
294+ Connection leastBusy = null;
295+ for (Connection connection : connections) {
258296 int inFlight = connection.inFlight.get();
259297 if (inFlight < minInFlight) {
260298 minInFlight = inFlight;
@@ -282,7 +320,7 @@
282320 throw new TimeoutException();
283321 }
284322
285- public void returnConnection(PooledConnection connection) {
323+ public void returnConnection(Connection connection) {
286324 connection.inFlight.decrementAndGet();
287325 totalInFlight.decrementAndGet();
288326
@@ -308,7 +346,7 @@
308346
309347 // Trash the connection and create a new one, but we don't call trashConnection
310348 // directly because we want to make sure the connection is always trashed.
311- private void replaceConnection(PooledConnection connection) {
349+ private void replaceConnection(Connection connection) {
312350 if (!connection.state.compareAndSet(OPEN, TRASHED))
313351 return;
314352 open.decrementAndGet();
@@ -317,7 +355,7 @@
317355 doTrashConnection(connection);
318356 }
319357
320- private boolean trashConnection(PooledConnection connection) {
358+ private boolean trashConnection(Connection connection) {
321359 if (!connection.state.compareAndSet(OPEN, TRASHED))
322360 return true;
323361
@@ -338,7 +376,7 @@
338376 return true;
339377 }
340378
341- private void doTrashConnection(PooledConnection connection) {
379+ private void doTrashConnection(Connection connection) {
342380 connections.remove(connection);
343381 trash.add(connection);
344382 }
@@ -355,14 +393,14 @@
355393 break;
356394 }
357395
358- if (isClosing) {
396+ if (phase != Phase.READY) {
359397 open.decrementAndGet();
360398 return false;
361399 }
362400
363401 // Now really open the connection
364402 try {
365- PooledConnection newConnection = tryResurrectFromTrash();
403+ Connection newConnection = tryResurrectFromTrash();
366404 if (newConnection == null) {
367405 logger.debug("Creating new connection on busy pool to {}", host);
368406 newConnection = manager.connectionFactory().open(this);
@@ -372,7 +410,7 @@
372410 newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
373411
374412 // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
375- if (isClosing && !newConnection.isClosed()) {
413+ if (phase != Phase.READY && !newConnection.isClosed()) {
376414 close(newConnection);
377415 open.decrementAndGet();
378416 return false;
@@ -406,12 +444,12 @@
406444 }
407445 }
408446
409- private PooledConnection tryResurrectFromTrash() {
447+ private Connection tryResurrectFromTrash() {
410448 long highestMaxIdleTime = System.currentTimeMillis();
411- PooledConnection chosen = null;
449+ Connection chosen = null;
412450
413451 while (true) {
414- for (PooledConnection connection : trash)
452+ for (Connection connection : trash)
415453 if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) {
416454 chosen = connection;
417455 highestMaxIdleTime = connection.maxIdleTime;
@@ -439,7 +477,7 @@
439477 manager.blockingExecutor().submit(newConnectionTask);
440478 }
441479
442- void replaceDefunctConnection(final PooledConnection connection) {
480+ void replaceDefunctConnection(final Connection connection) {
443481 if (connection.state.compareAndSet(OPEN, GONE))
444482 open.decrementAndGet();
445483 if (connections.remove(connection))
@@ -477,7 +515,7 @@
477515 if (toTrash <= 0)
478516 return;
479517
480- for (PooledConnection connection : connections)
518+ for (Connection connection : connections)
481519 if (trashConnection(connection)) {
482520 toTrash -= 1;
483521 if (toTrash == 0)
@@ -487,7 +525,7 @@
487525
488526 /** Close connections that have been sitting in the trash for too long */
489527 private void cleanupTrash(long now) {
490- for (PooledConnection connection : trash) {
528+ for (Connection connection : trash) {
491529 if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
492530 if (connection.inFlight.get() == 0) {
493531 logger.trace("Cleaning up {}", connection);
@@ -517,7 +555,7 @@
517555 if (future != null)
518556 return future;
519557
520- isClosing = true;
558+ phase = Phase.CLOSING;
521559
522560 // Wake up all threads that wait
523561 signalAllAvailableConnection();
@@ -538,13 +576,12 @@
538576 }
539577
540578 private List<CloseFuture> discardAvailableConnections() {
541- // This can happen if creating the connections in the constructor fails
542- if (connections == null)
543- return Lists.newArrayList(CloseFuture.immediateFuture());
579+ // Note: if this gets called before initialization has completed, both connections and trash will be empty,
580+ // so this will return an empty list
544581
545582 List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
546583
547- for (final PooledConnection connection : connections) {
584+ for (final Connection connection : connections) {
548585 CloseFuture future = connection.closeAsync();
549586 future.addListener(new Runnable() {
550587 public void run() {
@@ -556,7 +593,7 @@
556593 }
557594
558595 // Some connections in the trash might still be open if they hadn't reached their idle timeout
559- for (PooledConnection connection : trash)
596+ for (Connection connection : trash)
560597 futures.add(connection.closeAsync());
561598
562599 return futures;
deleted driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +0 −66
@@ -1,66 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.net.InetSocketAddress;
19-import java.util.concurrent.atomic.AtomicReference;
20-
21-/**
22- * A connection that is associated to a pool.
23- */
24-class PooledConnection extends Connection {
25-
26- final HostConnectionPool pool;
27-
28- enum State {OPEN, TRASHED, RESURRECTING, GONE }
29-
30- final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
31-
32- volatile long maxIdleTime;
33-
34- PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
35- super(name, address, factory);
36- this.pool = pool;
37- }
38-
39- /**
40- * Return the pooled connection to its pool.
41- * The connection should generally not be reused after that.
42- */
43- public void release() {
44- // This can happen if the query to initialize the transport in the
45- // parent constructor times out. In that case the pool will handle
46- // it itself.
47- if (pool == null)
48- return;
49-
50- pool.returnConnection(this);
51- }
52-
53- @Override
54- protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
55- // This can happen if an exception is thrown at construction time. In
56- // that case the pool will handle it itself.
57- if (pool == null)
58- return;
59-
60- if (hostIsDown) {
61- pool.closeAsync().force();
62- } else {
63- pool.replaceDefunctConnection(this);
64- }
65- }
66-}
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +45 −0
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.concurrent.Executor;
19+
20+import com.google.common.base.Preconditions;
21+import com.google.common.util.concurrent.MoreExecutors;
22+
1823 /**
1924 * Options related to connection pooling.
2025 * <p>
@@ -53,6 +58,8 @@
5358 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
5459 private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
5560
61+ private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor();
62+
5663 private volatile Cluster.Manager manager;
5764
5865 private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 };
@@ -64,6 +71,8 @@
6471 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
6572 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
6673
74+ private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
75+
6776 public PoolingOptions() {}
6877
6978 void register(Cluster.Manager manager) {
@@ -308,6 +317,42 @@
308317 return this;
309318 }
310319
320+ /**
321+ * Returns the executor to use for connection initialization.
322+ *
323+ * @return the executor.
324+ * @see #setInitializationExecutor(java.util.concurrent.Executor)
325+ */
326+ public Executor getInitializationExecutor() {
327+ return initializationExecutor;
328+ }
329+
330+ /**
331+ * Sets the executor to use for connection initialization.
332+ * <p>
333+ * Connections are open in a completely asynchronous manner. Since initializing the transport
334+ * requires separate CQL queries, the futures representing the completion of these queries are
335+ * transformed and chained. This executor is where these transformations happen.
336+ * <p>
337+ * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to
338+ * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations
339+ * on the network I/O threads; this is fine if the transformations are fast and not I/O bound
340+ * (which is the case by default).
341+ * One reason why you might want to provide a custom executor is if you use authentication with
342+ * a custom {@link com.datastax.driver.core.Authenticator} implementation that performs blocking
343+ * calls.
344+ *
345+ * @param initializationExecutor the executor to use
346+ * @return this {@code PoolingOptions}
347+ *
348+ * @throws java.lang.NullPointerException if the executor is null
349+ */
350+ public PoolingOptions setInitializationExecutor(Executor initializationExecutor) {
351+ Preconditions.checkNotNull(initializationExecutor);
352+ this.initializationExecutor = initializationExecutor;
353+ return this;
354+ }
355+
311356 /**
312357 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
313358 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −9
@@ -111,7 +111,7 @@
111111 if (currentPool == null || currentPool.isClosed())
112112 return false;
113113
114- PooledConnection connection = null;
114+ Connection connection = null;
115115 try {
116116 connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
117117 if (current != null) {
@@ -157,8 +157,7 @@
157157 while (true) {
158158 QueryState previous = queryStateRef.get();
159159 if (previous.isCancelled()) {
160- if (connection instanceof PooledConnection)
161- ((PooledConnection)connection).release();
160+ connection.release();
162161 return;
163162 }
164163 if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext()))
@@ -472,8 +471,7 @@
472471 exceptionToReport = e;
473472 setFinalException(connection, e);
474473 } finally {
475- if (releaseConnection && connection instanceof PooledConnection)
476- ((PooledConnection)connection).release();
474+ connection.release();
477475 if (queriedHost != null && statement != Statement.DEFAULT)
478476 manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency);
479477 }
@@ -502,8 +500,7 @@
502500 return;
503501 }
504502
505- if (connection instanceof PooledConnection)
506- ((PooledConnection)connection).release();
503+ connection.release();
507504
508505 // TODO should we check the response ?
509506 switch (response.type) {
@@ -562,8 +559,7 @@
562559
563560 Host queriedHost = current;
564561 try {
565- if (connection instanceof PooledConnection)
566- ((PooledConnection)connection).release();
562+ connection.release();
567563
568564 if (exception instanceof ConnectionException) {
569565 if (metricsEnabled())
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +124 −116
@@ -20,10 +20,10 @@
2020 import java.util.*;
2121 import java.util.concurrent.*;
2222 import java.util.concurrent.atomic.AtomicReference;
23-import java.util.concurrent.locks.Lock;
2423
2524 import com.google.common.base.Function;
2625 import com.google.common.collect.ImmutableList;
26+import com.google.common.collect.Lists;
2727 import com.google.common.util.concurrent.*;
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
@@ -33,6 +33,7 @@
3333 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3434 import com.datastax.driver.core.policies.LoadBalancingPolicy;
3535 import com.datastax.driver.core.policies.ReconnectionPolicy;
36+import com.datastax.driver.core.utils.MoreFutures;
3637
3738 /**
3839 * Driver implementation of the Session interface.
@@ -46,8 +47,6 @@
4647 final HostConnectionPool.PoolState poolsState;
4748 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
4849
49- private final Striped<Lock> poolCreationLocks = Striped.lazyWeakLock(5);
50-
5150 private volatile boolean isInit;
5251 private volatile boolean isClosing;
5352
@@ -67,50 +66,28 @@
6766
6867 // Create pools to initial nodes (and wait for them to be created)
6968 Collection<Host> hosts = cluster.getMetadata().allHosts();
70- if (cluster.manager.sessions.size() == 1) {
71- // We only do it in parallel if this is the first session (meaning that the cluster just initialized).
72- createPoolsInParallel(hosts);
73- } else {
74- // Otherwise, we don't want to fill executor() because this is also where up/down notifications are processed,
75- // it's important that existing sessions get them in a timely manner. So we create the pools one by one:
76- createPoolsSequentially(hosts);
77- }
69+ createPoolsInParallel(hosts);
7870
7971 isInit = true;
80- updateCreatedPools(executor());
72+ updateCreatedPools();
8173 return this;
8274 }
8375
8476 private void createPoolsInParallel(Collection<Host> hosts) {
85- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size());
77+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
8678 for (Host host : hosts)
8779 if (host.state != Host.State.DOWN)
88- futures.add(maybeAddPool(host, executor()));
89- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
80+ futures.add(maybeAddPool(host, null));
9081 try {
91- f.get();
82+ Futures.successfulAsList(futures).get();
9283 } catch (ExecutionException e) {
93- // This is not supposed to happen
94- throw new DriverInternalError(e);
84+ // Won't happen because we used successfulAsList
85+ // And if a particular pool failed, maybeAddPool already handled it
9586 } catch (InterruptedException e) {
9687 Thread.currentThread().interrupt();
9788 }
9889 }
9990
100- private void createPoolsSequentially(Collection<Host> hosts) {
101- for (Host host : cluster.getMetadata().allHosts()) {
102- try {
103- if (host.state != Host.State.DOWN)
104- maybeAddPool(host, executor()).get();
105- } catch (ExecutionException e) {
106- // This is not supposed to happen
107- throw new DriverInternalError(e);
108- } catch (InterruptedException e) {
109- Thread.currentThread().interrupt();
110- }
111- }
112- }
113-
11491 public String getLoggedKeyspace() {
11592 return poolsState.keyspace;
11693 }
@@ -215,77 +192,94 @@
215192 }
216193
217194 // Returns whether there was problem creating the pool
218- ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) {
195+ ListenableFuture<Boolean> forceRenewPool(final Host host, Connection reusedConnection) {
219196 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
220197 if (distance == HostDistance.IGNORED)
221198 return Futures.immediateFuture(true);
222199
223- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
224- return executor.submit(new Callable<Boolean>() {
225- public Boolean call() {
226- while (true) {
227- try {
228- if (isClosing)
229- return true;
230-
231- HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
232- HostConnectionPool previous = pools.put(host, newPool);
233- if (previous == null) {
234- logger.debug("Added connection pool for {}", host);
235- } else {
236- logger.debug("Renewed connection pool for {}", host);
237- previous.closeAsync();
238- }
200+ if (isClosing)
201+ return Futures.immediateFuture(false);
202+
203+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
204+ ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
205+
206+ final SettableFuture<Boolean> future = SettableFuture.create();
207+
208+ Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
209+ @Override
210+ public void onSuccess(Void result) {
211+ // If we raced with a session shutdown, ensure that the pool will be closed.
212+ HostConnectionPool previous = pools.put(host, newPool);
213+ if (previous == null) {
214+ logger.debug("Added connection pool for {}", host);
215+ } else {
216+ logger.debug("Renewed connection pool for {}", host);
217+ previous.closeAsync();
218+ }
239219
240- // If we raced with a session shutdown, ensure that the pool will be closed.
241- if (isClosing)
242- newPool.closeAsync();
243-
244- return true;
245- } catch (Exception e) {
246- logger.error("Error creating pool to " + host, e);
247- return false;
248- }
220+ // If we raced with a session shutdown, ensure that the pool will be closed.
221+ if (isClosing) {
222+ newPool.closeAsync();
223+ pools.remove(host);
224+ future.set(false);
225+ } else {
226+ future.set(true);
249227 }
250228 }
229+
230+ @Override
231+ public void onFailure(Throwable t) {
232+ logger.error("Error creating pool to " + host, t);
233+ future.set(false);
234+ }
251235 });
236+
237+ return future;
252238 }
253239
254- // Replace pool for a given only if it's the given previous value (which can be null)
255- // Note that the goal of this function is to make sure that 2 concurrent thread calling
256- // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools
257- // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we
258- // want to avoid
259- private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
240+ // Replace pool for a given host only if it's the given previous value (which can be null)
241+ // This returns a future if the replacement was successful, or null if we raced.
242+ private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous, Connection reusedConnection) {
260243 if (isClosing)
261- return true;
262-
263- Lock l = poolCreationLocks.get(host);
264- l.lock();
265- try {
266- HostConnectionPool previous = pools.get(host);
267- if (previous != condition)
268- return false;
269-
270- HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
271- previous = pools.put(host, newPool);
272- if (previous != null && !previous.isClosed()) {
244+ return MoreFutures.VOID_SUCCESS;
245+
246+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
247+ if (previous == null) {
248+ if (pools.putIfAbsent(host, newPool) != null) {
249+ return null;
250+ }
251+ } else {
252+ if (!pools.replace(host, previous, newPool)) {
253+ return null;
254+ }
255+ if (!previous.isClosed()) {
273256 logger.warn("Replacing a pool that wasn't closed. Closing it now, but this was not expected.");
274257 previous.closeAsync();
275258 }
259+ }
276260
277- // If we raced with a session shutdown, ensure that the pool will be closed.
278- if (isClosing)
279- newPool.closeAsync();
261+ ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
262+
263+ Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
264+ @Override
265+ public void onSuccess(Void result) {
266+ // If we raced with a session shutdown, ensure that the pool will be closed.
267+ if (isClosing) {
268+ newPool.closeAsync();
269+ pools.remove(host);
270+ }
271+ }
280272
281- return true;
282- } finally {
283- l.unlock();
284- }
273+ @Override
274+ public void onFailure(Throwable t) {
275+ pools.remove(host);
276+ }
277+ });
278+ return poolInitFuture;
285279 }
286280
287281 // Returns whether there was problem creating the pool
288- ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) {
282+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
289283 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
290284 if (distance == HostDistance.IGNORED)
291285 return Futures.immediateFuture(true);
@@ -294,34 +288,39 @@
294288 if (previous != null && !previous.isClosed())
295289 return Futures.immediateFuture(true);
296290
297- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
298- return executor.submit(new Callable<Boolean>() {
299- public Boolean call() {
300- try {
301- while (true) {
302- HostConnectionPool previous = pools.get(host);
303- if (previous != null && !previous.isClosed())
304- return true;
305-
306- if (replacePool(host, distance, previous)) {
307- logger.debug("Added connection pool for {}", host);
308- return true;
291+ while (true) {
292+ previous = pools.get(host);
293+ if (previous != null && !previous.isClosed())
294+ return Futures.immediateFuture(true);
295+
296+ final SettableFuture<Boolean> future = SettableFuture.create();
297+ ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous, reusedConnection);
298+ if (newPoolInit != null) {
299+ Futures.addCallback(newPoolInit, new FutureCallback<Void>() {
300+ @Override
301+ public void onSuccess(Void result) {
302+ logger.debug("Added connection pool for {}", host);
303+ future.set(true);
304+ }
305+
306+ @Override
307+ public void onFailure(Throwable t) {
308+ if (t instanceof UnsupportedProtocolVersionException) {
309+ cluster.manager.logUnsupportedVersionProtocol(host);
310+ cluster.manager.triggerOnDown(host, false);
311+ } else if (t instanceof ClusterNameMismatchException) {
312+ ClusterNameMismatchException e = (ClusterNameMismatchException)t;
313+ cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
314+ cluster.manager.triggerOnDown(host, false);
315+ } else {
316+ logger.error("Error creating pool to " + host, t);
309317 }
318+ future.set(false);
310319 }
311- } catch (UnsupportedProtocolVersionException e) {
312- cluster.manager.logUnsupportedVersionProtocol(host);
313- cluster.manager.triggerOnDown(host, false);
314- return false;
315- } catch (ClusterNameMismatchException e) {
316- cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
317- cluster.manager.triggerOnDown(host, false);
318- return false;
319- } catch (Exception e) {
320- logger.error("Error creating pool to " + host, e);
321- return false;
322- }
320+ });
321+ return future;
323322 }
324- });
323+ }
325324 }
326325
327326 CloseFuture removePool(Host host) {
@@ -340,7 +339,7 @@
340339 * This method ensures that all hosts for which a pool should exist
341340 * have one, and hosts that shouldn't don't.
342341 */
343- void updateCreatedPools(ListeningExecutorService executor) {
342+ void updateCreatedPools() {
344343 // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if
345344 // we execute the code below we would try to create their pool over and over again.
346345 // It's called explicitly at the end of init(), once isInit has been set to true.
@@ -359,7 +358,7 @@
359358
360359 if (pool == null) {
361360 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
362- poolCreationFutures.add(maybeAddPool(h, executor));
361+ poolCreationFutures.add(maybeAddPool(h, null));
363362 } else if (dist != pool.hostDistance) {
364363 if (dist == HostDistance.IGNORED) {
365364 toRemove.add(h);
@@ -371,7 +370,12 @@
371370 }
372371
373372 // Wait pool creation before removing, so we don't lose connectivity
374- Futures.allAsList(poolCreationFutures).get();
373+ try {
374+ Futures.successfulAsList(poolCreationFutures).get();
375+ } catch (ExecutionException e) {
376+ // Won't happen because we used successfulAsList
377+ // And if a particular pool failed, maybeAddPool already handled it
378+ }
375379
376380 List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size());
377381 for (Host h : toRemove)
@@ -385,14 +389,18 @@
385389 }
386390 }
387391
388- void updateCreatedPools(Host h, ListeningExecutorService executor) {
392+ void updateCreatedPools(Host h) {
389393 HostDistance dist = loadBalancingPolicy().distance(h);
390394 HostConnectionPool pool = pools.get(h);
391395
392396 try {
393397 if (pool == null) {
394398 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
395- maybeAddPool(h, executor).get();
399+ try {
400+ maybeAddPool(h, null).get();
401+ } catch (ExecutionException e) {
402+ // Ignore, maybeAddPool has already handled the error
403+ }
396404 } else if (dist != pool.hostDistance) {
397405 if (dist == HostDistance.IGNORED) {
398406 removePool(h).get();
@@ -412,7 +420,7 @@
412420 // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
413421 // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
414422 removePool(host).force().get();
415- updateCreatedPools(MoreExecutors.sameThreadExecutor());
423+ updateCreatedPools();
416424 }
417425
418426 void onSuspected(Host host) {
@@ -532,7 +540,7 @@
532540
533541 // Let's not wait too long if we can't get a connection. Things
534542 // will fix themselves once the user tries a query anyway.
535- PooledConnection c = null;
543+ Connection c = null;
536544 boolean timedOut = false;
537545 try {
538546 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
added driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java +46 −0
@@ -0,0 +1,46 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.utils;
17+
18+import com.google.common.util.concurrent.FutureCallback;
19+import com.google.common.util.concurrent.Futures;
20+import com.google.common.util.concurrent.ListenableFuture;
21+
22+/**
23+ * Helpers to work with Guava's {@link ListenableFuture}.
24+ */
25+public class MoreFutures {
26+ /**
27+ * An immediate successful {@code ListenableFuture<Void>}.
28+ */
29+ public static final ListenableFuture<Void> VOID_SUCCESS = Futures.immediateFuture(null);
30+
31+ /**
32+ * A {@link FutureCallback} that does nothing on failure.
33+ */
34+ public static abstract class SuccessCallback<V> implements FutureCallback<V> {
35+ @Override
36+ public void onFailure(Throwable t) { /* nothing */ }
37+ }
38+
39+ /**
40+ * A {@link FutureCallback} that does nothing on success.
41+ */
42+ public static abstract class FailureCallback<V> implements FutureCallback<V> {
43+ @Override
44+ public void onSuccess(V result) { /* nothing */ }
45+ }
46+}
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +1 −1
@@ -489,7 +489,7 @@
489489
490490 ports = new int[5];
491491 for (int i = 0; i < 5; i++) {
492- ports[i] = TestUtils.findAvailablePort(10000 + i);
492+ ports[i] = TestUtils.findAvailablePort(11000 + i);
493493 }
494494
495495 ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4]);
added driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +228 −0
@@ -0,0 +1,228 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetSocketAddress;
25+import java.util.ArrayList;
26+import java.util.Collection;
27+import java.util.Collections;
28+import java.util.List;
29+import java.util.concurrent.*;
30+
31+import static org.testng.Assert.assertEquals;
32+
33+public class ClusterStressTest extends CCMBridge.PerClassSingleNodeCluster {
34+ private static final Logger logger = LoggerFactory.getLogger(ClusterStressTest.class);
35+
36+ private ExecutorService executorService;
37+
38+ public ClusterStressTest() {
39+ // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
40+ executorService = Executors.newFixedThreadPool(8);
41+ }
42+
43+ @Override
44+ protected Collection<String> getTableDefinitions() {
45+ return new ArrayList<String>(0);
46+ }
47+
48+ @Test(groups = "long")
49+ public void clusters_should_not_leak_connections() {
50+ int numberOfClusters = 10;
51+ int numberOfIterations = 500;
52+ for (int i = 1; i < numberOfIterations; i++) {
53+ logger.info("On iteration {}/{}.", i, numberOfIterations);
54+ logger.info("Creating {} clusters", numberOfClusters);
55+ List<CreateClusterAndCheckConnections> actions =
56+ waitForCreates(createClustersConcurrently(numberOfClusters));
57+ waitForCloses(closeClustersConcurrently(actions));
58+ logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size());
59+ }
60+ }
61+
62+ private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters) {
63+ final CountDownLatch countDownLatch = new CountDownLatch(1);
64+ return createClustersConcurrently(numberOfClusters, countDownLatch);
65+ }
66+
67+ private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters,
68+ CountDownLatch countDownLatch) {
69+ List<Future<CreateClusterAndCheckConnections>> clusterFutures =
70+ Lists.newArrayListWithCapacity(numberOfClusters);
71+ for (int i = 0; i < numberOfClusters; i++) {
72+ clusterFutures.add(executorService.submit(new CreateClusterAndCheckConnections(countDownLatch)));
73+ }
74+ countDownLatch.countDown();
75+ return clusterFutures;
76+ }
77+
78+ private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions) {
79+ final CountDownLatch countDownLatch = new CountDownLatch(1);
80+ return closeClustersConcurrently(actions, countDownLatch);
81+ }
82+
83+ private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions,
84+ CountDownLatch startSignal) {
85+ List<Future<Void>> closeFutures = Lists.newArrayListWithCapacity(actions.size());
86+ for (CreateClusterAndCheckConnections action : actions) {
87+ closeFutures.add(executorService.submit(new CloseCluster(action.cluster, action.channelMonitor,
88+ startSignal)));
89+ }
90+ startSignal.countDown();
91+ return closeFutures;
92+ }
93+
94+ private List<CreateClusterAndCheckConnections> waitForCreates(
95+ List<Future<CreateClusterAndCheckConnections>> futures) {
96+ List<CreateClusterAndCheckConnections> actions = Lists.newArrayListWithCapacity(futures.size());
97+ // If an error occurs, we will abort the test, but we still want to close all the clusters
98+ // that were opened successfully, so we iterate over the whole list no matter what.
99+ AssertionError error = null;
100+ for (Future<CreateClusterAndCheckConnections> future : futures) {
101+ try {
102+ actions.add(future.get());
103+ } catch (InterruptedException e) {
104+ Thread.currentThread().interrupt();
105+ if (error == null)
106+ error = assertionError("Interrupted while waiting for future creation", e);
107+ } catch (ExecutionException e) {
108+ if (error == null) {
109+ Throwable cause = e.getCause();
110+ if (cause instanceof AssertionError)
111+ error = (AssertionError)cause;
112+ else
113+ error = assertionError("Error while creating a cluster", cause);
114+ }
115+ }
116+ }
117+ if (error != null) {
118+ for (CreateClusterAndCheckConnections action : actions)
119+ action.cluster.close();
120+ throw error;
121+ } else
122+ return actions;
123+ }
124+
125+ private List<Void> waitForCloses(List<Future<Void>> futures) {
126+ List<Void> result = new ArrayList<Void>(futures.size());
127+ AssertionError error = null;
128+ for (Future<Void> future : futures) {
129+ try {
130+ result.add(future.get());
131+ } catch (InterruptedException e) {
132+ Thread.currentThread().interrupt();
133+ if (error == null)
134+ error = assertionError("Interrupted while waiting for future", e);
135+ } catch (ExecutionException e) {
136+ if (error == null) {
137+ Throwable cause = e.getCause();
138+ if (cause instanceof AssertionError)
139+ error = (AssertionError)cause;
140+ else
141+ error = assertionError("Error while closing a cluster", cause);
142+ }
143+ }
144+ }
145+ if (error != null)
146+ throw error;
147+ else
148+ return result;
149+ }
150+
151+ private static class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
152+ private final CountDownLatch startSignal;
153+ private final Cluster cluster;
154+ private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
155+ private final List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
156+
157+ CreateClusterAndCheckConnections(CountDownLatch startSignal) {
158+ this.startSignal = startSignal;
159+ this.cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
160+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
161+ .withNettyOptions(channelMonitor.nettyOptions()).build();
162+ }
163+
164+ @Override
165+ public CreateClusterAndCheckConnections call() throws Exception {
166+ startSignal.await();
167+
168+ try {
169+ // There should be 1 control connection after initializing.
170+ cluster.init();
171+ assertEquals(cluster.manager.sessions.size(), 0);
172+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
173+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
174+
175+ // The first session initializes the cluster and its control connection
176+ Session session = cluster.connect();
177+ assertEquals(cluster.manager.sessions.size(), 1);
178+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
179+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
180+
181+ // Closing the session keeps the control connection opened
182+ session.close();
183+ assertEquals(cluster.manager.sessions.size(), 0);
184+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
185+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
186+
187+ return this;
188+ } catch (AssertionError e) {
189+ // If an assertion fails, close the cluster now, because it's the last time we
190+ // have a reference to it.
191+ cluster.close();
192+ throw e;
193+ } finally {
194+ channelMonitor.stop();
195+ }
196+ }
197+ }
198+
199+ private static class CloseCluster implements Callable<Void> {
200+ private final Cluster cluster;
201+ private final SocketChannelMonitor channelMonitor;
202+ private final CountDownLatch startSignal;
203+
204+ CloseCluster(Cluster cluster, SocketChannelMonitor channelMonitor, CountDownLatch startSignal) {
205+ this.cluster = cluster;
206+ this.channelMonitor = channelMonitor;
207+ this.startSignal = startSignal;
208+ }
209+
210+ @Override
211+ public Void call() throws Exception {
212+ startSignal.await();
213+
214+ cluster.close();
215+ assertEquals(cluster.manager.sessions.size(), 0);
216+ assertEquals(channelMonitor.openChannels(Collections.singletonList(hostAddress)).size(), 0);
217+ channelMonitor.stop();
218+
219+ return null;
220+ }
221+ }
222+
223+ private static AssertionError assertionError(String message, Throwable cause) {
224+ AssertionError error = new AssertionError(message);
225+ error.initCause(cause);
226+ return error;
227+ }
228+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +14 −14
@@ -56,10 +56,10 @@
5656 HostConnectionPool pool = createPool(2, 2);
5757
5858 assertThat(pool.connections.size()).isEqualTo(2);
59- List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections);
59+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
6060
6161 for (int i = 0; i < 256; i++) {
62- PooledConnection connection = pool.borrowConnection(100, MILLISECONDS);
62+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
6363 assertThat(coreConnections).contains(connection);
6464 }
6565
@@ -85,17 +85,17 @@
8585 HostConnectionPool pool = createPool(1, 2);
8686
8787 assertThat(pool.connections.size()).isEqualTo(1);
88- List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections);
88+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
8989
9090 //
9191 for (int i = 0; i < 128; i++) {
92- PooledConnection connection = pool.borrowConnection(100, MILLISECONDS);
92+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
9393 assertThat(coreConnections).contains(connection);
9494 }
9595
9696 // Borrow more and ensure the connection returned is a non-core connection.
9797 for (int i = 0; i < 128; i++) {
98- PooledConnection connection = pool.borrowConnection(100, MILLISECONDS);
98+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
9999 assertThat(coreConnections).doesNotContain(connection);
100100 }
101101
@@ -121,7 +121,7 @@
121121 .setIdleTimeoutSeconds(20);
122122
123123 HostConnectionPool pool = createPool(1, 2);
124- PooledConnection core = pool.connections.get(0);
124+ Connection core = pool.connections.get(0);
125125
126126 // Fill core connection
127127 for (int i = 0; i < 128; i++)
@@ -148,14 +148,14 @@
148148 .setIdleTimeoutSeconds(20);
149149
150150 HostConnectionPool pool = createPool(1, 2);
151- PooledConnection connection1 = pool.connections.get(0);
151+ Connection connection1 = pool.connections.get(0);
152152
153153 for (int i = 0; i < 101; i++)
154154 assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
155155
156156 TimeUnit.MILLISECONDS.sleep(100);
157157 assertThat(pool.connections).hasSize(2);
158- PooledConnection connection2 = pool.connections.get(1);
158+ Connection connection2 = pool.connections.get(1);
159159
160160 assertThat(connection1.inFlight.get()).isEqualTo(101);
161161 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -205,14 +205,14 @@
205205 .setIdleTimeoutSeconds(20);
206206
207207 HostConnectionPool pool = createPool(1, 2);
208- PooledConnection connection1 = pool.connections.get(0);
208+ Connection connection1 = pool.connections.get(0);
209209
210210 for (int i = 0; i < 101; i++)
211211 assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
212212
213213 TimeUnit.MILLISECONDS.sleep(100);
214214 assertThat(pool.connections).hasSize(2);
215- PooledConnection connection2 = pool.connections.get(1);
215+ Connection connection2 = pool.connections.get(1);
216216
217217 assertThat(connection1.inFlight.get()).isEqualTo(101);
218218 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -247,7 +247,7 @@
247247 TimeUnit.MILLISECONDS.sleep(100);
248248
249249 // Borrow again to get the new connection
250- PooledConnection connection3 = pool.borrowConnection(100, MILLISECONDS);
250+ Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
251251 assertThat(connection3)
252252 .isNotEqualTo(connection2) // should not be the full connection
253253 .isNotEqualTo(connection1); // should not be the previously trashed one
@@ -267,7 +267,7 @@
267267 .setIdleTimeoutSeconds(20);
268268
269269 HostConnectionPool pool = createPool(1, 2);
270- PooledConnection connection1 = pool.connections.get(0);
270+ Connection connection1 = pool.connections.get(0);
271271
272272 // Fill core connection enough to trigger creation of another one
273273 for (int i = 0; i < 110; i++)
@@ -314,7 +314,7 @@
314314 public void should_trash_on_returning_connection_with_insufficient_streams()
315315 throws ConnectionException, TimeoutException, InterruptedException {
316316 HostConnectionPool pool = createPool(1, 2);
317- PooledConnection core = pool.connections.get(0);
317+ Connection core = pool.connections.get(0);
318318
319319 for (int i = 0; i < 128; i++)
320320 assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
@@ -323,7 +323,7 @@
323323 assertThat(pool.connections).hasSize(2);
324324
325325 // Grab the new non-core connection and replace it with a spy.
326- PooledConnection extra1 = spy(pool.connections.get(1));
326+ Connection extra1 = spy(pool.connections.get(1));
327327 pool.connections.set(1, extra1);
328328
329329 // Borrow 10 times to ensure pool is utilized.
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +54 −79
@@ -15,98 +15,73 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static java.util.concurrent.TimeUnit.SECONDS;
19-
20-import org.mockito.Mockito;
2118 import org.testng.annotations.Test;
2219
23-import com.datastax.driver.core.Host.State;
24-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
25-import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
26-import com.datastax.driver.core.policies.RoundRobinPolicy;
20+import java.util.Collection;
21+import java.util.Collections;
22+import java.util.concurrent.*;
2723
28-import static com.datastax.driver.core.Assertions.assertThat;
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.mockito.Matchers.any;
26+import static org.mockito.Mockito.*;
2927
30-public class PoolingOptionsTest {
28+public class PoolingOptionsTest extends CCMBridge.PerClassSingleNodeCluster {
29+ @Override
30+ protected Collection<String> getTableDefinitions() {
31+ return Collections.emptyList();
32+ }
3133
3234 /**
33- * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
35+ * <p>
36+ * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it
37+ * is used to create and tear down connections.
38+ * </p>
39+ *
40+ * @test_category connection:connection_pool
41+ * @expected_result executor is used and successfully able to connect and tear down connections.
42+ * @jira_ticket JAVA-692
43+ * @since 2.0.10, 2.1.6
3444 */
35- @Test(groups = "long")
36- public void should_refresh_single_connected_host() {
37- CCMBridge ccm = null;
38- Cluster cluster = null;
45+ @Test(groups = "short")
46+ public void should_be_able_to_use_custom_initialization_executor() {
47+ ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
48+ new LinkedBlockingQueue<Runnable>()));
49+
50+ PoolingOptions poolingOptions = new PoolingOptions();
51+ poolingOptions.setInitializationExecutor(executor);
52+
53+ Cluster cluster = Cluster.builder()
54+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
55+ .withPoolingOptions(poolingOptions).build();
3956 try {
40- // This will make the driver use at most 2 hosts, the others will be ignored
41- LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
42-
43- // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
44- ccm = CCMBridge.create("test");
45- ccm.populate(3);
46- ccm.start(1);
47- ccm.start(2);
48- ccm.waitForUp(1);
49- ccm.waitForUp(2);
50-
51- PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
52- cluster = Cluster.builder()
53- .addContactPoint(CCMBridge.ipOfNode(1))
54- .withPoolingOptions(poolingOptions)
55- .withLoadBalancingPolicy(loadBalancingPolicy)
56- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
57- .build();
57+ cluster.init();
58+ // Ensure executor used.
59+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
60+
61+ // Reset invocation count.
62+ reset();
5863
5964 Session session = cluster.connect();
6065
61- assertThat(cluster).usesControlHost(1);
62- assertThat(cluster).host(1)
63- .hasState(State.UP)
64- .isAtDistance(HostDistance.LOCAL);
65- // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
66- // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
67- assertThat(cluster).host(2)
68- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69- .isAtDistance(HostDistance.LOCAL);
70-
71- // Bring host 3 up, its presence should be acknowledged but it should be ignored
72- ccm.start(3);
73- ccm.waitForUp(3);
74-
75- assertThat(cluster).host(1)
76- .hasState(State.UP)
77- .isAtDistance(HostDistance.LOCAL);
78- assertThat(cluster).host(2)
79- .hasState(State.UP)
80- .isAtDistance(HostDistance.LOCAL);
81- assertThat(cluster).host(3)
82- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
83- .isAtDistance(HostDistance.IGNORED);
84- assertThat(session).hasNoPoolFor(3);
85-
86- // Kill host 2, host 3 should take its place
87- ccm.stop(2);
88- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
89-
90- assertThat(cluster).host(1)
91- .hasState(State.UP)
92- .isAtDistance(HostDistance.LOCAL);
93- assertThat(cluster).host(2)
94- .hasState(State.DOWN);
95- assertThat(cluster).host(3)
96- .hasState(State.UP)
97- .isAtDistance(HostDistance.LOCAL);
98- assertThat(session).hasPoolFor(3);
99-
100- // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
101- // we switch the node from IGNORED to UP:
102- Mockito.verify(poolingOptions)
103- .refreshConnectedHost(TestUtils.findHost(cluster, 3));
66+ // Ensure executor used again to establish core connections.
67+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
68+
69+ // Expect core connections + control connection.
70+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
71+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
72+
73+ reset();
74+
75+ session.close();
76+
77+ // Executor should have been used to close connections associated with the session.
78+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
10479
80+ // Only the control connection should remain.
81+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
10582 } finally {
106- if (cluster != null)
107- cluster.close();
108- if (ccm != null)
109- ccm.remove();
83+ cluster.close();
84+ executor.shutdown();
11085 }
11186 }
11287 }
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +65 −2
@@ -33,6 +33,10 @@
3333 import org.testng.annotations.Test;
3434
3535 import static org.assertj.core.api.Assertions.assertThat;
36+import static org.mockito.Mockito.reset;
37+import static org.mockito.Mockito.spy;
38+import static org.mockito.Mockito.times;
39+import static org.mockito.Mockito.verify;
3640
3741 import com.datastax.driver.core.Host.State;
3842 import com.datastax.driver.core.policies.*;
@@ -141,7 +145,7 @@
141145 CCMBridge ccm = null;
142146 Cluster cluster = null;
143147
144- long reconnectionDelayMillis = 1 * 1000;
148+ long reconnectionDelayMillis = 1000;
145149 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
146150
147151 try {
@@ -182,7 +186,7 @@
182186 CCMBridge ccm = null;
183187 Cluster cluster = null;
184188
185- long reconnectionDelayMillis = 1 * 1000;
189+ long reconnectionDelayMillis = 1000;
186190 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
187191
188192 try {
@@ -220,6 +224,7 @@
220224 // down for the driver.
221225 ccm.start(1);
222226 ccm.waitForUp(1);
227+ assertThat(cluster).host(1).hasState(State.DOWN);
223228
224229 TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
225230 assertThat(cluster).host(1).hasState(State.DOWN);
@@ -236,6 +241,64 @@
236241 }
237242 }
238243
244+ /**
245+ * The connection established by a successful reconnection attempt should be reused in one of the
246+ * connection pools (JAVA-505).
247+ */
248+ @Test(groups = "long")
249+ public void should_use_connection_from_reconnection_in_pool() {
250+ CCMBridge ccm = null;
251+ Cluster cluster = null;
252+
253+ TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
254+
255+ // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
256+ SocketOptions socketOptions = spy(new SocketOptions());
257+
258+ try {
259+ ccm = CCMBridge.create("test", 1);
260+ cluster = Cluster.builder()
261+ .addContactPoint(CCMBridge.ipOfNode(1))
262+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
263+ .withLoadBalancingPolicy(loadBalancingPolicy)
264+ .withSocketOptions(socketOptions)
265+ .build();
266+ // Create two sessions to have multiple pools
267+ cluster.connect();
268+ cluster.connect();
269+
270+ // Right after init, 1 connection has been opened by the control connection, and 2 (core size) for each pool.
271+ verify(socketOptions, times(5)).getKeepAlive();
272+
273+ // Tweak the LBP so that the control connection never reconnects. This makes it easier
274+ // to reason about the number of connection attempts.
275+ loadBalancingPolicy.returnEmptyQueryPlan = true;
276+
277+ // Stop the node and cancel the reconnection attempts to it
278+ ccm.stop(1);
279+ ccm.waitForDown(1);
280+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
281+ Host host1 = TestUtils.findHost(cluster, 1);
282+ host1.getReconnectionAttemptFuture().cancel(false);
283+
284+ ccm.start(1);
285+ ccm.waitForUp(1);
286+
287+ // Reset the spy and count the number of connections attempts for 1 reconnect
288+ reset(socketOptions);
289+ host1.tryReconnectOnce();
290+ assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
291+ // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
292+ // but the one from the reconnection attempt gets reused).
293+ verify(socketOptions, times(4)).getKeepAlive();
294+ } finally {
295+ if (cluster != null)
296+ cluster.close();
297+ if (ccm != null)
298+ ccm.remove();
299+ }
300+ }
301+
239302 /**
240303 * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested.
241304 */
added driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +112 −0
@@ -0,0 +1,112 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import static java.util.concurrent.TimeUnit.SECONDS;
19+
20+import org.mockito.Mockito;
21+import org.testng.annotations.Test;
22+
23+import com.datastax.driver.core.Host.State;
24+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
25+import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
26+import com.datastax.driver.core.policies.RoundRobinPolicy;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
29+
30+public class RefreshConnectedHostTest {
31+
32+ /**
33+ * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
34+ */
35+ @Test(groups = "long")
36+ public void should_refresh_single_connected_host() {
37+ CCMBridge ccm = null;
38+ Cluster cluster = null;
39+ try {
40+ // This will make the driver use at most 2 hosts, the others will be ignored
41+ LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
42+
43+ // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
44+ ccm = CCMBridge.create("test");
45+ ccm.populate(3);
46+ ccm.start(1);
47+ ccm.start(2);
48+ ccm.waitForUp(1);
49+ ccm.waitForUp(2);
50+
51+ PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
52+ cluster = Cluster.builder()
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withPoolingOptions(poolingOptions)
55+ .withLoadBalancingPolicy(loadBalancingPolicy)
56+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
57+ .build();
58+
59+ Session session = cluster.connect();
60+
61+ assertThat(cluster).usesControlHost(1);
62+ assertThat(cluster).host(1)
63+ .hasState(State.UP)
64+ .isAtDistance(HostDistance.LOCAL);
65+ // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
66+ // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
67+ assertThat(cluster).host(2)
68+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69+ .isAtDistance(HostDistance.LOCAL);
70+
71+ // Bring host 3 up, its presence should be acknowledged but it should be ignored
72+ ccm.start(3);
73+ ccm.waitForUp(3);
74+
75+ assertThat(cluster).host(1)
76+ .hasState(State.UP)
77+ .isAtDistance(HostDistance.LOCAL);
78+ assertThat(cluster).host(2)
79+ .hasState(State.UP)
80+ .isAtDistance(HostDistance.LOCAL);
81+ assertThat(cluster).host(3)
82+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
83+ .isAtDistance(HostDistance.IGNORED);
84+ assertThat(session).hasNoPoolFor(3);
85+
86+ // Kill host 2, host 3 should take its place
87+ ccm.stop(2);
88+ TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
89+
90+ assertThat(cluster).host(1)
91+ .hasState(State.UP)
92+ .isAtDistance(HostDistance.LOCAL);
93+ assertThat(cluster).host(2)
94+ .hasState(State.DOWN);
95+ assertThat(cluster).host(3)
96+ .hasState(State.UP)
97+ .isAtDistance(HostDistance.LOCAL);
98+ assertThat(session).hasPoolFor(3);
99+
100+ // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
101+ // we switch the node from IGNORED to UP:
102+ Mockito.verify(poolingOptions)
103+ .refreshConnectedHost(TestUtils.findHost(cluster, 3));
104+
105+ } finally {
106+ if (cluster != null)
107+ cluster.close();
108+ if (ccm != null)
109+ ccm.remove();
110+ }
111+ }
112+}
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +2 −2
@@ -72,7 +72,7 @@
7272 }
7373 }
7474
75- PooledConnection connection = getSingleConnection(session);
75+ Connection connection = getSingleConnection(session);
7676 assertThat(connection.inFlight.get()).isEqualTo(0);
7777 } finally {
7878 if (cluster != null)
@@ -81,7 +81,7 @@
8181 }
8282 }
8383
84- private PooledConnection getSingleConnection(Session session) {
84+ private Connection getSingleConnection(Session session) {
8585 HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
8686 return pool.connections.get(0);
8787 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +25 −1
@@ -15,9 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
1820 import org.testng.annotations.Test;
1921
22+import java.net.InetSocketAddress;
2023 import java.util.Collections;
24+import java.util.List;
25+import java.util.concurrent.TimeUnit;
2126
2227 import static org.testng.Assert.assertEquals;
2328
@@ -31,9 +36,18 @@
3136 CCMBridge ccmBridge;
3237 ccmBridge = CCMBridge.create("test", 1);
3338 Cluster cluster = null;
39+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
40+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
41+
42+ List<InetSocketAddress> nodes = Lists.newArrayList(
43+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
44+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
3445 try {
3546 // create a new cluster object and ensure 0 sessions and connections
36- cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
47+ cluster = Cluster.builder()
48+ .addContactPointsWithPorts(Collections.singletonList(
49+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
50+ .withNettyOptions(channelMonitor.nettyOptions()).build();
3751 cluster.init();
3852
3953 int corePoolSize = cluster.getConfiguration()
@@ -43,21 +57,25 @@
4357 assertEquals(cluster.manager.sessions.size(), 0);
4458 // Should be 1 control connection after initialization.
4559 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
60+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
4661
4762 // ensure sessions.size() returns with 1 control connection + core pool size.
4863 Session session = cluster.connect();
4964 assertEquals(cluster.manager.sessions.size(), 1);
5065 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
66+ assertEquals(channelMonitor.openChannels(nodes).size(), 1 + corePoolSize);
5167
5268 // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
5369 session.close();
5470 assertEquals(cluster.manager.sessions.size(), 0);
5571 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
72+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
5673
5774 // ensure bootstrapping a node does not create additional connections
5875 ccmBridge.bootstrapNode(2);
5976 assertEquals(cluster.manager.sessions.size(), 0);
6077 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
78+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
6179
6280 // ensure a new session gets registered and core connections are established
6381 // there should be corePoolSize more connections to accommodate for the new host.
@@ -65,12 +83,14 @@
6583 assertEquals(cluster.manager.sessions.size(), 1);
6684
6785 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + (corePoolSize * 2));
86+ assertEquals(channelMonitor.openChannels(nodes).size(), 1 + (corePoolSize * 2));
6887
6988 // ensure bootstrapping a node does not create additional connections that won't get cleaned up
7089 thisSession.close();
7190
7291 assertEquals(cluster.manager.sessions.size(), 0);
7392 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
93+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
7494 } finally {
7595 if(cluster != null){
7696 cluster.close();
@@ -78,6 +98,10 @@
7898 if (ccmBridge != null) {
7999 ccmBridge.remove();
80100 }
101+ // Ensure no channels remain open.
102+ channelMonitor.stop();
103+ channelMonitor.report();
104+ assertEquals(channelMonitor.openChannels(nodes).size(), 0);
81105 }
82106 }
83107 }
added driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +262 −0
@@ -0,0 +1,262 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.*;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
23+import org.testng.annotations.Test;
24+
25+import java.net.InetSocketAddress;
26+import java.util.*;
27+import java.util.concurrent.*;
28+
29+import static org.testng.Assert.assertEquals;
30+import static org.testng.Assert.fail;
31+
32+public class SessionStressTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ private static final Logger logger = LoggerFactory.getLogger(SessionStressTest.class);
35+
36+ private ListeningExecutorService executorService;
37+
38+ public SessionStressTest() {
39+ // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
40+ executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8));
41+ }
42+
43+ @Override
44+ protected Collection<String> getTableDefinitions() {
45+ return new ArrayList<String>(0);
46+ }
47+
48+
49+ /**
50+ * Stress test on opening/closing sessions.
51+ * <p/>
52+ * This test opens and closes {@code Session} in a multithreaded environment and makes sure that there is not
53+ * connection leak. More specifically, this test performs the following steps:
54+ * <p/>
55+ * <ul>
56+ * <li>Open 2000 {@code Session} concurrently</li>
57+ * <li>Verify that 2000 sessions are reported as open by the {@code Cluster}</li>
58+ * <li>Verify that 4001 connections are reported as open by the {@code Cluster}</li>
59+ * <li>Close 1000 {@code Session} concurrently</li>
60+ * <li>Verify that 1000 sessions are reported as open by the {@code Cluster}</li>
61+ * <li>Verify that 2001 connections are reported as open by the {@code Cluster}</li>
62+ * <li>Open concurrently 1000 {@code Session} while 1000 other {@code Session} are closed concurrently</li>
63+ * <li>Verify that 1000 sessions are reported as open by the {@code Cluster}</li>
64+ * <li>Verify that 2001 connections are reported as open by the {@code Cluster}</li>
65+ * <li>Close 1000 {@code Session} concurrently</li>
66+ * <li>Verify that 0 sessions are reported as open by the {@code Cluster}</li>
67+ * <li>Verify that 1 connection is reported as open by the {@code Cluster}</li>
68+ * </ul>
69+ * <p/>
70+ * This test is linked to JAVA-432.
71+ */
72+ @Test(groups = "long")
73+ public void sessions_should_not_leak_connections() {
74+ // override inherited field with a new cluster object and ensure 0 sessions and connections
75+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
76+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
77+ List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
78+ cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
79+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
80+ .withNettyOptions(channelMonitor.nettyOptions()).build();
81+ cluster.init();
82+
83+ // The cluster has been initialized, we should have 1 connection.
84+ assertEquals(cluster.manager.sessions.size(), 0);
85+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
86+
87+ // The first session initializes the cluster and its control connection
88+ // This is a local cluster so we also have 2 connections per session
89+ Session session = cluster.connect();
90+ assertEquals(cluster.manager.sessions.size(), 1);
91+ int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster);
92+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
93+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
94+
95+ // Closing the session keeps the control connection opened
96+ session.close();
97+ assertEquals(cluster.manager.sessions.size(), 0);
98+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
99+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
100+
101+ try {
102+ int nbOfSessions = 2000;
103+ int halfOfTheSessions = nbOfSessions / 2;
104+ int nbOfIterations = 5;
105+ int sleepTime = 20;
106+
107+ for (int iteration = 1; iteration <= nbOfIterations; iteration++) {
108+ logger.info("On iteration {}/{}.", iteration, nbOfIterations);
109+ logger.info("Creating {} sessions.", nbOfSessions);
110+ waitFor(openSessionsConcurrently(nbOfSessions));
111+
112+ // We should see the exact number of opened sessions
113+ // Since we have 2 connections per session, we should see 2 * sessions + control connection
114+ assertEquals(cluster.manager.sessions.size(), nbOfSessions);
115+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
116+ coreConnections * nbOfSessions + 1);
117+ assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
118+
119+ // Close half of the sessions asynchronously
120+ logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
121+ waitFor(closeSessionsConcurrently(halfOfTheSessions));
122+
123+ // Check that we have the right number of sessions and connections
124+ assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
125+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
126+ coreConnections * (nbOfSessions / 2) + 1);
127+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
128+ coreConnections * (nbOfSessions / 2) + 1);
129+
130+ // Close and open the same number of sessions concurrently
131+ logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions);
132+ CountDownLatch startSignal = new CountDownLatch(2);
133+ List<ListenableFuture<Session>> openSessionFutures =
134+ openSessionsConcurrently(halfOfTheSessions, startSignal);
135+ List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions,
136+ startSignal);
137+ startSignal.countDown();
138+ waitFor(openSessionFutures);
139+ waitFor(closeSessionsFutures);
140+
141+ // Check that we have the same number of sessions and connections
142+ assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
143+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
144+ coreConnections * (nbOfSessions / 2) + 1);
145+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
146+ coreConnections * (nbOfSessions / 2) + 1);
147+
148+ // Close the remaining sessions
149+ logger.info("Closing remaining {} sessions.", halfOfTheSessions);
150+ waitFor(closeSessionsConcurrently(halfOfTheSessions));
151+
152+ // Check that we have a clean state
153+ assertEquals(cluster.manager.sessions.size(), 0);
154+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
155+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
156+
157+ // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
158+ logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
159+ Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS);
160+ }
161+ } finally {
162+ cluster.close();
163+
164+ // Ensure no channels remain open.
165+ channelMonitor.stop();
166+ channelMonitor.report();
167+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
168+ }
169+ }
170+
171+ private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations) {
172+ final CountDownLatch countDownLatch = new CountDownLatch(1);
173+ return openSessionsConcurrently(iterations, countDownLatch);
174+ }
175+
176+ private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
177+ // Open new sessions once all tasks have been created
178+ List<ListenableFuture<Session>> sessionFutures = Lists.newArrayListWithCapacity(iterations);
179+ for (int i = 0; i < iterations; i++) {
180+ sessionFutures.add(executorService.submit(new OpenSession(cluster, countDownLatch)));
181+ }
182+ countDownLatch.countDown();
183+ return sessionFutures;
184+ }
185+
186+ private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations) {
187+ final CountDownLatch countDownLatch = new CountDownLatch(1);
188+ return closeSessionsConcurrently(iterations, countDownLatch);
189+ }
190+
191+ private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
192+ // Get a reference to every session we want to close
193+ Stack<Session> sessionsToClose = new Stack<Session>();
194+ Iterator<? extends Session> iterator = cluster.manager.sessions.iterator();
195+ for (int i = 0; i < iterations; i++) {
196+ sessionsToClose.push(iterator.next());
197+ }
198+
199+ // Close sessions asynchronously once all tasks have been created
200+ List<ListenableFuture<CloseFuture>> closeFutures = Lists.newArrayListWithCapacity(iterations);
201+ for (int i = 0; i < iterations; i++) {
202+ closeFutures.add(executorService.submit(new CloseSession(sessionsToClose.pop(), countDownLatch)));
203+ }
204+ countDownLatch.countDown();
205+
206+ // Immediately wait for CloseFutures, this should be very quick since all this work does is call closeAsync.
207+ List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(iterations);
208+ for(ListenableFuture<CloseFuture> closeFuture : closeFutures) {
209+ try {
210+ futures.add(closeFuture.get());
211+ } catch(Exception e) {
212+ logger.error("Got interrupted exception while waiting on closeFuture.", e);
213+ }
214+ }
215+ return futures;
216+ }
217+
218+ private <E> void waitFor(List<ListenableFuture<E>> futures) {
219+ for (Future<E> future : futures) {
220+ try {
221+ future.get();
222+ } catch (InterruptedException e) {
223+ throw new RuntimeException("Interrupted while waiting for future", e);
224+ } catch (ExecutionException e) {
225+ e.printStackTrace();
226+ fail(e.getMessage());
227+ }
228+ }
229+ }
230+
231+ private static class OpenSession implements Callable<Session> {
232+ private final Cluster cluster;
233+ private final CountDownLatch startSignal;
234+
235+ OpenSession(Cluster cluster, CountDownLatch startSignal) {
236+ this.cluster = cluster;
237+ this.startSignal = startSignal;
238+ }
239+
240+ @Override
241+ public Session call() throws Exception {
242+ startSignal.await();
243+ return cluster.connect();
244+ }
245+ }
246+
247+ private static class CloseSession implements Callable<CloseFuture> {
248+ private final Session session;
249+ private final CountDownLatch startSignal;
250+
251+ CloseSession(Session session, CountDownLatch startSignal) {
252+ this.session = session;
253+ this.startSignal = startSignal;
254+ }
255+
256+ @Override
257+ public CloseFuture call() throws Exception {
258+ startSignal.await();
259+ return session.closeAsync();
260+ }
261+ }
262+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +22 −1
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.*;
1920 import java.util.concurrent.CountDownLatch;
2021 import java.util.concurrent.ExecutorService;
@@ -22,6 +23,10 @@
2223 import java.util.concurrent.TimeUnit;
2324
2425 import com.datastax.driver.core.utils.CassandraVersion;
26+import com.datastax.driver.core.utils.SocketChannelMonitor;
27+import io.netty.channel.socket.SocketChannel;
28+import org.slf4j.Logger;
29+import org.slf4j.LoggerFactory;
2530 import org.testng.annotations.Test;
2631
2732 import static org.testng.Assert.assertEquals;
@@ -35,6 +40,8 @@
3540 */
3641 public class SessionTest extends CCMBridge.PerClassSingleNodeCluster {
3742
43+ private static final Logger logger = LoggerFactory.getLogger(SessionTest.class);
44+
3845 private static final String TABLE1 = "test1";
3946 private static final String TABLE2 = "test2";
4047 private static final String TABLE3 = "test3";
@@ -173,11 +180,15 @@
173180
174181 // create a new cluster object and ensure 0 sessions and connections
175182 int corePoolSize = 2;
183+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
184+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
176185 PoolingOptions poolingOptions = new PoolingOptions()
177186 .setCoreConnectionsPerHost(HostDistance.LOCAL, corePoolSize);
187+ Collection<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
178188 Cluster cluster = Cluster.builder()
179- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
189+ .addContactPointsWithPorts(contactPoints)
180190 .withPoolingOptions(poolingOptions)
191+ .withNettyOptions(channelMonitor.nettyOptions())
181192 .build();
182193
183194 try {
@@ -185,15 +196,18 @@
185196
186197 assertEquals(cluster.manager.sessions.size(), 0);
187198 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
199+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
188200
189201 Session session = cluster.connect();
190202 assertEquals(cluster.manager.sessions.size(), 1);
191203 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
204+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + corePoolSize);
192205
193206 // ensure sessions.size() returns to 0 with only 1 active connection
194207 session.close();
195208 assertEquals(cluster.manager.sessions.size(), 0);
196209 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
210+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
197211
198212 // give the driver time to close sessions
199213 Thread.sleep(10);
@@ -202,11 +216,13 @@
202216 // ensure 0 sessions with a single control connection
203217 assertEquals(cluster.manager.sessions.size(), 0);
204218 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
219+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
205220
206221 // ensure a new session gets registered and control connections are established
207222 session = cluster.connect();
208223 assertEquals(cluster.manager.sessions.size(), 1);
209224 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
225+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + corePoolSize);
210226 session.close();
211227
212228 // give the driver time to close sessions
@@ -215,9 +231,14 @@
215231 // ensure sessions.size() always returns to 0 with only 1 active connection
216232 assertEquals(cluster.manager.sessions.size(), 0);
217233 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
234+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
218235 }
219236 } finally {
220237 cluster.close();
238+ // Ensure no channels remain open.
239+ channelMonitor.stop();
240+ channelMonitor.report();
241+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
221242 }
222243 }
223244
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +4 −0
@@ -393,6 +393,10 @@
393393 return null; // never reached
394394 }
395395
396+ public static int numberOfLocalCoreConnections(Cluster cluster) {
397+ Configuration configuration = cluster.getConfiguration();
398+ return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
399+ }
396400 /**
397401 * @return A Scassandra instance with an arbitrarily chosen binary port from 8042-8142 and admin port from
398402 * 8052-8152.
added driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +279 −0
@@ -0,0 +1,279 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.utils.SocketChannelMonitor;
20+import com.google.common.collect.Lists;
21+import com.google.common.util.concurrent.FutureCallback;
22+import com.google.common.util.concurrent.Futures;
23+import com.google.common.util.concurrent.ThreadFactoryBuilder;
24+import com.google.common.util.concurrent.Uninterruptibles;
25+import io.netty.channel.socket.SocketChannel;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+import org.testng.annotations.AfterClass;
29+import org.testng.annotations.BeforeClass;
30+import org.testng.annotations.Test;
31+
32+import java.net.InetSocketAddress;
33+import java.util.Collection;
34+import java.util.List;
35+import java.util.concurrent.*;
36+import java.util.concurrent.atomic.AtomicBoolean;
37+import java.util.concurrent.atomic.AtomicInteger;
38+
39+import static org.assertj.core.api.Assertions.assertThat;
40+
41+public class TimeoutStressTest {
42+
43+ static final Logger logger = LoggerFactory.getLogger(TimeoutStressTest.class);
44+
45+ // Maximum number of concurrent queries running at a given time.
46+ static final int CONCURRENT_QUERIES = 25;
47+
48+ // How long the test should run for, may want to consider running for longer periods to time to check for leaks
49+ // that could occur over very tiny timing windows.
50+ static final long DURATION = 60000;
51+
52+ // Configured read timeout - this may need to be tuned to the host system running the test.
53+ static final int READ_TIMEOUT_IN_MS = 50;
54+
55+ // Configured connection timeout - this may need to be tuned to the host system running the test.
56+ static final int CONNECTION_TIMEOUT_IN_MS = 20;
57+
58+ // Keyspace to use.
59+ static final String KEYSPACE = "testks";
60+
61+ static Cluster cluster;
62+
63+ static CCMBridge ccmBridge;
64+
65+ static SocketChannelMonitor channelMonitor;
66+
67+ static AtomicInteger executedQueries = new AtomicInteger(0);
68+
69+ static List<InetSocketAddress> nodes;
70+
71+ static PreparedStatement statement;
72+
73+ @BeforeClass(groups = "long")
74+ public void beforeClass() throws Exception {
75+ ccmBridge = CCMBridge.create("test", 3);
76+ channelMonitor = new SocketChannelMonitor();
77+ nodes = Lists.newArrayList(
78+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
79+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
80+ new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
81+ );
82+
83+ PoolingOptions poolingOptions = new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 8);
84+
85+ cluster = Cluster.builder()
86+ .addContactPointsWithPorts(nodes)
87+ .withPoolingOptions(poolingOptions)
88+ .withNettyOptions(channelMonitor.nettyOptions())
89+ .build();
90+ Session session = cluster.connect();
91+ setupSchema(session);
92+ session.close();
93+ }
94+
95+ @AfterClass(groups = "long")
96+ public void afterClass() {
97+ if(ccmBridge != null) {
98+ ccmBridge.stop();
99+ }
100+ if(channelMonitor != null) {
101+ channelMonitor.stop();
102+ }
103+ if(cluster != null) {
104+ cluster.close();
105+ }
106+ }
107+
108+ /**
109+ * <p>
110+ * Validates that under extreme timeout conditions the driver is able to properly maintain connection pools in
111+ * addition to not leaking connections.
112+ *
113+ * <p>
114+ * Does the following:
115+ * <ol>
116+ * <li>Creates a table and loads 30k rows in a single partition.</li>
117+ * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
118+ * <li>Spawns workers that concurrently execute queries.</li>
119+ * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
120+ * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
121+ * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
122+ * <li>Ensure pools are restored.</li>
123+ * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
124+ * </ol>
125+ *
126+ * @test_category connection:connection_pool
127+ * @expected_result no connections leak and all host pools are maintained.
128+ * @jira_ticket JAVA-692
129+ * @since 2.0.10, 2.1.6
130+ */
131+ @Test(groups = "long")
132+ public void host_state_should_be_maintained_with_timeouts() {
133+ // Set very low timeouts.
134+ cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
135+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
136+ Session session = cluster.connect();
137+
138+ int workers = Runtime.getRuntime().availableProcessors();
139+ ExecutorService workerPool = Executors.newFixedThreadPool(workers,
140+ new ThreadFactoryBuilder().setNameFormat("timeout-stress-test-worker-%d").setDaemon(true).build());
141+
142+ AtomicBoolean stopped = new AtomicBoolean(false);
143+
144+ // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection.
145+ int maxConnections = cluster.getConfiguration()
146+ .getPoolingOptions().getMaxConnectionsPerHost(HostDistance.LOCAL) * nodes.size() + 1;
147+
148+ try {
149+ Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES);
150+ for (int i = 0; i < workers; i++) {
151+ workerPool.submit(new TimeoutStressWorker(session, concurrentQueries, stopped));
152+ }
153+
154+ long startTime = System.currentTimeMillis();
155+ while (System.currentTimeMillis() - startTime < DURATION) {
156+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
157+ channelMonitor.report();
158+ // Some connections that are being closed may have had active requests which are delegated to the
159+ // reaper for cleanup later.
160+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
161+
162+ // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
163+ // factor between retrieving open connections and checking the reaper.
164+ if(openChannels.size() > maxConnections) {
165+ logger.warn("{} of open channels: {} exceeds maximum expected: {}. " +
166+ "This could be because there are connections to be cleaned up in the reaper.",
167+ openChannels.size(), maxConnections, openChannels);
168+ }
169+ }
170+ } finally {
171+ stopped.set(true);
172+
173+ // Reset socket timeouts to allow pool to recover.
174+ cluster.getConfiguration().getSocketOptions()
175+ .setConnectTimeoutMillis(SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS);
176+ cluster.getConfiguration().getSocketOptions()
177+ .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
178+
179+ logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
180+ "and for the pools to recover.");
181+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
182+
183+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
184+ assertThat(openChannels.size())
185+ .as("Number of open connections does not meet expected: %s", openChannels)
186+ .isEqualTo(maxConnections);
187+
188+ session.close();
189+
190+ openChannels = channelMonitor.openChannels(nodes);
191+ assertThat(openChannels.size())
192+ .as("Number of open connections does not meet expected: %s", openChannels)
193+ .isEqualTo(1);
194+
195+ workerPool.shutdown();
196+ }
197+ }
198+
199+ /**
200+ * Creates the testks schema with a 'record' table and preloads 30k records.
201+ */
202+ private static void setupSchema(Session session) throws InterruptedException, ExecutionException, TimeoutException {
203+ logger.debug("Creating keyspace");
204+ session.execute("create KEYSPACE if not exists " + KEYSPACE +
205+ " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}");
206+ session.execute("use " + KEYSPACE);
207+
208+ logger.debug("Creating table");
209+ session.execute("create table if NOT EXISTS record (\n"
210+ + " name text,\n"
211+ + " phone text,\n"
212+ + " value text,\n"
213+ + " PRIMARY KEY (name, phone)\n"
214+ + ");");
215+
216+ int records = 30000;
217+ List<ResultSetFuture> futures = Lists.newArrayListWithExpectedSize(records);
218+
219+ for (int i = 0; i < records; i++) {
220+ if (i % 1000 == 0)
221+ logger.debug("Inserting record {}.", i);
222+ futures.add(session.executeAsync(
223+ "insert into record (name, phone, value) values (?, ?, ?)", "0", Integer.toString(i), "test"));
224+ }
225+
226+ statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;");
227+
228+ logger.debug("Completed inserting data. Waiting up to 30 for inserts to complete seconds before proceeding.");
229+ Futures.allAsList(futures).get(30, TimeUnit.SECONDS);
230+ logger.debug("Inserts complete.");
231+ }
232+
233+ public static class TimeoutStressWorker implements Runnable {
234+
235+ private final Semaphore concurrentQueries;
236+ private final AtomicBoolean stopped;
237+ private final Session session;
238+
239+ public TimeoutStressWorker(Session session, Semaphore concurrentQueries, AtomicBoolean stopped) {
240+ this.session = session;
241+ this.concurrentQueries = concurrentQueries;
242+ this.stopped = stopped;
243+ }
244+
245+
246+ @Override
247+ public void run() {
248+
249+ while(!stopped.get()) {
250+ try {
251+ concurrentQueries.acquire();
252+ ResultSetFuture future = session.executeAsync(statement.bind("0"));
253+ Futures.addCallback(future, new FutureCallback<ResultSet>() {
254+
255+ @Override
256+ public void onSuccess(ResultSet result) {
257+ concurrentQueries.release();
258+ if(executedQueries.incrementAndGet() % 1000 == 0)
259+ logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching());
260+ }
261+
262+ @Override
263+ public void onFailure(Throwable t) {
264+ concurrentQueries.release();
265+ if(t instanceof NoHostAvailableException) {
266+ //logger.error("NHAE: {}", t.getMessage());
267+ } else {
268+ //logger.error("Exception", t);
269+ }
270+ }
271+ });
272+ } catch(Exception e) {
273+ logger.error("Failure while submitting query.", e);
274+ }
275+ }
276+
277+ }
278+ }
279+}
added driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +174 −0
@@ -0,0 +1,174 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.utils;
17+
18+import com.datastax.driver.core.NettyOptions;
19+import com.google.common.base.Predicate;
20+import com.google.common.base.Predicates;
21+import com.google.common.collect.Iterables;
22+import com.google.common.collect.Lists;
23+import com.google.common.collect.MapMaker;
24+import com.google.common.util.concurrent.ThreadFactoryBuilder;
25+import io.netty.channel.socket.SocketChannel;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+
29+import java.net.InetSocketAddress;
30+import java.net.Socket;
31+import java.net.SocketAddress;
32+import java.util.*;
33+import java.util.concurrent.Executors;
34+import java.util.concurrent.ScheduledExecutorService;
35+import java.util.concurrent.TimeUnit;
36+import java.util.concurrent.atomic.AtomicLong;
37+
38+/**
39+ * Utility that observes {@link SocketChannel}s. Helpful for ensuring that Sockets are actually closed
40+ * when they should be. Utilizes {@link NettyOptions} to monitor created {@link SocketChannel}s.
41+ */
42+public class SocketChannelMonitor implements Runnable {
43+
44+ private static final Logger logger = LoggerFactory.getLogger(SocketChannelMonitor.class);
45+
46+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1,
47+ new ThreadFactoryBuilder().setDaemon(true).setNameFormat("SocketMonitor-%d").build());
48+
49+ // use a weak set so channels may be garbage collected.
50+ private final Collection<SocketChannel> channels = Collections.newSetFromMap(
51+ new MapMaker().weakKeys().<SocketChannel, Boolean>makeMap());
52+
53+ private final AtomicLong channelsCreated = new AtomicLong(0);
54+
55+ private final NettyOptions nettyOptions = new NettyOptions() {
56+ public void afterChannelInitialized(SocketChannel channel) throws Exception {
57+ channels.add(channel);
58+ channelsCreated.incrementAndGet();
59+ }
60+ };
61+
62+ @Override
63+ public void run() {
64+ try {
65+ report();
66+ } catch(Exception e) {
67+ logger.error("Error countered.", e);
68+ }
69+ }
70+
71+ public void stop() {
72+ executor.shutdown();
73+ try {
74+ executor.awaitTermination(1, TimeUnit.SECONDS);
75+ } catch (InterruptedException e) {
76+ }
77+ }
78+
79+ /**
80+ * @return A custom {@link NettyOptions} instance that hooks into afterChannelInitialized added channels may be
81+ * monitored.
82+ */
83+ public NettyOptions nettyOptions() {
84+ return nettyOptions;
85+ }
86+
87+ public static Predicate<SocketChannel> openChannels = new Predicate<SocketChannel>() {
88+ @Override
89+ public boolean apply(SocketChannel input) {
90+ return input.isOpen();
91+ }
92+ };
93+
94+ /**
95+ * Schedules a {@link #report()} to be called every configured interval.
96+ * @param interval how often to report.
97+ * @param timeUnit at what time precision to report at.
98+ */
99+ public void reportAtFixedInterval(int interval, TimeUnit timeUnit) {
100+ executor.scheduleAtFixedRate(this, interval, interval, timeUnit);
101+ }
102+
103+ /**
104+ * Reports for all sockets.
105+ */
106+ public void report() {
107+ report(Predicates.<SocketChannel>alwaysTrue());
108+ }
109+
110+ /**
111+ * <p>
112+ * Report for all sockets matching the given predicate. The report format reflects the number of open, closed,
113+ * live and total sockets created. This is logged at DEBUG if enabled.
114+ *
115+ * <p>
116+ * If TRACE is enabled, each individual socket will be logged as well.
117+ *
118+ * @param channelFilter used to determine which sockets to report on.
119+ */
120+ public void report(Predicate<SocketChannel> channelFilter) {
121+ if(logger.isDebugEnabled()) {
122+ Iterable<SocketChannel> channels = matchingChannels(channelFilter);
123+ Iterable<SocketChannel> open = Iterables.filter(channels, openChannels);
124+ Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels));
125+
126+ logger.debug("Channel states: {} open, {} closed, live {}, total sockets created " +
127+ "(including those that don't match filter) {}.",
128+ Iterables.size(open),
129+ Iterables.size(closed),
130+ Iterables.size(channels),
131+ channelsCreated.get());
132+
133+ if(logger.isTraceEnabled()) {
134+ logger.trace("Open channels {}.", open);
135+ logger.trace("Closed channels {}.", closed);
136+ }
137+ }
138+ }
139+
140+ private static Comparator<SocketChannel> BY_REMOTE_ADDRESS = new Comparator<SocketChannel>() {
141+ @Override
142+ public int compare(SocketChannel t0, SocketChannel t1) {
143+ // Should not be null as these are filtered previously in matchingChannels.
144+ assert t0 != null && t0.remoteAddress() != null;
145+ assert t1 != null && t1.remoteAddress() != null;;
146+ return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString());
147+ }
148+ };
149+
150+ /**
151+ * @param addresses The addresses to include.
152+ * @return Open channels matching the given socket addresses.
153+ */
154+ public Collection<SocketChannel> openChannels(final Collection<InetSocketAddress> addresses) {
155+ List<SocketChannel> channels = Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() {
156+ @Override
157+ public boolean apply(SocketChannel input) {
158+ return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress());
159+ }
160+ }));
161+
162+ Collections.sort(channels, BY_REMOTE_ADDRESS);
163+
164+ return channels;
165+ }
166+
167+ /**
168+ * @param channelFilter {@link Predicate} to use to determine whether or not a socket shall be considered.
169+ * @return Channels matching the given {@link Predicate}.
170+ */
171+ public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) {
172+ return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter));
173+ }
174+}