kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 31367d613eddffe1143e7beebb4ee198baaf8ab0f81002a7fac011e70e05d48d |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-03-28 17:38 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-04-24 17:55 +02:00 |
| Parents | ad54027f9a3c |
24 files changed
modified driver-core/CHANGELOG.rst +2 −0
| @@ -43,6 +43,8 @@ | ||
| 43 | 43 | - [improvement] Remove "suspected" mechanism (JAVA-617) |
| 44 | 44 | - [improvement] Don't mark connection defunct on client timeout (reverts |
| 45 | 45 | JAVA-425) |
| 46 | +- [new feature] Speculative query executions (JAVA-561) | |
| 47 | +- [bug] Release connection before completing the ResultSetFuture (JAVA-666) | |
| 46 | 48 | |
| 47 | 49 | Merged from 2.0.9_fixes branch: |
| 48 | 50 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +25 −4
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 27 | |
| 28 | 28 | import com.google.common.annotations.VisibleForTesting; |
| 29 | +import com.google.common.base.Objects; | |
| 29 | 30 | import com.google.common.base.Predicates; |
| 30 | 31 | import com.google.common.collect.*; |
| 31 | 32 | import com.google.common.util.concurrent.*; |
| @@ -571,6 +572,7 @@ | ||
| 571 | 572 | private ReconnectionPolicy reconnectionPolicy; |
| 572 | 573 | private RetryPolicy retryPolicy; |
| 573 | 574 | private AddressTranslater addressTranslater; |
| 575 | + private SpeculativeExecutionPolicy speculativeExecutionPolicy; | |
| 574 | 576 | |
| 575 | 577 | private ProtocolOptions.Compression compression = ProtocolOptions.Compression.NONE; |
| 576 | 578 | private SSLOptions sslOptions = null; |
| @@ -871,7 +873,7 @@ | ||
| 871 | 873 | * Configures the address translater to use for the new cluster. |
| 872 | 874 | * <p> |
| 873 | 875 | * See {@link AddressTranslater} for more detail on address translation, |
| 874 | - * but the default tanslater, {@link IdentityTranslater}, should be | |
| 876 | + * but the default translater, {@link IdentityTranslater}, should be | |
| 875 | 877 | * correct in most cases. If unsure, stick to the default. |
| 876 | 878 | * |
| 877 | 879 | * @param translater the translater to use. |
| @@ -882,6 +884,20 @@ | ||
| 882 | 884 | return this; |
| 883 | 885 | } |
| 884 | 886 | |
| 887 | + /** | |
| 888 | + * Configures the speculative execution policy to use for the new cluster. | |
| 889 | + * <p> | |
| 890 | + * If no policy is set through this method, {@link Policies#defaultSpeculativeExecutionPolicy()} | |
| 891 | + * will be used instead. | |
| 892 | + * | |
| 893 | + * @param policy the policy to use. | |
| 894 | + * @return this Builder. | |
| 895 | + */ | |
| 896 | + public Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy) { | |
| 897 | + this.speculativeExecutionPolicy = policy; | |
| 898 | + return this; | |
| 899 | + } | |
| 900 | + | |
| 885 | 901 | /** |
| 886 | 902 | * Uses the provided credentials when connecting to Cassandra hosts. |
| 887 | 903 | * <p> |
| @@ -1067,9 +1083,10 @@ | ||
| 1067 | 1083 | public Configuration getConfiguration() { |
| 1068 | 1084 | Policies policies = new Policies( |
| 1069 | 1085 | loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy, |
| 1070 | - reconnectionPolicy == null ? Policies.defaultReconnectionPolicy() : reconnectionPolicy, | |
| 1071 | - retryPolicy == null ? Policies.defaultRetryPolicy() : retryPolicy, | |
| 1072 | - addressTranslater == null ? Policies.defaultAddressTranslater() : addressTranslater | |
| 1086 | + Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()), | |
| 1087 | + Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()), | |
| 1088 | + Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()), | |
| 1089 | + Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy()) | |
| 1073 | 1090 | ); |
| 1074 | 1091 | return new Configuration(policies, |
| 1075 | 1092 | new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression), |
| @@ -1301,6 +1318,10 @@ | ||
| 1301 | 1318 | return configuration.getPolicies().getLoadBalancingPolicy(); |
| 1302 | 1319 | } |
| 1303 | 1320 | |
| 1321 | + SpeculativeExecutionPolicy speculativeRetryPolicy() { | |
| 1322 | + return configuration.getPolicies().getSpeculativeExecutionPolicy(); | |
| 1323 | + } | |
| 1324 | + | |
| 1304 | 1325 | ReconnectionPolicy reconnectionPolicy() { |
| 1305 | 1326 | return configuration.getPolicies().getReconnectionPolicy(); |
| 1306 | 1327 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +9 −4
| @@ -62,11 +62,16 @@ | ||
| 62 | 62 | * The list of tried hosts for this query. |
| 63 | 63 | * <p> |
| 64 | 64 | * In general, this will be a singleton list with the host that coordinated |
| 65 | - * that query. However, if an host is tried by the driver but is dead or in | |
| 66 | - * error, that host is recorded and the query is retry. Also, on a timeout | |
| 67 | - * or unavailable exception, some | |
| 65 | + * that query. However: | |
| 66 | + * <ul> | |
| 67 | + * <li>if a host is tried by the driver but is dead or in | |
| 68 | + * error, that host is recorded and the query is retried;</li> | |
| 69 | + * <li>on a timeout or unavailable exception, some | |
| 68 | 70 | * {@link com.datastax.driver.core.policies.RetryPolicy} may retry the |
| 69 | - * query on the same host, so the same host might appear twice. | |
| 71 | + * query on the same host, so the same host might appear twice.</li> | |
| 72 | + * <li>if {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions} | |
| 73 | + * are enabled, other hosts might have been tried speculatively as well.</li> | |
| 74 | + * </ul> | |
| 70 | 75 | * <p> |
| 71 | 76 | * If you are only interested in fetching the final (and often only) node |
| 72 | 77 | * coordinating the query, {@link #getQueriedHost} provides a shortcut to |
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +26 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.nio.ByteBuffer; | |
| 18 | 19 | import java.util.EnumSet; |
| 19 | 20 | import java.util.List; |
| 20 | 21 | import java.util.UUID; |
| @@ -102,6 +103,31 @@ | ||
| 102 | 103 | public boolean isTracingRequested() { |
| 103 | 104 | return tracingRequested; |
| 104 | 105 | } |
| 106 | + | |
| 107 | + ConsistencyLevel consistency() { | |
| 108 | + switch (this.type) { | |
| 109 | + case QUERY: return ((Requests.Query)this).options.consistency; | |
| 110 | + case EXECUTE: return ((Requests.Execute)this).options.consistency; | |
| 111 | + case BATCH: return ((Requests.Batch)this).consistency; | |
| 112 | + default: return null; | |
| 113 | + } | |
| 114 | + } | |
| 115 | + | |
| 116 | + ConsistencyLevel serialConsistency() { | |
| 117 | + switch (this.type) { | |
| 118 | + case QUERY: return ((Requests.Query)this).options.serialConsistency; | |
| 119 | + case EXECUTE: return ((Requests.Execute)this).options.serialConsistency; | |
| 120 | + default: return null; | |
| 121 | + } | |
| 122 | + } | |
| 123 | + | |
| 124 | + ByteBuffer pagingState() { | |
| 125 | + switch (this.type) { | |
| 126 | + case QUERY: return ((Requests.Query)this).options.pagingState; | |
| 127 | + case EXECUTE: return ((Requests.Execute)this).options.pagingState; | |
| 128 | + default: return null; | |
| 129 | + } | |
| 130 | + } | |
| 105 | 131 | } |
| 106 | 132 | |
| 107 | 133 | public static abstract class Response extends Message { |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +15 −3
| @@ -18,11 +18,10 @@ | ||
| 18 | 18 | import java.util.HashSet; |
| 19 | 19 | import java.util.Set; |
| 20 | 20 | |
| 21 | -import com.codahale.metrics.Gauge; | |
| 22 | -import com.codahale.metrics.MetricRegistryListener; | |
| 23 | - | |
| 24 | 21 | import com.codahale.metrics.*; |
| 25 | 22 | |
| 23 | +import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; | |
| 24 | + | |
| 26 | 25 | /** |
| 27 | 26 | * Metrics exposed by the driver. |
| 28 | 27 | * <p> |
| @@ -286,6 +285,8 @@ | ||
| 286 | 285 | private final Counter ignoresOnReadTimeout = registry.counter("ignores-on-read-timeout"); |
| 287 | 286 | private final Counter ignoresOnUnavailable = registry.counter("ignores-on-unavailable"); |
| 288 | 287 | |
| 288 | + private final Counter speculativeExecutions = registry.counter("speculative-executions"); | |
| 289 | + | |
| 289 | 290 | /** |
| 290 | 291 | * Returns the number of connection to Cassandra nodes errors. |
| 291 | 292 | * <p> |
| @@ -445,5 +446,16 @@ | ||
| 445 | 446 | public Counter getIgnoresOnUnavailable() { |
| 446 | 447 | return ignoresOnUnavailable; |
| 447 | 448 | } |
| 449 | + | |
| 450 | + /** | |
| 451 | + * Returns the number of times a speculative execution was started | |
| 452 | + * because a previous execution did not complete within the delay | |
| 453 | + * specified by {@link SpeculativeExecutionPolicy}. | |
| 454 | + * | |
| 455 | + * @return the number of speculative executions. | |
| 456 | + */ | |
| 457 | + public Counter getSpeculativeExecutions() { | |
| 458 | + return speculativeExecutions; | |
| 459 | + } | |
| 448 | 460 | } |
| 449 | 461 | } |
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +3 −0
| @@ -535,6 +535,9 @@ | ||
| 535 | 535 | } |
| 536 | 536 | |
| 537 | 537 | private int append(Statement statement, StringBuilder buffer, int remaining) { |
| 538 | + if (statement instanceof StatementWrapper) | |
| 539 | + statement = ((StatementWrapper)statement).getWrappedStatement(); | |
| 540 | + | |
| 538 | 541 | if (statement instanceof RegularStatement) { |
| 539 | 542 | remaining = append(((RegularStatement)statement).getQueryString().trim(), buffer, remaining); |
| 540 | 543 | } else if (statement instanceof BoundStatement) { |
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +31 −0
| @@ -37,9 +37,15 @@ | ||
| 37 | 37 | */ |
| 38 | 38 | public static final int DEFAULT_FETCH_SIZE = 5000; |
| 39 | 39 | |
| 40 | + /** | |
| 41 | + * The default value for {@link #getDefaultIdempotence()}: {@code false}. | |
| 42 | + */ | |
| 43 | + public static final boolean DEFAULT_IDEMPOTENCE = false; | |
| 44 | + | |
| 40 | 45 | private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL; |
| 41 | 46 | private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL; |
| 42 | 47 | private volatile int fetchSize = DEFAULT_FETCH_SIZE; |
| 48 | + private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE; | |
| 43 | 49 | private volatile Cluster.Manager manager; |
| 44 | 50 | |
| 45 | 51 | /** |
| @@ -138,4 +144,29 @@ | ||
| 138 | 144 | public int getFetchSize() { |
| 139 | 145 | return fetchSize; |
| 140 | 146 | } |
| 147 | + | |
| 148 | + /** | |
| 149 | + * Sets the default idempotence for queries. | |
| 150 | + * <p> | |
| 151 | + * This will be used for statements for which {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 152 | + * returns {@code null}. | |
| 153 | + * | |
| 154 | + * @param defaultIdempotence the new value to set as default idempotence. | |
| 155 | + * @return this {@code QueryOptions} instance. | |
| 156 | + */ | |
| 157 | + public QueryOptions setDefaultIdempotence(boolean defaultIdempotence) { | |
| 158 | + this.defaultIdempotence = defaultIdempotence; | |
| 159 | + return this; | |
| 160 | + } | |
| 161 | + | |
| 162 | + /** | |
| 163 | + * The default idempotence for queries. | |
| 164 | + * <p> | |
| 165 | + * It defaults to {@link #DEFAULT_IDEMPOTENCE}. | |
| 166 | + * | |
| 167 | + * @return the default idempotence for queries. | |
| 168 | + */ | |
| 169 | + public boolean getDefaultIdempotence() { | |
| 170 | + return defaultIdempotence; | |
| 171 | + } | |
| 141 | 172 | } |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +633 −479
| @@ -16,608 +16,745 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.net.InetSocketAddress; |
| 19 | -import java.nio.ByteBuffer; | |
| 20 | -import java.util.ArrayList; | |
| 21 | -import java.util.Collections; | |
| 22 | -import java.util.HashMap; | |
| 23 | -import java.util.Iterator; | |
| 24 | -import java.util.List; | |
| 25 | -import java.util.Map; | |
| 19 | +import java.util.*; | |
| 20 | +import java.util.concurrent.ConcurrentHashMap; | |
| 21 | +import java.util.concurrent.CopyOnWriteArrayList; | |
| 26 | 22 | import java.util.concurrent.TimeUnit; |
| 27 | 23 | import java.util.concurrent.TimeoutException; |
| 24 | +import java.util.concurrent.atomic.AtomicBoolean; | |
| 25 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 28 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 29 | 27 | |
| 30 | 28 | import com.codahale.metrics.Timer; |
| 29 | +import com.google.common.collect.Sets; | |
| 30 | +import io.netty.util.HashedWheelTimer; | |
| 31 | +import io.netty.util.Timeout; | |
| 32 | +import io.netty.util.TimerTask; | |
| 31 | 33 | import org.slf4j.Logger; |
| 32 | 34 | import org.slf4j.LoggerFactory; |
| 33 | 35 | |
| 34 | 36 | import com.datastax.driver.core.exceptions.*; |
| 35 | -import com.datastax.driver.core.policies.*; | |
| 37 | +import com.datastax.driver.core.policies.RetryPolicy; | |
| 36 | 38 | import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type; |
| 39 | +import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan; | |
| 37 | 40 | |
| 38 | 41 | /** |
| 39 | 42 | * Handles a request to cassandra, dealing with host failover and retries on |
| 40 | 43 | * unavailable/timeout. |
| 41 | 44 | */ |
| 42 | -class RequestHandler implements Connection.ResponseCallback { | |
| 45 | +class RequestHandler { | |
| 43 | 46 | private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class); |
| 44 | 47 | |
| 48 | + final String id; | |
| 49 | + | |
| 45 | 50 | private final SessionManager manager; |
| 46 | 51 | private final Callback callback; |
| 47 | 52 | |
| 48 | - private final Iterator<Host> queryPlan; | |
| 53 | + private final QueryPlan queryPlan; | |
| 54 | + private final SpeculativeExecutionPlan speculativeExecutionPlan; | |
| 55 | + private final boolean allowSpeculativeExecutions; | |
| 56 | + private final Set<SpeculativeExecution> runningExecutions = Sets.newCopyOnWriteArraySet(); | |
| 57 | + private final Set<Timeout> scheduledExecutions = Sets.newCopyOnWriteArraySet(); | |
| 49 | 58 | private final Statement statement; |
| 50 | - private volatile Host current; | |
| 51 | - private volatile List<Host> triedHosts; | |
| 52 | - private volatile HostConnectionPool currentPool; | |
| 53 | - private final AtomicReference<QueryState> queryStateRef; | |
| 54 | - | |
| 55 | - // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from | |
| 56 | - // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an | |
| 57 | - // OVERLOADED error). | |
| 58 | - // This is incremented by one writer at a time, so volatile is good enough. | |
| 59 | - private volatile int retriesByPolicy; | |
| 59 | + private final HashedWheelTimer scheduler; | |
| 60 | 60 | |
| 61 | - private volatile ConsistencyLevel retryConsistencyLevel; | |
| 61 | + private volatile List<Host> triedHosts; | |
| 62 | 62 | |
| 63 | 63 | private volatile Map<InetSocketAddress, Throwable> errors; |
| 64 | 64 | |
| 65 | - private volatile Connection.ResponseHandler connectionHandler; | |
| 66 | - | |
| 67 | 65 | private final Timer.Context timerContext; |
| 68 | 66 | private final long startTime; |
| 69 | 67 | |
| 68 | + private final AtomicBoolean isDone = new AtomicBoolean(); | |
| 69 | + private AtomicInteger executionCount = new AtomicInteger(); | |
| 70 | + | |
| 70 | 71 | public RequestHandler(SessionManager manager, Callback callback, Statement statement) { |
| 72 | + this.id = Long.toString(System.identityHashCode(this)); | |
| 73 | + if(logger.isTraceEnabled()) | |
| 74 | + logger.trace("[{}] {}", id, statement); | |
| 71 | 75 | this.manager = manager; |
| 72 | 76 | this.callback = callback; |
| 77 | + this.scheduler = manager.cluster.manager.connectionFactory.timer; | |
| 73 | 78 | |
| 74 | 79 | callback.register(this); |
| 75 | 80 | |
| 76 | - this.queryPlan = manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement); | |
| 81 | + this.queryPlan = new QueryPlan(manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement)); | |
| 82 | + this.speculativeExecutionPlan = manager.speculativeRetryPolicy().newPlan(manager.poolsState.keyspace, statement); | |
| 83 | + this.allowSpeculativeExecutions = statement != Statement.DEFAULT | |
| 84 | + && statement.isIdempotentWithDefault(manager.configuration().getQueryOptions()); | |
| 77 | 85 | this.statement = statement; |
| 78 | - this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL); | |
| 79 | 86 | |
| 80 | 87 | this.timerContext = metricsEnabled() |
| 81 | - ? metrics().getRequestsTimer().time() | |
| 82 | - : null; | |
| 88 | + ? metrics().getRequestsTimer().time() | |
| 89 | + : null; | |
| 83 | 90 | this.startTime = System.nanoTime(); |
| 84 | 91 | } |
| 85 | 92 | |
| 86 | - private boolean metricsEnabled() { | |
| 87 | - return manager.configuration().getMetricsOptions() != null; | |
| 93 | + void sendRequest() { | |
| 94 | + startNewExecution(); | |
| 88 | 95 | } |
| 89 | 96 | |
| 90 | - private Metrics metrics() { | |
| 91 | - return manager.cluster.manager.metrics; | |
| 92 | - } | |
| 97 | + // Called when the corresponding ResultSetFuture is cancelled by the client | |
| 98 | + void cancel() { | |
| 99 | + if (!isDone.compareAndSet(false, true)) | |
| 100 | + return; | |
| 93 | 101 | |
| 94 | - public void sendRequest() { | |
| 95 | - try { | |
| 96 | - while (queryPlan.hasNext() && !queryStateRef.get().isCancelled()) { | |
| 97 | - Host host = queryPlan.next(); | |
| 98 | - logger.trace("Querying node {}", host); | |
| 99 | - if (query(host)) | |
| 100 | - return; | |
| 101 | - } | |
| 102 | - setFinalException(null, new NoHostAvailableException(errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors)); | |
| 103 | - } catch (Exception e) { | |
| 104 | - // Shouldn't happen really, but if ever the loadbalancing policy returned iterator throws, we don't want to block. | |
| 105 | - setFinalException(null, new DriverInternalError("An unexpected error happened while sending requests", e)); | |
| 106 | - } | |
| 102 | + cancelPendingExecutions(null); | |
| 107 | 103 | } |
| 108 | 104 | |
| 109 | - private boolean query(Host host) { | |
| 110 | - currentPool = manager.pools.get(host); | |
| 111 | - if (currentPool == null || currentPool.isClosed()) | |
| 112 | - return false; | |
| 105 | + private void startNewExecution() { | |
| 106 | + if (isDone.get()) | |
| 107 | + return; | |
| 113 | 108 | |
| 114 | - Connection connection = null; | |
| 115 | - try { | |
| 116 | - connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS); | |
| 117 | - if (current != null) { | |
| 118 | - if (triedHosts == null) | |
| 119 | - triedHosts = new ArrayList<Host>(); | |
| 120 | - triedHosts.add(current); | |
| 121 | - } | |
| 122 | - current = host; | |
| 123 | - write(connection, this); | |
| 124 | - return true; | |
| 125 | - } catch (ConnectionException e) { | |
| 126 | - // If we have any problem with the connection, move to the next node. | |
| 127 | - if (metricsEnabled()) | |
| 128 | - metrics().getErrorMetrics().getConnectionErrors().inc(); | |
| 129 | - if (connection != null) | |
| 130 | - connection.release(); | |
| 131 | - logError(host.getSocketAddress(), e); | |
| 132 | - return false; | |
| 133 | - } catch (BusyConnectionException e) { | |
| 134 | - // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host. | |
| 135 | - connection.release(); | |
| 136 | - logError(host.getSocketAddress(), e); | |
| 137 | - return false; | |
| 138 | - } catch (TimeoutException e) { | |
| 139 | - // We timeout, log it but move to the next node. | |
| 140 | - logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)")); | |
| 141 | - return false; | |
| 142 | - } catch (RuntimeException e) { | |
| 143 | - if (connection != null) | |
| 144 | - connection.release(); | |
| 145 | - logger.error("Unexpected error while querying " + host.getAddress(), e); | |
| 146 | - logError(host.getSocketAddress(), e); | |
| 147 | - return false; | |
| 148 | - } | |
| 109 | + Message.Request request = callback.request(); | |
| 110 | + int position = executionCount.incrementAndGet(); | |
| 111 | + // Clone the request after the first execution, since we set the streamId on it later and we | |
| 112 | + // don't want to share that across executions. | |
| 113 | + if (position > 1) | |
| 114 | + request = manager.makeRequestMessage(statement, request.pagingState()) ; | |
| 115 | + | |
| 116 | + SpeculativeExecution execution = new SpeculativeExecution(request, position); | |
| 117 | + runningExecutions.add(execution); | |
| 118 | + execution.sendRequest(); | |
| 149 | 119 | } |
| 150 | 120 | |
| 151 | - private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException { | |
| 152 | - // Make sure cancel() does not see a stale connectionHandler if it sees the new query state | |
| 153 | - // before connection.write has completed | |
| 154 | - connectionHandler = null; | |
| 155 | - | |
| 156 | - // Ensure query state is "in progress" (can be already if connection.write failed on a previous node and we're retrying) | |
| 157 | - while (true) { | |
| 158 | - QueryState previous = queryStateRef.get(); | |
| 159 | - if (previous.isCancelled()) { | |
| 160 | - connection.release(); | |
| 161 | - return; | |
| 162 | - } | |
| 163 | - if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext())) | |
| 164 | - break; | |
| 165 | - } | |
| 121 | + private void scheduleExecution(long delayMillis) { | |
| 122 | + if (isDone.get() || delayMillis <= 0) | |
| 123 | + return; | |
| 124 | + if(logger.isTraceEnabled()) | |
| 125 | + logger.trace("[{}] Schedule next speculative execution in {} ms", id, delayMillis); | |
| 126 | + scheduledExecutions.add(scheduler.newTimeout(newExecutionTask, delayMillis, TimeUnit.MILLISECONDS)); | |
| 127 | + } | |
| 166 | 128 | |
| 167 | - connectionHandler = connection.write(responseCallback, false); | |
| 168 | - // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered | |
| 169 | - // *before* the call to connection.write had returned. | |
| 170 | - connectionHandler.startTimeout(); | |
| 171 | - | |
| 172 | - // Note that we could have already received the response here (so onSet() / onException() would have been called). This is | |
| 173 | - // why we only test for CANCELLED_WHILE_IN_PROGRESS below. | |
| 174 | - | |
| 175 | - // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have | |
| 176 | - // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice, | |
| 177 | - // but it knows how to deal with it). | |
| 178 | - if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS) | |
| 179 | - connectionHandler.cancelHandler(); | |
| 129 | + private final TimerTask newExecutionTask = new TimerTask() { | |
| 130 | + @Override | |
| 131 | + public void run(final Timeout timeout) throws Exception { | |
| 132 | + scheduledExecutions.remove(timeout); | |
| 133 | + if (!isDone.get()) | |
| 134 | + // We're on the timer thread so reschedule to another executor | |
| 135 | + manager.executor().execute(new Runnable() { | |
| 136 | + @Override | |
| 137 | + public void run() { | |
| 138 | + metrics().getErrorMetrics().getSpeculativeExecutions().inc(); | |
| 139 | + startNewExecution(); | |
| 140 | + } | |
| 141 | + }); | |
| 142 | + } | |
| 143 | + }; | |
| 144 | + | |
| 145 | + private void cancelPendingExecutions(SpeculativeExecution ignore) { | |
| 146 | + for (SpeculativeExecution execution : runningExecutions) | |
| 147 | + if (execution != ignore) // not vital but this produces nicer logs | |
| 148 | + execution.cancel(); | |
| 149 | + for (Timeout execution : scheduledExecutions) | |
| 150 | + execution.cancel(); | |
| 180 | 151 | } |
| 181 | 152 | |
| 182 | 153 | private void logError(InetSocketAddress address, Throwable exception) { |
| 183 | 154 | logger.debug("Error querying {}, trying next host (error is: {})", address, exception.toString()); |
| 184 | 155 | if (errors == null) |
| 185 | - errors = new HashMap<InetSocketAddress, Throwable>(); | |
| 156 | + errors = new ConcurrentHashMap<InetSocketAddress, Throwable>(); | |
| 186 | 157 | errors.put(address, exception); |
| 187 | 158 | } |
| 188 | 159 | |
| 189 | - private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { | |
| 190 | - final Host h = current; | |
| 191 | - this.retryConsistencyLevel = newConsistencyLevel; | |
| 192 | - | |
| 193 | - // We should not retry on the current thread as this will be an IO thread. | |
| 194 | - manager.executor().execute(new Runnable() { | |
| 195 | - @Override | |
| 196 | - public void run() { | |
| 197 | - if (queryStateRef.get().isCancelled()) | |
| 198 | - return; | |
| 199 | - try { | |
| 200 | - if (retryCurrent) { | |
| 201 | - if (query(h)) | |
| 202 | - return; | |
| 203 | - } | |
| 204 | - sendRequest(); | |
| 205 | - } catch (Exception e) { | |
| 206 | - setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e)); | |
| 207 | - } | |
| 208 | - } | |
| 209 | - }); | |
| 210 | - } | |
| 211 | - | |
| 212 | - public void cancel() { | |
| 213 | - // Atomically set a special QueryState, that will cause any further operation to abort. | |
| 214 | - // We want to remember whether a request was in progress when we did this, so there are two cancel states. | |
| 215 | - while (true) { | |
| 216 | - QueryState previous = queryStateRef.get(); | |
| 217 | - if (previous.isCancelled()) { | |
| 218 | - return; | |
| 219 | - } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) { | |
| 220 | - // The connectionHandler should be non-null, but we might miss the update if we're racing with write(). | |
| 221 | - // If it's still null, this will be handled by re-checking queryStateRef at the end of write(). | |
| 222 | - if (connectionHandler != null) | |
| 223 | - connectionHandler.cancelHandler(); | |
| 224 | - return; | |
| 225 | - } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) { | |
| 226 | - return; | |
| 227 | - } | |
| 228 | - } | |
| 229 | - } | |
| 230 | - | |
| 231 | - @Override | |
| 232 | - public Message.Request request() { | |
| 233 | - | |
| 234 | - Message.Request request = callback.request(); | |
| 235 | - if (retryConsistencyLevel != null && retryConsistencyLevel != consistencyOf(request)) | |
| 236 | - request = manager.makeRequestMessage(statement, retryConsistencyLevel, serialConsistencyOf(request), pagingStateOf(request)); | |
| 237 | - return request; | |
| 238 | - } | |
| 239 | - | |
| 240 | - private ConsistencyLevel consistencyOf(Message.Request request) { | |
| 241 | - switch (request.type) { | |
| 242 | - case QUERY: return ((Requests.Query)request).options.consistency; | |
| 243 | - case EXECUTE: return ((Requests.Execute)request).options.consistency; | |
| 244 | - case BATCH: return ((Requests.Batch)request).consistency; | |
| 245 | - default: return null; | |
| 160 | + private void setFinalResult(SpeculativeExecution execution, Connection connection, Message.Response response) { | |
| 161 | + if (!isDone.compareAndSet(false, true)) { | |
| 162 | + if(logger.isTraceEnabled()) | |
| 163 | + logger.trace("[{}] Got beaten to setting the result", execution.id); | |
| 164 | + return; | |
| 246 | 165 | } |
| 247 | - } | |
| 248 | 166 | |
| 249 | - private ConsistencyLevel serialConsistencyOf(Message.Request request) { | |
| 250 | - switch (request.type) { | |
| 251 | - case QUERY: return ((Requests.Query)request).options.serialConsistency; | |
| 252 | - case EXECUTE: return ((Requests.Execute)request).options.serialConsistency; | |
| 253 | - default: return null; | |
| 254 | - } | |
| 255 | - } | |
| 167 | + if(logger.isTraceEnabled()) | |
| 168 | + logger.trace("[{}] Setting final result", execution.id); | |
| 256 | 169 | |
| 257 | - private ByteBuffer pagingStateOf(Message.Request request) { | |
| 258 | - switch (request.type) { | |
| 259 | - case QUERY: return ((Requests.Query)request).options.pagingState; | |
| 260 | - case EXECUTE: return ((Requests.Execute)request).options.pagingState; | |
| 261 | - default: return null; | |
| 262 | - } | |
| 263 | - } | |
| 170 | + cancelPendingExecutions(execution); | |
| 264 | 171 | |
| 265 | - private void setFinalResult(Connection connection, Message.Response response) { | |
| 266 | 172 | try { |
| 267 | 173 | if (timerContext != null) |
| 268 | 174 | timerContext.stop(); |
| 269 | 175 | |
| 270 | - ExecutionInfo info = current.defaultExecutionInfo; | |
| 176 | + ExecutionInfo info = execution.current.defaultExecutionInfo; | |
| 271 | 177 | if (triedHosts != null) { |
| 272 | - triedHosts.add(current); | |
| 178 | + triedHosts.add(execution.current); | |
| 273 | 179 | info = new ExecutionInfo(triedHosts); |
| 274 | 180 | } |
| 275 | - if (retryConsistencyLevel != null) | |
| 276 | - info = info.withAchievedConsistency(retryConsistencyLevel); | |
| 181 | + if (execution.retryConsistencyLevel != null) | |
| 182 | + info = info.withAchievedConsistency(execution.retryConsistencyLevel); | |
| 277 | 183 | callback.onSet(connection, response, info, statement, System.nanoTime() - startTime); |
| 278 | 184 | } catch (Exception e) { |
| 279 | - callback.onException(connection, new DriverInternalError("Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime, retryCount()); | |
| 185 | + callback.onException(connection, | |
| 186 | + new DriverInternalError("Unexpected exception while setting final result from " + response, e), | |
| 187 | + System.nanoTime() - startTime, /*unused*/0); | |
| 280 | 188 | } |
| 281 | 189 | } |
| 282 | 190 | |
| 283 | - private void setFinalException(Connection connection, Exception exception) { | |
| 191 | + private void setFinalException(SpeculativeExecution execution, Connection connection, Exception exception) { | |
| 192 | + if (!isDone.compareAndSet(false, true)) { | |
| 193 | + if(logger.isTraceEnabled()) | |
| 194 | + logger.trace("[{}] Got beaten to setting final exception", execution.id); | |
| 195 | + return; | |
| 196 | + } | |
| 197 | + | |
| 198 | + if(logger.isTraceEnabled()) | |
| 199 | + logger.trace("[{}] Setting final exception", execution.id); | |
| 200 | + | |
| 201 | + cancelPendingExecutions(execution); | |
| 202 | + | |
| 284 | 203 | try { |
| 285 | 204 | if (timerContext != null) |
| 286 | 205 | timerContext.stop(); |
| 287 | 206 | } finally { |
| 288 | - callback.onException(connection, exception, System.nanoTime() - startTime, retryCount()); | |
| 207 | + callback.onException(connection, exception, System.nanoTime() - startTime, /*unused*/0); | |
| 289 | 208 | } |
| 290 | 209 | } |
| 291 | 210 | |
| 292 | - @Override | |
| 293 | - public void onSet(Connection connection, Message.Response response, long latency, int retryCount) { | |
| 294 | - QueryState queryState = queryStateRef.get(); | |
| 295 | - if (!queryState.isInProgressAt(retryCount) || | |
| 296 | - !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 297 | - logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 298 | - retryCount, queryState, queryStateRef.get()); | |
| 299 | - return; | |
| 300 | - } | |
| 211 | + // Triggered when an execution reaches the end of the query plan. | |
| 212 | + // This is only a failure if there are no other running executions. | |
| 213 | + private void reportNoMoreHosts(SpeculativeExecution execution) { | |
| 214 | + runningExecutions.remove(execution); | |
| 215 | + if (runningExecutions.isEmpty()) | |
| 216 | + setFinalException(execution, null, new NoHostAvailableException( | |
| 217 | + errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors)); | |
| 218 | + } | |
| 301 | 219 | |
| 302 | - Host queriedHost = current; | |
| 220 | + private boolean metricsEnabled() { | |
| 221 | + return manager.configuration().getMetricsOptions() != null; | |
| 222 | + } | |
| 303 | 223 | |
| 304 | - boolean releaseConnection = true; | |
| 305 | - Exception exceptionToReport = null; | |
| 306 | - try { | |
| 307 | - switch (response.type) { | |
| 308 | - case RESULT: | |
| 309 | - setFinalResult(connection, response); | |
| 310 | - break; | |
| 311 | - case ERROR: | |
| 312 | - Responses.Error err = (Responses.Error)response; | |
| 313 | - exceptionToReport = err.asException(connection.address); | |
| 314 | - RetryPolicy.RetryDecision retry = null; | |
| 315 | - RetryPolicy retryPolicy = statement.getRetryPolicy() == null | |
| 316 | - ? manager.configuration().getPolicies().getRetryPolicy() | |
| 317 | - : statement.getRetryPolicy(); | |
| 318 | - switch (err.code) { | |
| 319 | - case READ_TIMEOUT: | |
| 320 | - assert err.infos instanceof ReadTimeoutException; | |
| 321 | - if (metricsEnabled()) | |
| 322 | - metrics().getErrorMetrics().getReadTimeouts().inc(); | |
| 323 | - | |
| 324 | - ReadTimeoutException rte = (ReadTimeoutException)err.infos; | |
| 325 | - retry = retryPolicy.onReadTimeout(statement, | |
| 326 | - rte.getConsistencyLevel(), | |
| 327 | - rte.getRequiredAcknowledgements(), | |
| 328 | - rte.getReceivedAcknowledgements(), | |
| 329 | - rte.wasDataRetrieved(), | |
| 330 | - retriesByPolicy); | |
| 331 | - | |
| 332 | - if (metricsEnabled()) { | |
| 333 | - if (retry.getType() == Type.RETRY) | |
| 334 | - metrics().getErrorMetrics().getRetriesOnReadTimeout().inc(); | |
| 335 | - if (retry.getType() == Type.IGNORE) | |
| 336 | - metrics().getErrorMetrics().getIgnoresOnReadTimeout().inc(); | |
| 337 | - } | |
| 338 | - break; | |
| 339 | - case WRITE_TIMEOUT: | |
| 340 | - assert err.infos instanceof WriteTimeoutException; | |
| 341 | - if (metricsEnabled()) | |
| 342 | - metrics().getErrorMetrics().getWriteTimeouts().inc(); | |
| 343 | - | |
| 344 | - WriteTimeoutException wte = (WriteTimeoutException)err.infos; | |
| 345 | - retry = retryPolicy.onWriteTimeout(statement, | |
| 346 | - wte.getConsistencyLevel(), | |
| 347 | - wte.getWriteType(), | |
| 348 | - wte.getRequiredAcknowledgements(), | |
| 349 | - wte.getReceivedAcknowledgements(), | |
| 350 | - retriesByPolicy); | |
| 351 | - | |
| 352 | - if (metricsEnabled()) { | |
| 353 | - if (retry.getType() == Type.RETRY) | |
| 354 | - metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc(); | |
| 355 | - if (retry.getType() == Type.IGNORE) | |
| 356 | - metrics().getErrorMetrics().getIgnoresOnWriteTimeout().inc(); | |
| 357 | - } | |
| 358 | - break; | |
| 359 | - case UNAVAILABLE: | |
| 360 | - assert err.infos instanceof UnavailableException; | |
| 361 | - if (metricsEnabled()) | |
| 362 | - metrics().getErrorMetrics().getUnavailables().inc(); | |
| 363 | - | |
| 364 | - UnavailableException ue = (UnavailableException)err.infos; | |
| 365 | - retry = retryPolicy.onUnavailable(statement, | |
| 366 | - ue.getConsistencyLevel(), | |
| 367 | - ue.getRequiredReplicas(), | |
| 368 | - ue.getAliveReplicas(), | |
| 369 | - retriesByPolicy); | |
| 370 | - | |
| 371 | - if (metricsEnabled()) { | |
| 372 | - if (retry.getType() == Type.RETRY) | |
| 373 | - metrics().getErrorMetrics().getRetriesOnUnavailable().inc(); | |
| 374 | - if (retry.getType() == Type.IGNORE) | |
| 375 | - metrics().getErrorMetrics().getIgnoresOnUnavailable().inc(); | |
| 376 | - } | |
| 377 | - break; | |
| 378 | - case OVERLOADED: | |
| 379 | - // Try another node | |
| 380 | - logger.warn("Host {} is overloaded, trying next host.", connection.address); | |
| 381 | - DriverException overloaded = new DriverException("Host overloaded"); | |
| 382 | - logError(connection.address, overloaded); | |
| 383 | - if (metricsEnabled()) | |
| 384 | - metrics().getErrorMetrics().getOthers().inc(); | |
| 385 | - retry(false, null); | |
| 386 | - return; | |
| 387 | - case SERVER_ERROR: | |
| 388 | - // Defunct connection and try another node | |
| 389 | - logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message); | |
| 390 | - DriverException exception = new DriverException("Host replied with server error: " + err.message); | |
| 391 | - logError(connection.address, exception); | |
| 392 | - connection.defunct(exception); | |
| 393 | - if (metricsEnabled()) | |
| 394 | - metrics().getErrorMetrics().getOthers().inc(); | |
| 395 | - retry(false, null); | |
| 396 | - return; | |
| 397 | - case IS_BOOTSTRAPPING: | |
| 398 | - // Try another node | |
| 399 | - logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address); | |
| 400 | - DriverException bootstrapping = new DriverException("Host is bootstrapping"); | |
| 401 | - logError(connection.address, bootstrapping); | |
| 402 | - if (metricsEnabled()) | |
| 403 | - metrics().getErrorMetrics().getOthers().inc(); | |
| 404 | - retry(false, null); | |
| 405 | - return; | |
| 406 | - case UNPREPARED: | |
| 407 | - assert err.infos instanceof MD5Digest; | |
| 408 | - MD5Digest id = (MD5Digest)err.infos; | |
| 409 | - PreparedStatement toPrepare = manager.cluster.manager.preparedQueries.get(id); | |
| 410 | - if (toPrepare == null) { | |
| 411 | - // This shouldn't happen | |
| 412 | - String msg = String.format("Tried to execute unknown prepared query %s", id); | |
| 413 | - logger.error(msg); | |
| 414 | - setFinalException(connection, new DriverInternalError(msg)); | |
| 415 | - return; | |
| 416 | - } | |
| 224 | + private Metrics metrics() { | |
| 225 | + return manager.cluster.manager.metrics; | |
| 226 | + } | |
| 417 | 227 | |
| 418 | - String currentKeyspace = connection.keyspace(); | |
| 419 | - String prepareKeyspace = toPrepare.getQueryKeyspace(); | |
| 420 | - if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) { | |
| 421 | - // This shouldn't happen in normal use, because a user shouldn't try to execute | |
| 422 | - // a prepared statement with the wrong keyspace set. | |
| 423 | - // Fail fast (we can't change the keyspace to reprepare, because we're using a pooled connection | |
| 424 | - // that's shared with other requests). | |
| 425 | - throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)", | |
| 426 | - toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString())); | |
| 427 | - } | |
| 228 | + interface Callback extends Connection.ResponseCallback { | |
| 229 | + void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency); | |
| 230 | + void register(RequestHandler handler); | |
| 231 | + } | |
| 428 | 232 | |
| 429 | - logger.info("Query {} is not prepared on {}, preparing before retrying executing. " | |
| 430 | - + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems", | |
| 431 | - toPrepare.getQueryString(), connection.address); | |
| 432 | - | |
| 433 | - releaseConnection = false; // we're reusing it for the prepare call | |
| 434 | - write(connection, prepareAndRetry(toPrepare.getQueryString())); | |
| 435 | - // we're done for now, the prepareAndRetry callback will handle the rest | |
| 436 | - return; | |
| 437 | - default: | |
| 438 | - if (metricsEnabled()) | |
| 439 | - metrics().getErrorMetrics().getOthers().inc(); | |
| 440 | - break; | |
| 441 | - } | |
| 233 | + /** | |
| 234 | + * An execution of the query against the cluster. | |
| 235 | + * There is at least one instance per RequestHandler, and possibly more (depending on the SpeculativeExecutionPolicy). | |
| 236 | + * Each instance may retry on the same host, or on other hosts as defined by the RetryPolicy. | |
| 237 | + * All instances run concurrently and share the same query plan. | |
| 238 | + * There are three ways a SpeculativeExecution can stop: | |
| 239 | + * - it completes the query (with either a success or a fatal error), and reports the result to the RequestHandler | |
| 240 | + * - it gets cancelled, either because another execution completed the query, or because the RequestHandler was cancelled | |
| 241 | + * - it reaches the end of the query plan and informs the RequestHandler, which will decide what to do | |
| 242 | + */ | |
| 243 | + class SpeculativeExecution implements Connection.ResponseCallback { | |
| 244 | + final String id; | |
| 245 | + private final Message.Request request; | |
| 246 | + private volatile Host current; | |
| 247 | + private volatile ConsistencyLevel retryConsistencyLevel; | |
| 248 | + private final AtomicReference<QueryState> queryStateRef; | |
| 249 | + private final AtomicBoolean nextExecutionScheduled = new AtomicBoolean(); | |
| 250 | + | |
| 251 | + // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from | |
| 252 | + // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an | |
| 253 | + // OVERLOADED error). | |
| 254 | + // This is incremented by one writer at a time, so volatile is good enough. | |
| 255 | + private volatile int retriesByPolicy; | |
| 256 | + | |
| 257 | + private volatile Connection.ResponseHandler connectionHandler; | |
| 258 | + | |
| 259 | + SpeculativeExecution(Message.Request request, int position) { | |
| 260 | + this.id = RequestHandler.this.id + "-" + position; | |
| 261 | + this.request = request; | |
| 262 | + this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL); | |
| 263 | + if(logger.isTraceEnabled()) | |
| 264 | + logger.trace("[{}] Starting", id); | |
| 265 | + } | |
| 442 | 266 | |
| 443 | - if (retry == null) | |
| 444 | - setFinalResult(connection, response); | |
| 445 | - else { | |
| 446 | - switch (retry.getType()) { | |
| 447 | - case RETRY: | |
| 448 | - ++retriesByPolicy; | |
| 449 | - if (logger.isDebugEnabled()) | |
| 450 | - logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel()); | |
| 451 | - if (metricsEnabled()) | |
| 452 | - metrics().getErrorMetrics().getRetries().inc(); | |
| 453 | - retry(true, retry.getRetryConsistencyLevel()); | |
| 454 | - break; | |
| 455 | - case RETHROW: | |
| 456 | - setFinalResult(connection, response); | |
| 457 | - break; | |
| 458 | - case IGNORE: | |
| 459 | - if (metricsEnabled()) | |
| 460 | - metrics().getErrorMetrics().getIgnores().inc(); | |
| 461 | - setFinalResult(connection, new Responses.Result.Void()); | |
| 462 | - break; | |
| 463 | - } | |
| 464 | - } | |
| 465 | - break; | |
| 466 | - default: | |
| 467 | - setFinalResult(connection, response); | |
| 468 | - break; | |
| 267 | + void sendRequest() { | |
| 268 | + try { | |
| 269 | + Host host; | |
| 270 | + while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) { | |
| 271 | + if(logger.isTraceEnabled()) | |
| 272 | + logger.trace("[{}] Querying node {}", id, host); | |
| 273 | + if (query(host)) | |
| 274 | + return; | |
| 275 | + } | |
| 276 | + reportNoMoreHosts(this); | |
| 277 | + } catch (Exception e) { | |
| 278 | + // Shouldn't happen really, but if ever the loadbalancing policy returned iterator throws, we don't want to block. | |
| 279 | + setFinalException(null, new DriverInternalError("An unexpected error happened while sending requests", e)); | |
| 469 | 280 | } |
| 470 | - } catch (Exception e) { | |
| 471 | - exceptionToReport = e; | |
| 472 | - setFinalException(connection, e); | |
| 473 | - } finally { | |
| 474 | - connection.release(); | |
| 475 | - if (queriedHost != null && statement != Statement.DEFAULT) | |
| 476 | - manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency); | |
| 477 | 281 | } |
| 478 | - } | |
| 479 | 282 | |
| 480 | - private Connection.ResponseCallback prepareAndRetry(final String toPrepare) { | |
| 481 | - return new Connection.ResponseCallback() { | |
| 482 | - | |
| 483 | - @Override | |
| 484 | - public Message.Request request() { | |
| 485 | - return new Requests.Prepare(toPrepare); | |
| 283 | + private boolean query(final Host host) { | |
| 284 | + HostConnectionPool currentPool = manager.pools.get(host); | |
| 285 | + if (currentPool == null || currentPool.isClosed()) | |
| 286 | + return false; | |
| 287 | + | |
| 288 | + if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true)) | |
| 289 | + scheduleExecution(speculativeExecutionPlan.nextExecution(host)); | |
| 290 | + | |
| 291 | + Connection connection = null; | |
| 292 | + try { | |
| 293 | + connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS); | |
| 294 | + if (current != null) { | |
| 295 | + if (triedHosts == null) | |
| 296 | + triedHosts = new CopyOnWriteArrayList<Host>(); | |
| 297 | + triedHosts.add(current); | |
| 298 | + } | |
| 299 | + current = host; | |
| 300 | + write(connection, this); | |
| 301 | + return true; | |
| 302 | + } catch (ConnectionException e) { | |
| 303 | + // If we have any problem with the connection, move to the next node. | |
| 304 | + if (metricsEnabled()) | |
| 305 | + metrics().getErrorMetrics().getConnectionErrors().inc(); | |
| 306 | + if (connection != null) | |
| 307 | + connection.release(); | |
| 308 | + logError(host.getSocketAddress(), e); | |
| 309 | + return false; | |
| 310 | + } catch (BusyConnectionException e) { | |
| 311 | + // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host. | |
| 312 | + connection.release(); | |
| 313 | + logError(host.getSocketAddress(), e); | |
| 314 | + return false; | |
| 315 | + } catch (TimeoutException e) { | |
| 316 | + // We timeout, log it but move to the next node. | |
| 317 | + logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)")); | |
| 318 | + return false; | |
| 319 | + } catch (RuntimeException e) { | |
| 320 | + if (connection != null) | |
| 321 | + connection.release(); | |
| 322 | + logger.error("Unexpected error while querying " + host.getAddress(), e); | |
| 323 | + logError(host.getSocketAddress(), e); | |
| 324 | + return false; | |
| 486 | 325 | } |
| 326 | + } | |
| 487 | 327 | |
| 488 | - @Override | |
| 489 | - public int retryCount() { | |
| 490 | - return RequestHandler.this.retryCount(); | |
| 328 | + private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException { | |
| 329 | + // Make sure cancel() does not see a stale connectionHandler if it sees the new query state | |
| 330 | + // before connection.write has completed | |
| 331 | + connectionHandler = null; | |
| 332 | + | |
| 333 | + // Ensure query state is "in progress" (can be already if connection.write failed on a previous node and we're retrying) | |
| 334 | + while (true) { | |
| 335 | + QueryState previous = queryStateRef.get(); | |
| 336 | + if (previous.isCancelled()) { | |
| 337 | + connection.release(); | |
| 338 | + return; | |
| 339 | + } | |
| 340 | + if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext())) | |
| 341 | + break; | |
| 491 | 342 | } |
| 492 | 343 | |
| 493 | - @Override | |
| 494 | - public void onSet(Connection connection, Message.Response response, long latency, int retryCount) { | |
| 495 | - QueryState queryState = queryStateRef.get(); | |
| 496 | - if (!queryState.isInProgressAt(retryCount) || | |
| 497 | - !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 498 | - logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 499 | - retryCount, queryState, queryStateRef.get()); | |
| 344 | + connectionHandler = connection.write(responseCallback, false); | |
| 345 | + // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered | |
| 346 | + // *before* the call to connection.write had returned. | |
| 347 | + connectionHandler.startTimeout(); | |
| 348 | + | |
| 349 | + // Note that we could have already received the response here (so onSet() / onException() would have been called). This is | |
| 350 | + // why we only test for CANCELLED_WHILE_IN_PROGRESS below. | |
| 351 | + | |
| 352 | + // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have | |
| 353 | + // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice, | |
| 354 | + // but it knows how to deal with it). | |
| 355 | + if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS) | |
| 356 | + connectionHandler.cancelHandler(); | |
| 357 | + } | |
| 358 | + | |
| 359 | + private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { | |
| 360 | + final Host h = current; | |
| 361 | + this.retryConsistencyLevel = newConsistencyLevel; | |
| 362 | + | |
| 363 | + // We should not retry on the current thread as this will be an IO thread. | |
| 364 | + manager.executor().execute(new Runnable() { | |
| 365 | + @Override | |
| 366 | + public void run() { | |
| 367 | + if (queryStateRef.get().isCancelled()) | |
| 368 | + return; | |
| 369 | + try { | |
| 370 | + if (retryCurrent) { | |
| 371 | + if (query(h)) | |
| 372 | + return; | |
| 373 | + } | |
| 374 | + sendRequest(); | |
| 375 | + } catch (Exception e) { | |
| 376 | + setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e)); | |
| 377 | + } | |
| 378 | + } | |
| 379 | + }); | |
| 380 | + } | |
| 381 | + | |
| 382 | + void cancel() { | |
| 383 | + // Atomically set a special QueryState, that will cause any further operation to abort. | |
| 384 | + // We want to remember whether a request was in progress when we did this, so there are two cancel states. | |
| 385 | + while (true) { | |
| 386 | + QueryState previous = queryStateRef.get(); | |
| 387 | + if (previous.isCancelled()) { | |
| 388 | + return; | |
| 389 | + } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) { | |
| 390 | + if(logger.isTraceEnabled()) | |
| 391 | + logger.trace("[{}] Cancelled while in progress", id); | |
| 392 | + // The connectionHandler should be non-null, but we might miss the update if we're racing with write(). | |
| 393 | + // If it's still null, this will be handled by re-checking queryStateRef at the end of write(). | |
| 394 | + if (connectionHandler != null) | |
| 395 | + connectionHandler.cancelHandler(); | |
| 396 | + return; | |
| 397 | + } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) { | |
| 398 | + if(logger.isTraceEnabled()) | |
| 399 | + logger.trace("[{}] Cancelled while complete", id); | |
| 500 | 400 | return; |
| 501 | 401 | } |
| 402 | + } | |
| 403 | + } | |
| 502 | 404 | |
| 503 | - connection.release(); | |
| 405 | + @Override | |
| 406 | + public Message.Request request() { | |
| 407 | + if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency()) | |
| 408 | + return manager.makeRequestMessage(statement, retryConsistencyLevel, request.consistency(), request.pagingState()); | |
| 409 | + else | |
| 410 | + return request; | |
| 411 | + } | |
| 504 | 412 | |
| 505 | - // TODO should we check the response ? | |
| 413 | + @Override | |
| 414 | + public void onSet(Connection connection, Message.Response response, long latency, int retryCount) { | |
| 415 | + QueryState queryState = queryStateRef.get(); | |
| 416 | + if (!queryState.isInProgressAt(retryCount) || | |
| 417 | + !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 418 | + logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 419 | + retryCount, queryState, queryStateRef.get()); | |
| 420 | + return; | |
| 421 | + } | |
| 422 | + | |
| 423 | + Host queriedHost = current; | |
| 424 | + Exception exceptionToReport = null; | |
| 425 | + try { | |
| 506 | 426 | switch (response.type) { |
| 507 | 427 | case RESULT: |
| 508 | - if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) { | |
| 509 | - logger.debug("Scheduling retry now that query is prepared"); | |
| 510 | - retry(true, null); | |
| 511 | - } else { | |
| 512 | - logError(connection.address, new DriverException("Got unexpected response to prepare message: " + response)); | |
| 513 | - retry(false, null); | |
| 514 | - } | |
| 428 | + connection.release(); | |
| 429 | + setFinalResult(connection, response); | |
| 515 | 430 | break; |
| 516 | 431 | case ERROR: |
| 517 | - logError(connection.address, new DriverException("Error preparing query, got " + response)); | |
| 518 | - if (metricsEnabled()) | |
| 519 | - metrics().getErrorMetrics().getOthers().inc(); | |
| 520 | - retry(false, null); | |
| 432 | + Responses.Error err = (Responses.Error)response; | |
| 433 | + exceptionToReport = err.asException(connection.address); | |
| 434 | + RetryPolicy.RetryDecision retry = null; | |
| 435 | + RetryPolicy retryPolicy = statement.getRetryPolicy() == null | |
| 436 | + ? manager.configuration().getPolicies().getRetryPolicy() | |
| 437 | + : statement.getRetryPolicy(); | |
| 438 | + switch (err.code) { | |
| 439 | + case READ_TIMEOUT: | |
| 440 | + connection.release(); | |
| 441 | + assert err.infos instanceof ReadTimeoutException; | |
| 442 | + if (metricsEnabled()) | |
| 443 | + metrics().getErrorMetrics().getReadTimeouts().inc(); | |
| 444 | + | |
| 445 | + ReadTimeoutException rte = (ReadTimeoutException)err.infos; | |
| 446 | + retry = retryPolicy.onReadTimeout(statement, | |
| 447 | + rte.getConsistencyLevel(), | |
| 448 | + rte.getRequiredAcknowledgements(), | |
| 449 | + rte.getReceivedAcknowledgements(), | |
| 450 | + rte.wasDataRetrieved(), | |
| 451 | + retriesByPolicy); | |
| 452 | + | |
| 453 | + if (metricsEnabled()) { | |
| 454 | + if (retry.getType() == Type.RETRY) | |
| 455 | + metrics().getErrorMetrics().getRetriesOnReadTimeout().inc(); | |
| 456 | + if (retry.getType() == Type.IGNORE) | |
| 457 | + metrics().getErrorMetrics().getIgnoresOnReadTimeout().inc(); | |
| 458 | + } | |
| 459 | + break; | |
| 460 | + case WRITE_TIMEOUT: | |
| 461 | + connection.release(); | |
| 462 | + assert err.infos instanceof WriteTimeoutException; | |
| 463 | + if (metricsEnabled()) | |
| 464 | + metrics().getErrorMetrics().getWriteTimeouts().inc(); | |
| 465 | + | |
| 466 | + WriteTimeoutException wte = (WriteTimeoutException)err.infos; | |
| 467 | + retry = retryPolicy.onWriteTimeout(statement, | |
| 468 | + wte.getConsistencyLevel(), | |
| 469 | + wte.getWriteType(), | |
| 470 | + wte.getRequiredAcknowledgements(), | |
| 471 | + wte.getReceivedAcknowledgements(), | |
| 472 | + retriesByPolicy); | |
| 473 | + | |
| 474 | + if (metricsEnabled()) { | |
| 475 | + if (retry.getType() == Type.RETRY) | |
| 476 | + metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc(); | |
| 477 | + if (retry.getType() == Type.IGNORE) | |
| 478 | + metrics().getErrorMetrics().getIgnoresOnWriteTimeout().inc(); | |
| 479 | + } | |
| 480 | + break; | |
| 481 | + case UNAVAILABLE: | |
| 482 | + connection.release(); | |
| 483 | + assert err.infos instanceof UnavailableException; | |
| 484 | + if (metricsEnabled()) | |
| 485 | + metrics().getErrorMetrics().getUnavailables().inc(); | |
| 486 | + | |
| 487 | + UnavailableException ue = (UnavailableException)err.infos; | |
| 488 | + retry = retryPolicy.onUnavailable(statement, | |
| 489 | + ue.getConsistencyLevel(), | |
| 490 | + ue.getRequiredReplicas(), | |
| 491 | + ue.getAliveReplicas(), | |
| 492 | + retriesByPolicy); | |
| 493 | + | |
| 494 | + if (metricsEnabled()) { | |
| 495 | + if (retry.getType() == Type.RETRY) | |
| 496 | + metrics().getErrorMetrics().getRetriesOnUnavailable().inc(); | |
| 497 | + if (retry.getType() == Type.IGNORE) | |
| 498 | + metrics().getErrorMetrics().getIgnoresOnUnavailable().inc(); | |
| 499 | + } | |
| 500 | + break; | |
| 501 | + case OVERLOADED: | |
| 502 | + connection.release(); | |
| 503 | + // Try another node | |
| 504 | + logger.warn("Host {} is overloaded, trying next host.", connection.address); | |
| 505 | + DriverException overloaded = new DriverException("Host overloaded"); | |
| 506 | + logError(connection.address, overloaded); | |
| 507 | + if (metricsEnabled()) | |
| 508 | + metrics().getErrorMetrics().getOthers().inc(); | |
| 509 | + retry(false, null); | |
| 510 | + return; | |
| 511 | + case SERVER_ERROR: | |
| 512 | + connection.release(); | |
| 513 | + // Defunct connection and try another node | |
| 514 | + logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message); | |
| 515 | + DriverException exception = new DriverException("Host replied with server error: " + err.message); | |
| 516 | + logError(connection.address, exception); | |
| 517 | + connection.defunct(exception); | |
| 518 | + if (metricsEnabled()) | |
| 519 | + metrics().getErrorMetrics().getOthers().inc(); | |
| 520 | + retry(false, null); | |
| 521 | + return; | |
| 522 | + case IS_BOOTSTRAPPING: | |
| 523 | + connection.release(); | |
| 524 | + // Try another node | |
| 525 | + logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address); | |
| 526 | + DriverException bootstrapping = new DriverException("Host is bootstrapping"); | |
| 527 | + logError(connection.address, bootstrapping); | |
| 528 | + if (metricsEnabled()) | |
| 529 | + metrics().getErrorMetrics().getOthers().inc(); | |
| 530 | + retry(false, null); | |
| 531 | + return; | |
| 532 | + case UNPREPARED: | |
| 533 | + // Do not release connection yet, because we might reuse it to send the PREPARE message (see write() call below) | |
| 534 | + assert err.infos instanceof MD5Digest; | |
| 535 | + MD5Digest id = (MD5Digest)err.infos; | |
| 536 | + PreparedStatement toPrepare = manager.cluster.manager.preparedQueries.get(id); | |
| 537 | + if (toPrepare == null) { | |
| 538 | + // This shouldn't happen | |
| 539 | + connection.release(); | |
| 540 | + String msg = String.format("Tried to execute unknown prepared query %s", id); | |
| 541 | + logger.error(msg); | |
| 542 | + setFinalException(connection, new DriverInternalError(msg)); | |
| 543 | + return; | |
| 544 | + } | |
| 545 | + | |
| 546 | + String currentKeyspace = connection.keyspace(); | |
| 547 | + String prepareKeyspace = toPrepare.getQueryKeyspace(); | |
| 548 | + if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) { | |
| 549 | + // This shouldn't happen in normal use, because a user shouldn't try to execute | |
| 550 | + // a prepared statement with the wrong keyspace set. | |
| 551 | + // Fail fast (we can't change the keyspace to reprepare, because we're using a pooled connection | |
| 552 | + // that's shared with other requests). | |
| 553 | + connection.release(); | |
| 554 | + throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)", | |
| 555 | + toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString())); | |
| 556 | + } | |
| 557 | + | |
| 558 | + logger.info("Query {} is not prepared on {}, preparing before retrying executing. " | |
| 559 | + + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems", | |
| 560 | + toPrepare.getQueryString(), connection.address); | |
| 561 | + | |
| 562 | + write(connection, prepareAndRetry(toPrepare.getQueryString())); | |
| 563 | + // we're done for now, the prepareAndRetry callback will handle the rest | |
| 564 | + return; | |
| 565 | + default: | |
| 566 | + connection.release(); | |
| 567 | + if (metricsEnabled()) | |
| 568 | + metrics().getErrorMetrics().getOthers().inc(); | |
| 569 | + break; | |
| 570 | + } | |
| 571 | + | |
| 572 | + if (retry == null) | |
| 573 | + setFinalResult(connection, response); | |
| 574 | + else { | |
| 575 | + switch (retry.getType()) { | |
| 576 | + case RETRY: | |
| 577 | + ++retriesByPolicy; | |
| 578 | + if (logger.isDebugEnabled()) | |
| 579 | + logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel()); | |
| 580 | + if (metricsEnabled()) | |
| 581 | + metrics().getErrorMetrics().getRetries().inc(); | |
| 582 | + retry(true, retry.getRetryConsistencyLevel()); | |
| 583 | + break; | |
| 584 | + case RETHROW: | |
| 585 | + setFinalResult(connection, response); | |
| 586 | + break; | |
| 587 | + case IGNORE: | |
| 588 | + if (metricsEnabled()) | |
| 589 | + metrics().getErrorMetrics().getIgnores().inc(); | |
| 590 | + setFinalResult(connection, new Responses.Result.Void()); | |
| 591 | + break; | |
| 592 | + } | |
| 593 | + } | |
| 521 | 594 | break; |
| 522 | 595 | default: |
| 523 | - // Something's wrong, so we return but we let setFinalResult propagate the exception | |
| 524 | - RequestHandler.this.setFinalResult(connection, response); | |
| 596 | + connection.release(); | |
| 597 | + setFinalResult(connection, response); | |
| 525 | 598 | break; |
| 526 | 599 | } |
| 600 | + } catch (Exception e) { | |
| 601 | + exceptionToReport = e; | |
| 602 | + setFinalException(connection, e); | |
| 603 | + } finally { | |
| 604 | + if (queriedHost != null && statement != Statement.DEFAULT) | |
| 605 | + manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency); | |
| 527 | 606 | } |
| 607 | + } | |
| 528 | 608 | |
| 529 | - @Override | |
| 530 | - public void onException(Connection connection, Exception exception, long latency, int retryCount) { | |
| 531 | - RequestHandler.this.onException(connection, exception, latency, retryCount); | |
| 532 | - } | |
| 609 | + private Connection.ResponseCallback prepareAndRetry(final String toPrepare) { | |
| 610 | + return new Connection.ResponseCallback() { | |
| 533 | 611 | |
| 534 | - @Override | |
| 535 | - public boolean onTimeout(Connection connection, long latency, int retryCount) { | |
| 536 | - QueryState queryState = queryStateRef.get(); | |
| 537 | - if (!queryState.isInProgressAt(retryCount) || | |
| 538 | - !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 539 | - logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 540 | - retryCount, queryState, queryStateRef.get()); | |
| 541 | - return false; | |
| 612 | + @Override | |
| 613 | + public Message.Request request() { | |
| 614 | + return new Requests.Prepare(toPrepare); | |
| 542 | 615 | } |
| 543 | - logError(connection.address, new DriverException("Timeout waiting for response to prepare message")); | |
| 544 | - retry(false, null); | |
| 545 | - return true; | |
| 616 | + | |
| 617 | + @Override | |
| 618 | + public int retryCount() { | |
| 619 | + return SpeculativeExecution.this.retryCount(); | |
| 620 | + } | |
| 621 | + | |
| 622 | + @Override | |
| 623 | + public void onSet(Connection connection, Message.Response response, long latency, int retryCount) { | |
| 624 | + QueryState queryState = queryStateRef.get(); | |
| 625 | + if (!queryState.isInProgressAt(retryCount) || | |
| 626 | + !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 627 | + logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 628 | + retryCount, queryState, queryStateRef.get()); | |
| 629 | + return; | |
| 630 | + } | |
| 631 | + | |
| 632 | + connection.release(); | |
| 633 | + | |
| 634 | + // TODO should we check the response ? | |
| 635 | + switch (response.type) { | |
| 636 | + case RESULT: | |
| 637 | + if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) { | |
| 638 | + logger.debug("Scheduling retry now that query is prepared"); | |
| 639 | + retry(true, null); | |
| 640 | + } else { | |
| 641 | + logError(connection.address, new DriverException("Got unexpected response to prepare message: " + response)); | |
| 642 | + retry(false, null); | |
| 643 | + } | |
| 644 | + break; | |
| 645 | + case ERROR: | |
| 646 | + logError(connection.address, new DriverException("Error preparing query, got " + response)); | |
| 647 | + if (metricsEnabled()) | |
| 648 | + metrics().getErrorMetrics().getOthers().inc(); | |
| 649 | + retry(false, null); | |
| 650 | + break; | |
| 651 | + default: | |
| 652 | + // Something's wrong, so we return but we let setFinalResult propagate the exception | |
| 653 | + SpeculativeExecution.this.setFinalResult(connection, response); | |
| 654 | + break; | |
| 655 | + } | |
| 656 | + } | |
| 657 | + | |
| 658 | + @Override | |
| 659 | + public void onException(Connection connection, Exception exception, long latency, int retryCount) { | |
| 660 | + SpeculativeExecution.this.onException(connection, exception, latency, retryCount); | |
| 661 | + } | |
| 662 | + | |
| 663 | + @Override | |
| 664 | + public boolean onTimeout(Connection connection, long latency, int retryCount) { | |
| 665 | + QueryState queryState = queryStateRef.get(); | |
| 666 | + if (!queryState.isInProgressAt(retryCount) || | |
| 667 | + !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 668 | + logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 669 | + retryCount, queryState, queryStateRef.get()); | |
| 670 | + return false; | |
| 671 | + } | |
| 672 | + logError(connection.address, new DriverException("Timeout waiting for response to prepare message")); | |
| 673 | + retry(false, null); | |
| 674 | + return true; | |
| 675 | + } | |
| 676 | + }; | |
| 677 | + } | |
| 678 | + | |
| 679 | + @Override | |
| 680 | + public void onException(Connection connection, Exception exception, long latency, int retryCount) { | |
| 681 | + QueryState queryState = queryStateRef.get(); | |
| 682 | + if (!queryState.isInProgressAt(retryCount) || | |
| 683 | + !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 684 | + logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 685 | + retryCount, queryState, queryStateRef.get()); | |
| 686 | + return; | |
| 546 | 687 | } |
| 547 | - }; | |
| 548 | - } | |
| 549 | 688 | |
| 550 | - @Override | |
| 551 | - public void onException(Connection connection, Exception exception, long latency, int retryCount) { | |
| 552 | - QueryState queryState = queryStateRef.get(); | |
| 553 | - if (!queryState.isInProgressAt(retryCount) || | |
| 554 | - !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 555 | - logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 556 | - retryCount, queryState, queryStateRef.get()); | |
| 557 | - return; | |
| 689 | + Host queriedHost = current; | |
| 690 | + try { | |
| 691 | + connection.release(); | |
| 692 | + | |
| 693 | + if (exception instanceof ConnectionException) { | |
| 694 | + if (metricsEnabled()) | |
| 695 | + metrics().getErrorMetrics().getConnectionErrors().inc(); | |
| 696 | + ConnectionException ce = (ConnectionException)exception; | |
| 697 | + logError(ce.address, ce); | |
| 698 | + retry(false, null); | |
| 699 | + return; | |
| 700 | + } | |
| 701 | + setFinalException(connection, exception); | |
| 702 | + } catch (Exception e) { | |
| 703 | + // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely | |
| 704 | + setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e)); | |
| 705 | + } finally { | |
| 706 | + if (queriedHost != null && statement != Statement.DEFAULT) | |
| 707 | + manager.cluster.manager.reportLatency(queriedHost, statement, exception, latency); | |
| 708 | + } | |
| 558 | 709 | } |
| 559 | 710 | |
| 560 | - Host queriedHost = current; | |
| 561 | - try { | |
| 562 | - connection.release(); | |
| 711 | + @Override | |
| 712 | + public boolean onTimeout(Connection connection, long latency, int retryCount) { | |
| 713 | + QueryState queryState = queryStateRef.get(); | |
| 714 | + if (!queryState.isInProgressAt(retryCount) || | |
| 715 | + !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 716 | + logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 717 | + retryCount, queryState, queryStateRef.get()); | |
| 718 | + return false; | |
| 719 | + } | |
| 563 | 720 | |
| 564 | - if (exception instanceof ConnectionException) { | |
| 565 | - if (metricsEnabled()) | |
| 566 | - metrics().getErrorMetrics().getConnectionErrors().inc(); | |
| 567 | - ConnectionException ce = (ConnectionException)exception; | |
| 568 | - logError(ce.address, ce); | |
| 721 | + Host queriedHost = current; | |
| 722 | + OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address); | |
| 723 | + try { | |
| 724 | + logError(connection.address, timeoutException); | |
| 569 | 725 | retry(false, null); |
| 570 | - return; | |
| 726 | + } catch (Exception e) { | |
| 727 | + // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely | |
| 728 | + setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e)); | |
| 729 | + } finally { | |
| 730 | + if (queriedHost != null && statement != Statement.DEFAULT) | |
| 731 | + manager.cluster.manager.reportLatency(queriedHost, statement, timeoutException, latency); | |
| 571 | 732 | } |
| 572 | - setFinalException(connection, exception); | |
| 573 | - } catch (Exception e) { | |
| 574 | - // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely | |
| 575 | - setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e)); | |
| 576 | - } finally { | |
| 577 | - if (queriedHost != null && statement != Statement.DEFAULT) | |
| 578 | - manager.cluster.manager.reportLatency(queriedHost, statement, exception, latency); | |
| 733 | + return true; | |
| 579 | 734 | } |
| 580 | - } | |
| 581 | 735 | |
| 582 | - @Override | |
| 583 | - public boolean onTimeout(Connection connection, long latency, int retryCount) { | |
| 584 | - QueryState queryState = queryStateRef.get(); | |
| 585 | - if (!queryState.isInProgressAt(retryCount) || | |
| 586 | - !queryStateRef.compareAndSet(queryState, queryState.complete())) { | |
| 587 | - logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})", | |
| 588 | - retryCount, queryState, queryStateRef.get()); | |
| 589 | - return false; | |
| 736 | + @Override | |
| 737 | + public int retryCount() { | |
| 738 | + return queryStateRef.get().retryCount; | |
| 590 | 739 | } |
| 591 | 740 | |
| 592 | - Host queriedHost = current; | |
| 593 | - OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address); | |
| 594 | - try { | |
| 595 | - logError(connection.address, timeoutException); | |
| 596 | - retry(false, null); | |
| 597 | - } catch (Exception e) { | |
| 598 | - // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely | |
| 599 | - setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e)); | |
| 600 | - } finally { | |
| 601 | - if (queriedHost != null && statement != Statement.DEFAULT) | |
| 602 | - manager.cluster.manager.reportLatency(queriedHost, statement, timeoutException, latency); | |
| 741 | + private void setFinalException(Connection connection, Exception exception) { | |
| 742 | + RequestHandler.this.setFinalException(this, connection, exception); | |
| 603 | 743 | } |
| 604 | - return true; | |
| 605 | - } | |
| 606 | - | |
| 607 | - @Override | |
| 608 | - public int retryCount() { | |
| 609 | - return queryStateRef.get().retryCount; | |
| 610 | - } | |
| 611 | 744 | |
| 612 | - interface Callback extends Connection.ResponseCallback { | |
| 613 | - public void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency); | |
| 614 | - public void register(RequestHandler handler); | |
| 745 | + private void setFinalResult(Connection connection, Message.Response response) { | |
| 746 | + RequestHandler.this.setFinalResult(this, connection, response); | |
| 747 | + } | |
| 615 | 748 | } |
| 616 | 749 | |
| 617 | - // This is used to prevent races between request completion (either success or error) and timeout. | |
| 618 | - // A retry is in progress once we have written the request to the connection and until we get back a response (see onSet | |
| 619 | - // or onException) or a timeout (see onTimeout). | |
| 620 | - // The count increments on each retry. | |
| 750 | + /** | |
| 751 | + * The state of a SpeculativeExecution. | |
| 752 | + * | |
| 753 | + * This is used to prevent races between request completion (either success or error) and timeout. | |
| 754 | + * A retry is in progress once we have written the request to the connection and until we get back a response (see onSet | |
| 755 | + * or onException) or a timeout (see onTimeout). | |
| 756 | + * The count increments on each retry. | |
| 757 | + */ | |
| 621 | 758 | static class QueryState { |
| 622 | 759 | static final QueryState INITIAL = new QueryState(-1, false); |
| 623 | 760 | static final QueryState CANCELLED_WHILE_IN_PROGRESS = new QueryState(Integer.MIN_VALUE, false); |
| @@ -654,4 +791,21 @@ | ||
| 654 | 791 | return String.format("QueryState(count=%d, inProgress=%s, cancelled=%s)", retryCount, inProgress, isCancelled()); |
| 655 | 792 | } |
| 656 | 793 | } |
| 794 | + | |
| 795 | + /** | |
| 796 | + * Wraps the iterator return by {@link com.datastax.driver.core.policies.LoadBalancingPolicy} to make it safe for | |
| 797 | + * concurrent access by multiple threads. | |
| 798 | + */ | |
| 799 | + static class QueryPlan { | |
| 800 | + private final Iterator<Host> iterator; | |
| 801 | + | |
| 802 | + QueryPlan(Iterator<Host> iterator) { | |
| 803 | + this.iterator = iterator; | |
| 804 | + } | |
| 805 | + | |
| 806 | + /** @return null if there are no more hosts */ | |
| 807 | + synchronized Host next() { | |
| 808 | + return iterator.hasNext() ? iterator.next() : null; | |
| 809 | + } | |
| 810 | + } | |
| 657 | 811 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +8 −0
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 34 | 34 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| 35 | 35 | import com.datastax.driver.core.policies.ReconnectionPolicy; |
| 36 | +import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; | |
| 36 | 37 | import com.datastax.driver.core.utils.MoreFutures; |
| 37 | 38 | |
| 38 | 39 | /** |
| @@ -179,6 +180,10 @@ | ||
| 179 | 180 | return cluster.manager.loadBalancingPolicy(); |
| 180 | 181 | } |
| 181 | 182 | |
| 183 | + SpeculativeExecutionPolicy speculativeRetryPolicy() { | |
| 184 | + return cluster.manager.speculativeRetryPolicy(); | |
| 185 | + } | |
| 186 | + | |
| 182 | 187 | ReconnectionPolicy reconnectionPolicy() { |
| 183 | 188 | return cluster.manager.reconnectionPolicy(); |
| 184 | 189 | } |
| @@ -477,6 +482,9 @@ | ||
| 477 | 482 | usedPagingState = statement.getPagingState(); |
| 478 | 483 | } |
| 479 | 484 | |
| 485 | + if (statement instanceof StatementWrapper) | |
| 486 | + statement = ((StatementWrapper)statement).getWrappedStatement(); | |
| 487 | + | |
| 480 | 488 | if (statement instanceof RegularStatement) { |
| 481 | 489 | RegularStatement rs = (RegularStatement)statement; |
| 482 | 490 |
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +47 −2
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | |
| 20 | 20 | import com.datastax.driver.core.exceptions.PagingStateException; |
| 21 | 21 | import com.datastax.driver.core.policies.RetryPolicy; |
| 22 | +import com.datastax.driver.core.querybuilder.BuiltStatement; | |
| 22 | 23 | |
| 23 | 24 | /** |
| 24 | 25 | * An executable query. |
| @@ -47,10 +48,9 @@ | ||
| 47 | 48 | private volatile ConsistencyLevel serialConsistency; |
| 48 | 49 | private volatile boolean traceQuery; |
| 49 | 50 | private volatile int fetchSize; |
| 50 | - | |
| 51 | 51 | private volatile RetryPolicy retryPolicy; |
| 52 | - | |
| 53 | 52 | private volatile ByteBuffer pagingState; |
| 53 | + protected volatile Boolean idempotent; | |
| 54 | 54 | |
| 55 | 55 | // We don't want to expose the constructor, because the code relies on this being only sub-classed by RegularStatement, BoundStatement and BatchStatement |
| 56 | 56 | Statement() { |
| @@ -326,4 +326,49 @@ | ||
| 326 | 326 | ByteBuffer getPagingState() { |
| 327 | 327 | return pagingState; |
| 328 | 328 | } |
| 329 | + | |
| 330 | + /** | |
| 331 | + * Sets whether this statement is idempotent. | |
| 332 | + * <p> | |
| 333 | + * See {@link #isIdempotent()} for more explanations about this property. | |
| 334 | + * | |
| 335 | + * @param idempotent the new value. | |
| 336 | + * @return this {@code Statement} object. | |
| 337 | + */ | |
| 338 | + public Statement setIdempotent(boolean idempotent) { | |
| 339 | + this.idempotent = idempotent; | |
| 340 | + return this; | |
| 341 | + } | |
| 342 | + | |
| 343 | + /** | |
| 344 | + * Whether this statement is idempotent, i.e. whether it can be applied multiple times | |
| 345 | + * without changing the result beyond the initial application. | |
| 346 | + * <p> | |
| 347 | + * Idempotence plays a role in {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}. | |
| 348 | + * If a statement is <em>not idempotent</em>, the driver will not schedule speculative | |
| 349 | + * executions for it. | |
| 350 | + * <p> | |
| 351 | + * Note that this method can return {@code null}, in which case the driver will default to | |
| 352 | + * {@link QueryOptions#getDefaultIdempotence()}. | |
| 353 | + * <p> | |
| 354 | + * By default, this method returns {@code null} for all statements, except for | |
| 355 | + * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates | |
| 356 | + * counters or prepends/appends to a list, the result will be {@code false}, otherwise it | |
| 357 | + * will be {@code true}. In all cases, calling {@link #setIdempotent(boolean)} forces a | |
| 358 | + * value that overrides every other mechanism. | |
| 359 | + * | |
| 360 | + * @return whether this statement is idempotent, or {@code null} to use | |
| 361 | + * {@link QueryOptions#getDefaultIdempotence()}. | |
| 362 | + */ | |
| 363 | + public Boolean isIdempotent() { | |
| 364 | + return idempotent; | |
| 365 | + } | |
| 366 | + | |
| 367 | + boolean isIdempotentWithDefault(QueryOptions queryOptions) { | |
| 368 | + Boolean myValue = this.isIdempotent(); | |
| 369 | + if (myValue != null) | |
| 370 | + return myValue; | |
| 371 | + else | |
| 372 | + return queryOptions.getDefaultIdempotence(); | |
| 373 | + } | |
| 329 | 374 | } |
| No newline at the end of the file |
added driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java +152 −0
| @@ -0,0 +1,152 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.nio.ByteBuffer; | |
| 19 | + | |
| 20 | +import com.datastax.driver.core.policies.LoadBalancingPolicy; | |
| 21 | +import com.datastax.driver.core.policies.RetryPolicy; | |
| 22 | +import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; | |
| 23 | + | |
| 24 | +/** | |
| 25 | + * Base class for custom {@link Statement} implementations that wrap another statement. | |
| 26 | + * <p> | |
| 27 | + * This is intended for use with a custom {@link RetryPolicy}, {@link LoadBalancingPolicy} or | |
| 28 | + * {@link SpeculativeExecutionPolicy}. The client code can wrap a statement to "mark" it, or | |
| 29 | + * add information that will lead to special handling in the policy. | |
| 30 | + * <p> | |
| 31 | + * Example: | |
| 32 | + * <pre> | |
| 33 | + * {@code | |
| 34 | + * // Define your own subclass | |
| 35 | + * public class MyCustomStatement extends StatementWrapper { | |
| 36 | + * public MyCustomStatement(Statement wrapped) { | |
| 37 | + * super(wrapped); | |
| 38 | + * } | |
| 39 | + * } | |
| 40 | + * | |
| 41 | + * // In your load balancing policy, add a special case for that new type | |
| 42 | + * public class MyLoadBalancingPolicy implements LoadBalancingPolicy { | |
| 43 | + * public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 44 | + * if (statement instanceof MyCustomStatement) { | |
| 45 | + * // return specially crafted plan | |
| 46 | + * } else { | |
| 47 | + * // return default plan | |
| 48 | + * } | |
| 49 | + * } | |
| 50 | + * } | |
| 51 | + * | |
| 52 | + * // The client wraps whenever it wants to trigger the special plan | |
| 53 | + * Statement s = new SimpleStatement("..."); | |
| 54 | + * session.execute(s); // will use default plan | |
| 55 | + * session.execute(new MyCustomStatement(s)); // will use special plan | |
| 56 | + * } | |
| 57 | + * </pre> | |
| 58 | + */ | |
| 59 | +public abstract class StatementWrapper extends Statement { | |
| 60 | + private final Statement wrapped; | |
| 61 | + | |
| 62 | + /** | |
| 63 | + * Builds a new instance. | |
| 64 | + * | |
| 65 | + * @param wrapped the wrapped statement. | |
| 66 | + */ | |
| 67 | + protected StatementWrapper(Statement wrapped) { | |
| 68 | + this.wrapped = wrapped; | |
| 69 | + } | |
| 70 | + | |
| 71 | + Statement getWrappedStatement() { | |
| 72 | + // Protect against multiple levels of wrapping (even though there is no practical reason for that) | |
| 73 | + return (wrapped instanceof StatementWrapper) | |
| 74 | + ? ((StatementWrapper)wrapped).getWrappedStatement() | |
| 75 | + : wrapped; | |
| 76 | + } | |
| 77 | + | |
| 78 | + @Override | |
| 79 | + public Statement setConsistencyLevel(ConsistencyLevel consistency) { | |
| 80 | + return wrapped.setConsistencyLevel(consistency); | |
| 81 | + } | |
| 82 | + | |
| 83 | + @Override | |
| 84 | + public Statement disableTracing() { | |
| 85 | + return wrapped.disableTracing(); | |
| 86 | + } | |
| 87 | + | |
| 88 | + @Override | |
| 89 | + public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) { | |
| 90 | + return wrapped.setSerialConsistencyLevel(serialConsistency); | |
| 91 | + } | |
| 92 | + | |
| 93 | + @Override | |
| 94 | + public Statement enableTracing() { | |
| 95 | + return wrapped.enableTracing(); | |
| 96 | + } | |
| 97 | + | |
| 98 | + @Override | |
| 99 | + public ByteBuffer getPagingState() { | |
| 100 | + return wrapped.getPagingState(); | |
| 101 | + } | |
| 102 | + | |
| 103 | + @Override | |
| 104 | + public boolean isTracing() { | |
| 105 | + return wrapped.isTracing(); | |
| 106 | + } | |
| 107 | + | |
| 108 | + @Override | |
| 109 | + public RetryPolicy getRetryPolicy() { | |
| 110 | + return wrapped.getRetryPolicy(); | |
| 111 | + } | |
| 112 | + | |
| 113 | + @Override | |
| 114 | + public ByteBuffer getRoutingKey() { | |
| 115 | + return wrapped.getRoutingKey(); | |
| 116 | + } | |
| 117 | + | |
| 118 | + @Override | |
| 119 | + public Statement setRetryPolicy(RetryPolicy policy) { | |
| 120 | + return wrapped.setRetryPolicy(policy); | |
| 121 | + } | |
| 122 | + | |
| 123 | + @Override | |
| 124 | + public ConsistencyLevel getConsistencyLevel() { | |
| 125 | + return wrapped.getConsistencyLevel(); | |
| 126 | + } | |
| 127 | + | |
| 128 | + @Override | |
| 129 | + public Statement setPagingState(PagingState pagingState) { | |
| 130 | + return wrapped.setPagingState(pagingState); | |
| 131 | + } | |
| 132 | + | |
| 133 | + @Override | |
| 134 | + public ConsistencyLevel getSerialConsistencyLevel() { | |
| 135 | + return wrapped.getSerialConsistencyLevel(); | |
| 136 | + } | |
| 137 | + | |
| 138 | + @Override | |
| 139 | + public String getKeyspace() { | |
| 140 | + return wrapped.getKeyspace(); | |
| 141 | + } | |
| 142 | + | |
| 143 | + @Override | |
| 144 | + public int getFetchSize() { | |
| 145 | + return wrapped.getFetchSize(); | |
| 146 | + } | |
| 147 | + | |
| 148 | + @Override | |
| 149 | + public Statement setFetchSize(int fetchSize) { | |
| 150 | + return wrapped.setFetchSize(fetchSize); | |
| 151 | + } | |
| 152 | +} |
added driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java +71 −0
| @@ -0,0 +1,71 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 19 | + | |
| 20 | +import com.google.common.base.Preconditions; | |
| 21 | + | |
| 22 | +import com.datastax.driver.core.Cluster; | |
| 23 | +import com.datastax.driver.core.Host; | |
| 24 | +import com.datastax.driver.core.Statement; | |
| 25 | + | |
| 26 | +/** | |
| 27 | + * A {@link SpeculativeExecutionPolicy} that schedules a given number of speculative executions, separated by a fixed delay. | |
| 28 | + */ | |
| 29 | +public class ConstantSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { | |
| 30 | + private final int maxSpeculativeExecutions; | |
| 31 | + private final long constantDelayMillis; | |
| 32 | + | |
| 33 | + /** | |
| 34 | + * Builds a new instance. | |
| 35 | + * | |
| 36 | + * @param maxSpeculativeExecutions the number of speculative executions. Must be strictly positive. | |
| 37 | + * @param constantDelayMillis the delay between each speculative execution. Must be strictly positive. | |
| 38 | + * | |
| 39 | + * @throws IllegalArgumentException if one of the arguments does not respect the preconditions above. | |
| 40 | + */ | |
| 41 | + public ConstantSpeculativeExecutionPolicy(final int maxSpeculativeExecutions, final long constantDelayMillis) { | |
| 42 | + this.maxSpeculativeExecutions = maxSpeculativeExecutions; | |
| 43 | + this.constantDelayMillis = constantDelayMillis; | |
| 44 | + Preconditions.checkArgument(maxSpeculativeExecutions > 0, | |
| 45 | + "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions); | |
| 46 | + Preconditions.checkArgument(constantDelayMillis > 0, | |
| 47 | + "delay must be strictly positive (was %d)", constantDelayMillis); | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Override | |
| 51 | + public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) { | |
| 52 | + return new SpeculativeExecutionPlan() { | |
| 53 | + private final AtomicInteger remaining = new AtomicInteger(maxSpeculativeExecutions); | |
| 54 | + | |
| 55 | + @Override | |
| 56 | + public long nextExecution(Host lastQueried) { | |
| 57 | + return (remaining.getAndDecrement() > 0) ? constantDelayMillis : -1; | |
| 58 | + } | |
| 59 | + }; | |
| 60 | + } | |
| 61 | + | |
| 62 | + @Override | |
| 63 | + public void init(Cluster cluster) { | |
| 64 | + // do nothing | |
| 65 | + } | |
| 66 | + | |
| 67 | + @Override | |
| 68 | + public void close() { | |
| 69 | + // do nothing | |
| 70 | + } | |
| 71 | +} |
added driver-core/src/main/java/com/datastax/driver/core/policies/NoSpeculativeExecutionPolicy.java +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Cluster; | |
| 19 | +import com.datastax.driver.core.Host; | |
| 20 | +import com.datastax.driver.core.Statement; | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * A {@link SpeculativeExecutionPolicy} that never schedules speculative executions. | |
| 24 | + */ | |
| 25 | +public class NoSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { | |
| 26 | + | |
| 27 | + /** The single instance (this class is stateless). */ | |
| 28 | + public static final NoSpeculativeExecutionPolicy INSTANCE = new NoSpeculativeExecutionPolicy(); | |
| 29 | + | |
| 30 | + private static final SpeculativeExecutionPlan PLAN = new SpeculativeExecutionPlan() { | |
| 31 | + @Override | |
| 32 | + public long nextExecution(Host lastQueried) { | |
| 33 | + return -1; | |
| 34 | + } | |
| 35 | + }; | |
| 36 | + | |
| 37 | + @Override | |
| 38 | + public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) { | |
| 39 | + return PLAN; | |
| 40 | + } | |
| 41 | + | |
| 42 | + private NoSpeculativeExecutionPolicy() { | |
| 43 | + // do nothing | |
| 44 | + } | |
| 45 | + | |
| 46 | + @Override | |
| 47 | + public void init(Cluster cluster) { | |
| 48 | + // do nothing | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Override | |
| 52 | + public void close() { | |
| 53 | + // do nothing | |
| 54 | + } | |
| 55 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +31 −5
| @@ -23,14 +23,17 @@ | ||
| 23 | 23 | private static final ReconnectionPolicy DEFAULT_RECONNECTION_POLICY = new ExponentialReconnectionPolicy(1000, 10 * 60 * 1000); |
| 24 | 24 | private static final RetryPolicy DEFAULT_RETRY_POLICY = DefaultRetryPolicy.INSTANCE; |
| 25 | 25 | private static final AddressTranslater DEFAULT_ADDRESS_TRANSLATER = new IdentityTranslater(); |
| 26 | + private static final SpeculativeExecutionPolicy DEFAULT_SPECULATIVE_EXECUTION_POLICY = NoSpeculativeExecutionPolicy.INSTANCE; | |
| 26 | 27 | |
| 27 | 28 | private final LoadBalancingPolicy loadBalancingPolicy; |
| 28 | 29 | private final ReconnectionPolicy reconnectionPolicy; |
| 29 | 30 | private final RetryPolicy retryPolicy; |
| 30 | 31 | private final AddressTranslater addressTranslater; |
| 32 | + private final SpeculativeExecutionPolicy speculativeExecutionPolicy; | |
| 31 | 33 | |
| 32 | 34 | public Policies() { |
| 33 | - this(defaultLoadBalancingPolicy(), defaultReconnectionPolicy(), defaultRetryPolicy(), defaultAddressTranslater()); | |
| 35 | + this(defaultLoadBalancingPolicy(), defaultReconnectionPolicy(), defaultRetryPolicy(), | |
| 36 | + defaultAddressTranslater(), defaultSpeculativeExecutionPolicy()); | |
| 34 | 37 | } |
| 35 | 38 | |
| 36 | 39 | /** |
| @@ -44,8 +47,9 @@ | ||
| 44 | 47 | */ |
| 45 | 48 | public Policies(LoadBalancingPolicy loadBalancingPolicy, |
| 46 | 49 | ReconnectionPolicy reconnectionPolicy, |
| 47 | - RetryPolicy retryPolicy) { | |
| 48 | - this(loadBalancingPolicy, reconnectionPolicy, retryPolicy, DEFAULT_ADDRESS_TRANSLATER); | |
| 50 | + RetryPolicy retryPolicy, | |
| 51 | + SpeculativeExecutionPolicy speculativeExecutionPolicy) { | |
| 52 | + this(loadBalancingPolicy, reconnectionPolicy, retryPolicy, DEFAULT_ADDRESS_TRANSLATER, speculativeExecutionPolicy); | |
| 49 | 53 | } |
| 50 | 54 | |
| 51 | 55 | /** |
| @@ -59,11 +63,13 @@ | ||
| 59 | 63 | public Policies(LoadBalancingPolicy loadBalancingPolicy, |
| 60 | 64 | ReconnectionPolicy reconnectionPolicy, |
| 61 | 65 | RetryPolicy retryPolicy, |
| 62 | - AddressTranslater addressTranslater) { | |
| 66 | + AddressTranslater addressTranslater, | |
| 67 | + SpeculativeExecutionPolicy speculativeExecutionPolicy) { | |
| 63 | 68 | this.loadBalancingPolicy = loadBalancingPolicy; |
| 64 | 69 | this.reconnectionPolicy = reconnectionPolicy; |
| 65 | 70 | this.retryPolicy = retryPolicy; |
| 66 | 71 | this.addressTranslater = addressTranslater; |
| 72 | + this.speculativeExecutionPolicy = speculativeExecutionPolicy; | |
| 67 | 73 | } |
| 68 | 74 | |
| 69 | 75 | /** |
| @@ -110,7 +116,7 @@ | ||
| 110 | 116 | /** |
| 111 | 117 | * The default address translater. |
| 112 | 118 | * <p> |
| 113 | - * The default address tanslater is {@link IdentityTranslater}. | |
| 119 | + * The default address translater is {@link IdentityTranslater}. | |
| 114 | 120 | * |
| 115 | 121 | * @return the default address translater. |
| 116 | 122 | */ |
| @@ -118,6 +124,17 @@ | ||
| 118 | 124 | return DEFAULT_ADDRESS_TRANSLATER; |
| 119 | 125 | } |
| 120 | 126 | |
| 127 | + /** | |
| 128 | + * The default speculative retry policy. | |
| 129 | + * <p> | |
| 130 | + * The default speculative retry policy is a {@link NoSpeculativeExecutionPolicy}. | |
| 131 | + * | |
| 132 | + * @return the default speculative retry policy. | |
| 133 | + */ | |
| 134 | + public static SpeculativeExecutionPolicy defaultSpeculativeExecutionPolicy() { | |
| 135 | + return DEFAULT_SPECULATIVE_EXECUTION_POLICY; | |
| 136 | + } | |
| 137 | + | |
| 121 | 138 | /** |
| 122 | 139 | * The load balancing policy in use. |
| 123 | 140 | * <p> |
| @@ -160,4 +177,13 @@ | ||
| 160 | 177 | public AddressTranslater getAddressTranslater() { |
| 161 | 178 | return addressTranslater; |
| 162 | 179 | } |
| 180 | + | |
| 181 | + /** | |
| 182 | + * The speculative execution policy in use. | |
| 183 | + * | |
| 184 | + * @return the speculative execution policy in use. | |
| 185 | + */ | |
| 186 | + public SpeculativeExecutionPolicy getSpeculativeExecutionPolicy() { | |
| 187 | + return speculativeExecutionPolicy; | |
| 188 | + } | |
| 163 | 189 | } |
added driver-core/src/main/java/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.java +72 −0
| @@ -0,0 +1,72 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Cluster; | |
| 19 | +import com.datastax.driver.core.Host; | |
| 20 | +import com.datastax.driver.core.Statement; | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * The policy that decides if the driver will send speculative queries to the next hosts when the current host takes too | |
| 24 | + * long to respond. | |
| 25 | + * <p> | |
| 26 | + * Note that only idempotent statements will be speculatively retried, see | |
| 27 | + * {@link com.datastax.driver.core.Statement#isIdempotent()} for more information. | |
| 28 | + */ | |
| 29 | +public interface SpeculativeExecutionPolicy { | |
| 30 | + /** | |
| 31 | + * Gets invoked at cluster startup. | |
| 32 | + * | |
| 33 | + * @param cluster the cluster that this policy is associated with. | |
| 34 | + */ | |
| 35 | + void init(Cluster cluster); | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * Returns the plan to use for a new query. | |
| 39 | + * | |
| 40 | + * @param loggedKeyspace the currently logged keyspace (the one set through either | |
| 41 | + * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for | |
| 42 | + * the session on which this plan need to be built. This can be {@code null} if | |
| 43 | + * the corresponding session has no keyspace logged in. | |
| 44 | + * @param statement the query for which to build a plan. | |
| 45 | + * @return the plan. | |
| 46 | + */ | |
| 47 | + SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement); | |
| 48 | + | |
| 49 | + /** | |
| 50 | + * Gets invoked at cluster shutdown. | |
| 51 | + * | |
| 52 | + * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started. | |
| 53 | + */ | |
| 54 | + void close(); | |
| 55 | + | |
| 56 | + /** | |
| 57 | + * A plan that governs speculative executions for a given query. | |
| 58 | + * <p> | |
| 59 | + * Each time a host is queried, {@link #nextExecution(Host)} is invoked to determine if and when a speculative query to | |
| 60 | + * the next host will be sent. | |
| 61 | + */ | |
| 62 | + interface SpeculativeExecutionPlan { | |
| 63 | + /** | |
| 64 | + * Returns the time before the next speculative query. | |
| 65 | + * | |
| 66 | + * @param lastQueried the host that was just queried. | |
| 67 | + * @return the time (in milliseconds) before a speculative query is sent to the next host. If zero or negative, | |
| 68 | + * no speculative query will be sent. | |
| 69 | + */ | |
| 70 | + long nextExecution(Host lastQueried); | |
| 71 | + } | |
| 72 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +39 −1
| @@ -29,6 +29,8 @@ | ||
| 29 | 29 | this.name = name; |
| 30 | 30 | } |
| 31 | 31 | |
| 32 | + abstract boolean isIdempotent(); | |
| 33 | + | |
| 32 | 34 | static class SetAssignment extends Assignment { |
| 33 | 35 | |
| 34 | 36 | private final Object value; |
| @@ -49,6 +51,11 @@ | ||
| 49 | 51 | boolean containsBindMarker() { |
| 50 | 52 | return Utils.containsBindMarker(value); |
| 51 | 53 | } |
| 54 | + | |
| 55 | + @Override | |
| 56 | + boolean isIdempotent() { | |
| 57 | + return true; | |
| 58 | + } | |
| 52 | 59 | } |
| 53 | 60 | |
| 54 | 61 | static class CounterAssignment extends Assignment { |
| @@ -78,6 +85,11 @@ | ||
| 78 | 85 | boolean containsBindMarker() { |
| 79 | 86 | return Utils.containsBindMarker(value); |
| 80 | 87 | } |
| 88 | + | |
| 89 | + @Override | |
| 90 | + boolean isIdempotent() { | |
| 91 | + return false; | |
| 92 | + } | |
| 81 | 93 | } |
| 82 | 94 | |
| 83 | 95 | static class ListPrependAssignment extends Assignment { |
| @@ -101,6 +113,11 @@ | ||
| 101 | 113 | boolean containsBindMarker() { |
| 102 | 114 | return Utils.containsBindMarker(value); |
| 103 | 115 | } |
| 116 | + | |
| 117 | + @Override | |
| 118 | + boolean isIdempotent() { | |
| 119 | + return false; | |
| 120 | + } | |
| 104 | 121 | } |
| 105 | 122 | |
| 106 | 123 | static class ListSetIdxAssignment extends Assignment { |
| @@ -124,17 +141,28 @@ | ||
| 124 | 141 | boolean containsBindMarker() { |
| 125 | 142 | return Utils.containsBindMarker(value); |
| 126 | 143 | } |
| 144 | + | |
| 145 | + @Override | |
| 146 | + boolean isIdempotent() { | |
| 147 | + return true; | |
| 148 | + } | |
| 127 | 149 | } |
| 128 | 150 | |
| 129 | 151 | static class CollectionAssignment extends Assignment { |
| 130 | 152 | |
| 131 | 153 | private final Object collection; |
| 132 | 154 | private final boolean isAdd; |
| 155 | + private final boolean isIdempotent; | |
| 133 | 156 | |
| 134 | - CollectionAssignment(String name, Object collection, boolean isAdd) { | |
| 157 | + CollectionAssignment(String name, Object collection, boolean isAdd, boolean isIdempotent) { | |
| 135 | 158 | super(name); |
| 136 | 159 | this.collection = collection; |
| 137 | 160 | this.isAdd = isAdd; |
| 161 | + this.isIdempotent = isIdempotent; | |
| 162 | + } | |
| 163 | + | |
| 164 | + CollectionAssignment(String name, Object collection, boolean isAdd) { | |
| 165 | + this(name, collection, isAdd, true); | |
| 138 | 166 | } |
| 139 | 167 | |
| 140 | 168 | @Override |
| @@ -148,6 +176,11 @@ | ||
| 148 | 176 | boolean containsBindMarker() { |
| 149 | 177 | return Utils.containsBindMarker(collection); |
| 150 | 178 | } |
| 179 | + | |
| 180 | + @Override | |
| 181 | + public boolean isIdempotent() { | |
| 182 | + return isIdempotent; | |
| 183 | + } | |
| 151 | 184 | } |
| 152 | 185 | |
| 153 | 186 | static class MapPutAssignment extends Assignment { |
| @@ -173,5 +206,10 @@ | ||
| 173 | 206 | boolean containsBindMarker() { |
| 174 | 207 | return Utils.containsBindMarker(key) || Utils.containsBindMarker(value); |
| 175 | 208 | } |
| 209 | + | |
| 210 | + @Override | |
| 211 | + boolean isIdempotent() { | |
| 212 | + return true; | |
| 213 | + } | |
| 176 | 214 | } |
| 177 | 215 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +24 −0
| @@ -39,6 +39,7 @@ | ||
| 39 | 39 | private ByteBuffer[] values; |
| 40 | 40 | |
| 41 | 41 | Boolean isCounterOp; |
| 42 | + boolean hasNonIdempotentOps; | |
| 42 | 43 | |
| 43 | 44 | // Whether the user has inputted bind markers. If that's the case, we never generate values as |
| 44 | 45 | // it means the user meant for the statement to be prepared and we shouldn't add our own markers. |
| @@ -120,6 +121,14 @@ | ||
| 120 | 121 | this.isCounterOp = isCounterOp; |
| 121 | 122 | } |
| 122 | 123 | |
| 124 | + boolean hasNonIdempotentOps() { | |
| 125 | + return hasNonIdempotentOps; | |
| 126 | + } | |
| 127 | + | |
| 128 | + void setNonIdempotentOps() { | |
| 129 | + hasNonIdempotentOps = true; | |
| 130 | + } | |
| 131 | + | |
| 123 | 132 | void checkForBindMarkers(Object value) { |
| 124 | 133 | dirty = true; |
| 125 | 134 | if (Utils.containsBindMarker(value)) |
| @@ -170,6 +179,16 @@ | ||
| 170 | 179 | return values; |
| 171 | 180 | } |
| 172 | 181 | |
| 182 | + @Override | |
| 183 | + public Boolean isIdempotent() { | |
| 184 | + // If a value was forced with setIdempotent, it takes priority | |
| 185 | + if (idempotent != null) | |
| 186 | + return idempotent; | |
| 187 | + | |
| 188 | + // Otherwise return the computed value | |
| 189 | + return !hasNonIdempotentOps(); | |
| 190 | + } | |
| 191 | + | |
| 173 | 192 | @Override |
| 174 | 193 | public String toString() { |
| 175 | 194 | if (forceNoValues) |
| @@ -272,6 +291,11 @@ | ||
| 272 | 291 | return statement.isCounterOp(); |
| 273 | 292 | } |
| 274 | 293 | |
| 294 | + @Override | |
| 295 | + boolean hasNonIdempotentOps() { | |
| 296 | + return statement.hasNonIdempotentOps(); | |
| 297 | + } | |
| 298 | + | |
| 275 | 299 | @Override |
| 276 | 300 | public RegularStatement setForceNoValues(boolean forceNoValues) { |
| 277 | 301 | statement.setForceNoValues(forceNoValues); |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +3 −3
| @@ -641,7 +641,7 @@ | ||
| 641 | 641 | */ |
| 642 | 642 | public static Assignment append(String name, Object value) { |
| 643 | 643 | Object v = value instanceof BindMarker ? value : Collections.singletonList(value); |
| 644 | - return new Assignment.CollectionAssignment(name, v, true); | |
| 644 | + return new Assignment.CollectionAssignment(name, v, true, false); | |
| 645 | 645 | } |
| 646 | 646 | |
| 647 | 647 | /** |
| @@ -654,7 +654,7 @@ | ||
| 654 | 654 | * @return the correspond assignment (to use in an update query) |
| 655 | 655 | */ |
| 656 | 656 | public static Assignment appendAll(String name, List<?> list) { |
| 657 | - return new Assignment.CollectionAssignment(name, list, true); | |
| 657 | + return new Assignment.CollectionAssignment(name, list, true, false); | |
| 658 | 658 | } |
| 659 | 659 | |
| 660 | 660 | /** |
| @@ -667,7 +667,7 @@ | ||
| 667 | 667 | * @return the correspond assignment (to use in an update query) |
| 668 | 668 | */ |
| 669 | 669 | public static Assignment appendAll(String name, BindMarker list) { |
| 670 | - return new Assignment.CollectionAssignment(name, list, true); | |
| 670 | + return new Assignment.CollectionAssignment(name, list, true, false); | |
| 671 | 671 | } |
| 672 | 672 | |
| 673 | 673 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +2 −0
| @@ -175,6 +175,8 @@ | ||
| 175 | 175 | */ |
| 176 | 176 | public Assignments and(Assignment assignment) { |
| 177 | 177 | statement.setCounterOp(assignment instanceof CounterAssignment); |
| 178 | + if (!assignment.isIdempotent()) | |
| 179 | + statement.setNonIdempotentOps(); | |
| 178 | 180 | assignments.add(assignment); |
| 179 | 181 | checkForBindMarkers(assignment); |
| 180 | 182 | return this; |
added driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +129 −0
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.UnknownHostException; | |
| 20 | +import java.util.List; | |
| 21 | +import java.util.Map; | |
| 22 | + | |
| 23 | +import com.google.common.collect.ImmutableMap; | |
| 24 | +import com.google.common.collect.ImmutableSet; | |
| 25 | +import com.google.common.collect.Lists; | |
| 26 | +import org.scassandra.Scassandra; | |
| 27 | +import org.scassandra.ScassandraFactory; | |
| 28 | +import org.scassandra.http.client.ColumnTypes; | |
| 29 | +import org.scassandra.http.client.PrimingClient; | |
| 30 | +import org.scassandra.http.client.PrimingRequest; | |
| 31 | + | |
| 32 | +/** | |
| 33 | + * Launches multiple SCassandra instances, and mocks the appropriate request to make the driver think | |
| 34 | + * that they belong to the same cluster. | |
| 35 | + * | |
| 36 | + * Note: this uses the same addresses as {@link CCMBridge}, so make sure IP aliases have been set up, | |
| 37 | + * and a CCM cluster is not running at the same time. | |
| 38 | + */ | |
| 39 | +public class SCassandraCluster { | |
| 40 | + private static final int BINARY_PORT = 9042; | |
| 41 | + private static final int ADMIN_PORT = 9052; | |
| 42 | + | |
| 43 | + private final List<Scassandra> scassandras; | |
| 44 | + private final List<InetAddress> addresses; | |
| 45 | + private final List<PrimingClient> primingClients; | |
| 46 | + | |
| 47 | + public SCassandraCluster(String ipPrefix, int nodeCount) { | |
| 48 | + scassandras = Lists.newArrayListWithCapacity(nodeCount); | |
| 49 | + addresses = Lists.newArrayListWithCapacity(nodeCount); | |
| 50 | + primingClients = Lists.newArrayListWithCapacity(nodeCount); | |
| 51 | + | |
| 52 | + for (int i = 1; i <= nodeCount; i++) { | |
| 53 | + String ip = ipPrefix + i; | |
| 54 | + try { | |
| 55 | + addresses.add(InetAddress.getByName(ip)); | |
| 56 | + } catch (UnknownHostException e) { | |
| 57 | + throw new AssertionError(e); | |
| 58 | + } | |
| 59 | + Scassandra scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT); | |
| 60 | + scassandra.start(); | |
| 61 | + scassandras.add(scassandra); | |
| 62 | + | |
| 63 | + // Currently Scassandra#primingClient() uses localhost by default, so build manually: | |
| 64 | + primingClients.add(PrimingClient.builder() | |
| 65 | + .withHost(ip).withPort(scassandra.getAdminPort()) | |
| 66 | + .build()); | |
| 67 | + } | |
| 68 | + primePeers(); | |
| 69 | + } | |
| 70 | + | |
| 71 | + public List<InetAddress> addresses() { | |
| 72 | + return addresses; | |
| 73 | + } | |
| 74 | + | |
| 75 | + public void stop() { | |
| 76 | + for (Scassandra scassandra : scassandras) | |
| 77 | + scassandra.stop(); | |
| 78 | + } | |
| 79 | + | |
| 80 | + public SCassandraCluster prime(int node, PrimingRequest request) { | |
| 81 | + primingClients.get(node - 1).prime(request); | |
| 82 | + return this; | |
| 83 | + } | |
| 84 | + | |
| 85 | + public void clearAllPrimes() { | |
| 86 | + for (PrimingClient primingClient : primingClients) | |
| 87 | + primingClient.clearAllPrimes(); | |
| 88 | + primePeers(); | |
| 89 | + } | |
| 90 | + | |
| 91 | + private void primePeers() { | |
| 92 | + for (int i = 0; i < scassandras.size(); i++) | |
| 93 | + primePeers(primingClients.get(i), scassandras.get(i)); | |
| 94 | + } | |
| 95 | + | |
| 96 | + @SuppressWarnings("unchecked") | |
| 97 | + private void primePeers(PrimingClient primingClient, Scassandra toIgnore) { | |
| 98 | + List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(scassandras.size()); | |
| 99 | + for (int i = 0; i < scassandras.size(); i++) { | |
| 100 | + if (scassandras.get(i).equals(toIgnore)) | |
| 101 | + continue; | |
| 102 | + InetAddress address = addresses.get(i); | |
| 103 | + rows.add(ImmutableMap.<String, Object>builder() | |
| 104 | + .put("peer", address) | |
| 105 | + .put("rpc_address", address) | |
| 106 | + .put("data_center", "datacenter1") | |
| 107 | + .put("rack", "rack1") | |
| 108 | + .put("release_version", "2.0.1") | |
| 109 | + .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i))) | |
| 110 | + .build()); | |
| 111 | + } | |
| 112 | + primingClient.prime( | |
| 113 | + PrimingRequest.queryBuilder() | |
| 114 | + .withQuery("SELECT * FROM system.peers") | |
| 115 | + .withColumnTypes(SELECT_PEERS_COLUMN_TYPES) | |
| 116 | + .withRows(rows) | |
| 117 | + .build()); | |
| 118 | + } | |
| 119 | + | |
| 120 | + private static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES = | |
| 121 | + ImmutableMap.<String, ColumnTypes>builder() | |
| 122 | + .put("peer", ColumnTypes.Inet) | |
| 123 | + .put("rpc_address", ColumnTypes.Inet) | |
| 124 | + .put("data_center", ColumnTypes.Text) | |
| 125 | + .put("rack", ColumnTypes.Text) | |
| 126 | + .put("release_version", ColumnTypes.Text) | |
| 127 | + .put("tokens", ColumnTypes.TextSet) | |
| 128 | + .build(); | |
| 129 | +} |
added driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +270 −0
| @@ -0,0 +1,270 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.*; | |
| 19 | +import java.util.concurrent.ConcurrentSkipListSet; | |
| 20 | + | |
| 21 | +import com.google.common.collect.ImmutableList; | |
| 22 | +import com.google.common.collect.ImmutableMap; | |
| 23 | +import com.google.common.primitives.UnsignedBytes; | |
| 24 | +import org.scassandra.http.client.PrimingRequest; | |
| 25 | +import org.testng.annotations.*; | |
| 26 | + | |
| 27 | +import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy; | |
| 28 | +import com.datastax.driver.core.policies.LoadBalancingPolicy; | |
| 29 | +import com.datastax.driver.core.policies.RetryPolicy; | |
| 30 | + | |
| 31 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 32 | + | |
| 33 | +public class SpeculativeExecutionTest { | |
| 34 | + SCassandraCluster scassandras; | |
| 35 | + | |
| 36 | + Cluster cluster = null; | |
| 37 | + SortingLoadBalancingPolicy loadBalancingPolicy; | |
| 38 | + Metrics.Errors errors; | |
| 39 | + Host host1, host2, host3; | |
| 40 | + Session session; | |
| 41 | + | |
| 42 | + @BeforeClass(groups = "short") | |
| 43 | + public void beforeClass() { | |
| 44 | + scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 3); | |
| 45 | + } | |
| 46 | + | |
| 47 | + @BeforeMethod(groups = "short") | |
| 48 | + public void beforeMethod() { | |
| 49 | + int speculativeExecutionDelay = 200; | |
| 50 | + | |
| 51 | + loadBalancingPolicy = new SortingLoadBalancingPolicy(); | |
| 52 | + cluster = Cluster.builder() | |
| 53 | + .addContactPoint(CCMBridge.ipOfNode(2)) | |
| 54 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 55 | + .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, speculativeExecutionDelay)) | |
| 56 | + .withQueryOptions(new QueryOptions().setDefaultIdempotence(true)) | |
| 57 | + .withRetryPolicy(new CustomRetryPolicy()) | |
| 58 | + .build(); | |
| 59 | + | |
| 60 | + session = cluster.connect(); | |
| 61 | + | |
| 62 | + host1 = TestUtils.findHost(cluster, 1); | |
| 63 | + host2 = TestUtils.findHost(cluster, 2); | |
| 64 | + host3 = TestUtils.findHost(cluster, 3); | |
| 65 | + | |
| 66 | + errors = cluster.getMetrics().getErrorMetrics(); | |
| 67 | + } | |
| 68 | + | |
| 69 | + @Test(groups = "short") | |
| 70 | + public void should_not_start_speculative_execution_if_first_execution_completes_successfully() { | |
| 71 | + scassandras.prime(1, PrimingRequest.queryBuilder() | |
| 72 | + .withQuery("mock query") | |
| 73 | + .withRows(row("result", "result1")) | |
| 74 | + .build() | |
| 75 | + ); | |
| 76 | + | |
| 77 | + long execStartCount = errors.getSpeculativeExecutions().getCount(); | |
| 78 | + | |
| 79 | + ResultSet rs = session.execute("mock query"); | |
| 80 | + Row row = rs.one(); | |
| 81 | + | |
| 82 | + assertThat(row.getString("result")).isEqualTo("result1"); | |
| 83 | + assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount); | |
| 84 | + assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host1); | |
| 85 | + } | |
| 86 | + | |
| 87 | + @Test(groups = "short") | |
| 88 | + public void should_not_start_speculative_execution_if_first_execution_retries_but_is_still_fast_enough() { | |
| 89 | + // will retry once on this node: | |
| 90 | + scassandras.prime(1, PrimingRequest.queryBuilder() | |
| 91 | + .withQuery("mock query") | |
| 92 | + .withConsistency(PrimingRequest.Consistency.TWO) | |
| 93 | + .withResult(PrimingRequest.Result.read_request_timeout) | |
| 94 | + .build() | |
| 95 | + ).prime(1, PrimingRequest.queryBuilder() | |
| 96 | + .withQuery("mock query") | |
| 97 | + .withConsistency(PrimingRequest.Consistency.ONE) | |
| 98 | + .withRows(row("result", "result1")) | |
| 99 | + .build() | |
| 100 | + ); | |
| 101 | + | |
| 102 | + long execStartCount = errors.getSpeculativeExecutions().getCount(); | |
| 103 | + long retriesStartCount = errors.getRetriesOnUnavailable().getCount(); | |
| 104 | + | |
| 105 | + SimpleStatement statement = new SimpleStatement("mock query"); | |
| 106 | + statement.setConsistencyLevel(ConsistencyLevel.TWO); | |
| 107 | + ResultSet rs = session.execute(statement); | |
| 108 | + Row row = rs.one(); | |
| 109 | + | |
| 110 | + assertThat(row.getString("result")).isEqualTo("result1"); | |
| 111 | + assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount); | |
| 112 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(retriesStartCount + 1); | |
| 113 | + assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host1); | |
| 114 | + } | |
| 115 | + | |
| 116 | + @Test(groups = "short") | |
| 117 | + public void should_start_speculative_execution_if_first_execution_takes_too_long() { | |
| 118 | + scassandras.prime(1, PrimingRequest.queryBuilder() | |
| 119 | + .withQuery("mock query") | |
| 120 | + .withFixedDelay(400) | |
| 121 | + .withRows(row("result", "result1")) | |
| 122 | + .build() | |
| 123 | + ).prime(2, PrimingRequest.queryBuilder() | |
| 124 | + .withQuery("mock query") | |
| 125 | + .withRows(row("result", "result2")) | |
| 126 | + .build() | |
| 127 | + ); | |
| 128 | + long execStartCount = errors.getSpeculativeExecutions().getCount(); | |
| 129 | + | |
| 130 | + ResultSet rs = session.execute("mock query"); | |
| 131 | + Row row = rs.one(); | |
| 132 | + | |
| 133 | + assertThat(row.getString("result")).isEqualTo("result2"); | |
| 134 | + assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1); | |
| 135 | + assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host2); | |
| 136 | + } | |
| 137 | + | |
| 138 | + @Test(groups = "short") | |
| 139 | + public void should_wait_until_all_executions_have_finished() { | |
| 140 | + // Rely on read timeouts to trigger errors that cause an execution to move to the next node | |
| 141 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1000); | |
| 142 | + | |
| 143 | + scassandras | |
| 144 | + // execution1 starts with host1, which will time out at t=1000 | |
| 145 | + .prime(1, PrimingRequest.queryBuilder() | |
| 146 | + .withQuery("mock query") | |
| 147 | + .withFixedDelay(2000) | |
| 148 | + .withRows(row("result", "result1")) | |
| 149 | + .build()) | |
| 150 | + // at t=1000, execution1 moves to host3, which eventually succeeds at t=1500 | |
| 151 | + .prime(3, PrimingRequest.queryBuilder() | |
| 152 | + .withQuery("mock query") | |
| 153 | + .withFixedDelay(500) | |
| 154 | + .withRows(row("result", "result3")) | |
| 155 | + .build()) | |
| 156 | + // meanwhile, execution2 starts at t=200, using host2 which times out at t=1200 | |
| 157 | + // at that time, the query plan is empty so execution2 fails | |
| 158 | + // The goal of this test is to check that execution2 does not fail the query, since execution1 is still running | |
| 159 | + .prime(2, PrimingRequest.queryBuilder() | |
| 160 | + .withQuery("mock query") | |
| 161 | + .withFixedDelay(2000) | |
| 162 | + .withRows(row("result", "result2")) | |
| 163 | + .build()); | |
| 164 | + long execStartCount = errors.getSpeculativeExecutions().getCount(); | |
| 165 | + | |
| 166 | + ResultSet rs = session.execute("mock query"); | |
| 167 | + Row row = rs.one(); | |
| 168 | + | |
| 169 | + assertThat(row.getString("result")).isEqualTo("result3"); | |
| 170 | + assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1); | |
| 171 | + assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host3); | |
| 172 | + } | |
| 173 | + | |
| 174 | + @AfterMethod(groups = "short") | |
| 175 | + public void afterMethod() { | |
| 176 | + scassandras.clearAllPrimes(); | |
| 177 | + if (cluster != null) | |
| 178 | + cluster.close(); | |
| 179 | + } | |
| 180 | + | |
| 181 | + @AfterClass(groups = "short") | |
| 182 | + public void afterClass() { | |
| 183 | + if (scassandras != null) | |
| 184 | + scassandras.stop(); | |
| 185 | + } | |
| 186 | + | |
| 187 | + /** | |
| 188 | + * A load balancing policy that sorts hosts on the last byte of the address, | |
| 189 | + * so that the query plan is always [host1, host2, host3]. | |
| 190 | + */ | |
| 191 | + static class SortingLoadBalancingPolicy implements LoadBalancingPolicy { | |
| 192 | + | |
| 193 | + private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 194 | + @Override | |
| 195 | + public int compare(Host host1, Host host2) { | |
| 196 | + byte[] address1 = host1.getAddress().getAddress(); | |
| 197 | + byte[] address2 = host2.getAddress().getAddress(); | |
| 198 | + return UnsignedBytes.compare( | |
| 199 | + address1[address1.length - 1], | |
| 200 | + address2[address2.length - 1]); | |
| 201 | + } | |
| 202 | + }); | |
| 203 | + | |
| 204 | + @Override | |
| 205 | + public void init(Cluster cluster, Collection<Host> hosts) { | |
| 206 | + this.hosts.addAll(hosts); | |
| 207 | + } | |
| 208 | + | |
| 209 | + @Override | |
| 210 | + public HostDistance distance(Host host) { | |
| 211 | + return HostDistance.LOCAL; | |
| 212 | + } | |
| 213 | + | |
| 214 | + @Override | |
| 215 | + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 216 | + return hosts.iterator(); | |
| 217 | + } | |
| 218 | + | |
| 219 | + @Override | |
| 220 | + public void onAdd(Host host) { | |
| 221 | + onUp(host); | |
| 222 | + } | |
| 223 | + | |
| 224 | + @Override | |
| 225 | + public void onUp(Host host) { | |
| 226 | + hosts.add(host); | |
| 227 | + } | |
| 228 | + | |
| 229 | + @Override | |
| 230 | + public void onDown(Host host) { | |
| 231 | + hosts.remove(host); | |
| 232 | + } | |
| 233 | + | |
| 234 | + @Override | |
| 235 | + public void onRemove(Host host) { | |
| 236 | + onDown(host); | |
| 237 | + } | |
| 238 | + | |
| 239 | + @Override | |
| 240 | + public void onSuspected(Host host) { | |
| 241 | + } | |
| 242 | + } | |
| 243 | + | |
| 244 | + /** | |
| 245 | + * Custom retry policy that retries at ONE on read timeout. | |
| 246 | + * This deals with the fact that Scassandra only allows read timeouts with 0 replicas. | |
| 247 | + */ | |
| 248 | + static class CustomRetryPolicy implements RetryPolicy { | |
| 249 | + @Override | |
| 250 | + public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 251 | + if (nbRetry != 0) | |
| 252 | + return RetryDecision.rethrow(); | |
| 253 | + return RetryDecision.retry(ConsistencyLevel.ONE); | |
| 254 | + } | |
| 255 | + | |
| 256 | + @Override | |
| 257 | + public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 258 | + return RetryDecision.rethrow(); | |
| 259 | + } | |
| 260 | + | |
| 261 | + @Override | |
| 262 | + public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 263 | + return RetryDecision.rethrow(); | |
| 264 | + } | |
| 265 | + } | |
| 266 | + | |
| 267 | + private static List<Map<String, ?>> row(String key, String value) { | |
| 268 | + return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value)); | |
| 269 | + } | |
| 270 | +} |
added driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +103 −0
| @@ -0,0 +1,103 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import com.google.common.collect.ImmutableList; | |
| 19 | +import org.testng.annotations.Test; | |
| 20 | + | |
| 21 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 22 | + | |
| 23 | +import com.datastax.driver.core.querybuilder.BuiltStatement; | |
| 24 | + | |
| 25 | +import static com.datastax.driver.core.querybuilder.QueryBuilder.*; | |
| 26 | + | |
| 27 | +public class StatementIdempotenceTest { | |
| 28 | + @Test(groups = "unit") | |
| 29 | + public void should_default_to_false_when_not_set_on_statement_nor_query_options() { | |
| 30 | + QueryOptions queryOptions = new QueryOptions(); | |
| 31 | + SimpleStatement statement = new SimpleStatement(""); | |
| 32 | + | |
| 33 | + assertThat(statement.isIdempotentWithDefault(queryOptions)).isFalse(); | |
| 34 | + } | |
| 35 | + | |
| 36 | + @Test(groups = "unit") | |
| 37 | + public void should_use_query_options_when_not_set_on_statement() { | |
| 38 | + QueryOptions queryOptions = new QueryOptions(); | |
| 39 | + SimpleStatement statement = new SimpleStatement(""); | |
| 40 | + | |
| 41 | + for (boolean valueInOptions : new boolean[]{ true, false }) { | |
| 42 | + queryOptions.setDefaultIdempotence(valueInOptions); | |
| 43 | + assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInOptions); | |
| 44 | + } | |
| 45 | + } | |
| 46 | + | |
| 47 | + @Test(groups = "unit") | |
| 48 | + public void should_use_statement_when_set_on_statement() { | |
| 49 | + QueryOptions queryOptions = new QueryOptions(); | |
| 50 | + SimpleStatement statement = new SimpleStatement(""); | |
| 51 | + | |
| 52 | + for (boolean valueInOptions : new boolean[]{ true, false }) | |
| 53 | + for (boolean valueInStatement : new boolean[]{ true, false }) { | |
| 54 | + queryOptions.setDefaultIdempotence(valueInOptions); | |
| 55 | + statement.setIdempotent(valueInStatement); | |
| 56 | + assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInStatement); | |
| 57 | + } | |
| 58 | + } | |
| 59 | + | |
| 60 | + @Test(groups = "unit") | |
| 61 | + public void should_infer_for_built_statement() { | |
| 62 | + for (BuiltStatement statement : idempotentBuiltStatements()) | |
| 63 | + assertThat(statement.isIdempotent()) | |
| 64 | + .as(statement.getQueryString()) | |
| 65 | + .isTrue(); | |
| 66 | + | |
| 67 | + for (BuiltStatement statement : nonIdempotentBuiltStatements()) | |
| 68 | + assertThat(statement.isIdempotent()) | |
| 69 | + .as(statement.getQueryString()) | |
| 70 | + .isFalse(); | |
| 71 | + } | |
| 72 | + | |
| 73 | + @Test(groups = "unit") | |
| 74 | + public void should_override_inferred_value_when_manually_set_on_built_statement() { | |
| 75 | + for (boolean manualValue : new boolean[]{ true, false }) { | |
| 76 | + for (BuiltStatement statement : idempotentBuiltStatements()) { | |
| 77 | + statement.setIdempotent(manualValue); | |
| 78 | + assertThat(statement.isIdempotent()).isEqualTo(manualValue); | |
| 79 | + } | |
| 80 | + | |
| 81 | + for (BuiltStatement statement : nonIdempotentBuiltStatements()) { | |
| 82 | + statement.setIdempotent(manualValue); | |
| 83 | + assertThat(statement.isIdempotent()).isEqualTo(manualValue); | |
| 84 | + } | |
| 85 | + } | |
| 86 | + } | |
| 87 | + | |
| 88 | + private static ImmutableList<BuiltStatement> idempotentBuiltStatements() { | |
| 89 | + return ImmutableList.<BuiltStatement>of( | |
| 90 | + update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value | |
| 91 | + update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set | |
| 92 | + update("foo").with(put("m", "a", 1)).where(eq("k", 1)) // put in map | |
| 93 | + ); | |
| 94 | + } | |
| 95 | + | |
| 96 | + private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() { | |
| 97 | + return ImmutableList.<BuiltStatement>of( | |
| 98 | + update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list | |
| 99 | + update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list | |
| 100 | + update("foo").with(incr("c")).where(eq("k", 1)) // counter update | |
| 101 | + ); | |
| 102 | + } | |
| 103 | +} |
added driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +147 −0
| @@ -0,0 +1,147 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.Collection; | |
| 19 | +import java.util.Iterator; | |
| 20 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 21 | + | |
| 22 | +import com.google.common.collect.Lists; | |
| 23 | +import org.testng.annotations.Test; | |
| 24 | + | |
| 25 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 26 | + | |
| 27 | +import com.datastax.driver.core.policies.*; | |
| 28 | + | |
| 29 | +public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 30 | + @Override | |
| 31 | + protected Collection<String> getTableDefinitions() { | |
| 32 | + return Lists.newArrayList(); | |
| 33 | + } | |
| 34 | + | |
| 35 | + CustomLoadBalancingPolicy loadBalancingPolicy = new CustomLoadBalancingPolicy(); | |
| 36 | + CustomSpeculativeExecutionPolicy speculativeExecutionPolicy = new CustomSpeculativeExecutionPolicy(); | |
| 37 | + CustomRetryPolicy retryPolicy = new CustomRetryPolicy(); | |
| 38 | + | |
| 39 | + @Override | |
| 40 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 41 | + return builder | |
| 42 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 43 | + .withSpeculativeExecutionPolicy(speculativeExecutionPolicy) | |
| 44 | + .withRetryPolicy(retryPolicy); | |
| 45 | + } | |
| 46 | + | |
| 47 | + @Test(groups = "short") | |
| 48 | + public void should_pass_wrapped_statement_to_load_balancing_policy() { | |
| 49 | + loadBalancingPolicy.customStatementsHandled.set(0); | |
| 50 | + | |
| 51 | + SimpleStatement s = new SimpleStatement("select * from system.local"); | |
| 52 | + session.execute(s); | |
| 53 | + assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0); | |
| 54 | + | |
| 55 | + session.execute(new CustomStatement(s)); | |
| 56 | + assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1); | |
| 57 | + } | |
| 58 | + | |
| 59 | + @Test(groups = "short") | |
| 60 | + public void should_pass_wrapped_statement_to_speculative_execution_policy() { | |
| 61 | + speculativeExecutionPolicy.customStatementsHandled.set(0); | |
| 62 | + | |
| 63 | + SimpleStatement s = new SimpleStatement("select * from system.local"); | |
| 64 | + session.execute(s); | |
| 65 | + assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0); | |
| 66 | + | |
| 67 | + session.execute(new CustomStatement(s)); | |
| 68 | + assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(1); | |
| 69 | + } | |
| 70 | + | |
| 71 | + @Test(groups = "short") | |
| 72 | + public void should_pass_wrapped_statement_to_retry_policy() { | |
| 73 | + retryPolicy.customStatementsHandled.set(0); | |
| 74 | + | |
| 75 | + // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE, | |
| 76 | + // which our custom policy ignores. | |
| 77 | + Statement s = new SimpleStatement("select * from system.local") | |
| 78 | + .setConsistencyLevel(ConsistencyLevel.TWO); | |
| 79 | + | |
| 80 | + session.execute(s); | |
| 81 | + assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0); | |
| 82 | + | |
| 83 | + session.execute(new CustomStatement(s)); | |
| 84 | + assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1); | |
| 85 | + } | |
| 86 | + | |
| 87 | + /** A custom wrapper that's just used to mark statements. */ | |
| 88 | + static class CustomStatement extends StatementWrapper { | |
| 89 | + protected CustomStatement(Statement wrapped) { | |
| 90 | + super(wrapped); | |
| 91 | + } | |
| 92 | + } | |
| 93 | + | |
| 94 | + /** A load balancing policy that counts how many times it has seen the custom wrapper */ | |
| 95 | + static class CustomLoadBalancingPolicy extends DelegatingLoadBalancingPolicy { | |
| 96 | + final AtomicInteger customStatementsHandled = new AtomicInteger(); | |
| 97 | + | |
| 98 | + public CustomLoadBalancingPolicy() { | |
| 99 | + super(new RoundRobinPolicy()); | |
| 100 | + } | |
| 101 | + | |
| 102 | + @Override | |
| 103 | + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 104 | + if (statement instanceof CustomStatement) | |
| 105 | + customStatementsHandled.incrementAndGet(); | |
| 106 | + return super.newQueryPlan(loggedKeyspace, statement); | |
| 107 | + } | |
| 108 | + } | |
| 109 | + | |
| 110 | + /** A speculative execution policy that counts how many times it has seen the custom wrapper */ | |
| 111 | + static class CustomSpeculativeExecutionPolicy extends DelegatingSpeculativeExecutionPolicy { | |
| 112 | + final AtomicInteger customStatementsHandled = new AtomicInteger(); | |
| 113 | + | |
| 114 | + protected CustomSpeculativeExecutionPolicy() { | |
| 115 | + super(NoSpeculativeExecutionPolicy.INSTANCE); | |
| 116 | + } | |
| 117 | + | |
| 118 | + @Override | |
| 119 | + public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) { | |
| 120 | + if (statement instanceof CustomStatement) | |
| 121 | + customStatementsHandled.incrementAndGet(); | |
| 122 | + return super.newPlan(loggedKeyspace, statement); | |
| 123 | + } | |
| 124 | + } | |
| 125 | + | |
| 126 | + /** A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors. */ | |
| 127 | + static class CustomRetryPolicy implements RetryPolicy { | |
| 128 | + final AtomicInteger customStatementsHandled = new AtomicInteger(); | |
| 129 | + | |
| 130 | + @Override | |
| 131 | + public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 132 | + if (statement instanceof CustomStatement) | |
| 133 | + customStatementsHandled.incrementAndGet(); | |
| 134 | + return RetryDecision.ignore(); | |
| 135 | + } | |
| 136 | + | |
| 137 | + @Override | |
| 138 | + public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 139 | + return RetryDecision.rethrow(); | |
| 140 | + } | |
| 141 | + | |
| 142 | + @Override | |
| 143 | + public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 144 | + return RetryDecision.rethrow(); | |
| 145 | + } | |
| 146 | + } | |
| 147 | +} | |
| No newline at the end of the file |
added driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java +47 −0
| @@ -0,0 +1,47 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Cluster; | |
| 19 | +import com.datastax.driver.core.Statement; | |
| 20 | + | |
| 21 | +/** | |
| 22 | + * Base class for tests that want to wrap a policy to add some instrumentation. | |
| 23 | + * | |
| 24 | + * NB: this is currently only used in tests, but could be provided as a convenience in the production code. | |
| 25 | + */ | |
| 26 | +public abstract class DelegatingSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { | |
| 27 | + private final SpeculativeExecutionPolicy delegate; | |
| 28 | + | |
| 29 | + protected DelegatingSpeculativeExecutionPolicy(SpeculativeExecutionPolicy delegate) { | |
| 30 | + this.delegate = delegate; | |
| 31 | + } | |
| 32 | + | |
| 33 | + @Override | |
| 34 | + public void init(Cluster cluster) { | |
| 35 | + delegate.init(cluster); | |
| 36 | + } | |
| 37 | + | |
| 38 | + @Override | |
| 39 | + public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) { | |
| 40 | + return delegate.newPlan(loggedKeyspace, statement); | |
| 41 | + } | |
| 42 | + | |
| 43 | + @Override | |
| 44 | + public void close() { | |
| 45 | + delegate.close(); | |
| 46 | + } | |
| 47 | +} |