Elffuss BraidHub

kikocis/java-driver public

Percentile-based variant of query logger and speculative executions (JAVA-723).

This commit brings percentile-based latency tracking through the
newly-introduced class PerHostPercentileTracker.
This feature benefits to two components:
- the newly-introduced PercentileSpeculativeExecutionPolicy;
- and to the QueryLogger, that now can be configured with either a
  constant or a dynamic threshold for slow queries.
Percentile-based latency tracking is still in beta right now, and is
provided for evaluation purposes only until further notice.
Changeset334084c93e381941029e3457314af6633be1a36f8fdd65bfadc6a884d00af885
Authorolim7t <omichallat+github@gmail.com> · 2015-04-24 17:54 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-28 18:42 +02:00
Parents92389abdcf2b

Browse the files at this changeset

7 files changed

modified driver-core/CHANGELOG.rst +2 −0
@@ -45,6 +45,8 @@
4545 JAVA-425)
4646 - [new feature] Speculative query executions (JAVA-561)
4747 - [bug] Release connection before completing the ResultSetFuture (JAVA-666)
48+- [new feature BETA] Percentile-based variant of query logger and speculative
49+ executions (JAVA-723)
4850
4951 Merged from 2.0.9_fixes branch:
5052
modified driver-core/pom.xml +8 −1
@@ -68,6 +68,8 @@
6868 <optional>true</optional>
6969 </dependency>
7070
71+ <!-- End of compression libraries -->
72+
7173 <dependency>
7274 <groupId>io.netty</groupId>
7375 <artifactId>netty-transport-native-epoll</artifactId>
@@ -75,7 +77,12 @@
7577 <optional>true</optional>
7678 </dependency>
7779
78- <!-- End of compression libraries -->
80+ <dependency>
81+ <groupId>org.hdrhistogram</groupId>
82+ <artifactId>HdrHistogram</artifactId>
83+ <version>2.1.4</version>
84+ <optional>true</optional>
85+ </dependency>
7986
8087 <dependency>
8188 <groupId>org.testng</groupId>
added driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +317 −0
@@ -0,0 +1,317 @@
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.Set;
19+import java.util.concurrent.ConcurrentMap;
20+import java.util.concurrent.ExecutionException;
21+import java.util.concurrent.TimeUnit;
22+import java.util.concurrent.TimeoutException;
23+
24+import static java.util.concurrent.TimeUnit.MILLISECONDS;
25+import static java.util.concurrent.TimeUnit.MINUTES;
26+import static java.util.concurrent.TimeUnit.NANOSECONDS;
27+
28+import com.google.common.annotations.Beta;
29+import com.google.common.collect.ImmutableSet;
30+import com.google.common.collect.MapMaker;
31+import com.google.common.util.concurrent.Futures;
32+import com.google.common.util.concurrent.ListenableFuture;
33+import com.google.common.util.concurrent.SettableFuture;
34+import org.HdrHistogram.Histogram;
35+import org.HdrHistogram.Recorder;
36+import org.slf4j.Logger;
37+import org.slf4j.LoggerFactory;
38+
39+import static com.google.common.base.Preconditions.checkArgument;
40+
41+import com.datastax.driver.core.exceptions.*;
42+
43+/**
44+ * A {@link LatencyTracker} that records latencies for each host over a sliding time interval, and exposes an
45+ * API to retrieve the latency at a given percentile.
46+ * <p>
47+ * To use this class, build an instance with {@link #builderWithHighestTrackableLatencyMillis(long)} and register
48+ * it with your {@link com.datastax.driver.core.Cluster} instance:
49+ * <pre>
50+ * PerHostPercentileTracker tracker = PerHostPercentileTracker
51+ * .builderWithHighestTrackableLatencyMillis(15000)
52+ * .build();
53+ *
54+ * cluster.register(tracker);
55+ * ...
56+ * tracker.getLatencyAtPercentile(host1, 99.0);
57+ * </pre>
58+ * <p>
59+ * This class uses <a href="http://hdrhistogram.github.io/HdrHistogram/">HdrHistogram</a> to record latencies:
60+ * for each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
61+ * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
62+ * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
63+ * interval at cluster startup, since we don't have a cached histogram yet.
64+ * <p>
65+ * Note that this class is currently marked "beta": it hasn't been extensively tested yet, and the API is still subject
66+ * to change.
67+ */
68+@Beta
69+public class PerHostPercentileTracker implements LatencyTracker {
70+ private static final Logger logger = LoggerFactory.getLogger(PerHostPercentileTracker.class);
71+
72+ private final ConcurrentMap<Host, Recorder> recorders;
73+ private final ConcurrentMap<Host, CachedHistogram> cachedHistograms;
74+ private final long highestTrackableLatencyMillis;
75+ private final int numberOfSignificantValueDigits;
76+ private final int minRecordedValues;
77+ private final long intervalMs;
78+
79+ private PerHostPercentileTracker(long highestTrackableLatencyMillis, int numberOfSignificantValueDigits,
80+ int numberOfHosts,
81+ int minRecordedValues,
82+ long intervalMs) {
83+ this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
84+ this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
85+ this.minRecordedValues = minRecordedValues;
86+ this.intervalMs = intervalMs;
87+ this.recorders = new MapMaker().initialCapacity(numberOfHosts).makeMap();
88+ this.cachedHistograms = new MapMaker().initialCapacity(numberOfHosts).makeMap();
89+ }
90+
91+ /**
92+ * Returns a builder to create a new instance.
93+ *
94+ * @param highestTrackableLatencyMillis the highest expected latency. If a higher value is reported, it will be ignored and a
95+ * warning will be logged. A good rule of thumb is to set it slightly higher than
96+ * {@link SocketOptions#getReadTimeoutMillis()}.
97+ * @return the builder.
98+ */
99+ public static Builder builderWithHighestTrackableLatencyMillis(long highestTrackableLatencyMillis) {
100+ return new Builder(highestTrackableLatencyMillis);
101+ }
102+
103+ /**
104+ * Helper class to builder {@code PerHostPercentileTracker} instances with a fluent interface.
105+ */
106+ public static class Builder {
107+ private final long highestTrackableLatencyMillis;
108+ private int numberOfSignificantValueDigits = 3;
109+ private int minRecordedValues = 1000;
110+ private int numberOfHosts = 16;
111+ private long intervalMs = MINUTES.toMillis(5);
112+
113+ Builder(long highestTrackableLatencyMillis) {
114+ this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
115+ }
116+
117+ /**
118+ * Sets the number of significant decimal digits to which histograms will maintain value
119+ * resolution and separation. This must be an integer between 0 and 5.
120+ * <p>
121+ * If not set explicitly, this value defaults to 3.
122+ *
123+ * @param numberOfSignificantValueDigits the new value.
124+ * @return this builder.
125+ *
126+ * @see <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a>
127+ * for a more detailed explanation on how this parameter affects the resolution of recorded samples.
128+ */
129+ public Builder withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) {
130+ this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
131+ return this;
132+ }
133+
134+ /**
135+ * Sets the minimum number of values that must be recorded for a host before we consider
136+ * the sample size significant.
137+ * <p>
138+ * If this count is not reached during a given interval, {@link #getLatencyAtPercentile(Host, double)}
139+ * will return a negative value, indicating that statistics are not available. In particular, this is true
140+ * during the first interval.
141+ * <p>
142+ * If not set explicitly, this value default to 1000.
143+ *
144+ * @param minRecordedValues the new value.
145+ * @return this builder.
146+ */
147+ public Builder withMinRecordedValues(int minRecordedValues) {
148+ this.minRecordedValues = minRecordedValues;
149+ return this;
150+ }
151+
152+ /**
153+ * Sets the number of distinct hosts that the driver will ever connect to.
154+ * <p>
155+ * This parameter is only used to pre-size internal maps in order to avoid unnecessary rehashing.
156+ * <p>
157+ * If not set explicitly, this value defaults to 16.
158+ *
159+ * @param numberOfHosts the new value.
160+ * @return this builder.
161+ */
162+ public Builder withNumberOfHosts(int numberOfHosts) {
163+ this.numberOfHosts = numberOfHosts;
164+ return this;
165+ }
166+
167+ /**
168+ * Sets the time interval over which samples are recorded.
169+ * <p>
170+ * For each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
171+ * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
172+ * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
173+ * interval at cluster startup, since we don't have a cached histogram yet.
174+ * <p>
175+ * If not set explicitly, this value defaults to 5 minutes.
176+ *
177+ * @param interval the new interval.
178+ * @param unit the unit that the interval is expressed in.
179+ * @return this builder.
180+ */
181+ public Builder withInterval(long interval, TimeUnit unit) {
182+ this.intervalMs = MILLISECONDS.convert(interval, unit);
183+ return this;
184+ }
185+
186+ /**
187+ * Builds the {@code PerHostPercentileTracker} instance configured with this builder.
188+ *
189+ * @return the instance.
190+ */
191+ public PerHostPercentileTracker build() {
192+ return new PerHostPercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits, numberOfHosts, minRecordedValues, intervalMs);
193+ }
194+ }
195+
196+ @Override
197+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
198+ if (!shouldConsiderNewLatency(statement, exception))
199+ return;
200+
201+ long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
202+ try {
203+ getRecorder(host).recordValue(latencyMs);
204+ } catch (ArrayIndexOutOfBoundsException e) {
205+ logger.warn("Got request with latency of {} ms, which exceeds the configured maximum trackable value {}",
206+ latencyMs, highestTrackableLatencyMillis);
207+ }
208+ }
209+
210+ /**
211+ * Returns the request latency for a host at a given percentile.
212+ *
213+ * @param host the host.
214+ * @param percentile the percentile (for example, {@code 99.0} for the 99th percentile).
215+ * @return the latency (in milliseconds) at the given percentile, or a negative value if it's not available yet.
216+ */
217+ public long getLatencyAtPercentile(Host host, double percentile) {
218+ checkArgument(percentile >= 0.0 && percentile < 100,
219+ "percentile must be between 0.0 and 100 (was %f)");
220+ Histogram histogram = getLastIntervalHistogram(host);
221+ if (histogram == null || histogram.getTotalCount() < minRecordedValues)
222+ return -1;
223+
224+ return histogram.getValueAtPercentile(percentile);
225+ }
226+
227+ private Recorder getRecorder(Host host) {
228+ Recorder recorder = recorders.get(host);
229+ if (recorder == null) {
230+ recorder = new Recorder(highestTrackableLatencyMillis, numberOfSignificantValueDigits);
231+ Recorder old = recorders.putIfAbsent(host, recorder);
232+ if (old != null) {
233+ // We got beaten at creating the recorder, use the actual instance and discard ours
234+ recorder = old;
235+ } else {
236+ // Also set an empty cache entry to remember the time we started recording:
237+ cachedHistograms.putIfAbsent(host, CachedHistogram.empty());
238+ }
239+ }
240+ return recorder;
241+ }
242+
243+ /** @return null if no histogram is available yet (no entries recorded, or not for long enough) */
244+ private Histogram getLastIntervalHistogram(Host host) {
245+ try {
246+ while (true) {
247+ CachedHistogram entry = cachedHistograms.get(host);
248+ if (entry == null)
249+ return null;
250+
251+ long age = System.currentTimeMillis() - entry.timestamp;
252+ if (age < intervalMs) { // current histogram is recent enough
253+ return entry.histogram.get();
254+ } else { // need to refresh
255+ Recorder recorder = recorders.get(host);
256+ // intervalMs should be much larger than the time it takes to replace a histogram, so this future should never block
257+ Histogram staleHistogram = entry.histogram.get(0, MILLISECONDS);
258+ SettableFuture<Histogram> future = SettableFuture.create();
259+ CachedHistogram newEntry = new CachedHistogram(future);
260+ if (cachedHistograms.replace(host, entry, newEntry)) {
261+ // Only get the new histogram if we successfully replaced the cache entry.
262+ // This ensures that only one thread will do it.
263+ Histogram newHistogram = recorder.getIntervalHistogram(staleHistogram);
264+ future.set(newHistogram);
265+ return newHistogram;
266+ }
267+ // If we couldn't replace the entry it means we raced, so loop to try again
268+ }
269+ }
270+ } catch (InterruptedException e) {
271+ Thread.currentThread().interrupt();
272+ return null;
273+ } catch (ExecutionException e) {
274+ throw new DriverInternalError("Unexpected error", e.getCause());
275+ } catch (TimeoutException e) {
276+ throw new DriverInternalError("Unexpected timeout while getting histogram", e);
277+ }
278+ }
279+
280+ static class CachedHistogram {
281+ final ListenableFuture<Histogram> histogram;
282+ final long timestamp;
283+
284+ CachedHistogram(ListenableFuture<Histogram> histogram) {
285+ this.histogram = histogram;
286+ this.timestamp = System.currentTimeMillis();
287+ }
288+
289+ static CachedHistogram empty() {
290+ return new CachedHistogram(Futures.<Histogram>immediateFuture(null));
291+ }
292+ }
293+
294+ // TODO this was copy/pasted from LatencyAwarePolicy, maybe it could be refactored as a shared method
295+ private boolean shouldConsiderNewLatency(Statement statement, Exception exception) {
296+ // query was successful: always consider
297+ if (exception == null)
298+ return true;
299+ // filter out "fast" errors
300+ return !EXCLUDED_EXCEPTIONS.contains(exception.getClass());
301+ }
302+
303+ /**
304+ * A set of DriverException subclasses that we should prevent from updating the host's score.
305+ * The intent behind it is to filter out "fast" errors: when a host replies with such errors,
306+ * it usually does so very quickly, because it did not involve any actual
307+ * coordination work. Such errors are not good indicators of the host's responsiveness,
308+ * and tend to make the host's score look better than it actually is.
309+ */
310+ private static final Set<Class<? extends Exception>> EXCLUDED_EXCEPTIONS = ImmutableSet.<Class<? extends Exception>>of(
311+ UnavailableException.class, // this is done via the snitch and is usually very fast
312+ OverloadedException.class,
313+ BootstrappingException.class,
314+ UnpreparedException.class,
315+ QueryValidationException.class // query validation also happens at early stages in the coordinator
316+ );
317+}
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +314 −105
@@ -20,6 +20,7 @@
2020
2121 import static java.util.concurrent.TimeUnit.NANOSECONDS;
2222
23+import com.google.common.annotations.Beta;
2324 import com.google.common.annotations.VisibleForTesting;
2425 import org.slf4j.Logger;
2526 import org.slf4j.LoggerFactory;
@@ -33,7 +34,7 @@
3334 * <pre>
3435 * Cluster cluster = ...
3536 * QueryLogger queryLogger = QueryLogger.builder(cluster)
36- * .withSlowQueryLatencyThresholdMillis(...)
37+ * .withConstantThreshold(...)
3738 * .withMaxQueryStringLength(...)
3839 * .build();
3940 * cluster.register(queryLogger);
@@ -54,9 +55,9 @@
5455 *
5556 * <ol>
5657 * <li>{@link #NORMAL_LOGGER}: used to log normal queries, i.e., queries that completed successfully
57- * within a {@link #getSlowQueryLatencyThresholdMillis() configurable threshold in milliseconds}.</li>
58+ * within a configurable threshold in milliseconds.</li>
5859 * <li>{@link #SLOW_LOGGER}: used to log slow queries, i.e., queries that completed successfully
59- * but that took longer than a {@link #getSlowQueryLatencyThresholdMillis() configurable threshold in milliseconds} to complete.</li>
60+ * but that took longer than a configurable threshold in milliseconds to complete.</li>
6061 * <li>{@link #ERROR_LOGGER}: used to log unsuccessful queries, i.e.,
6162 * queries that did not completed normally and threw an exception.
6263 * Note this this logger will also print the full stack trace of the reported exception.</li>
@@ -66,7 +67,7 @@
6667 * The appropriate logger is chosen according to the following algorithm:
6768 * <ol>
6869 * <li>if an exception has been thrown: use {@link #ERROR_LOGGER};</li>
69- * <li>otherwise, if the reported latency is greater than {@link #getSlowQueryLatencyThresholdMillis()} the configured threshold in milliseconds}: use {@link #SLOW_LOGGER};</li>
70+ * <li>otherwise, if the reported latency is greater than the configured threshold in milliseconds: use {@link #SLOW_LOGGER};</li>
7071 * <li>otherwise, use {@link #NORMAL_LOGGER}.</li>
7172 * </ol>
7273 *
@@ -75,19 +76,50 @@
7576 * If the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
7677 * then the query parameters (if any) will be logged as well (names and actual values).
7778 *
79+ * <p>
80+ * <strong>Constant thresholds vs. Dynamic thresholds</strong>
81+ * <p>
82+ * Currently the QueryLogger can track slow queries in two different ways:
83+ * using a constant threshold in milliseconds (which is the default behavior),
84+ * or using a dynamic threshold based on per-host percentiles computed by
85+ * {@link PerHostPercentileTracker}.
86+ * <p>
87+ * <b>Note that the dynamic threshold version is currently provided as a beta preview: it hasn't been extensively
88+ * tested yet, and the API is still subject to change.</b> To use it, you must first obtain and register
89+ * an instance of {@link PerHostPercentileTracker}, then create your QueryLogger as follows:
90+ *
91+ * <pre>
92+ * Cluster cluster = ...
93+ * // create an instance of PerHostPercentileTracker and register it
94+ * PerHostPercentileTracker tracker = ...;
95+ * cluster.register(tracker);
96+ * // create an instance of QueryLogger and register it
97+ * QueryLogger queryLogger = QueryLogger.builder(cluster)
98+ * .withDynamicThreshold(tracker, ...)
99+ * .withMaxQueryStringLength(...)
100+ * .build();
101+ * cluster.register(queryLogger);
102+ * </pre>
103+
78104 * <p>
79105 * This class is thread-safe.
80106 *
81107 * @since 2.0.10
82108 */
83-public class QueryLogger implements LatencyTracker {
109+public abstract class QueryLogger implements LatencyTracker {
84110
85111 /**
86- * The default threshold in milliseconds beyond which queries are considered 'slow'
112+ * The default latency threshold in milliseconds beyond which queries are considered 'slow'
87113 * and logged as such by the driver.
88114 */
89115 public static final long DEFAULT_SLOW_QUERY_THRESHOLD_MS = 5000;
90116
117+ /**
118+ * The default latency percentile beyond which queries are considered 'slow'
119+ * and logged as such by the driver.
120+ */
121+ public static final double DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE = 99.0;
122+
91123 /**
92124 * The default maximum length of a CQL query string that can be logged verbatim
93125 * by the driver. Query strings longer than this value will be truncated
@@ -113,7 +145,7 @@
113145
114146 /**
115147 * The logger used to log normal queries, i.e., queries that completed successfully
116- * within a configurable threshold in milliseconds (see {@link #getSlowQueryLatencyThresholdMillis()}).
148+ * within a configurable threshold in milliseconds.
117149 * <p>
118150 * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
119151 * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
@@ -125,8 +157,7 @@
125157
126158 /**
127159 * The logger used to log slow queries, i.e., queries that completed successfully
128- * but whose execution time exceeded a configurable threshold in milliseconds
129- * (see {@link #getSlowQueryLatencyThresholdMillis()}).
160+ * but whose execution time exceeded a configurable threshold in milliseconds.
130161 * <p>
131162 * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
132163 * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
@@ -152,7 +183,9 @@
152183
153184 private static final String NORMAL_TEMPLATE = "[%s] [%s] Query completed normally, took %s ms: %s";
154185
155- private static final String SLOW_TEMPLATE = "[%s] [%s] Query too slow, took %s ms: %s";
186+ private static final String SLOW_TEMPLATE_MILLIS = "[%s] [%s] Query too slow, took %s ms: %s";
187+
188+ private static final String SLOW_TEMPLATE_PERCENTILE = "[%s] [%s] Query too slow, took %s ms (%s percentile = %s ms): %s";
156189
157190 private static final String ERROR_TEMPLATE = "[%s] [%s] Query error after %s ms: %s";
158191
@@ -162,22 +195,22 @@
162195 @VisibleForTesting
163196 static final String FURTHER_PARAMS_OMITTED = " [further parameters omitted]";
164197
165- private final Cluster cluster;
198+ protected final Cluster cluster;
166199
167- private volatile long slowQueryLatencyThresholdMillis = DEFAULT_SLOW_QUERY_THRESHOLD_MS;
200+ protected volatile int maxQueryStringLength;
168201
169- private volatile int maxQueryStringLength = DEFAULT_MAX_QUERY_STRING_LENGTH;
202+ protected volatile int maxParameterValueLength;
170203
171- private volatile int maxParameterValueLength = DEFAULT_MAX_PARAMETER_VALUE_LENGTH;
172-
173- private volatile int maxLoggedParameters = DEFAULT_MAX_LOGGED_PARAMETERS;
204+ protected volatile int maxLoggedParameters;
174205
175206 /**
176207 * Private constructor. Instances of QueryLogger should be obtained via the {@link #builder(Cluster)} method.
177- * @param cluster The cluster this logger is attached to
178208 */
179- private QueryLogger(Cluster cluster) {
209+ private QueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters) {
180210 this.cluster = cluster;
211+ this.maxQueryStringLength = maxQueryStringLength;
212+ this.maxParameterValueLength = maxParameterValueLength;
213+ this.maxLoggedParameters = maxLoggedParameters;
181214 }
182215
183216 /**
@@ -186,7 +219,6 @@
186219 * This is a convenience method for {@code new QueryLogger.Builder()}.
187220 *
188221 * @param cluster the {@link Cluster} this QueryLogger will be attached to.
189- * Note: this parameter is currently not used, but it is included in the public API in anticipation of future use.
190222 * @return the new QueryLogger builder.
191223 * @throws NullPointerException if {@code cluster} is {@code null}.
192224 */
@@ -196,28 +228,221 @@
196228 }
197229
198230 /**
199- * Helper class to build {@link QueryLogger} instances with a fluent API.
231+ * A QueryLogger that uses a constant threshold in milliseconds
232+ * to track slow queries.
233+ * This implementation is the default and should be preferred to {@link DynamicThresholdQueryLogger}
234+ * which is still in beta state.
200235 */
201- public static class Builder {
236+ public static class ConstantThresholdQueryLogger extends QueryLogger {
202237
203- private final QueryLogger instance;
238+ private volatile long slowQueryLatencyThresholdMillis;
204239
205- public Builder(Cluster cluster) {
206- instance = new QueryLogger(cluster);
240+ private ConstantThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, long slowQueryLatencyThresholdMillis) {
241+ super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters);
242+ this.setSlowQueryLatencyThresholdMillis(slowQueryLatencyThresholdMillis);
243+ }
244+
245+ /**
246+ * Return the threshold in milliseconds beyond which queries are considered 'slow'
247+ * and logged as such by the driver.
248+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}.
249+ *
250+ * @return The threshold in milliseconds beyond which queries are considered 'slow'
251+ * and logged as such by the driver.
252+ */
253+ public long getSlowQueryLatencyThresholdMillis() {
254+ return slowQueryLatencyThresholdMillis;
207255 }
208256
209257 /**
210258 * Set the threshold in milliseconds beyond which queries are considered 'slow'
211259 * and logged as such by the driver.
212- * The default for this setting is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}.
213260 *
214261 * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds.
215262 * It must be strictly positive.
216- * @return this {@link Builder} instance (for method chaining).
217263 * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}.
218264 */
219- public Builder withSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) {
220- instance.setSlowQueryLatencyThresholdMillis(slowQueryLatencyThresholdMillis);
265+ public void setSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) {
266+ if (slowQueryLatencyThresholdMillis <= 0)
267+ throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdMillis, should be > 0, got " + slowQueryLatencyThresholdMillis);
268+ this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis;
269+ }
270+
271+ @Override
272+ protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) {
273+ if (latencyMs > slowQueryLatencyThresholdMillis) {
274+ maybeLogSlowQuery(host, statement, latencyMs);
275+ } else {
276+ maybeLogNormalQuery(host, statement, latencyMs);
277+ }
278+ }
279+
280+ protected void maybeLogSlowQuery(Host host, Statement statement, long latencyMs) {
281+ if (SLOW_LOGGER.isDebugEnabled()) {
282+ String message = String.format(SLOW_TEMPLATE_MILLIS, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
283+ logQuery(statement, null, SLOW_LOGGER, message);
284+ }
285+ }
286+ }
287+
288+ /**
289+ * A QueryLogger that uses a dynamic threshold in milliseconds
290+ * to track slow queries.
291+ * <p>
292+ * Dynamic thresholds are based on per-host latency percentiles, as computed
293+ * by {@link PerHostPercentileTracker}.
294+ * <p>
295+ * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
296+ * to change.</b>
297+ */
298+ @Beta
299+ public static class DynamicThresholdQueryLogger extends QueryLogger {
300+
301+ private volatile double slowQueryLatencyThresholdPercentile;
302+
303+ private volatile PerHostPercentileTracker perHostPercentileLatencyTracker;
304+
305+ private DynamicThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, double slowQueryLatencyThresholdPercentile, PerHostPercentileTracker perHostPercentileLatencyTracker) {
306+ super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters);
307+ this.setSlowQueryLatencyThresholdPercentile(slowQueryLatencyThresholdPercentile);
308+ this.setPerHostPercentileLatencyTracker(perHostPercentileLatencyTracker);
309+ }
310+
311+ /**
312+ * Return the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
313+ * Cannot be {@code null}.
314+ *
315+ * @return the {@link PerHostPercentileTracker} instance to use.
316+ */
317+ public PerHostPercentileTracker getPerHostPercentileLatencyTracker() {
318+ return perHostPercentileLatencyTracker;
319+ }
320+
321+ /**
322+ * Set the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
323+ * Cannot be {@code null}.
324+ *
325+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use.
326+ * @throws IllegalArgumentException if {@code perHostPercentileLatencyTracker == null}.
327+ */
328+ public void setPerHostPercentileLatencyTracker(PerHostPercentileTracker perHostPercentileLatencyTracker) {
329+ if (perHostPercentileLatencyTracker == null)
330+ throw new IllegalArgumentException("perHostPercentileLatencyTracker cannot be null");
331+ this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
332+ }
333+
334+ /**
335+ * Return the threshold percentile beyond which queries are considered 'slow'
336+ * and logged as such by the driver.
337+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}.
338+ *
339+ * @return threshold percentile beyond which queries are considered 'slow'
340+ * and logged as such by the driver.
341+ */
342+ public double getSlowQueryLatencyThresholdPercentile() {
343+ return slowQueryLatencyThresholdPercentile;
344+ }
345+
346+ /**
347+ * Set the threshold percentile beyond which queries are considered 'slow'
348+ * and logged as such by the driver.
349+ *
350+ * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
351+ * It must be comprised between 0 inclusive and 100 exclusive.
352+ * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdPercentile < 0 || slowQueryLatencyThresholdPercentile >= 100}.
353+ */
354+ public void setSlowQueryLatencyThresholdPercentile(double slowQueryLatencyThresholdPercentile) {
355+ if (slowQueryLatencyThresholdPercentile < 0.0 || slowQueryLatencyThresholdPercentile >= 100.0)
356+ throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdPercentile, should be >= 0 and < 100, got " + slowQueryLatencyThresholdPercentile);
357+ this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile;
358+ }
359+
360+ @Override
361+ protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) {
362+ long threshold = perHostPercentileLatencyTracker.getLatencyAtPercentile(host, slowQueryLatencyThresholdPercentile);
363+ if (threshold >= 0 && latencyMs > threshold) {
364+ maybeLogSlowQuery(host, statement, latencyMs, threshold);
365+ } else {
366+ maybeLogNormalQuery(host, statement, latencyMs);
367+ }
368+ }
369+
370+ protected void maybeLogSlowQuery(Host host, Statement statement, long latencyMs, long threshold) {
371+ if (SLOW_LOGGER.isDebugEnabled()) {
372+ String message = String.format(SLOW_TEMPLATE_PERCENTILE, cluster.getClusterName(), host, latencyMs, slowQueryLatencyThresholdPercentile, threshold, statementAsString(statement));
373+ logQuery(statement, null, SLOW_LOGGER, message);
374+ }
375+ }
376+ }
377+
378+ /**
379+ * Helper class to build {@link QueryLogger} instances with a fluent API.
380+ */
381+ public static class Builder {
382+
383+ private final Cluster cluster;
384+
385+ private int maxQueryStringLength = DEFAULT_MAX_QUERY_STRING_LENGTH;
386+
387+ private int maxParameterValueLength = DEFAULT_MAX_PARAMETER_VALUE_LENGTH;
388+
389+ private int maxLoggedParameters = DEFAULT_MAX_LOGGED_PARAMETERS;
390+
391+ private long slowQueryLatencyThresholdMillis = DEFAULT_SLOW_QUERY_THRESHOLD_MS;
392+
393+ private double slowQueryLatencyThresholdPercentile = DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE;
394+
395+ private PerHostPercentileTracker perHostPercentileLatencyTracker;
396+
397+ private boolean constantThreshold = true;
398+
399+ public Builder(Cluster cluster) {
400+ this.cluster = cluster;
401+ }
402+
403+ /**
404+ * Enables slow query latency tracking based on constant thresholds.
405+ * <p>
406+ * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
407+ * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
408+ * not both.
409+ *
410+ * @param slowQueryLatencyThresholdMillis The threshold in milliseconds beyond which queries are considered 'slow'
411+ * and logged as such by the driver.
412+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}
413+ * @return this {@link Builder} instance (for method chaining).
414+ */
415+ public Builder withConstantThreshold(long slowQueryLatencyThresholdMillis) {
416+ this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis;
417+ constantThreshold = true;
418+ return this;
419+ }
420+
421+ /**
422+ * Enables slow query latency tracking based on dynamic thresholds.
423+ * <p>
424+ * Dynamic thresholds are based on per-host latency percentiles, as computed
425+ * by {@link PerHostPercentileTracker}.
426+ * <p>
427+ * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
428+ * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
429+ * not both.
430+ * <p>
431+ * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
432+ * to change.</b>
433+ *
434+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
435+ * Cannot be {@code null}.
436+ * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
437+ * It must be comprised between 0 inclusive and 100 exclusive.
438+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
439+ * @return this {@link Builder} instance (for method chaining).
440+ */
441+ @Beta
442+ public Builder withDynamicThreshold(PerHostPercentileTracker perHostPercentileLatencyTracker, double slowQueryLatencyThresholdPercentile) {
443+ this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
444+ this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile;
445+ constantThreshold = false;
221446 return this;
222447 }
223448
@@ -225,18 +450,17 @@
225450 * Set the maximum length of a CQL query string that can be logged verbatim
226451 * by the driver. Query strings longer than this value will be truncated
227452 * when logged.
228- * The default for this setting is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
229453 *
230454 * @param maxQueryStringLength The maximum length of a CQL query string
231455 * that can be logged verbatim by the driver.
232456 * It must be strictly positive or {@code -1},
233457 * in which case the query is never truncated
234458 * (use with care).
459+ * The default value is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
235460 * @return this {@link Builder} instance (for method chaining).
236- * @throws IllegalArgumentException if {@code maxQueryStringLength <= 0 && maxQueryStringLength != -1}.
237461 */
238462 public Builder withMaxQueryStringLength(int maxQueryStringLength) {
239- instance.setMaxQueryStringLength(maxQueryStringLength);
463+ this.maxQueryStringLength = maxQueryStringLength;
240464 return this;
241465 }
242466
@@ -244,18 +468,17 @@
244468 * Set the maximum length of a query parameter value that can be logged verbatim
245469 * by the driver. Parameter values longer than this value will be truncated
246470 * when logged.
247- * The default for this setting is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
248471 *
249472 * @param maxParameterValueLength The maximum length of a query parameter value
250473 * that can be logged verbatim by the driver.
251474 * It must be strictly positive or {@code -1},
252475 * in which case the parameter value is never truncated
253476 * (use with care).
477+ * The default value is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
254478 * @return this {@link Builder} instance (for method chaining).
255- * @throws IllegalArgumentException if {@code maxParameterValueLength <= 0 && maxParameterValueLength != -1}.
256479 */
257480 public Builder withMaxParameterValueLength(int maxParameterValueLength) {
258- instance.setMaxParameterValueLength(maxParameterValueLength);
481+ this.maxParameterValueLength = maxParameterValueLength;
259482 return this;
260483 }
261484
@@ -263,58 +486,41 @@
263486 * Set the maximum number of query parameters that can be logged
264487 * by the driver. Queries with a number of parameters higher than this value
265488 * will not have all their parameters logged.
266- * The default for this setting is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
267489 *
268490 * @param maxLoggedParameters The maximum number of query parameters that can be logged
269491 * by the driver. It must be strictly positive or {@code -1},
270492 * in which case all parameters will be logged, regardless of their number
271493 * (use with care).
494+ * The default value is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
272495 * @return this {@link Builder} instance (for method chaining).
273- * @throws IllegalArgumentException if {@code maxLoggedParameters <= 0 && maxLoggedParameters != -1}.
274496 */
275497 public Builder withMaxLoggedParameters(int maxLoggedParameters) {
276- instance.setMaxLoggedParameters(maxLoggedParameters);
498+ this.maxLoggedParameters = maxLoggedParameters;
277499 return this;
278500 }
279501
502+ /**
503+ * Build the {@link QueryLogger} instance.
504+ * @return the {@link QueryLogger} instance.
505+ * @throws IllegalArgumentException if the builder is unable to build a valid instance due to incorrect settings.
506+ */
280507 public QueryLogger build() {
281- return instance;
508+ if(constantThreshold) {
509+ return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
510+ } else {
511+ return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
512+ }
282513 }
283- }
284-
285- // Getters and Setters
286514
287- /**
288- * Return the threshold in milliseconds beyond which queries are considered 'slow'
289- * and logged as such by the driver.
290- * The default for this setting is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}.
291- *
292- * @return The threshold in milliseconds beyond which queries are considered 'slow'
293- * and logged as such by the driver.
294- */
295- public long getSlowQueryLatencyThresholdMillis() {
296- return slowQueryLatencyThresholdMillis;
297515 }
298516
299- /**
300- * Set the threshold in milliseconds beyond which queries are considered 'slow'
301- * and logged as such by the driver.
302- *
303- * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds.
304- * It must be strictly positive.
305- * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}.
306- */
307- public void setSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) {
308- if (slowQueryLatencyThresholdMillis <= 0)
309- throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdMillis, should be > 0, got " + slowQueryLatencyThresholdMillis);
310- this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis;
311- }
517+ // Getters and Setters
312518
313519 /**
314520 * Return the maximum length of a CQL query string that can be logged verbatim
315521 * by the driver. Query strings longer than this value will be truncated
316522 * when logged.
317- * The default for this setting is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
523+ * The default value is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
318524 *
319525 * @return The maximum length of a CQL query string that can be logged verbatim
320526 * by the driver.
@@ -345,7 +551,7 @@
345551 * Return the maximum length of a query parameter value that can be logged verbatim
346552 * by the driver. Parameter values longer than this value will be truncated
347553 * when logged.
348- * The default for this setting is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
554+ * The default value is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
349555 *
350556 * @return The maximum length of a query parameter value that can be logged verbatim
351557 * by the driver.
@@ -376,7 +582,7 @@
376582 * Return the maximum number of query parameters that can be logged
377583 * by the driver. Queries with a number of parameters higher than this value
378584 * will not have all their parameters logged.
379- * The default for this setting is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
585+ * The default value is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
380586 *
381587 * @return The maximum number of query parameters that can be logged
382588 * by the driver.
@@ -407,51 +613,54 @@
407613 */
408614 @Override
409615 public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
410- Logger logger;
411- String template;
412616 long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
413617 if (exception == null) {
414- if (latencyMs > slowQueryLatencyThresholdMillis) {
415- logger = SLOW_LOGGER;
416- template = SLOW_TEMPLATE;
417- } else {
418- logger = NORMAL_LOGGER;
419- template = NORMAL_TEMPLATE;
420- }
618+ maybeLogNormalOrSlowQuery(host, statement, latencyMs);
421619 } else {
422- logger = ERROR_LOGGER;
423- template = ERROR_TEMPLATE;
620+ maybeLogErrorQuery(host, statement, exception, latencyMs);
424621 }
425- logQuery(host, statement, exception, latencyMs, logger, template);
426622 }
427623
428- private void logQuery(Host host, Statement statement, Exception exception, long latencyMs, Logger logger, String template) {
429- if (logger.isDebugEnabled()) {
430- String message = String.format(template, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
431- boolean showParameterValues = logger.isTraceEnabled();
432- if (showParameterValues) {
433- StringBuilder params = new StringBuilder();
434- if (statement instanceof BoundStatement) {
435- appendParameters((BoundStatement)statement, params, maxLoggedParameters);
436- } else if (statement instanceof BatchStatement) {
437- BatchStatement batchStatement = (BatchStatement)statement;
438- int remaining = maxLoggedParameters;
439- for (Statement inner : batchStatement.getStatements()) {
440- if (inner instanceof BoundStatement) {
441- remaining = appendParameters((BoundStatement)inner, params, remaining);
442- }
624+ protected abstract void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs);
625+
626+ protected void maybeLogNormalQuery(Host host, Statement statement, long latencyMs) {
627+ if (NORMAL_LOGGER.isDebugEnabled()) {
628+ String message = String.format(NORMAL_TEMPLATE, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
629+ logQuery(statement, null, NORMAL_LOGGER, message);
630+ }
631+ }
632+
633+ protected void maybeLogErrorQuery(Host host, Statement statement, Exception exception, long latencyMs) {
634+ if (ERROR_LOGGER.isDebugEnabled()) {
635+ String message = String.format(ERROR_TEMPLATE, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
636+ logQuery(statement, exception, ERROR_LOGGER, message);
637+ }
638+ }
639+
640+ protected void logQuery(Statement statement, Exception exception, Logger logger, String message) {
641+ boolean showParameterValues = logger.isTraceEnabled();
642+ if (showParameterValues) {
643+ StringBuilder params = new StringBuilder();
644+ if (statement instanceof BoundStatement) {
645+ appendParameters((BoundStatement)statement, params, maxLoggedParameters);
646+ } else if (statement instanceof BatchStatement) {
647+ BatchStatement batchStatement = (BatchStatement)statement;
648+ int remaining = maxLoggedParameters;
649+ for (Statement inner : batchStatement.getStatements()) {
650+ if (inner instanceof BoundStatement) {
651+ remaining = appendParameters((BoundStatement)inner, params, remaining);
443652 }
444653 }
445- if (params.length() > 0)
446- params.append("]");
447- logger.trace(message + params, exception);
448- } else {
449- logger.debug(message, exception);
450654 }
655+ if (params.length() > 0)
656+ params.append("]");
657+ logger.trace(message + params, exception);
658+ } else {
659+ logger.debug(message, exception);
451660 }
452661 }
453662
454- private String statementAsString(Statement statement) {
663+ protected String statementAsString(Statement statement) {
455664 StringBuilder sb = new StringBuilder();
456665 if (statement instanceof BatchStatement) {
457666 BatchStatement bs = (BatchStatement)statement;
@@ -467,7 +676,7 @@
467676 return sb.toString();
468677 }
469678
470- private int countBoundValues(BatchStatement bs) {
679+ protected int countBoundValues(BatchStatement bs) {
471680 int count = 0;
472681 for (Statement s : bs.getStatements()) {
473682 if (s instanceof BoundStatement)
@@ -476,7 +685,7 @@
476685 return count;
477686 }
478687
479- private int appendParameters(BoundStatement statement, StringBuilder buffer, int remaining) {
688+ protected int appendParameters(BoundStatement statement, StringBuilder buffer, int remaining) {
480689 if (remaining == 0)
481690 return 0;
482691 ColumnDefinitions metadata = statement.preparedStatement().getVariables();
@@ -504,7 +713,7 @@
504713 return remaining;
505714 }
506715
507- private String parameterValueAsString(ColumnDefinitions.Definition definition, ByteBuffer raw) {
716+ protected String parameterValueAsString(ColumnDefinitions.Definition definition, ByteBuffer raw) {
508717 String valueStr;
509718 if (raw == null || raw.remaining() == 0) {
510719 valueStr = "NULL";
@@ -534,7 +743,7 @@
534743 return valueStr;
535744 }
536745
537- private int append(Statement statement, StringBuilder buffer, int remaining) {
746+ protected int append(Statement statement, StringBuilder buffer, int remaining) {
538747 if (statement instanceof StatementWrapper)
539748 statement = ((StatementWrapper)statement).getWrappedStatement();
540749
@@ -570,7 +779,7 @@
570779 return remaining;
571780 }
572781
573- private int append(CharSequence str, StringBuilder buffer, int remaining) {
782+ protected int append(CharSequence str, StringBuilder buffer, int remaining) {
574783 if (remaining == -2) {
575784 // capacity exceeded
576785 } else if (remaining == -1) {
added driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java +100 −0
@@ -0,0 +1,100 @@
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.annotations.Beta;
21+
22+import static com.google.common.base.Preconditions.checkArgument;
23+
24+import com.datastax.driver.core.Cluster;
25+import com.datastax.driver.core.Host;
26+import com.datastax.driver.core.Statement;
27+import com.datastax.driver.core.PerHostPercentileTracker;
28+
29+/**
30+ * A policy that triggers speculative executions when the request to the current host is above a given percentile.
31+ *
32+ * This class uses a {@link PerHostPercentileTracker} that must be registered with the cluster instance:
33+ * <pre>
34+ * PerHostPercentileTracker tracker = PerHostPercentileTracker
35+ * .builderWithHighestTrackableLatencyMillis(15000)
36+ * .build();
37+ * PercentileSpeculativeExecutionPolicy policy = new PercentileSpeculativeExecutionPolicy(tracker, 99.0, 2);
38+ * cluster = Cluster.builder()
39+ * .addContactPoint("127.0.0.1")
40+ * .withSpeculativeExecutionPolicy(policy)
41+ * .build();
42+ * cluster.register(tracker);
43+ * </pre>
44+ * You <b>must</b> register the tracker with the cluster yourself (as shown on the last line above), this class will not
45+ * do it itself.
46+ * <p>
47+ * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
48+ * to change.</b>
49+ */
50+@Beta
51+public class PercentileSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
52+ private final PerHostPercentileTracker percentileTracker;
53+ private final double percentile;
54+ private final int maxSpeculativeExecutions;
55+
56+ /**
57+ * Builds a new instance.
58+ *
59+ * @param percentileTracker the component that will record latencies. Note that this policy doesn't register it with the {@code Cluster},
60+ * you <b>must</b> do it yourself (see the code example in this class's Javadoc).
61+ * @param percentile the percentile that a request's latency must fall into to be considered slow (ex: {@code 99.0}).
62+ * @param maxSpeculativeExecutions the maximum number of speculative executions that will be triggered for a given request (this does not
63+ * include the initial, normal request). Must be strictly positive.
64+ */
65+ public PercentileSpeculativeExecutionPolicy(PerHostPercentileTracker percentileTracker, double percentile, int maxSpeculativeExecutions) {
66+ checkArgument(maxSpeculativeExecutions > 0,
67+ "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
68+ checkArgument(percentile >= 0.0 && percentile < 100,
69+ "percentile must be between 0.0 and 100 (was %f)");
70+
71+ this.percentileTracker = percentileTracker;
72+ this.percentile = percentile;
73+ this.maxSpeculativeExecutions = maxSpeculativeExecutions;
74+ }
75+
76+ @Override
77+ public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) {
78+ return new SpeculativeExecutionPlan() {
79+ private final AtomicInteger remaining = new AtomicInteger(maxSpeculativeExecutions);
80+
81+ @Override
82+ public long nextExecution(Host lastQueried) {
83+ if (remaining.getAndDecrement() > 0)
84+ return percentileTracker.getLatencyAtPercentile(lastQueried, percentile);
85+ else
86+ return -1;
87+ }
88+ };
89+ }
90+
91+ @Override
92+ public void init(Cluster cluster) {
93+ // nothing
94+ }
95+
96+ @Override
97+ public void close() {
98+ // nothing
99+ }
100+}
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +1 −1
@@ -89,7 +89,7 @@
8989 // given
9090 slow.setLevel(DEBUG);
9191 queryLogger = builder(cluster)
92- .withSlowQueryLatencyThresholdMillis(10)
92+ .withConstantThreshold(10)
9393 .build();
9494 cluster.register(queryLogger);
9595 String query = "SELECT foo FROM bar";
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +7 −7
@@ -135,7 +135,7 @@
135135 // given
136136 normal.setLevel(DEBUG);
137137 queryLogger = QueryLogger.builder(cluster)
138- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
138+ .withConstantThreshold(Long.MAX_VALUE)
139139 .build();
140140 cluster.register(queryLogger);
141141 String query = "SELECT c_text FROM test WHERE pk = 42";
@@ -154,7 +154,7 @@
154154 // given
155155 normal.setLevel(DEBUG);
156156 queryLogger = QueryLogger.builder(cluster)
157- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
157+ .withConstantThreshold(Long.MAX_VALUE)
158158 .build();
159159 cluster.register(queryLogger);
160160 String query = "SELECT * FROM test where pk = ?";
@@ -176,7 +176,7 @@
176176 // given
177177 normal.setLevel(DEBUG);
178178 queryLogger = QueryLogger.builder(cluster)
179- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
179+ .withConstantThreshold(Long.MAX_VALUE)
180180 .withMaxQueryStringLength(Integer.MAX_VALUE)
181181 .build();
182182 cluster.register(queryLogger);
@@ -207,7 +207,7 @@
207207 // given
208208 normal.setLevel(DEBUG);
209209 queryLogger = QueryLogger.builder(cluster)
210- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
210+ .withConstantThreshold(Long.MAX_VALUE)
211211 .withMaxQueryStringLength(Integer.MAX_VALUE)
212212 .build();
213213 cluster.register(queryLogger);
@@ -242,7 +242,7 @@
242242 // given
243243 normal.setLevel(DEBUG);
244244 queryLogger = QueryLogger.builder(cluster)
245- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
245+ .withConstantThreshold(Long.MAX_VALUE)
246246 .withMaxQueryStringLength(Integer.MAX_VALUE)
247247 .build();
248248 cluster.register(queryLogger);
@@ -348,7 +348,7 @@
348348 // given
349349 normal.setLevel(DEBUG);
350350 queryLogger = QueryLogger.builder(cluster)
351- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
351+ .withConstantThreshold(Long.MAX_VALUE)
352352 .withMaxQueryStringLength(Integer.MAX_VALUE)
353353 .build();
354354 cluster.register(queryLogger);
@@ -376,7 +376,7 @@
376376 // given
377377 normal.setLevel(TRACE);
378378 queryLogger = QueryLogger.builder(cluster)
379- .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
379+ .withConstantThreshold(Long.MAX_VALUE)
380380 .withMaxQueryStringLength(Integer.MAX_VALUE)
381381 .build();
382382 cluster.register(queryLogger);