kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 9913b399123d389f87d6bfb74af975697795cc3d50f749ac4f8cc6d10e1444f2 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-01-30 15:48 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-01-30 15:48 +01:00 |
| Parents | b2cec176a184, 00adccdfeee8 |
9 files changed
modified driver-core/CHANGELOG.rst +6 −0
| @@ -4,6 +4,12 @@ | ||
| 4 | 4 | 2.0.9.1: |
| 5 | 5 | -------- |
| 6 | 6 | |
| 7 | +- [bug] Prevent race between cancellation and query completion (JAVA-614) | |
| 8 | +- [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if | |
| 9 | + streamId was already released and reused (JAVA-632). | |
| 10 | +- [bug] Fix issue when newly opened pool fails before we could mark the node UP | |
| 11 | + (JAVA-642) | |
| 12 | + | |
| 7 | 13 | |
| 8 | 14 | 2.0.9: |
| 9 | 15 | ------ |
modified driver-core/pom.xml +14 −0
| @@ -89,6 +89,20 @@ | ||
| 89 | 89 | <scope>test</scope> |
| 90 | 90 | </dependency> |
| 91 | 91 | |
| 92 | + <dependency> | |
| 93 | + <groupId>org.scassandra</groupId> | |
| 94 | + <artifactId>java-client</artifactId> | |
| 95 | + <!-- N.B. later versions of scassandra require JDK 7 --> | |
| 96 | + <version>0.4.1</version> | |
| 97 | + <scope>test</scope> | |
| 98 | + <exclusions> | |
| 99 | + <exclusion> | |
| 100 | + <groupId>ch.qos.logback</groupId> | |
| 101 | + <artifactId>logback-classic</artifactId> | |
| 102 | + </exclusion> | |
| 103 | + </exclusions> | |
| 104 | + </dependency> | |
| 105 | + | |
| 92 | 106 | </dependencies> |
| 93 | 107 | |
| 94 | 108 | <build> |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +30 −12
| @@ -276,9 +276,19 @@ | ||
| 276 | 276 | // sure the "suspected" mechanism work as expected |
| 277 | 277 | Host host = factory.manager.metadata.getHost(address); |
| 278 | 278 | if (host != null) { |
| 279 | + | |
| 280 | + // If the host was reconnecting, and this error happens right after we opened a connection pool, but | |
| 281 | + // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can | |
| 282 | + // lead to a race condition that leaves the node UP with a closed pool. | |
| 283 | + boolean belongsToReconnectingPool = host.state != Host.State.UP && | |
| 284 | + this instanceof PooledConnection && | |
| 285 | + (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed()); | |
| 286 | + | |
| 287 | + boolean markSuspected = isInitialized && !belongsToReconnectingPool; | |
| 288 | + | |
| 279 | 289 | // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant. |
| 280 | 290 | // This is not too much of a problem since calling onDown on a node that is already down has no effect. |
| 281 | - boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized); | |
| 291 | + boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), markSuspected); | |
| 282 | 292 | notifyOwnerWhenDefunct(isDown); |
| 283 | 293 | } |
| 284 | 294 | |
| @@ -364,12 +374,12 @@ | ||
| 364 | 374 | * never leave a handler that won't get an answer or be errored out. |
| 365 | 375 | */ |
| 366 | 376 | if (isDefunct) { |
| 367 | - dispatcher.removeHandler(handler.streamId, true); | |
| 377 | + dispatcher.removeHandler(handler, true); | |
| 368 | 378 | throw new ConnectionException(address, "Write attempt on defunct connection"); |
| 369 | 379 | } |
| 370 | 380 | |
| 371 | 381 | if (isClosed()) { |
| 372 | - dispatcher.removeHandler(handler.streamId, true); | |
| 382 | + dispatcher.removeHandler(handler, true); | |
| 373 | 383 | throw new ConnectionException(address, "Connection has been closed"); |
| 374 | 384 | } |
| 375 | 385 | |
| @@ -390,7 +400,7 @@ | ||
| 390 | 400 | logger.debug("{} Error writing request {}", Connection.this, request); |
| 391 | 401 | // Remove this handler from the dispatcher so it don't get notified of the error |
| 392 | 402 | // twice (we will fail that method already) |
| 393 | - dispatcher.removeHandler(handler.streamId, true); | |
| 403 | + dispatcher.removeHandler(handler, true); | |
| 394 | 404 | |
| 395 | 405 | final ConnectionException ce; |
| 396 | 406 | if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) { |
| @@ -623,19 +633,27 @@ | ||
| 623 | 633 | assert old == null; |
| 624 | 634 | } |
| 625 | 635 | |
| 626 | - public void removeHandler(int streamId, boolean releaseStreamId) { | |
| 636 | + public void removeHandler(ResponseHandler handler, boolean releaseStreamId) { | |
| 627 | 637 | |
| 628 | 638 | // If we don't release the ID, mark first so that we can rely later on the fact that if |
| 629 | 639 | // we receive a response for an ID with no handler, it's that this ID has been marked. |
| 630 | 640 | if (!releaseStreamId) |
| 631 | - streamIdHandler.mark(streamId); | |
| 632 | - | |
| 633 | - ResponseHandler handler = pending.remove(streamId); | |
| 634 | - if (handler != null) | |
| 635 | - handler.cancelTimeout(); | |
| 641 | + streamIdHandler.mark(handler.streamId); | |
| 642 | + | |
| 643 | + // If a RequestHandler is cancelled right when the response arrives, this method (called with releaseStreamId=false) will race with messageReceived. | |
| 644 | + // messageReceived could have already released the streamId, which could have already been reused by another request. We must not remove the handler | |
| 645 | + // if it's not ours, because that would cause the other request to hang forever. | |
| 646 | + boolean removed = pending.remove(handler.streamId, handler); | |
| 647 | + if (!removed) { | |
| 648 | + // We raced, so if we marked the streamId above, that was wrong. | |
| 649 | + if (!releaseStreamId) | |
| 650 | + streamIdHandler.unmark(handler.streamId); | |
| 651 | + return; | |
| 652 | + } | |
| 653 | + handler.cancelTimeout(); | |
| 636 | 654 | |
| 637 | 655 | if (releaseStreamId) |
| 638 | - streamIdHandler.release(streamId); | |
| 656 | + streamIdHandler.release(handler.streamId); | |
| 639 | 657 | |
| 640 | 658 | if (isClosed()) |
| 641 | 659 | tryTerminate(false); |
| @@ -864,7 +882,7 @@ | ||
| 864 | 882 | // request and there is no point in holding the handler, but we don't release the streamId. If we |
| 865 | 883 | // were, a new request could reuse that ID but get the answer to the request we just gave up on instead |
| 866 | 884 | // of its own answer, and we would have no way to detect that. |
| 867 | - connection.dispatcher.removeHandler(streamId, false); | |
| 885 | + connection.dispatcher.removeHandler(this, false); | |
| 868 | 886 | if (connection instanceof PooledConnection) |
| 869 | 887 | ((PooledConnection)connection).release(); |
| 870 | 888 | } |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +2 −2
| @@ -260,6 +260,8 @@ | ||
| 260 | 260 | } |
| 261 | 261 | |
| 262 | 262 | public void returnConnection(PooledConnection connection) { |
| 263 | + int inFlight = connection.inFlight.decrementAndGet(); | |
| 264 | + | |
| 263 | 265 | if (isClosed()) { |
| 264 | 266 | close(connection); |
| 265 | 267 | return; |
| @@ -271,8 +273,6 @@ | ||
| 271 | 273 | return; |
| 272 | 274 | } |
| 273 | 275 | |
| 274 | - int inFlight = connection.inFlight.decrementAndGet(); | |
| 275 | - | |
| 276 | 276 | if (trash.contains(connection)) { |
| 277 | 277 | if (inFlight == 0 && trash.remove(connection)) |
| 278 | 278 | close(connection); |
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +1 −1
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | */ |
| 24 | 24 | class PooledConnection extends Connection { |
| 25 | 25 | |
| 26 | - private final HostConnectionPool pool; | |
| 26 | + final HostConnectionPool pool; | |
| 27 | 27 | |
| 28 | 28 | /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */ |
| 29 | 29 | final AtomicBoolean markForTrash = new AtomicBoolean(); |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +44 −12
| @@ -56,6 +56,7 @@ | ||
| 56 | 56 | private volatile List<Host> triedHosts; |
| 57 | 57 | private volatile HostConnectionPool currentPool; |
| 58 | 58 | private final AtomicReference<QueryState> queryStateRef; |
| 59 | + private volatile boolean shouldCancelConnectionHandler; | |
| 59 | 60 | |
| 60 | 61 | // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from |
| 61 | 62 | // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an |
| @@ -67,7 +68,6 @@ | ||
| 67 | 68 | |
| 68 | 69 | private volatile Map<InetSocketAddress, Throwable> errors; |
| 69 | 70 | |
| 70 | - private volatile boolean isCanceled; | |
| 71 | 71 | private volatile Connection.ResponseHandler connectionHandler; |
| 72 | 72 | |
| 73 | 73 | private final Timer.Context timerContext; |
| @@ -99,7 +99,7 @@ | ||
| 99 | 99 | |
| 100 | 100 | public void sendRequest() { |
| 101 | 101 | try { |
| 102 | - while (queryPlan.hasNext() && !isCanceled) { | |
| 102 | + while (queryPlan.hasNext() && queryStateRef.get() != QueryState.CANCELLED) { | |
| 103 | 103 | Host host = queryPlan.next(); |
| 104 | 104 | logger.trace("Querying node {}", host); |
| 105 | 105 | if (query(host)) |
| @@ -126,7 +126,7 @@ | ||
| 126 | 126 | triedHosts.add(current); |
| 127 | 127 | } |
| 128 | 128 | current = host; |
| 129 | - connectionHandler = connection.write(this); | |
| 129 | + write(connection, this); | |
| 130 | 130 | return true; |
| 131 | 131 | } catch (ConnectionException e) { |
| 132 | 132 | // If we have any problem with the connection, move to the next node. |
| @@ -154,6 +154,33 @@ | ||
| 154 | 154 | } |
| 155 | 155 | } |
| 156 | 156 | |
| 157 | + private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException { | |
| 158 | + // Make sure cancel() does not see a stale connectionHandler if it sees the new query state | |
| 159 | + // before connection.write has completed | |
| 160 | + connectionHandler = null; | |
| 161 | + | |
| 162 | + // Set query state to "in progress" at next iteration | |
| 163 | + while (true) { | |
| 164 | + QueryState previous = queryStateRef.get(); | |
| 165 | + assert !previous.inProgress; | |
| 166 | + if (previous == QueryState.CANCELLED) { | |
| 167 | + return; | |
| 168 | + } | |
| 169 | + if (queryStateRef.compareAndSet(previous, previous.startNext())) | |
| 170 | + break; | |
| 171 | + } | |
| 172 | + | |
| 173 | + connectionHandler = connection.write(responseCallback); | |
| 174 | + | |
| 175 | + // N.B: onSet/onException could have already been called at this point | |
| 176 | + | |
| 177 | + // If cancel was called after we set the state to "in progress", but before connection.write, it might have seen a null connectionHandler. | |
| 178 | + // In this case we need to cancel it now to release the connection (because the next onSet/onException/onTimeout will see the CANCELLED | |
| 179 | + // state and return immediately). | |
| 180 | + if (shouldCancelConnectionHandler) | |
| 181 | + connectionHandler.cancelHandler(); | |
| 182 | + } | |
| 183 | + | |
| 157 | 184 | private void logError(InetSocketAddress address, Throwable exception) { |
| 158 | 185 | logger.debug("Error querying {}, trying next host (error is: {})", address, exception.toString()); |
| 159 | 186 | if (errors == null) |
| @@ -162,8 +189,6 @@ | ||
| 162 | 189 | } |
| 163 | 190 | |
| 164 | 191 | private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { |
| 165 | - queryStateRef.set(queryStateRef.get().startNext()); | |
| 166 | - | |
| 167 | 192 | final Host h = current; |
| 168 | 193 | this.retryConsistencyLevel = newConsistencyLevel; |
| 169 | 194 | |
| @@ -171,6 +196,8 @@ | ||
| 171 | 196 | manager.executor().execute(new Runnable() { |
| 172 | 197 | @Override |
| 173 | 198 | public void run() { |
| 199 | + if (queryStateRef.get() == QueryState.CANCELLED) | |
| 200 | + return; | |
| 174 | 201 | try { |
| 175 | 202 | if (retryCurrent) { |
| 176 | 203 | if (query(h)) |
| @@ -185,9 +212,13 @@ | ||
| 185 | 212 | } |
| 186 | 213 | |
| 187 | 214 | public void cancel() { |
| 188 | - isCanceled = true; | |
| 189 | - if (connectionHandler != null) | |
| 190 | - connectionHandler.cancelHandler(); | |
| 215 | + QueryState previous = queryStateRef.getAndSet(QueryState.CANCELLED); | |
| 216 | + if (previous.inProgress) { | |
| 217 | + if (connectionHandler != null) | |
| 218 | + connectionHandler.cancelHandler(); | |
| 219 | + else | |
| 220 | + shouldCancelConnectionHandler = true; | |
| 221 | + } | |
| 191 | 222 | } |
| 192 | 223 | |
| 193 | 224 | @Override |
| @@ -388,9 +419,8 @@ | ||
| 388 | 419 | connection.setKeyspace(prepareKeyspace); |
| 389 | 420 | } |
| 390 | 421 | |
| 391 | - queryStateRef.set(queryStateRef.get().startNext()); | |
| 392 | 422 | try { |
| 393 | - connection.write(prepareAndRetry(toPrepare.getQueryString())); | |
| 423 | + write(connection, prepareAndRetry(toPrepare.getQueryString())); | |
| 394 | 424 | } finally { |
| 395 | 425 | // Always reset the previous keyspace if needed |
| 396 | 426 | if (connection.keyspace() == null || !connection.keyspace().equals(currentKeyspace)) |
| @@ -583,10 +613,12 @@ | ||
| 583 | 613 | } |
| 584 | 614 | |
| 585 | 615 | // This is used to prevent races between request completion (either success or error) and timeout. |
| 586 | - // A retry is in progress once we have written the request to the connection and until we get back a response or a timeout. | |
| 616 | + // A retry is in progress once we have written the request to the connection and until we get back a response (see onSet | |
| 617 | + // or onException) or a timeout (see onTimeout). | |
| 587 | 618 | // The count increments on each retry. |
| 588 | 619 | static class QueryState { |
| 589 | - static QueryState INITIAL = new QueryState(0, true); | |
| 620 | + static final QueryState INITIAL = new QueryState(-1, false); | |
| 621 | + static final QueryState CANCELLED = new QueryState(Integer.MIN_VALUE, false); | |
| 590 | 622 | |
| 591 | 623 | final int retryCount; |
| 592 | 624 | final boolean inProgress; |
added driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +72 −0
| @@ -0,0 +1,72 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.concurrent.TimeUnit; | |
| 4 | +import java.util.concurrent.TimeoutException; | |
| 5 | + | |
| 6 | +import com.google.common.collect.ImmutableMap; | |
| 7 | +import org.scassandra.Scassandra; | |
| 8 | +import org.scassandra.http.client.PrimingRequest; | |
| 9 | +import org.testng.annotations.Test; | |
| 10 | + | |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 12 | + | |
| 13 | +public class RequestHandlerTest { | |
| 14 | + | |
| 15 | + @Test(groups = "long") | |
| 16 | + public void should_handle_race_between_response_and_cancellation() { | |
| 17 | + Scassandra scassandra = TestUtils.createScassandraServer(); | |
| 18 | + Cluster cluster = null; | |
| 19 | + | |
| 20 | + try { | |
| 21 | + // Use a mock server that takes a constant time to reply | |
| 22 | + scassandra.start(); | |
| 23 | + scassandra.primingClient().prime( | |
| 24 | + PrimingRequest.queryBuilder() | |
| 25 | + .withQuery("mock query") | |
| 26 | + .withRows(ImmutableMap.of("key", 1)) | |
| 27 | + .withFixedDelay(10) | |
| 28 | + .build() | |
| 29 | + ); | |
| 30 | + | |
| 31 | + cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(scassandra.getBinaryPort()) | |
| 32 | + .withPoolingOptions(new PoolingOptions() | |
| 33 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) | |
| 34 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)) | |
| 35 | + .build(); | |
| 36 | + | |
| 37 | + Session session = cluster.connect(); | |
| 38 | + | |
| 39 | + // To reproduce, we need to cancel the query exactly when the reply arrives. | |
| 40 | + // Run a few queries to estimate how much that will take. | |
| 41 | + int samples = 100; | |
| 42 | + long start = System.currentTimeMillis(); | |
| 43 | + for (int i = 0; i < samples; i++) { | |
| 44 | + session.execute("mock query"); | |
| 45 | + } | |
| 46 | + long elapsed = System.currentTimeMillis() - start; | |
| 47 | + long queryDuration = elapsed / samples; | |
| 48 | + | |
| 49 | + // Now run queries and cancel them after that estimated time | |
| 50 | + for (int i = 0; i < 2000; i++) { | |
| 51 | + ResultSetFuture future = session.executeAsync("mock query"); | |
| 52 | + try { | |
| 53 | + future.getUninterruptibly(queryDuration, TimeUnit.MILLISECONDS); | |
| 54 | + } catch (TimeoutException e) { | |
| 55 | + future.cancel(true); | |
| 56 | + } | |
| 57 | + } | |
| 58 | + | |
| 59 | + PooledConnection connection = getSingleConnection(session); | |
| 60 | + assertThat(connection.inFlight.get()).isEqualTo(0); | |
| 61 | + } finally { | |
| 62 | + if (cluster != null) | |
| 63 | + cluster.close(); | |
| 64 | + scassandra.stop(); | |
| 65 | + } | |
| 66 | + } | |
| 67 | + | |
| 68 | + private PooledConnection getSingleConnection(Session session) { | |
| 69 | + HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next(); | |
| 70 | + return pool.connections.get(0); | |
| 71 | + } | |
| 72 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +34 −0
| @@ -15,14 +15,18 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.io.IOException; | |
| 18 | 19 | import java.math.BigDecimal; |
| 19 | 20 | import java.math.BigInteger; |
| 20 | 21 | import java.net.InetAddress; |
| 22 | +import java.net.ServerSocket; | |
| 21 | 23 | import java.nio.ByteBuffer; |
| 22 | 24 | import java.util.*; |
| 23 | 25 | |
| 24 | 26 | import static org.testng.Assert.fail; |
| 25 | 27 | |
| 28 | +import org.scassandra.Scassandra; | |
| 29 | +import org.scassandra.ScassandraFactory; | |
| 26 | 30 | import org.slf4j.Logger; |
| 27 | 31 | import org.slf4j.LoggerFactory; |
| 28 | 32 | import org.testng.SkipException; |
| @@ -382,4 +386,34 @@ | ||
| 382 | 386 | fail(address + " not found in cluster metadata"); |
| 383 | 387 | return null; // never reached |
| 384 | 388 | } |
| 389 | + | |
| 390 | + /** | |
| 391 | + * @return A Scassandra instance with an arbitrarily chosen binary port from 8042-8142 and admin port from | |
| 392 | + * 8052-8152. | |
| 393 | + */ | |
| 394 | + public static Scassandra createScassandraServer() { | |
| 395 | + int binaryPort = findAvailablePort(8042); | |
| 396 | + int adminPort = findAvailablePort(8052); | |
| 397 | + return ScassandraFactory.createServer(binaryPort, adminPort); | |
| 398 | + } | |
| 399 | + | |
| 400 | + /** | |
| 401 | + * @param startingWith The first port to try, if unused will keep trying the next port until one is found up to | |
| 402 | + * 100 subsequent ports. | |
| 403 | + * @return A local port that is currently unused. | |
| 404 | + */ | |
| 405 | + public static int findAvailablePort(int startingWith) { | |
| 406 | + IOException last = null; | |
| 407 | + for(int port = startingWith; port < startingWith+100; port++) { | |
| 408 | + try { | |
| 409 | + ServerSocket s = new ServerSocket(port); | |
| 410 | + s.close(); | |
| 411 | + return port; | |
| 412 | + } catch (IOException e) { | |
| 413 | + last = e; | |
| 414 | + } | |
| 415 | + } | |
| 416 | + // If for whatever reason a port could not be acquired throw the last encountered exception. | |
| 417 | + throw new RuntimeException("Could not acquire an available port", last); | |
| 418 | + } | |
| 385 | 419 | } |
modified driver-core/src/test/resources/log4j.properties +3 −0
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | # Set root logger level to DEBUG and its only appender to A1. |
| 2 | 2 | log4j.rootLogger=INFO, A1 |
| 3 | 3 | |
| 4 | +# Scassandra's info log is a bit verbose | |
| 5 | +log4j.logger.org.scassandra=WARN | |
| 6 | + | |
| 4 | 7 | # A1 is set to be a ConsoleAppender. |
| 5 | 8 | log4j.appender.A1=org.apache.log4j.ConsoleAppender |
| 6 | 9 |