kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | a6025d8125efbd4d1083e3debf6c145445f83fb0f1b91fdf52d82d19ae7fadc2 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2017-02-01 15:12 -08:00 |
| Committer | GitHub <noreply@github.com> · 2017-02-01 15:12 -08:00 |
| Parents | 89b1172e93b0 |
8 files changed
modified changelog/README.md +5 −0
| @@ -1,5 +1,10 @@ | ||
| 1 | 1 | ## Changelog |
| 2 | 2 | |
| 3 | +### 3.0.7 (in progress) | |
| 4 | + | |
| 5 | +- [bug] JAVA-1371: Reintroduce connection pool timeout. | |
| 6 | + | |
| 7 | + | |
| 3 | 8 | ### 3.0.6 |
| 4 | 9 | |
| 5 | 10 | - [bug] JAVA-1330: Add un/register for SchemaChangeListener in DelegatingCluster |
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/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
| @@ -289,8 +289,10 @@ | ||
| 289 | 289 | if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true)) |
| 290 | 290 | scheduleExecution(speculativeExecutionPlan.nextExecution(host)); |
| 291 | 291 | |
| 292 | + PoolingOptions poolingOptions = manager.configuration().getPoolingOptions(); | |
| 292 | 293 | ListenableFuture<Connection> connectionFuture = pool.borrowConnection( |
| 293 | - manager.configuration().getPoolingOptions().getMaxQueueSize()); | |
| 294 | + poolingOptions.getPoolTimeoutMillis(), TimeUnit.MILLISECONDS, | |
| 295 | + poolingOptions.getMaxQueueSize()); | |
| 294 | 296 | Futures.addCallback(connectionFuture, new FutureCallback<Connection>() { |
| 295 | 297 | @Override |
| 296 | 298 | 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/HostConnectionPoolTest.java +104 −15
| @@ -16,10 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.codahale.metrics.Gauge; |
| 19 | -import com.datastax.driver.core.exceptions.BusyConnectionException; | |
| 20 | -import com.datastax.driver.core.exceptions.BusyPoolException; | |
| 21 | -import com.datastax.driver.core.exceptions.ConnectionException; | |
| 22 | -import com.datastax.driver.core.exceptions.DriverException; | |
| 19 | +import com.datastax.driver.core.exceptions.*; | |
| 23 | 20 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 24 | 21 | import com.datastax.driver.core.utils.MoreFutures; |
| 25 | 22 | import com.google.common.base.Predicate; |
| @@ -31,6 +28,7 @@ | ||
| 31 | 28 | import org.testng.annotations.Test; |
| 32 | 29 | |
| 33 | 30 | import java.net.InetSocketAddress; |
| 31 | +import java.util.Collection; | |
| 34 | 32 | import java.util.Collections; |
| 35 | 33 | import java.util.Iterator; |
| 36 | 34 | import java.util.List; |
| @@ -42,10 +40,13 @@ | ||
| 42 | 40 | import static com.datastax.driver.core.ConditionChecker.check; |
| 43 | 41 | import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY; |
| 44 | 42 | import static com.google.common.collect.Lists.newArrayList; |
| 43 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 45 | 44 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 46 | 45 | import static org.mockito.Mockito.*; |
| 47 | 46 | import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE; |
| 47 | +import static org.scassandra.http.client.PrimingRequest.queryBuilder; | |
| 48 | 48 | import static org.scassandra.http.client.PrimingRequest.then; |
| 49 | +import static org.scassandra.http.client.Result.server_error; | |
| 49 | 50 | import static org.testng.Assert.fail; |
| 50 | 51 | |
| 51 | 52 | public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster { |
| @@ -115,13 +116,95 @@ | ||
| 115 | 116 | try { |
| 116 | 117 | failedBorrow.getConnection(); |
| 117 | 118 | fail("Expected a BusyPoolException"); |
| 118 | - } 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 | + } | |
| 119 | 153 | } finally { |
| 120 | 154 | MockRequest.completeAll(allRequests); |
| 121 | 155 | cluster.close(); |
| 122 | 156 | } |
| 123 | 157 | } |
| 124 | 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 | + | |
| 125 | 208 | /** |
| 126 | 209 | * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes. |
| 127 | 210 | * |
| @@ -209,8 +292,11 @@ | ||
| 209 | 292 | try { |
| 210 | 293 | Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS); |
| 211 | 294 | count++; |
| 212 | - } catch (TimeoutException te) { | |
| 295 | + } catch (ExecutionException e) { | |
| 213 | 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"); | |
| 214 | 300 | assertThat(count).isEqualTo(128); |
| 215 | 301 | break; |
| 216 | 302 | } |
| @@ -1156,8 +1242,8 @@ | ||
| 1156 | 1242 | |
| 1157 | 1243 | // Should create up to core connections. |
| 1158 | 1244 | verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class)); |
| 1159 | - assertThat(pool.connections).hasSize(1); | |
| 1160 | 1245 | |
| 1246 | + assertPoolSize(pool, 1); | |
| 1161 | 1247 | request.simulateSuccessResponse(); |
| 1162 | 1248 | } finally { |
| 1163 | 1249 | cluster.close(); |
| @@ -1271,7 +1357,11 @@ | ||
| 1271 | 1357 | } |
| 1272 | 1358 | |
| 1273 | 1359 | static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException { |
| 1274 | - 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); | |
| 1275 | 1365 | } |
| 1276 | 1366 | |
| 1277 | 1367 | private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException { |
| @@ -1312,8 +1402,8 @@ | ||
| 1312 | 1402 | } |
| 1313 | 1403 | } |
| 1314 | 1404 | |
| 1315 | - private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException { | |
| 1316 | - this.connectionFuture = pool.borrowConnection(maxQueueSize); | |
| 1405 | + private MockRequest(HostConnectionPool pool, int timeoutMillis, int maxQueueSize) throws ConnectionException { | |
| 1406 | + this.connectionFuture = pool.borrowConnection(timeoutMillis, MILLISECONDS, maxQueueSize); | |
| 1317 | 1407 | Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() { |
| 1318 | 1408 | @Override |
| 1319 | 1409 | public void onSuccess(Connection connection) { |
| @@ -1339,15 +1429,14 @@ | ||
| 1339 | 1429 | responseHandler.cancelHandler(); |
| 1340 | 1430 | } |
| 1341 | 1431 | |
| 1342 | - // Get the connection, assuming pool acquisition completed | |
| 1343 | 1432 | Connection getConnection() { |
| 1344 | 1433 | try { |
| 1345 | - if (!connectionFuture.isDone()) { | |
| 1346 | - throw new AssertionError("Borrow call did not complete"); | |
| 1347 | - } | |
| 1348 | - return Uninterruptibles.getUninterruptibly(connectionFuture); | |
| 1434 | + return Uninterruptibles.getUninterruptibly(connectionFuture, 500, MILLISECONDS); | |
| 1349 | 1435 | } catch (ExecutionException e) { |
| 1350 | 1436 | throw Throwables.propagate(e.getCause()); |
| 1437 | + } catch (TimeoutException e) { | |
| 1438 | + fail("Timed out getting connection"); | |
| 1439 | + return null; // never reached | |
| 1351 | 1440 | } |
| 1352 | 1441 | } |
| 1353 | 1442 |
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-- |