Elffuss BraidHub

kikocis/java-driver public

Check cluster name when connecting to a new node (JAVA-397).
Changeset104fa6de54172dfb2427e810ad9191d4a7576607f080a9c68badf11fc29a87da
Authorolim7t <omichallat+github@gmail.com> · 2014-08-27 11:52 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-08-27 11:58 +02:00
Parents465eeff48b33

Browse the files at this changeset

11 files changed

modified driver-core/CHANGELOG.rst +5 −0
@@ -1,6 +1,11 @@
11 CHANGELOG
22 =========
33
4+2.0.6:
5+------
6+
7+- [bug] Check cluster name when connecting to a new node (JAVA-397)
8+
49 2.0.5:
510 ------
611
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +11 −1
@@ -45,7 +45,7 @@
4545 this.currentAttempt = currentAttempt;
4646 }
4747
48- protected abstract Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException;
48+ protected abstract Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException;
4949 protected abstract void onReconnection(Connection connection);
5050
5151 protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { return true; }
@@ -54,6 +54,7 @@
5454 // Retrying on authentication or unsupported protocol version error is unlikely to work
5555 protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) { return false; }
5656 protected boolean onUnsupportedProtocolVersionException(UnsupportedProtocolVersionException e, long nextDelayMs) { return false; }
57+ protected boolean onClusterNameMismatchException(ClusterNameMismatchException e, long nextDelayMs) { return false; }
5758
5859 public void start() {
5960 long firstDelay = schedule.nextDelayMs();
@@ -118,6 +119,15 @@
118119 logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.address);
119120 currentAttempt.compareAndSet(localFuture, null);
120121 }
122+ } catch (ClusterNameMismatchException e) {
123+ logger.error(e.getMessage());
124+ long nextDelay = schedule.nextDelayMs();
125+ if (onClusterNameMismatchException(e, nextDelay)) {
126+ reschedule(nextDelay);
127+ } else {
128+ logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.address);
129+ currentAttempt.compareAndSet(localFuture, null);
130+ }
121131 } catch (Exception e) {
122132 long nextDelay = schedule.nextDelayMs();
123133 if (onUnknownException(e, nextDelay))
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +15 −3
@@ -1252,6 +1252,12 @@
12521252 + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host);
12531253 }
12541254
1255+ void logClusterNameMismatch(Host host, String expectedClusterName, String actualClusterName) {
1256+ logger.warn("Detected added or restarted Cassandra host {} but ignoring it since its cluster name '{}' does not match the one "
1257+ + "currently known ({})",
1258+ host, actualClusterName, expectedClusterName);
1259+ }
1260+
12551261 public ListenableFuture<?> triggerOnUp(final Host host) {
12561262 return executor.submit(new ExceptionCatchingRunnable() {
12571263 @Override
@@ -1300,6 +1306,9 @@
13001306 } catch (UnsupportedProtocolVersionException e) {
13011307 logUnsupportedVersionProtocol(host);
13021308 return;
1309+ } catch (ClusterNameMismatchException e) {
1310+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1311+ return;
13031312 }
13041313
13051314 // Session#onUp() expects the load balancing policy to have been updated first, so that
@@ -1472,7 +1481,7 @@
14721481 logger.debug("{} is down, scheduling connection retries", host);
14731482 new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) {
14741483
1475- protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException {
1484+ protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
14761485 return connectionFactory.open(host);
14771486 }
14781487
@@ -1507,7 +1516,7 @@
15071516 }
15081517
15091518 protected boolean onUnknownException(Exception e, long nextDelayMs) {
1510- logger.error(String.format("Unknown error during control connection reconnection, scheduling retry in %d milliseconds", nextDelayMs), e);
1519+ logger.error(String.format("Unknown error during reconnection to %s, scheduling retry in %d milliseconds", host, nextDelayMs), e);
15111520 return true;
15121521 }
15131522
@@ -1560,6 +1569,9 @@
15601569 } catch (UnsupportedProtocolVersionException e) {
15611570 logUnsupportedVersionProtocol(host);
15621571 return;
1572+ } catch (ClusterNameMismatchException e) {
1573+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1574+ return;
15631575 }
15641576
15651577 controlConnection.onAdd(host);
@@ -1687,7 +1699,7 @@
16871699 return stmt;
16881700 }
16891701
1690- private void prepareAllQueries(Host host) throws InterruptedException, UnsupportedProtocolVersionException {
1702+ private void prepareAllQueries(Host host) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
16911703 if (preparedQueries.isEmpty())
16921704 return;
16931705
added driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java +38 −0
@@ -0,0 +1,38 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.net.InetSocketAddress;
19+
20+/**
21+ * Indicates that we've attempted to connect to a node which cluster name doesn't match that of the other nodes known to the driver.
22+ */
23+class ClusterNameMismatchException extends Exception {
24+
25+ private static final long serialVersionUID = 0;
26+
27+ public final InetSocketAddress address;
28+ public final String expectedClusterName;
29+ public final String actualClusterName;
30+
31+ public ClusterNameMismatchException(InetSocketAddress address, String actualClusterName, String expectedClusterName) {
32+ super(String.format("[%s] Host %s reports cluster name '%s' that doesn't match our cluster name '%s'. This host will be ignored.",
33+ address, address, actualClusterName, expectedClusterName));
34+ this.address = address;
35+ this.expectedClusterName = expectedClusterName;
36+ this.actualClusterName = actualClusterName;
37+ }
38+}
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +23 −5
@@ -80,7 +80,7 @@
8080 * @throws ConnectionException if the connection attempts fails or is
8181 * refused by the server.
8282 */
83- protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException {
83+ protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
8484 this.address = address;
8585 this.factory = factory;
8686 this.name = name;
@@ -108,7 +108,7 @@
108108 }
109109
110110 logger.trace("[{}] Connection opened successfully", name);
111- initializeTransport(protocolVersion);
111+ initializeTransport(protocolVersion, factory.manager.metadata.clusterName);
112112 logger.debug("[{}] Transport initialized and ready", name);
113113 isInitialized = true;
114114 }
@@ -122,7 +122,7 @@
122122 return " (" + msg + ')';
123123 }
124124
125- private void initializeTransport(int version) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException {
125+ private void initializeTransport(int version, String clusterName) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
126126 try {
127127 ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
128128 Message.Response response = write(new Requests.Startup(compression)).get();
@@ -151,6 +151,8 @@
151151 default:
152152 throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
153153 }
154+
155+ checkClusterName(clusterName);
154156 } catch (BusyConnectionException e) {
155157 throw defunct(new DriverInternalError("Newly created connection should not be busy"));
156158 } catch (ExecutionException e) {
@@ -221,6 +223,22 @@
221223 }
222224 }
223225
226+ // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
227+ // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
228+ // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
229+ private void checkClusterName(String expected) throws ClusterNameMismatchException, ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
230+ // At initialization, the cluster is not known yet
231+ if (expected == null)
232+ return;
233+
234+ DefaultResultSetFuture future = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
235+ write(future);
236+ Row row = future.get().one();
237+ String actual = row.getString("cluster_name");
238+ if (!expected.equals(actual))
239+ throw new ClusterNameMismatchException(address, actual, expected);
240+ }
241+
224242 public boolean isDefunct() {
225243 return isDefunct;
226244 }
@@ -435,7 +453,7 @@
435453 *
436454 * @throws ConnectionException if connection attempt fails.
437455 */
438- public Connection open(Host host) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException {
456+ public Connection open(Host host) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
439457 InetSocketAddress address = host.getSocketAddress();
440458
441459 if (isShutdown)
@@ -448,7 +466,7 @@
448466 /**
449467 * Same as open, but associate the created connection to the provided connection pool.
450468 */
451- public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException {
469+ public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
452470 InetSocketAddress address = pool.host.getSocketAddress();
453471
454472 if (isShutdown)
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +5 −2
@@ -179,7 +179,10 @@
179179 if (cluster.protocolVersion() < 1)
180180 throw e;
181181 logger.debug("Ignoring host {}: {}", host, e.getMessage());
182- errors = logError(host, e.getCause(), errors, iter);
182+ errors = logError(host, e, errors, iter);
183+ } catch (ClusterNameMismatchException e) {
184+ logger.debug("Ignoring host {}: {}", host, e.getMessage());
185+ errors = logError(host, e, errors, iter);
183186 }
184187 }
185188 } catch (InterruptedException e) {
@@ -211,7 +214,7 @@
211214 return errors;
212215 }
213216
214- private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException {
217+ private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
215218 Connection connection = cluster.connectionFactory.open(host);
216219
217220 try {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +5 −1
@@ -64,7 +64,7 @@
6464
6565 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
6666
67- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException {
67+ public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
6868 assert hostDistance != HostDistance.IGNORED;
6969 this.host = host;
7070 this.hostDistance = hostDistance;
@@ -336,6 +336,10 @@
336336 open.decrementAndGet();
337337 logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
338338 return false;
339+ } catch (ClusterNameMismatchException e) {
340+ open.decrementAndGet();
341+ logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
342+ return false;
339343 }
340344 }
341345
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +1 −1
@@ -24,7 +24,7 @@
2424
2525 private final HostConnectionPool pool;
2626
27- PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException {
27+ PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
2828 super(name, address, factory);
2929 this.pool = pool;
3030 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +1 −1
@@ -227,7 +227,7 @@
227227 // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools
228228 // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we
229229 // want to avoid
230- private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException {
230+ private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
231231 if (isClosing)
232232 return true;
233233
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +13 −0
@@ -34,6 +34,8 @@
3434 import java.util.Collection;
3535 import java.util.Map;
3636
37+import static com.google.common.base.Preconditions.checkArgument;
38+
3739 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
3840 import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
3941
@@ -73,18 +75,25 @@
7375 }
7476
7577 public static CCMBridge create(String name) {
78+ // This leads to a confusing CCM error message so check explicitly:
79+ checkArgument(!"current".equals(name.toLowerCase()),
80+ "cluster can't be called \"current\"");
7681 CCMBridge bridge = new CCMBridge();
7782 bridge.execute("ccm create %s -b -i %s %s", name, IP_PREFIX, CASSANDRA_VERSION);
7883 return bridge;
7984 }
8085
8186 public static CCMBridge create(String name, int nbNodes) {
87+ checkArgument(!"current".equals(name.toLowerCase()),
88+ "cluster can't be called \"current\"");
8289 CCMBridge bridge = new CCMBridge();
8390 bridge.execute("ccm create %s -n %d -s -i %s -b %s", name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
8491 return bridge;
8592 }
8693
8794 public static CCMBridge create(String name, int nbNodesDC1, int nbNodesDC2) {
95+ checkArgument(!"current".equals(name.toLowerCase()),
96+ "cluster can't be called \"current\"");
8897 CCMBridge bridge = new CCMBridge();
8998 bridge.execute("ccm create %s -n %d:%d -s -i %s -b %s", name, nbNodesDC1, nbNodesDC2, IP_PREFIX, CASSANDRA_VERSION);
9099 return bridge;
@@ -330,6 +339,10 @@
330339 return new CCMCluster(CCMBridge.create("test", nbNodesDC1, nbNodesDC2), builder, nbNodesDC1 + nbNodesDC2);
331340 }
332341
342+ public static CCMCluster create(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
343+ return new CCMCluster(cassandraCluster, builder, totalNodes);
344+ }
345+
333346 private CCMCluster(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
334347 this.cassandraCluster = cassandraCluster;
335348 try {
added driver-core/src/test/java/com/datastax/driver/core/RecommissionnedNodeTest.java +165 −0
@@ -0,0 +1,165 @@
1+package com.datastax.driver.core;
2+
3+import java.io.IOException;
4+import java.net.InetAddress;
5+import java.net.Socket;
6+import java.util.concurrent.TimeUnit;
7+
8+import org.slf4j.Logger;
9+import org.slf4j.LoggerFactory;
10+import org.testng.annotations.AfterMethod;
11+import org.testng.annotations.Test;
12+import static org.testng.Assert.*;
13+
14+/**
15+ * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
16+ *
17+ * This class tests scenarios where these nodes have been recommissionned to another cluster and
18+ * come back up. The driver must detect that they are not part of the cluster anymore, and ignore them.
19+ */
20+public class RecommissionnedNodeTest {
21+ private static final Logger logger = LoggerFactory.getLogger(RecommissionnedNodeTest.class);
22+
23+ CCMBridge mainCcm, otherCcm;
24+ Cluster mainCluster;
25+
26+ /**
27+ * Tests the case when trying to reconnect to the foreign node results from a scheduled reconnection attempt.
28+ */
29+ @Test(groups = "long")
30+ public void testReconnectionToRegularNode() throws Exception {
31+ mainCcm = CCMBridge.create("main", 3);
32+ // node1 will be our "recommissionned" node, for now we just stop it so that it stays in the peers table.
33+ mainCcm.stop(1);
34+ waitForDown(1);
35+
36+ // Now start the driver that will connect to node2 and node3, and consider node1 down
37+ Cluster mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
38+ mainCluster.connect();
39+ waitForCountUpHosts(mainCluster, 2);
40+ // From that point, reconnections to node1 have been scheduled.
41+
42+ // Start another ccm that will reuse node1's address
43+ otherCcm = CCMBridge.create("other", 1);
44+ waitForUp(1);
45+
46+ // Give the driver the time to notice the node is back up and try to connect to it.
47+ TimeUnit.SECONDS.sleep(32);
48+
49+ assertEquals(countUpHosts(mainCluster), 2);
50+ }
51+
52+ /**
53+ * Tests the case when trying to reconnect to the foreign node results from a scheduled reconnection attempt.
54+ */
55+ @Test(groups = "long")
56+ public void testControlConnection() throws Exception {
57+ mainCcm = CCMBridge.create("main", 2);
58+ mainCcm.stop(1);
59+ waitForDown(1);
60+
61+ // Start the driver, the control connection will be on node2
62+ Cluster mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
63+ mainCluster.connect();
64+ waitForCountUpHosts(mainCluster, 1);
65+
66+ // Start another ccm that will reuse node1's address
67+ otherCcm = CCMBridge.create("other", 1);
68+ waitForUp(1);
69+
70+ // Stop node2, the control connection gets defunct
71+ mainCcm.stop(2);
72+ TimeUnit.SECONDS.sleep(32);
73+
74+ // The driver should not try to reconnect the control connection to node1
75+ assertFalse(mainCluster.manager.controlConnection.isOpen());
76+ }
77+
78+ @AfterMethod(groups = "long")
79+ public void teardown() {
80+ if (mainCluster != null)
81+ mainCluster.close();
82+
83+ if (mainCcm != null)
84+ mainCcm.remove();
85+ if (otherCcm != null)
86+ otherCcm.remove();
87+ }
88+
89+ private static int countUpHosts(Cluster cluster) {
90+ int ups = 0;
91+ for (Host host : cluster.getMetadata().getAllHosts()) {
92+ if (host.isUp())
93+ ups += 1;
94+ }
95+ return ups;
96+ }
97+
98+ private static void waitForCountUpHosts(Cluster cluster, int expectedCount) throws InterruptedException {
99+ int maxRetries = 30;
100+ int interval = 10;
101+
102+ for (int i = 0; i <= maxRetries; i++) {
103+ int actualCount = countUpHosts(cluster);
104+ if (actualCount == expectedCount)
105+ return;
106+
107+ if (i == maxRetries)
108+ fail(String.format("Up host count didn't reach %d after %d seconds",
109+ expectedCount, i * interval));
110+ else
111+ logger.debug("Counted {} up hosts after {} seconds", actualCount, i * interval);
112+
113+ TimeUnit.SECONDS.sleep(interval);
114+ }
115+ }
116+
117+ // Methods to wait for a node's state by pinging the TCP socket directly, instead of using a Cluster instance.
118+ // This decouples these checks from the system under test, and avoids CASSANDRA-7510.
119+ // Contributed by Pierre Laporte.
120+ // TODO: move to a utility class, generalize their use to other tests.
121+
122+ private static void waitForUp(int node) throws Exception {
123+ InetAddress address = InetAddress.getByName(CCMBridge.IP_PREFIX + Integer.toString(node));
124+ busyWaitForPort(address, 9042, true);
125+ }
126+
127+ private static void waitForDown(int node) throws Exception {
128+ InetAddress address = InetAddress.getByName(CCMBridge.IP_PREFIX + Integer.toString(node));
129+ busyWaitForPort(address, 9042, false);
130+ }
131+
132+ private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) throws Exception {
133+ long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10);
134+ long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500);
135+ long waitTimeSoFar = 0;
136+ boolean connectionState = !expectedConnectionState;
137+
138+ while (connectionState != expectedConnectionState && waitTimeSoFar < maxAcceptableWaitTime) {
139+ connectionState = pingPort(address, port);
140+ try {
141+ Thread.sleep(waitQuantum);
142+ waitTimeSoFar += waitQuantum;
143+ } catch (InterruptedException e) {
144+ throw new RuntimeException("Interrupted while pinging " + address + ":" + port, e);
145+ }
146+ }
147+ }
148+
149+ private static boolean pingPort(InetAddress address, int port) throws Exception {
150+ logger.debug("Trying {}:{}...", address, port);
151+ boolean connectionSuccessful = false;
152+ Socket socket = null;
153+ try {
154+ socket = new Socket(address, port);
155+ connectionSuccessful = true;
156+ logger.debug("Successfully connected");
157+ } catch (IOException e) {
158+ logger.debug("Connection failed");
159+ } finally {
160+ if (socket != null)
161+ socket.close();
162+ }
163+ return connectionSuccessful;
164+ }
165+}
No newline at the end of the file