Elffuss BraidHub

kikocis/java-driver public

Merge pull request #277 from datastax/java651

Fix edge cases where a connection was released twice (JAVA-651).
Fix edge cases in query cancellation (JAVA-653).
Changeset58b7bcd1beb58dab9638d9d24a7f6d535c99ede4186ebf5b555bd760d285cc4f
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-11 15:06 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-11 15:06 +01:00
Parents3b424b26e723, 04d7447ddfe4

Browse the files at this changeset

6 files changed

modified driver-core/CHANGELOG.rst +3 −0
@@ -4,6 +4,9 @@
44 2.0.9.2:
55 --------
66
7+- [bug] Fix edge cases where a connection was released twice (JAVA-651).
8+- [bug] Fix edge cases in query cancellation (JAVA-653).
9+
710
811 2.0.9.1:
912 --------
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
@@ -314,11 +315,12 @@
314315 if (this.keyspace != null && this.keyspace.equals(keyspace))
315316 return;
316317
318+ Future future = null;
317319 try {
318320 logger.trace("{} Setting keyspace {}", this, keyspace);
319321 long timeout = factory.getConnectTimeoutMillis();
320322 // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
321- Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
323+ future = write(new Requests.Query("USE \"" + keyspace + '"'));
322324 Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
323325 switch (response.type) {
324326 case RESULT:
@@ -336,9 +338,16 @@
336338 } catch (ConnectionException e) {
337339 throw defunct(e);
338340 } catch (TimeoutException e) {
341+ // We've given up waiting on the future, but it's still running. Cancel to make sure that the request timeout logic
342+ // (readTimeout) will not kick in, because that would release the connection. This will work since connectTimeout is
343+ // generally lower than readTimeout (and if not, we'll get an ExecutionException and defunct below).
344+ future.cancel(true);
339345 logger.warn(String.format("Timeout while setting keyspace on connection to %s. This should not happen but is not critical (it will retried)", address));
346+ // Rethrow so that the caller will not try to use the connection, but do not defunct as we don't want to mark down
347+ throw new ConnectionException(address, "Timeout while setting keyspace on connection");
340348 } catch (BusyConnectionException e) {
341349 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));
350+ throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
342351 } catch (ExecutionException e) {
343352 throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
344353 }
@@ -360,6 +369,10 @@
360369 }
361370
362371 public ResponseHandler write(ResponseCallback callback) throws ConnectionException, BusyConnectionException {
372+ return write(callback, true);
373+ }
374+
375+ public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException {
363376
364377 Message.Request request = callback.request();
365378
@@ -386,6 +399,10 @@
386399 logger.trace("{} writing request {}", this, request);
387400 writer.incrementAndGet();
388401 channel.write(request).addListener(writeHandler(request, handler));
402+
403+ if (startTimeout)
404+ handler.startTimeout();
405+
389406 return handler;
390407 }
391408
@@ -833,8 +850,7 @@
833850 public boolean onTimeout(Connection connection, long latency, int retryCount) {
834851 assert connection != null; // We always timeout on a specific connection, so this shouldn't be null
835852 this.address = connection.address;
836- super.setException(new ConnectionException(connection.address, "Operation timed out"));
837- return true;
853+ return super.setException(new OperationTimedOutException(connection.address));
838854 }
839855
840856 public InetSocketAddress getAddress() {
@@ -857,8 +873,10 @@
857873 public final ResponseCallback callback;
858874 public final int retryCount;
859875
860- private final Timeout timeout;
861876 private final long startTime;
877+ private volatile Timeout timeout;
878+
879+ private final AtomicBoolean isCancelled = new AtomicBoolean();
862880
863881 public ResponseHandler(Connection connection, ResponseCallback callback) throws BusyConnectionException {
864882 this.connection = connection;
@@ -866,10 +884,12 @@
866884 this.callback = callback;
867885 this.retryCount = callback.retryCount();
868886
887+ this.startTime = System.nanoTime();
888+ }
889+
890+ void startTimeout() {
869891 long timeoutMs = connection.factory.getReadTimeoutMillis();
870892 this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
871-
872- this.startTime = System.nanoTime();
873893 }
874894
875895 void cancelTimeout() {
@@ -878,6 +898,9 @@
878898 }
879899
880900 public void cancelHandler() {
901+ if (!isCancelled.compareAndSet(false, true))
902+ return;
903+
881904 // We haven't really received a response: we want to remove the handle because we gave up on that
882905 // request and there is no point in holding the handler, but we don't release the streamId. If we
883906 // 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 }