Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset0ffa4fe1cebce8ce3574d5d616df84e5e4c07f841bb17c18f91f787af6ffa25b
Authorolim7t <omichallat+github@gmail.com> · 2014-12-15 19:20 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-12-15 19:20 +01:00
Parentsddeff16a1cf4, b1c77be54e84

Browse the files at this changeset

16 files changed

modified driver-core/CHANGELOG.rst +4 −1
@@ -14,6 +14,10 @@
1414 - [bug] Avoid deadlock when multiple connections to the same host get write
1515 errors (JAVA-557)
1616 - [improvement] Make shuffle=true the default for TokenAwarePolicy (JAVA-504)
17+- [bug] Fix bug when SUSPECT reconnection succeeds, but one of the pooled
18+ connections fails while bringing the node back up (JAVA-577)
19+- [bug] Prevent faulty control connection from ignoring reconnecting hosts
20+ (JAVA-587)
1721
1822
1923 2.1.3:
@@ -167,7 +171,6 @@
167171 - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504)
168172 - [improvement] Make schema agreement wait tuneable (JAVA-507)
169173 - [improvement] Document how to inject the driver metrics into another registry (JAVA-494)
170-- [improvement] Add idle timeout to the connection pool (JAVA-419)
171174 - [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516)
172175 - [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with
173176 an explicit but null or empty local datacenter (JAVA-451).
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +17 −20
@@ -26,6 +26,7 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.annotations.VisibleForTesting;
29+import com.google.common.base.Function;
2930 import com.google.common.base.Predicates;
3031 import com.google.common.collect.*;
3132 import com.google.common.util.concurrent.*;
@@ -1281,9 +1282,6 @@
12811282 close();
12821283 throw e;
12831284 }
1284-
1285- if (connectionFactory.protocolVersion.compareTo(ProtocolVersion.V3) < 0)
1286- this.scheduledTasksExecutor.scheduleWithFixedDelay(new TrashIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
12871285 }
12881286
12891287 ProtocolVersion protocolVersion() {
@@ -1539,15 +1537,23 @@
15391537 host.initialReconnectionAttempt.set(executor.submit(new ExceptionCatchingRunnable() {
15401538 @Override
15411539 public void runMayThrow() throws InterruptedException, ExecutionException {
1540+ boolean success;
15421541 try {
15431542 // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection
15441543 connectionFactory.open(host).closeAsync();
15451544 // Note that we want to do the pool creation on this thread because we want that
15461545 // when onUp return, the host is ready for querying
15471546 onUp(host, MoreExecutors.sameThreadExecutor());
1547+ // If one of the connections in onUp failed, it signaled the error and triggerd onDown,
1548+ // but onDown aborted because this reconnection attempt was in progress (JAVA-577).
1549+ // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was
1550+ // executed synchronously).
1551+ success = host.state == Host.State.UP;
15481552 } catch (Exception e) {
1549- onDown(host, false, true);
1553+ success = false;
15501554 }
1555+ if (!success)
1556+ onDown(host, false, true);
15511557 }
15521558 }));
15531559
@@ -1569,19 +1575,23 @@
15691575 if (isClosed())
15701576 return;
15711577
1572- // If we're SUSPECT and not the task validating the suspection, then some other task is
1578+ // If we're SUSPECT and not the task validating the suspicion, then some other task is
15731579 // already checking to verify if the node is really down (or if it's simply that the
15741580 // connections where broken). So just skip this in that case.
1575- if (!isSuspectedVerification && host.state == Host.State.SUSPECT)
1581+ if (!isSuspectedVerification && host.state == Host.State.SUSPECT) {
1582+ logger.debug("Aborting onDown because a reconnection is running on SUSPECT host {}", host);
15761583 return;
1584+ }
15771585
15781586 // Note: we don't want to skip that method if !host.isUp() because we set isUp
15791587 // late in onUp, and so we can rely on isUp if there is an error during onUp.
15801588 // But if there is a reconnection attempt in progress already, then we know
15811589 // we've already gone through that method since the last successful onUp(), so
15821590 // we're good skipping it.
1583- if (host.reconnectionAttempt.get() != null)
1591+ if (host.reconnectionAttempt.get() != null) {
1592+ logger.debug("Aborting onDown because a reconnection is running on DOWN host {}", host);
15841593 return;
1594+ }
15851595
15861596 // Remember if we care about this node at all. We must call this before
15871597 // we've signalled the load balancing policy, since most policy will always
@@ -2225,19 +2235,6 @@
22252235 }).start();
22262236 }
22272237 }
2228-
2229- private class TrashIdleConnectionsTask implements Runnable {
2230- @Override public void run() {
2231- try {
2232- long now = System.currentTimeMillis();
2233- for (SessionManager session : sessions) {
2234- session.trashIdleConnections(now);
2235- }
2236- } catch (Exception e) {
2237- logger.warn("Error while trashing idle connections", e);
2238- }
2239- }
2240- }
22412238 }
22422239
22432240 /**
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +2 −9
@@ -265,15 +265,8 @@
265265 // sure the "suspected" mechanism work as expected
266266 Host host = factory.manager.metadata.getHost(address);
267267 if (host != null) {
268- // If we get an error on a host that was already DOWN or SUSPECTED, this is a reconnection attempt.
269- // We don't want to signal, because that would invoke triggerOnDown unnecessarily (the host's bad
270- // condition is already taken care of by the reattempt in progress)
271- boolean isReconnectionAttempt = (host.state == Host.State.DOWN || host.state == Host.State.SUSPECT)
272- && !(this instanceof PooledConnection);
273- if (!isReconnectionAttempt) {
274- boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized);
275- notifyOwnerWhenDefunct(isDown);
276- }
268+ boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized);
269+ notifyOwnerWhenDefunct(isDown);
277270 }
278271
279272 // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +56 −49
@@ -407,39 +407,23 @@
407407 return cluster.translateAddress(addr);
408408 }
409409
410- private Row fetchNodeInfo(Host host, Connection c) {
411- try {
412- boolean isConnectedHost = c.address.equals(host.getSocketAddress());
413- if (isConnectedHost || host.listenAddress != null) {
414- DefaultResultSetFuture future = isConnectedHost
415- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL))
416- : new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
417- c.write(future);
418- return future.get().one();
419- }
420-
421- // We have to fetch the whole peers table and find the host we're looking for
422- DefaultResultSetFuture future = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS));
410+ private Row fetchNodeInfo(Host host, Connection c) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
411+ boolean isConnectedHost = c.address.equals(host.getSocketAddress());
412+ if (isConnectedHost || host.listenAddress != null) {
413+ DefaultResultSetFuture future = isConnectedHost
414+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL))
415+ : new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
423416 c.write(future);
424- for (Row row : future.get()) {
425- InetSocketAddress addr = addressToUseForPeerHost(row, c.address, cluster, true);
426- if (addr != null && addr.equals(host.getSocketAddress()))
427- return row;
428- }
429- } catch (ConnectionException e) {
430- logger.debug("[Control connection] Connection error while refreshing node info ({})", e.getMessage());
431- signalError();
432- } catch (ExecutionException e) {
433- // If we're being shutdown during refresh, this can happen. That's fine so don't scare the user.
434- if (!isShutdown)
435- logger.debug("[Control connection] Unexpected error while refreshing node info", e);
436- signalError();
437- } catch (BusyConnectionException e) {
438- logger.debug("[Control connection] Connection is busy, reconnecting");
439- signalError();
440- } catch (InterruptedException e) {
441- Thread.currentThread().interrupt();
442- logger.debug("[Control connection] Interrupted while refreshing node list and token map, skipping it.");
417+ return future.get().one();
418+ }
419+
420+ // We have to fetch the whole peers table and find the host we're looking for
421+ DefaultResultSetFuture future = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS));
422+ c.write(future);
423+ for (Row row : future.get()) {
424+ InetSocketAddress addr = addressToUseForPeerHost(row, c.address, cluster, true);
425+ if (addr != null && addr.equals(host.getSocketAddress()))
426+ return row;
443427 }
444428 return null;
445429 }
@@ -455,26 +439,49 @@
455439 return true;
456440
457441 logger.debug("[Control connection] Refreshing node info on {}", host);
458- Row row = fetchNodeInfo(host, c);
459- if (row == null) {
460- if (c.isDefunct()) {
461- logger.debug("Control connection is down, could not refresh node info");
462- // Keep going with what we currently know about the node, otherwise we will ignore all nodes
463- // until the control connection is back up (which leads to a catch-22 if there is only one)
464- return true;
465- } else {
466- logger.error("No row found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress());
442+ try {
443+ Row row = fetchNodeInfo(host, c);
444+ if (row == null) {
445+ if (c.isDefunct()) {
446+ logger.debug("Control connection is down, could not refresh node info");
447+ // Keep going with what we currently know about the node, otherwise we will ignore all nodes
448+ // until the control connection is back up (which leads to a catch-22 if there is only one)
449+ return true;
450+ } else {
451+ logger.error("No row found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress());
452+ return false;
453+ }
454+ // Ignore hosts with a null rpc_address, as this is most likely a phantom row in system.peers (JAVA-428).
455+ // Don't test this for the control host since we're already connected to it anyway, and we read the info from system.local
456+ // which doesn't have an rpc_address column (JAVA-546).
457+ } else if (!c.address.equals(host.getSocketAddress()) && row.getInet("rpc_address") == null) {
458+ logger.error("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress());
467459 return false;
468460 }
469- // Ignore hosts with a null rpc_address, as this is most likely a phantom row in system.peers (JAVA-428).
470- // Don't test this for the control host since we're already connected to it anyway, and we read the info from system.local
471- // which doesn't have an rpc_address column (JAVA-546).
472- } else if (!c.address.equals(host.getSocketAddress()) && row.getInet("rpc_address") == null) {
473- logger.error("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress());
474- return false;
475- }
476461
477- updateInfo(host, row, cluster);
462+ updateInfo(host, row, cluster);
463+ return true;
464+
465+ } catch (ConnectionException e) {
466+ logger.debug("[Control connection] Connection error while refreshing node info ({})", e.getMessage());
467+ signalError();
468+ } catch (ExecutionException e) {
469+ // If we're being shutdown during refresh, this can happen. That's fine so don't scare the user.
470+ if (!isShutdown)
471+ logger.debug("[Control connection] Unexpected error while refreshing node info", e);
472+ signalError();
473+ } catch (BusyConnectionException e) {
474+ logger.debug("[Control connection] Connection is busy, reconnecting");
475+ signalError();
476+ } catch (InterruptedException e) {
477+ Thread.currentThread().interrupt();
478+ logger.debug("[Control connection] Interrupted while refreshing node info, skipping it.");
479+ } catch (Exception e) {
480+ logger.debug("[Control connection] Unexpected error while refreshing node info", e);
481+ signalError();
482+ }
483+ // If we got an exception, always return true. Otherwise a faulty control connection would cause
484+ // reconnected hosts to be ignored permanently.
478485 return true;
479486 }
480487
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +8 −15
@@ -255,25 +255,15 @@
255255 close(connection);
256256 } else {
257257 if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) {
258- connection.setTrashTimeIn(options().getIdleTimeoutSeconds());
258+ trashConnection(connection);
259259 } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
260260 replaceConnection(connection);
261261 } else {
262- connection.cancelTrashTime();
263262 signalAvailableConnection();
264263 }
265264 }
266265 }
267266
268- @Override
269- void trashIdleConnections(long now) {
270- for (PooledConnection connection : connections) {
271- if (connection.getTrashTime() < now) {
272- trashConnection(connection);
273- }
274- }
275- }
276-
277267 // Trash the connection and create a new one, but we don't call trashConnection
278268 // directly because we want to make sure the connection is always trashed.
279269 private void replaceConnection(PooledConnection connection) {
@@ -290,7 +280,6 @@
290280 int opened = open.get();
291281 if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
292282 connection.markForTrash.set(false);
293- connection.cancelTrashTime();
294283 return false;
295284 }
296285
@@ -300,9 +289,13 @@
300289
301290 doTrashConnection(connection);
302291 }
303- // If compareAndSet failed, it means we raced with another thread that will execute doTrashConnection.
304- // Since trashConnection is called from a scheduled task, we're sure that the current thread did not modify
305- // inFlight, so the other thread will take care of closing the connection if necessary (i.e. if inFlight == 0).
292+ // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection.
293+ // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do
294+ // it:
295+ // - the current thread decremented inFlight in returnConnection
296+ // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))`
297+ // in returnConnection and not arrived here.
298+ // - so the other thread will see the up-to-date value of inFlight and take appropriate action.
306299 return true;
307300 }
308301
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +0 −2
@@ -59,8 +59,6 @@
5959
6060 abstract void replaceDefunctConnection(final PooledConnection connection);
6161
62- abstract void trashIdleConnections(long now);
63-
6462 abstract int opened();
6563
6664 abstract int inFlightQueriesCount();
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +1 −16
@@ -25,10 +25,7 @@
2525
2626 private final HostConnectionPool pool;
2727
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 DynamicConnectionPool} to handle races between two threads trying to trash the same connection */
28+ /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
3229 final AtomicBoolean markForTrash = new AtomicBoolean();
3330
3431 PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -63,16 +60,4 @@
6360 pool.replaceDefunctConnection(this);
6461 }
6562 }
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- }
7863 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +0 −31
@@ -58,7 +58,6 @@
5858 private static final int DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL = 1024;
5959 private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256;
6060
61- private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
6261 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
6362
6463 private volatile Cluster.Manager manager;
@@ -73,7 +72,6 @@
7372 private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE;
7473
7574
76- private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
7775 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
7876
7977 public PoolingOptions() {}
@@ -250,35 +248,6 @@
250248 return this;
251249 }
252250
253- /**
254- * Returns the timeout before an idle connection is removed.
255- *
256- * @return the timeout.
257- */
258- public int getIdleTimeoutSeconds() {
259- return idleTimeoutSeconds;
260- }
261-
262- /**
263- * Sets the timeout before an idle connection is removed.
264- * <p>
265- * The order of magnitude should be a few minutes (the default is 120 seconds). The
266- * timeout that triggers the removal has a granularity of 10 seconds.
267- * <p>
268- * This option is only used with {@code ProtocolVersion#V2} or below.
269-
270- * @param idleTimeoutSeconds the new timeout in seconds.
271- * @return this {@code PoolingOptions}.
272- *
273- * @throws IllegalArgumentException if the timeout is negative.
274- */
275- public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) {
276- if (idleTimeoutSeconds < 0)
277- throw new IllegalArgumentException("Idle timeout must be positive");
278- this.idleTimeoutSeconds = idleTimeoutSeconds;
279- return this;
280- }
281-
282251 /**
283252 * Returns the timeout when trying to acquire a connection from a host's pool.
284253 *
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +3 −6
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetAddress;
1819 import java.net.InetSocketAddress;
1920 import java.nio.ByteBuffer;
2021 import java.util.*;
@@ -28,6 +29,8 @@
2829 import org.slf4j.Logger;
2930 import org.slf4j.LoggerFactory;
3031
32+
33+import com.datastax.driver.core.exceptions.AuthenticationException;
3134 import com.datastax.driver.core.exceptions.DriverInternalError;
3235 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3336 import com.datastax.driver.core.policies.LoadBalancingPolicy;
@@ -562,12 +565,6 @@
562565 return future;
563566 }
564567
565- void trashIdleConnections(long now) {
566- for (HostConnectionPool pool : pools.values()) {
567- pool.trashIdleConnections(now);
568- }
569- }
570-
571568 private static class State implements Session.State {
572569
573570 private final SessionManager session;
modified driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +0 −4
@@ -341,10 +341,6 @@
341341 }
342342 }
343343
344- @Override void trashIdleConnections(long now) {
345- // Nothing to do
346- }
347-
348344 @Override
349345 public int opened() {
350346 return open.get() ? 1 : 0;
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +14 −6
@@ -138,7 +138,7 @@
138138
139139 @Test(groups = "long")
140140 public void testRFTwoTokenAware() throws Throwable {
141- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
141+ Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
142142 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
143143 try {
144144
@@ -235,7 +235,7 @@
235235
236236 @Test(groups = "long")
237237 public void testRFThreeTokenAware() throws Throwable {
238- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
238+ Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
239239 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
240240 try {
241241
@@ -424,7 +424,9 @@
424424
425425 @Test(groups = "long")
426426 public void testRFTwoDowngradingCL() throws Throwable {
427- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
427+ Cluster.Builder builder = Cluster.builder()
428+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
429+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
428430 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
429431 try {
430432
@@ -483,7 +485,9 @@
483485
484486 @Test(groups = "long")
485487 public void testRFThreeTokenAwareDowngradingCL() throws Throwable {
486- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
488+ Cluster.Builder builder = Cluster.builder()
489+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
490+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
487491 testRFThreeDowngradingCL(builder);
488492 }
489493
@@ -549,7 +553,9 @@
549553
550554 @Test(groups = "long")
551555 public void testRFThreeDowngradingCLTwoDCs() throws Throwable {
552- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
556+ Cluster.Builder builder = Cluster.builder()
557+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
558+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
553559 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
554560 try {
555561
@@ -646,7 +652,9 @@
646652
647653 @Test(groups = "long")
648654 public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable {
649- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"))).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
655+ Cluster.Builder builder = Cluster.builder()
656+ .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"), false))
657+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
650658 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
651659 try {
652660
deleted driver-core/src/test/java/com/datastax/driver/core/DynamicConnectionPoolTimeoutTest.java +0 −183
@@ -1,183 +0,0 @@
1-package com.datastax.driver.core;
2-
3-import java.net.InetSocketAddress;
4-import java.util.HashSet;
5-import java.util.Set;
6-import java.util.concurrent.TimeUnit;
7-import java.util.concurrent.atomic.AtomicInteger;
8-
9-import com.codahale.metrics.Gauge;
10-import org.testng.annotations.Test;
11-
12-import static org.assertj.core.api.Assertions.assertThat;
13-
14-import com.datastax.driver.core.exceptions.DriverException;
15-import com.datastax.driver.core.exceptions.NoHostAvailableException;
16-
17-public class DynamicConnectionPoolTimeoutTest {
18- @Test(groups = "long")
19- public void should_wait_for_idle_timeout_before_trashing_connections() throws Exception {
20- CCMBridge ccm = null;
21- Cluster cluster = null;
22- try {
23- ccm = CCMBridge.create("test");
24- ccm.populate(1);
25- ccm.updateConfig("authenticator", "PasswordAuthenticator");
26- ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
27-
28- // Hijack the auth provider to be notified each time a connection instance is built
29- CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
30- AtomicInteger createdConnections = authProvider.newAuthenticatorCount;
31-
32- cluster = Cluster.builder()
33- .withProtocolVersion(ProtocolVersion.V2) // force v2 to use dynamic pool
34- .addContactPoint(CCMBridge.ipOfNode(1))
35- .withAuthProvider(authProvider)
36- .build();
37-
38- PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
39- poolingOptions.setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 1);
40- // Set to the max, which makes it slightly easier to reason about when new connections will be created:
41- poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 128);
42- int idleTimeoutSeconds = 10;
43- poolingOptions.setIdleTimeoutSeconds(idleTimeoutSeconds);
44-
45- Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections();
46-
47- Session session = cluster.connect();
48-
49- Host host1 = TestUtils.findHost(cluster, 1);
50- HostConnectionPool pool = ((SessionManager)session).pools.get(host1);
51-
52- Set<PooledConnection> coreConnections = new HashSet<PooledConnection>();
53-
54- // Idle pool: 2 core connections + control connection
55- assertThat(openConnections.getValue()).isEqualTo(3);
56- assertThat(createdConnections.get()).isEqualTo(3);
57-
58- // Max out the two core connections
59- for (int i = 0; i < 2 * 128; i++) {
60- PooledConnection connection = pool.borrowConnection(1, TimeUnit.SECONDS);
61- coreConnections.add(connection);
62- }
63-
64- assertThat(coreConnections).hasSize(2);
65-
66- assertThat(openConnections.getValue()).isEqualTo(3);
67- assertThat(createdConnections.get()).isEqualTo(3);
68-
69- // Borrow one more stream, which should spawn a new connection
70- PooledConnection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS);
71- assertThat(coreConnections).doesNotContain(nonCoreConnection);
72- assertThat(openConnections.getValue()).isEqualTo(4);
73- assertThat(createdConnections.get()).isEqualTo(4);
74-
75- // Return the connection, it should not be trashed immediately
76- pool.returnConnection(nonCoreConnection);
77- TimeUnit.SECONDS.sleep(idleTimeoutSeconds / 2);
78- assertThat(openConnections.getValue()).isEqualTo(4);
79- assertThat(createdConnections.get()).isEqualTo(4);
80-
81- // If we borrow again at this point, it should return the same connection
82- PooledConnection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS);
83- assertThat(nonCoreConnection2).isSameAs(nonCoreConnection);
84- assertThat(openConnections.getValue()).isEqualTo(4);
85- assertThat(createdConnections.get()).isEqualTo(4);
86-
87- // Borrow two more and return 1 to reach inFlight = 2 (above the min). The connection should not be trashed.
88- assertThat(pool.borrowConnection(1, TimeUnit.SECONDS)).isSameAs(nonCoreConnection2);
89- assertThat(pool.borrowConnection(1, TimeUnit.SECONDS)).isSameAs(nonCoreConnection2);
90- pool.returnConnection(nonCoreConnection2); // (we need to return one because we cancel the timeout on return)
91- TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2);
92- assertThat(openConnections.getValue()).isEqualTo(4);
93- assertThat(createdConnections.get()).isEqualTo(4);
94-
95- // Return everything for the non-core connection and wait long enough, it should eventually get trashed
96- pool.returnConnection(nonCoreConnection);
97- pool.returnConnection(nonCoreConnection);
98- TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2);
99- assertThat(openConnections.getValue()).isEqualTo(3);
100- assertThat(createdConnections.get()).isEqualTo(4);
101-
102- // Return all the streams of the core connections, they should not get trashed
103- for (PooledConnection coreConnection : coreConnections)
104- for (int i = 0; i < 128; i++)
105- pool.returnConnection(coreConnection);
106- assertThat(session.getState().getInFlightQueries(host1)).isEqualTo(0);
107-
108- TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2);
109- assertThat(openConnections.getValue()).isEqualTo(3);
110- assertThat(createdConnections.get()).isEqualTo(4);
111-
112- } finally {
113- if (cluster != null)
114- cluster.close();
115- if (ccm != null)
116- ccm.remove();
117- }
118- }
119-
120- @Test(groups = "short")
121- public void should_timeout_immediately_if_pool_timeout_is_zero() throws Exception {
122- CCMBridge ccm = null;
123- Cluster cluster = null;
124- try {
125- ccm = CCMBridge.create("test", 1);
126- cluster = Cluster.builder()
127- .withProtocolVersion(ProtocolVersion.V2) // force v2 to use dynamic pool
128- .addContactPoint(CCMBridge.ipOfNode(1))
129- .build();
130-
131- cluster.getConfiguration().getPoolingOptions()
132- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
133- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
134- .setPoolTimeoutMillis(0);
135-
136- Session session = cluster.connect();
137-
138- Host host1 = TestUtils.findHost(cluster, 1);
139-
140- // Borrow all streams to simulate a busy pool (the timeout doesn't matter here)
141- HostConnectionPool pool = ((SessionManager)session).pools.get(host1);
142- for (int i = 0; i < 128; i++)
143- pool.borrowConnection(1, TimeUnit.SECONDS);
144-
145- boolean threw = false;
146- long beforeQuery = System.nanoTime();
147- try {
148- session.execute("select release_version from system.local");
149- } catch (NoHostAvailableException e) {
150- long afterQuery = System.nanoTime();
151- // This is a bit arbitrary, but we can expect that the time to find out there is no available connection
152- // is less than 20 ms
153- assertThat(afterQuery - beforeQuery).isLessThan(20 * 1000 * 1000);
154- Throwable host1Error = e.getErrors().get(host1.getSocketAddress());
155- assertThat(host1Error).isInstanceOf(DriverException.class);
156- assertThat(host1Error.getMessage()).contains("Timeout while trying to acquire available connection");
157- threw = true;
158- }
159- assertThat(threw).isTrue();
160- } finally {
161- if (cluster != null)
162- cluster.close();
163- if (ccm != null)
164- ccm.remove();
165- }
166- }
167-
168- /**
169- * An auth provider that counts how many authenticators it has returned.
170- */
171- static class CountingAuthProvider extends PlainTextAuthProvider {
172- final AtomicInteger newAuthenticatorCount = new AtomicInteger();
173-
174- public CountingAuthProvider(String username, String password) {
175- super(username, password);
176- }
177-
178- @Override public Authenticator newAuthenticator(InetSocketAddress host) {
179- newAuthenticatorCount.incrementAndGet();
180- return super.newAuthenticator(host);
181- }
182- }
183-}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyTest.java +1 −1
@@ -406,7 +406,7 @@
406406
407407 @Test(groups = "long")
408408 public void tokenAwareWithRF2Test() throws Throwable {
409- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
409+ Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
410410 CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
411411 try {
412412
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +1 −1
@@ -63,7 +63,7 @@
6363 .hasState(State.UP)
6464 .isAtDistance(HostDistance.LOCAL);
6565 assertThat(cluster).host(3)
66- .hasState(State.ADDED)
66+ .hasState(State.UP)
6767 .isAtDistance(HostDistance.IGNORED);
6868 assertThat(session).hasNoPoolFor(3);
6969
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java +21 −33
@@ -13,54 +13,42 @@
1313 @Test(groups = "unit")
1414 public void should_build_default_message_when_less_than_3_errors() {
1515 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3));
16- assertThat(e.getMessage())
17- .isEqualTo("All host(s) tried for query failed (tried: "
18- + "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1), "
19- + "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3), "
20- + "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)"
21- + ")"
22- );
16+ String message = e.getMessage();
17+ assertThat(message).startsWith("All host(s) tried for query failed");
18+ assertThat(message).contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)");
19+ assertThat(message).contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)");
20+ assertThat(message).contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)");
2321 }
2422
2523 @Test(groups = "unit")
2624 public void should_build_default_message_when_more_than_3_errors() {
2725 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(4));
28- assertThat(e.getMessage())
29- .isEqualTo("All host(s) tried for query failed (tried: "
30- + "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1), "
31- + "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3), "
32- + "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2), "
33- + "/127.0.0.4:9042 "
34- + "[only showing errors of first 3 hosts, use getErrors() for more details]"
35- + ")"
36- );
26+ String message = e.getMessage();
27+ assertThat(message).startsWith("All host(s) tried for query failed");
28+ assertThat(message).contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)");
29+ assertThat(message).contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)");
30+ assertThat(message).contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)");
31+ assertThat(message).contains("only showing errors of first 3 hosts, use getErrors() for more details");
3732 }
3833
3934 @Test(groups = "unit")
4035 public void should_build_formatted_message_without_stack_traces() {
4136 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3));
42- assertThat(e.getCustomMessage(3, true, false))
43- .isEqualTo("All host(s) tried for query failed (tried:\n"
44- + "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)\n"
45- + "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)\n"
46- + "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)\n"
47- + ")"
48- );
37+ String message = e.getCustomMessage(3, true, false);
38+ assertThat(message).startsWith("All host(s) tried for query failed (tried:\n");
39+ assertThat(message).contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)\n");
40+ assertThat(message).contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)\n");
41+ assertThat(message).contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)\n");
4942 }
5043
5144 @Test(groups = "unit")
5245 public void should_build_formatted_message_with_stack_traces() {
5346 NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3));
54- assertThat(e.getCustomMessage(3, true, true))
55- .isEqualTo("All host(s) tried for query failed (tried:\n"
56- + "/127.0.0.1:9042\n"
57- + "mock stack trace 1\n\n"
58- + "/127.0.0.3:9042\n"
59- + "mock stack trace 3\n\n"
60- + "/127.0.0.2:9042\n"
61- + "mock stack trace 2\n"
62- + ")"
63- );
47+ String message = e.getCustomMessage(3, true, true);
48+ assertThat(message).startsWith("All host(s) tried for query failed (tried:\n");
49+ assertThat(message).contains("/127.0.0.1:9042\nmock stack trace 1\n");
50+ assertThat(message).contains("/127.0.0.3:9042\nmock stack trace 3\n");
51+ assertThat(message).contains("/127.0.0.2:9042\nmock stack trace 2\n");
6452 }
6553
6654 private static Map<InetSocketAddress, Throwable> buildMockErrors(int count) {
modified driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java +7 −5
@@ -46,11 +46,13 @@
4646 @Override
4747 public void init(Cluster cluster, Collection<Host> hosts) {
4848 this.cluster = cluster;
49- for (Host host : hosts)
50- if (host.isUp())
51- this.liveHosts.add(host);
52- this.delegate.init(cluster, Collections.<Host>emptyList());
53- updateChosenHosts();
49+
50+ Iterator<Host> hostIt = hosts.iterator();
51+ while(hostIt.hasNext() && chosenHosts.size() <= maxHosts - threshold) {
52+ chosenHosts.add(hostIt.next());
53+ }
54+
55+ this.delegate.init(cluster, new ArrayList<Host>(chosenHosts));
5456 }
5557
5658 private void updateChosenHosts() {