Elffuss BraidHub

kikocis/java-driver public

Fix edge cases in query cancellation (JAVA-653).
Changeset04d7447ddfe460ec8861cfc2fe9c6788594f4c427279d51df4e4bcd6982856c0
Authorolim7t <omichallat+github@gmail.com> · 2015-02-06 18:31 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-02-11 12:51 +01:00
Parents32fe6b31edc5

Browse the files at this changeset

3 files changed

modified driver-core/CHANGELOG.rst +2 −0
@@ -5,6 +5,8 @@
55 --------
66
77 - [bug] Fix edge cases where a connection was released twice (JAVA-651).
8+- [bug] Fix edge cases in query cancellation (JAVA-653).
9+
810
911 2.0.9.1:
1012 --------
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +19 −3
@@ -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
@@ -368,6 +369,10 @@
368369 }
369370
370371 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 {
371376
372377 Message.Request request = callback.request();
373378
@@ -394,6 +399,10 @@
394399 logger.trace("{} writing request {}", this, request);
395400 writer.incrementAndGet();
396401 channel.write(request).addListener(writeHandler(request, handler));
402+
403+ if (startTimeout)
404+ handler.startTimeout();
405+
397406 return handler;
398407 }
399408
@@ -864,8 +873,10 @@
864873 public final ResponseCallback callback;
865874 public final int retryCount;
866875
867- private final Timeout timeout;
868876 private final long startTime;
877+ private volatile Timeout timeout;
878+
879+ private final AtomicBoolean isCancelled = new AtomicBoolean();
869880
870881 public ResponseHandler(Connection connection, ResponseCallback callback) throws BusyConnectionException {
871882 this.connection = connection;
@@ -873,10 +884,12 @@
873884 this.callback = callback;
874885 this.retryCount = callback.retryCount();
875886
887+ this.startTime = System.nanoTime();
888+ }
889+
890+ void startTimeout() {
876891 long timeoutMs = connection.factory.getReadTimeoutMillis();
877892 this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
878-
879- this.startTime = System.nanoTime();
880893 }
881894
882895 void cancelTimeout() {
@@ -885,6 +898,9 @@
885898 }
886899
887900 public void cancelHandler() {
901+ if (!isCancelled.compareAndSet(false, true))
902+ return;
903+
888904 // We haven't really received a response: we want to remove the handle because we gave up on that
889905 // request and there is no point in holding the handler, but we don't release the streamId. If we
890906 // 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/RequestHandler.java +41 −23
@@ -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
@@ -615,7 +628,8 @@
615628 // The count increments on each retry.
616629 static class QueryState {
617630 static final QueryState INITIAL = new QueryState(-1, false);
618- 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);
619633
620634 final int retryCount;
621635 final boolean inProgress;
@@ -639,9 +653,13 @@
639653 return new QueryState(retryCount + 1, true);
640654 }
641655
656+ public boolean isCancelled() {
657+ return this == CANCELLED_WHILE_IN_PROGRESS || this == CANCELLED_WHILE_COMPLETE;
658+ }
659+
642660 @Override
643661 public String toString() {
644- return String.format("QueryState(count=%d, inProgress=%s)", retryCount, inProgress);
662+ return String.format("QueryState(count=%d, inProgress=%s, cancelled=%s)", retryCount, inProgress, isCancelled());
645663 }
646664 }
647665 }