Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1

Conflicts:
	README.md
	docs.yaml
	driver-core/CHANGELOG.rst
	driver-core/README.rst
	driver-core/pom.xml
	driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java
	driver-core/src/main/java/com/datastax/driver/core/Cluster.java
	driver-core/src/main/java/com/datastax/driver/core/Connection.java
	driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java
	driver-core/src/main/java/com/datastax/driver/core/DataType.java
	driver-core/src/main/java/com/datastax/driver/core/Frame.java
	driver-core/src/main/java/com/datastax/driver/core/GettableData.java
	driver-core/src/main/java/com/datastax/driver/core/Host.java
	driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java
	driver-core/src/main/java/com/datastax/driver/core/Message.java
	driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java
	driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java
	driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java
	driver-core/src/main/java/com/datastax/driver/core/Requests.java
	driver-core/src/main/java/com/datastax/driver/core/Responses.java
	driver-core/src/main/java/com/datastax/driver/core/SessionManager.java
	driver-core/src/main/java/com/datastax/driver/core/Statement.java
	driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java
	driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java
	driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java
	driver-core/src/test/java/com/datastax/driver/core/SessionTest.java
	driver-core/src/test/java/com/datastax/driver/core/TestUtils.java
	driver-dist/pom.xml
	driver-dse/pom.xml
	driver-dse/src/main/java/com/datastax/driver/auth/DseAuthProvider.java
	driver-examples/osgi/pom.xml
	driver-examples/pom.xml
	driver-examples/stress/pom.xml
	features/README.md
	features/address_resolution/README.md
	features/native_protocol/README.md
	features/shaded_jar/README.md
	pom.xml
Changesetdcebaac4fdde8576a3f25477d6e2d9c1495aebe6d84acb5888683fdd594453c1
Authorolim7t <omichallat+github@gmail.com> · 2015-05-10 16:33 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-05-11 15:02 +02:00
Parentsb728b57e853c, 5b2ba50eec1f

Browse the files at this changeset

More than 300 files changed

modified .gitignore +1 −0
@@ -5,6 +5,7 @@
55 .classpath
66 .project
77 doc
8+docs
89 notes
910 .DS_Store
1011
modified README.md +57 −27
@@ -2,7 +2,7 @@
22
33 [![Build Status](https://travis-ci.org/datastax/java-driver.svg?branch=2.1)](https://travis-ci.org/datastax/java-driver)
44
5-*If you're reading this on GitHub, please note that this is the readme
5+*If you're reading this on github.com, please note that this is the readme
66 for the development version and that some features described here might
77 not yet have been released. You can find the documentation for latest
88 version through [Java driver
@@ -10,21 +10,39 @@
1010 [e.g.
1111 2.1.5](https://github.com/datastax/java-driver/tree/2.1.5).*
1212
13-A Java client driver for Apache Cassandra. This driver works exclusively with
14-the Cassandra Query Language version 3 (CQL3) and Cassandra's binary protocol.
15-
16-- JIRA: https://datastax-oss.atlassian.net/browse/JAVA
17-- MAILING LIST: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user
18-- IRC: #datastax-drivers on [irc.freenode.net](http://freenode.net)
19-- TWITTER: Follow the latest news about DataStax Drivers - [@olim7t](http://twitter.com/olim7t), [@mfiguiere](http://twitter.com/mfiguiere)
20-- DOCS: http://www.datastax.com/documentation/developer/java-driver/2.1/index.html
21-- API: http://www.datastax.com/drivers/java/2.1
22-- CHANGELOG: https://github.com/datastax/java-driver/blob/2.1/driver-core/CHANGELOG.rst
13+A modern, [feature-rich](features/) and highly tunable Java client
14+library for Apache Cassandra (1.2+) and DataStax Enterprise (3.1+) using
15+exclusively Cassandra's binary protocol and Cassandra Query Language v3.
16+
17+**Features:**
18+
19+* [Sync][sync] and [Async][async] API
20+* [Simple][simple_st], [Prepared][prepared_st], and [Batch][batch_st] statements
21+* Asynchronous IO, parallel execution, request pipelining
22+* [Connection pooling][pool]
23+* Auto node discovery
24+* Automatic reconnection
25+* Configurable [load balancing][lbp] and [retry policies][retry_policy]
26+* Works with any cluster size
27+* [Query builder][query_builder]
28+* [Object mapper][mapper]
29+
30+
31+[sync]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#execute(com.datastax.driver.core.Statement)
32+[async]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
33+[simple_st]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html
34+[prepared_st]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#prepare(com.datastax.driver.core.RegularStatement)
35+[batch_st]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html
36+[pool]: features/pooling/
37+[lbp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html
38+[retry_policy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html
39+[query_builder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html
40+[mapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/MappingManager.html
2341
2442 The driver architecture is based on layers. At the bottom lies the driver core.
2543 This core handles everything related to the connections to a Cassandra
2644 cluster (for example, connection pool, discovering new nodes, etc.) and exposes a simple,
27-relatively low-level API on top of which higher level layer can be built.
45+relatively low-level API on top of which higher level layers can be built.
2846
2947 The driver contains the following modules:
3048
@@ -35,26 +53,40 @@
3553
3654 Please refer to the README of each module for more information.
3755
56+**Community:**
57+
58+- JIRA: https://datastax-oss.atlassian.net/browse/JAVA
59+- MAILING LIST: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user
60+- IRC: #datastax-drivers on [irc.freenode.net](http://freenode.net)
61+- TWITTER: Follow the latest news about DataStax Drivers - [@olim7t](http://twitter.com/olim7t), [@mfiguiere](http://twitter.com/mfiguiere)
62+- DOCS: http://www.datastax.com/documentation/developer/java-driver/2.1/index.html
63+- API: http://www.datastax.com/drivers/java/2.1
64+- CHANGELOG: https://github.com/datastax/java-driver/blob/2.1/driver-core/CHANGELOG.rst
65+
3866 ## Maven
3967
4068 The last release of the driver is available on Maven Central. You can install
4169 it in your application using the following Maven dependency:
4270
43- <dependency>
44- <groupId>com.datastax.cassandra</groupId>
45- <artifactId>cassandra-driver-core</artifactId>
46- <version>2.1.5</version>
47- </dependency>
71+```xml
72+<dependency>
73+ <groupId>com.datastax.cassandra</groupId>
74+ <artifactId>cassandra-driver-core</artifactId>
75+ <version>2.1.5</version>
76+</dependency>
77+```
4878
4979 Note that the object mapper is published as a separate artifact:
5080
51- <dependency>
52- <groupId>com.datastax.cassandra</groupId>
53- <artifactId>cassandra-driver-mapping</artifactId>
54- <version>2.1.5</version>
55- </dependency>
56-
57-We also provide a [shaded JAR](http://datastax.github.io/java-driver/features/shaded_jar/)
81+```xml
82+<dependency>
83+ <groupId>com.datastax.cassandra</groupId>
84+ <artifactId>cassandra-driver-mapping</artifactId>
85+ <version>2.1.5</version>
86+</dependency>
87+```
88+
89+We also provide a [shaded JAR](features/shaded_jar/)
5890 to avoid the explicit dependency to Netty.
5991
6092 ## Compatibility
@@ -87,10 +119,8 @@
87119 [connection requirements](https://github.com/datastax/java-driver/wiki/Connection-requirements).
88120
89121
90-
91-
92122 ## License
93-Copyright 2012-2014, DataStax
123+Copyright 2012-2015, DataStax
94124
95125 Licensed under the Apache License, Version 2.0 (the "License");
96126 you may not use this file except in compliance with the License.
modified driver-core/CHANGELOG.rst +92 −2
@@ -4,8 +4,38 @@
44 2.1.6:
55 ------
66
7-- [new feature] Add getObject to BoundStatement, Row, UDTValue and TupleValue
8- (JAVA-584)
7+Merged from 2.0 branch:
8+
9+- [new feature] Add getObject to BoundStatement and Row (JAVA-584)
10+- [improvement] Improve connection pool resizing algorithm (JAVA-419)
11+- [bug] Fix race condition between pool expansion and shutdown (JAVA-599)
12+- [improvement] Upgrade Netty to 4.0.27 (JAVA-622)
13+- [improvement] Coalesce frames before flushing them to the connection
14+ (JAVA-562)
15+- [improvement] Rename threads to indicate that they are for the driver
16+ (JAVA-583)
17+- [new feature] Expose paging state (JAVA-550)
18+- [new feature] Slow Query Logger (JAVA-646)
19+- [improvement] Exclude some errors from measurements in LatencyAwarePolicy
20+ (JAVA-698)
21+- [bug] Fix issue when executing a PreparedStatement from another cluster
22+ (JAVA-641)
23+- [improvement] Log keyspace xxx does not exist at WARN level (JAVA-534)
24+- [improvement] Allow Cluster subclasses to delegate to another instance
25+ (JAVA-619)
26+- [new feature] Expose an API to check for schema agreement after a
27+ schema-altering statement (JAVA-669)
28+- [improvement] Make connection and pool creation fully async (JAVA-692)
29+- [improvement] Optimize connection use after reconnection (JAVA-505)
30+- [improvement] Remove "suspected" mechanism (JAVA-617)
31+- [improvement] Don't mark connection defunct on client timeout (reverts
32+ JAVA-425)
33+- [new feature] Speculative query executions (JAVA-561)
34+- [bug] Release connection before completing the ResultSetFuture (JAVA-666)
35+- [new feature BETA] Percentile-based variant of query logger and speculative
36+ executions (JAVA-723)
37+- [bug] Fix buffer leaks when compression is enabled (JAVA-734).
38+- [improvement] Use Netty's pooled ByteBufAllocator by default (JAVA-756)
939
1040
1141 2.1.5:
@@ -190,6 +220,66 @@
190220 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
191221
192222
223+2.0.10:
224+-------
225+
226+- [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
227+- [improvement] Add connection heartbeat (JAVA-533)
228+- [improvement] Reduce level of logs on missing rpc_address (JAVA-568)
229+- [improvement] Expose node token and range information (JAVA-312, JAVA-681)
230+- [bug] Fix cluster name mismatch check at startup (JAVA-595)
231+- [bug] Fix guava dependency when using OSGI (JAVA-620)
232+- [bug] Fix handling of DROP events when ks name is case-sensitive (JAVA-678)
233+- [improvement] Use List<?> instead of List<Object> in QueryBuilder API
234+ (JAVA-631)
235+- [improvement] Exclude Netty POM from META-INF in shaded JAR (JAVA-654)
236+- [bug] Quote single quotes contained in table comments in asCQLQuery method
237+ (JAVA-655)
238+- [bug] Empty TokenRange returned in a one token cluster (JAVA-684)
239+- [improvement] Expose TokenRange#contains (JAVA-687)
240+- [new feature] Expose values of BoundStatement (JAVA-547)
241+- [new feature] Add getObject to BoundStatement and Row (JAVA-584)
242+- [improvement] Improve connection pool resizing algorithm (JAVA-419)
243+- [bug] Fix race condition between pool expansion and shutdown (JAVA-599)
244+- [improvement] Upgrade Netty to 4.0.27 (JAVA-622)
245+- [improvement] Coalesce frames before flushing them to the connection
246+ (JAVA-562)
247+- [improvement] Rename threads to indicate that they are for the driver
248+ (JAVA-583)
249+- [new feature] Expose paging state (JAVA-550)
250+- [new feature] Slow Query Logger (JAVA-646)
251+- [improvement] Exclude some errors from measurements in LatencyAwarePolicy
252+ (JAVA-698)
253+- [bug] Fix issue when executing a PreparedStatement from another cluster
254+ (JAVA-641)
255+- [improvement] Log keyspace xxx does not exist at WARN level (JAVA-534)
256+- [improvement] Allow Cluster subclasses to delegate to another instance
257+ (JAVA-619)
258+- [new feature] Expose an API to check for schema agreement after a
259+ schema-altering statement (JAVA-669)
260+- [improvement] Make connection and pool creation fully async (JAVA-692)
261+- [improvement] Optimize connection use after reconnection (JAVA-505)
262+- [improvement] Remove "suspected" mechanism (JAVA-617)
263+- [improvement] Don't mark connection defunct on client timeout (reverts
264+ JAVA-425)
265+- [new feature] Speculative query executions (JAVA-561)
266+- [bug] Release connection before completing the ResultSetFuture (JAVA-666)
267+- [new feature BETA] Percentile-based variant of query logger and speculative
268+ executions (JAVA-723)
269+- [bug] Fix buffer leaks when compression is enabled (JAVA-734).
270+
271+Merged from 2.0.9_fixes branch:
272+
273+- [bug] Prevent race between cancellation and query completion (JAVA-614)
274+- [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if
275+ streamId was already released and reused (JAVA-632).
276+- [bug] Fix issue when newly opened pool fails before we could mark the node UP
277+ (JAVA-642)
278+- [bug] Fix unwanted LBP notifications when a contact host is down (JAVA-613)
279+- [bug] Fix edge cases where a connection was released twice (JAVA-651).
280+- [bug] Fix edge cases in query cancellation (JAVA-653).
281+
282+
193283 2.0.9.2:
194284 --------
195285
modified driver-core/README.rst +1 −1
@@ -96,5 +96,5 @@
9696 would use this host to discover the other ones and use the whole cluster
9797 automatically. This is also true for new nodes joining the cluster.
9898
99-For now, please refer to the API reference (http://www.datastax.com/drivers/java/apidocs/).
99+For now, please refer to the API reference (http://docs.datastax.com/en/drivers/java/2.0).
100100 More informations and documentation will come later.
modified driver-core/Upgrade_guide_to_2.0.rst +32 −15
@@ -1,21 +1,17 @@
1-Upgrade Guide to 2.0.0
2-======================
3-
4-The purpose of this guide is to detail the changes made by the version 2.0 of
5-the Java Driver that are relevant to an upgrade from version 1.0.
6-
7-We used the opportunity of a major version bump to incorporate your feedback
8-and improve the API, to fix a number of inconsistencies and remove cruft.
9-Unfortunately this means there are some breaking changes, but the new API should
10-be both simpler and more complete.
1+Upgrade Guide to 2.0
2+====================
113
12-The first part goes into the breaking changes made to the API (upgraders from 1.0
13-should review this section carefully), while the second part lists noteworthy
14-but backward incompatible changes.
4+The purpose of this guide is to detail the changes made by version 2.0 of
5+the Java Driver.
156
167
17-Breaking API Changes
18---------------------
8+1.0 to 2.0
9+----------
10+
11+We used the opportunity of a major version bump to incorporate your feedback
12+and improve the API, to fix a number of inconsistencies and remove cruft.
13+Unfortunately this means there are some breaking changes, but the new API should
14+be both simpler and more complete.
1915
2016 The following describes the changes for 2.0 that are breaking changes of the
2117 1.0 API. For ease of use, we distinguish two categories of API changes: the "main"
@@ -156,6 +152,27 @@
156152 class.
157153
158154
155+2.0.10
156+------
157+
158+1. LatencyTracker#update 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+
164+2. SocketOptions#getTcpNoDelay() is now TRUE by default (it was previously undefined).
165+ This reflects the new behavior of Netty (which was upgraded from version 3.9.0 to
166+ 4.0.27): TCP_NODELAY is now turned on by default, instead of depending on the OS
167+ default like in previous versions.
168+
169+3. Netty is not shaded anymore in the default Maven artifact. However we publish a
170+ shaded artifact under a different classifier. See `Using the shaded JAR<http://datastax.github.io/java-driver/features/shaded_jar/>`_
171+ for more information.
172+
173+4. The internal initialization sequence of the Cluster object has been slightly changed:
174+ some fields that were previously initialized in the constructor are now set when
175+ the init() method is called. This is unlikely to affect regular driver users.
159176
160177
161178 Features available only with Cassandra 2.0
modified driver-core/pom.xml +73 −19
@@ -1,17 +1,19 @@
11 <!--
2- Copyright (C) 2012 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.
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
1517 -->
1618 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
1719 <modelVersion>4.0.0</modelVersion>
@@ -26,10 +28,14 @@
2628 <description>A driver for Apache Cassandra 1.2+ that works exclusively with the Cassandra Query Language version 3 (CQL3) and Cassandra's binary protocol.</description>
2729 <url>https://github.com/datastax/java-driver</url>
2830
31+ <properties>
32+ <main.basedir>${project.parent.basedir}</main.basedir>
33+ </properties>
34+
2935 <dependencies>
3036 <dependency>
3137 <groupId>io.netty</groupId>
32- <artifactId>netty</artifactId>
38+ <artifactId>netty-handler</artifactId>
3339 <version>${netty.version}</version>
3440 </dependency>
3541
@@ -64,6 +70,20 @@
6470
6571 <!-- End of compression libraries -->
6672
73+ <dependency>
74+ <groupId>io.netty</groupId>
75+ <artifactId>netty-transport-native-epoll</artifactId>
76+ <version>${netty.version}</version>
77+ <optional>true</optional>
78+ </dependency>
79+
80+ <dependency>
81+ <groupId>org.hdrhistogram</groupId>
82+ <artifactId>HdrHistogram</artifactId>
83+ <version>${hdr.version}</version>
84+ <optional>true</optional>
85+ </dependency>
86+
6787 <dependency>
6888 <groupId>org.testng</groupId>
6989 <artifactId>testng</artifactId>
@@ -98,6 +118,13 @@
98118 </exclusions>
99119 </dependency>
100120
121+ <dependency>
122+ <groupId>org.apache.commons</groupId>
123+ <artifactId>commons-exec</artifactId>
124+ <version>1.3</version>
125+ <scope>test</scope>
126+ </dependency>
127+
101128 </dependencies>
102129
103130 <build>
@@ -162,7 +189,7 @@
162189 <configuration>
163190 <manifestLocation>${project.build.directory}/META-INF-shaded</manifestLocation>
164191 <instructions>
165- <Import-Package><![CDATA[com.google.common.*;version="[14.0,19)",!org.jboss.netty.*,*]]></Import-Package>
192+ <Import-Package><![CDATA[com.google.common.*;version="[14.0,19)",!io.netty.*,*]]></Import-Package>
166193 <Private-Package>com.datastax.shaded.*</Private-Package>
167194 </instructions>
168195 </configuration>
@@ -180,12 +207,15 @@
180207 <shadedArtifactAttached>true</shadedArtifactAttached>
181208 <artifactSet>
182209 <includes>
183- <include>io.netty:netty</include>
210+ <include>io.netty:*</include>
184211 </includes>
212+ <excludes>
213+ <exclude>io.netty:netty-transport-native-epoll</exclude>
214+ </excludes>
185215 </artifactSet>
186216 <relocations>
187217 <relocation>
188- <pattern>org.jboss.netty</pattern>
218+ <pattern>io.netty</pattern>
189219 <shadedPattern>com.datastax.shaded.netty</shadedPattern>
190220 </relocation>
191221 </relocations>
@@ -193,8 +223,17 @@
193223 <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
194224 <resources>
195225 <resource>META-INF/MANIFEST.MF</resource>
196- <resource>META-INF/maven/io.netty/netty/pom.properties</resource>
197- <resource>META-INF/maven/io.netty/netty/pom.xml</resource>
226+ <resource>META-INF/io.netty.versions.properties</resource>
227+ <resource>META-INF/maven/io.netty/netty-buffer/pom.properties</resource>
228+ <resource>META-INF/maven/io.netty/netty-buffer/pom.xml</resource>
229+ <resource>META-INF/maven/io.netty/netty-codec/pom.properties</resource>
230+ <resource>META-INF/maven/io.netty/netty-codec/pom.xml</resource>
231+ <resource>META-INF/maven/io.netty/netty-common/pom.properties</resource>
232+ <resource>META-INF/maven/io.netty/netty-common/pom.xml</resource>
233+ <resource>META-INF/maven/io.netty/netty-handler/pom.properties</resource>
234+ <resource>META-INF/maven/io.netty/netty-handler/pom.xml</resource>
235+ <resource>META-INF/maven/io.netty/netty-transport/pom.properties</resource>
236+ <resource>META-INF/maven/io.netty/netty-transport/pom.xml</resource>
198237 </resources>
199238 </transformer>
200239 <!-- Pick up the alternate manifest that was generated by the alternate execution of the bundle plugin -->
@@ -263,6 +302,9 @@
263302 <ipprefix>${ipprefix}</ipprefix>
264303 <com.datastax.driver.NEW_NODE_DELAY_SECONDS>60</com.datastax.driver.NEW_NODE_DELAY_SECONDS>
265304 </systemPropertyVariables>
305+ <classpathDependencyExcludes>
306+ <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
307+ </classpathDependencyExcludes>
266308 <!--May be needed for debugging-->
267309 <!--<forkMode>never</forkMode>-->
268310 </configuration>
@@ -289,6 +331,9 @@
289331 <cassandra.version>${cassandra.version}</cassandra.version>
290332 <ipprefix>${ipprefix}</ipprefix>
291333 </systemPropertyVariables>
334+ <classpathDependencyExcludes>
335+ <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
336+ </classpathDependencyExcludes>
292337 </configuration>
293338 </plugin>
294339 </plugins>
@@ -313,6 +358,9 @@
313358 <cassandra.version>${cassandra.version}</cassandra.version>
314359 <ipprefix>${ipprefix}</ipprefix>
315360 </systemPropertyVariables>
361+ <classpathDependencyExcludes>
362+ <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
363+ </classpathDependencyExcludes>
316364 </configuration>
317365 </plugin>
318366 </plugins>
@@ -337,6 +385,9 @@
337385 <cassandra.version>${cassandra.version}</cassandra.version>
338386 <ipprefix>${ipprefix}</ipprefix>
339387 </systemPropertyVariables>
388+ <classpathDependencyExcludes>
389+ <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
390+ </classpathDependencyExcludes>
340391 </configuration>
341392 </plugin>
342393 </plugins>
@@ -361,6 +412,9 @@
361412 <cassandra.version>${cassandra.version}</cassandra.version>
362413 <ipprefix>${ipprefix}</ipprefix>
363414 </systemPropertyVariables>
415+ <classpathDependencyExcludes>
416+ <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
417+ </classpathDependencyExcludes>
364418 </configuration>
365419 </plugin>
366420 </plugins>
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +7 −6
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@
2121 import java.util.concurrent.ExecutionException;
2222 import java.util.concurrent.LinkedBlockingDeque;
2323
24-import com.google.common.util.concurrent.Futures;
2524 import com.google.common.util.concurrent.ListenableFuture;
2625 import com.google.common.util.concurrent.SettableFuture;
2726 import com.google.common.util.concurrent.Uninterruptibles;
@@ -29,6 +28,7 @@
2928 import org.slf4j.LoggerFactory;
3029
3130 import com.datastax.driver.core.exceptions.DriverInternalError;
31+import com.datastax.driver.core.utils.MoreFutures;
3232
3333 /**
3434 * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
@@ -183,7 +183,7 @@
183183 }
184184
185185 public ListenableFuture<Void> fetchMoreResults() {
186- return Futures.immediateFuture(null);
186+ return MoreFutures.VOID_SUCCESS;
187187 }
188188
189189 public ExecutionInfo getExecutionInfo() {
@@ -234,7 +234,7 @@
234234 // that this will never change, so apply the generic check by peeking at the first row.
235235 super(metadata, tokenFactory, rows.peek(), protocolVersion);
236236 this.currentPage = rows;
237- this.infos.offer(info);
237+ this.infos.offer(info.withPagingState(pagingState, protocolVersion).withStatement(statement));
238238
239239 this.fetchState = new FetchingState(pagingState, null);
240240 this.session = session;
@@ -293,7 +293,7 @@
293293
294294 private ListenableFuture<Void> fetchMoreResults(FetchingState fetchState) {
295295 if (fetchState == null)
296- return Futures.immediateFuture(null);
296+ return MoreFutures.VOID_SUCCESS;
297297
298298 if (fetchState.inProgress != null)
299299 return fetchState.inProgress;
@@ -328,9 +328,10 @@
328328 case RESULT:
329329 Responses.Result rm = (Responses.Result)response;
330330 info = update(info, rm, MultiPage.this.session);
331-
332331 if (rm.kind == Responses.Result.Kind.ROWS) {
333332 Responses.Result.Rows rows = (Responses.Result.Rows)rm;
333+ if (rows.metadata.pagingState != null)
334+ info = info.withPagingState(rows.metadata.pagingState, protocolVersion).withStatement(statement);
334335 MultiPage.this.nextPages.offer(rows.data);
335336 MultiPage.this.fetchState = rows.metadata.pagingState == null ? null : new FetchingState(rows.metadata.pagingState, null);
336337 } else if (rm.kind == Responses.Result.Kind.VOID) {
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Authenticator.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/BusyConnectionException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/CBUtil.java +37 −33
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -22,19 +22,19 @@
2222 import java.nio.charset.CharacterCodingException;
2323 import java.util.*;
2424
25-import org.jboss.netty.buffer.ChannelBuffer;
26-import org.jboss.netty.util.CharsetUtil;
25+import io.netty.buffer.ByteBuf;
26+import io.netty.util.CharsetUtil;
2727
2828 import com.datastax.driver.core.exceptions.DriverInternalError;
2929
3030 /**
31- * ChannelBuffer utility methods.
31+ * ByteBuf utility methods.
3232 */
33-abstract class CBUtil {
33+abstract class CBUtil { // TODO rename
3434
3535 private CBUtil() {}
3636
37- private static String readString(ChannelBuffer cb, int length) {
37+ private static String readString(ByteBuf cb, int length) {
3838 try {
3939 String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
4040 cb.readerIndex(cb.readerIndex() + length);
@@ -48,7 +48,7 @@
4848 }
4949 }
5050
51- public static String readString(ChannelBuffer cb) {
51+ public static String readString(ByteBuf cb) {
5252 try {
5353 int length = cb.readUnsignedShort();
5454 return readString(cb, length);
@@ -57,7 +57,7 @@
5757 }
5858 }
5959
60- public static void writeString(String str, ChannelBuffer cb) {
60+ public static void writeString(String str, ByteBuf cb) {
6161 byte[] bytes = str.getBytes(CharsetUtil.UTF_8);
6262 cb.writeShort(bytes.length);
6363 cb.writeBytes(bytes);
@@ -82,7 +82,7 @@
8282 return utflen;
8383 }
8484
85- public static String readLongString(ChannelBuffer cb) {
85+ public static String readLongString(ByteBuf cb) {
8686 try {
8787 int length = cb.readInt();
8888 return readString(cb, length);
@@ -91,7 +91,7 @@
9191 }
9292 }
9393
94- public static void writeLongString(String str, ChannelBuffer cb) {
94+ public static void writeLongString(String str, ByteBuf cb) {
9595 byte[] bytes = str.getBytes(CharsetUtil.UTF_8);
9696 cb.writeInt(bytes.length);
9797 cb.writeBytes(bytes);
@@ -101,7 +101,7 @@
101101 return 4 + str.getBytes(CharsetUtil.UTF_8).length;
102102 }
103103
104- public static byte[] readBytes(ChannelBuffer cb) {
104+ public static byte[] readBytes(ByteBuf cb) {
105105 try {
106106 int length = cb.readUnsignedShort();
107107 byte[] bytes = new byte[length];
@@ -112,7 +112,7 @@
112112 }
113113 }
114114
115- public static void writeBytes(byte[] bytes, ChannelBuffer cb) {
115+ public static void writeBytes(byte[] bytes, ByteBuf cb) {
116116 cb.writeShort(bytes.length);
117117 cb.writeBytes(bytes);
118118 }
@@ -121,11 +121,11 @@
121121 return 2 + bytes.length;
122122 }
123123
124- public static ConsistencyLevel readConsistencyLevel(ChannelBuffer cb) {
124+ public static ConsistencyLevel readConsistencyLevel(ByteBuf cb) {
125125 return ConsistencyLevel.fromCode(cb.readUnsignedShort());
126126 }
127127
128- public static void writeConsistencyLevel(ConsistencyLevel consistency, ChannelBuffer cb) {
128+ public static void writeConsistencyLevel(ConsistencyLevel consistency, ByteBuf cb) {
129129 cb.writeShort(consistency.code);
130130 }
131131
@@ -133,7 +133,7 @@
133133 return 2;
134134 }
135135
136- public static <T extends Enum<T>> T readEnumValue(Class<T> enumType, ChannelBuffer cb) {
136+ public static <T extends Enum<T>> T readEnumValue(Class<T> enumType, ByteBuf cb) {
137137 String value = CBUtil.readString(cb);
138138 try {
139139 return Enum.valueOf(enumType, value.toUpperCase());
@@ -142,7 +142,7 @@
142142 }
143143 }
144144
145- public static <T extends Enum<T>> void writeEnumValue(T enumValue, ChannelBuffer cb) {
145+ public static <T extends Enum<T>> void writeEnumValue(T enumValue, ByteBuf cb) {
146146 writeString(enumValue.toString(), cb);
147147 }
148148
@@ -150,13 +150,13 @@
150150 return sizeOfString(enumValue.toString());
151151 }
152152
153- public static UUID readUUID(ChannelBuffer cb) {
153+ public static UUID readUUID(ByteBuf cb) {
154154 long msb = cb.readLong();
155155 long lsb = cb.readLong();
156156 return new UUID(msb, lsb);
157157 }
158158
159- public static void writeUUID(UUID uuid, ChannelBuffer cb) {
159+ public static void writeUUID(UUID uuid, ByteBuf cb) {
160160 cb.writeLong(uuid.getMostSignificantBits());
161161 cb.writeLong(uuid.getLeastSignificantBits());
162162 }
@@ -165,7 +165,7 @@
165165 return 16;
166166 }
167167
168- public static List<String> readStringList(ChannelBuffer cb) {
168+ public static List<String> readStringList(ByteBuf cb) {
169169 int length = cb.readUnsignedShort();
170170 List<String> l = new ArrayList<String>(length);
171171 for (int i = 0; i < length; i++)
@@ -173,7 +173,7 @@
173173 return l;
174174 }
175175
176- public static void writeStringList(List<String> l, ChannelBuffer cb) {
176+ public static void writeStringList(List<String> l, ByteBuf cb) {
177177 cb.writeShort(l.size());
178178 for (String str : l)
179179 writeString(str, cb);
@@ -186,7 +186,7 @@
186186 return size;
187187 }
188188
189- public static Map<String, String> readStringMap(ChannelBuffer cb) {
189+ public static Map<String, String> readStringMap(ByteBuf cb) {
190190 int length = cb.readUnsignedShort();
191191 Map<String, String> m = new HashMap<String, String>(length);
192192 for (int i = 0; i < length; i++) {
@@ -197,7 +197,7 @@
197197 return m;
198198 }
199199
200- public static void writeStringMap(Map<String, String> m, ChannelBuffer cb) {
200+ public static void writeStringMap(Map<String, String> m, ByteBuf cb) {
201201 cb.writeShort(m.size());
202202 for (Map.Entry<String, String> entry : m.entrySet()) {
203203 writeString(entry.getKey(), cb);
@@ -214,7 +214,7 @@
214214 return size;
215215 }
216216
217- public static Map<String, List<String>> readStringToStringListMap(ChannelBuffer cb) {
217+ public static Map<String, List<String>> readStringToStringListMap(ByteBuf cb) {
218218 int length = cb.readUnsignedShort();
219219 Map<String, List<String>> m = new HashMap<String, List<String>>(length);
220220 for (int i = 0; i < length; i++) {
@@ -225,7 +225,7 @@
225225 return m;
226226 }
227227
228- public static void writeStringToStringListMap(Map<String, List<String>> m, ChannelBuffer cb) {
228+ public static void writeStringToStringListMap(Map<String, List<String>> m, ByteBuf cb) {
229229 cb.writeShort(m.size());
230230 for (Map.Entry<String, List<String>> entry : m.entrySet()) {
231231 writeString(entry.getKey(), cb);
@@ -242,12 +242,16 @@
242242 return size;
243243 }
244244
245- public static ByteBuffer readValue(ChannelBuffer cb) {
245+ public static ByteBuffer readValue(ByteBuf cb) {
246246 int length = cb.readInt();
247- return length < 0 ? null : cb.readSlice(length).toByteBuffer();
247+ if (length < 0)
248+ return null;
249+ ByteBuf slice = cb.readSlice(length);
250+
251+ return ByteBuffer.wrap(readRawBytes(slice));
248252 }
249253
250- public static void writeValue(byte[] bytes, ChannelBuffer cb) {
254+ public static void writeValue(byte[] bytes, ByteBuf cb) {
251255 if (bytes == null) {
252256 cb.writeInt(-1);
253257 return;
@@ -257,7 +261,7 @@
257261 cb.writeBytes(bytes);
258262 }
259263
260- public static void writeValue(ByteBuffer bytes, ChannelBuffer cb) {
264+ public static void writeValue(ByteBuffer bytes, ByteBuf cb) {
261265 if (bytes == null) {
262266 cb.writeInt(-1);
263267 return;
@@ -275,7 +279,7 @@
275279 return 4 + (bytes == null ? 0 : bytes.remaining());
276280 }
277281
278- public static List<ByteBuffer> readValueList(ChannelBuffer cb) {
282+ public static List<ByteBuffer> readValueList(ByteBuf cb) {
279283 int size = cb.readUnsignedShort();
280284 if (size == 0)
281285 return Collections.<ByteBuffer>emptyList();
@@ -286,7 +290,7 @@
286290 return l;
287291 }
288292
289- public static void writeValueList(List<ByteBuffer> values, ChannelBuffer cb) {
293+ public static void writeValueList(List<ByteBuffer> values, ByteBuf cb) {
290294 cb.writeShort(values.size());
291295 for (ByteBuffer value : values)
292296 CBUtil.writeValue(value, cb);
@@ -299,7 +303,7 @@
299303 return size;
300304 }
301305
302- public static InetSocketAddress readInet(ChannelBuffer cb) {
306+ public static InetSocketAddress readInet(ByteBuf cb) {
303307 int addrSize = cb.readByte();
304308 byte[] address = new byte[addrSize];
305309 cb.readBytes(address);
@@ -311,7 +315,7 @@
311315 }
312316 }
313317
314- public static void writeInet(InetSocketAddress inet, ChannelBuffer cb) {
318+ public static void writeInet(InetSocketAddress inet, ByteBuf cb) {
315319 byte[] address = inet.getAddress().getAddress();
316320
317321 cb.writeByte(address.length);
@@ -328,7 +332,7 @@
328332 * Reads *all* readable bytes from {@code cb} and return them.
329333 * If {@code cb} is backed by an array, this will return the underlying array directly, without copy.
330334 */
331- public static byte[] readRawBytes(ChannelBuffer cb) {
335+ public static byte[] readRawBytes(ByteBuf cb) {
332336 if (cb.hasArray() && cb.readableBytes() == cb.array().length) {
333337 // Move the readerIndex just so we consistently consume the input
334338 cb.readerIndex(cb.writerIndex());
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/CloseFuture.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +387 −367
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.annotations.VisibleForTesting;
29+import com.google.common.base.Objects;
2930 import com.google.common.base.Predicates;
3031 import com.google.common.collect.*;
3132 import com.google.common.util.concurrent.*;
@@ -218,6 +219,7 @@
218219 * @return a new, non-initialized session on this cluster.
219220 */
220221 public Session newSession() {
222+ checkNotClosed(manager);
221223 return manager.newSession();
222224 }
223225
@@ -242,6 +244,7 @@
242244 * Cluster.
243245 */
244246 public Session connect() {
247+ checkNotClosed(manager);
245248 init();
246249 Session session = manager.newSession();
247250 session.init();
@@ -351,6 +354,7 @@
351354 * returns {@code null}).
352355 */
353356 public Metrics getMetrics() {
357+ checkNotClosed(manager);
354358 return manager.metrics;
355359 }
356360
@@ -369,6 +373,7 @@
369373 * @return this {@code Cluster} object;
370374 */
371375 public Cluster register(Host.StateListener listener) {
376+ checkNotClosed(manager);
372377 manager.listeners.add(listener);
373378 return this;
374379 }
@@ -383,6 +388,7 @@
383388 * @return this {@code Cluster} object;
384389 */
385390 public Cluster unregister(Host.StateListener listener) {
391+ checkNotClosed(manager);
386392 manager.listeners.remove(listener);
387393 return this;
388394 }
@@ -407,6 +413,7 @@
407413 * @return this {@code Cluster} object;
408414 */
409415 public Cluster register(LatencyTracker tracker) {
416+ checkNotClosed(manager);
410417 manager.trackers.add(tracker);
411418 return this;
412419 }
@@ -422,6 +429,7 @@
422429 * @return this {@code Cluster} object;
423430 */
424431 public Cluster unregister(LatencyTracker tracker) {
432+ checkNotClosed(manager);
425433 manager.trackers.remove(tracker);
426434 return this;
427435 }
@@ -480,6 +488,11 @@
480488 return manager.closeFuture.get() != null;
481489 }
482490
491+ private static void checkNotClosed(Manager manager) {
492+ if (manager.isClosed())
493+ throw new IllegalStateException("Can't use this cluster instance because it was previously closed");
494+ }
495+
483496 /**
484497 * Initializer for {@link Cluster} instances.
485498 * <p>
@@ -560,6 +573,7 @@
560573 private RetryPolicy retryPolicy;
561574 private AddressTranslater addressTranslater;
562575 private TimestampGenerator timestampGenerator;
576+ private SpeculativeExecutionPolicy speculativeExecutionPolicy;
563577
564578 private ProtocolOptions.Compression compression = ProtocolOptions.Compression.NONE;
565579 private SSLOptions sslOptions = null;
@@ -570,6 +584,8 @@
570584 private SocketOptions socketOptions;
571585 private QueryOptions queryOptions;
572586
587+ private NettyOptions nettyOptions = NettyOptions.DEFAULT_INSTANCE;
588+
573589 private Collection<Host.StateListener> listeners;
574590
575591
@@ -658,7 +674,7 @@
658674 * <p>
659675 * By default, the driver will "auto-detect" which protocol version it can use
660676 * when connecting to the first node. More precisely, it will try first with
661- * {@value ProtocolVersion.NEWEST_SUPPORTED}, and if not supported fallback to
677+ * {@link ProtocolVersion#NEWEST_SUPPORTED}, and if not supported fallback to
662678 * the highest version supported by the first node it connects to. Please note
663679 * that once the version is "auto-detected", it won't change: if the first node
664680 * the driver connects to is a Cassandra 1.2 node and auto-detection is used
@@ -877,7 +893,7 @@
877893 * Configures the address translater to use for the new cluster.
878894 * <p>
879895 * See {@link AddressTranslater} for more detail on address translation,
880- * but the default tanslater, {@link IdentityTranslater}, should be
896+ * but the default translater, {@link IdentityTranslater}, should be
881897 * correct in most cases. If unsure, stick to the default.
882898 *
883899 * @param translater the translater to use.
@@ -908,6 +924,20 @@
908924 return this;
909925 }
910926
927+ /**
928+ * Configures the speculative execution policy to use for the new cluster.
929+ * <p>
930+ * If no policy is set through this method, {@link Policies#defaultSpeculativeExecutionPolicy()}
931+ * will be used instead.
932+ *
933+ * @param policy the policy to use.
934+ * @return this Builder.
935+ */
936+ public Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy) {
937+ this.speculativeExecutionPolicy = policy;
938+ return this;
939+ }
940+
911941 /**
912942 * Uses the provided credentials when connecting to Cassandra hosts.
913943 * <p>
@@ -1066,6 +1096,20 @@
10661096 return this;
10671097 }
10681098
1099+ /**
1100+ * Set the {@link NettyOptions} to use for the newly created Cluster.
1101+ * <p>
1102+ * If no Netty options are set through this method, {@link NettyOptions#DEFAULT_INSTANCE}
1103+ * will be used as a default value, which means that no customization will be applied.
1104+ *
1105+ * @param nettyOptions the {@link NettyOptions} to use.
1106+ * @return this builder.
1107+ */
1108+ public Builder withNettyOptions(NettyOptions nettyOptions) {
1109+ this.nettyOptions = nettyOptions;
1110+ return this;
1111+ }
1112+
10691113 /**
10701114 * The configuration that will be used for the new cluster.
10711115 * <p>
@@ -1079,17 +1123,19 @@
10791123 public Configuration getConfiguration() {
10801124 Policies policies = new Policies(
10811125 loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
1082- reconnectionPolicy == null ? Policies.defaultReconnectionPolicy() : reconnectionPolicy,
1083- retryPolicy == null ? Policies.defaultRetryPolicy() : retryPolicy,
1084- addressTranslater == null ? Policies.defaultAddressTranslater() : addressTranslater,
1085- timestampGenerator == null ? Policies.defaultTimestampGenerator() : timestampGenerator
1126+ Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
1127+ Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
1128+ Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()),
1129+ Objects.firstNonNull(timestampGenerator, Policies.defaultTimestampGenerator()),
1130+ Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy())
10861131 );
10871132 return new Configuration(policies,
10881133 new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
10891134 poolingOptions == null ? new PoolingOptions() : poolingOptions,
10901135 socketOptions == null ? new SocketOptions() : socketOptions,
10911136 metricsEnabled ? new MetricsOptions(jmxEnabled) : null,
1092- queryOptions == null ? new QueryOptions() : queryOptions);
1137+ queryOptions == null ? new QueryOptions() : queryOptions,
1138+ nettyOptions);
10931139 }
10941140
10951141 @Override
@@ -1110,10 +1156,6 @@
11101156 }
11111157 }
11121158
1113- private static ThreadFactory threadFactory(String nameFormat) {
1114- return new ThreadFactoryBuilder().setNameFormat(nameFormat).build();
1115- }
1116-
11171159 static long timeSince(long startNanos, TimeUnit destUnit) {
11181160 return destUnit.convert(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
11191161 }
@@ -1122,18 +1164,6 @@
11221164 return "cluster" + CLUSTER_ID.incrementAndGet();
11231165 }
11241166
1125- private static ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
1126- ThreadPoolExecutor executor = new ThreadPoolExecutor(threads,
1127- threads,
1128- DEFAULT_THREAD_KEEP_ALIVE,
1129- TimeUnit.SECONDS,
1130- workQueue,
1131- threadFactory(name));
1132-
1133- executor.allowCoreThreadTimeOut(true);
1134- return MoreExecutors.listeningDecorator(executor);
1135- }
1136-
11371167 /**
11381168 * The sessions and hosts managed by this a Cluster instance.
11391169 * <p>
@@ -1151,33 +1181,31 @@
11511181 final List<InetSocketAddress> contactPoints;
11521182 final Set<SessionManager> sessions = new CopyOnWriteArraySet<SessionManager>();
11531183
1154- final Metadata metadata;
1184+ Metadata metadata;
11551185 final Configuration configuration;
1156- final Metrics metrics;
1186+ Metrics metrics;
11571187
1158- final Connection.Factory connectionFactory;
1159- final ControlConnection controlConnection;
1188+ Connection.Factory connectionFactory;
1189+ ControlConnection controlConnection;
11601190
11611191 final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.Simple.Factory();
11621192
1163- final ScheduledThreadPoolExecutor reconnectionExecutor = new ScheduledThreadPoolExecutor(2, threadFactory("Reconnection-%d"));
1164- // scheduledTasksExecutor is used to process C* notifications. So having it mono-threaded ensures notifications are
1165- // applied in the order received.
1166- final ScheduledThreadPoolExecutor scheduledTasksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory("Scheduled Tasks-%d"));
1193+ ScheduledThreadPoolExecutor reconnectionExecutor;
1194+ ScheduledThreadPoolExecutor scheduledTasksExecutor;
11671195
11681196 // Executor used for tasks that shouldn't be executed on an IO thread. Used for short-lived, generally non-blocking tasks
1169- final ListeningExecutorService executor;
1197+ ListeningExecutorService executor;
11701198
11711199 // Work Queue used by executor.
1172- final LinkedBlockingQueue<Runnable> executorQueue = new LinkedBlockingQueue<Runnable>();
1200+ LinkedBlockingQueue<Runnable> executorQueue;
11731201
11741202 // An executor for tasks that might block some time, like creating new connection, but are generally not too critical.
1175- final ListeningExecutorService blockingExecutor;
1203+ ListeningExecutorService blockingExecutor;
11761204
11771205 // Work Queue used by blockingExecutor.
1178- final LinkedBlockingQueue<Runnable> blockingExecutorQueue = new LinkedBlockingQueue<Runnable>();
1206+ LinkedBlockingQueue<Runnable> blockingExecutorQueue;
11791207
1180- final ConnectionReaper reaper;
1208+ ConnectionReaper reaper;
11811209
11821210 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
11831211
@@ -1185,41 +1213,49 @@
11851213 // new one join the cluster).
11861214 // Note: we could move this down to the session level, but since prepared statement are global to a node,
11871215 // this would yield a slightly less clear behavior.
1188- final ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries = new MapMaker().weakValues().makeMap();
1216+ ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries;
11891217
11901218 final Set<Host.StateListener> listeners;
11911219 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
11921220
11931221 private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) {
1194- logger.debug("Starting new cluster with contact points " + contactPoints);
1195-
11961222 this.clusterName = clusterName == null ? generateClusterName() : clusterName;
11971223 this.configuration = configuration;
1198- this.configuration.register(this);
1199-
1200- this.executor = makeExecutor(NON_BLOCKING_EXECUTOR_SIZE, "Cassandra Java Driver worker-%d", executorQueue);
1201- this.blockingExecutor = makeExecutor(2, "Cassandra Java Driver blocking tasks worker-%d", blockingExecutorQueue);
1202-
1203- this.reaper = new ConnectionReaper();
1204-
1205- this.metadata = new Metadata(this);
12061224 this.contactPoints = contactPoints;
1207- this.connectionFactory = new Connection.Factory(this, configuration);
1208- this.controlConnection = new ControlConnection(this);
1209-
1210- this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
12111225 this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners);
12121226 }
12131227
12141228 // Initialization is not too performance intensive and in practice there shouldn't be contention
12151229 // on it so synchronized is good enough.
12161230 synchronized void init() {
1217- if (isClosed())
1218- throw new IllegalStateException("Can't use this Cluster instance because it was previously closed");
1231+ checkNotClosed(this);
12191232 if (isInit)
12201233 return;
12211234 isInit = true;
12221235
1236+ logger.debug("Starting new cluster with contact points " + contactPoints);
1237+
1238+ this.configuration.register(this);
1239+
1240+ this.executorQueue = new LinkedBlockingQueue<Runnable>();
1241+ this.executor = makeExecutor(NON_BLOCKING_EXECUTOR_SIZE, "worker", executorQueue);
1242+ this.blockingExecutorQueue = new LinkedBlockingQueue<Runnable>();
1243+ this.blockingExecutor = makeExecutor(2, "blocking-task-worker", blockingExecutorQueue);
1244+ this.reconnectionExecutor = new ScheduledThreadPoolExecutor(2, threadFactory("reconnection"));
1245+ // scheduledTasksExecutor is used to process C* notifications. So having it mono-threaded ensures notifications are
1246+ // applied in the order received.
1247+ this.scheduledTasksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory("scheduled-task-worker"));
1248+
1249+ this.reaper = new ConnectionReaper(this);
1250+ this.metadata = new Metadata(this);
1251+ this.connectionFactory = new Connection.Factory(this, configuration);
1252+ this.controlConnection = new ControlConnection(this);
1253+ this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
1254+ this.preparedQueries = new MapMaker().weakValues().makeMap();
1255+
1256+ this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
1257+
1258+
12231259 for (InetSocketAddress address : contactPoints) {
12241260 // We don't want to signal -- call onAdd() -- because nothing is ready
12251261 // yet (loadbalancing policy, control connection, ...). All we want is
@@ -1295,6 +1331,22 @@
12951331 return connectionFactory.protocolVersion;
12961332 }
12971333
1334+ ThreadFactory threadFactory(String name) {
1335+ return new ThreadFactoryBuilder().setNameFormat(clusterName + "-" + name + "-%d").build();
1336+ }
1337+
1338+ private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
1339+ ThreadPoolExecutor executor = new ThreadPoolExecutor(threads,
1340+ threads,
1341+ DEFAULT_THREAD_KEEP_ALIVE,
1342+ TimeUnit.SECONDS,
1343+ workQueue,
1344+ threadFactory(name));
1345+
1346+ executor.allowCoreThreadTimeOut(true);
1347+ return MoreExecutors.listeningDecorator(executor);
1348+ }
1349+
12981350 Cluster getCluster() {
12991351 return Cluster.this;
13001352 }
@@ -1303,6 +1355,10 @@
13031355 return configuration.getPolicies().getLoadBalancingPolicy();
13041356 }
13051357
1358+ SpeculativeExecutionPolicy speculativeRetryPolicy() {
1359+ return configuration.getPolicies().getSpeculativeExecutionPolicy();
1360+ }
1361+
13061362 ReconnectionPolicy reconnectionPolicy() {
13071363 return configuration.getPolicies().getReconnectionPolicy();
13081364 }
@@ -1323,9 +1379,9 @@
13231379 return sessions.remove(session);
13241380 }
13251381
1326- void reportLatency(Host host, long latencyNanos) {
1382+ void reportLatency(Host host, Statement statement, Exception exception, long latencyNanos) {
13271383 for (LatencyTracker tracker : trackers) {
1328- tracker.update(host, latencyNanos);
1384+ tracker.update(host, statement, exception, latencyNanos);
13291385 }
13301386 }
13311387
@@ -1339,42 +1395,46 @@
13391395 if (future != null)
13401396 return future;
13411397
1342- logger.debug("Shutting down");
1343-
1344- // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
1345- // delivery or blocking tasks so we use shutdownNow
1346- shutdownNow(reconnectionExecutor);
1347- shutdownNow(scheduledTasksExecutor);
1348- shutdownNow(blockingExecutor);
1349-
1350- // but for the worker executor, we want to let submitted tasks finish unless the shutdown is forced.
1351- executor.shutdown();
1352-
1353- // We also close the metrics
1354- if (metrics != null)
1355- metrics.shutdown();
1356-
1357- // And the load balancing policy
1358- LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy();
1359- if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
1360- ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
1361-
1362- AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1363- if (translater instanceof CloseableAddressTranslater)
1364- ((CloseableAddressTranslater)translater).close();
1365-
1366- // Then we shutdown all connections
1367- List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
1368- futures.add(controlConnection.closeAsync());
1369- for (Session session : sessions)
1370- futures.add(session.closeAsync());
1371-
1372- future = new ClusterCloseFuture(futures);
1398+ if (isInit) {
1399+ logger.debug("Shutting down");
1400+
1401+ // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
1402+ // delivery or blocking tasks so we use shutdownNow
1403+ shutdownNow(reconnectionExecutor);
1404+ shutdownNow(scheduledTasksExecutor);
1405+ shutdownNow(blockingExecutor);
1406+
1407+ // but for the worker executor, we want to let submitted tasks finish unless the shutdown is forced.
1408+ executor.shutdown();
1409+
1410+ // We also close the metrics
1411+ if (metrics != null)
1412+ metrics.shutdown();
1413+
1414+ // And the load balancing policy
1415+ LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy();
1416+ if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
1417+ ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
1418+
1419+ AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1420+ if (translater instanceof CloseableAddressTranslater)
1421+ ((CloseableAddressTranslater)translater).close();
1422+
1423+ // Then we shutdown all connections
1424+ List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
1425+ futures.add(controlConnection.closeAsync());
1426+ for (Session session : sessions)
1427+ futures.add(session.closeAsync());
1428+
1429+ future = new ClusterCloseFuture(futures);
1430+ // The rest will happen asynchronously, when all connections are successfully closed
1431+ } else {
1432+ future = CloseFuture.immediateFuture();
1433+ }
13731434
1374- // The rest will happen asynchronously, when all connections are successfully closed
13751435 return closeFuture.compareAndSet(null, future)
1376- ? future
1377- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
1436+ ? future
1437+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
13781438 }
13791439
13801440 private void shutdownNow(ExecutorService executor) {
@@ -1402,21 +1462,13 @@
14021462 return executor.submit(new ExceptionCatchingRunnable() {
14031463 @Override
14041464 public void runMayThrow() throws InterruptedException, ExecutionException {
1405- onUp(host);
1465+ onUp(host, null);
14061466 }
14071467 });
14081468 }
14091469
1410- private void onUp(final Host host) throws InterruptedException, ExecutionException {
1411- // Note that in generalize we can parallelize the pool creation on
1412- // each session, but we shouldn't use executor since we're already
1413- // running on it most probably (and so we could deadlock). Use the
1414- // blockingExecutor instead, that's why it's for.
1415- onUp(host, blockingExecutor);
1416- }
1417-
14181470 // Use triggerOnUp unless you're sure you want to run this on the current thread.
1419- private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
1471+ private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
14201472 logger.debug("Host {} is UP", host);
14211473
14221474 if (isClosed())
@@ -1427,59 +1479,61 @@
14271479 return;
14281480 }
14291481
1430- boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1431- if (!locked) {
1432- logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1433- return;
1434- }
14351482 try {
1436-
1437- // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1438- if (host.state == Host.State.UP)
1439- return;
1440-
1441- // If there is a reconnection attempt scheduled for that node, cancel it
1442- Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1443- if (scheduledAttempt != null) {
1444- logger.debug("Cancelling reconnection attempt since node is UP");
1445- scheduledAttempt.cancel(false);
1446- }
14471483
1448- try {
1449- prepareAllQueries(host);
1450- } catch (InterruptedException e) {
1451- Thread.currentThread().interrupt();
1452- // Don't propagate because we don't want to prevent other listener to run
1453- } catch (UnsupportedProtocolVersionException e) {
1454- logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1455- return;
1456- } catch (ClusterNameMismatchException e) {
1457- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1484+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1485+ if (!locked) {
1486+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
14581487 return;
14591488 }
1489+ try {
1490+
1491+ // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1492+ if (host.state == Host.State.UP)
1493+ return;
14601494
1461- // Session#onUp() expects the load balancing policy to have been updated first, so that
1462- // Host distances are up to date. This mean the policy could return the node before the
1463- // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1464- // will ignore the node, but we do want to make sure there is no prior pool so we don't
1465- // query from a pool we will shutdown right away.
1466- for (SessionManager s : sessions)
1467- s.removePool(host);
1468- loadBalancingPolicy().onUp(host);
1469- controlConnection.onUp(host);
1495+ // If there is a reconnection attempt scheduled for that node, cancel it
1496+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1497+ if (scheduledAttempt != null) {
1498+ logger.debug("Cancelling reconnection attempt since node is UP");
1499+ scheduledAttempt.cancel(false);
1500+ }
1501+
1502+ try {
1503+ reusedConnection = prepareAllQueries(host, reusedConnection);
1504+ } catch (InterruptedException e) {
1505+ Thread.currentThread().interrupt();
1506+ // Don't propagate because we don't want to prevent other listener to run
1507+ } catch (UnsupportedProtocolVersionException e) {
1508+ logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1509+ return;
1510+ } catch (ClusterNameMismatchException e) {
1511+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1512+ return;
1513+ }
14701514
1471- logger.trace("Adding/renewing host pools for newly UP host {}", host);
1515+ // Session#onUp() expects the load balancing policy to have been updated first, so that
1516+ // Host distances are up to date. This mean the policy could return the node before the
1517+ // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1518+ // will ignore the node, but we do want to make sure there is no prior pool so we don't
1519+ // query from a pool we will shutdown right away.
1520+ for (SessionManager s : sessions)
1521+ s.removePool(host);
1522+ loadBalancingPolicy().onUp(host);
1523+ controlConnection.onUp(host);
1524+
1525+ logger.trace("Adding/renewing host pools for newly UP host {}", host);
1526+
1527+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1528+ for (SessionManager s : sessions)
1529+ futures.add(s.forceRenewPool(host, reusedConnection));
1530+
1531+ try {
1532+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1533+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1534+ // to the node.
1535+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
14721536
1473- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1474- for (SessionManager s : sessions)
1475- futures.add(s.forceRenewPool(host, poolCreationExecutor));
1476-
1477- // Only mark the node up once all session have re-added their pool (if the load-balancing
1478- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1479- // to the node.
1480- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1481- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1482- public void onSuccess(List<Boolean> poolCreationResults) {
14831537 // If any of the creation failed, they will have signaled a connection failure
14841538 // which will trigger a reconnection to the node. So don't bother marking UP.
14851539 if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
@@ -1491,24 +1545,26 @@
14911545
14921546 for (Host.StateListener listener : listeners)
14931547 listener.onUp(host);
1494- }
14951548
1496- public void onFailure(Throwable t) {
1549+ } catch (ExecutionException e) {
1550+ Throwable t = e.getCause();
14971551 // That future is not really supposed to throw unexpected exceptions
14981552 if (!(t instanceof InterruptedException))
14991553 logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
15001554 }
1501- });
15021555
1503- f.get();
1556+ // Now, check if there isn't pools to create/remove following the addition.
1557+ // We do that now only so that it's not called before we've set the node up.
1558+ for (SessionManager s : sessions)
1559+ s.updateCreatedPools();
15041560
1505- // Now, check if there isn't pools to create/remove following the addition.
1506- // We do that now only so that it's not called before we've set the node up.
1507- for (SessionManager s : sessions)
1508- s.updateCreatedPools(blockingExecutor);
1561+ } finally {
1562+ host.notificationsLock.unlock();
1563+ }
15091564
15101565 } finally {
1511- host.notificationsLock.unlock();
1566+ if (reusedConnection != null && !reusedConnection.hasPool())
1567+ reusedConnection.closeAsync();
15121568 }
15131569 }
15141570
@@ -1520,78 +1576,13 @@
15201576 return executor.submit(new ExceptionCatchingRunnable() {
15211577 @Override
15221578 public void runMayThrow() throws InterruptedException, ExecutionException {
1523- onDown(host, isHostAddition, false, startReconnection);
1579+ onDown(host, isHostAddition, startReconnection);
15241580 }
15251581 });
15261582 }
15271583
1528- public void onSuspected(final Host host) {
1529- logger.debug("Host {} is Suspected", host);
1530-
1531- if (isClosed())
1532- return;
1533-
1534- // We shouldn't really get there for IGNORED nodes since we shouldn't have
1535- // connected to one in the first place, but if we ever do, simply hand it
1536- // off to onDown
1537- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1538- triggerOnDown(host, true);
1539- return;
1540- }
1541-
1542- // We need to
1543- // 1) mark the node suspect if no-one has bitten us to it
1544- // 2) start the reconnection attempt
1545- // 3) inform the loadbalancing policy
1546- // We must do 2) before 3) as we want the policy to be able to rely
1547- // on the reconnection attempt future.
1548- //
1549- // If multiple threads get there, we want to start reconnection attempts only
1550- // once, but we also don't want said threads to return from this method before
1551- // the loadbalancing policy has been informed (otherwise those threads won't
1552- // consider the host suspect but simply ignore it). So we synchronize.
1553- synchronized (host) {
1554- // If we've already marked the node down/suspected, ignore this
1555- if (!host.setSuspected() || host.reconnectionAttempt.get() != null)
1556- return;
1557-
1558- // Start the initial initial reconnection attempt
1559- host.initialReconnectionAttempt.set(executor.submit(new ExceptionCatchingRunnable() {
1560- @Override
1561- public void runMayThrow() throws InterruptedException, ExecutionException {
1562- boolean success;
1563- try {
1564- // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection
1565- connectionFactory.open(host).closeAsync();
1566- // Note that we want to do the pool creation on this thread because we want that
1567- // when onUp return, the host is ready for querying
1568- onUp(host, MoreExecutors.sameThreadExecutor());
1569- // If one of the connections in onUp failed, it signaled the error and triggerd onDown,
1570- // but onDown aborted because this reconnection attempt was in progress (JAVA-577).
1571- // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was
1572- // executed synchronously).
1573- success = host.state == Host.State.UP;
1574- } catch (Exception e) {
1575- success = false;
1576- }
1577- if (!success)
1578- onDown(host, false, true, true);
1579- }
1580- }));
1581-
1582- loadBalancingPolicy().onSuspected(host);
1583- }
1584-
1585- controlConnection.onSuspected(host);
1586- for (SessionManager s : sessions)
1587- s.onSuspected(host);
1588-
1589- for (Host.StateListener listener : listeners)
1590- listener.onSuspected(host);
1591- }
1592-
15931584 // Use triggerOnDown unless you're sure you want to run this on the current thread.
1594- private void onDown(final Host host, final boolean isHostAddition, final boolean isSuspectedVerification, boolean startReconnection) throws InterruptedException, ExecutionException {
1585+ private void onDown(final Host host, final boolean isHostAddition, boolean startReconnection) throws InterruptedException, ExecutionException {
15951586 logger.debug("Host {} is DOWN", host);
15961587
15971588 if (isClosed())
@@ -1604,14 +1595,6 @@
16041595 }
16051596 try {
16061597
1607- // If we're SUSPECT and not the task validating the suspicion, then some other task is
1608- // already checking to verify if the node is really down (or if it's simply that the
1609- // connections where broken). So just skip this in that case.
1610- if (!isSuspectedVerification && host.state == Host.State.SUSPECT) {
1611- logger.debug("Aborting onDown because a reconnection is running on SUSPECT host {}", host);
1612- return;
1613- }
1614-
16151598 // Note: we don't want to skip that method if !host.isUp() because we set isUp
16161599 // late in onUp, and so we can rely on isUp if there is an error during onUp.
16171600 // But if there is a reconnection attempt in progress already, then we know
@@ -1647,7 +1630,6 @@
16471630 if (distance == HostDistance.IGNORED || !startReconnection)
16481631 return;
16491632
1650- // Note: we basically waste the first successful reconnection, but it's probably not a big deal
16511633 logger.debug("{} is down, scheduling connection retries", host);
16521634 startPeriodicReconnectionAttempt(host, isHostAddition);
16531635 } finally {
@@ -1663,19 +1645,15 @@
16631645 }
16641646
16651647 protected void onReconnection(Connection connection) {
1666- // We don't use that first connection so close it.
1667- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1668- // we use it for the first HostConnectionPool created
1669- connection.closeAsync();
16701648 // Make sure we have up-to-date infos on that host before adding it (so we typically
16711649 // catch that an upgraded node uses a new cassandra version).
16721650 if (controlConnection.refreshNodeInfo(host)) {
16731651 logger.debug("Successful reconnection to {}, setting host UP", host);
16741652 try {
16751653 if (isHostAddition)
1676- onAdd(host);
1654+ onAdd(host, connection);
16771655 else
1678- onUp(host);
1656+ onUp(host, connection);
16791657 } catch (InterruptedException e) {
16801658 Thread.currentThread().interrupt();
16811659 } catch (Exception e) {
@@ -1683,6 +1661,7 @@
16831661 }
16841662 } else {
16851663 logger.debug("Not enough info for {}, ignoring host", host);
1664+ connection.closeAsync();
16861665 }
16871666 }
16881667
@@ -1719,16 +1698,12 @@
17191698 }
17201699
17211700 protected void onReconnection(Connection connection) {
1722- // We don't use that first connection so close it.
1723- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1724- // we use it for the first HostConnectionPool created
1725- connection.closeAsync();
17261701 // Make sure we have up-to-date infos on that host before adding it (so we typically
17271702 // catch that an upgraded node uses a new cassandra version).
17281703 if (controlConnection.refreshNodeInfo(host)) {
17291704 logger.debug("Successful reconnection to {}, setting host UP", host);
17301705 try {
1731- onUp(host);
1706+ onUp(host, connection);
17321707 } catch (InterruptedException e) {
17331708 Thread.currentThread().interrupt();
17341709 } catch (Exception e) {
@@ -1736,6 +1711,7 @@
17361711 }
17371712 } else {
17381713 logger.debug("Not enough info for {}, ignoring host", host);
1714+ connection.closeAsync();
17391715 }
17401716 }
17411717
@@ -1761,13 +1737,13 @@
17611737 return executor.submit(new ExceptionCatchingRunnable() {
17621738 @Override
17631739 public void runMayThrow() throws InterruptedException, ExecutionException {
1764- onAdd(host);
1740+ onAdd(host, null);
17651741 }
17661742 });
17671743 }
17681744
17691745 // Use triggerOnAdd unless you're sure you want to run this on the current thread.
1770- private void onAdd(final Host host) throws InterruptedException, ExecutionException {
1746+ private void onAdd(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
17711747 if (isClosed())
17721748 return;
17731749
@@ -1778,55 +1754,57 @@
17781754 return;
17791755 }
17801756
1781- boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1782- if (!locked) {
1783- logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1784- return;
1785- }
17861757 try {
17871758
1788- // Adds to the load balancing first and foremost, as doing so might change the decision
1789- // it will make for distance() on that node (not likely but we leave that possibility).
1790- // This does mean the policy may start returning that node for query plan, but as long
1791- // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1792- loadBalancingPolicy().onAdd(host);
1793-
1794- // Next, if the host should be ignored, well, ignore it.
1795- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1796- // We still mark the node UP though as it should be (and notifiy the listeners).
1797- // We'll mark it down if we have a notification anyway and we've documented that especially
1798- // for IGNORED hosts, the isUp() method was a best effort guess
1799- host.setUp();
1800- for (Host.StateListener listener : listeners)
1801- listener.onAdd(host);
1759+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1760+ if (!locked) {
1761+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
18021762 return;
18031763 }
1804-
18051764 try {
1806- prepareAllQueries(host);
1807- } catch (InterruptedException e) {
1808- Thread.currentThread().interrupt();
1809- // Don't propagate because we don't want to prevent other listener to run
1810- } catch (UnsupportedProtocolVersionException e) {
1811- logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1812- return;
1813- } catch (ClusterNameMismatchException e) {
1814- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1815- return;
1816- }
18171765
1818- controlConnection.onAdd(host);
1766+ // Adds to the load balancing first and foremost, as doing so might change the decision
1767+ // it will make for distance() on that node (not likely but we leave that possibility).
1768+ // This does mean the policy may start returning that node for query plan, but as long
1769+ // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1770+ loadBalancingPolicy().onAdd(host);
1771+
1772+ // Next, if the host should be ignored, well, ignore it.
1773+ if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1774+ // We still mark the node UP though as it should be (and notifiy the listeners).
1775+ // We'll mark it down if we have a notification anyway and we've documented that especially
1776+ // for IGNORED hosts, the isUp() method was a best effort guess
1777+ host.setUp();
1778+ for (Host.StateListener listener : listeners)
1779+ listener.onAdd(host);
1780+ return;
1781+ }
1782+
1783+ try {
1784+ reusedConnection = prepareAllQueries(host, reusedConnection);
1785+ } catch (InterruptedException e) {
1786+ Thread.currentThread().interrupt();
1787+ // Don't propagate because we don't want to prevent other listener to run
1788+ } catch (UnsupportedProtocolVersionException e) {
1789+ logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1790+ return;
1791+ } catch (ClusterNameMismatchException e) {
1792+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1793+ return;
1794+ }
1795+
1796+ controlConnection.onAdd(host);
1797+
1798+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1799+ for (SessionManager s : sessions)
1800+ futures.add(s.maybeAddPool(host, reusedConnection));
1801+
1802+ try {
1803+ // Only mark the node up once all session have added their pool (if the load-balancing
1804+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1805+ // to the node.
1806+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
18191807
1820- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1821- for (SessionManager s : sessions)
1822- futures.add(s.maybeAddPool(host, blockingExecutor));
1823-
1824- // Only mark the node up once all session have added their pool (if the load-balancing
1825- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1826- // to the node.
1827- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1828- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1829- public void onSuccess(List<Boolean> poolCreationResults) {
18301808 // If any of the creation failed, they will have signaled a connection failure
18311809 // which will trigger a reconnection to the node. So don't bother marking UP.
18321810 if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
@@ -1838,24 +1816,26 @@
18381816
18391817 for (Host.StateListener listener : listeners)
18401818 listener.onAdd(host);
1841- }
18421819
1843- public void onFailure(Throwable t) {
1820+ } catch (ExecutionException e) {
1821+ Throwable t = e.getCause();
18441822 // That future is not really supposed to throw unexpected exceptions
18451823 if (!(t instanceof InterruptedException))
18461824 logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
18471825 }
1848- });
18491826
1850- f.get();
1827+ // Now, check if there isn't pools to create/remove following the addition.
1828+ // We do that now only so that it's not called before we've set the node up.
1829+ for (SessionManager s : sessions)
1830+ s.updateCreatedPools();
18511831
1852- // Now, check if there isn't pools to create/remove following the addition.
1853- // We do that now only so that it's not called before we've set the node up.
1854- for (SessionManager s : sessions)
1855- s.updateCreatedPools(blockingExecutor);
1832+ } finally {
1833+ host.notificationsLock.unlock();
1834+ }
18561835
18571836 } finally {
1858- host.notificationsLock.unlock();
1837+ if (reusedConnection != null && !reusedConnection.hasPool())
1838+ reusedConnection.closeAsync();
18591839 }
18601840 }
18611841
@@ -1895,24 +1875,15 @@
18951875 }
18961876 }
18971877
1898- public boolean signalConnectionFailure(Host host, ConnectionException exception, boolean isHostAddition, boolean markSuspected) {
1878+ public boolean signalConnectionFailure(Host host, ConnectionException exception, boolean isHostAddition) {
18991879 // Don't signal failure until we've fully initialized the controlConnection as this might mess up with
19001880 // the protocol detection
19011881 if (!isFullyInit || isClosed())
19021882 return true;
19031883
19041884 boolean isDown = host.signalConnectionFailure(exception);
1905- if (isDown) {
1906- if (isHostAddition || !markSuspected) {
1907- triggerOnDown(host, isHostAddition, true);
1908- } else {
1909- // Note that we do want to call onSuspected on the current thread, as the whole point is
1910- // that by the time this method return, the host initialReconnectionAttempt will have been
1911- // set and the load balancing policy informed of the suspection. We know that onSuspected
1912- // does little work (and non blocking one) itself however.
1913- onSuspected(host);
1914- }
1915- }
1885+ if (isDown)
1886+ triggerOnDown(host, isHostAddition, true);
19161887 return isDown;
19171888 }
19181889
@@ -1953,69 +1924,85 @@
19531924 return stmt;
19541925 }
19551926
1956- private void prepareAllQueries(Host host) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
1927+ /**
1928+ * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
1929+ * reuse to prepare the statements (might be null).
1930+ * @return a connection that the rest of the initialization process can use (it will be made part
1931+ * of a connection pool). Can be reusedConnection, or one that was open in the method.
1932+ */
1933+ private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
19571934 if (preparedQueries.isEmpty())
1958- return;
1935+ return reusedConnection;
19591936
19601937 logger.debug("Preparing {} prepared queries on newly up node {}", preparedQueries.size(), host);
1938+ Connection connection = null;
19611939 try {
1962- Connection connection = connectionFactory.open(host);
1940+ connection = (reusedConnection == null)
1941+ ? connectionFactory.open(host)
1942+ : reusedConnection;
19631943
1964- try
1965- {
1966- try {
1967- ControlConnection.waitForSchemaAgreement(connection, this);
1968- } catch (ExecutionException e) {
1969- // As below, just move on
1970- }
1944+ try {
1945+ ControlConnection.waitForSchemaAgreement(connection, this);
1946+ } catch (ExecutionException e) {
1947+ // As below, just move on
1948+ }
19711949
1972- // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation
1973- // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the
1974- // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is
1975- // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed.
1976-
1977- // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally
1978- // used for preparing it. However, since we are likely that all prepared query belong to only a handful
1979- // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed,
1980- // we first sort the query per keyspace.
1981- SetMultimap<String, String> perKeyspace = HashMultimap.create();
1982- for (PreparedStatement ps : preparedQueries.values()) {
1983- // It's possible for a query to not have a current keyspace. But since null doesn't work well as
1984- // map keys, we use the empty string instead (that is not a valid keyspace name).
1985- String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace();
1986- perKeyspace.put(keyspace, ps.getQueryString());
1987- }
1950+ // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation
1951+ // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the
1952+ // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is
1953+ // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed.
1954+
1955+ // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally
1956+ // used for preparing it. However, since we are likely that all prepared query belong to only a handful
1957+ // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed,
1958+ // we first sort the query per keyspace.
1959+ SetMultimap<String, String> perKeyspace = HashMultimap.create();
1960+ for (PreparedStatement ps : preparedQueries.values()) {
1961+ // It's possible for a query to not have a current keyspace. But since null doesn't work well as
1962+ // map keys, we use the empty string instead (that is not a valid keyspace name).
1963+ String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace();
1964+ perKeyspace.put(keyspace, ps.getQueryString());
1965+ }
19881966
1989- for (String keyspace : perKeyspace.keySet())
1990- {
1991- // Empty string mean no particular keyspace to set
1992- if (!keyspace.isEmpty())
1993- connection.setKeyspace(keyspace);
1994-
1995- List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size());
1996- for (String query : perKeyspace.get(keyspace)) {
1997- futures.add(connection.write(new Requests.Prepare(query)));
1998- }
1999- for (Connection.Future future : futures) {
2000- try {
2001- future.get();
2002- } catch (ExecutionException e) {
2003- // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do
2004- // currently). It's not a big deal however as if it's a more serious problem it'll show up later when
2005- // the query is tried for execution.
2006- logger.debug("Unexpected error while preparing queries on new/newly up host", e);
2007- }
1967+ for (String keyspace : perKeyspace.keySet()) {
1968+ // Empty string mean no particular keyspace to set
1969+ if (!keyspace.isEmpty())
1970+ connection.setKeyspace(keyspace);
1971+
1972+ List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size());
1973+ for (String query : perKeyspace.get(keyspace)) {
1974+ futures.add(connection.write(new Requests.Prepare(query)));
1975+ }
1976+ for (Connection.Future future : futures) {
1977+ try {
1978+ future.get();
1979+ } catch (ExecutionException e) {
1980+ // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do
1981+ // currently). It's not a big deal however as if it's a more serious problem it'll show up later when
1982+ // the query is tried for execution.
1983+ logger.debug("Unexpected error while preparing queries on new/newly up host", e);
20081984 }
20091985 }
2010- } finally {
2011- connection.closeAsync();
20121986 }
1987+
1988+ return connection;
20131989 } catch (ConnectionException e) {
20141990 // Ignore, not a big deal
1991+ if (connection != null)
1992+ connection.closeAsync();
1993+ return null;
20151994 } catch (AuthenticationException e) {
20161995 // That's a bad news, but ignore at this point
1996+ if (connection != null)
1997+ connection.closeAsync();
1998+ return null;
20171999 } catch (BusyConnectionException e) {
20182000 // Ignore, not a big deal
2001+ // In theory the problem is transient so the connection could be reused later, but if the core pool size is 1
2002+ // it's better to close this one so that we start with a fresh connection.
2003+ if (connection != null)
2004+ connection.closeAsync();
2005+ return null;
20192006 }
20202007 }
20212008
@@ -2034,20 +2021,38 @@
20342021 if (logger.isDebugEnabled())
20352022 logger.debug("Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table);
20362023
2024+ maybeRefreshSchemaAndSignal(connection, future, rs, keyspace, table, udt);
2025+ }
2026+
2027+ public void waitForSchemaAgreementAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs) {
2028+ maybeRefreshSchemaAndSignal(connection, future, rs, null, null, null);
2029+ }
2030+
2031+ private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table, final String udt) {
2032+ final boolean refreshSchema = (keyspace != null); // if false, only wait for schema agreement
2033+
20372034 executor.submit(new Runnable() {
20382035 @Override
20392036 public void run() {
2037+ boolean schemaInAgreement = false;
20402038 try {
20412039 // Before refreshing the schema, wait for schema agreement so
20422040 // that querying a table just after having created it don't fail.
2043- if (!ControlConnection.waitForSchemaAgreement(connection, Cluster.Manager.this))
2041+ schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this);
2042+ if (!schemaInAgreement)
20442043 logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds());
2045- ControlConnection.refreshSchema(connection, keyspace, table, udt, Cluster.Manager.this, false);
2044+ if (refreshSchema)
2045+ ControlConnection.refreshSchema(connection, keyspace, table, udt, Manager.this, false);
20462046 } catch (Exception e) {
2047- logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage());
2048- submitSchemaRefresh(keyspace, table, udt);
2047+ if (refreshSchema) {
2048+ logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage());
2049+ submitSchemaRefresh(keyspace, table, udt);
2050+ } else {
2051+ logger.warn("Error while waiting for schema agreement", e);
2052+ }
20492053 } finally {
2050- // Always sets the result
2054+ // Always sets the result, but remember if we reached schema agreement
2055+ rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement);
20512056 future.setResult(rs);
20522057 }
20532058 }
@@ -2086,7 +2091,7 @@
20862091 // Make sure we have up-to-date infos on that host before adding it (so we typically
20872092 // catch that an upgraded node uses a new cassandra version).
20882093 if (controlConnection.refreshNodeInfo(newHost)) {
2089- onAdd(newHost);
2094+ onAdd(newHost, null);
20902095 } else {
20912096 logger.debug("Not enough info for {}, ignoring host", newHost);
20922097 }
@@ -2128,7 +2133,7 @@
21282133 // Make sure we have up-to-date infos on that host before adding it (so we typically
21292134 // catch that an upgraded node uses a new cassandra version).
21302135 if (controlConnection.refreshNodeInfo(h)) {
2131- onAdd(h);
2136+ onAdd(h, null);
21322137 } else {
21332138 logger.debug("Not enough info for {}, ignoring host", h);
21342139 }
@@ -2141,7 +2146,7 @@
21412146 // Make sure we have up-to-date infos on that host before adding it (so we typically
21422147 // catch that an upgraded node uses a new cassandra version).
21432148 if (controlConnection.refreshNodeInfo(hostUp)) {
2144- onUp(hostUp);
2149+ onUp(hostUp, null);
21452150 } else {
21462151 logger.debug("Not enough info for {}, ignoring host", hostUp);
21472152 }
@@ -2226,7 +2231,7 @@
22262231 controlConnection.reconnect();
22272232
22282233 for (SessionManager s : sessions)
2229- s.updateCreatedPools(executor);
2234+ s.updateCreatedPools();
22302235 }
22312236
22322237 void refreshConnectedHost(Host host) {
@@ -2236,7 +2241,7 @@
22362241 controlConnection.reconnect();
22372242
22382243 for (SessionManager s : sessions)
2239- s.updateCreatedPools(host, executor);
2244+ s.updateCreatedPools(host);
22402245 }
22412246
22422247 private class ClusterCloseFuture extends CloseFuture.Forwarding {
@@ -2288,6 +2293,19 @@
22882293 }).start();
22892294 }
22902295 }
2296+
2297+ private class CleanupIdleConnectionsTask implements Runnable {
2298+ @Override public void run() {
2299+ try {
2300+ long now = System.currentTimeMillis();
2301+ for (SessionManager session : sessions) {
2302+ session.cleanupIdleConnections(now);
2303+ }
2304+ } catch (Exception e) {
2305+ logger.warn("Error while trashing idle connections", e);
2306+ }
2307+ }
2308+ }
22912309 }
22922310
22932311 /**
@@ -2302,8 +2320,9 @@
23022320 static class ConnectionReaper {
23032321 private static final int INTERVAL_MS = 15000;
23042322
2305- private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory("Reaper-%d"));
2306- private final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
2323+ private final ScheduledExecutorService executor;
2324+ @VisibleForTesting
2325+ final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
23072326
23082327 private volatile boolean shutdown;
23092328
@@ -2325,7 +2344,8 @@
23252344 }
23262345 };
23272346
2328- ConnectionReaper() {
2347+ ConnectionReaper(Cluster.Manager manager) {
2348+ executor = Executors.newScheduledThreadPool(1, manager.threadFactory("connection-reaper"));
23292349 executor.scheduleWithFixedDelay(reaperTask, INTERVAL_MS, INTERVAL_MS, TimeUnit.MILLISECONDS);
23302350 }
23312351
modified driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +17 −3
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@
2626 * <li>low-level TCP configuration options (tcpNoDelay, keepAlive, ...).</li>
2727 * <li>Metrics related options.</li>
2828 * <li>Query related options (default consistency level, fetchSize, ...).</li>
29+ * <li>Netty layer customization options.</li>
2930 * </ul>
3031 * This is also where you get the configured policies, though those cannot be changed
3132 * (they are set during the built of the Cluster object).
@@ -39,6 +40,7 @@
3940 private final SocketOptions socketOptions;
4041 private final MetricsOptions metricsOptions;
4142 private final QueryOptions queryOptions;
43+ private final NettyOptions nettyOptions;
4244
4345 /*
4446 * Creates a configuration object.
@@ -49,7 +51,8 @@
4951 new PoolingOptions(),
5052 new SocketOptions(),
5153 new MetricsOptions(),
52- new QueryOptions());
54+ new QueryOptions(),
55+ NettyOptions.DEFAULT_INSTANCE);
5356 }
5457
5558 /**
@@ -61,19 +64,22 @@
6164 * @param socketOptions the socket options to use
6265 * @param metricsOptions the metrics options, or null to disable metrics.
6366 * @param queryOptions defaults related to queries.
67+ * @param nettyOptions the {@link NettyOptions} instance to use
6468 */
6569 public Configuration(Policies policies,
6670 ProtocolOptions protocolOptions,
6771 PoolingOptions poolingOptions,
6872 SocketOptions socketOptions,
6973 MetricsOptions metricsOptions,
70- QueryOptions queryOptions) {
74+ QueryOptions queryOptions,
75+ NettyOptions nettyOptions) {
7176 this.policies = policies;
7277 this.protocolOptions = protocolOptions;
7378 this.poolingOptions = poolingOptions;
7479 this.socketOptions = socketOptions;
7580 this.metricsOptions = metricsOptions;
7681 this.queryOptions = queryOptions;
82+ this.nettyOptions = nettyOptions;
7783 }
7884
7985 void register(Cluster.Manager manager) {
@@ -138,4 +144,12 @@
138144 public QueryOptions getQueryOptions() {
139145 return queryOptions;
140146 }
147+
148+ /**
149+ * Returns the {@link NettyOptions} instance for this configuration.
150+ * @return the {@link NettyOptions} instance for this configuration.
151+ */
152+ public NettyOptions getNettyOptions() {
153+ return nettyOptions;
154+ }
141155 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +528 −259
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,34 +15,42 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import javax.net.ssl.SSLEngine;
18+import java.lang.ref.WeakReference;
1919 import java.net.InetSocketAddress;
20+import java.util.HashSet;
2021 import java.util.Iterator;
22+import java.util.List;
23+import java.util.Queue;
2124 import java.util.concurrent.*;
2225 import java.util.concurrent.atomic.AtomicBoolean;
2326 import java.util.concurrent.atomic.AtomicInteger;
2427 import java.util.concurrent.atomic.AtomicReference;
2528
26-import com.google.common.util.concurrent.AbstractFuture;
27-import com.google.common.util.concurrent.ThreadFactoryBuilder;
28-import com.google.common.util.concurrent.Uninterruptibles;
29-import org.jboss.netty.bootstrap.ClientBootstrap;
30-import org.jboss.netty.channel.*;
31-import org.jboss.netty.channel.group.ChannelGroup;
32-import org.jboss.netty.channel.group.DefaultChannelGroup;
33-import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
34-import org.jboss.netty.handler.ssl.SslHandler;
35-import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler;
36-import org.jboss.netty.handler.timeout.IdleStateEvent;
37-import org.jboss.netty.handler.timeout.IdleStateHandler;
38-import org.jboss.netty.util.HashedWheelTimer;
39-import org.jboss.netty.util.Timeout;
40-import org.jboss.netty.util.TimerTask;
29+import com.google.common.collect.Lists;
30+import com.google.common.collect.MapMaker;
31+import com.google.common.util.concurrent.*;
32+import io.netty.bootstrap.Bootstrap;
33+import io.netty.channel.*;
34+import io.netty.channel.group.ChannelGroup;
35+import io.netty.channel.group.DefaultChannelGroup;
36+import io.netty.channel.socket.SocketChannel;
37+import io.netty.handler.ssl.SslHandler;
38+import io.netty.handler.timeout.IdleStateEvent;
39+import io.netty.handler.timeout.IdleStateHandler;
40+import io.netty.util.HashedWheelTimer;
41+import io.netty.util.Timeout;
42+import io.netty.util.TimerTask;
43+import io.netty.util.concurrent.GlobalEventExecutor;
44+import javax.net.ssl.SSLEngine;
4145 import org.slf4j.Logger;
4246 import org.slf4j.LoggerFactory;
4347
48+import static io.netty.handler.timeout.IdleState.ALL_IDLE;
49+
4450 import com.datastax.driver.core.exceptions.AuthenticationException;
51+import com.datastax.driver.core.exceptions.DriverException;
4552 import com.datastax.driver.core.exceptions.DriverInternalError;
53+import com.datastax.driver.core.utils.MoreFutures;
4654
4755 // For LoggingHandler
4856 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -56,10 +64,18 @@
5664 private static final Logger logger = LoggerFactory.getLogger(Connection.class);
5765 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
5866
67+ private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false);
68+
69+ enum State {OPEN, TRASHED, RESURRECTING, GONE }
70+
71+ final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
72+
73+ volatile long maxIdleTime;
74+
5975 public final InetSocketAddress address;
6076 private final String name;
6177
62- private final Channel channel;
78+ private volatile Channel channel;
6379 private final Factory factory;
6480
6581 private final Dispatcher dispatcher;
@@ -75,64 +91,126 @@
7591
7692 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
7793
94+ private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
95+
7896 /**
79- * Create a new connection to a Cassandra node.
97+ /**
98+ * Create a new connection to a Cassandra node and associate it with the given pool.
8099 *
81- * The connection is open and initialized by the constructor.
82- *
83- * @throws ConnectionException if the connection attempts fails or is
84- * refused by the server.
100+ * @param name the connection name
101+ * @param address the remote address
102+ * @param factory the connection factory to use
103+ * @param pool the pool this connection belongs to. May be null if this connection does not belong to a pool.
104+ * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}.
85105 */
86- protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
106+ protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
87107 this.address = address;
88108 this.factory = factory;
89109 this.dispatcher = new Dispatcher();
90110 this.name = name;
111+ this.poolRef.set(pool);
112+ }
113+
114+ /**
115+ * Create a new connection to a Cassandra node.
116+ */
117+ Connection(String name, InetSocketAddress address, Factory factory) {
118+ this(name, address, factory, null);
119+ }
120+
121+ public ListenableFuture<Void> initAsync() {
122+ if (factory.isShutdown)
123+ return Futures.immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down"));
124+
125+ ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED : factory.protocolVersion;
126+ final SettableFuture<Void> channelReadyFuture = SettableFuture.create();
91127
92128 try {
93- ClientBootstrap bootstrap = factory.newBootstrap();
129+ Bootstrap bootstrap = factory.newBootstrap();
94130 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
95- ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED : factory.protocolVersion;
96- bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions(),
97- factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), factory.timer));
131+ bootstrap.handler(
132+ new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
133+ factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
134+ factory.configuration.getNettyOptions()));
98135
99136 ChannelFuture future = bootstrap.connect(address);
100137
101138 writer.incrementAndGet();
102- try {
103- // Wait until the connection attempt succeeds or fails.
104- this.channel = future.awaitUninterruptibly().getChannel();
105- this.factory.allChannels.add(this.channel);
106- if (!future.isSuccess()) {
107- if (logger.isDebugEnabled())
108- logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.getCause())));
109- throw defunct(new TransportException(address, "Cannot connect", future.getCause()));
139+ future.addListener(new ChannelFutureListener() {
140+ @Override
141+ public void operationComplete(ChannelFuture future) throws Exception {
142+ writer.decrementAndGet();
143+ channel = future.channel();
144+ if (isClosed()) {
145+ channel.close().addListener(new ChannelFutureListener() {
146+ @Override
147+ public void operationComplete(ChannelFuture future) throws Exception {
148+ channelReadyFuture.setException(new TransportException(Connection.this.address, "Connection closed during initialization."));
149+ }
150+ });
151+ } else {
152+ Connection.this.factory.allChannels.add(channel);
153+ if (!future.isSuccess()) {
154+ if (logger.isDebugEnabled())
155+ logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause())));
156+ channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause()));
157+ } else {
158+ logger.debug("{} Connection opened successfully", Connection.this);
159+ channel.closeFuture().addListener(new ChannelCloseListener());
160+ channelReadyFuture.set(null);
161+ }
162+ }
110163 }
111- } finally {
112- writer.decrementAndGet();
113- }
114-
115- logger.trace("{} Connection opened successfully", this);
116- initializeTransport(protocolVersion, factory.manager.metadata.clusterName);
117- logger.debug("{} Transport initialized and ready", this);
118- isInitialized = true;
119-
120- } catch (ConnectionException e) {
121- closeAsync().force();
122- throw e;
123- } catch (ClusterNameMismatchException e) {
124- closeAsync().force();
125- throw e;
126- } catch (UnsupportedProtocolVersionException e) {
127- closeAsync().force();
128- throw e;
129- } catch (InterruptedException e) {
130- closeAsync().force();
131- throw e;
164+ });
132165 } catch (RuntimeException e) {
133166 closeAsync().force();
134167 throw e;
135168 }
169+
170+ Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();
171+
172+ ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
173+ onChannelReady(protocolVersion, initExecutor), initExecutor);
174+
175+ // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
176+ ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() {
177+ @Override
178+ public ListenableFuture<Void> create(Throwable t) throws Exception {
179+ SettableFuture<Void> future = SettableFuture.create();
180+ // Make sure the connection gets properly closed.
181+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
182+ // These exceptions cause the node to be ignored, so just propagate
183+ closeAsync().force();
184+ future.setException(t);
185+ } else {
186+ // Defunct to ensure that the error will be signaled (marking the host down)
187+ Exception e = (t instanceof ConnectionException || t instanceof DriverException || t instanceof InterruptedException)
188+ ? (Exception)t
189+ : new ConnectionException(Connection.this.address,
190+ String.format("Unexpected error during transport initialization (%s)", t),
191+ t);
192+ future.setException(defunct(e));
193+ }
194+ return future;
195+ }
196+ }, initExecutor);
197+
198+ // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel.
199+ Futures.addCallback(initFuture, new FutureCallback<Void>() {
200+ @Override
201+ public void onSuccess(Void result) {
202+ isInitialized = true;
203+ }
204+
205+ @Override
206+ public void onFailure(Throwable t) {
207+ if (!isClosed()) {
208+ closeAsync().force();
209+ }
210+ }
211+ }, initExecutor);
212+
213+ return initFuture;
136214 }
137215
138216 private static String extractMessage(Throwable t) {
@@ -144,124 +222,160 @@
144222 return " (" + msg + ')';
145223 }
146224
147- private void initializeTransport(ProtocolVersion version, String clusterName) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
148- try {
149- ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
150- Message.Response response = write(new Requests.Startup(compression)).get();
151- switch (response.type) {
152- case READY:
153- break;
154- case ERROR:
155- Responses.Error error = (Responses.Error)response;
156- // Testing for a specific string is a tad fragile but well, we don't have much choice
157- if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
158- throw unsupportedProtocolVersionException(version, error.serverProtocolVersion);
159- throw defunct(new TransportException(address, String.format("Error initializing connection: %s", error.message)));
160- case AUTHENTICATE:
161- Authenticator authenticator = factory.authProvider.newAuthenticator(address);
162- switch (version) {
163- case V1:
164- if (authenticator instanceof ProtocolV1Authenticator)
165- authenticateV1(authenticator);
166- else
167- // DSE 3.x always uses SASL authentication backported from protocol v2
168- authenticateV2(authenticator);
169- break;
170- case V2:
171- case V3:
172- authenticateV2(authenticator);
173- break;
174- default:
175- throw defunct(version.unsupported());
176- }
177- break;
178- default:
179- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
225+ private AsyncFunction<Void, Void> onChannelReady(final ProtocolVersion protocolVersion, final Executor initExecutor) {
226+ return new AsyncFunction<Void, Void>() {
227+ @Override
228+ public ListenableFuture<Void> apply(Void input) throws Exception {
229+ ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
230+ Future startupResponseFuture = write(new Requests.Startup(compression));
231+ return Futures.transform(startupResponseFuture,
232+ onStartupResponse(protocolVersion, initExecutor), initExecutor);
180233 }
234+ };
235+ }
181236
182- checkClusterName(version, clusterName);
183- } catch (BusyConnectionException e) {
184- throw defunct(new DriverInternalError("Newly created connection should not be busy"));
185- } catch (ExecutionException e) {
186- throw defunct(new ConnectionException(address, String.format("Unexpected error during transport initialization (%s)", e.getCause()), e.getCause()));
187- }
237+ private AsyncFunction<Message.Response, Void> onStartupResponse(final ProtocolVersion protocolVersion, final Executor initExecutor) {
238+ return new AsyncFunction<Message.Response, Void>() {
239+ @Override
240+ public ListenableFuture<Void> apply(Message.Response response) throws Exception {
241+ switch (response.type) {
242+ case READY:
243+ return checkClusterName(protocolVersion, initExecutor);
244+ case ERROR:
245+ Responses.Error error = (Responses.Error)response;
246+ // Testing for a specific string is a tad fragile but well, we don't have much choice
247+ if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
248+ throw unsupportedProtocolVersionException(protocolVersion, error.serverProtocolVersion);
249+ throw new TransportException(address, String.format("Error initializing connection: %s", error.message));
250+ case AUTHENTICATE:
251+ Authenticator authenticator = factory.authProvider.newAuthenticator(address);
252+ switch (protocolVersion) {
253+ case V1:
254+ if (authenticator instanceof ProtocolV1Authenticator)
255+ return authenticateV1(authenticator, protocolVersion, initExecutor);
256+ else
257+ // DSE 3.x always uses SASL authentication backported from protocol v2
258+ return authenticateV2(authenticator, protocolVersion, initExecutor);
259+ case V2:
260+ case V3:
261+ return authenticateV2(authenticator, protocolVersion, initExecutor);
262+ default:
263+ throw defunct(protocolVersion.unsupported());
264+ }
265+ default:
266+ throw new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type));
267+ }
268+ }
269+ };
188270 }
189271
190- private UnsupportedProtocolVersionException unsupportedProtocolVersionException(ProtocolVersion triedVersion, ProtocolVersion serverProtocolVersion) {
191- logger.debug("Got unsupported protocol version error from {} for version {} server supports version {}", address, triedVersion, serverProtocolVersion);
192- return new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion);
272+ // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
273+ // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
274+ // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
275+ private ListenableFuture<Void> checkClusterName(ProtocolVersion protocolVersion, final Executor executor) {
276+ final String expected = factory.manager.metadata.clusterName;
277+
278+ // At initialization, the cluster is not known yet
279+ if (expected == null)
280+ return MoreFutures.VOID_SUCCESS;
281+
282+ DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null, protocolVersion, new Requests.Query("select cluster_name from system.local"));
283+ try {
284+ write(clusterNameFuture);
285+ return Futures.transform(clusterNameFuture,
286+ new AsyncFunction<ResultSet, Void>() {
287+ @Override
288+ public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
289+ Row row = rs.one();
290+ String actual = row.getString("cluster_name");
291+ if (!expected.equals(actual))
292+ throw new ClusterNameMismatchException(address, actual, expected);
293+ return MoreFutures.VOID_SUCCESS;
294+ }
295+ }, executor);
296+ } catch (Exception e) {
297+ return Futures.immediateFailedFuture(e);
298+ }
193299 }
194300
195- private void authenticateV1(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
301+ private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
196302 Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
197- Message.Response authResponse = write(creds).get();
198- switch (authResponse.type) {
199- case READY:
200- break;
201- case ERROR:
202- throw defunct(new AuthenticationException(address, ((Responses.Error)authResponse).message));
203- default:
204- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
303+ try {
304+ Future authResponseFuture = write(creds);
305+ return Futures.transform(authResponseFuture,
306+ new AsyncFunction<Message.Response, Void>() {
307+ @Override
308+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
309+ switch (authResponse.type) {
310+ case READY:
311+ return checkClusterName(protocolVersion, executor);
312+ case ERROR:
313+ throw new AuthenticationException(address, ((Responses.Error)authResponse).message);
314+ default:
315+ throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
316+ }
317+ }
318+ }, executor);
319+ } catch (Exception e) {
320+ return Futures.immediateFailedFuture(e);
205321 }
206322 }
207323
208- private void authenticateV2(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
324+ private ListenableFuture<Void> authenticateV2(final Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
209325 byte[] initialResponse = authenticator.initialResponse();
210326 if (null == initialResponse)
211327 initialResponse = EMPTY_BYTE_ARRAY;
212328
213- Message.Response authResponse = write(new Requests.AuthResponse(initialResponse)).get();
214- waitForAuthCompletion(authResponse, authenticator);
215- }
216-
217- private void waitForAuthCompletion(Message.Response authResponse, Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
218- switch (authResponse.type) {
219- case AUTH_SUCCESS:
220- logger.trace("{} Authentication complete", this);
221- authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
222- break;
223- case AUTH_CHALLENGE:
224- byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
225- if (responseToServer == null) {
226- // If we generate a null response, then authentication has completed, return without
227- // sending a further response back to the server.
228- logger.trace("{} Authentication complete (No response to server)", this);
229- return;
230- } else {
231- // Otherwise, send the challenge response back to the server
232- logger.trace("{} Sending Auth response to challenge", this);
233- waitForAuthCompletion(write(new Requests.AuthResponse(responseToServer)).get(), authenticator);
234- }
235- break;
236- case ERROR:
237- // This is not very nice, but we're trying to identify if we
238- // attempted v2 auth against a server which only supports v1
239- // The AIOOBE indicates that the server didn't recognise the
240- // initial AuthResponse message
241- String message = ((Responses.Error)authResponse).message;
242- if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
243- message = String.format("Cannot use authenticator %s with protocol version 1, "
244- + "only plain text authentication is supported with this protocol version", authenticator);
245- throw defunct(new AuthenticationException(address, message));
246- default:
247- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type)));
329+ try {
330+ Future authResponseFuture = write(new Requests.AuthResponse(initialResponse));
331+ return Futures.transform(authResponseFuture, onV2AuthResponse(authenticator, protocolVersion, executor), executor);
332+ } catch (Exception e) {
333+ return Futures.immediateFailedFuture(e);
248334 }
249335 }
250336
251- // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
252- // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
253- // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
254- private void checkClusterName(ProtocolVersion version, String expected) throws ClusterNameMismatchException, ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
255- // At initialization, the cluster is not known yet
256- if (expected == null)
257- return;
337+ private AsyncFunction<Message.Response, Void> onV2AuthResponse(final Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
338+ return new AsyncFunction<Message.Response, Void>() {
339+ @Override
340+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
341+ switch (authResponse.type) {
342+ case AUTH_SUCCESS:
343+ logger.trace("{} Authentication complete", this);
344+ authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
345+ return checkClusterName(protocolVersion, executor);
346+ case AUTH_CHALLENGE:
347+ byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
348+ if (responseToServer == null) {
349+ // If we generate a null response, then authentication has completed, proceed without
350+ // sending a further response back to the server.
351+ logger.trace("{} Authentication complete (No response to server)", this);
352+ return checkClusterName(protocolVersion, executor);
353+ } else {
354+ // Otherwise, send the challenge response back to the server
355+ logger.trace("{} Sending Auth response to challenge", this);
356+ Future nextResponseFuture = write(new Requests.AuthResponse(responseToServer));
357+ return Futures.transform(nextResponseFuture, onV2AuthResponse(authenticator, protocolVersion, executor), executor);
358+ }
359+ case ERROR:
360+ // This is not very nice, but we're trying to identify if we
361+ // attempted v2 auth against a server which only supports v1
362+ // The AIOOBE indicates that the server didn't recognise the
363+ // initial AuthResponse message
364+ String message = ((Responses.Error)authResponse).message;
365+ if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
366+ message = String.format("Cannot use authenticator %s with protocol version 1, "
367+ + "only plain text authentication is supported with this protocol version", authenticator);
368+ throw new AuthenticationException(address, message);
369+ default:
370+ throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
371+ }
372+ }
373+ };
374+ }
258375
259- DefaultResultSetFuture future = new DefaultResultSetFuture(null, version, new Requests.Query("select cluster_name from system.local"));
260- write(future);
261- Row row = future.get().one();
262- String actual = row.getString("cluster_name");
263- if (!expected.equals(actual))
264- throw new ClusterNameMismatchException(address, actual, expected);
376+ private UnsupportedProtocolVersionException unsupportedProtocolVersionException(ProtocolVersion triedVersion, ProtocolVersion serverProtocolVersion) {
377+ logger.debug("Got unsupported protocol version error from {} for version {} server supports version {}", address, triedVersion, serverProtocolVersion);
378+ return new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion);
265379 }
266380
267381 public boolean isDefunct() {
@@ -281,23 +395,11 @@
281395 ? (ConnectionException)e
282396 : new ConnectionException(address, "Connection problem", e);
283397
284- // We need to signal the connection failure before erroring out handlers to make
285- // sure the "suspected" mechanism work as expected
286398 Host host = factory.manager.metadata.getHost(address);
287399 if (host != null) {
288-
289- // If the host was reconnecting, and this error happens right after we opened a connection pool, but
290- // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can
291- // lead to a race condition that leaves the node UP with a closed pool.
292- boolean belongsToReconnectingPool = host.state != Host.State.UP &&
293- this instanceof PooledConnection &&
294- (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed());
295-
296- boolean markSuspected = isInitialized && !belongsToReconnectingPool;
297-
298400 // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant.
299401 // This is not too much of a problem since calling onDown on a node that is already down has no effect.
300- boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), markSuspected);
402+ boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded());
301403 notifyOwnerWhenDefunct(isDown);
302404 }
303405
@@ -310,6 +412,19 @@
310412 }
311413
312414 protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
415+ // If an error happens during initialization, the owner will detect it and take appropriate action
416+ if (!isInitialized)
417+ return;
418+
419+ HostConnectionPool pool = this.poolRef.get();
420+ if (pool == null)
421+ return;
422+
423+ if (hostIsDown) {
424+ pool.closeAsync().force();
425+ } else {
426+ pool.replaceDefunctConnection(this);
427+ }
313428 }
314429
315430 public String keyspace() {
@@ -340,7 +455,9 @@
340455 // It can happen however that the node we're connecting to
341456 // is not up on the schema yet. In that case, defuncting
342457 // the connection is not a bad choice.
343- defunct(new ConnectionException(address, String.format("Problem while setting keyspace, got %s as response", response)));
458+ String message = String.format("Problem while setting keyspace, got %s as response", response);
459+ logger.warn("{} {}", this, message);
460+ defunct(new ConnectionException(address, message));
344461 break;
345462 }
346463 } catch (ConnectionException e) {
@@ -406,8 +523,12 @@
406523
407524 logger.trace("{} writing request {}", this, request);
408525 writer.incrementAndGet();
409- channel.write(request).addListener(writeHandler(request, handler));
410526
527+ if (DISABLE_COALESCING) {
528+ channel.writeAndFlush(request).addListener(writeHandler(request, handler));
529+ } else {
530+ flush(new FlushItem(channel, request, writeHandler(request, handler)));
531+ }
411532 if (startTimeout)
412533 handler.startTimeout();
413534
@@ -428,10 +549,10 @@
428549 dispatcher.removeHandler(handler, true);
429550
430551 final ConnectionException ce;
431- if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) {
552+ if (writeFuture.cause() instanceof java.nio.channels.ClosedChannelException) {
432553 ce = new TransportException(address, "Error writing: Closed channel");
433554 } else {
434- ce = new TransportException(address, "Error writing", writeFuture.getCause());
555+ ce = new TransportException(address, "Error writing", writeFuture.cause());
435556 }
436557 final long latency = System.nanoTime() - handler.startTime;
437558 // This handler is executed while holding the writeLock of the channel.
@@ -452,6 +573,25 @@
452573 };
453574 }
454575
576+ boolean hasPool() {
577+ return this.poolRef.get() != null;
578+ }
579+
580+ /** @return whether the connection was already associated with a pool */
581+ boolean setPool(HostConnectionPool pool) {
582+ return poolRef.compareAndSet(null, pool);
583+ }
584+
585+ /**
586+ * If the connection is part of a pool, return it to the pool.
587+ * The connection should generally not be reused after that.
588+ */
589+ void release() {
590+ HostConnectionPool pool = poolRef.get();
591+ if (pool != null)
592+ pool.returnConnection(this);
593+ }
594+
455595 public boolean isClosed() {
456596 return closeFuture.get() != null;
457597 }
@@ -525,12 +665,12 @@
525665
526666 public static class Factory {
527667
528- private final ExecutorService bossExecutor = Executors.newCachedThreadPool();
529- private final ExecutorService workerExecutor = Executors.newCachedThreadPool();
530- public final HashedWheelTimer timer = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat("Timeouter-%d").build());
668+ public final HashedWheelTimer timer;
531669
532- private final ChannelFactory channelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor);
533- private final ChannelGroup allChannels = new DefaultChannelGroup();
670+ private final EventLoopGroup eventLoopGroup;
671+ private final Class<? extends Channel> channelClass;
672+
673+ private final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
534674
535675 private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<Host, AtomicInteger>();
536676 public final DefaultResponseHandler defaultHandler;
@@ -542,6 +682,7 @@
542682 private volatile boolean isShutdown;
543683
544684 volatile ProtocolVersion protocolVersion;
685+ private final NettyOptions nettyOptions;
545686
546687 Factory(Cluster.Manager manager, Configuration configuration) {
547688 this.defaultHandler = manager;
@@ -550,6 +691,10 @@
550691 this.configuration = configuration;
551692 this.authProvider = configuration.getProtocolOptions().getAuthProvider();
552693 this.protocolVersion = configuration.getProtocolOptions().initialProtocolVersion;
694+ this.nettyOptions = configuration.getNettyOptions();
695+ this.eventLoopGroup = nettyOptions.eventLoopGroup(manager.threadFactory("nio-worker"));
696+ this.channelClass = nettyOptions.channelClass();
697+ this.timer = new HashedWheelTimer(manager.threadFactory("timeouter"));
553698 }
554699
555700 public int getPort() {
@@ -570,20 +715,53 @@
570715 throw new ConnectionException(address, "Connection factory is shut down");
571716
572717 String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement();
573- return new Connection(name, address, this);
718+ Connection connection = new Connection(name, address, this);
719+ // This method opens the connection synchronously, so wait until it's initialized
720+ try {
721+ connection.initAsync().get();
722+ return connection;
723+ } catch (ExecutionException e) {
724+ throw launderAsyncInitException(e);
725+ }
574726 }
575727
576728 /**
577729 * Same as open, but associate the created connection to the provided connection pool.
578730 */
579- public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
731+ public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
732+ try {
733+ Connection connection = newConnection(pool);
734+ connection.initAsync().get();
735+ return connection;
736+ } catch (ExecutionException e) {
737+ throw launderAsyncInitException(e);
738+ }
739+ }
740+
741+ /**
742+ * Creates a new connection and associates it to the provided connection pool, but does not start it.
743+ */
744+ public Connection newConnection(HostConnectionPool pool) {
580745 InetSocketAddress address = pool.host.getSocketAddress();
746+ String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
581747
582- if (isShutdown)
583- throw new ConnectionException(address, "Connection factory is shut down");
748+ return new Connection(name, address, this, pool);
749+ }
584750
585- String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
586- return new PooledConnection(name, address, this, pool);
751+ static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
752+ Throwable t = e.getCause();
753+ if (t instanceof ConnectionException)
754+ throw (ConnectionException)t;
755+ if (t instanceof InterruptedException)
756+ throw (InterruptedException)t;
757+ if (t instanceof UnsupportedProtocolVersionException)
758+ throw (UnsupportedProtocolVersionException)t;
759+ if (t instanceof ClusterNameMismatchException)
760+ throw (ClusterNameMismatchException)t;
761+ if (t instanceof DriverException)
762+ throw (DriverException)t;
763+
764+ return new RuntimeException("Unexpected exception during connection initialization", t);
587765 }
588766
589767 private AtomicInteger getIdGenerator(Host host) {
@@ -605,31 +783,34 @@
605783 return configuration.getSocketOptions().getReadTimeoutMillis();
606784 }
607785
608- private ClientBootstrap newBootstrap() {
609- ClientBootstrap b = new ClientBootstrap(channelFactory);
786+ private Bootstrap newBootstrap() {
787+ Bootstrap b = new Bootstrap();
788+ b.group(eventLoopGroup)
789+ .channel(channelClass);
610790
611791 SocketOptions options = configuration.getSocketOptions();
612792
613- b.setOption("connectTimeoutMillis", options.getConnectTimeoutMillis());
793+ b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeoutMillis());
614794 Boolean keepAlive = options.getKeepAlive();
615795 if (keepAlive != null)
616- b.setOption("keepAlive", keepAlive);
796+ b.option(ChannelOption.SO_KEEPALIVE, keepAlive);
617797 Boolean reuseAddress = options.getReuseAddress();
618798 if (reuseAddress != null)
619- b.setOption("reuseAddress", reuseAddress);
799+ b.option(ChannelOption.SO_REUSEADDR, reuseAddress);
620800 Integer soLinger = options.getSoLinger();
621801 if (soLinger != null)
622- b.setOption("soLinger", soLinger);
802+ b.option(ChannelOption.SO_LINGER, soLinger);
623803 Boolean tcpNoDelay = options.getTcpNoDelay();
624804 if (tcpNoDelay != null)
625- b.setOption("tcpNoDelay", tcpNoDelay);
805+ b.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
626806 Integer receiveBufferSize = options.getReceiveBufferSize();
627807 if (receiveBufferSize != null)
628- b.setOption("receiveBufferSize", receiveBufferSize);
808+ b.option(ChannelOption.SO_RCVBUF, receiveBufferSize);
629809 Integer sendBufferSize = options.getSendBufferSize();
630810 if (sendBufferSize != null)
631- b.setOption("sendBufferSize", sendBufferSize);
811+ b.option(ChannelOption.SO_SNDBUF, sendBufferSize);
632812
813+ nettyOptions.afterBootstrapInitialized(b);
633814 return b;
634815 }
635816
@@ -641,14 +822,104 @@
641822 // we're not on an I/O thread or anything, so just call await.
642823 allChannels.close().awaitUninterruptibly();
643824
644- // This will call shutdownNow on the boss and worker executor. Since this is called
645- // only once all connection have been individually closed, it's fine.
646- channelFactory.releaseExternalResources();
825+ nettyOptions.onClusterClose(eventLoopGroup);
647826 timer.stop();
648827 }
649828 }
650829
651- private class Dispatcher extends IdleStateAwareChannelUpstreamHandler {
830+ private static final class Flusher implements Runnable {
831+ final WeakReference<EventLoop> eventLoopRef;
832+ final Queue<FlushItem> queued = new ConcurrentLinkedQueue<FlushItem>();
833+ final AtomicBoolean running = new AtomicBoolean(false);
834+ final HashSet<Channel> channels = new HashSet<Channel>();
835+ final List<FlushItem> flushed = Lists.newArrayListWithExpectedSize(50);
836+ int runsSinceFlush = 0;
837+ int runsWithNoWork = 0;
838+
839+ private Flusher(EventLoop eventLoop) {
840+ this.eventLoopRef = new WeakReference<EventLoop>(eventLoop);
841+ }
842+
843+ void start() {
844+ if (!running.get() && running.compareAndSet(false, true)) {
845+ EventLoop eventLoop = eventLoopRef.get();
846+ if (eventLoop != null)
847+ eventLoop.execute(this);
848+ }
849+ }
850+
851+ @Override
852+ public void run() {
853+
854+ boolean doneWork = false;
855+ FlushItem flush;
856+ while (null != (flush = queued.poll())) {
857+ channels.add(flush.channel);
858+ flush.channel.write(flush.request).addListener(flush.listener);
859+ flushed.add(flush);
860+ doneWork = true;
861+ }
862+
863+ runsSinceFlush++;
864+
865+ if (!doneWork || runsSinceFlush > 2 || flushed.size() > 50) {
866+ for (Channel channel : channels)
867+ channel.flush();
868+
869+ channels.clear();
870+ flushed.clear();
871+ runsSinceFlush = 0;
872+ }
873+
874+ if (doneWork) {
875+ runsWithNoWork = 0;
876+ } else {
877+ // either reschedule or cancel
878+ if (++runsWithNoWork > 5) {
879+ running.set(false);
880+ if (queued.isEmpty() || !running.compareAndSet(false, true))
881+ return;
882+ }
883+ }
884+
885+ EventLoop eventLoop = eventLoopRef.get();
886+ if(eventLoop != null) {
887+ eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
888+ }
889+ }
890+ }
891+
892+ private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
893+ .concurrencyLevel(16)
894+ .weakKeys()
895+ .makeMap();
896+
897+ private static class FlushItem {
898+ final Channel channel;
899+ final Object request;
900+ final ChannelFutureListener listener;
901+
902+ private FlushItem(Channel channel, Object request, ChannelFutureListener listener) {
903+ this.channel = channel;
904+ this.request = request;
905+ this.listener = listener;
906+ }
907+ }
908+
909+ private void flush(FlushItem item) {
910+ EventLoop loop = item.channel.eventLoop();
911+ Flusher flusher = flusherLookup.get(loop);
912+ if (flusher == null) {
913+ Flusher alt = flusherLookup.putIfAbsent(loop, flusher = new Flusher(loop));
914+ if (alt != null)
915+ flusher = alt;
916+ }
917+
918+ flusher.queued.add(item);
919+ flusher.start();
920+ }
921+
922+ private class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
652923
653924 public final StreamIdGenerator streamIdHandler;
654925 private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
@@ -658,7 +929,7 @@
658929 if (protocolVersion == null) {
659930 // This happens for the first control connection because the protocol version has not been
660931 // negociated yet.
661- assert !(Connection.this instanceof PooledConnection);
932+ assert !Connection.this.hasPool();
662933 protocolVersion = ProtocolVersion.V2;
663934 }
664935 streamIdHandler = StreamIdGenerator.newInstance(protocolVersion);
@@ -696,54 +967,50 @@
696967 }
697968
698969 @Override
699- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
700- if (!(e.getMessage() instanceof Message.Response)) {
701- String msg = asDebugString(e.getMessage());
702- logger.error("{} Received unexpected message: {}", Connection.this, msg);
703- defunct(new TransportException(address, "Unexpected message received: " + msg));
704- } else {
705- Message.Response response = (Message.Response)e.getMessage();
706- int streamId = response.getStreamId();
970+ protected void channelRead0(ChannelHandlerContext ctx, Message.Response response) throws Exception {
971+ int streamId = response.getStreamId();
707972
708- logger.trace("{} received: {}", Connection.this, e.getMessage());
973+ if(logger.isTraceEnabled())
974+ logger.trace("{} received: {}", Connection.this, asDebugString(response));
709975
710- if (streamId < 0) {
711- factory.defaultHandler.handle(response);
712- return;
713- }
976+ if (streamId < 0) {
977+ factory.defaultHandler.handle(response);
978+ return;
979+ }
714980
715- ResponseHandler handler = pending.remove(streamId);
716- streamIdHandler.release(streamId);
717- if (handler == null) {
718- /**
719- * During normal operation, we should not receive responses for which we don't have a handler. There is
720- * two cases however where this can happen:
721- * 1) The connection has been defuncted due to some internal error and we've raced between removing the
722- * handler and actually closing the connection; since the original error has been logged, we're fine
723- * ignoring this completely.
724- * 2) This request has timed out. In that case, we've already switched to another host (or errored out
725- * to the user). So log it for debugging purpose, but it's fine ignoring otherwise.
726- */
727- streamIdHandler.unmark(streamId);
728- if (logger.isDebugEnabled())
729- logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
730- + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
731- return;
732- }
733- handler.cancelTimeout();
734- handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime, handler.retryCount);
735-
736- // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
737- // (note: this is racy as the signaling can be called more than once, but that's not a problem)
738- if (isClosed())
739- tryTerminate(false);
981+ ResponseHandler handler = pending.remove(streamId);
982+ streamIdHandler.release(streamId);
983+ if (handler == null) {
984+ /**
985+ * During normal operation, we should not receive responses for which we don't have a handler. There is
986+ * two cases however where this can happen:
987+ * 1) The connection has been defuncted due to some internal error and we've raced between removing the
988+ * handler and actually closing the connection; since the original error has been logged, we're fine
989+ * ignoring this completely.
990+ * 2) This request has timed out. In that case, we've already switched to another host (or errored out
991+ * to the user). So log it for debugging purpose, but it's fine ignoring otherwise.
992+ */
993+ streamIdHandler.unmark(streamId);
994+ if (logger.isDebugEnabled())
995+ logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
996+ + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
997+ return;
740998 }
999+ handler.cancelTimeout();
1000+ handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime, handler.retryCount);
1001+
1002+ // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
1003+ // (note: this is racy as the signaling can be called more than once, but that's not a problem)
1004+ if (isClosed())
1005+ tryTerminate(false);
7411006 }
7421007
7431008 @Override
744- public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
745- logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
746- write(HEARTBEAT_CALLBACK);
1009+ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
1010+ if (evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
1011+ logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
1012+ write(HEARTBEAT_CALLBACK);
1013+ }
7471014 }
7481015
7491016 // Make sure we don't print huge responses in debug/error logs.
@@ -759,15 +1026,15 @@
7591026 }
7601027
7611028 @Override
762- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
1029+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
7631030 if (logger.isDebugEnabled())
764- logger.debug(String.format("%s connection error", Connection.this), e.getCause());
1031+ logger.debug(String.format("%s connection error", Connection.this), cause);
7651032
7661033 // Ignore exception while writing, this will be handled by write() directly
7671034 if (writer.get() > 0)
7681035 return;
7691036
770- defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", e.getCause()), e.getCause()));
1037+ defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", cause), cause));
7711038 }
7721039
7731040 public void errorOutAllHandler(ConnectionException ce) {
@@ -780,13 +1047,15 @@
7801047 iter.remove();
7811048 }
7821049 }
1050+ }
7831051
1052+ private class ChannelCloseListener implements ChannelFutureListener {
7841053 @Override
785- public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
1054+ public void operationComplete(ChannelFuture future) throws Exception {
7861055 // If we've closed the channel client side then we don't really want to defunct the connection, but
7871056 // if there is remaining thread waiting on us, we still want to wake them up
7881057 if (!isInitialized || isClosed()) {
789- errorOutAllHandler(new TransportException(address, "Channel has been closed"));
1058+ dispatcher.errorOutAllHandler(new TransportException(address, "Channel has been closed"));
7901059 // we still want to force so that the future completes
7911060 Connection.this.closeAsync().force();
7921061 } else
@@ -839,7 +1108,7 @@
8391108 public ConnectionCloseFuture force() {
8401109 // Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared
8411110
842- // This method can be thrown during Connection ctor, at which point channel is not yet set. This is ok.
1111+ // This method can be thrown during initialization, at which point channel is not yet set. This is ok.
8431112 if (channel == null) {
8441113 set(null);
8451114 return this;
@@ -854,9 +1123,9 @@
8541123 future.addListener(new ChannelFutureListener() {
8551124 public void operationComplete(ChannelFuture future) {
8561125 factory.allChannels.remove(channel);
857- if (future.getCause() != null) {
858- logger.warn("Error closing channel", future.getCause());
859- ConnectionCloseFuture.this.setException(future.getCause());
1126+ if (future.cause() != null) {
1127+ logger.warn("Error closing channel", future.cause());
1128+ ConnectionCloseFuture.this.setException(future.cause());
8601129 } else
8611130 ConnectionCloseFuture.this.set(null);
8621131 }
@@ -970,8 +1239,7 @@
9701239 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
9711240 // of its own answer, and we would have no way to detect that.
9721241 connection.dispatcher.removeHandler(this, false);
973- if (connection instanceof PooledConnection)
974- ((PooledConnection)connection).release();
1242+ connection.release();
9751243 }
9761244
9771245 private TimerTask onTimeoutTask() {
@@ -989,7 +1257,7 @@
9891257 public void handle(Message.Response response);
9901258 }
9911259
992- private static class PipelineFactory implements ChannelPipelineFactory {
1260+ private static class Initializer extends ChannelInitializer<SocketChannel> {
9931261 // Stateless handlers
9941262 private static final Message.ProtocolDecoder messageDecoder = new Message.ProtocolDecoder();
9951263 private static final Message.ProtocolEncoder messageEncoderV1 = new Message.ProtocolEncoder(ProtocolVersion.V1);
@@ -1001,30 +1269,31 @@
10011269 private final Connection connection;
10021270 private final FrameCompressor compressor;
10031271 private final SSLOptions sslOptions;
1272+ private final NettyOptions nettyOptions;
10041273 private final ChannelHandler idleStateHandler;
10051274
1006- public PipelineFactory(Connection connection, ProtocolVersion protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds, HashedWheelTimer timer) {
1275+ public Initializer(Connection connection, ProtocolVersion protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds, NettyOptions nettyOptions) {
10071276 this.connection = connection;
10081277 this.protocolVersion = protocolVersion;
10091278 this.compressor = compressor;
10101279 this.sslOptions = sslOptions;
1011- this.idleStateHandler = new IdleStateHandler(timer, 0, 0, heartBeatIntervalSeconds);
1280+ this.nettyOptions = nettyOptions;
1281+ this.idleStateHandler = new IdleStateHandler(0, 0, heartBeatIntervalSeconds);
10121282 }
10131283
10141284 @Override
1015- public ChannelPipeline getPipeline() throws Exception {
1016- ChannelPipeline pipeline = Channels.pipeline();
1285+ protected void initChannel(SocketChannel channel) throws Exception {
1286+ ChannelPipeline pipeline = channel.pipeline();
10171287
10181288 if (sslOptions != null) {
10191289 SSLEngine engine = sslOptions.context.createSSLEngine();
10201290 engine.setUseClientMode(true);
10211291 engine.setEnabledCipherSuites(sslOptions.cipherSuites);
10221292 SslHandler handler = new SslHandler(engine);
1023- handler.setCloseOnSSLException(true);
10241293 pipeline.addLast("ssl", handler);
10251294 }
10261295
1027- //pipeline.addLast("debug", new LoggingHandler(InternalLogLevel.INFO));
1296+// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
10281297
10291298 pipeline.addLast("frameDecoder", new Frame.Decoder());
10301299 pipeline.addLast("frameEncoder", frameEncoder);
@@ -1041,7 +1310,7 @@
10411310
10421311 pipeline.addLast("dispatcher", connection.dispatcher);
10431312
1044- return pipeline;
1313+ nettyOptions.afterChannelInitialized(channel);
10451314 }
10461315
10471316 private Message.ProtocolEncoder messageEncoderFor(ProtocolVersion version) {
modified driver-core/src/main/java/com/datastax/driver/core/ConnectionException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +36 −24
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -620,40 +620,52 @@
620620 int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds();
621621 while (elapsed < maxSchemaAgreementWaitSeconds * 1000) {
622622
623- DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_PEERS));
624- DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL));
625- connection.write(peersFuture);
626- connection.write(localFuture);
623+ if (checkSchemaAgreement(connection, cluster))
624+ return true;
627625
628- Set<UUID> versions = new HashSet<UUID>();
626+ // let's not flood the node too much
627+ Thread.sleep(200);
629628
630- Row localRow = localFuture.get().one();
631- if (localRow != null && !localRow.isNull("schema_version"))
632- versions.add(localRow.getUUID("schema_version"));
629+ elapsed = Cluster.timeSince(start, TimeUnit.MILLISECONDS);
630+ }
633631
634- for (Row row : peersFuture.get()) {
632+ return false;
633+ }
635634
636- InetSocketAddress addr = addressToUseForPeerHost(row, connection.address, cluster, true);
637- if (addr == null || row.isNull("schema_version"))
638- continue;
635+ private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException {
636+ DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_PEERS));
637+ DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL));
638+ connection.write(peersFuture);
639+ connection.write(localFuture);
639640
640- Host peer = cluster.metadata.getHost(addr);
641- if (peer != null && peer.isUp())
642- versions.add(row.getUUID("schema_version"));
643- }
641+ Set<UUID> versions = new HashSet<UUID>();
644642
645- logger.debug("Checking for schema agreement: versions are {}", versions);
643+ Row localRow = localFuture.get().one();
644+ if (localRow != null && !localRow.isNull("schema_version"))
645+ versions.add(localRow.getUUID("schema_version"));
646646
647- if (versions.size() <= 1)
648- return true;
647+ for (Row row : peersFuture.get()) {
649648
650- // let's not flood the node too much
651- Thread.sleep(200);
649+ InetSocketAddress addr = addressToUseForPeerHost(row, connection.address, cluster, true);
650+ if (addr == null || row.isNull("schema_version"))
651+ continue;
652652
653- elapsed = Cluster.timeSince(start, TimeUnit.MILLISECONDS);
653+ Host peer = cluster.metadata.getHost(addr);
654+ if (peer != null && peer.isUp())
655+ versions.add(row.getUUID("schema_version"));
654656 }
657+ logger.debug("Checking for schema agreement: versions are {}", versions);
658+ return versions.size() <= 1;
659+ }
655660
656- return false;
661+ boolean checkSchemaAgreement() {
662+ Connection c = connectionRef.get();
663+ try {
664+ return c != null && checkSchemaAgreement(c, cluster);
665+ } catch (Exception e) {
666+ logger.warn("Error while checking schema agreement", e);
667+ return false;
668+ }
657669 }
658670
659671 boolean isOpen() {
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +3 −3
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@
2525 import com.google.common.collect.ImmutableList;
2626 import com.google.common.collect.ImmutableSet;
2727 import com.google.common.reflect.TypeToken;
28-import org.jboss.netty.buffer.ChannelBuffer;
28+import io.netty.buffer.ByteBuf;
2929
3030 import com.datastax.driver.core.exceptions.DriverInternalError;
3131 import com.datastax.driver.core.exceptions.InvalidTypeException;
@@ -166,7 +166,7 @@
166166 this.name = name;
167167 }
168168
169- static DataType decode(ChannelBuffer buffer) {
169+ static DataType decode(ByteBuf buffer) {
170170 Name name = Name.fromProtocolId(buffer.readUnsignedShort());
171171 switch (name) {
172172 case CUSTOM:
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +5 −3
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -111,7 +111,7 @@
111111 keyspace.removeUserType(scc.name);
112112 break;
113113 }
114- this.setResult(rs);
114+ session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs);
115115 break;
116116 case UPDATED:
117117 switch (scc.target) {
@@ -275,7 +275,9 @@
275275 if (!super.cancel(mayInterruptIfRunning))
276276 return false;
277277
278- handler.cancel();
278+ if(handler != null) {
279+ handler.cancel();
280+ }
279281 return true;
280282 }
281283
added driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +126 −0
@@ -0,0 +1,126 @@
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.net.InetSocketAddress;
19+import java.util.Collections;
20+
21+/**
22+ * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern).
23+ */
24+public abstract class DelegatingCluster extends Cluster {
25+ /**
26+ * Builds a new instance.
27+ */
28+ protected DelegatingCluster() {
29+ // Implementation notes:
30+ // If Cluster was an interface, delegates would be trivial to write. But, for historical reasons, it's a class,
31+ // and changing that would break backward compatibility. That makes delegates rather convoluted and error-prone
32+ // to write, so we provide DelegatingCluster to abstract the details.
33+ // This class ensures that:
34+ // - init() is never called on the parent class, because that would initialize the Cluster.Manager instance and
35+ // create a lot of internal state (thread pools, etc.) that we don't need, since another Cluster instance is
36+ // already handling the calls.
37+ // - all public methods are properly forwarded to the delegate (otherwise they would call the parent class and
38+ // return inconsistent results).
39+ // These two goals are closely related, since a lot of public methods call init(), so accidentally calling a
40+ // parent method could initialize the parent state.
41+
42+ // Construct parent class with dummy parameters that will never get used (since super.init() is never called).
43+ super("delegating_cluster", Collections.<InetSocketAddress>emptyList(), null);
44+
45+ // Immediately close the parent class's internal Manager, to make sure that it will fail fast if it's ever
46+ // accidentally invoked.
47+ super.closeAsync();
48+ }
49+
50+ /**
51+ * Returns the delegate instance where all calls will be forwarded.
52+ *
53+ * @return the delegate.
54+ */
55+ protected abstract Cluster delegate();
56+
57+ @Override
58+ public Cluster init() {
59+ return delegate().init();
60+ }
61+
62+ @Override
63+ public Session newSession() {
64+ return delegate().newSession();
65+ }
66+
67+ @Override
68+ public Session connect() {
69+ return delegate().connect();
70+ }
71+
72+ @Override
73+ public Session connect(String keyspace) {
74+ return delegate().connect(keyspace);
75+ }
76+
77+ @Override
78+ public Metadata getMetadata() {
79+ return delegate().getMetadata();
80+ }
81+
82+ @Override
83+ public Configuration getConfiguration() {
84+ return delegate().getConfiguration();
85+ }
86+
87+ @Override
88+ public Metrics getMetrics() {
89+ return delegate().getMetrics();
90+ }
91+
92+ @Override
93+ public Cluster register(Host.StateListener listener) {
94+ return delegate().register(listener);
95+ }
96+
97+ @Override
98+ public Cluster unregister(Host.StateListener listener) {
99+ return delegate().unregister(listener);
100+ }
101+
102+ @Override
103+ public Cluster register(LatencyTracker tracker) {
104+ return delegate().register(tracker);
105+ }
106+
107+ @Override
108+ public Cluster unregister(LatencyTracker tracker) {
109+ return delegate().unregister(tracker);
110+ }
111+
112+ @Override
113+ public CloseFuture closeAsync() {
114+ return delegate().closeAsync();
115+ }
116+
117+ @Override
118+ public void close() {
119+ delegate().close();
120+ }
121+
122+ @Override
123+ public boolean isClosed() {
124+ return delegate().isClosed();
125+ }
126+}
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +242 −95
@@ -21,12 +21,16 @@
2121 import java.util.concurrent.atomic.AtomicInteger;
2222 import java.util.concurrent.locks.*;
2323
24+import com.google.common.annotations.VisibleForTesting;
2425 import com.google.common.collect.Lists;
25-import com.google.common.util.concurrent.MoreExecutors;
26+import com.google.common.util.concurrent.*;
2627 import org.slf4j.Logger;
2728 import org.slf4j.LoggerFactory;
2829
2930 import com.datastax.driver.core.exceptions.AuthenticationException;
31+import com.datastax.driver.core.utils.MoreFutures;
32+
33+import static com.datastax.driver.core.Connection.State.*;
3034
3135 /**
3236 * A connection pool with a varying number of connections.
@@ -44,9 +48,15 @@
4448 // following threshold, we just replace the connection by a new one.
4549 private static final int MIN_AVAILABLE_STREAMS = 96;
4650
47- final List<PooledConnection> connections;
51+ final List<Connection> connections;
4852 private final AtomicInteger open;
49- private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
53+ /** The total number of in-flight requests on all connections of this pool. */
54+ final AtomicInteger totalInFlight = new AtomicInteger();
55+ /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
56+ private final AtomicInteger maxTotalInFlight = new AtomicInteger();
57+
58+ @VisibleForTesting
59+ final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
5060
5161 private volatile int waiter = 0;
5262 private final Lock waitLock = new ReentrantLock(true);
@@ -56,7 +66,7 @@
5666
5767 private final AtomicInteger scheduledForCreation = new AtomicInteger();
5868
59- public DynamicConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
69+ public DynamicConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
6070 super(host, hostDistance, manager);
6171
6272 this.newConnectionTask = new Runnable() {
@@ -67,37 +77,66 @@
6777 }
6878 };
6979
80+ this.connections = new CopyOnWriteArrayList<Connection>();
81+ this.open = new AtomicInteger();
82+ }
83+
84+ @Override
85+ ListenableFuture<Void> initAsync(Connection reusedConnection) {
7086 // Create initial core connections
71- List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance));
72- try {
73- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
74- l.add(manager.connectionFactory().open(this));
75- } catch (InterruptedException e) {
76- Thread.currentThread().interrupt();
77- // If asked to interrupt, we can skip opening core connections, the pool will still work.
78- // But we ignore otherwise cause I'm not sure we can do much better currently.
79- } catch (ConnectionException e) {
80- forceClose(l);
81- throw e;
82- } catch (UnsupportedProtocolVersionException e) {
83- forceClose(l);
84- throw e;
85- } catch (ClusterNameMismatchException e) {
86- forceClose(l);
87- throw e;
88- } catch (RuntimeException e) {
89- forceClose(l);
90- throw e;
87+ int capacity = options().getCoreConnectionsPerHost(hostDistance);
88+ final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
89+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
90+ for (int i = 0; i < capacity; i++) {
91+ Connection connection;
92+ ListenableFuture<Void> connectionFuture;
93+ // reuse the existing connection only once
94+ if (reusedConnection != null && reusedConnection.setPool(this)) {
95+ connection = reusedConnection;
96+ connectionFuture = MoreFutures.VOID_SUCCESS;
97+ } else {
98+ connection = manager.connectionFactory().newConnection(this);
99+ connectionFuture = connection.initAsync();
100+ }
101+ reusedConnection = null;
102+ connections.add(connection);
103+ connectionFutures.add(connectionFuture);
91104 }
92- this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
93- this.open = new AtomicInteger(connections.size());
94105
95- logger.trace("Created connection pool to host {}", host);
106+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
107+
108+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
109+
110+ final SettableFuture<Void> initFuture = SettableFuture.create();
111+ Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
112+ @Override
113+ public void onSuccess(List<Void> l) {
114+ DynamicConnectionPool.this.connections.addAll(connections);
115+ open.set(l.size());
116+ if (isClosed()) {
117+ initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
118+ // we're not sure if closeAsync() saw the connections, so ensure they get closed
119+ forceClose(connections);
120+ } else {
121+ logger.trace("Created connection pool to host {}", host);
122+ phase = Phase.READY;
123+ initFuture.set(null);
124+ }
125+ }
126+
127+ @Override
128+ public void onFailure(Throwable t) {
129+ phase = Phase.INIT_FAILED;
130+ forceClose(connections);
131+ initFuture.setException(t);
132+ }
133+ }, initExecutor);
134+ return initFuture;
96135 }
97136
98137 // Clean up if we got an error at construction time but still created part of the core connections
99- private void forceClose(List<PooledConnection> l) {
100- for (PooledConnection connection : l) {
138+ private void forceClose(List<Connection> connections) {
139+ for (Connection connection : connections) {
101140 connection.closeAsync().force();
102141 }
103142 }
@@ -107,11 +146,14 @@
107146 }
108147
109148 @Override
110- public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
111- if (isClosed())
149+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
150+ if (phase == Phase.INITIALIZING)
151+ throw new ConnectionException(host.getSocketAddress(), "Pool is initializing.");
152+
153+ if (phase != Phase.READY)
112154 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
113155 // That being said, maybe having a specific exception could be cleaner.
114- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
156+ throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
115157
116158 if (connections.isEmpty()) {
117159 for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
@@ -120,14 +162,15 @@
120162 scheduledForCreation.incrementAndGet();
121163 manager.blockingExecutor().submit(newConnectionTask);
122164 }
123- PooledConnection c = waitForConnection(timeout, unit);
165+ Connection c = waitForConnection(timeout, unit);
166+ totalInFlight.incrementAndGet();
124167 c.setKeyspace(manager.poolsState.keyspace);
125168 return c;
126169 }
127170
128171 int minInFlight = Integer.MAX_VALUE;
129- PooledConnection leastBusy = null;
130- for (PooledConnection connection : connections) {
172+ Connection leastBusy = null;
173+ for (Connection connection : connections) {
131174 int inFlight = connection.inFlight.get();
132175 if (inFlight < minInFlight) {
133176 minInFlight = inFlight;
@@ -135,9 +178,6 @@
135178 }
136179 }
137180
138- if (minInFlight >= options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance) && connections.size() < options().getMaxConnectionsPerHost(hostDistance))
139- maybeSpawnNewConnection();
140-
141181 if (leastBusy == null) {
142182 // We could have raced with a shutdown since the last check
143183 if (isClosed())
@@ -159,6 +199,24 @@
159199 break;
160200 }
161201 }
202+
203+ int totalInFlightCount = totalInFlight.incrementAndGet();
204+ // update max atomically:
205+ while (true) {
206+ int oldMax = maxTotalInFlight.get();
207+ if (totalInFlightCount <= oldMax || maxTotalInFlight.compareAndSet(oldMax, totalInFlightCount))
208+ break;
209+ }
210+
211+ int connectionCount = open.get() + scheduledForCreation.get();
212+ if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
213+ // Add a connection if we fill the first n-1 connections and almost fill the last one
214+ int currentCapacity = (connectionCount - 1) * StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2
215+ + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance);
216+ if (totalInFlightCount > currentCapacity)
217+ maybeSpawnNewConnection();
218+ }
219+
162220 leastBusy.setKeyspace(manager.poolsState.keyspace);
163221 return leastBusy;
164222 }
@@ -200,7 +258,7 @@
200258 }
201259 }
202260
203- private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
261+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
204262 if (timeout == 0)
205263 throw new TimeoutException();
206264
@@ -219,8 +277,8 @@
219277 throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
220278
221279 int minInFlight = Integer.MAX_VALUE;
222- PooledConnection leastBusy = null;
223- for (PooledConnection connection : connections) {
280+ Connection leastBusy = null;
281+ for (Connection connection : connections) {
224282 int inFlight = connection.inFlight.get();
225283 if (inFlight < minInFlight) {
226284 minInFlight = inFlight;
@@ -249,8 +307,9 @@
249307 }
250308
251309 @Override
252- public void returnConnection(PooledConnection connection) {
253- int inFlight = connection.inFlight.decrementAndGet();
310+ public void returnConnection(Connection connection) {
311+ connection.inFlight.decrementAndGet();
312+ totalInFlight.decrementAndGet();
254313
255314 if (isClosed()) {
256315 close(connection);
@@ -263,13 +322,8 @@
263322 return;
264323 }
265324
266- if (trash.contains(connection)) {
267- if (inFlight == 0 && trash.remove(connection))
268- close(connection);
269- } else {
270- if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) {
271- trashConnection(connection);
272- } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
325+ if (connection.state.get() != TRASHED) {
326+ if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
273327 replaceConnection(connection);
274328 } else {
275329 signalAvailableConnection();
@@ -279,45 +333,39 @@
279333
280334 // Trash the connection and create a new one, but we don't call trashConnection
281335 // directly because we want to make sure the connection is always trashed.
282- private void replaceConnection(PooledConnection connection) {
283- if (connection.markForTrash.compareAndSet(false, true))
284- open.decrementAndGet();
336+ private void replaceConnection(Connection connection) {
337+ if (!connection.state.compareAndSet(OPEN, TRASHED))
338+ return;
339+ open.decrementAndGet();
285340 maybeSpawnNewConnection();
341+ connection.maxIdleTime = Long.MIN_VALUE;
286342 doTrashConnection(connection);
287343 }
288344
289- private boolean trashConnection(PooledConnection connection) {
290- if (connection.markForTrash.compareAndSet(false, true)) {
291- // First, make sure we don't go below core connections
292- for (;;) {
293- int opened = open.get();
294- if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
295- connection.markForTrash.set(false);
296- return false;
297- }
345+ private boolean trashConnection(Connection connection) {
346+ if (!connection.state.compareAndSet(OPEN, TRASHED))
347+ return true;
298348
299- if (open.compareAndSet(opened, opened - 1))
300- break;
349+ // First, make sure we don't go below core connections
350+ for (;;) {
351+ int opened = open.get();
352+ if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
353+ connection.state.set(OPEN);
354+ return false;
301355 }
302356
303- doTrashConnection(connection);
357+ if (open.compareAndSet(opened, opened - 1))
358+ break;
304359 }
305- // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection.
306- // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do
307- // it:
308- // - the current thread decremented inFlight in returnConnection
309- // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))`
310- // in returnConnection and not arrived here.
311- // - so the other thread will see the up-to-date value of inFlight and take appropriate action.
360+ logger.trace("Trashing {}", connection);
361+ connection.maxIdleTime = System.currentTimeMillis() + options().getIdleTimeoutSeconds() * 1000;
362+ doTrashConnection(connection);
312363 return true;
313364 }
314365
315- private void doTrashConnection(PooledConnection connection) {
316- trash.add(connection);
366+ private void doTrashConnection(Connection connection) {
317367 connections.remove(connection);
318-
319- if (connection.inFlight.get() == 0 && trash.remove(connection))
320- close(connection);
368+ trash.add(connection);
321369 }
322370
323371 private boolean addConnectionIfUnderMaximum() {
@@ -332,14 +380,29 @@
332380 break;
333381 }
334382
335- if (isClosed()) {
383+ if (phase != Phase.READY) {
336384 open.decrementAndGet();
337385 return false;
338386 }
339387
340388 // Now really open the connection
341389 try {
342- connections.add(manager.connectionFactory().open(this));
390+ Connection newConnection = tryResurrectFromTrash();
391+ if (newConnection == null) {
392+ logger.debug("Creating new connection on busy pool to {}", host);
393+ newConnection = manager.connectionFactory().open(this);
394+ }
395+ connections.add(newConnection);
396+
397+ newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
398+
399+ // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
400+ if (phase != Phase.READY && !newConnection.isClosed()) {
401+ close(newConnection);
402+ open.decrementAndGet();
403+ return false;
404+ }
405+
343406 signalAvailableConnection();
344407 return true;
345408 } catch (InterruptedException e) {
@@ -368,6 +431,27 @@
368431 }
369432 }
370433
434+ private Connection tryResurrectFromTrash() {
435+ long highestMaxIdleTime = System.currentTimeMillis();
436+ Connection chosen = null;
437+
438+ while (true) {
439+ for (Connection connection : trash)
440+ if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) {
441+ chosen = connection;
442+ highestMaxIdleTime = connection.maxIdleTime;
443+ }
444+
445+ if (chosen == null)
446+ return null;
447+ else if (chosen.state.compareAndSet(TRASHED, RESURRECTING))
448+ break;
449+ }
450+ logger.trace("Resurrecting {}", chosen);
451+ trash.remove(chosen);
452+ return chosen;
453+ }
454+
371455 private void maybeSpawnNewConnection() {
372456 while (true) {
373457 int inCreation = scheduledForCreation.get();
@@ -377,22 +461,73 @@
377461 break;
378462 }
379463
380- logger.debug("Creating new connection on busy pool to {}", host);
381464 manager.blockingExecutor().submit(newConnectionTask);
382465 }
383466
384467 @Override
385- public void replaceDefunctConnection(final PooledConnection connection) {
386- if (connection.markForTrash.compareAndSet(false, true))
468+ void replaceDefunctConnection(final Connection connection) {
469+ if (connection.state.compareAndSet(OPEN, GONE))
387470 open.decrementAndGet();
388- connections.remove(connection);
471+ if (connections.remove(connection))
472+ manager.blockingExecutor().submit(new Runnable() {
473+ @Override
474+ public void run() {
475+ addConnectionIfUnderMaximum();
476+ }
477+ });
389478 connection.closeAsync();
390- manager.blockingExecutor().submit(new Runnable() {
391- @Override
392- public void run() {
393- addConnectionIfUnderMaximum();
479+ }
480+
481+ @Override
482+ void cleanupIdleConnections(long now) {
483+ if (isClosed())
484+ return;
485+
486+ shrinkIfBelowCapacity();
487+ cleanupTrash(now);
488+ }
489+
490+ /** If we have more active connections than needed, trash some of them */
491+ private void shrinkIfBelowCapacity() {
492+ int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
493+
494+ int needed = currentLoad / StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 + 1;
495+ if (currentLoad % StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 > options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance))
496+ needed += 1;
497+ needed = Math.max(needed, options().getCoreConnectionsPerHost(hostDistance));
498+ int actual = open.get();
499+ int toTrash = Math.max(0, actual - needed);
500+
501+ logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
502+ currentLoad, needed, actual, toTrash);
503+
504+ if (toTrash <= 0)
505+ return;
506+
507+ for (Connection connection : connections)
508+ if (trashConnection(connection)) {
509+ toTrash -= 1;
510+ if (toTrash == 0)
511+ return;
512+ }
513+ }
514+
515+ /** Close connections that have been sitting in the trash for too long */
516+ private void cleanupTrash(long now) {
517+ for (Connection connection : trash) {
518+ if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
519+ if (connection.inFlight.get() == 0) {
520+ logger.trace("Cleaning up {}", connection);
521+ trash.remove(connection);
522+ close(connection);
523+ } else {
524+ // Given that idleTimeout >> request timeout, all outstanding requests should
525+ // have finished by now, so we should not get here.
526+ // Restore the status so that it's retried on the next cleanup.
527+ connection.state.set(TRASHED);
528+ }
394529 }
395- });
530+ }
396531 }
397532
398533 private void close(final Connection connection) {
@@ -400,6 +535,8 @@
400535 }
401536
402537 protected CloseFuture makeCloseFuture() {
538+ phase = Phase.CLOSING;
539+
403540 // Wake up all threads that wait
404541 signalAllAvailableConnection();
405542
@@ -408,21 +545,26 @@
408545 }
409546
410547 private List<CloseFuture> discardAvailableConnections() {
411- // This can happen if creating the connections in the constructor fails
412- if (connections == null)
413- return Lists.newArrayList(CloseFuture.immediateFuture());
414-
415- List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size());
416- for (final PooledConnection connection : connections) {
548+ // Note: if this gets called before initialization has completed, both connections and trash will be empty,
549+ // so this will return an empty list
550+
551+ List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
552+
553+ for (final Connection connection : connections) {
417554 CloseFuture future = connection.closeAsync();
418555 future.addListener(new Runnable() {
419556 public void run() {
420- if (connection.markForTrash.compareAndSet(false, true))
557+ if (connection.state.compareAndSet(OPEN, GONE))
421558 open.decrementAndGet();
422559 }
423560 }, MoreExecutors.sameThreadExecutor());
424561 futures.add(future);
425562 }
563+
564+ // Some connections in the trash might still be open if they hadn't reached their idle timeout
565+ for (Connection connection : trash)
566+ futures.add(connection.closeAsync());
567+
426568 return futures;
427569 }
428570
@@ -450,6 +592,11 @@
450592 return open.get();
451593 }
452594
595+ @Override
596+ int trashed() {
597+ return trash.size();
598+ }
599+
453600 @Override
454601 public int inFlightQueriesCount() {
455602 int count = 0;
modified driver-core/src/main/java/com/datastax/driver/core/ExceptionCatchingRunnable.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +74 −24
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,56 +15,65 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.nio.ByteBuffer;
1819 import java.util.List;
1920
2021 /**
21- * Basic informations on the execution of a query.
22- * <p>
23- * This provides the following information on the execution of a (successful)
24- * query:
25- * <ul>
26- * <li>The list of Cassandra hosts tried in order (usually just one, unless
27- * a node has been tried but was dead/in error or a timeout provoked a retry
28- * (which depends on the RetryPolicy)).</li>
29- * <li>The consistency level achieved by the query (usually the one asked,
30- * though some specific RetryPolicy may allow this to be different).</li>
31- * <li>The query trace recorded by Cassandra if tracing had been set for the
32- * query.</li>
33- * </ul>
22+ * Basic information on the execution of a query.
3423 */
35-public class ExecutionInfo
36-{
24+public class ExecutionInfo {
3725 private final List<Host> triedHosts;
3826 private final ConsistencyLevel achievedConsistency;
3927 private final QueryTrace trace;
28+ private final ByteBuffer pagingState;
29+ private final ProtocolVersion protocolVersion;
30+ private final Statement statement;
31+ private volatile boolean schemaInAgreement;
4032
41- private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace) {
33+ private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace, ByteBuffer pagingState, ProtocolVersion protocolVersion, Statement statement, boolean schemaAgreement) {
4234 this.triedHosts = triedHosts;
4335 this.achievedConsistency = achievedConsistency;
4436 this.trace = trace;
37+ this.pagingState = pagingState;
38+ this.protocolVersion = protocolVersion;
39+ this.statement = statement;
40+ this.schemaInAgreement = schemaAgreement;
4541 }
4642
4743 ExecutionInfo(List<Host> triedHosts) {
48- this(triedHosts, null, null);
44+ this(triedHosts, null, null, null, null, null, true);
4945 }
5046
5147 ExecutionInfo withTrace(QueryTrace newTrace) {
52- return new ExecutionInfo(triedHosts, achievedConsistency, newTrace);
48+ return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, protocolVersion, statement, schemaInAgreement);
5349 }
5450
5551 ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) {
56- return new ExecutionInfo(triedHosts, newConsistency, trace);
52+ return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement);
53+ }
54+
55+ ExecutionInfo withPagingState(ByteBuffer pagingState, ProtocolVersion protocolVersion) {
56+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement);
57+ }
58+
59+ ExecutionInfo withStatement(Statement statement) {
60+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement);
5761 }
5862
5963 /**
6064 * The list of tried hosts for this query.
6165 * <p>
6266 * In general, this will be a singleton list with the host that coordinated
63- * that query. However, if an host is tried by the driver but is dead or in
64- * error, that host is recorded and the query is retry. Also, on a timeout
65- * or unavailable exception, some
67+ * that query. However:
68+ * <ul>
69+ * <li>if a host is tried by the driver but is dead or in
70+ * error, that host is recorded and the query is retried;</li>
71+ * <li>on a timeout or unavailable exception, some
6672 * {@link com.datastax.driver.core.policies.RetryPolicy} may retry the
67- * query on the same host, so the same host might appear twice.
73+ * query on the same host, so the same host might appear twice.</li>
74+ * <li>if {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}
75+ * are enabled, other hosts might have been tried speculatively as well.</li>
76+ * </ul>
6877 * <p>
6978 * If you are only interested in fetching the final (and often only) node
7079 * coordinating the query, {@link #getQueriedHost} provides a shortcut to
@@ -119,4 +128,45 @@
119128 public QueryTrace getQueryTrace() {
120129 return trace;
121130 }
131+
132+ /**
133+ * The paging state of the query.
134+ *
135+ * This object represents the next page to be fetched if this query is
136+ * multi page. It can be saved and reused later on the same statement.
137+ *
138+ * @return the paging state or null if there is no next page.
139+ *
140+ * @see Statement#setPagingState(PagingState)
141+ */
142+ public PagingState getPagingState() {
143+ if (this.pagingState == null)
144+ return null;
145+ return new PagingState(this.pagingState, this.statement, this.protocolVersion);
146+ }
147+
148+ /**
149+ * Whether the cluster had reached schema agreement after the execution of this query.
150+ *
151+ * After a successful schema-altering query (ex: creating a table), the driver
152+ * will check if the cluster's nodes agree on the new schema version. If not,
153+ * it will keep retrying for a given delay (configurable via
154+ * {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}).
155+ * <p>
156+ * If this method returns {@code false}, clients can call {@link Metadata#checkSchemaAgreement()}
157+ * later to perform the check manually.
158+ * <p>
159+ * Note that the schema agreement check is only performed for schema-altering queries
160+ * For other query types, this method will always return {@code true}.
161+ *
162+ * @return whether the cluster reached schema agreement, or {@code true} for a non
163+ * schema-altering statement.
164+ */
165+ public boolean isSchemaInAgreement() {
166+ return schemaInAgreement;
167+ }
168+
169+ void setSchemaInAgreement(boolean schemaAgreement) {
170+ this.schemaInAgreement = schemaAgreement;
171+ }
122172 }
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +90 −109
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,26 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.IOException;
1918 import java.util.EnumSet;
19+import java.util.List;
2020
21-import org.jboss.netty.buffer.ChannelBuffer;
22-import org.jboss.netty.buffer.ChannelBuffers;
23-import org.jboss.netty.channel.Channel;
24-import org.jboss.netty.channel.ChannelHandlerContext;
25-import org.jboss.netty.handler.codec.frame.CorruptedFrameException;
26-import org.jboss.netty.handler.codec.frame.FrameDecoder;
27-import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
28-import org.jboss.netty.handler.codec.frame.TooLongFrameException;
29-import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
30-import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
21+import io.netty.buffer.ByteBuf;
22+import io.netty.channel.ChannelHandler;
23+import io.netty.channel.ChannelHandlerContext;
24+import io.netty.handler.codec.*;
3125
3226 import com.datastax.driver.core.exceptions.DriverInternalError;
3327
3428 class Frame {
3529
3630 public final Header header;
37- public final ChannelBuffer body;
31+ public final ByteBuf body;
3832
3933 /**
4034 * On-wire frame.
@@ -58,12 +52,12 @@
5852 * | length |
5953 * +---------+
6054 */
61- private Frame(Header header, ChannelBuffer body) {
55+ private Frame(Header header, ByteBuf body) {
6256 this.header = header;
6357 this.body = body;
6458 }
6559
66- private static Frame create(ChannelBuffer fullFrame) {
60+ private static Frame create(ByteBuf fullFrame) {
6761 assert fullFrame.readableBytes() >= 1 : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());
6862
6963 int versionBytes = fullFrame.readByte();
@@ -82,7 +76,7 @@
8276 return new Frame(header, fullFrame);
8377 }
8478
85- private static int readStreamid(ChannelBuffer fullFrame, ProtocolVersion version) {
79+ private static int readStreamid(ByteBuf fullFrame, ProtocolVersion version) {
8680 switch (version) {
8781 case V1:
8882 case V2:
@@ -94,7 +88,7 @@
9488 }
9589 }
9690
97- public static Frame create(ProtocolVersion version, int opcode, int streamId, EnumSet<Header.Flag> flags, ChannelBuffer body) {
91+ public static Frame create(ProtocolVersion version, int opcode, int streamId, EnumSet<Header.Flag> flags, ByteBuf body) {
9892 Header header = new Header(version, flags, streamId, opcode);
9993 return new Frame(header, body);
10094 }
@@ -154,104 +148,83 @@
154148 }
155149 }
156150
157- public Frame with(ChannelBuffer newBody) {
151+ public Frame with(ByteBuf newBody) {
158152 return new Frame(header, newBody);
159153 }
160154
161- public static final class Decoder extends FrameDecoder {
162- static final DecoderV1 decoderV1 = new DecoderV1();
163- static final DecoderV3 decoderV3 = new DecoderV3();
155+ public static final class Decoder extends ByteToMessageDecoder {
156+ static final DecoderForStreamIdSize decoderV1 = new DecoderForStreamIdSize(1);
157+ static final DecoderForStreamIdSize decoderV3 = new DecoderForStreamIdSize(2);
158+
159+ @Override
160+ protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
161+ if (buffer.readableBytes() < 1)
162+ return;
164163
165- @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
166164 int version = buffer.getByte(0);
167165 // version first bit is the "direction" of the frame (request or response)
168166 version = version & 0x7F;
169167
170- return version >= 3 ? decoderV3.decode(ctx, channel, buffer) : decoderV1.decode(ctx, channel, buffer);
171- }
172- }
173-
174- public static class DecoderV1 extends LengthFieldBasedFrameDecoder {
175-
176- private static final int MAX_FRAME_LENTH = 256 * 1024 * 1024; // 256 MB
177-
178- public DecoderV1() {
179- super(MAX_FRAME_LENTH, 4, 4, 0, 0, true);
168+ DecoderForStreamIdSize decoder = (version >= 3) ? decoderV3 : decoderV1;
169+ Object frame = decoder.decode(ctx, buffer);
170+ if (frame != null)
171+ out.add(frame);
180172 }
181173
182- @Override
183- protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
184- try {
185- if (buffer.readableBytes() < 4)
186- return null;
187-
188- // Validate the opcode (this will throw if it's not a response)
189- Message.Response.Type.fromOpcode(buffer.getByte(3));
190-
191- ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
192- if (frame == null) {
193- return null;
194- }
174+ static class DecoderForStreamIdSize extends LengthFieldBasedFrameDecoder {
175+ private static final int MAX_FRAME_LENGTH = 256 * 1024 * 1024; // 256 MB
176+ private final int opcodeOffset;
195177
196- return Frame.create(frame);
197- } catch (CorruptedFrameException e) {
198- throw new DriverInternalError(e.getMessage());
199- } catch (TooLongFrameException e) {
200- throw new DriverInternalError(e.getMessage());
178+ DecoderForStreamIdSize(int streamIdSize) {
179+ super(MAX_FRAME_LENGTH, /*lengthOffset=*/ 3 + streamIdSize, 4, 0, 0, true);
180+ this.opcodeOffset = 2 + streamIdSize;
201181 }
202- }
203- }
204-
205- public static class DecoderV3 extends LengthFieldBasedFrameDecoder {
206182
207- private static final int MAX_FRAME_LENTH = 256 * 1024 * 1024; // 256 MB
208-
209- public DecoderV3() {
210- super(MAX_FRAME_LENTH, 5, 4, 0, 0, true);
211- }
212-
213- @Override
214- protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
215- try {
216- if (buffer.readableBytes() < 4)
217- return null;
218-
219- // Validate the opcode (this will throw if it's not a response)
220- Message.Response.Type.fromOpcode(buffer.getByte(4));
221-
222- ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
223- if (frame == null) {
224- return null;
183+ @Override
184+ protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
185+ try {
186+ if (buffer.readableBytes() < opcodeOffset + 1)
187+ return null;
188+
189+ // Validate the opcode (this will throw if it's not a response)
190+ Message.Response.Type.fromOpcode(buffer.getByte(opcodeOffset));
191+
192+ ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
193+ if (frame == null) {
194+ return null;
195+ }
196+ // Do not deallocate `frame` just yet, because it is stored as Frame.body and will be used
197+ // in Message.ProtocolDecoder or Frame.Decompressor if compression is enabled (we deallocate
198+ // it there).
199+ return Frame.create(frame);
200+ } catch (CorruptedFrameException e) {
201+ throw new DriverInternalError(e.getMessage());
202+ } catch (TooLongFrameException e) {
203+ throw new DriverInternalError(e.getMessage());
225204 }
226-
227- return Frame.create(frame);
228- } catch (CorruptedFrameException e) {
229- throw new DriverInternalError(e.getMessage());
230- } catch (TooLongFrameException e) {
231- throw new DriverInternalError(e.getMessage());
232205 }
233206 }
234207 }
235208
236- public static class Encoder extends OneToOneEncoder {
237-
238- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws IOException {
239- assert msg instanceof Frame : "Expecting frame, got " + msg;
209+ @ChannelHandler.Sharable
210+ public static class Encoder extends MessageToMessageEncoder<Frame> {
240211
241- Frame frame = (Frame)msg;
212+ @Override
213+ protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
242214 ProtocolVersion protocolVersion = frame.header.version;
243-
244- ChannelBuffer header = ChannelBuffers.buffer(Header.lengthFor(protocolVersion));
215+ ByteBuf header = ctx.alloc().ioBuffer(Frame.Header.lengthFor(protocolVersion));
245216 // We don't bother with the direction, we only send requests.
246217 header.writeByte(frame.header.version.toInt());
247218 header.writeByte(Header.Flag.serialize(frame.header.flags));
248219 writeStreamId(frame.header.streamId, header, protocolVersion);
249220 header.writeByte(frame.header.opcode);
250221 header.writeInt(frame.body.readableBytes());
251- return ChannelBuffers.wrappedBuffer(header, frame.body);
222+
223+ out.add(header);
224+ out.add(frame.body);
252225 }
253226
254- private void writeStreamId(int streamId, ChannelBuffer header, ProtocolVersion protocolVersion) {
227+ private void writeStreamId(int streamId, ByteBuf header, ProtocolVersion protocolVersion) {
255228 switch (protocolVersion) {
256229 case V1:
257230 case V2:
@@ -266,7 +239,7 @@
266239 }
267240 }
268241
269- public static class Decompressor extends OneToOneDecoder {
242+ public static class Decompressor extends MessageToMessageDecoder<Frame> {
270243
271244 private final FrameCompressor compressor;
272245
@@ -275,19 +248,24 @@
275248 this.compressor = compressor;
276249 }
277250
278- public Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws IOException {
279-
280- assert msg instanceof Frame : "Expecting frame, got " + msg;
281-
282- Frame frame = (Frame)msg;
283-
284- return frame.header.flags.contains(Header.Flag.COMPRESSED)
285- ? compressor.decompress(frame)
286- : frame;
251+ @Override
252+ protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
253+ if (frame.header.flags.contains(Header.Flag.COMPRESSED)) {
254+ // All decompressors allocate a new buffer for the decompressed data, so this is the last time
255+ // we have a reference to the compressed body (and therefore a chance to release it).
256+ ByteBuf compressedBody = frame.body;
257+ try {
258+ out.add(compressor.decompress(frame));
259+ } finally {
260+ compressedBody.release();
261+ }
262+ } else {
263+ out.add(frame);
264+ }
287265 }
288266 }
289267
290- public static class Compressor extends OneToOneEncoder {
268+ public static class Compressor extends MessageToMessageEncoder<Frame> {
291269
292270 private final FrameCompressor compressor;
293271
@@ -296,18 +274,21 @@
296274 this.compressor = compressor;
297275 }
298276
299- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws IOException {
300-
301- assert msg instanceof Frame : "Expecting frame, got " + msg;
302-
303- Frame frame = (Frame)msg;
304-
277+ @Override
278+ protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
305279 // Never compress STARTUP messages
306- if (frame.header.opcode == Message.Request.Type.STARTUP.opcode)
307- return frame;
308-
309- frame.header.flags.add(Header.Flag.COMPRESSED);
310- return compressor.compress(frame);
280+ if (frame.header.opcode == Message.Request.Type.STARTUP.opcode) {
281+ out.add(frame);
282+ } else {
283+ frame.header.flags.add(Header.Flag.COMPRESSED);
284+ // See comment in decode()
285+ ByteBuf uncompressedBody = frame.body;
286+ try {
287+ out.add(compressor.compress(frame));
288+ } finally {
289+ uncompressedBody.release();
290+ }
291+ }
311292 }
312293 }
313294 }
modified driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +7 −6
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -17,8 +17,8 @@
1717
1818 import java.io.IOException;
1919
20+import io.netty.buffer.Unpooled;
2021 import net.jpountz.lz4.LZ4Factory;
21-import org.jboss.netty.buffer.ChannelBuffers;
2222 import org.slf4j.Logger;
2323 import org.slf4j.LoggerFactory;
2424 import org.xerial.snappy.Snappy;
@@ -60,7 +60,7 @@
6060 byte[] output = new byte[Snappy.maxCompressedLength(input.length)];
6161
6262 int written = Snappy.compress(input, 0, input.length, output, 0);
63- return frame.with(ChannelBuffers.wrappedBuffer(output, 0, written));
63+ return frame.with(Unpooled.wrappedBuffer(output, 0, written));
6464 }
6565
6666 public Frame decompress(Frame frame) throws IOException {
@@ -71,7 +71,7 @@
7171
7272 byte[] output = new byte[Snappy.uncompressedLength(input)];
7373 int size = Snappy.uncompress(input, 0, input.length, output, 0);
74- return frame.with(ChannelBuffers.wrappedBuffer(output, 0, size));
74+ return frame.with(Unpooled.wrappedBuffer(output, 0, size));
7575 }
7676 }
7777
@@ -98,6 +98,7 @@
9898
9999 private LZ4Compressor() {
100100 final LZ4Factory lz4Factory = LZ4Factory.fastestInstance();
101+ logger.info("Using {}", lz4Factory.toString());
101102 compressor = lz4Factory.fastCompressor();
102103 decompressor = lz4Factory.fastDecompressor();
103104 }
@@ -115,7 +116,7 @@
115116
116117 try {
117118 int written = compressor.compress(input, 0, input.length, output, INTEGER_BYTES, maxCompressedLength);
118- return frame.with(ChannelBuffers.wrappedBuffer(output, 0, INTEGER_BYTES + written));
119+ return frame.with(Unpooled.wrappedBuffer(output, 0, INTEGER_BYTES + written));
119120 } catch (Exception e) {
120121 throw new IOException(e);
121122 }
@@ -136,7 +137,7 @@
136137 if (read != input.length - INTEGER_BYTES)
137138 throw new IOException("Compressed lengths mismatch");
138139
139- return frame.with(ChannelBuffers.wrappedBuffer(output));
140+ return frame.with(Unpooled.wrappedBuffer(output));
140141 } catch (Exception e) {
141142 throw new IOException(e);
142143 }
modified driver-core/src/main/java/com/datastax/driver/core/GettableData.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +25 −19
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -27,8 +27,6 @@
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
30-import com.datastax.driver.core.policies.ReconnectionPolicy;
31-
3230 /**
3331 * A Cassandra node.
3432 *
@@ -41,7 +39,7 @@
4139
4240 private final InetSocketAddress address;
4341
44- enum State { ADDED, DOWN, SUSPECT, UP }
42+ enum State { ADDED, DOWN, UP }
4543 volatile State state;
4644 /** Ensures state change notifications for that host are handled serially */
4745 final ReentrantLock notificationsLock = new ReentrantLock(true);
@@ -49,9 +47,6 @@
4947 private final ConvictionPolicy policy;
5048 private final Cluster.Manager manager;
5149
52- // Tracks the first "immediate" reconnection attempt when a node get suspected.
53- final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null));
54-
5550 // Tracks later reconnection attempts to that host so we avoid adding multiple tasks.
5651 final AtomicReference<ListenableFuture<?>> reconnectionAttempt = new AtomicReference<ListenableFuture<?>>();
5752
@@ -188,9 +183,20 @@
188183 * @return whether the node is considered up.
189184 */
190185 public boolean isUp() {
191- // Consider a suspected host UP until proved otherwise to avoid
192- // having the status flapping if it turns out the host is not really down.
193- return state == State.UP || state == State.SUSPECT;
186+ return state == State.UP;
187+ }
188+
189+ /**
190+ * Returns a description of the host's state, as seen by the driver.
191+ * <p>
192+ * This is exposed for debugging purposes only; the format of this string might
193+ * change between driver versions, so clients should not make any assumptions
194+ * about it.
195+ *
196+ * @return a description of the host's state.
197+ */
198+ public String getState() {
199+ return state.name();
194200 }
195201
196202 /**
@@ -201,9 +207,13 @@
201207 * we are trying suspected nodes.
202208 *
203209 * @return the future.
210+ *
211+ * @deprecated the suspicion mechanism has been disabled. This will always return
212+ * a completed future.
204213 */
214+ @Deprecated
205215 public ListenableFuture<?> getInitialReconnectionAttemptFuture() {
206- return initialReconnectionAttempt.get();
216+ return Futures.immediateFuture(null);
207217 }
208218
209219 /**
@@ -271,14 +281,6 @@
271281 state = State.UP;
272282 }
273283
274- boolean setSuspected() {
275- if (state != State.UP)
276- return false;
277-
278- state = State.SUSPECT;
279- return true;
280- }
281-
282284 boolean signalConnectionFailure(ConnectionException exception) {
283285 return policy.addFailure(exception);
284286 }
@@ -328,7 +330,11 @@
328330 * that is suspected down turns out to be truly down (that is, the driver
329331 * cannot successfully connect to it right away), then {@link #onDown} will
330332 * be called.
333+ *
334+ * @deprecated the suspicion mechanism has been disabled. This will never
335+ * get called.
331336 */
337+ @Deprecated
332338 public void onSuspected(Host host);
333339
334340 /**
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +20 −4
@@ -19,6 +19,8 @@
1919 import java.util.concurrent.TimeoutException;
2020 import java.util.concurrent.atomic.AtomicReference;
2121
22+import com.google.common.util.concurrent.ListenableFuture;
23+
2224 /**
2325 * A set of connections to a live host.
2426 *
@@ -26,7 +28,7 @@
2628 */
2729 abstract class HostConnectionPool {
2830
29- static HostConnectionPool newInstance(Host host, HostDistance hostDistance, SessionManager manager, ProtocolVersion version) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
31+ static HostConnectionPool newInstance(Host host, HostDistance hostDistance, SessionManager manager, ProtocolVersion version) {
3032 switch (version) {
3133 case V1:
3234 case V2:
@@ -44,6 +46,9 @@
4446
4547 protected final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
4648
49+ protected enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
50+ protected volatile Phase phase = Phase.INITIALIZING;
51+
4752 protected HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
4853 assert hostDistance != HostDistance.IGNORED;
4954 this.host = host;
@@ -51,16 +56,27 @@
5156 this.manager = manager;
5257 }
5358
54- abstract PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException;
59+ /**
60+ * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
61+ * reuse as part of this pool. Might be null or already used by another
62+ * pool.
63+ */
64+ abstract ListenableFuture<Void> initAsync(Connection reusedConnection);
5565
56- abstract void returnConnection(PooledConnection connection);
66+ abstract Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException;
67+
68+ abstract void returnConnection(Connection connection);
5769
5870 abstract void ensureCoreConnections();
5971
60- abstract void replaceDefunctConnection(final PooledConnection connection);
72+ abstract void replaceDefunctConnection(final Connection connection);
73+
74+ abstract void cleanupIdleConnections(long now);
6175
6276 abstract int opened();
6377
78+ abstract int trashed();
79+
6480 abstract int inFlightQueriesCount();
6581
6682 protected abstract CloseFuture makeCloseFuture();
modified driver-core/src/main/java/com/datastax/driver/core/HostDistance.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java +17 −11
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -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 }
modified driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +63 −25
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,15 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.nio.ByteBuffer;
1819 import java.util.EnumSet;
20+import java.util.List;
1921 import java.util.UUID;
2022
21-import org.jboss.netty.buffer.ChannelBuffer;
22-import org.jboss.netty.buffer.ChannelBuffers;
23-import org.jboss.netty.channel.Channel;
24-import org.jboss.netty.channel.ChannelHandlerContext;
25-import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
26-import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
23+import io.netty.buffer.ByteBuf;
24+import io.netty.channel.ChannelHandler;
25+import io.netty.channel.ChannelHandlerContext;
26+import io.netty.handler.codec.MessageToMessageDecoder;
27+import io.netty.handler.codec.MessageToMessageEncoder;
2728 import org.slf4j.Logger;
2829 import org.slf4j.LoggerFactory;
2930
@@ -37,12 +38,12 @@
3738 protected static final Logger logger = LoggerFactory.getLogger(Message.class);
3839
3940 public interface Coder<R extends Request> {
40- public void encode(R request, ChannelBuffer dest, ProtocolVersion version);
41+ public void encode(R request, ByteBuf dest, ProtocolVersion version);
4142 public int encodedSize(R request, ProtocolVersion version);
4243 }
4344
4445 public interface Decoder<R extends Response> {
45- public R decode(ChannelBuffer body, ProtocolVersion version);
46+ public R decode(ByteBuf body, ProtocolVersion version);
4647 }
4748
4849 private volatile int streamId;
@@ -94,6 +95,41 @@
9495 public boolean isTracingRequested() {
9596 return tracingRequested;
9697 }
98+
99+ ConsistencyLevel consistency() {
100+ switch (this.type) {
101+ case QUERY: return ((Requests.Query)this).options.consistency;
102+ case EXECUTE: return ((Requests.Execute)this).options.consistency;
103+ case BATCH: return ((Requests.Batch)this).options.consistency;
104+ default: return null;
105+ }
106+ }
107+
108+ ConsistencyLevel serialConsistency() {
109+ switch (this.type) {
110+ case QUERY: return ((Requests.Query)this).options.serialConsistency;
111+ case EXECUTE: return ((Requests.Execute)this).options.serialConsistency;
112+ case BATCH: return ((Requests.Batch)this).options.serialConsistency;
113+ default: return null;
114+ }
115+ }
116+
117+ long defaultTimestamp() {
118+ switch (this.type) {
119+ case QUERY: return ((Requests.Query)this).options.defaultTimestamp;
120+ case EXECUTE: return ((Requests.Execute)this).options.defaultTimestamp;
121+ case BATCH: return ((Requests.Batch)this).options.defaultTimestamp;
122+ default: return 0;
123+ }
124+ }
125+
126+ ByteBuffer pagingState() {
127+ switch (this.type) {
128+ case QUERY: return ((Requests.Query)this).options.pagingState;
129+ case EXECUTE: return ((Requests.Execute)this).options.pagingState;
130+ default: return null;
131+ }
132+ }
97133 }
98134
99135 public static abstract class Response extends Message {
@@ -156,21 +192,26 @@
156192 }
157193 }
158194
159- public static class ProtocolDecoder extends OneToOneDecoder {
195+ @ChannelHandler.Sharable
196+ public static class ProtocolDecoder extends MessageToMessageDecoder<Frame> {
160197
161- public Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) {
162- assert msg instanceof Frame : "Expecting frame, got " + msg;
163-
164- Frame frame = (Frame)msg;
198+ @Override
199+ protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
165200 boolean isTracing = frame.header.flags.contains(Frame.Header.Flag.TRACING);
166201 UUID tracingId = isTracing ? CBUtil.readUUID(frame.body) : null;
167202
168- Response response = Response.Type.fromOpcode(frame.header.opcode).decoder.decode(frame.body, frame.header.version);
169- return response.setTracingId(tracingId).setStreamId(frame.header.streamId);
203+ try {
204+ Response response = Response.Type.fromOpcode(frame.header.opcode).decoder.decode(frame.body, frame.header.version);
205+ response.setTracingId(tracingId).setStreamId(frame.header.streamId);
206+ out.add(response);
207+ } finally {
208+ frame.body.release();
209+ }
170210 }
171211 }
172212
173- public static class ProtocolEncoder extends OneToOneEncoder {
213+ @ChannelHandler.Sharable
214+ public static class ProtocolEncoder extends MessageToMessageEncoder<Request> {
174215
175216 private final ProtocolVersion protocolVersion;
176217
@@ -178,21 +219,18 @@
178219 this.protocolVersion = version;
179220 }
180221
181- @SuppressWarnings("unchecked")
182- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) {
183- assert msg instanceof Request : "Expecting request, got " + msg;
184-
185- Request request = (Request)msg;
186-
222+ @Override
223+ protected void encode(ChannelHandlerContext ctx, Request request, List<Object> out) throws Exception {
187224 EnumSet<Frame.Header.Flag> flags = EnumSet.noneOf(Frame.Header.Flag.class);
188225 if (request.isTracingRequested())
189226 flags.add(Frame.Header.Flag.TRACING);
190227
228+ @SuppressWarnings("unchecked")
191229 Coder<Request> coder = (Coder<Request>)request.type.coder;
192- ChannelBuffer body = ChannelBuffers.buffer(coder.encodedSize(request, protocolVersion));
230+ ByteBuf body = ctx.alloc().buffer(coder.encodedSize(request, protocolVersion));
193231 coder.encode(request, body, protocolVersion);
194232
195- return Frame.create(protocolVersion, request.type.opcode, request.getStreamId(), flags, body);
233+ out.add(Frame.create(protocolVersion, request.type.opcode, request.getStreamId(), flags, body));
196234 }
197235 }
198236 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +14 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -383,6 +383,19 @@
383383 return new HashSet<Host>(allHosts());
384384 }
385385
386+ /**
387+ * Checks whether hosts that are currently up agree on the schema definition.
388+ * <p>
389+ * This method performs a one-time check only, without any form of retry; therefore {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}
390+ * does not apply in this case.
391+ *
392+ * @return {@code true} if all hosts agree on the schema; {@code false} if they don't agree, or if the check could not be performed
393+ * (for example, if the control connection is down).
394+ */
395+ public boolean checkSchemaAgreement() {
396+ return cluster.controlConnection.checkSchemaAgreement();
397+ }
398+
386399 /**
387400 * Returns the metadata of a keyspace given its name.
388401 *
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +40 −4
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -18,11 +18,10 @@
1818 import java.util.HashSet;
1919 import java.util.Set;
2020
21-import com.codahale.metrics.Gauge;
22-import com.codahale.metrics.MetricRegistryListener;
23-
2421 import com.codahale.metrics.*;
2522
23+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
24+
2625 /**
2726 * Metrics exposed by the driver.
2827 * <p>
@@ -69,6 +68,16 @@
6968 return value;
7069 }
7170 });
71+ private final Gauge<Integer> trashedConnections = registry.register("trashed-connections", new Gauge<Integer>() {
72+ @Override
73+ public Integer getValue() {
74+ int value = 0;
75+ for (SessionManager session : manager.sessions)
76+ for (HostConnectionPool pool : session.pools.values())
77+ value += pool.trashed();
78+ return value;
79+ }
80+ });
7281
7382 private final Gauge<Integer> executorQueueDepth = registry.register("executor-queue-depth", new Gauge<Integer>() {
7483 @Override
@@ -205,6 +214,20 @@
205214 return openConnections;
206215 }
207216
217+ /**
218+ * Returns the total number of currently "trashed" connections to Cassandra hosts.
219+ * <p>
220+ * When the load to a host decreases, the driver will reclaim some connections in order to save
221+ * resources. No requests are sent to these connections anymore, but they are kept open for an
222+ * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load
223+ * goes up again. This metric counts connections in that state.
224+ *
225+ * @return The total number of currently trashed connections to Cassandra hosts.
226+ */
227+ public Gauge<Integer> getTrashedConnections() {
228+ return trashedConnections;
229+ }
230+
208231 /**
209232 * @return The number of queued up tasks in the non-blocking executor (Cassandra Java Driver workers).
210233 */
@@ -262,6 +285,8 @@
262285 private final Counter ignoresOnReadTimeout = registry.counter("ignores-on-read-timeout");
263286 private final Counter ignoresOnUnavailable = registry.counter("ignores-on-unavailable");
264287
288+ private final Counter speculativeExecutions = registry.counter("speculative-executions");
289+
265290 /**
266291 * Returns the number of connection to Cassandra nodes errors.
267292 * <p>
@@ -421,5 +446,16 @@
421446 public Counter getIgnoresOnUnavailable() {
422447 return ignoresOnUnavailable;
423448 }
449+
450+ /**
451+ * Returns the number of times a speculative execution was started
452+ * because a previous execution did not complete within the delay
453+ * specified by {@link SpeculativeExecutionPolicy}.
454+ *
455+ * @return the number of speculative executions.
456+ */
457+ public Counter getSpeculativeExecutions() {
458+ return speculativeExecutions;
459+ }
424460 }
425461 }
modified driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +202 −0
@@ -0,0 +1,202 @@
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.concurrent.ThreadFactory;
19+import java.util.concurrent.TimeUnit;
20+
21+import static java.util.concurrent.TimeUnit.SECONDS;
22+
23+import io.netty.bootstrap.Bootstrap;
24+import io.netty.buffer.ByteBufAllocator;
25+import io.netty.buffer.PooledByteBufAllocator;
26+import io.netty.channel.ChannelOption;
27+import io.netty.channel.EventLoopGroup;
28+import io.netty.channel.nio.NioEventLoopGroup;
29+import io.netty.channel.socket.SocketChannel;
30+import io.netty.channel.socket.nio.NioSocketChannel;
31+
32+/**
33+ * A set of hooks that allow clients to customize the driver's underlying Netty layer.
34+ * <p>
35+ * Clients that need to hook into the driver's underlying Netty layer can
36+ * subclass this class and provide the necessary customization by overriding
37+ * its methods.
38+ * <p>
39+ * Typically, clients would register this class with {@link Cluster#builder()}:
40+ *
41+ * <pre>
42+ * NettyOptions nettyOptions = ...
43+ * Cluster cluster = Cluster.builder()
44+ * .addContactPoint(...)
45+ * .withNettyOptions(nettyOptions)
46+ * .build();
47+ * </pre>
48+ *
49+ * <strong>Extending the NettyOptions API</strong>
50+ * <p>
51+ * Contrary to other driver options, the options available in this class should
52+ * be considered as advanced features and as such, <em>they should only be
53+ * modified by expert users</em>.
54+ * <p>
55+ * <strong>A misconfiguration introduced by the means of this API can have unexpected results
56+ * and cause the driver to completely fail to connect.</strong>
57+ * <p>
58+ * Moreover, since versions 2.0.9 and 2.1.4 (see JAVA-538),
59+ * the driver is available in two different flavors: with a standard Maven dependency on Netty,
60+ * or with a "shaded" (internalized) Netty dependency.
61+ * <p>
62+ * Given that NettyOptions API exposes Netty classes ({@link SocketChannel}, etc.),
63+ * <em>it should only be extended by clients using the non-shaded
64+ * version of driver</em>.
65+ * <p>
66+ * <strong>Extending this API with shaded Netty classes is not supported,
67+ * and in particular for OSGi applications, it is likely that such a configuration would lead to
68+ * compile and/or runtime errors.</strong>
69+ *
70+ * @jira_ticket JAVA-640
71+ * @since 2.0.10
72+ */
73+public class NettyOptions {
74+
75+ /**
76+ * The default instance of {@link NettyOptions} to use.
77+ */
78+ public static final NettyOptions DEFAULT_INSTANCE = new NettyOptions();
79+
80+ /**
81+ * Return the {@link EventLoopGroup} instance to use.
82+ * <p>
83+ * This hook is invoked only once at {@link Cluster} initialization;
84+ * the returned instance will be kept in use throughout the cluster lifecycle.
85+ * <p>
86+ * Typically, implementors would return a newly-created instance;
87+ * it is however possible to re-use a shared instance, but in this
88+ * case implementors should also override {@link #onClusterClose(EventLoopGroup)}
89+ * to prevent the shared instance to be closed when the cluster is closed.
90+ * <p>
91+ * The default implementation returns a new instance of {@link io.netty.channel.epoll.EpollEventLoopGroup}
92+ * if {@link NettyUtil#isEpollAvailable() epoll is available},
93+ * or {@link NioEventLoopGroup} otherwise.
94+ *
95+ * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link EventLoopGroup} instance;
96+ * The driver will provide its own internal thread factory here.
97+ * It is safe to ignore it and use another thread factory.
98+ * @return the {@link EventLoopGroup} instance to use.
99+ */
100+ public EventLoopGroup eventLoopGroup(ThreadFactory threadFactory) {
101+ return NettyUtil.newEventLoopGroupInstance(threadFactory);
102+ }
103+
104+ /**
105+ * Return the specific {@link SocketChannel} subclass to use.
106+ * <p>
107+ * This hook is invoked only once at {@link Cluster} initialization;
108+ * the returned instance will then be used each time the driver creates a new {@link Connection}
109+ * and configures a new instance of {@link Bootstrap} for it.
110+ * <p>
111+ * The default implementation returns {@link io.netty.channel.epoll.EpollSocketChannel} if {@link NettyUtil#isEpollAvailable() epoll is available},
112+ * or {@link NioSocketChannel} otherwise.
113+ *
114+ * @return The {@link SocketChannel} subclass to use.
115+ */
116+ public Class<? extends SocketChannel> channelClass() {
117+ return NettyUtil.channelClass();
118+ }
119+
120+ /**
121+ * Hook invoked each time the driver creates a new {@link Connection}
122+ * and configures a new instance of {@link Bootstrap} for it.
123+ * <p>
124+ * This hook is guaranteed to be called <em>after</em> the driver has applied all
125+ * {@link SocketOptions}s.
126+ * <p>
127+ * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelOption}s to the boostrap; e.g.
128+ * plug a custom {@link io.netty.buffer.ByteBufAllocator ByteBufAllocator} implementation:
129+ *
130+ * <pre>
131+ * ByteBufAllocator myCustomByteBufAllocator = ...
132+ *
133+ * public void afterBootstrapInitialized(Bootstrap bootstrap) {
134+ * bootstrap.option(ChannelOption.ALLOCATOR, myCustomByteBufAllocator);
135+ * }
136+ * </pre>
137+ *
138+ * Note that the default implementation of this method configures a pooled {@code ByteBufAllocator} (Netty 4.0
139+ * defaults to unpooled). If you override this method to set unrelated options, make sure you call
140+ * {@code super.afterBootstrapInitialized(bootstrap)}.
141+ *
142+ * @param bootstrap the {@link Bootstrap} being initialized.
143+ */
144+ public void afterBootstrapInitialized(Bootstrap bootstrap) {
145+ // In Netty 4.1.x, pooled will be the default, so this won't be necessary anymore
146+ bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
147+ }
148+
149+ /**
150+ * Hook invoked each time the driver creates a new {@link Connection}
151+ * and initializes the {@link SocketChannel channel}.
152+ * <p>
153+ * This hook is guaranteed to be called <em>after</em> the driver has registered
154+ * all its internal channel handlers, and applied the configured {@link SSLOptions}, if any.
155+ * <p>
156+ * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelHandler}s
157+ * to the channel's pipeline; e.g. to add a custom SSL handler to the beginning of the handler chain,
158+ * do the following:
159+ *
160+ * <pre>
161+ * ChannelPipeline pipeline = channel.pipeline();
162+ * SSLEngine myCustomSSLEngine = ...
163+ * SslHandler myCustomSSLHandler = new SslHandler(myCustomSSLEngine);
164+ * pipeline.addFirst("ssl", myCustomSSLHandler);
165+ * </pre>
166+ *
167+ * Note: if you intend to provide your own SSL implementation,
168+ * do not enable the driver's built-in {@link SSLOptions} at the same time.
169+ *
170+ * @param channel the {@link SocketChannel} instance, after being initialized by the driver.
171+ * @throws Exception if this methods encounters any errors.
172+ */
173+ public void afterChannelInitialized(SocketChannel channel) throws Exception {
174+ //noop
175+ }
176+
177+ /**
178+ * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
179+ * <p>
180+ * This is guaranteed to be called only after all connections have been individually
181+ * closed, and their channels closed, and only once per {@link EventLoopGroup} instance.
182+ * <p>
183+ * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required.
184+ * <p>
185+ * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully(long, long, TimeUnit) graceful shutdown}
186+ * of the passed {@link EventLoopGroup} instance with no "quiet period" and a timeout of 15 seconds;
187+ * then waits uninterruptibly for the shutdown to complete, or the timeout to occur, whichever happens first.
188+ * <p>
189+ * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to
190+ * coordinate Netty events for the current cluster, than it should not be shut down here;
191+ * subclasses would have to override this method accordingly to take the appropriate action.
192+ *
193+ * @param eventLoopGroup the event loop group used by the cluster being closed
194+ */
195+ public void onClusterClose(EventLoopGroup eventLoopGroup) {
196+ // shutdownGracefully with default parameters employs a quiet period of 2 seconds
197+ // where in pre-Netty4 versions, closing a cluster instance was very quick (milliseconds).
198+ // Since we close the channels before shutting down the eventLoopGroup,
199+ // it is safe to reduce the quiet period to 0 seconds
200+ eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly();
201+ }
202+}
added driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java +160 −0
@@ -0,0 +1,160 @@
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.lang.reflect.Constructor;
19+import java.util.Locale;
20+import java.util.concurrent.ThreadFactory;
21+
22+import com.google.common.base.Throwables;
23+import io.netty.channel.EventLoopGroup;
24+import io.netty.channel.nio.NioEventLoopGroup;
25+import io.netty.channel.socket.SocketChannel;
26+import io.netty.channel.socket.nio.NioSocketChannel;
27+import org.slf4j.Logger;
28+import org.slf4j.LoggerFactory;
29+
30+/**
31+ * A set of utilities related to the underlying Netty layer.
32+ */
33+@SuppressWarnings("unchecked")
34+class NettyUtil {
35+
36+ private static final boolean FORCE_NIO = SystemProperties.getBoolean("com.datastax.driver.FORCE_NIO", false);
37+
38+ private static final Logger LOGGER = LoggerFactory.getLogger(NettyUtil.class);
39+
40+ private static final boolean SHADED;
41+
42+ private static final boolean USE_EPOLL;
43+
44+ private static final Constructor<? extends EventLoopGroup> EPOLL_EVENT_LOOP_GROUP_CONSTRUCTOR;
45+
46+ private static final Class<? extends SocketChannel> EPOLL_CHANNEL_CLASS;
47+
48+ private static final Class[] EVENT_GROUP_ARGUMENTS = { int.class, ThreadFactory.class };
49+
50+ static {
51+ boolean shaded;
52+ try {
53+ // prevent this string from being shaded
54+ Class.forName(String.format("%s.%s.channel.Channel", "io", "netty"));
55+ shaded = false;
56+ } catch (ClassNotFoundException e) {
57+ try {
58+ Class.forName("com.datastax.shaded.netty.channel.Channel");
59+ shaded = true;
60+ } catch (ClassNotFoundException e1) {
61+ throw new AssertionError("Cannot locate Netty classes in the classpath:" + e1);
62+ }
63+ }
64+ SHADED = shaded;
65+ boolean useEpoll = false;
66+ if (!SHADED) {
67+ try {
68+ Class<?> epoll = Class.forName("io.netty.channel.epoll.Epoll");
69+ if (FORCE_NIO) {
70+ LOGGER.info("Found Netty's native epoll transport in the classpath, "
71+ + "but NIO was forced through the FORCE_NIO system property.");
72+ } else if (!System.getProperty("os.name", "").toLowerCase(Locale.US).equals("linux")) {
73+ LOGGER.warn("Found Netty's native epoll transport, but not running on linux-based operating " +
74+ "system. Using NIO instead.");
75+ } else if (!(Boolean)epoll.getMethod("isAvailable").invoke(null)) {
76+ LOGGER.warn("Found Netty's native epoll transport in the classpath, but epoll is not available. "
77+ + "Using NIO instead.", (Throwable)epoll.getMethod("unavailabilityCause").invoke(null));
78+ } else {
79+ LOGGER.info("Found Netty's native epoll transport in the classpath, using it");
80+ useEpoll = true;
81+ }
82+ } catch (ClassNotFoundException e) {
83+ LOGGER.info("Did not find Netty's native epoll transport in the classpath, defaulting to NIO.");
84+ } catch (Exception e) {
85+ LOGGER.warn("Unexpected error trying to find Netty's native epoll transport in the classpath, defaulting to NIO.", e);
86+ }
87+ } else {
88+ LOGGER.info("Detected shaded Netty classes in the classpath; native epoll transport will not work properly, "
89+ + "defaulting to NIO.");
90+ }
91+ USE_EPOLL = useEpoll;
92+ Constructor<? extends EventLoopGroup> constructor = null;
93+ Class<? extends SocketChannel> channelClass = null;
94+ if (USE_EPOLL) {
95+ try {
96+ channelClass = (Class<? extends SocketChannel>)Class.forName("io.netty.channel.epoll.EpollSocketChannel");
97+ Class<?> epoolEventLoupGroupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup");
98+ constructor = (Constructor<? extends EventLoopGroup>)epoolEventLoupGroupClass.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS);
99+ } catch (Exception e) {
100+ throw new AssertionError("Netty's native epoll is in use but cannot locate Epoll classes, this should not happen: " + e);
101+ }
102+ }
103+ EPOLL_EVENT_LOOP_GROUP_CONSTRUCTOR = constructor;
104+ EPOLL_CHANNEL_CLASS = channelClass;
105+ }
106+
107+ /**
108+ *
109+ * @return true if the current driver bundle is using shaded Netty classes, false otherwise.
110+ */
111+
112+ public static boolean isShaded() {
113+ return SHADED;
114+ }
115+
116+ /**
117+ * @return true if native epoll transport is available in the classpath, false otherwise.
118+ */
119+ public static boolean isEpollAvailable() {
120+ return USE_EPOLL;
121+ }
122+
123+ /**
124+ * Return a new instance of {@link EventLoopGroup}.
125+ * <p>
126+ * Returns an instance of {@link io.netty.channel.epoll.EpollEventLoopGroup} if {@link #isEpollAvailable() epoll is available},
127+ * or an instance of {@link NioEventLoopGroup} otherwise.
128+ *
129+ * @param factory the {@link ThreadFactory} instance to use to create the new instance of {@link EventLoopGroup}
130+ * @return a new instance of {@link EventLoopGroup}
131+ */
132+ public static EventLoopGroup newEventLoopGroupInstance(ThreadFactory factory) {
133+ if (isEpollAvailable()) {
134+ try {
135+ return EPOLL_EVENT_LOOP_GROUP_CONSTRUCTOR.newInstance(0, factory);
136+ } catch (Exception e) {
137+ throw Throwables.propagate(e); // should not happen
138+ }
139+ } else {
140+ return new NioEventLoopGroup(0, factory);
141+ }
142+ }
143+
144+ /**
145+ * Return the SocketChannel class to use.
146+ * <p>
147+ * Returns an instance of {@link io.netty.channel.epoll.EpollSocketChannel} if {@link #isEpollAvailable() epoll is available},
148+ * or an instance of {@link NioSocketChannel} otherwise.
149+ *
150+ * @return the SocketChannel class to use.
151+ */
152+ public static Class<? extends SocketChannel> channelClass() {
153+ if (isEpollAvailable()) {
154+ return EPOLL_CHANNEL_CLASS;
155+ } else {
156+ return NioSocketChannel.class;
157+ }
158+ }
159+
160+}
modified driver-core/src/main/java/com/datastax/driver/core/OperationTimedOutException.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.net.InetSocketAddress;
added driver-core/src/main/java/com/datastax/driver/core/PagingState.java +172 −0
@@ -0,0 +1,172 @@
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+
17+package com.datastax.driver.core;
18+
19+import java.nio.ByteBuffer;
20+import java.security.MessageDigest;
21+import java.security.NoSuchAlgorithmException;
22+import java.util.Arrays;
23+
24+import com.datastax.driver.core.exceptions.PagingStateException;
25+import com.datastax.driver.core.utils.Bytes;
26+
27+/**
28+ * The paging state of a query.
29+ *
30+ * This object represents the next page to be fetched if the query is
31+ * multi page. It can be saved and reused later on the same statement.
32+ *
33+ * The PagingState can be serialized and deserialized either as a String
34+ * or as a byte array.
35+ *
36+ * @see Statement#setPagingState(PagingState)
37+ */
38+public class PagingState {
39+
40+ private byte[] pagingState;
41+ private byte[] hash;
42+ private ProtocolVersion protocolVersion;
43+
44+ PagingState(ByteBuffer pagingState, Statement statement, ProtocolVersion protocolVersion) {
45+ this.pagingState = Bytes.getArray(pagingState);
46+ this.hash = hash(statement, protocolVersion);
47+ this.protocolVersion = protocolVersion;
48+ }
49+
50+ // The serialized form of the paging state is:
51+ // size of raw state|size of hash|raw state|hash|protocol version
52+ //
53+ // The protocol version might be absent, in which case it defaults to V2 (this is for backward
54+ // compatibility with 2.0.10 where it is always absent).
55+ private PagingState(byte[] complete) {
56+ // Check the sizes in the beginning of the buffer, otherwise we cannot build the paging state object
57+ ByteBuffer pagingStateBB = ByteBuffer.wrap(complete);
58+ int pagingSize = pagingStateBB.getShort();
59+ int hashSize = pagingStateBB.getShort();
60+ if (pagingSize + hashSize != pagingStateBB.remaining() && pagingSize + hashSize + 2 != pagingStateBB.remaining()) {
61+ throw new PagingStateException("Cannot deserialize paging state, invalid format. "
62+ + "The serialized form was corrupted, or not initially generated from a PagingState object.");
63+ }
64+ this.pagingState = new byte[pagingSize];
65+ pagingStateBB.get(this.pagingState);
66+ this.hash = new byte[hashSize];
67+ pagingStateBB.get(this.hash);
68+ this.protocolVersion = (pagingStateBB.remaining() > 0)
69+ ? ProtocolVersion.fromInt(pagingStateBB.getShort())
70+ : ProtocolVersion.V2;
71+ }
72+
73+ private byte[] hash(Statement statement, ProtocolVersion protocolVersion) {
74+ byte[] digest;
75+ ByteBuffer[] values;
76+ MessageDigest md;
77+ assert !(statement instanceof BatchStatement);
78+ try {
79+ md = MessageDigest.getInstance("MD5");
80+ if (statement instanceof BoundStatement) {
81+ BoundStatement bs = ((BoundStatement)statement);
82+ md.update(bs.preparedStatement().getQueryString().getBytes());
83+ values = bs.wrapper.values;
84+ } else {
85+ //it is a RegularStatement since Batch statements are not allowed
86+ RegularStatement rs = (RegularStatement)statement;
87+ md.update(rs.getQueryString().getBytes());
88+ values = rs.getValues(protocolVersion);
89+ }
90+ if (values != null) {
91+ for (ByteBuffer value : values) {
92+ md.update(value.duplicate());
93+ }
94+ }
95+ md.update(this.pagingState);
96+ digest = md.digest();
97+
98+ } catch (NoSuchAlgorithmException e) {
99+ throw new RuntimeException("MD5 doesn't seem to be available on this JVM", e);
100+ }
101+ return digest;
102+ }
103+
104+ boolean matches(Statement statement) {
105+ byte[] toTest = hash(statement, protocolVersion);
106+ return Arrays.equals(toTest, this.hash);
107+ }
108+
109+ private ByteBuffer generateCompleteOutput() {
110+ ByteBuffer res = ByteBuffer.allocate(pagingState.length + hash.length + 6);
111+
112+ res.putShort((short)pagingState.length);
113+ res.putShort((short)hash.length);
114+
115+ res.put(pagingState);
116+ res.put(hash);
117+
118+ res.putShort((short)protocolVersion.toInt());
119+
120+ res.rewind();
121+
122+ return res;
123+ }
124+
125+ ByteBuffer getRawState() {
126+ return ByteBuffer.wrap(this.pagingState);
127+ }
128+
129+ @Override
130+ public String toString() {
131+ return Bytes.toRawHexString(generateCompleteOutput());
132+ }
133+
134+ /**
135+ * Create a PagingState object from a string previously generated with {@link #toString()}.
136+ *
137+ * @param string the string value.
138+ * @return the PagingState object created.
139+ *
140+ * @throws PagingStateException if the string does not have the correct format.
141+ */
142+ public static PagingState fromString(String string) {
143+ try {
144+ byte[] complete = Bytes.fromRawHexString(string, 0);
145+ return new PagingState(complete);
146+ } catch (Exception e) {
147+ throw new PagingStateException("Cannot deserialize paging state, invalid format. "
148+ + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
149+ }
150+ }
151+
152+ /**
153+ * Return a representation of the paging state object as a byte array.
154+ *
155+ * @return the paging state as a byte array.
156+ */
157+ public byte[] toBytes() {
158+ return generateCompleteOutput().array();
159+ }
160+
161+ /**
162+ * Create a PagingState object from a byte array previously generated with {@link #toBytes()}.
163+ *
164+ * @param pagingState The byte array representation.
165+ * @return the PagingState object created.
166+ *
167+ * @throws PagingStateException if the byte array does not have the correct format.
168+ */
169+ public static PagingState fromBytes(byte[] pagingState) {
170+ return new PagingState(pagingState);
171+ }
172+}
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/PlainTextAuthProvider.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
deleted driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +0 −63
@@ -1,63 +0,0 @@
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.net.InetSocketAddress;
19-import java.util.concurrent.atomic.AtomicBoolean;
20-
21-/**
22- * A connection that is associated to a pool.
23- */
24-class PooledConnection extends Connection {
25-
26- final HostConnectionPool pool;
27-
28- /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
29- final AtomicBoolean markForTrash = new AtomicBoolean();
30-
31- PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
32- super(name, address, factory);
33- this.pool = pool;
34- }
35-
36- /**
37- * Return the pooled connection to its pool.
38- * The connection should generally not be reused after that.
39- */
40- public void release() {
41- // This can happen if the query to initialize the transport in the
42- // parent constructor times out. In that case the pool will handle
43- // it itself.
44- if (pool == null)
45- return;
46-
47- pool.returnConnection(this);
48- }
49-
50- @Override
51- protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
52- // This can happen if an exception is thrown at construction time. In
53- // that case the pool will handle it itself.
54- if (pool == null)
55- return;
56-
57- if (hostIsDown) {
58- pool.closeAsync().force();
59- } else {
60- pool.replaceDefunctConnection(this);
61- }
62- }
63-}
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +86 −39
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.concurrent.Executor;
19+
20+import com.google.common.base.Preconditions;
21+import com.google.common.util.concurrent.MoreExecutors;
22+
1823 /**
1924 * Options related to connection pooling.
2025 * <p>
@@ -32,14 +37,7 @@
3237 * more connections are created up to the configurable maximum number of
3338 * connections ({@link #getMaxConnectionsPerHost}). When the pool exceeds
3439 * the maximum number of connections, connections in excess are
35- * reclaimed if the use of opened connections drops below the
36- * configured threshold ({@link #getMinSimultaneousRequestsPerConnectionThreshold}).
37- * <p>
38- * Due to known issues with the current {@code ProtocolVersion#V2} pool implementation (see
39- * <a href="https://datastax-oss.atlassian.net/browse/JAVA-419">JAVA-419</a>),
40- * it is <b>strongly recommended</b> to use a fixed-size pool (core connections =
41- * max connections).
42- * The default values respect this (8 for local hosts, 2 for remote hosts).
40+ * reclaimed.
4341 * <p>
4442 * <b>With {@code ProtocolVersion#V3} or above:</b>
4543 * the driver uses a single connection for each {@code LOCAL} or {@code REMOTE}
@@ -52,11 +50,10 @@
5250 */
5351 public class PoolingOptions {
5452
55- private static final int DEFAULT_MIN_REQUESTS_PER_CONNECTION = 25;
5653 private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 100;
5754
58- private static final int DEFAULT_CORE_POOL_LOCAL = 8;
59- private static final int DEFAULT_CORE_POOL_REMOTE = 2;
55+ private static final int DEFAULT_CORE_POOL_LOCAL = 2;
56+ private static final int DEFAULT_CORE_POOL_REMOTE = 1;
6057
6158 private static final int DEFAULT_MAX_POOL_LOCAL = 8;
6259 private static final int DEFAULT_MAX_POOL_REMOTE = 2;
@@ -64,12 +61,14 @@
6461 private static final int DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL = 1024;
6562 private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256;
6663
64+ private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
6765 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
6866 private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
6967
68+ private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor();
69+
7070 private volatile Cluster.Manager manager;
7171
72- private final int[] minSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MIN_REQUESTS_PER_CONNECTION, DEFAULT_MIN_REQUESTS_PER_CONNECTION, 0 };
7372 private final int[] maxSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MAX_REQUESTS_PER_CONNECTION, DEFAULT_MAX_REQUESTS_PER_CONNECTION, 0 };
7473
7574 private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
@@ -77,11 +76,13 @@
7776
7877 private volatile int maxSimultaneousRequestsPerHostLocal = DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL;
7978 private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE;
80-
81-
79+
80+ private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
8281 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
8382 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
8483
84+ private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
85+
8586 public PoolingOptions() {}
8687
8788 void register(Cluster.Manager manager) {
@@ -104,9 +105,12 @@
104105 *
105106 * @param distance the {@code HostDistance} for which to return this threshold.
106107 * @return the configured threshold, or the default one if none have been set.
108+ *
109+ * @deprecated this option isn't used anymore with the current pool resizing algorithm.
107110 */
111+ @Deprecated
108112 public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
109- return minSimultaneousRequestsPerConnection[distance.ordinal()];
113+ return 0;
110114 }
111115
112116 /**
@@ -121,14 +125,11 @@
121125 *
122126 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code minSimultaneousRequests}
123127 * is not in range, or if {@code newMinSimultaneousRequests} is greater than the maximum value for this distance.
128+ *
129+ * @deprecated this option isn't used anymore with the current pool resizing algorithm.
124130 */
131+ @Deprecated
125132 public synchronized PoolingOptions setMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMinSimultaneousRequests) {
126- if (distance == HostDistance.IGNORED)
127- throw new IllegalArgumentException("Cannot set min simultaneous requests per connection threshold for " + distance + " hosts");
128-
129- checkRequestsPerConnectionRange(newMinSimultaneousRequests, "Min simultaneous requests per connection", distance);
130- checkRequestsPerConnectionOrder(newMinSimultaneousRequests, maxSimultaneousRequestsPerConnection[distance.ordinal()], distance);
131- minSimultaneousRequestsPerConnection[distance.ordinal()] = newMinSimultaneousRequests;
132133 return this;
133134 }
134135
@@ -175,7 +176,6 @@
175176 throw new IllegalArgumentException("Cannot set max simultaneous requests per connection threshold for " + distance + " hosts");
176177
177178 checkRequestsPerConnectionRange(newMaxSimultaneousRequests, "Max simultaneous requests per connection", distance);
178- checkRequestsPerConnectionOrder(minSimultaneousRequestsPerConnection[distance.ordinal()], newMaxSimultaneousRequests, distance);
179179 maxSimultaneousRequestsPerConnection[distance.ordinal()] = newMaxSimultaneousRequests;
180180 return this;
181181 }
@@ -200,11 +200,6 @@
200200 * Sets the core number of connections per host.
201201 * <p>
202202 * This option is only used with {@code ProtocolVersion#V2} or below.
203- * <p>
204- * Due to known issues with the current pool implementation (see
205- * <a href="https://datastax-oss.atlassian.net/browse/JAVA-419">JAVA-419</a>),
206- * it is <b>strongly recommended</b> to use a fixed-size pool (core connections =
207- * max connections).
208203 *
209204 * @param distance the {@code HostDistance} for which to set this threshold.
210205 * @param newCoreConnections the value to set
@@ -244,11 +239,6 @@
244239 * Sets the maximum number of connections per host.
245240 * <p>
246241 * This option is only used with {@code ProtocolVersion#V2} or below.
247- * <p>
248- * Due to known issues with the current pool implementation (see
249- * <a href="https://datastax-oss.atlassian.net/browse/JAVA-419">JAVA-419</a>),
250- * it is <b>strongly recommended</b> to use a fixed-size pool (core connections =
251- * max connections).
252242 *
253243 * @param distance the {@code HostDistance} for which to set this threshold.
254244 * @param newMaxConnections the value to set
@@ -266,6 +256,33 @@
266256 return this;
267257 }
268258
259+ /**
260+ * Returns the timeout before an idle connection is removed.
261+ *
262+ * @return the timeout.
263+ */
264+ public int getIdleTimeoutSeconds() {
265+ return idleTimeoutSeconds;
266+ }
267+
268+ /**
269+ * Sets the timeout before an idle connection is removed.
270+ * <p>
271+ * The order of magnitude should be a few minutes (the default is 120 seconds). The
272+ * timeout that triggers the removal has a granularity of 10 seconds.
273+ *
274+ * @param idleTimeoutSeconds the new timeout in seconds.
275+ * @return this {@code PoolingOptions}.
276+ *
277+ * @throws IllegalArgumentException if the timeout is negative.
278+ */
279+ public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) {
280+ if (idleTimeoutSeconds < 0)
281+ throw new IllegalArgumentException("Idle timeout must be positive");
282+ this.idleTimeoutSeconds = idleTimeoutSeconds;
283+ return this;
284+ }
285+
269286 /**
270287 * Returns the timeout when trying to acquire a connection from a host's pool.
271288 *
@@ -378,6 +395,42 @@
378395 return this;
379396 }
380397
398+ /**
399+ * Returns the executor to use for connection initialization.
400+ *
401+ * @return the executor.
402+ * @see #setInitializationExecutor(java.util.concurrent.Executor)
403+ */
404+ public Executor getInitializationExecutor() {
405+ return initializationExecutor;
406+ }
407+
408+ /**
409+ * Sets the executor to use for connection initialization.
410+ * <p>
411+ * Connections are open in a completely asynchronous manner. Since initializing the transport
412+ * requires separate CQL queries, the futures representing the completion of these queries are
413+ * transformed and chained. This executor is where these transformations happen.
414+ * <p>
415+ * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to
416+ * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations
417+ * on the network I/O threads; this is fine if the transformations are fast and not I/O bound
418+ * (which is the case by default).
419+ * One reason why you might want to provide a custom executor is if you use authentication with
420+ * a custom {@link com.datastax.driver.core.Authenticator} implementation that performs blocking
421+ * calls.
422+ *
423+ * @param initializationExecutor the executor to use
424+ * @return this {@code PoolingOptions}
425+ *
426+ * @throws java.lang.NullPointerException if the executor is null
427+ */
428+ public PoolingOptions setInitializationExecutor(Executor initializationExecutor) {
429+ Preconditions.checkNotNull(initializationExecutor);
430+ this.initializationExecutor = initializationExecutor;
431+ return this;
432+ }
433+
381434 /**
382435 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
383436 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
@@ -405,12 +458,6 @@
405458 StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2));
406459 }
407460
408- private static void checkRequestsPerConnectionOrder(int min, int max, HostDistance distance) {
409- if (min > max)
410- throw new IllegalArgumentException(String.format("Min simultaneous requests per connection for %s hosts must be less than max (%d > %d)",
411- distance, min, max));
412- }
413-
414461 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
415462 if (core > max)
416463 throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)",
modified driver-core/src/main/java/com/datastax/driver/core/PreparedId.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java +21 −21
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
1717
1818 import java.net.InetSocketAddress;
1919
20-import org.jboss.netty.buffer.ChannelBuffer;
20+import io.netty.buffer.ByteBuf;
2121
2222 class ProtocolEvent {
2323
@@ -29,14 +29,14 @@
2929 this.type = type;
3030 }
3131
32- public static ProtocolEvent deserialize(ChannelBuffer cb, ProtocolVersion version) {
33- switch (CBUtil.readEnumValue(Type.class, cb)) {
32+ public static ProtocolEvent deserialize(ByteBuf bb, ProtocolVersion version) {
33+ switch (CBUtil.readEnumValue(Type.class, bb)) {
3434 case TOPOLOGY_CHANGE:
35- return TopologyChange.deserializeEvent(cb);
35+ return TopologyChange.deserializeEvent(bb);
3636 case STATUS_CHANGE:
37- return StatusChange.deserializeEvent(cb);
37+ return StatusChange.deserializeEvent(bb);
3838 case SCHEMA_CHANGE:
39- return SchemaChange.deserializeEvent(cb, version);
39+ return SchemaChange.deserializeEvent(bb, version);
4040 }
4141 throw new AssertionError();
4242 }
@@ -54,9 +54,9 @@
5454 }
5555
5656 // Assumes the type has already been deserialized
57- private static TopologyChange deserializeEvent(ChannelBuffer cb) {
58- Change change = CBUtil.readEnumValue(Change.class, cb);
59- InetSocketAddress node = CBUtil.readInet(cb);
57+ private static TopologyChange deserializeEvent(ByteBuf bb) {
58+ Change change = CBUtil.readEnumValue(Change.class, bb);
59+ InetSocketAddress node = CBUtil.readInet(bb);
6060 return new TopologyChange(change, node);
6161 }
6262
@@ -80,9 +80,9 @@
8080 }
8181
8282 // Assumes the type has already been deserialized
83- private static StatusChange deserializeEvent(ChannelBuffer cb) {
84- Status status = CBUtil.readEnumValue(Status.class, cb);
85- InetSocketAddress node = CBUtil.readInet(cb);
83+ private static StatusChange deserializeEvent(ByteBuf bb) {
84+ Status status = CBUtil.readEnumValue(Status.class, bb);
85+ InetSocketAddress node = CBUtil.readInet(bb);
8686 return new StatusChange(status, node);
8787 }
8888
@@ -111,23 +111,23 @@
111111 }
112112
113113 // Assumes the type has already been deserialized
114- private static SchemaChange deserializeEvent(ChannelBuffer cb, ProtocolVersion version) {
114+ private static SchemaChange deserializeEvent(ByteBuf bb, ProtocolVersion version) {
115115 Change change;
116116 Target target;
117117 String keyspace, name;
118118 switch (version) {
119119 case V1:
120120 case V2:
121- change = CBUtil.readEnumValue(Change.class, cb);
122- keyspace = CBUtil.readString(cb);
123- name = CBUtil.readString(cb);
121+ change = CBUtil.readEnumValue(Change.class, bb);
122+ keyspace = CBUtil.readString(bb);
123+ name = CBUtil.readString(bb);
124124 target = name.isEmpty() ? Target.KEYSPACE : Target.TABLE;
125125 return new SchemaChange(change, target, keyspace, name);
126126 case V3:
127- change = CBUtil.readEnumValue(Change.class, cb);
128- target = CBUtil.readEnumValue(Target.class, cb);
129- keyspace = CBUtil.readString(cb);
130- name = (target == Target.KEYSPACE) ? "" : CBUtil.readString(cb);
127+ change = CBUtil.readEnumValue(Change.class, bb);
128+ target = CBUtil.readEnumValue(Target.class, bb);
129+ keyspace = CBUtil.readString(bb);
130+ name = (target == Target.KEYSPACE) ? "" : CBUtil.readString(bb);
131131 return new SchemaChange(change, target, keyspace, name);
132132 default:
133133 throw version.unsupported();
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +26 −12
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.annotations.VisibleForTesting;
19+
1820 /**
1921 * Options of the Cassandra native binary protocol.
2022 */
@@ -25,23 +27,34 @@
2527 */
2628 public enum Compression {
2729 /** No compression */
28- NONE("", null),
30+ NONE("") {
31+ @Override
32+ FrameCompressor compressor() {
33+ return null;
34+ }
35+ },
2936 /** Snappy compression */
30- SNAPPY("snappy", FrameCompressor.SnappyCompressor.instance),
37+ SNAPPY("snappy") {
38+ @Override
39+ FrameCompressor compressor() {
40+ return FrameCompressor.SnappyCompressor.instance;
41+ }
42+ },
3143 /** LZ4 compression */
32- LZ4("lz4", FrameCompressor.LZ4Compressor.instance);
44+ LZ4("lz4") {
45+ @Override
46+ FrameCompressor compressor() {
47+ return FrameCompressor.LZ4Compressor.instance;
48+ }
49+ };
3350
3451 final String protocolName;
35- final FrameCompressor compressor;
3652
37- private Compression(String protocolName, FrameCompressor compressor) {
53+ private Compression(String protocolName) {
3854 this.protocolName = protocolName;
39- this.compressor = compressor;
4055 }
4156
42- FrameCompressor compressor() {
43- return compressor;
44- }
57+ abstract FrameCompressor compressor();
4558
4659 static Compression fromString(String str) {
4760 for (Compression c : values()) {
@@ -80,7 +93,8 @@
8093 private final int port;
8194 final ProtocolVersion initialProtocolVersion; // What the user asked us. Will be null by default.
8295
83- private final int maxSchemaAgreementWaitSeconds;
96+ @VisibleForTesting
97+ volatile int maxSchemaAgreementWaitSeconds;
8498
8599 private final SSLOptions sslOptions; // null if no SSL
86100 private final AuthProvider authProvider;
@@ -201,7 +215,7 @@
201215 * unavailable.
202216 */
203217 public ProtocolOptions setCompression(Compression compression) {
204- if (compression != Compression.NONE && compression.compressor == null)
218+ if (compression != Compression.NONE && compression.compressor() == null)
205219 throw new IllegalStateException("The requested compression is not available (some compression require a JAR to be found in the classpath)");
206220
207221 this.compression = compression;
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +812 −0
@@ -0,0 +1,812 @@
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.nio.ByteBuffer;
19+import java.util.List;
20+
21+import static java.util.concurrent.TimeUnit.NANOSECONDS;
22+
23+import com.google.common.annotations.Beta;
24+import com.google.common.annotations.VisibleForTesting;
25+import org.slf4j.Logger;
26+import org.slf4j.LoggerFactory;
27+
28+/**
29+ * A configurable {@link LatencyTracker} that logs all executed statements.
30+ * <p>
31+ * Typically, client applications would instantiate one single query logger (using its {@link Builder}),
32+ * configure it and register it on the relevant {@link Cluster} instance, e.g.:
33+ *
34+ * <pre>
35+ * Cluster cluster = ...
36+ * QueryLogger queryLogger = QueryLogger.builder(cluster)
37+ * .withConstantThreshold(...)
38+ * .withMaxQueryStringLength(...)
39+ * .build();
40+ * cluster.register(queryLogger);
41+ * </pre>
42+ *
43+ * Refer to the {@link Builder} documentation for more information on
44+ * configuration settings for the query logger.
45+ * <p>
46+ * Once registered, the query logger will log every {@link RegularStatement}, {@link BoundStatement} or {@link BatchStatement}
47+ * executed by the driver;
48+ * note that it will never log other types of statement, null statements nor any special statement used internally by the driver.
49+ * <p>
50+ * There is one log for each request to a Cassandra node; because the driver sometimes retries the same statement on multiple nodes,
51+ * a single statement execution (for example, a single call to {@link Session#execute(Statement)}) can produce multiple logs on
52+ * different nodes.
53+ * <p>
54+ * For more flexibility, the query logger uses 3 different {@link Logger} instances:
55+ *
56+ * <ol>
57+ * <li>{@link #NORMAL_LOGGER}: used to log normal queries, i.e., queries that completed successfully
58+ * within a configurable threshold in milliseconds.</li>
59+ * <li>{@link #SLOW_LOGGER}: used to log slow queries, i.e., queries that completed successfully
60+ * but that took longer than a configurable threshold in milliseconds to complete.</li>
61+ * <li>{@link #ERROR_LOGGER}: used to log unsuccessful queries, i.e.,
62+ * queries that did not completed normally and threw an exception.
63+ * Note this this logger will also print the full stack trace of the reported exception.</li>
64+ * </ol>
65+ *
66+ * <p>
67+ * The appropriate logger is chosen according to the following algorithm:
68+ * <ol>
69+ * <li>if an exception has been thrown: use {@link #ERROR_LOGGER};</li>
70+ * <li>otherwise, if the reported latency is greater than the configured threshold in milliseconds: use {@link #SLOW_LOGGER};</li>
71+ * <li>otherwise, use {@link #NORMAL_LOGGER}.</li>
72+ * </ol>
73+ *
74+ * <p>
75+ * All loggers are activated by setting their levels to {@code DEBUG} or {@code TRACE} (including {@link #ERROR_LOGGER}).
76+ * If the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
77+ * then the query parameters (if any) will be logged as well (names and actual values).
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+
104+ * <p>
105+ * This class is thread-safe.
106+ *
107+ * @since 2.0.10
108+ */
109+public abstract class QueryLogger implements LatencyTracker {
110+
111+ /**
112+ * The default latency threshold in milliseconds beyond which queries are considered 'slow'
113+ * and logged as such by the driver.
114+ */
115+ public static final long DEFAULT_SLOW_QUERY_THRESHOLD_MS = 5000;
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+
123+ /**
124+ * The default maximum length of a CQL query string that can be logged verbatim
125+ * by the driver. Query strings longer than this value will be truncated
126+ * when logged.
127+ */
128+ public static final int DEFAULT_MAX_QUERY_STRING_LENGTH = 500;
129+
130+ /**
131+ * The default maximum length of a query parameter value that can be logged verbatim
132+ * by the driver. Parameter values longer than this value will be truncated
133+ * when logged.
134+ */
135+ public static final int DEFAULT_MAX_PARAMETER_VALUE_LENGTH = 50;
136+
137+ /**
138+ * The default maximum number of query parameters that can be logged
139+ * by the driver. Queries with a number of parameters higher than this value
140+ * will not have all their parameters logged.
141+ */
142+ public static final int DEFAULT_MAX_LOGGED_PARAMETERS = 50;
143+
144+ // Loggers
145+
146+ /**
147+ * The logger used to log normal queries, i.e., queries that completed successfully
148+ * within a configurable threshold in milliseconds.
149+ * <p>
150+ * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
151+ * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
152+ * then the query parameters (if any) will be logged as well (names and actual values).
153+ * <p>
154+ * The name of this logger is {@code com.datastax.driver.core.QueryLogger.NORMAL}.
155+ */
156+ public static final Logger NORMAL_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.NORMAL");
157+
158+ /**
159+ * The logger used to log slow queries, i.e., queries that completed successfully
160+ * but whose execution time exceeded a configurable threshold in milliseconds.
161+ * <p>
162+ * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
163+ * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
164+ * then the query parameters (if any) will be logged as well (names and actual values).
165+ * <p>
166+ * The name of this logger is {@code com.datastax.driver.core.QueryLogger.SLOW}.
167+ */
168+ public static final Logger SLOW_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.SLOW");
169+
170+ /**
171+ * The logger used to log unsuccessful queries, i.e., queries that did not completed normally and threw an exception.
172+ * <p>
173+ * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
174+ * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement},
175+ * then the query parameters (if any) will be logged as well (names and actual values).
176+ * Note this this logger will also print the full stack trace of the reported exception.
177+ * <p>
178+ * The name of this logger is {@code com.datastax.driver.core.QueryLogger.ERROR}.
179+ */
180+ public static final Logger ERROR_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.ERROR");
181+
182+ // Message templates
183+
184+ private static final String NORMAL_TEMPLATE = "[%s] [%s] Query completed normally, took %s ms: %s";
185+
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";
189+
190+ private static final String ERROR_TEMPLATE = "[%s] [%s] Query error after %s ms: %s";
191+
192+ @VisibleForTesting
193+ static final String TRUNCATED_OUTPUT = "... [truncated output]";
194+
195+ @VisibleForTesting
196+ static final String FURTHER_PARAMS_OMITTED = " [further parameters omitted]";
197+
198+ protected final Cluster cluster;
199+
200+ private volatile ProtocolVersion protocolVersion;
201+
202+ protected volatile int maxQueryStringLength;
203+
204+ protected volatile int maxParameterValueLength;
205+
206+ protected volatile int maxLoggedParameters;
207+
208+ /**
209+ * Private constructor. Instances of QueryLogger should be obtained via the {@link #builder(Cluster)} method.
210+ */
211+ private QueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters) {
212+ this.cluster = cluster;
213+ this.maxQueryStringLength = maxQueryStringLength;
214+ this.maxParameterValueLength = maxParameterValueLength;
215+ this.maxLoggedParameters = maxLoggedParameters;
216+ }
217+
218+ /**
219+ * Creates a new {@link QueryLogger.Builder} instance.
220+ * <p>
221+ * This is a convenience method for {@code new QueryLogger.Builder()}.
222+ *
223+ * @param cluster the {@link Cluster} this QueryLogger will be attached to.
224+ * @return the new QueryLogger builder.
225+ * @throws NullPointerException if {@code cluster} is {@code null}.
226+ */
227+ public static QueryLogger.Builder builder(Cluster cluster) {
228+ if(cluster == null) throw new NullPointerException("QueryLogger.Builder: cluster parameter cannot be null");
229+ return new QueryLogger.Builder(cluster);
230+ }
231+
232+ /**
233+ * A QueryLogger that uses a constant threshold in milliseconds
234+ * to track slow queries.
235+ * This implementation is the default and should be preferred to {@link DynamicThresholdQueryLogger}
236+ * which is still in beta state.
237+ */
238+ public static class ConstantThresholdQueryLogger extends QueryLogger {
239+
240+ private volatile long slowQueryLatencyThresholdMillis;
241+
242+ private ConstantThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, long slowQueryLatencyThresholdMillis) {
243+ super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters);
244+ this.setSlowQueryLatencyThresholdMillis(slowQueryLatencyThresholdMillis);
245+ }
246+
247+ /**
248+ * Return the threshold in milliseconds beyond which queries are considered 'slow'
249+ * and logged as such by the driver.
250+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}.
251+ *
252+ * @return The threshold in milliseconds beyond which queries are considered 'slow'
253+ * and logged as such by the driver.
254+ */
255+ public long getSlowQueryLatencyThresholdMillis() {
256+ return slowQueryLatencyThresholdMillis;
257+ }
258+
259+ /**
260+ * Set the threshold in milliseconds beyond which queries are considered 'slow'
261+ * and logged as such by the driver.
262+ *
263+ * @param slowQueryLatencyThresholdMillis Slow queries threshold in milliseconds.
264+ * It must be strictly positive.
265+ * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdMillis <= 0}.
266+ */
267+ public void setSlowQueryLatencyThresholdMillis(long slowQueryLatencyThresholdMillis) {
268+ if (slowQueryLatencyThresholdMillis <= 0)
269+ throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdMillis, should be > 0, got " + slowQueryLatencyThresholdMillis);
270+ this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis;
271+ }
272+
273+ @Override
274+ protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) {
275+ if (latencyMs > slowQueryLatencyThresholdMillis) {
276+ maybeLogSlowQuery(host, statement, latencyMs);
277+ } else {
278+ maybeLogNormalQuery(host, statement, latencyMs);
279+ }
280+ }
281+
282+ protected void maybeLogSlowQuery(Host host, Statement statement, long latencyMs) {
283+ if (SLOW_LOGGER.isDebugEnabled()) {
284+ String message = String.format(SLOW_TEMPLATE_MILLIS, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
285+ logQuery(statement, null, SLOW_LOGGER, message);
286+ }
287+ }
288+ }
289+
290+ /**
291+ * A QueryLogger that uses a dynamic threshold in milliseconds
292+ * to track slow queries.
293+ * <p>
294+ * Dynamic thresholds are based on per-host latency percentiles, as computed
295+ * by {@link PerHostPercentileTracker}.
296+ * <p>
297+ * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
298+ * to change.</b>
299+ */
300+ @Beta
301+ public static class DynamicThresholdQueryLogger extends QueryLogger {
302+
303+ private volatile double slowQueryLatencyThresholdPercentile;
304+
305+ private volatile PerHostPercentileTracker perHostPercentileLatencyTracker;
306+
307+ private DynamicThresholdQueryLogger(Cluster cluster, int maxQueryStringLength, int maxParameterValueLength, int maxLoggedParameters, double slowQueryLatencyThresholdPercentile, PerHostPercentileTracker perHostPercentileLatencyTracker) {
308+ super(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters);
309+ this.setSlowQueryLatencyThresholdPercentile(slowQueryLatencyThresholdPercentile);
310+ this.setPerHostPercentileLatencyTracker(perHostPercentileLatencyTracker);
311+ }
312+
313+ /**
314+ * Return the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
315+ * Cannot be {@code null}.
316+ *
317+ * @return the {@link PerHostPercentileTracker} instance to use.
318+ */
319+ public PerHostPercentileTracker getPerHostPercentileLatencyTracker() {
320+ return perHostPercentileLatencyTracker;
321+ }
322+
323+ /**
324+ * Set the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
325+ * Cannot be {@code null}.
326+ *
327+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use.
328+ * @throws IllegalArgumentException if {@code perHostPercentileLatencyTracker == null}.
329+ */
330+ public void setPerHostPercentileLatencyTracker(PerHostPercentileTracker perHostPercentileLatencyTracker) {
331+ if (perHostPercentileLatencyTracker == null)
332+ throw new IllegalArgumentException("perHostPercentileLatencyTracker cannot be null");
333+ this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
334+ }
335+
336+ /**
337+ * Return the threshold percentile beyond which queries are considered 'slow'
338+ * and logged as such by the driver.
339+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}.
340+ *
341+ * @return threshold percentile beyond which queries are considered 'slow'
342+ * and logged as such by the driver.
343+ */
344+ public double getSlowQueryLatencyThresholdPercentile() {
345+ return slowQueryLatencyThresholdPercentile;
346+ }
347+
348+ /**
349+ * Set the threshold percentile beyond which queries are considered 'slow'
350+ * and logged as such by the driver.
351+ *
352+ * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
353+ * It must be comprised between 0 inclusive and 100 exclusive.
354+ * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdPercentile < 0 || slowQueryLatencyThresholdPercentile >= 100}.
355+ */
356+ public void setSlowQueryLatencyThresholdPercentile(double slowQueryLatencyThresholdPercentile) {
357+ if (slowQueryLatencyThresholdPercentile < 0.0 || slowQueryLatencyThresholdPercentile >= 100.0)
358+ throw new IllegalArgumentException("Invalid slowQueryLatencyThresholdPercentile, should be >= 0 and < 100, got " + slowQueryLatencyThresholdPercentile);
359+ this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile;
360+ }
361+
362+ @Override
363+ protected void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs) {
364+ long threshold = perHostPercentileLatencyTracker.getLatencyAtPercentile(host, slowQueryLatencyThresholdPercentile);
365+ if (threshold >= 0 && latencyMs > threshold) {
366+ maybeLogSlowQuery(host, statement, latencyMs, threshold);
367+ } else {
368+ maybeLogNormalQuery(host, statement, latencyMs);
369+ }
370+ }
371+
372+ protected void maybeLogSlowQuery(Host host, Statement statement, long latencyMs, long threshold) {
373+ if (SLOW_LOGGER.isDebugEnabled()) {
374+ String message = String.format(SLOW_TEMPLATE_PERCENTILE, cluster.getClusterName(), host, latencyMs, slowQueryLatencyThresholdPercentile, threshold, statementAsString(statement));
375+ logQuery(statement, null, SLOW_LOGGER, message);
376+ }
377+ }
378+ }
379+
380+ /**
381+ * Helper class to build {@link QueryLogger} instances with a fluent API.
382+ */
383+ public static class Builder {
384+
385+ private final Cluster cluster;
386+
387+ private int maxQueryStringLength = DEFAULT_MAX_QUERY_STRING_LENGTH;
388+
389+ private int maxParameterValueLength = DEFAULT_MAX_PARAMETER_VALUE_LENGTH;
390+
391+ private int maxLoggedParameters = DEFAULT_MAX_LOGGED_PARAMETERS;
392+
393+ private long slowQueryLatencyThresholdMillis = DEFAULT_SLOW_QUERY_THRESHOLD_MS;
394+
395+ private double slowQueryLatencyThresholdPercentile = DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE;
396+
397+ private PerHostPercentileTracker perHostPercentileLatencyTracker;
398+
399+ private boolean constantThreshold = true;
400+
401+ public Builder(Cluster cluster) {
402+ this.cluster = cluster;
403+ }
404+
405+ /**
406+ * Enables slow query latency tracking based on constant thresholds.
407+ * <p>
408+ * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
409+ * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
410+ * not both.
411+ *
412+ * @param slowQueryLatencyThresholdMillis The threshold in milliseconds beyond which queries are considered 'slow'
413+ * and logged as such by the driver.
414+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_MS}
415+ * @return this {@link Builder} instance (for method chaining).
416+ */
417+ public Builder withConstantThreshold(long slowQueryLatencyThresholdMillis) {
418+ this.slowQueryLatencyThresholdMillis = slowQueryLatencyThresholdMillis;
419+ constantThreshold = true;
420+ return this;
421+ }
422+
423+ /**
424+ * Enables slow query latency tracking based on dynamic thresholds.
425+ * <p>
426+ * Dynamic thresholds are based on per-host latency percentiles, as computed
427+ * by {@link PerHostPercentileTracker}.
428+ * <p>
429+ * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
430+ * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
431+ * not both.
432+ * <p>
433+ * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
434+ * to change.</b>
435+ *
436+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
437+ * Cannot be {@code null}.
438+ * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
439+ * It must be comprised between 0 inclusive and 100 exclusive.
440+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
441+ * @return this {@link Builder} instance (for method chaining).
442+ */
443+ @Beta
444+ public Builder withDynamicThreshold(PerHostPercentileTracker perHostPercentileLatencyTracker, double slowQueryLatencyThresholdPercentile) {
445+ this.perHostPercentileLatencyTracker = perHostPercentileLatencyTracker;
446+ this.slowQueryLatencyThresholdPercentile = slowQueryLatencyThresholdPercentile;
447+ constantThreshold = false;
448+ return this;
449+ }
450+
451+ /**
452+ * Set the maximum length of a CQL query string that can be logged verbatim
453+ * by the driver. Query strings longer than this value will be truncated
454+ * when logged.
455+ *
456+ * @param maxQueryStringLength The maximum length of a CQL query string
457+ * that can be logged verbatim by the driver.
458+ * It must be strictly positive or {@code -1},
459+ * in which case the query is never truncated
460+ * (use with care).
461+ * The default value is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
462+ * @return this {@link Builder} instance (for method chaining).
463+ */
464+ public Builder withMaxQueryStringLength(int maxQueryStringLength) {
465+ this.maxQueryStringLength = maxQueryStringLength;
466+ return this;
467+ }
468+
469+ /**
470+ * Set the maximum length of a query parameter value that can be logged verbatim
471+ * by the driver. Parameter values longer than this value will be truncated
472+ * when logged.
473+ *
474+ * @param maxParameterValueLength The maximum length of a query parameter value
475+ * that can be logged verbatim by the driver.
476+ * It must be strictly positive or {@code -1},
477+ * in which case the parameter value is never truncated
478+ * (use with care).
479+ * The default value is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
480+ * @return this {@link Builder} instance (for method chaining).
481+ */
482+ public Builder withMaxParameterValueLength(int maxParameterValueLength) {
483+ this.maxParameterValueLength = maxParameterValueLength;
484+ return this;
485+ }
486+
487+ /**
488+ * Set the maximum number of query parameters that can be logged
489+ * by the driver. Queries with a number of parameters higher than this value
490+ * will not have all their parameters logged.
491+ *
492+ * @param maxLoggedParameters The maximum number of query parameters that can be logged
493+ * by the driver. It must be strictly positive or {@code -1},
494+ * in which case all parameters will be logged, regardless of their number
495+ * (use with care).
496+ * The default value is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
497+ * @return this {@link Builder} instance (for method chaining).
498+ */
499+ public Builder withMaxLoggedParameters(int maxLoggedParameters) {
500+ this.maxLoggedParameters = maxLoggedParameters;
501+ return this;
502+ }
503+
504+ /**
505+ * Build the {@link QueryLogger} instance.
506+ * @return the {@link QueryLogger} instance.
507+ * @throws IllegalArgumentException if the builder is unable to build a valid instance due to incorrect settings.
508+ */
509+ public QueryLogger build() {
510+ if(constantThreshold) {
511+ return new ConstantThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
512+ } else {
513+ return new DynamicThresholdQueryLogger(cluster, maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
514+ }
515+ }
516+
517+ }
518+
519+ // Getters and Setters
520+
521+ /**
522+ * Return the maximum length of a CQL query string that can be logged verbatim
523+ * by the driver. Query strings longer than this value will be truncated
524+ * when logged.
525+ * The default value is {@link #DEFAULT_MAX_QUERY_STRING_LENGTH}.
526+ *
527+ * @return The maximum length of a CQL query string that can be logged verbatim
528+ * by the driver.
529+ */
530+ public int getMaxQueryStringLength() {
531+ return maxQueryStringLength;
532+ }
533+
534+ /**
535+ * Set the maximum length of a CQL query string that can be logged verbatim
536+ * by the driver. Query strings longer than this value will be truncated
537+ * when logged.
538+ *
539+ * @param maxQueryStringLength The maximum length of a CQL query string
540+ * that can be logged verbatim by the driver.
541+ * It must be strictly positive or {@code -1},
542+ * in which case the query is never truncated
543+ * (use with care).
544+ * @throws IllegalArgumentException if {@code maxQueryStringLength <= 0 && maxQueryStringLength != -1}.
545+ */
546+ public void setMaxQueryStringLength(int maxQueryStringLength) {
547+ if (maxQueryStringLength <= 0 && maxQueryStringLength != -1)
548+ throw new IllegalArgumentException("Invalid maxQueryStringLength, should be > 0 or -1, got " + maxQueryStringLength);
549+ this.maxQueryStringLength = maxQueryStringLength;
550+ }
551+
552+ /**
553+ * Return the maximum length of a query parameter value that can be logged verbatim
554+ * by the driver. Parameter values longer than this value will be truncated
555+ * when logged.
556+ * The default value is {@link #DEFAULT_MAX_PARAMETER_VALUE_LENGTH}.
557+ *
558+ * @return The maximum length of a query parameter value that can be logged verbatim
559+ * by the driver.
560+ */
561+ public int getMaxParameterValueLength() {
562+ return maxParameterValueLength;
563+ }
564+
565+ /**
566+ * Set the maximum length of a query parameter value that can be logged verbatim
567+ * by the driver. Parameter values longer than this value will be truncated
568+ * when logged.
569+ *
570+ * @param maxParameterValueLength The maximum length of a query parameter value
571+ * that can be logged verbatim by the driver.
572+ * It must be strictly positive or {@code -1},
573+ * in which case the parameter value is never truncated
574+ * (use with care).
575+ * @throws IllegalArgumentException if {@code maxParameterValueLength <= 0 && maxParameterValueLength != -1}.
576+ */
577+ public void setMaxParameterValueLength(int maxParameterValueLength) {
578+ if (maxParameterValueLength <= 0 && maxParameterValueLength != -1)
579+ throw new IllegalArgumentException("Invalid maxParameterValueLength, should be > 0 or -1, got " + maxParameterValueLength);
580+ this.maxParameterValueLength = maxParameterValueLength;
581+ }
582+
583+ /**
584+ * Return the maximum number of query parameters that can be logged
585+ * by the driver. Queries with a number of parameters higher than this value
586+ * will not have all their parameters logged.
587+ * The default value is {@link #DEFAULT_MAX_LOGGED_PARAMETERS}.
588+ *
589+ * @return The maximum number of query parameters that can be logged
590+ * by the driver.
591+ */
592+ public int getMaxLoggedParameters() {
593+ return maxLoggedParameters;
594+ }
595+
596+ /**
597+ * Set the maximum number of query parameters that can be logged
598+ * by the driver. Queries with a number of parameters higher than this value
599+ * will not have all their parameters logged.
600+ *
601+ * @param maxLoggedParameters the maximum number of query parameters that can be logged
602+ * by the driver. It must be strictly positive or {@code -1},
603+ * in which case all parameters will be logged, regardless of their number
604+ * (use with care).
605+ * @throws IllegalArgumentException if {@code maxLoggedParameters <= 0 && maxLoggedParameters != -1}.
606+ */
607+ public void setMaxLoggedParameters(int maxLoggedParameters) {
608+ if (maxLoggedParameters <= 0 && maxLoggedParameters != -1)
609+ throw new IllegalArgumentException("Invalid maxLoggedParameters, should be > 0 or -1, got " + maxLoggedParameters);
610+ this.maxLoggedParameters = maxLoggedParameters;
611+ }
612+
613+ /**
614+ * {@inheritDoc}
615+ */
616+ @Override
617+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
618+ long latencyMs = NANOSECONDS.toMillis(newLatencyNanos);
619+ if (exception == null) {
620+ maybeLogNormalOrSlowQuery(host, statement, latencyMs);
621+ } else {
622+ maybeLogErrorQuery(host, statement, exception, latencyMs);
623+ }
624+ }
625+
626+ protected abstract void maybeLogNormalOrSlowQuery(Host host, Statement statement, long latencyMs);
627+
628+ protected void maybeLogNormalQuery(Host host, Statement statement, long latencyMs) {
629+ if (NORMAL_LOGGER.isDebugEnabled()) {
630+ String message = String.format(NORMAL_TEMPLATE, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
631+ logQuery(statement, null, NORMAL_LOGGER, message);
632+ }
633+ }
634+
635+ protected void maybeLogErrorQuery(Host host, Statement statement, Exception exception, long latencyMs) {
636+ if (ERROR_LOGGER.isDebugEnabled()) {
637+ String message = String.format(ERROR_TEMPLATE, cluster.getClusterName(), host, latencyMs, statementAsString(statement));
638+ logQuery(statement, exception, ERROR_LOGGER, message);
639+ }
640+ }
641+
642+ protected void logQuery(Statement statement, Exception exception, Logger logger, String message) {
643+ boolean showParameterValues = logger.isTraceEnabled();
644+ if (showParameterValues) {
645+ StringBuilder params = new StringBuilder();
646+ if (statement instanceof BoundStatement) {
647+ appendParameters((BoundStatement)statement, params, maxLoggedParameters);
648+ } else if (statement instanceof BatchStatement) {
649+ BatchStatement batchStatement = (BatchStatement)statement;
650+ int remaining = maxLoggedParameters;
651+ for (Statement inner : batchStatement.getStatements()) {
652+ if (inner instanceof BoundStatement) {
653+ remaining = appendParameters((BoundStatement)inner, params, remaining);
654+ }
655+ }
656+ }
657+ if (params.length() > 0)
658+ params.append("]");
659+ logger.trace(message + params, exception);
660+ } else {
661+ logger.debug(message, exception);
662+ }
663+ }
664+
665+ protected String statementAsString(Statement statement) {
666+ StringBuilder sb = new StringBuilder();
667+ if (statement instanceof BatchStatement) {
668+ BatchStatement bs = (BatchStatement)statement;
669+ int statements = bs.getStatements().size();
670+ int boundValues = countBoundValues(bs);
671+ sb.append("[" + statements + " statements, " + boundValues + " bound values] ");
672+ } else if (statement instanceof BoundStatement) {
673+ int boundValues = ((BoundStatement)statement).wrapper.values.length;
674+ sb.append("[" + boundValues + " bound values] ");
675+ }
676+
677+ append(statement, sb, maxQueryStringLength);
678+ return sb.toString();
679+ }
680+
681+ protected int countBoundValues(BatchStatement bs) {
682+ int count = 0;
683+ for (Statement s : bs.getStatements()) {
684+ if (s instanceof BoundStatement)
685+ count += ((BoundStatement)s).wrapper.values.length;
686+ }
687+ return count;
688+ }
689+
690+ protected int appendParameters(BoundStatement statement, StringBuilder buffer, int remaining) {
691+ if (remaining == 0)
692+ return 0;
693+ ColumnDefinitions metadata = statement.preparedStatement().getVariables();
694+ int numberOfParameters = metadata.size();
695+ if (numberOfParameters > 0) {
696+ List<ColumnDefinitions.Definition> definitions = metadata.asList();
697+ int numberOfLoggedParameters;
698+ if (remaining == -1) {
699+ numberOfLoggedParameters = numberOfParameters;
700+ } else {
701+ numberOfLoggedParameters = remaining > numberOfParameters ? numberOfParameters : remaining;
702+ remaining -= numberOfLoggedParameters;
703+ }
704+ for (int i = 0; i < numberOfLoggedParameters; i++) {
705+ if (buffer.length() == 0)
706+ buffer.append(" [");
707+ else
708+ buffer.append(", ");
709+ buffer.append(String.format("%s:%s", metadata.getName(i), parameterValueAsString(definitions.get(i), statement.wrapper.values[i])));
710+ }
711+ if (numberOfLoggedParameters < numberOfParameters) {
712+ buffer.append(FURTHER_PARAMS_OMITTED);
713+ }
714+ }
715+ return remaining;
716+ }
717+
718+ protected String parameterValueAsString(ColumnDefinitions.Definition definition, ByteBuffer raw) {
719+ String valueStr;
720+ if (raw == null || raw.remaining() == 0) {
721+ valueStr = "NULL";
722+ } else {
723+ DataType type = definition.getType();
724+ int maxParameterValueLength = this.maxParameterValueLength;
725+ if (type.equals(DataType.blob()) && maxParameterValueLength != -1) {
726+ // prevent large blobs from being converted to strings
727+ int maxBufferLength = Math.max(2, (maxParameterValueLength - 2) / 2);
728+ boolean bufferTooLarge = raw.remaining() > maxBufferLength;
729+ if (bufferTooLarge) {
730+ raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength);
731+ }
732+ Object value = type.deserialize(raw, protocolVersion());
733+ valueStr = type.format(value);
734+ if (bufferTooLarge) {
735+ valueStr = valueStr + TRUNCATED_OUTPUT;
736+ }
737+ } else {
738+ Object value = type.deserialize(raw, protocolVersion());
739+ valueStr = type.format(value);
740+ if (maxParameterValueLength != -1 && valueStr.length() > maxParameterValueLength) {
741+ valueStr = valueStr.substring(0, maxParameterValueLength) + TRUNCATED_OUTPUT;
742+ }
743+ }
744+ }
745+ return valueStr;
746+ }
747+
748+ private ProtocolVersion protocolVersion() {
749+ // Since the QueryLogger can be registered before the Cluster was initialized, we can't retrieve
750+ // it at construction time. Cache it field at first use (a volatile field is good enough since we
751+ // don't need mutual exclusion).
752+ if (protocolVersion == null) {
753+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
754+ // At least one connection was established when QueryLogger is invoked
755+ assert protocolVersion != null : "protocol version should be defined";
756+ }
757+ return protocolVersion;
758+ }
759+
760+ protected int append(Statement statement, StringBuilder buffer, int remaining) {
761+ if (statement instanceof StatementWrapper)
762+ statement = ((StatementWrapper)statement).getWrappedStatement();
763+
764+ if (statement instanceof RegularStatement) {
765+ remaining = append(((RegularStatement)statement).getQueryString().trim(), buffer, remaining);
766+ } else if (statement instanceof BoundStatement) {
767+ remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining);
768+ } else if (statement instanceof BatchStatement) {
769+ BatchStatement batchStatement = (BatchStatement)statement;
770+ remaining = append("BEGIN", buffer, remaining);
771+ switch (batchStatement.batchType) {
772+ case UNLOGGED:
773+ append(" UNLOGGED", buffer, remaining);
774+ break;
775+ case COUNTER:
776+ append(" COUNTER", buffer, remaining);
777+ break;
778+ }
779+ remaining = append(" BATCH", buffer, remaining);
780+ for (Statement stmt : batchStatement.getStatements()) {
781+ remaining = append(" ", buffer, remaining);
782+ remaining = append(stmt, buffer, remaining);
783+ }
784+ remaining = append(" APPLY BATCH", buffer, remaining);
785+ } else {
786+ // Unknown types of statement
787+ // Call toString() as a last resort
788+ remaining = append(statement.toString(), buffer, remaining);
789+ }
790+ if (buffer.charAt(buffer.length() - 1) != ';') {
791+ remaining = append(";", buffer, remaining);
792+ }
793+ return remaining;
794+ }
795+
796+ protected int append(CharSequence str, StringBuilder buffer, int remaining) {
797+ if (remaining == -2) {
798+ // capacity exceeded
799+ } else if (remaining == -1) {
800+ // unlimited capacity
801+ buffer.append(str);
802+ } else if (str.length() > remaining) {
803+ buffer.append(str, 0, remaining).append(TRUNCATED_OUTPUT);
804+ remaining = -2;
805+ } else {
806+ buffer.append(str);
807+ remaining -= str.length();
808+ }
809+ return remaining;
810+ }
811+
812+}
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +36 −5
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -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
@@ -37,14 +37,20 @@
3737 */
3838 public static final int DEFAULT_FETCH_SIZE = 5000;
3939
40+ /**
41+ * The default value for {@link #getDefaultIdempotence()}: {@code false}.
42+ */
43+ public static final boolean DEFAULT_IDEMPOTENCE = false;
44+
4045 private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL;
4146 private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL;
4247 private volatile int fetchSize = DEFAULT_FETCH_SIZE;
48+ private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE;
4349 private volatile Cluster.Manager manager;
4450
4551 /**
46- * Creates a new {@code QueryOptions} instance using the {@code DEFAULT_CONSISTENCY_LEVEL},
47- * {@code DEFAULT_SERIAL_CONSISTENCY_LEVEL} and {@code DEFAULT_FETCH_SIZE}.
52+ * Creates a new {@link QueryOptions} instance using the {@link #DEFAULT_CONSISTENCY_LEVEL},
53+ * {@link #DEFAULT_SERIAL_CONSISTENCY_LEVEL} and {@link #DEFAULT_FETCH_SIZE}.
4854 */
4955 public QueryOptions() {}
5056
@@ -138,4 +144,29 @@
138144 public int getFetchSize() {
139145 return fetchSize;
140146 }
147+
148+ /**
149+ * Sets the default idempotence for queries.
150+ * <p>
151+ * This will be used for statements for which {@link com.datastax.driver.core.Statement#isIdempotent()}
152+ * returns {@code null}.
153+ *
154+ * @param defaultIdempotence the new value to set as default idempotence.
155+ * @return this {@code QueryOptions} instance.
156+ */
157+ public QueryOptions setDefaultIdempotence(boolean defaultIdempotence) {
158+ this.defaultIdempotence = defaultIdempotence;
159+ return this;
160+ }
161+
162+ /**
163+ * The default idempotence for queries.
164+ * <p>
165+ * It defaults to {@link #DEFAULT_IDEMPOTENCE}.
166+ *
167+ * @return the default idempotence for queries.
168+ */
169+ public boolean getDefaultIdempotence() {
170+ return defaultIdempotence;
171+ }
141172 }
modified driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +636 −500
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -16,626 +16,745 @@
1616 package com.datastax.driver.core;
1717
1818 import java.net.InetSocketAddress;
19-import java.nio.ByteBuffer;
20-import java.util.ArrayList;
21-import java.util.Collections;
22-import java.util.HashMap;
23-import java.util.Iterator;
24-import java.util.List;
25-import java.util.Map;
19+import java.util.*;
20+import java.util.concurrent.ConcurrentHashMap;
21+import java.util.concurrent.CopyOnWriteArrayList;
2622 import java.util.concurrent.TimeUnit;
2723 import java.util.concurrent.TimeoutException;
24+import java.util.concurrent.atomic.AtomicBoolean;
25+import java.util.concurrent.atomic.AtomicInteger;
2826 import java.util.concurrent.atomic.AtomicReference;
2927
3028 import com.codahale.metrics.Timer;
29+import com.google.common.collect.Sets;
30+import io.netty.util.HashedWheelTimer;
31+import io.netty.util.Timeout;
32+import io.netty.util.TimerTask;
3133 import org.slf4j.Logger;
3234 import org.slf4j.LoggerFactory;
3335
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;
40-import com.datastax.driver.core.policies.*;
36+import com.datastax.driver.core.exceptions.*;
37+import com.datastax.driver.core.policies.RetryPolicy;
4138 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
39+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan;
4240
4341 /**
4442 * Handles a request to cassandra, dealing with host failover and retries on
4543 * unavailable/timeout.
4644 */
47-class RequestHandler implements Connection.ResponseCallback {
45+class RequestHandler {
4846 private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
4947
48+ final String id;
49+
5050 private final SessionManager manager;
5151 private final Callback callback;
5252
53- private final Iterator<Host> queryPlan;
53+ private final QueryPlan queryPlan;
54+ private final SpeculativeExecutionPlan speculativeExecutionPlan;
55+ private final boolean allowSpeculativeExecutions;
56+ private final Set<SpeculativeExecution> runningExecutions = Sets.newCopyOnWriteArraySet();
57+ private final Set<Timeout> scheduledExecutions = Sets.newCopyOnWriteArraySet();
5458 private final Statement statement;
55- private volatile Host current;
56- private volatile List<Host> triedHosts;
57- private volatile HostConnectionPool currentPool;
58- private final AtomicReference<QueryState> queryStateRef;
59-
60- // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from
61- // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an
62- // OVERLOADED error).
63- // This is incremented by one writer at a time, so volatile is good enough.
64- private volatile int retriesByPolicy;
59+ private final HashedWheelTimer scheduler;
6560
66- private volatile ConsistencyLevel retryConsistencyLevel;
61+ private volatile List<Host> triedHosts;
6762
6863 private volatile Map<InetSocketAddress, Throwable> errors;
6964
70- private volatile Connection.ResponseHandler connectionHandler;
71-
7265 private final Timer.Context timerContext;
7366 private final long startTime;
7467
68+ private final AtomicBoolean isDone = new AtomicBoolean();
69+ private AtomicInteger executionCount = new AtomicInteger();
70+
7571 public RequestHandler(SessionManager manager, Callback callback, Statement statement) {
72+ this.id = Long.toString(System.identityHashCode(this));
73+ if(logger.isTraceEnabled())
74+ logger.trace("[{}] {}", id, statement);
7675 this.manager = manager;
7776 this.callback = callback;
77+ this.scheduler = manager.cluster.manager.connectionFactory.timer;
7878
7979 callback.register(this);
8080
81- this.queryPlan = manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement);
81+ this.queryPlan = new QueryPlan(manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement));
82+ this.speculativeExecutionPlan = manager.speculativeRetryPolicy().newPlan(manager.poolsState.keyspace, statement);
83+ this.allowSpeculativeExecutions = statement != Statement.DEFAULT
84+ && statement.isIdempotentWithDefault(manager.configuration().getQueryOptions());
8285 this.statement = statement;
83- this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL);
8486
8587 this.timerContext = metricsEnabled()
86- ? metrics().getRequestsTimer().time()
87- : null;
88+ ? metrics().getRequestsTimer().time()
89+ : null;
8890 this.startTime = System.nanoTime();
8991 }
9092
91- private boolean metricsEnabled() {
92- return manager.configuration().getMetricsOptions() != null;
93+ void sendRequest() {
94+ startNewExecution();
9395 }
9496
95- private Metrics metrics() {
96- return manager.cluster.manager.metrics;
97- }
97+ // Called when the corresponding ResultSetFuture is cancelled by the client
98+ void cancel() {
99+ if (!isDone.compareAndSet(false, true))
100+ return;
98101
99- public void sendRequest() {
100- try {
101- while (queryPlan.hasNext() && !queryStateRef.get().isCancelled()) {
102- Host host = queryPlan.next();
103- logger.trace("Querying node {}", host);
104- if (query(host))
105- return;
106- }
107- setFinalException(null, new NoHostAvailableException(errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors));
108- } catch (Exception e) {
109- // Shouldn't happen really, but if ever the loadbalancing policy returned iterator throws, we don't want to block.
110- setFinalException(null, new DriverInternalError("An unexpected error happened while sending requests", e));
111- }
102+ cancelPendingExecutions(null);
112103 }
113104
114- private boolean query(Host host) {
115- currentPool = manager.pools.get(host);
116- if (currentPool == null || currentPool.isClosed())
117- return false;
105+ private void startNewExecution() {
106+ if (isDone.get())
107+ return;
118108
119- PooledConnection connection = null;
120- try {
121- connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
122- if (current != null) {
123- if (triedHosts == null)
124- triedHosts = new ArrayList<Host>();
125- triedHosts.add(current);
126- }
127- current = host;
128- write(connection, this);
129- return true;
130- } catch (ConnectionException e) {
131- // If we have any problem with the connection, move to the next node.
132- if (metricsEnabled())
133- metrics().getErrorMetrics().getConnectionErrors().inc();
134- if (connection != null)
135- connection.release();
136- logError(host.getSocketAddress(), e);
137- return false;
138- } catch (BusyConnectionException e) {
139- // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
140- connection.release();
141- logError(host.getSocketAddress(), e);
142- return false;
143- } catch (TimeoutException e) {
144- // We timeout, log it but move to the next node.
145- logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)"));
146- return false;
147- } catch (RuntimeException e) {
148- if (connection != null)
149- connection.release();
150- logger.error("Unexpected error while querying " + host.getAddress(), e);
151- logError(host.getSocketAddress(), e);
152- return false;
153- }
109+ Message.Request request = callback.request();
110+ int position = executionCount.incrementAndGet();
111+ // Clone the request after the first execution, since we set the streamId on it later and we
112+ // don't want to share that across executions.
113+ if (position > 1)
114+ request = manager.makeRequestMessage(statement, request.pagingState()) ;
115+
116+ SpeculativeExecution execution = new SpeculativeExecution(request, position);
117+ runningExecutions.add(execution);
118+ execution.sendRequest();
154119 }
155120
156- private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException {
157- // Make sure cancel() does not see a stale connectionHandler if it sees the new query state
158- // before connection.write has completed
159- connectionHandler = null;
160-
161- // Ensure query state is "in progress" (can be already if connection.write failed on a previous node and we're retrying)
162- while (true) {
163- QueryState previous = queryStateRef.get();
164- if (previous.isCancelled()) {
165- if (connection instanceof PooledConnection)
166- ((PooledConnection)connection).release();
167- return;
168- }
169- if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext()))
170- break;
171- }
121+ private void scheduleExecution(long delayMillis) {
122+ if (isDone.get() || delayMillis <= 0)
123+ return;
124+ if(logger.isTraceEnabled())
125+ logger.trace("[{}] Schedule next speculative execution in {} ms", id, delayMillis);
126+ scheduledExecutions.add(scheduler.newTimeout(newExecutionTask, delayMillis, TimeUnit.MILLISECONDS));
127+ }
172128
173- connectionHandler = connection.write(responseCallback, false);
174- // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered
175- // *before* the call to connection.write had returned.
176- connectionHandler.startTimeout();
177-
178- // Note that we could have already received the response here (so onSet() / onException() would have been called). This is
179- // why we only test for CANCELLED_WHILE_IN_PROGRESS below.
180-
181- // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have
182- // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice,
183- // but it knows how to deal with it).
184- if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS)
185- connectionHandler.cancelHandler();
129+ private final TimerTask newExecutionTask = new TimerTask() {
130+ @Override
131+ public void run(final Timeout timeout) throws Exception {
132+ scheduledExecutions.remove(timeout);
133+ if (!isDone.get())
134+ // We're on the timer thread so reschedule to another executor
135+ manager.executor().execute(new Runnable() {
136+ @Override
137+ public void run() {
138+ metrics().getErrorMetrics().getSpeculativeExecutions().inc();
139+ startNewExecution();
140+ }
141+ });
142+ }
143+ };
144+
145+ private void cancelPendingExecutions(SpeculativeExecution ignore) {
146+ for (SpeculativeExecution execution : runningExecutions)
147+ if (execution != ignore) // not vital but this produces nicer logs
148+ execution.cancel();
149+ for (Timeout execution : scheduledExecutions)
150+ execution.cancel();
186151 }
187152
188153 private void logError(InetSocketAddress address, Throwable exception) {
189154 logger.debug("Error querying {}, trying next host (error is: {})", address, exception.toString());
190155 if (errors == null)
191- errors = new HashMap<InetSocketAddress, Throwable>();
156+ errors = new ConcurrentHashMap<InetSocketAddress, Throwable>();
192157 errors.put(address, exception);
193158 }
194159
195- private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
196- final Host h = current;
197- this.retryConsistencyLevel = newConsistencyLevel;
198-
199- // We should not retry on the current thread as this will be an IO thread.
200- manager.executor().execute(new Runnable() {
201- @Override
202- public void run() {
203- if (queryStateRef.get().isCancelled())
204- return;
205- try {
206- if (retryCurrent) {
207- if (query(h))
208- return;
209- }
210- sendRequest();
211- } catch (Exception e) {
212- setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e));
213- }
214- }
215- });
216- }
217-
218- public void cancel() {
219- // Atomically set a special QueryState, that will cause any further operation to abort.
220- // We want to remember whether a request was in progress when we did this, so there are two cancel states.
221- while (true) {
222- QueryState previous = queryStateRef.get();
223- if (previous.isCancelled()) {
224- return;
225- } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) {
226- // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
227- // If it's still null, this will be handled by re-checking queryStateRef at the end of write().
228- if (connectionHandler != null)
229- connectionHandler.cancelHandler();
230- return;
231- } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
232- return;
233- }
234- }
235- }
236-
237- @Override
238- public Message.Request request() {
239-
240- Message.Request request = callback.request();
241- if (retryConsistencyLevel != null && retryConsistencyLevel != consistencyOf(request))
242- request = manager.makeRequestMessage(statement, retryConsistencyLevel, serialConsistencyOf(request), pagingStateOf(request), defaultTimestampOf(request));
243- return request;
244- }
245-
246- private ConsistencyLevel consistencyOf(Message.Request request) {
247- switch (request.type) {
248- case QUERY: return ((Requests.Query)request).options.consistency;
249- case EXECUTE: return ((Requests.Execute)request).options.consistency;
250- case BATCH: return ((Requests.Batch)request).options.consistency;
251- default: return null;
252- }
253- }
254-
255- private ConsistencyLevel serialConsistencyOf(Message.Request request) {
256- switch (request.type) {
257- case QUERY: return ((Requests.Query)request).options.serialConsistency;
258- case EXECUTE: return ((Requests.Execute)request).options.serialConsistency;
259- case BATCH: return ((Requests.Batch)request).options.serialConsistency;
260- default: return null;
160+ private void setFinalResult(SpeculativeExecution execution, Connection connection, Message.Response response) {
161+ if (!isDone.compareAndSet(false, true)) {
162+ if(logger.isTraceEnabled())
163+ logger.trace("[{}] Got beaten to setting the result", execution.id);
164+ return;
261165 }
262- }
263166
264- private long defaultTimestampOf(Message.Request request) {
265- switch (request.type) {
266- case QUERY: return ((Requests.Query)request).options.defaultTimestamp;
267- case EXECUTE: return ((Requests.Execute)request).options.defaultTimestamp;
268- case BATCH: return ((Requests.Batch)request).options.defaultTimestamp;
269- default: return 0;
270- }
271- }
167+ if(logger.isTraceEnabled())
168+ logger.trace("[{}] Setting final result", execution.id);
272169
273- private ByteBuffer pagingStateOf(Message.Request request) {
274- switch (request.type) {
275- case QUERY: return ((Requests.Query)request).options.pagingState;
276- case EXECUTE: return ((Requests.Execute)request).options.pagingState;
277- default: return null;
278- }
279- }
170+ cancelPendingExecutions(execution);
280171
281- private void setFinalResult(Connection connection, Message.Response response) {
282172 try {
283173 if (timerContext != null)
284174 timerContext.stop();
285175
286- ExecutionInfo info = current.defaultExecutionInfo;
176+ ExecutionInfo info = execution.current.defaultExecutionInfo;
287177 if (triedHosts != null) {
288- triedHosts.add(current);
178+ triedHosts.add(execution.current);
289179 info = new ExecutionInfo(triedHosts);
290180 }
291- if (retryConsistencyLevel != null)
292- info = info.withAchievedConsistency(retryConsistencyLevel);
181+ if (execution.retryConsistencyLevel != null)
182+ info = info.withAchievedConsistency(execution.retryConsistencyLevel);
293183 callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
294184 } catch (Exception e) {
295- callback.onException(connection, new DriverInternalError("Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime, retryCount());
185+ callback.onException(connection,
186+ new DriverInternalError("Unexpected exception while setting final result from " + response, e),
187+ System.nanoTime() - startTime, /*unused*/0);
296188 }
297189 }
298190
299- private void setFinalException(Connection connection, Exception exception) {
191+ private void setFinalException(SpeculativeExecution execution, Connection connection, Exception exception) {
192+ if (!isDone.compareAndSet(false, true)) {
193+ if(logger.isTraceEnabled())
194+ logger.trace("[{}] Got beaten to setting final exception", execution.id);
195+ return;
196+ }
197+
198+ if(logger.isTraceEnabled())
199+ logger.trace("[{}] Setting final exception", execution.id);
200+
201+ cancelPendingExecutions(execution);
202+
300203 try {
301204 if (timerContext != null)
302205 timerContext.stop();
303206 } finally {
304- callback.onException(connection, exception, System.nanoTime() - startTime, retryCount());
207+ callback.onException(connection, exception, System.nanoTime() - startTime, /*unused*/0);
305208 }
306209 }
307210
308- @Override
309- public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
310- QueryState queryState = queryStateRef.get();
311- if (!queryState.isInProgressAt(retryCount) ||
312- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
313- logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
314- retryCount, queryState, queryStateRef.get());
315- return;
316- }
211+ // Triggered when an execution reaches the end of the query plan.
212+ // This is only a failure if there are no other running executions.
213+ private void reportNoMoreHosts(SpeculativeExecution execution) {
214+ runningExecutions.remove(execution);
215+ if (runningExecutions.isEmpty())
216+ setFinalException(execution, null, new NoHostAvailableException(
217+ errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors));
218+ }
317219
318- Host queriedHost = current;
319- boolean releaseConnection = true;
320- try {
321- switch (response.type) {
322- case RESULT:
323- setFinalResult(connection, response);
324- break;
325- case ERROR:
326- Responses.Error err = (Responses.Error)response;
327- RetryPolicy.RetryDecision retry = null;
328- RetryPolicy retryPolicy = statement.getRetryPolicy() == null
329- ? manager.configuration().getPolicies().getRetryPolicy()
330- : statement.getRetryPolicy();
331- switch (err.code) {
332- case READ_TIMEOUT:
333- assert err.infos instanceof ReadTimeoutException;
334- if (metricsEnabled())
335- metrics().getErrorMetrics().getReadTimeouts().inc();
336-
337- ReadTimeoutException rte = (ReadTimeoutException)err.infos;
338- retry = retryPolicy.onReadTimeout(statement,
339- rte.getConsistencyLevel(),
340- rte.getRequiredAcknowledgements(),
341- rte.getReceivedAcknowledgements(),
342- rte.wasDataRetrieved(),
343- retriesByPolicy);
344-
345- if (metricsEnabled()) {
346- if (retry.getType() == Type.RETRY)
347- metrics().getErrorMetrics().getRetriesOnReadTimeout().inc();
348- if (retry.getType() == Type.IGNORE)
349- metrics().getErrorMetrics().getIgnoresOnReadTimeout().inc();
350- }
351- break;
352- case WRITE_TIMEOUT:
353- assert err.infos instanceof WriteTimeoutException;
354- if (metricsEnabled())
355- metrics().getErrorMetrics().getWriteTimeouts().inc();
356-
357- WriteTimeoutException wte = (WriteTimeoutException)err.infos;
358- retry = retryPolicy.onWriteTimeout(statement,
359- wte.getConsistencyLevel(),
360- wte.getWriteType(),
361- wte.getRequiredAcknowledgements(),
362- wte.getReceivedAcknowledgements(),
363- retriesByPolicy);
364-
365- if (metricsEnabled()) {
366- if (retry.getType() == Type.RETRY)
367- metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc();
368- if (retry.getType() == Type.IGNORE)
369- metrics().getErrorMetrics().getIgnoresOnWriteTimeout().inc();
370- }
371- break;
372- case UNAVAILABLE:
373- assert err.infos instanceof UnavailableException;
374- if (metricsEnabled())
375- metrics().getErrorMetrics().getUnavailables().inc();
376-
377- UnavailableException ue = (UnavailableException)err.infos;
378- retry = retryPolicy.onUnavailable(statement,
379- ue.getConsistencyLevel(),
380- ue.getRequiredReplicas(),
381- ue.getAliveReplicas(),
382- retriesByPolicy);
383-
384- if (metricsEnabled()) {
385- if (retry.getType() == Type.RETRY)
386- metrics().getErrorMetrics().getRetriesOnUnavailable().inc();
387- if (retry.getType() == Type.IGNORE)
388- metrics().getErrorMetrics().getIgnoresOnUnavailable().inc();
389- }
390- break;
391- case OVERLOADED:
392- // Try another node
393- logger.warn("Host {} is overloaded, trying next host.", connection.address);
394- logError(connection.address, new DriverException("Host overloaded"));
395- if (metricsEnabled())
396- metrics().getErrorMetrics().getOthers().inc();
397- retry(false, null);
398- return;
399- case SERVER_ERROR:
400- // Defunct connection and try another node
401- logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message);
402- DriverException exception = new DriverException("Host replied with server error: " + err.message);
403- logError(connection.address, exception);
404- connection.defunct(exception);
405- if (metricsEnabled())
406- metrics().getErrorMetrics().getOthers().inc();
407- retry(false, null);
408- return;
409- case IS_BOOTSTRAPPING:
410- // Try another node
411- logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address);
412- logError(connection.address, new DriverException("Host is bootstrapping"));
413- if (metricsEnabled())
414- metrics().getErrorMetrics().getOthers().inc();
415- retry(false, null);
416- return;
417- case UNPREPARED:
418- assert err.infos instanceof MD5Digest;
419- MD5Digest id = (MD5Digest)err.infos;
420- PreparedStatement toPrepare = manager.cluster.manager.preparedQueries.get(id);
421- if (toPrepare == null) {
422- // This shouldn't happen
423- String msg = String.format("Tried to execute unknown prepared query %s", id);
424- logger.error(msg);
425- setFinalException(connection, new DriverInternalError(msg));
426- return;
427- }
220+ private boolean metricsEnabled() {
221+ return manager.configuration().getMetricsOptions() != null;
222+ }
428223
429- String currentKeyspace = connection.keyspace();
430- String prepareKeyspace = toPrepare.getQueryKeyspace();
431- if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) {
432- // This shouldn't happen in normal use, because a user shouldn't try to execute
433- // a prepared statement with the wrong keyspace set.
434- // Fail fast (we can't change the keyspace to reprepare, because we're using a pooled connection
435- // that's shared with other requests).
436- throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)",
437- toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
438- }
224+ private Metrics metrics() {
225+ return manager.cluster.manager.metrics;
226+ }
439227
440- logger.info("Query {} is not prepared on {}, preparing before retrying executing. "
441- + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
442- toPrepare.getQueryString(), connection.address);
443-
444- releaseConnection = false; // we're reusing it for the prepare call
445- write(connection, prepareAndRetry(toPrepare.getQueryString()));
446- // we're done for now, the prepareAndRetry callback will handle the rest
447- return;
448- default:
449- if (metricsEnabled())
450- metrics().getErrorMetrics().getOthers().inc();
451- break;
452- }
228+ interface Callback extends Connection.ResponseCallback {
229+ void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
230+ void register(RequestHandler handler);
231+ }
453232
454- if (retry == null)
455- setFinalResult(connection, response);
456- else {
457- switch (retry.getType()) {
458- case RETRY:
459- ++retriesByPolicy;
460- if (logger.isDebugEnabled())
461- logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel());
462- if (metricsEnabled())
463- metrics().getErrorMetrics().getRetries().inc();
464- retry(true, retry.getRetryConsistencyLevel());
465- break;
466- case RETHROW:
467- setFinalResult(connection, response);
468- break;
469- case IGNORE:
470- if (metricsEnabled())
471- metrics().getErrorMetrics().getIgnores().inc();
472- setFinalResult(connection, new Responses.Result.Void());
473- break;
474- }
475- }
476- break;
477- default:
478- setFinalResult(connection, response);
479- break;
480- }
481- } catch (Exception e) {
482- setFinalException(connection, e);
483- } finally {
484- if (releaseConnection && connection instanceof PooledConnection)
485- ((PooledConnection)connection).release();
486-
487- if (queriedHost != null)
488- manager.cluster.manager.reportLatency(queriedHost, latency);
233+ /**
234+ * An execution of the query against the cluster.
235+ * There is at least one instance per RequestHandler, and possibly more (depending on the SpeculativeExecutionPolicy).
236+ * Each instance may retry on the same host, or on other hosts as defined by the RetryPolicy.
237+ * All instances run concurrently and share the same query plan.
238+ * There are three ways a SpeculativeExecution can stop:
239+ * - it completes the query (with either a success or a fatal error), and reports the result to the RequestHandler
240+ * - it gets cancelled, either because another execution completed the query, or because the RequestHandler was cancelled
241+ * - it reaches the end of the query plan and informs the RequestHandler, which will decide what to do
242+ */
243+ class SpeculativeExecution implements Connection.ResponseCallback {
244+ final String id;
245+ private final Message.Request request;
246+ private volatile Host current;
247+ private volatile ConsistencyLevel retryConsistencyLevel;
248+ private final AtomicReference<QueryState> queryStateRef;
249+ private final AtomicBoolean nextExecutionScheduled = new AtomicBoolean();
250+
251+ // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from
252+ // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an
253+ // OVERLOADED error).
254+ // This is incremented by one writer at a time, so volatile is good enough.
255+ private volatile int retriesByPolicy;
256+
257+ private volatile Connection.ResponseHandler connectionHandler;
258+
259+ SpeculativeExecution(Message.Request request, int position) {
260+ this.id = RequestHandler.this.id + "-" + position;
261+ this.request = request;
262+ this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL);
263+ if(logger.isTraceEnabled())
264+ logger.trace("[{}] Starting", id);
489265 }
490- }
491266
492- private Connection.ResponseCallback prepareAndRetry(final String toPrepare) {
493- return new Connection.ResponseCallback() {
267+ void sendRequest() {
268+ try {
269+ Host host;
270+ while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) {
271+ if(logger.isTraceEnabled())
272+ logger.trace("[{}] Querying node {}", id, host);
273+ if (query(host))
274+ return;
275+ }
276+ reportNoMoreHosts(this);
277+ } catch (Exception e) {
278+ // Shouldn't happen really, but if ever the loadbalancing policy returned iterator throws, we don't want to block.
279+ setFinalException(null, new DriverInternalError("An unexpected error happened while sending requests", e));
280+ }
281+ }
494282
495- @Override
496- public Message.Request request() {
497- return new Requests.Prepare(toPrepare);
283+ private boolean query(final Host host) {
284+ HostConnectionPool currentPool = manager.pools.get(host);
285+ if (currentPool == null || currentPool.isClosed())
286+ return false;
287+
288+ if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true))
289+ scheduleExecution(speculativeExecutionPlan.nextExecution(host));
290+
291+ Connection connection = null;
292+ try {
293+ connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
294+ if (current != null) {
295+ if (triedHosts == null)
296+ triedHosts = new CopyOnWriteArrayList<Host>();
297+ triedHosts.add(current);
298+ }
299+ current = host;
300+ write(connection, this);
301+ return true;
302+ } catch (ConnectionException e) {
303+ // If we have any problem with the connection, move to the next node.
304+ if (metricsEnabled())
305+ metrics().getErrorMetrics().getConnectionErrors().inc();
306+ if (connection != null)
307+ connection.release();
308+ logError(host.getSocketAddress(), e);
309+ return false;
310+ } catch (BusyConnectionException e) {
311+ // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
312+ connection.release();
313+ logError(host.getSocketAddress(), e);
314+ return false;
315+ } catch (TimeoutException e) {
316+ // We timeout, log it but move to the next node.
317+ logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)"));
318+ return false;
319+ } catch (RuntimeException e) {
320+ if (connection != null)
321+ connection.release();
322+ logger.error("Unexpected error while querying " + host.getAddress(), e);
323+ logError(host.getSocketAddress(), e);
324+ return false;
498325 }
326+ }
499327
500- @Override
501- public int retryCount() {
502- return RequestHandler.this.retryCount();
328+ private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException {
329+ // Make sure cancel() does not see a stale connectionHandler if it sees the new query state
330+ // before connection.write has completed
331+ connectionHandler = null;
332+
333+ // Ensure query state is "in progress" (can be already if connection.write failed on a previous node and we're retrying)
334+ while (true) {
335+ QueryState previous = queryStateRef.get();
336+ if (previous.isCancelled()) {
337+ connection.release();
338+ return;
339+ }
340+ if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext()))
341+ break;
503342 }
504343
505- @Override
506- public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
507- QueryState queryState = queryStateRef.get();
508- if (!queryState.isInProgressAt(retryCount) ||
509- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
510- logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
511- retryCount, queryState, queryStateRef.get());
344+ connectionHandler = connection.write(responseCallback, false);
345+ // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered
346+ // *before* the call to connection.write had returned.
347+ connectionHandler.startTimeout();
348+
349+ // Note that we could have already received the response here (so onSet() / onException() would have been called). This is
350+ // why we only test for CANCELLED_WHILE_IN_PROGRESS below.
351+
352+ // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have
353+ // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice,
354+ // but it knows how to deal with it).
355+ if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS)
356+ connectionHandler.cancelHandler();
357+ }
358+
359+ private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
360+ final Host h = current;
361+ this.retryConsistencyLevel = newConsistencyLevel;
362+
363+ // We should not retry on the current thread as this will be an IO thread.
364+ manager.executor().execute(new Runnable() {
365+ @Override
366+ public void run() {
367+ if (queryStateRef.get().isCancelled())
368+ return;
369+ try {
370+ if (retryCurrent) {
371+ if (query(h))
372+ return;
373+ }
374+ sendRequest();
375+ } catch (Exception e) {
376+ setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e));
377+ }
378+ }
379+ });
380+ }
381+
382+ void cancel() {
383+ // Atomically set a special QueryState, that will cause any further operation to abort.
384+ // We want to remember whether a request was in progress when we did this, so there are two cancel states.
385+ while (true) {
386+ QueryState previous = queryStateRef.get();
387+ if (previous.isCancelled()) {
388+ return;
389+ } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) {
390+ if(logger.isTraceEnabled())
391+ logger.trace("[{}] Cancelled while in progress", id);
392+ // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
393+ // If it's still null, this will be handled by re-checking queryStateRef at the end of write().
394+ if (connectionHandler != null)
395+ connectionHandler.cancelHandler();
396+ return;
397+ } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
398+ if(logger.isTraceEnabled())
399+ logger.trace("[{}] Cancelled while complete", id);
512400 return;
513401 }
402+ }
403+ }
404+
405+ @Override
406+ public Message.Request request() {
407+ if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency())
408+ return manager.makeRequestMessage(statement, retryConsistencyLevel, request.serialConsistency(), request.pagingState(), request.defaultTimestamp());
409+ else
410+ return request;
411+ }
514412
515- if (connection instanceof PooledConnection)
516- ((PooledConnection)connection).release();
413+ @Override
414+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
415+ QueryState queryState = queryStateRef.get();
416+ if (!queryState.isInProgressAt(retryCount) ||
417+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
418+ logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
419+ retryCount, queryState, queryStateRef.get());
420+ return;
421+ }
517422
518- // TODO should we check the response ?
423+ Host queriedHost = current;
424+ Exception exceptionToReport = null;
425+ try {
519426 switch (response.type) {
520427 case RESULT:
521- if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) {
522- logger.debug("Scheduling retry now that query is prepared");
523- retry(true, null);
524- } else {
525- logError(connection.address, new DriverException("Got unexpected response to prepare message: " + response));
526- retry(false, null);
527- }
428+ connection.release();
429+ setFinalResult(connection, response);
528430 break;
529431 case ERROR:
530- logError(connection.address, new DriverException("Error preparing query, got " + response));
531- if (metricsEnabled())
532- metrics().getErrorMetrics().getOthers().inc();
533- retry(false, null);
432+ Responses.Error err = (Responses.Error)response;
433+ exceptionToReport = err.asException(connection.address);
434+ RetryPolicy.RetryDecision retry = null;
435+ RetryPolicy retryPolicy = statement.getRetryPolicy() == null
436+ ? manager.configuration().getPolicies().getRetryPolicy()
437+ : statement.getRetryPolicy();
438+ switch (err.code) {
439+ case READ_TIMEOUT:
440+ connection.release();
441+ assert err.infos instanceof ReadTimeoutException;
442+ if (metricsEnabled())
443+ metrics().getErrorMetrics().getReadTimeouts().inc();
444+
445+ ReadTimeoutException rte = (ReadTimeoutException)err.infos;
446+ retry = retryPolicy.onReadTimeout(statement,
447+ rte.getConsistencyLevel(),
448+ rte.getRequiredAcknowledgements(),
449+ rte.getReceivedAcknowledgements(),
450+ rte.wasDataRetrieved(),
451+ retriesByPolicy);
452+
453+ if (metricsEnabled()) {
454+ if (retry.getType() == Type.RETRY)
455+ metrics().getErrorMetrics().getRetriesOnReadTimeout().inc();
456+ if (retry.getType() == Type.IGNORE)
457+ metrics().getErrorMetrics().getIgnoresOnReadTimeout().inc();
458+ }
459+ break;
460+ case WRITE_TIMEOUT:
461+ connection.release();
462+ assert err.infos instanceof WriteTimeoutException;
463+ if (metricsEnabled())
464+ metrics().getErrorMetrics().getWriteTimeouts().inc();
465+
466+ WriteTimeoutException wte = (WriteTimeoutException)err.infos;
467+ retry = retryPolicy.onWriteTimeout(statement,
468+ wte.getConsistencyLevel(),
469+ wte.getWriteType(),
470+ wte.getRequiredAcknowledgements(),
471+ wte.getReceivedAcknowledgements(),
472+ retriesByPolicy);
473+
474+ if (metricsEnabled()) {
475+ if (retry.getType() == Type.RETRY)
476+ metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc();
477+ if (retry.getType() == Type.IGNORE)
478+ metrics().getErrorMetrics().getIgnoresOnWriteTimeout().inc();
479+ }
480+ break;
481+ case UNAVAILABLE:
482+ connection.release();
483+ assert err.infos instanceof UnavailableException;
484+ if (metricsEnabled())
485+ metrics().getErrorMetrics().getUnavailables().inc();
486+
487+ UnavailableException ue = (UnavailableException)err.infos;
488+ retry = retryPolicy.onUnavailable(statement,
489+ ue.getConsistencyLevel(),
490+ ue.getRequiredReplicas(),
491+ ue.getAliveReplicas(),
492+ retriesByPolicy);
493+
494+ if (metricsEnabled()) {
495+ if (retry.getType() == Type.RETRY)
496+ metrics().getErrorMetrics().getRetriesOnUnavailable().inc();
497+ if (retry.getType() == Type.IGNORE)
498+ metrics().getErrorMetrics().getIgnoresOnUnavailable().inc();
499+ }
500+ break;
501+ case OVERLOADED:
502+ connection.release();
503+ // Try another node
504+ logger.warn("Host {} is overloaded, trying next host.", connection.address);
505+ DriverException overloaded = new DriverException("Host overloaded");
506+ logError(connection.address, overloaded);
507+ if (metricsEnabled())
508+ metrics().getErrorMetrics().getOthers().inc();
509+ retry(false, null);
510+ return;
511+ case SERVER_ERROR:
512+ connection.release();
513+ // Defunct connection and try another node
514+ logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message);
515+ DriverException exception = new DriverException("Host replied with server error: " + err.message);
516+ logError(connection.address, exception);
517+ connection.defunct(exception);
518+ if (metricsEnabled())
519+ metrics().getErrorMetrics().getOthers().inc();
520+ retry(false, null);
521+ return;
522+ case IS_BOOTSTRAPPING:
523+ connection.release();
524+ // Try another node
525+ logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address);
526+ DriverException bootstrapping = new DriverException("Host is bootstrapping");
527+ logError(connection.address, bootstrapping);
528+ if (metricsEnabled())
529+ metrics().getErrorMetrics().getOthers().inc();
530+ retry(false, null);
531+ return;
532+ case UNPREPARED:
533+ // Do not release connection yet, because we might reuse it to send the PREPARE message (see write() call below)
534+ assert err.infos instanceof MD5Digest;
535+ MD5Digest id = (MD5Digest)err.infos;
536+ PreparedStatement toPrepare = manager.cluster.manager.preparedQueries.get(id);
537+ if (toPrepare == null) {
538+ // This shouldn't happen
539+ connection.release();
540+ String msg = String.format("Tried to execute unknown prepared query %s", id);
541+ logger.error(msg);
542+ setFinalException(connection, new DriverInternalError(msg));
543+ return;
544+ }
545+
546+ String currentKeyspace = connection.keyspace();
547+ String prepareKeyspace = toPrepare.getQueryKeyspace();
548+ if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) {
549+ // This shouldn't happen in normal use, because a user shouldn't try to execute
550+ // a prepared statement with the wrong keyspace set.
551+ // Fail fast (we can't change the keyspace to reprepare, because we're using a pooled connection
552+ // that's shared with other requests).
553+ connection.release();
554+ throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)",
555+ toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
556+ }
557+
558+ logger.info("Query {} is not prepared on {}, preparing before retrying executing. "
559+ + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
560+ toPrepare.getQueryString(), connection.address);
561+
562+ write(connection, prepareAndRetry(toPrepare.getQueryString()));
563+ // we're done for now, the prepareAndRetry callback will handle the rest
564+ return;
565+ default:
566+ connection.release();
567+ if (metricsEnabled())
568+ metrics().getErrorMetrics().getOthers().inc();
569+ break;
570+ }
571+
572+ if (retry == null)
573+ setFinalResult(connection, response);
574+ else {
575+ switch (retry.getType()) {
576+ case RETRY:
577+ ++retriesByPolicy;
578+ if (logger.isDebugEnabled())
579+ logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel());
580+ if (metricsEnabled())
581+ metrics().getErrorMetrics().getRetries().inc();
582+ retry(true, retry.getRetryConsistencyLevel());
583+ break;
584+ case RETHROW:
585+ setFinalResult(connection, response);
586+ break;
587+ case IGNORE:
588+ if (metricsEnabled())
589+ metrics().getErrorMetrics().getIgnores().inc();
590+ setFinalResult(connection, new Responses.Result.Void());
591+ break;
592+ }
593+ }
534594 break;
535595 default:
536- // Something's wrong, so we return but we let setFinalResult propagate the exception
537- RequestHandler.this.setFinalResult(connection, response);
596+ connection.release();
597+ setFinalResult(connection, response);
538598 break;
539599 }
600+ } catch (Exception e) {
601+ exceptionToReport = e;
602+ setFinalException(connection, e);
603+ } finally {
604+ if (queriedHost != null && statement != Statement.DEFAULT)
605+ manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency);
540606 }
607+ }
541608
542- @Override
543- public void onException(Connection connection, Exception exception, long latency, int retryCount) {
544- RequestHandler.this.onException(connection, exception, latency, retryCount);
545- }
609+ private Connection.ResponseCallback prepareAndRetry(final String toPrepare) {
610+ return new Connection.ResponseCallback() {
546611
547- @Override
548- public boolean onTimeout(Connection connection, long latency, int retryCount) {
549- QueryState queryState = queryStateRef.get();
550- if (!queryState.isInProgressAt(retryCount) ||
551- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
552- logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
553- retryCount, queryState, queryStateRef.get());
554- return false;
612+ @Override
613+ public Message.Request request() {
614+ return new Requests.Prepare(toPrepare);
555615 }
556- logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
557- retry(false, null);
558- return true;
616+
617+ @Override
618+ public int retryCount() {
619+ return SpeculativeExecution.this.retryCount();
620+ }
621+
622+ @Override
623+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
624+ QueryState queryState = queryStateRef.get();
625+ if (!queryState.isInProgressAt(retryCount) ||
626+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
627+ logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
628+ retryCount, queryState, queryStateRef.get());
629+ return;
630+ }
631+
632+ connection.release();
633+
634+ // TODO should we check the response ?
635+ switch (response.type) {
636+ case RESULT:
637+ if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) {
638+ logger.debug("Scheduling retry now that query is prepared");
639+ retry(true, null);
640+ } else {
641+ logError(connection.address, new DriverException("Got unexpected response to prepare message: " + response));
642+ retry(false, null);
643+ }
644+ break;
645+ case ERROR:
646+ logError(connection.address, new DriverException("Error preparing query, got " + response));
647+ if (metricsEnabled())
648+ metrics().getErrorMetrics().getOthers().inc();
649+ retry(false, null);
650+ break;
651+ default:
652+ // Something's wrong, so we return but we let setFinalResult propagate the exception
653+ SpeculativeExecution.this.setFinalResult(connection, response);
654+ break;
655+ }
656+ }
657+
658+ @Override
659+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
660+ SpeculativeExecution.this.onException(connection, exception, latency, retryCount);
661+ }
662+
663+ @Override
664+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
665+ QueryState queryState = queryStateRef.get();
666+ if (!queryState.isInProgressAt(retryCount) ||
667+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
668+ logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
669+ retryCount, queryState, queryStateRef.get());
670+ return false;
671+ }
672+ logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
673+ retry(false, null);
674+ return true;
675+ }
676+ };
677+ }
678+
679+ @Override
680+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
681+ QueryState queryState = queryStateRef.get();
682+ if (!queryState.isInProgressAt(retryCount) ||
683+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
684+ logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
685+ retryCount, queryState, queryStateRef.get());
686+ return;
559687 }
560- };
561- }
562688
563- @Override
564- public void onException(Connection connection, Exception exception, long latency, int retryCount) {
565- QueryState queryState = queryStateRef.get();
566- if (!queryState.isInProgressAt(retryCount) ||
567- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
568- logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
569- retryCount, queryState, queryStateRef.get());
570- return;
689+ Host queriedHost = current;
690+ try {
691+ connection.release();
692+
693+ if (exception instanceof ConnectionException) {
694+ if (metricsEnabled())
695+ metrics().getErrorMetrics().getConnectionErrors().inc();
696+ ConnectionException ce = (ConnectionException)exception;
697+ logError(ce.address, ce);
698+ retry(false, null);
699+ return;
700+ }
701+ setFinalException(connection, exception);
702+ } catch (Exception e) {
703+ // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely
704+ setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e));
705+ } finally {
706+ if (queriedHost != null && statement != Statement.DEFAULT)
707+ manager.cluster.manager.reportLatency(queriedHost, statement, exception, latency);
708+ }
571709 }
572710
573- Host queriedHost = current;
574- try {
575- if (connection instanceof PooledConnection)
576- ((PooledConnection)connection).release();
711+ @Override
712+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
713+ QueryState queryState = queryStateRef.get();
714+ if (!queryState.isInProgressAt(retryCount) ||
715+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
716+ logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
717+ retryCount, queryState, queryStateRef.get());
718+ return false;
719+ }
577720
578- if (exception instanceof ConnectionException) {
579- if (metricsEnabled())
580- metrics().getErrorMetrics().getConnectionErrors().inc();
581- ConnectionException ce = (ConnectionException)exception;
582- logError(ce.address, ce);
721+ Host queriedHost = current;
722+ OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address);
723+ try {
724+ logError(connection.address, timeoutException);
583725 retry(false, null);
584- return;
726+ } catch (Exception e) {
727+ // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely
728+ setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e));
729+ } finally {
730+ if (queriedHost != null && statement != Statement.DEFAULT)
731+ manager.cluster.manager.reportLatency(queriedHost, statement, timeoutException, latency);
585732 }
586- setFinalException(connection, exception);
587- } catch (Exception e) {
588- // This shouldn't happen, but if it does, we want to signal the callback, not let him hang indefinitively
589- setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e));
590- } finally {
591- if (queriedHost != null)
592- manager.cluster.manager.reportLatency(queriedHost, latency);
733+ return true;
593734 }
594- }
595735
596- @Override
597- public boolean onTimeout(Connection connection, long latency, int retryCount) {
598- QueryState queryState = queryStateRef.get();
599- if (!queryState.isInProgressAt(retryCount) ||
600- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
601- logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
602- retryCount, queryState, queryStateRef.get());
603- return false;
736+ @Override
737+ public int retryCount() {
738+ return queryStateRef.get().retryCount;
604739 }
605740
606- Host queriedHost = current;
607- try {
608- // If a query times out, we consider that the host is unstable, so we defunct
609- // the connection to mark it down.
610- DriverException timeoutException = new DriverException("Timed out waiting for server response");
611- connection.defunct(timeoutException);
612-
613- logError(connection.address, timeoutException);
614- retry(false, null);
615- } catch (Exception e) {
616- // This shouldn't happen, but if it does, we want to signal the callback, not let him hang indefinitively
617- setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e));
618- } finally {
619- if (queriedHost != null)
620- manager.cluster.manager.reportLatency(queriedHost, latency);
741+ private void setFinalException(Connection connection, Exception exception) {
742+ RequestHandler.this.setFinalException(this, connection, exception);
621743 }
622- return true;
623- }
624-
625- @Override
626- public int retryCount() {
627- return queryStateRef.get().retryCount;
628- }
629744
630- interface Callback extends Connection.ResponseCallback {
631- public void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
632- public void register(RequestHandler handler);
745+ private void setFinalResult(Connection connection, Message.Response response) {
746+ RequestHandler.this.setFinalResult(this, connection, response);
747+ }
633748 }
634749
635- // This is used to prevent races between request completion (either success or error) and timeout.
636- // A retry is in progress once we have written the request to the connection and until we get back a response (see onSet
637- // or onException) or a timeout (see onTimeout).
638- // The count increments on each retry.
750+ /**
751+ * The state of a SpeculativeExecution.
752+ *
753+ * This is used to prevent races between request completion (either success or error) and timeout.
754+ * A retry is in progress once we have written the request to the connection and until we get back a response (see onSet
755+ * or onException) or a timeout (see onTimeout).
756+ * The count increments on each retry.
757+ */
639758 static class QueryState {
640759 static final QueryState INITIAL = new QueryState(-1, false);
641760 static final QueryState CANCELLED_WHILE_IN_PROGRESS = new QueryState(Integer.MIN_VALUE, false);
@@ -672,4 +791,21 @@
672791 return String.format("QueryState(count=%d, inProgress=%s, cancelled=%s)", retryCount, inProgress, isCancelled());
673792 }
674793 }
794+
795+ /**
796+ * Wraps the iterator return by {@link com.datastax.driver.core.policies.LoadBalancingPolicy} to make it safe for
797+ * concurrent access by multiple threads.
798+ */
799+ static class QueryPlan {
800+ private final Iterator<Host> iterator;
801+
802+ QueryPlan(Iterator<Host> iterator) {
803+ this.iterator = iterator;
804+ }
805+
806+ /** @return null if there are no more hosts */
807+ synchronized Host next() {
808+ return iterator.hasNext() ? iterator.next() : null;
809+ }
810+ }
675811 }
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +13 −13
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -22,7 +22,7 @@
2222 import java.util.Map;
2323
2424 import com.google.common.collect.ImmutableMap;
25-import org.jboss.netty.buffer.ChannelBuffer;
25+import io.netty.buffer.ByteBuf;
2626
2727 class Requests {
2828
@@ -35,7 +35,7 @@
3535 public static final String COMPRESSION_OPTION = "COMPRESSION";
3636
3737 public static final Message.Coder<Startup> coder = new Message.Coder<Startup>() {
38- public void encode(Startup msg, ChannelBuffer dest, ProtocolVersion version) {
38+ public void encode(Startup msg, ByteBuf dest, ProtocolVersion version) {
3939 CBUtil.writeStringMap(msg.options, dest);
4040 }
4141
@@ -67,7 +67,7 @@
6767
6868 public static final Message.Coder<Credentials> coder = new Message.Coder<Credentials>() {
6969
70- public void encode(Credentials msg, ChannelBuffer dest, ProtocolVersion version) {
70+ public void encode(Credentials msg, ByteBuf dest, ProtocolVersion version) {
7171 assert version == ProtocolVersion.V1;
7272 CBUtil.writeStringMap(msg.credentials, dest);
7373 }
@@ -90,7 +90,7 @@
9090
9191 public static final Message.Coder<Options> coder = new Message.Coder<Options>()
9292 {
93- public void encode(Options msg, ChannelBuffer dest, ProtocolVersion version) {}
93+ public void encode(Options msg, ByteBuf dest, ProtocolVersion version) {}
9494
9595 public int encodedSize(Options msg, ProtocolVersion version) {
9696 return 0;
@@ -110,7 +110,7 @@
110110 public static class Query extends Message.Request {
111111
112112 public static final Message.Coder<Query> coder = new Message.Coder<Query>() {
113- public void encode(Query msg, ChannelBuffer dest, ProtocolVersion version) {
113+ public void encode(Query msg, ByteBuf dest, ProtocolVersion version) {
114114 CBUtil.writeLongString(msg.query, dest);
115115 msg.options.encode(dest, version);
116116 }
@@ -143,7 +143,7 @@
143143 public static class Execute extends Message.Request {
144144
145145 public static final Message.Coder<Execute> coder = new Message.Coder<Execute>() {
146- public void encode(Execute msg, ChannelBuffer dest, ProtocolVersion version) {
146+ public void encode(Execute msg, ByteBuf dest, ProtocolVersion version) {
147147 CBUtil.writeBytes(msg.statementId.bytes, dest);
148148 msg.options.encode(dest, version);
149149 }
@@ -248,7 +248,7 @@
248248 flags.add(QueryFlag.DEFAULT_TIMESTAMP);
249249 }
250250
251- public void encode(ChannelBuffer dest, ProtocolVersion version) {
251+ public void encode(ByteBuf dest, ProtocolVersion version) {
252252 switch (version) {
253253 case V1:
254254 if (flags.contains(QueryFlag.VALUES))
@@ -310,7 +310,7 @@
310310 public static class Batch extends Message.Request {
311311
312312 public static final Message.Coder<Batch> coder = new Message.Coder<Batch>() {
313- public void encode(Batch msg, ChannelBuffer dest, ProtocolVersion version) {
313+ public void encode(Batch msg, ByteBuf dest, ProtocolVersion version) {
314314 int queries = msg.queryOrIdList.size();
315315 assert queries <= 0xFFFF;
316316
@@ -398,7 +398,7 @@
398398 flags.add(QueryFlag.DEFAULT_TIMESTAMP);
399399 }
400400
401- public void encode(ChannelBuffer dest, ProtocolVersion version) {
401+ public void encode(ByteBuf dest, ProtocolVersion version) {
402402 switch (version) {
403403 case V2:
404404 CBUtil.writeConsistencyLevel(consistency, dest);
@@ -445,7 +445,7 @@
445445
446446 public static final Message.Coder<Prepare> coder = new Message.Coder<Prepare>() {
447447
448- public void encode(Prepare msg, ChannelBuffer dest, ProtocolVersion version) {
448+ public void encode(Prepare msg, ByteBuf dest, ProtocolVersion version) {
449449 CBUtil.writeLongString(msg.query, dest);
450450 }
451451
@@ -470,7 +470,7 @@
470470 public static class Register extends Message.Request {
471471
472472 public static final Message.Coder<Register> coder = new Message.Coder<Register>() {
473- public void encode(Register msg, ChannelBuffer dest, ProtocolVersion version) {
473+ public void encode(Register msg, ByteBuf dest, ProtocolVersion version) {
474474 dest.writeShort(msg.eventTypes.size());
475475 for (ProtocolEvent.Type type : msg.eventTypes)
476476 CBUtil.writeEnumValue(type, dest);
@@ -501,7 +501,7 @@
501501
502502 public static final Message.Coder<AuthResponse> coder = new Message.Coder<AuthResponse>() {
503503
504- public void encode(AuthResponse response, ChannelBuffer dest, ProtocolVersion version) {
504+ public void encode(AuthResponse response, ByteBuf dest, ProtocolVersion version) {
505505 CBUtil.writeValue(response.token, dest);
506506 }
507507
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +21 −22
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -18,9 +18,8 @@
1818 import java.net.InetSocketAddress;
1919 import java.nio.ByteBuffer;
2020 import java.util.*;
21-import java.util.concurrent.LinkedBlockingQueue;
2221
23-import org.jboss.netty.buffer.ChannelBuffer;
22+import io.netty.buffer.ByteBuf;
2423
2524 import com.datastax.driver.core.ProtocolEvent.SchemaChange;
2625 import com.datastax.driver.core.ProtocolEvent.SchemaChange.Change;
@@ -37,7 +36,7 @@
3736
3837 public static final Message.Decoder<Error> decoder = new Message.Decoder<Error>() {
3938 @Override
40- public Error decode(ChannelBuffer body, ProtocolVersion version) {
39+ public Error decode(ByteBuf body, ProtocolVersion version) {
4140 ExceptionCode code = ExceptionCode.fromValue(body.readInt());
4241 String msg = CBUtil.readString(body);
4342 Object infos = null;
@@ -93,8 +92,8 @@
9392 case PROTOCOL_ERROR: return new DriverInternalError("An unexpected protocol error occurred. This is a bug in this library, please report: " + message);
9493 case BAD_CREDENTIALS: return new AuthenticationException(host, message);
9594 case UNAVAILABLE: return ((UnavailableException)infos).copy(); // We copy to have a nice stack trace
96- case OVERLOADED: return new DriverInternalError(String.format("Queried host (%s) was overloaded; this shouldn't happen, another node should have been tried", host));
97- case IS_BOOTSTRAPPING: return new DriverInternalError(String.format("Queried host (%s) was bootstrapping; this shouldn't happen, another node should have been tried", host));
95+ case OVERLOADED: return new OverloadedException(host, message);
96+ case IS_BOOTSTRAPPING: return new BootstrappingException(host, message);
9897 case TRUNCATE_ERROR: return new TruncateException(message);
9998 case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy();
10099 case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy();
@@ -103,7 +102,7 @@
103102 case INVALID: return new InvalidQueryException(message);
104103 case CONFIG_ERROR: return new InvalidConfigurationInQueryException(message);
105104 case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy();
106- 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));
105+ case UNPREPARED: return new UnpreparedException(host, message);
107106 default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
108107 }
109108 }
@@ -117,7 +116,7 @@
117116 public static class Ready extends Message.Response {
118117
119118 public static final Message.Decoder<Ready> decoder = new Message.Decoder<Ready>() {
120- public Ready decode(ChannelBuffer body, ProtocolVersion version) {
119+ public Ready decode(ByteBuf body, ProtocolVersion version) {
121120 // TODO: Would it be cool to return a singleton? Check we don't need to
122121 // set the streamId or something
123122 return new Ready();
@@ -137,7 +136,7 @@
137136 public static class Authenticate extends Message.Response {
138137
139138 public static final Message.Decoder<Authenticate> decoder = new Message.Decoder<Authenticate>() {
140- public Authenticate decode(ChannelBuffer body, ProtocolVersion version) {
139+ public Authenticate decode(ByteBuf body, ProtocolVersion version) {
141140 String authenticator = CBUtil.readString(body);
142141 return new Authenticate(authenticator);
143142 }
@@ -159,7 +158,7 @@
159158 public static class Supported extends Message.Response {
160159
161160 public static final Message.Decoder<Supported> decoder = new Message.Decoder<Supported>() {
162- public Supported decode(ChannelBuffer body, ProtocolVersion version) {
161+ public Supported decode(ByteBuf body, ProtocolVersion version) {
163162 return new Supported(CBUtil.readStringToStringListMap(body));
164163 }
165164 };
@@ -195,7 +194,7 @@
195194 public static abstract class Result extends Message.Response {
196195
197196 public static final Message.Decoder<Result> decoder = new Message.Decoder<Result>() {
198- public Result decode(ChannelBuffer body, ProtocolVersion version) {
197+ public Result decode(ByteBuf body, ProtocolVersion version) {
199198 Kind kind = Kind.fromId(body.readInt());
200199 return kind.subDecoder.decode(body, version);
201200 }
@@ -252,7 +251,7 @@
252251 }
253252
254253 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
255- public Result decode(ChannelBuffer body, ProtocolVersion version) {
254+ public Result decode(ByteBuf body, ProtocolVersion version) {
256255 return new Void();
257256 }
258257 };
@@ -272,7 +271,7 @@
272271 }
273272
274273 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
275- public Result decode(ChannelBuffer body, ProtocolVersion version) {
274+ public Result decode(ByteBuf body, ProtocolVersion version) {
276275 return new SetKeyspace(CBUtil.readString(body));
277276 }
278277 };
@@ -324,7 +323,7 @@
324323 this.pagingState = pagingState;
325324 }
326325
327- public static Metadata decode(ChannelBuffer body) {
326+ public static Metadata decode(ByteBuf body) {
328327
329328 // flags & column count
330329 EnumSet<Flag> flags = Flag.deserialize(body.readInt());
@@ -378,7 +377,7 @@
378377 }
379378
380379 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
381- public Result decode(ChannelBuffer body, ProtocolVersion version) {
380+ public Result decode(ByteBuf body, ProtocolVersion version) {
382381
383382 Metadata metadata = Metadata.decode(body);
384383
@@ -441,14 +440,14 @@
441440 public static class Prepared extends Result {
442441
443442 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
444- public Result decode(ChannelBuffer body, ProtocolVersion version) {
443+ public Result decode(ByteBuf body, ProtocolVersion version) {
445444 MD5Digest id = MD5Digest.wrap(CBUtil.readBytes(body));
446445 Rows.Metadata metadata = Rows.Metadata.decode(body);
447446 Rows.Metadata resultMetadata = decodeResultMetadata(body, version);
448447 return new Prepared(id, metadata, resultMetadata);
449448 }
450449
451- private Metadata decodeResultMetadata(ChannelBuffer body, ProtocolVersion version) {
450+ private Metadata decodeResultMetadata(ByteBuf body, ProtocolVersion version) {
452451 switch (version) {
453452 case V1:
454453 return Rows.Metadata.EMPTY;
@@ -489,7 +488,7 @@
489488 public final String name;
490489
491490 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
492- public Result decode(ChannelBuffer body, ProtocolVersion version)
491+ public Result decode(ByteBuf body, ProtocolVersion version)
493492 {
494493 // Note: the CREATE KEYSPACE/TABLE/TYPE SCHEMA_CHANGE response is different from the SCHEMA_CHANGE EVENT type
495494 Change change;
@@ -514,7 +513,7 @@
514513 }
515514 }
516515
517- private Target maybeReadTarget(ChannelBuffer body, ProtocolVersion version) {
516+ private Target maybeReadTarget(ByteBuf body, ProtocolVersion version) {
518517 switch (version) {
519518 case V1:
520519 case V2:
@@ -545,7 +544,7 @@
545544 public static class Event extends Message.Response {
546545
547546 public static final Message.Decoder<Event> decoder = new Message.Decoder<Event>() {
548- public Event decode(ChannelBuffer body, ProtocolVersion version) {
547+ public Event decode(ByteBuf body, ProtocolVersion version) {
549548 return new Event(ProtocolEvent.deserialize(body, version));
550549 }
551550 };
@@ -566,7 +565,7 @@
566565 public static class AuthChallenge extends Message.Response {
567566
568567 public static final Message.Decoder<AuthChallenge> decoder = new Message.Decoder<AuthChallenge>() {
569- public AuthChallenge decode(ChannelBuffer body, ProtocolVersion version) {
568+ public AuthChallenge decode(ByteBuf body, ProtocolVersion version) {
570569 ByteBuffer b = CBUtil.readValue(body);
571570 if (b == null)
572571 return new AuthChallenge(null);
@@ -588,7 +587,7 @@
588587 public static class AuthSuccess extends Message.Response {
589588
590589 public static final Message.Decoder<AuthSuccess> decoder = new Message.Decoder<AuthSuccess>() {
591- public AuthSuccess decode(ChannelBuffer body, ProtocolVersion version) {
590+ public AuthSuccess decode(ByteBuf body, ProtocolVersion version) {
592591 ByteBuffer b = CBUtil.readValue(body);
593592 if (b == null)
594593 return new AuthSuccess(null);
modified driver-core/src/main/java/com/datastax/driver/core/ResultSet.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +31 −6
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
1717
1818 import java.io.Closeable;
1919 import java.util.Collection;
20-import java.util.Map;
2120
2221 import com.google.common.util.concurrent.ListenableFuture;
2322
@@ -297,10 +296,12 @@
297296 * This method has no particular effect if the session was already closed
298297 * (in which case the returned future will return immediately).
299298 * <p>
300- * Note that if you want to close the full {@code Cluster} instance
301- * this session is part of, you should use {@link Cluster#close} instead
302- * (which will call this method for all sessions but also release some
303- * additional resources).
299+ * Note that this method does not close the corresponding {@code Cluster}
300+ * instance (which holds additional resources, in particular internal
301+ * executors that must be shut down in order for the client program to
302+ * terminate).
303+ * If you want to do so, use {@link Cluster#close}, but note that it will
304+ * close all sessions created from that cluster.
304305 *
305306 * @return a future on the completion of the shutdown process.
306307 */
@@ -311,6 +312,13 @@
311312 * that shutdown completes.
312313 * <p>
313314 * This method is a shortcut for {@code closeAsync().get()}.
315+ * <p>
316+ * Note that this method does not close the corresponding {@code Cluster}
317+ * instance (which holds additional resources, in particular internal
318+ * executors that must be shut down in order for the client program to
319+ * terminate).
320+ * If you want to do so, use {@link Cluster#close}, but note that it will
321+ * close all sessions created from that cluster.
314322 */
315323 public void close();
316324
@@ -376,6 +384,9 @@
376384
377385 /**
378386 * The number of open connections to a given host.
387+ * <p>
388+ * Note that this refers to <em>active</em> connections. The actual number of connections also
389+ * includes {@link #getTrashedConnections(Host)}.
379390 *
380391 * @param host the host to get open connections for.
381392 * @return The number of open connections to {@code host}. If the session
@@ -383,6 +394,20 @@
383394 */
384395 public int getOpenConnections(Host host);
385396
397+ /**
398+ * The number of "trashed" connections to a given host.
399+ * <p>
400+ * When the load to a host decreases, the driver will reclaim some connections in order to save
401+ * resources. No requests are sent to these connections anymore, but they are kept open for an
402+ * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load
403+ * goes up again. This method counts connections in that state.
404+ *
405+ * @param host the host to get trashed connections for.
406+ * @return The number of trashed connections to {@code host}. If the session
407+ * is not connected to that host, 0 is returned.
408+ */
409+ public int getTrashedConnections(Host host);
410+
386411 /**
387412 * The number of queries that are currently being executed though a given host.
388413 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +165 −128
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -20,19 +20,21 @@
2020 import java.util.*;
2121 import java.util.concurrent.*;
2222 import java.util.concurrent.atomic.AtomicReference;
23-import java.util.concurrent.locks.Lock;
2423
2524 import com.google.common.base.Function;
2625 import com.google.common.collect.ImmutableList;
26+import com.google.common.collect.Lists;
2727 import com.google.common.util.concurrent.*;
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
3030
31-
3231 import com.datastax.driver.core.exceptions.DriverInternalError;
32+import com.datastax.driver.core.exceptions.InvalidQueryException;
3333 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3434 import com.datastax.driver.core.policies.LoadBalancingPolicy;
3535 import com.datastax.driver.core.policies.ReconnectionPolicy;
36+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
37+import com.datastax.driver.core.utils.MoreFutures;
3638
3739 /**
3840 * Driver implementation of the Session interface.
@@ -46,8 +48,6 @@
4648 final HostConnectionPool.PoolState poolsState;
4749 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
4850
49- private final Striped<Lock> poolCreationLocks = Striped.lazyWeakLock(5);
50-
5151 private volatile boolean isInit;
5252 private volatile boolean isClosing;
5353
@@ -67,50 +67,28 @@
6767
6868 // Create pools to initial nodes (and wait for them to be created)
6969 Collection<Host> hosts = cluster.getMetadata().allHosts();
70- if (cluster.manager.sessions.size() == 1) {
71- // We only do it in parallel if this is the first session (meaning that the cluster just initialized).
72- createPoolsInParallel(hosts);
73- } else {
74- // Otherwise, we don't want to fill executor() because this is also where up/down notifications are processed,
75- // it's important that existing sessions get them in a timely manner. So we create the pools one by one:
76- createPoolsSequentially(hosts);
77- }
70+ createPoolsInParallel(hosts);
7871
7972 isInit = true;
80- updateCreatedPools(executor());
73+ updateCreatedPools();
8174 return this;
8275 }
8376
8477 private void createPoolsInParallel(Collection<Host> hosts) {
85- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size());
78+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
8679 for (Host host : hosts)
8780 if (host.state != Host.State.DOWN)
88- futures.add(maybeAddPool(host, executor()));
89- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
81+ futures.add(maybeAddPool(host, null));
9082 try {
91- f.get();
83+ Futures.successfulAsList(futures).get();
9284 } catch (ExecutionException e) {
93- // This is not supposed to happen
94- throw new DriverInternalError(e);
85+ // Won't happen because we used successfulAsList
86+ // And if a particular pool failed, maybeAddPool already handled it
9587 } catch (InterruptedException e) {
9688 Thread.currentThread().interrupt();
9789 }
9890 }
9991
100- private void createPoolsSequentially(Collection<Host> hosts) {
101- for (Host host : cluster.getMetadata().allHosts()) {
102- try {
103- if (host.state != Host.State.DOWN)
104- maybeAddPool(host, executor()).get();
105- } catch (ExecutionException e) {
106- // This is not supposed to happen
107- throw new DriverInternalError(e);
108- } catch (InterruptedException e) {
109- Thread.currentThread().interrupt();
110- }
111- }
112- }
113-
11492 public String getLoggedKeyspace() {
11593 return poolsState.keyspace;
11694 }
@@ -202,6 +180,10 @@
202180 return cluster.manager.loadBalancingPolicy();
203181 }
204182
183+ SpeculativeExecutionPolicy speculativeRetryPolicy() {
184+ return cluster.manager.speculativeRetryPolicy();
185+ }
186+
205187 ReconnectionPolicy reconnectionPolicy() {
206188 return cluster.manager.reconnectionPolicy();
207189 }
@@ -215,79 +197,96 @@
215197 }
216198
217199 // Returns whether there was problem creating the pool
218- ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) {
200+ ListenableFuture<Boolean> forceRenewPool(final Host host, Connection reusedConnection) {
219201 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
220202 if (distance == HostDistance.IGNORED)
221203 return Futures.immediateFuture(true);
222204
223- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
224- return executor.submit(new Callable<Boolean>() {
225- public Boolean call() {
226- while (true) {
227- try {
228- if (isClosing)
229- return true;
230-
231- HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, SessionManager.this,
232- cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
233- HostConnectionPool previous = pools.put(host, newPool);
234- if (previous == null) {
235- logger.debug("Added connection pool for {}", host);
236- } else {
237- logger.debug("Renewed connection pool for {}", host);
238- previous.closeAsync();
239- }
205+ if (isClosing)
206+ return Futures.immediateFuture(false);
207+
208+ final HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, SessionManager.this,
209+ cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
210+ ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
211+
212+ final SettableFuture<Boolean> future = SettableFuture.create();
213+
214+ Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
215+ @Override
216+ public void onSuccess(Void result) {
217+ // If we raced with a session shutdown, ensure that the pool will be closed.
218+ HostConnectionPool previous = pools.put(host, newPool);
219+ if (previous == null) {
220+ logger.debug("Added connection pool for {}", host);
221+ } else {
222+ logger.debug("Renewed connection pool for {}", host);
223+ previous.closeAsync();
224+ }
240225
241- // If we raced with a session shutdown, ensure that the pool will be closed.
242- if (isClosing)
243- newPool.closeAsync();
244-
245- return true;
246- } catch (Exception e) {
247- logger.error("Error creating pool to " + host, e);
248- return false;
249- }
226+ // If we raced with a session shutdown, ensure that the pool will be closed.
227+ if (isClosing) {
228+ newPool.closeAsync();
229+ pools.remove(host);
230+ future.set(false);
231+ } else {
232+ future.set(true);
250233 }
251234 }
235+
236+ @Override
237+ public void onFailure(Throwable t) {
238+ logger.error("Error creating pool to " + host, t);
239+ future.set(false);
240+ }
252241 });
242+
243+ return future;
253244 }
254245
255- // Replace pool for a given only if it's the given previous value (which can be null)
256- // Note that the goal of this function is to make sure that 2 concurrent thread calling
257- // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools
258- // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we
259- // want to avoid
260- private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
246+ // Replace pool for a given host only if it's the given previous value (which can be null)
247+ // This returns a future if the replacement was successful, or null if we raced.
248+ private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous, Connection reusedConnection) {
261249 if (isClosing)
262- return true;
263-
264- Lock l = poolCreationLocks.get(host);
265- l.lock();
266- try {
267- HostConnectionPool previous = pools.get(host);
268- if (previous != condition)
269- return false;
270-
271- HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, SessionManager.this,
272- cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
273- previous = pools.put(host, newPool);
274- if (previous != null && !previous.isClosed()) {
250+ return MoreFutures.VOID_SUCCESS;
251+
252+ final HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, this,
253+ cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
254+ if (previous == null) {
255+ if (pools.putIfAbsent(host, newPool) != null) {
256+ return null;
257+ }
258+ } else {
259+ if (!pools.replace(host, previous, newPool)) {
260+ return null;
261+ }
262+ if (!previous.isClosed()) {
275263 logger.warn("Replacing a pool that wasn't closed. Closing it now, but this was not expected.");
276264 previous.closeAsync();
277265 }
266+ }
278267
279- // If we raced with a session shutdown, ensure that the pool will be closed.
280- if (isClosing)
281- newPool.closeAsync();
268+ ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
269+
270+ Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
271+ @Override
272+ public void onSuccess(Void result) {
273+ // If we raced with a session shutdown, ensure that the pool will be closed.
274+ if (isClosing) {
275+ newPool.closeAsync();
276+ pools.remove(host);
277+ }
278+ }
282279
283- return true;
284- } finally {
285- l.unlock();
286- }
280+ @Override
281+ public void onFailure(Throwable t) {
282+ pools.remove(host);
283+ }
284+ });
285+ return poolInitFuture;
287286 }
288287
289288 // Returns whether there was problem creating the pool
290- ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) {
289+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
291290 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
292291 if (distance == HostDistance.IGNORED)
293292 return Futures.immediateFuture(true);
@@ -296,41 +295,46 @@
296295 if (previous != null && !previous.isClosed())
297296 return Futures.immediateFuture(true);
298297
299- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
300- return executor.submit(new Callable<Boolean>() {
301- public Boolean call() {
302- try {
303- while (true) {
304- HostConnectionPool previous = pools.get(host);
305- if (previous != null && !previous.isClosed())
306- return true;
307-
308- if (replacePool(host, distance, previous)) {
309- logger.debug("Added connection pool for {}", host);
310- return true;
298+ while (true) {
299+ previous = pools.get(host);
300+ if (previous != null && !previous.isClosed())
301+ return Futures.immediateFuture(true);
302+
303+ final SettableFuture<Boolean> future = SettableFuture.create();
304+ ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous, reusedConnection);
305+ if (newPoolInit != null) {
306+ Futures.addCallback(newPoolInit, new FutureCallback<Void>() {
307+ @Override
308+ public void onSuccess(Void result) {
309+ logger.debug("Added connection pool for {}", host);
310+ future.set(true);
311+ }
312+
313+ @Override
314+ public void onFailure(Throwable t) {
315+ if (t instanceof UnsupportedProtocolVersionException) {
316+ cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException)t).unsupportedVersion);
317+ cluster.manager.triggerOnDown(host, false);
318+ } else if (t instanceof ClusterNameMismatchException) {
319+ ClusterNameMismatchException e = (ClusterNameMismatchException)t;
320+ cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
321+ cluster.manager.triggerOnDown(host, false);
322+ } else {
323+ logger.error("Error creating pool to " + host, t);
311324 }
325+ future.set(false);
312326 }
313- } catch (UnsupportedProtocolVersionException e) {
314- cluster.manager.logUnsupportedVersionProtocol(host, e.unsupportedVersion);
315- cluster.manager.triggerOnDown(host, false);
316- return false;
317- } catch (ClusterNameMismatchException e) {
318- cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
319- cluster.manager.triggerOnDown(host, false);
320- return false;
321- } catch (Exception e) {
322- logger.error("Error creating pool to " + host, e);
323- return false;
324- }
327+ });
328+ return future;
325329 }
326- });
330+ }
327331 }
328332
329333 CloseFuture removePool(Host host) {
330334 final HostConnectionPool pool = pools.remove(host);
331335 return pool == null
332- ? CloseFuture.immediateFuture()
333- : pool.closeAsync();
336+ ? CloseFuture.immediateFuture()
337+ : pool.closeAsync();
334338 }
335339
336340 /*
@@ -342,7 +346,7 @@
342346 * This method ensures that all hosts for which a pool should exist
343347 * have one, and hosts that shouldn't don't.
344348 */
345- void updateCreatedPools(ListeningExecutorService executor) {
349+ void updateCreatedPools() {
346350 // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if
347351 // we execute the code below we would try to create their pool over and over again.
348352 // It's called explicitly at the end of init(), once isInit has been set to true.
@@ -361,7 +365,7 @@
361365
362366 if (pool == null) {
363367 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
364- poolCreationFutures.add(maybeAddPool(h, executor));
368+ poolCreationFutures.add(maybeAddPool(h, null));
365369 } else if (dist != pool.hostDistance) {
366370 if (dist == HostDistance.IGNORED) {
367371 toRemove.add(h);
@@ -373,7 +377,12 @@
373377 }
374378
375379 // Wait pool creation before removing, so we don't lose connectivity
376- Futures.allAsList(poolCreationFutures).get();
380+ try {
381+ Futures.successfulAsList(poolCreationFutures).get();
382+ } catch (ExecutionException e) {
383+ // Won't happen because we used successfulAsList
384+ // And if a particular pool failed, maybeAddPool already handled it
385+ }
377386
378387 List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size());
379388 for (Host h : toRemove)
@@ -387,14 +396,18 @@
387396 }
388397 }
389398
390- void updateCreatedPools(Host h, ListeningExecutorService executor) {
399+ void updateCreatedPools(Host h) {
391400 HostDistance dist = loadBalancingPolicy().distance(h);
392401 HostConnectionPool pool = pools.get(h);
393402
394403 try {
395404 if (pool == null) {
396405 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
397- maybeAddPool(h, executor).get();
406+ try {
407+ maybeAddPool(h, null).get();
408+ } catch (ExecutionException e) {
409+ // Ignore, maybeAddPool has already handled the error
410+ }
398411 } else if (dist != pool.hostDistance) {
399412 if (dist == HostDistance.IGNORED) {
400413 removePool(h).get();
@@ -414,10 +427,7 @@
414427 // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
415428 // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
416429 removePool(host).force().get();
417- updateCreatedPools(MoreExecutors.sameThreadExecutor());
418- }
419-
420- void onSuspected(Host host) {
430+ updateCreatedPools();
421431 }
422432
423433 void onRemove(Host host) throws InterruptedException, ExecutionException {
@@ -468,6 +478,7 @@
468478 Message.Request makeRequestMessage(Statement statement, ConsistencyLevel cl, ConsistencyLevel scl, ByteBuffer pagingState, long defaultTimestamp) {
469479 ProtocolVersion protoVersion = cluster.manager.protocolVersion();
470480 int fetchSize = statement.getFetchSize();
481+ ByteBuffer usedPagingState = pagingState;
471482
472483 if (protoVersion == ProtocolVersion.V1) {
473484 assert pagingState == null;
@@ -484,6 +495,13 @@
484495 if (fetchSize == Integer.MAX_VALUE)
485496 fetchSize = -1;
486497
498+ if (pagingState == null) {
499+ usedPagingState = statement.getPagingState();
500+ }
501+
502+ if (statement instanceof StatementWrapper)
503+ statement = ((StatementWrapper)statement).getWrappedStatement();
504+
487505 if (statement instanceof RegularStatement) {
488506 RegularStatement rs = (RegularStatement)statement;
489507
@@ -501,14 +519,18 @@
501519 List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues);
502520 String qString = rs.getQueryString();
503521 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, values, false,
504- fetchSize, pagingState, scl, defaultTimestamp);
522+ fetchSize, usedPagingState, scl, defaultTimestamp);
505523 return new Requests.Query(qString, options);
506524 } else if (statement instanceof BoundStatement) {
507525 BoundStatement bs = (BoundStatement)statement;
526+ if (!cluster.manager.preparedQueries.containsKey(bs.statement.getPreparedId().id)) {
527+ throw new InvalidQueryException(String.format("Tried to execute unknown prepared query : %s. "
528+ + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
529+ }
508530 bs.ensureAllSet();
509531 boolean skipMetadata = protoVersion != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
510532 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, Arrays.asList(bs.wrapper.values), skipMetadata,
511- fetchSize, pagingState, scl, defaultTimestamp);
533+ fetchSize, usedPagingState, scl, defaultTimestamp);
512534 return new Requests.Execute(bs.statement.getPreparedId().id, options);
513535 } else {
514536 assert statement instanceof BatchStatement : statement;
@@ -545,7 +567,7 @@
545567
546568 // Let's not wait too long if we can't get a connection. Things
547569 // will fix themselves once the user tries a query anyway.
548- PooledConnection c = null;
570+ Connection c = null;
549571 boolean timedOut = false;
550572 try {
551573 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
@@ -578,11 +600,18 @@
578600 return future;
579601 }
580602
603+ void cleanupIdleConnections(long now) {
604+ for (HostConnectionPool pool : pools.values()) {
605+ pool.cleanupIdleConnections(now);
606+ }
607+ }
608+
581609 private static class State implements Session.State {
582610
583611 private final SessionManager session;
584612 private final List<Host> connectedHosts;
585613 private final int[] openConnections;
614+ private final int[] trashedConnections;
586615 private final int[] inFlightQueries;
587616
588617 private State(SessionManager session) {
@@ -590,6 +619,7 @@
590619 this.connectedHosts = ImmutableList.copyOf(session.pools.keySet());
591620
592621 this.openConnections = new int[connectedHosts.size()];
622+ this.trashedConnections = new int[connectedHosts.size()];
593623 this.inFlightQueries = new int[connectedHosts.size()];
594624
595625 int i = 0;
@@ -600,12 +630,14 @@
600630 // connections will be slightly weird, but it's unlikely enough that we don't bother avoiding.
601631 if (p == null) {
602632 openConnections[i] = 0;
633+ trashedConnections[i] = 0;
603634 inFlightQueries[i] = 0;
604635 continue;
605636 }
606637
607638 openConnections[i] = p.opened();
608- inFlightQueries[i] = p.inFlightQueriesCount();
639+ trashedConnections[i] = p.inFlightQueriesCount();
640+ inFlightQueries[i] = p.trashed();
609641 i++;
610642 }
611643 }
@@ -636,6 +668,11 @@
636668 return i < 0 ? 0 : openConnections[i];
637669 }
638670
671+ public int getTrashedConnections(Host host) {
672+ int i = getIdx(host);
673+ return i < 0 ? 0 : trashedConnections[i];
674+ }
675+
639676 public int getInFlightQueries(Host host) {
640677 int i = getIdx(host);
641678 return i < 0 ? 0 : inFlightQueries[i];
modified driver-core/src/main/java/com/datastax/driver/core/SimpleJSONParser.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +79 −31
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@
2020 import java.util.List;
2121 import java.util.Set;
2222 import java.util.concurrent.CopyOnWriteArraySet;
23+import java.util.concurrent.Executor;
2324 import java.util.concurrent.TimeUnit;
2425 import java.util.concurrent.TimeoutException;
2526 import java.util.concurrent.atomic.AtomicBoolean;
@@ -28,11 +29,16 @@
2829 import java.util.concurrent.locks.Lock;
2930 import java.util.concurrent.locks.ReentrantLock;
3031
31-import com.google.common.util.concurrent.MoreExecutors;
32+import com.google.common.util.concurrent.*;
3233 import org.slf4j.Logger;
3334 import org.slf4j.LoggerFactory;
3435
3536 import com.datastax.driver.core.exceptions.AuthenticationException;
37+import com.datastax.driver.core.utils.MoreFutures;
38+
39+import static com.datastax.driver.core.Connection.State.GONE;
40+import static com.datastax.driver.core.Connection.State.OPEN;
41+import static com.datastax.driver.core.Connection.State.TRASHED;
3642
3743 /**
3844 * A connection pool with a a single connection.
@@ -48,7 +54,7 @@
4854 // following threshold, we just replace the connection by a new one.
4955 private static final int MIN_AVAILABLE_STREAMS = 32768 * 3 / 4;
5056
51- volatile AtomicReference<PooledConnection> connectionRef = new AtomicReference<PooledConnection>();
57+ volatile AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
5258 private final AtomicBoolean open = new AtomicBoolean();
5359 private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
5460
@@ -60,7 +66,7 @@
6066
6167 private final AtomicBoolean scheduledForCreation = new AtomicBoolean();
6268
63- public SingleConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
69+ public SingleConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
6470 super(host, hostDistance, manager);
6571
6672 this.newConnectionTask = new Runnable() {
@@ -70,18 +76,47 @@
7076 scheduledForCreation.set(false);
7177 }
7278 };
79+ }
7380
74- // Create initial core connections
75- try {
76- connectionRef.set(manager.connectionFactory().open(this));
77- } catch (InterruptedException e) {
78- Thread.currentThread().interrupt();
79- // If asked to interrupt, we can skip opening core connections, the pool will still work.
80- // But we ignore otherwise cause I'm not sure we can do much better currently.
81+ @Override
82+ ListenableFuture<Void> initAsync(Connection reusedConnection) {
83+ final Connection connection;
84+ ListenableFuture<Void> connectionFuture;
85+ if (reusedConnection != null && reusedConnection.setPool(this)) {
86+ connection = reusedConnection;
87+ connectionFuture = MoreFutures.VOID_SUCCESS;
88+ } else {
89+ connection = manager.connectionFactory().newConnection(this);
90+ connectionFuture = connection.initAsync();
8191 }
82- this.open.set(true);
8392
84- logger.trace("Created connection pool to host {}", host);
93+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
94+
95+ final SettableFuture<Void> initFuture = SettableFuture.create();
96+ Futures.addCallback(connectionFuture, new FutureCallback<Void>() {
97+ @Override
98+ public void onSuccess(Void result) {
99+ connectionRef.set(connection);
100+ open.set(true);
101+ if (isClosed()) {
102+ initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
103+ // we're not sure if closeAsync() saw the connection, so ensure it gets closed
104+ connection.closeAsync().force();
105+ } else {
106+ logger.trace("Created connection pool to host {}", host);
107+ phase = Phase.READY;
108+ initFuture.set(null);
109+ }
110+ }
111+
112+ @Override
113+ public void onFailure(Throwable t) {
114+ phase = Phase.INIT_FAILED;
115+ initFuture.setException(t);
116+ }
117+ }, initExecutor);
118+
119+ return initFuture;
85120 }
86121
87122 private PoolingOptions options() {
@@ -89,13 +124,16 @@
89124 }
90125
91126 @Override
92- public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
93- if (isClosed())
127+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
128+ if (phase == Phase.INITIALIZING)
129+ throw new ConnectionException(host.getSocketAddress(), "Pool is initializing.");
130+
131+ if (phase != Phase.READY)
94132 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
95133 // That being said, maybe having a specific exception could be cleaner.
96- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
134+ throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
97135
98- PooledConnection connection = connectionRef.get();
136+ Connection connection = connectionRef.get();
99137 if (connection == null) {
100138 if (scheduledForCreation.compareAndSet(false, true))
101139 manager.blockingExecutor().submit(newConnectionTask);
@@ -155,7 +193,7 @@
155193 }
156194 }
157195
158- private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
196+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
159197 if (timeout == 0)
160198 throw new TimeoutException();
161199
@@ -173,7 +211,7 @@
173211 if (isClosed())
174212 throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
175213
176- PooledConnection connection = connectionRef.get();
214+ Connection connection = connectionRef.get();
177215 // If we race with shutdown, connection could be null. In that case we just loop and we'll throw on the next
178216 // iteration anyway
179217 if (connection != null) {
@@ -196,7 +234,7 @@
196234 }
197235
198236 @Override
199- public void returnConnection(PooledConnection connection) {
237+ public void returnConnection(Connection connection) {
200238 if (isClosed()) {
201239 close(connection);
202240 return;
@@ -224,14 +262,14 @@
224262
225263 // Trash the connection and create a new one, but we don't call trashConnection
226264 // directly because we want to make sure the connection is always trashed.
227- private void replaceConnection(PooledConnection connection) {
228- if (connection.markForTrash.compareAndSet(false, true))
265+ private void replaceConnection(Connection connection) {
266+ if (!connection.state.compareAndSet(OPEN, TRASHED))
229267 open.set(false);
230268 maybeSpawnNewConnection();
231269 doTrashConnection(connection);
232270 }
233271
234- private void doTrashConnection(PooledConnection connection) {
272+ private void doTrashConnection(Connection connection) {
235273 trash.add(connection);
236274 connectionRef.compareAndSet(connection, null);
237275
@@ -243,7 +281,7 @@
243281 if (!open.compareAndSet(false, true))
244282 return false;
245283
246- if (isClosed()) {
284+ if (phase != Phase.READY) {
247285 open.set(false);
248286 return false;
249287 }
@@ -288,8 +326,8 @@
288326 }
289327
290328 @Override
291- public void replaceDefunctConnection(final PooledConnection connection) {
292- if (connection.markForTrash.compareAndSet(false, true))
329+ public void replaceDefunctConnection(final Connection connection) {
330+ if (connection.state.compareAndSet(OPEN, GONE))
293331 open.set(false);
294332 connectionRef.compareAndSet(connection, null);
295333 connection.closeAsync();
@@ -301,28 +339,33 @@
301339 });
302340 }
303341
342+ @Override
343+ void cleanupIdleConnections(long now) {
344+ }
345+
304346 private void close(final Connection connection) {
305347 connection.closeAsync();
306348 }
307349
308350 protected CloseFuture makeCloseFuture() {
351+ phase = Phase.CLOSING;
352+
309353 // Wake up all threads that wait
310354 signalAllAvailableConnection();
311355
312- CloseFuture future = new CloseFuture.Forwarding(discardConnection());
313- return future;
356+ return new CloseFuture.Forwarding(discardConnection());
314357 }
315358
316359 private List<CloseFuture> discardConnection() {
317360
318361 List<CloseFuture> futures = new ArrayList<CloseFuture>();
319362
320- final PooledConnection connection = connectionRef.get();
363+ final Connection connection = connectionRef.get();
321364 if (connection != null) {
322365 CloseFuture future = connection.closeAsync();
323366 future.addListener(new Runnable() {
324367 public void run() {
325- if (connection.markForTrash.compareAndSet(false, true))
368+ if (connection.state.compareAndSet(OPEN, GONE))
326369 open.set(false);
327370 }
328371 }, MoreExecutors.sameThreadExecutor());
@@ -346,9 +389,14 @@
346389 return open.get() ? 1 : 0;
347390 }
348391
392+ @Override
393+ int trashed() {
394+ return trash.size();
395+ }
396+
349397 @Override
350398 public int inFlightQueriesCount() {
351- PooledConnection connection = connectionRef.get();
399+ Connection connection = connectionRef.get();
352400 return connection == null ? 0 : connection.inFlight.get();
353401 }
354402 }
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +107 −2
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@
4545 private volatile Boolean keepAlive;
4646 private volatile Boolean reuseAddress;
4747 private volatile Integer soLinger;
48- private volatile Boolean tcpNoDelay;
48+ private volatile Boolean tcpNoDelay = Boolean.TRUE;
4949 private volatile Integer receiveBufferSize;
5050 private volatile Integer sendBufferSize;
5151
@@ -131,55 +131,160 @@
131131 return this;
132132 }
133133
134+ /**
135+ * Returns whether TCP keepalive is enabled.
136+ *
137+ * @return the value of the option, or {@code null} if it is not set.
138+ * @see #setKeepAlive(boolean)
139+ */
134140 public Boolean getKeepAlive() {
135141 return keepAlive;
136142 }
137143
144+ /**
145+ * Sets whether to enable TCP keepalive.
146+ * <p>
147+ * By default, this option is not set by the driver. The actual value will be the default
148+ * from the underlying Netty transport (Java NIO or native epoll).
149+ *
150+ * @param keepAlive whether to enable or disable the option.
151+ * @return this {@code SocketOptions}.
152+ *
153+ * @see java.net.SocketOptions#TCP_NODELAY
154+ */
138155 public SocketOptions setKeepAlive(boolean keepAlive) {
139156 this.keepAlive = keepAlive;
140157 return this;
141158 }
142159
160+ /**
161+ * Returns whether reuse-address is enabled.
162+ *
163+ * @return the value of the option, or {@code null} if it is not set.
164+ * @see #setReuseAddress(boolean)
165+ */
143166 public Boolean getReuseAddress() {
144167 return reuseAddress;
145168 }
146169
170+ /**
171+ * Sets whether to enable reuse-address.
172+ * <p>
173+ * By default, this option is not set by the driver. The actual value will be the default
174+ * from the underlying Netty transport (Java NIO or native epoll).
175+ *
176+ * @param reuseAddress whether to enable or disable the option.
177+ * @return this {@code SocketOptions}.
178+ *
179+ * @see java.net.SocketOptions#SO_REUSEADDR
180+ */
147181 public SocketOptions setReuseAddress(boolean reuseAddress) {
148182 this.reuseAddress = reuseAddress;
149183 return this;
150184 }
151185
186+ /**
187+ * Returns the linger-on-close timeout.
188+ *
189+ * @return the value of the option, or {@code null} if it is not set.
190+ *
191+ * @see #setSoLinger(int)
192+ */
152193 public Integer getSoLinger() {
153194 return soLinger;
154195 }
155196
197+ /**
198+ * Sets the linger-on-close timeout.
199+ * <p>
200+ * By default, this option is not set by the driver. The actual value will be the default
201+ * from the underlying Netty transport (Java NIO or native epoll).
202+
203+ * @param soLinger the new value.
204+ * @return this {@code SocketOptions}.
205+ *
206+ * @see java.net.SocketOptions#SO_LINGER
207+ */
156208 public SocketOptions setSoLinger(int soLinger) {
157209 this.soLinger = soLinger;
158210 return this;
159211 }
160212
213+ /**
214+ * Returns whether Nagle's algorithm is disabled.
215+ *
216+ * @return the value of the option ({@code true} means Nagle is disabled), or {@code null} if it is not set.
217+ *
218+ * @see #setTcpNoDelay(boolean)
219+ */
161220 public Boolean getTcpNoDelay() {
162221 return tcpNoDelay;
163222 }
164223
224+ /**
225+ * Sets whether to disable Nagle's algorithm.
226+ * <p>
227+ * By default, this option is set to {@code true} (Nagle disabled).
228+ *
229+ * @param tcpNoDelay whether to enable or disable the option.
230+ * @return this {@code SocketOptions}.
231+ *
232+ * @see java.net.SocketOptions#TCP_NODELAY
233+ */
165234 public SocketOptions setTcpNoDelay(boolean tcpNoDelay) {
166235 this.tcpNoDelay = tcpNoDelay;
167236 return this;
168237 }
169238
239+ /**
240+ * Returns the hint to the size of the underlying buffers for incoming network I/O.
241+ *
242+ * @return the value of the option, or {@code null} if it is not set.
243+ *
244+ * @see #setReceiveBufferSize(int)
245+ */
170246 public Integer getReceiveBufferSize() {
171247 return receiveBufferSize;
172248 }
173249
250+ /**
251+ * Sets a hint to the size of the underlying buffers for incoming network I/O.
252+ * <p>
253+ * By default, this option is not set by the driver. The actual value will be the default
254+ * from the underlying Netty transport (Java NIO or native epoll).
255+ *
256+ * @param receiveBufferSize the new value.
257+ * @return this {@code SocketOptions}.
258+ *
259+ * @see java.net.SocketOptions#SO_RCVBUF
260+ */
174261 public SocketOptions setReceiveBufferSize(int receiveBufferSize) {
175262 this.receiveBufferSize = receiveBufferSize;
176263 return this;
177264 }
178265
266+ /**
267+ * Returns the hint to the size of the underlying buffers for outgoing network I/O.
268+ *
269+ * @return the value of the option, or {@code null} if it is not set.
270+ *
271+ * @see #setSendBufferSize(int)
272+ */
179273 public Integer getSendBufferSize() {
180274 return sendBufferSize;
181275 }
182276
277+ /**
278+ * Sets a hint to the size of the underlying buffers for outgoing network I/O.
279+ * <p>
280+ * By default, this option is not set by the driver. The actual value will be the default
281+ * from the underlying Netty transport (Java NIO or native epoll).
282+ *
283+ * @param sendBufferSize the new value.
284+ * @return this {@code SocketOptions}.
285+ *
286+ * @see java.net.SocketOptions#SO_SNDBUF
287+ */
183288 public SocketOptions setSendBufferSize(int sendBufferSize) {
184289 this.sendBufferSize = sendBufferSize;
185290 return this;
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +125 −6
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
1717
1818 import java.nio.ByteBuffer;
1919
20+import com.datastax.driver.core.exceptions.PagingStateException;
2021 import com.datastax.driver.core.policies.RetryPolicy;
22+import com.datastax.driver.core.querybuilder.BuiltStatement;
2123
2224 /**
2325 * An executable query.
@@ -32,10 +34,14 @@
3234 // used when preparing a statement and for other internal queries. Do not expose publicly.
3335 static final Statement DEFAULT = new Statement() {
3436 @Override
35- public ByteBuffer getRoutingKey() { return null; }
37+ public ByteBuffer getRoutingKey() {
38+ return null;
39+ }
3640
3741 @Override
38- public String getKeyspace() { return null; }
42+ public String getKeyspace() {
43+ return null;
44+ }
3945 };
4046
4147 private volatile ConsistencyLevel consistency;
@@ -43,11 +49,13 @@
4349 private volatile boolean traceQuery;
4450 private volatile int fetchSize;
4551 private volatile long defaultTimestamp = Long.MIN_VALUE;
46-
4752 private volatile RetryPolicy retryPolicy;
53+ private volatile ByteBuffer pagingState;
54+ protected volatile Boolean idempotent;
4855
4956 // We don't want to expose the constructor, because the code relies on this being only sub-classed by RegularStatement, BoundStatement and BatchStatement
50- Statement() {}
57+ Statement() {
58+ }
5159
5260 /**
5361 * Sets the consistency level for the query.
@@ -293,4 +301,115 @@
293301 public long getDefaultTimestamp() {
294302 return defaultTimestamp;
295303 }
296-}
304+
305+ /**
306+ * Sets the paging state.
307+ * <p>
308+ * This will cause the next execution of this statement to fetch results from a given
309+ * page, rather than restarting from the beginning.
310+ * <p>
311+ * You get the paging state from a previous execution of the statement. This is typically
312+ * used to iterate in a "stateless" manner (e.g. across HTTP requests):
313+ * <pre>
314+ * {@code
315+ * Statement st = new SimpleStatement("your query");
316+ * ResultSet rs = session.execute(st.setFetchSize(20));
317+ * int available = rs.getAvailableWithoutFetching();
318+ * for (int i = 0; i < available; i++) {
319+ * Row row = rs.one();
320+ * // Do something with row (e.g. display it to the user...)
321+ * }
322+ * // Get state and serialize as string or byte[] to store it for the next execution
323+ * // (e.g. pass it as a parameter in the "next page" URI)
324+ * PagingState pagingState = rs.getExecutionInfo().getPagingState();
325+ * String savedState = pagingState.toString();
326+ *
327+ * // Next execution:
328+ * // Get serialized state back (e.g. get URI parameter)
329+ * String savedState = ...
330+ * Statement st = new SimpleStatement("your query");
331+ * st.setPagingState(PagingState.fromString(savedState));
332+ * ResultSet rs = session.execute(st.setFetchSize(20));
333+ * int available = rs.getAvailableWithoutFetching();
334+ * for (int i = 0; i < available; i++) {
335+ * ...
336+ * }
337+ * }
338+ * </pre>
339+ * <p>
340+ * Note that the paging state can only be reused between perfectly identical statements
341+ * (same query string, same bound parameters). Altering the contents of the paging state
342+ * or trying to set it on a different statement will cause this method to fail.
343+ *
344+ * @param pagingState the paging state to set, or {@code null} to remove any state that was
345+ * previously set on this statement.
346+ * @return this {@code Statement} object.
347+ *
348+ * @throws PagingStateException if the paging state does not match this statement.
349+ */
350+ public Statement setPagingState(PagingState pagingState) {
351+ if (this instanceof BatchStatement) {
352+ throw new UnsupportedOperationException("Cannot set the paging state on a batch statement");
353+ } else {
354+ if (pagingState == null) {
355+ this.pagingState = null;
356+ } else if (pagingState.matches(this)) {
357+ this.pagingState = pagingState.getRawState();
358+ } else {
359+ throw new PagingStateException("Paging state mismatch, "
360+ + "this means that either the paging state contents were altered, "
361+ + "or you're trying to apply it to a different statement");
362+ }
363+ }
364+ return this;
365+ }
366+
367+ ByteBuffer getPagingState() {
368+ return pagingState;
369+ }
370+
371+ /**
372+ * Sets whether this statement is idempotent.
373+ * <p>
374+ * See {@link #isIdempotent()} for more explanations about this property.
375+ *
376+ * @param idempotent the new value.
377+ * @return this {@code Statement} object.
378+ */
379+ public Statement setIdempotent(boolean idempotent) {
380+ this.idempotent = idempotent;
381+ return this;
382+ }
383+
384+ /**
385+ * Whether this statement is idempotent, i.e. whether it can be applied multiple times
386+ * without changing the result beyond the initial application.
387+ * <p>
388+ * Idempotence plays a role in {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}.
389+ * If a statement is <em>not idempotent</em>, the driver will not schedule speculative
390+ * executions for it.
391+ * <p>
392+ * Note that this method can return {@code null}, in which case the driver will default to
393+ * {@link QueryOptions#getDefaultIdempotence()}.
394+ * <p>
395+ * By default, this method returns {@code null} for all statements, except for
396+ * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
397+ * counters or prepends/appends to a list, the result will be {@code false}, otherwise it
398+ * will be {@code true}. In all cases, calling {@link #setIdempotent(boolean)} forces a
399+ * value that overrides every other mechanism.
400+ *
401+ * @return whether this statement is idempotent, or {@code null} to use
402+ * {@link QueryOptions#getDefaultIdempotence()}.
403+ */
404+ public Boolean isIdempotent() {
405+ return idempotent;
406+ }
407+
408+ boolean isIdempotentWithDefault(QueryOptions queryOptions) {
409+ Boolean myValue = this.isIdempotent();
410+ if (myValue != null)
411+ return myValue;
412+ else
413+ return queryOptions.getDefaultIdempotence();
414+ }
415+}
No newline at the end of the file
added driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java +152 −0
@@ -0,0 +1,152 @@
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.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.policies.LoadBalancingPolicy;
21+import com.datastax.driver.core.policies.RetryPolicy;
22+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
23+
24+/**
25+ * Base class for custom {@link Statement} implementations that wrap another statement.
26+ * <p>
27+ * This is intended for use with a custom {@link RetryPolicy}, {@link LoadBalancingPolicy} or
28+ * {@link SpeculativeExecutionPolicy}. The client code can wrap a statement to "mark" it, or
29+ * add information that will lead to special handling in the policy.
30+ * <p>
31+ * Example:
32+ * <pre>
33+ * {@code
34+ * // Define your own subclass
35+ * public class MyCustomStatement extends StatementWrapper {
36+ * public MyCustomStatement(Statement wrapped) {
37+ * super(wrapped);
38+ * }
39+ * }
40+ *
41+ * // In your load balancing policy, add a special case for that new type
42+ * public class MyLoadBalancingPolicy implements LoadBalancingPolicy {
43+ * public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
44+ * if (statement instanceof MyCustomStatement) {
45+ * // return specially crafted plan
46+ * } else {
47+ * // return default plan
48+ * }
49+ * }
50+ * }
51+ *
52+ * // The client wraps whenever it wants to trigger the special plan
53+ * Statement s = new SimpleStatement("...");
54+ * session.execute(s); // will use default plan
55+ * session.execute(new MyCustomStatement(s)); // will use special plan
56+ * }
57+ * </pre>
58+ */
59+public abstract class StatementWrapper extends Statement {
60+ private final Statement wrapped;
61+
62+ /**
63+ * Builds a new instance.
64+ *
65+ * @param wrapped the wrapped statement.
66+ */
67+ protected StatementWrapper(Statement wrapped) {
68+ this.wrapped = wrapped;
69+ }
70+
71+ Statement getWrappedStatement() {
72+ // Protect against multiple levels of wrapping (even though there is no practical reason for that)
73+ return (wrapped instanceof StatementWrapper)
74+ ? ((StatementWrapper)wrapped).getWrappedStatement()
75+ : wrapped;
76+ }
77+
78+ @Override
79+ public Statement setConsistencyLevel(ConsistencyLevel consistency) {
80+ return wrapped.setConsistencyLevel(consistency);
81+ }
82+
83+ @Override
84+ public Statement disableTracing() {
85+ return wrapped.disableTracing();
86+ }
87+
88+ @Override
89+ public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) {
90+ return wrapped.setSerialConsistencyLevel(serialConsistency);
91+ }
92+
93+ @Override
94+ public Statement enableTracing() {
95+ return wrapped.enableTracing();
96+ }
97+
98+ @Override
99+ public ByteBuffer getPagingState() {
100+ return wrapped.getPagingState();
101+ }
102+
103+ @Override
104+ public boolean isTracing() {
105+ return wrapped.isTracing();
106+ }
107+
108+ @Override
109+ public RetryPolicy getRetryPolicy() {
110+ return wrapped.getRetryPolicy();
111+ }
112+
113+ @Override
114+ public ByteBuffer getRoutingKey() {
115+ return wrapped.getRoutingKey();
116+ }
117+
118+ @Override
119+ public Statement setRetryPolicy(RetryPolicy policy) {
120+ return wrapped.setRetryPolicy(policy);
121+ }
122+
123+ @Override
124+ public ConsistencyLevel getConsistencyLevel() {
125+ return wrapped.getConsistencyLevel();
126+ }
127+
128+ @Override
129+ public Statement setPagingState(PagingState pagingState) {
130+ return wrapped.setPagingState(pagingState);
131+ }
132+
133+ @Override
134+ public ConsistencyLevel getSerialConsistencyLevel() {
135+ return wrapped.getSerialConsistencyLevel();
136+ }
137+
138+ @Override
139+ public String getKeyspace() {
140+ return wrapped.getKeyspace();
141+ }
142+
143+ @Override
144+ public int getFetchSize() {
145+ return wrapped.getFetchSize();
146+ }
147+
148+ @Override
149+ public Statement setFetchSize(int fetchSize) {
150+ return wrapped.setFetchSize(fetchSize);
151+ }
152+}
modified driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +31 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import org.slf4j.Logger;
@@ -26,4 +41,20 @@
2641 return defaultValue;
2742 }
2843 }
44+
45+ static boolean getBoolean(String key, boolean defaultValue) {
46+ String stringValue = System.getProperty(key);
47+ if (stringValue == null) {
48+ logger.debug("{} is undefined, using default value {}", key, defaultValue);
49+ return defaultValue;
50+ }
51+ try {
52+ boolean value = Boolean.parseBoolean(stringValue);
53+ logger.warn("{} is defined, using value {}", key, value);
54+ return value;
55+ } catch (NumberFormatException e) {
56+ logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue);
57+ return defaultValue;
58+ }
59+ }
2960 }
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/TokenRange.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/TransportException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/UnsupportedProtocolVersionException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/WriteType.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +59 −0
@@ -0,0 +1,59 @@
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.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/DriverException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java +2 −2
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -38,7 +38,7 @@
3838 }
3939
4040 @Override
41- public DriverException copy() {
41+ public DriverInternalError copy() {
4242 return new DriverInternalError(getMessage(), this);
4343 }
4444 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidTypeException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +59 −0
@@ -0,0 +1,59 @@
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.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/PagingStateException.java +30 −0
@@ -0,0 +1,30 @@
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.exceptions;
17+
18+public class PagingStateException extends DriverException {
19+
20+ private static final long serialVersionUID = 0;
21+
22+ public PagingStateException(String msg) {
23+ super(msg);
24+ }
25+
26+ public PagingStateException(String msg, Throwable cause) {
27+ super(msg, cause);
28+ }
29+
30+}
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryTimeoutException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryValidationException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/SyntaxError.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java +59 −0
@@ -0,0 +1,59 @@
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.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/exceptions/UnsupportedFeatureException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/package-info.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/package-info.java +2 −2
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -16,6 +16,6 @@
1616 /**
1717 * The main package for the DataStax Java driver for Cassandra.
1818 * <p>
19- * The main entry for this package is the {@code Cluster} class.
19+ * The main entry for this package is the {@link com.datastax.driver.core.Cluster} class.
2020 */
2121 package com.datastax.driver.core;
modified driver-core/src/main/java/com/datastax/driver/core/policies/AddressTranslater.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/ChainableLoadBalancingPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/CloseableAddressTranslater.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/ConstantReconnectionPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java +71 −0
@@ -0,0 +1,71 @@
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.base.Preconditions;
21+
22+import com.datastax.driver.core.Cluster;
23+import com.datastax.driver.core.Host;
24+import com.datastax.driver.core.Statement;
25+
26+/**
27+ * A {@link SpeculativeExecutionPolicy} that schedules a given number of speculative executions, separated by a fixed delay.
28+ */
29+public class ConstantSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
30+ private final int maxSpeculativeExecutions;
31+ private final long constantDelayMillis;
32+
33+ /**
34+ * Builds a new instance.
35+ *
36+ * @param constantDelayMillis the delay between each speculative execution. Must be strictly positive.
37+ * @param maxSpeculativeExecutions the number of speculative executions. Must be strictly positive.
38+ *
39+ * @throws IllegalArgumentException if one of the arguments does not respect the preconditions above.
40+ */
41+ public ConstantSpeculativeExecutionPolicy(final long constantDelayMillis, final int maxSpeculativeExecutions) {
42+ Preconditions.checkArgument(constantDelayMillis > 0,
43+ "delay must be strictly positive (was %d)", constantDelayMillis);
44+ Preconditions.checkArgument(maxSpeculativeExecutions > 0,
45+ "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
46+ this.constantDelayMillis = constantDelayMillis;
47+ this.maxSpeculativeExecutions = maxSpeculativeExecutions;
48+ }
49+
50+ @Override
51+ public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) {
52+ return new SpeculativeExecutionPlan() {
53+ private final AtomicInteger remaining = new AtomicInteger(maxSpeculativeExecutions);
54+
55+ @Override
56+ public long nextExecution(Host lastQueried) {
57+ return (remaining.getAndDecrement() > 0) ? constantDelayMillis : -1;
58+ }
59+ };
60+ }
61+
62+ @Override
63+ public void init(Cluster cluster) {
64+ // do nothing
65+ }
66+
67+ @Override
68+ public void close() {
69+ // do nothing
70+ }
71+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +20 −79
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -65,8 +65,6 @@
6565 @VisibleForTesting
6666 volatile String localDc;
6767
68- private final ConcurrentMap<String, CopyOnWriteArrayList<Host>> perDcSuspectedHosts = new ConcurrentHashMap<String, CopyOnWriteArrayList<Host>>();
69-
7068 private final int usedHostsPerRemoteDc;
7169 private final boolean dontHopForLocalCL;
7270
@@ -282,51 +280,23 @@
282280 private int idx = startIdx;
283281 private int remainingLocal = hosts.size();
284282
285- private Iterator<Host> localSuspected;
286-
287283 // For remote Dcs
288284 private Iterator<String> remoteDcs;
289285 private List<Host> currentDcHosts;
290286 private int currentDcRemaining;
291- private Iterator<Host> currentDcSuspected;
292287
293288 @Override
294289 protected Host computeNext() {
295- if (remainingLocal > 0) {
296- remainingLocal--;
297- int c = idx++ % hosts.size();
298- if (c < 0) {
299- c += hosts.size();
290+ while (true) {
291+ if (remainingLocal > 0) {
292+ remainingLocal--;
293+ int c = idx++ % hosts.size();
294+ if (c < 0) {
295+ c += hosts.size();
296+ }
297+ return hosts.get(c);
300298 }
301- return hosts.get(c);
302- }
303-
304- if (localSuspected == null) {
305- List<Host> l = perDcSuspectedHosts.get(localDc);
306- localSuspected = l == null ? Collections.<Host>emptySet().iterator() : l.iterator();
307- }
308-
309- while (localSuspected.hasNext()) {
310- Host h = localSuspected.next();
311- waitOnReconnection(h);
312- if (h.isUp())
313- return h;
314- }
315-
316- ConsistencyLevel cl = statement.getConsistencyLevel() == null
317- ? configuration.getQueryOptions().getConsistencyLevel()
318- : statement.getConsistencyLevel();
319-
320- if (dontHopForLocalCL && cl.isDCLocal())
321- return endOfData();
322-
323- if (remoteDcs == null) {
324- Set<String> copy = new HashSet<String>(perDcLiveHosts.keySet());
325- copy.remove(localDc);
326- remoteDcs = copy.iterator();
327- }
328299
329- while (true) {
330300 if (currentDcHosts != null && currentDcRemaining > 0) {
331301 currentDcRemaining--;
332302 int c = idx++ % currentDcHosts.size();
@@ -336,13 +306,17 @@
336306 return currentDcHosts.get(c);
337307 }
338308
339- if (currentDcSuspected != null) {
340- while (currentDcSuspected.hasNext()) {
341- Host h = currentDcSuspected.next();
342- waitOnReconnection(h);
343- if (h.isUp())
344- return h;
345- }
309+ ConsistencyLevel cl = statement.getConsistencyLevel() == null
310+ ? configuration.getQueryOptions().getConsistencyLevel()
311+ : statement.getConsistencyLevel();
312+
313+ if (dontHopForLocalCL && cl.isDCLocal())
314+ return endOfData();
315+
316+ if (remoteDcs == null) {
317+ Set<String> copy = new HashSet<String>(perDcLiveHosts.keySet());
318+ copy.remove(localDc);
319+ remoteDcs = copy.iterator();
346320 }
347321
348322 if (!remoteDcs.hasNext())
@@ -356,27 +330,12 @@
356330 currentDcHosts = dcHosts.subList(0, Math.min(dcHosts.size(), usedHostsPerRemoteDc));
357331 currentDcRemaining = currentDcHosts.size();
358332 }
359- List<Host> suspectedList = perDcSuspectedHosts.get(nextRemoteDc);
360- currentDcSuspected = suspectedList == null ? null : suspectedList.iterator();
361333 }
362334 return endOfData();
363335 }
364336 };
365337 }
366338
367- private void waitOnReconnection(Host h) {
368- try {
369- h.getInitialReconnectionAttemptFuture().get(configuration.getSocketOptions().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
370- } catch (InterruptedException e) {
371- Thread.currentThread().interrupt();
372- } catch (ExecutionException e) {
373- throw new AssertionError(e);
374- } catch (TimeoutException e) {
375- // Shouldn't really happen but isn't really a huge deal
376- logger.debug("Timeout while waiting on initial reconnection future for " + h, e);
377- }
378- }
379-
380339 @Override
381340 public void onUp(Host host) {
382341 String dc = dc(host);
@@ -396,24 +355,10 @@
396355 return;
397356 }
398357 dcHosts.addIfAbsent(host);
399-
400- CopyOnWriteArrayList<Host> dcSuspected = perDcSuspectedHosts.get(dc(host));
401- if (dcSuspected != null)
402- dcSuspected.remove(host);
403358 }
404359
405360 @Override
406361 public void onSuspected(Host host) {
407- String dc = dc(host);
408- CopyOnWriteArrayList<Host> dcSuspected = perDcSuspectedHosts.get(dc);
409- if (dcSuspected == null) {
410- CopyOnWriteArrayList<Host> newMap = new CopyOnWriteArrayList<Host>(Collections.singletonList(host));
411- dcSuspected = perDcSuspectedHosts.putIfAbsent(dc, newMap);
412- // If we've successfully put our new host, we're good, otherwise we've been beaten so continue
413- if (dcSuspected == null)
414- return;
415- }
416- dcSuspected.addIfAbsent(host);
417362 }
418363
419364 @Override
@@ -421,10 +366,6 @@
421366 CopyOnWriteArrayList<Host> dcHosts = perDcLiveHosts.get(dc(host));
422367 if (dcHosts != null)
423368 dcHosts.remove(host);
424-
425- CopyOnWriteArrayList<Host> dcSuspected = perDcSuspectedHosts.get(dc(host));
426- if (dcSuspected != null)
427- dcSuspected.remove(host);
428369 }
429370
430371 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslater.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +39 −10
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -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/main/java/com/datastax/driver/core/policies/LoadBalancingPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/main/java/com/datastax/driver/core/policies/NoSpeculativeExecutionPolicy.java +55 −0
@@ -0,0 +1,55 @@
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 com.datastax.driver.core.Cluster;
19+import com.datastax.driver.core.Host;
20+import com.datastax.driver.core.Statement;
21+
22+/**
23+ * A {@link SpeculativeExecutionPolicy} that never schedules speculative executions.
24+ */
25+public class NoSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
26+
27+ /** The single instance (this class is stateless). */
28+ public static final NoSpeculativeExecutionPolicy INSTANCE = new NoSpeculativeExecutionPolicy();
29+
30+ private static final SpeculativeExecutionPlan PLAN = new SpeculativeExecutionPlan() {
31+ @Override
32+ public long nextExecution(Host lastQueried) {
33+ return -1;
34+ }
35+ };
36+
37+ @Override
38+ public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) {
39+ return PLAN;
40+ }
41+
42+ private NoSpeculativeExecutionPolicy() {
43+ // do nothing
44+ }
45+
46+ @Override
47+ public void init(Cluster cluster) {
48+ // do nothing
49+ }
50+
51+ @Override
52+ public void close() {
53+ // do nothing
54+ }
55+}
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/main/java/com/datastax/driver/core/policies/Policies.java +34 −6
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -26,15 +26,17 @@
2626 private static final ReconnectionPolicy DEFAULT_RECONNECTION_POLICY = new ExponentialReconnectionPolicy(1000, 10 * 60 * 1000);
2727 private static final RetryPolicy DEFAULT_RETRY_POLICY = DefaultRetryPolicy.INSTANCE;
2828 private static final AddressTranslater DEFAULT_ADDRESS_TRANSLATER = new IdentityTranslater();
29+ private static final SpeculativeExecutionPolicy DEFAULT_SPECULATIVE_EXECUTION_POLICY = NoSpeculativeExecutionPolicy.INSTANCE;
2930
3031 private final LoadBalancingPolicy loadBalancingPolicy;
3132 private final ReconnectionPolicy reconnectionPolicy;
3233 private final RetryPolicy retryPolicy;
3334 private final AddressTranslater addressTranslater;
3435 private final TimestampGenerator timestampGenerator;
36+ private final SpeculativeExecutionPolicy speculativeExecutionPolicy;
3537
3638 public Policies() {
37- this(defaultLoadBalancingPolicy(), defaultReconnectionPolicy(), defaultRetryPolicy(), defaultAddressTranslater(), defaultTimestampGenerator());
39+ this(defaultLoadBalancingPolicy(), defaultReconnectionPolicy(), defaultRetryPolicy(), defaultAddressTranslater(), defaultTimestampGenerator(), defaultSpeculativeExecutionPolicy());
3840 }
3941
4042 /**
@@ -48,8 +50,9 @@
4850 */
4951 public Policies(LoadBalancingPolicy loadBalancingPolicy,
5052 ReconnectionPolicy reconnectionPolicy,
51- RetryPolicy retryPolicy) {
52- this(loadBalancingPolicy, reconnectionPolicy, retryPolicy, DEFAULT_ADDRESS_TRANSLATER, defaultTimestampGenerator());
53+ RetryPolicy retryPolicy,
54+ SpeculativeExecutionPolicy speculativeExecutionPolicy) {
55+ this(loadBalancingPolicy, reconnectionPolicy, retryPolicy, DEFAULT_ADDRESS_TRANSLATER, speculativeExecutionPolicy);
5356 }
5457
5558 /**
@@ -63,12 +66,14 @@
6366 public Policies(LoadBalancingPolicy loadBalancingPolicy,
6467 ReconnectionPolicy reconnectionPolicy,
6568 RetryPolicy retryPolicy,
66- AddressTranslater addressTranslater) {
69+ AddressTranslater addressTranslater,
70+ SpeculativeExecutionPolicy speculativeExecutionPolicy) {
6771 // NB: this constructor is provided for backward compatibility with 2.1.0
6872 this.loadBalancingPolicy = loadBalancingPolicy;
6973 this.reconnectionPolicy = reconnectionPolicy;
7074 this.retryPolicy = retryPolicy;
7175 this.addressTranslater = addressTranslater;
76+ this.speculativeExecutionPolicy = speculativeExecutionPolicy;
7277 this.timestampGenerator = defaultTimestampGenerator();
7378 }
7479
@@ -80,17 +85,20 @@
8085 * @param retryPolicy the retry policy to use.
8186 * @param addressTranslater the address translater to use.
8287 * @param timestampGenerator the timestamp generator to use.
88+ * @param speculativeExecutionPolicy the speculative execution policy to use.
8389 */
8490 public Policies(LoadBalancingPolicy loadBalancingPolicy,
8591 ReconnectionPolicy reconnectionPolicy,
8692 RetryPolicy retryPolicy,
8793 AddressTranslater addressTranslater,
88- TimestampGenerator timestampGenerator) {
94+ TimestampGenerator timestampGenerator,
95+ SpeculativeExecutionPolicy speculativeExecutionPolicy) {
8996 this.loadBalancingPolicy = loadBalancingPolicy;
9097 this.reconnectionPolicy = reconnectionPolicy;
9198 this.retryPolicy = retryPolicy;
9299 this.addressTranslater = addressTranslater;
93100 this.timestampGenerator = timestampGenerator;
101+ this.speculativeExecutionPolicy = speculativeExecutionPolicy;
94102 }
95103
96104 /**
@@ -156,6 +164,17 @@
156164 return ServerSideTimestampGenerator.INSTANCE;
157165 }
158166
167+ /**
168+ * The default speculative retry policy.
169+ * <p>
170+ * The default speculative retry policy is a {@link NoSpeculativeExecutionPolicy}.
171+ *
172+ * @return the default speculative retry policy.
173+ */
174+ public static SpeculativeExecutionPolicy defaultSpeculativeExecutionPolicy() {
175+ return DEFAULT_SPECULATIVE_EXECUTION_POLICY;
176+ }
177+
159178 /**
160179 * The load balancing policy in use.
161180 * <p>
@@ -207,4 +226,13 @@
207226 public TimestampGenerator getTimestampGenerator() {
208227 return timestampGenerator;
209228 }
229+
230+ /**
231+ * The speculative execution policy in use.
232+ *
233+ * @return the speculative execution policy in use.
234+ */
235+ public SpeculativeExecutionPolicy getSpeculativeExecutionPolicy() {
236+ return speculativeExecutionPolicy;
237+ }
210238 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java +2 −32
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -55,8 +55,6 @@
5555 private final CopyOnWriteArrayList<Host> liveHosts = new CopyOnWriteArrayList<Host>();
5656 private final AtomicInteger index = new AtomicInteger();
5757
58- private final CopyOnWriteArrayList<Host> suspectedHosts = new CopyOnWriteArrayList<Host>();
59-
6058 private volatile Configuration configuration;
6159 private volatile boolean hasLoggedLocalCLUse;
6260
@@ -132,23 +130,11 @@
132130
133131 private int idx = startIdx;
134132 private int remaining = hosts.size();
135- private Iterator<Host> suspected;
136133
137134 @Override
138135 protected Host computeNext() {
139- if (remaining <= 0) {
140-
141- if (suspected == null)
142- suspected = suspectedHosts.iterator();
143-
144- while (suspected.hasNext()) {
145- Host h = suspected.next();
146- waitOnReconnection(h);
147- if (h.isUp())
148- return h;
149- }
136+ if (remaining <= 0)
150137 return endOfData();
151- }
152138
153139 remaining--;
154140 int c = idx++ % hosts.size();
@@ -159,34 +145,18 @@
159145 };
160146 }
161147
162- private void waitOnReconnection(Host h) {
163- try {
164- h.getInitialReconnectionAttemptFuture().get(configuration.getSocketOptions().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
165- } catch (InterruptedException e) {
166- Thread.currentThread().interrupt();
167- } catch (ExecutionException e) {
168- throw new AssertionError(e);
169- } catch (TimeoutException e) {
170- // Shouldn't really happen but isn't really a huge deal
171- logger.debug("Timeout while waiting only host initial reconnection future", e);
172- }
173- }
174-
175148 @Override
176149 public void onUp(Host host) {
177150 liveHosts.addIfAbsent(host);
178- suspectedHosts.remove(host);
179151 }
180152
181153 @Override
182154 public void onSuspected(Host host) {
183- suspectedHosts.addIfAbsent(host);
184155 }
185156
186157 @Override
187158 public void onDown(Host host) {
188159 liveHosts.remove(host);
189- suspectedHosts.remove(host);
190160 }
191161
192162 @Override
added driver-core/src/main/java/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.java +72 −0
@@ -0,0 +1,72 @@
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 com.datastax.driver.core.Cluster;
19+import com.datastax.driver.core.Host;
20+import com.datastax.driver.core.Statement;
21+
22+/**
23+ * The policy that decides if the driver will send speculative queries to the next hosts when the current host takes too
24+ * long to respond.
25+ * <p>
26+ * Note that only idempotent statements will be speculatively retried, see
27+ * {@link com.datastax.driver.core.Statement#isIdempotent()} for more information.
28+ */
29+public interface SpeculativeExecutionPolicy {
30+ /**
31+ * Gets invoked at cluster startup.
32+ *
33+ * @param cluster the cluster that this policy is associated with.
34+ */
35+ void init(Cluster cluster);
36+
37+ /**
38+ * Returns the plan to use for a new query.
39+ *
40+ * @param loggedKeyspace the currently logged keyspace (the one set through either
41+ * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
42+ * the session on which this plan need to be built. This can be {@code null} if
43+ * the corresponding session has no keyspace logged in.
44+ * @param statement the query for which to build a plan.
45+ * @return the plan.
46+ */
47+ SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement);
48+
49+ /**
50+ * Gets invoked at cluster shutdown.
51+ *
52+ * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started.
53+ */
54+ void close();
55+
56+ /**
57+ * A plan that governs speculative executions for a given query.
58+ * <p>
59+ * Each time a host is queried, {@link #nextExecution(Host)} is invoked to determine if and when a speculative query to
60+ * the next host will be sent.
61+ */
62+ interface SpeculativeExecutionPlan {
63+ /**
64+ * Returns the time before the next speculative query.
65+ *
66+ * @param lastQueried the host that was just queried.
67+ * @return the time (in milliseconds) before a speculative query is sent to the next host. If zero or negative,
68+ * no speculative query will be sent.
69+ */
70+ long nextExecution(Host lastQueried);
71+ }
72+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/policies/package-info.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +40 −2
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -38,6 +38,8 @@
3838 return name;
3939 }
4040
41+ abstract boolean isIdempotent();
42+
4143 static class SetAssignment extends Assignment {
4244
4345 private final Object value;
@@ -58,6 +60,11 @@
5860 boolean containsBindMarker() {
5961 return Utils.containsBindMarker(value);
6062 }
63+
64+ @Override
65+ boolean isIdempotent() {
66+ return true;
67+ }
6168 }
6269
6370 static class CounterAssignment extends Assignment {
@@ -87,6 +94,11 @@
8794 boolean containsBindMarker() {
8895 return Utils.containsBindMarker(value);
8996 }
97+
98+ @Override
99+ boolean isIdempotent() {
100+ return false;
101+ }
90102 }
91103
92104 static class ListPrependAssignment extends Assignment {
@@ -110,6 +122,11 @@
110122 boolean containsBindMarker() {
111123 return Utils.containsBindMarker(value);
112124 }
125+
126+ @Override
127+ boolean isIdempotent() {
128+ return false;
129+ }
113130 }
114131
115132 static class ListSetIdxAssignment extends Assignment {
@@ -133,17 +150,28 @@
133150 boolean containsBindMarker() {
134151 return Utils.containsBindMarker(value);
135152 }
153+
154+ @Override
155+ boolean isIdempotent() {
156+ return true;
157+ }
136158 }
137159
138160 static class CollectionAssignment extends Assignment {
139161
140162 private final Object collection;
141163 private final boolean isAdd;
164+ private final boolean isIdempotent;
142165
143- CollectionAssignment(String name, Object collection, boolean isAdd) {
166+ CollectionAssignment(String name, Object collection, boolean isAdd, boolean isIdempotent) {
144167 super(name);
145168 this.collection = collection;
146169 this.isAdd = isAdd;
170+ this.isIdempotent = isIdempotent;
171+ }
172+
173+ CollectionAssignment(String name, Object collection, boolean isAdd) {
174+ this(name, collection, isAdd, true);
147175 }
148176
149177 @Override
@@ -157,6 +185,11 @@
157185 boolean containsBindMarker() {
158186 return Utils.containsBindMarker(collection);
159187 }
188+
189+ @Override
190+ public boolean isIdempotent() {
191+ return isIdempotent;
192+ }
160193 }
161194
162195 static class MapPutAssignment extends Assignment {
@@ -182,5 +215,10 @@
182215 boolean containsBindMarker() {
183216 return Utils.containsBindMarker(key) || Utils.containsBindMarker(value);
184217 }
218+
219+ @Override
220+ boolean isIdempotent() {
221+ return true;
222+ }
185223 }
186224 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +25 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -39,6 +39,7 @@
3939 private List<Object> values;
4040
4141 Boolean isCounterOp;
42+ boolean hasNonIdempotentOps;
4243
4344 // Whether the user has inputted bind markers. If that's the case, we never generate values as
4445 // it means the user meant for the statement to be prepared and we shouldn't add our own markers.
@@ -119,6 +120,14 @@
119120 this.isCounterOp = isCounterOp;
120121 }
121122
123+ boolean hasNonIdempotentOps() {
124+ return hasNonIdempotentOps;
125+ }
126+
127+ void setNonIdempotentOps() {
128+ hasNonIdempotentOps = true;
129+ }
130+
122131 void checkForBindMarkers(Object value) {
123132 dirty = true;
124133 if (Utils.containsBindMarker(value))
@@ -178,6 +187,16 @@
178187 return values != null;
179188 }
180189
190+ @Override
191+ public Boolean isIdempotent() {
192+ // If a value was forced with setIdempotent, it takes priority
193+ if (idempotent != null)
194+ return idempotent;
195+
196+ // Otherwise return the computed value
197+ return !hasNonIdempotentOps();
198+ }
199+
181200 @Override
182201 public String toString() {
183202 if (forceNoValues)
@@ -286,6 +305,11 @@
286305 return statement.isCounterOp();
287306 }
288307
308+ @Override
309+ boolean hasNonIdempotentOps() {
310+ return statement.hasNonIdempotentOps();
311+ }
312+
289313 @Override
290314 public RegularStatement setForceNoValues(boolean forceNoValues) {
291315 statement.setForceNoValues(forceNoValues);
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +4 −4
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -641,7 +641,7 @@
641641 */
642642 public static Assignment append(String name, Object value) {
643643 Object v = value instanceof BindMarker ? value : Collections.singletonList(value);
644- return new Assignment.CollectionAssignment(name, v, true);
644+ return new Assignment.CollectionAssignment(name, v, true, false);
645645 }
646646
647647 /**
@@ -654,7 +654,7 @@
654654 * @return the correspond assignment (to use in an update query)
655655 */
656656 public static Assignment appendAll(String name, List<?> list) {
657- return new Assignment.CollectionAssignment(name, list, true);
657+ return new Assignment.CollectionAssignment(name, list, true, false);
658658 }
659659
660660 /**
@@ -667,7 +667,7 @@
667667 * @return the correspond assignment (to use in an update query)
668668 */
669669 public static Assignment appendAll(String name, BindMarker list) {
670- return new Assignment.CollectionAssignment(name, list, true);
670+ return new Assignment.CollectionAssignment(name, list, true, false);
671671 }
672672
673673 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +3 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -175,6 +175,8 @@
175175 */
176176 public Assignments and(Assignment assignment) {
177177 statement.setCounterOp(assignment instanceof CounterAssignment);
178+ if (!assignment.isIdempotent())
179+ statement.setNonIdempotentOps();
178180 assignments.add(assignment);
179181 checkForBindMarkers(assignment);
180182 return this;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java +38 −3
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -100,6 +100,29 @@
100100 return toRawHexString(bytes, array, 2);
101101 }
102102
103+ /**
104+ * Converts a blob to its CQL hex string representation.
105+ * <p>
106+ * A CQL blob string representation consist of the hexadecimal
107+ * representation of the blob bytes.
108+ *
109+ * @param bytes the blob/bytes to convert to a string.
110+ * @return the CQL string representation of {@code bytes}. If {@code bytes}
111+ * is {@code null}, this method returns {@code null}.
112+ */
113+ public static String toRawHexString(ByteBuffer bytes) {
114+ if (bytes == null)
115+ return null;
116+
117+ if (bytes.remaining() == 0) {
118+ return "";
119+ }
120+
121+
122+ char[] array = new char[2 * (bytes.remaining())];
123+ return toRawHexString(bytes, array, 0);
124+ }
125+
103126 /**
104127 * Converts a blob to its CQL hex string representation.
105128 * <p>
@@ -165,7 +188,7 @@
165188 bytes.duplicate().get(array);
166189 return array;
167190 }
168-
191+
169192 private static String toRawHexString(ByteBuffer bytes, char[] array, int offset) {
170193 int size = bytes.remaining();
171194 int bytesOffset = bytes.position();
@@ -178,7 +201,19 @@
178201 return wrapCharArray(array);
179202 }
180203
181- static byte[] fromRawHexString(String str, int strOffset) {
204+ /**
205+ * Converts a CQL hex string representation into a byte array.
206+ * <p>
207+ * A CQL blob string representation consist of the hexadecimal
208+ * representation of the blob bytes.
209+ *
210+ * @param str the string converted in hex representation.
211+ * @param strOffset he offset for starting the string conversion
212+ *
213+ * @return the byte array which the String was representing.
214+ */
215+
216+ public static byte[] fromRawHexString(String str, int strOffset) {
182217 byte[] bytes = new byte[(str.length() - strOffset) / 2];
183218 for (int i = 0; i < bytes.length; i++) {
184219 byte halfByte1 = charToByte[str.charAt(strOffset + i * 2)];
added driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java +46 −0
@@ -0,0 +1,46 @@
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.utils;
17+
18+import com.google.common.util.concurrent.FutureCallback;
19+import com.google.common.util.concurrent.Futures;
20+import com.google.common.util.concurrent.ListenableFuture;
21+
22+/**
23+ * Helpers to work with Guava's {@link ListenableFuture}.
24+ */
25+public class MoreFutures {
26+ /**
27+ * An immediate successful {@code ListenableFuture<Void>}.
28+ */
29+ public static final ListenableFuture<Void> VOID_SUCCESS = Futures.immediateFuture(null);
30+
31+ /**
32+ * A {@link FutureCallback} that does nothing on failure.
33+ */
34+ public static abstract class SuccessCallback<V> implements FutureCallback<V> {
35+ @Override
36+ public void onFailure(Throwable t) { /* nothing */ }
37+ }
38+
39+ /**
40+ * A {@link FutureCallback} that does nothing on success.
41+ */
42+ public static abstract class FailureCallback<V> implements FutureCallback<V> {
43+ @Override
44+ public void onSuccess(V result) { /* nothing */ }
45+ }
46+}
modified driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/main/resources/com/datastax/driver/core/Driver.properties +16 −0
@@ -1,1 +1,17 @@
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+
117 driver.version=${project.version}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.net.InetSocketAddress;
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 /**
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Collection;
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +52 −47
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -28,9 +28,11 @@
2828
2929 import com.google.common.base.Joiner;
3030 import com.google.common.collect.ImmutableMap;
31+import com.google.common.collect.Maps;
3132 import com.google.common.io.ByteStreams;
3233 import com.google.common.io.Closer;
3334 import com.google.common.io.Files;
35+import org.apache.commons.exec.*;
3436 import org.slf4j.Logger;
3537 import org.slf4j.LoggerFactory;
3638 import org.testng.annotations.AfterClass;
@@ -71,6 +73,36 @@
7173
7274 private static final File DEFAULT_SERVER_KEYSTORE_FILE = createTempStore(DEFAULT_SERVER_KEYSTORE_PATH);
7375
76+ /**
77+ * The environment variables to use when invoking CCM. Inherits the current processes environment, but will also
78+ * prepend to the PATH variable the value of the 'ccm.path' property and set JAVA_HOME variable to the
79+ * 'ccm.java.home' variable.
80+ *
81+ * At times it is necessary to use a separate java install for CCM then what is being used for running tests.
82+ * For example, if you want to run tests with JDK 6 but against Cassandra 2.0, which requires JDK 7.
83+ */
84+ private static final Map<String,String> ENVIRONMENT_MAP;
85+
86+ static {
87+ // Inherit the current environment.
88+ Map<String,String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
89+ // If ccm.path is set, override the PATH variable with it.
90+ String ccmPath = System.getProperty("ccm.path");
91+ if(ccmPath != null) {
92+ String existingPath = envMap.get("PATH");
93+ if(existingPath == null) {
94+ existingPath = "";
95+ }
96+ envMap.put("PATH", ccmPath + ":" + existingPath);
97+ }
98+ // If ccm.java.home is set, override the JAVA_HOME variable with it.
99+ String ccmJavaHome = System.getProperty("ccm.java.home");
100+ if(ccmJavaHome != null) {
101+ envMap.put("JAVA_HOME", ccmJavaHome);
102+ }
103+ ENVIRONMENT_MAP = ImmutableMap.copyOf(envMap);
104+ }
105+
74106 static final File CASSANDRA_DIR;
75107 static final String CASSANDRA_VERSION;
76108
@@ -226,14 +258,6 @@
226258 execute("ccm node%d remove", n);
227259 }
228260
229- public void ring() {
230- ring(1);
231- }
232-
233- public void ring(int n) {
234- executeAndPrint("ccm node%d ring", n);
235- }
236-
237261 public void bootstrapNode(int n) {
238262 bootstrapNode(n, null);
239263 }
@@ -280,49 +304,30 @@
280304 try {
281305 String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
282306 logger.debug("Executing: " + fullCommand);
283- Process p = runtime.exec(fullCommand, null, CASSANDRA_DIR);
284- int retValue = p.waitFor();
285-
286- if (retValue != 0) {
287- BufferedReader outReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
288- BufferedReader errReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
289-
290- String line = outReader.readLine();
291- while (line != null) {
292- logger.info("out> " + line);
293- line = outReader.readLine();
307+ CommandLine cli = CommandLine.parse(fullCommand);
308+ Executor executor = new DefaultExecutor();
309+
310+ LogOutputStream outStream = new LogOutputStream() {
311+ @Override protected void processLine(String line, int logLevel) {
312+ logger.debug("ccmout> " + line);
294313 }
295- line = errReader.readLine();
296- while (line != null) {
297- logger.error("err> " + line);
298- line = errReader.readLine();
314+ };
315+ LogOutputStream errStream = new LogOutputStream() {
316+ @Override protected void processLine(String line, int logLevel) {
317+ logger.error("ccmerr> " + line);
299318 }
300- throw new RuntimeException();
301- }
302- } catch (IOException e) {
303- throw new RuntimeException(e);
304- } catch (InterruptedException e) {
305- throw new RuntimeException(e);
306- }
307- }
319+ };
308320
309- private void executeAndPrint(String command, Object... args) {
310- try {
311- String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
312- logger.debug("Executing: " + fullCommand);
313- Process p = runtime.exec(fullCommand, null, CASSANDRA_DIR);
314- int retValue = p.waitFor();
315-
316- BufferedReader outReaderOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
317- String line = outReaderOutput.readLine();
318- while (line != null) {
319- System.out.println(line);
320- line = outReaderOutput.readLine();
321+ ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
322+ executor.setStreamHandler(streamHandler);
323+
324+ int retValue = executor.execute(cli, ENVIRONMENT_MAP);
325+ if (retValue != 0) {
326+ logger.error("Non-zero exit code ({}) returned from executing ccm command: {}", retValue, fullCommand);
327+ throw new RuntimeException();
321328 }
322329 } catch (IOException e) {
323330 throw new RuntimeException(e);
324- } catch (InterruptedException e) {
325- throw new RuntimeException(e);
326331 }
327332 }
328333
@@ -484,7 +489,7 @@
484489
485490 ports = new int[5];
486491 for (int i = 0; i < 5; i++) {
487- ports[i] = TestUtils.findAvailablePort(10000 + i);
492+ ports[i] = TestUtils.findAvailablePort(11000 + i);
488493 }
489494
490495 ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4]);
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/CassandraTypeParserTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Iterator;
added driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +53 −0
@@ -0,0 +1,53 @@
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.Collection;
19+
20+import com.google.common.collect.Lists;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+public class ClusterDelegateTest extends CCMBridge.PerClassSingleNodeCluster {
26+ @Override
27+ protected Collection<String> getTableDefinitions() {
28+ return Lists.newArrayList();
29+ }
30+
31+ @Test(groups = "short")
32+ public void should_allow_subclass_to_delegate_to_other_instance() {
33+ SimpleDelegatingCluster delegatingCluster = new SimpleDelegatingCluster(cluster);
34+
35+ ResultSet rs = delegatingCluster.connect().execute("select * from system.local");
36+
37+ assertThat(rs.all()).hasSize(1);
38+ }
39+
40+ static class SimpleDelegatingCluster extends DelegatingCluster {
41+
42+ private final Cluster delegate;
43+
44+ public SimpleDelegatingCluster(Cluster delegate) {
45+ this.delegate = delegate;
46+ }
47+
48+ @Override
49+ protected Cluster delegate() {
50+ return delegate;
51+ }
52+ }
53+}
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +52 −16
@@ -1,29 +1,40 @@
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+ */
116 package com.datastax.driver.core;
217
3-import java.net.InetAddress;
4-import java.util.List;
5-import java.util.concurrent.TimeUnit;
6-
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
20+import com.datastax.driver.core.querybuilder.Insert;
21+import com.datastax.driver.core.utils.UUIDs;
722 import com.google.common.collect.Lists;
8-import org.mockito.Mockito;
923 import org.slf4j.Logger;
1024 import org.slf4j.LoggerFactory;
1125 import org.testng.annotations.Test;
1226
13-import static org.assertj.core.api.Assertions.assertThat;
14-import static org.assertj.core.api.Assertions.fail;
15-import static org.mockito.Mockito.atMost;
16-import static org.mockito.Mockito.spy;
17-import static org.mockito.Mockito.times;
18-import static org.mockito.Mockito.verify;
19-
20-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
21-import com.datastax.driver.core.querybuilder.Insert;
22-import com.datastax.driver.core.utils.UUIDs;
27+import java.net.InetAddress;
28+import java.net.InetSocketAddress;
29+import java.util.Collections;
30+import java.util.List;
31+import java.util.concurrent.TimeUnit;
32+import java.util.concurrent.TimeoutException;
2333
2434 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
25-
2635 import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36+import static org.assertj.core.api.Assertions.fail;
37+import static org.mockito.Mockito.*;
2738
2839 public class ClusterInitTest {
2940 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -95,6 +106,31 @@
95106 }
96107 }
97108
109+ /**
110+ * <p>
111+ * Validates that a Cluster that was never able to successfully establish connection a session can be closed
112+ * properly.
113+ *
114+ * @test_category connection
115+ * @expected_result Cluster closes within 1 second.
116+ */
117+ @Test(groups="unit")
118+ public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
119+ Cluster cluster = Cluster.builder()
120+ .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
121+ .build();
122+ try {
123+ cluster.connect();
124+ fail("Should not have been able to connect.");
125+ } catch(NoHostAvailableException e) {} // Expected.
126+ CloseFuture closeFuture = cluster.closeAsync();
127+ try {
128+ closeFuture.get(1, TimeUnit.SECONDS);
129+ } catch(TimeoutException e) {
130+ fail("Close Future did not complete quickly.");
131+ }
132+ }
133+
98134 private void fakePeerRowsInNode1() {
99135 Cluster cluster = null;
100136 try {
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +69 −34
@@ -1,16 +1,33 @@
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+ */
116 package com.datastax.driver.core;
217
18+import com.datastax.driver.core.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetSocketAddress;
325 import java.util.ArrayList;
426 import java.util.Collection;
527 import java.util.Collections;
628 import java.util.List;
729 import java.util.concurrent.*;
830
9-import com.google.common.util.concurrent.Uninterruptibles;
10-import org.slf4j.Logger;
11-import org.slf4j.LoggerFactory;
12-import org.testng.annotations.Test;
13-
1431 import static org.testng.Assert.assertEquals;
1532
1633 public class ClusterStressTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -35,19 +52,22 @@
3552 for (int i = 1; i < numberOfIterations; i++) {
3653 logger.info("On iteration {}/{}.", i, numberOfIterations);
3754 logger.info("Creating {} clusters", numberOfClusters);
38- List<Cluster> clusters = waitForCreates(createClustersConcurrently(numberOfClusters));
39- waitForCloses(closeClustersConcurrently(clusters));
55+ List<CreateClusterAndCheckConnections> actions =
56+ waitForCreates(createClustersConcurrently(numberOfClusters));
57+ waitForCloses(closeClustersConcurrently(actions));
4058 logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size());
4159 }
4260 }
4361
44- private List<Future<Cluster>> createClustersConcurrently(int numberOfClusters) {
62+ private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters) {
4563 final CountDownLatch countDownLatch = new CountDownLatch(1);
4664 return createClustersConcurrently(numberOfClusters, countDownLatch);
4765 }
4866
49- private List<Future<Cluster>> createClustersConcurrently(int numberOfClusters, CountDownLatch countDownLatch) {
50- List<Future<Cluster>> clusterFutures = new ArrayList<Future<Cluster>>(numberOfClusters);
67+ private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters,
68+ CountDownLatch countDownLatch) {
69+ List<Future<CreateClusterAndCheckConnections>> clusterFutures =
70+ Lists.newArrayListWithCapacity(numberOfClusters);
5171 for (int i = 0; i < numberOfClusters; i++) {
5272 clusterFutures.add(executorService.submit(new CreateClusterAndCheckConnections(countDownLatch)));
5373 }
@@ -55,28 +75,31 @@
5575 return clusterFutures;
5676 }
5777
58- private List<Future<Void>> closeClustersConcurrently(List<Cluster> clusters) {
78+ private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions) {
5979 final CountDownLatch countDownLatch = new CountDownLatch(1);
60- return closeClustersConcurrently(clusters, countDownLatch);
80+ return closeClustersConcurrently(actions, countDownLatch);
6181 }
6282
63- private List<Future<Void>> closeClustersConcurrently(List<Cluster> clusters, CountDownLatch startSignal) {
64- List<Future<Void>> closeFutures = new ArrayList<Future<Void>>(clusters.size());
65- for (Cluster cluster : clusters) {
66- closeFutures.add(executorService.submit(new CloseCluster(cluster, startSignal)));
83+ private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions,
84+ CountDownLatch startSignal) {
85+ List<Future<Void>> closeFutures = Lists.newArrayListWithCapacity(actions.size());
86+ for (CreateClusterAndCheckConnections action : actions) {
87+ closeFutures.add(executorService.submit(new CloseCluster(action.cluster, action.channelMonitor,
88+ startSignal)));
6789 }
6890 startSignal.countDown();
6991 return closeFutures;
7092 }
7193
72- private List<Cluster> waitForCreates(List<Future<Cluster>> futures) {
73- List<Cluster> clusters = new ArrayList<Cluster>(futures.size());
94+ private List<CreateClusterAndCheckConnections> waitForCreates(
95+ List<Future<CreateClusterAndCheckConnections>> futures) {
96+ List<CreateClusterAndCheckConnections> actions = Lists.newArrayListWithCapacity(futures.size());
7497 // If an error occurs, we will abort the test, but we still want to close all the clusters
7598 // that were opened successfully, so we iterate over the whole list no matter what.
7699 AssertionError error = null;
77- for (Future<Cluster> future : futures) {
100+ for (Future<CreateClusterAndCheckConnections> future : futures) {
78101 try {
79- clusters.add(future.get());
102+ actions.add(future.get());
80103 } catch (InterruptedException e) {
81104 Thread.currentThread().interrupt();
82105 if (error == null)
@@ -92,11 +115,11 @@
92115 }
93116 }
94117 if (error != null) {
95- for (Cluster cluster : clusters)
96- cluster.close();
118+ for (CreateClusterAndCheckConnections action : actions)
119+ action.cluster.close();
97120 throw error;
98121 } else
99- return clusters;
122+ return actions;
100123 }
101124
102125 private List<Void> waitForCloses(List<Future<Void>> futures) {
@@ -125,51 +148,62 @@
125148 return result;
126149 }
127150
128- private static class CreateClusterAndCheckConnections implements Callable<Cluster> {
151+ private static class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
129152 private final CountDownLatch startSignal;
153+ private final Cluster cluster;
154+ private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
155+ private final List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
130156
131157 CreateClusterAndCheckConnections(CountDownLatch startSignal) {
132158 this.startSignal = startSignal;
159+ this.cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
160+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
161+ .withNettyOptions(channelMonitor.nettyOptions()).build();
133162 }
134163
135164 @Override
136- public Cluster call() throws Exception {
165+ public CreateClusterAndCheckConnections call() throws Exception {
137166 startSignal.await();
138167
139- Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress))
140- .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)).build();
141-
142168 try {
143- // The cluster has not been initialized yet, therefore the control connection is not opened
169+ // There should be 1 control connection after initializing.
170+ cluster.init();
144171 assertEquals(cluster.manager.sessions.size(), 0);
145- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 0);
172+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
173+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
146174
147175 // The first session initializes the cluster and its control connection
148176 Session session = cluster.connect();
149177 assertEquals(cluster.manager.sessions.size(), 1);
150178 assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
179+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
151180
152181 // Closing the session keeps the control connection opened
153182 session.close();
154183 assertEquals(cluster.manager.sessions.size(), 0);
155184 assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
185+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
156186
157- return cluster;
187+ return this;
158188 } catch (AssertionError e) {
159189 // If an assertion fails, close the cluster now, because it's the last time we
160190 // have a reference to it.
161191 cluster.close();
162192 throw e;
193+ } finally {
194+ channelMonitor.stop();
163195 }
164196 }
165197 }
166198
167199 private static class CloseCluster implements Callable<Void> {
168200 private final Cluster cluster;
201+ private final SocketChannelMonitor channelMonitor;
169202 private final CountDownLatch startSignal;
170203
171- CloseCluster(Cluster cluster, CountDownLatch startSignal) {
204+ CloseCluster(Cluster cluster, SocketChannelMonitor channelMonitor, CountDownLatch startSignal) {
172205 this.cluster = cluster;
206+ this.channelMonitor = channelMonitor;
173207 this.startSignal = startSignal;
174208 }
175209
@@ -179,7 +213,8 @@
179213
180214 cluster.close();
181215 assertEquals(cluster.manager.sessions.size(), 0);
182- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0);
216+ assertEquals(channelMonitor.openChannels(Collections.singletonList(hostAddress)).size(), 0);
217+ channelMonitor.stop();
183218
184219 return null;
185220 }
@@ -190,4 +225,4 @@
190225 error.initCause(cause);
191226 return error;
192227 }
193-}
228+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Collection;
added driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +130 −0
@@ -0,0 +1,130 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.collect.ImmutableMap;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.AsyncFunction;
21+import com.google.common.util.concurrent.Futures;
22+import com.google.common.util.concurrent.ListenableFuture;
23+import org.scassandra.http.client.PrimingRequest;
24+import org.testng.annotations.Test;
25+
26+import java.util.Collection;
27+import java.util.Collections;
28+import java.util.concurrent.TimeUnit;
29+import java.util.concurrent.TimeoutException;
30+
31+import static org.assertj.core.api.Assertions.assertThat;
32+import static org.testng.Assert.fail;
33+
34+public class ConnectionReleaseTest extends ScassandraTestBase {
35+
36+ /**
37+ * <p>
38+ * Validates that when a future is set that the stream associated with the future's request is released.
39+ * This prevents situations where a user may not be specifying a separate executor on a callback/
40+ * transform to a ResultSetFuture, which is not recommended, causing executeAsync to block in borrowConnection
41+ * until stream ids become available.
42+ *
43+ * Executes the following:
44+ *
45+ * <ol>
46+ * <li>Sets # of connections per host to 1.</li>
47+ * <li>Sends MAX_STREAM_PER_CONNECTION-1 requests that take 10 seconds to execute.</li>
48+ * <li>Calls executeAsync to retrieve records from test1 with k=1.</li>
49+ * <li>Transforms executeAsync to take the 'c' column from the result and query test2.
50+ * This is done without an executor to ensure the netty worker is used and has to wait for the function
51+ * completion.</li>
52+ * <li>Asserts that the transformed future completes within pool timeout and the value is as expected.</li>
53+ * </ol>
54+ *
55+ * @jira_ticket JAVA-666
56+ * @expected_result Are able to transform a Future without hanging in executeAsync as connection should be freed
57+ * before the transform function is called.
58+ * @test_category queries:async
59+ * @since 2.0.10, 2.1.6
60+ */
61+ @SuppressWarnings("unchecked")
62+ @Test(groups="short")
63+ public void should_release_connection_before_completing_future() throws Exception {
64+ Cluster cluster = null;
65+ Collection<ResultSetFuture> mockFutures = Lists.newArrayList();
66+ try {
67+ primingClient.prime(
68+ PrimingRequest.queryBuilder()
69+ .withQuery("mock query")
70+ .withRows(ImmutableMap.of("key", 1))
71+ .withFixedDelay(10000)
72+ .build()
73+ );
74+ primingClient.prime(
75+ PrimingRequest.queryBuilder()
76+ .withQuery("select c from test1 where k=1")
77+ .withRows(ImmutableMap.of("c", "hello"))
78+ .build()
79+ );
80+ primingClient.prime(
81+ PrimingRequest.queryBuilder()
82+ .withQuery("select n from test2 where c='hello'")
83+ .withRows(ImmutableMap.of("n", "world"))
84+ .build()
85+ );
86+
87+ cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress))
88+ .withProtocolVersion(ProtocolVersion.V2)
89+ .withPoolingOptions(new PoolingOptions()
90+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
91+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1))
92+ .build();
93+
94+ final Session session = cluster.connect("ks");
95+ // Consume all stream ids except one.
96+ for(int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2-1; i++)
97+ mockFutures.add(session.executeAsync("mock query"));
98+
99+
100+ ListenableFuture<ResultSet> future = Futures.transform(session.executeAsync("select c from test1 where k=1"),
101+ new AsyncFunction<ResultSet, ResultSet>() {
102+ @Override
103+ public ListenableFuture<ResultSet> apply(ResultSet result) {
104+ Row row = result.one();
105+ String c = row.getString("c");
106+ // Execute async might hang if no streams are available. This happens if the connection
107+ // was not release.
108+ return session.executeAsync("select n from test2 where c='" + c + "'");
109+ }
110+ });
111+
112+ // Wait for up to pool timeout for response. If future is not complete by then, we can assume
113+ // that it is likely that the execute is hung because the connection wasn't released yet.
114+ long waitTimeInMs = cluster.getConfiguration().getPoolingOptions().getPoolTimeoutMillis();
115+ try {
116+ ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS);
117+ assertThat(result.one().getString("n")).isEqualTo("world");
118+ } catch (TimeoutException e) {
119+ fail("Future timed out after " + waitTimeInMs + "ms. " +
120+ "There is a strong possibility connection is not being released.");
121+ }
122+ } finally {
123+ // Cancel all pending requests.
124+ for(ResultSetFuture future : mockFutures)
125+ future.cancel(true);
126+ if(cluster != null)
127+ cluster.close();
128+ }
129+ }
130+}
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Iterator;
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/DynamicConnectionPoolTest.java +344 −11
@@ -1,17 +1,35 @@
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+ */
116 package com.datastax.driver.core;
217
3-import com.codahale.metrics.Gauge;
4-import com.google.common.collect.Lists;
5-import org.testng.annotations.Test;
6-
718 import java.util.Collection;
8-import java.util.concurrent.CountDownLatch;
9-import java.util.concurrent.ExecutorService;
10-import java.util.concurrent.Executors;
11-import java.util.concurrent.ScheduledExecutorService;
19+import java.util.List;
20+import java.util.concurrent.*;
1221 import java.util.concurrent.atomic.AtomicBoolean;
1322
23+import static java.util.concurrent.TimeUnit.MILLISECONDS;
1424 import static java.util.concurrent.TimeUnit.SECONDS;
25+
26+import com.codahale.metrics.Gauge;
27+import com.google.common.collect.Lists;
28+import org.testng.annotations.Test;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.mockito.Mockito.doReturn;
32+import static org.mockito.Mockito.spy;
1533 import static org.testng.Assert.fail;
1634
1735 public class DynamicConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -25,16 +43,331 @@
2543 return Lists.newArrayList(sb.toString());
2644 }
2745
46+ @Override
47+ protected Cluster.Builder configure(Cluster.Builder builder) {
48+ return builder.withProtocolVersion(ProtocolVersion.V2);
49+ }
2850
2951 /**
30- * Test for #JAVA-349 - Negative openConnection count results in broken connection release.
31- * <p/>
52+ * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
53+ * of creating a new connection.
54+ *
55+ * @since 2.0.10, 2.1.6
56+ * @jira_ticket JAVA-419
57+ * @test_category connection:connection_pool
58+ */
59+ @Test(groups = "short")
60+ public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
61+ DynamicConnectionPool pool = createPool(2, 2);
62+
63+ assertThat(pool.connections.size()).isEqualTo(2);
64+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
65+
66+ for (int i = 0; i < 256; i++) {
67+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
68+ assertThat(coreConnections).contains(connection);
69+ }
70+
71+ boolean timedOut = false;
72+ try {
73+ pool.borrowConnection(100, MILLISECONDS);
74+ } catch (TimeoutException e) {
75+ timedOut = true;
76+ }
77+ assertThat(timedOut).isTrue();
78+ }
79+
80+ /**
81+ * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
82+ * timeout instead of creating a new connection.
83+ *
84+ * @since 2.0.10, 2.1.6
85+ * @jira_ticket JAVA-419
86+ * @test_category connection:connection_pool
87+ */
88+ @Test(groups = "short")
89+ public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
90+ DynamicConnectionPool pool = createPool(1, 2);
91+
92+ assertThat(pool.connections.size()).isEqualTo(1);
93+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
94+
95+ //
96+ for (int i = 0; i < 128; i++) {
97+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
98+ assertThat(coreConnections).contains(connection);
99+ }
100+
101+ // Borrow more and ensure the connection returned is a non-core connection.
102+ for (int i = 0; i < 128; i++) {
103+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
104+ assertThat(coreConnections).doesNotContain(connection);
105+ }
106+
107+ boolean timedOut = false;
108+ try {
109+ pool.borrowConnection(100, MILLISECONDS);
110+ } catch (TimeoutException e) {
111+ timedOut = true;
112+ }
113+ assertThat(timedOut).isTrue();
114+ }
115+
116+ /**
117+ * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
118+ *
119+ * @since 2.0.10, 2.1.6
120+ * @jira_ticket JAVA-419
121+ * @test_category connection:connection_pool
122+ */
123+ @Test(groups = "short")
124+ public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
125+ cluster.getConfiguration().getPoolingOptions()
126+ .setIdleTimeoutSeconds(20);
127+
128+ DynamicConnectionPool pool = createPool(1, 2);
129+ Connection core = pool.connections.get(0);
130+
131+ // Fill core connection
132+ for (int i = 0; i < 128; i++)
133+ assertThat(
134+ pool.borrowConnection(100, MILLISECONDS)
135+ ).isEqualTo(core);
136+
137+ // Reaching 128 on the core connection should have triggered the creation of an extra one
138+ TimeUnit.MILLISECONDS.sleep(100);
139+ assertThat(pool.connections).hasSize(2);
140+ }
141+
142+ /**
143+ * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
144+ * borrowConnection is called and a new connection is needed.
145+ *
146+ * @since 2.0.10, 2.1.6
147+ * @jira_ticket JAVA-419
148+ * @test_category connection:connection_pool
149+ */
150+ @Test(groups = "long")
151+ public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
152+ cluster.getConfiguration().getPoolingOptions()
153+ .setIdleTimeoutSeconds(20);
154+
155+ DynamicConnectionPool pool = createPool(1, 2);
156+ Connection connection1 = pool.connections.get(0);
157+
158+ for (int i = 0; i < 101; i++)
159+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
160+
161+ TimeUnit.MILLISECONDS.sleep(100);
162+ assertThat(pool.connections).hasSize(2);
163+ Connection connection2 = pool.connections.get(1);
164+
165+ assertThat(connection1.inFlight.get()).isEqualTo(101);
166+ assertThat(connection2.inFlight.get()).isEqualTo(0);
167+
168+ // Go back under the capacity of 1 connection
169+ for (int i = 0; i < 51; i++)
170+ pool.returnConnection(connection1);
171+
172+ assertThat(connection1.inFlight.get()).isEqualTo(50);
173+ assertThat(connection2.inFlight.get()).isEqualTo(0);
174+
175+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
176+ TimeUnit.SECONDS.sleep(20);
177+ assertThat(pool.connections).containsExactly(connection2);
178+ assertThat(pool.trash).containsExactly(connection1);
179+
180+ // Now borrow enough to go just under the 1 connection threshold
181+ for (int i = 0; i < 50; i++)
182+ pool.borrowConnection(100, MILLISECONDS);
183+
184+ assertThat(pool.connections).containsExactly(connection2);
185+ assertThat(pool.trash).containsExactly(connection1);
186+ assertThat(connection1.inFlight.get()).isEqualTo(50);
187+ assertThat(connection2.inFlight.get()).isEqualTo(50);
188+
189+ // Borrowing one more time should resurrect the trashed connection
190+ pool.borrowConnection(100, MILLISECONDS);
191+ TimeUnit.MILLISECONDS.sleep(100);
192+
193+ assertThat(pool.connections).containsExactly(connection2, connection1);
194+ assertThat(pool.trash).isEmpty();
195+ assertThat(connection1.inFlight.get()).isEqualTo(50);
196+ assertThat(connection2.inFlight.get()).isEqualTo(51);
197+ }
198+
199+ /**
200+ * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
201+ * borrowConnection is called and a new connection is needed.
202+ *
203+ * @since 2.0.10, 2.1.6
204+ * @jira_ticket JAVA-419
205+ * @test_category connection:connection_pool
206+ */
207+ @Test(groups = "long")
208+ public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
209+ cluster.getConfiguration().getPoolingOptions()
210+ .setIdleTimeoutSeconds(20);
211+
212+ DynamicConnectionPool pool = createPool(1, 2);
213+ Connection connection1 = pool.connections.get(0);
214+
215+ for (int i = 0; i < 101; i++)
216+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
217+
218+ TimeUnit.MILLISECONDS.sleep(100);
219+ assertThat(pool.connections).hasSize(2);
220+ Connection connection2 = pool.connections.get(1);
221+
222+ assertThat(connection1.inFlight.get()).isEqualTo(101);
223+ assertThat(connection2.inFlight.get()).isEqualTo(0);
224+
225+ // Go back under the capacity of 1 connection
226+ for (int i = 0; i < 51; i++)
227+ pool.returnConnection(connection1);
228+
229+ assertThat(connection1.inFlight.get()).isEqualTo(50);
230+ assertThat(connection2.inFlight.get()).isEqualTo(0);
231+
232+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
233+ TimeUnit.SECONDS.sleep(20);
234+ assertThat(pool.connections).containsExactly(connection2);
235+ assertThat(pool.trash).containsExactly(connection1);
236+
237+ // Return trashed connection down to 0 inFlight
238+ for (int i = 0; i < 50; i++)
239+ pool.returnConnection(connection1);
240+ assertThat(connection1.inFlight.get()).isEqualTo(0);
241+
242+ // Give enough time for trashed connection to be cleaned up from the trash:
243+ TimeUnit.SECONDS.sleep(30);
244+ assertThat(pool.connections).containsExactly(connection2);
245+ assertThat(pool.trash).isEmpty();
246+ assertThat(connection1.isClosed()).isTrue();
247+
248+ // Fill the live connection to go over the threshold where a second one is needed
249+ for (int i = 0; i < 101; i++)
250+ assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
251+ assertThat(connection2.inFlight.get()).isEqualTo(101);
252+ TimeUnit.MILLISECONDS.sleep(100);
253+
254+ // Borrow again to get the new connection
255+ Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
256+ assertThat(connection3)
257+ .isNotEqualTo(connection2) // should not be the full connection
258+ .isNotEqualTo(connection1); // should not be the previously trashed one
259+ }
260+
261+ /**
262+ * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
263+ *
264+ * @since 2.0.10, 2.1.6
265+ * @jira_ticket JAVA-419
266+ * @test_category connection:connection_pool
267+ */
268+ @Test(groups = "long")
269+ public void should_not_close_trashed_connection_until_no_in_flight()
270+ throws ConnectionException, TimeoutException, InterruptedException {
271+ cluster.getConfiguration().getPoolingOptions()
272+ .setIdleTimeoutSeconds(20);
273+
274+ DynamicConnectionPool pool = createPool(1, 2);
275+ Connection connection1 = pool.connections.get(0);
276+
277+ // Fill core connection enough to trigger creation of another one
278+ for (int i = 0; i < 110; i++)
279+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
280+
281+ TimeUnit.MILLISECONDS.sleep(100);
282+ assertThat(pool.connections).hasSize(2);
283+
284+ // Return enough times to get back under the threshold where one connection is enough
285+ for (int i = 0; i < 50; i++)
286+ pool.returnConnection(connection1);
287+
288+ // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
289+ // It still has in-flight requests so should not get closed.
290+ TimeUnit.SECONDS.sleep(30);
291+ assertThat(pool.trash).containsExactly(connection1);
292+ assertThat(connection1.inFlight.get()).isEqualTo(60);
293+ assertThat(connection1.isClosed()).isFalse();
294+
295+ // Consume all inFlight requests on the trashed connection.
296+ while (connection1.inFlight.get() > 0) {
297+ pool.returnConnection(connection1);
298+ }
299+
300+ // Sleep enough time for the connection to be consider idled and closed.
301+ TimeUnit.SECONDS.sleep(30);
302+
303+ // The connection should be now closed.
304+ // The trashed connection should be closed and not in the pool or trash.
305+ assertThat(connection1.isClosed()).isTrue();
306+ assertThat(pool.connections).doesNotContain(connection1);
307+ assertThat(pool.trash).doesNotContain(connection1);
308+ }
309+
310+ /**
311+ * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
312+ * the connection is put in the trash.
313+ *
314+ * @since 2.0.10, 2.1.6
315+ * @jira_ticket JAVA-419
316+ * @test_category connection:connection_pool
317+ */
318+ @Test(groups = "short")
319+ public void should_trash_on_returning_connection_with_insufficient_streams()
320+ throws ConnectionException, TimeoutException, InterruptedException {
321+ DynamicConnectionPool pool = createPool(1, 2);
322+ Connection core = pool.connections.get(0);
323+
324+ for (int i = 0; i < 128; i++)
325+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
326+
327+ TimeUnit.MILLISECONDS.sleep(100);
328+ assertThat(pool.connections).hasSize(2);
329+
330+ // Grab the new non-core connection and replace it with a spy.
331+ Connection extra1 = spy(pool.connections.get(1));
332+ pool.connections.set(1, extra1);
333+
334+ // Borrow 10 times to ensure pool is utilized.
335+ for (int i = 0; i < 10; i++) {
336+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
337+ }
338+
339+ // Return connection, it should not be trashed since it still has 9 inflight requests.
340+ pool.returnConnection(extra1);
341+ assertThat(pool.connections).hasSize(2);
342+
343+ // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
344+ // this should cause the connection to be replaced and trashed on returnConnection.
345+ doReturn(0).when(extra1).maxAvailableStreams();
346+
347+ // On returning of the connection, should detect that there are no available streams and trash it.
348+ pool.returnConnection(extra1);
349+ assertThat(pool.connections).hasSize(1);
350+ }
351+
352+ private DynamicConnectionPool createPool(int coreConnections, int maxConnections) {
353+ cluster.getConfiguration().getPoolingOptions()
354+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
355+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
356+ Session session = cluster.connect();
357+ Host host = TestUtils.findHost(cluster, 1);
358+ return (DynamicConnectionPool)((SessionManager)session).pools.get(host);
359+ }
360+
361+ /**
362+ * <p>
32363 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
33364 * insertions are being executed, the number of opened connection is monitored.
34365 * <p/>
35366 * If at anytime, the number of opened connections is negative, this test will fail.
36367 *
37- * @throws InterruptedException
368+ * @since 2.0.6, 2.1.1
369+ * @jira_ticket JAVA-349
370+ * @test_category connection:connection_pool
38371 */
39372 @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
40373 public void open_connections_metric_should_always_be_positive() throws InterruptedException {
modified driver-core/src/test/java/com/datastax/driver/core/ExceptionsTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/FakeHost.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.io.IOException;
modified driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import static java.util.concurrent.TimeUnit.SECONDS;
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +15 −7
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.concurrent.CountDownLatch;
@@ -38,13 +53,6 @@
3853 return this;
3954 }
4055
41- public HostAssert isNotReconnectingFromSuspected() {
42- assertThat(actual.getInitialReconnectionAttemptFuture() != null && !actual.getInitialReconnectionAttemptFuture().isDone())
43- .isFalse();
44- return this;
45-
46- }
47-
4856 public HostAssert comesUpWithin(long duration, TimeUnit unit) {
4957 final CountDownLatch upSignal = new CountDownLatch(1);
5058 StateListener upListener = new StateListenerBase() {
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.List;
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import com.datastax.driver.core.Token.M3PToken;
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 public class M3PTokenVnodeIntegrationTest extends TokenIntegrationTest {
modified driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +63 −0
@@ -1,9 +1,31 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.io.StringWriter;
19+import java.util.concurrent.TimeoutException;
20+import java.util.concurrent.locks.Condition;
21+import java.util.concurrent.locks.Lock;
22+import java.util.concurrent.locks.ReentrantLock;
23+
24+import static java.util.concurrent.TimeUnit.MILLISECONDS;
425
526 import org.apache.log4j.PatternLayout;
627 import org.apache.log4j.WriterAppender;
28+import org.apache.log4j.spi.LoggingEvent;
729
830 /**
931 * Simple Log4J appender that captures logs to memory in order to inspect them in unit tests.
@@ -12,6 +34,11 @@
1234 * done with an {@code @After} method that removes it).
1335 */
1436 public class MemoryAppender extends WriterAppender {
37+
38+ private final Lock appendLock = new ReentrantLock();
39+
40+ private final Condition append = appendLock.newCondition();
41+
1542 public final StringWriter writer = new StringWriter();
1643
1744 private int nextLogIdx = 0;
@@ -21,10 +48,46 @@
2148 setLayout(new PatternLayout("%m%n"));
2249 }
2350
51+ @Override
52+ protected void subAppend(LoggingEvent event) {
53+ appendLock.lock();
54+ try {
55+ super.subAppend(event);
56+ append.signal();
57+ } finally {
58+ appendLock.unlock();
59+ }
60+ }
61+
2462 public String get() {
2563 return writer.toString();
2664 }
2765
66+ /**
67+ * Wait until at least one log event is appended to the current appender,
68+ * or a timeout occurs, whichever happens first,
69+ * then return the appender contents.
70+ * Not thread safe.
71+ * Useful when asynchronous code needs to wait until
72+ * the appender is actually invoked at least once.
73+ *
74+ * @param timeoutMillis timeout in milliseconds
75+ * @return The appender contents. Not thread safe.
76+ */
77+ public String waitAndGet(long timeoutMillis) throws InterruptedException {
78+ long nanos = MILLISECONDS.toNanos(timeoutMillis);
79+ appendLock.lock();
80+ try {
81+ while (get().isEmpty()) {
82+ if (nanos <= 0L) break; // timeout
83+ nanos = append.awaitNanos(nanos);
84+ }
85+ return get();
86+ } finally {
87+ appendLock.unlock();
88+ }
89+ }
90+
2891 /**
2992 * @return The next set of logs after getNext was last called. Not thread safe.
3093 */
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Map;
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Collection;
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.net.InetAddress;
added driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +101 −0
@@ -0,0 +1,101 @@
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.concurrent.ThreadFactory;
19+
20+import io.netty.bootstrap.Bootstrap;
21+import io.netty.channel.ChannelHandler;
22+import io.netty.channel.ChannelHandlerContext;
23+import io.netty.channel.EventLoopGroup;
24+import io.netty.channel.nio.NioEventLoopGroup;
25+import io.netty.channel.socket.SocketChannel;
26+import org.mockito.ArgumentCaptor;
27+import org.mockito.invocation.InvocationOnMock;
28+import org.mockito.stubbing.Answer;
29+import org.testng.annotations.DataProvider;
30+import org.testng.annotations.Test;
31+
32+import static org.mockito.Answers.CALLS_REAL_METHODS;
33+import static org.mockito.Matchers.any;
34+import static org.mockito.Mockito.*;
35+
36+import static com.datastax.driver.core.Assertions.assertThat;
37+import static com.datastax.driver.core.CCMBridge.ipOfNode;
38+
39+public class NettyOptionsTest {
40+
41+ @DataProvider(name = "NettyOptionsTest")
42+ public static Object[][] parameters() {
43+ Object[][] params = new Object[][] { {1,1}, {3,4} };
44+ return params;
45+ }
46+
47+ @Test(groups = "short", dataProvider = "NettyOptionsTest")
48+ public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
49+ //given
50+ CCMBridge ccm = CCMBridge.create("test", hosts);
51+ Cluster cluster = null;
52+ try {
53+ NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
54+ EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
55+ when(nettyOptions.eventLoopGroup(any(ThreadFactory.class))).thenReturn(eventLoopGroup);
56+ final ChannelHandler handler = mock(ChannelHandler.class);
57+ doAnswer(new Answer() {
58+ @Override
59+ public Object answer(InvocationOnMock invocation) throws Throwable {
60+ SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
61+ channel.pipeline().addLast("test-handler", handler);
62+ return null;
63+ }
64+ }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
65+ cluster = Cluster.builder()
66+ .addContactPoint(ipOfNode(1))
67+ .withPoolingOptions(new PoolingOptions()
68+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
69+ )
70+ .withNettyOptions(nettyOptions)
71+ .build();
72+ // when
73+ cluster.connect();// force session creation to populate pools
74+
75+ int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
76+ // If the driver supports a more recent protocol version than C*, the negotiation at startup
77+ // will open 1 extra connection.
78+ if (!ProtocolVersion.NEWEST_SUPPORTED.isSupportedBy(TestUtils.findHost(cluster, 1)))
79+ expectedNumberOfCalls += 1;
80+
81+ cluster.close();
82+ // then
83+ ArgumentCaptor<EventLoopGroup> captor = ArgumentCaptor.forClass(EventLoopGroup.class);
84+ verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
85+ verify(nettyOptions, times(1)).channelClass();
86+ // per-connection hooks will be called coreConnections * hosts + 1 times:
87+ // the extra call is for the control connection
88+ verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
89+ verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
90+ verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
91+ verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
92+ verify(nettyOptions, times(1)).onClusterClose(captor.capture());
93+ assertThat(captor.getValue()).isSameAs(eventLoopGroup);
94+ } finally {
95+ if (cluster != null)
96+ cluster.close();
97+ ccm.remove();
98+ }
99+ }
100+
101+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.math.BigInteger;
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import com.datastax.driver.core.Token.OPPToken;
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 public class OPPTokenVnodeIntegrationTest extends TokenIntegrationTest {
added driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +213 −0
@@ -0,0 +1,213 @@
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.Collection;
19+import java.util.Collections;
20+import java.util.Iterator;
21+
22+import com.datastax.driver.core.utils.CassandraVersion;
23+import org.slf4j.Logger;
24+import org.slf4j.LoggerFactory;
25+import org.testng.annotations.BeforeClass;
26+import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+
30+import com.datastax.driver.core.exceptions.PagingStateException;
31+
32+@CassandraVersion(major=2.0)
33+public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster {
34+ private static final Logger logger = LoggerFactory.getLogger(PagingStateTest.class);
35+ public static final String KEY = "paging_test";
36+
37+ @Override
38+ protected Collection<String> getTableDefinitions() {
39+ return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
40+ }
41+
42+ @BeforeClass(groups = "short")
43+ public void initData() {
44+ for (int i = 0; i < 100; i++) {
45+ session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
46+ }
47+ }
48+
49+ /**
50+ * Validates that {@link PagingState} can be reused with the same Statement.
51+ *
52+ * @test_category paging
53+ * @expected_result {@link ResultSet} from the query with the provided {@link PagingState} starts from the
54+ * subsequent row from the first query.
55+ */
56+ @Test(groups = "short")
57+ public void should_complete_when_using_paging_state() {
58+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
59+ ResultSet result = session.execute(st.setFetchSize(20));
60+ int pageSize = result.getAvailableWithoutFetching();
61+ String savedPagingStateString = result.getExecutionInfo().getPagingState().toString();
62+
63+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
64+ result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
65+
66+ //We have the result starting from the next page we stopped
67+ assertThat(result.one().getInt("v")).isEqualTo(pageSize);
68+ }
69+
70+ /**
71+ * <p>
72+ * Validates that if the {@link PagingState} is altered in any way that it may not be reused.
73+ * The paging state is altered in the following ways:
74+ *
75+ * <ol>
76+ * <li>Altering a byte in the paging state raw bytes.</li>
77+ * <li>Setting the {@link PagingState} on a different Statement. (should fail hash validation)</li>
78+ * </ol>
79+ *
80+ * @test_category paging
81+ * @expected_result {@link PagingState} refused to be reused if it is changed or used on a different statement.
82+ */
83+ @Test(groups = "short")
84+ public void should_fail_if_paging_state_altered() {
85+ boolean setWithFalseContent = false;
86+ boolean setWithWrongStatement = false;
87+
88+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
89+ ResultSet result = session.execute(st.setFetchSize(20));
90+
91+ PagingState savedPagingState = result.getExecutionInfo().getPagingState();
92+ byte[] savedPagingStateBuffer = savedPagingState.toBytes();
93+ String savedPagingStateString = savedPagingState.toString();
94+
95+ // corrupting the paging state
96+ savedPagingStateBuffer[6] = (byte)42;
97+
98+ try {
99+ st.setFetchSize(20).setPagingState(PagingState.fromBytes(savedPagingStateBuffer));
100+ } catch (PagingStateException e) {
101+ setWithFalseContent = true;
102+ logger.debug(e.getMessage());
103+ } finally {
104+ assertThat(setWithFalseContent).isTrue();
105+ assertThat(st.getPagingState()).isNull();
106+ }
107+
108+ // Changing the statement
109+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", "paging"));
110+ try {
111+ st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString));
112+ } catch (PagingStateException e) {
113+ setWithWrongStatement = true;
114+ logger.debug(e.getMessage());
115+ } finally {
116+ assertThat(setWithWrongStatement).isTrue();
117+ assertThat(st.getPagingState()).isNull();
118+ }
119+ }
120+
121+ /**
122+ * Validates that {@link PagingState} can be reused with the same {@link BoundStatement}.
123+ *
124+ * @test_category paging
125+ * @expected_result {@link ResultSet} from the query with the provided paging state starts from the subsequent row
126+ * from the first query.
127+ */
128+ @Test(groups = "short")
129+ @CassandraVersion(major=2.0)
130+ public void should_be_able_to_use_state_with_bound_statement() {
131+ PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
132+ BoundStatement bs = prepared.bind(KEY);
133+
134+ ResultSet result = session.execute(bs.setFetchSize(20));
135+ int pageSize = result.getAvailableWithoutFetching();
136+ PagingState pagingState = result.getExecutionInfo().getPagingState();
137+
138+ result = session.execute(bs.setFetchSize(20).setPagingState(pagingState));
139+
140+ //We have the result starting from the next page we stopped
141+ assertThat(result.one().getInt("v")).isEqualTo(pageSize);
142+ }
143+
144+ /**
145+ * Validates that {@link PagingState} cannot be reused with a different {@link BoundStatement} than the original,
146+ * even if its source {@link PreparedStatement} was the same.
147+ *
148+ * @test_category paging
149+ * @expected_result A failure is thrown when setting paging state on a different {@link BoundStatement}.
150+ */
151+ @Test(groups = "short", expectedExceptions = {PagingStateException.class})
152+ @CassandraVersion(major=2.0)
153+ public void should_not_be_able_to_use_state_with_different_bound_statement() {
154+ PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
155+ BoundStatement bs0 = prepared.bind(KEY);
156+
157+ ResultSet result = session.execute(bs0.setFetchSize(20));
158+ PagingState pagingState = result.getExecutionInfo().getPagingState();
159+
160+ BoundStatement bs1 = prepared.bind("different_key");
161+ session.execute(bs1.setFetchSize(20).setPagingState(pagingState));
162+ }
163+
164+ /**
165+ * Validates if all results of a query are paged in through a queries result set that the {@link PagingState} it
166+ * returns will return an empty set when queried with.
167+ *
168+ * @test_category paging
169+ * @expected_result Query with the {@link PagingState} returns 0 rows.
170+ */
171+ @Test(groups = "short")
172+ public void should_return_no_rows_when_paged_to_end() {
173+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
174+ ResultSet result = session.execute(st.setFetchSize(20));
175+
176+ // Consume enough of the iterator to cause all the results to be paged in.
177+ Iterator<Row> rowIt = result.iterator();
178+ for (int i = 0; i < 83; i++) {
179+ rowIt.next().getInt("v");
180+ }
181+
182+ String savedPagingStateString = result.getExecutionInfo().getPagingState().toString();
183+
184+ st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
185+ result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)));
186+
187+ assertThat(result.one()).isNull();
188+ }
189+
190+ @Test(groups = "unit", expectedExceptions = {PagingStateException.class})
191+ public void should_fail_when_given_invalid_string() {
192+ // An invalid string cannot be parsed and a PagingStateException is thrown.
193+ PagingState.fromString("0101");
194+ }
195+
196+ @Test(groups = "unit", expectedExceptions = {PagingStateException.class})
197+ public void should_fail_when_given_invalid_byte_array() {
198+ // Given an expected page state of size 1 and hash of size 1, we should expect 6 bytes, but only receive 5.
199+ byte[] complete = { 0x00, 0x01, 0x00, 0x01, 0x00 };
200+ PagingState.fromBytes(complete);
201+ }
202+
203+ @Test(groups = "unit", expectedExceptions = {UnsupportedOperationException.class})
204+ public void should_fail_when_setting_paging_state_on_batch_statement() {
205+ // Should not be able to set paging state on a batch statement.
206+ PagingState emptyStatement = PagingState.fromString("00000000");
207+
208+ BatchStatement batch = new BatchStatement();
209+ batch.setPagingState(emptyStatement);
210+ }
211+
212+}
213+
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +69 −79
@@ -1,97 +1,87 @@
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+ */
116 package com.datastax.driver.core;
217
3-import static java.util.concurrent.TimeUnit.SECONDS;
4-
5-import org.mockito.Mockito;
618 import org.testng.annotations.Test;
719
8-import com.datastax.driver.core.Host.State;
9-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
10-import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
11-import com.datastax.driver.core.policies.RoundRobinPolicy;
20+import java.util.Collection;
21+import java.util.Collections;
22+import java.util.concurrent.*;
1223
13-import static com.datastax.driver.core.Assertions.assertThat;
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.mockito.Matchers.any;
26+import static org.mockito.Mockito.*;
1427
15-public class PoolingOptionsTest {
28+public class PoolingOptionsTest extends CCMBridge.PerClassSingleNodeCluster {
29+ @Override
30+ protected Collection<String> getTableDefinitions() {
31+ return Collections.emptyList();
32+ }
1633
1734 /**
18- * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
35+ * <p>
36+ * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it
37+ * is used to create and tear down connections.
38+ * </p>
39+ *
40+ * @test_category connection:connection_pool
41+ * @expected_result executor is used and successfully able to connect and tear down connections.
42+ * @jira_ticket JAVA-692
43+ * @since 2.0.10, 2.1.6
1944 */
20- @Test(groups = "long")
21- public void should_refresh_single_connected_host() {
22- CCMBridge ccm = null;
23- Cluster cluster = null;
45+ @Test(groups = "short")
46+ public void should_be_able_to_use_custom_initialization_executor() {
47+ ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
48+ new LinkedBlockingQueue<Runnable>()));
49+
50+ PoolingOptions poolingOptions = new PoolingOptions();
51+ poolingOptions.setInitializationExecutor(executor);
52+
53+ Cluster cluster = Cluster.builder()
54+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
55+ .withPoolingOptions(poolingOptions).build();
2456 try {
25- // This will make the driver use at most 2 hosts, the others will be ignored
26- LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
27-
28- // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
29- ccm = CCMBridge.create("test");
30- ccm.populate(3);
31- ccm.start(1);
32- ccm.start(2);
33- ccm.waitForUp(1);
34- ccm.waitForUp(2);
35-
36- PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
37- cluster = Cluster.builder()
38- .addContactPoint(CCMBridge.ipOfNode(1))
39- .withPoolingOptions(poolingOptions)
40- .withLoadBalancingPolicy(loadBalancingPolicy)
41- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
42- .build();
57+ cluster.init();
58+ // Ensure executor used.
59+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
60+
61+ // Reset invocation count.
62+ reset();
4363
4464 Session session = cluster.connect();
4565
46- assertThat(cluster).usesControlHost(1);
47- assertThat(cluster).host(1)
48- .hasState(State.UP)
49- .isAtDistance(HostDistance.LOCAL);
50- // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
51- // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
52- assertThat(cluster).host(2)
53- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
54- .isAtDistance(HostDistance.LOCAL);
55-
56- // Bring host 3 up, its presence should be acknowledged but it should be ignored
57- ccm.start(3);
58- ccm.waitForUp(3);
59-
60- assertThat(cluster).host(1)
61- .hasState(State.UP)
62- .isAtDistance(HostDistance.LOCAL);
63- assertThat(cluster).host(2)
64- .hasState(State.UP)
65- .isAtDistance(HostDistance.LOCAL);
66- assertThat(cluster).host(3)
67- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
68- .isAtDistance(HostDistance.IGNORED);
69- assertThat(session).hasNoPoolFor(3);
70-
71- // Kill host 2, host 3 should take its place
72- ccm.stop(2);
73- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
74-
75- assertThat(cluster).host(1)
76- .hasState(State.UP)
77- .isAtDistance(HostDistance.LOCAL);
78- assertThat(cluster).host(2)
79- .hasState(State.DOWN);
80- assertThat(cluster).host(3)
81- .hasState(State.UP)
82- .isAtDistance(HostDistance.LOCAL);
83- assertThat(session).hasPoolFor(3);
84-
85- // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
86- // we switch the node from IGNORED to UP:
87- Mockito.verify(poolingOptions)
88- .refreshConnectedHost(TestUtils.findHost(cluster, 3));
66+ // Ensure executor used again to establish core connections.
67+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
68+
69+ // Expect core connections + control connection.
70+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
71+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
72+
73+ reset();
74+
75+ session.close();
76+
77+ // Executor should have been used to close connections associated with the session.
78+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
8979
80+ // Only the control connection should remain.
81+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
9082 } finally {
91- if (cluster != null)
92- cluster.close();
93- if (ccm != null)
94- ccm.remove();
83+ cluster.close();
84+ executor.shutdown();
9585 }
9686 }
9787 }
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +16 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,8 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetAddress;
1819 import java.util.*;
1920
21+import com.google.common.collect.ImmutableList;
2022 import org.testng.annotations.Test;
2123
2224 import static org.assertj.core.api.Assertions.assertThat;
@@ -24,6 +26,7 @@
2426 import static org.testng.Assert.assertFalse;
2527 import static org.testng.Assert.assertTrue;
2628
29+import com.datastax.driver.core.exceptions.InvalidQueryException;
2730 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2831 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2932 import com.datastax.driver.core.utils.CassandraVersion;
@@ -452,4 +455,16 @@
452455 BoundStatement bs = ps.bind(1);
453456 assertThat(bs.getRoutingKey()).isNotNull();
454457 }
458+
459+ @Test(groups="short", expectedExceptions = InvalidQueryException.class)
460+ public void should_fail_when_prepared_on_another_cluster() throws Exception {
461+ Cluster otherCluster = Cluster.builder()
462+ .addContactPointsWithPorts(ImmutableList.of(hostAddress))
463+ .build();
464+ PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
465+ BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
466+
467+ // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
468+ session.executeAsync(bs);
469+ }
455470 }
modified driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +233 −0
@@ -0,0 +1,233 @@
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 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+ .withConstantThreshold(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 +724 −0
@@ -0,0 +1,724 @@
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.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+ .withConstantThreshold(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+ .withConstantThreshold(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+ .withConstantThreshold(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+ .withConstantThreshold(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+ .withConstantThreshold(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+ @Override
285+ public String toString() {
286+ return "weird statement";
287+ }
288+ };
289+ // when
290+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
291+ queryLogger.update(null, unknownStatement, null, 0);
292+ // then
293+ String line = normalAppender.get();
294+ assertThat(line).contains("weird statement");
295+ }
296+
297+ // Tests for different log levels
298+
299+ @Test(groups = "unit")
300+ public void should_not_log_normal_if_level_higher_than_DEBUG() throws Exception {
301+ // given
302+ normal.setLevel(INFO);
303+ slow.setLevel(INFO);
304+ error.setLevel(INFO);
305+ // when
306+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
307+ queryLogger.update(null, mock(BoundStatement.class), null, 0);
308+ // then
309+ assertThat(normalAppender.get()).isEmpty();
310+ assertThat(slowAppender.get()).isEmpty();
311+ assertThat(errorAppender.get()).isEmpty();
312+ }
313+
314+ @Test(groups = "unit")
315+ public void should_not_log_slow_if_level_higher_than_DEBUG() throws Exception {
316+ // given
317+ normal.setLevel(INFO);
318+ slow.setLevel(INFO);
319+ error.setLevel(INFO);
320+ // when
321+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
322+ queryLogger.update(null, mock(BoundStatement.class), null, DEFAULT_SLOW_QUERY_THRESHOLD_MS + 1);
323+ // then
324+ assertThat(normalAppender.get()).isEmpty();
325+ assertThat(slowAppender.get()).isEmpty();
326+ assertThat(errorAppender.get()).isEmpty();
327+ }
328+
329+ @Test(groups = "unit")
330+ public void should_not_log_error_if_level_higher_than_DEBUG() throws Exception {
331+ // given
332+ normal.setLevel(INFO);
333+ slow.setLevel(INFO);
334+ error.setLevel(INFO);
335+ // when
336+ queryLogger = QueryLogger.builder(mock(Cluster.class)).build();
337+ queryLogger.update(null, mock(BoundStatement.class), new DriverException("booh"), 0);
338+ // then
339+ assertThat(normalAppender.get()).isEmpty();
340+ assertThat(slowAppender.get()).isEmpty();
341+ assertThat(errorAppender.get()).isEmpty();
342+ }
343+
344+ // Tests for different query types (normal, slow, exception)
345+
346+ @Test(groups = "short")
347+ public void should_log_normal_queries() throws Exception {
348+ // given
349+ normal.setLevel(DEBUG);
350+ queryLogger = QueryLogger.builder(cluster)
351+ .withConstantThreshold(Long.MAX_VALUE)
352+ .withMaxQueryStringLength(Integer.MAX_VALUE)
353+ .build();
354+ cluster.register(queryLogger);
355+ // when
356+ String query = "SELECT * FROM test where pk = ?";
357+ PreparedStatement ps = session.prepare(query);
358+ BoundStatement bs = ps.bind(42);
359+ session.execute(bs);
360+ // then
361+ String line = normalAppender.waitAndGet(10000);
362+ assertThat(line)
363+ .contains("Query completed normally")
364+ .contains(ipOfNode(1))
365+ .contains(query)
366+ .doesNotContain("pk:42");
367+ }
368+
369+ // Tests for slow and error queries are in QueryLoggerErrorsTest
370+
371+ // Tests with query parameters (log level TRACE)
372+
373+ @Test(groups = "short")
374+ @CassandraVersion(major=2.0)
375+ public void should_log_non_null_named_parameter() throws Exception {
376+ // given
377+ normal.setLevel(TRACE);
378+ queryLogger = QueryLogger.builder(cluster)
379+ .withConstantThreshold(Long.MAX_VALUE)
380+ .withMaxQueryStringLength(Integer.MAX_VALUE)
381+ .build();
382+ cluster.register(queryLogger);
383+ // when
384+ String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2";
385+ PreparedStatement ps = session.prepare(query);
386+ BoundStatement bs = ps.bind();
387+ bs.setString("param1", "foo");
388+ bs.setInt("param2", 42);
389+ session.execute(bs);
390+ // then
391+ String line = normalAppender.waitAndGet(10000);
392+ assertThat(line)
393+ .contains("Query completed normally")
394+ .contains(ipOfNode(1))
395+ .contains(query)
396+ .contains("param2:42")
397+ .contains("param1:'foo'");
398+ }
399+
400+ @Test(groups = "short")
401+ public void should_log_non_null_positional_parameter() throws Exception {
402+ // given
403+ normal.setLevel(TRACE);
404+ queryLogger = QueryLogger.builder(cluster).build();
405+ cluster.register(queryLogger);
406+ // when
407+ String query = "UPDATE test SET c_text = ? WHERE pk = ?";
408+ PreparedStatement ps = session.prepare(query);
409+ BoundStatement bs = ps.bind();
410+ bs.setString("c_text", "foo");
411+ bs.setInt("pk", 42);
412+ session.execute(bs);
413+ // then
414+ String line = normalAppender.waitAndGet(10000);
415+ assertThat(line)
416+ .contains("Query completed normally")
417+ .contains(ipOfNode(1))
418+ .contains(query)
419+ .contains("pk:42")
420+ .contains("c_text:'foo'");
421+ }
422+
423+ @Test(groups = "short")
424+ public void should_log_null_parameter() throws Exception {
425+ // given
426+ normal.setLevel(TRACE);
427+ queryLogger = QueryLogger.builder(cluster).build();
428+ cluster.register(queryLogger);
429+ // when
430+ String query = "UPDATE test SET c_text = ? WHERE pk = ?";
431+ PreparedStatement ps = session.prepare(query);
432+ BoundStatement bs = ps.bind();
433+ bs.setString("c_text", null);
434+ bs.setInt("pk", 42);
435+ session.execute(bs);
436+ // then
437+ String line = normalAppender.waitAndGet(10000);
438+ assertThat(line)
439+ .contains("Query completed normally")
440+ .contains(ipOfNode(1))
441+ .contains(query)
442+ .contains("pk:42")
443+ .contains("c_text:NULL");
444+ }
445+
446+ @Test(groups = "short")
447+ @CassandraVersion(major=2.0)
448+ public void should_log_bound_statement_parameters_inside_batch_statement() throws Exception {
449+ // given
450+ normal.setLevel(TRACE);
451+ queryLogger = QueryLogger.builder(cluster).build();
452+ cluster.register(queryLogger);
453+ // when
454+ String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
455+ String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
456+ BatchStatement batch = new BatchStatement();
457+ batch.add(session.prepare(query1).bind("foo", 42));
458+ batch.add(session.prepare(query2).bind(12345, 43));
459+ session.execute(batch);
460+ // then
461+ String line = normalAppender.waitAndGet(10000);
462+ assertThat(line)
463+ .contains("Query completed normally")
464+ .contains(ipOfNode(1))
465+ .contains(query1)
466+ .contains(query2)
467+ .contains("pk:42")
468+ .contains("pk:43")
469+ .contains("c_text:'foo'")
470+ .contains("c_int:12345");
471+ }
472+ // Test different CQL types
473+
474+ @Test(groups = "short")
475+ public void should_log_all_parameter_types() throws Exception {
476+ // given
477+ normal.setLevel(TRACE);
478+ queryLogger = QueryLogger.builder(cluster)
479+ .withMaxParameterValueLength(Integer.MAX_VALUE)
480+ .build();
481+ cluster.register(queryLogger);
482+ // when
483+ String query = "UPDATE test SET " + assignments + " WHERE pk = 42";
484+ PreparedStatement ps = session.prepare(query);
485+ BoundStatement bs = ps.bind(values.toArray());
486+ session.execute(bs);
487+ // then
488+ String line = normalAppender.waitAndGet(10000);
489+ assertThat(line)
490+ .contains("Query completed normally")
491+ .contains(ipOfNode(1))
492+ .contains(query);
493+ for (DataType type : dataTypes) {
494+ assertThat(line).contains(type.format(getFixedValue(type)));
495+ }
496+ }
497+
498+ // Tests for truncation of query strings and parameter values
499+
500+ @Test(groups = "short")
501+ public void should_truncate_query_when_max_length_exceeded() throws Exception {
502+ // given
503+ normal.setLevel(DEBUG);
504+ queryLogger = QueryLogger.builder(cluster)
505+ .withMaxQueryStringLength(5)
506+ .build();
507+ cluster.register(queryLogger);
508+ // when
509+ String query = "SELECT * FROM test WHERE pk = 42";
510+ session.execute(query);
511+ // then
512+ String line = normalAppender.waitAndGet(10000);
513+ assertThat(line)
514+ .contains("Query completed normally")
515+ .contains(ipOfNode(1))
516+ .contains("SELEC" + TRUNCATED_OUTPUT)
517+ .doesNotContain(query);
518+ }
519+
520+ @CassandraVersion(major=2.0)
521+ @Test(groups = "short")
522+ public void should_show_total_statements_for_batches_even_if_query_truncated() throws Exception {
523+ // given
524+ normal.setLevel(DEBUG);
525+ queryLogger = QueryLogger.builder(cluster)
526+ .withMaxQueryStringLength(5)
527+ .build();
528+ cluster.register(queryLogger);
529+ // when
530+ String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
531+ String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
532+ BatchStatement batch = new BatchStatement();
533+ batch.add(session.prepare(query1).bind("foo", 42));
534+ batch.add(session.prepare(query2).bind(12345, 43));
535+ session.execute(batch);
536+ // then
537+ String line = normalAppender.waitAndGet(10000);
538+ assertThat(line)
539+ .contains("Query completed normally")
540+ .contains(ipOfNode(1))
541+ .contains("BEGIN" + TRUNCATED_OUTPUT)
542+ .doesNotContain(query1)
543+ .doesNotContain(query2)
544+ .contains(" [2 statements");
545+ }
546+
547+ @Test(groups = "short")
548+ public void should_not_truncate_query_when_max_length_unlimited() throws Exception {
549+ // given
550+ normal.setLevel(DEBUG);
551+ queryLogger = QueryLogger.builder(cluster)
552+ .withMaxQueryStringLength(-1)
553+ .build();
554+ cluster.register(queryLogger);
555+ // when
556+ String query = "SELECT * FROM test WHERE pk = 42";
557+ session.execute(query);
558+ // then
559+ String line = normalAppender.waitAndGet(10000);
560+ assertThat(line)
561+ .contains("Query completed normally")
562+ .contains(ipOfNode(1))
563+ .contains(query)
564+ .doesNotContain(TRUNCATED_OUTPUT);
565+ }
566+
567+ @CassandraVersion(major=2.0)
568+ @Test(groups = "short")
569+ public void should_truncate_parameter_when_max_length_exceeded() throws Exception {
570+ // given
571+ normal.setLevel(TRACE);
572+ queryLogger = QueryLogger.builder(cluster)
573+ .withMaxParameterValueLength(5)
574+ .build();
575+ cluster.register(queryLogger);
576+ // when
577+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
578+ PreparedStatement ps = session.prepare(query);
579+ BoundStatement bs = ps.bind();
580+ bs.setInt("c_int", 123456);
581+ bs.setInt("pk", 42);
582+ session.execute(bs);
583+ // then
584+ String line = normalAppender.waitAndGet(10000);
585+ assertThat(line)
586+ .contains("Query completed normally")
587+ .contains(ipOfNode(1))
588+ .contains("c_int:12345" + TRUNCATED_OUTPUT)
589+ .doesNotContain("123456");
590+ }
591+
592+ @Test(groups = "short")
593+ public void should_truncate_blob_parameter_when_max_length_exceeded() throws Exception {
594+ // given
595+ normal.setLevel(TRACE);
596+ queryLogger = QueryLogger.builder(cluster)
597+ .withMaxParameterValueLength(6)
598+ .build();
599+ cluster.register(queryLogger);
600+ // when
601+ String query = "UPDATE test SET c_blob = ? WHERE pk = ?";
602+ PreparedStatement ps = session.prepare(query);
603+ BoundStatement bs = ps.bind();
604+ bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1,2,3))));
605+ bs.setInt("pk", 42);
606+ session.execute(bs);
607+ // then
608+ String line = normalAppender.waitAndGet(10000);
609+ assertThat(line)
610+ .contains("Query completed normally")
611+ .contains(ipOfNode(1))
612+ .contains("c_blob:0x0102" + TRUNCATED_OUTPUT)
613+ .doesNotContain("123456");
614+ }
615+
616+ @Test(groups = "short")
617+ public void should_not_truncate_parameter_when_max_length_unlimited() throws Exception {
618+ // given
619+ normal.setLevel(TRACE);
620+ queryLogger = QueryLogger.builder(cluster)
621+ .withMaxParameterValueLength(-1)
622+ .build();
623+ cluster.register(queryLogger);
624+ // when
625+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
626+ PreparedStatement ps = session.prepare(query);
627+ BoundStatement bs = ps.bind();
628+ bs.setInt("c_int", 123456);
629+ bs.setInt("pk", 42);
630+ session.execute(bs);
631+ // then
632+ String line = normalAppender.waitAndGet(10000);
633+ assertThat(line)
634+ .contains("Query completed normally")
635+ .contains(ipOfNode(1))
636+ .contains("c_int:123456")
637+ .doesNotContain(TRUNCATED_OUTPUT);
638+ }
639+
640+ @Test(groups = "short")
641+ public void should_not_log_exceeding_number_of_parameters() throws Exception {
642+ // given
643+ normal.setLevel(TRACE);
644+ queryLogger = QueryLogger.builder(cluster)
645+ .withMaxLoggedParameters(1)
646+ .build();
647+ cluster.register(queryLogger);
648+ // when
649+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
650+ PreparedStatement ps = session.prepare(query);
651+ BoundStatement bs = ps.bind();
652+ bs.setInt("c_int", 123456);
653+ bs.setInt("pk", 42);
654+ session.execute(bs);
655+ // then
656+ String line = normalAppender.waitAndGet(10000);
657+ assertThat(line)
658+ .contains("Query completed normally")
659+ .contains(ipOfNode(1))
660+ .contains("c_int:123456")
661+ .doesNotContain("pk:42")
662+ .contains(FURTHER_PARAMS_OMITTED);
663+ }
664+
665+ @Test(groups = "short")
666+ @CassandraVersion(major=2.0)
667+ public void should_not_log_exceeding_number_of_parameters_in_batch_statement() throws Exception {
668+ // given
669+ normal.setLevel(TRACE);
670+ queryLogger = QueryLogger.builder(cluster)
671+ .withMaxLoggedParameters(1)
672+ .build();
673+ cluster.register(queryLogger);
674+ // when
675+ String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
676+ String query2 = "UPDATE test SET c_int = ? WHERE pk = ?";
677+ BatchStatement batch = new BatchStatement();
678+ batch.add(session.prepare(query1).bind("foo", 42));
679+ batch.add(session.prepare(query2).bind(12345, 43));
680+ session.execute(batch);
681+ // then
682+ String line = normalAppender.waitAndGet(10000);
683+ assertThat(line)
684+ .contains("Query completed normally")
685+ .contains(ipOfNode(1))
686+ .contains(query1)
687+ .contains(query2)
688+ .contains("c_text:'foo'")
689+ .doesNotContain("pk:42")
690+ .doesNotContain("c_int:12345")
691+ .doesNotContain("pk:43")
692+ .contains(FURTHER_PARAMS_OMITTED);
693+ }
694+
695+ @Test(groups = "short")
696+ public void should_log_all_parameters_when_max_unlimited() throws Exception {
697+ // given
698+ normal.setLevel(TRACE);
699+ queryLogger = QueryLogger.builder(cluster)
700+ .withMaxLoggedParameters(-1)
701+ .build();
702+ cluster.register(queryLogger);
703+ // when
704+ String query = "UPDATE test SET c_int = ? WHERE pk = ?";
705+ PreparedStatement ps = session.prepare(query);
706+ BoundStatement bs = ps.bind();
707+ bs.setInt("c_int", 123456);
708+ bs.setInt("pk", 42);
709+ session.execute(bs);
710+ // then
711+ String line = normalAppender.waitAndGet(10000);
712+ assertThat(line)
713+ .contains("Query completed normally")
714+ .contains(ipOfNode(1))
715+ .contains("c_int:123456")
716+ .contains("pk:42");
717+ }
718+
719+ @Override
720+ protected List<String> getTableDefinitions() {
721+ return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")");
722+ }
723+
724+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.List;
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import com.datastax.driver.core.Token.RPToken;
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 public class RPTokenVnodeIntegrationTest extends TokenIntegrationTest {
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +17 −4
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.concurrent.TimeUnit;
@@ -96,8 +111,7 @@
96111 // Node 1 should now be DOWN with no reconnection attempt
97112 assertThat(mainCluster).host(1)
98113 .hasState(DOWN)
99- .isNotReconnectingFromDown()
100- .isNotReconnectingFromSuspected();
114+ .isNotReconnectingFromDown();
101115 }
102116
103117 @Test(groups = "long")
@@ -120,8 +134,7 @@
120134 // Node 1 should now be DOWN with no reconnection attempt
121135 assertThat(mainCluster).host(1)
122136 .hasState(DOWN)
123- .isNotReconnectingFromDown()
124- .isNotReconnectingFromSuspected();
137+ .isNotReconnectingFromDown();
125138 }
126139
127140 @AfterMethod(groups = "long")
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +82 −2
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.io.IOException;
@@ -18,6 +33,10 @@
1833 import org.testng.annotations.Test;
1934
2035 import static org.assertj.core.api.Assertions.assertThat;
36+import static org.mockito.Mockito.reset;
37+import static org.mockito.Mockito.spy;
38+import static org.mockito.Mockito.times;
39+import static org.mockito.Mockito.verify;
2140
2241 import com.datastax.driver.core.Host.State;
2342 import com.datastax.driver.core.policies.*;
@@ -126,7 +145,7 @@
126145 CCMBridge ccm = null;
127146 Cluster cluster = null;
128147
129- long reconnectionDelayMillis = 1 * 1000;
148+ long reconnectionDelayMillis = 1000;
130149 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
131150
132151 try {
@@ -167,7 +186,7 @@
167186 CCMBridge ccm = null;
168187 Cluster cluster = null;
169188
170- long reconnectionDelayMillis = 1 * 1000;
189+ long reconnectionDelayMillis = 1000;
171190 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
172191
173192 try {
@@ -205,6 +224,7 @@
205224 // down for the driver.
206225 ccm.start(1);
207226 ccm.waitForUp(1);
227+ assertThat(cluster).host(1).hasState(State.DOWN);
208228
209229 TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
210230 assertThat(cluster).host(1).hasState(State.DOWN);
@@ -221,6 +241,66 @@
221241 }
222242 }
223243
244+ /**
245+ * The connection established by a successful reconnection attempt should be reused in one of the
246+ * connection pools (JAVA-505).
247+ */
248+ @Test(groups = "long")
249+ public void should_use_connection_from_reconnection_in_pool() {
250+ CCMBridge ccm = null;
251+ Cluster cluster = null;
252+
253+ TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
254+
255+ // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
256+ SocketOptions socketOptions = spy(new SocketOptions());
257+
258+ try {
259+ ccm = CCMBridge.create("test", 1);
260+ cluster = Cluster.builder()
261+ .addContactPoint(CCMBridge.ipOfNode(1))
262+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
263+ .withLoadBalancingPolicy(loadBalancingPolicy)
264+ .withSocketOptions(socketOptions)
265+ .build();
266+ // Create two sessions to have multiple pools
267+ cluster.connect();
268+ cluster.connect();
269+
270+ int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
271+
272+ // Right after init, 1 connection has been opened by the control connection, and the core size for each pool.
273+ verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive();
274+
275+ // Tweak the LBP so that the control connection never reconnects. This makes it easier
276+ // to reason about the number of connection attempts.
277+ loadBalancingPolicy.returnEmptyQueryPlan = true;
278+
279+ // Stop the node and cancel the reconnection attempts to it
280+ ccm.stop(1);
281+ ccm.waitForDown(1);
282+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
283+ Host host1 = TestUtils.findHost(cluster, 1);
284+ host1.getReconnectionAttemptFuture().cancel(false);
285+
286+ ccm.start(1);
287+ ccm.waitForUp(1);
288+
289+ // Reset the spy and count the number of connections attempts for 1 reconnect
290+ reset(socketOptions);
291+ host1.tryReconnectOnce();
292+ assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
293+ // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
294+ // but the one from the reconnection attempt gets reused).
295+ verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
296+ } finally {
297+ if (cluster != null)
298+ cluster.close();
299+ if (ccm != null)
300+ ccm.remove();
301+ }
302+ }
303+
224304 /**
225305 * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested.
226306 */
added driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +112 −0
@@ -0,0 +1,112 @@
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 static java.util.concurrent.TimeUnit.SECONDS;
19+
20+import org.mockito.Mockito;
21+import org.testng.annotations.Test;
22+
23+import com.datastax.driver.core.Host.State;
24+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
25+import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
26+import com.datastax.driver.core.policies.RoundRobinPolicy;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
29+
30+public class RefreshConnectedHostTest {
31+
32+ /**
33+ * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
34+ */
35+ @Test(groups = "long")
36+ public void should_refresh_single_connected_host() {
37+ CCMBridge ccm = null;
38+ Cluster cluster = null;
39+ try {
40+ // This will make the driver use at most 2 hosts, the others will be ignored
41+ LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
42+
43+ // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
44+ ccm = CCMBridge.create("test");
45+ ccm.populate(3);
46+ ccm.start(1);
47+ ccm.start(2);
48+ ccm.waitForUp(1);
49+ ccm.waitForUp(2);
50+
51+ PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
52+ cluster = Cluster.builder()
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withPoolingOptions(poolingOptions)
55+ .withLoadBalancingPolicy(loadBalancingPolicy)
56+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
57+ .build();
58+
59+ Session session = cluster.connect();
60+
61+ assertThat(cluster).usesControlHost(1);
62+ assertThat(cluster).host(1)
63+ .hasState(State.UP)
64+ .isAtDistance(HostDistance.LOCAL);
65+ // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
66+ // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
67+ assertThat(cluster).host(2)
68+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69+ .isAtDistance(HostDistance.LOCAL);
70+
71+ // Bring host 3 up, its presence should be acknowledged but it should be ignored
72+ ccm.start(3);
73+ ccm.waitForUp(3);
74+
75+ assertThat(cluster).host(1)
76+ .hasState(State.UP)
77+ .isAtDistance(HostDistance.LOCAL);
78+ assertThat(cluster).host(2)
79+ .hasState(State.UP)
80+ .isAtDistance(HostDistance.LOCAL);
81+ assertThat(cluster).host(3)
82+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
83+ .isAtDistance(HostDistance.IGNORED);
84+ assertThat(session).hasNoPoolFor(3);
85+
86+ // Kill host 2, host 3 should take its place
87+ ccm.stop(2);
88+ TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
89+
90+ assertThat(cluster).host(1)
91+ .hasState(State.UP)
92+ .isAtDistance(HostDistance.LOCAL);
93+ assertThat(cluster).host(2)
94+ .hasState(State.DOWN);
95+ assertThat(cluster).host(3)
96+ .hasState(State.UP)
97+ .isAtDistance(HostDistance.LOCAL);
98+ assertThat(session).hasPoolFor(3);
99+
100+ // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
101+ // we switch the node from IGNORED to UP:
102+ Mockito.verify(poolingOptions)
103+ .refreshConnectedHost(TestUtils.findHost(cluster, 3));
104+
105+ } finally {
106+ if (cluster != null)
107+ cluster.close();
108+ if (ccm != null)
109+ ccm.remove();
110+ }
111+ }
112+}
modified driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +17 −2
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.concurrent.TimeUnit;
@@ -57,7 +72,7 @@
5772 }
5873 }
5974
60- PooledConnection connection = getSingleConnection(session);
75+ Connection connection = getSingleConnection(session);
6176 assertThat(connection.inFlight.get()).isEqualTo(0);
6277 } finally {
6378 if (cluster != null)
@@ -66,7 +81,7 @@
6681 }
6782 }
6883
69- private PooledConnection getSingleConnection(Session session) {
84+ private Connection getSingleConnection(Session session) {
7085 HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
7186 if (pool instanceof DynamicConnectionPool)
7287 return ((DynamicConnectionPool)pool).connections.get(0);
modified driver-core/src/test/java/com/datastax/driver/core/RetryPolicyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +129 −0
@@ -0,0 +1,129 @@
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.net.InetAddress;
19+import java.net.UnknownHostException;
20+import java.util.List;
21+import java.util.Map;
22+
23+import com.google.common.collect.ImmutableMap;
24+import com.google.common.collect.ImmutableSet;
25+import com.google.common.collect.Lists;
26+import org.scassandra.Scassandra;
27+import org.scassandra.ScassandraFactory;
28+import org.scassandra.http.client.ColumnTypes;
29+import org.scassandra.http.client.PrimingClient;
30+import org.scassandra.http.client.PrimingRequest;
31+
32+/**
33+ * Launches multiple SCassandra instances, and mocks the appropriate request to make the driver think
34+ * that they belong to the same cluster.
35+ *
36+ * Note: this uses the same addresses as {@link CCMBridge}, so make sure IP aliases have been set up,
37+ * and a CCM cluster is not running at the same time.
38+ */
39+public class SCassandraCluster {
40+ private static final int BINARY_PORT = 9042;
41+ private static final int ADMIN_PORT = 9052;
42+
43+ private final List<Scassandra> scassandras;
44+ private final List<InetAddress> addresses;
45+ private final List<PrimingClient> primingClients;
46+
47+ public SCassandraCluster(String ipPrefix, int nodeCount) {
48+ scassandras = Lists.newArrayListWithCapacity(nodeCount);
49+ addresses = Lists.newArrayListWithCapacity(nodeCount);
50+ primingClients = Lists.newArrayListWithCapacity(nodeCount);
51+
52+ for (int i = 1; i <= nodeCount; i++) {
53+ String ip = ipPrefix + i;
54+ try {
55+ addresses.add(InetAddress.getByName(ip));
56+ } catch (UnknownHostException e) {
57+ throw new AssertionError(e);
58+ }
59+ Scassandra scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
60+ scassandra.start();
61+ scassandras.add(scassandra);
62+
63+ // Currently Scassandra#primingClient() uses localhost by default, so build manually:
64+ primingClients.add(PrimingClient.builder()
65+ .withHost(ip).withPort(scassandra.getAdminPort())
66+ .build());
67+ }
68+ primePeers();
69+ }
70+
71+ public List<InetAddress> addresses() {
72+ return addresses;
73+ }
74+
75+ public void stop() {
76+ for (Scassandra scassandra : scassandras)
77+ scassandra.stop();
78+ }
79+
80+ public SCassandraCluster prime(int node, PrimingRequest request) {
81+ primingClients.get(node - 1).prime(request);
82+ return this;
83+ }
84+
85+ public void clearAllPrimes() {
86+ for (PrimingClient primingClient : primingClients)
87+ primingClient.clearAllPrimes();
88+ primePeers();
89+ }
90+
91+ private void primePeers() {
92+ for (int i = 0; i < scassandras.size(); i++)
93+ primePeers(primingClients.get(i), scassandras.get(i));
94+ }
95+
96+ @SuppressWarnings("unchecked")
97+ private void primePeers(PrimingClient primingClient, Scassandra toIgnore) {
98+ List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(scassandras.size());
99+ for (int i = 0; i < scassandras.size(); i++) {
100+ if (scassandras.get(i).equals(toIgnore))
101+ continue;
102+ InetAddress address = addresses.get(i);
103+ rows.add(ImmutableMap.<String, Object>builder()
104+ .put("peer", address)
105+ .put("rpc_address", address)
106+ .put("data_center", "datacenter1")
107+ .put("rack", "rack1")
108+ .put("release_version", "2.0.1")
109+ .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i)))
110+ .build());
111+ }
112+ primingClient.prime(
113+ PrimingRequest.queryBuilder()
114+ .withQuery("SELECT * FROM system.peers")
115+ .withColumnTypes(SELECT_PEERS_COLUMN_TYPES)
116+ .withRows(rows)
117+ .build());
118+ }
119+
120+ private static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES =
121+ ImmutableMap.<String, ColumnTypes>builder()
122+ .put("peer", ColumnTypes.Inet)
123+ .put("rpc_address", ColumnTypes.Inet)
124+ .put("data_center", ColumnTypes.Text)
125+ .put("rack", ColumnTypes.Text)
126+ .put("release_version", ColumnTypes.Text)
127+ .put("tokens", ColumnTypes.TextSet)
128+ .build();
129+}
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import com.google.common.base.Optional;
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.concurrent.TimeUnit;
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.security.KeyStore;
added driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +127 −0
@@ -0,0 +1,127 @@
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.net.InetSocketAddress;
19+
20+import org.scassandra.Scassandra;
21+import org.scassandra.http.client.ActivityClient;
22+import org.scassandra.http.client.PrimingClient;
23+import org.slf4j.Logger;
24+import org.slf4j.LoggerFactory;
25+import org.testng.annotations.AfterClass;
26+import org.testng.annotations.AfterMethod;
27+import org.testng.annotations.BeforeClass;
28+import org.testng.annotations.BeforeMethod;
29+
30+import static org.assertj.core.api.Assertions.fail;
31+
32+/**
33+ * Base class for Scassandra tests.
34+ * This class takes care of starting and stopping a Scassandra server,
35+ * and provides some helper methods to leverage the creation of Cluster and Session objects.
36+ * The actual creation of such objects is however left to subclasses.
37+ * If a single cluster instance can be shared by all test methods,
38+ * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead.
39+ */
40+public abstract class ScassandraTestBase {
41+
42+ private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
43+
44+ protected Scassandra scassandra;
45+
46+ protected InetSocketAddress hostAddress;
47+
48+ protected PrimingClient primingClient;
49+
50+ protected ActivityClient activityClient;
51+
52+ @BeforeClass(groups = { "short", "long" })
53+ public void startScassandra() {
54+ scassandra = TestUtils.createScassandraServer();
55+ scassandra.start();
56+ primingClient = scassandra.primingClient();
57+ activityClient = scassandra.activityClient();
58+ hostAddress = new InetSocketAddress("127.0.0.1", scassandra.getBinaryPort());
59+ }
60+
61+ @AfterClass(groups = { "short", "long" })
62+ public void stopScassandra() {
63+ if(scassandra != null)
64+ scassandra.stop();
65+ }
66+
67+ @BeforeMethod(groups = { "short", "long" })
68+ @AfterMethod(groups = { "short", "long" })
69+ public void resetClients() {
70+ activityClient.clearAllRecordedActivity();
71+ primingClient.clearAllPrimes();
72+ }
73+
74+ protected Cluster.Builder createClusterBuilder() {
75+ Cluster.Builder builder = Cluster.builder()
76+ .addContactPoint("127.0.0.1")
77+ .withPoolingOptions(new PoolingOptions()
78+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
79+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
80+ .setHeartbeatIntervalSeconds(0))
81+ .withPort(scassandra.getBinaryPort());
82+ return builder;
83+ }
84+
85+ protected Host retrieveSingleHost(Cluster cluster) {
86+ Host host = cluster.getMetadata().getHost(hostAddress);
87+ if(host == null) {
88+ fail("Unable to retrieve host");
89+ }
90+ return host;
91+ }
92+
93+ /**
94+ * This subclass of ScassandraTestBase assumes that
95+ * the same Cluster instance will be used for all tests.
96+ */
97+ public static abstract class PerClassCluster extends ScassandraTestBase {
98+
99+ protected Cluster cluster;
100+
101+ protected Session session;
102+
103+ protected Host host;
104+
105+ @BeforeClass(groups = { "short", "long" }, dependsOnMethods = "startScassandra")
106+ public void initCluster() {
107+ Cluster.Builder builder = createClusterBuilder();
108+ cluster = builder.build();
109+ host = retrieveSingleHost(cluster);
110+ session = cluster.connect();
111+ }
112+
113+ @AfterClass(groups = { "short", "long" })
114+ public void closeCluster() {
115+ if (cluster != null)
116+ cluster.close();
117+ }
118+
119+ @AfterClass(groups = { "short", "long" }, dependsOnMethods = "closeCluster")
120+ @Override
121+ public void stopScassandra() {
122+ super.stopScassandra();
123+ }
124+
125+ }
126+
127+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +124 −0
@@ -0,0 +1,124 @@
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.net.InetAddress;
19+import java.util.UUID;
20+
21+import org.testng.annotations.AfterClass;
22+import org.testng.annotations.AfterMethod;
23+import org.testng.annotations.BeforeClass;
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+
28+import com.datastax.driver.core.exceptions.DriverException;
29+import com.datastax.driver.core.utils.UUIDs;
30+
31+public class SchemaAgreementTest {
32+
33+ // Don't use "IF EXISTS" to remain compatible with older C* versions
34+ static final String CREATE_TABLE = "CREATE TABLE foo (k int primary key, v int)";
35+ static final String DROP_TABLE = "DROP TABLE foo";
36+
37+ CCMBridge ccm;
38+ Cluster cluster;
39+ Session session;
40+ ProtocolOptions protocolOptions;
41+
42+ @BeforeClass(groups = "short")
43+ public void setup() {
44+ ccm = CCMBridge.create("schema_agreement", 2);
45+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
46+ session = cluster.connect();
47+ session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
48+ session.execute("use test");
49+ protocolOptions = cluster.getConfiguration().getProtocolOptions();
50+ }
51+
52+ @Test(groups = "short")
53+ public void should_set_flag_on_successful_agreement() {
54+ protocolOptions.maxSchemaAgreementWaitSeconds = 10;
55+ ResultSet rs = session.execute(CREATE_TABLE);
56+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
57+ }
58+
59+ @Test(groups = "short")
60+ public void should_set_flag_on_non_schema_altering_statement() {
61+ protocolOptions.maxSchemaAgreementWaitSeconds = 10;
62+ ResultSet rs = session.execute("select release_version from system.local");
63+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
64+ }
65+
66+ @Test(groups = "short")
67+ public void should_unset_flag_on_failed_agreement() {
68+ // Setting to 0 results in no query being set, so agreement fails
69+ protocolOptions.maxSchemaAgreementWaitSeconds = 0;
70+ ResultSet rs = session.execute(CREATE_TABLE);
71+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isFalse();
72+ }
73+
74+ @Test(groups = "short")
75+ public void should_check_agreement_through_cluster_metadata() {
76+ Cluster controlCluster = null;
77+ try {
78+ controlCluster = TestUtils.buildControlCluster(cluster);
79+ Session controlSession = controlCluster.connect();
80+
81+ Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one();
82+ UUID localVersion = localRow.getUUID("schema_version");
83+ Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one();
84+ InetAddress peerAddress = peerRow.getInet("peer");
85+ UUID peerVersion = peerRow.getUUID("schema_version");
86+ // The two nodes should be in agreement at this point, but check just in case:
87+ assertThat(localVersion).isEqualTo(peerVersion);
88+
89+ // Now check the method under test:
90+ assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue();
91+
92+ // Insert a fake version to simulate a disagreement:
93+ forceSchemaVersion(controlSession, peerAddress, UUIDs.random());
94+ assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse();
95+
96+ forceSchemaVersion(controlSession, peerAddress, peerVersion);
97+ } finally {
98+ if (controlCluster != null)
99+ controlCluster.close();
100+ }
101+ }
102+
103+ private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) {
104+ session.execute(String.format("UPDATE system.peers SET schema_version = %s WHERE peer = %s",
105+ DataType.uuid().format(schemaVersion), DataType.inet().format(peerAddress)));
106+ }
107+
108+ @AfterMethod(groups = "short")
109+ public void cleanupSchema() {
110+ protocolOptions.maxSchemaAgreementWaitSeconds = 10;
111+ try {
112+ session.execute(DROP_TABLE);
113+ } catch (DriverException e) { /*ignore*/ }
114+ }
115+
116+ @AfterClass(groups = "short")
117+ public void teardown() {
118+ if (cluster != null)
119+ cluster.close();
120+ if (ccm != null)
121+ ccm.remove();
122+ }
123+}
124+
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.List;
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import org.assertj.core.api.AbstractAssert;
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +74 −33
@@ -1,67 +1,108 @@
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+ */
116 package com.datastax.driver.core;
217
18+import java.net.InetSocketAddress;
19+import java.util.Collections;
20+import java.util.List;
21+import java.util.concurrent.TimeUnit;
22+
23+import static java.util.concurrent.TimeUnit.MINUTES;
24+
25+import com.google.common.collect.Lists;
326 import org.testng.annotations.Test;
427
5-import static org.testng.Assert.assertEquals;
28+import com.datastax.driver.core.utils.SocketChannelMonitor;
29+
30+import static com.datastax.driver.core.Assertions.assertThat;
31+
632
733 public class SessionLeakTest {
834
35+ Cluster cluster;
36+ List<InetSocketAddress> nodes = Lists.newArrayList(
37+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
38+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
39+ SocketChannelMonitor channelMonitor;
40+
941 @Test(groups = "short")
1042 public void connectionLeakTest() throws Exception {
11- CCMBridge ccm = null;
12- Cluster cluster = null;
13-
43+ // Checking for JAVA-342
44+ CCMBridge ccmBridge;
45+ ccmBridge = CCMBridge.create("test", 1);
46+ channelMonitor = new SocketChannelMonitor();
47+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
1448 try {
15- ccm = CCMBridge.create("test", 1);
16-
17- // create a new cluster object and ensure 0 sessions and connections
18- cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
49+ cluster = Cluster.builder()
50+ .addContactPointsWithPorts(Collections.singletonList(
51+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
52+ .withNettyOptions(channelMonitor.nettyOptions()).build();
1953
54+ cluster.init();
2055
21- assertEquals(cluster.manager.sessions.size(), 0);
22- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 0);
56+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
57+ // Should be 1 control connection after initialization.
58+ assertOpenConnections(1);
2359
2460 // ensure sessions.size() returns with 1 control connection + core pool size.
25- Session session = cluster.connect();
26-
27- // Special check for protocol version 3, number of connections should be 1.
2861 int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster);
62+ Session session = cluster.connect();
2963
30- assertEquals(cluster.manager.sessions.size(), 1);
31- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
64+ assertThat(cluster.manager.sessions.size()).isEqualTo(1);
65+ assertOpenConnections(1 + corePoolSize);
3266
3367 // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
3468 session.close();
35- assertEquals(cluster.manager.sessions.size(), 0);
36- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
37-
38- Session thisSession;
69+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
70+ assertOpenConnections(1);
3971
4072 // ensure bootstrapping a node does not create additional connections
73+ ccmBridge.bootstrapNode(2);
74+ assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
4175
42- ccm.bootstrapNode(2);
43- assertEquals(cluster.manager.sessions.size(), 0);
44- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
76+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
77+ assertOpenConnections(1);
4578
4679 // ensure a new session gets registered and core connections are established
4780 // there should be corePoolSize more connections to accommodate for the new host.
48- thisSession = cluster.connect();
49- assertEquals(cluster.manager.sessions.size(), 1);
50-
51- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + (corePoolSize * 2));
81+ Session thisSession = cluster.connect();
82+ assertThat(cluster.manager.sessions.size()).isEqualTo(1);
83+ assertOpenConnections(1 + (corePoolSize * 2));
5284
5385 // ensure bootstrapping a node does not create additional connections that won't get cleaned up
5486 thisSession.close();
5587
56- assertEquals(cluster.manager.sessions.size(), 0);
57-
58- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
59-
88+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
89+ assertOpenConnections(1);
6090 } finally {
61- if (cluster != null)
91+ if(cluster != null){
6292 cluster.close();
63- if (ccm != null)
64- ccm.remove();
93+ }
94+ if (ccmBridge != null) {
95+ ccmBridge.remove();
96+ }
97+ // Ensure no channels remain open.
98+ channelMonitor.stop();
99+ channelMonitor.report();
100+ assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0);
65101 }
66102 }
103+
104+ private void assertOpenConnections(int expected) {
105+ assertThat((cluster.getMetrics().getOpenConnections().getValue())).isEqualTo(expected);
106+ assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(expected);
107+ }
67108 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +70 −23
@@ -1,10 +1,28 @@
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+ */
116 package com.datastax.driver.core;
217
3-import com.google.common.util.concurrent.Uninterruptibles;
18+import com.datastax.driver.core.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.*;
421 import org.slf4j.Logger;
522 import org.slf4j.LoggerFactory;
623 import org.testng.annotations.Test;
724
25+import java.net.InetSocketAddress;
826 import java.util.*;
927 import java.util.concurrent.*;
1028
@@ -15,11 +33,11 @@
1533
1634 private static final Logger logger = LoggerFactory.getLogger(SessionStressTest.class);
1735
18- private ExecutorService executorService;
36+ private ListeningExecutorService executorService;
1937
2038 public SessionStressTest() {
2139 // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
22- executorService = Executors.newFixedThreadPool(8);
40+ executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8));
2341 }
2442
2543 @Override
@@ -54,12 +72,17 @@
5472 @Test(groups = "long")
5573 public void sessions_should_not_leak_connections() {
5674 // override inherited field with a new cluster object and ensure 0 sessions and connections
57- cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress))
58- .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)).build();
59-
60- // The cluster has not been initialized yet, therefore the control connection is not opened
75+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
76+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
77+ List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
78+ cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
79+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
80+ .withNettyOptions(channelMonitor.nettyOptions()).build();
81+ cluster.init();
82+
83+ // The cluster has been initialized, we should have 1 connection.
6184 assertEquals(cluster.manager.sessions.size(), 0);
62- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0);
85+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
6386
6487 // The first session initializes the cluster and its control connection
6588 // This is a local cluster so we also have 2 connections per session
@@ -67,11 +90,13 @@
6790 assertEquals(cluster.manager.sessions.size(), 1);
6891 int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster);
6992 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
93+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
7094
7195 // Closing the session keeps the control connection opened
7296 session.close();
7397 assertEquals(cluster.manager.sessions.size(), 0);
7498 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
99+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
75100
76101 try {
77102 int nbOfSessions = 2000;
@@ -88,7 +113,8 @@
88113 // Since we have 2 connections per session, we should see 2 * sessions + control connection
89114 assertEquals(cluster.manager.sessions.size(), nbOfSessions);
90115 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
91- coreConnections * nbOfSessions + 1);
116+ coreConnections * nbOfSessions + 1);
117+ assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
92118
93119 // Close half of the sessions asynchronously
94120 logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
@@ -97,13 +123,16 @@
97123 // Check that we have the right number of sessions and connections
98124 assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
99125 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
100- coreConnections * (nbOfSessions / 2) + 1);
126+ coreConnections * (nbOfSessions / 2) + 1);
127+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
128+ coreConnections * (nbOfSessions / 2) + 1);
101129
102130 // Close and open the same number of sessions concurrently
103131 logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions);
104- CountDownLatch startSignal = new CountDownLatch(1);
105- List<Future<Session>> openSessionFutures = openSessionsConcurrently(halfOfTheSessions, startSignal);
106- List<Future<CloseFuture>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions,
132+ CountDownLatch startSignal = new CountDownLatch(2);
133+ List<ListenableFuture<Session>> openSessionFutures =
134+ openSessionsConcurrently(halfOfTheSessions, startSignal);
135+ List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions,
107136 startSignal);
108137 startSignal.countDown();
109138 waitFor(openSessionFutures);
@@ -112,7 +141,9 @@
112141 // Check that we have the same number of sessions and connections
113142 assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
114143 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
115- coreConnections * (nbOfSessions / 2) + 1);
144+ coreConnections * (nbOfSessions / 2) + 1);
145+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
146+ coreConnections * (nbOfSessions / 2) + 1);
116147
117148 // Close the remaining sessions
118149 logger.info("Closing remaining {} sessions.", halfOfTheSessions);
@@ -121,6 +152,7 @@
121152 // Check that we have a clean state
122153 assertEquals(cluster.manager.sessions.size(), 0);
123154 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
155+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
124156
125157 // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
126158 logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
@@ -128,17 +160,22 @@
128160 }
129161 } finally {
130162 cluster.close();
163+
164+ // Ensure no channels remain open.
165+ channelMonitor.stop();
166+ channelMonitor.report();
167+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
131168 }
132169 }
133170
134- private List<Future<Session>> openSessionsConcurrently(int iterations) {
171+ private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations) {
135172 final CountDownLatch countDownLatch = new CountDownLatch(1);
136173 return openSessionsConcurrently(iterations, countDownLatch);
137174 }
138175
139- private List<Future<Session>> openSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
176+ private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
140177 // Open new sessions once all tasks have been created
141- List<Future<Session>> sessionFutures = new ArrayList<Future<Session>>(iterations);
178+ List<ListenableFuture<Session>> sessionFutures = Lists.newArrayListWithCapacity(iterations);
142179 for (int i = 0; i < iterations; i++) {
143180 sessionFutures.add(executorService.submit(new OpenSession(cluster, countDownLatch)));
144181 }
@@ -146,12 +183,12 @@
146183 return sessionFutures;
147184 }
148185
149- private List<Future<CloseFuture>> closeSessionsConcurrently(int iterations) {
186+ private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations) {
150187 final CountDownLatch countDownLatch = new CountDownLatch(1);
151188 return closeSessionsConcurrently(iterations, countDownLatch);
152189 }
153190
154- private List<Future<CloseFuture>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
191+ private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
155192 // Get a reference to every session we want to close
156193 Stack<Session> sessionsToClose = new Stack<Session>();
157194 Iterator<? extends Session> iterator = cluster.manager.sessions.iterator();
@@ -160,15 +197,25 @@
160197 }
161198
162199 // Close sessions asynchronously once all tasks have been created
163- List<Future<CloseFuture>> closeFutures = new ArrayList<Future<CloseFuture>>(iterations);
200+ List<ListenableFuture<CloseFuture>> closeFutures = Lists.newArrayListWithCapacity(iterations);
164201 for (int i = 0; i < iterations; i++) {
165202 closeFutures.add(executorService.submit(new CloseSession(sessionsToClose.pop(), countDownLatch)));
166203 }
167204 countDownLatch.countDown();
168- return closeFutures;
205+
206+ // Immediately wait for CloseFutures, this should be very quick since all this work does is call closeAsync.
207+ List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(iterations);
208+ for(ListenableFuture<CloseFuture> closeFuture : closeFutures) {
209+ try {
210+ futures.add(closeFuture.get());
211+ } catch(Exception e) {
212+ logger.error("Got interrupted exception while waiting on closeFuture.", e);
213+ }
214+ }
215+ return futures;
169216 }
170217
171- private <E> void waitFor(List<Future<E>> futures) {
218+ private <E> void waitFor(List<ListenableFuture<E>> futures) {
172219 for (Future<E> future : futures) {
173220 try {
174221 future.get();
@@ -212,4 +259,4 @@
212259 return session.closeAsync();
213260 }
214261 }
215-}
262+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +39 −31
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -15,26 +15,33 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Collection;
20-import java.util.List;
21-import java.util.Locale;
18+import java.net.InetSocketAddress;
19+import java.util.*;
2220 import java.util.concurrent.CountDownLatch;
2321 import java.util.concurrent.ExecutorService;
2422 import java.util.concurrent.Executors;
2523 import java.util.concurrent.TimeUnit;
2624
25+import com.datastax.driver.core.utils.CassandraVersion;
26+import com.datastax.driver.core.utils.SocketChannelMonitor;
27+import io.netty.channel.socket.SocketChannel;
28+import org.slf4j.Logger;
29+import org.slf4j.LoggerFactory;
2730 import org.testng.annotations.Test;
2831
2932 import static org.testng.Assert.assertEquals;
3033 import static org.testng.Assert.assertTrue;
3134 import static org.testng.Assert.fail;
3235
36+
37+
3338 /**
3439 * Simple test of the Sessions methods against a one node cluster.
3540 */
3641 public class SessionTest extends CCMBridge.PerClassSingleNodeCluster {
3742
43+ private static final Logger logger = LoggerFactory.getLogger(SessionTest.class);
44+
3845 private static final String TABLE1 = "test1";
3946 private static final String TABLE2 = "test2";
4047 private static final String TABLE3 = "test3";
@@ -107,19 +114,38 @@
107114 assertEquals(rows.get(0).getLong("c"), 2L);
108115 }
109116
117+ /**
118+ * Validates that a session can be established using snappy compression and executes some queries that inserts and
119+ * retrieves data using that session.
120+ *
121+ * @test_category connection:compression
122+ * @expected_result session established and queries made successfully using it.
123+ */
110124 @Test(groups = "short")
111- public void compressionTest() throws Exception {
112-
113- // Same as executeTest, but with compression enabled
125+ public void session_should_function_with_snappy_compression() throws Exception {
126+ compressionTest(ProtocolOptions.Compression.SNAPPY);
127+ }
114128
115- cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.SNAPPY);
129+ /**
130+ * Validates that a session can be established using lz4 compression and executes some queries that inserts and
131+ * retrieves data using that session.
132+ *
133+ * @test_category connection:compression
134+ * @expected_result session established and queries made successfully using it.
135+ */
136+ @Test(groups = "short")
137+ @CassandraVersion(major=2.0)
138+ public void session_should_function_with_lz4_compression() throws Exception {
139+ compressionTest(ProtocolOptions.Compression.LZ4);
140+ }
116141
142+ public void compressionTest(ProtocolOptions.Compression compression) {
143+ cluster.getConfiguration().getProtocolOptions().setCompression(compression);
117144 try {
118-
119145 Session compressedSession = cluster.connect(keyspace);
120146
121147 // Simple calls to all versions of the execute/executeAsync methods
122- String key = "execute_compressed_test";
148+ String key = "execute_compressed_test_" + compression;
123149 ResultSet rs = compressedSession.execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE3, key, "foo", 42, 24.03f));
124150 assertTrue(rs.isExhausted());
125151
@@ -138,24 +164,6 @@
138164 }
139165 }
140166
141- @Test(groups = "short")
142- public void getStateTest() throws Exception {
143- Session.State state = session.getState();
144- Host host = state.getConnectedHosts().iterator().next();
145-
146- String hostAddress = String.format("/%s1", CCMBridge.IP_PREFIX);
147-
148- assertEquals(state.getConnectedHosts().size(), 1);
149- assertEquals(host.getAddress().toString(), hostAddress);
150- assertEquals(host.getDatacenter(), "datacenter1");
151- assertEquals(host.getRack(), "rack1");
152- assertEquals(host.getSocketAddress().toString(), hostAddress + ":" + ports[2]);
153-
154- assertEquals(state.getOpenConnections(host), TestUtils.numberOfLocalCoreConnections(cluster));
155- assertEquals(state.getInFlightQueries(host), 0);
156- assertEquals(state.getSession(), session);
157- }
158-
159167 /**
160168 * Checks for deadlocks when a session shutdown races with the initialization of the cluster (JAVA-418).
161169 */
@@ -165,7 +173,7 @@
165173
166174 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
167175 // (note the use of newSession below)
168- final Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "1").build();
176+ final Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
169177 final Session session = cluster.newSession();
170178
171179 // Spawn two threads to simulate the race
@@ -201,7 +209,7 @@
201209 startLatch.countDown();
202210
203211 executor.shutdown();
204- boolean normalShutdown = executor.awaitTermination(1, TimeUnit.SECONDS);
212+ boolean normalShutdown = executor.awaitTermination(500, TimeUnit.MILLISECONDS);
205213 assertTrue(normalShutdown);
206214
207215 // The deadlock occurred here before JAVA-418
modified driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Collections;
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +270 −0
@@ -0,0 +1,270 @@
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.*;
19+import java.util.concurrent.ConcurrentSkipListSet;
20+
21+import com.google.common.collect.ImmutableList;
22+import com.google.common.collect.ImmutableMap;
23+import com.google.common.primitives.UnsignedBytes;
24+import org.scassandra.http.client.PrimingRequest;
25+import org.testng.annotations.*;
26+
27+import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
28+import com.datastax.driver.core.policies.LoadBalancingPolicy;
29+import com.datastax.driver.core.policies.RetryPolicy;
30+
31+import static com.datastax.driver.core.Assertions.assertThat;
32+
33+public class SpeculativeExecutionTest {
34+ SCassandraCluster scassandras;
35+
36+ Cluster cluster = null;
37+ SortingLoadBalancingPolicy loadBalancingPolicy;
38+ Metrics.Errors errors;
39+ Host host1, host2, host3;
40+ Session session;
41+
42+ @BeforeClass(groups = "short")
43+ public void beforeClass() {
44+ scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 3);
45+ }
46+
47+ @BeforeMethod(groups = "short")
48+ public void beforeMethod() {
49+ int speculativeExecutionDelay = 200;
50+
51+ loadBalancingPolicy = new SortingLoadBalancingPolicy();
52+ cluster = Cluster.builder()
53+ .addContactPoint(CCMBridge.ipOfNode(2))
54+ .withLoadBalancingPolicy(loadBalancingPolicy)
55+ .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
56+ .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
57+ .withRetryPolicy(new CustomRetryPolicy())
58+ .build();
59+
60+ session = cluster.connect();
61+
62+ host1 = TestUtils.findHost(cluster, 1);
63+ host2 = TestUtils.findHost(cluster, 2);
64+ host3 = TestUtils.findHost(cluster, 3);
65+
66+ errors = cluster.getMetrics().getErrorMetrics();
67+ }
68+
69+ @Test(groups = "short")
70+ public void should_not_start_speculative_execution_if_first_execution_completes_successfully() {
71+ scassandras.prime(1, PrimingRequest.queryBuilder()
72+ .withQuery("mock query")
73+ .withRows(row("result", "result1"))
74+ .build()
75+ );
76+
77+ long execStartCount = errors.getSpeculativeExecutions().getCount();
78+
79+ ResultSet rs = session.execute("mock query");
80+ Row row = rs.one();
81+
82+ assertThat(row.getString("result")).isEqualTo("result1");
83+ assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount);
84+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host1);
85+ }
86+
87+ @Test(groups = "short")
88+ public void should_not_start_speculative_execution_if_first_execution_retries_but_is_still_fast_enough() {
89+ // will retry once on this node:
90+ scassandras.prime(1, PrimingRequest.queryBuilder()
91+ .withQuery("mock query")
92+ .withConsistency(PrimingRequest.Consistency.TWO)
93+ .withResult(PrimingRequest.Result.read_request_timeout)
94+ .build()
95+ ).prime(1, PrimingRequest.queryBuilder()
96+ .withQuery("mock query")
97+ .withConsistency(PrimingRequest.Consistency.ONE)
98+ .withRows(row("result", "result1"))
99+ .build()
100+ );
101+
102+ long execStartCount = errors.getSpeculativeExecutions().getCount();
103+ long retriesStartCount = errors.getRetriesOnUnavailable().getCount();
104+
105+ SimpleStatement statement = new SimpleStatement("mock query");
106+ statement.setConsistencyLevel(ConsistencyLevel.TWO);
107+ ResultSet rs = session.execute(statement);
108+ Row row = rs.one();
109+
110+ assertThat(row.getString("result")).isEqualTo("result1");
111+ assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount);
112+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(retriesStartCount + 1);
113+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host1);
114+ }
115+
116+ @Test(groups = "short")
117+ public void should_start_speculative_execution_if_first_execution_takes_too_long() {
118+ scassandras.prime(1, PrimingRequest.queryBuilder()
119+ .withQuery("mock query")
120+ .withFixedDelay(400)
121+ .withRows(row("result", "result1"))
122+ .build()
123+ ).prime(2, PrimingRequest.queryBuilder()
124+ .withQuery("mock query")
125+ .withRows(row("result", "result2"))
126+ .build()
127+ );
128+ long execStartCount = errors.getSpeculativeExecutions().getCount();
129+
130+ ResultSet rs = session.execute("mock query");
131+ Row row = rs.one();
132+
133+ assertThat(row.getString("result")).isEqualTo("result2");
134+ assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1);
135+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host2);
136+ }
137+
138+ @Test(groups = "short")
139+ public void should_wait_until_all_executions_have_finished() {
140+ // Rely on read timeouts to trigger errors that cause an execution to move to the next node
141+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1000);
142+
143+ scassandras
144+ // execution1 starts with host1, which will time out at t=1000
145+ .prime(1, PrimingRequest.queryBuilder()
146+ .withQuery("mock query")
147+ .withFixedDelay(2000)
148+ .withRows(row("result", "result1"))
149+ .build())
150+ // at t=1000, execution1 moves to host3, which eventually succeeds at t=1500
151+ .prime(3, PrimingRequest.queryBuilder()
152+ .withQuery("mock query")
153+ .withFixedDelay(500)
154+ .withRows(row("result", "result3"))
155+ .build())
156+ // meanwhile, execution2 starts at t=200, using host2 which times out at t=1200
157+ // at that time, the query plan is empty so execution2 fails
158+ // The goal of this test is to check that execution2 does not fail the query, since execution1 is still running
159+ .prime(2, PrimingRequest.queryBuilder()
160+ .withQuery("mock query")
161+ .withFixedDelay(2000)
162+ .withRows(row("result", "result2"))
163+ .build());
164+ long execStartCount = errors.getSpeculativeExecutions().getCount();
165+
166+ ResultSet rs = session.execute("mock query");
167+ Row row = rs.one();
168+
169+ assertThat(row.getString("result")).isEqualTo("result3");
170+ assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1);
171+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host3);
172+ }
173+
174+ @AfterMethod(groups = "short")
175+ public void afterMethod() {
176+ scassandras.clearAllPrimes();
177+ if (cluster != null)
178+ cluster.close();
179+ }
180+
181+ @AfterClass(groups = "short")
182+ public void afterClass() {
183+ if (scassandras != null)
184+ scassandras.stop();
185+ }
186+
187+ /**
188+ * A load balancing policy that sorts hosts on the last byte of the address,
189+ * so that the query plan is always [host1, host2, host3].
190+ */
191+ static class SortingLoadBalancingPolicy implements LoadBalancingPolicy {
192+
193+ private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
194+ @Override
195+ public int compare(Host host1, Host host2) {
196+ byte[] address1 = host1.getAddress().getAddress();
197+ byte[] address2 = host2.getAddress().getAddress();
198+ return UnsignedBytes.compare(
199+ address1[address1.length - 1],
200+ address2[address2.length - 1]);
201+ }
202+ });
203+
204+ @Override
205+ public void init(Cluster cluster, Collection<Host> hosts) {
206+ this.hosts.addAll(hosts);
207+ }
208+
209+ @Override
210+ public HostDistance distance(Host host) {
211+ return HostDistance.LOCAL;
212+ }
213+
214+ @Override
215+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
216+ return hosts.iterator();
217+ }
218+
219+ @Override
220+ public void onAdd(Host host) {
221+ onUp(host);
222+ }
223+
224+ @Override
225+ public void onUp(Host host) {
226+ hosts.add(host);
227+ }
228+
229+ @Override
230+ public void onDown(Host host) {
231+ hosts.remove(host);
232+ }
233+
234+ @Override
235+ public void onRemove(Host host) {
236+ onDown(host);
237+ }
238+
239+ @Override
240+ public void onSuspected(Host host) {
241+ }
242+ }
243+
244+ /**
245+ * Custom retry policy that retries at ONE on read timeout.
246+ * This deals with the fact that Scassandra only allows read timeouts with 0 replicas.
247+ */
248+ static class CustomRetryPolicy implements RetryPolicy {
249+ @Override
250+ public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
251+ if (nbRetry != 0)
252+ return RetryDecision.rethrow();
253+ return RetryDecision.retry(ConsistencyLevel.ONE);
254+ }
255+
256+ @Override
257+ public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
258+ return RetryDecision.rethrow();
259+ }
260+
261+ @Override
262+ public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
263+ return RetryDecision.rethrow();
264+ }
265+ }
266+
267+ private static List<Map<String, ?>> row(String key, String value) {
268+ return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value));
269+ }
270+}
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
added driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +103 −0
@@ -0,0 +1,103 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.collect.ImmutableList;
19+import org.testng.annotations.Test;
20+
21+import static org.assertj.core.api.Assertions.assertThat;
22+
23+import com.datastax.driver.core.querybuilder.BuiltStatement;
24+
25+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
26+
27+public class StatementIdempotenceTest {
28+ @Test(groups = "unit")
29+ public void should_default_to_false_when_not_set_on_statement_nor_query_options() {
30+ QueryOptions queryOptions = new QueryOptions();
31+ SimpleStatement statement = new SimpleStatement("");
32+
33+ assertThat(statement.isIdempotentWithDefault(queryOptions)).isFalse();
34+ }
35+
36+ @Test(groups = "unit")
37+ public void should_use_query_options_when_not_set_on_statement() {
38+ QueryOptions queryOptions = new QueryOptions();
39+ SimpleStatement statement = new SimpleStatement("");
40+
41+ for (boolean valueInOptions : new boolean[]{ true, false }) {
42+ queryOptions.setDefaultIdempotence(valueInOptions);
43+ assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInOptions);
44+ }
45+ }
46+
47+ @Test(groups = "unit")
48+ public void should_use_statement_when_set_on_statement() {
49+ QueryOptions queryOptions = new QueryOptions();
50+ SimpleStatement statement = new SimpleStatement("");
51+
52+ for (boolean valueInOptions : new boolean[]{ true, false })
53+ for (boolean valueInStatement : new boolean[]{ true, false }) {
54+ queryOptions.setDefaultIdempotence(valueInOptions);
55+ statement.setIdempotent(valueInStatement);
56+ assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInStatement);
57+ }
58+ }
59+
60+ @Test(groups = "unit")
61+ public void should_infer_for_built_statement() {
62+ for (BuiltStatement statement : idempotentBuiltStatements())
63+ assertThat(statement.isIdempotent())
64+ .as(statement.getQueryString())
65+ .isTrue();
66+
67+ for (BuiltStatement statement : nonIdempotentBuiltStatements())
68+ assertThat(statement.isIdempotent())
69+ .as(statement.getQueryString())
70+ .isFalse();
71+ }
72+
73+ @Test(groups = "unit")
74+ public void should_override_inferred_value_when_manually_set_on_built_statement() {
75+ for (boolean manualValue : new boolean[]{ true, false }) {
76+ for (BuiltStatement statement : idempotentBuiltStatements()) {
77+ statement.setIdempotent(manualValue);
78+ assertThat(statement.isIdempotent()).isEqualTo(manualValue);
79+ }
80+
81+ for (BuiltStatement statement : nonIdempotentBuiltStatements()) {
82+ statement.setIdempotent(manualValue);
83+ assertThat(statement.isIdempotent()).isEqualTo(manualValue);
84+ }
85+ }
86+ }
87+
88+ private static ImmutableList<BuiltStatement> idempotentBuiltStatements() {
89+ return ImmutableList.<BuiltStatement>of(
90+ update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
91+ update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
92+ update("foo").with(put("m", "a", 1)).where(eq("k", 1)) // put in map
93+ );
94+ }
95+
96+ private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
97+ return ImmutableList.<BuiltStatement>of(
98+ update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
99+ update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
100+ update("foo").with(incr("c")).where(eq("k", 1)) // counter update
101+ );
102+ }
103+}
added driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +147 −0
@@ -0,0 +1,147 @@
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.Collection;
19+import java.util.Iterator;
20+import java.util.concurrent.atomic.AtomicInteger;
21+
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.Test;
24+
25+import static org.assertj.core.api.Assertions.assertThat;
26+
27+import com.datastax.driver.core.policies.*;
28+
29+public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster {
30+ @Override
31+ protected Collection<String> getTableDefinitions() {
32+ return Lists.newArrayList();
33+ }
34+
35+ CustomLoadBalancingPolicy loadBalancingPolicy = new CustomLoadBalancingPolicy();
36+ CustomSpeculativeExecutionPolicy speculativeExecutionPolicy = new CustomSpeculativeExecutionPolicy();
37+ CustomRetryPolicy retryPolicy = new CustomRetryPolicy();
38+
39+ @Override
40+ protected Cluster.Builder configure(Cluster.Builder builder) {
41+ return builder
42+ .withLoadBalancingPolicy(loadBalancingPolicy)
43+ .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
44+ .withRetryPolicy(retryPolicy);
45+ }
46+
47+ @Test(groups = "short")
48+ public void should_pass_wrapped_statement_to_load_balancing_policy() {
49+ loadBalancingPolicy.customStatementsHandled.set(0);
50+
51+ SimpleStatement s = new SimpleStatement("select * from system.local");
52+ session.execute(s);
53+ assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0);
54+
55+ session.execute(new CustomStatement(s));
56+ assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1);
57+ }
58+
59+ @Test(groups = "short")
60+ public void should_pass_wrapped_statement_to_speculative_execution_policy() {
61+ speculativeExecutionPolicy.customStatementsHandled.set(0);
62+
63+ SimpleStatement s = new SimpleStatement("select * from system.local");
64+ session.execute(s);
65+ assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0);
66+
67+ session.execute(new CustomStatement(s));
68+ assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(1);
69+ }
70+
71+ @Test(groups = "short")
72+ public void should_pass_wrapped_statement_to_retry_policy() {
73+ retryPolicy.customStatementsHandled.set(0);
74+
75+ // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE,
76+ // which our custom policy ignores.
77+ Statement s = new SimpleStatement("select * from system.local")
78+ .setConsistencyLevel(ConsistencyLevel.TWO);
79+
80+ session.execute(s);
81+ assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0);
82+
83+ session.execute(new CustomStatement(s));
84+ assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1);
85+ }
86+
87+ /** A custom wrapper that's just used to mark statements. */
88+ static class CustomStatement extends StatementWrapper {
89+ protected CustomStatement(Statement wrapped) {
90+ super(wrapped);
91+ }
92+ }
93+
94+ /** A load balancing policy that counts how many times it has seen the custom wrapper */
95+ static class CustomLoadBalancingPolicy extends DelegatingLoadBalancingPolicy {
96+ final AtomicInteger customStatementsHandled = new AtomicInteger();
97+
98+ public CustomLoadBalancingPolicy() {
99+ super(new RoundRobinPolicy());
100+ }
101+
102+ @Override
103+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
104+ if (statement instanceof CustomStatement)
105+ customStatementsHandled.incrementAndGet();
106+ return super.newQueryPlan(loggedKeyspace, statement);
107+ }
108+ }
109+
110+ /** A speculative execution policy that counts how many times it has seen the custom wrapper */
111+ static class CustomSpeculativeExecutionPolicy extends DelegatingSpeculativeExecutionPolicy {
112+ final AtomicInteger customStatementsHandled = new AtomicInteger();
113+
114+ protected CustomSpeculativeExecutionPolicy() {
115+ super(NoSpeculativeExecutionPolicy.INSTANCE);
116+ }
117+
118+ @Override
119+ public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) {
120+ if (statement instanceof CustomStatement)
121+ customStatementsHandled.incrementAndGet();
122+ return super.newPlan(loggedKeyspace, statement);
123+ }
124+ }
125+
126+ /** A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors. */
127+ static class CustomRetryPolicy implements RetryPolicy {
128+ final AtomicInteger customStatementsHandled = new AtomicInteger();
129+
130+ @Override
131+ public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
132+ if (statement instanceof CustomStatement)
133+ customStatementsHandled.incrementAndGet();
134+ return RetryDecision.ignore();
135+ }
136+
137+ @Override
138+ public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
139+ return RetryDecision.rethrow();
140+ }
141+
142+ @Override
143+ public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
144+ return RetryDecision.rethrow();
145+ }
146+ }
147+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Collection;
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +17 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@
1919 import java.math.BigDecimal;
2020 import java.math.BigInteger;
2121 import java.net.InetAddress;
22+import java.net.InetSocketAddress;
2223 import java.net.ServerSocket;
2324 import java.nio.ByteBuffer;
2425 import java.util.*;
@@ -31,6 +32,9 @@
3132 import org.slf4j.LoggerFactory;
3233 import org.testng.SkipException;
3334
35+import com.datastax.driver.core.policies.RoundRobinPolicy;
36+import com.datastax.driver.core.policies.WhiteListPolicy;
37+
3438 /**
3539 * A number of static fields/methods handy for tests.
3640 */
@@ -440,4 +444,16 @@
440444 return 2;
441445 }
442446 }
447+
448+ /**
449+ * @return a {@Cluster} instance that connects only to the control host of the given cluster.
450+ */
451+ public static Cluster buildControlCluster(Cluster cluster) {
452+ Host controlHost = cluster.manager.controlConnection.connectedHost();
453+ List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
454+ return Cluster.builder()
455+ .addContactPointsWithPorts(singleAddress)
456+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
457+ .build();
458+ }
443459 }
added driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +279 −0
@@ -0,0 +1,279 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.utils.SocketChannelMonitor;
20+import com.google.common.collect.Lists;
21+import com.google.common.util.concurrent.FutureCallback;
22+import com.google.common.util.concurrent.Futures;
23+import com.google.common.util.concurrent.ThreadFactoryBuilder;
24+import com.google.common.util.concurrent.Uninterruptibles;
25+import io.netty.channel.socket.SocketChannel;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+import org.testng.annotations.AfterClass;
29+import org.testng.annotations.BeforeClass;
30+import org.testng.annotations.Test;
31+
32+import java.net.InetSocketAddress;
33+import java.util.Collection;
34+import java.util.List;
35+import java.util.concurrent.*;
36+import java.util.concurrent.atomic.AtomicBoolean;
37+import java.util.concurrent.atomic.AtomicInteger;
38+
39+import static org.assertj.core.api.Assertions.assertThat;
40+
41+public class TimeoutStressTest {
42+
43+ static final Logger logger = LoggerFactory.getLogger(TimeoutStressTest.class);
44+
45+ // Maximum number of concurrent queries running at a given time.
46+ static final int CONCURRENT_QUERIES = 25;
47+
48+ // How long the test should run for, may want to consider running for longer periods to time to check for leaks
49+ // that could occur over very tiny timing windows.
50+ static final long DURATION = 60000;
51+
52+ // Configured read timeout - this may need to be tuned to the host system running the test.
53+ static final int READ_TIMEOUT_IN_MS = 50;
54+
55+ // Configured connection timeout - this may need to be tuned to the host system running the test.
56+ static final int CONNECTION_TIMEOUT_IN_MS = 20;
57+
58+ // Keyspace to use.
59+ static final String KEYSPACE = "testks";
60+
61+ static Cluster cluster;
62+
63+ static CCMBridge ccmBridge;
64+
65+ static SocketChannelMonitor channelMonitor;
66+
67+ static AtomicInteger executedQueries = new AtomicInteger(0);
68+
69+ static List<InetSocketAddress> nodes;
70+
71+ static PreparedStatement statement;
72+
73+ @BeforeClass(groups = "long")
74+ public void beforeClass() throws Exception {
75+ ccmBridge = CCMBridge.create("test", 3);
76+ channelMonitor = new SocketChannelMonitor();
77+ nodes = Lists.newArrayList(
78+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
79+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
80+ new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
81+ );
82+
83+ PoolingOptions poolingOptions = new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 8);
84+
85+ cluster = Cluster.builder()
86+ .addContactPointsWithPorts(nodes)
87+ .withPoolingOptions(poolingOptions)
88+ .withNettyOptions(channelMonitor.nettyOptions())
89+ .build();
90+ Session session = cluster.connect();
91+ setupSchema(session);
92+ session.close();
93+ }
94+
95+ @AfterClass(groups = "long")
96+ public void afterClass() {
97+ if(ccmBridge != null) {
98+ ccmBridge.stop();
99+ }
100+ if(channelMonitor != null) {
101+ channelMonitor.stop();
102+ }
103+ if(cluster != null) {
104+ cluster.close();
105+ }
106+ }
107+
108+ /**
109+ * <p>
110+ * Validates that under extreme timeout conditions the driver is able to properly maintain connection pools in
111+ * addition to not leaking connections.
112+ *
113+ * <p>
114+ * Does the following:
115+ * <ol>
116+ * <li>Creates a table and loads 30k rows in a single partition.</li>
117+ * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
118+ * <li>Spawns workers that concurrently execute queries.</li>
119+ * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
120+ * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
121+ * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
122+ * <li>Ensure pools are restored.</li>
123+ * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
124+ * </ol>
125+ *
126+ * @test_category connection:connection_pool
127+ * @expected_result no connections leak and all host pools are maintained.
128+ * @jira_ticket JAVA-692
129+ * @since 2.0.10, 2.1.6
130+ */
131+ @Test(groups = "long")
132+ public void host_state_should_be_maintained_with_timeouts() {
133+ // Set very low timeouts.
134+ cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
135+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
136+ Session session = cluster.connect();
137+
138+ int workers = Runtime.getRuntime().availableProcessors();
139+ ExecutorService workerPool = Executors.newFixedThreadPool(workers,
140+ new ThreadFactoryBuilder().setNameFormat("timeout-stress-test-worker-%d").setDaemon(true).build());
141+
142+ AtomicBoolean stopped = new AtomicBoolean(false);
143+
144+ // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection.
145+ int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster) * nodes.size() + 1;
146+
147+ try {
148+ Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES);
149+ for (int i = 0; i < workers; i++) {
150+ workerPool.submit(new TimeoutStressWorker(session, concurrentQueries, stopped));
151+ }
152+
153+ long startTime = System.currentTimeMillis();
154+ while (System.currentTimeMillis() - startTime < DURATION) {
155+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
156+ channelMonitor.report();
157+ // Some connections that are being closed may have had active requests which are delegated to the
158+ // reaper for cleanup later.
159+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
160+
161+ // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
162+ // factor between retrieving open connections and checking the reaper.
163+ if(openChannels.size() > maxConnections) {
164+ logger.warn("{} of open channels: {} exceeds maximum expected: {}. " +
165+ "This could be because there are connections to be cleaned up in the reaper.",
166+ openChannels.size(), maxConnections, openChannels);
167+ }
168+ }
169+ } finally {
170+ stopped.set(true);
171+
172+ // Reset socket timeouts to allow pool to recover.
173+ cluster.getConfiguration().getSocketOptions()
174+ .setConnectTimeoutMillis(SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS);
175+ cluster.getConfiguration().getSocketOptions()
176+ .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
177+
178+ logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
179+ "and for the pools to recover.");
180+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
181+
182+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
183+ assertThat(openChannels.size())
184+ .as("Number of open connections does not meet expected: %s", openChannels)
185+ .isEqualTo(maxConnections);
186+
187+ session.close();
188+
189+ openChannels = channelMonitor.openChannels(nodes);
190+ assertThat(openChannels.size())
191+ .as("Number of open connections does not meet expected: %s", openChannels)
192+ .isEqualTo(1);
193+
194+ workerPool.shutdown();
195+ }
196+ }
197+
198+ /**
199+ * Creates the testks schema with a 'record' table and preloads 30k records.
200+ */
201+ private static void setupSchema(Session session) throws InterruptedException, ExecutionException, TimeoutException {
202+ logger.debug("Creating keyspace");
203+ session.execute("create KEYSPACE " + KEYSPACE +
204+ " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}");
205+ session.execute("use " + KEYSPACE);
206+
207+ logger.debug("Creating table");
208+ session.execute("create table record (\n"
209+ + " name text,\n"
210+ + " phone text,\n"
211+ + " value text,\n"
212+ + " PRIMARY KEY (name, phone)\n"
213+ + ");");
214+
215+ int records = 30000;
216+ List<ResultSetFuture> futures = Lists.newArrayListWithExpectedSize(records);
217+
218+ PreparedStatement insertStmt = session.prepare("insert into record (name, phone, value) values (?, ?, ?)");
219+
220+ for (int i = 0; i < records; i++) {
221+ if (i % 1000 == 0)
222+ logger.debug("Inserting record {}.", i);
223+ futures.add(session.executeAsync(insertStmt.bind("0", Integer.toString(i), "test")));
224+ }
225+
226+ statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;");
227+
228+ logger.debug("Completed inserting data. Waiting up to 30 for inserts to complete seconds before proceeding.");
229+ Futures.allAsList(futures).get(30, TimeUnit.SECONDS);
230+ logger.debug("Inserts complete.");
231+ }
232+
233+ public static class TimeoutStressWorker implements Runnable {
234+
235+ private final Semaphore concurrentQueries;
236+ private final AtomicBoolean stopped;
237+ private final Session session;
238+
239+ public TimeoutStressWorker(Session session, Semaphore concurrentQueries, AtomicBoolean stopped) {
240+ this.session = session;
241+ this.concurrentQueries = concurrentQueries;
242+ this.stopped = stopped;
243+ }
244+
245+
246+ @Override
247+ public void run() {
248+
249+ while(!stopped.get()) {
250+ try {
251+ concurrentQueries.acquire();
252+ ResultSetFuture future = session.executeAsync(statement.bind("0"));
253+ Futures.addCallback(future, new FutureCallback<ResultSet>() {
254+
255+ @Override
256+ public void onSuccess(ResultSet result) {
257+ concurrentQueries.release();
258+ if(executedQueries.incrementAndGet() % 1000 == 0)
259+ logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching());
260+ }
261+
262+ @Override
263+ public void onFailure(Throwable t) {
264+ concurrentQueries.release();
265+ if(t instanceof NoHostAvailableException) {
266+ //logger.error("NHAE: {}", t.getMessage());
267+ } else {
268+ //logger.error("Exception", t);
269+ }
270+ }
271+ });
272+ } catch(Exception e) {
273+ logger.error("Failure while submitting query.", e);
274+ }
275+ }
276+
277+ }
278+ }
279+}
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.net.InetSocketAddress;
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.Iterator;
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core;
217
318 import java.util.List;
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.exceptions;
217
318 import java.io.PrintWriter;
modified driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysIgnoreRetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysRetryRetryPolicy.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.policies;
217
318 import org.testng.annotations.Test;
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.policies;
217
318 import java.util.Collection;
modified driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.policies;
217
318 import java.util.Collection;
added driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java +47 −0
@@ -0,0 +1,47 @@
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 com.datastax.driver.core.Cluster;
19+import com.datastax.driver.core.Statement;
20+
21+/**
22+ * Base class for tests that want to wrap a policy to add some instrumentation.
23+ *
24+ * NB: this is currently only used in tests, but could be provided as a convenience in the production code.
25+ */
26+public abstract class DelegatingSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
27+ private final SpeculativeExecutionPolicy delegate;
28+
29+ protected DelegatingSpeculativeExecutionPolicy(SpeculativeExecutionPolicy delegate) {
30+ this.delegate = delegate;
31+ }
32+
33+ @Override
34+ public void init(Cluster cluster) {
35+ delegate.init(cluster);
36+ }
37+
38+ @Override
39+ public SpeculativeExecutionPlan newPlan(String loggedKeyspace, Statement statement) {
40+ return delegate.newPlan(loggedKeyspace, statement);
41+ }
42+
43+ @Override
44+ public void close() {
45+ delegate.close();
46+ }
47+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslaterTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.policies;
217
318 import org.testng.annotations.Test;
added driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +170 −0
@@ -0,0 +1,170 @@
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.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+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java +15 −7
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.policies;
217
318 import java.util.*;
@@ -118,13 +133,6 @@
118133 onAdd(host);
119134 }
120135
121- @Override
122- public void onSuspected(Host host) {
123- // If a node gets suspected, it means the driver was connected to it, so it was a chosen node.
124- // Keep it as chosen for now, but notify the child policy which might reorder the query plan accordingly.
125- delegate.onSuspected(host);
126- }
127-
128136 @Override
129137 public void onDown(Host host) {
130138 delegate.onDown(host);
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.policies;
217
318 import java.nio.ByteBuffer;
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java +15 −0
@@ -1,3 +1,18 @@
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+ */
116 package com.datastax.driver.core.utils;
217
318 import java.lang.annotation.Retention;
added driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +174 −0
@@ -0,0 +1,174 @@
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.utils;
17+
18+import com.datastax.driver.core.NettyOptions;
19+import com.google.common.base.Predicate;
20+import com.google.common.base.Predicates;
21+import com.google.common.collect.Iterables;
22+import com.google.common.collect.Lists;
23+import com.google.common.collect.MapMaker;
24+import com.google.common.util.concurrent.ThreadFactoryBuilder;
25+import io.netty.channel.socket.SocketChannel;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+
29+import java.net.InetSocketAddress;
30+import java.net.Socket;
31+import java.net.SocketAddress;
32+import java.util.*;
33+import java.util.concurrent.Executors;
34+import java.util.concurrent.ScheduledExecutorService;
35+import java.util.concurrent.TimeUnit;
36+import java.util.concurrent.atomic.AtomicLong;
37+
38+/**
39+ * Utility that observes {@link SocketChannel}s. Helpful for ensuring that Sockets are actually closed
40+ * when they should be. Utilizes {@link NettyOptions} to monitor created {@link SocketChannel}s.
41+ */
42+public class SocketChannelMonitor implements Runnable {
43+
44+ private static final Logger logger = LoggerFactory.getLogger(SocketChannelMonitor.class);
45+
46+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1,
47+ new ThreadFactoryBuilder().setDaemon(true).setNameFormat("SocketMonitor-%d").build());
48+
49+ // use a weak set so channels may be garbage collected.
50+ private final Collection<SocketChannel> channels = Collections.newSetFromMap(
51+ new MapMaker().weakKeys().<SocketChannel, Boolean>makeMap());
52+
53+ private final AtomicLong channelsCreated = new AtomicLong(0);
54+
55+ private final NettyOptions nettyOptions = new NettyOptions() {
56+ public void afterChannelInitialized(SocketChannel channel) throws Exception {
57+ channels.add(channel);
58+ channelsCreated.incrementAndGet();
59+ }
60+ };
61+
62+ @Override
63+ public void run() {
64+ try {
65+ report();
66+ } catch(Exception e) {
67+ logger.error("Error countered.", e);
68+ }
69+ }
70+
71+ public void stop() {
72+ executor.shutdown();
73+ try {
74+ executor.awaitTermination(1, TimeUnit.SECONDS);
75+ } catch (InterruptedException e) {
76+ }
77+ }
78+
79+ /**
80+ * @return A custom {@link NettyOptions} instance that hooks into afterChannelInitialized added channels may be
81+ * monitored.
82+ */
83+ public NettyOptions nettyOptions() {
84+ return nettyOptions;
85+ }
86+
87+ public static Predicate<SocketChannel> openChannels = new Predicate<SocketChannel>() {
88+ @Override
89+ public boolean apply(SocketChannel input) {
90+ return input.isOpen();
91+ }
92+ };
93+
94+ /**
95+ * Schedules a {@link #report()} to be called every configured interval.
96+ * @param interval how often to report.
97+ * @param timeUnit at what time precision to report at.
98+ */
99+ public void reportAtFixedInterval(int interval, TimeUnit timeUnit) {
100+ executor.scheduleAtFixedRate(this, interval, interval, timeUnit);
101+ }
102+
103+ /**
104+ * Reports for all sockets.
105+ */
106+ public void report() {
107+ report(Predicates.<SocketChannel>alwaysTrue());
108+ }
109+
110+ /**
111+ * <p>
112+ * Report for all sockets matching the given predicate. The report format reflects the number of open, closed,
113+ * live and total sockets created. This is logged at DEBUG if enabled.
114+ *
115+ * <p>
116+ * If TRACE is enabled, each individual socket will be logged as well.
117+ *
118+ * @param channelFilter used to determine which sockets to report on.
119+ */
120+ public void report(Predicate<SocketChannel> channelFilter) {
121+ if(logger.isDebugEnabled()) {
122+ Iterable<SocketChannel> channels = matchingChannels(channelFilter);
123+ Iterable<SocketChannel> open = Iterables.filter(channels, openChannels);
124+ Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels));
125+
126+ logger.debug("Channel states: {} open, {} closed, live {}, total sockets created " +
127+ "(including those that don't match filter) {}.",
128+ Iterables.size(open),
129+ Iterables.size(closed),
130+ Iterables.size(channels),
131+ channelsCreated.get());
132+
133+ if(logger.isTraceEnabled()) {
134+ logger.trace("Open channels {}.", open);
135+ logger.trace("Closed channels {}.", closed);
136+ }
137+ }
138+ }
139+
140+ private static Comparator<SocketChannel> BY_REMOTE_ADDRESS = new Comparator<SocketChannel>() {
141+ @Override
142+ public int compare(SocketChannel t0, SocketChannel t1) {
143+ // Should not be null as these are filtered previously in matchingChannels.
144+ assert t0 != null && t0.remoteAddress() != null;
145+ assert t1 != null && t1.remoteAddress() != null;;
146+ return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString());
147+ }
148+ };
149+
150+ /**
151+ * @param addresses The addresses to include.
152+ * @return Open channels matching the given socket addresses.
153+ */
154+ public Collection<SocketChannel> openChannels(final Collection<InetSocketAddress> addresses) {
155+ List<SocketChannel> channels = Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() {
156+ @Override
157+ public boolean apply(SocketChannel input) {
158+ return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress());
159+ }
160+ }));
161+
162+ Collections.sort(channels, BY_REMOTE_ADDRESS);
163+
164+ return channels;
165+ }
166+
167+ /**
168+ * @param channelFilter {@link Predicate} to use to determine whether or not a socket shall be considered.
169+ * @return Channels matching the given {@link Predicate}.
170+ */
171+ public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) {
172+ return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter));
173+ }
174+}
modified driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-core/src/test/resources/log4j.properties +16 −0
@@ -1,3 +1,19 @@
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+
117 # Set root logger level to DEBUG and its only appender to A1.
218 log4j.rootLogger=INFO, A1
319
modified driver-dist/pom.xml +19 −13
@@ -1,17 +1,19 @@
11 <!--
2- Copyright (C) 2012 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.
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
1517 -->
1618 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
1719 <modelVersion>4.0.0</modelVersion>
@@ -22,6 +24,10 @@
2224 </parent>
2325 <artifactId>cassandra-driver-dist</artifactId>
2426
27+ <properties>
28+ <main.basedir>${project.parent.basedir}</main.basedir>
29+ </properties>
30+
2531 <!-- Should be pom but Javadoc generation requires a "classpath-capable" package -->
2632 <packaging>jar</packaging>
2733
modified driver-dist/src/assembly/binary-tarball.xml +17 −0
@@ -1,3 +1,20 @@
1+<!--
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
17+-->
118 <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
219 xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
320 <id>binary-tarball</id>
modified driver-dse/pom.xml +19 −13
@@ -1,17 +1,19 @@
11 <!--
2- Copyright (C) 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.
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
1517 -->
1618 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
1719 <modelVersion>4.0.0</modelVersion>
@@ -26,6 +28,10 @@
2628 <description>Extensions to the CQL driver for use with DataStax Enterprise.</description>
2729 <url>https://github.com/datastax/java-driver</url>
2830
31+ <properties>
32+ <main.basedir>${project.parent.basedir}</main.basedir>
33+ </properties>
34+
2935 <dependencies>
3036 <dependency>
3137 <groupId>com.datastax.cassandra</groupId>
modified driver-dse/src/main/java/com/datastax/driver/auth/DseAuthProvider.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-dse/src/main/java/com/datastax/driver/auth/KerberosAuthenticator.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-dse/src/main/java/com/datastax/driver/auth/PrivilegedSaslClient.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/osgi/README.rst +1 −1
@@ -12,7 +12,7 @@
1212
1313 To build the bundle and run tests execute the following maven task::
1414
15- mvn test -P short
15+ mvn integration-test -P short
1616
1717 The short profile needs to be activated since the tests run under
1818 this group.
modified driver-examples/osgi/pom.xml +24 −11
@@ -1,15 +1,19 @@
11 <!--
2- Licensed under the Apache License, Version 2.0 (the "License");
3- you may not use this file except in compliance with the License.
4- You may obtain a copy of the License at
5-
6- http://www.apache.org/licenses/LICENSE-2.0
7-
8- Unless required by applicable law or agreed to in writing, software
9- distributed under the License is distributed on an "AS IS" BASIS,
10- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11- See the License for the specific language governing permissions and
12- limitations under the License. See accompanying LICENSE file.
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
1317 -->
1418 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
1519 <modelVersion>4.0.0</modelVersion>
@@ -27,6 +31,7 @@
2731 <properties>
2832 <felix.version>4.6.0</felix.version>
2933 <pax-exam.version>3.6.0</pax-exam.version>
34+ <main.basedir>${project.parent.parent.basedir}</main.basedir>
3035 </properties>
3136
3237 <dependencies>
@@ -112,12 +117,20 @@
112117 <version>3.1.0</version>
113118 <scope>test</scope>
114119 </dependency>
120+
115121 <dependency>
116122 <groupId>javax.inject</groupId>
117123 <artifactId>javax.inject</artifactId>
118124 <version>1</version>
119125 <scope>test</scope>
120126 </dependency>
127+
128+ <dependency>
129+ <groupId>org.apache.commons</groupId>
130+ <artifactId>commons-exec</artifactId>
131+ <version>1.3</version>
132+ <scope>test</scope>
133+ </dependency>
121134 </dependencies>
122135
123136 <build>
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +19 −7
@@ -57,8 +57,20 @@
5757 return mavenBundle("com.google.guava", "guava", "14.0.1");
5858 }
5959
60- private MavenArtifactProvisionOption nettyBundle() {
61- return mavenBundle("io.netty", "netty", "3.9.0.Final");
60+ private CompositeOption nettyBundles() {
61+ final String nettyVersion = "4.0.27.Final";
62+ return new CompositeOption() {
63+
64+ @Override public Option[] getOptions() {
65+ return options(
66+ mavenBundle("io.netty", "netty-buffer", nettyVersion),
67+ mavenBundle("io.netty", "netty-codec", nettyVersion),
68+ mavenBundle("io.netty", "netty-common", nettyVersion),
69+ mavenBundle("io.netty", "netty-handler", nettyVersion),
70+ mavenBundle("io.netty", "netty-transport", nettyVersion)
71+ );
72+ }
73+ };
6274 }
6375
6476 private CompositeOption defaultOptions() {
@@ -92,7 +104,7 @@
92104 return options(
93105 driverBundle(),
94106 guavaBundle(),
95- nettyBundle(),
107+ nettyBundles(),
96108 defaultOptions()
97109 );
98110 }
@@ -101,7 +113,7 @@
101113 public Option[] guava15Config() {
102114 return options(
103115 driverBundle(),
104- nettyBundle(),
116+ nettyBundles(),
105117 guavaBundle().version("15.0"),
106118 defaultOptions()
107119 );
@@ -111,7 +123,7 @@
111123 public Option[] guava16Config() {
112124 return options(
113125 driverBundle(),
114- nettyBundle(),
126+ nettyBundles(),
115127 guavaBundle().version("16.0.1"),
116128 defaultOptions()
117129 );
@@ -121,7 +133,7 @@
121133 public Option[] guava17Config() {
122134 return options(
123135 driverBundle(),
124- nettyBundle(),
136+ nettyBundles(),
125137 guavaBundle().version("17.0"),
126138 defaultOptions()
127139 );
@@ -131,7 +143,7 @@
131143 public Option[] guava18Config() {
132144 return options(
133145 driverBundle(),
134- nettyBundle(),
146+ nettyBundles(),
135147 guavaBundle().version("18.0"),
136148 defaultOptions()
137149 );
modified driver-examples/osgi/src/test/resources/log4j.properties +16 −0
@@ -1,3 +1,19 @@
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+
117 # Set root logger level to DEBUG and its only appender to A1.
218 log4j.rootLogger=INFO, A1
319
modified driver-examples/pom.xml +40 −11
@@ -1,15 +1,19 @@
11 <!--
2- Licensed under the Apache License, Version 2.0 (the "License");
3- you may not use this file except in compliance with the License.
4- You may obtain a copy of the License at
5-
6- http://www.apache.org/licenses/LICENSE-2.0
7-
8- Unless required by applicable law or agreed to in writing, software
9- distributed under the License is distributed on an "AS IS" BASIS,
10- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11- See the License for the specific language governing permissions and
12- limitations under the License. See accompanying LICENSE file.
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
1317 -->
1418 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
1519 <modelVersion>4.0.0</modelVersion>
@@ -24,6 +28,10 @@
2428 <description>A collection of examples to demonstrate DataStax Java Driver for Apache Cassandra.</description>
2529 <url>https://github.com/datastax/java-driver</url>
2630
31+ <properties>
32+ <main.basedir>${project.parent.basedir}</main.basedir>
33+ </properties>
34+
2735 <modules>
2836 <module>stress</module>
2937 <module>osgi</module>
@@ -51,4 +59,25 @@
5159 <organization>DataStax</organization>
5260 </developer>
5361 </developers>
62+
63+ <build>
64+ <plugins>
65+ <plugin>
66+ <groupId>org.apache.maven.plugins</groupId>
67+ <artifactId>maven-install-plugin</artifactId>
68+ <version>2.5.1</version>
69+ <configuration>
70+ <skip>true</skip>
71+ </configuration>
72+ </plugin>
73+ <plugin>
74+ <groupId>org.apache.maven.plugins</groupId>
75+ <artifactId>maven-deploy-plugin</artifactId>
76+ <version>2.8.1</version>
77+ <configuration>
78+ <skip>true</skip>
79+ </configuration>
80+ </plugin>
81+ </plugins>
82+ </build>
5483 </project>
modified driver-examples/stress/pom.xml +19 −11
@@ -1,15 +1,19 @@
11 <!--
2- Licensed under the Apache License, Version 2.0 (the "License");
3- you may not use this file except in compliance with the License.
4- You may obtain a copy of the License at
5-
6- http://www.apache.org/licenses/LICENSE-2.0
7-
8- Unless required by applicable law or agreed to in writing, software
9- distributed under the License is distributed on an "AS IS" BASIS,
10- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11- See the License for the specific language governing permissions and
12- limitations under the License. See accompanying LICENSE file.
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
1317 -->
1418 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
1519 <modelVersion>4.0.0</modelVersion>
@@ -24,6 +28,10 @@
2428 <description>A stress test example for DataStax Java Driver for Apache Cassandra.</description>
2529 <url>https://github.com/datastax/java-driver</url>
2630
31+ <properties>
32+ <main.basedir>${project.parent.parent.basedir}</main.basedir>
33+ </properties>
34+
2735 <dependencies>
2836 <dependency>
2937 <groupId>com.datastax.cassandra</groupId>
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/AsynchronousConsumer.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/BlockingConsumer.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Consumer.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/QueryGenerator.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Reporter.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Stress.java +1 −1
@@ -1,5 +1,5 @@
11 /*
2- * Copyright (C) 2012-2014 DataStax Inc.
2+ * Copyright (C) 2012-2015 DataStax Inc.
33 *
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
modified features/README.md +15 −5
@@ -1,7 +1,17 @@
11 ## Features
22
3-This documentation is a work in progress. Use the "Read More" menu on the right hand side to browse currently documented features.
4-
5-You can also refer to the
6-[user documentation](http://www.datastax.com/documentation/developer/java-driver/2.1/java-driver/whatsNew2.html)
7-on the DataStax website.
No newline at the end of the file
3+This part of the documentation is organized into sub-sections covering
4+specific topics.
5+
6+If you're reading this from the [generated HTML documentation on
7+github.io](http://datastax.github.io/java-driver/), use the "Read More"
8+menu on the right hand side. If you're [browsing the source files on
9+github.com](https://github.com/datastax/java-driver/tree/2.1/features),
10+simply navigate to each sub-directory.
11+
12+This is a work in progress: new sections will be added to cover existing
13+features or document new ones.
14+
15+You can also find more help in the legacy
16+[user documentation](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html)
17+on the DataStax website.
modified features/address_resolution/README.md +31 −22
@@ -10,37 +10,42 @@
1010 (for instance, it might be a private IP, but some clients may have to use a public IP, or
1111 go through a router).
1212
13-### The `AddressTranslater` interface
13+### The [AddressTranslater][at] interface
1414
1515 This interface allows you to deal with such cases, by transforming the address sent by a
1616 Cassandra node to another address to be used by the driver for connection.
1717
18- public class MyAddressTranslater implements AddressTranslater {
19- public InetSocketAddress translate(InetSocketAddress address) {
20- ... // your custom translation logic
21- }
18+```java
19+public class MyAddressTranslater implements AddressTranslater {
20+ public InetSocketAddress translate(InetSocketAddress address) {
21+ ... // your custom translation logic
2222 }
23+}
2324
24- Cluster cluster = Cluster.builder()
25- .addContactPoint("1.2.3.4")
26- .withAddressTranslater(new MyAddressTranslater())
27- .build();
25+Cluster cluster = Cluster.builder()
26+ .addContactPoint("1.2.3.4")
27+ .withAddressTranslater(new MyAddressTranslater())
28+ .build();
29+```
2830
2931 Notes:
3032
3133 * the contact points provided while creating the `Cluster` are not translated, only addresses
3234 retrieved from or sent by Cassandra nodes are;
33-* you might want to implement `CloseableAddressTranslater` if your implementation has state that
34- should be cleaned up when the `Cluster` shuts down. This is provided as a separate interface for
35- historical reasons, the `close()` method will be merged in `AddressTranslater` in a future
36- release.
37-
35+* you might want to implement [CloseableAddressTranslater][cat] if your
36+ implementation has state that should be cleaned up when the `Cluster`
37+ shuts down. This is provided as a separate interface for historical
38+ reasons, the `close()` method will be merged in `AddressTranslater` in a
39+ future release.
40+
41+[at]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/AddressTranslater.html
42+[cat]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/CloseableAddressTranslater.html
3843
3944 ### EC2 multi-region
4045
41-`EC2MultiRegionAddressTranslater` is provided out of the box. It helps optimize network costs when
42-your infrastructure (both Cassandra nodes *and* clients) is distributed across multiple Amazon EC2
43-regions:
46+[EC2MultiRegionAddressTranslater][ec2] is provided out of the box. It
47+helps optimize network costs when your infrastructure (both Cassandra
48+nodes *and* clients) is distributed across multiple Amazon EC2 regions:
4449
4550 * a client communicating with a Cassandra node *in the same EC2 region* should use the node's
4651 private IP (which is less expensive);
@@ -48,11 +53,15 @@
4853
4954 To use this implementation, provide an instance when initializing the `Cluster`:
5055
51- Cluster cluster = Cluster.builder()
52- .addContactPoint("1.2.3.4")
53- .withAddressTranslater(new EC2MultiRegionAddressTranslater())
54- .build();
56+```java
57+Cluster cluster = Cluster.builder()
58+ .addContactPoint("1.2.3.4")
59+ .withAddressTranslater(new EC2MultiRegionAddressTranslater())
60+ .build();
61+```
5562
5663 This class performs a reverse DNS lookup of the origin address, to find the domain name of the
5764 target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the
58-private/public switch automatically based on location.
No newline at the end of the file
65+private/public switch automatically based on location.
66+
67+[ec2]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.html
added features/logging/README.md +304 −0
@@ -0,0 +1,304 @@
1+## Logging
2+
3+### Setup
4+
5+DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages;
6+SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete
7+implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend.
8+
9+The driver itself does not attempt to configure any concrete logging framework.
10+It is up to client applications using the driver to correctly set up their classpath and
11+runtime configuration to be able to capture log messages emitted by the driver.
12+Concretely, client applications need to provide, at runtime, a *binding* to any logging framework
13+of their choice that is [compatible with SLF4J](http://www.slf4j.org/manual.html#swapping).
14+
15+If your application is built with Maven, this usually involves adding one (runtime) dependency to your POM file.
16+For example, if you intend to use [Logback](http://logback.qos.ch), add the following dependency:
17+
18+```xml
19+<dependency>
20+ <groupId>ch.qos.logback</groupId>
21+ <artifactId>logback-classic</artifactId>
22+ <version>1.1.3</version>
23+</dependency>
24+```
25+
26+If you are using Log4J 1.2 instead, add the following dependency:
27+
28+```xml
29+<dependency>
30+ <groupId>org.slf4j</groupId>
31+ <artifactId>slf4j-log4j12</artifactId>
32+ <version>1.7.12</version>
33+</dependency>
34+```
35+
36+Check [SLF4J's documentation](http://www.slf4j.org/manual.html#projectDep) for examples for
37+other logging frameworks, and for troubleshooting dependency resolution problems.
38+
39+### Configuration
40+
41+Each logging framework has its own configuration rules, but all of them provide
42+different levels (DEBUG, INFO, WARN, ERROR...), different *loggers* or *categories*
43+(messages from different categories or loggers can be filtered out separately or printed out
44+differently), and different *appenders* (message receptacles such as the standard console,
45+the error console, a file on disk, a socket...).
46+
47+Check your logging framework documentation for more information about how to properly configure it.
48+You can also find some configuration examples below.
49+
50+### Useful loggers
51+
52+When debugging the Java driver, the following loggers could be particularly useful
53+and provide hints about what's going wrong.
54+
55+* `com.datastax.driver.core.Cluster`
56+ * ERROR
57+ * Authentication errors
58+ * Unexpected errors when handling events, reconnecting, refreshing schemas
59+ * Unexpected events
60+ * WARN
61+ * Cluster name mismatches
62+ * Unreachable contact points
63+ * Unsupported protocol versions
64+ * Schema disagreements
65+ * Ignored notifications due to high contention
66+ * INFO
67+ * Hosts added or removed
68+ * DEBUG
69+ * Cluster lifecycle (start, shutdown)
70+ * Event delivery notifications (schema changes, topology changes)
71+ * Topology change events: hosts Up / Down / Added / Removed
72+ * Hosts being ignored
73+ * Protocol version negotiation
74+ * Reconnection attempts
75+ * Schema metadata refreshes
76+ * TRACE
77+ * Connection pools lifecycle (create, renew, refresh)
78+* `com.datastax.driver.core.Session`
79+ * ERROR
80+ * Errors related to connection pools
81+ * WARN
82+ * Problems related to connection pools
83+ * DEBUG
84+ * Connection pools lifecycle (create, renew, refresh)
85+* `com.datastax.driver.core.RequestHandler`
86+ * ERROR
87+ * Unexpected errors preparing queries
88+ * Queries sent to a bootstrapping host
89+ * Unexpected server errors
90+ * WARN
91+ * Queries sent to an overloaded host
92+ * INFO
93+ * Unprepared queries
94+ * DEBUG
95+ * Retry attempts
96+ * TRACE
97+ * Host currently being queried
98+* `com.datastax.driver.core.Connection`
99+ * WARN
100+ * Problem setting keyspace
101+ * Errors closing Netty channel
102+ * DEBUG
103+ * Connection lifecycle (open, close, defunct)
104+ * Error connecting or writing requests
105+ * Heartbeats
106+ * TRACE
107+ * Authentication progress
108+ * Sending requests
109+ * Receiving responses
110+
111+### Logging query latencies
112+
113+Version 2.0.10 of the driver introduces a new feature: the `QueryLogger`.
114+
115+This new API provides clients with the ability to log queries executed by the driver,
116+and especially, it allows client to track slow queries, i.e. queries that take longer to
117+complete than a configured threshold in milliseconds.
118+
119+To turn on this feature, you first need to instantiate and register a `QueryLogger` instance:
120+
121+```java
122+Cluster cluster = ...
123+QueryLogger queryLogger = QueryLogger.builder(cluster)
124+ .withConstantThreshold(...)
125+ .withMaxQueryStringLength(...)
126+.build();
127+cluster.register(queryLogger);
128+```
129+
130+Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide.
131+Besides, you can adjust several parameters such as the maximum query string length to be printed,
132+the maximum number of parameters to print, etc. Refer to the
133+`QueryLogger` [API docs][query_logger] for more information.
134+
135+Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger`
136+uses 3 different loggers:
137+
138+* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds.
139+* `com.datastax.driver.core.QueryLogger.SLOW` : Used to log slow queries, i.e., queries that completed successfully but that took longer than a configurable threshold in milliseconds to complete.
140+* `com.datastax.driver.core.QueryLogger.ERROR`: Used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. Note this this logger will also print the full stack trace of the reported exception.
141+
142+You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries
143+that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above),
144+then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J:
145+
146+```xml
147+ <logger name="com.datastax.driver.core.QueryLogger.SLOW">
148+ <level value="DEBUG"/>
149+ </logger>
150+```
151+
152+The `QueryLogger` would then print messages such as this for every slow query:
153+
154+```
155+DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?;
156+```
157+
158+As you can see, actual query parameters are not logged; if you want them to be printed as well, set the `com.datastax.driver.core.QueryLogger.SLOW` logger
159+to TRACE instead, e.g. with Log4J:
160+
161+```xml
162+ <logger name="com.datastax.driver.core.QueryLogger.SLOW">
163+ <level value="TRACE"/>
164+ </logger>
165+```
166+
167+The `QueryLogger` would then print messages such as this for every slow query:
168+
169+```
170+TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42];
171+```
172+
173+Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters.
174+See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary.
175+
176+#### Constant vs Dynamic thresholds
177+
178+Currently the `QueryLogger` can be configured to track slow queries using either
179+a constant threshold in milliseconds (which is the default behavior), or
180+a dynamic threshold based on per-host latency percentiles, as computed by `PerHostPercentileTracker`.
181+
182+**Dynamic thresholds are still a beta feature as of version 2.0.10: they
183+haven't been extensively tested yet, and the API is still subject to
184+change.**
185+
186+Refer to the `QueryLogger` [API docs][query_logger] for an example of usage.
187+
188+### Performance Tips
189+
190+* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html)
191+and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders
192+that can significantly boost latencies when writing log messages.
193+* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration
194+without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html);
195+Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)).
196+
197+### Logback Example
198+
199+Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!*
200+
201+It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
202+By default, only messages with ERROR level or higher are logged.
203+
204+It also turns on slow query tracing as described above.
205+
206+```xml
207+<?xml version="1.0" encoding="UTF-8"?>
208+<configuration>
209+
210+ <!-- log INFO or higher messages to the console -->
211+ <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
212+ <encoder>
213+ <pattern>%-5p %msg%n</pattern>
214+ </encoder>
215+ </appender>
216+
217+ <!-- log everything to a rolling file -->
218+ <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
219+ <file>driver.log</file>
220+ <encoder>
221+ <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern>
222+ </encoder>
223+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
224+ <!-- daily rollover -->
225+ <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern>
226+ <!-- keep 30 days' worth of history -->
227+ <maxHistory>30</maxHistory>
228+ </rollingPolicy>
229+ </appender>
230+
231+ <!-- use AsyncAppender for lower latencies -->
232+ <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
233+ <appender-ref ref="console" />
234+ <appender-ref ref="file" />
235+ </appender>
236+
237+ <!--
238+ Turn on slow query logging by setting this logger to DEBUG;
239+ set level to TRACE to also log query parameters
240+ -->
241+ <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" />
242+
243+ <root level="ERROR">
244+ <appender-ref ref="async" />
245+ </root>
246+
247+</configuration>
248+```
249+
250+### Log4J Example
251+
252+Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!*
253+
254+It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
255+By default, only messages with ERROR level or higher are logged.
256+
257+It also turns on slow query tracing as described above.
258+
259+```xml
260+<log4j:configuration>
261+
262+ <!-- log INFO or higher messages to the console -->
263+ <appender name="console" class="org.apache.log4j.ConsoleAppender">
264+ <param name="threshold" value="INFO"/>
265+ <layout class="org.apache.log4j.PatternLayout">
266+ <param name="ConversionPattern" value="%-5p %m%n"/>
267+ </layout>
268+ </appender>
269+
270+ <!-- log everything to a rolling file -->
271+ <appender name="file" class="org.apache.log4j.RollingFileAppender">
272+ <param name="file" value="driver.log"/>
273+ <param name="append" value="false"/>
274+ <param name="maxFileSize" value="1GB"/>
275+ <param name="maxBackupIndex" value="10"/>
276+ <layout class="org.apache.log4j.PatternLayout">
277+ <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/>
278+ </layout>
279+ </appender>
280+
281+ <!-- use AsyncAppender for lower latencies -->
282+ <appender name="async" class="org.apache.log4j.AsyncAppender">
283+ <param name="BufferSize" value="500"/>
284+ <appender-ref ref="file"/>
285+ <appender-ref ref="console"/>
286+ </appender>
287+
288+ <!--
289+ Turn on slow query logging by setting this logger to DEBUG;
290+ set level to TRACE to also log query parameters
291+ -->
292+ <logger name="com.datastax.driver.core.QueryLogger.SLOW">
293+ <level value="DEBUG"/>
294+ </logger>
295+
296+ <root>
297+ <priority value="ERROR"/>
298+ <appender-ref ref="async"/>
299+ </root>
300+
301+</log4j:configuration>
302+```
303+
304+[query_logger]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryLogger.html
No newline at the end of the file
added features/metadata/README.md +171 −0
@@ -0,0 +1,171 @@
1+## Metadata
2+
3+The driver maintains global information about the Cassandra cluster it
4+is connected to. It is available via
5+[Cluster#getMetadata()][getMetadata].
6+
7+[getMetadata]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#getMetadata()
8+
9+### Schema metadata
10+
11+Use [getKeyspace(String)][getKeyspace] or [getKeyspaces()][getKeyspaces]
12+to get keyspace-level metadata. From there you can access the keyspace's
13+objects (tables, and UDTs and UDFs if relevant).
14+
15+[getKeyspace]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getKeyspace(java.lang.String)
16+[getKeyspaces]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getKeyspaces()
17+
18+#### Refreshes
19+
20+Schema metadata gets refreshed in the following circumstances:
21+
22+* **schema changes via the driver**: after successfully executing a
23+ schema-altering query (ex: `CREATE TABLE`), the driver waits for
24+ schema agreement (see below), then refreshes the schema.
25+* **third-party schema changes**: if another client (cqlsh, other driver
26+ instance...) changes the schema, the driver gets notified by Cassandra
27+ via a push notification. It refreshes the schema directly (there is no
28+ need to wait for schema agreement since Cassandra has already done it).
29+
30+#### Schema agreement
31+
32+Schema changes need to be propagated to all nodes in the cluster. Once
33+they have settled on a common version, we say that they are in
34+agreement.
35+
36+As explained above, the driver waits for schema agreement after
37+executing a schema-altering query. This is to ensure that subsequent
38+requests (which might get routed to different nodes) see an up-to-date
39+version of the schema.
40+
41+```ditaa
42+ Application Driver Cassandra
43+------+--------------------+------------------+-----
44+ | | |
45+ | CREATE TABLE... | |
46+ |------------------->| |
47+ | | send request |
48+ | |----------------->|
49+ | | |
50+ | | success |
51+ | |<-----------------|
52+ | | |
53+ | /--------------------\ |
54+ | :Wait until all nodes+------>|
55+ | :agree (or timeout) : |
56+ | \--------------------/ |
57+ | | ^ |
58+ | | | |
59+ | | +---------|
60+ | | |
61+ | | refresh schema |
62+ | |----------------->|
63+ | |<-----------------|
64+ | complete query | |
65+ |<-------------------| |
66+ | | |
67+```
68+
69+The schema agreement wait is performed synchronously, so the `execute`
70+call -- or the completion of the `ResultSetFuture` if you use the async
71+API -- will only return after it has completed.
72+
73+The check is implemented by repeatedly querying system tables for the
74+schema version reported by each node, until they all converge to the
75+same value. If that doesn't happen within a given timeout, the driver
76+will give up waiting. The default timeout is 10 seconds, it can be
77+customized when building your cluster:
78+
79+```java
80+Cluster cluster = Cluster.builder()
81+ .addContactPoint("127.0.0.1")
82+ .withMaxSchemaAgreementWaitSeconds(20)
83+ .build();
84+```
85+
86+After executing a statement, you can check whether schema agreement was
87+successful or timed out:
88+
89+```java
90+ResultSet rs = session.execute("CREATE TABLE...");
91+if (rs.getExecutionInfo().isSchemaInAgreement()) {
92+ // schema is in agreement
93+} else {
94+ // schema agreement timed out
95+}
96+```
97+
98+You can also perform an on-demand check at any time:
99+
100+```java
101+if (cluster.getMetadata().checkSchemaAgreement()) {
102+ // schema is in agreement
103+} else {
104+ // schema is not in agreement
105+}
106+```
107+
108+The on-demand check does not retry, it only queries system tables once
109+(so `maxSchemaAgreementWaitSeconds` does not apply). If you need
110+retries, you'll have to schedule them yourself (for example with a
111+custom executor).
112+
113+Check out the API docs for the features in this section:
114+
115+* [withMaxSchemaAgreementWaitSeconds(int)](http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds(int))
116+* [isSchemaInAgreement()](http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement())
117+* [checkSchemaAgreement()](http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#checkSchemaAgreement())
118+
119+
120+### Token metadata
121+
122+This feature is probably of less interest to regular driver users, but
123+it will be useful if you're writing an analytics client on top of the
124+driver.
125+
126+[Metadata][metadata] exposes a number of methods to manipulate tokens
127+and ranges: [getTokenRanges()][getTokenRanges], [getTokenRanges(String
128+keyspace, Host host)][getTokenRanges2], [getReplicas(String keyspace,
129+TokenRange range)][getReplicas], [newToken(String)][newToken] and
130+[newTokenRange(Token start, Token end)][newTokenRange].
131+
132+[TokenRange][TokenRange] provides various operations on ranges
133+(splitting, merging, etc.).
134+
135+Each host exposes its primary tokens as [getTokens()][getTokens].
136+
137+Finally, you can inject tokens in CQL queries with
138+[BoundStatement#setToken][setToken], and retrieve them from results with
139+[Row#getToken][getToken] and [Row#getPartitionKeyToken][getPKToken].
140+
141+As an example, here is how you could compute the splits to partition a
142+job (pseudocode):
143+
144+```
145+metadata = cluster.getMetadata()
146+for range : metadata.getTokenRanges() {
147+ hosts = metadata.getReplicas(keyspace, range)
148+ int n = estimateNumberOfSplits() // more on that below
149+ for split : range.splitEvenly(n)
150+ // pick a host to process split
151+}
152+```
153+
154+For `estimateNumberOfSplits`, you need a way to estimate the total
155+number of partition keys (this is what analytics clients would
156+traditionally do with the Thrift operation `describe_splits_ex`).
157+Starting with Cassandra 2.1.5, this information is available in a system
158+table (see
159+[CASSANDRA-7688](https://issues.apache.org/jira/browse/CASSANDRA-7688)).
160+
161+[metadata]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html
162+[getTokenRanges]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getTokenRanges()
163+[getTokenRanges2]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getTokenRanges(java.lang.String,%20com.datastax.driver.core.Host)
164+[getReplicas]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getReplicas(java.lang.String,%20com.datastax.driver.core.TokenRange)
165+[newToken]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#newToken(java.lang.String)
166+[newTokenRange]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metadata.html#newTokenRange(com.datastax.driver.core.Token,%20com.datastax.driver.core.Token)
167+[TokenRange]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/TokenRange.html
168+[getTokens]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Host.html#getTokens()
169+[setToken]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/BoundStatement.html#setToken(int,%20com.datastax.driver.core.Token)
170+[getToken]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Row.html#getToken(int)
171+[getPKToken]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Row.html#getPartitionKeyToken()
added features/paging/README.md +175 −0
@@ -0,0 +1,175 @@
1+## Paging
2+
3+When a query returns many rows, it would be inefficient to return them
4+as a single response message. Instead, the driver breaks the results
5+into *pages* which get returned as they are needed.
6+
7+### Setting the fetch size
8+
9+The *fetch size* specifies how many rows will be returned at once by
10+Cassandra (in other words, it's the size of each page).
11+
12+You can set a default fetch size globally for a `Cluster` instance:
13+
14+```java
15+// At initialization:
16+Cluster cluster = Cluster.builder()
17+ .addContactPoint("127.0.0.1")
18+ .withQueryOptions(new QueryOptions().setFetchSize(2000))
19+ .build();
20+
21+// Or at runtime:
22+cluster.getConfiguration().getQueryOptions().setFetchSize(2000);
23+```
24+
25+The fetch size can also be set on a statement:
26+
27+```java
28+Statement statement = new SimpleStatement("your query");
29+statement.setFetchSize(2000);
30+```
31+
32+If the fetch size is set on a statement, it will take precedence;
33+otherwise, the cluster-wide value (which defaults to 5000) will be used.
34+
35+Note that setting a fetch size doesn't mean that Cassandra will always
36+return the exact number of rows, it is possible that it returns slightly
37+more or less results.
38+
39+### Result set iteration
40+
41+The fetch size limits the number of results that are returned in one
42+page; if you iterate past that, the driver will run background queries
43+to fetch subsequent pages. Here's an example with a fetch size of 20:
44+
45+```ditaa
46+ client Session Cassandra
47+ --+--------------+---------------------------------+-----
48+ |execute(query)| |
49+ |------------->| |
50+ | | query rows 1 to 20 |
51+ | |-------------------------------->|
52+ | | |
53+ | |create |
54+ | |------>ResultSet |
55+ | | |
56++-----+--------+-----------------+-+ |
57+|For i in 1..20| | | |
58++--------------+ | | |
59+| | get next row | | |
60+| |------------------------->| | |
61+| | row i | | |
62+| |<-------------------------| | |
63+| | | | |
64++-----+--------------------------+-+ |
65+ | | |
66+ | | |
67+ | get next row | |
68+ |------------------------->| |
69+ | | query rows 21 to 40 |
70+ | |-------------------->|
71+ | row 21 | |
72+ |<------------------------ | |
73+```
74+
75+By default, the background fetch happens at the last moment, when there
76+are no more "local" rows available. If you need finer control, the
77+[ResultSet][result_set] interface provides the following methods:
78+
79+* `getAvailableWithoutFetching()` and `isFullyFetched()` to check the
80+ current state;
81+* `fetchMoreResults()` to force a page fetch.
82+
83+Here's how you could use these methods to pre-fetch the next page in
84+advance, in order to avoid the performance hit at the end of each page:
85+
86+```java
87+ResultSet rs = session.execute("your query");
88+for (Row row : rs) {
89+ if (rs.getAvailableWithoutFetching() == 100 && !rs.isFullyFetched())
90+ rs.fetchMoreResults(); // this is asynchronous
91+ // Process the row ...
92+ System.out.println(row);
93+}
94+```
95+
96+### Manual paging
97+
98+Sometimes it is convenient to save the paging state in order to restore
99+it later. For example, consider a stateless web service that displays a
100+list of results with a link to the next page. When the user clicks that
101+link, we want to run the exact same query, except that the iteration
102+should start where we stopped on the previous page.
103+
104+To do so, the driver exposes a [PagingState][paging_state] object that represents
105+where we were in the result set when the last page was fetched:
106+
107+```java
108+ResultSet resultSet = session.execute("your query");
109+// iterate the result set...
110+PagingState pagingState = resultSet.getExecutionInfo().getPagingState();
111+```
112+
113+This object can be serialized to a `String` or a byte array:
114+
115+```java
116+String string = pagingState.toString();
117+byte[] bytes = pagingState.toBytes();
118+```
119+
120+This serialized form can be saved in some form of persistent storage to
121+be reused later. In our web service example, we would probably save the
122+string version as a query parameter in the URL to the next page
123+(`http://myservice.com/results?page=<...>`). When that value is
124+retrieved later, we can deserialize it and reinject it in a statement:
125+
126+```java
127+PagingState pagingState = PagingState.fromString(string);
128+Statement st = new SimpleStatement("your query");
129+st.setPagingState(pagingState);
130+ResultSet rs = session.execute(st);
131+```
132+
133+Note that the paging state can only be reused with the exact same
134+statement (same query string, same parameters). Also, it is an opaque
135+value that is only meant to be collected, stored an re-used. If you try
136+to modify its contents or reuse it with a different statement, the
137+driver will raise an error.
138+
139+Putting it all together, here's a more comprehensive example
140+implementation for our web service:
141+
142+```java
143+final int RESULTS_PER_PAGE = 100;
144+
145+Statement st = new SimpleStatement("your query");
146+st.setFetchSize(RESULTS_PER_PAGE);
147+
148+String requestedPage = extractPagingStateStringFromURL();
149+// This will be absent for the first page
150+if (requestedPage != null) {
151+ st.setPagingState(
152+ PagingState.fromString(requestedPage));
153+}
154+
155+ResultSet rs = session.execute(st);
156+PagingState nextPage = rs.getExecutionInfo().getPagingState();
157+
158+// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might
159+// have not respected it, or we might be at the end of the result set
160+int remaining = rs.getAvailableWithoutFetching();
161+for (Row row : rs) {
162+ renderInResponse(row);
163+ if (--remaining == 0) {
164+ break;
165+ }
166+}
167+
168+// This will be null if there are no more pages
169+if (nextPage != null) {
170+ renderNextPageLink(nextPage.toString());
171+}
172+```
173+
174+[result_set]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ResultSet.html
175+[paging_state]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PagingState.html
No newline at the end of the file
added features/pooling/README.md +187 −0
@@ -0,0 +1,187 @@
1+## Connection pooling
2+
3+### Basics
4+
5+The driver communicates with Cassandra over TCP, using the Cassandra
6+binary protocol. This protocol is asynchronous, which allows each TCP
7+connection to handle multiple simultaneous requests:
8+
9+* when a query gets executed, a *stream id* gets assigned to it. It is a
10+ unique identifier for the current connection;
11+* the driver writes a request containing the stream id and the query on
12+ the connection, and then proceeds without waiting for the response (if
13+ you're using the asynchronous API, this is when the driver will send you
14+ back a [ResultSetFuture][result_set_future]).
15+ Once the request has been written to the
16+ connection, we say that it is *in flight*;
17+* at some point, Cassandra will send back a response on the connection.
18+ This response also contains the stream id, which allows the driver to
19+ trigger a callback that will complete the corresponding query (this is
20+ the point where your `ResultSetFuture` will get completed).
21+
22+Version 2.0.x of the driver uses version 1 of the binary protocol when
23+connecting to Cassandra 1.2, and version 2 when connecting to Cassandra
24+2.0 or higher. In both cases, that gives you **128 stream ids per
25+connection**.
26+
27+Because the number of stream ids per connection is limited, we use a
28+pool with multiple connections to each host. **For each `Session`
29+object, there is one connection pool per connected host**. The number of
30+connections per pool depends on the configuration, this will be
31+described in the next section.
32+
33+```ditaa
34++-------+1 n+-------+1 n+----+1 n+----------+1 128+-------+
35+|Cluster+-----+Session+-----+Pool+-----+Connection+-------+Request+
36++-------+ +-------+ +----+ +----------+ +-------+
37+```
38+
39+### Configuring the connection pool
40+
41+Connections pools are configured with a [PoolingOptions][pooling_options] object, which
42+is global to a `Cluster` instance. You can pass that object when
43+building the cluster:
44+
45+```java
46+PoolingOptions poolingOptions = new PoolingOptions();
47+// customize options...
48+
49+Cluster cluster = Cluster.builder()
50+ .withContactPoints("127.0.0.1")
51+ .withPoolingOptions(poolingOptions)
52+ .build();
53+```
54+
55+Most options can also be changed at runtime. If you don't have a
56+reference to the `PoolingOptions` instance, here's how you can get it:
57+
58+```java
59+PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
60+// customize options...
61+```
62+
63+#### Pool size
64+
65+Connection pools have a variable size, which gets adjusted automatically
66+depending on the current load. There will always be at least a *core*
67+number of connections, and at most a *max* number. These values can be
68+configured independently by host *distance* (the distance is determined
69+by your [LoadBalancingPolicy][lbp], and will generally indicate whether a
70+host is in the same datacenter or not).
71+
72+```java
73+poolingOptions
74+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 4)
75+ .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
76+ .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
77+ .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
78+```
79+
80+Note: the setters always enforce core <= max, which can get annoying
81+when you try to set both values at once.
82+[JAVA-662](https://datastax-oss.atlassian.net/browse/JAVA-662) will
83+address this issue.
84+
85+[PoolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold][msrpct]
86+has a slightly misleading name: it does not limit the number of requests per
87+connection, but only determines the threshold that triggers the creation
88+of a new connection when the pool is not at its maximum capacity. In
89+general, you shouldn't have to change its default value.
90+
91+
92+#### Heartbeat
93+
94+If connections stay idle for too long, they might be dropped by
95+intermediate network devices (routers, firewalls...). Normally, TCP
96+keepalive should take care of this; but tweaking low-level keepalive
97+settings might be impractical in some environments.
98+
99+The driver provides application-side keepalive in the form of a
100+connection heartbeat: when a connection has been idle for a given amount
101+of time, the driver will simulate activity by writing a dummy request to
102+it.
103+
104+This feature is enabled by default. The default heartbeat interval is 30
105+seconds, it can be customized with the following method:
106+
107+```java
108+poolingOptions.setHeartbeatIntervalSeconds(60);
109+```
110+
111+If it gets changed at runtime, only connections created after that will
112+use the new interval. Most users will want to do this at startup.
113+
114+The heartbeat interval should be set higher than
115+[SocketOptions.readTimeoutMillis][rtm]:
116+the read timeout is the maximum time that the driver waits for a regular
117+query to complete, therefore the connection should not be considered
118+idle before it has elapsed.
119+
120+To disable heartbeat, set the interval to 0.
121+
122+Implementation note: the dummy request sent by heartbeat is an
123+[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
124+message.
125+
126+
127+#### Acquisition timeout
128+
129+When the driver tries to send a request to a host, it will first try to
130+acquire a connection from this host's pool. If the pool is busy (i.e.
131+all connections are already handling their maximum number of in flight
132+requests), the client thread will block for a while, until a connection
133+becomes available (note that this will block even if you're using the
134+asynchronous API, like [Session.executeAsync][exec_async]).
135+
136+The time that the driver blocks is controlled by
137+[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
138+available after this timeout, the driver will try the next host.
139+
140+For some applications, blocking is not acceptable, and it is preferable
141+to fail fast if the request cannot be fulfilled. If that's your case,
142+set the pool timeout to 0. If all hosts are busy, you will get a
143+[NoHostAvailableException][nhae] (if you look at the exception's details, you
144+will see a `java.util.concurrent.TimeoutException` for each host).
145+
146+
147+### Monitoring and tuning the pool
148+
149+The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
150+a simple example that will print the number of open connections, active
151+requests, and maximum capacity for each host, every 5 seconds:
152+
153+```java
154+ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
155+scheduled.scheduleAtFixedRate(new Runnable() {
156+ @Override
157+ public void run() {
158+ Session.State state = session.getState();
159+ for (Host host : state.getConnectedHosts()) {
160+ int connections = state.getOpenConnections(host);
161+ int inFlightQueries = state.getInFlightQueries(host);
162+ System.out.printf("%s connections=%d current load=%d max load=%d%n",
163+ host, connections, inFlightQueries, connections * 128);
164+ }
165+ }
166+}, 5, 5, TimeUnit.SECONDS);
167+```
168+
169+In real life, you'll probably want something more sophisticated, like
170+exposing a JMX MBean or sending the data to your favorite monitoring
171+tool.
172+
173+If you find that the current load stays close or equal to the maximum
174+load at all time, it's a sign that your connection pools are saturated
175+and you should raise the max connections per host. On the other hand, if
176+the load is often less than core * 128, your pools are underused and you
177+could get away with less core connections.
178+
179+[result_set_future]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ResultSetFuture.html
180+[pooling_options]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html
181+[lbp]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
182+[msrpct]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
183+[rtm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
184+[exec_async]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
185+[ptm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
186+[nhae]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
187+[get_state]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#getState()
No newline at the end of the file
modified features/shaded_jar/README.md +39 −35
@@ -8,44 +8,48 @@
88 version of the JAR, which bundles the Netty classes under a different
99 package name:
1010
11- <dependency>
12- <groupId>${project.groupId}</groupId>
13- <artifactId>cassandra-driver-core</artifactId>
14- <version>2.1.5</version>
15- <classifier>shaded</classifier>
16- <!-- Because the shaded JAR uses the original POM, you still need
17- to exclude this dependency explicitly: -->
18- <exclusions>
19- <exclusion>
20- <groupId>io.netty</groupId>
21- <artifactId>*</artifactId>
22- </exclusion>
23- </exclusions>
24- </dependency>
11+```xml
12+<dependency>
13+ <groupId>${project.groupId}</groupId>
14+ <artifactId>cassandra-driver-core</artifactId>
15+ <version>2.1.5</version>
16+ <classifier>shaded</classifier>
17+ <!-- Because the shaded JAR uses the original POM, you still need
18+ to exclude this dependency explicitly: -->
19+ <exclusions>
20+ <exclusion>
21+ <groupId>io.netty</groupId>
22+ <artifactId>*</artifactId>
23+ </exclusion>
24+ </exclusions>
25+</dependency>
26+```
2527
2628 If you also use the mapper, you need to remove its dependency to the
2729 non-shaded JAR:
2830
29- <dependency>
31+```xml
32+<dependency>
33+ <groupId>com.datastax.cassandra</groupId>
34+ <artifactId>cassandra-driver-core</artifactId>
35+ <version>2.1.5</version>
36+ <classifier>shaded</classifier>
37+ <exclusions>
38+ <exclusion>
39+ <groupId>io.netty</groupId>
40+ <artifactId>*</artifactId>
41+ </exclusion>
42+ </exclusions>
43+</dependency>
44+<dependency>
45+ <groupId>com.datastax.cassandra</groupId>
46+ <artifactId>cassandra-driver-mapping</artifactId>
47+ <version>2.1.5</version>
48+ <exclusions>
49+ <exclusion>
3050 <groupId>com.datastax.cassandra</groupId>
3151 <artifactId>cassandra-driver-core</artifactId>
32- <version>2.1.5</version>
33- <classifier>shaded</classifier>
34- <exclusions>
35- <exclusion>
36- <groupId>io.netty</groupId>
37- <artifactId>*</artifactId>
38- </exclusion>
39- </exclusions>
40- </dependency>
41- <dependency>
42- <groupId>com.datastax.cassandra</groupId>
43- <artifactId>cassandra-driver-mapping</artifactId>
44- <version>2.1.5</version>
45- <exclusions>
46- <exclusion>
47- <groupId>com.datastax.cassandra</groupId>
48- <artifactId>cassandra-driver-core</artifactId>
49- </exclusion>
50- </exclusions>
51- </dependency>
52+ </exclusion>
53+ </exclusions>
54+</dependency>
55+```
No newline at the end of the file
added features/speculative_execution/README.md +342 −0
@@ -0,0 +1,342 @@
1+## Speculative query execution
2+
3+Sometimes a Cassandra node might be experiencing difficulties (ex: long
4+GC pause) and take longer than usual to reply. Queries sent to that node
5+will experience bad latency.
6+
7+One thing we can do to improve that is pre-emptively start a second
8+execution of the query against another node, before the first node has
9+replied or errored out. If that second node replies faster, we can send
10+the response back to the client (we also cancel the first query):
11+
12+```ditaa
13+client driver exec1 exec2
14+--+----------------+--------------+------+---
15+ | execute(query) |
16+ |--------------->|
17+ | | query host1
18+ | |------------->|
19+ | | |
20+ | | |
21+ | | query host2
22+ | |-------------------->|
23+ | | | |
24+ | | | |
25+ | | host2 replies |
26+ | |<--------------------|
27+ | complete | |
28+ |<---------------| |
29+ | | cancel |
30+ | |------------->|
31+```
32+
33+Or the first node could reply just after the second execution was
34+started. In this case, we cancel the second execution. In other words,
35+whichever node replies faster "wins" and completes the client query:
36+
37+```ditaa
38+client driver exec1 exec2
39+--+----------------+--------------+------+---
40+ | execute(query) |
41+ |--------------->|
42+ | | query host1
43+ | |------------->|
44+ | | |
45+ | | |
46+ | | query host2
47+ | |-------------------->|
48+ | | | |
49+ | | | |
50+ | | host1 replies| |
51+ | |<-------------| |
52+ | complete | |
53+ |<---------------| |
54+ | | cancel |
55+ | |-------------------->|
56+```
57+
58+Speculative executions are **disabled** by default. The following
59+sections cover the practical details and how to enable them.
60+
61+### Query idempotence
62+
63+One important aspect to consider is whether queries are idempotent, i.e.
64+whether they can be applied multiple times without changing the result
65+beyond the initial application. **If a query is not idempotent, the
66+driver will never schedule speculative executions for it**, because
67+there is no way to guarantee that only one node will apply the mutation.
68+
69+As of Cassandra 2.1.4, the only queries that are *not* idempotent are:
70+
71+* counter operations;
72+* prepending or appending to a list column;
73+* using non-idempotent CQL functions, like `now()` or `uuid()`.
74+
75+In the driver, this is determined by
76+[Statement#isIdempotent()][isIdempotent]. Unfortunately, the driver
77+doesn't parse query strings, so in most cases it has no information
78+about what the query actually does. Therefore:
79+
80+* **`Statement#isIdempotent()` is only computed automatically for
81+ statements built with [QueryBuilder][QueryBuilder]**. Note that there
82+ is a known issue in 2.0.10 where calls to `now()` or `uuid()` are not
83+ taken into account (see
84+ [JAVA-733](https://datastax-oss.atlassian.net/browse/JAVA-733)). If
85+ you're using these CQL functions with built statements, force
86+ idempotence to `false` manually (see below);
87+* **for all other types of statements, it defaults to `false`.** You'll
88+ need to set it manually, with one of the mechanism described below.
89+
90+You can override the value on each statement:
91+
92+```java
93+Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1");
94+s.setIdempotent(true);
95+```
96+
97+Note that this will also work for built statements (and override the
98+computed value).
99+
100+Additionally, if you know for a fact that your application does not use
101+any of the non-idempotent CQL queries listed above, you can change the
102+default cluster-wide:
103+
104+```java
105+// Make all statements idempotent by default:
106+cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true);
107+```
108+
109+[isIdempotent]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Statement.html#isIdempotent()
110+[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/querybuilder/QueryBuilder.html
111+
112+### Enabling speculative executions
113+
114+Speculative executions are controlled by an instance of
115+[SpeculativeExecutionPolicy][sep] provided when initializing the
116+`Cluster`. This policy defines the threshold after which a new
117+speculative execution will be triggered.
118+
119+[sep]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
120+
121+Two implementations are provided with the driver:
122+
123+#### [ConstantSpeculativeExecutionPolicy][csep]
124+
125+This simple policy uses a constant threshold:
126+
127+```java
128+Cluster cluster = Cluster.builder()
129+ .addContactPoint("127.0.0.1")
130+ .withSpeculativeExecutionPolicy(
131+ new ConstantSpeculativeExecutionPolicy(
132+ 500, // delay before a new execution is launched
133+ 2 // maximum number of executions
134+ ))
135+ .build();
136+```
137+
138+Given the above configuration, an idempotent query would be handled this
139+way:
140+
141+* start the initial execution at t0;
142+* if no response has been received at t0 + 500 milliseconds, start a
143+ speculative execution on another node;
144+* if no response has been received at t0 + 1000 milliseconds, start
145+ another speculative execution on a third node.
146+
147+[csep]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html
148+
149+#### [PercentileSpeculativeExecutionPolicy][psep]
150+
151+This policy sets the threshold at a given latency percentile for the
152+current host, based on recent statistics.
153+
154+**As of 2.0.10, this class is provided as a beta preview: it hasn't been
155+extensively tested yet, and the API is still subject to change.**
156+
157+First and foremost, make sure that the [HdrHistogram][hdr] library (used
158+under the hood to collect latencies) is in your classpath. It's defined
159+as an optional dependency in the driver's POM, so you'll need to
160+explicitly depend on it:
161+
162+```xml
163+<dependency>
164+ <groupId>org.hdrhistogram</groupId>
165+ <artifactId>HdrHistogram</artifactId>
166+ <version>2.1.4</version>
167+</dependency>
168+```
169+
170+Then create an instance of [PerHostPercentileTracker][phpt] that will collect
171+latency statistics for your `Cluster`:
172+
173+```java
174+// There are more options than shown here, please refer to the API docs
175+// for more information
176+PerHostPercentileTracker tracker = PerHostPercentileTracker
177+ .builderWithHighestTrackableLatencyMillis(15000)
178+ .build();
179+```
180+
181+Create an instance of the policy with the tracker, and pass it to your
182+cluster:
183+
184+```java
185+PercentileSpeculativeExecutionPolicy policy =
186+ new PercentileSpeculativeExecutionPolicy(
187+ tracker,
188+ 99.0, // percentile
189+ 2); // maximum number of executions
190+
191+Cluster cluster = Cluster.builder()
192+ .addContactPoint("127.0.0.1")
193+ .withSpeculativeExecutionPolicy(policy)
194+ .build();
195+```
196+
197+Finally, don't forget to register your tracker with the cluster (the
198+policy does not do this itself):
199+
200+```java
201+cluster.register(tracker);
202+```
203+
204+Note that `PerHostPercentileTracker` may also be used with a slow query
205+logger (see the [Logging](../logging/) section). In that case, you would
206+create a single tracker object and share it with both components.
207+
208+[psep]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html
209+[hdr]: http://hdrhistogram.github.io/HdrHistogram/
210+[phpt]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PerHostPercentileTracker.html
211+
212+#### Using your own
213+
214+As with all policies, you are free to provide your own by implementing
215+`SpeculativeExecutionPolicy`.
216+
217+### How speculative executions affect retries
218+
219+Regardless of speculative executions, the driver has a retry mechanism:
220+
221+* on an internal error, it will try the next host;
222+* when the consistency level could not be reached (`unavailable` error
223+ or read or write timeout), it will delegate the decision to
224+ [RetryPolicy][retry_policy], which might trigger a retry on the same
225+ host.
226+
227+Turning speculative executions on doesn't change this behavior. Each
228+parallel execution will trigger retries independently:
229+
230+```ditaa
231+client driver exec1 exec2
232+--+----------------+--------------+------+---
233+ | execute(query) |
234+ |--------------->|
235+ | | query host1
236+ | |------------->|
237+ | | |
238+ | | unavailable |
239+ | |<-------------|
240+ | |
241+ | |retry at lower CL
242+ | |------------->|
243+ | | |
244+ | | query host2
245+ | |-------------------->|
246+ | | | |
247+ | | server error |
248+ | |<--------------------|
249+ | | |
250+ | | retry on host3
251+ | |-------------------->|
252+ | | | |
253+ | | host1 replies| |
254+ | |<-------------| |
255+ | complete | |
256+ |<---------------| |
257+ | | cancel |
258+ | |-------------------->|
259+```
260+
261+The only impact is that all executions of the same query always share
262+the same query plan, so each host will be used by at most one execution.
263+
264+[retry_policy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/RetryPolicy.html
265+
266+### Tuning and practical details
267+
268+The goal of speculative executions is to improve overall latency (the
269+time between `execute(query)` and `complete` in the diagrams above) at
270+high percentiles. On the flipside, they cause the driver to send more
271+individual requests, so throughput will not necessarily improve.
272+
273+You can monitor how many speculative executions were triggered with the
274+`speculative-executions` metric (exposed in the Java API as
275+[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]).
276+It should only be a few percents of the total number of requests
277+([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]).
278+
279+[se_metric]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions()
280+[request_metric]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metrics.html#getRequestsTimer()
281+
282+#### Stream id exhaustion
283+
284+One side-effect of speculative executions is that many requests are
285+cancelled, which can lead to a phenomenon called *stream id exhaustion*:
286+each TCP connection can handle multiple simultaneous requests,
287+identified by a unique number called *stream id*. When a request gets
288+cancelled, we can't reuse its stream id immediately because we might
289+still receive a response from the server later. If this happens often,
290+the number of available stream ids diminishes over time, and when it
291+goes below a given threshold we close the connection and create a new
292+one. If requests are often cancelled, so will see connections being
293+recycled at a high rate.
294+
295+One way to detect this is to monitor open connections per host
296+([Session.getState().getOpenConnections(host)][session_state]) against
297+TCP connections at the OS level. If open connections stay constant but
298+you see many TCP connections in closing states, you might be running
299+into this issue. Try raising the speculative execution threshold.
300+
301+This problem is more likely to happen with version 2 of the native
302+protocol, because each TCP connection only has 128 stream ids. With
303+version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are
304+32K stream ids per connection, so higher cancellation rates can be
305+sustained. If you're unsure of which native protocol version you're
306+using, you can check with
307+[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version].
308+
309+[session_state]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.State.html
310+[protocol_version]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion()
311+
312+#### Request ordering and client timestamps
313+
314+Another issue that might arise is that you get unintuitive results
315+because of request ordering. Suppose you run the following query with
316+speculative executions enabled:
317+
318+ insert into my_table (k, v) values (1, 1);
319+
320+The first execution is a bit too slow, so a second execution gets
321+triggered. Finally, the first execution completes, so the client code
322+gets back an acknowledgement, and the second execution is cancelled.
323+However, cancelling only means that the driver stops waiting for the
324+server's response, the request could still be "on the wire"; let's
325+assume that this is the case.
326+
327+Now you run the following query, which completes successfully:
328+
329+ delete from my_table where k = 1;
330+
331+But now the second execution of the first query finally reaches its
332+target node, which applies the mutation. The row that you've just
333+deleted is back!
334+
335+The workaround is to use a timestamp with your queries:
336+
337+ insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
338+
339+If you're using native protocol v3, you can also enable client-side
340+timestamps to have this done automatically; see
341+[this blog post](http://www.datastax.com/dev/blog/java-driver-2-1-2-native-protocol-v3)
342+for more information.

Next files