Elffuss BraidHub

kikocis/java-driver public

Merge pull request #403 from datastax/java618

JAVA-618: Randomize contact points list to prevent hotspots.
Changeseta66ea280088ce6e081b06dd21b74f0963444b29a94cd33f360fc554518a79557
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-04 10:21 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-04 10:21 +02:00
Parentsd4861195664d, 8a71bb617645

Browse the files at this changeset

7 files changed

modified changelog/README.md +1 −0
@@ -25,6 +25,7 @@
2525 - [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
2626 - [improvement] Provide API to retrieve values of a Parameterized SimpleStatement (JAVA-765)
2727 - [improvement] implement UPDATE ... IF EXISTS in QueryBuilder (JAVA-827)
28+- [improvement] Randomize contact points list to prevent hotspots (JAVA-618)
2829
2930 Merged from 2.0.10_fixes branch:
3031
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +4 −1
@@ -74,7 +74,10 @@
7474 return;
7575
7676 // NB: at this stage, allHosts() only contains the initial contact points
77- setNewConnection(reconnectInternal(cluster.metadata.allHosts().iterator(), true));
77+ List<Host> hosts = new ArrayList<Host>(cluster.metadata.allHosts());
78+ // shuffle so that multiple clients with the same contact points don't all pick the same control host
79+ Collections.shuffle(hosts);
80+ setNewConnection(reconnectInternal(hosts.iterator(), true));
7881 }
7982
8083 public CloseFuture closeAsync() {
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +3 −3
@@ -19,9 +19,6 @@
1919 import java.util.concurrent.ConcurrentHashMap;
2020 import java.util.concurrent.ConcurrentMap;
2121 import java.util.concurrent.CopyOnWriteArrayList;
22-import java.util.concurrent.ExecutionException;
23-import java.util.concurrent.TimeUnit;
24-import java.util.concurrent.TimeoutException;
2522 import java.util.concurrent.atomic.AtomicInteger;
2623
2724 import com.google.common.annotations.VisibleForTesting;
@@ -210,6 +207,9 @@
210207 String nonLocalHosts = Joiner.on(",").join(notInLocalDC);
211208 logger.warn("Some contact points don't match local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts);
212209 }
210+
211+ this.index.set(new Random().nextInt(Math.max(hosts.size(), 1)));
212+
213213 }
214214
215215 private String dc(Host host) {
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +66 −0
@@ -15,10 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetAddress;
1819 import java.util.Iterator;
20+import java.util.Map;
1921 import java.util.concurrent.TimeUnit;
2022 import java.util.concurrent.atomic.AtomicInteger;
2123
24+import com.google.common.base.Function;
25+import com.google.common.collect.Collections2;
26+import com.google.common.collect.HashMultiset;
27+import com.google.common.collect.Maps;
28+import org.slf4j.Logger;
29+import org.slf4j.LoggerFactory;
2230 import org.testng.annotations.Test;
2331
2432 import static org.assertj.core.api.Assertions.assertThat;
@@ -29,6 +37,9 @@
2937 import com.datastax.driver.core.policies.ReconnectionPolicy;
3038
3139 public class ControlConnectionTest {
40+
41+ static final Logger logger = LoggerFactory.getLogger(ControlConnectionTest.class);
42+
3243 @Test(groups = "short")
3344 public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException {
3445 CCMBridge ccm = null;
@@ -122,6 +133,61 @@
122133 }
123134 }
124135
136+ /**
137+ * <p>
138+ * Ensures that contact points are randomized when determining the initial control connection
139+ * by default. Initializes a cluster with 5 contact points 100 times and ensures that all 5
140+ * were used.
141+ * </p>
142+ *
143+ * @jira_ticket JAVA-618
144+ * @expected_result All 5 hosts were chosen within 100 attempts. There is a very small possibility
145+ * that this may not be the case and this is not actually an error.
146+ * @test_category control_connection
147+ * @since 2.0.11, 2.1.8, 2.2.0
148+ */
149+ @Test(groups = "short")
150+ public void should_randomize_contact_points_when_determining_control_connection() {
151+ int hostCount = 5;
152+ int iterations = 100;
153+ SCassandraCluster scassandras = new SCassandraCluster(hostCount);
154+
155+ try {
156+ final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
157+ for(int i = 0; i < iterations; i++) {
158+ Cluster cluster = Cluster.builder()
159+ .addContactPoints(scassandras.addresses())
160+ .build();
161+
162+ try {
163+ cluster.init();
164+ occurrencesByHost.add(cluster.manager.controlConnection.connectedHost().getAddress());
165+ } finally {
166+ cluster.close();
167+ }
168+ }
169+ if(logger.isDebugEnabled()) {
170+ Map<InetAddress, Integer> hostCounts = Maps.toMap(occurrencesByHost.elementSet(), new Function<InetAddress, Integer>() {
171+ @Override
172+ public Integer apply(InetAddress input) {
173+ return occurrencesByHost.count(input);
174+ }
175+ });
176+ logger.debug("Control Connection Use Counts by Host: {}", hostCounts);
177+ }
178+ // There is an incredibly low chance that a host may not be used based on randomness.
179+ // This probability is very low however.
180+ assertThat(occurrencesByHost.elementSet().size())
181+ .as("Not all hosts were used as contact points. There is a very small chance"
182+ + " of this happening based on randomness, investigate whether or not this"
183+ + " is a bug.")
184+ .isEqualTo(hostCount);
185+ } finally {
186+ scassandras.stop();
187+ }
188+
189+ }
190+
125191 static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy {
126192
127193 final AtomicInteger counter = new AtomicInteger();
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +4 −0
@@ -43,6 +43,10 @@
4343 private final List<PrimingClient> primingClients;
4444 private final List<ActivityClient> activityClients;
4545
46+ public SCassandraCluster(int nodeCount) {
47+ this(CCMBridge.IP_PREFIX, nodeCount);
48+ }
49+
4650 public SCassandraCluster(String ipPrefix, int nodeCount) {
4751 scassandras = Lists.newArrayListWithCapacity(nodeCount);
4852 addresses = Lists.newArrayListWithCapacity(nodeCount);
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +0 −1
@@ -191,7 +191,6 @@
191191 }
192192
193193 @Override public void init(Cluster cluster, Collection<Host> hosts) {
194- System.out.println("init " + hosts);
195194 initHosts.addAll(hosts);
196195 super.init(cluster, hosts);
197196 }
modified upgrade_guide/README.md +12 −0
@@ -5,6 +5,9 @@
55
66 ### 2.0.11
77
8+2.0.11 preserves binary compatibility with previous versions. There are a few
9+changes in the driver's behavior:
10+
811 1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
912 exception received from a request. The new behaviour will cause the driver to
1013 process a Retry on a different node at most once, otherwise an exception will
@@ -13,11 +16,20 @@
1316 because of a network partition) but can still answer to the client normally.
1417 In this case, trying another node has a chance of success.
1518 The previous behaviour was to always throw an exception.
19+
1620 2. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
1721 or `raw()` is used to build a value to be inserted in the database.
1822 If you know that the CQL functions or expressions are safe, use
1923 `setIdempotent(true)` on the statement.
2024
25+3. The list of contact points provided at startup is now shuffled before trying
26+ to open the control connection, so that multiple clients with the same contact
27+ points don't all pick the same control host. As a result, you can't assume that
28+ the driver will try contact points in a deterministic order. In particular, if
29+ you use the `DCAwareRoundRobinPolicy` without specifying a primary datacenter
30+ name, make sure that you only provide local hosts as contact points.
31+
32+
2133 ### 2.0.x to 2.0.10
2234
2335 We try to avoid breaking changes within a branch (2.0.x to 2.0.y), but