Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0.9_fixes' into 2.0
Changeset895c38bf77aa23666dbe72971a2ebfeb5f228a2c1315b1965aab4b85451a83a9
Authorolim7t <omichallat+github@gmail.com> · 2015-02-11 18:19 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-02-11 18:19 +01:00
Parents7d498797e847, 1a570ed7d747

Browse the files at this changeset

8 files changed

modified README.rst +1 −1
@@ -37,7 +37,7 @@
3737 <dependency>
3838 <groupId>com.datastax.cassandra</groupId>
3939 <artifactId>cassandra-driver-core</artifactId>
40- <version>2.0.9</version>
40+ <version>2.0.9.2</version>
4141 </dependency>
4242
4343 Compatibility
modified driver-core/CHANGELOG.rst +20 −0
@@ -10,6 +10,26 @@
1010
1111 Merged from 2.0.9_fixes branch:
1212
13+- [bug] Prevent race between cancellation and query completion (JAVA-614)
14+- [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if
15+ streamId was already released and reused (JAVA-632).
16+- [bug] Fix issue when newly opened pool fails before we could mark the node UP
17+ (JAVA-642)
18+- [bug] Fix unwanted LBP notifications when a contact host is down (JAVA-613)
19+- [bug] Fix edge cases where a connection was released twice (JAVA-651).
20+- [bug] Fix edge cases in query cancellation (JAVA-653).
21+
22+
23+2.0.9.2:
24+--------
25+
26+- [bug] Fix edge cases where a connection was released twice (JAVA-651).
27+- [bug] Fix edge cases in query cancellation (JAVA-653).
28+
29+
30+2.0.9.1:
31+--------
32+
1333 - [bug] Prevent race between cancellation and query completion (JAVA-614)
1434 - [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if
1535 streamId was already released and reused (JAVA-632).
modified driver-core/README.rst +1 −1
@@ -60,7 +60,7 @@
6060 <dependency>
6161 <groupId>com.datastax.cassandra</groupId>
6262 <artifactId>cassandra-driver-core</artifactId>
63- <version>2.0.9</version>
63+ <version>2.0.9.2</version>
6464 </dependency>
6565
6666
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +29 −6
@@ -19,6 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.Iterator;
2121 import java.util.concurrent.*;
22+import java.util.concurrent.atomic.AtomicBoolean;
2223 import java.util.concurrent.atomic.AtomicInteger;
2324 import java.util.concurrent.atomic.AtomicReference;
2425
@@ -318,11 +319,12 @@
318319 if (this.keyspace != null && this.keyspace.equals(keyspace))
319320 return;
320321
322+ Future future = null;
321323 try {
322324 logger.trace("{} Setting keyspace {}", this, keyspace);
323325 long timeout = factory.getConnectTimeoutMillis();
324326 // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
325- Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
327+ future = write(new Requests.Query("USE \"" + keyspace + '"'));
326328 Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
327329 switch (response.type) {
328330 case RESULT:
@@ -340,9 +342,16 @@
340342 } catch (ConnectionException e) {
341343 throw defunct(e);
342344 } catch (TimeoutException e) {
345+ // We've given up waiting on the future, but it's still running. Cancel to make sure that the request timeout logic
346+ // (readTimeout) will not kick in, because that would release the connection. This will work since connectTimeout is
347+ // generally lower than readTimeout (and if not, we'll get an ExecutionException and defunct below).
348+ future.cancel(true);
343349 logger.warn(String.format("Timeout while setting keyspace on connection to %s. This should not happen but is not critical (it will retried)", address));
350+ // Rethrow so that the caller will not try to use the connection, but do not defunct as we don't want to mark down
351+ throw new ConnectionException(address, "Timeout while setting keyspace on connection");
344352 } catch (BusyConnectionException e) {
345353 logger.warn(String.format("Tried to set the keyspace on busy connection to %s. This should not happen but is not critical (it will retried)", address));
354+ throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
346355 } catch (ExecutionException e) {
347356 throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
348357 }
@@ -364,6 +373,10 @@
364373 }
365374
366375 public ResponseHandler write(ResponseCallback callback) throws ConnectionException, BusyConnectionException {
376+ return write(callback, true);
377+ }
378+
379+ public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException {
367380
368381 Message.Request request = callback.request();
369382
@@ -390,6 +403,10 @@
390403 logger.trace("{} writing request {}", this, request);
391404 writer.incrementAndGet();
392405 channel.write(request).addListener(writeHandler(request, handler));
406+
407+ if (startTimeout)
408+ handler.startTimeout();
409+
393410 return handler;
394411 }
395412
@@ -882,8 +899,7 @@
882899 public boolean onTimeout(Connection connection, long latency, int retryCount) {
883900 assert connection != null; // We always timeout on a specific connection, so this shouldn't be null
884901 this.address = connection.address;
885- super.setException(new ConnectionException(connection.address, "Operation timed out"));
886- return true;
902+ return super.setException(new OperationTimedOutException(connection.address));
887903 }
888904
889905 public InetSocketAddress getAddress() {
@@ -906,8 +922,10 @@
906922 public final ResponseCallback callback;
907923 public final int retryCount;
908924
909- private final Timeout timeout;
910925 private final long startTime;
926+ private volatile Timeout timeout;
927+
928+ private final AtomicBoolean isCancelled = new AtomicBoolean();
911929
912930 public ResponseHandler(Connection connection, ResponseCallback callback) throws BusyConnectionException {
913931 this.connection = connection;
@@ -915,10 +933,12 @@
915933 this.callback = callback;
916934 this.retryCount = callback.retryCount();
917935
936+ this.startTime = System.nanoTime();
937+ }
938+
939+ void startTimeout() {
918940 long timeoutMs = connection.factory.getReadTimeoutMillis();
919941 this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
920-
921- this.startTime = System.nanoTime();
922942 }
923943
924944 void cancelTimeout() {
@@ -927,6 +947,9 @@
927947 }
928948
929949 public void cancelHandler() {
950+ if (!isCancelled.compareAndSet(false, true))
951+ return;
952+
930953 // We haven't really received a response: we want to remove the handle because we gave up on that
931954 // request and there is no point in holding the handler, but we don't release the streamId. If we
932955 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +1 −1
@@ -141,7 +141,7 @@
141141 public boolean onTimeout(Connection connection, long latency, int retryCount) {
142142 // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
143143 // So just set an exception for the final result, which should be handled correctly by said internal call.
144- setException(new ConnectionException(connection.address, "Operation timed out"));
144+ setException(new OperationTimedOutException(connection.address));
145145 return true;
146146 }
147147
added driver-core/src/main/java/com/datastax/driver/core/OperationTimedOutException.java +13 −0
@@ -0,0 +1,13 @@
1+package com.datastax.driver.core;
2+
3+import java.net.InetSocketAddress;
4+
5+/**
6+ * Thrown on a client-side timeout, i.e. when the client didn't hear back from the server within
7+ * {@link SocketOptions#getReadTimeoutMillis()}.
8+ */
9+class OperationTimedOutException extends ConnectionException {
10+ public OperationTimedOutException(InetSocketAddress address) {
11+ super(address, "Operation timed out");
12+ }
13+}
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +61 −46
@@ -56,7 +56,6 @@
5656 private volatile List<Host> triedHosts;
5757 private volatile HostConnectionPool currentPool;
5858 private final AtomicReference<QueryState> queryStateRef;
59- private volatile boolean shouldCancelConnectionHandler;
6059
6160 // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from
6261 // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an
@@ -99,7 +98,7 @@
9998
10099 public void sendRequest() {
101100 try {
102- while (queryPlan.hasNext() && queryStateRef.get() != QueryState.CANCELLED) {
101+ while (queryPlan.hasNext() && !queryStateRef.get().isCancelled()) {
103102 Host host = queryPlan.next();
104103 logger.trace("Querying node {}", host);
105104 if (query(host))
@@ -159,25 +158,30 @@
159158 // before connection.write has completed
160159 connectionHandler = null;
161160
162- // Set query state to "in progress" at next iteration
161+ // Ensure query state is "in progress" (can be already if connection.write failed on a previous node and we're retrying)
163162 while (true) {
164163 QueryState previous = queryStateRef.get();
165- assert !previous.inProgress;
166- if (previous == QueryState.CANCELLED) {
164+ if (previous.isCancelled()) {
165+ if (connection instanceof PooledConnection)
166+ ((PooledConnection)connection).release();
167167 return;
168168 }
169- if (queryStateRef.compareAndSet(previous, previous.startNext()))
169+ if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext()))
170170 break;
171171 }
172172
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)
173+ connectionHandler = connection.write(responseCallback, false);
174+ // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered
175+ // *before* the call to connection.write had returned.
176+ connectionHandler.startTimeout();
177+
178+ // Note that we could have already received the response here (so onSet() / onException() would have been called). This is
179+ // why we only test for CANCELLED_WHILE_IN_PROGRESS below.
180+
181+ // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have
182+ // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice,
183+ // but it knows how to deal with it).
184+ if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS)
181185 connectionHandler.cancelHandler();
182186 }
183187
@@ -196,7 +200,7 @@
196200 manager.executor().execute(new Runnable() {
197201 @Override
198202 public void run() {
199- if (queryStateRef.get() == QueryState.CANCELLED)
203+ if (queryStateRef.get().isCancelled())
200204 return;
201205 try {
202206 if (retryCurrent) {
@@ -212,12 +216,21 @@
212216 }
213217
214218 public void cancel() {
215- QueryState previous = queryStateRef.getAndSet(QueryState.CANCELLED);
216- if (previous.inProgress) {
217- if (connectionHandler != null)
218- connectionHandler.cancelHandler();
219- else
220- shouldCancelConnectionHandler = true;
219+ // Atomically set a special QueryState, that will cause any further operation to abort.
220+ // We want to remember whether a request was in progress when we did this, so there are two cancel states.
221+ while (true) {
222+ QueryState previous = queryStateRef.get();
223+ if (previous.isCancelled()) {
224+ return;
225+ } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) {
226+ // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
227+ // If it's still null, this will be handled by re-checking queryStateRef at the end of write().
228+ if (connectionHandler != null)
229+ connectionHandler.cancelHandler();
230+ return;
231+ } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
232+ return;
233+ }
221234 }
222235 }
223236
@@ -293,10 +306,8 @@
293306 }
294307
295308 Host queriedHost = current;
309+ boolean releaseConnection = true;
296310 try {
297- if (connection instanceof PooledConnection)
298- ((PooledConnection)connection).release();
299-
300311 switch (response.type) {
301312 case RESULT:
302313 setFinalResult(connection, response);
@@ -405,30 +416,23 @@
405416 return;
406417 }
407418
408- logger.info("Query {} is not prepared on {}, preparing before retrying executing. "
409- + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
410- toPrepare.getQueryString(), connection.address);
411419 String currentKeyspace = connection.keyspace();
412420 String prepareKeyspace = toPrepare.getQueryKeyspace();
413- // This shouldn't happen in normal use, because a user shouldn't try to execute
414- // a prepared statement with the wrong keyspace set. However, if it does, we'd rather
415- // prepare the query correctly and let the query executing return a meaningful error message
416- if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace)))
417- {
418- logger.debug("Setting keyspace for prepared query to {}", prepareKeyspace);
419- connection.setKeyspace(prepareKeyspace);
421+ if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) {
422+ // This shouldn't happen in normal use, because a user shouldn't try to execute
423+ // a prepared statement with the wrong keyspace set.
424+ // Fail fast (we can't change the keyspace to reprepare, because we're using a pooled connection
425+ // that's shared with other requests).
426+ throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)",
427+ toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
420428 }
421429
422- try {
423- write(connection, prepareAndRetry(toPrepare.getQueryString()));
424- } finally {
425- // Always reset the previous keyspace if needed
426- if (connection.keyspace() == null || !connection.keyspace().equals(currentKeyspace))
427- {
428- logger.debug("Setting back keyspace post query preparation to {}", currentKeyspace);
429- connection.setKeyspace(currentKeyspace);
430- }
431- }
430+ logger.info("Query {} is not prepared on {}, preparing before retrying executing. "
431+ + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
432+ toPrepare.getQueryString(), connection.address);
433+
434+ releaseConnection = false; // we're reusing it for the prepare call
435+ write(connection, prepareAndRetry(toPrepare.getQueryString()));
432436 // we're done for now, the prepareAndRetry callback will handle the rest
433437 return;
434438 default:
@@ -467,6 +471,9 @@
467471 } catch (Exception e) {
468472 setFinalException(connection, e);
469473 } finally {
474+ if (releaseConnection && connection instanceof PooledConnection)
475+ ((PooledConnection)connection).release();
476+
470477 if (queriedHost != null)
471478 manager.cluster.manager.reportLatency(queriedHost, latency);
472479 }
@@ -495,6 +502,9 @@
495502 return;
496503 }
497504
505+ if (connection instanceof PooledConnection)
506+ ((PooledConnection)connection).release();
507+
498508 // TODO should we check the response ?
499509 switch (response.type) {
500510 case RESULT:
@@ -618,7 +628,8 @@
618628 // The count increments on each retry.
619629 static class QueryState {
620630 static final QueryState INITIAL = new QueryState(-1, false);
621- static final QueryState CANCELLED = new QueryState(Integer.MIN_VALUE, false);
631+ static final QueryState CANCELLED_WHILE_IN_PROGRESS = new QueryState(Integer.MIN_VALUE, false);
632+ static final QueryState CANCELLED_WHILE_COMPLETE = new QueryState(Integer.MIN_VALUE + 1, false);
622633
623634 final int retryCount;
624635 final boolean inProgress;
@@ -642,9 +653,13 @@
642653 return new QueryState(retryCount + 1, true);
643654 }
644655
656+ public boolean isCancelled() {
657+ return this == CANCELLED_WHILE_IN_PROGRESS || this == CANCELLED_WHILE_COMPLETE;
658+ }
659+
645660 @Override
646661 public String toString() {
647- return String.format("QueryState(count=%d, inProgress=%s)", retryCount, inProgress);
662+ return String.format("QueryState(count=%d, inProgress=%s, cancelled=%s)", retryCount, inProgress, isCancelled());
648663 }
649664 }
650665 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +4 −1
@@ -516,6 +516,7 @@
516516 // Let's not wait too long if we can't get a connection. Things
517517 // will fix themselves once the user tries a query anyway.
518518 PooledConnection c = null;
519+ boolean timedOut = false;
519520 try {
520521 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
521522 c.write(new Requests.Prepare(query)).get();
@@ -529,8 +530,10 @@
529530 // We shouldn't really get exception while preparing a
530531 // query, so log this (but ignore otherwise as it's not a big deal)
531532 logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e);
533+ // If the query timed out, that already released the connection
534+ timedOut = e.getCause() instanceof OperationTimedOutException;
532535 } finally {
533- if (c != null)
536+ if (c != null && !timedOut)
534537 c.release();
535538 }
536539 }