kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | d99db6eb76638f26cfd9cfa0c847c892aa0f14d56eb0583f3b1194e4a35d80b0 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2017-02-01 15:21 -08:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2017-02-01 15:21 -08:00 |
| Parents | eeacad6f1010, a6025d8125ef |
21 files changed
modified build.yaml +8 −0
| @@ -21,6 +21,14 @@ | ||
| 21 | 21 | include: ["/\\d+(\\.[\\dx]+)+/"] |
| 22 | 22 | env_vars: | |
| 23 | 23 | 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" | |
| 24 | 32 | java: |
| 25 | 33 | - openjdk6 |
| 26 | 34 | - oraclejdk7 |
modified changelog/README.md +7 −0
| @@ -1,5 +1,12 @@ | ||
| 1 | 1 | ## Changelog |
| 2 | 2 | |
| 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 | + | |
| 3 | 10 | ### 3.1.3 |
| 4 | 11 | |
| 5 | 12 | Merged from 3.0.x branch: |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +59 −18
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | import com.google.common.base.Throwables; |
| 25 | 25 | import com.google.common.collect.Lists; |
| 26 | 26 | import com.google.common.util.concurrent.*; |
| 27 | +import io.netty.util.concurrent.EventExecutor; | |
| 27 | 28 | import org.slf4j.Logger; |
| 28 | 29 | import org.slf4j.LoggerFactory; |
| 29 | 30 | |
| @@ -57,14 +58,16 @@ | ||
| 57 | 58 | @VisibleForTesting |
| 58 | 59 | final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); |
| 59 | 60 | |
| 60 | - private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>(); | |
| 61 | + private final Queue<PendingBorrow> pendingBorrows = new ConcurrentLinkedQueue<PendingBorrow>(); | |
| 61 | 62 | private final AtomicInteger pendingBorrowCount = new AtomicInteger(); |
| 62 | 63 | |
| 63 | 64 | private final Runnable newConnectionTask; |
| 64 | 65 | |
| 65 | 66 | private final AtomicInteger scheduledForCreation = new AtomicInteger(); |
| 66 | 67 | |
| 67 | - protected final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); | |
| 68 | + private final EventExecutor timeoutsExecutor; | |
| 69 | + | |
| 70 | + private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); | |
| 68 | 71 | |
| 69 | 72 | private enum Phase {INITIALIZING, READY, INIT_FAILED, CLOSING} |
| 70 | 73 | |
| @@ -93,6 +96,8 @@ | ||
| 93 | 96 | this.open = new AtomicInteger(); |
| 94 | 97 | |
| 95 | 98 | this.minAllowedStreams = options().getMaxRequestsPerConnection(hostDistance) * 3 / 4; |
| 99 | + | |
| 100 | + this.timeoutsExecutor = manager.getCluster().manager.connectionFactory.eventLoopGroup.next(); | |
| 96 | 101 | } |
| 97 | 102 | |
| 98 | 103 | /** |
| @@ -190,7 +195,7 @@ | ||
| 190 | 195 | return manager.configuration().getPoolingOptions(); |
| 191 | 196 | } |
| 192 | 197 | |
| 193 | - ListenableFuture<Connection> borrowConnection(int maxQueueSize) { | |
| 198 | + ListenableFuture<Connection> borrowConnection(long timeout, TimeUnit unit, int maxQueueSize) { | |
| 194 | 199 | Phase phase = this.phase.get(); |
| 195 | 200 | if (phase != Phase.READY) |
| 196 | 201 | return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase)); |
| @@ -207,7 +212,7 @@ | ||
| 207 | 212 | manager.blockingExecutor().submit(newConnectionTask); |
| 208 | 213 | } |
| 209 | 214 | } |
| 210 | - return enqueue(maxQueueSize); | |
| 215 | + return enqueue(timeout, unit, maxQueueSize); | |
| 211 | 216 | } |
| 212 | 217 | } |
| 213 | 218 | |
| @@ -228,13 +233,13 @@ | ||
| 228 | 233 | // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between |
| 229 | 234 | // the previous check to connections and now. But in that case, the line above will have trigger the creation of |
| 230 | 235 | // a new connection, so just wait that connection and move on |
| 231 | - return enqueue(maxQueueSize); | |
| 236 | + return enqueue(timeout, unit, maxQueueSize); | |
| 232 | 237 | } else { |
| 233 | 238 | while (true) { |
| 234 | 239 | int inFlight = leastBusy.inFlight.get(); |
| 235 | 240 | |
| 236 | 241 | if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) { |
| 237 | - return enqueue(maxQueueSize); | |
| 242 | + return enqueue(timeout, unit, maxQueueSize); | |
| 238 | 243 | } |
| 239 | 244 | |
| 240 | 245 | if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) |
| @@ -264,8 +269,8 @@ | ||
| 264 | 269 | return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace); |
| 265 | 270 | } |
| 266 | 271 | |
| 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) { | |
| 269 | 274 | return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0)); |
| 270 | 275 | } |
| 271 | 276 | |
| @@ -279,16 +284,16 @@ | ||
| 279 | 284 | } |
| 280 | 285 | } |
| 281 | 286 | |
| 282 | - SettableFuture<Connection> future = SettableFuture.create(); | |
| 283 | - pendingBorrows.add(future); | |
| 287 | + PendingBorrow pendingBorrow = new PendingBorrow(timeout, unit, timeoutsExecutor); | |
| 288 | + pendingBorrows.add(pendingBorrow); | |
| 284 | 289 | |
| 285 | 290 | // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly |
| 286 | 291 | // handled in closeAsync. |
| 287 | 292 | 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")); | |
| 289 | 294 | } |
| 290 | 295 | |
| 291 | - return future; | |
| 296 | + return pendingBorrow.future; | |
| 292 | 297 | } |
| 293 | 298 | |
| 294 | 299 | void returnConnection(Connection connection) { |
| @@ -316,7 +321,7 @@ | ||
| 316 | 321 | } |
| 317 | 322 | |
| 318 | 323 | // 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) { | |
| 320 | 325 | while (!pendingBorrows.isEmpty()) { |
| 321 | 326 | |
| 322 | 327 | // We can only reuse the connection if it's under its maximum number of inFlight requests. |
| @@ -333,21 +338,25 @@ | ||
| 333 | 338 | } |
| 334 | 339 | } |
| 335 | 340 | |
| 336 | - final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll(); | |
| 341 | + final PendingBorrow pendingBorrow = pendingBorrows.poll(); | |
| 337 | 342 | if (pendingBorrow == null) { |
| 338 | 343 | // Another thread has emptied the queue since our last check, restore the count |
| 339 | 344 | connection.inFlight.decrementAndGet(); |
| 340 | 345 | } else { |
| 341 | - totalInFlight.incrementAndGet(); | |
| 342 | 346 | pendingBorrowCount.decrementAndGet(); |
| 343 | 347 | // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be. |
| 344 | 348 | ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace); |
| 345 | 349 | // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here. |
| 346 | 350 | if (setKeyspaceFuture.isDone()) { |
| 347 | 351 | try { |
| 348 | - pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture)); | |
| 352 | + if (pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture))) { | |
| 353 | + totalInFlight.incrementAndGet(); | |
| 354 | + } else { | |
| 355 | + connection.inFlight.decrementAndGet(); | |
| 356 | + } | |
| 349 | 357 | } catch (ExecutionException e) { |
| 350 | 358 | pendingBorrow.setException(e.getCause()); |
| 359 | + connection.inFlight.decrementAndGet(); | |
| 351 | 360 | } |
| 352 | 361 | } else { |
| 353 | 362 | // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion. |
| @@ -355,12 +364,17 @@ | ||
| 355 | 364 | |
| 356 | 365 | @Override |
| 357 | 366 | public void onSuccess(Connection c) { |
| 358 | - pendingBorrow.set(c); | |
| 367 | + if (pendingBorrow.set(c)) { | |
| 368 | + totalInFlight.incrementAndGet(); | |
| 369 | + } else { | |
| 370 | + connection.inFlight.decrementAndGet(); | |
| 371 | + } | |
| 359 | 372 | } |
| 360 | 373 | |
| 361 | 374 | @Override |
| 362 | 375 | public void onFailure(Throwable t) { |
| 363 | 376 | pendingBorrow.setException(t); |
| 377 | + connection.inFlight.decrementAndGet(); | |
| 364 | 378 | } |
| 365 | 379 | }); |
| 366 | 380 | } |
| @@ -592,7 +606,7 @@ | ||
| 592 | 606 | |
| 593 | 607 | phase.set(Phase.CLOSING); |
| 594 | 608 | |
| 595 | - for (SettableFuture<Connection> pendingBorrow : pendingBorrows) { | |
| 609 | + for (PendingBorrow pendingBorrow : pendingBorrows) { | |
| 596 | 610 | pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); |
| 597 | 611 | } |
| 598 | 612 | |
| @@ -664,4 +678,31 @@ | ||
| 664 | 678 | this.keyspace = keyspace; |
| 665 | 679 | } |
| 666 | 680 | } |
| 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 | + } | |
| 667 | 708 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +5 −5
| @@ -26,13 +26,13 @@ | ||
| 26 | 26 | /** |
| 27 | 27 | * Metrics exposed by the driver. |
| 28 | 28 | * <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. | |
| 32 | 32 | * <p/> |
| 33 | 33 | * By default, metrics are exposed through JMX, which is very useful for |
| 34 | 34 | * 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> | |
| 36 | 36 | * provided by the Metrics library which could be more efficient/adapted. |
| 37 | 37 | */ |
| 38 | 38 | public class Metrics { |
| @@ -111,7 +111,7 @@ | ||
| 111 | 111 | * Returns the registry containing all metrics. |
| 112 | 112 | * <p/> |
| 113 | 113 | * 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> | |
| 115 | 115 | * or a custom written one. |
| 116 | 116 | * <p/> |
| 117 | 117 | * 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 @@ | ||
| 128 | 128 | public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; |
| 129 | 129 | |
| 130 | 130 | /** |
| 131 | - * @deprecated see {@link #setPoolTimeoutMillis(int)} | |
| 131 | + * The default value for {@link #getPoolTimeoutMillis()} ({@value}). | |
| 132 | 132 | */ |
| 133 | - @Deprecated | |
| 134 | 133 | public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 135 | 134 | |
| 136 | 135 | /** |
| @@ -157,6 +156,7 @@ | ||
| 157 | 156 | private volatile int maxRequestsPerConnectionRemote = UNSET; |
| 158 | 157 | |
| 159 | 158 | private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS; |
| 159 | + private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; | |
| 160 | 160 | private volatile int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; |
| 161 | 161 | private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; |
| 162 | 162 | |
| @@ -406,19 +406,39 @@ | ||
| 406 | 406 | } |
| 407 | 407 | |
| 408 | 408 | /** |
| 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. | |
| 410 | 412 | */ |
| 411 | - @Deprecated | |
| 412 | 413 | public int getPoolTimeoutMillis() { |
| 413 | - return 0; | |
| 414 | + return poolTimeoutMillis; | |
| 414 | 415 | } |
| 415 | 416 | |
| 416 | 417 | /** |
| 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. | |
| 419 | 437 | */ |
| 420 | - @Deprecated | |
| 421 | 438 | public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) { |
| 439 | + if (poolTimeoutMillis < 0) | |
| 440 | + throw new IllegalArgumentException("Pool timeout must be positive"); | |
| 441 | + this.poolTimeoutMillis = poolTimeoutMillis; | |
| 422 | 442 | return this; |
| 423 | 443 | } |
| 424 | 444 | |
| @@ -434,8 +454,17 @@ | ||
| 434 | 454 | /** |
| 435 | 455 | * Sets the maximum number of requests that get enqueued if no connection is available. |
| 436 | 456 | * <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}. | |
| 439 | 468 | * <p/> |
| 440 | 469 | * The default value is {@value DEFAULT_MAX_QUEUE_SIZE}. If this option is set to zero, the driver will never |
| 441 | 470 | * enqueue requests. |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +3 −1
| @@ -290,8 +290,10 @@ | ||
| 290 | 290 | if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true)) |
| 291 | 291 | scheduleExecution(speculativeExecutionPlan.nextExecution(host)); |
| 292 | 292 | |
| 293 | + PoolingOptions poolingOptions = manager.configuration().getPoolingOptions(); | |
| 293 | 294 | ListenableFuture<Connection> connectionFuture = pool.borrowConnection( |
| 294 | - manager.configuration().getPoolingOptions().getMaxQueueSize()); | |
| 295 | + poolingOptions.getPoolTimeoutMillis(), TimeUnit.MILLISECONDS, | |
| 296 | + poolingOptions.getMaxQueueSize()); | |
| 295 | 297 | Futures.addCallback(connectionFuture, new FutureCallback<Connection>() { |
| 296 | 298 | @Override |
| 297 | 299 | public void onSuccess(Connection connection) { |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +2 −1
| @@ -624,7 +624,8 @@ | ||
| 624 | 624 | try { |
| 625 | 625 | // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute |
| 626 | 626 | // 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); | |
| 628 | 629 | ListenableFuture<Response> prepareFuture = Futures.transform(connectionFuture, |
| 629 | 630 | new AsyncFunction<Connection, Response>() { |
| 630 | 631 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +15 −6
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | |
| 21 | 21 | import java.net.InetAddress; |
| 22 | 22 | import java.net.InetSocketAddress; |
| 23 | +import java.util.concurrent.TimeUnit; | |
| 23 | 24 | |
| 24 | 25 | /** |
| 25 | 26 | * Indicates that a connection pool has run out of available connections. |
| @@ -44,16 +45,18 @@ | ||
| 44 | 45 | private static final long serialVersionUID = 0; |
| 45 | 46 | |
| 46 | 47 | private final InetSocketAddress address; |
| 47 | - private final int queueSize; | |
| 48 | 48 | |
| 49 | 49 | public BusyPoolException(InetSocketAddress address, int queueSize) { |
| 50 | - this(address, queueSize, null); | |
| 50 | + this(address, buildMessage(address, queueSize), null); | |
| 51 | 51 | } |
| 52 | 52 | |
| 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); | |
| 55 | 59 | this.address = address; |
| 56 | - this.queueSize = queueSize; | |
| 57 | 60 | } |
| 58 | 61 | |
| 59 | 62 | private static String buildMessage(InetSocketAddress address, int queueSize) { |
| @@ -62,6 +65,12 @@ | ||
| 62 | 65 | queueSize); |
| 63 | 66 | } |
| 64 | 67 | |
| 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 | + | |
| 65 | 74 | @Override |
| 66 | 75 | public InetAddress getHost() { |
| 67 | 76 | return address.getAddress(); |
| @@ -74,7 +83,7 @@ | ||
| 74 | 83 | |
| 75 | 84 | @Override |
| 76 | 85 | public BusyPoolException copy() { |
| 77 | - return new BusyPoolException(address, queueSize, this); | |
| 86 | + return new BusyPoolException(address, getMessage(), this); | |
| 78 | 87 | } |
| 79 | 88 | |
| 80 | 89 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +0 −5
| @@ -26,7 +26,6 @@ | ||
| 26 | 26 | import org.scassandra.http.client.PrimingRequest; |
| 27 | 27 | import org.slf4j.Logger; |
| 28 | 28 | import org.slf4j.LoggerFactory; |
| 29 | -import org.testng.SkipException; | |
| 30 | 29 | import org.testng.annotations.Test; |
| 31 | 30 | |
| 32 | 31 | import java.net.InetAddress; |
| @@ -55,9 +54,6 @@ | ||
| 55 | 54 | */ |
| 56 | 55 | @Test(groups = "short") |
| 57 | 56 | 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 | - | |
| 61 | 57 | Cluster cluster = null; |
| 62 | 58 | Scassandra scassandra = null; |
| 63 | 59 | List<FakeHost> failingHosts = Lists.newArrayList(); |
| @@ -107,7 +103,6 @@ | ||
| 107 | 103 | .withSocketOptions(socketOptions) |
| 108 | 104 | .withReconnectionPolicy(reconnectionPolicy) |
| 109 | 105 | .withPoolingOptions(poolingOptions) |
| 110 | - .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) | |
| 111 | 106 | .build(); |
| 112 | 107 | cluster.connect(); |
| 113 | 108 |
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +0 −1
| @@ -86,7 +86,6 @@ | ||
| 86 | 86 | cluster = Cluster.builder() |
| 87 | 87 | .addContactPoints(hostAddress.getAddress()) |
| 88 | 88 | .withPort(scassandra.getBinaryPort()) |
| 89 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 90 | 89 | .withPoolingOptions(new PoolingOptions() |
| 91 | 90 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) |
| 92 | 91 | .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)) |
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +0 −3
| @@ -67,7 +67,6 @@ | ||
| 67 | 67 | Cluster cluster = Cluster.builder() |
| 68 | 68 | .addContactPoints(hostAddress.getAddress()) |
| 69 | 69 | .withPort(scassandra.getBinaryPort()) |
| 70 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 71 | 70 | .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3)) |
| 72 | 71 | .build(); |
| 73 | 72 | |
| @@ -157,7 +156,6 @@ | ||
| 157 | 156 | Cluster cluster = Cluster.builder() |
| 158 | 157 | .addContactPoints(hostAddress.getAddress()) |
| 159 | 158 | .withPort(scassandra.getBinaryPort()) |
| 160 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 161 | 159 | .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3).setConnectionsPerHost(HostDistance.LOCAL, 1, 1)) |
| 162 | 160 | .build(); |
| 163 | 161 | |
| @@ -257,7 +255,6 @@ | ||
| 257 | 255 | .withPort(scassandra.getBinaryPort()) |
| 258 | 256 | .withPoolingOptions(new PoolingOptions() |
| 259 | 257 | .setHeartbeatIntervalSeconds(0)) |
| 260 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 261 | 258 | .build(); |
| 262 | 259 | |
| 263 | 260 | try { |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +109 −33
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | import org.testng.annotations.Test; |
| 29 | 29 | |
| 30 | 30 | import java.net.InetSocketAddress; |
| 31 | +import java.util.Collection; | |
| 31 | 32 | import java.util.Collections; |
| 32 | 33 | import java.util.Iterator; |
| 33 | 34 | import java.util.List; |
| @@ -39,10 +40,13 @@ | ||
| 39 | 40 | import static com.datastax.driver.core.ConditionChecker.check; |
| 40 | 41 | import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY; |
| 41 | 42 | import static com.google.common.collect.Lists.newArrayList; |
| 43 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 42 | 44 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 43 | 45 | import static org.mockito.Mockito.*; |
| 44 | 46 | import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE; |
| 47 | +import static org.scassandra.http.client.PrimingRequest.queryBuilder; | |
| 45 | 48 | import static org.scassandra.http.client.PrimingRequest.then; |
| 49 | +import static org.scassandra.http.client.Result.server_error; | |
| 46 | 50 | import static org.testng.Assert.fail; |
| 47 | 51 | |
| 48 | 52 | public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster { |
| @@ -112,13 +116,95 @@ | ||
| 112 | 116 | try { |
| 113 | 117 | failedBorrow.getConnection(); |
| 114 | 118 | 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 | + } | |
| 116 | 153 | } finally { |
| 117 | 154 | MockRequest.completeAll(allRequests); |
| 118 | 155 | cluster.close(); |
| 119 | 156 | } |
| 120 | 157 | } |
| 121 | 158 | |
| 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 | + | |
| 122 | 208 | /** |
| 123 | 209 | * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes. |
| 124 | 210 | * |
| @@ -201,32 +287,17 @@ | ||
| 201 | 287 | // be called when connection is released by previous requests completing, and that one set |
| 202 | 288 | // keyspace attempt should be tried. |
| 203 | 289 | |
| 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; | |
| 210 | 291 | for (MockRequest queuedRequest : queuedRequests) { |
| 211 | 292 | try { |
| 212 | 293 | Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS); |
| 213 | - fail("Expected an exception (because Scassandra doesn't support 'USE keyspace'"); | |
| 294 | + count++; | |
| 214 | 295 | } 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); | |
| 230 | 301 | break; |
| 231 | 302 | } |
| 232 | 303 | } |
| @@ -291,9 +362,9 @@ | ||
| 291 | 362 | Cluster cluster = createClusterBuilder().build(); |
| 292 | 363 | List<MockRequest> requests = newArrayList(); |
| 293 | 364 | try { |
| 365 | + HostConnectionPool pool = createPool(cluster, 1, 1); | |
| 294 | 366 | // Limit requests per connection to 100 so we don't exhaust stream ids. |
| 295 | 367 | cluster.getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, 100); |
| 296 | - HostConnectionPool pool = createPool(cluster, 1, 1); | |
| 297 | 368 | int maxQueueSize = 256; |
| 298 | 369 | |
| 299 | 370 | assertThat(pool.connections.size()).isEqualTo(1); |
| @@ -1171,8 +1242,8 @@ | ||
| 1171 | 1242 | |
| 1172 | 1243 | // Should create up to core connections. |
| 1173 | 1244 | verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class)); |
| 1174 | - assertThat(pool.connections).hasSize(1); | |
| 1175 | 1245 | |
| 1246 | + assertPoolSize(pool, 1); | |
| 1176 | 1247 | request.simulateSuccessResponse(); |
| 1177 | 1248 | } finally { |
| 1178 | 1249 | cluster.close(); |
| @@ -1181,6 +1252,8 @@ | ||
| 1181 | 1252 | |
| 1182 | 1253 | private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) { |
| 1183 | 1254 | cluster.getConfiguration().getPoolingOptions() |
| 1255 | + .setNewConnectionThreshold(HostDistance.LOCAL, 100) | |
| 1256 | + .setMaxRequestsPerConnection(HostDistance.LOCAL, 128) | |
| 1184 | 1257 | .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections) |
| 1185 | 1258 | .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections); |
| 1186 | 1259 | Session session = cluster.connect(); |
| @@ -1284,7 +1357,11 @@ | ||
| 1284 | 1357 | } |
| 1285 | 1358 | |
| 1286 | 1359 | 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); | |
| 1288 | 1365 | } |
| 1289 | 1366 | |
| 1290 | 1367 | private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException { |
| @@ -1325,8 +1402,8 @@ | ||
| 1325 | 1402 | } |
| 1326 | 1403 | } |
| 1327 | 1404 | |
| 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); | |
| 1330 | 1407 | Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() { |
| 1331 | 1408 | @Override |
| 1332 | 1409 | public void onSuccess(Connection connection) { |
| @@ -1352,15 +1429,14 @@ | ||
| 1352 | 1429 | responseHandler.cancelHandler(); |
| 1353 | 1430 | } |
| 1354 | 1431 | |
| 1355 | - // Get the connection, assuming pool acquisition completed | |
| 1356 | 1432 | Connection getConnection() { |
| 1357 | 1433 | 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); | |
| 1362 | 1435 | } catch (ExecutionException e) { |
| 1363 | 1436 | throw Throwables.propagate(e.getCause()); |
| 1437 | + } catch (TimeoutException e) { | |
| 1438 | + fail("Timed out getting connection"); | |
| 1439 | + return null; // never reached | |
| 1364 | 1440 | } |
| 1365 | 1441 | } |
| 1366 | 1442 |
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +0 −2
| @@ -46,8 +46,6 @@ | ||
| 46 | 46 | cluster = Cluster.builder() |
| 47 | 47 | .addContactPoint(TestUtils.ipOfNode(1)) |
| 48 | 48 | .withPort(scassandra.getBinaryPort()) |
| 49 | - // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash | |
| 50 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 51 | 49 | .withPoolingOptions(new PoolingOptions() |
| 52 | 50 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) |
| 53 | 51 | .setMaxConnectionsPerHost(HostDistance.LOCAL, 1) |
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +73 −23
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import com.google.common.collect.*; |
| 20 | 20 | import org.scassandra.Scassandra; |
| 21 | 21 | import org.scassandra.ScassandraFactory; |
| 22 | +import org.scassandra.cql.MapType; | |
| 22 | 23 | import org.scassandra.http.client.PrimingClient; |
| 23 | 24 | import org.scassandra.http.client.PrimingRequest; |
| 24 | 25 | import org.slf4j.Logger; |
| @@ -52,16 +53,26 @@ | ||
| 52 | 53 | |
| 53 | 54 | private final List<Map<String, ?>> keyspaceRows; |
| 54 | 55 | |
| 55 | - private static final java.util.UUID schemaVersion = UUIDs.random(); | |
| 56 | + private final String cassandraVersion; | |
| 56 | 57 | |
| 58 | + private static final java.util.UUID schemaVersion = UUIDs.random(); | |
| 57 | 59 | |
| 58 | 60 | private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos; |
| 59 | 61 | |
| 62 | + private final String keyspaceQuery; | |
| 63 | + | |
| 64 | + private final org.scassandra.http.client.types.ColumnMetadata[] keyspaceColumnTypes; | |
| 65 | + | |
| 60 | 66 | ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort, |
| 61 | - List<Map<String, ?>> keyspaceRows, | |
| 67 | + List<Map<String, ?>> keyspaceRows, String cassandraVersion, | |
| 62 | 68 | Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos) { |
| 63 | 69 | this.ipPrefix = ipPrefix; |
| 64 | 70 | 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"; | |
| 65 | 76 | this.forcedPeerInfos = forcedPeerInfos; |
| 66 | 77 | |
| 67 | 78 | int node = 1; |
| @@ -79,7 +90,30 @@ | ||
| 79 | 90 | } |
| 80 | 91 | instances = instanceListBuilder.build(); |
| 81 | 92 | 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 | + | |
| 83 | 117 | } |
| 84 | 118 | |
| 85 | 119 | public Scassandra node(int node) { |
| @@ -297,7 +331,7 @@ | ||
| 297 | 331 | addPeerInfo(row, dc, n + 1, "listen_address", getPeerInfo(dc, n + 1, "listen_address", address)); |
| 298 | 332 | addPeerInfo(row, dc, n + 1, "partitioner", "org.apache.cassandra.dht.Murmur3Partitioner"); |
| 299 | 333 | 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)); | |
| 301 | 335 | addPeerInfo(row, dc, n + 1, "tokens", ImmutableSet.of(tokens.get(n))); |
| 302 | 336 | addPeerInfo(row, dc, n + 1, "schema_version", schemaVersion); |
| 303 | 337 | addPeerInfo(row, dc, n + 1, "graph", false); |
| @@ -314,7 +348,7 @@ | ||
| 314 | 348 | addPeerInfo(row, dc, n + 1, "rpc_address", address); |
| 315 | 349 | addPeerInfo(row, dc, n + 1, "data_center", datacenter(dc)); |
| 316 | 350 | 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)); | |
| 318 | 352 | addPeerInfo(row, dc, n + 1, "tokens", ImmutableSet.of(Long.toString(tokens.get(n)))); |
| 319 | 353 | addPeerInfo(row, dc, n + 1, "host_id", UUIDs.random()); |
| 320 | 354 | addPeerInfo(row, dc, n + 1, "schema_version", schemaVersion); |
| @@ -356,11 +390,11 @@ | ||
| 356 | 390 | .build()) |
| 357 | 391 | .build()); |
| 358 | 392 | |
| 359 | - // Prime keyspaces | |
| 393 | + | |
| 360 | 394 | client.prime(PrimingRequest.queryBuilder() |
| 361 | - .withQuery("SELECT * FROM system.schema_keyspaces") | |
| 395 | + .withQuery(keyspaceQuery) | |
| 362 | 396 | .withThen(then() |
| 363 | - .withColumnTypes(SELECT_SCHEMA_KEYSPACES) | |
| 397 | + .withColumnTypes(keyspaceColumnTypes) | |
| 364 | 398 | .withRows(keyspaceRows) |
| 365 | 399 | .build()) |
| 366 | 400 | .build()); |
| @@ -440,6 +474,12 @@ | ||
| 440 | 474 | column("strategy_options", TEXT) |
| 441 | 475 | }; |
| 442 | 476 | |
| 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 | + | |
| 443 | 483 | static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMN_FAMILIES = { |
| 444 | 484 | column("bloom_filter_fp_chance", DOUBLE), |
| 445 | 485 | column("caching", TEXT), |
| @@ -495,6 +535,7 @@ | ||
| 495 | 535 | private String ipPrefix = TestUtils.IP_PREFIX; |
| 496 | 536 | private final List<Map<String, ?>> keyspaceRows = Lists.newArrayList(); |
| 497 | 537 | private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap(); |
| 538 | + private String cassandraVersion = null; | |
| 498 | 539 | |
| 499 | 540 | public ScassandraClusterBuilder withNodes(Integer... nodes) { |
| 500 | 541 | this.nodes = nodes; |
| @@ -507,36 +548,40 @@ | ||
| 507 | 548 | } |
| 508 | 549 | |
| 509 | 550 | 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 + "\"}"); | |
| 517 | 559 | keyspaceRows.add(simpleKeyspaceRow); |
| 518 | 560 | return this; |
| 519 | 561 | } |
| 520 | 562 | |
| 521 | 563 | public ScassandraClusterBuilder withNetworkTopologyKeyspace(String name, Map<Integer, Integer> replicationFactors) { |
| 522 | 564 | StringBuilder strategyOptionsBuilder = new StringBuilder("{"); |
| 565 | + ImmutableMap.Builder<String, String> replicationBuilder = ImmutableMap.builder(); | |
| 566 | + replicationBuilder.put("class", "org.apache.cassandra.locator.NetworkTopologyStrategy"); | |
| 567 | + | |
| 523 | 568 | for (Map.Entry<Integer, Integer> dc : replicationFactors.entrySet()) { |
| 524 | 569 | strategyOptionsBuilder.append("\""); |
| 525 | 570 | strategyOptionsBuilder.append(datacenter(dc.getKey())); |
| 526 | 571 | strategyOptionsBuilder.append("\":\""); |
| 527 | 572 | strategyOptionsBuilder.append(dc.getValue()); |
| 528 | 573 | strategyOptionsBuilder.append("\","); |
| 574 | + replicationBuilder.put(datacenter(dc.getKey()), "" + dc.getValue()); | |
| 529 | 575 | } |
| 530 | 576 | |
| 531 | 577 | String strategyOptions = strategyOptionsBuilder.substring(0, strategyOptionsBuilder.length() - 1) + "}"; |
| 532 | 578 | |
| 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()); | |
| 540 | 585 | keyspaceRows.add(ntsKeyspaceRow); |
| 541 | 586 | return this; |
| 542 | 587 | } |
| @@ -556,8 +601,13 @@ | ||
| 556 | 601 | return this; |
| 557 | 602 | } |
| 558 | 603 | |
| 604 | + public ScassandraClusterBuilder withCassandraVersion(String version) { | |
| 605 | + this.cassandraVersion = version; | |
| 606 | + return this; | |
| 607 | + } | |
| 608 | + | |
| 559 | 609 | 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); | |
| 561 | 611 | } |
| 562 | 612 | } |
| 563 | 613 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +0 −2
| @@ -79,8 +79,6 @@ | ||
| 79 | 79 | .withPort(scassandra.getBinaryPort()) |
| 80 | 80 | .addContactPoints(hostAddress.getAddress()) |
| 81 | 81 | .withPort(scassandra.getBinaryPort()) |
| 82 | - // Scassandra does not support V3 yet, and V4 may cause the server to crash | |
| 83 | - .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V2)) | |
| 84 | 82 | .withPoolingOptions(new PoolingOptions() |
| 85 | 83 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) |
| 86 | 84 | .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 @@ | ||
| 21 | 21 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; |
| 22 | 22 | import com.google.common.collect.ImmutableList; |
| 23 | 23 | import com.google.common.collect.ImmutableMap; |
| 24 | +import org.mockito.Mockito; | |
| 24 | 25 | import org.scassandra.http.client.Consistency; |
| 25 | 26 | import org.scassandra.http.client.PrimingRequest; |
| 26 | 27 | import org.scassandra.http.client.Result; |
| @@ -55,7 +56,6 @@ | ||
| 55 | 56 | cluster = Cluster.builder() |
| 56 | 57 | .addContactPoints(scassandras.address(2).getAddress()) |
| 57 | 58 | .withPort(scassandras.getBinaryPort()) |
| 58 | - .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet | |
| 59 | 59 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 60 | 60 | .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1)) |
| 61 | 61 | .withQueryOptions(new QueryOptions().setDefaultIdempotence(true)) |
| @@ -208,8 +208,6 @@ | ||
| 208 | 208 | Cluster cluster = Cluster.builder() |
| 209 | 209 | .addContactPoints(scassandras.address(2).getAddress()) |
| 210 | 210 | .withPort(scassandras.getBinaryPort()) |
| 211 | - // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash | |
| 212 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 213 | 211 | .withSpeculativeExecutionPolicy(mockPolicy) |
| 214 | 212 | .build(); |
| 215 | 213 | |
| @@ -225,6 +223,52 @@ | ||
| 225 | 223 | } |
| 226 | 224 | } |
| 227 | 225 | |
| 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 | + | |
| 228 | 272 | /** |
| 229 | 273 | * Custom retry policy that retries at ONE on read timeout. |
| 230 | 274 | * 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 @@ | ||
| 82 | 82 | .withPort(scassandras.getBinaryPort()) |
| 83 | 83 | .withRetryPolicy(retryPolicy) |
| 84 | 84 | .withLoadBalancingPolicy(new SortingLoadBalancingPolicy()) |
| 85 | - // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash | |
| 86 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 87 | 85 | .withPoolingOptions(new PoolingOptions() |
| 88 | 86 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) |
| 89 | 87 | .setMaxConnectionsPerHost(HostDistance.LOCAL, 1) |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +0 −2
| @@ -119,8 +119,6 @@ | ||
| 119 | 119 | Cluster whiteListedCluster = Cluster.builder() |
| 120 | 120 | .addContactPoints(scassandras.address(1).getAddress()) |
| 121 | 121 | .withPort(scassandras.getBinaryPort()) |
| 122 | - // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash | |
| 123 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 124 | 122 | .withRetryPolicy(retryPolicy) |
| 125 | 123 | .withLoadBalancingPolicy(firstHostOnlyPolicy) |
| 126 | 124 | .build(); |
modified manual/pooling/README.md +10 −5
| @@ -188,11 +188,15 @@ | ||
| 188 | 188 | requests), the acquisition attempt gets enqueued until a connection becomes |
| 189 | 189 | available again. |
| 190 | 190 | |
| 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. | |
| 196 | 200 | |
| 197 | 201 | If all hosts are busy with a full queue, the request will fail with a |
| 198 | 202 | [NoHostAvailableException][nhae]. If you inspect the map returns by this |
| @@ -286,6 +290,7 @@ | ||
| 286 | 290 | [sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int- |
| 287 | 291 | [rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis-- |
| 288 | 292 | [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- | |
| 289 | 294 | [nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html |
| 290 | 295 | [getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- |
| 291 | 296 | [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 @@ | ||
| 68 | 68 | <assertj.version>1.7.0</assertj.version> |
| 69 | 69 | <mockito.version>1.10.8</mockito.version> |
| 70 | 70 | <commons-exec.version>1.3</commons-exec.version> |
| 71 | - <scassandra.version>1.0.9</scassandra.version> | |
| 71 | + <scassandra.version>1.1.1</scassandra.version> | |
| 72 | 72 | <main.basedir>${project.basedir}</main.basedir> |
| 73 | 73 | <ipprefix>127.0.1.</ipprefix> |
| 74 | 74 | <test.groups>unit</test.groups> |