Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changesetb74e56ba219129d668a075ed3c9b2f17f66ad3977dcc92533e17318df1663fd8
Authorolim7t <omichallat+github@gmail.com> · 2015-03-05 16:04 -08:00
Committerolim7t <omichallat+github@gmail.com> · 2015-03-05 16:04 -08:00
Parentsa5e878a53851, bccef797dff9

Browse the files at this changeset

18 files changed

modified driver-core/CHANGELOG.rst +4 −1
@@ -11,9 +11,12 @@
1111 - [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
1212 - [improvement] Add connection heartbeat (JAVA-533)
1313 - [improvement] Reduce level of logs on missing rpc_address (JAVA-568)
14-- [improvement] Expose node token and range information (JAVA-312)
14+- [improvement] Expose node token and range information (JAVA-312, JAVA-681)
15+- [bug] Fix cluster name mismatch check at startup (JAVA-595)
1516 - [bug] Fix guava dependency when using OSGI (JAVA-620)
1617 - [bug] Fix handling of DROP events when ks name is case-sensitive (JAVA-678)
18+- [improvement] Use List<?> instead of List<Object> in QueryBuilder API
19+ (JAVA-631)
1720 - [bug] Prevent race between cancellation and query completion (JAVA-614)
1821 - [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if
1922 streamId was already released and reused (JAVA-632).
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +12 −12
@@ -1388,8 +1388,8 @@
13881388
13891389 void logClusterNameMismatch(Host host, String expectedClusterName, String actualClusterName) {
13901390 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since its cluster name '{}' does not match the one "
1391- + "currently known ({})",
1392- host, actualClusterName, expectedClusterName);
1391+ + "currently known ({})",
1392+ host, actualClusterName, expectedClusterName);
13931393 }
13941394
13951395 public ListenableFuture<?> triggerOnUp(final Host host) {
@@ -1506,15 +1506,15 @@
15061506 }
15071507 }
15081508
1509- public ListenableFuture<?> triggerOnDown(final Host host) {
1510- return triggerOnDown(host, false);
1509+ public ListenableFuture<?> triggerOnDown(final Host host, boolean startReconnection) {
1510+ return triggerOnDown(host, false, startReconnection);
15111511 }
15121512
1513- public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition) {
1513+ public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition, final boolean startReconnection) {
15141514 return executor.submit(new ExceptionCatchingRunnable() {
15151515 @Override
15161516 public void runMayThrow() throws InterruptedException, ExecutionException {
1517- onDown(host, isHostAddition, false);
1517+ onDown(host, isHostAddition, false, startReconnection);
15181518 }
15191519 });
15201520 }
@@ -1529,7 +1529,7 @@
15291529 // connected to one in the first place, but if we ever do, simply hand it
15301530 // off to onDown
15311531 if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1532- triggerOnDown(host);
1532+ triggerOnDown(host, true);
15331533 return;
15341534 }
15351535
@@ -1569,7 +1569,7 @@
15691569 success = false;
15701570 }
15711571 if (!success)
1572- onDown(host, false, true);
1572+ onDown(host, false, true, true);
15731573 }
15741574 }));
15751575
@@ -1585,7 +1585,7 @@
15851585 }
15861586
15871587 // Use triggerOnDown unless you're sure you want to run this on the current thread.
1588- private void onDown(final Host host, final boolean isHostAddition, final boolean isSuspectedVerification) throws InterruptedException, ExecutionException {
1588+ private void onDown(final Host host, final boolean isHostAddition, final boolean isSuspectedVerification, boolean startReconnection) throws InterruptedException, ExecutionException {
15891589 logger.debug("Host {} is DOWN", host);
15901590
15911591 if (isClosed())
@@ -1638,7 +1638,7 @@
16381638 }
16391639
16401640 // Don't start a reconnection if we ignore the node anyway (JAVA-314)
1641- if (distance == HostDistance.IGNORED)
1641+ if (distance == HostDistance.IGNORED || !startReconnection)
16421642 return;
16431643
16441644 // Note: we basically waste the first successful reconnection, but it's probably not a big deal
@@ -1898,7 +1898,7 @@
18981898 boolean isDown = host.signalConnectionFailure(exception);
18991899 if (isDown) {
19001900 if (isHostAddition || !markSuspected) {
1901- triggerOnDown(host, isHostAddition);
1901+ triggerOnDown(host, isHostAddition, true);
19021902 } else {
19031903 // Note that we do want to call onSuspected on the current thread, as the whole point is
19041904 // that by the time this method return, the host initialReconnectionAttempt will have been
@@ -2150,7 +2150,7 @@
21502150 // right away, so we favor the detection to make the Host.isUp method more reliable.
21512151 Host hostDown = metadata.getHost(stAddr);
21522152 if (hostDown != null)
2153- triggerOnDown(hostDown);
2153+ triggerOnDown(hostDown, true);
21542154 break;
21552155 }
21562156 break;
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +1 −3
@@ -189,9 +189,7 @@
189189
190190 private UnsupportedProtocolVersionException unsupportedProtocolVersionException(ProtocolVersion triedVersion, ProtocolVersion serverProtocolVersion) {
191191 logger.debug("Got unsupported protocol version error from {} for version {} server supports version {}", address, triedVersion, serverProtocolVersion);
192- UnsupportedProtocolVersionException exc = new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion);
193- defunct(new TransportException(address, "Cannot initialize transport", exc));
194- return exc;
192+ return new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion);
195193 }
196194
197195 private void authenticateV1(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +32 −0
@@ -27,6 +27,8 @@
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
30+import com.datastax.driver.core.exceptions.DriverInternalError;
31+
3032 /**
3133 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
3234 */
@@ -437,6 +439,36 @@
437439 return sb.toString();
438440 }
439441
442+ /**
443+ * Builds a new {@link Token} from its string representation, according to the partitioner
444+ * reported by the Cassandra nodes.
445+ *
446+ * @param tokenStr the string representation.
447+ * @return the token.
448+ */
449+ public Token newToken(String tokenStr) {
450+ TokenMap current = tokenMap;
451+ if (current == null)
452+ throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
453+
454+ return current.factory.fromString(tokenStr);
455+ }
456+
457+ /**
458+ * Builds a new {@link TokenRange}.
459+ *
460+ * @param start the start token.
461+ * @param end the end token.
462+ * @return the range.
463+ */
464+ public TokenRange newTokenRange(Token start, Token end) {
465+ TokenMap current = tokenMap;
466+ if (current == null)
467+ throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
468+
469+ return new TokenRange(start, end, current.factory);
470+ }
471+
440472 Token.Factory tokenFactory() {
441473 TokenMap current = tokenMap;
442474 return (current == null) ? null : current.factory;
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +8 −0
@@ -310,6 +310,14 @@
310310 return true;
311311 }
312312 }
313+ } catch (UnsupportedProtocolVersionException e) {
314+ cluster.manager.logUnsupportedVersionProtocol(host);
315+ cluster.manager.triggerOnDown(host, false);
316+ return false;
317+ } catch (ClusterNameMismatchException e) {
318+ cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
319+ cluster.manager.triggerOnDown(host, false);
320+ return false;
313321 } catch (Exception e) {
314322 logger.error("Error creating pool to " + host, e);
315323 return false;
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +18 −11
@@ -100,8 +100,8 @@
100100
101101 private static final BigInteger RING_END = BigInteger.valueOf(Long.MAX_VALUE);
102102 private static final BigInteger RING_LENGTH = RING_END.subtract(BigInteger.valueOf(Long.MIN_VALUE));
103- public static final M3PToken MIN_TOKEN = new M3PToken(Long.MIN_VALUE);
104- public static final M3PToken MAX_TOKEN = new M3PToken(Long.MAX_VALUE);
103+ static final M3PToken MIN_TOKEN = new M3PToken(Long.MIN_VALUE);
104+ static final M3PToken MAX_TOKEN = new M3PToken(Long.MAX_VALUE);
105105
106106 private long getblock(ByteBuffer key, int offset, int index) {
107107 int i_8 = index << 3;
@@ -202,7 +202,7 @@
202202 }
203203
204204 @Override
205- public M3PToken fromString(String tokenStr) {
205+ M3PToken fromString(String tokenStr) {
206206 return new M3PToken(Long.parseLong(tokenStr));
207207 }
208208
@@ -222,7 +222,7 @@
222222 }
223223
224224 @Override
225- public M3PToken hash(ByteBuffer partitionKey) {
225+ M3PToken hash(ByteBuffer partitionKey) {
226226 long v = murmur(partitionKey);
227227 return new M3PToken(v == Long.MIN_VALUE ? Long.MAX_VALUE : v);
228228 }
@@ -305,8 +305,15 @@
305305
306306 @Override
307307 public OPPToken fromString(String tokenStr) {
308- String prefix = (tokenStr.length() % 2 == 0) ? "0x" : "0x0";
309- ByteBuffer value = Bytes.fromHexString(prefix + tokenStr);
308+ // This method must be able to parse the contents of system.peers.tokens, which do not have the "0x" prefix.
309+ // On the other hand, OPPToken#toString has the "0x" because it should be usable in a CQL query, and it's
310+ // nice to have fromString and toString symetrical.
311+ // So handle both cases:
312+ if (!tokenStr.startsWith("0x")) {
313+ String prefix = (tokenStr.length() % 2 == 0) ? "0x" : "0x0";
314+ tokenStr = prefix + tokenStr;
315+ }
316+ ByteBuffer value = Bytes.fromHexString(tokenStr);
310317 return new OPPToken(value);
311318 }
312319
@@ -326,12 +333,12 @@
326333 }
327334
328335 @Override
329- public OPPToken hash(ByteBuffer partitionKey) {
336+ OPPToken hash(ByteBuffer partitionKey) {
330337 return new OPPToken(partitionKey);
331338 }
332339
333340 @Override
334- public List<Token> split(Token startToken, Token endToken, int numberOfSplits) {
341+ List<Token> split(Token startToken, Token endToken, int numberOfSplits) {
335342 int tokenOrder = startToken.compareTo(endToken);
336343
337344 // ]min,min] means the whole ring. However, since there is no "max token" with this partitioner, we can't come up
@@ -514,7 +521,7 @@
514521 }
515522
516523 @Override
517- public RPToken fromString(String tokenStr) {
524+ RPToken fromString(String tokenStr) {
518525 return new RPToken(new BigInteger(tokenStr));
519526 }
520527
@@ -534,7 +541,7 @@
534541 }
535542
536543 @Override
537- public RPToken hash(ByteBuffer partitionKey) {
544+ RPToken hash(ByteBuffer partitionKey) {
538545 return new RPToken(md5(partitionKey));
539546 }
540547
@@ -559,7 +566,7 @@
559566 tokens.add(new RPToken(value));
560567 return tokens;
561568 }
562- };
569+ }
563570
564571 private RPToken(BigInteger value) {
565572 this.value = value;
modified driver-core/src/main/java/com/datastax/driver/core/TokenRange.java +20 −0
@@ -163,6 +163,26 @@
163163 || that.contains(this.end, false);
164164 }
165165
166+ /**
167+ * Computes the intersection of this range with another one.
168+ * <p>
169+ * This call will fail if the two ranges do not intersect, you must check by calling
170+ * {@link #intersects(TokenRange)} beforehand.
171+ *
172+ * @param that the other range.
173+ * @return the range resulting from the intersection.
174+ * @throws IllegalArgumentException if the ranges do not intersect.
175+ */
176+ public TokenRange intersectWith(TokenRange that) {
177+ if (!this.intersects(that))
178+ throw new IllegalArgumentException("The two ranges do not intersect, use intersects() before calling this method");
179+
180+ return new TokenRange(
181+ (this.contains(that.start, true)) ? that.start : this.start,
182+ (this.contains(that.end, false)) ? that.end : this.end,
183+ factory);
184+ }
185+
166186 // isStart handles the case where the token is the start of another range, for example:
167187 // * ]1,2] contains 2, but it does not contain the start of ]2,3]
168188 // * ]1,2] does not contain 1, but it contains the start of ]1,3]
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +4 −4
@@ -66,9 +66,9 @@
6666
6767 static class InClause extends AbstractClause {
6868
69- private final List<Object> values;
69+ private final List<?> values;
7070
71- InClause(String name, List<Object> values) {
71+ InClause(String name, List<?> values) {
7272 super(name);
7373 this.values = values;
7474
@@ -114,9 +114,9 @@
114114 static class CompoundClause extends Clause {
115115 private String op;
116116 private final List<String> names;
117- private final List<Object> values;
117+ private final List<?> values;
118118
119- CompoundClause(List<String> names, String op, List<Object> values) {
119+ CompoundClause(List<String> names, String op, List<?> values) {
120120 assert names.size() == values.size();
121121 this.op = op;
122122 this.names = names;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +2 −2
@@ -27,13 +27,13 @@
2727 public class Delete extends BuiltStatement {
2828
2929 private final String table;
30- private final List<Object> columnNames;
30+ private final List<?> columnNames;
3131 private final Where where;
3232 private final Options usings;
3333 private final Conditions conditions;
3434 private boolean ifExists;
3535
36- Delete(String keyspace, String table, List<Object> columnNames) {
36+ Delete(String keyspace, String table, List<?> columnNames) {
3737 super(keyspace);
3838 this.table = table;
3939 this.columnNames = columnNames;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +5 −5
@@ -295,7 +295,7 @@
295295 * @param values the values
296296 * @return the corresponding where clause.
297297 */
298- public static Clause in(String name, List<Object> values) {
298+ public static Clause in(String name, List<?> values) {
299299 return new Clause.InClause(name, values);
300300 }
301301
@@ -325,7 +325,7 @@
325325 *
326326 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
327327 */
328- public static Clause lt(List<String> names, List<Object> values) {
328+ public static Clause lt(List<String> names, List<?> values) {
329329 if (names.size() != values.size())
330330 throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size()));
331331
@@ -358,7 +358,7 @@
358358 *
359359 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
360360 */
361- public static Clause lte(List<String> names, List<Object> values) {
361+ public static Clause lte(List<String> names, List<?> values) {
362362 if (names.size() != values.size())
363363 throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size()));
364364
@@ -391,7 +391,7 @@
391391 *
392392 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
393393 */
394- public static Clause gt(List<String> names, List<Object> values) {
394+ public static Clause gt(List<String> names, List<?> values) {
395395 if (names.size() != values.size())
396396 throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size()));
397397
@@ -424,7 +424,7 @@
424424 *
425425 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
426426 */
427- public static Clause gte(List<String> names, List<Object> values) {
427+ public static Clause gte(List<String> names, List<?> values) {
428428 if (names.size() != values.size())
429429 throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size()));
430430
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +2 −2
@@ -42,7 +42,7 @@
4242 return sb;
4343 }
4444
45- static StringBuilder joinAndAppendNames(StringBuilder sb, String separator, List<Object> values) {
45+ static StringBuilder joinAndAppendNames(StringBuilder sb, String separator, List<?> values) {
4646 for (int i = 0; i < values.size(); i++) {
4747 if (i > 0)
4848 sb.append(separator);
@@ -51,7 +51,7 @@
5151 return sb;
5252 }
5353
54- static StringBuilder joinAndAppendValues(StringBuilder sb, String separator, List<Object> values, List<Object> variables) {
54+ static StringBuilder joinAndAppendValues(StringBuilder sb, String separator, List<?> values, List<Object> variables) {
5555 for (int i = 0; i < values.size(); i++) {
5656 if (i > 0)
5757 sb.append(separator);
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +8 −0
@@ -97,6 +97,14 @@
9797 return bridge;
9898 }
9999
100+ public static CCMBridge createWithCustomVersion(String name, int nbNodes, String cassandraVersion) {
101+ checkArgument(!"current".equals(name.toLowerCase()),
102+ "cluster can't be called \"current\"");
103+ CCMBridge bridge = new CCMBridge();
104+ bridge.execute("ccm create %s -n %d -s -i %s -b -v %s ", name, nbNodes, IP_PREFIX, cassandraVersion);
105+ return bridge;
106+ }
107+
100108 public static CCMBridge create(String name, int nbNodesDC1, int nbNodesDC2) {
101109 checkArgument(!"current".equals(name.toLowerCase()),
102110 "cluster can't be called \"current\"");
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +5 −0
@@ -21,6 +21,11 @@
2121 return this;
2222 }
2323
24+ public ClusterAssert hasClosedControlConnection() {
25+ assertThat(actual.manager.controlConnection.isOpen()).isFalse();
26+ return this;
27+ }
28+
2429 public HostAssert host(int hostNumber) {
2530 // TODO at some point this won't work anymore if we have assertions that wait for a node to
2631 // join the cluster, e.g. assertThat(cluster).node(3).comesUp().
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +13 −0
@@ -32,6 +32,19 @@
3232 return this;
3333 }
3434
35+ public HostAssert isNotReconnectingFromDown() {
36+ assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone())
37+ .isFalse();
38+ return this;
39+ }
40+
41+ public HostAssert isNotReconnectingFromSuspected() {
42+ assertThat(actual.getInitialReconnectionAttemptFuture() != null && !actual.getInitialReconnectionAttemptFuture().isDone())
43+ .isFalse();
44+ return this;
45+
46+ }
47+
3548 public HostAssert comesUpWithin(long duration, TimeUnit unit) {
3649 final CountDownLatch upSignal = new CountDownLatch(1);
3750 StateListener upListener = new StateListenerBase() {
added driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +163 −0
@@ -0,0 +1,163 @@
1+package com.datastax.driver.core;
2+
3+import java.util.concurrent.TimeUnit;
4+
5+import org.slf4j.Logger;
6+import org.slf4j.LoggerFactory;
7+import org.testng.annotations.AfterMethod;
8+import org.testng.annotations.Test;
9+
10+import com.datastax.driver.core.utils.CassandraVersion;
11+
12+import static com.datastax.driver.core.Assertions.*;
13+import static com.datastax.driver.core.Host.State.DOWN;
14+import static com.datastax.driver.core.Host.State.UP;
15+
16+/**
17+ * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
18+ *
19+ * This class tests scenarios where these nodes have been recommissioned to another cluster and
20+ * come back up. The driver must detect that they are not part of the cluster anymore, and ignore them.
21+ */
22+public class RecommissionedNodeTest {
23+ private static final Logger logger = LoggerFactory.getLogger(RecommissionedNodeTest.class);
24+
25+ CCMBridge mainCcm, otherCcm;
26+ Cluster mainCluster;
27+
28+ @Test(groups = "long")
29+ public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
30+ mainCcm = CCMBridge.create("main", 3);
31+ // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
32+ mainCcm.stop(1);
33+ mainCcm.waitForDown(1);
34+
35+ // Now start the driver that will connect to node2 and node3, and consider node1 down
36+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
37+ mainCluster.connect();
38+ waitForCountUpHosts(mainCluster, 2);
39+ // From that point, reconnections to node1 have been scheduled.
40+
41+ // Start another ccm that will reuse node1's address
42+ otherCcm = CCMBridge.create("other", 1);
43+ otherCcm.waitForUp(1);
44+
45+ // Give the driver the time to notice the node is back up and try to connect to it.
46+ TimeUnit.SECONDS.sleep(32);
47+
48+ assertThat(countUpHosts(mainCluster)).isEqualTo(2);
49+ }
50+
51+ @Test(groups = "long")
52+ public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
53+ mainCcm = CCMBridge.create("main", 2);
54+ mainCcm.stop(1);
55+ mainCcm.waitForDown(1);
56+
57+ // Start the driver, the control connection will be on node2
58+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
59+ mainCluster.connect();
60+ waitForCountUpHosts(mainCluster, 1);
61+
62+ // Start another ccm that will reuse node1's address
63+ otherCcm = CCMBridge.create("other", 1);
64+ otherCcm.waitForUp(1);
65+
66+ // Stop node2, the control connection gets defunct
67+ mainCcm.stop(2);
68+ TimeUnit.SECONDS.sleep(32);
69+
70+ // The driver should not try to reconnect the control connection to node1
71+ assertThat(mainCluster).hasClosedControlConnection();
72+ }
73+
74+ @Test(groups = "long")
75+ public void should_ignore_recommissioned_node_on_session_init() throws Exception {
76+ // Simulate the bug before starting the cluster
77+ mainCcm = CCMBridge.create("main", 2);
78+ mainCcm.stop(1);
79+ mainCcm.waitForDown(1);
80+
81+ otherCcm = CCMBridge.create("other", 1);
82+ otherCcm.waitForUp(1);
83+
84+ // Start the driver, it should only connect to node 2
85+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
86+
87+ // When we first initialize the Cluster, all hosts are marked UP
88+ assertThat(mainCluster).host(2).hasState(UP);
89+ assertThat(mainCluster).host(1).hasState(UP);
90+
91+ // Create a session. This will try to open a pool to node 1 and find out that the cluster name doesn't match.
92+ mainCluster.connect();
93+
94+ // Node 1 should now be DOWN with no reconnection attempt
95+ assertThat(mainCluster).host(1)
96+ .hasState(DOWN)
97+ .isNotReconnectingFromDown()
98+ .isNotReconnectingFromSuspected();
99+ }
100+
101+ @Test(groups = "long")
102+ @CassandraVersion(major=2.0)
103+ public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
104+ // Simulate the bug before starting the cluster
105+ mainCcm = CCMBridge.create("main", 2);
106+ mainCcm.stop(1);
107+ mainCcm.waitForDown(1);
108+
109+ otherCcm = CCMBridge.createWithCustomVersion("main", 1, "1.2.19");
110+ otherCcm.waitForUp(1);
111+
112+ // Start the driver, it should only connect to node 2
113+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
114+
115+ // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
116+ mainCluster.connect();
117+
118+ // Node 1 should now be DOWN with no reconnection attempt
119+ assertThat(mainCluster).host(1)
120+ .hasState(DOWN)
121+ .isNotReconnectingFromDown()
122+ .isNotReconnectingFromSuspected();
123+ }
124+
125+ @AfterMethod(groups = "long")
126+ public void teardown() {
127+ if (mainCluster != null)
128+ mainCluster.close();
129+
130+ if (mainCcm != null)
131+ mainCcm.remove();
132+ if (otherCcm != null)
133+ otherCcm.remove();
134+ }
135+
136+ private static int countUpHosts(Cluster cluster) {
137+ int ups = 0;
138+ for (Host host : cluster.getMetadata().getAllHosts()) {
139+ if (host.isUp())
140+ ups += 1;
141+ }
142+ return ups;
143+ }
144+
145+ private static void waitForCountUpHosts(Cluster cluster, int expectedCount) throws InterruptedException {
146+ int maxRetries = 30;
147+ int interval = 10;
148+
149+ for (int i = 0; i <= maxRetries; i++) {
150+ int actualCount = countUpHosts(cluster);
151+ if (actualCount == expectedCount)
152+ return;
153+
154+ if (i == maxRetries)
155+ fail(String.format("Up host count didn't reach %d after %d seconds",
156+ expectedCount, i * interval));
157+ else
158+ logger.debug("Counted {} up hosts after {} seconds", actualCount, i * interval);
159+
160+ TimeUnit.SECONDS.sleep(interval);
161+ }
162+ }
163+}
No newline at the end of the file
deleted driver-core/src/test/java/com/datastax/driver/core/RecommissionnedNodeTest.java +0 −113
@@ -1,113 +0,0 @@
1-package com.datastax.driver.core;
2-
3-import java.util.concurrent.TimeUnit;
4-
5-import org.slf4j.Logger;
6-import org.slf4j.LoggerFactory;
7-import org.testng.annotations.AfterMethod;
8-import org.testng.annotations.Test;
9-import static org.testng.Assert.*;
10-
11-/**
12- * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
13- *
14- * This class tests scenarios where these nodes have been recommissionned to another cluster and
15- * come back up. The driver must detect that they are not part of the cluster anymore, and ignore them.
16- */
17-public class RecommissionnedNodeTest {
18- private static final Logger logger = LoggerFactory.getLogger(RecommissionnedNodeTest.class);
19-
20- CCMBridge mainCcm, otherCcm;
21- Cluster mainCluster;
22-
23- /**
24- * Tests the case when trying to reconnect to the foreign node results from a scheduled reconnection attempt.
25- */
26- @Test(groups = "long")
27- public void testReconnectionToRegularNode() throws Exception {
28- mainCcm = CCMBridge.create("main", 3);
29- // node1 will be our "recommissionned" node, for now we just stop it so that it stays in the peers table.
30- mainCcm.stop(1);
31- mainCcm.waitForDown(1);
32-
33- // Now start the driver that will connect to node2 and node3, and consider node1 down
34- Cluster mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
35- mainCluster.connect();
36- waitForCountUpHosts(mainCluster, 2);
37- // From that point, reconnections to node1 have been scheduled.
38-
39- // Start another ccm that will reuse node1's address
40- otherCcm = CCMBridge.create("other", 1);
41- otherCcm.waitForUp(1);
42-
43- // Give the driver the time to notice the node is back up and try to connect to it.
44- TimeUnit.SECONDS.sleep(32);
45-
46- assertEquals(countUpHosts(mainCluster), 2);
47- }
48-
49- /**
50- * Tests the case when trying to reconnect to the foreign node results from a scheduled reconnection attempt.
51- */
52- @Test(groups = "long")
53- public void testControlConnection() throws Exception {
54- mainCcm = CCMBridge.create("main", 2);
55- mainCcm.stop(1);
56- mainCcm.waitForDown(1);
57-
58- // Start the driver, the control connection will be on node2
59- Cluster mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
60- mainCluster.connect();
61- waitForCountUpHosts(mainCluster, 1);
62-
63- // Start another ccm that will reuse node1's address
64- otherCcm = CCMBridge.create("other", 1);
65- otherCcm.waitForUp(1);
66-
67- // Stop node2, the control connection gets defunct
68- mainCcm.stop(2);
69- TimeUnit.SECONDS.sleep(32);
70-
71- // The driver should not try to reconnect the control connection to node1
72- assertFalse(mainCluster.manager.controlConnection.isOpen());
73- }
74-
75- @AfterMethod(groups = "long")
76- public void teardown() {
77- if (mainCluster != null)
78- mainCluster.close();
79-
80- if (mainCcm != null)
81- mainCcm.remove();
82- if (otherCcm != null)
83- otherCcm.remove();
84- }
85-
86- private static int countUpHosts(Cluster cluster) {
87- int ups = 0;
88- for (Host host : cluster.getMetadata().getAllHosts()) {
89- if (host.isUp())
90- ups += 1;
91- }
92- return ups;
93- }
94-
95- private static void waitForCountUpHosts(Cluster cluster, int expectedCount) throws InterruptedException {
96- int maxRetries = 30;
97- int interval = 10;
98-
99- for (int i = 0; i <= maxRetries; i++) {
100- int actualCount = countUpHosts(cluster);
101- if (actualCount == expectedCount)
102- return;
103-
104- if (i == maxRetries)
105- fail(String.format("Up host count didn't reach %d after %d seconds",
106- expectedCount, i * interval));
107- else
108- logger.debug("Counted {} up hosts after {} seconds", actualCount, i * interval);
109-
110- TimeUnit.SECONDS.sleep(interval);
111- }
112- }
113-}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +14 −1
@@ -76,7 +76,6 @@
7676
7777 @AfterClass(groups = "short", alwaysRun=true)
7878 public void teardown() {
79- System.out.println("Tearing down");
8079 if (cluster != null)
8180 cluster.close();
8281 if (ccm != null)
@@ -360,5 +359,19 @@
360359 }
361360 }
362361
362+ @Test(groups = "short")
363+ public void should_expose_token_and_range_creation_methods() {
364+ Metadata metadata = cluster.getMetadata();
365+
366+ // Pick a random range
367+ TokenRange range = metadata.getTokenRanges().iterator().next();
368+
369+ Token start = metadata.newToken(range.getStart().toString());
370+ Token end = metadata.newToken(range.getEnd().toString());
371+
372+ assertThat(metadata.newTokenRange(start, end))
373+ .isEqualTo(range);
374+ }
375+
363376 protected abstract Token.Factory tokenFactory();
364377 }
modified driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +27 −12
@@ -1,14 +1,11 @@
11 package com.datastax.driver.core;
22
3-import java.math.BigInteger;
43 import java.util.List;
54
65 import org.testng.annotations.Test;
76
87 import static org.testng.Assert.fail;
98
10-import com.datastax.driver.core.Token.M3PToken;
11-
129 import static com.datastax.driver.core.Assertions.assertThat;
1310
1411 public class TokenRangeTest {
@@ -76,6 +73,25 @@
7673 ;
7774 }
7875
76+ @Test(groups = "unit")
77+ public void should_compute_intersection() {
78+ assertThat(tokenRange(3, 9).intersectWith(tokenRange(2, 4)))
79+ .isEqualTo(tokenRange(3, 4));
80+ assertThat(tokenRange(3, 9).intersectWith(tokenRange(3, 5)))
81+ .isEqualTo(tokenRange(3, 5));
82+ assertThat(tokenRange(3, 9).intersectWith(tokenRange(4, 6)))
83+ .isEqualTo(tokenRange(4, 6));
84+ assertThat(tokenRange(3, 9).intersectWith(tokenRange(7, 9)))
85+ .isEqualTo(tokenRange(7, 9));
86+ assertThat(tokenRange(3, 9).intersectWith(tokenRange(8, 10)))
87+ .isEqualTo(tokenRange(8, 9));
88+ }
89+
90+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
91+ public void should_fail_to_compute_intersection_when_ranges_dont_intersect() {
92+ tokenRange(1, 2).intersectWith(tokenRange(2, 3));
93+ }
94+
7995 @Test(groups = "unit")
8096 public void should_merge_with_other_range() {
8197 assertThat(tokenRange(3, 9).mergeWith(tokenRange(2, 3))).isEqualTo(tokenRange(2, 9));
@@ -128,12 +144,12 @@
128144
129145 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
130146 public void should_not_merge_with_nonadjacent_and_disjoint_ranges() {
131- tokenRange(0,5).mergeWith(tokenRange(7,14));
147+ tokenRange(0, 5).mergeWith(tokenRange(7, 14));
132148 }
133149
134150 @Test(groups = "unit")
135151 public void should_return_non_empty_range_if_other_range_is_empty() {
136- assertThat(tokenRange(1,5).mergeWith(tokenRange(5,5))).isEqualTo(tokenRange(1,5));
152+ assertThat(tokenRange(1, 5).mergeWith(tokenRange(5, 5))).isEqualTo(tokenRange(1, 5));
137153 }
138154
139155 @Test(groups = "unit")
@@ -155,14 +171,13 @@
155171 assertThat(splits).containsExactly(tokenRange(3, 5), tokenRange(5, 7), tokenRange(7, 9));
156172 }
157173
158-
159174 @Test(groups = "unit")
160175 public void should_throw_error_with_less_than_1_splits() {
161- for(int i = -255; i < 1; i++) {
176+ for (int i = -255; i < 1; i++) {
162177 try {
163178 tokenRange(0, 1).splitEvenly(i);
164179 fail("Expected error when providing " + i + " splits.");
165- } catch(IllegalArgumentException e) {
180+ } catch (IllegalArgumentException e) {
166181 // expected.
167182 }
168183 }
@@ -175,15 +190,15 @@
175190
176191 @Test(groups = "unit")
177192 public void should_create_empty_token_ranges_if_too_many_splits() {
178- TokenRange range = tokenRange(0,10);
193+ TokenRange range = tokenRange(0, 10);
179194
180195 List<TokenRange> ranges = range.splitEvenly(255);
181196 assertThat(ranges).hasSize(255);
182197
183- for(int i = 0; i < ranges.size(); i++) {
198+ for (int i = 0; i < ranges.size(); i++) {
184199 TokenRange tr = ranges.get(i);
185- if(i < 10) {
186- assertThat(tr).isEqualTo(tokenRange(i, i+1));
200+ if (i < 10) {
201+ assertThat(tr).isEqualTo(tokenRange(i, i + 1));
187202 } else {
188203 assertThat(tr.isEmpty());
189204 }