Elffuss BraidHub

kikocis/java-driver public

Temporarily revert JAVA-505 and JAVA-518.

We are delaying these tickets to 2.0.10 to speed up the release of
2.0.9, which fixes critical bugs.
Changeseta8f731741d38f85b46ceb409aa0f2cf422c47c779ac6da10fb0650998b906ce2
Authorolim7t <omichallat+github@gmail.com> · 2014-12-09 18:24 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-12-09 18:29 +01:00
Parentsacf10ecd97aa

Browse the files at this changeset

12 files changed

modified driver-core/CHANGELOG.rst +0 −2
@@ -6,9 +6,7 @@
66
77 - [improvement] Shade Netty dependency (JAVA-538)
88 - [improvement] Target schema refreshes more precisely (JAVA-543)
9-- [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
109 - [bug] Don't check rpc_address for control host (JAVA-546)
11-- [improvement] Optimize connection use after reconnection (JAVA-505)
1210 - [improvement] Improve message of NoHostAvailableException (JAVA-409)
1311
1412
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +162 −169
@@ -1315,10 +1315,6 @@
13151315 if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
13161316 ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
13171317
1318- AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1319- if (translater instanceof CloseableAddressTranslater)
1320- ((CloseableAddressTranslater)translater).close();
1321-
13221318 // Then we shutdown all connections
13231319 List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
13241320 futures.add(controlConnection.closeAsync());
@@ -1358,107 +1354,103 @@
13581354 return executor.submit(new ExceptionCatchingRunnable() {
13591355 @Override
13601356 public void runMayThrow() throws InterruptedException, ExecutionException {
1361- onUp(host, null);
1357+ onUp(host);
13621358 }
13631359 });
13641360 }
13651361
1366- private void onUp(final Host host, Connection preExistentConnection) throws InterruptedException, ExecutionException {
1362+ private void onUp(final Host host) throws InterruptedException, ExecutionException {
13671363 // Note that in generalize we can parallelize the pool creation on
13681364 // each session, but we shouldn't use executor since we're already
13691365 // running on it most probably (and so we could deadlock). Use the
13701366 // blockingExecutor instead, that's why it's for.
1371- onUp(host, preExistentConnection, blockingExecutor);
1367+ onUp(host, blockingExecutor);
13721368 }
13731369
13741370 // Use triggerOnUp unless you're sure you want to run this on the current thread.
1375- private void onUp(final Host host, Connection preExistentConnection, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
1371+ private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
13761372 logger.debug("Host {} is UP", host);
1377- try {
1378- if (isClosed())
1379- return;
13801373
1381- // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1382- if (host.state == Host.State.UP)
1383- return;
1374+ if (isClosed())
1375+ return;
13841376
1385- if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1386- logUnsupportedVersionProtocol(host);
1387- return;
1388- }
1377+ // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1378+ if (host.state == Host.State.UP)
1379+ return;
13891380
1390- // If there is a reconnection attempt scheduled for that node, cancel it
1391- Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1392- if (scheduledAttempt != null) {
1393- logger.debug("Cancelling reconnection attempt since node is UP");
1394- scheduledAttempt.cancel(false);
1395- }
1381+ if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1382+ logUnsupportedVersionProtocol(host);
1383+ return;
1384+ }
13961385
1397- try {
1398- prepareAllQueries(host);
1399- } catch (InterruptedException e) {
1400- Thread.currentThread().interrupt();
1401- // Don't propagate because we don't want to prevent other listener to run
1402- } catch (UnsupportedProtocolVersionException e) {
1403- logUnsupportedVersionProtocol(host);
1404- return;
1405- } catch (ClusterNameMismatchException e) {
1406- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1407- return;
1408- }
1386+ // If there is a reconnection attempt scheduled for that node, cancel it
1387+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1388+ if (scheduledAttempt != null) {
1389+ logger.debug("Cancelling reconnection attempt since node is UP");
1390+ scheduledAttempt.cancel(false);
1391+ }
14091392
1410- // Session#onUp() expects the load balancing policy to have been updated first, so that
1411- // Host distances are up to date. This mean the policy could return the node before the
1412- // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1413- // will ignore the node, but we do want to make sure there is no prior pool so we don't
1414- // query from a pool we will shutdown right away.
1415- for (SessionManager s : sessions)
1416- s.removePool(host);
1417- loadBalancingPolicy().onUp(host);
1418- controlConnection.onUp(host);
1419-
1420- logger.trace("Adding/renewing host pools for newly UP host {}", host);
1421-
1422- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1423- for (SessionManager s : sessions)
1424- futures.add(s.forceRenewPool(host, preExistentConnection, poolCreationExecutor));
1425-
1426- // Only mark the node up once all session have re-added their pool (if the load-balancing
1427- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1428- // to the node.
1429- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1430- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1431- public void onSuccess(List<Boolean> poolCreationResults) {
1432- // If any of the creation failed, they will have signaled a connection failure
1433- // which will trigger a reconnection to the node. So don't bother marking UP.
1434- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1435- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1436- return;
1437- }
1393+ try {
1394+ prepareAllQueries(host);
1395+ } catch (InterruptedException e) {
1396+ Thread.currentThread().interrupt();
1397+ // Don't propagate because we don't want to prevent other listener to run
1398+ } catch (UnsupportedProtocolVersionException e) {
1399+ logUnsupportedVersionProtocol(host);
1400+ return;
1401+ } catch (ClusterNameMismatchException e) {
1402+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1403+ return;
1404+ }
14381405
1439- host.setUp();
1406+ // Session#onUp() expects the load balancing policy to have been updated first, so that
1407+ // Host distances are up to date. This mean the policy could return the node before the
1408+ // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1409+ // will ignore the node, but we do want to make sure there is no prior pool so we don't
1410+ // query from a pool we will shutdown right away.
1411+ for (SessionManager s : sessions)
1412+ s.removePool(host);
1413+ loadBalancingPolicy().onUp(host);
1414+ controlConnection.onUp(host);
14401415
1441- for (Host.StateListener listener : listeners)
1442- listener.onUp(host);
1443- }
1416+ logger.trace("Adding/renewing host pools for newly UP host {}", host);
14441417
1445- public void onFailure(Throwable t) {
1446- // That future is not really supposed to throw unexpected exceptions
1447- if (!(t instanceof InterruptedException))
1448- logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1418+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1419+ for (SessionManager s : sessions)
1420+ futures.add(s.forceRenewPool(host, poolCreationExecutor));
1421+
1422+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1423+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1424+ // to the node.
1425+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1426+ Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1427+ public void onSuccess(List<Boolean> poolCreationResults) {
1428+ // If any of the creation failed, they will have signaled a connection failure
1429+ // which will trigger a reconnection to the node. So don't bother marking UP.
1430+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1431+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1432+ return;
14491433 }
1450- });
1451-
1452- f.get();
1453-
1454- // Now, check if there isn't pools to create/remove following the addition.
1455- // We do that now only so that it's not called before we've set the node up.
1456- for (SessionManager s : sessions)
1457- s.updateCreatedPools(blockingExecutor);
1458- } finally {
1459- if (preExistentConnection != null && !preExistentConnection.hasPool())
1460- preExistentConnection.closeAsync();
1461- }
1434+
1435+ host.setUp();
1436+
1437+ for (Host.StateListener listener : listeners)
1438+ listener.onUp(host);
1439+ }
1440+
1441+ public void onFailure(Throwable t) {
1442+ // That future is not really supposed to throw unexpected exceptions
1443+ if (!(t instanceof InterruptedException))
1444+ logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1445+ }
1446+ });
1447+
1448+ f.get();
1449+
1450+ // Now, check if there isn't pools to create/remove following the addition.
1451+ // We do that now only so that it's not called before we've set the node up.
1452+ for (SessionManager s : sessions)
1453+ s.updateCreatedPools(blockingExecutor);
14621454 }
14631455
14641456 public ListenableFuture<?> triggerOnDown(final Host host) {
@@ -1509,10 +1501,11 @@
15091501 @Override
15101502 public void runMayThrow() throws InterruptedException, ExecutionException {
15111503 try {
1512- Connection connection = connectionFactory.open(host);
1504+ // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection
1505+ connectionFactory.open(host).closeAsync();
15131506 // Note that we want to do the pool creation on this thread because we want that
15141507 // when onUp return, the host is ready for querying
1515- onUp(host, connection, MoreExecutors.sameThreadExecutor());
1508+ onUp(host, MoreExecutors.sameThreadExecutor());
15161509 } catch (Exception e) {
15171510 onDown(host, false, true);
15181511 }
@@ -1576,6 +1569,7 @@
15761569 if (distance == HostDistance.IGNORED)
15771570 return;
15781571
1572+ // Note: we basically waste the first successful reconnection, but it's probably not a big deal
15791573 logger.debug("{} is down, scheduling connection retries", host);
15801574 startPeriodicReconnectionAttempt(host, isHostAddition);
15811575 }
@@ -1588,16 +1582,19 @@
15881582 }
15891583
15901584 protected void onReconnection(Connection connection) {
1585+ // We don't use that first connection so close it.
1586+ // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1587+ // we use it for the first HostConnectionPool created
1588+ connection.closeAsync();
15911589 // Make sure we have up-to-date infos on that host before adding it (so we typically
15921590 // catch that an upgraded node uses a new cassandra version).
15931591 if (controlConnection.refreshNodeInfo(host)) {
15941592 logger.debug("Successful reconnection to {}, setting host UP", host);
15951593 try {
1596- // We pass the connection to onAdd/onUp so that it can be reused in a pool
15971594 if (isHostAddition)
1598- onAdd(host, connection);
1595+ onAdd(host);
15991596 else
1600- onUp(host, connection);
1597+ onUp(host);
16011598 } catch (InterruptedException e) {
16021599 Thread.currentThread().interrupt();
16031600 } catch (Exception e) {
@@ -1605,7 +1602,6 @@
16051602 }
16061603 } else {
16071604 logger.debug("Not enough info for {}, ignoring host", host);
1608- connection.closeAsync();
16091605 }
16101606 }
16111607
@@ -1642,13 +1638,16 @@
16421638 }
16431639
16441640 protected void onReconnection(Connection connection) {
1641+ // We don't use that first connection so close it.
1642+ // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1643+ // we use it for the first HostConnectionPool created
1644+ connection.closeAsync();
16451645 // Make sure we have up-to-date infos on that host before adding it (so we typically
16461646 // catch that an upgraded node uses a new cassandra version).
16471647 if (controlConnection.refreshNodeInfo(host)) {
16481648 logger.debug("Successful reconnection to {}, setting host UP", host);
16491649 try {
1650- // We pass the connection so that it can be reused in a pool
1651- onUp(host, connection);
1650+ onUp(host);
16521651 } catch (InterruptedException e) {
16531652 Thread.currentThread().interrupt();
16541653 } catch (Exception e) {
@@ -1656,7 +1655,6 @@
16561655 }
16571656 } else {
16581657 logger.debug("Not enough info for {}, ignoring host", host);
1659- connection.closeAsync();
16601658 }
16611659 }
16621660
@@ -1682,96 +1680,91 @@
16821680 return executor.submit(new ExceptionCatchingRunnable() {
16831681 @Override
16841682 public void runMayThrow() throws InterruptedException, ExecutionException {
1685- onAdd(host, null);
1683+ onAdd(host);
16861684 }
16871685 });
16881686 }
16891687
16901688 // Use triggerOnAdd unless you're sure you want to run this on the current thread.
1691- private void onAdd(final Host host, Connection preExistentConnection) throws InterruptedException, ExecutionException {
1689+ private void onAdd(final Host host) throws InterruptedException, ExecutionException {
1690+ if (isClosed())
1691+ return;
1692+
1693+ logger.info("New Cassandra host {} added", host);
1694+
1695+ if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1696+ logUnsupportedVersionProtocol(host);
1697+ return;
1698+ }
1699+
1700+ // Adds to the load balancing first and foremost, as doing so might change the decision
1701+ // it will make for distance() on that node (not likely but we leave that possibility).
1702+ // This does mean the policy may start returning that node for query plan, but as long
1703+ // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1704+ loadBalancingPolicy().onAdd(host);
1705+
1706+ // Next, if the host should be ignored, well, ignore it.
1707+ if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1708+ // We still mark the node UP though as it should be (and notifiy the listeners).
1709+ // We'll mark it down if we have a notification anyway and we've documented that especially
1710+ // for IGNORED hosts, the isUp() method was a best effort guess
1711+ host.setUp();
1712+ for (Host.StateListener listener : listeners)
1713+ listener.onAdd(host);
1714+ return;
1715+ }
1716+
16921717 try {
1693- if (isClosed())
1694- return;
1718+ prepareAllQueries(host);
1719+ } catch (InterruptedException e) {
1720+ Thread.currentThread().interrupt();
1721+ // Don't propagate because we don't want to prevent other listener to run
1722+ } catch (UnsupportedProtocolVersionException e) {
1723+ logUnsupportedVersionProtocol(host);
1724+ return;
1725+ } catch (ClusterNameMismatchException e) {
1726+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1727+ return;
1728+ }
16951729
1696- logger.info("New Cassandra host {} added", host);
1730+ controlConnection.onAdd(host);
16971731
1698- if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
1699- logUnsupportedVersionProtocol(host);
1700- return;
1701- }
1732+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1733+ for (SessionManager s : sessions)
1734+ futures.add(s.maybeAddPool(host, blockingExecutor));
1735+
1736+ // Only mark the node up once all session have added their pool (if the load-balancing
1737+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1738+ // to the node.
1739+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1740+ Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1741+ public void onSuccess(List<Boolean> poolCreationResults) {
1742+ // If any of the creation failed, they will have signaled a connection failure
1743+ // which will trigger a reconnection to the node. So don't bother marking UP.
1744+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1745+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1746+ return;
1747+ }
17021748
1703- // Adds to the load balancing first and foremost, as doing so might change the decision
1704- // it will make for distance() on that node (not likely but we leave that possibility).
1705- // This does mean the policy may start returning that node for query plan, but as long
1706- // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1707- loadBalancingPolicy().onAdd(host);
1708-
1709- // Next, if the host should be ignored, well, ignore it.
1710- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1711- // We still mark the node UP though as it should be (and notifiy the listeners).
1712- // We'll mark it down if we have a notification anyway and we've documented that especially
1713- // for IGNORED hosts, the isUp() method was a best effort guess
17141749 host.setUp();
1750+
17151751 for (Host.StateListener listener : listeners)
17161752 listener.onAdd(host);
1717- return;
17181753 }
17191754
1720- try {
1721- prepareAllQueries(host);
1722- } catch (InterruptedException e) {
1723- Thread.currentThread().interrupt();
1724- // Don't propagate because we don't want to prevent other listener to run
1725- } catch (UnsupportedProtocolVersionException e) {
1726- logUnsupportedVersionProtocol(host);
1727- return;
1728- } catch (ClusterNameMismatchException e) {
1729- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1730- return;
1755+ public void onFailure(Throwable t) {
1756+ // That future is not really supposed to throw unexpected exceptions
1757+ if (!(t instanceof InterruptedException))
1758+ logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
17311759 }
1760+ });
17321761
1733- controlConnection.onAdd(host);
1734-
1735- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1736- for (SessionManager s : sessions)
1737- futures.add(s.maybeAddPool(host, preExistentConnection, blockingExecutor));
1738-
1739- // Only mark the node up once all session have added their pool (if the load-balancing
1740- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1741- // to the node.
1742- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1743- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1744- public void onSuccess(List<Boolean> poolCreationResults) {
1745- // If any of the creation failed, they will have signaled a connection failure
1746- // which will trigger a reconnection to the node. So don't bother marking UP.
1747- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1748- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1749- return;
1750- }
1751-
1752- host.setUp();
1753-
1754- for (Host.StateListener listener : listeners)
1755- listener.onAdd(host);
1756- }
1762+ f.get();
17571763
1758- public void onFailure(Throwable t) {
1759- // That future is not really supposed to throw unexpected exceptions
1760- if (!(t instanceof InterruptedException))
1761- logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1762- }
1763- });
1764-
1765- f.get();
1766-
1767- // Now, check if there isn't pools to create/remove following the addition.
1768- // We do that now only so that it's not called before we've set the node up.
1769- for (SessionManager s : sessions)
1770- s.updateCreatedPools(blockingExecutor);
1771- } finally {
1772- if (preExistentConnection != null && !preExistentConnection.hasPool())
1773- preExistentConnection.closeAsync();
1774- }
1764+ // Now, check if there isn't pools to create/remove following the addition.
1765+ // We do that now only so that it's not called before we've set the node up.
1766+ for (SessionManager s : sessions)
1767+ s.updateCreatedPools(blockingExecutor);
17751768 }
17761769
17771770 public ListenableFuture<?> triggerOnRemove(final Host host) {
@@ -1992,7 +1985,7 @@
19921985 // Make sure we have up-to-date infos on that host before adding it (so we typically
19931986 // catch that an upgraded node uses a new cassandra version).
19941987 if (controlConnection.refreshNodeInfo(newHost)) {
1995- onAdd(newHost, null);
1988+ onAdd(newHost);
19961989 } else {
19971990 logger.debug("Not enough info for {}, ignoring host", newHost);
19981991 }
@@ -2034,7 +2027,7 @@
20342027 // Make sure we have up-to-date infos on that host before adding it (so we typically
20352028 // catch that an upgraded node uses a new cassandra version).
20362029 if (controlConnection.refreshNodeInfo(h)) {
2037- onAdd(h, null);
2030+ onAdd(h);
20382031 } else {
20392032 logger.debug("Not enough info for {}, ignoring host", h);
20402033 }
@@ -2047,7 +2040,7 @@
20472040 // Make sure we have up-to-date infos on that host before adding it (so we typically
20482041 // catch that an upgraded node uses a new cassandra version).
20492042 if (controlConnection.refreshNodeInfo(hostUp)) {
2050- onUp(hostUp, null);
2043+ onUp(hostUp);
20512044 } else {
20522045 logger.debug("Not enough info for {}, ignoring host", hostUp);
20532046 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +7 −66
@@ -19,7 +19,6 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.Iterator;
2121 import java.util.concurrent.*;
22-import java.util.concurrent.atomic.AtomicBoolean;
2322 import java.util.concurrent.atomic.AtomicInteger;
2423 import java.util.concurrent.atomic.AtomicReference;
2524
@@ -74,30 +73,18 @@
7473
7574 private final Object terminationLock = new Object();
7675
77-
78- private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
79-
80- /** The instant when the connection should be trashed after being idle for too long */
81- private volatile long trashTime = Long.MAX_VALUE;
82-
83- /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
84- final AtomicBoolean markForTrash = new AtomicBoolean();
85-
8676 /**
87- * Create a new connection to a Cassandra node and associate it with a pool.
77+ * Create a new connection to a Cassandra node.
8878 *
8979 * The connection is open and initialized by the constructor.
9080 *
91- * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}
92- *
9381 * @throws ConnectionException if the connection attempts fails or is
9482 * refused by the server.
9583 */
96- Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
84+ protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
9785 this.address = address;
9886 this.factory = factory;
9987 this.name = name;
100- this.poolRef.set(pool);
10188
10289 ClientBootstrap bootstrap = factory.newBootstrap();
10390 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
@@ -127,13 +114,6 @@
127114 isInitialized = true;
128115 }
129116
130- /**
131- * Create a new connection to a Cassandra node, and associate it to a connection pool.
132- */
133- Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
134- this(name, address, factory, null);
135- }
136-
137117 private static String extractMessage(Throwable t) {
138118 if (t == null)
139119 return "";
@@ -285,7 +265,7 @@
285265 // We don't want to signal, because that would invoke triggerOnDown unnecessarily (the host's bad
286266 // condition is already taken care of by the reattempt in progress)
287267 boolean isReconnectionAttempt = (host.state == Host.State.DOWN || host.state == Host.State.SUSPECT)
288- && (!this.hasPool());
268+ && !(this instanceof PooledConnection);
289269 if (!isReconnectionAttempt) {
290270 boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized);
291271 notifyOwnerWhenDefunct(isDown);
@@ -301,15 +281,6 @@
301281 }
302282
303283 protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
304- HostConnectionPool pool = this.poolRef.get();
305- if (pool == null)
306- return;
307-
308- if (hostIsDown) {
309- pool.closeAsync().force();
310- } else {
311- pool.replaceDefunctConnection(this);
312- }
313284 }
314285
315286 public String keyspace() {
@@ -425,37 +396,6 @@
425396 };
426397 }
427398
428- boolean hasPool() {
429- return this.poolRef.get() != null;
430- }
431-
432- /** @return whether the connection was already associated with a pool */
433- boolean setPool(HostConnectionPool pool) {
434- return poolRef.compareAndSet(null, pool);
435- }
436-
437- /**
438- * If the connection is part of a pool, return it to the pool.
439- * The connection should generally not be reused after that.
440- */
441- void release() {
442- HostConnectionPool pool = poolRef.get();
443- if (pool != null)
444- pool.returnConnection(this);
445- }
446-
447- long getTrashTime() {
448- return trashTime;
449- }
450-
451- void cancelTrashTime() {
452- trashTime = Long.MAX_VALUE;
453- }
454-
455- void setTrashTimeIn(int timeoutSeconds) {
456- trashTime = System.currentTimeMillis() + 1000 * timeoutSeconds;
457- }
458-
459399 public boolean isClosed() {
460400 return closeFuture.get() != null;
461401 }
@@ -572,14 +512,14 @@
572512 /**
573513 * Same as open, but associate the created connection to the provided connection pool.
574514 */
575- public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
515+ public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
576516 InetSocketAddress address = pool.host.getSocketAddress();
577517
578518 if (isShutdown)
579519 throw new ConnectionException(address, "Connection factory is shut down");
580520
581521 String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
582- return new Connection(name, address, this, pool);
522+ return new PooledConnection(name, address, this, pool);
583523 }
584524
585525 private AtomicInteger getIdGenerator(Host host) {
@@ -894,7 +834,8 @@
894834 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
895835 // of its own answer, and we would have no way to detect that.
896836 connection.dispatcher.removeHandler(streamId, false);
897- connection.release();
837+ if (connection instanceof PooledConnection)
838+ ((PooledConnection)connection).release();
898839 }
899840
900841 private TimerTask onTimeoutTask() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +21 −30
@@ -51,7 +51,7 @@
5151 public volatile HostDistance hostDistance;
5252 private final SessionManager manager;
5353
54- final List<Connection> connections;
54+ final List<PooledConnection> connections;
5555 private final AtomicInteger open;
5656 private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
5757
@@ -65,12 +65,7 @@
6565
6666 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
6767
68- /**
69- * @param preExistentConnection an existing connection (from a reconnection attempt) that we want to
70- * reuse as part of this pool. Might be null or already used by another
71- * pool.
72- */
73- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager, Connection preExistentConnection) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
68+ public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
7469 assert hostDistance != HostDistance.IGNORED;
7570 this.host = host;
7671 this.hostDistance = hostDistance;
@@ -85,26 +80,22 @@
8580 };
8681
8782 // Create initial core connections
88- List<Connection> l = new ArrayList<Connection>(options().getCoreConnectionsPerHost(hostDistance));
83+ List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance));
8984 try {
90- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
91- if (preExistentConnection != null && preExistentConnection.setPool(this))
92- l.add(preExistentConnection);
93- else
94- l.add(manager.connectionFactory().open(this));
95- }
85+ for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
86+ l.add(manager.connectionFactory().open(this));
9687 } catch (InterruptedException e) {
9788 Thread.currentThread().interrupt();
9889 // If asked to interrupt, we can skip opening core connections, the pool will still work.
9990 // But we ignore otherwise cause I'm not sure we can do much better currently.
10091 } catch (RuntimeException e) {
10192 // Rethrow but make sure to properly close the connections in our temporary list.
102- for (Connection connection : l) {
93+ for (PooledConnection connection : l) {
10394 connection.closeAsync().force();
10495 }
10596 throw e;
10697 }
107- this.connections = new CopyOnWriteArrayList<Connection>(l);
98+ this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
10899 this.open = new AtomicInteger(connections.size());
109100
110101 logger.trace("Created connection pool to host {}", host);
@@ -114,7 +105,7 @@
114105 return manager.configuration().getPoolingOptions();
115106 }
116107
117- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
108+ public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
118109 if (isClosed())
119110 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
120111 // That being said, maybe having a specific exception could be cleaner.
@@ -127,14 +118,14 @@
127118 scheduledForCreation.incrementAndGet();
128119 manager.blockingExecutor().submit(newConnectionTask);
129120 }
130- Connection c = waitForConnection(timeout, unit);
121+ PooledConnection c = waitForConnection(timeout, unit);
131122 c.setKeyspace(manager.poolsState.keyspace);
132123 return c;
133124 }
134125
135126 int minInFlight = Integer.MAX_VALUE;
136- Connection leastBusy = null;
137- for (Connection connection : connections) {
127+ PooledConnection leastBusy = null;
128+ for (PooledConnection connection : connections) {
138129 int inFlight = connection.inFlight.get();
139130 if (inFlight < minInFlight) {
140131 minInFlight = inFlight;
@@ -207,7 +198,7 @@
207198 }
208199 }
209200
210- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
201+ private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
211202 if (timeout == 0)
212203 throw new TimeoutException();
213204
@@ -226,8 +217,8 @@
226217 throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
227218
228219 int minInFlight = Integer.MAX_VALUE;
229- Connection leastBusy = null;
230- for (Connection connection : connections) {
220+ PooledConnection leastBusy = null;
221+ for (PooledConnection connection : connections) {
231222 int inFlight = connection.inFlight.get();
232223 if (inFlight < minInFlight) {
233224 minInFlight = inFlight;
@@ -255,7 +246,7 @@
255246 throw new TimeoutException();
256247 }
257248
258- public void returnConnection(Connection connection) {
249+ public void returnConnection(PooledConnection connection) {
259250 if (isClosed()) {
260251 close(connection);
261252 return;
@@ -285,7 +276,7 @@
285276 }
286277
287278 void trashIdleConnections(long now) {
288- for (Connection connection : connections) {
279+ for (PooledConnection connection : connections) {
289280 if (connection.getTrashTime() < now) {
290281 trashConnection(connection);
291282 }
@@ -294,14 +285,14 @@
294285
295286 // Trash the connection and create a new one, but we don't call trashConnection
296287 // directly because we want to make sure the connection is always trashed.
297- private void replaceConnection(Connection connection) {
288+ private void replaceConnection(PooledConnection connection) {
298289 if (connection.markForTrash.compareAndSet(false, true))
299290 open.decrementAndGet();
300291 maybeSpawnNewConnection();
301292 doTrashConnection(connection);
302293 }
303294
304- private boolean trashConnection(Connection connection) {
295+ private boolean trashConnection(PooledConnection connection) {
305296 if (connection.markForTrash.compareAndSet(false, true)) {
306297 // First, make sure we don't go below core connections
307298 for (;;) {
@@ -324,7 +315,7 @@
324315 return true;
325316 }
326317
327- private void doTrashConnection(Connection connection) {
318+ private void doTrashConnection(PooledConnection connection) {
328319 trash.add(connection);
329320 connections.remove(connection);
330321
@@ -393,7 +384,7 @@
393384 manager.blockingExecutor().submit(newConnectionTask);
394385 }
395386
396- void replaceDefunctConnection(final Connection connection) {
387+ void replaceDefunctConnection(final PooledConnection connection) {
397388 if (connection.markForTrash.compareAndSet(false, true))
398389 open.decrementAndGet();
399390 connections.remove(connection);
@@ -440,7 +431,7 @@
440431 return Lists.newArrayList(CloseFuture.immediateFuture());
441432
442433 List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size());
443- for (final Connection connection : connections) {
434+ for (final PooledConnection connection : connections) {
444435 CloseFuture future = connection.closeAsync();
445436 future.addListener(new Runnable() {
446437 public void run() {
added driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +78 −0
@@ -0,0 +1,78 @@
1+/*
2+ * Copyright (C) 2012-2014 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.AtomicBoolean;
20+
21+/**
22+ * A connection that is associated to a pool.
23+ */
24+class PooledConnection extends Connection {
25+
26+ private final HostConnectionPool pool;
27+
28+ /** The instant when the connection should be trashed after being idle for too long */
29+ private volatile long trashTime = Long.MAX_VALUE;
30+
31+ /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
32+ final AtomicBoolean markForTrash = new AtomicBoolean();
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+
67+ long getTrashTime() {
68+ return trashTime;
69+ }
70+
71+ void cancelTrashTime() {
72+ trashTime = Long.MAX_VALUE;
73+ }
74+
75+ void setTrashTimeIn(int timeoutSeconds) {
76+ trashTime = System.currentTimeMillis() + 1000 * timeoutSeconds;
77+ }
78+}
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −3
@@ -117,7 +117,7 @@
117117 if (currentPool == null || currentPool.isClosed())
118118 return false;
119119
120- Connection connection = null;
120+ PooledConnection connection = null;
121121 try {
122122 connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
123123 if (current != null) {
@@ -263,7 +263,8 @@
263263
264264 Host queriedHost = current;
265265 try {
266- connection.release();
266+ if (connection instanceof PooledConnection)
267+ ((PooledConnection)connection).release();
267268
268269 switch (response.type) {
269270 case RESULT:
@@ -521,7 +522,8 @@
521522
522523 Host queriedHost = current;
523524 try {
524- connection.release();
525+ if (connection instanceof PooledConnection)
526+ ((PooledConnection)connection).release();
525527
526528 if (exception instanceof ConnectionException) {
527529 if (metricsEnabled())
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +11 −11
@@ -84,7 +84,7 @@
8484 List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size());
8585 for (Host host : hosts)
8686 if (host.state != Host.State.DOWN)
87- futures.add(maybeAddPool(host, null, executor()));
87+ futures.add(maybeAddPool(host, executor()));
8888 ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
8989 try {
9090 f.get();
@@ -100,7 +100,7 @@
100100 for (Host host : cluster.getMetadata().allHosts()) {
101101 try {
102102 if (host.state != Host.State.DOWN)
103- maybeAddPool(host, null, executor()).get();
103+ maybeAddPool(host, executor()).get();
104104 } catch (ExecutionException e) {
105105 // This is not supposed to happen
106106 throw new DriverInternalError(e);
@@ -214,7 +214,7 @@
214214 }
215215
216216 // Returns whether there was problem creating the pool
217- ListenableFuture<Boolean> forceRenewPool(final Host host, final Connection preExistentConnection, ListeningExecutorService executor) {
217+ ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) {
218218 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
219219 if (distance == HostDistance.IGNORED)
220220 return Futures.immediateFuture(true);
@@ -227,7 +227,7 @@
227227 if (isClosing)
228228 return true;
229229
230- HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this, preExistentConnection);
230+ HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
231231 HostConnectionPool previous = pools.put(host, newPool);
232232 if (previous == null) {
233233 logger.debug("Added connection pool for {}", host);
@@ -255,7 +255,7 @@
255255 // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools
256256 // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we
257257 // want to avoid
258- private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition, Connection preExistentConnection) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
258+ private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
259259 if (isClosing)
260260 return true;
261261
@@ -266,7 +266,7 @@
266266 if (previous != condition)
267267 return false;
268268
269- HostConnectionPool newPool = new HostConnectionPool(host, distance, this, preExistentConnection);
269+ HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
270270 pools.put(host, newPool);
271271
272272 // If we raced with a session shutdown, ensure that the pool will be closed.
@@ -280,7 +280,7 @@
280280 }
281281
282282 // Returns whether there was problem creating the pool
283- ListenableFuture<Boolean> maybeAddPool(final Host host, final Connection preExistentConnection, ListeningExecutorService executor) {
283+ ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) {
284284 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
285285 if (distance == HostDistance.IGNORED)
286286 return Futures.immediateFuture(true);
@@ -298,7 +298,7 @@
298298 if (previous != null && !previous.isClosed())
299299 return true;
300300
301- if (replacePool(host, distance, previous, preExistentConnection)) {
301+ if (replacePool(host, distance, previous)) {
302302 logger.debug("Added connection pool for {}", host);
303303 return true;
304304 }
@@ -346,7 +346,7 @@
346346
347347 if (pool == null) {
348348 if (dist != HostDistance.IGNORED && h.isUp())
349- poolCreationFutures.add(maybeAddPool(h, null, executor));
349+ poolCreationFutures.add(maybeAddPool(h, executor));
350350 } else if (dist != pool.hostDistance) {
351351 if (dist == HostDistance.IGNORED) {
352352 toRemove.add(h);
@@ -379,7 +379,7 @@
379379 try {
380380 if (pool == null) {
381381 if (dist != HostDistance.IGNORED && h.isUp())
382- maybeAddPool(h, null, executor).get();
382+ maybeAddPool(h, executor).get();
383383 } else if (dist != pool.hostDistance) {
384384 if (dist == HostDistance.IGNORED) {
385385 removePool(h).get();
@@ -510,7 +510,7 @@
510510
511511 // Let's not wait too long if we can't get a connection. Things
512512 // will fix themselves once the user tries a query anyway.
513- Connection c = null;
513+ PooledConnection c = null;
514514 try {
515515 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
516516 c.write(new Requests.Prepare(query)).get();
deleted driver-core/src/main/java/com/datastax/driver/core/policies/CloseableAddressTranslater.java +0 −32
@@ -1,32 +0,0 @@
1-/*
2- * Copyright (C) 2012-2014 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.policies;
17-
18-import com.datastax.driver.core.Cluster;
19-
20-/**
21- * Extends {@link AddressTranslater} for implementations that need to free some resources
22- * at {@link Cluster} shutdown.
23- * <p>
24- * Note: the only reason {@link #close()} was not added directly to {@code AddressTranslater}
25- * is backward-compatibility.
26- */
27-public interface CloseableAddressTranslater extends AddressTranslater {
28- /**
29- * Called at {@link Cluster} shutdown.
30- */
31- void close();
32-}
deleted driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.java +0 −139
@@ -1,139 +0,0 @@
1-/*
2- * Copyright (C) 2012-2014 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.policies;
17-
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.util.Enumeration;
21-import java.util.Hashtable;
22-
23-import com.google.common.annotations.VisibleForTesting;
24-import javax.naming.Context;
25-import javax.naming.NamingEnumeration;
26-import javax.naming.NamingException;
27-import javax.naming.directory.Attribute;
28-import javax.naming.directory.Attributes;
29-import javax.naming.directory.DirContext;
30-import javax.naming.directory.InitialDirContext;
31-import org.slf4j.Logger;
32-import org.slf4j.LoggerFactory;
33-
34-import com.datastax.driver.core.exceptions.DriverException;
35-
36-/**
37- * {@link AddressTranslater} implementation for a multi-region EC2 deployment <b>where clients are also deployed in EC2</b>.
38- * <p>
39- * Its distinctive feature is that it translates addresses according to the location of the Cassandra host:
40- * <ul>
41- * <li>addresses in different EC2 regions (than the client) are unchanged;</li>
42- * <li>addresses in the same EC2 region are <b>translated to private IPs</b>.</li>
43- * </ul>
44- * This optimizes network costs, because Amazon charges more for communication over public IPs.
45- *
46- * <p>
47- * Implementation note: this class performs a reverse DNS lookup of the origin address, to find the domain name of the target
48- * instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the private/public switch automatically
49- * based on location.
50- */
51-public class EC2MultiRegionAddressTranslater implements CloseableAddressTranslater {
52-
53- private static final Logger logger = LoggerFactory.getLogger(EC2MultiRegionAddressTranslater.class);
54-
55- // TODO when we switch to Netty 4.1, we can replace this with the Netty built-in DNS client
56- private final DirContext ctx;
57-
58- public EC2MultiRegionAddressTranslater() {
59- Hashtable<Object, Object> env = new Hashtable<Object, Object>();
60- env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
61- try {
62- ctx = new InitialDirContext(env);
63- } catch (NamingException e) {
64- throw new DriverException("Could not create translater", e);
65- }
66- }
67-
68- @Override
69- public InetSocketAddress translate(InetSocketAddress socketAddress) {
70- InetAddress address = socketAddress.getAddress();
71- try {
72- // InetAddress#getHostName() is supposed to perform a reverse DNS lookup, but for some reason it doesn't work
73- // within the same EC2 region (it returns the IP address itself).
74- // We use an alternate implementation:
75- String domainName = lookupPtrRecord(reverse(address));
76- if (domainName == null) {
77- logger.warn("Found no domain name for {}, returning it as-is", address);
78- return socketAddress;
79- }
80-
81- InetAddress translatedAddress = InetAddress.getByName(domainName);
82- logger.debug("Resolved {} to {}", address, translatedAddress);
83- return new InetSocketAddress(translatedAddress, socketAddress.getPort());
84- } catch (Exception e) {
85- logger.warn("Error resolving " + address + ", returning it as-is", e);
86- return socketAddress;
87- }
88- }
89-
90- private String lookupPtrRecord(String reversedDomain) throws Exception {
91- Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{ "PTR" });
92- for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) {
93- Attribute attr = (Attribute)ae.next();
94- for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
95- return vals.nextElement().toString();
96- }
97- return null;
98- }
99-
100- public void close() {
101- try {
102- ctx.close();
103- } catch (NamingException e) {
104- logger.warn("Error closing translater", e);
105- }
106- }
107-
108- // Builds the "reversed" domain name in the ARPA domain to perform the reverse lookup
109- @VisibleForTesting
110- static String reverse(InetAddress address) {
111- byte[] bytes = address.getAddress();
112- if (bytes.length == 4)
113- return reverseIpv4(bytes);
114- else
115- return reverseIpv6(bytes);
116- }
117-
118- private static String reverseIpv4(byte[] bytes) {
119- StringBuilder builder = new StringBuilder();
120- for (int i = bytes.length - 1; i >= 0; i--) {
121- builder.append(bytes[i] & 0xFF).append('.');
122- }
123- builder.append("in-addr.arpa");
124- return builder.toString();
125- }
126-
127- private static String reverseIpv6(byte[] bytes) {
128- StringBuilder builder = new StringBuilder();
129- for (int i = bytes.length - 1; i >= 0; i--) {
130- byte b = bytes[i];
131- int lowNibble = b & 0x0F;
132- int highNibble = b >> 4 & 0x0F;
133- builder.append(Integer.toHexString(lowNibble)).append('.')
134- .append(Integer.toHexString(highNibble)).append('.');
135- }
136- builder.append("ip6.arpa");
137- return builder.toString();
138- }
139-}
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTimeoutTest.java +5 −5
@@ -48,7 +48,7 @@
4848 Host host1 = TestUtils.findHost(cluster, 1);
4949 HostConnectionPool pool = ((SessionManager)session).pools.get(host1);
5050
51- Set<Connection> coreConnections = new HashSet<Connection>();
51+ Set<PooledConnection> coreConnections = new HashSet<PooledConnection>();
5252
5353 // Idle pool: 2 core connections + control connection
5454 assertThat(openConnections.getValue()).isEqualTo(3);
@@ -56,7 +56,7 @@
5656
5757 // Max out the two core connections
5858 for (int i = 0; i < 2 * 128; i++) {
59- Connection connection = pool.borrowConnection(1, TimeUnit.SECONDS);
59+ PooledConnection connection = pool.borrowConnection(1, TimeUnit.SECONDS);
6060 coreConnections.add(connection);
6161 }
6262
@@ -66,7 +66,7 @@
6666 assertThat(createdConnections.get()).isEqualTo(3);
6767
6868 // Borrow one more stream, which should spawn a new connection
69- Connection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS);
69+ PooledConnection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS);
7070 assertThat(coreConnections).doesNotContain(nonCoreConnection);
7171 assertThat(openConnections.getValue()).isEqualTo(4);
7272 assertThat(createdConnections.get()).isEqualTo(4);
@@ -78,7 +78,7 @@
7878 assertThat(createdConnections.get()).isEqualTo(4);
7979
8080 // If we borrow again at this point, it should return the same connection
81- Connection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS);
81+ PooledConnection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS);
8282 assertThat(nonCoreConnection2).isSameAs(nonCoreConnection);
8383 assertThat(openConnections.getValue()).isEqualTo(4);
8484 assertThat(createdConnections.get()).isEqualTo(4);
@@ -99,7 +99,7 @@
9999 assertThat(createdConnections.get()).isEqualTo(4);
100100
101101 // Return all the streams of the core connections, they should not get trashed
102- for (Connection coreConnection : coreConnections)
102+ for (PooledConnection coreConnection : coreConnections)
103103 for (int i = 0; i < 128; i++)
104104 pool.returnConnection(coreConnection);
105105 assertThat(session.getState().getInFlightQueries(host1)).isEqualTo(0);
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +20 −116
@@ -2,7 +2,6 @@
22
33 import java.io.IOException;
44 import java.net.InetSocketAddress;
5-import java.util.Collection;
65 import java.util.Collections;
76 import java.util.Iterator;
87 import java.util.Map;
@@ -14,12 +13,7 @@
1413 import com.google.common.base.Charsets;
1514 import com.google.common.collect.ImmutableMap;
1615 import org.testng.annotations.Test;
17-
1816 import static org.assertj.core.api.Assertions.assertThat;
19-import static org.mockito.Mockito.reset;
20-import static org.mockito.Mockito.spy;
21-import static org.mockito.Mockito.times;
22-import static org.mockito.Mockito.verify;
2317
2418 import com.datastax.driver.core.Host.State;
2519 import com.datastax.driver.core.policies.*;
@@ -39,9 +33,9 @@
3933 ccm = CCMBridge.create("test", 2);
4034 int reconnectionDelay = 1000;
4135 cluster = Cluster.builder()
42- .addContactPoint(CCMBridge.ipOfNode(1))
43- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
44- .build();
36+ .addContactPoint(CCMBridge.ipOfNode(1))
37+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
38+ .build();
4539 cluster.connect();
4640
4741 assertThat(cluster).usesControlHost(1);
@@ -84,11 +78,11 @@
8478 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
8579
8680 cluster = Cluster.builder()
87- .addContactPoint(CCMBridge.ipOfNode(1))
88- // Start with the correct auth so that we can initialize the server
89- .withAuthProvider(authProvider)
90- .withReconnectionPolicy(reconnectionPolicy)
91- .build();
81+ .addContactPoint(CCMBridge.ipOfNode(1))
82+ // Start with the correct auth so that we can initialize the server
83+ .withAuthProvider(authProvider)
84+ .withReconnectionPolicy(reconnectionPolicy)
85+ .build();
9286
9387 cluster.init();
9488 assertThat(cluster).usesControlHost(1);
@@ -128,15 +122,15 @@
128122 CCMBridge ccm = null;
129123 Cluster cluster = null;
130124
131- long reconnectionDelayMillis = 1000;
125+ long reconnectionDelayMillis = 1 * 1000;
132126 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
133127
134128 try {
135129 ccm = CCMBridge.create("test", 2);
136130 cluster = Cluster.builder()
137- .addContactPoint(CCMBridge.ipOfNode(1))
138- .withReconnectionPolicy(reconnectionPolicy)
139- .build();
131+ .addContactPoint(CCMBridge.ipOfNode(1))
132+ .withReconnectionPolicy(reconnectionPolicy)
133+ .build();
140134 cluster.connect();
141135
142136 // Stop a node and cancel the reconnection attempts to it
@@ -169,16 +163,16 @@
169163 CCMBridge ccm = null;
170164 Cluster cluster = null;
171165
172- long reconnectionDelayMillis = 1000;
166+ long reconnectionDelayMillis = 1 * 1000;
173167 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
174168
175169 try {
176170 ccm = CCMBridge.create("test", 1);
177171 cluster = Cluster.builder()
178- .addContactPoint(CCMBridge.ipOfNode(1))
179- .withLoadBalancingPolicy(loadBalancingPolicy)
180- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
181- .build();
172+ .addContactPoint(CCMBridge.ipOfNode(1))
173+ .withLoadBalancingPolicy(loadBalancingPolicy)
174+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
175+ .build();
182176 cluster.connect();
183177
184178 // Tweak the LBP so that the control connection never reconnects, otherwise
@@ -204,7 +198,6 @@
204198 // down for the driver.
205199 ccm.start(1);
206200 ccm.waitForUp(1);
207- assertThat(cluster).host(1).hasState(State.DOWN);
208201
209202 TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
210203 assertThat(cluster).host(1).hasState(State.DOWN);
@@ -221,64 +214,6 @@
221214 }
222215 }
223216
224- /**
225- * The connection established by a successful reconnection attempt should be reused in one of the
226- * connection pools (JAVA-505).
227- */
228- @Test(groups = "long")
229- public void should_use_connection_from_reconnection_in_pool() {
230- CCMBridge ccm = null;
231- Cluster cluster = null;
232-
233- TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
234-
235- // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
236- SocketOptions socketOptions = spy(new SocketOptions());
237-
238- try {
239- ccm = CCMBridge.create("test", 1);
240- cluster = Cluster.builder()
241- .addContactPoint(CCMBridge.ipOfNode(1))
242- .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
243- .withLoadBalancingPolicy(loadBalancingPolicy)
244- .withSocketOptions(socketOptions)
245- .build();
246- // Create two sessions to have multiple pools
247- cluster.connect();
248- cluster.connect();
249-
250- // Right after init, 1 connection has been opened by the control connection, and 2 (core size) for each pool.
251- verify(socketOptions, times(5)).getKeepAlive();
252-
253- // Tweak the LBP so that the control connection never reconnects. This makes it easier
254- // to reason about the number of connection attempts.
255- loadBalancingPolicy.returnEmptyQueryPlan = true;
256-
257- // Stop the node and cancel the reconnection attempts to it
258- ccm.stop(1);
259- ccm.waitForDown(1);
260- assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
261- Host host1 = TestUtils.findHost(cluster, 1);
262- host1.getReconnectionAttemptFuture().cancel(false);
263-
264- ccm.start(1);
265- ccm.waitForUp(1);
266-
267- // Reset the spy and count the number of connections attempts for 1 reconnect
268- reset(socketOptions);
269- host1.tryReconnectOnce();
270- assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
271- // Expect 1 connection from the reconnection attempt + 3 for the pools (we need 4
272- // but the one from the reconnection attempt gets reused).
273- verify(socketOptions, times(4)).getKeepAlive();
274- } finally {
275- if (cluster != null)
276- cluster.close();
277- if (ccm != null)
278- ccm.remove();
279- }
280- }
281-
282217 /**
283218 * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested.
284219 */
@@ -323,9 +258,10 @@
323258 // no-op, the server should send nothing anyway
324259 }
325260
326- @Override Map<String, String> getCredentials() {
261+ @Override
262+ Map<String, String> getCredentials() {
327263 return ImmutableMap.of("username", username,
328- "password", password);
264+ "password", password);
329265 }
330266 }
331267 }
@@ -380,36 +316,4 @@
380316 return super.newQueryPlan(loggedKeyspace, statement);
381317 }
382318 }
383-
384- public static class TryAllPolicy implements LoadBalancingPolicy {
385-
386- private Cluster cluster;
387-
388- @Override public void init(Cluster cluster, Collection<Host> hosts) {
389- this.cluster = cluster;
390- }
391-
392- @Override public HostDistance distance(Host host) {
393- return HostDistance.LOCAL;
394- }
395-
396- @Override public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
397- return cluster.getMetadata().allHosts().iterator();
398- }
399-
400- @Override public void onAdd(Host host) {
401- }
402-
403- @Override public void onUp(Host host) {
404- }
405-
406- @Override public void onSuspected(Host host) {
407- }
408-
409- @Override public void onDown(Host host) {
410- }
411-
412- @Override public void onRemove(Host host) {
413- }
414- }
415319 }
deleted driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslaterTest.java +0 −30
@@ -1,30 +0,0 @@
1-package com.datastax.driver.core.policies;
2-
3-import java.net.InetAddress;
4-import java.net.InetSocketAddress;
5-
6-import org.testng.annotations.Test;
7-
8-import static org.assertj.core.api.Assertions.assertThat;
9-
10-public class EC2MultiRegionAddressTranslaterTest {
11- @Test(groups = "unit")
12- public void should_build_reversed_domain_name_for_ip_v4() throws Exception {
13- InetAddress address = InetAddress.getByName("192.0.2.5");
14- assertThat(
15- EC2MultiRegionAddressTranslater.reverse(address)
16- ).isEqualTo(
17- "5.2.0.192.in-addr.arpa"
18- );
19- }
20-
21- @Test(groups = "unit")
22- public void should_build_reversed_domain_name_for_ip_v6() throws Exception {
23- InetAddress address = InetAddress.getByName("2001:db8::567:89ab");
24- assertThat(
25- EC2MultiRegionAddressTranslater.reverse(address)
26- ).isEqualTo(
27- "b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa"
28- );
29- }
30-}
No newline at the end of the file