Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset793eeb4d04484f4e5738615bfdb5ba646c298b9291a87e37134c66ee451c1ab0
Authorolim7t <omichallat+github@gmail.com> · 2014-10-28 18:31 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-28 21:48 +01:00
Parentsbfcc7c8134a2, 5eeeaae8a97f

Browse the files at this changeset

22 files changed

modified driver-core/CHANGELOG.rst +14 −0
@@ -25,6 +25,13 @@
2525 - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504)
2626 - [improvement] Make schema agreement wait tuneable (JAVA-507)
2727 - [improvement] Document how to inject the driver metrics into another registry (JAVA-494)
28+- [improvement] Add idle timeout to the connection pool (JAVA-419)
29+- [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516)
30+- [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with
31+ an explicit but null or empty local datacenter (JAVA-451).
32+- [bug] Fix check for local contact points in DCAware policy's init (JAVA-511)
33+- [improvement] Make timeout on saturated pool customizable (JAVA-457)
34+- [improvement] Downgrade Guava to 14.0.1 (JAVA-521)
2835
2936
3037 2.1.2:
@@ -133,6 +140,13 @@
133140 - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504)
134141 - [improvement] Make schema agreement wait tuneable (JAVA-507)
135142 - [improvement] Document how to inject the driver metrics into another registry (JAVA-494)
143+- [improvement] Add idle timeout to the connection pool (JAVA-419)
144+- [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516)
145+- [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with
146+ an explicit but null or empty local datacenter (JAVA-451).
147+- [bug] Fix check for local contact points in DCAware policy's init (JAVA-511)
148+- [improvement] Make timeout on saturated pool customizable (JAVA-457)
149+- [improvement] Downgrade Guava to 14.0.1 (JAVA-521)
136150
137151
138152 2.0.6:
modified driver-core/pom.xml +5 −1
@@ -36,7 +36,11 @@
3636 <dependency>
3737 <groupId>com.google.guava</groupId>
3838 <artifactId>guava</artifactId>
39- <version>16.0.1</version>
39+ <!--
40+ We use an old version of Guava to be compatible with Spark 1.1.
41+ Check with the spark-cassandra-connector team before upgrading this.
42+ -->
43+ <version>14.0.1</version>
4044 </dependency>
4145
4246 <dependency>
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +22 −14
@@ -26,6 +26,16 @@
2626 import com.datastax.driver.core.exceptions.AuthenticationException;
2727 import com.datastax.driver.core.policies.ReconnectionPolicy;
2828
29+/**
30+ * Manages periodic reconnection attempts after a host has been marked down.
31+ * <p>
32+ * Concurrent attempts are handled via the {@link #currentAttempt} reference passed to the constructor.
33+ * For a given reference, only one handler will run at a given time. Additional handlers will cancel
34+ * themselves if they find a previous handler running.
35+ * <p>
36+ * This class is designed for concurrency, but instances must not be shared: each thread creates and
37+ * starts its own private handler, all interactions happen through {@link #currentAttempt}.
38+ */
2939 abstract class AbstractReconnectionHandler implements Runnable {
3040
3141 private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandler.class);
@@ -41,7 +51,7 @@
4151
4252 private final long initialDelayMs;
4353
44- private volatile boolean isActive;
54+ private final CountDownLatch ready = new CountDownLatch(1);
4555
4656 public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt) {
4757 this(executor, schedule, currentAttempt, -1);
@@ -79,14 +89,14 @@
7989 if (previous != null && !previous.isCancelled()) {
8090 logger.debug("Found another already active handler, cancelling");
8191 handlerFuture.cancel(false);
82- return;
92+ break;
8393 }
8494 if (currentAttempt.compareAndSet(previous, handlerFuture)) {
8595 logger.debug("Becoming the active handler");
8696 break;
8797 }
8898 }
89- isActive = true;
99+ ready.countDown();
90100 } catch (RejectedExecutionException e) {
91101 // The executor has been shutdown, fair enough, just ignore
92102 logger.debug("Aborting reconnection handling since the cluster is shutting down");
@@ -95,23 +105,21 @@
95105
96106 @Override
97107 public void run() {
108+ // Just make sure we don't start the first try too fast, in case we find out in start() that we need to cancel ourselves
109+ try {
110+ ready.await();
111+ } catch (InterruptedException e) {
112+ // This can happen at shutdown
113+ Thread.currentThread().interrupt();
114+ return;
115+ }
116+
98117 if (handlerFuture.isCancelled()) {
99118 logger.debug("Got cancelled, stopping");
100119 currentAttempt.compareAndSet(handlerFuture, null);
101120 return;
102121 }
103122
104- // Just make sure we don't start the first try too fast, in case we find out in start() that we need to cancel ourselves
105- while (!isActive && !Thread.currentThread().isInterrupted()) {
106- try {
107- TimeUnit.MILLISECONDS.sleep(5);
108- } catch (InterruptedException e) {
109- // This can happen at shutdown
110- Thread.currentThread().interrupt();
111- return;
112- }
113- }
114-
115123 try {
116124 onReconnection(tryReconnect());
117125 handlerFuture.markAsDone();
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +27 −13
@@ -1208,12 +1208,9 @@
12081208 metadata.add(address);
12091209 }
12101210
1211- // Make a copy of the hosts - which only contain the contact points at this stage - before we initialize the
1212- // control connection. We use a set with guaranteed insertion order, so that the contact points will remain
1213- // first, before any other host discovered by the control connection.
1214- // This is important if the load balancing policy is the DCAware one, because it needs to see the contact points
1215- // first for the local DC detection to work properly.
1216- Set<Host> hosts = Sets.newLinkedHashSet(metadata.allHosts());
1211+ // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init().
1212+ // But the control connection will initialize first and discover more hosts, so make a copy.
1213+ Set<Host> contactPointHosts = Sets.newHashSet(metadata.allHosts());
12171214
12181215 try {
12191216 try {
@@ -1229,21 +1226,25 @@
12291226 }
12301227 }
12311228
1232- // metadata now also contains other hosts discovered by the connection, update our copy
1233- hosts.addAll(metadata.allHosts());
1234-
12351229 // Now that the control connection is ready, we have all the information we need about the nodes (datacenter,
12361230 // rack...) to initialize the load balancing policy
1237- loadBalancingPolicy().init(Cluster.this, hosts);
1238-
1231+ loadBalancingPolicy().init(Cluster.this, contactPointHosts);
1232+ // Add the remaining hosts that were discovered by the control connection:
1233+ for (Host host : metadata.allHosts()) {
1234+ if (!contactPointHosts.contains(host))
1235+ loadBalancingPolicy().onAdd(host);
1236+ }
12391237 isFullyInit = true;
12401238
1241- for (Host host : hosts)
1239+ for (Host host : metadata.allHosts())
12421240 triggerOnAdd(host);
12431241 } catch (NoHostAvailableException e) {
12441242 close();
12451243 throw e;
12461244 }
1245+
1246+ if (connectionFactory.protocolVersion.compareTo(ProtocolVersion.V3) < 0)
1247+ this.scheduledTasksExecutor.scheduleWithFixedDelay(new TrashIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
12471248 }
12481249
12491250 ProtocolVersion protocolVersion() {
@@ -2140,6 +2141,19 @@
21402141 }).start();
21412142 }
21422143 }
2144+
2145+ private class TrashIdleConnectionsTask implements Runnable {
2146+ @Override public void run() {
2147+ try {
2148+ long now = System.currentTimeMillis();
2149+ for (SessionManager session : sessions) {
2150+ session.trashIdleConnections(now);
2151+ }
2152+ } catch (Exception e) {
2153+ logger.warn("Error while trashing idle connections", e);
2154+ }
2155+ }
2156+ }
21432157 }
21442158
21452159 /**
@@ -2153,7 +2167,7 @@
21532167 private static final int INTERVAL_MS = 15000;
21542168
21552169 private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory("Reaper-%d"));
2156- private final Set<Connection> connections = Sets.newConcurrentHashSet();
2170+ private final Set<Connection> connections = Sets.newSetFromMap(new ConcurrentHashMap<Connection, Boolean>());
21572171
21582172 private volatile boolean shutdown;
21592173
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +2 −2
@@ -74,6 +74,7 @@
7474 if (isShutdown)
7575 return;
7676
77+ // NB: at this stage, allHosts() only contains the initial contact points
7778 setNewConnection(reconnectInternal(cluster.metadata.allHosts().iterator(), true));
7879 }
7980
@@ -160,8 +161,7 @@
160161 Connection connection = connectionRef.get();
161162 if (connection != null && connection.isDefunct()) {
162163 // If the connection was marked as defunct, this already reported the
163- // node down, which will trigger a reconnect. Otherwise, just reconnect
164- // manually
164+ // node down, which will trigger a reconnect.
165165 return;
166166 }
167167 // If the connection is not defunct, or the host has left, just reconnect manually
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +18 −8
@@ -188,6 +188,9 @@
188188 }
189189
190190 private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
191+ if (timeout == 0)
192+ throw new TimeoutException();
193+
191194 long start = System.nanoTime();
192195 long remaining = timeout;
193196 do {
@@ -252,15 +255,25 @@
252255 close(connection);
253256 } else {
254257 if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) {
255- trashConnection(connection);
258+ connection.setTrashTimeIn(options().getIdleTimeoutSeconds());
256259 } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
257260 replaceConnection(connection);
258261 } else {
262+ connection.cancelTrashTime();
259263 signalAvailableConnection();
260264 }
261265 }
262266 }
263267
268+ @Override
269+ void trashIdleConnections(long now) {
270+ for (PooledConnection connection : connections) {
271+ if (connection.getTrashTime() < now) {
272+ trashConnection(connection);
273+ }
274+ }
275+ }
276+
264277 // Trash the connection and create a new one, but we don't call trashConnection
265278 // directly because we want to make sure the connection is always trashed.
266279 private void replaceConnection(PooledConnection connection) {
@@ -277,6 +290,7 @@
277290 int opened = open.get();
278291 if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
279292 connection.markForTrash.set(false);
293+ connection.cancelTrashTime();
280294 return false;
281295 }
282296
@@ -286,13 +300,9 @@
286300
287301 doTrashConnection(connection);
288302 }
289- // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection.
290- // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do
291- // it:
292- // - the current thread decremented inFlight in returnConnection
293- // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))`
294- // in returnConnection and not arrived here.
295- // - so the other thread will see the up-to-date value of inFlight and take appropriate action.
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).
296306 return true;
297307 }
298308
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +2 −0
@@ -59,6 +59,8 @@
5959
6060 abstract void replaceDefunctConnection(final PooledConnection connection);
6161
62+ abstract void trashIdleConnections(long now);
63+
6264 abstract int opened();
6365
6466 abstract int inFlightQueriesCount();
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +1 −1
@@ -93,7 +93,7 @@
9393 * com.codahale.metrics.CsvReporter.forRegistry(metrics.getRegistry()).build(new File("measurements/")).start(1, TimeUnit.SECONDS);
9494 * </pre>
9595 * <p>
96- * If you already have a {@code MetricRegistry} in your application and which to
96+ * If you already have a {@code MetricRegistry} in your application and wish to
9797 * add the driver's metrics to it, the recommended approach is to use a listener:
9898 * <pre>
9999 * // Your existing registry:
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +15 −0
@@ -25,6 +25,9 @@
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+
2831 /** Used in {@link DynamicConnectionPool} to handle races between two threads trying to trash the same connection */
2932 final AtomicBoolean markForTrash = new AtomicBoolean();
3033
@@ -60,4 +63,16 @@
6063 pool.replaceDefunctConnection(this);
6164 }
6265 }
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+ }
6378 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +64 −0
@@ -58,6 +58,9 @@
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;
62+ private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
63+
6164 private volatile Cluster.Manager manager;
6265
6366 private final int[] minSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MIN_REQUESTS_PER_CONNECTION, DEFAULT_MIN_REQUESTS_PER_CONNECTION, 0 };
@@ -70,6 +73,9 @@
7073 private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE;
7174
7275
76+ private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
77+ private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
78+
7379 public PoolingOptions() {}
7480
7581 void register(Cluster.Manager manager) {
@@ -244,6 +250,64 @@
244250 return this;
245251 }
246252
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+
282+ /**
283+ * Returns the timeout when trying to acquire a connection from a host's pool.
284+ *
285+ * @return the timeout.
286+ */
287+ public int getPoolTimeoutMillis() {
288+ return poolTimeoutMillis;
289+ }
290+
291+ /**
292+ * Sets the timeout when trying to acquire a connection from a host's pool.
293+ * <p>
294+ * If no connection is available within that time, the driver will try the
295+ * next host from the query plan.
296+ * <p>
297+ * If this option is set to zero, the driver won't wait at all.
298+ *
299+ * @param poolTimeoutMillis the new value in milliseconds.
300+ * @return this {@code PoolingOptions}
301+ *
302+ * @throws IllegalArgumentException if the timeout is negative.
303+ */
304+ public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
305+ if (poolTimeoutMillis < 0)
306+ throw new IllegalArgumentException("Pool timeout must be positive");
307+ this.poolTimeoutMillis = poolTimeoutMillis;
308+ return this;
309+ }
310+
247311 /**
248312 * Returns the maximum number of requests per host.
249313 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +13 −9
@@ -57,6 +57,12 @@
5757 private volatile HostConnectionPool currentPool;
5858 private final AtomicReference<QueryState> queryStateRef;
5959
60+ // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from
61+ // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an
62+ // OVERLOADED error).
63+ // This is incremented by one writer at a time, so volatile is good enough.
64+ private volatile int retriesByPolicy;
65+
6066 private volatile ConsistencyLevel retryConsistencyLevel;
6167
6268 private volatile Map<InetSocketAddress, Throwable> errors;
@@ -113,9 +119,7 @@
113119
114120 PooledConnection connection = null;
115121 try {
116- // Note: this is not perfectly correct to use getConnectTimeoutMillis(), but
117- // until we provide a more fancy to control query timeouts, it's not a bad solution either
118- connection = currentPool.borrowConnection(manager.configuration().getSocketOptions().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
122+ connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
119123 if (current != null) {
120124 if (triedHosts == null)
121125 triedHosts = new ArrayList<Host>();
@@ -134,8 +138,7 @@
134138 return false;
135139 } catch (BusyConnectionException e) {
136140 // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
137- if (connection != null)
138- connection.release();
141+ connection.release();
139142 logError(host.getSocketAddress(), e);
140143 return false;
141144 } catch (TimeoutException e) {
@@ -295,7 +298,7 @@
295298 rte.getRequiredAcknowledgements(),
296299 rte.getReceivedAcknowledgements(),
297300 rte.wasDataRetrieved(),
298- retryCount);
301+ retriesByPolicy);
299302
300303 if (metricsEnabled()) {
301304 if (retry.getType() == Type.RETRY)
@@ -315,7 +318,7 @@
315318 wte.getWriteType(),
316319 wte.getRequiredAcknowledgements(),
317320 wte.getReceivedAcknowledgements(),
318- retryCount);
321+ retriesByPolicy);
319322
320323 if (metricsEnabled()) {
321324 if (retry.getType() == Type.RETRY)
@@ -334,7 +337,7 @@
334337 ue.getConsistencyLevel(),
335338 ue.getRequiredReplicas(),
336339 ue.getAliveReplicas(),
337- retryCount);
340+ retriesByPolicy);
338341
339342 if (metricsEnabled()) {
340343 if (retry.getType() == Type.RETRY)
@@ -419,8 +422,9 @@
419422 else {
420423 switch (retry.getType()) {
421424 case RETRY:
425+ ++retriesByPolicy;
422426 if (logger.isDebugEnabled())
423- logger.debug("Doing retry {} for query {} at consistency {}", retryCount, statement, retry.getRetryConsistencyLevel());
427+ logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel());
424428 if (metricsEnabled())
425429 metrics().getErrorMetrics().getRetries().inc();
426430 retry(true, retry.getRetryConsistencyLevel());
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +6 −0
@@ -521,6 +521,12 @@
521521 return future;
522522 }
523523
524+ void trashIdleConnections(long now) {
525+ for (HostConnectionPool pool : pools.values()) {
526+ pool.trashIdleConnections(now);
527+ }
528+ }
529+
524530 private static class State implements Session.State {
525531
526532 private final SessionManager session;
modified driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +7 −0
@@ -156,6 +156,9 @@
156156 }
157157
158158 private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
159+ if (timeout == 0)
160+ throw new TimeoutException();
161+
159162 long start = System.nanoTime();
160163 long remaining = timeout;
161164 do {
@@ -338,6 +341,10 @@
338341 }
339342 }
340343
344+ @Override void trashIdleConnections(long now) {
345+ // Nothing to do
346+ }
347+
341348 @Override
342349 public int opened() {
343350 return open.get() ? 1 : 0;
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +3 −1
@@ -200,6 +200,8 @@
200200 } else if (!dc.equals(localDc))
201201 notInLocalDC.add(String.format("%s (%s)", host.toString(), dc));
202202
203+ if (!dc.equals(localDc)) notInLocalDC.add(String.format("%s (%s)", host.toString(), host.getDatacenter()));
204+
203205 CopyOnWriteArrayList<Host> prev = perDcLiveHosts.get(dc);
204206 if (prev == null)
205207 perDcLiveHosts.put(dc, new CopyOnWriteArrayList<Host>(Collections.singletonList(host)));
@@ -209,7 +211,7 @@
209211
210212 if (notInLocalDC.size() > 0) {
211213 String nonLocalHosts = Joiner.on(",").join(notInLocalDC);
212- logger.warn("Some contact points don't match specified local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts);
214+ logger.warn("Some contact points don't match local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts);
213215 }
214216 }
215217
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +12 −7
@@ -23,6 +23,7 @@
2323 // Since we don't open any session from our Cluster, only the control connection reattempts are calling this
2424 // method, therefore the invocation count is equal to the number of attempts.
2525 QueryPlanCountingPolicy loadBalancingPolicy = new QueryPlanCountingPolicy(Policies.defaultLoadBalancingPolicy());
26+ AtomicInteger reconnectionAttempts = loadBalancingPolicy.counter;
2627
2728 // Custom reconnection policy with a very large delay (longer than the test duration), to make sure we count
2829 // only the first reconnection attempt of each reconnection handler.
@@ -39,18 +40,23 @@
3940 };
4041
4142 try {
42- ccm = CCMBridge.create("test", 1);
43+ ccm = CCMBridge.create("test", 2);
44+ // We pass only the first host as contact point, so we know the control connection will be on this host
4345 cluster = Cluster.builder()
44- .addContactPoint(CCMBridge.ipOfNode(1))
45- .withReconnectionPolicy(reconnectionPolicy)
46- .withLoadBalancingPolicy(loadBalancingPolicy)
47- .build();
46+ .addContactPoint(CCMBridge.ipOfNode(1))
47+ .withReconnectionPolicy(reconnectionPolicy)
48+ .withLoadBalancingPolicy(loadBalancingPolicy)
49+ .build();
4850 cluster.init();
4951
52+ // Kill the control connection host, there should be exactly one reconnection attempt
5053 ccm.stop(1);
54+ TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing
55+ assertThat(reconnectionAttempts.get()).isEqualTo(1);
5156
52- // Sleep for a while to make sure our final count is not the result of lucky timing
57+ ccm.stop(2);
5358 TimeUnit.SECONDS.sleep(1);
59+ assertThat(reconnectionAttempts.get()).isEqualTo(2);
5460
5561 } finally {
5662 if (cluster != null)
@@ -58,7 +64,6 @@
5864 if (ccm != null)
5965 ccm.remove();
6066 }
61- assertThat(loadBalancingPolicy.counter.get()).isEqualTo(1);
6267 }
6368
6469 /**
added driver-core/src/test/java/com/datastax/driver/core/DynamicConnectionPoolTimeoutTest.java +183 −0
@@ -0,0 +1,183 @@
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/HostAssert.java +12 −24
@@ -1,5 +1,6 @@
11 package com.datastax.driver.core;
22
3+import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicBoolean;
56
@@ -32,24 +33,18 @@
3233 }
3334
3435 public HostAssert comesUpWithin(long duration, TimeUnit unit) {
35- final AtomicBoolean notification = new AtomicBoolean();
36+ final CountDownLatch upSignal = new CountDownLatch(1);
3637 StateListener upListener = new StateListenerBase() {
3738 public void onUp(Host host) {
38- notification.set(true);
39- };
39+ upSignal.countDown();
40+ }
4041 };
4142 cluster.register(upListener);
4243 try {
43- // Make sure the host did not come up while we were installing the listener
44- if (actual.isUp())
44+ // If the host is already up or if we receive the UP signal within given time
45+ if (actual.isUp() || upSignal.await(duration, unit)) {
4546 return this;
46-
47- long maxTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(duration, unit);
48- do {
49- TimeUnit.SECONDS.sleep(10);
50- if (notification.get())
51- return this;
52- } while (System.nanoTime() < maxTime);
47+ }
5348 } catch (InterruptedException e) {
5449 fail("Got interrupted while waiting for host to come up");
5550 } finally {
@@ -60,24 +55,17 @@
6055 }
6156
6257 public HostAssert goesDownWithin(long duration, TimeUnit unit) {
63- final AtomicBoolean notification = new AtomicBoolean();
58+ final CountDownLatch downSignal = new CountDownLatch(1);
6459 StateListener upListener = new StateListenerBase() {
6560 public void onDown(Host host) {
66- notification.set(true);
67- };
61+ downSignal.countDown();
62+ }
6863 };
6964 cluster.register(upListener);
7065 try {
71- // Make sure the host did not go down while we were installing the listener
72- if (actual.state == State.DOWN)
66+ // If the host is already down or if we receive the DOWN signal within given time
67+ if (actual.state == State.DOWN || downSignal.await(duration, unit))
7368 return this;
74-
75- long maxTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(duration, unit);
76- do {
77- TimeUnit.SECONDS.sleep(10);
78- if (notification.get())
79- return this;
80- } while (System.nanoTime() < maxTime);
8169 } catch (InterruptedException e) {
8270 fail("Got interrupted while waiting for host to go down");
8371 } finally {
added driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +25 −0
@@ -0,0 +1,25 @@
1+package com.datastax.driver.core;
2+
3+import java.io.StringWriter;
4+
5+import org.apache.log4j.PatternLayout;
6+import org.apache.log4j.WriterAppender;
7+
8+/**
9+ * Simple Log4J appender that captures logs to memory in order to inspect them in unit tests.
10+ * <p>
11+ * There is no purging mechanism, so make sure it doesn't stay enabled for too long (this is best
12+ * done with an {@code @After} method that removes it).
13+ */
14+public class MemoryAppender extends WriterAppender {
15+ public final StringWriter writer = new StringWriter();
16+
17+ public MemoryAppender() {
18+ setWriter(writer);
19+ setLayout(new PatternLayout("%m%n"));
20+ }
21+
22+ public String get() {
23+ return writer.toString();
24+ }
25+}
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +1 −1
@@ -69,7 +69,7 @@
6969
7070 // Kill host 2, host 3 should take its place
7171 ccm.stop(2);
72- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
72+ TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster, 120);
7373
7474 assertThat(cluster).host(1)
7575 .hasState(State.UP)
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +162 −18
@@ -1,42 +1,186 @@
11 package com.datastax.driver.core.policies;
22
3-import org.testng.annotations.Test;
3+import java.util.Collection;
4+import java.util.Set;
5+import java.util.concurrent.CopyOnWriteArraySet;
6+
7+import org.apache.log4j.Level;
8+import org.apache.log4j.Logger;
9+import org.testng.annotations.*;
10+
11+import static org.assertj.core.api.Assertions.assertThat;
412 import static org.testng.Assert.assertEquals;
513
6-import com.datastax.driver.core.CCMBridge;
7-import com.datastax.driver.core.Cluster;
8-import com.datastax.driver.core.Host;
9-import com.datastax.driver.core.TestUtils;
14+import com.datastax.driver.core.*;
1015
1116 public class DCAwareRoundRobinPolicyTest {
17+ MemoryAppender logs;
18+ CCMBridge ccm;
19+
20+ @BeforeClass(groups = "short")
21+ public void createCcm() {
22+ // Two-DC cluster with one host in each DC
23+ ccm = CCMBridge.create("test", 1, 1);
24+ }
25+
26+ @AfterClass(groups = "short")
27+ public void deleteCcm() {
28+ if (ccm != null)
29+ ccm.remove();
30+ }
31+
32+ @BeforeMethod(groups = "short")
33+ public void startRecordingLogs() {
34+ Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class);
35+ assertThat(Level.WARN.isGreaterOrEqual(policyLogger.getEffectiveLevel()))
36+ .isTrue()
37+ .as("Log level must be at least WARN for this test to work");
38+
39+ logs = new MemoryAppender();
40+ policyLogger.addAppender(logs);
41+ }
42+
43+ @AfterMethod(groups = "short")
44+ public void stopRecordingLogs() {
45+ Logger.getLogger(DCAwareRoundRobinPolicy.class).removeAppender(logs);
46+ }
1247
1348 @Test(groups = "short")
14- public void should_pick_local_dc_from_contact_points() {
15- CCMBridge ccm = null;
49+ public void should_use_local_dc_from_contact_points_when_not_explicitly_specified() {
1650 Cluster cluster = null;
17- DCAwareRoundRobinPolicy policy;
51+ CountingDCAwarePolicy policy = new CountingDCAwarePolicy();
1852
1953 try {
20- // Create two-DC cluster with one host in each DC
21- ccm = CCMBridge.create("test", 1, 1);
22- policy = new DCAwareRoundRobinPolicy();
23-
2454 // Pass host1 as contact point
2555 cluster = Cluster.builder()
26- .addContactPoint(CCMBridge.ipOfNode(1))
27- .withLoadBalancingPolicy(policy)
28- .build();
56+ .addContactPoint(CCMBridge.ipOfNode(1))
57+ .withLoadBalancingPolicy(policy)
58+ .build();
2959 cluster.init();
3060
61+ Host host1 = TestUtils.findHost(cluster, 1);
62+
3163 // Policy's localDC should be the one from the contact point
64+ assertThat(policy.getLocalDc()).isEqualTo(host1.getDatacenter());
65+
66+ assertThat(policy.initHosts).containsExactly(host1);
67+
68+ assertThat(logs.get())
69+ .doesNotContain("Some contact points don't match local data center");
70+
71+ } finally {
72+ if (cluster != null)
73+ cluster.close();
74+ }
75+ }
76+
77+ @Test(groups = "short")
78+ public void should_warn_if_contact_points_have_different_dcs_when_not_explicitly_specified() {
79+ Cluster cluster = null;
80+ CountingDCAwarePolicy policy = new CountingDCAwarePolicy();
81+
82+ try {
83+ // Pass both hosts as contact points, they have different DCs
84+ cluster = Cluster.builder()
85+ .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
86+ .withLoadBalancingPolicy(policy)
87+ .build();
88+ cluster.init();
89+
90+ Host host1 = TestUtils.findHost(cluster, 1);
91+ Host host2 = TestUtils.findHost(cluster, 2);
92+
93+ assertThat(policy.initHosts).containsOnly(host1, host2);
94+
95+ assertThat(logs.get())
96+ .contains("Some contact points don't match local data center");
97+
98+ } finally {
99+ if (cluster != null)
100+ cluster.close();
101+ }
102+ }
103+
104+ @Test(groups = "short")
105+ public void should_use_provided_local_dc_and_not_warn_if_contact_points_match() {
106+ Cluster cluster = null;
107+ String providedLocalDc = "dc1";
108+ CountingDCAwarePolicy policy = new CountingDCAwarePolicy(providedLocalDc);
109+
110+ try {
111+ cluster = Cluster.builder()
112+ .addContactPoints(CCMBridge.ipOfNode(1))
113+ .withLoadBalancingPolicy(policy)
114+ .build();
115+ cluster.init();
116+
117+ Host host1 = TestUtils.findHost(cluster, 1);
118+
119+ assertEquals(policy.getLocalDc(), providedLocalDc);
120+
121+ assertThat(policy.initHosts).containsExactly(host1);
122+
123+ assertThat(logs.get())
124+ .doesNotContain("Some contact points don't match local data center");
125+
126+ } finally {
127+ if (cluster != null)
128+ cluster.close();
129+ }
130+ }
131+
132+ @Test(groups = "short")
133+ public void should_use_provided_local_dc_and_warn_if_contact_points_dont_match() {
134+ Cluster cluster = null;
135+ // Provide non-existent DC to make sure none of the contact points matches
136+ String providedLocalDc = "dc3";
137+ CountingDCAwarePolicy policy = new CountingDCAwarePolicy(providedLocalDc);
138+
139+ try {
140+ cluster = Cluster.builder()
141+ .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
142+ .withLoadBalancingPolicy(policy)
143+ .build();
144+ cluster.init();
145+
32146 Host host1 = TestUtils.findHost(cluster, 1);
33- assertEquals(policy.localDc, host1.getDatacenter());
147+ Host host2 = TestUtils.findHost(cluster, 2);
148+
149+ assertEquals(policy.getLocalDc(), providedLocalDc);
150+
151+ assertThat(policy.initHosts).containsOnly(host1, host2);
152+
153+ assertThat(logs.get())
154+ .contains("Some contact points don't match local data center");
34155
35156 } finally {
36157 if (cluster != null)
37158 cluster.close();
38- if (ccm != null)
39- ccm.remove();
159+ }
160+ }
161+
162+ /**
163+ * Wraps the policy under test to spy the calls to init.
164+ */
165+ static class CountingDCAwarePolicy extends DelegatingLoadBalancingPolicy {
166+ Set<Host> initHosts = new CopyOnWriteArraySet<Host>();
167+
168+ CountingDCAwarePolicy() {
169+ super(new DCAwareRoundRobinPolicy());
170+ }
171+
172+ CountingDCAwarePolicy(String localDc) {
173+ super(new DCAwareRoundRobinPolicy(localDc));
174+ }
175+
176+ String getLocalDc() {
177+ return ((DCAwareRoundRobinPolicy) delegate).localDc;
178+ }
179+
180+ @Override public void init(Cluster cluster, Collection<Host> hosts) {
181+ System.out.println("init " + hosts);
182+ initHosts.addAll(hosts);
183+ super.init(cluster, hosts);
40184 }
41185 }
42186 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java +3 −2
@@ -1,6 +1,7 @@
11 package com.datastax.driver.core.policies;
22
33 import java.util.*;
4+import java.util.concurrent.ConcurrentHashMap;
45 import java.util.concurrent.locks.Lock;
56 import java.util.concurrent.locks.ReentrantLock;
67
@@ -25,8 +26,8 @@
2526 public class LimitingLoadBalancingPolicy extends DelegatingLoadBalancingPolicy {
2627 private final int maxHosts;
2728 private final int threshold;
28- private final Set<Host> liveHosts = Sets.newConcurrentHashSet();
29- private final Set<Host> chosenHosts = Sets.newConcurrentHashSet();
29+ private final Set<Host> liveHosts = Sets.newSetFromMap(new ConcurrentHashMap<Host, Boolean>());
30+ private final Set<Host> chosenHosts = Sets.newSetFromMap(new ConcurrentHashMap<Host, Boolean>());
3031 private final Lock updateLock = new ReentrantLock();
3132
3233 private volatile Cluster cluster;
modified src/main/config/ide/intellij-code-style.jar +0 −0

Binary content is not shown. View the file.