Elffuss BraidHub

kikocis/java-driver public

Merge pull request #306 from datastax/java646

Slow Query Logger (JAVA-646)
Changeset7b0b25b50034a63086e76d221d92b0222e1ee28cc55c0df83e8f31650a166450
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-31 23:51 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-31 23:51 +02:00
Parentsc2d931b5bcf4, 38b7c3e564e7

Browse the files at this changeset

18 files changed

modified driver-core/CHANGELOG.rst +3 −0
@@ -28,6 +28,9 @@
2828 - [improvement] Rename threads to indicate that they are for the driver
2929 (JAVA-583)
3030 - [new feature] Expose paging state (JAVA-550)
31+- [improvement] Slow Query Logger (JAVA-646)
32+- [improvement] Exclude some errors from measurements in LatencyAwarePolicy
33+ (JAVA-698)
3134
3235 Merged from 2.0.9_fixes branch:
3336
modified driver-core/Upgrade_guide_to_2.0.rst +6 −0
@@ -155,6 +155,12 @@
155155 will now need to use Host#isUp and Cluster#register if you were using that
156156 class.
157157
158+11. LatencyTracker#update method now has a different signature and takes two new
159+ parameters: the statement that has been executed (never null), and the exception
160+ thrown while executing the query (or null, if the query executed successfully).
161+ Existing implementations of this interface, once upgraded to the new method
162+ signature, should continue to work as before.
163+
158164
159165
160166
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +2 −2
@@ -1290,9 +1290,9 @@
12901290 return sessions.remove(session);
12911291 }
12921292
1293- void reportLatency(Host host, long latencyNanos) {
1293+ void reportLatency(Host host, Statement statement, Exception exception, long latencyNanos) {
12941294 for (LatencyTracker tracker : trackers) {
1295- tracker.update(host, latencyNanos);
1295+ tracker.update(host, statement, exception, latencyNanos);
12961296 }
12971297 }
12981298
modified driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java +16 −10
@@ -16,12 +16,12 @@
1616 package com.datastax.driver.core;
1717
1818 /**
19- * Interface for object that are interested in tracking the latencies
19+ * Interface for objects that are interested in tracking the latencies
2020 * of the driver queries to each Cassandra nodes.
2121 * <p>
2222 * An implementation of this interface can be registered against a Cluster
2323 * object trough the {@link Cluster#register} method, after which the
24- * {@code update} will be called after each query of the driver to a Cassandra
24+ * {@link #update(Host, Statement, Exception, long)} method will be called after each query of the driver to a Cassandra
2525 * host with the latency/duration (in nanoseconds) of this operation.
2626 */
2727 public interface LatencyTracker {
@@ -31,15 +31,21 @@
3131 * the duration of that operation.
3232 * <p>
3333 * Note that there is no guarantee that this method won't be called
34- * concurrently by multiple thread, so implementations should synchronize
34+ * concurrently by multiple threads, so implementations should synchronize
3535 * internally if need be.
3636 *
37- * @param host the Cassandra host on which a request has been performed.
38- * @param newLatencyNanos the latency in nanoseconds of the operation. This
39- * latency corresponds to the time elapsed between when the query was send
40- * to {@code host} and when the response was received by the driver (or the
41- * operation timed out, in which {@code newLatencyNanos} will approximately
42- * be the timeout value).
37+ * @param host The Cassandra host on which a request has been performed.
38+ * This parameter is never {@code null}.
39+ * @param statement The {@link com.datastax.driver.core.Statement} that has been executed.
40+ * This parameter is never {@code null}.
41+ * @param exception An {@link Exception} thrown when receiving the response, or {@code null}
42+ * if the response was successful.
43+ * @param newLatencyNanos the latency in nanoseconds of the operation.
44+ * This latency corresponds to the time elapsed between
45+ * when the query was sent to {@code host} and
46+ * when the response was received by the driver
47+ * (or the operation timed out, in which {@code newLatencyNanos}
48+ * will approximately be the timeout value).
4349 */
44- public void update(Host host, long newLatencyNanos);
50+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos);
4551 }
added driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +568 −0
@@ -0,0 +1,568 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.nio.ByteBuffer;
19+import java.util.List;
20+
21+import static java.util.concurrent.TimeUnit.NANOSECONDS;
22+
23+import com.google.common.annotations.VisibleForTesting;
24+import org.slf4j.Logger;
25+import org.slf4j.LoggerFactory;
26+
27+/**
28+ * A configurable {@link LatencyTracker} that logs all executed statements.
29+ * <p>
30+ * Typically, client applications would instantiate one single query logger (using its {@link Builder}),
31+ * configure it and register it on the relevant {@link Cluster} instance, e.g.:
32+ *
33+ * <pre>
34+ * Cluster cluster = ...
35+ * QueryLogger queryLogger = QueryLogger.builder(cluster)
36+ * .withSlowQueryLatencyThresholdMillis(...)
37+ * .withMaxQueryStringLength(...)
38+ * .build();
39+ * cluster.register(queryLogger);
40+ * </pre>
41+ *
42+ * Refer to the {@link Builder} documentation for more information on
43+ * configuration settings for the query logger.
44+ * <p>
45+ * Once registered, the query logger will log every {@link RegularStatement}, {@link BoundStatement} or {@link BatchStatement}
46+ * executed by the driver;
47+ * note that it will never log other types of statement, null statements nor any special statement used internally by the driver.
48+ * <p>
49+ * There is one log for each request to a Cassandra node; because the driver sometimes retries the same statement on multiple nodes,
50+ * a single statement execution (for example, a single call to {@link Session#execute(Statement)}) can produce multiple logs on
51+ * different nodes.
52+ * <p>
53+ * For more flexibility, the query logger uses 3 different {@link Logger} instances:
54+ *
55+ * <ol>
56+ * <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+ * <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+ * <li>{@link #ERROR_LOGGER}: used to log unsuccessful queries, i.e.,
61+ * queries that did not completed normally and threw an exception.
62+ * Note this this logger will also print the full stack trace of the reported exception.</li>
63+ * </ol>
64+ *
65+ * <p>
66+ * The appropriate logger is chosen according to the following algorithm:
67+ * <ol>
68+ * <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, use {@link #NORMAL_LOGGER}.</li>
71+ * </ol>
72+ *
73+ * <p>
74+ * All loggers are activated by setting their levels to {@code DEBUG} or {@code TRACE} (including {@link #ERROR_LOGGER}).
75+ * If the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
76+ * then the query parameters (if any) will be logged as well (names and actual values).
77+ *
78+ * <p>
79+ * This class is thread-safe.
80+ *
81+ * @since 2.0.10
82+ */
83+public class QueryLogger implements LatencyTracker {
84+
85+ /**
86+ * The default threshold in milliseconds beyond which queries are considered 'slow'
87+ * and logged as such by the driver.
88+ */
89+ public static final long DEFAULT_SLOW_QUERY_THRESHOLD_MS = 5000;
90+
91+ /**
92+ * The default maximum length of a CQL query string that can be logged verbatim
93+ * by the driver. Query strings longer than this value will be truncated
94+ * when logged.
95+ */
96+ public static final int DEFAULT_MAX_QUERY_STRING_LENGTH = 500;
97+
98+ /**
99+ * The default maximum length of a query parameter value that can be logged verbatim
100+ * by the driver. Parameter values longer than this value will be truncated
101+ * when logged.
102+ */
103+ public static final int DEFAULT_MAX_PARAMETER_VALUE_LENGTH = 50;
104+
105+ /**
106+ * The default maximum number of query parameters that can be logged
107+ * by the driver. Queries with a number of parameters higher than this value
108+ * will not have all their parameters logged.
109+ */
110+ public static final int DEFAULT_MAX_LOGGED_PARAMETERS = 50;
111+
112+ // Loggers
113+
114+ /**
115+ * The logger used to log normal queries, i.e., queries that completed successfully
116+ * within a configurable threshold in milliseconds (see {@link #getSlowQueryLatencyThresholdMillis()}).
117+ * <p>
118+ * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
119+ * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
120+ * then the query parameters (if any) will be logged as well (names and actual values).
121+ * <p>
122+ * The name of this logger is {@code com.datastax.driver.core.QueryLogger.NORMAL}.
123+ */
124+ public static final Logger NORMAL_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.NORMAL");
125+
126+ /**
127+ * 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()}).
130+ * <p>
131+ * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
132+ * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
133+ * then the query parameters (if any) will be logged as well (names and actual values).
134+ * <p>
135+ * The name of this logger is {@code com.datastax.driver.core.QueryLogger.SLOW}.
136+ */
137+ public static final Logger SLOW_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.SLOW");
138+
139+ /**
140+ * The logger used to log unsuccessful queries, i.e., queries that did not completed normally and threw an exception.
141+ * <p>
142+ * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
143+ * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
144+ * then the query parameters (if any) will be logged as well (names and actual values).
145+ * Note this this logger will also print the full stack trace of the reported exception.
146+ * <p>
147+ * The name of this logger is {@code com.datastax.driver.core.QueryLogger.ERROR}.
148+ */
149+ public static final Logger ERROR_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.ERROR");
150+
151+ // Message templates
152+
153+ private static final String NORMAL_TEMPLATE = "[%s] [%s] Query completed normally, took %s ms: %s";
154+
155+ private static final String SLOW_TEMPLATE = "[%s] [%s] Query too slow, took %s ms: %s";
156+
157+ private static final String ERROR_TEMPLATE = "[%s] [%s] Query error after %s ms: %s";
158+
159+ @VisibleForTesting
160+ static final String TRUNCATED_OUTPUT = "... [truncated output]";
161+
162+ @VisibleForTesting
163+ static final String FURTHER_PARAMS_OMITTED = " [further parameters omitted]";
164+
165+ @VisibleForTesting
166+ static final String UNKNOWN_STATEMENT = "??Unknown Statement??";
167+
168+ private final Cluster cluster;
169+
170+ private volatile long slowQueryLatencyThresholdMillis = DEFAULT_SLOW_QUERY_THRESHOLD_MS;
171+
172+ private volatile int maxQueryStringLength = DEFAULT_MAX_QUERY_STRING_LENGTH;
173+
174+ private volatile int maxParameterValueLength = DEFAULT_MAX_PARAMETER_VALUE_LENGTH;
175+
176+ private volatile int maxLoggedParameters = DEFAULT_MAX_LOGGED_PARAMETERS;
177+
178+ /**
179+ * Private constructor. Instances of QueryLogger should be obtained via the {@link #builder(Cluster)} method.
180+ * @param cluster The cluster this logger is attached to
181+ */
182+ private QueryLogger(Cluster cluster) {
183+ this.cluster = cluster;
184+ }
185+
186+ /**
187+ * Creates a new {@link QueryLogger.Builder} instance.
188+ * <p>
189+ * This is a convenience method for {@code new QueryLogger.Builder()}.
190+ *
191+ * @param cluster the {@link Cluster} this QueryLogger will be attached to.
192+ * Note: this parameter is currently not used, but it is included in the public API in anticipation of future use.
193+ * @return the new QueryLogger builder.
194+ * @throws NullPointerException if {@code cluster} is {@code null}.
195+ */
196+ public static QueryLogger.Builder builder(Cluster cluster) {
197+ if(cluster == null) throw new NullPointerException("QueryLogger.Builder: cluster parameter cannot be null");
198+ return new QueryLogger.Builder(cluster);
199+ }
200+
201+ /**
202+ * Helper class to build {@link QueryLogger} instances with a fluent API.
203+ */
204+ public static class Builder {
205+
206+ private final QueryLogger instance;
207+
208+ public Builder(Cluster cluster) {
209+ instance = new QueryLogger(cluster);
210+ }
211+
212+ /**
213+ * Set the threshold in milliseconds beyond which queries are considered 'slow'
214+ * and logged as such by the driver.
215+ * The default for this setting is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}.
216+ *
217+ * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds.
218+ * It must be strictly positive.
219+ * @return this {@link Builder} instance (for method chaining).
220+ * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}.
221+ */
222+ public Builder withSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) {
223+ instance.setSlowQueryLatencyThresholdMillis(slowQueryLatencyThresholdMillis);
224+ return this;
225+ }
226+
227+ /**
228+ * Set the maximum length of a CQL query string that can be logged verbatim
229+ * by the driver. Query strings longer than this value will be truncated
230+ * when logged.
231+ * The default for this setting is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
232+ *
233+ * @param maxQueryStringLength The maximum length of a CQL query string
234+ * that can be logged verbatim by the driver.
235+ * It must be strictly positive or {@code -1},
236+ * in which case the query is never truncated
237+ * (use with care).
238+ * @return this {@link Builder} instance (for method chaining).
239+ * @throws IllegalArgumentException if {@code maxQueryStringLength <= 0 && maxQueryStringLength != -1}.
240+ */
241+ public Builder withMaxQueryStringLength(int maxQueryStringLength) {
242+ instance.setMaxQueryStringLength(maxQueryStringLength);
243+ return this;
244+ }
245+
246+ /**
247+ * Set the maximum length of a query parameter value that can be logged verbatim
248+ * by the driver. Parameter values longer than this value will be truncated
249+ * when logged.
250+ * The default for this setting is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
251+ *
252+ * @param maxParameterValueLength The maximum length of a query parameter value
253+ * that can be logged verbatim by the driver.
254+ * It must be strictly positive or {@code -1},
255+ * in which case the parameter value is never truncated
256+ * (use with care).
257+ * @return this {@link Builder} instance (for method chaining).
258+ * @throws IllegalArgumentException if {@code maxParameterValueLength <= 0 && maxParameterValueLength != -1}.
259+ */
260+ public Builder withMaxParameterValueLength(int maxParameterValueLength) {
261+ instance.setMaxParameterValueLength(maxParameterValueLength);
262+ return this;
263+ }
264+
265+ /**
266+ * Set the maximum number of query parameters that can be logged
267+ * by the driver. Queries with a number of parameters higher than this value
268+ * will not have all their parameters logged.
269+ * The default for this setting is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
270+ *
271+ * @param maxLoggedParameters The maximum number of query parameters that can be logged
272+ * by the driver. It must be strictly positive or {@code -1},
273+ * in which case all parameters will be logged, regardless of their number
274+ * (use with care).
275+ * @return this {@link Builder} instance (for method chaining).
276+ * @throws IllegalArgumentException if {@code maxLoggedParameters <= 0 && maxLoggedParameters != -1}.
277+ */
278+ public Builder withMaxLoggedParameters(int maxLoggedParameters) {
279+ instance.setMaxLoggedParameters(maxLoggedParameters);
280+ return this;
281+ }
282+
283+ public QueryLogger build() {
284+ return instance;
285+ }
286+ }
287+
288+ // Getters and Setters
289+
290+ /**
291+ * Return the threshold in milliseconds beyond which queries are considered 'slow'
292+ * and logged as such by the driver.
293+ * The default for this setting is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}.
294+ *
295+ * @return The threshold in milliseconds beyond which queries are considered 'slow'
296+ * and logged as such by the driver.
297+ */
298+ public long getSlowQueryLatencyThresholdMillis() {
299+ return slowQueryLatencyThresholdMillis;
300+ }
301+
302+ /**
303+ * Set the threshold in milliseconds beyond which queries are considered 'slow'
304+ * and logged as such by the driver.
305+ *
306+ * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds.
307+ * It must be strictly positive.
308+ * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}.
309+ */
310+ public void setSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) {
311+ if (slowQueryLatencyThresholdMillis <= 0)
312+ throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdMillis, should be > 0, got " + slowQueryLatencyThresholdMillis);
313+ this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis;
314+ }
315+
316+ /**
317+ * Return the maximum length of a CQL query string that can be logged verbatim
318+ * by the driver. Query strings longer than this value will be truncated
319+ * when logged.
320+ * The default for this setting is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
321+ *
322+ * @return The maximum length of a CQL query string that can be logged verbatim
323+ * by the driver.
324+ */
325+ public int getMaxQueryStringLength() {
326+ return maxQueryStringLength;
327+ }
328+
329+ /**
330+ * Set the maximum length of a CQL query string that can be logged verbatim
331+ * by the driver. Query strings longer than this value will be truncated
332+ * when logged.
333+ *
334+ * @param maxQueryStringLength The maximum length of a CQL query string
335+ * that can be logged verbatim by the driver.
336+ * It must be strictly positive or {@code -1},
337+ * in which case the query is never truncated
338+ * (use with care).
339+ * @throws IllegalArgumentException if {@code maxQueryStringLength <= 0 && maxQueryStringLength != -1}.
340+ */
341+ public void setMaxQueryStringLength(int maxQueryStringLength) {
342+ if (maxQueryStringLength <= 0 && maxQueryStringLength != -1)
343+ throw new IllegalArgumentException("Invalid maxQueryStringLength, should be > 0 or -1, got " + maxQueryStringLength);
344+ this.maxQueryStringLength = maxQueryStringLength;
345+ }
346+
347+ /**
348+ * Return the maximum length of a query parameter value that can be logged verbatim
349+ * by the driver. Parameter values longer than this value will be truncated
350+ * when logged.
351+ * The default for this setting is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
352+ *
353+ * @return The maximum length of a query parameter value that can be logged verbatim
354+ * by the driver.
355+ */
356+ public int getMaxParameterValueLength() {
357+ return maxParameterValueLength;
358+ }
359+
360+ /**
361+ * Set the maximum length of a query parameter value that can be logged verbatim
362+ * by the driver. Parameter values longer than this value will be truncated
363+ * when logged.
364+ *
365+ * @param maxParameterValueLength The maximum length of a query parameter value
366+ * that can be logged verbatim by the driver.
367+ * It must be strictly positive or {@code -1},
368+ * in which case the parameter value is never truncated
369+ * (use with care).
370+ * @throws IllegalArgumentException if {@code maxParameterValueLength <= 0 && maxParameterValueLength != -1}.
371+ */
372+ public void setMaxParameterValueLength(int maxParameterValueLength) {
373+ if (maxParameterValueLength <= 0 && maxParameterValueLength != -1)
374+ throw new IllegalArgumentException("Invalid maxParameterValueLength, should be > 0 or -1, got " + maxParameterValueLength);
375+ this.maxParameterValueLength = maxParameterValueLength;
376+ }
377+
378+ /**
379+ * Return the maximum number of query parameters that can be logged
380+ * by the driver. Queries with a number of parameters higher than this value
381+ * will not have all their parameters logged.
382+ * The default for this setting is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
383+ *
384+ * @return The maximum number of query parameters that can be logged
385+ * by the driver.
386+ */
387+ public int getMaxLoggedParameters() {
388+ return maxLoggedParameters;
389+ }
390+
391+ /**
392+ * Set the maximum number of query parameters that can be logged
393+ * by the driver. Queries with a number of parameters higher than this value
394+ * will not have all their parameters logged.
395+ *
396+ * @param maxLoggedParameters the maximum number of query parameters that can be logged
397+ * by the driver. It must be strictly positive or {@code -1},
398+ * in which case all parameters will be logged, regardless of their number
399+ * (use with care).
400+ * @throws IllegalArgumentException if {@code maxLoggedParameters <= 0 && maxLoggedParameters != -1}.
401+ */
402+ public void setMaxLoggedParameters(int maxLoggedParameters) {
403+ if (maxLoggedParameters <= 0 && maxLoggedParameters != -1)
404+ throw new IllegalArgumentException("Invalid maxLoggedParameters, should be > 0 or -1, got " + maxLoggedParameters);
405+ this.maxLoggedParameters = maxLoggedParameters;
406+ }
407+
408+ /**
409+ * {@inheritDoc}
410+ */
411+ @Override
412+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
413+ Logger logger;
414+ String template;
415+ long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
416+ if (exception == null) {
417+ if (latencyMs > slowQueryLatencyThresholdMillis) {
418+ logger = SLOW_LOGGER;
419+ template = SLOW_TEMPLATE;
420+ } else {
421+ logger = NORMAL_LOGGER;
422+ template = NORMAL_TEMPLATE;
423+ }
424+ } else {
425+ logger = ERROR_LOGGER;
426+ template = ERROR_TEMPLATE;
427+ }
428+ logQuery(host, statement, exception, latencyMs, logger, template);
429+ }
430+
431+ private void logQuery(Host host, Statement statement, Exception exception, long latencyMs, Logger logger, String template) {
432+ if (logger.isDebugEnabled()) {
433+ String message = String.format(template, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
434+ boolean showParameterValues = logger.isTraceEnabled();
435+ if (showParameterValues) {
436+ StringBuilder params = new StringBuilder();
437+ if (statement instanceof BoundStatement) {
438+ appendParameters((BoundStatement)statement, params, maxLoggedParameters);
439+ } else if (statement instanceof BatchStatement) {
440+ BatchStatement batchStatement = (BatchStatement)statement;
441+ int remaining = maxLoggedParameters;
442+ for (Statement inner : batchStatement.getStatements()) {
443+ if (inner instanceof BoundStatement) {
444+ remaining = appendParameters((BoundStatement)inner, params, remaining);
445+ }
446+ }
447+ }
448+ if (params.length() > 0)
449+ params.append("]");
450+ logger.trace(message + params, exception);
451+ } else {
452+ logger.debug(message, exception);
453+ }
454+ }
455+ }
456+
457+ private String statementAsString(Statement statement) {
458+ StringBuilder sb = new StringBuilder();
459+ append(statement, sb, maxQueryStringLength);
460+ return sb.toString();
461+ }
462+
463+ private int appendParameters(BoundStatement statement, StringBuilder buffer, int remaining) {
464+ if (remaining == 0)
465+ return 0;
466+ ColumnDefinitions metadata = statement.preparedStatement().getVariables();
467+ int numberOfParameters = metadata.size();
468+ if (numberOfParameters > 0) {
469+ List<ColumnDefinitions.Definition> definitions = metadata.asList();
470+ int numberOfLoggedParameters;
471+ if (remaining == -1) {
472+ numberOfLoggedParameters = numberOfParameters;
473+ } else {
474+ numberOfLoggedParameters = remaining > numberOfParameters ? numberOfParameters : remaining;
475+ remaining -= numberOfLoggedParameters;
476+ }
477+ for (int i = 0; i < numberOfLoggedParameters; i++) {
478+ if (buffer.length() == 0)
479+ buffer.append(" [");
480+ else
481+ buffer.append(", ");
482+ buffer.append(String.format("%s:%s", metadata.getName(i), parameterValueAsString(definitions.get(i), statement.values[i])));
483+ }
484+ if (numberOfLoggedParameters < numberOfParameters) {
485+ buffer.append(FURTHER_PARAMS_OMITTED);
486+ }
487+ }
488+ return remaining;
489+ }
490+
491+ private String parameterValueAsString(ColumnDefinitions.Definition definition, ByteBuffer raw) {
492+ String valueStr;
493+ if (raw == null || raw.remaining() == 0) {
494+ valueStr = "NULL";
495+ } else {
496+ DataType type = definition.getType();
497+ int maxParameterValueLength = this.maxParameterValueLength;
498+ if (type.equals(DataType.blob()) && maxParameterValueLength != -1) {
499+ // prevent large blobs from being converted to strings
500+ int maxBufferLength = Math.max(2, (maxParameterValueLength - 2) / 2);
501+ boolean bufferTooLarge = raw.remaining() > maxBufferLength;
502+ if (bufferTooLarge) {
503+ raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength);
504+ }
505+ Object value = type.deserialize(raw);
506+ valueStr = type.format(value);
507+ if (bufferTooLarge) {
508+ valueStr = valueStr + TRUNCATED_OUTPUT;
509+ }
510+ } else {
511+ Object value = type.deserialize(raw);
512+ valueStr = type.format(value);
513+ if (maxParameterValueLength != -1 && valueStr.length() > maxParameterValueLength) {
514+ valueStr = valueStr.substring(0, maxParameterValueLength) + TRUNCATED_OUTPUT;
515+ }
516+ }
517+ }
518+ return valueStr;
519+ }
520+
521+ private int append(Statement statement, StringBuilder buffer, int remaining) {
522+ if (statement instanceof RegularStatement) {
523+ remaining = append(((RegularStatement)statement).getQueryString().trim(), buffer, remaining);
524+ } else if (statement instanceof BoundStatement) {
525+ remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining);
526+ } else if (statement instanceof BatchStatement) {
527+ BatchStatement batchStatement = (BatchStatement)statement;
528+ remaining = append("BEGIN", buffer, remaining);
529+ switch (batchStatement.batchType) {
530+ case UNLOGGED:
531+ append(" UNLOGGED", buffer, remaining);
532+ break;
533+ case COUNTER:
534+ append(" COUNTER", buffer, remaining);
535+ break;
536+ }
537+ remaining = append(" BATCH", buffer, remaining);
538+ for (Statement stmt : batchStatement.getStatements()) {
539+ remaining = append(" ", buffer, remaining);
540+ remaining = append(stmt, buffer, remaining);
541+ }
542+ remaining = append(" APPLY BATCH", buffer, remaining);
543+ } else {
544+ // Unknown types of statement - should not happen
545+ remaining = append(UNKNOWN_STATEMENT, buffer, remaining);
546+ }
547+ if (buffer.charAt(buffer.length() - 1) != ';') {
548+ remaining = append(";", buffer, remaining);
549+ }
550+ return remaining;
551+ }
552+
553+ private int append(CharSequence str, StringBuilder buffer, int remaining) {
554+ if (remaining == -1) {
555+ buffer.append(str);
556+ } else if (remaining > 0) {
557+ if (str.length() > remaining) {
558+ buffer.append(str, 0, remaining).append(TRUNCATED_OUTPUT);
559+ remaining = 0;
560+ } else {
561+ buffer.append(str);
562+ remaining -= str.length();
563+ }
564+ }
565+ return remaining;
566+ }
567+
568+}
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +4 −4
@@ -23,12 +23,12 @@
2323 public class QueryOptions {
2424
2525 /**
26- * The default consistency level for queries: {@code ConsistencyLevel.ONE}.
26+ * The default consistency level for queries: {@link ConsistencyLevel#ONE}.
2727 */
2828 public static final ConsistencyLevel DEFAULT_CONSISTENCY_LEVEL = ConsistencyLevel.ONE;
2929
3030 /**
31- * The default serial consistency level for conditional updates: {@code ConsistencyLevel.SERIAL}.
31+ * The default serial consistency level for conditional updates: {@link ConsistencyLevel#SERIAL}.
3232 */
3333 public static final ConsistencyLevel DEFAULT_SERIAL_CONSISTENCY_LEVEL = ConsistencyLevel.SERIAL;
3434
@@ -43,8 +43,8 @@
4343 private volatile Cluster.Manager manager;
4444
4545 /**
46- * Creates a new {@code QueryOptions} instance using the {@code DEFAULT_CONSISTENCY_LEVEL},
47- * {@code DEFAULT_SERIAL_CONSISTENCY_LEVEL} and {@code DEFAULT_FETCH_SIZE}.
46+ * Creates a new {@link QueryOptions} instance using the {@link #DEFAULT_CONSISTENCY_LEVEL},
47+ * {@link #DEFAULT_SERIAL_CONSISTENCY_LEVEL} and {@link #DEFAULT_FETCH_SIZE}.
4848 */
4949 public QueryOptions() {}
5050
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +18 −18
@@ -31,12 +31,7 @@
3131 import org.slf4j.Logger;
3232 import org.slf4j.LoggerFactory;
3333
34-import com.datastax.driver.core.exceptions.DriverException;
35-import com.datastax.driver.core.exceptions.DriverInternalError;
36-import com.datastax.driver.core.exceptions.NoHostAvailableException;
37-import com.datastax.driver.core.exceptions.ReadTimeoutException;
38-import com.datastax.driver.core.exceptions.UnavailableException;
39-import com.datastax.driver.core.exceptions.WriteTimeoutException;
34+import com.datastax.driver.core.exceptions.*;
4035 import com.datastax.driver.core.policies.*;
4136 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
4237
@@ -306,7 +301,9 @@
306301 }
307302
308303 Host queriedHost = current;
304+
309305 boolean releaseConnection = true;
306+ Exception exceptionToReport = null;
310307 try {
311308 switch (response.type) {
312309 case RESULT:
@@ -314,6 +311,7 @@
314311 break;
315312 case ERROR:
316313 Responses.Error err = (Responses.Error)response;
314+ exceptionToReport = err.asException(connection.address);
317315 RetryPolicy.RetryDecision retry = null;
318316 RetryPolicy retryPolicy = statement.getRetryPolicy() == null
319317 ? manager.configuration().getPolicies().getRetryPolicy()
@@ -381,7 +379,8 @@
381379 case OVERLOADED:
382380 // Try another node
383381 logger.warn("Host {} is overloaded, trying next host.", connection.address);
384- logError(connection.address, new DriverException("Host overloaded"));
382+ DriverException overloaded = new DriverException("Host overloaded");
383+ logError(connection.address, overloaded);
385384 if (metricsEnabled())
386385 metrics().getErrorMetrics().getOthers().inc();
387386 retry(false, null);
@@ -399,7 +398,8 @@
399398 case IS_BOOTSTRAPPING:
400399 // Try another node
401400 logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address);
402- logError(connection.address, new DriverException("Host is bootstrapping"));
401+ DriverException bootstrapping = new DriverException("Host is bootstrapping");
402+ logError(connection.address, bootstrapping);
403403 if (metricsEnabled())
404404 metrics().getErrorMetrics().getOthers().inc();
405405 retry(false, null);
@@ -469,13 +469,13 @@
469469 break;
470470 }
471471 } catch (Exception e) {
472+ exceptionToReport = e;
472473 setFinalException(connection, e);
473474 } finally {
474475 if (releaseConnection && connection instanceof PooledConnection)
475476 ((PooledConnection)connection).release();
476-
477- if (queriedHost != null)
478- manager.cluster.manager.reportLatency(queriedHost, latency);
477+ if (queriedHost != null && statement != Statement.DEFAULT)
478+ manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency);
479479 }
480480 }
481481
@@ -578,8 +578,8 @@
578578 // This shouldn't happen, but if it does, we want to signal the callback, not let him hang indefinitively
579579 setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e));
580580 } finally {
581- if (queriedHost != null)
582- manager.cluster.manager.reportLatency(queriedHost, latency);
581+ if (queriedHost != null && statement != Statement.DEFAULT)
582+ manager.cluster.manager.reportLatency(queriedHost, statement, exception, latency);
583583 }
584584 }
585585
@@ -594,10 +594,10 @@
594594 }
595595
596596 Host queriedHost = current;
597+ // If a query times out, we consider that the host is unstable, so we defunct
598+ // the connection to mark it down.
599+ OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address);
597600 try {
598- // If a query times out, we consider that the host is unstable, so we defunct
599- // the connection to mark it down.
600- DriverException timeoutException = new DriverException("Timed out waiting for server response");
601601 connection.defunct(timeoutException);
602602
603603 logError(connection.address, timeoutException);
@@ -606,8 +606,8 @@
606606 // This shouldn't happen, but if it does, we want to signal the callback, not let him hang indefinitively
607607 setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e));
608608 } finally {
609- if (queriedHost != null)
610- manager.cluster.manager.reportLatency(queriedHost, latency);
609+ if (queriedHost != null && statement != Statement.DEFAULT)
610+ manager.cluster.manager.reportLatency(queriedHost, statement, timeoutException, latency);
611611 }
612612 return true;
613613 }
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +3 −3
@@ -86,8 +86,8 @@
8686 case PROTOCOL_ERROR: return new DriverInternalError("An unexpected protocol error occurred. This is a bug in this library, please report: " + message);
8787 case BAD_CREDENTIALS: return new AuthenticationException(host, message);
8888 case UNAVAILABLE: return ((UnavailableException)infos).copy(); // We copy to have a nice stack trace
89- case OVERLOADED: return new DriverInternalError(String.format("Queried host (%s) was overloaded; this shouldn't happen, another node should have been tried", host));
90- case IS_BOOTSTRAPPING: return new DriverInternalError(String.format("Queried host (%s) was bootstrapping; this shouldn't happen, another node should have been tried", host));
89+ case OVERLOADED: return new OverloadedException(host, message);
90+ case IS_BOOTSTRAPPING: return new BootstrappingException(host, message);
9191 case TRUNCATE_ERROR: return new TruncateException(message);
9292 case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy();
9393 case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy();
@@ -96,7 +96,7 @@
9696 case INVALID: return new InvalidQueryException(message);
9797 case CONFIG_ERROR: return new InvalidConfigurationInQueryException(message);
9898 case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy();
99- case UNPREPARED: return new DriverInternalError(String.format("A prepared query was submitted on %s but was not known of that node; this shouldn't happen, the query should have been re-prepared", host));
99+ case UNPREPARED: return new UnpreparedException(host, message);
100100 default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
101101 }
102102 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +59 −0
@@ -0,0 +1,59 @@
1+/*
2+ * Copyright (C) 2012-2014 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.exceptions;
17+
18+import java.net.InetSocketAddress;
19+
20+/**
21+ * Indicates that the contacted host was bootstrapping.
22+ * This class is mainly intended for internal use;
23+ * client applications are not expected to deal with this exception directly,
24+ * because the driver would transparently retry the same query on another host;
25+ * but such exceptions are likely to appear occasionally in the driver logs.
26+ */
27+public class BootstrappingException extends DriverInternalError {
28+
29+ private static final long serialVersionUID = 0;
30+
31+ private final InetSocketAddress address;
32+
33+ public BootstrappingException(InetSocketAddress address, String message) {
34+ super(String.format("Queried host (%s) was bootstrapping: %s", address, message));
35+ this.address = address;
36+ }
37+
38+ /**
39+ * Private constructor used solely when copying exceptions.
40+ */
41+ private BootstrappingException(InetSocketAddress address, String message, BootstrappingException cause) {
42+ super(message, cause);
43+ this.address = address;
44+ }
45+
46+ /**
47+ * The full address of the host that was bootstrapping.
48+ *
49+ * @return The full address of the host that was bootstrapping.
50+ */
51+ public InetSocketAddress getAddress() {
52+ return address;
53+ }
54+
55+ @Override
56+ public BootstrappingException copy() {
57+ return new BootstrappingException(address, getMessage(), this);
58+ }
59+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java +1 −1
@@ -38,7 +38,7 @@
3838 }
3939
4040 @Override
41- public DriverException copy() {
41+ public DriverInternalError copy() {
4242 return new DriverInternalError(getMessage(), this);
4343 }
4444 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +59 −0
@@ -0,0 +1,59 @@
1+/*
2+ * Copyright (C) 2012-2014 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.exceptions;
17+
18+import java.net.InetSocketAddress;
19+
20+/**
21+ * Indicates that the contacted host reported itself being overloaded.
22+ * This class is mainly intended for internal use;
23+ * client applications are not expected to deal with this exception directly,
24+ * because the driver would transparently retry the same query on another host;
25+ * but such exceptions are likely to appear occasionally in the driver logs.
26+ */
27+public class OverloadedException extends DriverInternalError {
28+
29+ private static final long serialVersionUID = 0;
30+
31+ private final InetSocketAddress address;
32+
33+ public OverloadedException(InetSocketAddress address, String message) {
34+ super(String.format("Queried host (%s) was overloaded: %s", address, message));
35+ this.address = address;
36+ }
37+
38+ /**
39+ * Private constructor used solely when copying exceptions.
40+ */
41+ private OverloadedException(InetSocketAddress address, String message, OverloadedException cause) {
42+ super(message, cause);
43+ this.address = address;
44+ }
45+
46+ /**
47+ * The full address of the host that reported itself being overloaded.
48+ *
49+ * @return The full address of the host that reported itself being overloaded.
50+ */
51+ public InetSocketAddress getAddress() {
52+ return address;
53+ }
54+
55+ @Override
56+ public OverloadedException copy() {
57+ return new OverloadedException(address, getMessage(), this);
58+ }
59+}
added driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java +59 −0
@@ -0,0 +1,59 @@
1+/*
2+ * Copyright (C) 2012-2014 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.exceptions;
17+
18+import java.net.InetSocketAddress;
19+
20+/**
21+ * Indicates that the contacted host replied with an UNPREPARED error code.
22+ * This class is mainly intended for internal use;
23+ * client applications are not expected to deal with this exception directly,
24+ * because the driver would transparently prepare the query and execute it again;
25+ * but such exceptions are likely to appear occasionally in the driver logs.
26+ */
27+public class UnpreparedException extends DriverInternalError {
28+
29+ private static final long serialVersionUID = 0;
30+
31+ private final InetSocketAddress address;
32+
33+ public UnpreparedException(InetSocketAddress address, String message) {
34+ super(String.format("A prepared query was submitted on %s but was not known of that node: %s", address, message));
35+ this.address = address;
36+ }
37+
38+ /**
39+ * Private constructor used solely when copying exceptions.
40+ */
41+ private UnpreparedException(InetSocketAddress address, String message, UnpreparedException cause) {
42+ super(message, cause);
43+ this.address = address;
44+ }
45+
46+ /**
47+ * The full address of the host that replied with an UNPREPARED error code.
48+ *
49+ * @return The full address of the host that replied with an UNPREPARED error code.
50+ */
51+ public InetSocketAddress getAddress() {
52+ return address;
53+ }
54+
55+ @Override
56+ public UnpreparedException copy() {
57+ return new UnpreparedException(address, getMessage(), this);
58+ }
59+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +38 −9
@@ -19,13 +19,16 @@
1919 import java.util.concurrent.*;
2020 import java.util.concurrent.atomic.AtomicReference;
2121
22+import com.google.common.annotations.VisibleForTesting;
2223 import com.google.common.collect.AbstractIterator;
2324 import com.google.common.collect.ImmutableMap;
25+import com.google.common.collect.ImmutableSet;
2426 import com.google.common.util.concurrent.ThreadFactoryBuilder;
2527 import org.slf4j.Logger;
2628 import org.slf4j.LoggerFactory;
2729
2830 import com.datastax.driver.core.*;
31+import com.datastax.driver.core.exceptions.*;
2932
3033 /**
3134 * A wrapper load balancing policy that adds latency awareness to a child policy.
@@ -104,7 +107,8 @@
104107 return new Builder(childPolicy);
105108 }
106109
107- private class Updater implements Runnable {
110+ @VisibleForTesting
111+ class Updater implements Runnable {
108112
109113 private Set<Host> excludedAtLastTick = Collections.<Host>emptySet();
110114
@@ -367,20 +371,45 @@
367371 }
368372 }
369373
374+ /**
375+ * A set of DriverException subclasses that we should prevent from updating the host's score.
376+ * The intent behind it is to filter out "fast" errors: when a host replies with such errors,
377+ * it usually does so very quickly, because it did not involve any actual
378+ * coordination work. Such errors are not good indicators of the host's responsiveness,
379+ * and tend to make the host's score look better than it actually is.
380+ */
381+ private static final Set<Class<? extends DriverException>> EXCLUDED_EXCEPTIONS = ImmutableSet.of(
382+ UnavailableException.class, // this is done via the snitch and is usually very fast
383+ OverloadedException.class,
384+ BootstrappingException.class,
385+ UnpreparedException.class,
386+ QueryValidationException.class // query validation also happens at early stages in the coordinator
387+ );
388+
370389 private class Tracker implements LatencyTracker {
371390
372391 private final ConcurrentMap<Host, HostLatencyTracker> latencies = new ConcurrentHashMap<Host, HostLatencyTracker>();
373392 private volatile long cachedMin = -1L;
374393
375- public void update(Host host, long newLatencyNanos) {
376- HostLatencyTracker hostTracker = latencies.get(host);
377- if (hostTracker == null) {
378- hostTracker = new HostLatencyTracker(scale, (30L * minMeasure) / 100L);
379- HostLatencyTracker old = latencies.putIfAbsent(host, hostTracker);
380- if (old != null)
381- hostTracker = old;
394+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
395+ if(shouldConsiderNewLatency(statement, exception)) {
396+ HostLatencyTracker hostTracker = latencies.get(host);
397+ if (hostTracker == null) {
398+ hostTracker = new HostLatencyTracker(scale, (30L * minMeasure) / 100L);
399+ HostLatencyTracker old = latencies.putIfAbsent(host, hostTracker);
400+ if (old != null)
401+ hostTracker = old;
402+ }
403+ hostTracker.add(newLatencyNanos);
382404 }
383- hostTracker.add(newLatencyNanos);
405+ }
406+
407+ private boolean shouldConsiderNewLatency(Statement statement, Exception exception) {
408+ // query was successful: always consider
409+ if(exception == null) return true;
410+ // filter out "fast" errors
411+ if(EXCLUDED_EXCEPTIONS.contains(exception.getClass())) return false;
412+ return true;
384413 }
385414
386415 public void updateMin() {
modified driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +48 −0
@@ -1,9 +1,16 @@
11 package com.datastax.driver.core;
22
33 import java.io.StringWriter;
4+import java.util.concurrent.TimeoutException;
5+import java.util.concurrent.locks.Condition;
6+import java.util.concurrent.locks.Lock;
7+import java.util.concurrent.locks.ReentrantLock;
8+
9+import static java.util.concurrent.TimeUnit.MILLISECONDS;
410
511 import org.apache.log4j.PatternLayout;
612 import org.apache.log4j.WriterAppender;
13+import org.apache.log4j.spi.LoggingEvent;
714
815 /**
916 * Simple Log4J appender that captures logs to memory in order to inspect them in unit tests.
@@ -12,6 +19,11 @@
1219 * done with an {@code @After} method that removes it).
1320 */
1421 public class MemoryAppender extends WriterAppender {
22+
23+ private final Lock appendLock = new ReentrantLock();
24+
25+ private final Condition append = appendLock.newCondition();
26+
1527 public final StringWriter writer = new StringWriter();
1628
1729 private int nextLogIdx = 0;
@@ -21,10 +33,46 @@
2133 setLayout(new PatternLayout("%m%n"));
2234 }
2335
36+ @Override
37+ protected void subAppend(LoggingEvent event) {
38+ appendLock.lock();
39+ try {
40+ super.subAppend(event);
41+ append.signal();
42+ } finally {
43+ appendLock.unlock();
44+ }
45+ }
46+
2447 public String get() {
2548 return writer.toString();
2649 }
2750
51+ /**
52+ * Wait until at least one log event is appended to the current appender,
53+ * or a timeout occurs, whichever happens first,
54+ * then return the appender contents.
55+ * Not thread safe.
56+ * Useful when asynchronous code needs to wait until
57+ * the appender is actually invoked at least once.
58+ *
59+ * @param timeoutMillis timeout in milliseconds
60+ * @return The appender contents. Not thread safe.
61+ */
62+ public String waitAndGet(long timeoutMillis) throws InterruptedException {
63+ long nanos = MILLISECONDS.toNanos(timeoutMillis);
64+ appendLock.lock();
65+ try {
66+ while (get().isEmpty()) {
67+ if (nanos <= 0L) break; // timeout
68+ nanos = append.awaitNanos(nanos);
69+ }
70+ return get();
71+ } finally {
72+ appendLock.unlock();
73+ }
74+ }
75+
2876 /**
2977 * @return The next set of logs after getNext was last called. Not thread safe.
3078 */
added driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +233 −0
@@ -0,0 +1,233 @@
1+/*
2+ * Copyright (C) 2012-2014 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 org.apache.log4j.Logger;
19+import org.testng.annotations.AfterMethod;
20+import org.testng.annotations.BeforeMethod;
21+import org.testng.annotations.Test;
22+
23+import static org.apache.log4j.Level.DEBUG;
24+import static org.apache.log4j.Level.INFO;
25+import static org.assertj.core.api.Assertions.assertThat;
26+import static org.assertj.core.api.Assertions.fail;
27+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
28+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
29+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
30+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
31+
32+import com.datastax.driver.core.exceptions.NoHostAvailableException;
33+import com.datastax.driver.core.exceptions.ReadTimeoutException;
34+import com.datastax.driver.core.exceptions.UnavailableException;
35+import com.datastax.driver.core.exceptions.WriteTimeoutException;
36+
37+import static com.datastax.driver.core.QueryLogger.builder;
38+
39+/**
40+ * Tests for {@link QueryLogger} using Scassandra.
41+ * Contains only tests for exceptions (client timeout, read timeout, unavailable...);
42+ * other tests can be found in {@link QueryLoggerTest}.
43+ */
44+public class QueryLoggerErrorsTest extends ScassandraTestBase.PerClassCluster {
45+
46+ private Logger slow = Logger.getLogger(QueryLogger.SLOW_LOGGER.getName());
47+ private Logger error = Logger.getLogger(QueryLogger.ERROR_LOGGER.getName());
48+
49+ private MemoryAppender slowAppender;
50+ private MemoryAppender errorAppender;
51+
52+ private QueryLogger queryLogger;
53+
54+ @BeforeMethod(groups = { "short", "unit" })
55+ public void startCapturingLogs() {
56+ slow.addAppender(slowAppender = new MemoryAppender());
57+ error.addAppender(errorAppender = new MemoryAppender());
58+ }
59+
60+ @AfterMethod(groups = { "short", "unit" })
61+ public void stopCapturingLogs() {
62+ slow.setLevel(null);
63+ error.setLevel(null);
64+ slow.removeAppender(slowAppender);
65+ error.removeAppender(errorAppender);
66+ }
67+
68+ @BeforeMethod(groups = { "short", "unit" })
69+ @AfterMethod(groups = { "short", "unit" })
70+ public void resetLogLevels() {
71+ slow.setLevel(INFO);
72+ error.setLevel(INFO);
73+ }
74+
75+ @BeforeMethod(groups = { "short", "unit" })
76+ public void resetQueryLogger() {
77+ queryLogger = null;
78+ }
79+
80+ @AfterMethod(groups = { "short", "unit" })
81+ public void unregisterQueryLogger() {
82+ if(cluster != null && queryLogger != null) {
83+ cluster.unregister(queryLogger);
84+ }
85+ }
86+
87+ @Test(groups = "short")
88+ public void should_log_slow_queries() throws Exception {
89+ // given
90+ slow.setLevel(DEBUG);
91+ queryLogger = builder(cluster)
92+ .withSlowQueryLatencyThresholdMillis(10)
93+ .build();
94+ cluster.register(queryLogger);
95+ String query = "SELECT foo FROM bar";
96+ primingClient.prime(
97+ queryBuilder()
98+ .withQuery(query)
99+ .withFixedDelay(100)
100+ .build()
101+ );
102+ // when
103+ session.execute(query);
104+ // then
105+ String line = slowAppender.waitAndGet(5000);
106+ assertThat(line)
107+ .contains("Query too slow")
108+ .contains("127.0.0.1")
109+ .contains(query);
110+ }
111+
112+ @Test(groups = "short")
113+ public void should_log_timed_out_queries() throws Exception {
114+ // given
115+ error.setLevel(DEBUG);
116+ queryLogger = builder(cluster).build();
117+ cluster.register(queryLogger);
118+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
119+ String query = "SELECT foo FROM bar";
120+ primingClient.prime(
121+ queryBuilder()
122+ .withQuery(query)
123+ .withFixedDelay(100)
124+ .build()
125+ );
126+ // when
127+ try {
128+ session.execute(query);
129+ fail("Should have thrown NoHostAvailableException");
130+ } catch (NoHostAvailableException e) {
131+ // ok
132+ }
133+ // then
134+ String line = errorAppender.waitAndGet(5000);
135+ assertThat(line)
136+ .contains("Query error")
137+ .contains("127.0.0.1")
138+ .contains(Integer.toString(scassandra.getBinaryPort()))
139+ .contains(query)
140+ .contains(OperationTimedOutException.class.getName());
141+ }
142+
143+ @Test(groups = "short")
144+ public void should_log_read_timeout_errors() throws Exception {
145+ // given
146+ error.setLevel(DEBUG);
147+ queryLogger = builder(cluster).build();
148+ cluster.register(queryLogger);
149+ String query = "SELECT foo FROM bar";
150+ primingClient.prime(
151+ queryBuilder()
152+ .withQuery(query)
153+ .withResult(read_request_timeout)
154+ .build()
155+ );
156+ // when
157+ try {
158+ session.execute(query);
159+ fail("Should have thrown ReadTimeoutException");
160+ } catch (ReadTimeoutException e) {
161+ // ok
162+ }
163+ // then
164+ String line = errorAppender.waitAndGet(5000);
165+ assertThat(line)
166+ .contains("Query error")
167+ .contains("127.0.0.1")
168+ .contains(Integer.toString(scassandra.getBinaryPort()))
169+ .contains(query)
170+ .contains(ReadTimeoutException.class.getName());
171+ }
172+
173+ @Test(groups = "short")
174+ public void should_log_write_timeout_errors() throws Exception {
175+ // given
176+ error.setLevel(DEBUG);
177+ queryLogger = builder(cluster).build();
178+ cluster.register(queryLogger);
179+ String query = "UPDATE test SET foo = 'bar' where qix = ?";
180+ primingClient.prime(
181+ queryBuilder()
182+ .withQuery(query)
183+ .withResult(write_request_timeout)
184+ .build()
185+ );
186+ // when
187+ try {
188+ session.execute(query);
189+ fail("Should have thrown WriteTimeoutException");
190+ } catch (WriteTimeoutException e) {
191+ // ok
192+ }
193+ // then
194+ String line = errorAppender.waitAndGet(5000);
195+ assertThat(line)
196+ .contains("Query error")
197+ .contains("127.0.0.1")
198+ .contains(Integer.toString(scassandra.getBinaryPort()))
199+ .contains(query)
200+ .contains(WriteTimeoutException.class.getName());
201+ }
202+
203+ @Test(groups = "short")
204+ public void should_log_unavailable_errors() throws Exception {
205+ // given
206+ error.setLevel(DEBUG);
207+ queryLogger = builder(cluster).build();
208+ cluster.register(queryLogger);
209+ String query = "SELECT foo FROM bar";
210+ primingClient.prime(
211+ queryBuilder()
212+ .withQuery(query)
213+ .withResult(unavailable)
214+ .build()
215+ );
216+ // when
217+ try {
218+ session.execute(query);
219+ fail("Should have thrown UnavailableException");
220+ } catch (UnavailableException e) {
221+ // ok
222+ }
223+ // then
224+ String line = errorAppender.waitAndGet(5000);
225+ assertThat(line)
226+ .contains("Query error")
227+ .contains("127.0.0.1")
228+ .contains(Integer.toString(scassandra.getBinaryPort()))
229+ .contains(query)
230+ .contains(UnavailableException.class.getName());
231+ }
232+
233+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +691 −0
@@ -0,0 +1,691 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.nio.ByteBuffer;
19+import java.util.ArrayList;
20+import java.util.List;
21+
22+import com.datastax.driver.core.utils.CassandraVersion;
23+import com.google.common.base.Function;
24+import com.google.common.base.Joiner;
25+import com.google.common.base.Predicate;
26+import com.google.common.collect.Lists;
27+import com.google.common.collect.Sets;
28+import com.google.common.primitives.Bytes;
29+import org.apache.log4j.Logger;
30+import org.testng.annotations.AfterMethod;
31+import org.testng.annotations.BeforeMethod;
32+import org.testng.annotations.Test;
33+
34+import static com.datastax.driver.core.BatchStatement.Type.COUNTER;
35+import static org.apache.log4j.Level.DEBUG;
36+import static org.apache.log4j.Level.INFO;
37+import static org.apache.log4j.Level.TRACE;
38+import static org.assertj.core.api.Assertions.assertThat;
39+import static org.mockito.Mockito.mock;
40+
41+import com.datastax.driver.core.exceptions.DriverException;
42+
43+import static com.datastax.driver.core.BatchStatement.Type.UNLOGGED;
44+import static com.datastax.driver.core.CCMBridge.ipOfNode;
45+import static com.datastax.driver.core.QueryLogger.*;
46+import static com.datastax.driver.core.TestUtils.getFixedValue;
47+
48+/**
49+ * Main tests for {@link QueryLogger} using {@link com.datastax.driver.core.CCMBridge}.
50+ * More tests, specifically targeting slow and unsuccessful queries, can be found in
51+ * {@link QueryLoggerErrorsTest}.
52+ */
53+public class QueryLoggerTest extends CCMBridge.PerClassSingleNodeCluster {
54+
55+ private static final List<DataType> dataTypes = new ArrayList<DataType>(Sets.filter(DataType.allPrimitiveTypes(), new Predicate<DataType>() {
56+ @Override
57+ public boolean apply(DataType type) {
58+ return type != DataType.counter();
59+ }
60+ }));
61+
62+ private static final List<Object> values = Lists.transform(dataTypes, new Function<DataType, Object>() {
63+ @Override
64+ public Object apply(DataType type) {
65+ return getFixedValue(type);
66+ }
67+ }
68+ );
69+
70+ private static final String definitions = Joiner.on(", ").join(
71+ Lists.transform(dataTypes, new Function<DataType, String>() {
72+ @Override
73+ public String apply(DataType type) {
74+ return "c_" + type + " " + type;
75+ }
76+ }
77+ )
78+ );
79+
80+ private static final String assignments = Joiner.on(", ").join(
81+ Lists.transform(dataTypes, new Function<DataType, String>() {
82+ @Override
83+ public String apply(DataType type) {
84+ return "c_" + type + " = ?";
85+ }
86+ }
87+ )
88+ );
89+
90+ private Logger normal = Logger.getLogger(NORMAL_LOGGER.getName());
91+ private Logger slow = Logger.getLogger(SLOW_LOGGER.getName());
92+ private Logger error = Logger.getLogger(ERROR_LOGGER.getName());
93+
94+ private MemoryAppender normalAppender;
95+ private MemoryAppender slowAppender;
96+ private MemoryAppender errorAppender;
97+
98+ private QueryLogger queryLogger;
99+
100+ @BeforeMethod(groups = { "short", "unit" })
101+ public void startCapturingLogs() {
102+ normal.addAppender(normalAppender = new MemoryAppender());
103+ slow.addAppender(slowAppender = new MemoryAppender());
104+ error.addAppender(errorAppender = new MemoryAppender());
105+ }
106+
107+ @AfterMethod(groups = { "short", "unit" })
108+ public void stopCapturingLogs() {
109+ normal.setLevel(null);
110+ slow.setLevel(null);
111+ error.setLevel(null);
112+ normal.removeAppender(normalAppender);
113+ slow.removeAppender(slowAppender);
114+ error.removeAppender(errorAppender);
115+ }
116+
117+ @BeforeMethod(groups = { "short", "unit" })
118+ public void resetLogLevels() {
119+ normal.setLevel(INFO);
120+ slow.setLevel(INFO);
121+ error.setLevel(INFO);
122+ }
123+
124+ @AfterMethod(groups = { "short", "unit" })
125+ public void unregisterQueryLogger() {
126+ if(cluster != null && queryLogger != null) {
127+ cluster.unregister(queryLogger);
128+ }
129+ }
130+
131+ // Tests for different types of statements (Regular, Bound, Batch)
132+
133+ @Test(groups = "short")
134+ public void should_log_regular_statements() throws Exception {
135+ // given
136+ normal.setLevel(DEBUG);
137+ queryLogger = QueryLogger.builder(cluster)
138+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
139+ .build();
140+ cluster.register(queryLogger);
141+ String query = "SELECT c_text FROM test WHERE pk = 42";
142+ session.execute(query);
143+ // then
144+ String line = normalAppender.waitAndGet(10000);
145+ assertThat(line)
146+ .contains("Query completed normally")
147+ .contains(ipOfNode(1))
148+ .contains(query)
149+ .doesNotContain("parameters");
150+ }
151+
152+ @Test(groups = "short")
153+ public void should_log_bound_statements() throws Exception {
154+ // given
155+ normal.setLevel(DEBUG);
156+ queryLogger = QueryLogger.builder(cluster)
157+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
158+ .build();
159+ cluster.register(queryLogger);
160+ String query = "SELECT * FROM test where pk = ?";
161+ PreparedStatement ps = session.prepare(query);
162+ BoundStatement bs = ps.bind(42);
163+ session.execute(bs);
164+ // then
165+ String line = normalAppender.waitAndGet(10000);
166+ assertThat(line)
167+ .contains("Query completed normally")
168+ .contains(ipOfNode(1))
169+ .contains(query)
170+ .doesNotContain("actual parameters");
171+ }
172+
173+ @Test(groups = "short")
174+ @CassandraVersion(major=2.0)
175+ public void should_log_batch_statements() throws Exception {
176+ // given
177+ normal.setLevel(DEBUG);
178+ queryLogger = QueryLogger.builder(cluster)
179+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
180+ .withMaxQueryStringLength(Integer.MAX_VALUE)
181+ .build();
182+ cluster.register(queryLogger);
183+ // when
184+ String query1 = "INSERT INTO test (pk) VALUES (?)";
185+ String query2 = "UPDATE test SET c_int = ? WHERE pk = 42";
186+ PreparedStatement ps1 = session.prepare(query1);
187+ PreparedStatement ps2 = session.prepare(query2);
188+ BatchStatement batch = new BatchStatement();
189+ batch.add(ps1.bind(42));
190+ batch.add(ps2.bind(1234));
191+ session.execute(batch);
192+ // then
193+ String line = normalAppender.waitAndGet(10000);
194+ assertThat(line)
195+ .contains("Query completed normally")
196+ .contains(ipOfNode(1))
197+ .contains("BEGIN BATCH")
198+ .contains("APPLY BATCH")
199+ .contains(query1)
200+ .contains(query2)
201+ .doesNotContain("c_int:");
202+ }
203+
204+ @Test(groups = "short")
205+ @CassandraVersion(major=2.0)
206+ public void should_log_unlogged_batch_statements() throws Exception {
207+ // given
208+ normal.setLevel(DEBUG);
209+ queryLogger = QueryLogger.builder(cluster)
210+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
211+ .withMaxQueryStringLength(Integer.MAX_VALUE)
212+ .build();
213+ cluster.register(queryLogger);
214+ // when
215+ String query1 = "INSERT INTO test (pk) VALUES (?)";
216+ String query2 = "UPDATE test SET c_int = ? WHERE pk = 42";
217+ PreparedStatement ps1 = session.prepare(query1);
218+ PreparedStatement ps2 = session.prepare(query2);
219+ BatchStatement batch = new BatchStatement(UNLOGGED);
220+ batch.add(ps1.bind(42));
221+ batch.add(ps2.bind(1234));
222+ session.execute(batch);
223+ // then
224+ String line = normalAppender.waitAndGet(10000);
225+ assertThat(line)
226+ .contains("Query completed normally")
227+ .contains(ipOfNode(1))
228+ .contains("BEGIN UNLOGGED BATCH")
229+ .contains("APPLY BATCH")
230+ .contains(query1)
231+ .contains(query2)
232+ .doesNotContain("c_int:");
233+ }
234+
235+ @Test(groups = "short")
236+ @CassandraVersion(major=2.0)
237+ public void should_log_counter_batch_statements() throws Exception {
238+ // Create a special table for testing with counters.
239+ session.execute(
240+ "CREATE TABLE IF NOT EXISTS counter_test (pk int PRIMARY KEY, c_count COUNTER, c_count2 COUNTER)");
241+
242+ // given
243+ normal.setLevel(DEBUG);
244+ queryLogger = QueryLogger.builder(cluster)
245+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
246+ .withMaxQueryStringLength(Integer.MAX_VALUE)
247+ .build();
248+ cluster.register(queryLogger);
249+ // when
250+ String query1 = "UPDATE counter_test SET c_count = c_count + ? WHERE pk = 42";
251+ String query2 = "UPDATE counter_test SET c_count2 = c_count2 + ? WHERE pk = 42";
252+ PreparedStatement ps1 = session.prepare(query1);
253+ PreparedStatement ps2 = session.prepare(query2);
254+ BatchStatement batch = new BatchStatement(COUNTER);
255+ batch.add(ps1.bind(1234L));
256+ batch.add(ps2.bind(5678L));
257+ session.execute(batch);
258+ // then
259+ String line = normalAppender.waitAndGet(10000);
260+ assertThat(line)
261+ .contains("Query completed normally")
262+ .contains(ipOfNode(1))
263+ .contains("BEGIN COUNTER BATCH")
264+ .contains("APPLY BATCH")
265+ .contains(query1)
266+ .contains(query2)
267+ .doesNotContain("c_count:");
268+ }
269+
270+ @Test(groups = "unit")
271+ public void should_log_unknown_statements() throws Exception {
272+ // given
273+ normal.setLevel(DEBUG);
274+ Statement unknownStatement = new Statement() {
275+ @Override
276+ public ByteBuffer getRoutingKey() {
277+ return null;
278+ }
279+ @Override
280+ public String getKeyspace() {
281+ return null;
282+ }
283+ };
284+ // when
285+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
286+ queryLogger.update(null, unknownStatement, null, 0);
287+ // then
288+ String line = normalAppender.get();
289+ assertThat(line).contains(UNKNOWN_STATEMENT);
290+ }
291+
292+ // Tests for different log levels
293+
294+ @Test(groups = "unit")
295+ public void should_not_log_normal_if_level_higher_than_DEBUG() throws Exception {
296+ // given
297+ normal.setLevel(INFO);
298+ slow.setLevel(INFO);
299+ error.setLevel(INFO);
300+ // when
301+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
302+ queryLogger.update(null, mock(BoundStatement.class), null, 0);
303+ // then
304+ assertThat(normalAppender.get()).isEmpty();
305+ assertThat(slowAppender.get()).isEmpty();
306+ assertThat(errorAppender.get()).isEmpty();
307+ }
308+
309+ @Test(groups = "unit")
310+ public void should_not_log_slow_if_level_higher_than_DEBUG() throws Exception {
311+ // given
312+ normal.setLevel(INFO);
313+ slow.setLevel(INFO);
314+ error.setLevel(INFO);
315+ // when
316+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
317+ queryLogger.update(null, mock(BoundStatement.class), null, DEFAULT_SLOW_QUERY_THRESHOLD_MS + 1);
318+ // then
319+ assertThat(normalAppender.get()).isEmpty();
320+ assertThat(slowAppender.get()).isEmpty();
321+ assertThat(errorAppender.get()).isEmpty();
322+ }
323+
324+ @Test(groups = "unit")
325+ public void should_not_log_error_if_level_higher_than_DEBUG() throws Exception {
326+ // given
327+ normal.setLevel(INFO);
328+ slow.setLevel(INFO);
329+ error.setLevel(INFO);
330+ // when
331+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
332+ queryLogger.update(null, mock(BoundStatement.class), new DriverException("booh"), 0);
333+ // then
334+ assertThat(normalAppender.get()).isEmpty();
335+ assertThat(slowAppender.get()).isEmpty();
336+ assertThat(errorAppender.get()).isEmpty();
337+ }
338+
339+ // Tests for different query types (normal, slow, exception)
340+
341+ @Test(groups = "short")
342+ public void should_log_normal_queries() throws Exception {
343+ // given
344+ normal.setLevel(DEBUG);
345+ queryLogger = QueryLogger.builder(cluster)
346+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
347+ .withMaxQueryStringLength(Integer.MAX_VALUE)
348+ .build();
349+ cluster.register(queryLogger);
350+ // when
351+ String query = "SELECT * FROM test where pk = ?";
352+ PreparedStatement ps = session.prepare(query);
353+ BoundStatement bs = ps.bind(42);
354+ session.execute(bs);
355+ // then
356+ String line = normalAppender.waitAndGet(10000);
357+ assertThat(line)
358+ .contains("Query completed normally")
359+ .contains(ipOfNode(1))
360+ .contains(query)
361+ .doesNotContain("pk:42");
362+ }
363+
364+ // Tests for slow and error queries are in QueryLoggerErrorsTest
365+
366+ // Tests with query parameters (log level TRACE)
367+
368+ @Test(groups = "short")
369+ @CassandraVersion(major=2.0)
370+ public void should_log_non_null_named_parameter() throws Exception {
371+ // given
372+ normal.setLevel(TRACE);
373+ queryLogger = QueryLogger.builder(cluster)
374+ .withSlowQueryLatencyThresholdMillis(Long.MAX_VALUE)
375+ .withMaxQueryStringLength(Integer.MAX_VALUE)
376+ .build();
377+ cluster.register(queryLogger);
378+ // when
379+ String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2";
380+ PreparedStatement ps = session.prepare(query);
381+ BoundStatement bs = ps.bind();
382+ bs.setString("param1", "foo");
383+ bs.setInt("param2", 42);
384+ session.execute(bs);
385+ // then
386+ String line = normalAppender.waitAndGet(10000);
387+ assertThat(line)
388+ .contains("Query completed normally")
389+ .contains(ipOfNode(1))
390+ .contains(query)
391+ .contains("param2:42")
392+ .contains("param1:'foo'");
393+ }
394+
395+ @Test(groups = "short")
396+ public void should_log_non_null_positional_parameter() throws Exception {
397+ // given
398+ normal.setLevel(TRACE);
399+ queryLogger = QueryLogger.builder(cluster).build();
400+ cluster.register(queryLogger);
401+ // when
402+ String query = "UPDATE test SET c_text = ? WHERE pk = ?";
403+ PreparedStatement ps = session.prepare(query);
404+ BoundStatement bs = ps.bind();
405+ bs.setString("c_text", "foo");
406+ bs.setInt("pk", 42);
407+ session.execute(bs);
408+ // then
409+ String line = normalAppender.waitAndGet(10000);
410+ assertThat(line)
411+ .contains("Query completed normally")
412+ .contains(ipOfNode(1))
413+ .contains(query)
414+ .contains("pk:42")
415+ .contains("c_text:'foo'");
416+ }
417+
418+ @Test(groups = "short")
419+ public void should_log_null_parameter() throws Exception {
420+ // given
421+ normal.setLevel(TRACE);
422+ queryLogger = QueryLogger.builder(cluster).build();
423+ cluster.register(queryLogger);
424+ // when
425+ String query = "UPDATE test SET c_text = ? WHERE pk = ?";
426+ PreparedStatement ps = session.prepare(query);
427+ BoundStatement bs = ps.bind();
428+ bs.setString("c_text", null);
429+ bs.setInt("pk", 42);
430+ session.execute(bs);
431+ // then
432+ String line = normalAppender.waitAndGet(10000);
433+ assertThat(line)
434+ .contains("Query completed normally")
435+ .contains(ipOfNode(1))
436+ .contains(query)
437+ .contains("pk:42")
438+ .contains("c_text:NULL");
439+ }
440+
441+ @Test(groups = "short")
442+ @CassandraVersion(major=2.0)
443+ public void should_log_bound_statement_parameters_inside_batch_statement() throws Exception {
444+ // given
445+ normal.setLevel(TRACE);
446+ queryLogger = QueryLogger.builder(cluster).build();
447+ cluster.register(queryLogger);
448+ // when
449+ String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
450+ String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
451+ BatchStatement batch = new BatchStatement();
452+ batch.add(session.prepare(query1).bind("foo", 42));
453+ batch.add(session.prepare(query2).bind(12345, 43));
454+ session.execute(batch);
455+ // then
456+ String line = normalAppender.waitAndGet(10000);
457+ assertThat(line)
458+ .contains("Query completed normally")
459+ .contains(ipOfNode(1))
460+ .contains(query1)
461+ .contains(query2)
462+ .contains("pk:42")
463+ .contains("pk:43")
464+ .contains("c_text:'foo'")
465+ .contains("c_int:12345");
466+ }
467+ // Test different CQL types
468+
469+ @Test(groups = "short")
470+ public void should_log_all_parameter_types() throws Exception {
471+ // given
472+ normal.setLevel(TRACE);
473+ queryLogger = QueryLogger.builder(cluster)
474+ .withMaxParameterValueLength(Integer.MAX_VALUE)
475+ .build();
476+ cluster.register(queryLogger);
477+ // when
478+ String query = "UPDATE test SET " + assignments + " WHERE pk = 42";
479+ PreparedStatement ps = session.prepare(query);
480+ BoundStatement bs = ps.bind(values.toArray());
481+ session.execute(bs);
482+ // then
483+ String line = normalAppender.waitAndGet(10000);
484+ assertThat(line)
485+ .contains("Query completed normally")
486+ .contains(ipOfNode(1))
487+ .contains(query);
488+ for (DataType type : dataTypes) {
489+ assertThat(line).contains(type.format(getFixedValue(type)));
490+ }
491+ }
492+
493+ // Tests for truncation of query strings and parameter values
494+
495+ @Test(groups = "short")
496+ public void should_truncate_query_when_max_length_exceeded() throws Exception {
497+ // given
498+ normal.setLevel(DEBUG);
499+ queryLogger = QueryLogger.builder(cluster)
500+ .withMaxQueryStringLength(5)
501+ .build();
502+ cluster.register(queryLogger);
503+ // when
504+ String query = "SELECT * FROM test WHERE pk = 42";
505+ session.execute(query);
506+ // then
507+ String line = normalAppender.waitAndGet(10000);
508+ assertThat(line)
509+ .contains("Query completed normally")
510+ .contains(ipOfNode(1))
511+ .contains("SELEC" + TRUNCATED_OUTPUT)
512+ .doesNotContain(query);
513+ }
514+
515+ @Test(groups = "short")
516+ public void should_not_truncate_query_when_max_length_unlimited() throws Exception {
517+ // given
518+ normal.setLevel(DEBUG);
519+ queryLogger = QueryLogger.builder(cluster)
520+ .withMaxQueryStringLength(-1)
521+ .build();
522+ cluster.register(queryLogger);
523+ // when
524+ String query = "SELECT * FROM test WHERE pk = 42";
525+ session.execute(query);
526+ // then
527+ String line = normalAppender.waitAndGet(10000);
528+ assertThat(line)
529+ .contains("Query completed normally")
530+ .contains(ipOfNode(1))
531+ .contains(query)
532+ .doesNotContain(TRUNCATED_OUTPUT);
533+ }
534+
535+ @Test(groups = "short")
536+ public void should_truncate_parameter_when_max_length_exceeded() throws Exception {
537+ // given
538+ normal.setLevel(TRACE);
539+ queryLogger = QueryLogger.builder(cluster)
540+ .withMaxParameterValueLength(5)
541+ .build();
542+ cluster.register(queryLogger);
543+ // when
544+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
545+ PreparedStatement ps = session.prepare(query);
546+ BoundStatement bs = ps.bind();
547+ bs.setInt("c_int", 123456);
548+ bs.setInt("pk", 42);
549+ session.execute(bs);
550+ // then
551+ String line = normalAppender.waitAndGet(10000);
552+ assertThat(line)
553+ .contains("Query completed normally")
554+ .contains(ipOfNode(1))
555+ .contains("c_int:12345" + TRUNCATED_OUTPUT)
556+ .doesNotContain("123456");
557+ }
558+
559+ @Test(groups = "short")
560+ public void should_truncate_blob_parameter_when_max_length_exceeded() throws Exception {
561+ // given
562+ normal.setLevel(TRACE);
563+ queryLogger = QueryLogger.builder(cluster)
564+ .withMaxParameterValueLength(6)
565+ .build();
566+ cluster.register(queryLogger);
567+ // when
568+ String query = "UPDATE test SET c_blob = ? WHERE pk = ?";
569+ PreparedStatement ps = session.prepare(query);
570+ BoundStatement bs = ps.bind();
571+ bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1,2,3))));
572+ bs.setInt("pk", 42);
573+ session.execute(bs);
574+ // then
575+ String line = normalAppender.waitAndGet(10000);
576+ assertThat(line)
577+ .contains("Query completed normally")
578+ .contains(ipOfNode(1))
579+ .contains("c_blob:0x0102" + TRUNCATED_OUTPUT)
580+ .doesNotContain("123456");
581+ }
582+
583+ @Test(groups = "short")
584+ public void should_not_truncate_parameter_when_max_length_unlimited() throws Exception {
585+ // given
586+ normal.setLevel(TRACE);
587+ queryLogger = QueryLogger.builder(cluster)
588+ .withMaxParameterValueLength(-1)
589+ .build();
590+ cluster.register(queryLogger);
591+ // when
592+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
593+ PreparedStatement ps = session.prepare(query);
594+ BoundStatement bs = ps.bind();
595+ bs.setInt("c_int", 123456);
596+ bs.setInt("pk", 42);
597+ session.execute(bs);
598+ // then
599+ String line = normalAppender.waitAndGet(10000);
600+ assertThat(line)
601+ .contains("Query completed normally")
602+ .contains(ipOfNode(1))
603+ .contains("c_int:123456")
604+ .doesNotContain(TRUNCATED_OUTPUT);
605+ }
606+
607+ @Test(groups = "short")
608+ public void should_not_log_exceeding_number_of_parameters() throws Exception {
609+ // given
610+ normal.setLevel(TRACE);
611+ queryLogger = QueryLogger.builder(cluster)
612+ .withMaxLoggedParameters(1)
613+ .build();
614+ cluster.register(queryLogger);
615+ // when
616+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
617+ PreparedStatement ps = session.prepare(query);
618+ BoundStatement bs = ps.bind();
619+ bs.setInt("c_int", 123456);
620+ bs.setInt("pk", 42);
621+ session.execute(bs);
622+ // then
623+ String line = normalAppender.waitAndGet(10000);
624+ assertThat(line)
625+ .contains("Query completed normally")
626+ .contains(ipOfNode(1))
627+ .contains("c_int:123456")
628+ .doesNotContain("pk:42")
629+ .contains(FURTHER_PARAMS_OMITTED);
630+ }
631+
632+ @Test(groups = "short")
633+ @CassandraVersion(major=2.0)
634+ public void should_not_log_exceeding_number_of_parameters_in_batch_statement() throws Exception {
635+ // given
636+ normal.setLevel(TRACE);
637+ queryLogger = QueryLogger.builder(cluster)
638+ .withMaxLoggedParameters(1)
639+ .build();
640+ cluster.register(queryLogger);
641+ // when
642+ String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
643+ String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
644+ BatchStatement batch = new BatchStatement();
645+ batch.add(session.prepare(query1).bind("foo", 42));
646+ batch.add(session.prepare(query2).bind(12345, 43));
647+ session.execute(batch);
648+ // then
649+ String line = normalAppender.waitAndGet(10000);
650+ assertThat(line)
651+ .contains("Query completed normally")
652+ .contains(ipOfNode(1))
653+ .contains(query1)
654+ .contains(query2)
655+ .contains("c_text:'foo'")
656+ .doesNotContain("pk:42")
657+ .doesNotContain("c_int:12345")
658+ .doesNotContain("pk:43")
659+ .contains(FURTHER_PARAMS_OMITTED);
660+ }
661+
662+ @Test(groups = "short")
663+ public void should_log_all_parameters_when_max_unlimited() throws Exception {
664+ // given
665+ normal.setLevel(TRACE);
666+ queryLogger = QueryLogger.builder(cluster)
667+ .withMaxLoggedParameters(-1)
668+ .build();
669+ cluster.register(queryLogger);
670+ // when
671+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
672+ PreparedStatement ps = session.prepare(query);
673+ BoundStatement bs = ps.bind();
674+ bs.setInt("c_int", 123456);
675+ bs.setInt("pk", 42);
676+ session.execute(bs);
677+ // then
678+ String line = normalAppender.waitAndGet(10000);
679+ assertThat(line)
680+ .contains("Query completed normally")
681+ .contains(ipOfNode(1))
682+ .contains("c_int:123456")
683+ .contains("pk:42");
684+ }
685+
686+ @Override
687+ protected List<String> getTableDefinitions() {
688+ return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
689+ }
690+
691+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +112 −0
@@ -0,0 +1,112 @@
1+package com.datastax.driver.core;
2+
3+import java.net.InetSocketAddress;
4+
5+import org.scassandra.Scassandra;
6+import org.scassandra.http.client.ActivityClient;
7+import org.scassandra.http.client.PrimingClient;
8+import org.slf4j.Logger;
9+import org.slf4j.LoggerFactory;
10+import org.testng.annotations.AfterClass;
11+import org.testng.annotations.AfterMethod;
12+import org.testng.annotations.BeforeClass;
13+import org.testng.annotations.BeforeMethod;
14+
15+import static org.assertj.core.api.Assertions.fail;
16+
17+/**
18+ * Base class for Scassandra tests.
19+ * This class takes care of starting and stopping a Scassandra server,
20+ * and provides some helper methods to leverage the creation of Cluster and Session objects.
21+ * The actual creation of such objects is however left to subclasses.
22+ * If a single cluster instance can be shared by all test methods,
23+ * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead.
24+ */
25+public abstract class ScassandraTestBase {
26+
27+ private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
28+
29+ protected Scassandra scassandra;
30+
31+ protected InetSocketAddress hostAddress;
32+
33+ protected PrimingClient primingClient;
34+
35+ protected ActivityClient activityClient;
36+
37+ @BeforeClass(groups = { "short", "long" })
38+ public void startScassandra() {
39+ scassandra = TestUtils.createScassandraServer();
40+ scassandra.start();
41+ primingClient = scassandra.primingClient();
42+ activityClient = scassandra.activityClient();
43+ hostAddress = new InetSocketAddress("127.0.0.1", scassandra.getBinaryPort());
44+ }
45+
46+ @AfterClass(groups = { "short", "long" })
47+ public void stopScassandra() {
48+ if(scassandra != null)
49+ scassandra.stop();
50+ }
51+
52+ @BeforeMethod(groups = { "short", "long" })
53+ @AfterMethod(groups = { "short", "long" })
54+ public void resetClients() {
55+ activityClient.clearAllRecordedActivity();
56+ primingClient.clearAllPrimes();
57+ }
58+
59+ protected Cluster.Builder createClusterBuilder() {
60+ Cluster.Builder builder = Cluster.builder()
61+ .addContactPoint("127.0.0.1")
62+ .withPoolingOptions(new PoolingOptions()
63+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
64+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
65+ .setHeartbeatIntervalSeconds(0))
66+ .withPort(scassandra.getBinaryPort());
67+ return builder;
68+ }
69+
70+ protected Host retrieveSingleHost(Cluster cluster) {
71+ Host host = cluster.getMetadata().getHost(hostAddress);
72+ if(host == null) {
73+ fail("Unable to retrieve host");
74+ }
75+ return host;
76+ }
77+
78+ /**
79+ * This subclass of ScassandraTestBase assumes that
80+ * the same Cluster instance will be used for all tests.
81+ */
82+ public static abstract class PerClassCluster extends ScassandraTestBase {
83+
84+ protected Cluster cluster;
85+
86+ protected Session session;
87+
88+ protected Host host;
89+
90+ @BeforeClass(groups = { "short", "long" }, dependsOnMethods = "startScassandra")
91+ public void initCluster() {
92+ Cluster.Builder builder = createClusterBuilder();
93+ cluster = builder.build();
94+ host = retrieveSingleHost(cluster);
95+ session = cluster.connect();
96+ }
97+
98+ @AfterClass(groups = { "short", "long" })
99+ public void closeCluster() {
100+ if (cluster != null)
101+ cluster.close();
102+ }
103+
104+ @AfterClass(groups = { "short", "long" }, dependsOnMethods = "closeCluster")
105+ @Override
106+ public void stopScassandra() {
107+ super.stopScassandra();
108+ }
109+
110+ }
111+
112+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +170 −0
@@ -0,0 +1,170 @@
1+/*
2+ * Copyright (C) 2012-2014 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.CountDownLatch;
19+
20+import static java.util.concurrent.TimeUnit.SECONDS;
21+
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.assertj.core.api.Assertions.fail;
26+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
27+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
28+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.exceptions.ReadTimeoutException;
32+import com.datastax.driver.core.exceptions.UnavailableException;
33+
34+public class LatencyAwarePolicyTest extends ScassandraTestBase {
35+
36+ /**
37+ * A special latency tracker used to signal to the main thread that all trackers have finished their jobs.
38+ */
39+ private class LatencyTrackerBarrier implements LatencyTracker {
40+
41+ private final CountDownLatch latch;
42+
43+ private LatencyTrackerBarrier(int numberOfQueries) {
44+ latch = new CountDownLatch(numberOfQueries);
45+ }
46+
47+ @Override
48+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
49+ latch.countDown();
50+ }
51+
52+ public void await() throws InterruptedException {
53+ latch.await(10, SECONDS);
54+ }
55+ }
56+
57+ @Test(groups = "short")
58+ public void should_consider_latency_when_query_successful() throws Exception {
59+ // given
60+ String query = "SELECT foo FROM bar";
61+ primingClient.prime(
62+ queryBuilder()
63+ .withQuery(query)
64+ .build()
65+ );
66+ LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
67+ .withMininumMeasurements(1)
68+ .build();
69+ Cluster.Builder builder = super.createClusterBuilder();
70+ builder.withLoadBalancingPolicy(latencyAwarePolicy);
71+ Cluster cluster = builder.build();
72+ cluster.init(); // force initialization of latency aware policy
73+ LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
74+ cluster.register(barrier); // add barrier to synchronize latency tracker threads with the current thread
75+ Session session = cluster.connect();
76+ // when
77+ session.execute(query);
78+ // then
79+ // wait until trackers have been notified
80+ barrier.await();
81+ // make sure the updater is called at least once
82+ latencyAwarePolicy.new Updater().run();
83+ LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
84+ assertThat(snapshot.getAllStats()).hasSize(1);
85+ LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
86+ assertThat(stats).isNotNull();
87+ assertThat(stats.getMeasurementsCount()).isEqualTo(1);
88+ assertThat(stats.getLatencyScore()).isNotEqualTo(-1);
89+ }
90+
91+ @Test(groups = "short")
92+ public void should_discard_latency_when_unavailable() throws Exception {
93+ // given
94+ String query = "SELECT foo FROM bar";
95+ primingClient.prime(
96+ queryBuilder()
97+ .withQuery(query)
98+ .withResult(unavailable)
99+ .build()
100+ );
101+ LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
102+ .withMininumMeasurements(1)
103+ .build();
104+ Cluster.Builder builder = super.createClusterBuilder();
105+ builder.withLoadBalancingPolicy(latencyAwarePolicy);
106+ Cluster cluster = builder.build();
107+ cluster.init(); // force initialization of latency aware policy
108+ LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
109+ cluster.register(barrier);
110+ Session session = cluster.connect();
111+ // when
112+ try {
113+ session.execute(query);
114+ fail("Should have thrown UnavailableException");
115+ } catch(UnavailableException e) {
116+ // ok
117+ }
118+ // then
119+ // wait until trackers have been notified
120+ barrier.await();
121+ // make sure the updater is called at least once
122+ latencyAwarePolicy.new Updater().run();
123+ LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
124+ assertThat(snapshot.getAllStats()).isEmpty();
125+ LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
126+ assertThat(stats).isNull();
127+ }
128+
129+ @Test(groups= "short")
130+ public void should_consider_latency_when_read_timeout() throws Exception {
131+ String query = "SELECT foo FROM bar";
132+ primingClient.prime(
133+ queryBuilder()
134+ .withQuery(query)
135+ .withResult(read_request_timeout)
136+ .build()
137+ );
138+
139+ LatencyAwarePolicy latencyAwarePolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy())
140+ .withMininumMeasurements(1)
141+ .build();
142+ Cluster.Builder builder = super.createClusterBuilder();
143+ builder.withLoadBalancingPolicy(latencyAwarePolicy);
144+ builder.withRetryPolicy(FallthroughRetryPolicy.INSTANCE);
145+ Cluster cluster = builder.build();
146+ cluster.init(); // force initialization of latency aware policy
147+ LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
148+ cluster.register(barrier);
149+ Session session = cluster.connect();
150+ // when
151+ try {
152+ session.execute(query);
153+ fail("Should have thrown ReadTimeoutException");
154+ } catch(ReadTimeoutException e) {
155+ // ok
156+ }
157+ // then
158+ // wait until trackers have been notified
159+ barrier.await();
160+ // make sure the updater is called at least once
161+ latencyAwarePolicy.new Updater().run();
162+ LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
163+ assertThat(snapshot.getAllStats()).hasSize(1);
164+ LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
165+ assertThat(stats).isNotNull();
166+ assertThat(stats.getMeasurementsCount()).isEqualTo(1);
167+ assertThat(stats.getLatencyScore()).isNotEqualTo(-1);
168+ }
169+
170+}