Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0
Changesetea460f7581545370ae82dc41da38f54341bb69ab7d299ca15ef989104c6d320b
Authorolim7t <omichallat+github@gmail.com> · 2015-12-03 17:07 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-12-03 17:07 +01:00
Parents392d4cde0c36, 4a8096457983

Browse the files at this changeset

25 files changed

modified changelog/README.md +11 −0
@@ -235,6 +235,11 @@
235235
236236 - [bug] JAVA-988: Metadata.handleId should handle escaped double quotes.
237237
238+Merged from 2.0 branch:
239+
240+- [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing.
241+- [bug] JAVA-995: Defunct connection even if initializing.
242+
238243
239244 ### 2.1.9
240245
@@ -555,6 +560,12 @@
555560 - [bug] JAVA-377, JAVA-391: Make metadata parsing more lenient.
556561
557562
563+### 2.0.13 (in progress)
564+
565+- [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing.
566+- [bug] JAVA-995: Defunct connection even if initializing.
567+
568+
558569 ### 2.0.12
559570
560571 - [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace.
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
@@ -71,7 +71,7 @@
7171 }
7272
7373 Token.Factory tokenFactory = (session == null) ? null
74- : session.getCluster().getMetadata().tokenFactory();
74+ : session.getCluster().manager.metadata.tokenFactory();
7575
7676 // info can be null only for internal calls, but we don't page those. We assert
7777 // this explicitly because MultiPage implementation don't support info == null.
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +40 −24
@@ -1631,12 +1631,16 @@
16311631 }
16321632
16331633 public ListenableFuture<?> triggerOnUp(final Host host) {
1634- return executor.submit(new ExceptionCatchingRunnable() {
1635- @Override
1636- public void runMayThrow() throws InterruptedException, ExecutionException {
1637- onUp(host, null);
1638- }
1639- });
1634+ if (!isClosed()) {
1635+ return executor.submit(new ExceptionCatchingRunnable() {
1636+ @Override
1637+ public void runMayThrow() throws InterruptedException, ExecutionException {
1638+ onUp(host, null);
1639+ }
1640+ });
1641+ } else {
1642+ return MoreFutures.VOID_SUCCESS;
1643+ }
16401644 }
16411645
16421646 // Use triggerOnUp unless you're sure you want to run this on the current thread.
@@ -1746,12 +1750,16 @@
17461750 }
17471751
17481752 public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition, final boolean startReconnection) {
1749- return executor.submit(new ExceptionCatchingRunnable() {
1750- @Override
1751- public void runMayThrow() throws InterruptedException, ExecutionException {
1752- onDown(host, isHostAddition, startReconnection);
1753- }
1754- });
1753+ if(!isClosed()) {
1754+ return executor.submit(new ExceptionCatchingRunnable() {
1755+ @Override
1756+ public void runMayThrow() throws InterruptedException, ExecutionException {
1757+ onDown(host, isHostAddition, startReconnection);
1758+ }
1759+ });
1760+ } else {
1761+ return MoreFutures.VOID_SUCCESS;
1762+ }
17551763 }
17561764
17571765 // Use triggerOnDown unless you're sure you want to run this on the current thread.
@@ -1906,12 +1914,16 @@
19061914 }
19071915
19081916 public ListenableFuture<?> triggerOnAdd(final Host host) {
1909- return executor.submit(new ExceptionCatchingRunnable() {
1910- @Override
1911- public void runMayThrow() throws InterruptedException, ExecutionException {
1912- onAdd(host, null);
1913- }
1914- });
1917+ if (!isClosed()) {
1918+ return executor.submit(new ExceptionCatchingRunnable() {
1919+ @Override
1920+ public void runMayThrow() throws InterruptedException, ExecutionException {
1921+ onAdd(host, null);
1922+ }
1923+ });
1924+ } else {
1925+ return MoreFutures.VOID_SUCCESS;
1926+ }
19151927 }
19161928
19171929 // Use triggerOnAdd unless you're sure you want to run this on the current thread.
@@ -2011,12 +2023,16 @@
20112023 }
20122024
20132025 public ListenableFuture<?> triggerOnRemove(final Host host) {
2014- return executor.submit(new ExceptionCatchingRunnable() {
2015- @Override
2016- public void runMayThrow() throws InterruptedException, ExecutionException {
2017- onRemove(host);
2018- }
2019- });
2026+ if (!isClosed()) {
2027+ return executor.submit(new ExceptionCatchingRunnable() {
2028+ @Override
2029+ public void runMayThrow() throws InterruptedException, ExecutionException {
2030+ onRemove(host);
2031+ }
2032+ });
2033+ } else {
2034+ return MoreFutures.VOID_SUCCESS;
2035+ }
20202036 }
20212037
20222038 // Use triggerOnRemove unless you're sure you want to run this on the current thread.
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +1 −1
@@ -1064,7 +1064,7 @@
10641064 public void operationComplete(ChannelFuture future) throws Exception {
10651065 // If we've closed the channel client side then we don't really want to defunct the connection, but
10661066 // if there is remaining thread waiting on us, we still want to wake them up
1067- if (!isInitialized || isClosed()) {
1067+ if (isClosed()) {
10681068 dispatcher.errorOutAllHandler(new TransportException(address, "Channel has been closed"));
10691069 // we still want to force so that the future completes
10701070 Connection.this.closeAsync().force();
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −0
@@ -23,6 +23,10 @@
2323 return new ClusterAssert(cluster);
2424 }
2525
26+ public static HostAssert assertThat(Host host) {
27+ return new HostAssert(host);
28+ }
29+
2630 public static SessionAssert assertThat(Session session) {
2731 return new SessionAssert(session);
2832 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +5 −0
@@ -47,6 +47,11 @@
4747 return this;
4848 }
4949
50+ public HostAssert controlHost() {
51+ Host host = TestUtils.findOrWaitForControlConnection(actual, 10, TimeUnit.SECONDS);
52+ return new HostAssert(host, actual);
53+ }
54+
5055 public HostAssert host(int hostNumber) {
5156 // Wait for the node to be added if it's not already known.
5257 // In 2.2+ C* does not send an added event until the node is ready so we wait a long time.
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +11 −8
@@ -230,19 +230,22 @@
230230 */
231231 @Test(groups="short")
232232 public void should_not_abort_init_if_host_does_not_support_protocol_version() {
233- Map<Integer,Map<String,Object>> nodeProperties = Maps.newHashMap();
234- // Configure node 2 to run with an older version which uses protocol v1.
235- nodeProperties.put(2, ImmutableMap.<String,Object>of("release_version", "1.2.19"));
236- SCassandraCluster scassandraCluster = new SCassandraCluster(CCMBridge.IP_PREFIX, 5, nodeProperties);
233+ ScassandraCluster scassandraCluster = ScassandraCluster.builder()
234+ .withIpPrefix(CCMBridge.IP_PREFIX)
235+ .withNodes(5)
236+ // For node 2, report an older version which uses protocol v1.
237+ .forcePeerInfo(1, 2, "release_version", "1.2.19")
238+ .build();
237239 Cluster cluster = Cluster.builder()
238- .addContactPoints(scassandraCluster.addresses().get(0))
240+ .addContactPoints(scassandraCluster.address(1))
239241 .withNettyOptions(nonQuietClusterCloseOptions)
240242 .build();
241243
242244 try {
245+ scassandraCluster.init();
243246 cluster.init();
244- for(int i = 0; i < scassandraCluster.addresses().size(); i++) {
245- String hostAddress = scassandraCluster.addresses().get(i).getHostAddress();
247+ for(int i = 1; i <= 5; i++) {
248+ String hostAddress = scassandraCluster.address(i);
246249 if (i == 2) {
247250 // As this host is at an older protocol version, it should be ignored and not marked up.
248251 assertThat(cluster).host(hostAddress).hasState(Host.State.ADDED);
@@ -281,7 +284,7 @@
281284 primingClient.prime(
282285 PrimingRequest.queryBuilder()
283286 .withQuery("SELECT * FROM system.peers")
284- .withColumnTypes(SCassandraCluster.SELECT_PEERS_COLUMN_TYPES)
287+ .withColumnTypes(ScassandraCluster.SELECT_PEERS)
285288 .withRows(rows)
286289 .build());
287290 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +11 −2
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import java.net.InetAddress;
19+import java.util.Collection;
1920 import java.util.Iterator;
2021 import java.util.Map;
2122 import java.util.concurrent.TimeUnit;
@@ -23,11 +24,14 @@
2324
2425 import com.google.common.base.Function;
2526 import com.google.common.collect.HashMultiset;
27+import com.google.common.collect.Iterables;
2628 import com.google.common.collect.Maps;
2729 import org.slf4j.Logger;
2830 import org.slf4j.LoggerFactory;
2931 import org.testng.annotations.Test;
3032
33+import static com.google.common.collect.Lists.newArrayList;
34+
3135 import static com.datastax.driver.core.Assertions.assertThat;
3236 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3337 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
@@ -175,13 +179,18 @@
175179 public void should_randomize_contact_points_when_determining_control_connection() {
176180 int hostCount = 5;
177181 int iterations = 100;
178- SCassandraCluster scassandras = new SCassandraCluster(hostCount);
182+ ScassandraCluster scassandras = ScassandraCluster.builder().withNodes(hostCount).build();
183+ scassandras.init();
179184
180185 try {
186+ Collection<String> contactPoints = newArrayList();
187+ for(int i = 1; i <= hostCount; i++) {
188+ contactPoints.add(scassandras.address(i));
189+ }
181190 final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
182191 for(int i = 0; i < iterations; i++) {
183192 Cluster cluster = Cluster.builder()
184- .addContactPoints(scassandras.addresses())
193+ .addContactPoints(contactPoints.toArray(new String[hostCount]))
185194 .withNettyOptions(nonQuietClusterCloseOptions)
186195 .build();
187196
added driver-core/src/test/java/com/datastax/driver/core/DataProviders.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;
17+
18+import java.util.Arrays;
19+import java.util.Iterator;
20+
21+import com.google.common.base.Predicate;
22+import com.google.common.collect.Iterables;
23+import org.testng.annotations.DataProvider;
24+
25+public class DataProviders {
26+
27+ /**
28+ * @return A DataProvider that provides all non-serial consistency levels
29+ */
30+ @DataProvider(name = "consistencyLevels")
31+ public static Iterator<Object[]> consistencyLevels() {
32+ final Iterator<ConsistencyLevel> consistencyLevels = Iterables.filter(Arrays.asList(ConsistencyLevel.values()), new Predicate<ConsistencyLevel>() {
33+ @Override
34+ public boolean apply(ConsistencyLevel input) {
35+ // filter out serial CLs.
36+ return !input.equals(ConsistencyLevel.SERIAL) && !input.equals(ConsistencyLevel.LOCAL_SERIAL);
37+ }
38+ }).iterator();
39+
40+ return new Iterator<Object[]> () {
41+
42+ @Override
43+ public boolean hasNext() {
44+ return consistencyLevels.hasNext();
45+ }
46+
47+ @Override
48+ public Object[] next() {
49+ return new Object[] {
50+ consistencyLevels.next()
51+ };
52+ }
53+
54+ @Override
55+ public void remove() {
56+ throw new UnsupportedOperationException("This shouldn't happen..");
57+ }
58+ };
59+ }
60+
61+ /**
62+ * @return A DataProvider that provides all serial consistency levels
63+ */
64+ @DataProvider(name = "serialConsistencyLevels")
65+ public static Object[][] serialConsistencyLevels() {
66+ return new Object[][] {
67+ { ConsistencyLevel.SERIAL },
68+ { ConsistencyLevel.LOCAL_SERIAL }
69+ };
70+ }
71+
72+}
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +9 −0
@@ -31,6 +31,10 @@
3131
3232 private final Cluster cluster;
3333
34+ protected HostAssert(Host host) {
35+ this(host, null);
36+ }
37+
3438 protected HostAssert(Host host, Cluster cluster) {
3539 super(host, HostAssert.class);
3640 this.cluster = cluster;
@@ -63,6 +67,11 @@
6367 return this;
6468 }
6569
70+ public HostAssert isInDatacenter(String datacenter) {
71+ assertThat(actual.getDatacenter()).isEqualTo(datacenter);
72+ return this;
73+ }
74+
6675 public HostAssert isNotReconnectingFromDown() {
6776 assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone())
6877 .isFalse();
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +6 −5
@@ -32,13 +32,14 @@
3232
3333 public class HostConnectionPoolMultiTest {
3434
35- private SCassandraCluster scassandra;
35+ private ScassandraCluster scassandra;
3636
3737 private Cluster cluster;
3838
3939 @BeforeMethod(groups={"short", "long"})
4040 private void setUp() {
41- scassandra = new SCassandraCluster(2);
41+ scassandra = ScassandraCluster.builder().withNodes(2).build();
42+ scassandra.init();
4243 }
4344
4445 @AfterMethod(groups={"short", "long"})
@@ -72,7 +73,7 @@
7273 @Test(groups="short")
7374 public void should_mark_host_down_if_all_connections_fail_on_init() {
7475 // Prevent any connections on node 2.
75- scassandra.instance(2).currentClient().disableListener();
76+ scassandra.node(2).currentClient().disableListener();
7677 createCluster(8,8);
7778
7879 // Node 2 should be in a down state while node 1 stays up.
@@ -80,7 +81,7 @@
8081 assertThat(cluster).host(1).isUp();
8182
8283 // Node 2 should come up as soon as it is able to reconnect.
83- scassandra.instance(2).currentClient().enableListener();
84+ scassandra.node(2).currentClient().enableListener();
8485 assertThat(cluster).host(2).comesUpWithin(2, SECONDS);
8586 }
8687
@@ -104,7 +105,7 @@
104105 InetSocketAddress controlSocket = (InetSocketAddress)controlConnection.channel.localAddress();
105106
106107 // Close the control connection.
107- scassandra.instance(1).currentClient()
108+ scassandra.node(1).currentClient()
108109 .closeConnection(CLOSE, controlSocket);
109110
110111 // Sleep reconnect interval * 2 to allow time to reconnect.
deleted driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyTest.java +0 −456
@@ -1,456 +0,0 @@
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.InetSocketAddress;
20-import java.util.Arrays;
21-import java.util.List;
22-import org.testng.annotations.Test;
23-
24-import com.datastax.driver.core.exceptions.*;
25-import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
26-import com.datastax.driver.core.policies.RoundRobinPolicy;
27-import com.datastax.driver.core.policies.TokenAwarePolicy;
28-import com.datastax.driver.core.policies.WhiteListPolicy;
29-
30-import static com.datastax.driver.core.TestUtils.*;
31-import static org.testng.Assert.*;
32-
33-public class LoadBalancingPolicyTest extends AbstractPoliciesTest {
34-
35- @Test(groups = "long")
36- public void roundRobinTest() throws Throwable {
37-
38- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy());
39- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
40- try {
41-
42- createSchema(c.session);
43- init(c, 12);
44- query(c, 12);
45-
46- assertQueried(CCMBridge.IP_PREFIX + '1', 6);
47- assertQueried(CCMBridge.IP_PREFIX + '2', 6);
48-
49- resetCoordinators();
50- c.cassandraCluster.bootstrapNode(3);
51- waitFor(CCMBridge.IP_PREFIX + '3', c.cluster);
52- Thread.sleep(50000);
53-
54- query(c, 12);
55-
56- assertQueried(CCMBridge.IP_PREFIX + '1', 4);
57- assertQueried(CCMBridge.IP_PREFIX + '2', 4);
58- assertQueried(CCMBridge.IP_PREFIX + '3', 4);
59-
60- resetCoordinators();
61- c.cassandraCluster.decommissionNode(1);
62- waitForDecommission(CCMBridge.IP_PREFIX + '1', c.cluster);
63-
64- query(c, 12);
65-
66- assertQueried(CCMBridge.IP_PREFIX + '2', 6);
67- assertQueried(CCMBridge.IP_PREFIX + '3', 6);
68-
69- } catch (Throwable e) {
70- c.errorOut();
71- throw e;
72- } finally {
73- resetCoordinators();
74- c.discard();
75- }
76- }
77-
78- @Test(groups = "long")
79- public void whiteListPolicyTest() throws Throwable {
80-
81- List<InetSocketAddress> whiteList = Arrays.asList(new InetSocketAddress(InetAddress.getByName(CCMBridge.IP_PREFIX + '2'), 9042));
82-
83- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList));
84- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
85- try {
86-
87- createSchema(c.session);
88- init(c, 12);
89- query(c, 12);
90-
91- assertQueried(CCMBridge.IP_PREFIX + "1", 0);
92- assertQueried(CCMBridge.IP_PREFIX + "2", 12);
93- assertQueried(CCMBridge.IP_PREFIX + "3", 0);
94-
95- resetCoordinators();
96- c.cassandraCluster.decommissionNode(2);
97- waitForDecommission(CCMBridge.IP_PREFIX + "2", c.cluster);
98-
99- try {
100- query(c, 12);
101- fail("Should work, we've only whitelisted node 2 and it's been removed");
102- } catch (NoHostAvailableException e) {
103- // That's what we expected
104- }
105-
106- } catch (Throwable e) {
107- c.errorOut();
108- throw e;
109- } finally {
110- resetCoordinators();
111- c.discard();
112- }
113- }
114-
115- @Test(groups = "long")
116- public void roundRobinWith2DCsTest() throws Throwable {
117-
118- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy());
119- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
120- try {
121-
122- createSchema(c.session);
123- init(c, 12);
124- query(c, 12);
125-
126- assertQueried(CCMBridge.IP_PREFIX + '1', 3);
127- assertQueried(CCMBridge.IP_PREFIX + '2', 3);
128- assertQueried(CCMBridge.IP_PREFIX + '3', 3);
129- assertQueried(CCMBridge.IP_PREFIX + '4', 3);
130-
131- resetCoordinators();
132- c.cassandraCluster.bootstrapNode(5, "dc2");
133- c.cassandraCluster.decommissionNode(1);
134- waitFor(CCMBridge.IP_PREFIX + '5', c.cluster);
135- waitForDecommission(CCMBridge.IP_PREFIX + '1', c.cluster);
136- Thread.sleep(50000);
137-
138- query(c, 12);
139-
140- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
141- assertQueried(CCMBridge.IP_PREFIX + '2', 3);
142- assertQueried(CCMBridge.IP_PREFIX + '3', 3);
143- assertQueried(CCMBridge.IP_PREFIX + '4', 3);
144- assertQueried(CCMBridge.IP_PREFIX + '5', 3);
145-
146- } catch (Throwable e) {
147- c.errorOut();
148- throw e;
149- } finally {
150- resetCoordinators();
151- c.discard();
152- }
153- }
154-
155- @Test(groups = "long")
156- public void DCAwareRoundRobinTest() throws Throwable {
157-
158- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build());
159- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
160- try {
161-
162- createMultiDCSchema(c.session);
163- init(c, 12);
164- query(c, 12);
165-
166- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
167- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
168- assertQueried(CCMBridge.IP_PREFIX + '3', 6);
169- assertQueried(CCMBridge.IP_PREFIX + '4', 6);
170-
171- } catch (Throwable e) {
172- c.errorOut();
173- throw e;
174- } finally {
175- resetCoordinators();
176- c.discard();
177- }
178- }
179-
180- @Test(groups = "long")
181- public void DCAwareRoundRobinTest2() throws Throwable {
182-
183- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc1").build());
184- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
185- try {
186-
187- createMultiDCSchema(c.session);
188- init(c, 12);
189- query(c, 12);
190-
191- assertQueried(CCMBridge.IP_PREFIX + '1', 6);
192- assertQueried(CCMBridge.IP_PREFIX + '2', 6);
193- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
194- assertQueried(CCMBridge.IP_PREFIX + '4', 0);
195-
196- } catch (Throwable e) {
197- c.errorOut();
198- throw e;
199- } finally {
200- resetCoordinators();
201- c.discard();
202- }
203- }
204-
205- @Test(groups = "long")
206- public void dcAwareRoundRobinTestWithOneRemoteHost() throws Throwable {
207-
208- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").withUsedHostsPerRemoteDc(1).build());
209- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
210- try {
211-
212- createMultiDCSchema(c.session);
213- init(c, 12);
214- query(c, 12);
215-
216- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
217- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
218- assertQueried(CCMBridge.IP_PREFIX + '3', 6);
219- assertQueried(CCMBridge.IP_PREFIX + '4', 6);
220- assertQueried(CCMBridge.IP_PREFIX + '5', 0);
221-
222- resetCoordinators();
223- c.cassandraCluster.bootstrapNode(5, "dc3");
224- waitFor(CCMBridge.IP_PREFIX + '5', c.cluster);
225-
226- query(c, 12);
227-
228- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
229- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
230- assertQueried(CCMBridge.IP_PREFIX + '3', 6);
231- assertQueried(CCMBridge.IP_PREFIX + '4', 6);
232- assertQueried(CCMBridge.IP_PREFIX + '5', 0);
233-
234- resetCoordinators();
235- c.cassandraCluster.decommissionNode(3);
236- c.cassandraCluster.decommissionNode(4);
237- waitForDecommission(CCMBridge.IP_PREFIX + '3', c.cluster);
238- waitForDecommission(CCMBridge.IP_PREFIX + '4', c.cluster);
239-
240- // TODO: Fix this now non-deterministic test
241- //query(c, 12);
242- //
243- //assertQueried(CCMBridge.IP_PREFIX + '1', 0);
244- //assertQueried(CCMBridge.IP_PREFIX + '2', 0);
245- //assertQueried(CCMBridge.IP_PREFIX + '3', 0);
246- //assertQueried(CCMBridge.IP_PREFIX + '4', 0);
247- //assertQueried(CCMBridge.IP_PREFIX + '5', 12);
248- //
249- //resetCoordinators();
250- c.cassandraCluster.decommissionNode(5);
251- waitForDecommission(CCMBridge.IP_PREFIX + '5', c.cluster, 120);
252-
253- query(c, 12);
254-
255- assertOneNodeQueried(12, CCMBridge.IP_PREFIX + '1', CCMBridge.IP_PREFIX + '2', CCMBridge.IP_PREFIX + '3');
256- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
257- assertQueried(CCMBridge.IP_PREFIX + '4', 0);
258- assertQueried(CCMBridge.IP_PREFIX + '5', 0);
259-
260- resetCoordinators();
261- c.cassandraCluster.decommissionNode(1);
262- waitForDecommission(CCMBridge.IP_PREFIX + '1', c.cluster);
263-
264- query(c, 12);
265-
266- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
267- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
268- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
269- assertQueried(CCMBridge.IP_PREFIX + '4', 0);
270- assertQueried(CCMBridge.IP_PREFIX + '5', 0);
271-
272- resetCoordinators();
273- c.cassandraCluster.forceStop(2);
274- waitForDown(CCMBridge.IP_PREFIX + '2', c.cluster);
275-
276- try {
277- query(c, 12);
278- fail();
279- } catch (NoHostAvailableException e) {
280- // No more nodes so ...
281- }
282-
283- } catch (Throwable e) {
284- c.errorOut();
285- throw e;
286- } finally {
287- resetCoordinators();
288- c.discard();
289- }
290- }
291-
292- @Test(groups = "long")
293- public void tokenAwareTest() throws Throwable {
294- tokenAwareTest(false);
295- }
296-
297- @Test(groups = "long")
298- public void tokenAwarePreparedTest() throws Throwable {
299- tokenAwareTest(true);
300- }
301-
302- /**
303- * Check for JAVA-123 bug. Doesn't really test token awareness, but rather
304- * that we do not destroy the keys.
305- */
306- @Test(groups = "long")
307- public void tokenAwareCompositeKeyTest() throws Throwable {
308-
309- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
310- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
311-
312- Session session = c.session;
313-
314- try {
315- String COMPOSITE_TABLE = "composite";
316- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, 2));
317- session.execute("USE " + SIMPLE_KEYSPACE);
318- session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", COMPOSITE_TABLE));
319-
320- PreparedStatement ps = session.prepare("INSERT INTO " + COMPOSITE_TABLE + "(k1, k2, i) VALUES (?, ?, ?)");
321- session.execute(ps.bind(1, 2, 3));
322-
323- ResultSet rs = session.execute("SELECT * FROM " + COMPOSITE_TABLE + " WHERE k1 = 1 AND k2 = 2");
324- assertTrue(!rs.isExhausted());
325- Row r = rs.one();
326- assertTrue(rs.isExhausted());
327-
328- assertEquals(r.getInt("i"), 3);
329- } catch (Throwable e) {
330- c.errorOut();
331- throw e;
332- } finally {
333- c.discard();
334- }
335- }
336-
337- public void tokenAwareTest(boolean usePrepared) throws Throwable {
338- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
339- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
340- try {
341-
342- createSchema(c.session);
343- init(c, 12);
344- query(c, 12);
345-
346- // Not the best test ever, we should use OPP and check we do it the
347- // right nodes. But since M3P is hard-coded for now, let just check
348- // we just hit only one node.
349- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
350- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
351- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
352-
353- resetCoordinators();
354- query(c, 12);
355-
356- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
357- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
358- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
359-
360- resetCoordinators();
361- c.cassandraCluster.stop(2);
362- waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10);
363-
364- try {
365- query(c, 12, usePrepared);
366- fail();
367- } catch (ReadTimeoutException e) {
368- assertEquals(1, e.getRequiredAcknowledgements());
369- assertEquals(0, e.getReceivedAcknowledgements());
370- } catch (UnavailableException e) {
371- assertEquals(1, e.getRequiredReplicas());
372- assertEquals(0, e.getAliveReplicas());
373- }
374-
375- resetCoordinators();
376- c.cassandraCluster.start(2);
377- waitFor(CCMBridge.IP_PREFIX + '2', c.cluster);
378-
379- // FIXME: remove sleep once waitFor() is fixed
380- Thread.sleep(2000);
381-
382- query(c, 12);
383-
384- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
385- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
386- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
387-
388- resetCoordinators();
389- c.cassandraCluster.decommissionNode(2);
390- waitForDecommission(CCMBridge.IP_PREFIX + '2', c.cluster);
391-
392- query(c, 12);
393-
394- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
395- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
396- assertQueried(CCMBridge.IP_PREFIX + '3', 12);
397-
398- } catch (Throwable e) {
399- c.errorOut();
400- throw e;
401- } finally {
402- resetCoordinators();
403- c.discard();
404- }
405- }
406-
407- @Test(groups = "long")
408- public void tokenAwareWithRF2Test() throws Throwable {
409- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
410- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
411- try {
412-
413- createSchema(c.session, 2);
414- init(c, 12);
415- query(c, 12);
416-
417- // Not the best test ever, we should use OPP and check we do hit the
418- // right nodes. But since M3P is hard-coded for now, let just check
419- // we just hit only one node.
420- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
421- assertQueried(CCMBridge.IP_PREFIX + '2', 12);
422- assertQueried(CCMBridge.IP_PREFIX + '3', 0);
423-
424- // TODO: Better testing infrastructure
425- // https://datastax-oss.atlassian.net/browse/JAVA-245
426- //resetCoordinators();
427- //c.cassandraCluster.bootstrapNode(3);
428- //waitFor(CCMBridge.IP_PREFIX + '3', c.cluster);
429- //
430- //query(c, 12);
431- //
432- //// We should still be hitting only one node
433- //assertQueried(CCMBridge.IP_PREFIX + '1', 0);
434- //assertQueried(CCMBridge.IP_PREFIX + '2', 12);
435- //assertQueried(CCMBridge.IP_PREFIX + '3', 0);
436- //
437- //resetCoordinators();
438- //c.cassandraCluster.stop(2);
439- //waitForDown(CCMBridge.IP_PREFIX + '2', c.cluster);
440- //
441- //query(c, 12);
442- //
443- //// Still only one node since RF=2
444- //assertQueried(CCMBridge.IP_PREFIX + '1', 12);
445- //assertQueried(CCMBridge.IP_PREFIX + '2', 0);
446- //assertQueried(CCMBridge.IP_PREFIX + '3', 0);
447-
448- } catch (Throwable e) {
449- c.errorOut();
450- throw e;
451- } finally {
452- resetCoordinators();
453- c.discard();
454- }
455- }
456-}
modified driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +16 −21
@@ -19,13 +19,15 @@
1919 import java.util.concurrent.TimeUnit;
2020
2121 import com.google.common.collect.Lists;
22+import org.scassandra.Scassandra;
2223 import org.scassandra.http.client.PreparedStatementPreparation;
2324 import org.testng.annotations.*;
2425
2526 import static com.datastax.driver.core.Assertions.assertThat;
27+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
2628
2729 public class QueryOptionsTest {
28- SCassandraCluster scassandra;
30+ ScassandraCluster scassandra;
2931
3032 QueryOptions queryOptions;
3133
@@ -36,19 +38,18 @@
3638 Host host1, host2, host3;
3739
3840
39- @BeforeClass(groups = "short")
40- public void beforeClass() {
41- scassandra = new SCassandraCluster(CCMBridge.IP_PREFIX, 3);
42- }
43-
4441 @BeforeMethod(groups = "short")
4542 public void beforeMethod() {
43+ scassandra = ScassandraCluster.builder().withNodes(3).build();
44+ scassandra.init();
45+
4646 queryOptions = new QueryOptions();
4747 loadBalancingPolicy = new SortingLoadBalancingPolicy();
4848 cluster = Cluster.builder()
4949 .addContactPoint(CCMBridge.ipOfNode(2))
5050 .withLoadBalancingPolicy(loadBalancingPolicy)
5151 .withQueryOptions(queryOptions)
52+ .withNettyOptions(nonQuietClusterCloseOptions)
5253 .build();
5354
5455 session = cluster.connect();
@@ -59,7 +60,7 @@
5960
6061 // Make sure there are no prepares
6162 for (int host : Lists.newArrayList(1, 2, 3)) {
62- assertThat(scassandra.retrievePreparedStatementPreparations(host)).hasSize(0);
63+ assertThat(scassandra.node(host).activityClient().retrievePreparedStatementPreparations()).hasSize(0);
6364 }
6465 }
6566
@@ -70,9 +71,9 @@
7071 assertThat(cluster.manager.preparedQueries).containsValue(statement);
7172
7273 // Ensure prepared properly based on expectation.
73- List<PreparedStatementPreparation> preparationOne = scassandra.retrievePreparedStatementPreparations(1);
74- List<PreparedStatementPreparation> preparationTwo = scassandra.retrievePreparedStatementPreparations(2);
75- List<PreparedStatementPreparation> preparationThree = scassandra.retrievePreparedStatementPreparations(3);
74+ List<PreparedStatementPreparation> preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations();
75+ List<PreparedStatementPreparation> preparationTwo = scassandra.node(2).activityClient().retrievePreparedStatementPreparations();
76+ List<PreparedStatementPreparation> preparationThree = scassandra.node(3).activityClient().retrievePreparedStatementPreparations();
7677
7778 assertThat(preparationOne).hasSize(1);
7879 assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
@@ -142,19 +143,19 @@
142143 String query = "select sansa_stark from the_known_world";
143144 session.prepare(query);
144145
145- List<PreparedStatementPreparation> preparationOne = scassandra.retrievePreparedStatementPreparations(1);
146+ List<PreparedStatementPreparation> preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations();
146147
147148 assertThat(preparationOne).hasSize(1);
148149 assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
149150
150- scassandra.clearAllRecordedActivity();
151- scassandra.stop(1);
151+ scassandra.node(1).activityClient().clearAllRecordedActivity();
152+ scassandra.node(1).stop();
152153 assertThat(cluster).host(1).goesDownWithin(10, TimeUnit.SECONDS);
153154
154- scassandra.start(1);
155+ scassandra.node(1).start();
155156 assertThat(cluster).host(1).comesUpWithin(60, TimeUnit.SECONDS);
156157
157- preparationOne = scassandra.retrievePreparedStatementPreparations(1);
158+ preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations();
158159 if (expectReprepare) {
159160 assertThat(preparationOne).hasSize(1);
160161 assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
@@ -218,12 +219,6 @@
218219 if (cluster != null)
219220 cluster.close();
220221
221- scassandra.clearAllPrimes();
222- scassandra.clearAllRecordedActivity();
223- }
224-
225- @AfterClass(groups = "short")
226- public void afterClass() {
227222 if (scassandra != null)
228223 scassandra.stop();
229224 }
added driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +109 −0
@@ -0,0 +1,109 @@
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.List;
20+import java.util.Map;
21+import java.util.concurrent.ExecutionException;
22+import java.util.concurrent.TimeUnit;
23+
24+import com.google.common.util.concurrent.Futures;
25+import com.google.common.util.concurrent.ListenableFuture;
26+import com.google.common.util.concurrent.Uninterruptibles;
27+import org.assertj.core.util.Maps;
28+
29+import static com.google.common.collect.Lists.newArrayList;
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.testng.Assert.fail;
32+
33+/**
34+ * A convenience utility for executing queries against a {@link Session} and tracking
35+ * which hosts were queried.
36+ */
37+public class QueryTracker {
38+ static final String QUERY = "select * from test.foo";
39+
40+ Map<InetAddress, Integer> coordinators = Maps.newConcurrentHashMap();
41+
42+ public void query(Session session, int times) {
43+ query(session, times, ConsistencyLevel.ONE);
44+ }
45+
46+ public void query(Session session, int times, ConsistencyLevel cl) {
47+ query(session, times, cl, null);
48+ }
49+
50+ public void query(Session session, int times, ConsistencyLevel cl, Class<? extends Exception> expectedException) {
51+ Statement statement = session.newSimpleStatement(QUERY);
52+ if(cl != null) {
53+ statement.setConsistencyLevel(cl);
54+ }
55+
56+ query(session, times, statement, expectedException);
57+ }
58+
59+ public void query(Session session, int times, Statement statement) {
60+ query(session, times, statement, null);
61+ }
62+
63+ public void query(Session session, int times, Statement statement, Class<? extends Exception> expectedException) {
64+ List<ListenableFuture<ResultSet>> futures = newArrayList();
65+
66+ for(int i = 0; i < times; i++) {
67+ futures.add(session.executeAsync(statement));
68+ }
69+
70+ try {
71+ List<ResultSet> results = Uninterruptibles.getUninterruptibly(Futures.allAsList(futures), 1, TimeUnit.MINUTES);
72+ for(ResultSet result : results) {
73+ InetAddress coordinator = result.getExecutionInfo().getQueriedHost().getAddress();
74+ Integer n = coordinators.get(coordinator);
75+ coordinators.put(coordinator, n == null ? 1 : n + 1);
76+ }
77+ } catch (ExecutionException ex) {
78+ Throwable cause = ex.getCause();
79+ if(expectedException == null) {
80+ fail("Queries failed", ex);
81+ } else {
82+ assertThat(cause).isInstanceOf(expectedException);
83+ }
84+ } catch (Exception e) {
85+ fail("Queries failed", e);
86+ }
87+ }
88+
89+ public int queryCount(ScassandraCluster sCluster, int dc, int node) {
90+ try {
91+ String host = sCluster.address(dc, node);
92+ Integer queried = coordinators.get(InetAddress.getByName(host));
93+ return queried != null ? queried : 0;
94+ } catch (Exception e) {
95+ throw new RuntimeException(e);
96+ }
97+ }
98+
99+ public void assertQueried(ScassandraCluster sCluster, int dc, int node, int n) {
100+ int queryCount = queryCount(sCluster, dc, node);
101+ assertThat(queryCount)
102+ .as("Expected node %d:%d to be queried %d times but was %d", dc, node, n, queryCount)
103+ .isEqualTo(n);
104+ }
105+
106+ public void reset() {
107+ this.coordinators.clear();
108+ }
109+}
deleted driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +0 −190
@@ -1,190 +0,0 @@
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.*;
29-
30-/**
31- * Launches multiple SCassandra instances, and mocks the appropriate request to make the driver think
32- * that they belong to the same cluster.
33- *
34- * Note: this uses the same addresses as {@link CCMBridge}, so make sure IP aliases have been set up,
35- * and a CCM cluster is not running at the same time.
36- */
37-public class SCassandraCluster {
38- private static final Map<Integer,Map<String,Object>> EMPTY_MAP = ImmutableMap.of();
39- public static final int BINARY_PORT = 9042;
40- private static final int ADMIN_PORT = 9052;
41-
42- private final List<Scassandra> scassandras;
43- private final List<InetAddress> addresses;
44- private final List<PrimingClient> primingClients;
45- private final List<ActivityClient> activityClients;
46- private final Map<Integer,Map<String,Object>> propertyMap;
47-
48- public SCassandraCluster(int nodeCount) {
49- this(CCMBridge.IP_PREFIX, nodeCount);
50- }
51-
52- public SCassandraCluster(String ipPrefix, int nodeCount) {
53- this(ipPrefix, nodeCount, EMPTY_MAP);
54- }
55-
56- public SCassandraCluster(String ipPrefix, int nodeCount, Map<Integer,Map<String,Object>> propertyMap) {
57- scassandras = Lists.newArrayListWithCapacity(nodeCount);
58- addresses = Lists.newArrayListWithCapacity(nodeCount);
59- primingClients = Lists.newArrayListWithCapacity(nodeCount);
60- activityClients = Lists.newArrayListWithCapacity(nodeCount);
61- this.propertyMap = propertyMap;
62-
63- for (int i = 1; i <= nodeCount; i++) {
64- String ip = ipPrefix + i;
65- try {
66- addresses.add(InetAddress.getByName(ip));
67- } catch (UnknownHostException e) {
68- throw new AssertionError(e);
69- }
70- Scassandra scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
71- scassandra.start();
72- scassandras.add(scassandra);
73-
74- // Currently Scassandra#primingClient() uses localhost by default, so build manually:
75- primingClients.add(PrimingClient.builder()
76- .withHost(ip).withPort(scassandra.getAdminPort())
77- .build());
78- activityClients.add(ActivityClient.builder()
79- .withHost(ip).withPort(scassandra.getAdminPort())
80- .build()
81- );
82- }
83- primePeers();
84- }
85-
86- public List<InetAddress> addresses() {
87- return addresses;
88- }
89-
90- public void stop() {
91- for (Scassandra scassandra : scassandras)
92- scassandra.stop();
93- }
94-
95- public void start(int node) {
96- int i = node - 1;
97- scassandras.get(i).start();
98- primePeers(primingClients.get(i), scassandras.get(i));
99- }
100-
101- public void stop(int node) {
102- scassandras.get(node - 1).stop();
103- }
104-
105- public SCassandraCluster prime(int node, PrimingRequest request) {
106- primingClients.get(node - 1).prime(request);
107- return this;
108- }
109-
110- public List<Query> retrieveQueries(int node) {
111- return activityClients.get(node - 1).retrieveQueries();
112- }
113-
114- public List<PreparedStatementExecution> retrievePreparedStatementExecutions(int node){
115- return activityClients.get(node - 1).retrievePreparedStatementExecutions();
116- }
117-
118- public List<PreparedStatementPreparation> retrievePreparedStatementPreparations(int node) {
119- return activityClients.get(node - 1).retrievePreparedStatementPreparations();
120- }
121-
122- public void clearAllPrimes() {
123- for (PrimingClient primingClient : primingClients)
124- primingClient.clearAllPrimes();
125- primePeers();
126- }
127-
128- public void clearAllRecordedActivity() {
129- for (ActivityClient activityClient : activityClients)
130- activityClient.clearAllRecordedActivity();
131- }
132-
133- public Scassandra instance(int node) {
134- return scassandras.get(node -1);
135- }
136-
137- private void primePeers() {
138- for (int i = 0; i < scassandras.size(); i++)
139- primePeers(primingClients.get(i), scassandras.get(i));
140- }
141-
142- @SuppressWarnings("unchecked")
143- private void primePeers(PrimingClient primingClient, Scassandra toIgnore) {
144- List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(scassandras.size());
145- for (int i = 0; i < scassandras.size(); i++) {
146- if (scassandras.get(i).equals(toIgnore))
147- continue;
148- InetAddress address = addresses.get(i);
149- Map<String, ?> row = ImmutableMap.<String, Object>builder()
150- .put("peer", address)
151- .put("rpc_address", address)
152- .put("data_center", getProperty(i, "data_center", "datacenter1"))
153- .put("rack", getProperty(i, "rack1", "rack1"))
154- .put("release_version", getProperty(i, "release_version", "2.0.1"))
155- .put("tokens", getProperty(i, "tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i))))
156- .build();
157-
158- rows.add(row);
159-
160- String query = "SELECT * FROM system.peers WHERE peer='" + address.toString().substring(1) + "'";
161- primingClient.prime(
162- PrimingRequest.queryBuilder()
163- .withQuery(query)
164- .withColumnTypes(SELECT_PEERS_COLUMN_TYPES)
165- .withRows(row)
166- .build());
167- }
168- primingClient.prime(
169- PrimingRequest.queryBuilder()
170- .withQuery("SELECT * FROM system.peers")
171- .withColumnTypes(SELECT_PEERS_COLUMN_TYPES)
172- .withRows(rows)
173- .build());
174- }
175-
176- private Object getProperty(int node, String property, Object defaultValue) {
177- Map<String,Object> nodeProperties = propertyMap.get(node);
178- return nodeProperties != null && nodeProperties.containsKey(property) ? nodeProperties.get(property) : defaultValue;
179- }
180-
181- static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES =
182- ImmutableMap.<String, ColumnTypes>builder()
183- .put("peer", ColumnTypes.Inet)
184- .put("rpc_address", ColumnTypes.Inet)
185- .put("data_center", ColumnTypes.Text)
186- .put("rack", ColumnTypes.Text)
187- .put("release_version", ColumnTypes.Text)
188- .put("tokens", ColumnTypes.TextSet)
189- .build();
190-}
added driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +513 −0
@@ -0,0 +1,513 @@
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.List;
19+import java.util.Map;
20+import java.util.TreeSet;
21+import java.util.concurrent.TimeUnit;
22+
23+import com.beust.jcommander.internal.Lists;
24+import com.beust.jcommander.internal.Maps;
25+import com.google.common.collect.ImmutableList;
26+import com.google.common.collect.ImmutableMap;
27+import com.google.common.collect.ImmutableSet;
28+import org.scassandra.Scassandra;
29+import org.scassandra.ScassandraFactory;
30+import org.scassandra.http.client.PrimingClient;
31+import org.scassandra.http.client.PrimingRequest;
32+import org.slf4j.Logger;
33+import org.slf4j.LoggerFactory;
34+
35+import static org.scassandra.cql.MapType.map;
36+import static org.scassandra.cql.PrimitiveType.*;
37+import static org.scassandra.cql.SetType.set;
38+import static org.scassandra.http.client.PrimingRequest.then;
39+import static org.scassandra.http.client.types.ColumnMetadata.column;
40+
41+import static com.datastax.driver.core.Assertions.assertThat;
42+
43+public class ScassandraCluster {
44+
45+ private static final Logger logger = LoggerFactory.getLogger(ScassandraCluster.class);
46+
47+ private final String ipPrefix;
48+
49+ private final List<Scassandra> instances;
50+
51+ private final Map<Integer, List<Scassandra>> dcNodeMap;
52+
53+ private final List<Map<String, ? extends Object>> keyspaceRows;
54+
55+ private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos;
56+
57+ ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort,
58+ List<Map<String, ? extends Object>> keyspaceRows,
59+ Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos) {
60+ this.ipPrefix = ipPrefix;
61+ this.forcedPeerInfos = forcedPeerInfos;
62+
63+ int node = 1;
64+ ImmutableList.Builder<Scassandra> instanceListBuilder = ImmutableList.builder();
65+ ImmutableMap.Builder<Integer, List<Scassandra>> dcNodeMapBuilder = ImmutableMap.builder();
66+ for (int dc = 0; dc < nodes.length; dc++) {
67+ ImmutableList.Builder<Scassandra> dcNodeListBuilder = ImmutableList.builder();
68+ for (int n = 0; n < nodes[dc]; n++) {
69+ String ip = ipPrefix + node++;
70+ Scassandra instance = ScassandraFactory.createServer(ip, binaryPort, ip, adminPort);
71+ instanceListBuilder = instanceListBuilder.add(instance);
72+ dcNodeListBuilder = dcNodeListBuilder.add(instance);
73+ }
74+ dcNodeMapBuilder.put(dc + 1, dcNodeListBuilder.build());
75+ }
76+ instances = instanceListBuilder.build();
77+ dcNodeMap = dcNodeMapBuilder.build();
78+ this.keyspaceRows = keyspaceRows;
79+ }
80+
81+ public Scassandra node(int node) {
82+ return instances.get(node - 1);
83+ }
84+
85+ public List<Scassandra> nodes() {
86+ return instances;
87+ }
88+
89+ public String address(int node) {
90+ return ipPrefix + node;
91+ }
92+
93+ public Scassandra node(int dc, int node) {
94+ return dcNodeMap.get(dc).get(node - 1);
95+ }
96+
97+ public List<Scassandra> nodes(int dc) {
98+ return dcNodeMap.get(dc);
99+ }
100+
101+ public int ipSuffix(int dc, int node) {
102+ // TODO: Scassandra should be updated to include address to avoid O(n) lookup.
103+ int nodeCount = 0;
104+ for (Integer dcNum : new TreeSet<Integer>(dcNodeMap.keySet())) {
105+ List<Scassandra> nodesInDc = dcNodeMap.get(dc);
106+ for (int n = 0; n < nodesInDc.size(); n++) {
107+ nodeCount++;
108+ if (dcNum == dc && n + 1 == node) {
109+ return nodeCount;
110+ }
111+ }
112+ }
113+ return -1;
114+ }
115+
116+ public String address(int dc, int node) {
117+ // TODO: Scassandra should be updated to include address to avoid O(n) lookup.
118+ int ipSuffix = ipSuffix(dc, node);
119+ return ipSuffix == -1 ? null : ipPrefix + ipSuffix;
120+ }
121+
122+ public Host host(Cluster cluster, int dc, int node) {
123+ String address = address(dc, node);
124+ for (Host host : cluster.getMetadata().getAllHosts()) {
125+ if (host.getAddress().getHostAddress().equals(address)) {
126+ return host;
127+ }
128+ }
129+ return null;
130+ }
131+
132+ public static String datacenter(int dc) {
133+ return "DC" + dc;
134+ }
135+
136+ public void init() {
137+ for (Map.Entry<Integer, List<Scassandra>> dc : dcNodeMap.entrySet()) {
138+ for (Scassandra node : dc.getValue()) {
139+ node.start();
140+ primeMetadata(node);
141+ }
142+ }
143+ }
144+
145+ public void stop() {
146+ logger.debug("Stopping ScassandraCluster.");
147+ for (Scassandra node : instances) {
148+ node.stop();
149+ }
150+ }
151+
152+ /**
153+ * First stops each node in {@code dc} and then asserts that each node's {@link Host}
154+ * is marked down for the given {@link Cluster} instance within 10 seconds.
155+ *
156+ * If any of the nodes are the control host, this node is stopped last, to reduce
157+ * likelihood of control connection choosing a host that will be shut down.
158+ *
159+ * @param cluster cluster to wait for down statuses on.
160+ * @param dc DC to stop.
161+ */
162+ public void stopDC(Cluster cluster, int dc) {
163+ logger.debug("Stopping all nodes in {}.", datacenter(dc));
164+ // If any node is the control host, stop it last.
165+ int controlHost = -1;
166+ for (int i = 1; i <= nodes(dc).size(); i++) {
167+ int id = ipSuffix(dc, i);
168+ Host host = TestUtils.findHost(cluster, id);
169+ if (cluster.manager.controlConnection.connectedHost() == host) {
170+ logger.debug("Node {} identified as control host. Stopping last.", id);
171+ controlHost = id;
172+ continue;
173+ }
174+ stop(cluster, id);
175+ }
176+
177+ if (controlHost != -1) {
178+ stop(cluster, controlHost);
179+ }
180+ }
181+
182+ /**
183+ * Stops a node by id and then asserts that its {@link Host} is marked down
184+ * for the given {@link Cluster} instance within 10 seconds.
185+ *
186+ * @param cluster cluster to wait for down status on.
187+ * @param node Node to stop.
188+ */
189+ public void stop(Cluster cluster, int node) {
190+ logger.debug("Stopping node {}.", node);
191+ Scassandra scassandra = node(node);
192+ scassandra.stop();
193+ assertThat(cluster).host(node).goesDownWithin(10, TimeUnit.SECONDS);
194+ }
195+
196+ /**
197+ * Stops a node by dc and id and then asserts that its {@link Host} is marked down
198+ * for the given {@link Cluster} instance within 10 seconds.
199+ *
200+ * @param cluster cluster to wait for down status on.
201+ * @param dc Data center node is in.
202+ * @param node Node to stop.
203+ */
204+ public void stop(Cluster cluster, int dc, int node) {
205+ logger.debug("Stopping node {} in {}.", node, datacenter(dc));
206+ stop(cluster, ipSuffix(dc, node));
207+ }
208+
209+ /**
210+ * First starts each node in {@code dc} and then asserts that each node's {@link Host}
211+ * is marked up for the given {@link Cluster} instance within 10 seconds.
212+ *
213+ * @param cluster cluster to wait for up statuses on.
214+ * @param dc DC to start.
215+ */
216+ public void startDC(Cluster cluster, int dc) {
217+ logger.debug("Starting all nodes in {}.", datacenter(dc));
218+ for (int i = 1; i <= nodes(dc).size(); i++) {
219+ int id = ipSuffix(dc, i);
220+ start(cluster, id);
221+ }
222+ }
223+
224+ /**
225+ * Starts a node by id and then asserts that its {@link Host} is marked up
226+ * for the given {@link Cluster} instance within 10 seconds.
227+ *
228+ * @param cluster cluster to wait for up status on.
229+ * @param node Node to start.
230+ */
231+ public void start(Cluster cluster, int node) {
232+ logger.debug("Starting node {}.", node);
233+ Scassandra scassandra = node(node);
234+ scassandra.start();
235+ assertThat(cluster).host(node).comesUpWithin(10, TimeUnit.SECONDS);
236+ }
237+
238+ /**
239+ * Starts a node by dc and id and then asserts that its {@link Host} is marked up
240+ * for the given {@link Cluster} instance within 10 seconds.
241+ *
242+ * @param cluster cluster to wait for up status on.
243+ * @param dc Data center node is in.
244+ * @param node Node to start.
245+ */
246+ public void start(Cluster cluster, int dc, int node) {
247+ logger.debug("Starting node {} in {}.", node, datacenter(dc));
248+ start(cluster, ipSuffix(dc, node));
249+ }
250+
251+ private List<Long> getTokensForDC(int dc) {
252+ // Offset DCs by dc * 100 to ensure unique tokens.
253+ int offset = (dc - 1) * 100;
254+ int dcNodeCount = nodes(dc).size();
255+ List<Long> tokens = Lists.newArrayList(dcNodeCount);
256+ for (int i = 0; i < dcNodeCount; i++) {
257+ tokens.add((i * ((long)Math.pow(2, 64) / dcNodeCount) + offset));
258+ }
259+ return tokens;
260+ }
261+
262+ private void primeMetadata(Scassandra node) {
263+ PrimingClient client = node.primingClient();
264+ int nodeCount = 0;
265+
266+ ImmutableList.Builder<Map<String, ?>> rows = ImmutableList.builder();
267+ for (Integer dc : new TreeSet<Integer>(dcNodeMap.keySet())) {
268+ List<Scassandra> nodesInDc = dcNodeMap.get(dc);
269+ List<Long> tokens = getTokensForDC(dc);
270+ for (int n = 0; n < nodesInDc.size(); n++) {
271+ String address = ipPrefix + ++nodeCount;
272+ Scassandra peer = nodesInDc.get(n);
273+ String query;
274+ Map<String, Object> row;
275+ org.scassandra.http.client.types.ColumnMetadata[] metadata;
276+ if (node == peer) { // prime system.local.
277+ metadata = SELECT_LOCAL;
278+ query = "SELECT * FROM system.local WHERE key='local'";
279+ row = ImmutableMap.<String, Object>builder()
280+ .put("key", "local")
281+ .put("bootstrapped", "COMPLETED")
282+ .put("broadcast_address", address)
283+ .put("cluster_name", "scassandra")
284+ .put("cql_version", "3.2.0")
285+ .put("data_center", datacenter(dc))
286+ .put("listen_address", address)
287+ .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
288+ .put("rack", "rack1")
289+ .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
290+ .put("tokens", ImmutableSet.of(tokens.get(n)))
291+ .build();
292+ } else { // prime system.peers.
293+ query = "SELECT * FROM system.peers WHERE peer='" + address + "'";
294+ metadata = SELECT_PEERS;
295+ row = ImmutableMap.<String, Object>builder()
296+ .put("peer", address)
297+ .put("rpc_address", address)
298+ .put("data_center", datacenter(dc))
299+ .put("rack", "rack1")
300+ .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
301+ .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
302+ .build();
303+ rows.add(row);
304+ }
305+ client.prime(PrimingRequest.queryBuilder()
306+ .withQuery(query)
307+ .withThen(then()
308+ .withColumnTypes(metadata)
309+ .withRows(row)
310+ .build())
311+ .build());
312+ }
313+ }
314+
315+ client.prime(PrimingRequest.queryBuilder()
316+ .withQuery("SELECT * FROM system.peers")
317+ .withThen(then()
318+ .withColumnTypes(SELECT_PEERS)
319+ .withRows(rows.build())
320+ .build())
321+ .build());
322+
323+ // Needed to ensure cluster_name matches what we expect on connection.
324+ Map<String, Object> clusterNameRow = ImmutableMap.<String, Object>builder()
325+ .put("cluster_name", "scassandra")
326+ .build();
327+ client.prime(PrimingRequest.queryBuilder()
328+ .withQuery("select cluster_name from system.local")
329+ .withThen(then()
330+ .withColumnTypes(SELECT_CLUSTER_NAME)
331+ .withRows(clusterNameRow)
332+ .build())
333+ .build());
334+
335+ // Prime keyspaces
336+ client.prime(PrimingRequest.queryBuilder()
337+ .withQuery("SELECT * FROM system.schema_keyspaces")
338+ .withThen(then()
339+ .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
340+ .withRows(keyspaceRows)
341+ .build())
342+ .build());
343+ }
344+
345+ private Object getPeerInfo(int dc, int node, String property, Object defaultValue) {
346+ Map<Integer, Map<String, Object>> forDc = forcedPeerInfos.get(dc);
347+ if (forDc == null)
348+ return defaultValue;
349+
350+ Map<String, Object> forNode = forDc.get(node);
351+ if (forNode == null)
352+ return defaultValue;
353+
354+ return (forNode.containsKey(property))
355+ ? forNode.get(property)
356+ : defaultValue;
357+ }
358+
359+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_PEERS = {
360+ column("peer", INET),
361+ column("rpc_address", INET),
362+ column("data_center", TEXT),
363+ column("rack", TEXT),
364+ column("release_version", TEXT),
365+ column("tokens", set(TEXT))
366+ };
367+
368+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_LOCAL = {
369+ column("key", TEXT),
370+ column("bootstrapped", TEXT),
371+ column("broadcast_address", INET),
372+ column("cluster_name", TEXT),
373+ column("cql_version", TEXT),
374+ column("data_center", TEXT),
375+ column("listen_address", INET),
376+ column("partitioner", TEXT),
377+ column("rack", TEXT),
378+ column("release_version", TEXT),
379+ column("tokens", set(TEXT)),
380+ };
381+
382+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_CLUSTER_NAME = {
383+ column("cluster_name", TEXT)
384+ };
385+
386+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_KEYSPACES = {
387+ column("durable_writes", BOOLEAN),
388+ column("keyspace_name", TEXT),
389+ column("strategy_class", TEXT),
390+ column("strategy_options", TEXT)
391+ };
392+
393+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMN_FAMILIES = {
394+ column("bloom_filter_fp_chance", DOUBLE),
395+ column("caching", TEXT),
396+ column("cf_id", UUID),
397+ column("column_aliases", TEXT),
398+ column("columnfamily_name", TEXT),
399+ column("comment", TEXT),
400+ column("compaction_strategy_class", TEXT),
401+ column("compaction_strategy_options", TEXT),
402+ column("comparator", TEXT),
403+ column("compression_parameters", TEXT),
404+ column("default_time_to_live", INT),
405+ column("default_validator", TEXT),
406+ column("dropped_columns", map(TEXT, BIG_INT)),
407+ column("gc_grace_seconds", INT),
408+ column("index_interval", INT),
409+ column("is_dense", BOOLEAN),
410+ column("key_aliases", TEXT),
411+ column("key_validator", TEXT),
412+ column("keyspace_name", TEXT),
413+ column("local_read_repair_chance", DOUBLE),
414+ column("max_compaction_threshold", INT),
415+ column("max_index_interval", INT),
416+ column("memtable_flush_period_in_ms", INT),
417+ column("min_compaction_threshold", INT),
418+ column("min_index_interval", INT),
419+ column("read_repair_chance", DOUBLE),
420+ column("speculative_retry", TEXT),
421+ column("subcomparator", TEXT),
422+ column("type", TEXT),
423+ column("value_alias", TEXT)
424+ };
425+
426+ static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMNS = {
427+ column("column_name", TEXT),
428+ column("columnfamily_name", TEXT),
429+ column("component_index", INT),
430+ column("index_name", TEXT),
431+ column("index_options", TEXT),
432+ column("index_type", TEXT),
433+ column("keyspace_name", TEXT),
434+ column("type", TEXT),
435+ column("validator", TEXT),
436+ };
437+
438+ public static ScassandraClusterBuilder builder() {
439+ return new ScassandraClusterBuilder();
440+ }
441+
442+ public static class ScassandraClusterBuilder {
443+
444+ private Integer nodes[] = { 1 };
445+ private String ipPrefix = CCMBridge.IP_PREFIX;
446+ private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList();
447+ private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap();
448+
449+ public ScassandraClusterBuilder withNodes(Integer... nodes) {
450+ this.nodes = nodes;
451+ return this;
452+ }
453+
454+ public ScassandraClusterBuilder withIpPrefix(String ipPrefix) {
455+ this.ipPrefix = ipPrefix;
456+ return this;
457+ }
458+
459+ public ScassandraClusterBuilder withSimpleKeyspace(String name, int replicationFactor) {
460+ Map<String, Object> simpleKeyspaceRow = ImmutableMap.<String, Object>builder()
461+ .put("durable_writes", false)
462+ .put("keyspace_name", name)
463+ .put("strategy_class", "SimpleStrategy")
464+ .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
465+ .build();
466+
467+ keyspaceRows.add(simpleKeyspaceRow);
468+ return this;
469+ }
470+
471+ public ScassandraClusterBuilder withNetworkTopologyKeyspace(String name, Map<Integer, Integer> replicationFactors) {
472+ StringBuilder strategyOptionsBuilder = new StringBuilder("{");
473+ for (Map.Entry<Integer, Integer> dc : replicationFactors.entrySet()) {
474+ strategyOptionsBuilder.append("\"");
475+ strategyOptionsBuilder.append(datacenter(dc.getKey()));
476+ strategyOptionsBuilder.append("\":\"");
477+ strategyOptionsBuilder.append(dc.getValue());
478+ strategyOptionsBuilder.append("\",");
479+ }
480+
481+ String strategyOptions = strategyOptionsBuilder.substring(0, strategyOptionsBuilder.length() - 1) + "}";
482+
483+ Map<String, Object> ntsKeyspaceRow = ImmutableMap.<String, Object>builder()
484+ .put("durable_writes", false)
485+ .put("keyspace_name", name)
486+ .put("strategy_class", "NetworkTopologyStrategy")
487+ .put("strategy_options", strategyOptions)
488+ .build();
489+
490+ keyspaceRows.add(ntsKeyspaceRow);
491+ return this;
492+ }
493+
494+ public ScassandraClusterBuilder forcePeerInfo(int dc, int node, String name, Object value) {
495+ Map<Integer, Map<String, Object>> forDc = forcedPeerInfos.get(dc);
496+ if (forDc == null) {
497+ forDc = Maps.newHashMap();
498+ forcedPeerInfos.put(dc, forDc);
499+ }
500+ Map<String, Object> forNode = forDc.get(node);
501+ if (forNode == null) {
502+ forNode = Maps.newHashMap();
503+ forDc.put(node, forNode);
504+ }
505+ forNode.put(name, value);
506+ return this;
507+ }
508+
509+ public ScassandraCluster build() {
510+ return new ScassandraCluster(nodes, ipPrefix, 9042, 9052, keyspaceRows, forcedPeerInfos);
511+ }
512+ }
513+}
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +34 −31
@@ -20,6 +20,7 @@
2020 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
23+import org.scassandra.Scassandra;
2324 import org.scassandra.http.client.PrimingRequest;
2425 import org.testng.annotations.*;
2526
@@ -27,12 +28,14 @@
2728 import com.datastax.driver.core.policies.RetryPolicy;
2829
2930 import static com.datastax.driver.core.Assertions.assertThat;
31+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
32+
3033 import static org.mockito.Mockito.mock;
3134 import static org.mockito.Mockito.times;
3235 import static org.mockito.Mockito.verify;
3336
3437 public class SpeculativeExecutionTest {
35- SCassandraCluster scassandras;
38+ ScassandraCluster scassandras;
3639
3740 Cluster cluster = null;
3841 SortingLoadBalancingPolicy loadBalancingPolicy;
@@ -40,23 +43,22 @@
4043 Host host1, host2, host3;
4144 Session session;
4245
43- @BeforeClass(groups = "short")
44- public void beforeClass() {
45- scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 3);
46- }
47-
4846 @BeforeMethod(groups = "short")
4947 public void beforeMethod() {
48+ scassandras = ScassandraCluster.builder().withNodes(3).build();
49+ scassandras.init();
50+
5051 int speculativeExecutionDelay = 200;
5152
5253 loadBalancingPolicy = new SortingLoadBalancingPolicy();
5354 cluster = Cluster.builder()
54- .addContactPoint(CCMBridge.ipOfNode(2))
55+ .addContactPoint(scassandras.address(2))
5556 .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet
5657 .withLoadBalancingPolicy(loadBalancingPolicy)
5758 .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
5859 .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
5960 .withRetryPolicy(new CustomRetryPolicy())
61+ .withNettyOptions(nonQuietClusterCloseOptions)
6062 .build();
6163
6264 session = cluster.connect();
@@ -68,9 +70,17 @@
6870 errors = cluster.getMetrics().getErrorMetrics();
6971 }
7072
73+ @AfterMethod(groups = "short")
74+ public void afterMethod() {
75+ if (cluster != null)
76+ cluster.close();
77+ if (scassandras != null)
78+ scassandras.stop();
79+ }
80+
7181 @Test(groups = "short")
7282 public void should_not_start_speculative_execution_if_first_execution_completes_successfully() {
73- scassandras.prime(1, PrimingRequest.queryBuilder()
83+ scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
7484 .withQuery("mock query")
7585 .withRows(row("result", "result1"))
7686 .build()
@@ -89,12 +99,14 @@
8999 @Test(groups = "short")
90100 public void should_not_start_speculative_execution_if_first_execution_retries_but_is_still_fast_enough() {
91101 // will retry once on this node:
92- scassandras.prime(1, PrimingRequest.queryBuilder()
102+ scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
93103 .withQuery("mock query")
94104 .withConsistency(PrimingRequest.Consistency.TWO)
95105 .withResult(PrimingRequest.Result.read_request_timeout)
96106 .build()
97- ).prime(1, PrimingRequest.queryBuilder()
107+ );
108+
109+ scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
98110 .withQuery("mock query")
99111 .withConsistency(PrimingRequest.Consistency.ONE)
100112 .withRows(row("result", "result1"))
@@ -117,12 +129,14 @@
117129
118130 @Test(groups = "short")
119131 public void should_start_speculative_execution_if_first_execution_takes_too_long() {
120- scassandras.prime(1, PrimingRequest.queryBuilder()
132+ scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
121133 .withQuery("mock query")
122134 .withFixedDelay(400)
123135 .withRows(row("result", "result1"))
124136 .build()
125- ).prime(2, PrimingRequest.queryBuilder()
137+ );
138+
139+ scassandras.node(2).primingClient().prime(PrimingRequest.queryBuilder()
126140 .withQuery("mock query")
127141 .withRows(row("result", "result2"))
128142 .build()
@@ -142,23 +156,25 @@
142156 // Rely on read timeouts to trigger errors that cause an execution to move to the next node
143157 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1000);
144158
145- scassandras
159+ scassandras.node(1).primingClient()
146160 // execution1 starts with host1, which will time out at t=1000
147- .prime(1, PrimingRequest.queryBuilder()
161+ .prime(PrimingRequest.queryBuilder()
148162 .withQuery("mock query")
149163 .withFixedDelay(2000)
150164 .withRows(row("result", "result1"))
151- .build())
165+ .build());
152166 // at t=1000, execution1 moves to host3, which eventually succeeds at t=1500
153- .prime(3, PrimingRequest.queryBuilder()
167+ scassandras.node(3).primingClient()
168+ .prime(PrimingRequest.queryBuilder()
154169 .withQuery("mock query")
155170 .withFixedDelay(500)
156171 .withRows(row("result", "result3"))
157- .build())
172+ .build());
158173 // meanwhile, execution2 starts at t=200, using host2 which times out at t=1200
159174 // at that time, the query plan is empty so execution2 fails
160175 // The goal of this test is to check that execution2 does not fail the query, since execution1 is still running
161- .prime(2, PrimingRequest.queryBuilder()
176+ scassandras.node(2).primingClient()
177+ .prime(PrimingRequest.queryBuilder()
162178 .withQuery("mock query")
163179 .withFixedDelay(2000)
164180 .withRows(row("result", "result2"))
@@ -205,19 +221,6 @@
205221 }
206222 }
207223
208- @AfterMethod(groups = "short")
209- public void afterMethod() {
210- scassandras.clearAllPrimes();
211- if (cluster != null)
212- cluster.close();
213- }
214-
215- @AfterClass(groups = "short")
216- public void afterClass() {
217- if (scassandras != null)
218- scassandras.stop();
219- }
220-
221224 /**
222225 * Custom retry policy that retries at ONE on read timeout.
223226 * This deals with the fact that Scassandra only allows read timeouts with 0 replicas.
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +14 −0
@@ -27,6 +27,7 @@
2727 import java.util.concurrent.TimeUnit;
2828
2929 import com.google.common.util.concurrent.Futures;
30+import com.google.common.util.concurrent.Uninterruptibles;
3031 import io.netty.channel.EventLoopGroup;
3132 import org.scassandra.Scassandra;
3233 import org.scassandra.ScassandraFactory;
@@ -600,6 +601,19 @@
600601 return null;
601602 }
602603
604+ public static Host findOrWaitForControlConnection(final Cluster cluster, long duration, TimeUnit unit) {
605+ ControlConnection controlConnection = cluster.manager.controlConnection;
606+ long durationNs = TimeUnit.NANOSECONDS.convert(duration, unit);
607+ long start = System.nanoTime();
608+ while(System.nanoTime() - start < durationNs) {
609+ if(controlConnection.isOpen()) {
610+ return controlConnection.connectedHost();
611+ }
612+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
613+ }
614+ return null;
615+ }
616+
603617 public static HostConnectionPool poolOf(Session session, int hostNumber) {
604618 SessionManager sessionManager = (SessionManager)session;
605619 return sessionManager.pools.get(findHost(session.getCluster(), hostNumber));
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +16 −10
@@ -20,6 +20,7 @@
2020
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
23+import org.scassandra.Scassandra;
2324 import org.scassandra.http.client.PrimingRequest;
2425 import org.testng.annotations.*;
2526
@@ -36,7 +37,7 @@
3637
3738 public class ExceptionsScassandraTest {
3839
39- protected SCassandraCluster scassandras;
40+ protected ScassandraCluster scassandras;
4041 protected Cluster cluster;
4142 protected Metrics.Errors errors;
4243 protected Host host1;
@@ -44,7 +45,8 @@
4445
4546 @BeforeClass(groups = "short")
4647 public void beforeClass() {
47- scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 1);
48+ scassandras = ScassandraCluster.builder().withNodes(1).build();
49+ scassandras.init();
4850 }
4951
5052 @BeforeMethod(groups = "short")
@@ -56,8 +58,11 @@
5658 session = cluster.connect();
5759 host1 = TestUtils.findHost(cluster, 1);
5860 errors = cluster.getMetrics().getErrorMetrics();
59- scassandras.clearAllPrimes();
60- scassandras.clearAllRecordedActivity();
61+
62+ for(Scassandra node : scassandras.nodes()) {
63+ node.primingClient().clearAllPrimes();
64+ node.activityClient().clearAllRecordedActivity();
65+ }
6166 }
6267
6368 @Test(groups = "short")
@@ -110,11 +115,10 @@
110115 }
111116
112117 protected void simulateError(int hostNumber, PrimingRequest.Result result) {
113- scassandras
114- .prime(hostNumber, PrimingRequest.queryBuilder()
115- .withQuery("mock query")
116- .withResult(result)
117- .build());
118+ scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
119+ .withQuery("mock query")
120+ .withResult(result)
121+ .build());
118122 }
119123
120124 private static List<Map<String, ?>> row(String key, String value) {
@@ -131,7 +135,9 @@
131135
132136 @AfterMethod(groups = "short")
133137 public void afterMethod() {
134- scassandras.clearAllPrimes();
138+ for(Scassandra node : scassandras.nodes()) {
139+ node.primingClient().clearAllPrimes();
140+ }
135141 if (cluster != null)
136142 cluster.close();
137143 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +18 −22
@@ -21,6 +21,7 @@
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
2323 import org.mockito.Mockito;
24+import org.scassandra.Scassandra;
2425 import org.scassandra.http.client.PrimingRequest;
2526 import org.testng.annotations.AfterClass;
2627 import org.testng.annotations.AfterMethod;
@@ -35,6 +36,8 @@
3536
3637 import com.datastax.driver.core.*;
3738
39+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
40+
3841 /**
3942 * Base class for retry policy integration tests.
4043 *
@@ -46,7 +49,7 @@
4649 * tests in child classes.
4750 */
4851 public class AbstractRetryPolicyIntegrationTest {
49- protected SCassandraCluster scassandras;
52+ protected ScassandraCluster scassandras;
5053 protected Cluster cluster = null;
5154 protected Metrics.Errors errors;
5255 protected Host host1, host2, host3;
@@ -58,13 +61,11 @@
5861 this.retryPolicy = Mockito.spy(retryPolicy);
5962 }
6063
61- @BeforeClass(groups = "short")
62- public void beforeClass() {
63- scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 3);
64- }
65-
6664 @BeforeMethod(groups = "short")
6765 public void beforeMethod() {
66+ scassandras = ScassandraCluster.builder().withNodes(3).build();
67+ scassandras.init();
68+
6869 cluster = Cluster.builder()
6970 .addContactPoint(CCMBridge.ipOfNode(1))
7071 .withRetryPolicy(retryPolicy)
@@ -75,7 +76,7 @@
7576 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
7677 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
7778 .setHeartbeatIntervalSeconds(0))
78- .withPort(SCassandraCluster.BINARY_PORT)
79+ .withNettyOptions(nonQuietClusterCloseOptions)
7980 .build();
8081
8182 session = cluster.connect();
@@ -87,21 +88,21 @@
8788 errors = cluster.getMetrics().getErrorMetrics();
8889
8990 Mockito.reset(retryPolicy);
90- scassandras.clearAllPrimes();
91- scassandras.clearAllRecordedActivity();
91+
92+ for(Scassandra node : scassandras.nodes()) {
93+ node.activityClient().clearAllRecordedActivity();
94+ }
9295 }
9396
9497 protected void simulateError(int hostNumber, PrimingRequest.Result result) {
95- scassandras
96- .prime(hostNumber, PrimingRequest.queryBuilder()
97- .withQuery("mock query")
98- .withResult(result)
99- .build());
98+ scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
99+ .withQuery("mock query")
100+ .withResult(result)
101+ .build());
100102 }
101103
102104 protected void simulateNormalResponse(int hostNumber) {
103- scassandras
104- .prime(hostNumber, PrimingRequest.queryBuilder()
105+ scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
105106 .withQuery("mock query")
106107 .withRows(row("result", "result1"))
107108 .build());
@@ -136,18 +137,13 @@
136137 }
137138
138139 protected void assertQueried(int hostNumber, int times) {
139- assertThat(scassandras.retrieveQueries(hostNumber)).hasSize(times);
140+ assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times);
140141 }
141142
142143 @AfterMethod(groups = "short")
143144 public void afterMethod() {
144- scassandras.clearAllPrimes();
145145 if (cluster != null)
146146 cluster.close();
147- }
148-
149- @AfterClass(groups = "short")
150- public void afterClass() {
151147 if (scassandras != null)
152148 scassandras.stop();
153149 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +451 −105
@@ -16,183 +16,529 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import java.util.Collection;
19-import java.util.Set;
20-import java.util.concurrent.CopyOnWriteArraySet;
2119
20+import com.google.common.collect.Lists;
2221 import org.apache.log4j.Level;
2322 import org.apache.log4j.Logger;
24-import org.testng.annotations.*;
25-
26-import static org.assertj.core.api.Assertions.assertThat;
27-import static org.testng.Assert.assertEquals;
28-
29-import com.datastax.driver.core.*;
23+import org.mockito.ArgumentCaptor;
24+import org.mockito.Captor;
25+import org.mockito.Mockito;
26+import org.testng.annotations.AfterMethod;
27+import org.testng.annotations.BeforeMethod;
28+import org.testng.annotations.Test;
29+
30+import static com.google.common.collect.Lists.newArrayList;
31+import static org.mockito.Matchers.any;
32+import static org.mockito.Mockito.spy;
33+import static org.mockito.MockitoAnnotations.initMocks;
34+
35+import com.datastax.driver.core.Cluster;
36+import com.datastax.driver.core.ConsistencyLevel;
37+import com.datastax.driver.core.DataProviders;
38+import com.datastax.driver.core.Host;
39+import com.datastax.driver.core.MemoryAppender;
40+import com.datastax.driver.core.QueryTracker;
41+import com.datastax.driver.core.ScassandraCluster;
42+import com.datastax.driver.core.Session;
43+import com.datastax.driver.core.SocketOptions;
44+import com.datastax.driver.core.exceptions.NoHostAvailableException;
45+
46+import static com.datastax.driver.core.Assertions.assertThat;
47+import static com.datastax.driver.core.ScassandraCluster.datacenter;
48+import static com.datastax.driver.core.TestUtils.findHost;
49+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3050
3151 public class DCAwareRoundRobinPolicyTest {
52+
3253 Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class);
3354 MemoryAppender logs;
34- CCMBridge ccm;
35-
36- @BeforeClass(groups = "short")
37- public void createCcm() {
38- // Two-DC cluster with one host in each DC
39- ccm = CCMBridge.builder("test").withNodes(1, 1).build();
40- }
55+ QueryTracker queryTracker;
4156
42- @AfterClass(groups = "short")
43- public void deleteCcm() {
44- if (ccm != null)
45- ccm.remove();
46- }
57+ @Captor
58+ ArgumentCaptor<Collection<Host>> initHostsCaptor;
4759
4860 @BeforeMethod(groups = "short")
49- public void startRecordingLogs() {
61+ public void setUp() {
62+ initMocks(this);
5063 policyLogger.setLevel(Level.WARN);
5164 logs = new MemoryAppender();
5265 policyLogger.addAppender(logs);
66+ queryTracker = new QueryTracker();
5367 }
5468
5569 @AfterMethod(groups = "short")
56- public void stopRecordingLogs() {
70+ public void tearDown() {
5771 policyLogger.setLevel(null);
5872 policyLogger.removeAppender(logs);
5973 }
6074
75+ private Cluster.Builder builder() {
76+ return Cluster.builder()
77+ // Close cluster immediately to speed up tests.
78+ .withNettyOptions(nonQuietClusterCloseOptions);
79+ }
80+
81+ /**
82+ * Ensures that {@link DCAwareRoundRobinPolicy} will round robin within hosts in the explicitly specific local DC
83+ * via {@link DCAwareRoundRobinPolicy.Builder#withLocalDc(String)}
84+ *
85+ * @test_category load_balancing:dc_aware
86+ */
6187 @Test(groups = "short")
62- public void should_use_local_dc_from_contact_points_when_not_explicitly_specified() {
63- Cluster cluster = null;
64- CountingDCAwarePolicy policy = new CountingDCAwarePolicy();
88+ public void should_round_robin_within_local_dc() {
89+ // given: a 10 node 2 DC cluster.
90+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
91+ Cluster cluster = builder()
92+ .addContactPoint(sCluster.address(1, 1))
93+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build())
94+ .build();
95+ try {
96+ sCluster.init();
97+
98+ Session session = cluster.connect();
99+ // when: a query is executed 50 times.
100+ queryTracker.query(session, 50);
101+
102+ // then: each node in local DC should get an equal (10) number of requests.
103+ // then: no node in the remote DC should get a request.
104+ for(int i = 1; i <= 5; i++) {
105+ queryTracker.assertQueried(sCluster, 1, i, 10);
106+ queryTracker.assertQueried(sCluster, 2, i, 0);
107+ }
108+ } finally {
109+ cluster.close();
110+ sCluster.stop();
111+ }
112+ }
113+
114+ /**
115+ * Ensures that {@link DCAwareRoundRobinPolicy} does not use remote hosts if replicas in the local DC are UP.
116+ *
117+ * @test_category load_balancing:dc_aware
118+ */
119+ @Test(groups="short")
120+ public void should_not_use_remote_hosts_if_some_nodes_are_up_in_local_dc() {
121+ // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts.
122+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
123+ Cluster cluster = builder()
124+ .addContactPoint(sCluster.address(1, 1))
125+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).withUsedHostsPerRemoteDc(2).build())
126+ .build();
65127
66128 try {
67- // Pass host1 as contact point
68- cluster = Cluster.builder()
69- .addContactPoint(CCMBridge.ipOfNode(1))
70- .withLoadBalancingPolicy(policy)
71- .build();
72- cluster.init();
129+ sCluster.init();
130+
131+ Session session = cluster.connect();
132+
133+ // when: a query is executed 50 times and some hosts are down in the local DC.
134+ sCluster.stop(cluster, 1, 5);
135+ sCluster.stop(cluster, 1, 3);
136+ sCluster.stop(cluster, 1, 1);
137+ assertThat(cluster).controlHost().isNotNull();
138+ queryTracker.query(session, 50);
139+
140+ // then: all requests should be distributed to the remaining up nodes in local DC.
141+ queryTracker.assertQueried(sCluster, 1, 2, 25);
142+ queryTracker.assertQueried(sCluster, 1, 4, 25);
143+
144+ // then: no nodes in the remote DC should have been queried.
145+ for(int i = 1; i <= 5; i++) {
146+ queryTracker.assertQueried(sCluster, 2, i, 0);
147+ }
148+ } finally {
149+ cluster.close();
150+ sCluster.stop();
151+ }
152+ }
73153
74- Host host1 = TestUtils.findHost(cluster, 1);
154+ /**
155+ * Ensures that {@link DCAwareRoundRobinPolicy} will round robin on remote hosts but only if
156+ * no local replicas are available and only within the number of hosts configured by
157+ * {@link DCAwareRoundRobinPolicy.Builder#withUsedHostsPerRemoteDc(int)}
158+ *
159+ * @test_category load_balancing:dc_aware
160+ */
161+ @Test(groups="short")
162+ public void should_round_robin_on_remote_hosts_when_no_up_nodes_in_local_dc() {
163+ // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts.
164+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build();
165+ Cluster cluster = builder()
166+ .addContactPoint(sCluster.address(1, 1))
167+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
168+ .build();
169+
170+ try {
171+ sCluster.init();
172+
173+ Session session = cluster.connect();
75174
76- // Policy's localDC should be the one from the contact point
77- assertThat(policy.getLocalDc()).isEqualTo(host1.getDatacenter());
175+ sCluster.stopDC(cluster, 1);
78176
79- assertThat(policy.initHosts).containsExactly(host1);
177+ // Wait for control connection to be re-established, needed as
178+ // control connection attempts increment LBP counter.
179+ assertThat(cluster).controlHost().isNotNull();
80180
81- assertThat(logs.get())
82- .doesNotContain("Some contact points don't match local data center");
181+ // when: a query is executed 50 times and all hosts are down in local DC.
182+ queryTracker.query(session, 50);
83183
184+ // then: only usedHostsPerRemoteDc nodes in the remote DC should get requests.
185+ Collection<Integer> queryCounts = newArrayList();
186+ for (int i = 1; i <= 5; i++) {
187+ queryCounts.add(queryTracker.queryCount(sCluster, 2, i));
188+ }
189+ assertThat(queryCounts).containsOnly(0, 0, 0, 25, 25);
84190 } finally {
85- if (cluster != null)
86- cluster.close();
191+ cluster.close();
192+ sCluster.stop();
87193 }
88194 }
89195
90- @Test(groups = "short")
91- public void should_warn_if_contact_points_have_different_dcs_when_not_explicitly_specified() {
92- Cluster cluster = null;
93- CountingDCAwarePolicy policy = new CountingDCAwarePolicy();
196+ /**
197+ * Ensures that {@link DCAwareRoundRobinPolicy} will by default only use remote hosts for non DC local
198+ * Consistency Levels. In the case that a DC local Consistency Level is provided a
199+ * {@link NoHostAvailableException} is raised.
200+ *
201+ * @test_category load_balancing:dc_aware
202+ */
203+ @Test(groups="short", dataProvider="consistencyLevels", dataProviderClass = DataProviders.class)
204+ public void should_only_use_remote_hosts_when_using_non_dc_local_cl(ConsistencyLevel cl) {
205+ // given: a 4 node 2 DC Cluster with a LB policy that specifies to not allow remote dcs for
206+ // a local consistency level.
207+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
208+ Cluster cluster = builder()
209+ .addContactPoint(sCluster.address(1, 1))
210+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build())
211+ .build();
94212
95213 try {
96- // Pass both hosts as contact points, they have different DCs
97- cluster = Cluster.builder()
98- .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
99- .withLoadBalancingPolicy(policy)
100- .build();
101- cluster.init();
214+ sCluster.init();
215+
216+ Session session = cluster.connect();
217+
218+ sCluster.stopDC(cluster, 1);
219+
220+ // Wait for control connection to be re-established, needed as
221+ // control connection attempts increment LBP counter.
222+ assertThat(cluster).controlHost().isNotNull();
223+
224+ // when: a query is executed 50 times and all hosts are down in local DC.
225+ // then: expect a NHAE for a local CL since no local replicas available.
226+ Class<? extends Exception> expectedException = cl.isDCLocal() ? NoHostAvailableException.class : null;
227+ queryTracker.query(session, 50, cl, expectedException);
228+
229+ int expectedQueryCount = cl.isDCLocal() ? 0 : 25;
230+ for (int i = 1; i <= 2; i++) {
231+ queryTracker.assertQueried(sCluster, 1, i, 0);
232+ // then: Remote hosts should only be queried for non local CLs.
233+ queryTracker.assertQueried(sCluster, 2, i, expectedQueryCount);
234+ }
235+ } finally {
236+ cluster.close();
237+ sCluster.stop();
238+ }
239+ }
240+
241+ /**
242+ * Ensures that {@link DCAwareRoundRobinPolicy} will use remote hosts for non DC local
243+ * Consistency Levels if {@link DCAwareRoundRobinPolicy.Builder#allowRemoteDCsForLocalConsistencyLevel} is used.
244+ * In the case that a DC local Consistency Level is provided a {@link NoHostAvailableException} is raised.
245+ *
246+ * @test_category load_balancing:dc_aware
247+ */
248+ @Test(groups="short", dataProvider="consistencyLevels", dataProviderClass = DataProviders.class)
249+ public void should_use_remote_hosts_for_local_cl_when_allowed(ConsistencyLevel cl) {
250+ // given: a 4 node 2 DC Cluster with a LB policy that specifies to allow remote dcs for
251+ // a local consistency level.
252+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
253+ Cluster cluster = builder()
254+ .addContactPoint(sCluster.address(1, 1))
255+ .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder()
256+ .allowRemoteDCsForLocalConsistencyLevel()
257+ .withUsedHostsPerRemoteDc(2).build())
258+ .build();
102259
103- Host host1 = TestUtils.findHost(cluster, 1);
104- Host host2 = TestUtils.findHost(cluster, 2);
260+ try {
261+ sCluster.init();
262+
263+ Session session = cluster.connect();
264+
265+ sCluster.stopDC(cluster, 1);
105266
106- assertThat(policy.initHosts).containsOnly(host1, host2);
267+ // Wait for control connection to be re-established, needed as
268+ // control connection attempts increment LBP counter.
269+ assertThat(cluster).controlHost().isNotNull();
107270
108- assertThat(logs.get())
109- .contains("Some contact points don't match local data center");
271+ // when: a query is executed 50 times and all hosts are down in local DC.
272+ queryTracker.query(session, 50, cl, null);
110273
274+ for (int i = 1; i <= 2; i++) {
275+ queryTracker.assertQueried(sCluster, 1, i, 0);
276+ // then: Remote hosts should be queried.
277+ queryTracker.assertQueried(sCluster, 2, i, 25);
278+ }
111279 } finally {
112- if (cluster != null)
113- cluster.close();
280+ cluster.close();
281+ sCluster.stop();
114282 }
115283 }
116284
285+ /**
286+ * Ensures that when {@link DCAwareRoundRobinPolicy} is wrapped with a {@link HostFilterPolicy} that
287+ * blacklists a data center that nodes in that datacenter are never queried.
288+ *
289+ * @test_category load_balancing:dc_aware
290+ */
117291 @Test(groups = "short")
118- public void should_use_provided_local_dc_and_not_warn_if_contact_points_match() {
119- Cluster cluster = null;
120- String providedLocalDc = "dc1";
121- CountingDCAwarePolicy policy = new CountingDCAwarePolicy(providedLocalDc);
292+ public void should_not_send_requests_to_blacklisted_dc_using_host_filter_policy() {
293+ // given: a 6 node 3 DC cluster with a DCAwareRoundRobinPolicy that is filtering hosts in DC2.
294+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2,2,2).build();
295+ LoadBalancingPolicy loadBalancingPolicy = HostFilterPolicy.fromDCBlackList(
296+ DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
297+ Lists.newArrayList(datacenter(2)));
298+ Cluster cluster = builder()
299+ .addContactPoint(sCluster.address(1, 1))
300+ .withLoadBalancingPolicy(loadBalancingPolicy)
301+ .build();
122302
123303 try {
124- cluster = Cluster.builder()
125- .addContactPoints(CCMBridge.ipOfNode(1))
126- .withLoadBalancingPolicy(policy)
127- .build();
128- cluster.init();
304+ sCluster.init();
305+
306+ Session session = cluster.connect();
307+
308+ // when: A query is made and nodes for the local dc are available.
309+ queryTracker.query(session, 50);
310+
311+ // then: only nodes in the local DC should have been queried.
312+ queryTracker.assertQueried(sCluster, 1, 1, 25);
313+ queryTracker.assertQueried(sCluster, 1, 2, 25);
314+ queryTracker.assertQueried(sCluster, 2, 1, 0);
315+ queryTracker.assertQueried(sCluster, 2, 2, 0);
316+ queryTracker.assertQueried(sCluster, 3, 1, 0);
317+ queryTracker.assertQueried(sCluster, 3, 1, 0);
318+
319+ // when: A query is made and all nodes in the local dc are down.
320+ sCluster.stopDC(cluster, 1);
321+ assertThat(cluster).controlHost().isNotNull();
322+ queryTracker.reset();
323+ queryTracker.query(session, 50);
324+
325+ // then: Only nodes in DC3 should have been queried, since DC2 is blacklisted and DC1 is down.
326+ queryTracker.assertQueried(sCluster, 1, 1, 0);
327+ queryTracker.assertQueried(sCluster, 1, 2, 0);
328+ queryTracker.assertQueried(sCluster, 2, 1, 0);
329+ queryTracker.assertQueried(sCluster, 2, 2, 0);
330+ queryTracker.assertQueried(sCluster, 3, 1, 25);
331+ queryTracker.assertQueried(sCluster, 3, 2, 25);
332+ } finally {
333+ cluster.close();
334+ sCluster.stop();
335+ }
336+ }
337+
338+ /**
339+ * Ensures that when {@link DCAwareRoundRobinPolicy} is wrapped with a {@link HostFilterPolicy} that
340+ * white lists data centers that only nodes in those data centers are queried.
341+ *
342+ * @test_category load_balancing:dc_aware
343+ */
344+ @Test(groups = "short")
345+ public void should_send_requests_to_whitelisted_dcs_using_host_filter_policy() {
346+ // given: a 6 node 3 DC cluster with a DCAwareRoundRobinPolicy that is whitelisting hosts in DC1 and DC2.
347+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2,2,2).build();
348+ LoadBalancingPolicy loadBalancingPolicy = HostFilterPolicy.fromDCWhiteList(
349+ DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(),
350+ Lists.newArrayList(datacenter(1), datacenter(2)));
351+ Cluster cluster = builder()
352+ .addContactPoint(sCluster.address(1, 1))
353+ .withLoadBalancingPolicy(loadBalancingPolicy)
354+ .build();
355+
356+ try {
357+ sCluster.init();
358+
359+ Session session = cluster.connect();
360+
361+ // when: A query is made and nodes for the local dc are available.
362+ queryTracker.query(session, 50);
363+
364+ // then: only nodes in the local DC should have been queried.
365+ queryTracker.assertQueried(sCluster, 1, 1, 25);
366+ queryTracker.assertQueried(sCluster, 1, 2, 25);
367+ queryTracker.assertQueried(sCluster, 2, 1, 0);
368+ queryTracker.assertQueried(sCluster, 2, 2, 0);
369+ queryTracker.assertQueried(sCluster, 3, 1, 0);
370+ queryTracker.assertQueried(sCluster, 3, 1, 0);
371+
372+ // when: A query is made and all nodes in the local dc are down.
373+ sCluster.stopDC(cluster, 1);
374+ assertThat(cluster).controlHost().isNotNull();
375+ queryTracker.reset();
376+ queryTracker.query(session, 50);
377+
378+ // then: Only nodes in DC2 should have been queried, since DC3 is not in the whitelist and DC1 is down.
379+ queryTracker.assertQueried(sCluster, 1, 1, 0);
380+ queryTracker.assertQueried(sCluster, 1, 2, 0);
381+ queryTracker.assertQueried(sCluster, 2, 1, 25);
382+ queryTracker.assertQueried(sCluster, 2, 2, 25);
383+ queryTracker.assertQueried(sCluster, 3, 1, 0);
384+ queryTracker.assertQueried(sCluster, 3, 1, 0);
385+ } finally {
386+ cluster.close();
387+ sCluster.stop();
388+ }
389+ }
129390
130- Host host1 = TestUtils.findHost(cluster, 1);
391+ /**
392+ * Ensures that {@link DCAwareRoundRobinPolicy} will determine it's local DC based on the data center of the
393+ * contact point(s).
394+ *
395+ * @test_category load_balancing:dc_aware
396+ */
397+ @Test(groups="short")
398+ public void should_use_local_dc_from_contact_points_when_not_explicitly_specified() {
399+ // given: a 4 node 2 DC cluster without a local DC specified.
400+ DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build());
401+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
402+ Cluster cluster = builder()
403+ .addContactPoint(sCluster.address(1, 1))
404+ .withLoadBalancingPolicy(policy)
405+ .build();
131406
132- assertEquals(policy.getLocalDc(), providedLocalDc);
407+ try {
408+ sCluster.init();
133409
134- assertThat(policy.initHosts).containsExactly(host1);
410+ Host host1 = findHost(cluster, 1);
135411
136- assertThat(logs.get())
137- .doesNotContain("Some contact points don't match local data center");
412+ // when: the cluster is initialized.
413+ cluster.init();
138414
415+ // then: should have been initialized with only the host given as the contact point.
416+ Mockito.verify(policy).init(any(Cluster.class), initHostsCaptor.capture());
417+ assertThat(initHostsCaptor.getValue()).containsExactly(host1);
418+ // then: the local dc should match the contact points' datacenter.
419+ assertThat(policy.localDc).isEqualTo(host1.getDatacenter());
420+ // then: should not indicate that contact points don't match the local datacenter.
421+ assertThat(logs.get()).doesNotContain("Some contact points don't match local datacenter");
139422 } finally {
140- if (cluster != null)
141- cluster.close();
423+ cluster.close();
424+ sCluster.stop();
142425 }
143426 }
144427
428+ /**
429+ * Ensures that {@link DCAwareRoundRobinPolicy} will determine it's local DC based on the data center of the
430+ * contact point(s) and if contact points in different DCs are detected that a log message is generated
431+ * indicating some contact points don't match the local data center.
432+ *
433+ * @test_category load_balancing:dc_aware
434+ */
145435 @Test(groups = "short")
146- public void should_use_provided_local_dc_and_warn_if_contact_points_dont_match() {
147- Cluster cluster = null;
148- // Provide non-existent DC to make sure none of the contact points matches
149- String providedLocalDc = "dc3";
150- CountingDCAwarePolicy policy = new CountingDCAwarePolicy(providedLocalDc);
436+ public void should_warn_if_contact_points_have_different_dcs_when_not_explicitly_specified() {
437+ // given: a 4 node 2 DC cluster with a Cluster instance with contact points in different DCs
438+ // and no contact point specified.
439+ DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build());
440+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
441+ Cluster cluster = builder()
442+ .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
443+ .withLoadBalancingPolicy(policy)
444+ .build();
151445
152446 try {
153- cluster = Cluster.builder()
154- .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
155- .withLoadBalancingPolicy(policy)
156- .build();
447+ sCluster.init();
448+
449+ Host host1 = findHost(cluster, 1);
450+ Host host3 = findHost(cluster, 3);
451+
452+ // when: the cluster is initialized.
157453 cluster.init();
158454
159- Host host1 = TestUtils.findHost(cluster, 1);
160- Host host2 = TestUtils.findHost(cluster, 2);
455+ // then: should have been initialized with only two hosts given as the contact point.
456+ Mockito.verify(policy).init(any(Cluster.class), initHostsCaptor.capture());
457+ assertThat(initHostsCaptor.getValue()).containsOnly(host1, host3);
458+ // then: should indicate that some contact points don't match the local datacenter.
459+ assertThat(logs.get()).contains("Some contact points don't match local data center");
460+ } finally {
461+ cluster.close();
462+ sCluster.stop();
463+ }
464+ }
465+
466+ /**
467+ * Ensures that {@link DCAwareRoundRobinPolicy} will not log a warning if all contact points match
468+ * the data center provided in {@link DCAwareRoundRobinPolicy.Builder#withLocalDc(String)} and that
469+ * the explicitly provided local data center is used.
470+ *
471+ * @test_category load_balancing:dc_aware
472+ */
473+ @Test(groups = "short")
474+ public void should_use_provided_local_dc_and_not_warn_if_contact_points_match() {
475+ // given: a 4 node 2 DC cluster with a Cluster instance with contact points in different DCs
476+ // and a local DC that doesn't match any contact points.
477+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
478+ DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build());
479+ Cluster cluster = builder()
480+ .addContactPoints(sCluster.address(1, 1))
481+ .withLoadBalancingPolicy(policy)
482+ .build();
161483
162- assertEquals(policy.getLocalDc(), providedLocalDc);
484+ try {
485+ sCluster.init();
163486
164- assertThat(policy.initHosts).containsOnly(host1, host2);
487+ Host host1 = findHost(cluster, 1);
165488
166- assertThat(logs.get())
167- .contains("Some contact points don't match local data center");
489+ // when: the cluster is initialized.
490+ cluster.init();
168491
492+ // then: should have been initialized with only two hosts given as the contact point.
493+ Mockito.verify(policy).init(any(Cluster.class), initHostsCaptor.capture());
494+ assertThat(initHostsCaptor.getValue()).containsOnly(host1);
495+ // then: the data center should appropriately be set to the one specified.
496+ assertThat(policy.localDc).isEqualTo(host1.getDatacenter());
497+ // then: should not indicate that contact points don't match the local datacenter.
498+ assertThat(logs.get()).doesNotContain("Some contact points don't match local data center");
169499 } finally {
170- if (cluster != null)
171- cluster.close();
500+ cluster.close();
501+ sCluster.stop();
172502 }
173503 }
174504
175505 /**
176- * Wraps the policy under test to spy the calls to init.
506+ * Ensures that {@link DCAwareRoundRobinPolicy} will log a warning if some contact points don't match
507+ * the data center provided in {@link DCAwareRoundRobinPolicy.Builder#withLocalDc(String)} and that
508+ * the explicitly provided local data center is used.
509+ *
510+ * @test_category load_balancing:dc_aware
177511 */
178- static class CountingDCAwarePolicy extends DelegatingLoadBalancingPolicy {
179- Set<Host> initHosts = new CopyOnWriteArraySet<Host>();
180-
181- CountingDCAwarePolicy() {
182- super(DCAwareRoundRobinPolicy.builder().build());
183- }
512+ @Test(groups = "short")
513+ public void should_use_provided_local_dc_and_warn_if_contact_points_dont_match() {
514+ // given: a 4 node 2 DC cluster with a Cluster instance with contact points in different DCs
515+ // and a local DC that doesn't match any contact points.
516+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build();
517+ DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(3)).build());
518+ Cluster cluster = builder()
519+ .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1))
520+ .withLoadBalancingPolicy(policy)
521+ .build();
184522
185- CountingDCAwarePolicy(String localDc) {
186- super(DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build());
187- }
523+ try {
524+ sCluster.init();
188525
189- String getLocalDc() {
190- return ((DCAwareRoundRobinPolicy) delegate).localDc;
191- }
526+ Host host1 = findHost(cluster, 1);
527+ Host host3 = findHost(cluster, 3);
192528
193- @Override public void init(Cluster cluster, Collection<Host> hosts) {
194- initHosts.addAll(hosts);
195- super.init(cluster, hosts);
529+ // when: the cluster is initialized.
530+ cluster.init();
531+
532+ // then: should have been initialized with only two hosts given as the contact point.
533+ Mockito.verify(policy).init(any(Cluster.class), initHostsCaptor.capture());
534+ assertThat(initHostsCaptor.getValue()).containsOnly(host1, host3);
535+ // then: the data center should appropriately be set to the one specified.
536+ assertThat(policy.localDc).isEqualTo(datacenter(3));
537+ // then: should indicate that some contact points don't match the local datacenter.
538+ assertThat(logs.get()).contains("Some contact points don't match local data center");
539+ } finally {
540+ cluster.close();
541+ sCluster.stop();
196542 }
197543 }
198544 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +5 −1
@@ -17,6 +17,8 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.NoHostAvailableException;
20+
21+import org.scassandra.Scassandra;
2022 import org.testng.annotations.Test;
2123
2224 import static org.assertj.core.api.Assertions.assertThat;
@@ -116,7 +118,9 @@
116118 try {
117119 Session whiteListedSession = whiteListedCluster.connect();
118120 // Clear all activity as result of connect.
119- scassandras.clearAllRecordedActivity();
121+ for(Scassandra node : scassandras.nodes()) {
122+ node.activityClient().clearAllRecordedActivity();
123+ }
120124
121125 simulateError(1, unavailable);
122126
added driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java +169 −0
@@ -0,0 +1,169 @@
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 org.apache.log4j.Level;
19+import org.apache.log4j.Logger;
20+import org.testng.annotations.AfterMethod;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import com.datastax.driver.core.Cluster;
25+import com.datastax.driver.core.ConsistencyLevel;
26+import com.datastax.driver.core.DataProviders;
27+import com.datastax.driver.core.MemoryAppender;
28+import com.datastax.driver.core.QueryTracker;
29+import com.datastax.driver.core.ScassandraCluster;
30+import com.datastax.driver.core.Session;
31+
32+import static com.datastax.driver.core.Assertions.assertThat;
33+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
34+
35+public class RoundRobinPolicyTest {
36+
37+ Logger policyLogger = Logger.getLogger(RoundRobinPolicy.class);
38+ MemoryAppender logs;
39+ QueryTracker queryTracker;
40+
41+ @BeforeMethod(groups = "short")
42+ public void setUp() {
43+ queryTracker = new QueryTracker();
44+ policyLogger.setLevel(Level.WARN);
45+ logs = new MemoryAppender();
46+ policyLogger.addAppender(logs);
47+ }
48+
49+ @AfterMethod(groups = "short")
50+ public void tearDown() {
51+ policyLogger.setLevel(null);
52+ policyLogger.removeAppender(logs);
53+ }
54+
55+ /**
56+ * Ensures that when used {@link RoundRobinPolicy} properly round robins requests within
57+ * nodes in a single datacenter.
58+ *
59+ * @test_category load_balancing:round_robin
60+ */
61+ @Test(groups="short")
62+ public void should_round_robin_within_single_datacenter() {
63+ // given: a 5 node cluster using RoundRobinPolicy.
64+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
65+
66+ Cluster cluster = Cluster.builder()
67+ .addContactPoint(sCluster.address(1))
68+ .withLoadBalancingPolicy(new RoundRobinPolicy())
69+ .withNettyOptions(nonQuietClusterCloseOptions)
70+ .build();
71+
72+ try {
73+ sCluster.init();
74+
75+ Session session = cluster.connect();
76+ // when: a query is executed 50 times.
77+ queryTracker.query(session, 50);
78+
79+ // then: all nodes should be queried equally.
80+ for(int i = 1; i <= 5; i++) {
81+ queryTracker.assertQueried(sCluster, 1, i, 10);
82+ }
83+ } finally {
84+ cluster.close();
85+ sCluster.stop();
86+ }
87+
88+ }
89+
90+ /**
91+ * Ensures that when used {@link RoundRobinPolicy} properly round robins requests to nodes irrespective
92+ * of cluster topology by ensuring nodes in different data centers are queried equally to others.
93+ *
94+ * @test_category load_balancing:round_robin
95+ */
96+ @Test(groups="short")
97+ public void should_round_robin_irrespective_of_topology() {
98+ // given: a 10 node, 5 DC cluster using RoundRobinPolicy.
99+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2,2,2,2,2).build();
100+
101+ Cluster cluster = Cluster.builder()
102+ .addContactPoint(sCluster.address(1))
103+ .withLoadBalancingPolicy(new RoundRobinPolicy())
104+ .withNettyOptions(nonQuietClusterCloseOptions)
105+ .build();
106+
107+ try {
108+ sCluster.init();
109+
110+ Session session = cluster.connect();
111+ // when: a query is executed 50 times.
112+ queryTracker.query(session, 50);
113+
114+ // then: all nodes should be queried equally.
115+ for(int dc = 1; dc <= 5; dc++) {
116+ for (int i = 1; i <= 2; i++) {
117+ queryTracker.assertQueried(sCluster, dc, i, 5);
118+ }
119+ }
120+ } finally {
121+ cluster.close();
122+ sCluster.stop();
123+ }
124+ }
125+
126+ /**
127+ * Ensures that when used {@link RoundRobinPolicy} generates a warning if a consistency level is used
128+ * that is data center local (i.e. LOCAL_QUORUM) and nodes from multiple data centers are in the cluster
129+ * and that warning is only generated once. Also validates that is a non-Dc local consistency level is
130+ * used (i.e. ONE) that no such warning is generated.
131+ *
132+ * @test_category load_balancing:round_robin
133+ */
134+ @Test(groups="short", dataProvider="consistencyLevels", dataProviderClass=DataProviders.class)
135+ public void should_warn_if_using_dc_local_consistency_level(ConsistencyLevel cl) {
136+ // given: a 2 node, 2 DC cluster using RoundRobinPolicy.
137+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(1,1).build();
138+
139+ Cluster cluster = Cluster.builder()
140+ .addContactPoint(sCluster.address(1))
141+ .withLoadBalancingPolicy(new RoundRobinPolicy())
142+ .withNettyOptions(nonQuietClusterCloseOptions)
143+ .build();
144+
145+ String expectedLogMessage = "Detected request at Consistency Level " + cl + " but the non-DC aware RoundRobinPolicy is in use.";
146+
147+ try {
148+ sCluster.init();
149+
150+ Session session = cluster.connect();
151+ // when: a query is executed 50 times.
152+ queryTracker.query(session, 50, cl);
153+
154+ // then: all nodes should be queried equally.
155+ queryTracker.assertQueried(sCluster, 1, 1, 25);
156+ queryTracker.assertQueried(sCluster, 2, 1, 25);
157+
158+ // Should get a warning if using a local DC cl.
159+ if(cl.isDCLocal()) {
160+ assertThat(logs.get()).containsOnlyOnce(expectedLogMessage);
161+ } else {
162+ assertThat(logs.get()).doesNotContain(expectedLogMessage);
163+ }
164+ } finally {
165+ cluster.close();
166+ sCluster.stop();
167+ }
168+ }
169+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +312 −46
@@ -18,77 +18,343 @@
1818 import java.nio.ByteBuffer;
1919 import java.util.List;
2020
21-import static org.assertj.core.api.Assertions.assertThat;
21+import com.google.common.collect.ImmutableMap;
2222 import com.google.common.collect.Lists;
23+import org.testng.annotations.BeforeMethod;
24+import org.testng.annotations.DataProvider;
2325 import org.testng.annotations.Test;
2426
2527 import com.datastax.driver.core.*;
26-import com.datastax.driver.core.utils.Bytes;
2728
28-import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
29+import static com.datastax.driver.core.Assertions.assertThat;
30+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
31+import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
32+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
2933
3034 public class TokenAwarePolicyTest {
31- @Test(groups = "long")
32- public void should_shuffle_replicas_when_requested() {
33- testShuffleReplicas(new TokenAwarePolicy(new RoundRobinPolicy(), true),
34- true);
35+
36+ QueryTracker queryTracker;
37+
38+ @BeforeMethod(groups = "short")
39+ public void setUp() {
40+ queryTracker = new QueryTracker();
3541 }
3642
37- @Test(groups = "long")
38- public void should_not_shuffle_replicas_when_not_requested() {
39- testShuffleReplicas(new TokenAwarePolicy(new RoundRobinPolicy(), false),
40- false);
43+ @DataProvider(name="shuffleProvider")
44+ public Object[][] shuffleProvider () {
45+ return new Object[][] {
46+ { true },
47+ { false },
48+ { null }
49+ };
4150 }
4251
43- private void testShuffleReplicas(TokenAwarePolicy loadBalancingPolicy, boolean expectShuffled) {
44- CCMBridge ccm = null;
45- Cluster cluster = null;
52+ /**
53+ * Ensures that {@link TokenAwarePolicy} will shuffle discovered replicas depending on the value of shuffleReplicas
54+ * used when constructing with {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy, boolean)} and that if not
55+ * provided replicas are shuffled by default when using {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy, boolean)}.
56+ *
57+ * @test_category load_balancing:token_aware
58+ */
59+ @Test(groups="short", dataProvider="shuffleProvider")
60+ public void should_shuffle_replicas_based_on_configuration(Boolean shuffleReplicas) {
61+ // given: an 8 node cluster using TokenAwarePolicy and some shuffle replica configuration with a keyspace with replication factor of 3.
62+ ScassandraCluster sCluster = ScassandraCluster.builder()
63+ .withNodes(8)
64+ .withSimpleKeyspace("keyspace", 3)
65+ .build();
66+
67+ LoadBalancingPolicy loadBalancingPolicy;
68+ if(shuffleReplicas == null) {
69+ loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy());
70+ shuffleReplicas = true;
71+ } else {
72+ loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy(), shuffleReplicas);
73+ }
74+
75+ Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
76+ .withNettyOptions(nonQuietClusterCloseOptions)
77+ .withLoadBalancingPolicy(loadBalancingPolicy)
78+ .build();
79+
4680 try {
47- ccm = CCMBridge.builder("test").withNodes(3).build();
48- cluster = Cluster.builder()
49- .addContactPoint(CCMBridge.ipOfNode(1))
50- .withLoadBalancingPolicy(loadBalancingPolicy)
51- .withQueryOptions(nonDebouncingQueryOptions())
52- .build();
53-
54- String keyspace = "ks";
55- ByteBuffer routingKey = Bytes.fromHexString("0xCAFEBABE");
81+ sCluster.init();
5682
5783 Session session = cluster.connect();
58- // Use a replication factor of 2, each routing key on this keyspace will corresponding to 2 hosts out of 3
59- session.execute(String.format("CREATE KEYSPACE %s "
60- + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}",
61- keyspace));
6284
85+ // given: A routing key that falls in the token range of node 6.
86+
87+ // Encodes into murmur hash '4874351301193663061' which should belong be owned by node 6 with replicas 7 and 8.
88+ ByteBuffer routingKey = TypeCodec.varchar().serialize("This is some sample text", ProtocolVersion.NEWEST_SUPPORTED);
89+
90+ // then: The replicas resolved from the cluster metadata must match node 6 and its replicas.
91+ List<Host> replicas = Lists.newArrayList(cluster.getMetadata().getReplicas("keyspace", routingKey));
92+ assertThat(replicas).containsExactly(
93+ sCluster.host(cluster, 1, 6),
94+ sCluster.host(cluster, 1, 7),
95+ sCluster.host(cluster, 1, 8));
96+
97+ // then: generating a query plan on a statement using that routing key should properly prioritize node 6 and its replicas.
6398 // Actual query does not matter, only the keyspace and routing key will be used
64- SimpleStatement statement = session.newSimpleStatement("foo");
65- statement.setKeyspace(keyspace);
99+ SimpleStatement statement = session.newSimpleStatement("select * from table where k=5");
66100 statement.setRoutingKey(routingKey);
101+ statement.setKeyspace("keyspace");
67102
68- // Identify the two replicas for our routing key
69- List<Host> replicas = Lists.newArrayList(cluster.getMetadata().getReplicas(keyspace, routingKey));
70- assertThat(replicas).hasSize(2);
71-
72- // Run a few query plans, make sure that these two replicas come first, shuffled or not depending on
73- // what we expect
74103 boolean shuffledAtLeastOnce = false;
75- for (int i = 0; i < 10; i++) {
104+ for(int i = 0; i < 1024; i++) {
76105 List<Host> queryPlan = Lists.newArrayList(loadBalancingPolicy.newQueryPlan(null, statement));
77- assertThat(queryPlan).hasSize(3);
106+ assertThat(queryPlan).containsOnlyElementsOf(cluster.getMetadata().getAllHosts());
107+
108+ List<Host> firstThree = queryPlan.subList(0, 3);
109+ // then: if shuffle replicas was used or using default, the first three hosts returned should be 6,7,8 in any order.
110+ // if shuffle replicas was not used, the first three hosts returned should be 6,7,8 in that order.
111+ if(shuffleReplicas) {
112+ assertThat(firstThree).containsOnlyElementsOf(replicas);
113+ if(!firstThree.equals(replicas)) {
114+ shuffledAtLeastOnce = true;
115+ }
116+ } else {
117+ assertThat(firstThree).containsExactlyElementsOf(replicas);
118+ }
119+ }
120+
121+ // then: given 1024 query plans, the replicas should be shuffled at least once.
122+ assertThat(shuffledAtLeastOnce).isEqualTo(shuffleReplicas);
123+ } finally {
124+ cluster.close();
125+ sCluster.stop();
126+ }
127+ }
128+
129+ /**
130+ * Ensures that {@link TokenAwarePolicy} will properly prioritize replicas if a provided
131+ * {@link SimpleStatement} is using an explicitly set keyspace and routing key and the
132+ * keyspace provided is using SimpleStrategy with a replication factor of 1.
133+ *
134+ * @test_category load_balancing:token_aware
135+ */
136+ @Test(groups="short")
137+ public void should_choose_proper_host_based_on_routing_key() {
138+ // given: A 3 node cluster using TokenAwarePolicy with a replication factor of 1.
139+ ScassandraCluster sCluster = ScassandraCluster.builder()
140+ .withNodes(3)
141+ .withSimpleKeyspace("keyspace", 1)
142+ .build();
143+ Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1))
144+ .withNettyOptions(nonQuietClusterCloseOptions)
145+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
146+ .build();
147+
148+ // when: A query is made with a routing key
149+ try {
150+ sCluster.init();
151+
152+ Session session = cluster.connect();
153+
154+ // Encodes into murmur hash '4557949199137838892' which should belong be owned by node 3.
155+ ByteBuffer routingKey = TypeCodec.varchar().serialize("should_choose_proper_host_based_on_routing_key", ProtocolVersion.NEWEST_SUPPORTED);
156+ SimpleStatement statement = session.newSimpleStatement("select * from table where k=5")
157+ .setRoutingKey(routingKey)
158+ .setKeyspace("keyspace");
159+
160+ queryTracker.query(session, 10, statement);
161+
162+ // then: The host having that token should be queried.
163+ queryTracker.assertQueried(sCluster, 1, 1, 0);
164+ queryTracker.assertQueried(sCluster, 1, 2, 0);
165+ queryTracker.assertQueried(sCluster, 1, 3, 10);
166+ } finally {
167+ cluster.close();
168+ sCluster.stop();
169+ }
170+ }
171+
172+ /**
173+ * Ensures that {@link TokenAwarePolicy} will properly prioritize replicas in the local datacenter
174+ * if a provided {@link SimpleStatement} is using an explicitly set keyspace and routing key and
175+ * the keyspace provided is using NetworkTopologyStrategy with an RF of 1:1.
176+ *
177+ * @test_category load_balancing:token_aware
178+ */
179+ @Test(groups="short")
180+ public void should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware() {
181+ // given: A 6 node, 2 DC cluster with RF 1:1, using TokenAwarePolicy wrapping DCAwareRoundRobinPolicy with remote hosts.
182+ ScassandraCluster sCluster = ScassandraCluster.builder()
183+ .withNodes(3, 3)
184+ .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1))
185+ .build();
186+ Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2,1))
187+ .withNettyOptions(nonQuietClusterCloseOptions)
188+ .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder()
189+ .withLocalDc(ScassandraCluster.datacenter(2))
190+ .withUsedHostsPerRemoteDc(3)
191+ .build()))
192+ .build();
193+
194+ // when: A query is made with a routing key
195+ try {
196+ sCluster.init();
197+
198+ Session session = cluster.connect();
199+
200+ // Encodes into murmur hash '-8124212968526248339' which should belong to 1:1 in DC1 and 2:1 in DC2.
201+ ByteBuffer routingKey = TypeCodec.varchar().serialize("should_choose_host_in_local_dc_when_using_network_topology_strategy_and_dc_aware", ProtocolVersion.NEWEST_SUPPORTED);
202+ SimpleStatement statement = session.newSimpleStatement("select * from table where k=5")
203+ .setRoutingKey(routingKey)
204+ .setKeyspace("keyspace");
205+
206+ queryTracker.query(session, 10, statement);
207+
208+ // then: The local replica (2:1) should be queried and never the remote one.
209+ queryTracker.assertQueried(sCluster, 2, 1, 10);
210+ queryTracker.assertQueried(sCluster, 1, 1, 0);
211+ } finally {
212+ cluster.close();
213+ sCluster.stop();
214+ }
215+ }
216+
217+ /**
218+ * Ensures that {@link TokenAwarePolicy} will properly handle unavailability of replicas
219+ * matching with routing keys by falling back on its child policy and that when those
220+ * replicas become available the policy uses those replicas once again.
221+ *
222+ * @test_category load_balancing:token_aware
223+ */
224+ @Test(groups="short")
225+ public void should_use_other_nodes_when_replicas_having_token_are_down() {
226+ // given: A 4 node cluster using TokenAwarePolicy with a replication factor of 2.
227+ ScassandraCluster sCluster = ScassandraCluster.builder()
228+ .withNodes(4)
229+ .withSimpleKeyspace("keyspace", 2)
230+ .build();
231+ Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2))
232+ .withNettyOptions(nonQuietClusterCloseOptions)
233+ // Don't shuffle replicas just to keep test deterministic.
234+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
235+ .build();
236+
237+ try {
238+ sCluster.init();
239+
240+ Session session = cluster.connect();
241+
242+ // when: A query is made with a routing key and both hosts having that key's token are down.
243+ // Encodes into murmur hash '6444339665561646341' which should belong to node 4.
244+ ByteBuffer routingKey = TypeCodec.varchar().serialize("should_use_other_nodes_when_replicas_having_token_are_down", ProtocolVersion.NEWEST_SUPPORTED);
245+ SimpleStatement statement = session.newSimpleStatement("select * from table where k=5")
246+ .setRoutingKey(routingKey)
247+ .setKeyspace("keyspace");
248+
249+ queryTracker.query(session, 10, statement);
250+
251+ // then: The node that is the primary for that key's hash is chosen.
252+ queryTracker.assertQueried(sCluster, 1, 1, 0);
253+ queryTracker.assertQueried(sCluster, 1, 2, 0);
254+ queryTracker.assertQueried(sCluster, 1, 3, 0);
255+ queryTracker.assertQueried(sCluster, 1, 4, 10);
256+
257+ // when: The primary node owning that key goes down and a query is made.
258+ queryTracker.reset();
259+ sCluster.stop(cluster, 4);
260+ queryTracker.query(session, 10, statement);
261+
262+ // then: The next replica having that data should be chosen (node 1).
263+ queryTracker.assertQueried(sCluster, 1, 1, 10);
264+ queryTracker.assertQueried(sCluster, 1, 2, 0);
265+ queryTracker.assertQueried(sCluster, 1, 3, 0);
266+ queryTracker.assertQueried(sCluster, 1, 4, 0);
267+
268+ // when: All nodes having that token are down and a query is made.
269+ queryTracker.reset();
270+ sCluster.stop(cluster, 1);
271+ queryTracker.query(session, 10, statement);
272+
273+ // then: The remaining nodes which are non-replicas of that token should be used
274+ // delegating to the child policy (RoundRobin).
275+ queryTracker.assertQueried(sCluster, 1, 1, 0);
276+ queryTracker.assertQueried(sCluster, 1, 2, 5);
277+ queryTracker.assertQueried(sCluster, 1, 3, 5);
278+ queryTracker.assertQueried(sCluster, 1, 4, 0);
279+
280+ // when: A replica having that key becomes up and a query is made.
281+ queryTracker.reset();
282+ sCluster.start(cluster, 1);
283+ queryTracker.query(session, 10, statement);
284+
285+ // then: The newly up replica should be queried.
286+ queryTracker.assertQueried(sCluster, 1, 1, 10);
287+ queryTracker.assertQueried(sCluster, 1, 2, 0);
288+ queryTracker.assertQueried(sCluster, 1, 3, 0);
289+ queryTracker.assertQueried(sCluster, 1, 4, 0);
290+
291+ // when: The primary replicas becomes up and a query is made.
292+ queryTracker.reset();
293+ sCluster.start(cluster, 4);
294+ queryTracker.query(session, 10, statement);
295+
296+ // then: The primary replica which is now up should be queried.
297+ queryTracker.assertQueried(sCluster, 1, 1, 0);
298+ queryTracker.assertQueried(sCluster, 1, 2, 0);
299+ queryTracker.assertQueried(sCluster, 1, 3, 0);
300+ queryTracker.assertQueried(sCluster, 1, 4, 10);
301+ } finally {
302+ cluster.close();
303+ sCluster.stop();
304+ }
305+ }
306+
307+ /**
308+ * Ensures that {@link TokenAwarePolicy} will properly handle a routing key for a {@link PreparedStatement}
309+ * whose table uses multiple columns for its partition key.
310+ *
311+ * @test_category load_balancing:token_aware
312+ * @jira_ticket JAVA-123 (to ensure routing key buffers are not destroyed).
313+ */
314+ @Test(groups = "long")
315+ public void should_properly_generate_and_use_routing_key_for_composite_partition_key() {
316+ // given: a 3 node cluster with a keyspace with RF 1.
317+ CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build();
318+
319+ Cluster cluster = Cluster.builder()
320+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
321+ .addContactPoint(CCMBridge.ipOfNode(1))
322+ .build();
323+
324+ try {
325+ ccm.start();
326+ Session session = cluster.connect();
327+
328+ String table = "composite";
329+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, 1));
330+ session.execute("USE " + SIMPLE_KEYSPACE);
331+ session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", table));
332+
333+ // (1,2) resolves to token '4881097376275569167' which belongs to node 1 so all queries should go to that node.
334+ PreparedStatement insertPs = session.prepare("INSERT INTO " + table + "(k1, k2, i) VALUES (?, ?, ?)");
335+ BoundStatement insertBs = insertPs.bind(1, 2, 3);
336+
337+ PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
338+ BoundStatement selectBs = selectPs.bind(1,2);
339+
340+ // when: executing a prepared statement with a composite partition key.
341+ // then: should query the correct node (1) in for both insert and select queries.
342+ for(int i = 0; i < 10; i++) {
343+ ResultSet rs = session.execute(insertBs);
344+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
78345
79- List<Host> firstTwo = queryPlan.subList(0, 2);
80- assertThat(firstTwo).containsAll(replicas); // order does not matter
346+ rs = session.execute(selectBs);
347+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
348+ assertThat(rs.isExhausted()).isFalse();
349+ Row r = rs.one();
350+ assertThat(rs.isExhausted()).isTrue();
81351
82- if (!firstTwo.equals(replicas))
83- shuffledAtLeastOnce = true;
352+ assertThat(r.getInt("i")).isEqualTo(3);
84353 }
85- assertThat(shuffledAtLeastOnce).isEqualTo(expectShuffled);
86354
87355 } finally {
88- if (cluster != null)
89- cluster.close();
90- if (ccm != null)
91- ccm.remove();
356+ cluster.close();
357+ ccm.remove();
92358 }
93359 }
94360 }
added driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java +134 −0
@@ -0,0 +1,134 @@
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.net.InetAddress;
19+import java.net.InetSocketAddress;
20+import java.util.List;
21+
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.BeforeMethod;
24+import org.testng.annotations.Test;
25+
26+import com.datastax.driver.core.Cluster;
27+import com.datastax.driver.core.ConsistencyLevel;
28+import com.datastax.driver.core.QueryTracker;
29+import com.datastax.driver.core.ScassandraCluster;
30+import com.datastax.driver.core.Session;
31+import com.datastax.driver.core.exceptions.NoHostAvailableException;
32+
33+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
34+
35+public class WhiteListPolicyTest {
36+
37+ QueryTracker queryTracker;
38+
39+ @BeforeMethod(groups = "short")
40+ public void setUp() {
41+ queryTracker = new QueryTracker();
42+ }
43+
44+ /**
45+ * Provides basic validation of {@link WhiteListPolicy}.
46+ * <p/>
47+ * Ensures that:
48+ * <ol>
49+ * <li>Only addresses provided in the whitelist are every used for querying.</li>
50+ * <li>If no nodes present in the whitelist are available, queries fail with a {@link NoHostAvailableException}</li>
51+ * </ol>
52+ *
53+ * @test_category load_balancing:white_list
54+ */
55+ @Test(groups="short")
56+ public void should_only_query_hosts_in_white_list() throws Exception {
57+ // given: a 5 node cluster with a WhiteListPolicy targeting nodes 3 and 5.
58+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
59+ List<InetSocketAddress> whiteList = Lists.newArrayList(
60+ new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042),
61+ new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042));
62+
63+ Cluster cluster = Cluster.builder()
64+ .addContactPoint(sCluster.address(5))
65+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
66+ .withNettyOptions(nonQuietClusterCloseOptions)
67+ .build();
68+
69+ try {
70+ sCluster.init();
71+
72+ Session session = cluster.connect();
73+ // when: a query is executed 50 times.
74+ queryTracker.query(session, 50);
75+
76+ // then: only nodes 3 and 5 should have been queried.
77+ queryTracker.assertQueried(sCluster, 1, 1, 0);
78+ queryTracker.assertQueried(sCluster, 1, 2, 0);
79+ queryTracker.assertQueried(sCluster, 1, 3, 25);
80+ queryTracker.assertQueried(sCluster, 1, 4, 0);
81+ queryTracker.assertQueried(sCluster, 1, 5, 25);
82+
83+ queryTracker.reset();
84+
85+ // when: the only nodes in the whitelist are stopped.
86+ sCluster.stop(cluster, 3);
87+ sCluster.stop(cluster, 5);
88+
89+ // then: all queries should raise a NHAE.
90+ queryTracker.query(session, 50, ConsistencyLevel.ONE, NoHostAvailableException.class);
91+
92+ queryTracker.assertQueried(sCluster, 1, 1, 0);
93+ queryTracker.assertQueried(sCluster, 1, 2, 0);
94+ queryTracker.assertQueried(sCluster, 1, 3, 0);
95+ queryTracker.assertQueried(sCluster, 1, 4, 0);
96+ queryTracker.assertQueried(sCluster, 1, 5, 0);
97+ } finally {
98+ cluster.close();
99+ sCluster.stop();
100+ }
101+ }
102+
103+ /**
104+ * Validates that a {@link Cluster} cannot be initiated if using a {@link WhiteListPolicy} and
105+ * none of the specified contact point addresses are present in the white list.
106+ *
107+ * @test_category load_balancing:white_list
108+ */
109+ @Test(groups="short", expectedExceptions = {IllegalArgumentException.class})
110+ public void should_require_contact_point_in_white_list() throws Exception {
111+ // given: a 5 node cluster with a WhiteListPolicy targeting node2.
112+ ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build();
113+
114+ // when: using a Cluster instance with none of the contact points in the declared
115+ // WhiteListPolicy.
116+ List<InetSocketAddress> whiteList = Lists.newArrayList(
117+ new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042));
118+ Cluster cluster = Cluster.builder()
119+ .addContactPoint(sCluster.address(3))
120+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList))
121+ .withNettyOptions(nonQuietClusterCloseOptions)
122+ .build();
123+
124+ try {
125+ sCluster.init();
126+ // then: The cluster instance should fail to initialize as none of the contact
127+ // points is present in the white list.
128+ cluster.init();
129+ } finally {
130+ cluster.close();
131+ sCluster.stop();
132+ }
133+ }
134+}