kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 334084c93e381941029e3457314af6633be1a36f8fdd65bfadc6a884d00af885 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-04-24 17:54 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-04-28 18:42 +02:00 |
| Parents | 92389abdcf2b |
7 files changed
modified driver-core/CHANGELOG.rst +2 −0
| @@ -45,6 +45,8 @@ | ||
| 45 | 45 | JAVA-425) |
| 46 | 46 | - [new feature] Speculative query executions (JAVA-561) |
| 47 | 47 | - [bug] Release connection before completing the ResultSetFuture (JAVA-666) |
| 48 | +- [new feature BETA] Percentile-based variant of query logger and speculative | |
| 49 | + executions (JAVA-723) | |
| 48 | 50 | |
| 49 | 51 | Merged from 2.0.9_fixes branch: |
| 50 | 52 |
modified driver-core/pom.xml +8 −1
| @@ -68,6 +68,8 @@ | ||
| 68 | 68 | <optional>true</optional> |
| 69 | 69 | </dependency> |
| 70 | 70 | |
| 71 | + <!-- End of compression libraries --> | |
| 72 | + | |
| 71 | 73 | <dependency> |
| 72 | 74 | <groupId>io.netty</groupId> |
| 73 | 75 | <artifactId>netty-transport-native-epoll</artifactId> |
| @@ -75,7 +77,12 @@ | ||
| 75 | 77 | <optional>true</optional> |
| 76 | 78 | </dependency> |
| 77 | 79 | |
| 78 | - <!-- End of compression libraries --> | |
| 80 | + <dependency> | |
| 81 | + <groupId>org.hdrhistogram</groupId> | |
| 82 | + <artifactId>HdrHistogram</artifactId> | |
| 83 | + <version>2.1.4</version> | |
| 84 | + <optional>true</optional> | |
| 85 | + </dependency> | |
| 79 | 86 | |
| 80 | 87 | <dependency> |
| 81 | 88 | <groupId>org.testng</groupId> |
added driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +317 −0
| @@ -0,0 +1,317 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.Set; | |
| 19 | +import java.util.concurrent.ConcurrentMap; | |
| 20 | +import java.util.concurrent.ExecutionException; | |
| 21 | +import java.util.concurrent.TimeUnit; | |
| 22 | +import java.util.concurrent.TimeoutException; | |
| 23 | + | |
| 24 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 25 | +import static java.util.concurrent.TimeUnit.MINUTES; | |
| 26 | +import static java.util.concurrent.TimeUnit.NANOSECONDS; | |
| 27 | + | |
| 28 | +import com.google.common.annotations.Beta; | |
| 29 | +import com.google.common.collect.ImmutableSet; | |
| 30 | +import com.google.common.collect.MapMaker; | |
| 31 | +import com.google.common.util.concurrent.Futures; | |
| 32 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 33 | +import com.google.common.util.concurrent.SettableFuture; | |
| 34 | +import org.HdrHistogram.Histogram; | |
| 35 | +import org.HdrHistogram.Recorder; | |
| 36 | +import org.slf4j.Logger; | |
| 37 | +import org.slf4j.LoggerFactory; | |
| 38 | + | |
| 39 | +import static com.google.common.base.Preconditions.checkArgument; | |
| 40 | + | |
| 41 | +import com.datastax.driver.core.exceptions.*; | |
| 42 | + | |
| 43 | +/** | |
| 44 | + * A {@link LatencyTracker} that records latencies for each host over a sliding time interval, and exposes an | |
| 45 | + * API to retrieve the latency at a given percentile. | |
| 46 | + * <p> | |
| 47 | + * To use this class, build an instance with {@link #builderWithHighestTrackableLatencyMillis(long)} and register | |
| 48 | + * it with your {@link com.datastax.driver.core.Cluster} instance: | |
| 49 | + * <pre> | |
| 50 | + * PerHostPercentileTracker tracker = PerHostPercentileTracker | |
| 51 | + * .builderWithHighestTrackableLatencyMillis(15000) | |
| 52 | + * .build(); | |
| 53 | + * | |
| 54 | + * cluster.register(tracker); | |
| 55 | + * ... | |
| 56 | + * tracker.getLatencyAtPercentile(host1, 99.0); | |
| 57 | + * </pre> | |
| 58 | + * <p> | |
| 59 | + * This class uses <a href="http://hdrhistogram.github.io/HdrHistogram/">HdrHistogram</a> to record latencies: | |
| 60 | + * for each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram | |
| 61 | + * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes | |
| 62 | + * older than the interval, the two histograms are switched. Note that statistics will not be available during the first | |
| 63 | + * interval at cluster startup, since we don't have a cached histogram yet. | |
| 64 | + * <p> | |
| 65 | + * Note that this class is currently marked "beta": it hasn't been extensively tested yet, and the API is still subject | |
| 66 | + * to change. | |
| 67 | + */ | |
| 68 | +@Beta | |
| 69 | +public class PerHostPercentileTracker implements LatencyTracker { | |
| 70 | + private static final Logger logger = LoggerFactory.getLogger(PerHostPercentileTracker.class); | |
| 71 | + | |
| 72 | + private final ConcurrentMap<Host, Recorder> recorders; | |
| 73 | + private final ConcurrentMap<Host, CachedHistogram> cachedHistograms; | |
| 74 | + private final long highestTrackableLatencyMillis; | |
| 75 | + private final int numberOfSignificantValueDigits; | |
| 76 | + private final int minRecordedValues; | |
| 77 | + private final long intervalMs; | |
| 78 | + | |
| 79 | + private PerHostPercentileTracker(long highestTrackableLatencyMillis, int numberOfSignificantValueDigits, | |
| 80 | + int numberOfHosts, | |
| 81 | + int minRecordedValues, | |
| 82 | + long intervalMs) { | |
| 83 | + this.highestTrackableLatencyMillis = highestTrackableLatencyMillis; | |
| 84 | + this.numberOfSignificantValueDigits = numberOfSignificantValueDigits; | |
| 85 | + this.minRecordedValues = minRecordedValues; | |
| 86 | + this.intervalMs = intervalMs; | |
| 87 | + this.recorders = new MapMaker().initialCapacity(numberOfHosts).makeMap(); | |
| 88 | + this.cachedHistograms = new MapMaker().initialCapacity(numberOfHosts).makeMap(); | |
| 89 | + } | |
| 90 | + | |
| 91 | + /** | |
| 92 | + * Returns a builder to create a new instance. | |
| 93 | + * | |
| 94 | + * @param highestTrackableLatencyMillis the highest expected latency. If a higher value is reported, it will be ignored and a | |
| 95 | + * warning will be logged. A good rule of thumb is to set it slightly higher than | |
| 96 | + * {@link SocketOptions#getReadTimeoutMillis()}. | |
| 97 | + * @return the builder. | |
| 98 | + */ | |
| 99 | + public static Builder builderWithHighestTrackableLatencyMillis(long highestTrackableLatencyMillis) { | |
| 100 | + return new Builder(highestTrackableLatencyMillis); | |
| 101 | + } | |
| 102 | + | |
| 103 | + /** | |
| 104 | + * Helper class to builder {@code PerHostPercentileTracker} instances with a fluent interface. | |
| 105 | + */ | |
| 106 | + public static class Builder { | |
| 107 | + private final long highestTrackableLatencyMillis; | |
| 108 | + private int numberOfSignificantValueDigits = 3; | |
| 109 | + private int minRecordedValues = 1000; | |
| 110 | + private int numberOfHosts = 16; | |
| 111 | + private long intervalMs = MINUTES.toMillis(5); | |
| 112 | + | |
| 113 | + Builder(long highestTrackableLatencyMillis) { | |
| 114 | + this.highestTrackableLatencyMillis = highestTrackableLatencyMillis; | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * Sets the number of significant decimal digits to which histograms will maintain value | |
| 119 | + * resolution and separation. This must be an integer between 0 and 5. | |
| 120 | + * <p> | |
| 121 | + * If not set explicitly, this value defaults to 3. | |
| 122 | + * | |
| 123 | + * @param numberOfSignificantValueDigits the new value. | |
| 124 | + * @return this builder. | |
| 125 | + * | |
| 126 | + * @see <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a> | |
| 127 | + * for a more detailed explanation on how this parameter affects the resolution of recorded samples. | |
| 128 | + */ | |
| 129 | + public Builder withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) { | |
| 130 | + this.numberOfSignificantValueDigits = numberOfSignificantValueDigits; | |
| 131 | + return this; | |
| 132 | + } | |
| 133 | + | |
| 134 | + /** | |
| 135 | + * Sets the minimum number of values that must be recorded for a host before we consider | |
| 136 | + * the sample size significant. | |
| 137 | + * <p> | |
| 138 | + * If this count is not reached during a given interval, {@link #getLatencyAtPercentile(Host, double)} | |
| 139 | + * will return a negative value, indicating that statistics are not available. In particular, this is true | |
| 140 | + * during the first interval. | |
| 141 | + * <p> | |
| 142 | + * If not set explicitly, this value default to 1000. | |
| 143 | + * | |
| 144 | + * @param minRecordedValues the new value. | |
| 145 | + * @return this builder. | |
| 146 | + */ | |
| 147 | + public Builder withMinRecordedValues(int minRecordedValues) { | |
| 148 | + this.minRecordedValues = minRecordedValues; | |
| 149 | + return this; | |
| 150 | + } | |
| 151 | + | |
| 152 | + /** | |
| 153 | + * Sets the number of distinct hosts that the driver will ever connect to. | |
| 154 | + * <p> | |
| 155 | + * This parameter is only used to pre-size internal maps in order to avoid unnecessary rehashing. | |
| 156 | + * <p> | |
| 157 | + * If not set explicitly, this value defaults to 16. | |
| 158 | + * | |
| 159 | + * @param numberOfHosts the new value. | |
| 160 | + * @return this builder. | |
| 161 | + */ | |
| 162 | + public Builder withNumberOfHosts(int numberOfHosts) { | |
| 163 | + this.numberOfHosts = numberOfHosts; | |
| 164 | + return this; | |
| 165 | + } | |
| 166 | + | |
| 167 | + /** | |
| 168 | + * Sets the time interval over which samples are recorded. | |
| 169 | + * <p> | |
| 170 | + * For each host, there is a "live" histogram where current latencies are recorded, and a "cached", read-only histogram | |
| 171 | + * that is used when clients call {@link #getLatencyAtPercentile(Host, double)}. Each time the cached histogram becomes | |
| 172 | + * older than the interval, the two histograms are switched. Note that statistics will not be available during the first | |
| 173 | + * interval at cluster startup, since we don't have a cached histogram yet. | |
| 174 | + * <p> | |
| 175 | + * If not set explicitly, this value defaults to 5 minutes. | |
| 176 | + * | |
| 177 | + * @param interval the new interval. | |
| 178 | + * @param unit the unit that the interval is expressed in. | |
| 179 | + * @return this builder. | |
| 180 | + */ | |
| 181 | + public Builder withInterval(long interval, TimeUnit unit) { | |
| 182 | + this.intervalMs = MILLISECONDS.convert(interval, unit); | |
| 183 | + return this; | |
| 184 | + } | |
| 185 | + | |
| 186 | + /** | |
| 187 | + * Builds the {@code PerHostPercentileTracker} instance configured with this builder. | |
| 188 | + * | |
| 189 | + * @return the instance. | |
| 190 | + */ | |
| 191 | + public PerHostPercentileTracker build() { | |
| 192 | + return new PerHostPercentileTracker(highestTrackableLatencyMillis, numberOfSignificantValueDigits, numberOfHosts, minRecordedValues, intervalMs); | |
| 193 | + } | |
| 194 | + } | |
| 195 | + | |
| 196 | + @Override | |
| 197 | + public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) { | |
| 198 | + if (!shouldConsiderNewLatency(statement, exception)) | |
| 199 | + return; | |
| 200 | + | |
| 201 | + long latencyMs = NANOSECONDS.toMillis(newLatencyNanos); | |
| 202 | + try { | |
| 203 | + getRecorder(host).recordValue(latencyMs); | |
| 204 | + } catch (ArrayIndexOutOfBoundsException e) { | |
| 205 | + logger.warn("Got request with latency of {} ms, which exceeds the configured maximum trackable value {}", | |
| 206 | + latencyMs, highestTrackableLatencyMillis); | |
| 207 | + } | |
| 208 | + } | |
| 209 | + | |
| 210 | + /** | |
| 211 | + * Returns the request latency for a host at a given percentile. | |
| 212 | + * | |
| 213 | + * @param host the host. | |
| 214 | + * @param percentile the percentile (for example, {@code 99.0} for the 99th percentile). | |
| 215 | + * @return the latency (in milliseconds) at the given percentile, or a negative value if it's not available yet. | |
| 216 | + */ | |
| 217 | + public long getLatencyAtPercentile(Host host, double percentile) { | |
| 218 | + checkArgument(percentile >= 0.0 && percentile < 100, | |
| 219 | + "percentile must be between 0.0 and 100 (was %f)"); | |
| 220 | + Histogram histogram = getLastIntervalHistogram(host); | |
| 221 | + if (histogram == null || histogram.getTotalCount() < minRecordedValues) | |
| 222 | + return -1; | |
| 223 | + | |
| 224 | + return histogram.getValueAtPercentile(percentile); | |
| 225 | + } | |
| 226 | + | |
| 227 | + private Recorder getRecorder(Host host) { | |
| 228 | + Recorder recorder = recorders.get(host); | |
| 229 | + if (recorder == null) { | |
| 230 | + recorder = new Recorder(highestTrackableLatencyMillis, numberOfSignificantValueDigits); | |
| 231 | + Recorder old = recorders.putIfAbsent(host, recorder); | |
| 232 | + if (old != null) { | |
| 233 | + // We got beaten at creating the recorder, use the actual instance and discard ours | |
| 234 | + recorder = old; | |
| 235 | + } else { | |
| 236 | + // Also set an empty cache entry to remember the time we started recording: | |
| 237 | + cachedHistograms.putIfAbsent(host, CachedHistogram.empty()); | |
| 238 | + } | |
| 239 | + } | |
| 240 | + return recorder; | |
| 241 | + } | |
| 242 | + | |
| 243 | + /** @return null if no histogram is available yet (no entries recorded, or not for long enough) */ | |
| 244 | + private Histogram getLastIntervalHistogram(Host host) { | |
| 245 | + try { | |
| 246 | + while (true) { | |
| 247 | + CachedHistogram entry = cachedHistograms.get(host); | |
| 248 | + if (entry == null) | |
| 249 | + return null; | |
| 250 | + | |
| 251 | + long age = System.currentTimeMillis() - entry.timestamp; | |
| 252 | + if (age < intervalMs) { // current histogram is recent enough | |
| 253 | + return entry.histogram.get(); | |
| 254 | + } else { // need to refresh | |
| 255 | + Recorder recorder = recorders.get(host); | |
| 256 | + // intervalMs should be much larger than the time it takes to replace a histogram, so this future should never block | |
| 257 | + Histogram staleHistogram = entry.histogram.get(0, MILLISECONDS); | |
| 258 | + SettableFuture<Histogram> future = SettableFuture.create(); | |
| 259 | + CachedHistogram newEntry = new CachedHistogram(future); | |
| 260 | + if (cachedHistograms.replace(host, entry, newEntry)) { | |
| 261 | + // Only get the new histogram if we successfully replaced the cache entry. | |
| 262 | + // This ensures that only one thread will do it. | |
| 263 | + Histogram newHistogram = recorder.getIntervalHistogram(staleHistogram); | |
| 264 | + future.set(newHistogram); | |
| 265 | + return newHistogram; | |
| 266 | + } | |
| 267 | + // If we couldn't replace the entry it means we raced, so loop to try again | |
| 268 | + } | |
| 269 | + } | |
| 270 | + } catch (InterruptedException e) { | |
| 271 | + Thread.currentThread().interrupt(); | |
| 272 | + return null; | |
| 273 | + } catch (ExecutionException e) { | |
| 274 | + throw new DriverInternalError("Unexpected error", e.getCause()); | |
| 275 | + } catch (TimeoutException e) { | |
| 276 | + throw new DriverInternalError("Unexpected timeout while getting histogram", e); | |
| 277 | + } | |
| 278 | + } | |
| 279 | + | |
| 280 | + static class CachedHistogram { | |
| 281 | + final ListenableFuture<Histogram> histogram; | |
| 282 | + final long timestamp; | |
| 283 | + | |
| 284 | + CachedHistogram(ListenableFuture<Histogram> histogram) { | |
| 285 | + this.histogram = histogram; | |
| 286 | + this.timestamp = System.currentTimeMillis(); | |
| 287 | + } | |
| 288 | + | |
| 289 | + static CachedHistogram empty() { | |
| 290 | + return new CachedHistogram(Futures.<Histogram>immediateFuture(null)); | |
| 291 | + } | |
| 292 | + } | |
| 293 | + | |
| 294 | + // TODO this was copy/pasted from LatencyAwarePolicy, maybe it could be refactored as a shared method | |
| 295 | + private boolean shouldConsiderNewLatency(Statement statement, Exception exception) { | |
| 296 | + // query was successful: always consider | |
| 297 | + if (exception == null) | |
| 298 | + return true; | |
| 299 | + // filter out "fast" errors | |
| 300 | + return !EXCLUDED_EXCEPTIONS.contains(exception.getClass()); | |
| 301 | + } | |
| 302 | + | |
| 303 | + /** | |
| 304 | + * A set of DriverException subclasses that we should prevent from updating the host's score. | |
| 305 | + * The intent behind it is to filter out "fast" errors: when a host replies with such errors, | |
| 306 | + * it usually does so very quickly, because it did not involve any actual | |
| 307 | + * coordination work. Such errors are not good indicators of the host's responsiveness, | |
| 308 | + * and tend to make the host's score look better than it actually is. | |
| 309 | + */ | |
| 310 | + private static final Set<Class<? extends Exception>> EXCLUDED_EXCEPTIONS = ImmutableSet.<Class<? extends Exception>>of( | |
| 311 | + UnavailableException.class, // this is done via the snitch and is usually very fast | |
| 312 | + OverloadedException.class, | |
| 313 | + BootstrappingException.class, | |
| 314 | + UnpreparedException.class, | |
| 315 | + QueryValidationException.class // query validation also happens at early stages in the coordinator | |
| 316 | + ); | |
| 317 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +314 −105
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | |
| 21 | 21 | import static java.util.concurrent.TimeUnit.NANOSECONDS; |
| 22 | 22 | |
| 23 | +import com.google.common.annotations.Beta; | |
| 23 | 24 | import com.google.common.annotations.VisibleForTesting; |
| 24 | 25 | import org.slf4j.Logger; |
| 25 | 26 | import org.slf4j.LoggerFactory; |
| @@ -33,7 +34,7 @@ | ||
| 33 | 34 | * <pre> |
| 34 | 35 | * Cluster cluster = ... |
| 35 | 36 | * QueryLogger queryLogger = QueryLogger.builder(cluster) |
| 36 | - * .withSlowQueryLatencyThresholdMillis(...) | |
| 37 | + * .withConstantThreshold(...) | |
| 37 | 38 | * .withMaxQueryStringLength(...) |
| 38 | 39 | * .build(); |
| 39 | 40 | * cluster.register(queryLogger); |
| @@ -54,9 +55,9 @@ | ||
| 54 | 55 | * |
| 55 | 56 | * <ol> |
| 56 | 57 | * <li>{@link #NORMAL_LOGGER}: used to log normal queries, i.e., queries that completed successfully |
| 57 | - * within a {@link #getSlowQueryLatencyThresholdMillis() configurable threshold in milliseconds}.</li> | |
| 58 | + * within a configurable threshold in milliseconds.</li> | |
| 58 | 59 | * <li>{@link #SLOW_LOGGER}: used to log slow queries, i.e., queries that completed successfully |
| 59 | - * but that took longer than a {@link #getSlowQueryLatencyThresholdMillis() configurable threshold in milliseconds} to complete.</li> | |
| 60 | + * but that took longer than a configurable threshold in milliseconds to complete.</li> | |
| 60 | 61 | * <li>{@link #ERROR_LOGGER}: used to log unsuccessful queries, i.e., |
| 61 | 62 | * queries that did not completed normally and threw an exception. |
| 62 | 63 | * Note this this logger will also print the full stack trace of the reported exception.</li> |
| @@ -66,7 +67,7 @@ | ||
| 66 | 67 | * The appropriate logger is chosen according to the following algorithm: |
| 67 | 68 | * <ol> |
| 68 | 69 | * <li>if an exception has been thrown: use {@link #ERROR_LOGGER};</li> |
| 69 | - * <li>otherwise, if the reported latency is greater than {@link #getSlowQueryLatencyThresholdMillis()} the configured threshold in milliseconds}: use {@link #SLOW_LOGGER};</li> | |
| 70 | + * <li>otherwise, if the reported latency is greater than the configured threshold in milliseconds: use {@link #SLOW_LOGGER};</li> | |
| 70 | 71 | * <li>otherwise, use {@link #NORMAL_LOGGER}.</li> |
| 71 | 72 | * </ol> |
| 72 | 73 | * |
| @@ -75,19 +76,50 @@ | ||
| 75 | 76 | * If the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, |
| 76 | 77 | * then the query parameters (if any) will be logged as well (names and actual values). |
| 77 | 78 | * |
| 79 | + * <p> | |
| 80 | + * <strong>Constant thresholds vs. Dynamic thresholds</strong> | |
| 81 | + * <p> | |
| 82 | + * Currently the QueryLogger can track slow queries in two different ways: | |
| 83 | + * using a constant threshold in milliseconds (which is the default behavior), | |
| 84 | + * or using a dynamic threshold based on per-host percentiles computed by | |
| 85 | + * {@link PerHostPercentileTracker}. | |
| 86 | + * <p> | |
| 87 | + * <b>Note that the dynamic threshold version is currently provided as a beta preview: it hasn't been extensively | |
| 88 | + * tested yet, and the API is still subject to change.</b> To use it, you must first obtain and register | |
| 89 | + * an instance of {@link PerHostPercentileTracker}, then create your QueryLogger as follows: | |
| 90 | + * | |
| 91 | + * <pre> | |
| 92 | + * Cluster cluster = ... | |
| 93 | + * // create an instance of PerHostPercentileTracker and register it | |
| 94 | + * PerHostPercentileTracker tracker = ...; | |
| 95 | + * cluster.register(tracker); | |
| 96 | + * // create an instance of QueryLogger and register it | |
| 97 | + * QueryLogger queryLogger = QueryLogger.builder(cluster) | |
| 98 | + * .withDynamicThreshold(tracker, ...) | |
| 99 | + * .withMaxQueryStringLength(...) | |
| 100 | + * .build(); | |
| 101 | + * cluster.register(queryLogger); | |
| 102 | + * </pre> | |
| 103 | + | |
| 78 | 104 | * <p> |
| 79 | 105 | * This class is thread-safe. |
| 80 | 106 | * |
| 81 | 107 | * @since 2.0.10 |
| 82 | 108 | */ |
| 83 | -public class QueryLogger implements LatencyTracker { | |
| 109 | +public abstract class QueryLogger implements LatencyTracker { | |
| 84 | 110 | |
| 85 | 111 | /** |
| 86 | - * The default threshold in milliseconds beyond which queries are considered 'slow' | |
| 112 | + * The default latency threshold in milliseconds beyond which queries are considered 'slow' | |
| 87 | 113 | * and logged as such by the driver. |
| 88 | 114 | */ |
| 89 | 115 | public static final long DEFAULT_SLOW_QUERY_THRESHOLD_MS = 5000; |
| 90 | 116 | |
| 117 | + /** | |
| 118 | + * The default latency percentile beyond which queries are considered 'slow' | |
| 119 | + * and logged as such by the driver. | |
| 120 | + */ | |
| 121 | + public static final double DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE = 99.0; | |
| 122 | + | |
| 91 | 123 | /** |
| 92 | 124 | * The default maximum length of a CQL query string that can be logged verbatim |
| 93 | 125 | * by the driver. Query strings longer than this value will be truncated |
| @@ -113,7 +145,7 @@ | ||
| 113 | 145 | |
| 114 | 146 | /** |
| 115 | 147 | * The logger used to log normal queries, i.e., queries that completed successfully |
| 116 | - * within a configurable threshold in milliseconds (see {@link #getSlowQueryLatencyThresholdMillis()}). | |
| 148 | + * within a configurable threshold in milliseconds. | |
| 117 | 149 | * <p> |
| 118 | 150 | * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}. |
| 119 | 151 | * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, |
| @@ -125,8 +157,7 @@ | ||
| 125 | 157 | |
| 126 | 158 | /** |
| 127 | 159 | * The logger used to log slow queries, i.e., queries that completed successfully |
| 128 | - * but whose execution time exceeded a configurable threshold in milliseconds | |
| 129 | - * (see {@link #getSlowQueryLatencyThresholdMillis()}). | |
| 160 | + * but whose execution time exceeded a configurable threshold in milliseconds. | |
| 130 | 161 | * <p> |
| 131 | 162 | * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}. |
| 132 | 163 | * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, |
| @@ -152,7 +183,9 @@ | ||
| 152 | 183 | |
| 153 | 184 | private static final String NORMAL_TEMPLATE = "[%s] [%s] Query completed normally, took %s ms: %s"; |
| 154 | 185 | |
| 155 | - private static final String SLOW_TEMPLATE = "[%s] [%s] Query too slow, took %s ms: %s"; | |
| 186 | + private static final String SLOW_TEMPLATE_MILLIS = "[%s] [%s] Query too slow, took %s ms: %s"; | |
| 187 | + | |
| 188 | + private static final String SLOW_TEMPLATE_PERCENTILE = "[%s] [%s] Query too slow, took %s ms (%s percentile = %s ms): %s"; | |
| 156 | 189 | |
| 157 | 190 | private static final String ERROR_TEMPLATE = "[%s] [%s] Query error after %s ms: %s"; |
| 158 | 191 | |
| @@ -162,22 +195,22 @@ | ||
| 162 | 195 | @VisibleForTesting |
| 163 | 196 | static final String FURTHER_PARAMS_OMITTED = " [further parameters omitted]"; |
| 164 | 197 | |
| 165 | - private final Cluster cluster; | |
| 198 | + protected final Cluster cluster; | |
| 166 | 199 | |
| 167 | - private volatile long slowQueryLatencyThresholdMillis = DEFAULT_SLOW_QUERY_THRESHOLD_MS; | |
| 200 | + protected volatile int maxQueryStringLength; | |
| 168 | 201 | |
| 169 | - private volatile int maxQueryStringLength = DEFAULT_MAX_QUERY_STRING_LENGTH; | |
| 202 | + protected volatile int maxParameterValueLength; | |
| 170 | 203 | |
| 171 | - private volatile int maxParameterValueLength = DEFAULT_MAX_PARAMETER_VALUE_LENGTH; | |
| 172 | - | |
| 173 | - private volatile int maxLoggedParameters = DEFAULT_MAX_LOGGED_PARAMETERS; | |
| 204 | + protected volatile int maxLoggedParameters; | |
| 174 | 205 | |
| 175 | 206 | /** |
| 176 | 207 | * Private constructor. Instances of QueryLogger should be obtained via the {@link #builder(Cluster)} method. |
| 177 | - * @param cluster The cluster this logger is attached to | |
| 178 | 208 | */ |
| 179 | - private QueryLogger(Cluster cluster) { | |
| 209 | + private QueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters) { | |
| 180 | 210 | this.cluster = cluster; |
| 211 | + this.maxQueryStringLength = maxQueryStringLength; | |
| 212 | + this.maxParameterValueLength = maxParameterValueLength; | |
| 213 | + this.maxLoggedParameters = maxLoggedParameters; | |
| 181 | 214 | } |
| 182 | 215 | |
| 183 | 216 | /** |
| @@ -186,7 +219,6 @@ | ||
| 186 | 219 | * This is a convenience method for {@code new QueryLogger.Builder()}. |
| 187 | 220 | * |
| 188 | 221 | * @param cluster the {@link Cluster} this QueryLogger will be attached to. |
| 189 | - * Note: this parameter is currently not used, but it is included in the public API in anticipation of future use. | |
| 190 | 222 | * @return the new QueryLogger builder. |
| 191 | 223 | * @throws NullPointerException if {@code cluster} is {@code null}. |
| 192 | 224 | */ |
| @@ -196,28 +228,221 @@ | ||
| 196 | 228 | } |
| 197 | 229 | |
| 198 | 230 | /** |
| 199 | - * Helper class to build {@link QueryLogger} instances with a fluent API. | |
| 231 | + * A QueryLogger that uses a constant threshold in milliseconds | |
| 232 | + * to track slow queries. | |
| 233 | + * This implementation is the default and should be preferred to {@link DynamicThresholdQueryLogger} | |
| 234 | + * which is still in beta state. | |
| 200 | 235 | */ |
| 201 | - public static class Builder { | |
| 236 | + public static class ConstantThresholdQueryLogger extends QueryLogger { | |
| 202 | 237 | |
| 203 | - private final QueryLogger instance; | |
| 238 | + private volatile long slowQueryLatencyThresholdMillis; | |
| 204 | 239 | |
| 205 | - public Builder(Cluster cluster) { | |
| 206 | - instance = new QueryLogger(cluster); | |
| 240 | + private ConstantThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, long slowQueryLatencyThresholdMillis) { | |
| 241 | + super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters); | |
| 242 | + this.setSlowQueryLatencyThresholdMillis(slowQueryLatencyThresholdMillis); | |
| 243 | + } | |
| 244 | + | |
| 245 | + /** | |
| 246 | + * Return the threshold in milliseconds beyond which queries are considered 'slow' | |
| 247 | + * and logged as such by the driver. | |
| 248 | + * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}. | |
| 249 | + * | |
| 250 | + * @return The threshold in milliseconds beyond which queries are considered 'slow' | |
| 251 | + * and logged as such by the driver. | |
| 252 | + */ | |
| 253 | + public long getSlowQueryLatencyThresholdMillis() { | |
| 254 | + return slowQueryLatencyThresholdMillis; | |
| 207 | 255 | } |
| 208 | 256 | |
| 209 | 257 | /** |
| 210 | 258 | * Set the threshold in milliseconds beyond which queries are considered 'slow' |
| 211 | 259 | * and logged as such by the driver. |
| 212 | - * The default for this setting is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}. | |
| 213 | 260 | * |
| 214 | 261 | * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds. |
| 215 | 262 | * It must be strictly positive. |
| 216 | - * @return this {@link Builder} instance (for method chaining). | |
| 217 | 263 | * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}. |
| 218 | 264 | */ |
| 219 | - public Builder withSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) { | |
| 220 | - instance.setSlowQueryLatencyThresholdMillis(slowQueryLatencyThresholdMillis); | |
| 265 | + public void setSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) { | |
| 266 | + if (slowQueryLatencyThresholdMillis <= 0) | |
| 267 | + throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdMillis, should be > 0, got " + slowQueryLatencyThresholdMillis); | |
| 268 | + this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis; | |
| 269 | + } | |
| 270 | + | |
| 271 | + @Override | |
| 272 | + protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) { | |
| 273 | + if (latencyMs > slowQueryLatencyThresholdMillis) { | |
| 274 | + maybeLogSlowQuery(host, statement, latencyMs); | |
| 275 | + } else { | |
| 276 | + maybeLogNormalQuery(host, statement, latencyMs); | |
| 277 | + } | |
| 278 | + } | |
| 279 | + | |
| 280 | + protected void maybeLogSlowQuery(Host host, Statement statement, long latencyMs) { | |
| 281 | + if (SLOW_LOGGER.isDebugEnabled()) { | |
| 282 | + String message = String.format(SLOW_TEMPLATE_MILLIS, cluster.getClusterName(), host, latencyMs, statementAsString(statement)); | |
| 283 | + logQuery(statement, null, SLOW_LOGGER, message); | |
| 284 | + } | |
| 285 | + } | |
| 286 | + } | |
| 287 | + | |
| 288 | + /** | |
| 289 | + * A QueryLogger that uses a dynamic threshold in milliseconds | |
| 290 | + * to track slow queries. | |
| 291 | + * <p> | |
| 292 | + * Dynamic thresholds are based on per-host latency percentiles, as computed | |
| 293 | + * by {@link PerHostPercentileTracker}. | |
| 294 | + * <p> | |
| 295 | + * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject | |
| 296 | + * to change.</b> | |
| 297 | + */ | |
| 298 | + @Beta | |
| 299 | + public static class DynamicThresholdQueryLogger extends QueryLogger { | |
| 300 | + | |
| 301 | + private volatile double slowQueryLatencyThresholdPercentile; | |
| 302 | + | |
| 303 | + private volatile PerHostPercentileTracker perHostPercentileLatencyTracker; | |
| 304 | + | |
| 305 | + private DynamicThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, double slowQueryLatencyThresholdPercentile, PerHostPercentileTracker perHostPercentileLatencyTracker) { | |
| 306 | + super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters); | |
| 307 | + this.setSlowQueryLatencyThresholdPercentile(slowQueryLatencyThresholdPercentile); | |
| 308 | + this.setPerHostPercentileLatencyTracker(perHostPercentileLatencyTracker); | |
| 309 | + } | |
| 310 | + | |
| 311 | + /** | |
| 312 | + * Return the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms. | |
| 313 | + * Cannot be {@code null}. | |
| 314 | + * | |
| 315 | + * @return the {@link PerHostPercentileTracker} instance to use. | |
| 316 | + */ | |
| 317 | + public PerHostPercentileTracker getPerHostPercentileLatencyTracker() { | |
| 318 | + return perHostPercentileLatencyTracker; | |
| 319 | + } | |
| 320 | + | |
| 321 | + /** | |
| 322 | + * Set the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms. | |
| 323 | + * Cannot be {@code null}. | |
| 324 | + * | |
| 325 | + * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use. | |
| 326 | + * @throws IllegalArgumentException if {@code perHostPercentileLatencyTracker == null}. | |
| 327 | + */ | |
| 328 | + public void setPerHostPercentileLatencyTracker(PerHostPercentileTracker perHostPercentileLatencyTracker) { | |
| 329 | + if (perHostPercentileLatencyTracker == null) | |
| 330 | + throw new IllegalArgumentException("perHostPercentileLatencyTracker cannot be null"); | |
| 331 | + this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker; | |
| 332 | + } | |
| 333 | + | |
| 334 | + /** | |
| 335 | + * Return the threshold percentile beyond which queries are considered 'slow' | |
| 336 | + * and logged as such by the driver. | |
| 337 | + * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}. | |
| 338 | + * | |
| 339 | + * @return threshold percentile beyond which queries are considered 'slow' | |
| 340 | + * and logged as such by the driver. | |
| 341 | + */ | |
| 342 | + public double getSlowQueryLatencyThresholdPercentile() { | |
| 343 | + return slowQueryLatencyThresholdPercentile; | |
| 344 | + } | |
| 345 | + | |
| 346 | + /** | |
| 347 | + * Set the threshold percentile beyond which queries are considered 'slow' | |
| 348 | + * and logged as such by the driver. | |
| 349 | + * | |
| 350 | + * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile. | |
| 351 | + * It must be comprised between 0 inclusive and 100 exclusive. | |
| 352 | + * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdPercentile < 0 || slowQueryLatencyThresholdPercentile >= 100}. | |
| 353 | + */ | |
| 354 | + public void setSlowQueryLatencyThresholdPercentile(double slowQueryLatencyThresholdPercentile) { | |
| 355 | + if (slowQueryLatencyThresholdPercentile < 0.0 || slowQueryLatencyThresholdPercentile >= 100.0) | |
| 356 | + throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdPercentile, should be >= 0 and < 100, got " + slowQueryLatencyThresholdPercentile); | |
| 357 | + this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile; | |
| 358 | + } | |
| 359 | + | |
| 360 | + @Override | |
| 361 | + protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) { | |
| 362 | + long threshold = perHostPercentileLatencyTracker.getLatencyAtPercentile(host, slowQueryLatencyThresholdPercentile); | |
| 363 | + if (threshold >= 0 && latencyMs > threshold) { | |
| 364 | + maybeLogSlowQuery(host, statement, latencyMs, threshold); | |
| 365 | + } else { | |
| 366 | + maybeLogNormalQuery(host, statement, latencyMs); | |
| 367 | + } | |
| 368 | + } | |
| 369 | + | |
| 370 | + protected void maybeLogSlowQuery(Host host, Statement statement, long latencyMs, long threshold) { | |
| 371 | + if (SLOW_LOGGER.isDebugEnabled()) { | |
| 372 | + String message = String.format(SLOW_TEMPLATE_PERCENTILE, cluster.getClusterName(), host, latencyMs, slowQueryLatencyThresholdPercentile, threshold, statementAsString(statement)); | |
| 373 | + logQuery(statement, null, SLOW_LOGGER, message); | |
| 374 | + } | |
| 375 | + } | |
| 376 | + } | |
| 377 | + | |
| 378 | + /** | |
| 379 | + * Helper class to build {@link QueryLogger} instances with a fluent API. | |
| 380 | + */ | |
| 381 | + public static class Builder { | |
| 382 | + | |
| 383 | + private final Cluster cluster; | |
| 384 | + | |
| 385 | + private int maxQueryStringLength = DEFAULT_MAX_QUERY_STRING_LENGTH; | |
| 386 | + | |
| 387 | + private int maxParameterValueLength = DEFAULT_MAX_PARAMETER_VALUE_LENGTH; | |
| 388 | + | |
| 389 | + private int maxLoggedParameters = DEFAULT_MAX_LOGGED_PARAMETERS; | |
| 390 | + | |
| 391 | + private long slowQueryLatencyThresholdMillis = DEFAULT_SLOW_QUERY_THRESHOLD_MS; | |
| 392 | + | |
| 393 | + private double slowQueryLatencyThresholdPercentile = DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE; | |
| 394 | + | |
| 395 | + private PerHostPercentileTracker perHostPercentileLatencyTracker; | |
| 396 | + | |
| 397 | + private boolean constantThreshold = true; | |
| 398 | + | |
| 399 | + public Builder(Cluster cluster) { | |
| 400 | + this.cluster = cluster; | |
| 401 | + } | |
| 402 | + | |
| 403 | + /** | |
| 404 | + * Enables slow query latency tracking based on constant thresholds. | |
| 405 | + * <p> | |
| 406 | + * Note: You should either use {@link #withConstantThreshold(long) constant thresholds} | |
| 407 | + * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds}, | |
| 408 | + * not both. | |
| 409 | + * | |
| 410 | + * @param slowQueryLatencyThresholdMillis The threshold in milliseconds beyond which queries are considered 'slow' | |
| 411 | + * and logged as such by the driver. | |
| 412 | + * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS} | |
| 413 | + * @return this {@link Builder} instance (for method chaining). | |
| 414 | + */ | |
| 415 | + public Builder withConstantThreshold(long slowQueryLatencyThresholdMillis) { | |
| 416 | + this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis; | |
| 417 | + constantThreshold = true; | |
| 418 | + return this; | |
| 419 | + } | |
| 420 | + | |
| 421 | + /** | |
| 422 | + * Enables slow query latency tracking based on dynamic thresholds. | |
| 423 | + * <p> | |
| 424 | + * Dynamic thresholds are based on per-host latency percentiles, as computed | |
| 425 | + * by {@link PerHostPercentileTracker}. | |
| 426 | + * <p> | |
| 427 | + * Note: You should either use {@link #withConstantThreshold(long) constant thresholds} | |
| 428 | + * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds}, | |
| 429 | + * not both. | |
| 430 | + * <p> | |
| 431 | + * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject | |
| 432 | + * to change.</b> | |
| 433 | + * | |
| 434 | + * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms. | |
| 435 | + * Cannot be {@code null}. | |
| 436 | + * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile. | |
| 437 | + * It must be comprised between 0 inclusive and 100 exclusive. | |
| 438 | + * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE} | |
| 439 | + * @return this {@link Builder} instance (for method chaining). | |
| 440 | + */ | |
| 441 | + @Beta | |
| 442 | + public Builder withDynamicThreshold(PerHostPercentileTracker perHostPercentileLatencyTracker, double slowQueryLatencyThresholdPercentile) { | |
| 443 | + this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker; | |
| 444 | + this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile; | |
| 445 | + constantThreshold = false; | |
| 221 | 446 | return this; |
| 222 | 447 | } |
| 223 | 448 | |
| @@ -225,18 +450,17 @@ | ||
| 225 | 450 | * Set the maximum length of a CQL query string that can be logged verbatim |
| 226 | 451 | * by the driver. Query strings longer than this value will be truncated |
| 227 | 452 | * when logged. |
| 228 | - * The default for this setting is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}. | |
| 229 | 453 | * |
| 230 | 454 | * @param maxQueryStringLength The maximum length of a CQL query string |
| 231 | 455 | * that can be logged verbatim by the driver. |
| 232 | 456 | * It must be strictly positive or {@code -1}, |
| 233 | 457 | * in which case the query is never truncated |
| 234 | 458 | * (use with care). |
| 459 | + * The default value is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}. | |
| 235 | 460 | * @return this {@link Builder} instance (for method chaining). |
| 236 | - * @throws IllegalArgumentException if {@code maxQueryStringLength <= 0 && maxQueryStringLength != -1}. | |
| 237 | 461 | */ |
| 238 | 462 | public Builder withMaxQueryStringLength(int maxQueryStringLength) { |
| 239 | - instance.setMaxQueryStringLength(maxQueryStringLength); | |
| 463 | + this.maxQueryStringLength = maxQueryStringLength; | |
| 240 | 464 | return this; |
| 241 | 465 | } |
| 242 | 466 | |
| @@ -244,18 +468,17 @@ | ||
| 244 | 468 | * Set the maximum length of a query parameter value that can be logged verbatim |
| 245 | 469 | * by the driver. Parameter values longer than this value will be truncated |
| 246 | 470 | * when logged. |
| 247 | - * The default for this setting is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}. | |
| 248 | 471 | * |
| 249 | 472 | * @param maxParameterValueLength The maximum length of a query parameter value |
| 250 | 473 | * that can be logged verbatim by the driver. |
| 251 | 474 | * It must be strictly positive or {@code -1}, |
| 252 | 475 | * in which case the parameter value is never truncated |
| 253 | 476 | * (use with care). |
| 477 | + * The default value is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}. | |
| 254 | 478 | * @return this {@link Builder} instance (for method chaining). |
| 255 | - * @throws IllegalArgumentException if {@code maxParameterValueLength <= 0 && maxParameterValueLength != -1}. | |
| 256 | 479 | */ |
| 257 | 480 | public Builder withMaxParameterValueLength(int maxParameterValueLength) { |
| 258 | - instance.setMaxParameterValueLength(maxParameterValueLength); | |
| 481 | + this.maxParameterValueLength = maxParameterValueLength; | |
| 259 | 482 | return this; |
| 260 | 483 | } |
| 261 | 484 | |
| @@ -263,58 +486,41 @@ | ||
| 263 | 486 | * Set the maximum number of query parameters that can be logged |
| 264 | 487 | * by the driver. Queries with a number of parameters higher than this value |
| 265 | 488 | * will not have all their parameters logged. |
| 266 | - * The default for this setting is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}. | |
| 267 | 489 | * |
| 268 | 490 | * @param maxLoggedParameters The maximum number of query parameters that can be logged |
| 269 | 491 | * by the driver. It must be strictly positive or {@code -1}, |
| 270 | 492 | * in which case all parameters will be logged, regardless of their number |
| 271 | 493 | * (use with care). |
| 494 | + * The default value is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}. | |
| 272 | 495 | * @return this {@link Builder} instance (for method chaining). |
| 273 | - * @throws IllegalArgumentException if {@code maxLoggedParameters <= 0 && maxLoggedParameters != -1}. | |
| 274 | 496 | */ |
| 275 | 497 | public Builder withMaxLoggedParameters(int maxLoggedParameters) { |
| 276 | - instance.setMaxLoggedParameters(maxLoggedParameters); | |
| 498 | + this.maxLoggedParameters = maxLoggedParameters; | |
| 277 | 499 | return this; |
| 278 | 500 | } |
| 279 | 501 | |
| 502 | + /** | |
| 503 | + * Build the {@link QueryLogger} instance. | |
| 504 | + * @return the {@link QueryLogger} instance. | |
| 505 | + * @throws IllegalArgumentException if the builder is unable to build a valid instance due to incorrect settings. | |
| 506 | + */ | |
| 280 | 507 | public QueryLogger build() { |
| 281 | - return instance; | |
| 508 | + if(constantThreshold) { | |
| 509 | + return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis); | |
| 510 | + } else { | |
| 511 | + return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker); | |
| 512 | + } | |
| 282 | 513 | } |
| 283 | - } | |
| 284 | - | |
| 285 | - // Getters and Setters | |
| 286 | 514 | |
| 287 | - /** | |
| 288 | - * Return the threshold in milliseconds beyond which queries are considered 'slow' | |
| 289 | - * and logged as such by the driver. | |
| 290 | - * The default for this setting is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}. | |
| 291 | - * | |
| 292 | - * @return The threshold in milliseconds beyond which queries are considered 'slow' | |
| 293 | - * and logged as such by the driver. | |
| 294 | - */ | |
| 295 | - public long getSlowQueryLatencyThresholdMillis() { | |
| 296 | - return slowQueryLatencyThresholdMillis; | |
| 297 | 515 | } |
| 298 | 516 | |
| 299 | - /** | |
| 300 | - * Set the threshold in milliseconds beyond which queries are considered 'slow' | |
| 301 | - * and logged as such by the driver. | |
| 302 | - * | |
| 303 | - * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds. | |
| 304 | - * It must be strictly positive. | |
| 305 | - * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}. | |
| 306 | - */ | |
| 307 | - public void setSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) { | |
| 308 | - if (slowQueryLatencyThresholdMillis <= 0) | |
| 309 | - throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdMillis, should be > 0, got " + slowQueryLatencyThresholdMillis); | |
| 310 | - this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis; | |
| 311 | - } | |
| 517 | + // Getters and Setters | |
| 312 | 518 | |
| 313 | 519 | /** |
| 314 | 520 | * Return the maximum length of a CQL query string that can be logged verbatim |
| 315 | 521 | * by the driver. Query strings longer than this value will be truncated |
| 316 | 522 | * when logged. |
| 317 | - * The default for this setting is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}. | |
| 523 | + * The default value is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}. | |
| 318 | 524 | * |
| 319 | 525 | * @return The maximum length of a CQL query string that can be logged verbatim |
| 320 | 526 | * by the driver. |
| @@ -345,7 +551,7 @@ | ||
| 345 | 551 | * Return the maximum length of a query parameter value that can be logged verbatim |
| 346 | 552 | * by the driver. Parameter values longer than this value will be truncated |
| 347 | 553 | * when logged. |
| 348 | - * The default for this setting is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}. | |
| 554 | + * The default value is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}. | |
| 349 | 555 | * |
| 350 | 556 | * @return The maximum length of a query parameter value that can be logged verbatim |
| 351 | 557 | * by the driver. |
| @@ -376,7 +582,7 @@ | ||
| 376 | 582 | * Return the maximum number of query parameters that can be logged |
| 377 | 583 | * by the driver. Queries with a number of parameters higher than this value |
| 378 | 584 | * will not have all their parameters logged. |
| 379 | - * The default for this setting is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}. | |
| 585 | + * The default value is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}. | |
| 380 | 586 | * |
| 381 | 587 | * @return The maximum number of query parameters that can be logged |
| 382 | 588 | * by the driver. |
| @@ -407,51 +613,54 @@ | ||
| 407 | 613 | */ |
| 408 | 614 | @Override |
| 409 | 615 | public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) { |
| 410 | - Logger logger; | |
| 411 | - String template; | |
| 412 | 616 | long latencyMs = NANOSECONDS.toMillis(newLatencyNanos); |
| 413 | 617 | if (exception == null) { |
| 414 | - if (latencyMs > slowQueryLatencyThresholdMillis) { | |
| 415 | - logger = SLOW_LOGGER; | |
| 416 | - template = SLOW_TEMPLATE; | |
| 417 | - } else { | |
| 418 | - logger = NORMAL_LOGGER; | |
| 419 | - template = NORMAL_TEMPLATE; | |
| 420 | - } | |
| 618 | + maybeLogNormalOrSlowQuery(host, statement, latencyMs); | |
| 421 | 619 | } else { |
| 422 | - logger = ERROR_LOGGER; | |
| 423 | - template = ERROR_TEMPLATE; | |
| 620 | + maybeLogErrorQuery(host, statement, exception, latencyMs); | |
| 424 | 621 | } |
| 425 | - logQuery(host, statement, exception, latencyMs, logger, template); | |
| 426 | 622 | } |
| 427 | 623 | |
| 428 | - private void logQuery(Host host, Statement statement, Exception exception, long latencyMs, Logger logger, String template) { | |
| 429 | - if (logger.isDebugEnabled()) { | |
| 430 | - String message = String.format(template, cluster.getClusterName(), host, latencyMs, statementAsString(statement)); | |
| 431 | - boolean showParameterValues = logger.isTraceEnabled(); | |
| 432 | - if (showParameterValues) { | |
| 433 | - StringBuilder params = new StringBuilder(); | |
| 434 | - if (statement instanceof BoundStatement) { | |
| 435 | - appendParameters((BoundStatement)statement, params, maxLoggedParameters); | |
| 436 | - } else if (statement instanceof BatchStatement) { | |
| 437 | - BatchStatement batchStatement = (BatchStatement)statement; | |
| 438 | - int remaining = maxLoggedParameters; | |
| 439 | - for (Statement inner : batchStatement.getStatements()) { | |
| 440 | - if (inner instanceof BoundStatement) { | |
| 441 | - remaining = appendParameters((BoundStatement)inner, params, remaining); | |
| 442 | - } | |
| 624 | + protected abstract void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs); | |
| 625 | + | |
| 626 | + protected void maybeLogNormalQuery(Host host, Statement statement, long latencyMs) { | |
| 627 | + if (NORMAL_LOGGER.isDebugEnabled()) { | |
| 628 | + String message = String.format(NORMAL_TEMPLATE, cluster.getClusterName(), host, latencyMs, statementAsString(statement)); | |
| 629 | + logQuery(statement, null, NORMAL_LOGGER, message); | |
| 630 | + } | |
| 631 | + } | |
| 632 | + | |
| 633 | + protected void maybeLogErrorQuery(Host host, Statement statement, Exception exception, long latencyMs) { | |
| 634 | + if (ERROR_LOGGER.isDebugEnabled()) { | |
| 635 | + String message = String.format(ERROR_TEMPLATE, cluster.getClusterName(), host, latencyMs, statementAsString(statement)); | |
| 636 | + logQuery(statement, exception, ERROR_LOGGER, message); | |
| 637 | + } | |
| 638 | + } | |
| 639 | + | |
| 640 | + protected void logQuery(Statement statement, Exception exception, Logger logger, String message) { | |
| 641 | + boolean showParameterValues = logger.isTraceEnabled(); | |
| 642 | + if (showParameterValues) { | |
| 643 | + StringBuilder params = new StringBuilder(); | |
| 644 | + if (statement instanceof BoundStatement) { | |
| 645 | + appendParameters((BoundStatement)statement, params, maxLoggedParameters); | |
| 646 | + } else if (statement instanceof BatchStatement) { | |
| 647 | + BatchStatement batchStatement = (BatchStatement)statement; | |
| 648 | + int remaining = maxLoggedParameters; | |
| 649 | + for (Statement inner : batchStatement.getStatements()) { | |
| 650 | + if (inner instanceof BoundStatement) { | |
| 651 | + remaining = appendParameters((BoundStatement)inner, params, remaining); | |
| 443 | 652 | } |
| 444 | 653 | } |
| 445 | - if (params.length() > 0) | |
| 446 | - params.append("]"); | |
| 447 | - logger.trace(message + params, exception); | |
| 448 | - } else { | |
| 449 | - logger.debug(message, exception); | |
| 450 | 654 | } |
| 655 | + if (params.length() > 0) | |
| 656 | + params.append("]"); | |
| 657 | + logger.trace(message + params, exception); | |
| 658 | + } else { | |
| 659 | + logger.debug(message, exception); | |
| 451 | 660 | } |
| 452 | 661 | } |
| 453 | 662 | |
| 454 | - private String statementAsString(Statement statement) { | |
| 663 | + protected String statementAsString(Statement statement) { | |
| 455 | 664 | StringBuilder sb = new StringBuilder(); |
| 456 | 665 | if (statement instanceof BatchStatement) { |
| 457 | 666 | BatchStatement bs = (BatchStatement)statement; |
| @@ -467,7 +676,7 @@ | ||
| 467 | 676 | return sb.toString(); |
| 468 | 677 | } |
| 469 | 678 | |
| 470 | - private int countBoundValues(BatchStatement bs) { | |
| 679 | + protected int countBoundValues(BatchStatement bs) { | |
| 471 | 680 | int count = 0; |
| 472 | 681 | for (Statement s : bs.getStatements()) { |
| 473 | 682 | if (s instanceof BoundStatement) |
| @@ -476,7 +685,7 @@ | ||
| 476 | 685 | return count; |
| 477 | 686 | } |
| 478 | 687 | |
| 479 | - private int appendParameters(BoundStatement statement, StringBuilder buffer, int remaining) { | |
| 688 | + protected int appendParameters(BoundStatement statement, StringBuilder buffer, int remaining) { | |
| 480 | 689 | if (remaining == 0) |
| 481 | 690 | return 0; |
| 482 | 691 | ColumnDefinitions metadata = statement.preparedStatement().getVariables(); |
| @@ -504,7 +713,7 @@ | ||
| 504 | 713 | return remaining; |
| 505 | 714 | } |
| 506 | 715 | |
| 507 | - private String parameterValueAsString(ColumnDefinitions.Definition definition, ByteBuffer raw) { | |
| 716 | + protected String parameterValueAsString(ColumnDefinitions.Definition definition, ByteBuffer raw) { | |
| 508 | 717 | String valueStr; |
| 509 | 718 | if (raw == null || raw.remaining() == 0) { |
| 510 | 719 | valueStr = "NULL"; |
| @@ -534,7 +743,7 @@ | ||
| 534 | 743 | return valueStr; |
| 535 | 744 | } |
| 536 | 745 | |
| 537 | - private int append(Statement statement, StringBuilder buffer, int remaining) { | |
| 746 | + protected int append(Statement statement, StringBuilder buffer, int remaining) { | |
| 538 | 747 | if (statement instanceof StatementWrapper) |
| 539 | 748 | statement = ((StatementWrapper)statement).getWrappedStatement(); |
| 540 | 749 | |
| @@ -570,7 +779,7 @@ | ||
| 570 | 779 | return remaining; |
| 571 | 780 | } |
| 572 | 781 | |
| 573 | - private int append(CharSequence str, StringBuilder buffer, int remaining) { | |
| 782 | + protected int append(CharSequence str, StringBuilder buffer, int remaining) { | |
| 574 | 783 | if (remaining == -2) { |
| 575 | 784 | // capacity exceeded |
| 576 | 785 | } else if (remaining == -1) { |
added driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java +100 −0
| @@ -0,0 +1,100 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 19 | + | |
| 20 | +import com.google.common.annotations.Beta; | |
| 21 | + | |
| 22 | +import static com.google.common.base.Preconditions.checkArgument; | |
| 23 | + | |
| 24 | +import com.datastax.driver.core.Cluster; | |
| 25 | +import com.datastax.driver.core.Host; | |
| 26 | +import com.datastax.driver.core.Statement; | |
| 27 | +import com.datastax.driver.core.PerHostPercentileTracker; | |
| 28 | + | |
| 29 | +/** | |
| 30 | + * A policy that triggers speculative executions when the request to the current host is above a given percentile. | |
| 31 | + * | |
| 32 | + * This class uses a {@link PerHostPercentileTracker} that must be registered with the cluster instance: | |
| 33 | + * <pre> | |
| 34 | + * PerHostPercentileTracker tracker = PerHostPercentileTracker | |
| 35 | + * .builderWithHighestTrackableLatencyMillis(15000) | |
| 36 | + * .build(); | |
| 37 | + * PercentileSpeculativeExecutionPolicy policy = new PercentileSpeculativeExecutionPolicy(tracker, 99.0, 2); | |
| 38 | + * cluster = Cluster.builder() | |
| 39 | + * .addContactPoint("127.0.0.1") | |
| 40 | + * .withSpeculativeExecutionPolicy(policy) | |
| 41 | + * .build(); | |
| 42 | + * cluster.register(tracker); | |
| 43 | + * </pre> | |
| 44 | + * You <b>must</b> register the tracker with the cluster yourself (as shown on the last line above), this class will not | |
| 45 | + * do it itself. | |
| 46 | + * <p> | |
| 47 | + * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject | |
| 48 | + * to change.</b> | |
| 49 | + */ | |
| 50 | +@Beta | |
| 51 | +public class PercentileSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { | |
| 52 | + private final PerHostPercentileTracker percentileTracker; | |
| 53 | + private final double percentile; | |
| 54 | + private final int maxSpeculativeExecutions; | |
| 55 | + | |
| 56 | + /** | |
| 57 | + * Builds a new instance. | |
| 58 | + * | |
| 59 | + * @param percentileTracker the component that will record latencies. Note that this policy doesn't register it with the {@code Cluster}, | |
| 60 | + * you <b>must</b> do it yourself (see the code example in this class's Javadoc). | |
| 61 | + * @param percentile the percentile that a request's latency must fall into to be considered slow (ex: {@code 99.0}). | |
| 62 | + * @param maxSpeculativeExecutions the maximum number of speculative executions that will be triggered for a given request (this does not | |
| 63 | + * include the initial, normal request). Must be strictly positive. | |
| 64 | + */ | |
| 65 | + public PercentileSpeculativeExecutionPolicy(PerHostPercentileTracker percentileTracker, double percentile, int maxSpeculativeExecutions) { | |
| 66 | + checkArgument(maxSpeculativeExecutions > 0, | |
| 67 | + "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions); | |
| 68 | + checkArgument(percentile >= 0.0 && percentile < 100, | |
| 69 | + "percentile must be between 0.0 and 100 (was %f)"); | |
| 70 | + | |
| 71 | + this.percentileTracker = percentileTracker; | |
| 72 | + this.percentile = percentile; | |
| 73 | + this.maxSpeculativeExecutions = maxSpeculativeExecutions; | |
| 74 | + } | |
| 75 | + | |
| 76 | + @Override | |
| 77 | + public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) { | |
| 78 | + return new SpeculativeExecutionPlan() { | |
| 79 | + private final AtomicInteger remaining = new AtomicInteger(maxSpeculativeExecutions); | |
| 80 | + | |
| 81 | + @Override | |
| 82 | + public long nextExecution(Host lastQueried) { | |
| 83 | + if (remaining.getAndDecrement() > 0) | |
| 84 | + return percentileTracker.getLatencyAtPercentile(lastQueried, percentile); | |
| 85 | + else | |
| 86 | + return -1; | |
| 87 | + } | |
| 88 | + }; | |
| 89 | + } | |
| 90 | + | |
| 91 | + @Override | |
| 92 | + public void init(Cluster cluster) { | |
| 93 | + // nothing | |
| 94 | + } | |
| 95 | + | |
| 96 | + @Override | |
| 97 | + public void close() { | |
| 98 | + // nothing | |
| 99 | + } | |
| 100 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +1 −1
| @@ -89,7 +89,7 @@ | ||
| 89 | 89 | // given |
| 90 | 90 | slow.setLevel(DEBUG); |
| 91 | 91 | queryLogger = builder(cluster) |
| 92 | - .withSlowQueryLatencyThresholdMillis(10) | |
| 92 | + .withConstantThreshold(10) | |
| 93 | 93 | .build(); |
| 94 | 94 | cluster.register(queryLogger); |
| 95 | 95 | String query = "SELECT foo FROM bar"; |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +7 −7
| @@ -135,7 +135,7 @@ | ||
| 135 | 135 | // given |
| 136 | 136 | normal.setLevel(DEBUG); |
| 137 | 137 | queryLogger = QueryLogger.builder(cluster) |
| 138 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 138 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 139 | 139 | .build(); |
| 140 | 140 | cluster.register(queryLogger); |
| 141 | 141 | String query = "SELECT c_text FROM test WHERE pk = 42"; |
| @@ -154,7 +154,7 @@ | ||
| 154 | 154 | // given |
| 155 | 155 | normal.setLevel(DEBUG); |
| 156 | 156 | queryLogger = QueryLogger.builder(cluster) |
| 157 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 157 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 158 | 158 | .build(); |
| 159 | 159 | cluster.register(queryLogger); |
| 160 | 160 | String query = "SELECT * FROM test where pk = ?"; |
| @@ -176,7 +176,7 @@ | ||
| 176 | 176 | // given |
| 177 | 177 | normal.setLevel(DEBUG); |
| 178 | 178 | queryLogger = QueryLogger.builder(cluster) |
| 179 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 179 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 180 | 180 | .withMaxQueryStringLength(Integer.MAX_VALUE) |
| 181 | 181 | .build(); |
| 182 | 182 | cluster.register(queryLogger); |
| @@ -207,7 +207,7 @@ | ||
| 207 | 207 | // given |
| 208 | 208 | normal.setLevel(DEBUG); |
| 209 | 209 | queryLogger = QueryLogger.builder(cluster) |
| 210 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 210 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 211 | 211 | .withMaxQueryStringLength(Integer.MAX_VALUE) |
| 212 | 212 | .build(); |
| 213 | 213 | cluster.register(queryLogger); |
| @@ -242,7 +242,7 @@ | ||
| 242 | 242 | // given |
| 243 | 243 | normal.setLevel(DEBUG); |
| 244 | 244 | queryLogger = QueryLogger.builder(cluster) |
| 245 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 245 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 246 | 246 | .withMaxQueryStringLength(Integer.MAX_VALUE) |
| 247 | 247 | .build(); |
| 248 | 248 | cluster.register(queryLogger); |
| @@ -348,7 +348,7 @@ | ||
| 348 | 348 | // given |
| 349 | 349 | normal.setLevel(DEBUG); |
| 350 | 350 | queryLogger = QueryLogger.builder(cluster) |
| 351 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 351 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 352 | 352 | .withMaxQueryStringLength(Integer.MAX_VALUE) |
| 353 | 353 | .build(); |
| 354 | 354 | cluster.register(queryLogger); |
| @@ -376,7 +376,7 @@ | ||
| 376 | 376 | // given |
| 377 | 377 | normal.setLevel(TRACE); |
| 378 | 378 | queryLogger = QueryLogger.builder(cluster) |
| 379 | - .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE) | |
| 379 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 380 | 380 | .withMaxQueryStringLength(Integer.MAX_VALUE) |
| 381 | 381 | .build(); |
| 382 | 382 | cluster.register(queryLogger); |