Elffuss BraidHub

kikocis/java-driver public

Merge branch '3.0.x' into 3.1.x
Changesetd99db6eb76638f26cfd9cfa0c847c892aa0f14d56eb0583f3b1194e4a35d80b0
Authorolim7t <omichallat+github@gmail.com> · 2017-02-01 15:21 -08:00
Committerolim7t <omichallat+github@gmail.com> · 2017-02-01 15:21 -08:00
Parentseeacad6f1010, a6025d8125ef

Browse the files at this changeset

21 files changed

modified build.yaml +8 −0
@@ -21,6 +21,14 @@
2121 include: ["/\\d+(\\.[\\dx]+)+/"]
2222 env_vars: |
2323 TEST_GROUP="long"
24+ adhoc:
25+ # Adhoc job for non-primary braches that doesn't have a schedule but may be used to run all configs.
26+ schedule: adhoc
27+ branches:
28+ # regex matches primary branch format (2.1, 3.x, 3.0.x, 3.1.x, etc).
29+ exclude: ["/\\d+(\\.[\\dx]+)+/"]
30+ env_vars: |
31+ TEST_GROUP="long"
2432 java:
2533 - openjdk6
2634 - oraclejdk7
modified changelog/README.md +7 −0
@@ -1,5 +1,12 @@
11 ## Changelog
22
3+### 3.1.4 (in progress)
4+
5+Merged from 3.0.x branch:
6+
7+- [bug] JAVA-1371: Reintroduce connection pool timeout.
8+
9+
310 ### 3.1.3
411
512 Merged from 3.0.x branch:
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +59 −18
@@ -24,6 +24,7 @@
2424 import com.google.common.base.Throwables;
2525 import com.google.common.collect.Lists;
2626 import com.google.common.util.concurrent.*;
27+import io.netty.util.concurrent.EventExecutor;
2728 import org.slf4j.Logger;
2829 import org.slf4j.LoggerFactory;
2930
@@ -57,14 +58,16 @@
5758 @VisibleForTesting
5859 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
5960
60- private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>();
61+ private final Queue<PendingBorrow> pendingBorrows = new ConcurrentLinkedQueue<PendingBorrow>();
6162 private final AtomicInteger pendingBorrowCount = new AtomicInteger();
6263
6364 private final Runnable newConnectionTask;
6465
6566 private final AtomicInteger scheduledForCreation = new AtomicInteger();
6667
67- protected final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
68+ private final EventExecutor timeoutsExecutor;
69+
70+ private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
6871
6972 private enum Phase {INITIALIZING, READY, INIT_FAILED, CLOSING}
7073
@@ -93,6 +96,8 @@
9396 this.open = new AtomicInteger();
9497
9598 this.minAllowedStreams = options().getMaxRequestsPerConnection(hostDistance) * 3 / 4;
99+
100+ this.timeoutsExecutor = manager.getCluster().manager.connectionFactory.eventLoopGroup.next();
96101 }
97102
98103 /**
@@ -190,7 +195,7 @@
190195 return manager.configuration().getPoolingOptions();
191196 }
192197
193- ListenableFuture<Connection> borrowConnection(int maxQueueSize) {
198+ ListenableFuture<Connection> borrowConnection(long timeout, TimeUnit unit, int maxQueueSize) {
194199 Phase phase = this.phase.get();
195200 if (phase != Phase.READY)
196201 return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase));
@@ -207,7 +212,7 @@
207212 manager.blockingExecutor().submit(newConnectionTask);
208213 }
209214 }
210- return enqueue(maxQueueSize);
215+ return enqueue(timeout, unit, maxQueueSize);
211216 }
212217 }
213218
@@ -228,13 +233,13 @@
228233 // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
229234 // the previous check to connections and now. But in that case, the line above will have trigger the creation of
230235 // a new connection, so just wait that connection and move on
231- return enqueue(maxQueueSize);
236+ return enqueue(timeout, unit, maxQueueSize);
232237 } else {
233238 while (true) {
234239 int inFlight = leastBusy.inFlight.get();
235240
236241 if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
237- return enqueue(maxQueueSize);
242+ return enqueue(timeout, unit, maxQueueSize);
238243 }
239244
240245 if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
@@ -264,8 +269,8 @@
264269 return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace);
265270 }
266271
267- private ListenableFuture<Connection> enqueue(int maxQueueSize) {
268- if (maxQueueSize == 0) {
272+ private ListenableFuture<Connection> enqueue(long timeout, TimeUnit unit, int maxQueueSize) {
273+ if (timeout == 0 || maxQueueSize == 0) {
269274 return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0));
270275 }
271276
@@ -279,16 +284,16 @@
279284 }
280285 }
281286
282- SettableFuture<Connection> future = SettableFuture.create();
283- pendingBorrows.add(future);
287+ PendingBorrow pendingBorrow = new PendingBorrow(timeout, unit, timeoutsExecutor);
288+ pendingBorrows.add(pendingBorrow);
284289
285290 // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly
286291 // handled in closeAsync.
287292 if (phase.get() == Phase.CLOSING) {
288- future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
293+ pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
289294 }
290295
291- return future;
296+ return pendingBorrow.future;
292297 }
293298
294299 void returnConnection(Connection connection) {
@@ -316,7 +321,7 @@
316321 }
317322
318323 // When a connection gets returned to the pool, check if there are pending borrows that can be completed with it.
319- private void dequeue(Connection connection) {
324+ private void dequeue(final Connection connection) {
320325 while (!pendingBorrows.isEmpty()) {
321326
322327 // We can only reuse the connection if it's under its maximum number of inFlight requests.
@@ -333,21 +338,25 @@
333338 }
334339 }
335340
336- final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
341+ final PendingBorrow pendingBorrow = pendingBorrows.poll();
337342 if (pendingBorrow == null) {
338343 // Another thread has emptied the queue since our last check, restore the count
339344 connection.inFlight.decrementAndGet();
340345 } else {
341- totalInFlight.incrementAndGet();
342346 pendingBorrowCount.decrementAndGet();
343347 // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be.
344348 ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace);
345349 // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here.
346350 if (setKeyspaceFuture.isDone()) {
347351 try {
348- pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture));
352+ if (pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture))) {
353+ totalInFlight.incrementAndGet();
354+ } else {
355+ connection.inFlight.decrementAndGet();
356+ }
349357 } catch (ExecutionException e) {
350358 pendingBorrow.setException(e.getCause());
359+ connection.inFlight.decrementAndGet();
351360 }
352361 } else {
353362 // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion.
@@ -355,12 +364,17 @@
355364
356365 @Override
357366 public void onSuccess(Connection c) {
358- pendingBorrow.set(c);
367+ if (pendingBorrow.set(c)) {
368+ totalInFlight.incrementAndGet();
369+ } else {
370+ connection.inFlight.decrementAndGet();
371+ }
359372 }
360373
361374 @Override
362375 public void onFailure(Throwable t) {
363376 pendingBorrow.setException(t);
377+ connection.inFlight.decrementAndGet();
364378 }
365379 });
366380 }
@@ -592,7 +606,7 @@
592606
593607 phase.set(Phase.CLOSING);
594608
595- for (SettableFuture<Connection> pendingBorrow : pendingBorrows) {
609+ for (PendingBorrow pendingBorrow : pendingBorrows) {
596610 pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
597611 }
598612
@@ -664,4 +678,31 @@
664678 this.keyspace = keyspace;
665679 }
666680 }
681+
682+ private class PendingBorrow {
683+ final SettableFuture<Connection> future;
684+ final Future<?> timeoutTask;
685+
686+ PendingBorrow(final long timeout, final TimeUnit unit, EventExecutor timeoutsExecutor) {
687+ this.future = SettableFuture.create();
688+ this.timeoutTask = timeoutsExecutor.schedule(new Runnable() {
689+ @Override
690+ public void run() {
691+ future.setException(
692+ new BusyPoolException(host.getSocketAddress(), timeout, unit));
693+ }
694+ }, timeout, unit);
695+ }
696+
697+ boolean set(Connection connection) {
698+ boolean succeeded = this.future.set(connection);
699+ this.timeoutTask.cancel(false);
700+ return succeeded;
701+ }
702+
703+ void setException(Throwable exception) {
704+ this.future.setException(exception);
705+ this.timeoutTask.cancel(false);
706+ }
707+ }
667708 }
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +5 −5
@@ -26,13 +26,13 @@
2626 /**
2727 * Metrics exposed by the driver.
2828 * <p/>
29- * The metrics exposed by this class use the <a href="http://metrics.codahale.com/">Metrics</a>
30- * library and you should refer its <a href="http://metrics.codahale.com/manual/">documentation</a>
31- * for details on how to handle the exposed metric objects.
29+ * The metrics exposed by this class use the <a href="http://metrics.dropwizard.io/">Metrics</a>
30+ * library and you should refer its documentation for details on how to handle the exposed
31+ * metric objects.
3232 * <p/>
3333 * By default, metrics are exposed through JMX, which is very useful for
3434 * development and browsing, but for production environments you may want to
35- * have a look at the <a href="http://metrics.codahale.com/manual/core/#reporters">reporters</a>
35+ * have a look at the <a href="http://metrics.dropwizard.io/3.1.0/manual/core/#reporters">reporters</a>
3636 * provided by the Metrics library which could be more efficient/adapted.
3737 */
3838 public class Metrics {
@@ -111,7 +111,7 @@
111111 * Returns the registry containing all metrics.
112112 * <p/>
113113 * The metrics registry allows you to easily use the reporters that ship
114- * with <a href="http://metrics.codahale.com/manual/core/#reporters">Metrics</a>
114+ * with <a href="http://metrics.dropwizard.io/3.1.0/manual/core/#reporters">Metrics</a>
115115 * or a custom written one.
116116 * <p/>
117117 * For instance, if {@code metrics} is {@code this} object, you could export the
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +39 −10
@@ -128,9 +128,8 @@
128128 public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
129129
130130 /**
131- * @deprecated see {@link #setPoolTimeoutMillis(int)}
131+ * The default value for {@link #getPoolTimeoutMillis()} ({@value}).
132132 */
133- @Deprecated
134133 public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
135134
136135 /**
@@ -157,6 +156,7 @@
157156 private volatile int maxRequestsPerConnectionRemote = UNSET;
158157
159158 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
159+ private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
160160 private volatile int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
161161 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
162162
@@ -406,19 +406,39 @@
406406 }
407407
408408 /**
409- * @deprecated see {@link #setPoolTimeoutMillis(int)}. This method always returns 0.
409+ * Returns the timeout when trying to acquire a connection from a host's pool.
410+ *
411+ * @return the timeout.
410412 */
411- @Deprecated
412413 public int getPoolTimeoutMillis() {
413- return 0;
414+ return poolTimeoutMillis;
414415 }
415416
416417 /**
417- * @deprecated the connection pool does not use a timeout anymore, incoming requests are now throttled with a
418- * threshold on the {@link #setMaxQueueSize(int) queue size}. This method has no effect.
418+ * Sets the timeout when trying to acquire a connection from a host's pool.
419+ * <p/>
420+ * This option works in concert with {@link #setMaxQueueSize(int)} to determine what happens if the driver tries
421+ * to borrow a connection from the pool but none is available:
422+ * <ul>
423+ * <li>if either option is set to zero, the attempt is rejected immediately;</li>
424+ * <li>else if more than {@code maxQueueSize} requests are already waiting for a connection, the attempt is also
425+ * rejected;</li>
426+ * <li>otherwise, the attempt is enqueued; if a connection becomes available before {@code poolTimeoutMillis}
427+ * has elapsed, then the attempt succeeds, otherwise it is rejected.</li>
428+ * </ul>
429+ * If the attempt is rejected, the driver will move to the next host in the
430+ * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement)} query plan}.
431+ * <p/>
432+ * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
433+ *
434+ * @param poolTimeoutMillis the new value in milliseconds.
435+ * @return this {@code PoolingOptions}
436+ * @throws IllegalArgumentException if the timeout is negative.
419437 */
420- @Deprecated
421438 public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
439+ if (poolTimeoutMillis < 0)
440+ throw new IllegalArgumentException("Pool timeout must be positive");
441+ this.poolTimeoutMillis = poolTimeoutMillis;
422442 return this;
423443 }
424444
@@ -434,8 +454,17 @@
434454 /**
435455 * Sets the maximum number of requests that get enqueued if no connection is available.
436456 * <p/>
437- * If the queue grows past this value, new requests will be rejected immediately (and the driver will move to the
438- * next host in the query plan). This limit is per connection pool, not global to the driver.
457+ * This option works in concert with {@link #setPoolTimeoutMillis(int)} to determine what happens if the driver
458+ * tries to borrow a connection from the pool but none is available:
459+ * <ul>
460+ * <li>if either options is set to zero, the attempt is rejected immediately;</li>
461+ * <li>else if more than {@code maxQueueSize} requests are already waiting for a connection, the attempt is also
462+ * rejected;</li>
463+ * <li>otherwise, the attempt is enqueued; if a connection becomes available before {@code poolTimeoutMillis}
464+ * has elapsed, then the attempt succeeds, otherwise it is rejected.</li>
465+ * </ul>
466+ * If the attempt is rejected, the driver will move to the next host in the
467+ * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement)} query plan}.
439468 * <p/>
440469 * The default value is {@value DEFAULT_MAX_QUEUE_SIZE}. If this option is set to zero, the driver will never
441470 * enqueue requests.
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +3 −1
@@ -290,8 +290,10 @@
290290 if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true))
291291 scheduleExecution(speculativeExecutionPlan.nextExecution(host));
292292
293+ PoolingOptions poolingOptions = manager.configuration().getPoolingOptions();
293294 ListenableFuture<Connection> connectionFuture = pool.borrowConnection(
294- manager.configuration().getPoolingOptions().getMaxQueueSize());
295+ poolingOptions.getPoolTimeoutMillis(), TimeUnit.MILLISECONDS,
296+ poolingOptions.getMaxQueueSize());
295297 Futures.addCallback(connectionFuture, new FutureCallback<Connection>() {
296298 @Override
297299 public void onSuccess(Connection connection) {
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +2 −1
@@ -624,7 +624,8 @@
624624 try {
625625 // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute
626626 // the prepared query. So don't wait if no connection is available, simply abort.
627- ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(0);
627+ ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(
628+ 0, TimeUnit.MILLISECONDS, 0);
628629 ListenableFuture<Response> prepareFuture = Futures.transform(connectionFuture,
629630 new AsyncFunction<Connection, Response>() {
630631 @Override
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +15 −6
@@ -20,6 +20,7 @@
2020
2121 import java.net.InetAddress;
2222 import java.net.InetSocketAddress;
23+import java.util.concurrent.TimeUnit;
2324
2425 /**
2526 * Indicates that a connection pool has run out of available connections.
@@ -44,16 +45,18 @@
4445 private static final long serialVersionUID = 0;
4546
4647 private final InetSocketAddress address;
47- private final int queueSize;
4848
4949 public BusyPoolException(InetSocketAddress address, int queueSize) {
50- this(address, queueSize, null);
50+ this(address, buildMessage(address, queueSize), null);
5151 }
5252
53- private BusyPoolException(InetSocketAddress address, int queueSize, Throwable cause) {
54- super(buildMessage(address, queueSize), cause);
53+ public BusyPoolException(InetSocketAddress address, long timeout, TimeUnit unit) {
54+ this(address, buildMessage(address, timeout, unit), null);
55+ }
56+
57+ private BusyPoolException(InetSocketAddress address, String message, Throwable cause) {
58+ super(message, cause);
5559 this.address = address;
56- this.queueSize = queueSize;
5760 }
5861
5962 private static String buildMessage(InetSocketAddress address, int queueSize) {
@@ -62,6 +65,12 @@
6265 queueSize);
6366 }
6467
68+ private static String buildMessage(InetSocketAddress address, long timeout, TimeUnit unit) {
69+ return String.format("[%s] Pool is busy (no available connection and timed out after %d %s)",
70+ address.getAddress(),
71+ timeout, unit);
72+ }
73+
6574 @Override
6675 public InetAddress getHost() {
6776 return address.getAddress();
@@ -74,7 +83,7 @@
7483
7584 @Override
7685 public BusyPoolException copy() {
77- return new BusyPoolException(address, queueSize, this);
86+ return new BusyPoolException(address, getMessage(), this);
7887 }
7988
8089 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +0 −5
@@ -26,7 +26,6 @@
2626 import org.scassandra.http.client.PrimingRequest;
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
29-import org.testng.SkipException;
3029 import org.testng.annotations.Test;
3130
3231 import java.net.InetAddress;
@@ -55,9 +54,6 @@
5554 */
5655 @Test(groups = "short")
5756 public void should_handle_failing_or_missing_contact_points() throws UnknownHostException {
58- if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V2) > 0)
59- throw new SkipException("Scassandra does not yet support protocol >= V3");
60-
6157 Cluster cluster = null;
6258 Scassandra scassandra = null;
6359 List<FakeHost> failingHosts = Lists.newArrayList();
@@ -107,7 +103,6 @@
107103 .withSocketOptions(socketOptions)
108104 .withReconnectionPolicy(reconnectionPolicy)
109105 .withPoolingOptions(poolingOptions)
110- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
111106 .build();
112107 cluster.connect();
113108
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +0 −1
@@ -86,7 +86,6 @@
8686 cluster = Cluster.builder()
8787 .addContactPoints(hostAddress.getAddress())
8888 .withPort(scassandra.getBinaryPort())
89- .withProtocolVersion(ProtocolVersion.V2)
9089 .withPoolingOptions(new PoolingOptions()
9190 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
9291 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1))
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +0 −3
@@ -67,7 +67,6 @@
6767 Cluster cluster = Cluster.builder()
6868 .addContactPoints(hostAddress.getAddress())
6969 .withPort(scassandra.getBinaryPort())
70- .withProtocolVersion(ProtocolVersion.V2)
7170 .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3))
7271 .build();
7372
@@ -157,7 +156,6 @@
157156 Cluster cluster = Cluster.builder()
158157 .addContactPoints(hostAddress.getAddress())
159158 .withPort(scassandra.getBinaryPort())
160- .withProtocolVersion(ProtocolVersion.V2)
161159 .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3).setConnectionsPerHost(HostDistance.LOCAL, 1, 1))
162160 .build();
163161
@@ -257,7 +255,6 @@
257255 .withPort(scassandra.getBinaryPort())
258256 .withPoolingOptions(new PoolingOptions()
259257 .setHeartbeatIntervalSeconds(0))
260- .withProtocolVersion(ProtocolVersion.V2)
261258 .build();
262259
263260 try {
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +109 −33
@@ -28,6 +28,7 @@
2828 import org.testng.annotations.Test;
2929
3030 import java.net.InetSocketAddress;
31+import java.util.Collection;
3132 import java.util.Collections;
3233 import java.util.Iterator;
3334 import java.util.List;
@@ -39,10 +40,13 @@
3940 import static com.datastax.driver.core.ConditionChecker.check;
4041 import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY;
4142 import static com.google.common.collect.Lists.newArrayList;
43+import static java.util.concurrent.TimeUnit.MILLISECONDS;
4244 import static java.util.concurrent.TimeUnit.SECONDS;
4345 import static org.mockito.Mockito.*;
4446 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
47+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
4548 import static org.scassandra.http.client.PrimingRequest.then;
49+import static org.scassandra.http.client.Result.server_error;
4650 import static org.testng.Assert.fail;
4751
4852 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
@@ -112,13 +116,95 @@
112116 try {
113117 failedBorrow.getConnection();
114118 fail("Expected a BusyPoolException");
115- } catch (BusyPoolException e) {/*expected*/}
119+ } catch (BusyPoolException e) {
120+ assertThat(e).hasMessageContaining("reached its max size");
121+ }
122+ } finally {
123+ MockRequest.completeAll(allRequests);
124+ cluster.close();
125+ }
126+ }
127+
128+ /**
129+ * Ensures that if a fixed-sized pool has filled its core connections and reached a number of requests to cause
130+ * it to be enqueued, that if the request is not serviced within 100ms, a BusyPoolException is raised with a timeout.
131+ *
132+ * @jira_ticket JAVA-1371
133+ * @test_category connection:connection_pool
134+ * @since 3.0.7 3.1.4 3.2.0
135+ */
136+ @Test(groups = "short")
137+ public void should_reject_if_enqueued_and_timeout_reached() {
138+ Cluster cluster = createClusterBuilder().build();
139+ List<MockRequest> allRequests = newArrayList();
140+ try {
141+ HostConnectionPool pool = createPool(cluster, 1, 1);
142+ List<MockRequest> requests = MockRequest.sendMany(128, pool);
143+ allRequests.addAll(requests);
144+
145+ // pool is now full, this request will be enqueued
146+ MockRequest failedBorrow = MockRequest.send(pool, 100, 128);
147+ try {
148+ failedBorrow.getConnection();
149+ fail("Expected a BusyPoolException");
150+ } catch (BusyPoolException e) {
151+ assertThat(e).hasMessageContaining("timed out");
152+ }
116153 } finally {
117154 MockRequest.completeAll(allRequests);
118155 cluster.close();
119156 }
120157 }
121158
159+ /**
160+ * Validates that if a borrow request is enqueued into a pool for a Host that is currently
161+ * within the window of reconnecting after an error that the future tied to that query times out
162+ * after {@link PoolingOptions#setPoolTimeoutMillis(int)}.
163+ * <p>
164+ * This primarily serves to demonstrate that the use case described in JAVA-1371 is fixed by using
165+ * {@link Session#execute(Statement)} shortly after a server error on a connection.
166+ *
167+ * @jira_ticket JAVA-1371
168+ * @test_category connection:connection_pool
169+ * @since 3.0.7 3.1.4 3.2.0
170+ */
171+ @Test(groups = "short")
172+ public void should_not_hang_when_executing_sync_queries() {
173+ primingClient.prime(
174+ queryBuilder()
175+ .withQuery("server_error query")
176+ .withThen(then().withResult(server_error))
177+ .build()
178+ );
179+
180+ Cluster cluster = createClusterBuilder()
181+ .withReconnectionPolicy(new ConstantReconnectionPolicy(10000)).build();
182+ // reduce timeout so test runs faster.
183+ cluster.getConfiguration().getPoolingOptions().setPoolTimeoutMillis(500);
184+ try {
185+ Session session = cluster.connect();
186+ try {
187+ session.execute("server_error query");
188+ fail("Exception expected");
189+ } catch (Exception e) {
190+ // error is expected in this case.
191+ }
192+
193+ try {
194+ session.execute("this should not block indefinitely");
195+ } catch (NoHostAvailableException nhae) {
196+ // should raise a NHAE with a BusyPoolException.
197+ Collection<Throwable> errors = nhae.getErrors().values();
198+ assertThat(errors).hasSize(1);
199+ Throwable e = errors.iterator().next();
200+ assertThat(e).isInstanceOf(BusyPoolException.class);
201+ assertThat(e).hasMessageContaining("timed out");
202+ }
203+ } finally {
204+ cluster.close();
205+ }
206+ }
207+
122208 /**
123209 * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes.
124210 *
@@ -201,32 +287,17 @@
201287 // be called when connection is released by previous requests completing, and that one set
202288 // keyspace attempt should be tried.
203289
204- // Because Scassandra currently returns a 'ROWS' response for set keyspace, the attempt
205- // will fail, and thus the enqueued connection futures will fail in the following ways:
206- // 1. DriverInternalError for set keyspace returning 'ROWS' response
207- // 2. TransportException for connection being closed, when this happens we stop checking these futures.
208- // 3. Never completing because no connections are available.
209- boolean timeoutAcceptable = false;
290+ int count = 0;
210291 for (MockRequest queuedRequest : queuedRequests) {
211292 try {
212293 Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
213- fail("Expected an exception (because Scassandra doesn't support 'USE keyspace'");
294+ count++;
214295 } catch (ExecutionException e) {
215- try {
216- throw e.getCause();
217- } catch (DriverInternalError die) {
218- assertThat(die.getMessage()).contains("Unexpected response while setting keyspace");
219- // Subsequent futures may timeout because the connection is closed.
220- timeoutAcceptable = true;
221- } catch (TransportException ce) {
222- /* expected, Scassandra returning a ROWS response for 'USE keyspace' should defunct and close the connection */
223- // all remaining futures will timeout since there are no remaining connections.
224- break;
225- } catch (Throwable t) {
226- fail("Unexpected cause of future failing", t);
227- }
228- } catch (TimeoutException te) {
229- assertThat(timeoutAcceptable).isTrue();
296+ // 128th request should timeout since all in flight requests are used.
297+ assertThat(e.getCause())
298+ .isInstanceOf(BusyPoolException.class)
299+ .hasMessageContaining("timed out after");
300+ assertThat(count).isEqualTo(128);
230301 break;
231302 }
232303 }
@@ -291,9 +362,9 @@
291362 Cluster cluster = createClusterBuilder().build();
292363 List<MockRequest> requests = newArrayList();
293364 try {
365+ HostConnectionPool pool = createPool(cluster, 1, 1);
294366 // Limit requests per connection to 100 so we don't exhaust stream ids.
295367 cluster.getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, 100);
296- HostConnectionPool pool = createPool(cluster, 1, 1);
297368 int maxQueueSize = 256;
298369
299370 assertThat(pool.connections.size()).isEqualTo(1);
@@ -1171,8 +1242,8 @@
11711242
11721243 // Should create up to core connections.
11731244 verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class));
1174- assertThat(pool.connections).hasSize(1);
11751245
1246+ assertPoolSize(pool, 1);
11761247 request.simulateSuccessResponse();
11771248 } finally {
11781249 cluster.close();
@@ -1181,6 +1252,8 @@
11811252
11821253 private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
11831254 cluster.getConfiguration().getPoolingOptions()
1255+ .setNewConnectionThreshold(HostDistance.LOCAL, 100)
1256+ .setMaxRequestsPerConnection(HostDistance.LOCAL, 128)
11841257 .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
11851258 .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
11861259 Session session = cluster.connect();
@@ -1284,7 +1357,11 @@
12841357 }
12851358
12861359 static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1287- return new MockRequest(pool, maxQueueSize);
1360+ return send(pool, 5000, maxQueueSize);
1361+ }
1362+
1363+ static MockRequest send(HostConnectionPool pool, int timeoutMillis, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1364+ return new MockRequest(pool, timeoutMillis, maxQueueSize);
12881365 }
12891366
12901367 private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException {
@@ -1325,8 +1402,8 @@
13251402 }
13261403 }
13271404
1328- private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1329- this.connectionFuture = pool.borrowConnection(maxQueueSize);
1405+ private MockRequest(HostConnectionPool pool, int timeoutMillis, int maxQueueSize) throws ConnectionException {
1406+ this.connectionFuture = pool.borrowConnection(timeoutMillis, MILLISECONDS, maxQueueSize);
13301407 Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() {
13311408 @Override
13321409 public void onSuccess(Connection connection) {
@@ -1352,15 +1429,14 @@
13521429 responseHandler.cancelHandler();
13531430 }
13541431
1355- // Get the connection, assuming pool acquisition completed
13561432 Connection getConnection() {
13571433 try {
1358- if (!connectionFuture.isDone()) {
1359- throw new AssertionError("Borrow call did not complete");
1360- }
1361- return Uninterruptibles.getUninterruptibly(connectionFuture);
1434+ return Uninterruptibles.getUninterruptibly(connectionFuture, 500, MILLISECONDS);
13621435 } catch (ExecutionException e) {
13631436 throw Throwables.propagate(e.getCause());
1437+ } catch (TimeoutException e) {
1438+ fail("Timed out getting connection");
1439+ return null; // never reached
13641440 }
13651441 }
13661442
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +0 −2
@@ -46,8 +46,6 @@
4646 cluster = Cluster.builder()
4747 .addContactPoint(TestUtils.ipOfNode(1))
4848 .withPort(scassandra.getBinaryPort())
49- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
50- .withProtocolVersion(ProtocolVersion.V2)
5149 .withPoolingOptions(new PoolingOptions()
5250 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
5351 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +73 −23
@@ -19,6 +19,7 @@
1919 import com.google.common.collect.*;
2020 import org.scassandra.Scassandra;
2121 import org.scassandra.ScassandraFactory;
22+import org.scassandra.cql.MapType;
2223 import org.scassandra.http.client.PrimingClient;
2324 import org.scassandra.http.client.PrimingRequest;
2425 import org.slf4j.Logger;
@@ -52,16 +53,26 @@
5253
5354 private final List<Map<String, ?>> keyspaceRows;
5455
55- private static final java.util.UUID schemaVersion = UUIDs.random();
56+ private final String cassandraVersion;
5657
58+ private static final java.util.UUID schemaVersion = UUIDs.random();
5759
5860 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos;
5961
62+ private final String keyspaceQuery;
63+
64+ private final org.scassandra.http.client.types.ColumnMetadata[] keyspaceColumnTypes;
65+
6066 ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort,
61- List<Map<String, ?>> keyspaceRows,
67+ List<Map<String, ?>> keyspaceRows, String cassandraVersion,
6268 Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos) {
6369 this.ipPrefix = ipPrefix;
6470 this.binaryPort = binaryPort;
71+ // If cassandraVersion is not explicitly provided, use 3.0.10 as current version of SCassandra that
72+ // supports up to protocol version 4. Without specifying a newer version, could cause the driver
73+ // to think the node doesn't support a protocol version that it indeed does.
74+ this.cassandraVersion = cassandraVersion != null ?
75+ cassandraVersion : "3.0.10";
6576 this.forcedPeerInfos = forcedPeerInfos;
6677
6778 int node = 1;
@@ -79,7 +90,30 @@
7990 }
8091 instances = instanceListBuilder.build();
8192 dcNodeMap = dcNodeMapBuilder.build();
82- this.keyspaceRows = keyspaceRows;
93+
94+ // Prime correct keyspace table based on C* version.
95+ String[] versionArray = this.cassandraVersion.split("\\.|-");
96+ double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]);
97+
98+ if (major < 3.0) {
99+ this.keyspaceQuery = "SELECT * FROM system.schema_keyspaces";
100+ this.keyspaceColumnTypes = SELECT_SCHEMA_KEYSPACES;
101+ this.keyspaceRows = Lists.newArrayList(keyspaceRows);
102+ // remove replication map as it is not part of the < 3.0 schema.
103+ for (Map<String, ?> keyspaceRow : this.keyspaceRows) {
104+ keyspaceRow.remove("replication");
105+ }
106+ } else {
107+ this.keyspaceQuery = "SELECT * FROM system_schema.keyspaces";
108+ this.keyspaceColumnTypes = SELECT_SCHEMA_KEYSPACES_V3;
109+ this.keyspaceRows = Lists.newArrayList(keyspaceRows);
110+ // remove strategy options and strategy class as these are not part of the 3.0+ schema.
111+ for (Map<String, ?> keyspaceRow : this.keyspaceRows) {
112+ keyspaceRow.remove("strategy_class");
113+ keyspaceRow.remove("strategy_options");
114+ }
115+ }
116+
83117 }
84118
85119 public Scassandra node(int node) {
@@ -297,7 +331,7 @@
297331 addPeerInfo(row, dc, n + 1, "listen_address", getPeerInfo(dc, n + 1, "listen_address", address));
298332 addPeerInfo(row, dc, n + 1, "partitioner", "org.apache.cassandra.dht.Murmur3Partitioner");
299333 addPeerInfo(row, dc, n + 1, "rack", getPeerInfo(dc, n + 1, "rack", "rack1"));
300- addPeerInfo(row, dc, n + 1, "release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"));
334+ addPeerInfo(row, dc, n + 1, "release_version", getPeerInfo(dc, n + 1, "release_version", cassandraVersion));
301335 addPeerInfo(row, dc, n + 1, "tokens", ImmutableSet.of(tokens.get(n)));
302336 addPeerInfo(row, dc, n + 1, "schema_version", schemaVersion);
303337 addPeerInfo(row, dc, n + 1, "graph", false);
@@ -314,7 +348,7 @@
314348 addPeerInfo(row, dc, n + 1, "rpc_address", address);
315349 addPeerInfo(row, dc, n + 1, "data_center", datacenter(dc));
316350 addPeerInfo(row, dc, n + 1, "rack", getPeerInfo(dc, n + 1, "rack", "rack1"));
317- addPeerInfo(row, dc, n + 1, "release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"));
351+ addPeerInfo(row, dc, n + 1, "release_version", getPeerInfo(dc, n + 1, "release_version", cassandraVersion));
318352 addPeerInfo(row, dc, n + 1, "tokens", ImmutableSet.of(Long.toString(tokens.get(n))));
319353 addPeerInfo(row, dc, n + 1, "host_id", UUIDs.random());
320354 addPeerInfo(row, dc, n + 1, "schema_version", schemaVersion);
@@ -356,11 +390,11 @@
356390 .build())
357391 .build());
358392
359- // Prime keyspaces
393+
360394 client.prime(PrimingRequest.queryBuilder()
361- .withQuery("SELECT * FROM system.schema_keyspaces")
395+ .withQuery(keyspaceQuery)
362396 .withThen(then()
363- .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
397+ .withColumnTypes(keyspaceColumnTypes)
364398 .withRows(keyspaceRows)
365399 .build())
366400 .build());
@@ -440,6 +474,12 @@
440474 column("strategy_options", TEXT)
441475 };
442476
477+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_KEYSPACES_V3 = {
478+ column("durable_writes", BOOLEAN),
479+ column("keyspace_name", TEXT),
480+ column("replication", MapType.map(TEXT, TEXT))
481+ };
482+
443483 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMN_FAMILIES = {
444484 column("bloom_filter_fp_chance", DOUBLE),
445485 column("caching", TEXT),
@@ -495,6 +535,7 @@
495535 private String ipPrefix = TestUtils.IP_PREFIX;
496536 private final List<Map<String, ?>> keyspaceRows = Lists.newArrayList();
497537 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap();
538+ private String cassandraVersion = null;
498539
499540 public ScassandraClusterBuilder withNodes(Integer... nodes) {
500541 this.nodes = nodes;
@@ -507,36 +548,40 @@
507548 }
508549
509550 public ScassandraClusterBuilder withSimpleKeyspace(String name, int replicationFactor) {
510- Map<String, Object> simpleKeyspaceRow = ImmutableMap.<String, Object>builder()
511- .put("durable_writes", false)
512- .put("keyspace_name", name)
513- .put("strategy_class", "SimpleStrategy")
514- .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
515- .build();
516-
551+ Map<String, Object> simpleKeyspaceRow = Maps.newHashMap();
552+ simpleKeyspaceRow.put("durable_writes", false);
553+ simpleKeyspaceRow.put("keyspace_name", name);
554+ simpleKeyspaceRow.put("replication", ImmutableMap.<String, String>builder()
555+ .put("class", "org.apache.cassandra.locator.SimpleStrategy")
556+ .put("replication_factor", "" + replicationFactor).build());
557+ simpleKeyspaceRow.put("strategy_class", "SimpleStrategy");
558+ simpleKeyspaceRow.put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}");
517559 keyspaceRows.add(simpleKeyspaceRow);
518560 return this;
519561 }
520562
521563 public ScassandraClusterBuilder withNetworkTopologyKeyspace(String name, Map<Integer, Integer> replicationFactors) {
522564 StringBuilder strategyOptionsBuilder = new StringBuilder("{");
565+ ImmutableMap.Builder<String, String> replicationBuilder = ImmutableMap.builder();
566+ replicationBuilder.put("class", "org.apache.cassandra.locator.NetworkTopologyStrategy");
567+
523568 for (Map.Entry<Integer, Integer> dc : replicationFactors.entrySet()) {
524569 strategyOptionsBuilder.append("\"");
525570 strategyOptionsBuilder.append(datacenter(dc.getKey()));
526571 strategyOptionsBuilder.append("\":\"");
527572 strategyOptionsBuilder.append(dc.getValue());
528573 strategyOptionsBuilder.append("\",");
574+ replicationBuilder.put(datacenter(dc.getKey()), "" + dc.getValue());
529575 }
530576
531577 String strategyOptions = strategyOptionsBuilder.substring(0, strategyOptionsBuilder.length() - 1) + "}";
532578
533- Map<String, Object> ntsKeyspaceRow = ImmutableMap.<String, Object>builder()
534- .put("durable_writes", false)
535- .put("keyspace_name", name)
536- .put("strategy_class", "NetworkTopologyStrategy")
537- .put("strategy_options", strategyOptions)
538- .build();
539-
579+ Map<String, Object> ntsKeyspaceRow = Maps.newHashMap();
580+ ntsKeyspaceRow.put("durable_writes", false);
581+ ntsKeyspaceRow.put("keyspace_name", name);
582+ ntsKeyspaceRow.put("strategy_class", "NetworkTopologyStrategy");
583+ ntsKeyspaceRow.put("strategy_options", strategyOptions);
584+ ntsKeyspaceRow.put("replication", replicationBuilder.build());
540585 keyspaceRows.add(ntsKeyspaceRow);
541586 return this;
542587 }
@@ -556,8 +601,13 @@
556601 return this;
557602 }
558603
604+ public ScassandraClusterBuilder withCassandraVersion(String version) {
605+ this.cassandraVersion = version;
606+ return this;
607+ }
608+
559609 public ScassandraCluster build() {
560- return new ScassandraCluster(nodes, ipPrefix, TestUtils.findAvailablePort(), TestUtils.findAvailablePort(), keyspaceRows, forcedPeerInfos);
610+ return new ScassandraCluster(nodes, ipPrefix, TestUtils.findAvailablePort(), TestUtils.findAvailablePort(), keyspaceRows, cassandraVersion, forcedPeerInfos);
561611 }
562612 }
563613 }
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +0 −2
@@ -79,8 +79,6 @@
7979 .withPort(scassandra.getBinaryPort())
8080 .addContactPoints(hostAddress.getAddress())
8181 .withPort(scassandra.getBinaryPort())
82- // Scassandra does not support V3 yet, and V4 may cause the server to crash
83- .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V2))
8482 .withPoolingOptions(new PoolingOptions()
8583 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
8684 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
deleted driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +0 −86
@@ -1,86 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
19-import com.datastax.driver.core.utils.CassandraVersion;
20-import org.mockito.Mockito;
21-import org.testng.annotations.Test;
22-
23-import static org.assertj.core.api.Assertions.fail;
24-import static org.mockito.Mockito.times;
25-
26-/**
27- * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because
28- * it uses a protocol v3 feature.
29- */
30-public class SpeculativeExecutionIntegrationTest extends CCMTestsSupport {
31-
32- TimestampGenerator timestampGenerator;
33-
34- @Override
35- public void onTestContextInitialized() {
36- execute("create table foo(k int primary key, v int)");
37- }
38-
39- @Override
40- public Cluster.Builder createClusterBuilder() {
41- timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
42- return Cluster.builder()
43- .withTimestampGenerator(timestampGenerator)
44- // Set an artificially low timeout to force speculative execution
45- .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
46- }
47-
48- /**
49- * Validates that if a query gets speculatively re-executed, the second execution uses the same default timestamp.
50- *
51- * @test_category tracing
52- * @jira_ticket JAVA-724
53- * @expected_result timestamp generator invoked only once for a query that caused two executions.
54- */
55- @Test(groups = "short")
56- @CassandraVersion(major = 2.1)
57- public void should_use_same_default_timestamp_for_all_executions() {
58- Metrics.Errors errors = cluster().getMetrics().getErrorMetrics();
59-
60- // The check is attempted up to 10 times to account for the small possibility that a
61- // scheduled execution is not needed/exercised. Even though the policy is set up
62- // to schedule an execution after 1ms, the timeout might not fire before the response is received.
63- int tryCount = 0;
64- int maxTries = 10;
65- while (tryCount++ < maxTries) {
66- Mockito.reset(timestampGenerator);
67- long execStartCount = errors.getSpeculativeExecutions().getCount();
68-
69- BatchStatement batch = new BatchStatement();
70- for (int k = 0; k < 1000; k++) {
71- batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k).setIdempotent(true));
72- }
73- batch.setIdempotent(true);
74- session().execute(batch);
75-
76- if (errors.getSpeculativeExecutions().getCount() == execStartCount + 1) {
77- Mockito.verify(timestampGenerator, times(1)).next();
78- break;
79- }
80- }
81-
82- if (tryCount == maxTries) {
83- fail("Observed no speculative executions in 10 attempts");
84- }
85- }
86-}
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +47 −3
@@ -21,6 +21,7 @@
2121 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2222 import com.google.common.collect.ImmutableList;
2323 import com.google.common.collect.ImmutableMap;
24+import org.mockito.Mockito;
2425 import org.scassandra.http.client.Consistency;
2526 import org.scassandra.http.client.PrimingRequest;
2627 import org.scassandra.http.client.Result;
@@ -55,7 +56,6 @@
5556 cluster = Cluster.builder()
5657 .addContactPoints(scassandras.address(2).getAddress())
5758 .withPort(scassandras.getBinaryPort())
58- .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet
5959 .withLoadBalancingPolicy(loadBalancingPolicy)
6060 .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
6161 .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
@@ -208,8 +208,6 @@
208208 Cluster cluster = Cluster.builder()
209209 .addContactPoints(scassandras.address(2).getAddress())
210210 .withPort(scassandras.getBinaryPort())
211- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
212- .withProtocolVersion(ProtocolVersion.V2)
213211 .withSpeculativeExecutionPolicy(mockPolicy)
214212 .build();
215213
@@ -225,6 +223,52 @@
225223 }
226224 }
227225
226+ /**
227+ * Validates that if a query gets speculatively re-executed, the second execution uses the same default timestamp.
228+ *
229+ * @test_category tracing
230+ * @jira_ticket JAVA-724
231+ * @expected_result timestamp generator invoked only once for a query that caused two executions.
232+ */
233+ @Test(groups = "short")
234+ public void should_use_same_default_timestamp_for_all_executions() {
235+ TimestampGenerator timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
236+ Cluster cluster = Cluster.builder()
237+ .addContactPoints(scassandras.address(2).getAddress())
238+ .withPort(scassandras.getBinaryPort())
239+ .withLoadBalancingPolicy(loadBalancingPolicy)
240+ .withTimestampGenerator(timestampGenerator)
241+ .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2))
242+ .withNettyOptions(nonQuietClusterCloseOptions)
243+ .build();
244+
245+ try {
246+ scassandras.node(1).primingClient()
247+ // execution1 starts with host1, which will time out at t=1000
248+ .prime(PrimingRequest.queryBuilder()
249+ .withQuery("mock query")
250+ .withFixedDelay(2000)
251+ .withRows(row("result", "result1"))
252+ .build());
253+
254+ Session session = cluster.connect();
255+ Metrics.Errors errors = cluster.getMetrics().getErrorMetrics();
256+
257+ long execStartCount = errors.getSpeculativeExecutions().getCount();
258+
259+ SimpleStatement statement = new SimpleStatement("mock query");
260+ statement.setIdempotent(true);
261+ session.execute(statement);
262+
263+ // Should have only requested one timestamp.
264+ if (errors.getSpeculativeExecutions().getCount() == execStartCount + 1) {
265+ Mockito.verify(timestampGenerator, times(1)).next();
266+ }
267+ } finally {
268+ cluster.close();
269+ }
270+ }
271+
228272 /**
229273 * Custom retry policy that retries at ONE on read timeout.
230274 * This deals with the fact that Scassandra only allows read timeouts with 0 replicas.
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +0 −2
@@ -82,8 +82,6 @@
8282 .withPort(scassandras.getBinaryPort())
8383 .withRetryPolicy(retryPolicy)
8484 .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
85- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
86- .withProtocolVersion(ProtocolVersion.V2)
8785 .withPoolingOptions(new PoolingOptions()
8886 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
8987 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +0 −2
@@ -119,8 +119,6 @@
119119 Cluster whiteListedCluster = Cluster.builder()
120120 .addContactPoints(scassandras.address(1).getAddress())
121121 .withPort(scassandras.getBinaryPort())
122- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
123- .withProtocolVersion(ProtocolVersion.V2)
124122 .withRetryPolicy(retryPolicy)
125123 .withLoadBalancingPolicy(firstHostOnlyPolicy)
126124 .build();
modified manual/pooling/README.md +10 −5
@@ -188,11 +188,15 @@
188188 requests), the acquisition attempt gets enqueued until a connection becomes
189189 available again.
190190
191-The size of that queue is controlled by [PoolingOptions.setMaxQueueSize][smqs].
192-If the queue has already reached its limit, further attempts to acquire a
193-connection will be rejected immediately: the driver will move on and try to
194-acquire a connection from the next host's pool. The limit can be set to 0 to
195-disable queueing entirely.
191+Two options control that queue: a maximum size ([PoolingOptions.setMaxQueueSize][smqs]) and a timeout
192+([PoolingOptions.setPoolTimeoutMillis][sptm]).
193+* if either option is set to zero, the attempt is rejected immediately;
194+* else if more than `maxQueueSize` requests are already waiting for a connection, the attempt is also rejected;
195+* otherwise, the attempt is enqueued; if a connection becomes available before `poolTimeoutMillis` has elapsed,
196+ then the attempt succeeds, otherwise it is rejected.
197+
198+If the attempt is rejected, the driver will move to the next host in the [query plan](../load_balancing/#query-plan),
199+and try to acquire a connection again.
196200
197201 If all hosts are busy with a full queue, the request will fail with a
198202 [NoHostAvailableException][nhae]. If you inspect the map returns by this
@@ -286,6 +290,7 @@
286290 [sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287291 [rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288292 [smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int-
293+[sptm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
289294 [nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290295 [getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors--
291296 [get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
modified pom.xml +1 −1
@@ -68,7 +68,7 @@
6868 <assertj.version>1.7.0</assertj.version>
6969 <mockito.version>1.10.8</mockito.version>
7070 <commons-exec.version>1.3</commons-exec.version>
71- <scassandra.version>1.0.9</scassandra.version>
71+ <scassandra.version>1.1.1</scassandra.version>
7272 <main.basedir>${project.basedir}</main.basedir>
7373 <ipprefix>127.0.1.</ipprefix>
7474 <test.groups>unit</test.groups>