Elffuss BraidHub

kikocis/java-driver public

JAVA-1051: Percentile tracker improvements.

(cherry-picked from 2.1).
Fixes JAVA-888, JAVA-963.
Changeset92b3da74a84960015d90fbe31c31f899ca0fb1cb7642b93750e38f628b7e4bef
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-03 16:54 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-06-16 20:05 -07:00
Parentsafbf07e123a0

Browse the files at this changeset

15 files changed

modified changelog/README.md +2 −0
@@ -50,6 +50,8 @@
5050 Merged from 2.1 branch:
5151
5252 - [improvement] JAVA-1038: Fetch node info by rpc_address if its broadcast_address is not in system.peers.
53+- [improvement] JAVA-888: Add cluster-wide percentile tracker.
54+- [improvement] JAVA-963: Automatically register PercentileTracker from components that use it.
5355
5456
5557 ### 3.0.2
modified clirr-ignores.xml +73 −0
@@ -56,4 +56,77 @@
5656 <justification>This class is only present if the project was compiled with JDK 8+</justification>
5757 </difference>
5858
59+ <difference>
60+ <differenceType>7002</differenceType> <!-- method removed -->
61+ <className>com/datastax/driver/core/PerHostPercentileTracker</className>
62+ <method>com.datastax.driver.core.PerHostPercentileTracker$Builder builderWithHighestTrackableLatencyMillis(long)
63+ </method>
64+ <justification>Renamed (API was marked as beta and still subject to change)</justification>
65+ </difference>
66+
67+ <difference>
68+ <differenceType>7002</differenceType> <!-- method removed -->
69+ <className>com/datastax/driver/core/PerHostPercentileTracker</className>
70+ <method>long getLatencyAtPercentile(com.datastax.driver.core.Host, double)</method>
71+ <justification>Moved to new parent class with more parameters (API was marked as beta and still subject to change)</justification>
72+ </difference>
73+
74+ <difference>
75+ <differenceType>7002</differenceType> <!-- method removed -->
76+ <className>com/datastax/driver/core/PerHostPercentileTracker$Builder</className>
77+ <method>com.datastax.driver.core.PerHostPercentileTracker$Builder withInterval(long, java.util.concurrent.TimeUnit)</method>
78+ <justification>False positive, method now inherited from generic parent class</justification>
79+ </difference>
80+
81+ <difference>
82+ <differenceType>7002</differenceType> <!-- method removed -->
83+ <className>com/datastax/driver/core/PerHostPercentileTracker$Builder</className>
84+ <method>com.datastax.driver.core.PerHostPercentileTracker$Builder withMinRecordedValues(int)</method>
85+ <justification>False positive, method now inherited from generic parent class</justification>
86+ </difference>
87+
88+ <difference>
89+ <differenceType>7002</differenceType> <!-- method removed -->
90+ <className>com/datastax/driver/core/PerHostPercentileTracker$Builder</className>
91+ <method>com.datastax.driver.core.PerHostPercentileTracker$Builder withNumberOfSignificantValueDigits(int)</method>
92+ <justification>False positive, method now inherited from generic parent class</justification>
93+ </difference>
94+
95+ <difference>
96+ <differenceType>7002</differenceType> <!-- method removed -->
97+ <className>com/datastax/driver/core/PerHostPercentileTracker$Builder</className>
98+ <method>com.datastax.driver.core.PerHostPercentileTracker$Builder withNumberOfHosts(int)</method>
99+ <justification>Removed (API was marked as beta and still subject to change)</justification>
100+ </difference>
101+
102+ <difference>
103+ <differenceType>7005</differenceType> <!-- method argument type changed -->
104+ <className>com/datastax/driver/core/QueryLogger$Builder</className>
105+ <method>com.datastax.driver.core.QueryLogger$Builder withDynamicThreshold(com.datastax.driver.core.PerHostPercentileTracker, double)</method>
106+ <to>com.datastax.driver.core.QueryLogger$Builder withDynamicThreshold(com.datastax.driver.core.PercentileTracker, double)</to>
107+ <justification>Introduced more generic parent type PercentileTracker (API was marked as beta and still subject to change)</justification>
108+ </difference>
109+
110+ <difference>
111+ <differenceType>7002</differenceType> <!-- method removed -->
112+ <className>com/datastax/driver/core/QueryLogger$DynamicThresholdQueryLogger</className>
113+ <method>com.datastax.driver.core.PerHostPercentileTracker getPerHostPercentileLatencyTracker()</method>
114+ <justification>Introduced more generic parent type PercentileTracker (API was marked as beta and still subject to change)</justification>
115+ </difference>
116+
117+ <difference>
118+ <differenceType>7002</differenceType> <!-- method removed -->
119+ <className>com/datastax/driver/core/QueryLogger$DynamicThresholdQueryLogger</className>
120+ <method>void setPerHostPercentileLatencyTracker(com.datastax.driver.core.PerHostPercentileTracker)</method>
121+ <justification>Introduced more generic parent type PercentileTracker (API was marked as beta and still subject to change)</justification>
122+ </difference>
123+
124+ <difference>
125+ <differenceType>7005</differenceType> <!-- method argument type changed -->
126+ <className>com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy</className>
127+ <method>PercentileSpeculativeExecutionPolicy(com.datastax.driver.core.PerHostPercentileTracker, double, int)</method>
128+ <to>*</to> <!-- didn't find a way to write the new signature -->
129+ <justification>Introduced more generic parent type PercentileTracker (API was marked as beta and still subject to change)</justification>
130+ </difference>
131+
59132 </differences>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +18 −12
@@ -444,8 +444,9 @@
444444 */
445445 public Cluster register(Host.StateListener listener) {
446446 checkNotClosed(manager);
447- listener.onRegister(this);
448- manager.listeners.add(listener);
447+ boolean added = manager.listeners.add(listener);
448+ if (added)
449+ listener.onRegister(this);
449450 return this;
450451 }
451452
@@ -460,8 +461,9 @@
460461 */
461462 public Cluster unregister(Host.StateListener listener) {
462463 checkNotClosed(manager);
463- listener.onUnregister(this);
464- manager.listeners.remove(listener);
464+ boolean removed = manager.listeners.remove(listener);
465+ if (removed)
466+ listener.onUnregister(this);
465467 return this;
466468 }
467469
@@ -488,8 +490,9 @@
488490 */
489491 public Cluster register(LatencyTracker tracker) {
490492 checkNotClosed(manager);
491- tracker.onRegister(this);
492- manager.trackers.add(tracker);
493+ boolean added = manager.trackers.add(tracker);
494+ if (added)
495+ tracker.onRegister(this);
493496 return this;
494497 }
495498
@@ -505,8 +508,9 @@
505508 */
506509 public Cluster unregister(LatencyTracker tracker) {
507510 checkNotClosed(manager);
508- tracker.onUnregister(this);
509- manager.trackers.remove(tracker);
511+ boolean removed = manager.trackers.remove(tracker);
512+ if (removed)
513+ tracker.onUnregister(this);
510514 return this;
511515 }
512516
@@ -520,8 +524,9 @@
520524 */
521525 public Cluster register(SchemaChangeListener listener) {
522526 checkNotClosed(manager);
523- listener.onRegister(this);
524- manager.schemaChangeListeners.add(listener);
527+ boolean added = manager.schemaChangeListeners.add(listener);
528+ if (added)
529+ listener.onRegister(this);
525530 return this;
526531 }
527532
@@ -537,8 +542,9 @@
537542 */
538543 public Cluster unregister(SchemaChangeListener listener) {
539544 checkNotClosed(manager);
540- listener.onUnregister(this);
541- manager.schemaChangeListeners.remove(listener);
545+ boolean removed = manager.schemaChangeListeners.remove(listener);
546+ if (removed)
547+ listener.onUnregister(this);
542548 return this;
543549 }
544550
added driver-core/src/main/java/com/datastax/driver/core/ClusterWidePercentileTracker.java +76 −0
@@ -0,0 +1,76 @@
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+/**
19+ * A {@code PercentileTracker} that aggregates all measurements into a single histogram.
20+ * <p/>
21+ * This gives you global latency percentiles for the whole cluster, meaning that latencies of slower hosts will tend to
22+ * appear in higher percentiles.
23+ */
24+public class ClusterWidePercentileTracker extends PercentileTracker {
25+ private volatile Cluster cluster;
26+
27+ private ClusterWidePercentileTracker(long highestTrackableLatencyMillis,
28+ int numberOfSignificantValueDigits,
29+ int minRecordedValues,
30+ long intervalMs) {
31+ super(highestTrackableLatencyMillis, numberOfSignificantValueDigits, minRecordedValues, intervalMs);
32+ }
33+
34+ @Override
35+ public void onRegister(Cluster cluster) {
36+ this.cluster = cluster;
37+ }
38+
39+ @Override
40+ protected Cluster computeKey(Host host, Statement statement, Exception exception) {
41+ return cluster;
42+ }
43+
44+ /**
45+ * Returns a builder to create a new instance.
46+ *
47+ * @param highestTrackableLatencyMillis the highest expected latency. If a higher value is reported, it will be
48+ * ignored and a warning will be logged. A good rule of thumb is to set it
49+ * slightly higher than {@link SocketOptions#getReadTimeoutMillis()}.
50+ * @return the builder.
51+ */
52+ public static Builder builder(long highestTrackableLatencyMillis) {
53+ return new Builder(highestTrackableLatencyMillis);
54+ }
55+
56+ /**
57+ * Helper class to build {@code PerHostPercentileTracker} instances with a fluent interface.
58+ */
59+ public static class Builder extends PercentileTracker.Builder<Builder, ClusterWidePercentileTracker> {
60+
61+ Builder(long highestTrackableLatencyMillis) {
62+ super(highestTrackableLatencyMillis);
63+ }
64+
65+ @Override
66+ protected Builder self() {
67+ return this;
68+ }
69+
70+ @Override
71+ public ClusterWidePercentileTracker build() {
72+ return new ClusterWidePercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits,
73+ minRecordedValues, intervalMs);
74+ }
75+ }
76+}
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +25 −0
@@ -447,4 +447,29 @@
447447 */
448448 void onUnregister(Cluster cluster);
449449 }
450+
451+ /**
452+ * A {@code StateListener} that tracks when it gets registered or unregistered with a cluster.
453+ * <p/>
454+ * This interface exists only for backward-compatibility reasons: starting with the 3.0 branch of the driver, its
455+ * methods are on the parent interface directly.
456+ */
457+ public interface LifecycleAwareStateListener extends StateListener {
458+ /**
459+ * Gets invoked when the listener is registered with a cluster, or at cluster startup if the
460+ * listener was registered at initialization with
461+ * {@link com.datastax.driver.core.Cluster.Initializer#register(StateListener)}.
462+ *
463+ * @param cluster the cluster that this listener is registered with.
464+ */
465+ void onRegister(Cluster cluster);
466+
467+ /**
468+ * Gets invoked when the listener is unregistered from a cluster, or at cluster shutdown if
469+ * the listener was not unregistered.
470+ *
471+ * @param cluster the cluster that this listener was registered with.
472+ */
473+ void onUnregister(Cluster cluster);
474+ }
450475 }
added driver-core/src/main/java/com/datastax/driver/core/LifecycleAwareLatencyTracker.java +41 −0
@@ -0,0 +1,41 @@
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+/**
19+ * A {@code LatencyTracker} that tracks when it gets registered or unregistered with a cluster.
20+ * <p/>
21+ * This interface exists only for backward-compatibility reasons: starting with the 3.0 branch of the driver, its
22+ * methods are on the parent interface directly.
23+ */
24+public interface LifecycleAwareLatencyTracker extends LatencyTracker {
25+ /**
26+ * Gets invoked when the tracker is registered with a cluster, or at cluster startup if the
27+ * tracker was registered at initialization with
28+ * {@link com.datastax.driver.core.Cluster.Initializer#register(LatencyTracker)}.
29+ *
30+ * @param cluster the cluster that this tracker is registered with.
31+ */
32+ void onRegister(Cluster cluster);
33+
34+ /**
35+ * Gets invoked when the tracker is unregistered from a cluster, or at cluster shutdown if
36+ * the tracker was not unregistered.
37+ *
38+ * @param cluster the cluster that this tracker was registered with.
39+ */
40+ void onUnregister(Cluster cluster);
41+}
modified driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +23 −286
@@ -15,317 +15,54 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.exceptions.*;
19-import com.google.common.annotations.Beta;
20-import com.google.common.collect.ImmutableSet;
21-import com.google.common.collect.MapMaker;
22-import com.google.common.util.concurrent.Futures;
23-import com.google.common.util.concurrent.ListenableFuture;
24-import com.google.common.util.concurrent.SettableFuture;
25-import org.HdrHistogram.Histogram;
26-import org.HdrHistogram.Recorder;
27-import org.slf4j.Logger;
28-import org.slf4j.LoggerFactory;
29-
30-import java.util.Set;
31-import java.util.concurrent.ConcurrentMap;
32-import java.util.concurrent.ExecutionException;
33-import java.util.concurrent.TimeUnit;
34-import java.util.concurrent.TimeoutException;
35-
36-import static com.google.common.base.Preconditions.checkArgument;
37-import static java.util.concurrent.TimeUnit.*;
38-
3918 /**
40- * A {@link LatencyTracker} that records latencies for each host over a sliding time interval, and exposes an
41- * API to retrieve the latency at a given percentile.
19+ * A {@code PercentileTracker} that maintains a separate histogram for each host.
4220 * <p/>
43- * To use this class, build an instance with {@link #builderWithHighestTrackableLatencyMillis(long)} and register
44- * it with your {@link com.datastax.driver.core.Cluster} instance:
45- * <pre>
46- * PerHostPercentileTracker tracker = PerHostPercentileTracker
47- * .builderWithHighestTrackableLatencyMillis(15000)
48- * .build();
49- *
50- * cluster.register(tracker);
51- * ...
52- * tracker.getLatencyAtPercentile(host1, 99.0);
53- * </pre>
54- * <p/>
55- * This class uses <a href="http://hdrhistogram.github.io/HdrHistogram/">HdrHistogram</a> to record latencies:
56- * for each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
57- * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
58- * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
59- * interval at cluster startup, since we don't have a cached histogram yet.
60- * <p/>
61- * Note that this class is currently marked "beta": it hasn't been extensively tested yet, and the API is still subject
62- * to change.
21+ * This gives you per-host latency percentiles, meaning that each host will only be compared to itself.
6322 */
64-@Beta
65-public class PerHostPercentileTracker implements LatencyTracker {
66- private static final Logger logger = LoggerFactory.getLogger(PerHostPercentileTracker.class);
67-
68- private final ConcurrentMap<Host, Recorder> recorders;
69- private final ConcurrentMap<Host, CachedHistogram> cachedHistograms;
70- private final long highestTrackableLatencyMillis;
71- private final int numberOfSignificantValueDigits;
72- private final int minRecordedValues;
73- private final long intervalMs;
74-
75- private PerHostPercentileTracker(long highestTrackableLatencyMillis, int numberOfSignificantValueDigits,
76- int numberOfHosts,
23+public class PerHostPercentileTracker extends PercentileTracker {
24+ private PerHostPercentileTracker(long highestTrackableLatencyMillis,
25+ int numberOfSignificantValueDigits,
7726 int minRecordedValues,
7827 long intervalMs) {
79- try {
80- Histogram.class.getName();
81- } catch (NoClassDefFoundError e) {
82- throw new IllegalStateException("HdrHistogram seems to be missing from the classpath. " +
83- "Make sure you depend on it explicitly (the driver declares it as optional).", e);
84- }
85- this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
86- this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
87- this.minRecordedValues = minRecordedValues;
88- this.intervalMs = intervalMs;
89- this.recorders = new MapMaker().initialCapacity(numberOfHosts).makeMap();
90- this.cachedHistograms = new MapMaker().initialCapacity(numberOfHosts).makeMap();
28+ super(highestTrackableLatencyMillis, numberOfSignificantValueDigits, minRecordedValues, intervalMs);
29+ }
30+
31+ @Override
32+ protected Host computeKey(Host host, Statement statement, Exception exception) {
33+ return host;
9134 }
9235
9336 /**
9437 * Returns a builder to create a new instance.
9538 *
96- * @param highestTrackableLatencyMillis the highest expected latency. If a higher value is reported, it will be ignored and a
97- * warning will be logged. A good rule of thumb is to set it slightly higher than
98- * {@link SocketOptions#getReadTimeoutMillis()}.
39+ * @param highestTrackableLatencyMillis the highest expected latency. If a higher value is reported, it will be
40+ * ignored and a warning will be logged. A good rule of thumb is to set it
41+ * slightly higher than {@link SocketOptions#getReadTimeoutMillis()}.
9942 * @return the builder.
10043 */
101- public static Builder builderWithHighestTrackableLatencyMillis(long highestTrackableLatencyMillis) {
44+ public static Builder builder(long highestTrackableLatencyMillis) {
10245 return new Builder(highestTrackableLatencyMillis);
10346 }
10447
10548 /**
106- * Helper class to builder {@code PerHostPercentileTracker} instances with a fluent interface.
49+ * Helper class to build {@code PerHostPercentileTracker} instances with a fluent interface.
10750 */
108- public static class Builder {
109- private final long highestTrackableLatencyMillis;
110- private int numberOfSignificantValueDigits = 3;
111- private int minRecordedValues = 1000;
112- private int numberOfHosts = 16;
113- private long intervalMs = MINUTES.toMillis(5);
51+ public static class Builder extends PercentileTracker.Builder<Builder, PerHostPercentileTracker> {
11452
11553 Builder(long highestTrackableLatencyMillis) {
116- this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
117- }
118-
119- /**
120- * Sets the number of significant decimal digits to which histograms will maintain value
121- * resolution and separation. This must be an integer between 0 and 5.
122- * <p/>
123- * If not set explicitly, this value defaults to 3.
124- * <p/>
125- * See <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a>
126- * for a more detailed explanation on how this parameter affects the resolution of recorded samples.
127- *
128- * @param numberOfSignificantValueDigits the new value.
129- * @return this builder.
130- */
131- public Builder withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) {
132- this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
133- return this;
54+ super(highestTrackableLatencyMillis);
13455 }
13556
136- /**
137- * Sets the minimum number of values that must be recorded for a host before we consider
138- * the sample size significant.
139- * <p/>
140- * If this count is not reached during a given interval, {@link #getLatencyAtPercentile(Host, double)}
141- * will return a negative value, indicating that statistics are not available. In particular, this is true
142- * during the first interval.
143- * <p/>
144- * If not set explicitly, this value default to 1000.
145- *
146- * @param minRecordedValues the new value.
147- * @return this builder.
148- */
149- public Builder withMinRecordedValues(int minRecordedValues) {
150- this.minRecordedValues = minRecordedValues;
57+ @Override
58+ protected Builder self() {
15159 return this;
15260 }
15361
154- /**
155- * Sets the number of distinct hosts that the driver will ever connect to.
156- * <p/>
157- * This parameter is only used to pre-size internal maps in order to avoid unnecessary rehashing.
158- * <p/>
159- * If not set explicitly, this value defaults to 16.
160- *
161- * @param numberOfHosts the new value.
162- * @return this builder.
163- */
164- public Builder withNumberOfHosts(int numberOfHosts) {
165- this.numberOfHosts = numberOfHosts;
166- return this;
167- }
168-
169- /**
170- * Sets the time interval over which samples are recorded.
171- * <p/>
172- * For each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
173- * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
174- * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
175- * interval at cluster startup, since we don't have a cached histogram yet.
176- * <p/>
177- * If not set explicitly, this value defaults to 5 minutes.
178- *
179- * @param interval the new interval.
180- * @param unit the unit that the interval is expressed in.
181- * @return this builder.
182- */
183- public Builder withInterval(long interval, TimeUnit unit) {
184- this.intervalMs = MILLISECONDS.convert(interval, unit);
185- return this;
186- }
187-
188- /**
189- * Builds the {@code PerHostPercentileTracker} instance configured with this builder.
190- *
191- * @return the instance.
192- */
62+ @Override
19363 public PerHostPercentileTracker build() {
194- return new PerHostPercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits, numberOfHosts, minRecordedValues, intervalMs);
195- }
196- }
197-
198- @Override
199- public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
200- if (!shouldConsiderNewLatency(statement, exception))
201- return;
202-
203- long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
204- try {
205- getRecorder(host).recordValue(latencyMs);
206- } catch (ArrayIndexOutOfBoundsException e) {
207- logger.warn("Got request with latency of {} ms, which exceeds the configured maximum trackable value {}",
208- latencyMs, highestTrackableLatencyMillis);
209- }
210- }
211-
212- /**
213- * Returns the request latency for a host at a given percentile.
214- *
215- * @param host the host.
216- * @param percentile the percentile (for example, {@code 99.0} for the 99th percentile).
217- * @return the latency (in milliseconds) at the given percentile, or a negative value if it's not available yet.
218- */
219- public long getLatencyAtPercentile(Host host, double percentile) {
220- checkArgument(percentile >= 0.0 && percentile < 100,
221- "percentile must be between 0.0 and 100 (was %f)");
222- Histogram histogram = getLastIntervalHistogram(host);
223- if (histogram == null || histogram.getTotalCount() < minRecordedValues)
224- return -1;
225-
226- return histogram.getValueAtPercentile(percentile);
227- }
228-
229- private Recorder getRecorder(Host host) {
230- Recorder recorder = recorders.get(host);
231- if (recorder == null) {
232- recorder = new Recorder(highestTrackableLatencyMillis, numberOfSignificantValueDigits);
233- Recorder old = recorders.putIfAbsent(host, recorder);
234- if (old != null) {
235- // We got beaten at creating the recorder, use the actual instance and discard ours
236- recorder = old;
237- } else {
238- // Also set an empty cache entry to remember the time we started recording:
239- cachedHistograms.putIfAbsent(host, CachedHistogram.empty());
240- }
241- }
242- return recorder;
243- }
244-
245- /**
246- * @return null if no histogram is available yet (no entries recorded, or not for long enough)
247- */
248- private Histogram getLastIntervalHistogram(Host host) {
249- try {
250- while (true) {
251- CachedHistogram entry = cachedHistograms.get(host);
252- if (entry == null)
253- return null;
254-
255- long age = System.currentTimeMillis() - entry.timestamp;
256- if (age < intervalMs) { // current histogram is recent enough
257- return entry.histogram.get();
258- } else { // need to refresh
259- Recorder recorder = recorders.get(host);
260- // intervalMs should be much larger than the time it takes to replace a histogram, so this future should never block
261- Histogram staleHistogram = entry.histogram.get(0, MILLISECONDS);
262- SettableFuture<Histogram> future = SettableFuture.create();
263- CachedHistogram newEntry = new CachedHistogram(future);
264- if (cachedHistograms.replace(host, entry, newEntry)) {
265- // Only get the new histogram if we successfully replaced the cache entry.
266- // This ensures that only one thread will do it.
267- Histogram newHistogram = recorder.getIntervalHistogram(staleHistogram);
268- future.set(newHistogram);
269- return newHistogram;
270- }
271- // If we couldn't replace the entry it means we raced, so loop to try again
272- }
273- }
274- } catch (InterruptedException e) {
275- Thread.currentThread().interrupt();
276- return null;
277- } catch (ExecutionException e) {
278- throw new DriverInternalError("Unexpected error", e.getCause());
279- } catch (TimeoutException e) {
280- throw new DriverInternalError("Unexpected timeout while getting histogram", e);
281- }
282- }
283-
284- static class CachedHistogram {
285- final ListenableFuture<Histogram> histogram;
286- final long timestamp;
287-
288- CachedHistogram(ListenableFuture<Histogram> histogram) {
289- this.histogram = histogram;
290- this.timestamp = System.currentTimeMillis();
291- }
292-
293- static CachedHistogram empty() {
294- return new CachedHistogram(Futures.<Histogram>immediateFuture(null));
64+ return new PerHostPercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits,
65+ minRecordedValues, intervalMs);
29566 }
29667 }
297-
298- // TODO this was copy/pasted from LatencyAwarePolicy, maybe it could be refactored as a shared method
299- private boolean shouldConsiderNewLatency(Statement statement, Exception exception) {
300- // query was successful: always consider
301- if (exception == null)
302- return true;
303- // filter out "fast" errors
304- return !EXCLUDED_EXCEPTIONS.contains(exception.getClass());
305- }
306-
307- /**
308- * A set of DriverException subclasses that we should prevent from updating the host's score.
309- * The intent behind it is to filter out "fast" errors: when a host replies with such errors,
310- * it usually does so very quickly, because it did not involve any actual
311- * coordination work. Such errors are not good indicators of the host's responsiveness,
312- * and tend to make the host's score look better than it actually is.
313- */
314- private static final Set<Class<? extends Exception>> EXCLUDED_EXCEPTIONS = ImmutableSet.<Class<? extends Exception>>of(
315- UnavailableException.class, // this is done via the snitch and is usually very fast
316- OverloadedException.class,
317- BootstrappingException.class,
318- UnpreparedException.class,
319- QueryValidationException.class // query validation also happens at early stages in the coordinator
320- );
321-
322- @Override
323- public void onRegister(Cluster cluster) {
324- // nothing to do
325- }
326-
327- @Override
328- public void onUnregister(Cluster cluster) {
329- // nothing to do
330- }
33168 }
added driver-core/src/main/java/com/datastax/driver/core/PercentileTracker.java +342 −0
@@ -0,0 +1,342 @@
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.datastax.driver.core.exceptions.*;
19+import com.google.common.collect.ImmutableSet;
20+import com.google.common.util.concurrent.Futures;
21+import com.google.common.util.concurrent.ListenableFuture;
22+import com.google.common.util.concurrent.SettableFuture;
23+import org.HdrHistogram.Histogram;
24+import org.HdrHistogram.Recorder;
25+import org.slf4j.Logger;
26+import org.slf4j.LoggerFactory;
27+
28+import java.util.Set;
29+import java.util.concurrent.*;
30+
31+import static com.google.common.base.Preconditions.checkArgument;
32+import static java.util.concurrent.TimeUnit.*;
33+
34+/**
35+ * A {@link LatencyTracker} that records query latencies over a sliding time interval, and exposes an API to retrieve
36+ * the latency at a given percentile.
37+ * <p/>
38+ * Percentiles may be computed separately for different categories of requests; this is implementation-dependent and
39+ * determined by {@link #computeKey(Host, Statement, Exception)}.
40+ * <p/>
41+ * This class is used by percentile-aware components such as
42+ * {@link QueryLogger.Builder#withDynamicThreshold(PercentileTracker, double)} QueryLogger} and
43+ * {@link com.datastax.driver.core.policies.PercentileSpeculativeExecutionPolicy}.
44+ * <p/>
45+ * It uses <a href="http://hdrhistogram.github.io/HdrHistogram/">HdrHistogram</a> to record latencies:
46+ * for each category, there is a "live" histogram where current latencies are recorded, and a "cached", read-only
47+ * histogram that is used when clients call {@link #getLatencyAtPercentile(Host, Statement, Exception, double)}. Each
48+ * time the cached histogram becomes older than the interval, the two histograms are switched. Statistics will not be
49+ * available during the first interval at cluster startup, since we don't have a cached histogram yet.
50+ */
51+public abstract class PercentileTracker implements LifecycleAwareLatencyTracker {
52+ private static final Logger logger = LoggerFactory.getLogger(PercentileTracker.class);
53+
54+ private final long highestTrackableLatencyMillis;
55+ private final int numberOfSignificantValueDigits;
56+ private final int minRecordedValues;
57+ private final long intervalMs;
58+
59+ // The "live" recorders: this is where we store the latencies received from the cluster
60+ private final ConcurrentMap<Object, Recorder> recorders;
61+ // The cached histograms, corresponding to the previous interval. This is where we get the percentiles from when the
62+ // user requests them. Each histogram is valid for a given duration, when it gets stale we request a new one from
63+ // the corresponding recorder.
64+ private final ConcurrentMap<Object, CachedHistogram> cachedHistograms;
65+
66+ /**
67+ * Builds a new instance.
68+ *
69+ * @see Builder
70+ */
71+ protected PercentileTracker(long highestTrackableLatencyMillis,
72+ int numberOfSignificantValueDigits,
73+ int minRecordedValues,
74+ long intervalMs) {
75+ this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
76+ this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
77+ this.minRecordedValues = minRecordedValues;
78+ this.intervalMs = intervalMs;
79+ this.recorders = new ConcurrentHashMap<Object, Recorder>();
80+ this.cachedHistograms = new ConcurrentHashMap<Object, CachedHistogram>();
81+ }
82+
83+ /**
84+ * Computes a key used to categorize measurements. Measurements with the same key will be recorded in the same
85+ * histogram.
86+ * <p/>
87+ * It's recommended to keep the number of distinct keys low, in order to limit the memory footprint of the
88+ * histograms.
89+ *
90+ * @param host the host that was queried.
91+ * @param statement the statement that was executed.
92+ * @param exception if the query failed, the corresponding exception.
93+ * @return the key.
94+ */
95+ protected abstract Object computeKey(Host host, Statement statement, Exception exception);
96+
97+ @Override
98+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
99+ if (!include(host, statement, exception))
100+ return;
101+
102+ long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
103+ try {
104+ Recorder recorder = getRecorder(host, statement, exception);
105+ if (recorder != null)
106+ recorder.recordValue(latencyMs);
107+ } catch (ArrayIndexOutOfBoundsException e) {
108+ logger.warn("Got request with latency of {} ms, which exceeds the configured maximum trackable value {}",
109+ latencyMs, highestTrackableLatencyMillis);
110+ }
111+ }
112+
113+ /**
114+ * Returns the request latency at a given percentile.
115+ *
116+ * @param host the host (if this is relevant in the way percentiles are categorized).
117+ * @param statement the statement (if this is relevant in the way percentiles are categorized).
118+ * @param exception the exception (if this is relevant in the way percentiles are categorized).
119+ * @param percentile the percentile (for example, {@code 99.0} for the 99th percentile).
120+ * @return the latency (in milliseconds) at the given percentile, or a negative value if it's not available yet.
121+ * @see #computeKey(Host, Statement, Exception)
122+ */
123+ public long getLatencyAtPercentile(Host host, Statement statement, Exception exception, double percentile) {
124+ checkArgument(percentile >= 0.0 && percentile < 100,
125+ "percentile must be between 0.0 and 100 (was %s)", percentile);
126+ Histogram histogram = getLastIntervalHistogram(host, statement, exception);
127+ if (histogram == null || histogram.getTotalCount() < minRecordedValues)
128+ return -1;
129+
130+ return histogram.getValueAtPercentile(percentile);
131+ }
132+
133+ private Recorder getRecorder(Host host, Statement statement, Exception exception) {
134+ Object key = computeKey(host, statement, exception);
135+ if (key == null)
136+ return null;
137+
138+ Recorder recorder = recorders.get(key);
139+ if (recorder == null) {
140+ recorder = new Recorder(highestTrackableLatencyMillis, numberOfSignificantValueDigits);
141+ Recorder old = recorders.putIfAbsent(key, recorder);
142+ if (old != null) {
143+ // We got beaten at creating the recorder, use the actual instance and discard ours
144+ recorder = old;
145+ } else {
146+ // Also set an empty cache entry to remember the time we started recording:
147+ cachedHistograms.putIfAbsent(key, CachedHistogram.empty());
148+ }
149+ }
150+ return recorder;
151+ }
152+
153+ /**
154+ * @return null if no histogram is available yet (no entries recorded, or not for long enough)
155+ */
156+ private Histogram getLastIntervalHistogram(Host host, Statement statement, Exception exception) {
157+ Object key = computeKey(host, statement, exception);
158+ if (key == null)
159+ return null;
160+
161+ try {
162+ while (true) {
163+ CachedHistogram entry = cachedHistograms.get(key);
164+ if (entry == null)
165+ return null;
166+
167+ long age = System.currentTimeMillis() - entry.timestamp;
168+ if (age < intervalMs) { // current histogram is recent enough
169+ return entry.histogram.get();
170+ } else { // need to refresh
171+ Recorder recorder = recorders.get(key);
172+ // intervalMs should be much larger than the time it takes to replace a histogram, so this future should never block
173+ Histogram staleHistogram = entry.histogram.get(0, MILLISECONDS);
174+ SettableFuture<Histogram> future = SettableFuture.create();
175+ CachedHistogram newEntry = new CachedHistogram(future);
176+ if (cachedHistograms.replace(key, entry, newEntry)) {
177+ // Only get the new histogram if we successfully replaced the cache entry.
178+ // This ensures that only one thread will do it.
179+ Histogram newHistogram = recorder.getIntervalHistogram(staleHistogram);
180+ future.set(newHistogram);
181+ return newHistogram;
182+ }
183+ // If we couldn't replace the entry it means we raced, so loop to try again
184+ }
185+ }
186+ } catch (InterruptedException e) {
187+ Thread.currentThread().interrupt();
188+ return null;
189+ } catch (ExecutionException e) {
190+ throw new DriverInternalError("Unexpected error", e.getCause());
191+ } catch (TimeoutException e) {
192+ throw new DriverInternalError("Unexpected timeout while getting histogram", e);
193+ }
194+ }
195+
196+ /**
197+ * A histogram and the timestamp at which it was retrieved.
198+ * The data is only relevant for (timestamp + intervalMs); after that, the histogram is stale and we want to
199+ * retrieve a new one.
200+ */
201+ static class CachedHistogram {
202+ final ListenableFuture<Histogram> histogram;
203+ final long timestamp;
204+
205+ CachedHistogram(ListenableFuture<Histogram> histogram) {
206+ this.histogram = histogram;
207+ this.timestamp = System.currentTimeMillis();
208+ }
209+
210+ static CachedHistogram empty() {
211+ return new CachedHistogram(Futures.<Histogram>immediateFuture(null));
212+ }
213+ }
214+
215+ @Override
216+ public void onRegister(Cluster cluster) {
217+ // nothing by default
218+ }
219+
220+ @Override
221+ public void onUnregister(Cluster cluster) {
222+ // nothing by default
223+ }
224+
225+ /**
226+ * Determines whether a particular measurement should be included.
227+ * <p/>
228+ * This is used to ignore measurements that could skew the statistics; for example, we typically want to ignore
229+ * invalid query errors because they have a very low latency and would make a given cluster/host appear faster than
230+ * it really is.
231+ *
232+ * @param host the host that was queried.
233+ * @param statement the statement that was executed.
234+ * @param exception if the query failed, the corresponding exception.
235+ * @return whether the measurement should be included.
236+ */
237+ protected boolean include(Host host, Statement statement, Exception exception) {
238+ // query was successful: always consider
239+ if (exception == null)
240+ return true;
241+ // filter out "fast" errors
242+ // TODO this was copy/pasted from LatencyAwarePolicy, maybe it could be refactored as a shared method
243+ return !EXCLUDED_EXCEPTIONS.contains(exception.getClass());
244+ }
245+
246+ /**
247+ * A set of DriverException subclasses that we should prevent from updating the host's score.
248+ * The intent behind it is to filter out "fast" errors: when a host replies with such errors,
249+ * it usually does so very quickly, because it did not involve any actual
250+ * coordination work. Such errors are not good indicators of the host's responsiveness,
251+ * and tend to make the host's score look better than it actually is.
252+ */
253+ private static final Set<Class<? extends Exception>> EXCLUDED_EXCEPTIONS = ImmutableSet.<Class<? extends Exception>>of(
254+ UnavailableException.class, // this is done via the snitch and is usually very fast
255+ OverloadedException.class,
256+ BootstrappingException.class,
257+ UnpreparedException.class,
258+ QueryValidationException.class // query validation also happens at early stages in the coordinator
259+ );
260+
261+ /**
262+ * Base class for {@code PercentileTracker} implementation builders.
263+ *
264+ * @param <B> the type of the concrete builder implementation.
265+ * @param <T> the type of the object to build.
266+ */
267+ public static abstract class Builder<B, T> {
268+ protected final long highestTrackableLatencyMillis;
269+ protected int numberOfSignificantValueDigits = 3;
270+ protected int minRecordedValues = 1000;
271+ protected long intervalMs = MINUTES.toMillis(5);
272+
273+ Builder(long highestTrackableLatencyMillis) {
274+ this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
275+ }
276+
277+ protected abstract B self();
278+
279+ /**
280+ * Sets the number of significant decimal digits to which histograms will maintain value
281+ * resolution and separation. This must be an integer between 0 and 5.
282+ * <p/>
283+ * If not set explicitly, this value defaults to 3.
284+ * <p/>
285+ * See <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a>
286+ * for a more detailed explanation on how this parameter affects the resolution of recorded samples.
287+ *
288+ * @param numberOfSignificantValueDigits the new value.
289+ * @return this builder.
290+ */
291+ public B withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) {
292+ this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
293+ return self();
294+ }
295+
296+ /**
297+ * Sets the minimum number of values that must be recorded for a host before we consider
298+ * the sample size significant.
299+ * <p/>
300+ * If this count is not reached during a given interval,
301+ * {@link #getLatencyAtPercentile(Host, Statement, Exception, double)} will return a negative value, indicating
302+ * that statistics are not available. In particular, this is true during the first interval.
303+ * <p/>
304+ * If not set explicitly, this value default to 1000.
305+ *
306+ * @param minRecordedValues the new value.
307+ * @return this builder.
308+ */
309+ public B withMinRecordedValues(int minRecordedValues) {
310+ this.minRecordedValues = minRecordedValues;
311+ return self();
312+ }
313+
314+ /**
315+ * Sets the time interval over which samples are recorded.
316+ * <p/>
317+ * For each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only
318+ * histogram that is used when clients call {@link #getLatencyAtPercentile(Host, Statement, Exception, double)}.
319+ * Each time the cached histogram becomes older than the interval, the two histograms are switched. Note that
320+ * statistics will not be available during the first interval at cluster startup, since we don't have a cached
321+ * histogram yet.
322+ * <p/>
323+ * If not set explicitly, this value defaults to 5 minutes.
324+ *
325+ * @param interval the new interval.
326+ * @param unit the unit that the interval is expressed in.
327+ * @return this builder.
328+ */
329+ public B withInterval(long interval, TimeUnit unit) {
330+ this.intervalMs = MILLISECONDS.convert(interval, unit);
331+ return self();
332+ }
333+
334+ /**
335+ * Builds the {@code PercentileTracker} instance configured with this builder.
336+ *
337+ * @return the instance.
338+ */
339+ public abstract T build();
340+ }
341+
342+}
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +47 −59
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.annotations.Beta;
1918 import com.google.common.annotations.VisibleForTesting;
2019 import org.slf4j.Logger;
2120 import org.slf4j.LoggerFactory;
@@ -81,33 +80,15 @@
8180 * <strong>Constant thresholds vs. Dynamic thresholds</strong>
8281 * <p/>
8382 * Currently the QueryLogger can track slow queries in two different ways:
84- * using a constant threshold in milliseconds (which is the default behavior),
85- * or using a dynamic threshold based on per-host percentiles computed by
86- * {@link PerHostPercentileTracker}.
87- * <p/>
88- * <b>Note that the dynamic threshold version is currently provided as a beta preview: it hasn't been extensively
89- * tested yet, and the API is still subject to change.</b> To use it, you must first obtain and register
90- * an instance of {@link PerHostPercentileTracker}, then create your QueryLogger as follows:
91- * <p/>
92- * <pre>
93- * Cluster cluster = ...
94- * // create an instance of PerHostPercentileTracker and register it
95- * PerHostPercentileTracker tracker = ...;
96- * cluster.register(tracker);
97- * // create an instance of QueryLogger and register it
98- * QueryLogger queryLogger = QueryLogger.builder()
99- * .withDynamicThreshold(tracker, ...)
100- * .withMaxQueryStringLength(...)
101- * .build();
102- * cluster.register(queryLogger);
103- * </pre>
104- * <p/>
83+ * using a {@link Builder#withConstantThreshold(long)} constant threshold} in milliseconds (which is the default
84+ * behavior), or using a {@link Builder#withDynamicThreshold(PercentileTracker, double) dynamic threshold}
85+ * based on latency percentiles.
10586 * <p/>
10687 * This class is thread-safe.
10788 *
10889 * @since 2.0.10
10990 */
110-public abstract class QueryLogger implements LatencyTracker {
91+public abstract class QueryLogger implements LifecycleAwareLatencyTracker {
11192
11293 /**
11394 * The default latency threshold in milliseconds beyond which queries are considered 'slow'
@@ -306,45 +287,43 @@
306287 * to track slow queries.
307288 * <p/>
308289 * Dynamic thresholds are based on per-host latency percentiles, as computed
309- * by {@link PerHostPercentileTracker}.
310- * <p/>
311- * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
312- * to change.</b>
290+ * by {@link PercentileTracker}.
313291 */
314- @Beta
315292 public static class DynamicThresholdQueryLogger extends QueryLogger {
316293
317294 private volatile double slowQueryLatencyThresholdPercentile;
318295
319- private volatile PerHostPercentileTracker perHostPercentileLatencyTracker;
296+ private volatile PercentileTracker percentileLatencyTracker;
320297
321- private DynamicThresholdQueryLogger(int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, double slowQueryLatencyThresholdPercentile, PerHostPercentileTracker perHostPercentileLatencyTracker) {
298+ private DynamicThresholdQueryLogger(int maxQueryStringLength, int maxParameterValueLength,
299+ int maxLoggedParameters, double slowQueryLatencyThresholdPercentile,
300+ PercentileTracker percentileLatencyTracker) {
322301 super(maxQueryStringLength, maxParameterValueLength, maxLoggedParameters);
323302 this.setSlowQueryLatencyThresholdPercentile(slowQueryLatencyThresholdPercentile);
324- this.setPerHostPercentileLatencyTracker(perHostPercentileLatencyTracker);
303+ this.setPercentileLatencyTracker(percentileLatencyTracker);
325304 }
326305
327306 /**
328- * Return the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
307+ * Return the percentile tracker to use for recording per-host latency histograms.
329308 * Cannot be {@code null}.
330309 *
331- * @return the {@link PerHostPercentileTracker} instance to use.
310+ * @return the percentile tracker to use.
332311 */
333- public PerHostPercentileTracker getPerHostPercentileLatencyTracker() {
334- return perHostPercentileLatencyTracker;
312+ public PercentileTracker getPercentileLatencyTracker() {
313+ return percentileLatencyTracker;
335314 }
336315
337316 /**
338- * Set the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
317+ * Set the percentile tracker to use for recording per-host latency histograms.
339318 * Cannot be {@code null}.
340319 *
341- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use.
342- * @throws IllegalArgumentException if {@code perHostPercentileLatencyTracker == null}.
320+ * @param percentileLatencyTracker the percentile tracker instance to use.
321+ * @throws IllegalArgumentException if {@code percentileLatencyTracker == null}.
343322 */
344- public void setPerHostPercentileLatencyTracker(PerHostPercentileTracker perHostPercentileLatencyTracker) {
345- if (perHostPercentileLatencyTracker == null)
323+ public void setPercentileLatencyTracker(PercentileTracker percentileLatencyTracker) {
324+ if (percentileLatencyTracker == null)
346325 throw new IllegalArgumentException("perHostPercentileLatencyTracker cannot be null");
347- this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
326+ this.percentileLatencyTracker = percentileLatencyTracker;
348327 }
349328
350329 /**
@@ -375,7 +354,7 @@
375354
376355 @Override
377356 protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) {
378- long threshold = perHostPercentileLatencyTracker.getLatencyAtPercentile(host, slowQueryLatencyThresholdPercentile);
357+ long threshold = percentileLatencyTracker.getLatencyAtPercentile(host, statement, null, slowQueryLatencyThresholdPercentile);
379358 if (threshold >= 0 && latencyMs > threshold) {
380359 maybeLogSlowQuery(host, statement, latencyMs, threshold);
381360 } else {
@@ -389,6 +368,15 @@
389368 logQuery(statement, null, SLOW_LOGGER, message);
390369 }
391370 }
371+
372+ @Override
373+ public void onRegister(Cluster cluster) {
374+ super.onRegister(cluster);
375+ cluster.register(percentileLatencyTracker);
376+ }
377+
378+ // Don't unregister the latency tracker in onUnregister, we can't guess if it's being used by another component
379+ // or not.
392380 }
393381
394382 /**
@@ -406,7 +394,7 @@
406394
407395 private double slowQueryLatencyThresholdPercentile = DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE;
408396
409- private PerHostPercentileTracker perHostPercentileLatencyTracker;
397+ private PercentileTracker percentileLatencyTracker;
410398
411399 private boolean constantThreshold = true;
412400
@@ -414,7 +402,7 @@
414402 * Enables slow query latency tracking based on constant thresholds.
415403 * <p/>
416404 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
417- * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
405+ * or {@link #withDynamicThreshold(PercentileTracker, double) dynamic thresholds},
418406 * not both.
419407 *
420408 * @param slowQueryLatencyThresholdMillis The threshold in milliseconds beyond which queries are considered 'slow'
@@ -431,26 +419,23 @@
431419 /**
432420 * Enables slow query latency tracking based on dynamic thresholds.
433421 * <p/>
434- * Dynamic thresholds are based on per-host latency percentiles, as computed
435- * by {@link PerHostPercentileTracker}.
436- * <p/>
437- * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
438- * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
439- * not both.
422+ * Dynamic thresholds are based on latency percentiles, as computed by {@link PercentileTracker}.
440423 * <p/>
441- * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
442- * to change.</b>
424+ * Note: You should either use {@link #withConstantThreshold(long) constant thresholds} or
425+ * {@link #withDynamicThreshold(PercentileTracker, double) dynamic thresholds}, not both.
443426 *
444- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
445- * Cannot be {@code null}.
427+ * @param percentileLatencyTracker the {@link PercentileTracker} instance to use for recording
428+ * latency histograms. Cannot be {@code null}.
429+ * It will get {@link Cluster#register(LatencyTracker) registered}
430+ * with the cluster at the same time as this logger.
446431 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
447432 * It must be comprised between 0 inclusive and 100 exclusive.
448433 * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
449434 * @return this {@link Builder} instance (for method chaining).
450435 */
451- @Beta
452- public Builder withDynamicThreshold(PerHostPercentileTracker perHostPercentileLatencyTracker, double slowQueryLatencyThresholdPercentile) {
453- this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
436+ public Builder withDynamicThreshold(PercentileTracker percentileLatencyTracker,
437+ double slowQueryLatencyThresholdPercentile) {
438+ this.percentileLatencyTracker = percentileLatencyTracker;
454439 this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile;
455440 constantThreshold = false;
456441 return this;
@@ -517,9 +502,12 @@
517502 */
518503 public QueryLogger build() {
519504 if (constantThreshold) {
520- return new ConstantThresholdQueryLogger(maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
505+ return new ConstantThresholdQueryLogger(maxQueryStringLength, maxParameterValueLength,
506+ maxLoggedParameters, slowQueryLatencyThresholdMillis);
521507 } else {
522- return new DynamicThresholdQueryLogger(maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
508+ return new DynamicThresholdQueryLogger(maxQueryStringLength, maxParameterValueLength,
509+ maxLoggedParameters, slowQueryLatencyThresholdPercentile,
510+ percentileLatencyTracker);
523511 }
524512 }
525513
modified driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java +14 −33
@@ -15,11 +15,7 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.datastax.driver.core.Cluster;
19-import com.datastax.driver.core.Host;
20-import com.datastax.driver.core.PerHostPercentileTracker;
21-import com.datastax.driver.core.Statement;
22-import com.google.common.annotations.Beta;
18+import com.datastax.driver.core.*;
2319
2420 import java.util.concurrent.atomic.AtomicInteger;
2521
@@ -27,41 +23,26 @@
2723
2824 /**
2925 * A policy that triggers speculative executions when the request to the current host is above a given percentile.
30- * <p/>
31- * This class uses a {@link PerHostPercentileTracker} that must be registered with the cluster instance:
32- * <pre>
33- * PerHostPercentileTracker tracker = PerHostPercentileTracker
34- * .builderWithHighestTrackableLatencyMillis(15000)
35- * .build();
36- * PercentileSpeculativeExecutionPolicy policy = new PercentileSpeculativeExecutionPolicy(tracker, 99.0, 2);
37- * cluster = Cluster.builder()
38- * .addContactPoint("127.0.0.1")
39- * .withSpeculativeExecutionPolicy(policy)
40- * .build();
41- * cluster.register(tracker);
42- * </pre>
43- * You <b>must</b> register the tracker with the cluster yourself (as shown on the last line above), this class will not
44- * do it itself.
45- * <p/>
46- * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
47- * to change.</b>
4826 */
49-@Beta
5027 public class PercentileSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
51- private final PerHostPercentileTracker percentileTracker;
28+ private final PercentileTracker percentileTracker;
5229 private final double percentile;
5330 private final int maxSpeculativeExecutions;
5431
5532 /**
5633 * Builds a new instance.
5734 *
58- * @param percentileTracker the component that will record latencies. Note that this policy doesn't register it with the {@code Cluster},
59- * you <b>must</b> do it yourself (see the code example in this class's Javadoc).
60- * @param percentile the percentile that a request's latency must fall into to be considered slow (ex: {@code 99.0}).
61- * @param maxSpeculativeExecutions the maximum number of speculative executions that will be triggered for a given request (this does not
62- * include the initial, normal request). Must be strictly positive.
35+ * @param percentileTracker the component that will record latencies. It will get
36+ * {@link Cluster#register(LatencyTracker) registered} with the cluster when this
37+ * policy initializes.
38+ * @param percentile the percentile that a request's latency must fall into to be considered slow (ex:
39+ * {@code 99.0}).
40+ * @param maxSpeculativeExecutions the maximum number of speculative executions that will be triggered for a given
41+ * request (this does not include the initial, normal request). Must be strictly
42+ * positive.
6343 */
64- public PercentileSpeculativeExecutionPolicy(PerHostPercentileTracker percentileTracker, double percentile, int maxSpeculativeExecutions) {
44+ public PercentileSpeculativeExecutionPolicy(PercentileTracker percentileTracker,
45+ double percentile, int maxSpeculativeExecutions) {
6546 checkArgument(maxSpeculativeExecutions > 0,
6647 "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
6748 checkArgument(percentile >= 0.0 && percentile < 100,
@@ -80,7 +61,7 @@
8061 @Override
8162 public long nextExecution(Host lastQueried) {
8263 if (remaining.getAndDecrement() > 0)
83- return percentileTracker.getLatencyAtPercentile(lastQueried, percentile);
64+ return percentileTracker.getLatencyAtPercentile(lastQueried, null, null, percentile);
8465 else
8566 return -1;
8667 }
@@ -89,7 +70,7 @@
8970
9071 @Override
9172 public void init(Cluster cluster) {
92- // nothing
73+ cluster.register(percentileTracker);
9374 }
9475
9576 @Override
added driver-core/src/test/java/com/datastax/driver/core/ClusterWidePercentileTrackerTest.java +65 −0
@@ -0,0 +1,65 @@
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.datastax.driver.core.exceptions.ReadTimeoutException;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.testng.annotations.Test;
22+
23+import java.util.List;
24+import java.util.concurrent.TimeUnit;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+import static org.mockito.Mockito.mock;
28+
29+public class ClusterWidePercentileTrackerTest
30+ extends PercentileTrackerTest<ClusterWidePercentileTracker.Builder, ClusterWidePercentileTracker> {
31+
32+ @Test(groups = "unit")
33+ public void should_track_all_measurements_for_cluster() {
34+ // given - a cluster wide percentile tracker.
35+ Cluster cluster0 = mock(Cluster.class);
36+ ClusterWidePercentileTracker tracker = builder()
37+ .withInterval(1, TimeUnit.SECONDS)
38+ .withMinRecordedValues(100).build();
39+ tracker.onRegister(cluster0);
40+
41+ List<Host> hosts = Lists.newArrayList(mock(Host.class), mock(Host.class), mock(Host.class));
42+ List<Statement> statements = Lists.newArrayList(mock(Statement.class), mock(Statement.class));
43+ List<Exception> exceptions = Lists.newArrayList(new Exception(), null, new ReadTimeoutException(ConsistencyLevel.ANY, 1, 1, true), null, null);
44+
45+ // when - recording latencies over a linear progression with varying hosts, statements and exceptions.
46+ for (int i = 0; i < 100; i++) {
47+ tracker.update(
48+ hosts.get(i % hosts.size()),
49+ statements.get(i % statements.size()),
50+ exceptions.get(i % exceptions.size()), TimeUnit.NANOSECONDS.convert(i + 1, TimeUnit.MILLISECONDS));
51+ }
52+ Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
53+
54+ // then - the resulting tracker's percentiles should represent that linear progression. (x percentile == x)
55+ for (int i = 1; i <= 99; i++) {
56+ long latencyAtPct = tracker.getLatencyAtPercentile(null, null, null, i);
57+ assertThat(latencyAtPct).isEqualTo(i);
58+ }
59+ }
60+
61+ @Override
62+ public ClusterWidePercentileTracker.Builder builder() {
63+ return ClusterWidePercentileTracker.builder(defaultMaxLatency);
64+ }
65+}
added driver-core/src/test/java/com/datastax/driver/core/CustomPercentileTrackerTest.java +75 −0
@@ -0,0 +1,75 @@
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.datastax.driver.core.exceptions.ReadTimeoutException;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.testng.annotations.Test;
22+
23+import java.util.List;
24+import java.util.concurrent.TimeUnit;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+import static org.mockito.Mockito.mock;
28+
29+public class CustomPercentileTrackerTest {
30+
31+ @Test(groups = "unit")
32+ public void should_return_negative_value_when_key_cant_be_computed() {
33+ // given - A custom tracker that returns null for a specific host and keys by host otherwise.
34+ final Cluster cluster0 = mock(Cluster.class);
35+ final Host host0 = mock(Host.class);
36+ final Host host1 = mock(Host.class);
37+
38+ PercentileTracker tracker = new PercentileTracker(1000, 3, 100, 50) {
39+ @Override
40+ protected Object computeKey(Host host, Statement statement, Exception exception) {
41+ if (host == host0) {
42+ return host;
43+ } else {
44+ return null;
45+ }
46+ }
47+ };
48+ tracker.onRegister(cluster0);
49+
50+ List<Statement> statements = Lists.newArrayList(mock(Statement.class), mock(Statement.class));
51+ List<Exception> exceptions = Lists.newArrayList(new Exception(), null, new ReadTimeoutException(ConsistencyLevel.ANY, 1, 1, true), null, null);
52+
53+ // when - recording latencies over a linear progression with varying hosts, statements and exceptions.
54+ for (int i = 0; i < 100; i++) {
55+ tracker.update(
56+ host0,
57+ statements.get(i % statements.size()),
58+ exceptions.get(i % exceptions.size()), TimeUnit.NANOSECONDS.convert((i + 1) * 2, TimeUnit.MILLISECONDS));
59+
60+ tracker.update(
61+ host1,
62+ statements.get(i % statements.size()),
63+ exceptions.get(i % exceptions.size()), TimeUnit.NANOSECONDS.convert(i + 1, TimeUnit.MILLISECONDS));
64+ }
65+ Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
66+
67+ // then - host0 should return a linear progression (i*2) since it has a tracker.
68+ // host1 should return -1 since it has no tracker since it has no key.
69+ for (int i = 1; i <= 99; i++) {
70+ assertThat(tracker.getLatencyAtPercentile(host0, null, null, i)).isEqualTo(i * 2);
71+ assertThat(tracker.getLatencyAtPercentile(host1, null, null, i)).isEqualTo(-1);
72+ }
73+
74+ }
75+}
added driver-core/src/test/java/com/datastax/driver/core/PerHostPercentileTrackerTest.java +80 −0
@@ -0,0 +1,80 @@
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.datastax.driver.core.exceptions.ReadTimeoutException;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.testng.annotations.Test;
22+
23+import java.util.List;
24+import java.util.concurrent.TimeUnit;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+import static org.mockito.Mockito.mock;
28+
29+public class PerHostPercentileTrackerTest
30+ extends PercentileTrackerTest<PerHostPercentileTracker.Builder, PerHostPercentileTracker> {
31+
32+ @Test(groups = "unit")
33+ public void should_track_measurements_by_host() {
34+ // given - a per host percentile tracker.
35+ Cluster cluster0 = mock(Cluster.class);
36+ PerHostPercentileTracker tracker = builder()
37+ .withInterval(1, TimeUnit.SECONDS)
38+ .withMinRecordedValues(100).build();
39+ tracker.onRegister(cluster0);
40+
41+ List<Host> hosts = Lists.newArrayList(mock(Host.class), mock(Host.class), mock(Host.class));
42+ List<Statement> statements = Lists.newArrayList(mock(Statement.class), mock(Statement.class));
43+ List<Exception> exceptions = Lists.newArrayList(new Exception(), null, new ReadTimeoutException(ConsistencyLevel.ANY, 1, 1, true), null, null);
44+
45+ // when - recording latencies over a linear progression with varying hosts, statements and exceptions.
46+ for (int i = 0; i < 100; i++) {
47+ tracker.update(hosts.get(0),
48+ statements.get(i % statements.size()),
49+ exceptions.get(i % exceptions.size()),
50+ TimeUnit.NANOSECONDS.convert(i + 1, TimeUnit.MILLISECONDS));
51+
52+ tracker.update(hosts.get(1),
53+ statements.get(i % statements.size()),
54+ exceptions.get(i % exceptions.size()),
55+ TimeUnit.NANOSECONDS.convert((i + 1) * 2, TimeUnit.MILLISECONDS));
56+
57+ tracker.update(hosts.get(2),
58+ statements.get(i % statements.size()),
59+ exceptions.get(i % exceptions.size()),
60+ TimeUnit.NANOSECONDS.convert((i + 1) * 3, TimeUnit.MILLISECONDS));
61+ }
62+ Uninterruptibles.sleepUninterruptibly(2000, TimeUnit.MILLISECONDS);
63+
64+ // then - the resulting tracker's percentiles should represent that linear progression for each host individually.
65+ // host0: (x percentile == x)
66+ // host1: (x percentile == 2x)
67+ // host2: (x percentile == 3x)
68+ for (int i = 1; i <= 99; i++) {
69+ assertThat(tracker.getLatencyAtPercentile(hosts.get(0), null, null, i)).isEqualTo(i);
70+ assertThat(tracker.getLatencyAtPercentile(hosts.get(1), null, null, i)).isEqualTo(i * 2);
71+ assertThat(tracker.getLatencyAtPercentile(hosts.get(2), null, null, i)).isEqualTo(i * 3);
72+ }
73+ }
74+
75+
76+ @Override
77+ public PerHostPercentileTracker.Builder builder() {
78+ return PerHostPercentileTracker.builder(defaultMaxLatency);
79+ }
80+}
added driver-core/src/test/java/com/datastax/driver/core/PercentileTrackerTest.java +166 −0
@@ -0,0 +1,166 @@
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.datastax.driver.core.exceptions.*;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.apache.log4j.Level;
22+import org.apache.log4j.Logger;
23+import org.testng.annotations.Test;
24+
25+import java.util.List;
26+import java.util.concurrent.TimeUnit;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+import static org.mockito.Mockito.mock;
30+
31+public abstract class PercentileTrackerTest<B extends PercentileTracker.Builder<B, T>, T extends PercentileTracker> {
32+
33+ Host defaultHost = mock(Host.class);
34+
35+ @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
36+ Exception defaultException = mock(Exception.class);
37+
38+ Statement defaultStatement = mock(Statement.class);
39+
40+ long defaultMaxLatency = 1000;
41+
42+ public abstract B builder();
43+
44+ @Test(groups = "unit")
45+ public void should_ignore_certain_exceptions() throws Exception {
46+ // given - a percentile tracker.
47+ Cluster cluster0 = mock(Cluster.class);
48+ T tracker = builder()
49+ .withInterval(50, TimeUnit.MILLISECONDS)
50+ .withMinRecordedValues(100).build();
51+ tracker.onRegister(cluster0);
52+
53+ // when - recording measurements with the following exceptions.
54+ List<Exception> exceptionsToIgnore = Lists.<Exception>newArrayList(
55+ new UnavailableException(ConsistencyLevel.ANY, 0, 0),
56+ new OverloadedException(null, "Overloaded"),
57+ new BootstrappingException(null, "Bootstrapping"),
58+ new UnpreparedException(null, "Unprepared"),
59+ new InvalidQueryException("Validation", new Exception()));
60+
61+ long startTime = System.currentTimeMillis();
62+ for (Exception exception : exceptionsToIgnore) {
63+ tracker.update(defaultHost, defaultStatement, exception, TimeUnit.NANOSECONDS.convert(999, TimeUnit.MILLISECONDS));
64+ }
65+ for (int i = 0; i < 100; i++) {
66+ tracker.update(defaultHost, defaultStatement, defaultException, TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS));
67+ }
68+ long waitTime = 50 - (System.currentTimeMillis() - startTime);
69+ Uninterruptibles.sleepUninterruptibly(waitTime + 100, TimeUnit.MILLISECONDS);
70+
71+ // then - the resulting tracker's percentiles should all be 1, indicating those exceptions were ignored.
72+ for (int i = 1; i <= 99; i++) {
73+ long latencyAtPct = tracker.getLatencyAtPercentile(defaultHost, defaultStatement, defaultException, i);
74+ assertThat(latencyAtPct).isEqualTo(1);
75+ }
76+ }
77+
78+ @Test(groups = "unit")
79+ public void should_not_record_anything_if_not_enough_measurements() throws Exception {
80+ // given - a percentile tracker with 100 min recorded values.
81+ Cluster cluster0 = mock(Cluster.class);
82+ T tracker = builder()
83+ .withInterval(50, TimeUnit.MILLISECONDS)
84+ .withMinRecordedValues(100).build();
85+ tracker.onRegister(cluster0);
86+
87+ // when - recording less measurements then required.
88+ long startTime = System.currentTimeMillis();
89+ for (int i = 0; i < 99; i++) {
90+ tracker.update(defaultHost, defaultStatement, defaultException, TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS));
91+ }
92+ long waitTime = 50 - (System.currentTimeMillis() - startTime);
93+ Uninterruptibles.sleepUninterruptibly(waitTime + 100, TimeUnit.MILLISECONDS);
94+
95+ // then - the resulting tracker's percentiles should all be -1, indicating there were not enough values to consider.
96+ for (int i = 1; i <= 99; i++) {
97+ long latencyAtPct = tracker.getLatencyAtPercentile(defaultHost, defaultStatement, defaultException, i);
98+ assertThat(latencyAtPct).isEqualTo(-1);
99+ }
100+ }
101+
102+ @Test(groups = "short")
103+ public void should_return_negative_value_when_interval_hasnt_elapsed() throws Exception {
104+ // given - a percentile tracker with a long interval.
105+ Cluster cluster0 = mock(Cluster.class);
106+ T tracker = builder()
107+ .withInterval(50, TimeUnit.MINUTES)
108+ .withMinRecordedValues(100).build();
109+ tracker.onRegister(cluster0);
110+
111+ // when - recording enough measurements.
112+ for (int i = 0; i < 99; i++) {
113+ tracker.update(defaultHost, defaultStatement, defaultException, TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS));
114+ }
115+
116+ // then - the resulting tracker's percentiles should all be -1, since not enough time was given to elapse interval.
117+ for (int i = 1; i <= 99; i++) {
118+ long latencyAtPct = tracker.getLatencyAtPercentile(defaultHost, defaultStatement, defaultException, i);
119+ assertThat(latencyAtPct).isEqualTo(-1);
120+ }
121+ }
122+
123+ @Test(groups = "unit")
124+ public void should_not_record_value_and_log_when_measurement_higher_than_max_trackable_value() throws Exception {
125+ // given - a percentile tracker with a long interval.
126+ Cluster cluster0 = mock(Cluster.class);
127+ T tracker = builder()
128+ .withInterval(50, TimeUnit.MILLISECONDS)
129+ .withMinRecordedValues(100).build();
130+ tracker.onRegister(cluster0);
131+
132+ Logger percentileLogger = Logger.getLogger(PercentileTracker.class);
133+ Level originalLevel = percentileLogger.getLevel();
134+ percentileLogger.setLevel(Level.WARN);
135+ MemoryAppender appender = new MemoryAppender();
136+ percentileLogger.addAppender(appender);
137+
138+ try {
139+ long startTime = System.currentTimeMillis();
140+ for (int i = 0; i < 100; i++) {
141+ tracker.update(defaultHost, defaultStatement, defaultException, TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS));
142+ }
143+
144+ // HdrHistogram adjusts its max based on bucket size, with these values it allows a max value of 2047 (2^11-1).
145+ long largeLatency = 2048;
146+ // when - recording a value larger than max trackable value.
147+ tracker.update(defaultHost, defaultStatement, defaultException, TimeUnit.NANOSECONDS.convert(largeLatency, TimeUnit.MILLISECONDS));
148+
149+ assertThat(appender.get())
150+ .contains("Got request with latency of " + largeLatency
151+ + " ms, which exceeds the configured maximum trackable value " + defaultMaxLatency);
152+
153+ long waitTime = 50 - (System.currentTimeMillis() - startTime);
154+ Uninterruptibles.sleepUninterruptibly(waitTime + 100, TimeUnit.MILLISECONDS);
155+
156+ // then - the resulting tracker's percentiles should all be 1, indicating the large value was ignored.
157+ for (int i = 1; i <= 99; i++) {
158+ long latencyAtPct = tracker.getLatencyAtPercentile(defaultHost, defaultStatement, defaultException, i);
159+ assertThat(latencyAtPct).isEqualTo(1);
160+ }
161+ } finally {
162+ percentileLogger.setLevel(originalLevel);
163+ percentileLogger.removeAppender(appender);
164+ }
165+ }
166+}
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +53 −1
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.*;
19+import com.google.common.util.concurrent.Uninterruptibles;
1920 import org.apache.log4j.Level;
2021 import org.apache.log4j.Logger;
2122 import org.scassandra.http.client.Result;
@@ -24,6 +25,8 @@
2425 import org.testng.annotations.DataProvider;
2526 import org.testng.annotations.Test;
2627
28+import java.util.concurrent.TimeUnit;
29+
2730 import static com.datastax.driver.core.QueryLogger.builder;
2831 import static org.apache.log4j.Level.DEBUG;
2932 import static org.apache.log4j.Level.INFO;
@@ -82,7 +85,7 @@
8285 }
8386
8487 @Test(groups = "short")
85- public void should_log_slow_queries() throws Exception {
88+ public void should_log_queries_beyond_constant_threshold() throws Exception {
8689 // given
8790 slow.setLevel(DEBUG);
8891 queryLogger = builder()
@@ -106,6 +109,55 @@
106109 .contains(query);
107110 }
108111
112+ @Test(groups = "short")
113+ public void should_log_queries_beyond_dynamic_threshold() throws Exception {
114+ // given
115+ slow.setLevel(DEBUG);
116+ queryLogger = builder()
117+ .withDynamicThreshold(ClusterWidePercentileTracker.builder(1000)
118+ .withMinRecordedValues(100)
119+ .withInterval(1, TimeUnit.SECONDS).build(), 99)
120+ .build();
121+ cluster.register(queryLogger);
122+
123+ // prime a fast query to respond right away.
124+ String fastQuery = "SELECT foo FROM bar";
125+ primingClient.prime(
126+ queryBuilder()
127+ .withQuery(fastQuery)
128+ .build()
129+ );
130+
131+ // prime a slow query to respond after 100ms.
132+ String slowQuery = "SELECT bar from foo";
133+ primingClient.prime(
134+ queryBuilder()
135+ .withQuery(slowQuery)
136+ .withThen(then().withFixedDelay(100L))
137+ .build()
138+ );
139+
140+ // submit 100 fast queries to prime to the histogram.
141+ long startTime = System.currentTimeMillis();
142+ for (int i = 0; i < 100; i++) {
143+ session.execute(fastQuery);
144+ }
145+
146+ // Wait up to 1 second to allow initial histogram to be cached.
147+ long waitTime = 1000 - (System.currentTimeMillis() - startTime);
148+ Uninterruptibles.sleepUninterruptibly(waitTime, TimeUnit.MILLISECONDS);
149+
150+ // when
151+ session.execute(slowQuery);
152+ // then
153+ String line = slowAppender.waitAndGet(5000);
154+ assertThat(line)
155+ .contains("Query too slow")
156+ .contains(ip)
157+ .contains(slowQuery)
158+ .doesNotContain(fastQuery);
159+ }
160+
109161 @Test(groups = "short")
110162 public void should_log_timed_out_queries() throws Exception {
111163 // given