kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | ed6a18bdb8a64ce439e9c7972fac0d6fc5d3cc3ad32b99008d89860d35fe5e5d |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-05-04 16:16 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-05-04 16:16 +02:00 |
| Parents | 08d1b5f9e8e0, 1f38b646a0dc |
14 files changed
modified .gitignore +1 −0
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | .classpath |
| 6 | 6 | .project |
| 7 | 7 | doc |
| 8 | +docs | |
| 8 | 9 | notes |
| 9 | 10 | .DS_Store |
| 10 | 11 |
added README.md +137 −0
| @@ -0,0 +1,137 @@ | ||
| 1 | +# Datastax Java Driver for Apache Cassandra | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | +*If you're reading this on github.com, please note that this is the readme | |
| 6 | +for the development version and that some features described here might | |
| 7 | +not yet have been released. You can find the documentation for latest | |
| 8 | +version through [Java driver | |
| 9 | +docs](http://datastax.github.io/java-driver/) or via the release tags, | |
| 10 | +[e.g. | |
| 11 | +2.0.10](https://github.com/datastax/java-driver/tree/2.0.10).* | |
| 12 | + | |
| 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 | + | |
| 29 | +[sync]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/Session.html#execute(com.datastax.driver.core.Statement) | |
| 30 | +[async]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement) | |
| 31 | +[simple_st]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/SimpleStatement.html | |
| 32 | +[prepared_st]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/Session.html#prepare(com.datastax.driver.core.RegularStatement) | |
| 33 | +[batch_st]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/BatchStatement.html | |
| 34 | +[pool]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html | |
| 35 | +[lbp]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 36 | +[retry_policy]: http://datastax.com/drivers/java/2.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| 37 | +[query_builder]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 38 | + | |
| 39 | +The driver architecture is based on layers. At the bottom lies the driver core. | |
| 40 | +This core handles everything related to the connections to a Cassandra | |
| 41 | +cluster (for example, connection pool, discovering new nodes, etc.) and exposes a simple, | |
| 42 | +relatively low-level API on top of which higher level layers can be built. | |
| 43 | + | |
| 44 | +The driver contains the following modules: | |
| 45 | + | |
| 46 | +- driver-core: the core layer. | |
| 47 | +- driver-examples: example applications using the other modules which are | |
| 48 | + only meant for demonstration purposes. | |
| 49 | + | |
| 50 | +More modules including a simple object mapper will come shortly. | |
| 51 | + | |
| 52 | +Please refer to the README of each module for more information. | |
| 53 | + | |
| 54 | +**Community:** | |
| 55 | + | |
| 56 | +- JIRA: https://datastax-oss.atlassian.net/browse/JAVA | |
| 57 | +- MAILING LIST: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user | |
| 58 | +- IRC: #datastax-drivers on [irc.freenode.net](http://freenode.net) | |
| 59 | +- TWITTER: Follow the latest news about DataStax Drivers - [@olim7t](http://twitter.com/olim7t), [@mfiguiere](http://twitter.com/mfiguiere) | |
| 60 | +- DOCS: http://www.datastax.com/documentation/developer/java-driver/2.0/index.html | |
| 61 | +- API: http://www.datastax.com/drivers/java/2.0 | |
| 62 | +- CHANGELOG: https://github.com/datastax/java-driver/blob/2.0/driver-core/CHANGELOG.rst | |
| 63 | + | |
| 64 | +## What's new in 2.0.10 | |
| 65 | + | |
| 66 | +* [Speculative query execution](features/speculative_execution/) | |
| 67 | +* [Query logger](features/logging/#logging-query-latencies) | |
| 68 | +* Access to the [paging state](features/paging/#manual-paging) | |
| 69 | +* Don't mark hosts down on client timeouts, and remove "suspected" | |
| 70 | + mechanism | |
| 71 | +* Upgrade to Netty 4 and internal improvements around connection | |
| 72 | + handling | |
| 73 | +* New connection pool resizing algorithm | |
| 74 | +* [Connection heartbeat](features/pooling/#heartbeat) | |
| 75 | +* Address translation for [EC2 | |
| 76 | + multi-region](features/address_resolution/#ec2-multi-region) deployments | |
| 77 | +* Changes to [dependency shading](features/shaded_jar/), and fixes to | |
| 78 | + OSGI deployment descriptors | |
| 79 | +* Expose [token metadata](features/metadata/#token-metadata) | |
| 80 | + | |
| 81 | +For the full list of tickets, refer to the | |
| 82 | +[changelog](https://github.com/datastax/java-driver/blob/2.0/driver-core/CHANGELOG.rst). | |
| 83 | + | |
| 84 | +## Maven | |
| 85 | + | |
| 86 | +The last release of the driver is available on Maven Central. You can install | |
| 87 | +it in your application using the following Maven dependency: | |
| 88 | + | |
| 89 | +```xml | |
| 90 | +<dependency> | |
| 91 | + <groupId>com.datastax.cassandra</groupId> | |
| 92 | + <artifactId>cassandra-driver-core</artifactId> | |
| 93 | + <version>2.0.10</version> | |
| 94 | +</dependency> | |
| 95 | +``` | |
| 96 | + | |
| 97 | +We also provide a [shaded JAR](http://datastax.github.io/java-driver/features/shaded_jar/) | |
| 98 | +to avoid the explicit dependency to Netty. | |
| 99 | + | |
| 100 | +## Compatibility | |
| 101 | + | |
| 102 | +The Java client driver 2.0 ([branch 2.0](https://github.com/datastax/java-driver/tree/2.0)) is compatible with Apache | |
| 103 | +Cassandra 1.2 and 2.0, but some features are available only when using Apache Cassandra 2.0 (e.g. result set paging, | |
| 104 | +[BatchStatement](https://github.com/datastax/java-driver/blob/2.0/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java), | |
| 105 | +[lightweight transactions](http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_ltweight_transaction_t.html) | |
| 106 | +-- see [What's new in Cassandra 2.0](http://www.datastax.com/documentation/cassandra/2.0/cassandra/features/features_key_c.html)). | |
| 107 | +Trying to use these with a cluster running Cassandra 1.2 will result in | |
| 108 | +an [UnsupportedFeatureException](https://github.com/datastax/java-driver/blob/2.0/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java) being thrown. | |
| 109 | + | |
| 110 | +## Upgrading from 1.x branch | |
| 111 | + | |
| 112 | +If you are upgrading from the 1.x branch of the driver, be sure to have a look at | |
| 113 | +the [upgrade guide](https://github.com/datastax/java-driver/blob/2.0/driver-core/Upgrade_guide_to_2.0.rst). | |
| 114 | + | |
| 115 | +We used the opportunity of a major version bump to incorporate your feedback and improve the API, | |
| 116 | +to fix a number of inconsistencies and remove cruft. | |
| 117 | +Unfortunately this means there are some breaking changes, but the new API should be both simpler and more complete. | |
| 118 | + | |
| 119 | +### Troubleshooting | |
| 120 | + | |
| 121 | +If you are having issues connecting to the cluster (seeing `NoHostAvailableConnection` exceptions) please check the | |
| 122 | +[connection requirements](https://github.com/datastax/java-driver/wiki/Connection-requirements). | |
| 123 | + | |
| 124 | +## License | |
| 125 | +Copyright 2012-2015, DataStax | |
| 126 | + | |
| 127 | +Licensed under the Apache License, Version 2.0 (the "License"); | |
| 128 | +you may not use this file except in compliance with the License. | |
| 129 | +You may obtain a copy of the License at | |
| 130 | + | |
| 131 | +http://www.apache.org/licenses/LICENSE-2.0 | |
| 132 | + | |
| 133 | +Unless required by applicable law or agreed to in writing, software | |
| 134 | +distributed under the License is distributed on an "AS IS" BASIS, | |
| 135 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 136 | +See the License for the specific language governing permissions and | |
| 137 | +limitations under the License. |
deleted README.rst +0 −94
| @@ -1,94 +0,0 @@ | ||
| 1 | -DataStax Java Driver for Apache Cassandra | |
| 2 | -========================================= | |
| 3 | - | |
| 4 | -.. image:: https://travis-ci.org/datastax/java-driver.svg?branch=2.0 | |
| 5 | - :target: https://travis-ci.org/datastax/java-driver | |
| 6 | - :alt: Travis Build | |
| 7 | - | |
| 8 | -A Java client driver for Apache Cassandra. This driver works exclusively with | |
| 9 | -the Cassandra Query Language version 3 (CQL3) and Cassandra's binary protocol. | |
| 10 | - | |
| 11 | -- JIRA: https://datastax-oss.atlassian.net/browse/JAVA | |
| 12 | -- MAILING LIST: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user | |
| 13 | -- IRC: #datastax-drivers on `irc.freenode.net <http://freenode.net>`_ | |
| 14 | -- TWITTER: Follow the latest news about DataStax Drivers - `@olim7t <http://twitter.com/olim7t>`_, `@mfiguiere <http://twitter.com/mfiguiere>`_ | |
| 15 | -- DOCS: http://www.datastax.com/documentation/developer/java-driver/2.0/index.html | |
| 16 | -- API: http://www.datastax.com/drivers/java/2.0 | |
| 17 | -- CHANGELOG: https://github.com/datastax/java-driver/blob/2.0/driver-core/CHANGELOG.rst | |
| 18 | - | |
| 19 | - | |
| 20 | -The driver architecture is based on layers. At the bottom lies the driver core. | |
| 21 | -This core handles everything related to the connections to a Cassandra | |
| 22 | -cluster (for example, connection pool, discovering new nodes, etc.) and exposes a simple, | |
| 23 | -relatively low-level API on top of which higher level layer can be built. | |
| 24 | - | |
| 25 | -The driver contains the following modules: | |
| 26 | - - driver-core: the core layer. | |
| 27 | - - driver-examples: example applications using the other modules which are | |
| 28 | - only meant for demonstration purposes. | |
| 29 | - | |
| 30 | -More modules including a simple object mapper will come shortly. | |
| 31 | - | |
| 32 | -Please refer to the README of each module for more information. | |
| 33 | - | |
| 34 | - | |
| 35 | -Maven | |
| 36 | ------ | |
| 37 | - | |
| 38 | -The last release of the driver is available on Maven Central. You can install | |
| 39 | -it in your application using the following Maven dependency:: | |
| 40 | - | |
| 41 | - <dependency> | |
| 42 | - <groupId>com.datastax.cassandra</groupId> | |
| 43 | - <artifactId>cassandra-driver-core</artifactId> | |
| 44 | - <version>2.0.9.2</version> | |
| 45 | - </dependency> | |
| 46 | - | |
| 47 | -Compatibility | |
| 48 | -------------- | |
| 49 | - | |
| 50 | -The Java client driver 2.0 (`branch 2.0 <https://github.com/datastax/java-driver/tree/2.0>`_) is compatible with Apache | |
| 51 | -Cassandra 1.2 and 2.0, but some features are available only when using Apache Cassandra 2.0 (e.g. result set paging, | |
| 52 | -`BatchStatement <https://github.com/datastax/java-driver/blob/2.0/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java>`_, | |
| 53 | -`lightweight transactions <http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_ltweight_transaction_t.html>`_ | |
| 54 | --- see `What's new in Cassandra 2.0 <http://www.datastax.com/documentation/cassandra/2.0/cassandra/features/features_key_c.html>`_). | |
| 55 | -Trying to use these with a cluster running Cassandra 1.2 will result in | |
| 56 | -an `UnsupportedFeatureException <https://github.com/datastax/java-driver/blob/2.0/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java>`_ being thrown. | |
| 57 | - | |
| 58 | - | |
| 59 | -Upgrading from 1.x branch | |
| 60 | -------------------------- | |
| 61 | - | |
| 62 | - | |
| 63 | -If you are upgrading from the 1.x branch of the driver, be sure to have a look at | |
| 64 | -the `upgrade guide <https://github.com/datastax/java-driver/blob/2.0/driver-core/Upgrade_guide_to_2.0.rst>`_. | |
| 65 | - | |
| 66 | -We used the opportunity of a major version bump to incorporate your feedback and improve the API, | |
| 67 | -to fix a number of inconsistencies and remove cruft. | |
| 68 | -Unfortunately this means there are some breaking changes, but the new API should be both simpler and more complete. | |
| 69 | - | |
| 70 | - | |
| 71 | -Troubleshooting | |
| 72 | -~~~~~~~~~~~~~~~ | |
| 73 | - | |
| 74 | -If you are having issues connecting to the cluster (seeing ``NoHostAvailableConnection`` exceptions) please check the | |
| 75 | -`connection requirements <https://github.com/datastax/java-driver/wiki/Connection-requirements>`_. | |
| 76 | - | |
| 77 | - | |
| 78 | - | |
| 79 | - | |
| 80 | -License | |
| 81 | -------- | |
| 82 | -Copyright 2012-2014, DataStax | |
| 83 | - | |
| 84 | -Licensed under the Apache License, Version 2.0 (the "License"); | |
| 85 | -you may not use this file except in compliance with the License. | |
| 86 | -You may obtain a copy of the License at | |
| 87 | - | |
| 88 | -http://www.apache.org/licenses/LICENSE-2.0 | |
| 89 | - | |
| 90 | -Unless required by applicable law or agreed to in writing, software | |
| 91 | -distributed under the License is distributed on an "AS IS" BASIS, | |
| 92 | -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 93 | -See the License for the specific language governing permissions and | |
| 94 | -limitations under the License. |
added docs.yaml +24 −0
| @@ -0,0 +1,24 @@ | ||
| 1 | +# This is provided on the 2.0 branch for convenience. Use docs.yaml from the | |
| 2 | +# 2.1 branch to generate the docs for all versions. | |
| 3 | +title: Java Driver for Apache Cassandra | |
| 4 | +summary: High performance Java client for Apache Cassandra | |
| 5 | +homepage: http://datastax.github.io/java-driver/ | |
| 6 | +sections: | |
| 7 | + - title: Features | |
| 8 | + prefix: /features | |
| 9 | + sources: | |
| 10 | + - type: markdown | |
| 11 | + files: 'features/**/*.md' | |
| 12 | +links: | |
| 13 | + - title: Code | |
| 14 | + href: https://github.com/datastax/java-driver/ | |
| 15 | + - title: Docs | |
| 16 | + href: http://datastax.github.io/java-driver/ | |
| 17 | + - title: Issues | |
| 18 | + href: https://datastax-oss.atlassian.net/browse/JAVA/ | |
| 19 | + - title: Mailing List | |
| 20 | + href: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user | |
| 21 | + - title: IRC Channel | |
| 22 | + href: irc://irc.freenode.net/datastax-drivers | |
| 23 | + - title: Releases | |
| 24 | + href: https://github.com/datastax/java-driver/releases |
modified driver-core/Upgrade_guide_to_2.0.rst +31 −20
| @@ -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 | +==================== | |
| 11 | 3 | |
| 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. | |
| 15 | 6 | |
| 16 | 7 | |
| 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. | |
| 19 | 15 | |
| 20 | 16 | The following describes the changes for 2.0 that are breaking changes of the |
| 21 | 17 | 1.0 API. For ease of use, we distinguish two categories of API changes: the "main" |
| @@ -155,13 +151,28 @@ | ||
| 155 | 151 | will now need to use Host#isUp and Cluster#register if you were using that |
| 156 | 152 | class. |
| 157 | 153 | |
| 158 | -11. LatencyTracker#update method now has a different signature and takes two new | |
| 159 | - parameters: the statement that has been executed (never null), and the exception | |
| 160 | - thrown while executing the query (or null, if the query executed successfully). | |
| 161 | - Existing implementations of this interface, once upgraded to the new method | |
| 162 | - signature, should continue to work as before. | |
| 163 | 154 | |
| 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. | |
| 164 | 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. | |
| 165 | 176 | |
| 166 | 177 | |
| 167 | 178 | Features available only with Cassandra 2.0 |
modified driver-core/src/main/java/com/datastax/driver/core/package-info.java +1 −1
| @@ -16,6 +16,6 @@ | ||
| 16 | 16 | /** |
| 17 | 17 | * The main package for the DataStax Java driver for Cassandra. |
| 18 | 18 | * <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. | |
| 20 | 20 | */ |
| 21 | 21 | package com.datastax.driver.core; |
added features/README.md +7 −0
| @@ -0,0 +1,7 @@ | ||
| 1 | +## Features | |
| 2 | + | |
| 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 |
added features/address_resolution/README.md +67 −0
| @@ -0,0 +1,67 @@ | ||
| 1 | +## Address resolution | |
| 2 | + | |
| 3 | +The driver auto-detects new Cassandra nodes added to the cluster through server | |
| 4 | +side push notifications and through checking the system tables. | |
| 5 | + | |
| 6 | +For each node, the address the driver will receive will correspond to the address set as | |
| 7 | +`rpc_address` in the node's `cassandra.yaml` file. In most cases, this is the correct value. | |
| 8 | +However, sometimes the addresses received through this mechanism will either not be | |
| 9 | +reachable directly by the driver, or should not be the preferred address to use | |
| 10 | +(for instance, it might be a private IP, but some clients may have to use a public IP, or | |
| 11 | +go through a router). | |
| 12 | + | |
| 13 | +### The [AddressTranslater][at] interface | |
| 14 | + | |
| 15 | +This interface allows you to deal with such cases, by transforming the address sent by a | |
| 16 | +Cassandra node to another address to be used by the driver for connection. | |
| 17 | + | |
| 18 | +```java | |
| 19 | +public class MyAddressTranslater implements AddressTranslater { | |
| 20 | + public InetSocketAddress translate(InetSocketAddress address) { | |
| 21 | + ... // your custom translation logic | |
| 22 | + } | |
| 23 | +} | |
| 24 | + | |
| 25 | +Cluster cluster = Cluster.builder() | |
| 26 | + .addContactPoint("1.2.3.4") | |
| 27 | + .withAddressTranslater(new MyAddressTranslater()) | |
| 28 | + .build(); | |
| 29 | +``` | |
| 30 | + | |
| 31 | +Notes: | |
| 32 | + | |
| 33 | +* the contact points provided while creating the `Cluster` are not translated, only addresses | |
| 34 | + retrieved from or sent by Cassandra nodes are; | |
| 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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/policies/AddressTranslater.html | |
| 42 | +[cat]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/policies/CloseableAddressTranslater.html | |
| 43 | + | |
| 44 | +### EC2 multi-region | |
| 45 | + | |
| 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: | |
| 49 | + | |
| 50 | +* a client communicating with a Cassandra node *in the same EC2 region* should use the node's | |
| 51 | + private IP (which is less expensive); | |
| 52 | +* a client communicating with a node in a different region should use the public IP. | |
| 53 | + | |
| 54 | +To use this implementation, provide an instance when initializing the `Cluster`: | |
| 55 | + | |
| 56 | +```java | |
| 57 | +Cluster cluster = Cluster.builder() | |
| 58 | + .addContactPoint("1.2.3.4") | |
| 59 | + .withAddressTranslater(new EC2MultiRegionAddressTranslater()) | |
| 60 | + .build(); | |
| 61 | +``` | |
| 62 | + | |
| 63 | +This class performs a reverse DNS lookup of the origin address, to find the domain name of the | |
| 64 | +target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the | |
| 65 | +private/public switch automatically based on location. | |
| 66 | + | |
| 67 | +[ec2]: http://www.datastax.com/drivers/java/2.0/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://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getKeyspace(java.lang.String) | |
| 16 | +[getKeyspaces]: http://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds(int)) | |
| 116 | +* [isSchemaInAgreement()](http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement()) | |
| 117 | +* [checkSchemaAgreement()](http://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html | |
| 162 | +[getTokenRanges]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getTokenRanges() | |
| 163 | +[getTokenRanges2]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getTokenRanges(java.lang.String,%20com.datastax.driver.core.Host) | |
| 164 | +[getReplicas]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html#getReplicas(java.lang.String,%20com.datastax.driver.core.TokenRange) | |
| 165 | +[newToken]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html#newToken(java.lang.String) | |
| 166 | +[newTokenRange]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metadata.html#newTokenRange(com.datastax.driver.core.Token,%20com.datastax.driver.core.Token) | |
| 167 | +[TokenRange]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/TokenRange.html | |
| 168 | +[getTokens]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Host.html#getTokens() | |
| 169 | +[setToken]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/BoundStatement.html#setToken(int,%20com.datastax.driver.core.Token) | |
| 170 | +[getToken]: http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Row.html#getToken(int) | |
| 171 | +[getPKToken]: http://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis() | |
| 184 | +[exec_async]:http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement) | |
| 185 | +[ptm]:http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 186 | +[nhae]:http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html | |
| 187 | +[get_state]:http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Session.html#getState() | |
| No newline at the end of the file |
added features/shaded_jar/README.md +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +## Using the shaded JAR | |
| 2 | + | |
| 3 | +The default driver JAR depends on [Netty](http://netty.io/), which is | |
| 4 | +used internally for networking. | |
| 5 | + | |
| 6 | +This explicit dependency can be a problem if your application already | |
| 7 | +uses another Netty version. To avoid conflicts, we provide a "shaded" | |
| 8 | +version of the JAR, which bundles the Netty classes under a different | |
| 9 | +package name: | |
| 10 | + | |
| 11 | +```xml | |
| 12 | +<dependency> | |
| 13 | + <groupId>${project.groupId}</groupId> | |
| 14 | + <artifactId>cassandra-driver-core</artifactId> | |
| 15 | + <version>2.0.10</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 | +``` |
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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Statement.html#isIdempotent() | |
| 110 | +[QueryBuilder]: http://www.datastax.com/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://www.datastax.com/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://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html | |
| 209 | +[hdr]: http://hdrhistogram.github.io/HdrHistogram/ | |
| 210 | +[phpt]: http://www.datastax.com/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://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions() | |
| 280 | +[request_metric]: http://www.datastax.com/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://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Session.State.html | |
| 310 | +[protocol_version]: http://www.datastax.com/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. |