Elffuss BraidHub

kikocis/java-driver public

Handle race between query timeout and completion (JAVA-449, JAVA-460, JAVA-471).
Changesete968aa87642cff786e7409f8f90657538667fde9e1ae0104ff95f1c39a0f5e31
Authorolim7t <omichallat+github@gmail.com> · 2014-09-27 20:58 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-09-29 15:57 +02:00
Parents7704c9cd2ab6

Browse the files at this changeset

5 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -7,6 +7,7 @@
77 - [bug] Handle null pool in PooledConnection.release (JAVA-449)
88 - [improvement] Defunct connection on request timeout (JAVA-425)
99 - [improvement] Try next host when we get a SERVER_ERROR (JAVA-426)
10+- [bug] Handle race between query timeout and completion (JAVA-449, JAVA-460, JAVA-471)
1011
1112
1213 2.0.6:
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +9 −3
@@ -351,21 +351,27 @@
351351
352352 // This is only called for internal calls, so don't bother with ExecutionInfo
353353 @Override
354- public void onSet(Connection connection, Message.Response response, long latency) {
354+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
355355 onSet(connection, response, null, null, latency);
356356 }
357357
358358 @Override
359- public void onException(Connection connection, Exception exception, long latency) {
359+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
360360 future.setException(exception);
361361 }
362362
363363 @Override
364- public void onTimeout(Connection connection, long latency) {
364+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
365365 // This won't be called directly since this will be wrapped by RequestHandler.
366366 throw new UnsupportedOperationException();
367367 }
368368
369+ @Override
370+ public int retryCount() {
371+ // This is only called for internal calls (i.e, when the callback is not wrapped in RequestHandler).
372+ // There is no retry logic in that case, so the value does not really matter.
373+ return 0;
374+ }
369375 }, statement);
370376
371377 return future;
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +22 −12
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import javax.net.ssl.SSLEngine;
19-import java.net.InetAddress;
2019 import java.net.InetSocketAddress;
2120 import java.util.Iterator;
2221 import java.util.concurrent.*;
@@ -382,7 +381,7 @@
382381 } else {
383382 ce = new TransportException(address, "Error writing", writeFuture.getCause());
384383 }
385- handler.callback.onException(Connection.this, defunct(ce), System.nanoTime() - handler.startTime);
384+ handler.callback.onException(Connection.this, defunct(ce), System.nanoTime() - handler.startTime, handler.retryCount);
386385 } else {
387386 logger.trace("{} request sent successfully", Connection.this);
388387 }
@@ -642,7 +641,7 @@
642641 return;
643642 }
644643 handler.cancelTimeout();
645- handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime);
644+ handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime, handler.retryCount);
646645
647646 // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
648647 // (note: this is racy as the signaling can be called more than once, but that's not a problem)
@@ -681,7 +680,7 @@
681680 {
682681 ResponseHandler handler = iter.next();
683682 handler.cancelTimeout();
684- handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime);
683+ handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime, handler.retryCount);
685684 iter.remove();
686685 }
687686 }
@@ -748,19 +747,25 @@
748747 return request;
749748 }
750749
750+ @Override
751+ public int retryCount() {
752+ // This is ignored, as there is no retry logic in this class
753+ return 0;
754+ }
755+
751756 @Override
752757 public void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency) {
753- onSet(connection, response, latency);
758+ onSet(connection, response, latency, 0);
754759 }
755760
756761 @Override
757- public void onSet(Connection connection, Message.Response response, long latency) {
762+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
758763 this.address = connection.address;
759764 super.set(response);
760765 }
761766
762767 @Override
763- public void onException(Connection connection, Exception exception, long latency) {
768+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
764769 // If all nodes are down, we will get a null connection here. This is fine, if we have
765770 // an exception, consumers shouldn't assume the address is not null.
766771 if (connection != null)
@@ -769,10 +774,11 @@
769774 }
770775
771776 @Override
772- public void onTimeout(Connection connection, long latency) {
777+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
773778 assert connection != null; // We always timeout on a specific connection, so this shouldn't be null
774779 this.address = connection.address;
775780 super.setException(new ConnectionException(connection.address, "Operation timed out"));
781+ return true;
776782 }
777783
778784 public InetSocketAddress getAddress() {
@@ -782,9 +788,10 @@
782788
783789 interface ResponseCallback {
784790 public Message.Request request();
785- public void onSet(Connection connection, Message.Response response, long latency);
786- public void onException(Connection connection, Exception exception, long latency);
787- public void onTimeout(Connection connection, long latency);
791+ public int retryCount();
792+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount);
793+ public void onException(Connection connection, Exception exception, long latency, int retryCount);
794+ public boolean onTimeout(Connection connection, long latency, int retryCount);
788795 }
789796
790797 static class ResponseHandler {
@@ -792,6 +799,7 @@
792799 public final Connection connection;
793800 public final int streamId;
794801 public final ResponseCallback callback;
802+ public final int retryCount;
795803
796804 private final Timeout timeout;
797805 private final long startTime;
@@ -800,6 +808,7 @@
800808 this.connection = connection;
801809 this.streamId = connection.dispatcher.streamIdHandler.next();
802810 this.callback = callback;
811+ this.retryCount = callback.retryCount();
803812
804813 long timeoutMs = connection.factory.getReadTimeoutMillis();
805814 this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
@@ -826,7 +835,8 @@
826835 return new TimerTask() {
827836 @Override
828837 public void run(Timeout timeout) {
829- callback.onTimeout(connection, System.nanoTime() - startTime);
838+ if (callback.onTimeout(connection, System.nanoTime() - startTime, retryCount))
839+ cancelHandler();
830840 }
831841 };
832842 }
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +12 −4
@@ -120,22 +120,23 @@
120120 }
121121
122122 @Override
123- public void onSet(Connection connection, Message.Response response, long latency) {
123+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
124124 // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler),
125125 // so don't bother with ExecutionInfo.
126126 onSet(connection, response, null, null, latency);
127127 }
128128
129129 @Override
130- public void onException(Connection connection, Exception exception, long latency) {
130+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
131131 setException(exception);
132132 }
133133
134134 @Override
135- public void onTimeout(Connection connection, long latency) {
136- // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler).
135+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
136+ // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
137137 // So just set an exception for the final result, which should be handled correctly by said internal call.
138138 setException(new ConnectionException(connection.address, "Operation timed out"));
139+ return true;
139140 }
140141
141142 // We sometimes need (in the driver) to set the future from outside this class,
@@ -257,4 +258,11 @@
257258 else
258259 throw new DriverInternalError("Unexpected exception thrown", e.getCause());
259260 }
261+
262+ @Override
263+ public int retryCount() {
264+ // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
265+ // There is no retry logic in that case, so the value does not really matter.
266+ return 0;
267+ }
260268 }
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +103 −20
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
1918 import java.net.InetSocketAddress;
2019 import java.nio.ByteBuffer;
2120 import java.util.ArrayList;
@@ -26,6 +25,7 @@
2625 import java.util.Map;
2726 import java.util.concurrent.TimeUnit;
2827 import java.util.concurrent.TimeoutException;
28+import java.util.concurrent.atomic.AtomicReference;
2929
3030 import com.codahale.metrics.Timer;
3131 import org.slf4j.Logger;
@@ -38,7 +38,6 @@
3838 import com.datastax.driver.core.exceptions.UnavailableException;
3939 import com.datastax.driver.core.exceptions.WriteTimeoutException;
4040 import com.datastax.driver.core.policies.*;
41-import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
4241 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
4342
4443 /**
@@ -46,7 +45,6 @@
4645 * unavailable/timeout.
4746 */
4847 class RequestHandler implements Connection.ResponseCallback {
49-
5048 private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
5149
5250 private final SessionManager manager;
@@ -57,10 +55,8 @@
5755 private volatile Host current;
5856 private volatile List<Host> triedHosts;
5957 private volatile HostConnectionPool currentPool;
58+ private final AtomicReference<QueryState> queryStateRef;
6059
61- // Note that we know that queryRetries can only be incremented by one writer at a time so a
62- // volatile is good enough.
63- private volatile int queryRetries;
6460 private volatile ConsistencyLevel retryConsistencyLevel;
6561
6662 private volatile Map<InetSocketAddress, Throwable> errors;
@@ -79,6 +75,7 @@
7975
8076 this.queryPlan = manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement);
8177 this.statement = statement;
78+ this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL);
8279
8380 this.timerContext = metricsEnabled()
8481 ? metrics().getRequestsTimer().time()
@@ -162,6 +159,8 @@
162159 }
163160
164161 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
162+ queryStateRef.set(queryStateRef.get().startNext());
163+
165164 final Host h = current;
166165 this.retryConsistencyLevel = newConsistencyLevel;
167166
@@ -236,7 +235,7 @@
236235 info = info.withAchievedConsistency(retryConsistencyLevel);
237236 callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
238237 } catch (Exception e) {
239- callback.onException(connection, new DriverInternalError("Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime);
238+ callback.onException(connection, new DriverInternalError("Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime, retryCount());
240239 }
241240 }
242241
@@ -245,12 +244,20 @@
245244 if (timerContext != null)
246245 timerContext.stop();
247246 } finally {
248- callback.onException(connection, exception, System.nanoTime() - startTime);
247+ callback.onException(connection, exception, System.nanoTime() - startTime, retryCount());
249248 }
250249 }
251250
252251 @Override
253- public void onSet(Connection connection, Message.Response response, long latency) {
252+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
253+ QueryState queryState = queryStateRef.get();
254+ if (!queryState.isInProgressAt(retryCount) ||
255+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
256+ logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
257+ retryCount, queryState, queryStateRef.get());
258+ return;
259+ }
260+
254261 Host queriedHost = current;
255262 try {
256263 if (connection instanceof PooledConnection)
@@ -278,7 +285,7 @@
278285 rte.getRequiredAcknowledgements(),
279286 rte.getReceivedAcknowledgements(),
280287 rte.wasDataRetrieved(),
281- queryRetries);
288+ retryCount);
282289
283290 if (metricsEnabled()) {
284291 if (retry.getType() == Type.RETRY)
@@ -298,7 +305,7 @@
298305 wte.getWriteType(),
299306 wte.getRequiredAcknowledgements(),
300307 wte.getReceivedAcknowledgements(),
301- queryRetries);
308+ retryCount);
302309
303310 if (metricsEnabled()) {
304311 if (retry.getType() == Type.RETRY)
@@ -317,7 +324,7 @@
317324 ue.getConsistencyLevel(),
318325 ue.getRequiredReplicas(),
319326 ue.getAliveReplicas(),
320- queryRetries);
327+ retryCount);
321328
322329 if (metricsEnabled()) {
323330 if (retry.getType() == Type.RETRY)
@@ -378,6 +385,7 @@
378385 connection.setKeyspace(prepareKeyspace);
379386 }
380387
388+ queryStateRef.set(queryStateRef.get().startNext());
381389 try {
382390 connection.write(prepareAndRetry(toPrepare.getQueryString()));
383391 } finally {
@@ -401,9 +409,8 @@
401409 else {
402410 switch (retry.getType()) {
403411 case RETRY:
404- ++queryRetries;
405412 if (logger.isDebugEnabled())
406- logger.debug("Doing retry {} for query {} at consistency {}", queryRetries, statement, retry.getRetryConsistencyLevel());
413+ logger.debug("Doing retry {} for query {} at consistency {}", retryCount, statement, retry.getRetryConsistencyLevel());
407414 if (metricsEnabled())
408415 metrics().getErrorMetrics().getRetries().inc();
409416 retry(true, retry.getRetryConsistencyLevel());
@@ -440,7 +447,20 @@
440447 }
441448
442449 @Override
443- public void onSet(Connection connection, Message.Response response, long latency) {
450+ public int retryCount() {
451+ return RequestHandler.this.retryCount();
452+ }
453+
454+ @Override
455+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
456+ QueryState queryState = queryStateRef.get();
457+ if (!queryState.isInProgressAt(retryCount) ||
458+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
459+ logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
460+ retryCount, queryState, queryStateRef.get());
461+ return;
462+ }
463+
444464 // TODO should we check the response ?
445465 switch (response.type) {
446466 case RESULT:
@@ -466,20 +486,35 @@
466486 }
467487
468488 @Override
469- public void onException(Connection connection, Exception exception, long latency) {
470- RequestHandler.this.onException(connection, exception, latency);
489+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
490+ RequestHandler.this.onException(connection, exception, latency, retryCount);
471491 }
472492
473493 @Override
474- public void onTimeout(Connection connection, long latency) {
494+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
495+ QueryState queryState = queryStateRef.get();
496+ if (!queryState.isInProgressAt(retryCount) ||
497+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
498+ logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
499+ retryCount, queryState, queryStateRef.get());
500+ return false;
501+ }
475502 logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
476503 retry(false, null);
504+ return true;
477505 }
478506 };
479507 }
480508
481509 @Override
482- public void onException(Connection connection, Exception exception, long latency) {
510+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
511+ QueryState queryState = queryStateRef.get();
512+ if (!queryState.isInProgressAt(retryCount) ||
513+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
514+ logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
515+ retryCount, queryState, queryStateRef.get());
516+ return;
517+ }
483518
484519 Host queriedHost = current;
485520 try {
@@ -505,7 +540,15 @@
505540 }
506541
507542 @Override
508- public void onTimeout(Connection connection, long latency) {
543+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
544+ QueryState queryState = queryStateRef.get();
545+ if (!queryState.isInProgressAt(retryCount) ||
546+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
547+ logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
548+ retryCount, queryState, queryStateRef.get());
549+ return false;
550+ }
551+
509552 Host queriedHost = current;
510553 try {
511554 // If a query times out, we consider that the host is unstable, so we defunct
@@ -522,10 +565,50 @@
522565 if (queriedHost != null)
523566 manager.cluster.manager.reportLatency(queriedHost, latency);
524567 }
568+ return true;
569+ }
570+
571+ @Override
572+ public int retryCount() {
573+ return queryStateRef.get().retryCount;
525574 }
526575
527576 interface Callback extends Connection.ResponseCallback {
528577 public void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
529578 public void register(RequestHandler handler);
530579 }
580+
581+ // This is used to prevent races between request completion (either success or error) and timeout.
582+ // A retry is in progress once we have written the request to the connection and until we get back a response or a timeout.
583+ // The count increments on each retry.
584+ static class QueryState {
585+ static QueryState INITIAL = new QueryState(0, true);
586+
587+ final int retryCount;
588+ final boolean inProgress;
589+
590+ private QueryState(int count, boolean inProgress) {
591+ this.retryCount = count;
592+ this.inProgress = inProgress;
593+ }
594+
595+ boolean isInProgressAt(int retryCount) {
596+ return inProgress && this.retryCount == retryCount;
597+ }
598+
599+ QueryState complete() {
600+ assert inProgress;
601+ return new QueryState(retryCount, false);
602+ }
603+
604+ QueryState startNext() {
605+ assert !inProgress;
606+ return new QueryState(retryCount + 1, true);
607+ }
608+
609+ @Override
610+ public String toString() {
611+ return String.format("QueryState(count=%d, inProgress=%s)", retryCount, inProgress);
612+ }
613+ }
531614 }