Elffuss BraidHub

kikocis/java-driver public

Merge pull request #586 from datastax/java1051

Percentile tracker improvements
Changeset449ad3d4341be1e857ba1e2a490d088e1c0625ce0c10bd2d05d7b29b4a2fd38e
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-03 16:54 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-03 16:54 +01:00
Parents732e04daae01, 19d71907ff87

Browse the files at this changeset

16 files changed

modified changelog/README.md +2 −0
@@ -26,6 +26,8 @@
2626 - [bug] JAVA-819: Expose more errors in RetryPolicy + provide idempotent-aware wrapper.
2727 - [improvement] JAVA-1040: SimpleStatement parameters support in QueryLogger.
2828 - [bug] JAVA-1064: getTable create statement doesn't properly handle quotes in primary key.
29+- [improvement] JAVA-888: Add cluster-wide percentile tracker.
30+- [improvement] JAVA-963: Automatically register PercentileTracker from components that use it.
2931
3032 Merged from 2.0 branch:
3133
modified clirr-ignores.xml +118 −42
@@ -7,50 +7,126 @@
77 * run `mvn clirr:clirr` at the root directory
88 * check the reports in `<module>/target/site/clirr-report.html`
99 * add new differences if needed. Difference types are explained at http://www.mojohaus.org/clirr-maven-plugin/examples/ignored-differences.html
10+
11+ The formatter introduces line breaks that make Clirr unhappy:
12+ @formatter:off
1013 -->
1114 <differences>
1215
13- <difference>
14- <differenceType>6006</differenceType> <!-- field now final -->
15- <className>com/datastax/driver/core/ProtocolVersion</className>
16- <field>NEWEST_SUPPORTED</field>
17- <justification>This was an oversight, this field was never intended to be non final</justification>
18- </difference>
19-
20- <difference>
21- <differenceType>8001</differenceType> <!-- class removed -->
22- <className>com/datastax/driver/core/schemabuilder/ColumnType$NativeColumnType</className>
23- <justification>This class was accidentally exposed, it was meant to be package-private</justification>
24- </difference>
25-
26- <difference>
27- <differenceType>1001</differenceType> <!-- decreased visibility -->
28- <className>com/datastax/driver/core/HostConnectionPool$Phase</className>
29- <justification>False positive: HostConnectionPool is not exposed to clients</justification>
30- </difference>
31-
32- <difference>
33- <differenceType>1001</differenceType> <!-- decreased visibility -->
34- <className>com/datastax/driver/core/ConvictionPolicy$Factory</className>
35- <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
36- </difference>
37-
38- <difference>
39- <differenceType>8001</differenceType> <!-- class removed -->
40- <className>com/datastax/driver/core/ConvictionPolicy$Simple</className>
41- <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
42- </difference>
43-
44- <difference>
45- <differenceType>8001</differenceType> <!-- class removed -->
46- <className>com/datastax/driver/core/ConvictionPolicy$Simple$Factory</className>
47- <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
48- </difference>
49-
50- <difference>
51- <differenceType>1001</differenceType> <!-- decreased visibility -->
52- <className>com/datastax/driver/mapping/ColumnMapper$Kind</className>
53- <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
54- </difference>
16+ <difference>
17+ <differenceType>6006</differenceType> <!-- field now final -->
18+ <className>com/datastax/driver/core/ProtocolVersion</className>
19+ <field>NEWEST_SUPPORTED</field>
20+ <justification>This was an oversight, this field was never intended to be non final</justification>
21+ </difference>
22+
23+ <difference>
24+ <differenceType>8001</differenceType> <!-- class removed -->
25+ <className>com/datastax/driver/core/schemabuilder/ColumnType$NativeColumnType</className>
26+ <justification>This class was accidentally exposed, it was meant to be package-private</justification>
27+ </difference>
28+
29+ <difference>
30+ <differenceType>1001</differenceType> <!-- decreased visibility -->
31+ <className>com/datastax/driver/core/HostConnectionPool$Phase</className>
32+ <justification>False positive: HostConnectionPool is not exposed to clients</justification>
33+ </difference>
34+
35+ <difference>
36+ <differenceType>1001</differenceType> <!-- decreased visibility -->
37+ <className>com/datastax/driver/core/ConvictionPolicy$Factory</className>
38+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
39+ </difference>
40+
41+ <difference>
42+ <differenceType>8001</differenceType> <!-- class removed -->
43+ <className>com/datastax/driver/core/ConvictionPolicy$Simple</className>
44+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
45+ </difference>
46+
47+ <difference>
48+ <differenceType>8001</differenceType> <!-- class removed -->
49+ <className>com/datastax/driver/core/ConvictionPolicy$Simple$Factory</className>
50+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
51+ </difference>
52+
53+ <difference>
54+ <differenceType>1001</differenceType> <!-- decreased visibility -->
55+ <className>com/datastax/driver/mapping/ColumnMapper$Kind</className>
56+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
57+ </difference>
58+
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>
55131
56132 </differences>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +34 −8
@@ -435,7 +435,9 @@
435435 */
436436 public Cluster register(Host.StateListener listener) {
437437 checkNotClosed(manager);
438- manager.listeners.add(listener);
438+ boolean added = manager.listeners.add(listener);
439+ if (added && listener instanceof Host.LifecycleAwareStateListener)
440+ ((Host.LifecycleAwareStateListener) listener).onRegister(this);
439441 return this;
440442 }
441443
@@ -450,7 +452,9 @@
450452 */
451453 public Cluster unregister(Host.StateListener listener) {
452454 checkNotClosed(manager);
453- manager.listeners.remove(listener);
455+ boolean removed = manager.listeners.remove(listener);
456+ if (removed && listener instanceof Host.LifecycleAwareStateListener)
457+ ((Host.LifecycleAwareStateListener) listener).onUnregister(this);
454458 return this;
455459 }
456460
@@ -475,7 +479,9 @@
475479 */
476480 public Cluster register(LatencyTracker tracker) {
477481 checkNotClosed(manager);
478- manager.trackers.add(tracker);
482+ boolean added = manager.trackers.add(tracker);
483+ if (added && tracker instanceof LifecycleAwareLatencyTracker)
484+ ((LifecycleAwareLatencyTracker) tracker).onRegister(this);
479485 return this;
480486 }
481487
@@ -491,7 +497,9 @@
491497 */
492498 public Cluster unregister(LatencyTracker tracker) {
493499 checkNotClosed(manager);
494- manager.trackers.remove(tracker);
500+ boolean removed = manager.trackers.remove(tracker);
501+ if (removed && tracker instanceof LifecycleAwareLatencyTracker)
502+ ((LifecycleAwareLatencyTracker) tracker).onUnregister(this);
495503 return this;
496504 }
497505
@@ -505,8 +513,9 @@
505513 */
506514 public Cluster register(SchemaChangeListener listener) {
507515 checkNotClosed(manager);
508- listener.onRegister(this);
509- manager.schemaChangeListeners.add(listener);
516+ boolean added = manager.schemaChangeListeners.add(listener);
517+ if (added)
518+ listener.onRegister(this);
510519 return this;
511520 }
512521
@@ -522,8 +531,9 @@
522531 */
523532 public Cluster unregister(SchemaChangeListener listener) {
524533 checkNotClosed(manager);
525- listener.onUnregister(this);
526- manager.schemaChangeListeners.remove(listener);
534+ boolean removed = manager.schemaChangeListeners.remove(listener);
535+ if (removed)
536+ listener.onUnregister(this);
527537 return this;
528538 }
529539
@@ -1471,6 +1481,14 @@
14711481 // rack...) to initialize the load balancing policy
14721482 loadBalancingPolicy().init(Cluster.this, contactPointHosts);
14731483 speculativeRetryPolicy().init(Cluster.this);
1484+ for (LatencyTracker tracker : trackers) {
1485+ if (tracker instanceof LifecycleAwareLatencyTracker)
1486+ ((LifecycleAwareLatencyTracker) tracker).onRegister(Cluster.this);
1487+ }
1488+ for (Host.StateListener listener : listeners) {
1489+ if (listener instanceof Host.LifecycleAwareStateListener)
1490+ ((Host.LifecycleAwareStateListener) listener).onRegister(Cluster.this);
1491+ }
14741492
14751493 for (Host host : removedContactPointHosts) {
14761494 loadBalancingPolicy().onRemove(host);
@@ -1622,6 +1640,14 @@
16221640 if (translater instanceof CloseableAddressTranslater)
16231641 ((CloseableAddressTranslater) translater).close();
16241642
1643+ for (LatencyTracker tracker : trackers) {
1644+ if (tracker instanceof LifecycleAwareLatencyTracker)
1645+ ((LifecycleAwareLatencyTracker) tracker).onUnregister(Cluster.this);
1646+ }
1647+ for (Host.StateListener listener : listeners) {
1648+ if (listener instanceof Host.LifecycleAwareStateListener)
1649+ ((Host.LifecycleAwareStateListener) listener).onUnregister(Cluster.this);
1650+ }
16251651 for (SchemaChangeListener listener : schemaChangeListeners) {
16261652 listener.onUnregister(Cluster.this);
16271653 }
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
@@ -330,4 +330,29 @@
330330 */
331331 public void onRemove(Host host);
332332 }
333+
334+ /**
335+ * A {@code StateListener} that tracks when it gets registered or unregistered with a cluster.
336+ * <p/>
337+ * This interface exists only for backward-compatibility reasons: starting with the 3.0 branch of the driver, its
338+ * methods are on the parent interface directly.
339+ */
340+ public interface LifecycleAwareStateListener extends StateListener {
341+ /**
342+ * Gets invoked when the listener is registered with a cluster, or at cluster startup if the
343+ * listener was registered at initialization with
344+ * {@link com.datastax.driver.core.Cluster.Initializer#register(StateListener)}.
345+ *
346+ * @param cluster the cluster that this listener is registered with.
347+ */
348+ void onRegister(Cluster cluster);
349+
350+ /**
351+ * Gets invoked when the listener is unregistered from a cluster, or at cluster shutdown if
352+ * the listener was not unregistered.
353+ *
354+ * @param cluster the cluster that this listener was registered with.
355+ */
356+ void onUnregister(Cluster cluster);
357+ }
333358 }
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 −270
@@ -15,301 +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- this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
80- this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
81- this.minRecordedValues = minRecordedValues;
82- this.intervalMs = intervalMs;
83- this.recorders = new MapMaker().initialCapacity(numberOfHosts).makeMap();
84- 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;
8534 }
8635
8736 /**
8837 * Returns a builder to create a new instance.
8938 *
90- * @param highestTrackableLatencyMillis the highest expected latency. If a higher value is reported, it will be ignored and a
91- * warning will be logged. A good rule of thumb is to set it slightly higher than
92- * {@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()}.
9342 * @return the builder.
9443 */
95- public static Builder builderWithHighestTrackableLatencyMillis(long highestTrackableLatencyMillis) {
44+ public static Builder builder(long highestTrackableLatencyMillis) {
9645 return new Builder(highestTrackableLatencyMillis);
9746 }
9847
9948 /**
100- * Helper class to builder {@code PerHostPercentileTracker} instances with a fluent interface.
49+ * Helper class to build {@code PerHostPercentileTracker} instances with a fluent interface.
10150 */
102- public static class Builder {
103- private final long highestTrackableLatencyMillis;
104- private int numberOfSignificantValueDigits = 3;
105- private int minRecordedValues = 1000;
106- private int numberOfHosts = 16;
107- private long intervalMs = MINUTES.toMillis(5);
51+ public static class Builder extends PercentileTracker.Builder<Builder, PerHostPercentileTracker> {
10852
10953 Builder(long highestTrackableLatencyMillis) {
110- this.highestTrackableLatencyMillis = highestTrackableLatencyMillis;
111- }
112-
113- /**
114- * Sets the number of significant decimal digits to which histograms will maintain value
115- * resolution and separation. This must be an integer between 0 and 5.
116- * <p/>
117- * If not set explicitly, this value defaults to 3.
118- * <p/>
119- * See <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a>
120- * for a more detailed explanation on how this parameter affects the resolution of recorded samples.
121- *
122- * @param numberOfSignificantValueDigits the new value.
123- * @return this builder.
124- */
125- public Builder withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) {
126- this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
127- return this;
128- }
129-
130- /**
131- * Sets the minimum number of values that must be recorded for a host before we consider
132- * the sample size significant.
133- * <p/>
134- * If this count is not reached during a given interval, {@link #getLatencyAtPercentile(Host, double)}
135- * will return a negative value, indicating that statistics are not available. In particular, this is true
136- * during the first interval.
137- * <p/>
138- * If not set explicitly, this value default to 1000.
139- *
140- * @param minRecordedValues the new value.
141- * @return this builder.
142- */
143- public Builder withMinRecordedValues(int minRecordedValues) {
144- this.minRecordedValues = minRecordedValues;
145- return this;
146- }
147-
148- /**
149- * Sets the number of distinct hosts that the driver will ever connect to.
150- * <p/>
151- * This parameter is only used to pre-size internal maps in order to avoid unnecessary rehashing.
152- * <p/>
153- * If not set explicitly, this value defaults to 16.
154- *
155- * @param numberOfHosts the new value.
156- * @return this builder.
157- */
158- public Builder withNumberOfHosts(int numberOfHosts) {
159- this.numberOfHosts = numberOfHosts;
160- return this;
54+ super(highestTrackableLatencyMillis);
16155 }
16256
163- /**
164- * Sets the time interval over which samples are recorded.
165- * <p/>
166- * For each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram
167- * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes
168- * older than the interval, the two histograms are switched. Note that statistics will not be available during the first
169- * interval at cluster startup, since we don't have a cached histogram yet.
170- * <p/>
171- * If not set explicitly, this value defaults to 5 minutes.
172- *
173- * @param interval the new interval.
174- * @param unit the unit that the interval is expressed in.
175- * @return this builder.
176- */
177- public Builder withInterval(long interval, TimeUnit unit) {
178- this.intervalMs = MILLISECONDS.convert(interval, unit);
57+ @Override
58+ protected Builder self() {
17959 return this;
18060 }
18161
182- /**
183- * Builds the {@code PerHostPercentileTracker} instance configured with this builder.
184- *
185- * @return the instance.
186- */
62+ @Override
18763 public PerHostPercentileTracker build() {
188- return new PerHostPercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits, numberOfHosts, minRecordedValues, intervalMs);
189- }
190- }
191-
192- @Override
193- public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
194- if (!shouldConsiderNewLatency(statement, exception))
195- return;
196-
197- long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
198- try {
199- getRecorder(host).recordValue(latencyMs);
200- } catch (ArrayIndexOutOfBoundsException e) {
201- logger.warn("Got request with latency of {} ms, which exceeds the configured maximum trackable value {}",
202- latencyMs, highestTrackableLatencyMillis);
203- }
204- }
205-
206- /**
207- * Returns the request latency for a host at a given percentile.
208- *
209- * @param host the host.
210- * @param percentile the percentile (for example, {@code 99.0} for the 99th percentile).
211- * @return the latency (in milliseconds) at the given percentile, or a negative value if it's not available yet.
212- */
213- public long getLatencyAtPercentile(Host host, double percentile) {
214- checkArgument(percentile >= 0.0 && percentile < 100,
215- "percentile must be between 0.0 and 100 (was %f)");
216- Histogram histogram = getLastIntervalHistogram(host);
217- if (histogram == null || histogram.getTotalCount() < minRecordedValues)
218- return -1;
219-
220- return histogram.getValueAtPercentile(percentile);
221- }
222-
223- private Recorder getRecorder(Host host) {
224- Recorder recorder = recorders.get(host);
225- if (recorder == null) {
226- recorder = new Recorder(highestTrackableLatencyMillis, numberOfSignificantValueDigits);
227- Recorder old = recorders.putIfAbsent(host, recorder);
228- if (old != null) {
229- // We got beaten at creating the recorder, use the actual instance and discard ours
230- recorder = old;
231- } else {
232- // Also set an empty cache entry to remember the time we started recording:
233- cachedHistograms.putIfAbsent(host, CachedHistogram.empty());
234- }
235- }
236- return recorder;
237- }
238-
239- /**
240- * @return null if no histogram is available yet (no entries recorded, or not for long enough)
241- */
242- private Histogram getLastIntervalHistogram(Host host) {
243- try {
244- while (true) {
245- CachedHistogram entry = cachedHistograms.get(host);
246- if (entry == null)
247- return null;
248-
249- long age = System.currentTimeMillis() - entry.timestamp;
250- if (age < intervalMs) { // current histogram is recent enough
251- return entry.histogram.get();
252- } else { // need to refresh
253- Recorder recorder = recorders.get(host);
254- // intervalMs should be much larger than the time it takes to replace a histogram, so this future should never block
255- Histogram staleHistogram = entry.histogram.get(0, MILLISECONDS);
256- SettableFuture<Histogram> future = SettableFuture.create();
257- CachedHistogram newEntry = new CachedHistogram(future);
258- if (cachedHistograms.replace(host, entry, newEntry)) {
259- // Only get the new histogram if we successfully replaced the cache entry.
260- // This ensures that only one thread will do it.
261- Histogram newHistogram = recorder.getIntervalHistogram(staleHistogram);
262- future.set(newHistogram);
263- return newHistogram;
264- }
265- // If we couldn't replace the entry it means we raced, so loop to try again
266- }
267- }
268- } catch (InterruptedException e) {
269- Thread.currentThread().interrupt();
270- return null;
271- } catch (ExecutionException e) {
272- throw new DriverInternalError("Unexpected error", e.getCause());
273- } catch (TimeoutException e) {
274- throw new DriverInternalError("Unexpected timeout while getting histogram", e);
275- }
276- }
277-
278- static class CachedHistogram {
279- final ListenableFuture<Histogram> histogram;
280- final long timestamp;
281-
282- CachedHistogram(ListenableFuture<Histogram> histogram) {
283- this.histogram = histogram;
284- this.timestamp = System.currentTimeMillis();
64+ return new PerHostPercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits,
65+ minRecordedValues, intervalMs);
28566 }
286-
287- static CachedHistogram empty() {
288- return new CachedHistogram(Futures.<Histogram>immediateFuture(null));
289- }
290- }
291-
292- // TODO this was copy/pasted from LatencyAwarePolicy, maybe it could be refactored as a shared method
293- private boolean shouldConsiderNewLatency(Statement statement, Exception exception) {
294- // query was successful: always consider
295- if (exception == null)
296- return true;
297- // filter out "fast" errors
298- return !EXCLUDED_EXCEPTIONS.contains(exception.getClass());
29967 }
300-
301- /**
302- * A set of DriverException subclasses that we should prevent from updating the host's score.
303- * The intent behind it is to filter out "fast" errors: when a host replies with such errors,
304- * it usually does so very quickly, because it did not involve any actual
305- * coordination work. Such errors are not good indicators of the host's responsiveness,
306- * and tend to make the host's score look better than it actually is.
307- */
308- private static final Set<Class<? extends Exception>> EXCLUDED_EXCEPTIONS = ImmutableSet.<Class<? extends Exception>>of(
309- UnavailableException.class, // this is done via the snitch and is usually very fast
310- OverloadedException.class,
311- BootstrappingException.class,
312- UnpreparedException.class,
313- QueryValidationException.class // query validation also happens at early stages in the coordinator
314- );
31568 }
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 +58 −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;
@@ -80,33 +79,15 @@
8079 * <strong>Constant thresholds vs. Dynamic thresholds</strong>
8180 * <p/>
8281 * 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- * <p/>
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- * <p/>
82+ * using a {@link Builder#withConstantThreshold(long)} constant threshold} in milliseconds (which is the default
83+ * behavior), or using a {@link Builder#withDynamicThreshold(PercentileTracker, double) dynamic threshold}
84+ * based on latency percentiles.
10485 * <p/>
10586 * This class is thread-safe.
10687 *
10788 * @since 2.0.10
10889 */
109-public abstract class QueryLogger implements LatencyTracker {
90+public abstract class QueryLogger implements LifecycleAwareLatencyTracker {
11091
11192 /**
11293 * The default latency threshold in milliseconds beyond which queries are considered 'slow'
@@ -288,6 +269,16 @@
288269 logQuery(statement, null, SLOW_LOGGER, message);
289270 }
290271 }
272+
273+ @Override
274+ public void onRegister(Cluster cluster) {
275+ // nothing to do
276+ }
277+
278+ @Override
279+ public void onUnregister(Cluster cluster) {
280+ // nothing to do
281+ }
291282 }
292283
293284 /**
@@ -295,45 +286,43 @@
295286 * to track slow queries.
296287 * <p/>
297288 * Dynamic thresholds are based on per-host latency percentiles, as computed
298- * by {@link PerHostPercentileTracker}.
299- * <p/>
300- * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
301- * to change.</b>
289+ * by {@link PercentileTracker}.
302290 */
303- @Beta
304291 public static class DynamicThresholdQueryLogger extends QueryLogger {
305292
306293 private volatile double slowQueryLatencyThresholdPercentile;
307294
308- private volatile PerHostPercentileTracker perHostPercentileLatencyTracker;
295+ private volatile PercentileTracker percentileLatencyTracker;
309296
310- private DynamicThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, double slowQueryLatencyThresholdPercentile, PerHostPercentileTracker perHostPercentileLatencyTracker) {
297+ private DynamicThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength,
298+ int maxLoggedParameters, double slowQueryLatencyThresholdPercentile,
299+ PercentileTracker percentileLatencyTracker) {
311300 super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters);
312301 this.setSlowQueryLatencyThresholdPercentile(slowQueryLatencyThresholdPercentile);
313- this.setPerHostPercentileLatencyTracker(perHostPercentileLatencyTracker);
302+ this.setPercentileLatencyTracker(percentileLatencyTracker);
314303 }
315304
316305 /**
317- * Return the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
306+ * Return the percentile tracker to use for recording per-host latency histograms.
318307 * Cannot be {@code null}.
319308 *
320- * @return the {@link PerHostPercentileTracker} instance to use.
309+ * @return the percentile tracker to use.
321310 */
322- public PerHostPercentileTracker getPerHostPercentileLatencyTracker() {
323- return perHostPercentileLatencyTracker;
311+ public PercentileTracker getPercentileLatencyTracker() {
312+ return percentileLatencyTracker;
324313 }
325314
326315 /**
327- * Set the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
316+ * Set the percentile tracker to use for recording per-host latency histograms.
328317 * Cannot be {@code null}.
329318 *
330- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use.
331- * @throws IllegalArgumentException if {@code perHostPercentileLatencyTracker == null}.
319+ * @param percentileLatencyTracker the percentile tracker instance to use.
320+ * @throws IllegalArgumentException if {@code percentileLatencyTracker == null}.
332321 */
333- public void setPerHostPercentileLatencyTracker(PerHostPercentileTracker perHostPercentileLatencyTracker) {
334- if (perHostPercentileLatencyTracker == null)
322+ public void setPercentileLatencyTracker(PercentileTracker percentileLatencyTracker) {
323+ if (percentileLatencyTracker == null)
335324 throw new IllegalArgumentException("perHostPercentileLatencyTracker cannot be null");
336- this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
325+ this.percentileLatencyTracker = percentileLatencyTracker;
337326 }
338327
339328 /**
@@ -364,7 +353,7 @@
364353
365354 @Override
366355 protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) {
367- long threshold = perHostPercentileLatencyTracker.getLatencyAtPercentile(host, slowQueryLatencyThresholdPercentile);
356+ long threshold = percentileLatencyTracker.getLatencyAtPercentile(host, statement, null, slowQueryLatencyThresholdPercentile);
368357 if (threshold >= 0 && latencyMs > threshold) {
369358 maybeLogSlowQuery(host, statement, latencyMs, threshold);
370359 } else {
@@ -378,6 +367,16 @@
378367 logQuery(statement, null, SLOW_LOGGER, message);
379368 }
380369 }
370+
371+ @Override
372+ public void onRegister(Cluster cluster) {
373+ cluster.register(percentileLatencyTracker);
374+ }
375+
376+ @Override
377+ public void onUnregister(Cluster cluster) {
378+ // Don't unregister the latency tracker, we can't guess if it's being used by another component or not.
379+ }
381380 }
382381
383382 /**
@@ -397,7 +396,7 @@
397396
398397 private double slowQueryLatencyThresholdPercentile = DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE;
399398
400- private PerHostPercentileTracker perHostPercentileLatencyTracker;
399+ private PercentileTracker percentileLatencyTracker;
401400
402401 private boolean constantThreshold = true;
403402
@@ -409,7 +408,7 @@
409408 * Enables slow query latency tracking based on constant thresholds.
410409 * <p/>
411410 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
412- * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
411+ * or {@link #withDynamicThreshold(PercentileTracker, double) dynamic thresholds},
413412 * not both.
414413 *
415414 * @param slowQueryLatencyThresholdMillis The threshold in milliseconds beyond which queries are considered 'slow'
@@ -426,26 +425,23 @@
426425 /**
427426 * Enables slow query latency tracking based on dynamic thresholds.
428427 * <p/>
429- * Dynamic thresholds are based on per-host latency percentiles, as computed
430- * by {@link PerHostPercentileTracker}.
431- * <p/>
432- * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
433- * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
434- * not both.
428+ * Dynamic thresholds are based on latency percentiles, as computed by {@link PercentileTracker}.
435429 * <p/>
436- * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
437- * to change.</b>
430+ * Note: You should either use {@link #withConstantThreshold(long) constant thresholds} or
431+ * {@link #withDynamicThreshold(PercentileTracker, double) dynamic thresholds}, not both.
438432 *
439- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
440- * Cannot be {@code null}.
433+ * @param percentileLatencyTracker the {@link PercentileTracker} instance to use for recording
434+ * latency histograms. Cannot be {@code null}.
435+ * It will get {@link Cluster#register(LatencyTracker) registered}
436+ * with the cluster at the same time as this logger.
441437 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
442438 * It must be comprised between 0 inclusive and 100 exclusive.
443439 * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
444440 * @return this {@link Builder} instance (for method chaining).
445441 */
446- @Beta
447- public Builder withDynamicThreshold(PerHostPercentileTracker perHostPercentileLatencyTracker, double slowQueryLatencyThresholdPercentile) {
448- this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
442+ public Builder withDynamicThreshold(PercentileTracker percentileLatencyTracker,
443+ double slowQueryLatencyThresholdPercentile) {
444+ this.percentileLatencyTracker = percentileLatencyTracker;
449445 this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile;
450446 constantThreshold = false;
451447 return this;
@@ -512,9 +508,12 @@
512508 */
513509 public QueryLogger build() {
514510 if (constantThreshold) {
515- return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
511+ return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength,
512+ maxLoggedParameters, slowQueryLatencyThresholdMillis);
516513 } else {
517- return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
514+ return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength,
515+ maxLoggedParameters, slowQueryLatencyThresholdPercentile,
516+ percentileLatencyTracker);
518517 }
519518 }
520519
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.PrimingRequest;
@@ -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(cluster)
@@ -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(cluster)
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
modified pom.xml +1 −1
@@ -157,7 +157,7 @@
157157 </execution>
158158 </executions>
159159 <configuration>
160- <comparisonVersion>2.1.8</comparisonVersion>
160+ <comparisonVersion>2.1.9</comparisonVersion>
161161 <ignoredDifferencesFile>../clirr-ignores.xml</ignoredDifferencesFile>
162162 <excludes>
163163 <!-- Package-private, internal classes -->