Elffuss BraidHub

kikocis/java-driver public

Ensure control connection does not trigger concurrent reconnects (JAVA-497).
Changeset20675bac40ab7168906d509fdc743e088ad316becdc02327ea511b96548ef76b
Authorolim7t <omichallat+github@gmail.com> · 2014-10-12 18:13 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-12 23:31 +02:00
Parentsc8289a3ecdad

Browse the files at this changeset

4 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -9,6 +9,7 @@
99 - [improvement] Try next host when we get a SERVER_ERROR (JAVA-426)
1010 - [bug] Handle race between query timeout and completion (JAVA-449, JAVA-460, JAVA-471)
1111 - [bug] Fix DCAwareRoundRobinPolicy datacenter auto-discovery (JAVA-496)
12+- [bug] Ensure control connection does not trigger concurrent reconnects (JAVA-497)
1213
1314
1415 2.0.6:
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +18 −6
@@ -18,8 +18,6 @@
1818 import java.util.concurrent.*;
1919 import java.util.concurrent.atomic.AtomicReference;
2020
21-import com.google.common.util.concurrent.Uninterruptibles;
22-
2321 import com.google.common.util.concurrent.AbstractFuture;
2422 import org.slf4j.Logger;
2523 import org.slf4j.LoggerFactory;
@@ -40,12 +38,19 @@
4038
4139 private final HandlerFuture handlerFuture = new HandlerFuture();
4240
41+ private final long initialDelayMs;
42+
4343 private volatile boolean isActive;
4444
4545 public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<Future<?>> currentAttempt) {
46+ this(executor, schedule, currentAttempt, -1);
47+ }
48+
49+ public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<Future<?>> currentAttempt, long initialDelayMs) {
4650 this.executor = executor;
4751 this.schedule = schedule;
4852 this.currentAttempt = currentAttempt;
53+ this.initialDelayMs = initialDelayMs;
4954 }
5055
5156 protected abstract Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException;
@@ -60,7 +65,7 @@
6065 protected boolean onClusterNameMismatchException(ClusterNameMismatchException e, long nextDelayMs) { return false; }
6166
6267 public void start() {
63- long firstDelay = schedule.nextDelayMs();
68+ long firstDelay = (initialDelayMs >= 0) ? initialDelayMs : schedule.nextDelayMs();
6469 logger.debug("First reconnection scheduled in {}ms", firstDelay);
6570 try {
6671 handlerFuture.nextTry = executor.schedule(this, firstDelay, TimeUnit.MILLISECONDS);
@@ -91,9 +96,16 @@
9196 return;
9297 }
9398
94- // Just make sure we don't start the first try too fast, in case we find out we need to cancel ourselves in start()
95- while (!isActive)
96- Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS);
99+ // Just make sure we don't start the first try too fast, in case we find out in start() that we need to cancel ourselves
100+ while (!isActive && !Thread.currentThread().isInterrupted()) {
101+ try {
102+ TimeUnit.MILLISECONDS.sleep(5);
103+ } catch (InterruptedException e) {
104+ // This can happen at shutdown
105+ Thread.currentThread().interrupt();
106+ return;
107+ }
108+ }
97109
98110 try {
99111 onReconnection(tryReconnect());
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +59 −45
@@ -83,6 +83,12 @@
8383 // We don't have to be fancy here. We just set a flag so that we stop trying to reconnect (and thus change the
8484 // connection used) and shutdown the current one.
8585 isShutdown = true;
86+
87+ // Cancel any reconnection attempt in progress
88+ Future<?> r = reconnectionAttempt.get();
89+ if (r != null)
90+ r.cancel(false);
91+
8692 Connection connection = connectionRef.get();
8793 return connection == null ? CloseFuture.immediateFuture() : connection.closeAsync();
8894 }
@@ -100,37 +106,7 @@
100106 setNewConnection(reconnectInternal(queryPlan(), false));
101107 } catch (NoHostAvailableException e) {
102108 logger.error("[Control connection] Cannot connect to any host, scheduling retry");
103- new AbstractReconnectionHandler(cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt) {
104- @Override
105- protected Connection tryReconnect() throws ConnectionException {
106- try {
107- return reconnectInternal(queryPlan(), false);
108- } catch (NoHostAvailableException e) {
109- throw new ConnectionException(null, e.getMessage());
110- } catch (UnsupportedProtocolVersionException e) {
111- // reconnectInternal only propagate those if we've not decided on the protocol version yet,
112- // which should only happen on the initial connection and thus in connect() but never here.
113- throw new AssertionError();
114- }
115- }
116-
117- @Override
118- protected void onReconnection(Connection connection) {
119- setNewConnection(connection);
120- }
121-
122- @Override
123- protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
124- logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs);
125- return true;
126- }
127-
128- @Override
129- protected boolean onUnknownException(Exception e, long nextDelayMs) {
130- logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e);
131- return true;
132- }
133- }.start();
109+ backgroundReconnect(-1);
134110 } catch (UnsupportedProtocolVersionException e) {
135111 // reconnectInternal only propagate those if we've not decided on the protocol version yet,
136112 // which should only happen on the initial connection and thus in connect() but never here.
@@ -138,18 +114,60 @@
138114 }
139115 }
140116
117+ /**
118+ * @param initialDelayMs if >=0, bypass the schedule and use this for the first call
119+ */
120+ private void backgroundReconnect(long initialDelayMs) {
121+ if (isShutdown)
122+ return;
123+
124+ new AbstractReconnectionHandler(cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
125+ @Override
126+ protected Connection tryReconnect() throws ConnectionException {
127+ try {
128+ return reconnectInternal(queryPlan(), false);
129+ } catch (NoHostAvailableException e) {
130+ throw new ConnectionException(null, e.getMessage());
131+ } catch (UnsupportedProtocolVersionException e) {
132+ // reconnectInternal only propagate those if we've not decided on the protocol version yet,
133+ // which should only happen on the initial connection and thus in connect() but never here.
134+ throw new AssertionError();
135+ }
136+ }
137+
138+ @Override
139+ protected void onReconnection(Connection connection) {
140+ setNewConnection(connection);
141+ }
142+
143+ @Override
144+ protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
145+ logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs);
146+ return true;
147+ }
148+
149+ @Override
150+ protected boolean onUnknownException(Exception e, long nextDelayMs) {
151+ logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e);
152+ return true;
153+ }
154+ }.start();
155+ }
156+
141157 private Iterator<Host> queryPlan() {
142158 return cluster.loadBalancingPolicy().newQueryPlan(null, Statement.DEFAULT);
143159 }
144160
145161 private void signalError() {
146- // If the connection was marked as defunct, this already reported the
147- // node down, which will trigger a reconnect. Otherwise, just reconnect
148- // manually
149162 Connection connection = connectionRef.get();
150- if (connection == null || !connection.isDefunct()) {
151- reconnect();
163+ if (connection != null && connection.isDefunct()) {
164+ // If the connection was marked as defunct, this already reported the
165+ // node down, which will trigger a reconnect. Otherwise, just reconnect
166+ // manually
167+ return;
152168 }
169+ // If the connection is not defunct, or the host has left, just reconnect manually
170+ backgroundReconnect(0);
153171 }
154172
155173 private void setNewConnection(Connection newConnection) {
@@ -601,15 +619,11 @@
601619 Connection current = connectionRef.get();
602620 if (logger.isDebugEnabled())
603621 logger.debug("[Control connection] {} is down, currently connected to {}", host, current == null ? "nobody" : current.address);
604- if (current != null && current.address.equals(host.getSocketAddress()) && reconnectionAttempt.get() == null) {
605- // We might very be on an I/O thread when we reach this so we should not do that on this thread.
606- // Besides, there is no reason to block the onDown method while we try to reconnect.
607- cluster.blockingExecutor.submit(new Runnable() {
608- @Override
609- public void run() {
610- reconnect();
611- }
612- });
622+
623+ if (current != null && current.address.equals(host.getSocketAddress())) {
624+ // This starts an AbstractReconnectionHandler, which will take care of checking if another reconnection is
625+ // already in progress
626+ backgroundReconnect(0);
613627 }
614628 }
615629
added driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +109 −0
@@ -0,0 +1,109 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Collection;
4+import java.util.Iterator;
5+import java.util.concurrent.TimeUnit;
6+import java.util.concurrent.atomic.AtomicInteger;
7+
8+import org.testng.annotations.Test;
9+
10+import static org.assertj.core.api.Assertions.assertThat;
11+
12+import com.datastax.driver.core.policies.LoadBalancingPolicy;
13+import com.datastax.driver.core.policies.Policies;
14+import com.datastax.driver.core.policies.ReconnectionPolicy;
15+
16+public class ControlConnectionTest {
17+ @Test(groups = "short")
18+ public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException {
19+ CCMBridge ccm = null;
20+ Cluster cluster = null;
21+
22+ // Custom load balancing policy that counts the number of calls to newQueryPlan().
23+ // Since we don't open any session from our Cluster, only the control connection reattempts are calling this
24+ // method, therefore the invocation count is equal to the number of attempts.
25+ final AtomicInteger reconnectionAttempts = new AtomicInteger();
26+ LoadBalancingPolicy loadBalancingPolicy = new QueryPlanCountingPolicy(Policies.defaultLoadBalancingPolicy(),
27+ reconnectionAttempts);
28+
29+ // Custom reconnection policy with a very large delay (longer than the test duration), to make sure we count
30+ // only the first reconnection attempt of each reconnection handler.
31+ ReconnectionPolicy reconnectionPolicy = new ReconnectionPolicy() {
32+ @Override
33+ public ReconnectionSchedule newSchedule() {
34+ return new ReconnectionSchedule() {
35+ @Override
36+ public long nextDelayMs() {
37+ return 60 * 1000;
38+ }
39+ };
40+ }
41+ };
42+
43+ try {
44+ ccm = CCMBridge.create("test", 1);
45+ cluster = Cluster.builder()
46+ .addContactPoint(CCMBridge.ipOfNode(1))
47+ .withReconnectionPolicy(reconnectionPolicy)
48+ .withLoadBalancingPolicy(loadBalancingPolicy)
49+ .build();
50+ cluster.init();
51+
52+ ccm.stop(1);
53+
54+ // Sleep for a while to make sure our final count is not the result of lucky timing
55+ TimeUnit.SECONDS.sleep(1);
56+
57+ } finally {
58+ if (cluster != null)
59+ cluster.close();
60+ if (ccm != null)
61+ ccm.remove();
62+ }
63+ assertThat(reconnectionAttempts.get()).isEqualTo(1);
64+ }
65+
66+ static class QueryPlanCountingPolicy implements LoadBalancingPolicy {
67+
68+ private final LoadBalancingPolicy childPolicy;
69+ private final AtomicInteger counter;
70+
71+ public QueryPlanCountingPolicy(LoadBalancingPolicy childPolicy, AtomicInteger counter) {
72+ this.childPolicy = childPolicy;
73+ this.counter = counter;
74+ }
75+
76+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
77+ counter.incrementAndGet();
78+ return childPolicy.newQueryPlan(loggedKeyspace, statement);
79+ }
80+
81+ public void init(Cluster cluster, Collection<Host> hosts) {
82+ childPolicy.init(cluster, hosts);
83+ }
84+
85+ public HostDistance distance(Host host) {
86+ return childPolicy.distance(host);
87+ }
88+
89+ public void onAdd(Host host) {
90+ childPolicy.onAdd(host);
91+ }
92+
93+ public void onUp(Host host) {
94+ childPolicy.onUp(host);
95+ }
96+
97+ public void onSuspected(Host host) {
98+ childPolicy.onSuspected(host);
99+ }
100+
101+ public void onDown(Host host) {
102+ childPolicy.onDown(host);
103+ }
104+
105+ public void onRemove(Host host) {
106+ childPolicy.onRemove(host);
107+ }
108+ }
109+}