Elffuss BraidHub

kikocis/java-driver public

Expose an API to cancel reconnection attempts (JAVA-493).
Changesetee2c87da056a36114f2cb037a3dee01e3fca8b2843c90423bf4c8839212bf928
Authorolim7t <omichallat+github@gmail.com> · 2014-10-13 11:10 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-15 17:40 +02:00
Parents85b9ff98a743

Browse the files at this changeset

8 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -13,6 +13,7 @@
1313 - [improvement] Keep trying to reconnect on authentication errors (JAVA-472)
1414 - [improvement] Expose close method on load balancing policy (JAVA-463)
1515 - [improvement] Allow load balancing policy to trigger refresh for a single host (JAVA-459)
16+- [bug] Expose an API to cancel reconnection attempts (JAVA-493)
1617
1718
1819 2.0.6:
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +1 −0
@@ -97,6 +97,7 @@
9797 public void run() {
9898 if (handlerFuture.isCancelled()) {
9999 logger.debug("Got cancelled, stopping");
100+ currentAttempt.compareAndSet(handlerFuture, null);
100101 return;
101102 }
102103
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +60 −1
@@ -24,6 +24,7 @@
2424 import java.util.concurrent.atomic.AtomicInteger;
2525 import java.util.concurrent.atomic.AtomicReference;
2626
27+import com.google.common.annotations.VisibleForTesting;
2728 import com.google.common.base.Predicates;
2829 import com.google.common.collect.HashMultimap;
2930 import com.google.common.collect.Iterables;
@@ -63,7 +64,8 @@
6364
6465 private static final Logger logger = LoggerFactory.getLogger(Cluster.class);
6566
66- private static final int NEW_NODE_DELAY_SECONDS = SystemProperties.getInt("com.datastax.driver.NEW_NODE_DELAY_SECONDS", 1);
67+ @VisibleForTesting
68+ static final int NEW_NODE_DELAY_SECONDS = SystemProperties.getInt("com.datastax.driver.NEW_NODE_DELAY_SECONDS", 1);
6769 private static final int NON_BLOCKING_EXECUTOR_SIZE = SystemProperties.getInt("com.datastax.driver.NON_BLOCKING_EXECUTOR_SIZE",
6870 Runtime.getRuntime().availableProcessors());
6971
@@ -1544,6 +1546,63 @@
15441546 return true;
15451547 }
15461548
1549+ protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) {
1550+ logger.error(String.format("Authentication error during reconnection to %s, scheduling retry in %d milliseconds", host, nextDelayMs), e);
1551+ return true;
1552+ }
1553+
1554+ }.start();
1555+ }
1556+
1557+ public void tryReconnectOnce(final Host host) {
1558+ if (isClosed() || host.isUp())
1559+ return;
1560+
1561+ logger.debug("Scheduling one-time reconnection to {}", host);
1562+
1563+ // Setting an initial delay of 0 to start immediately, and all the exception handlers return false to prevent further attempts
1564+ new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) {
1565+
1566+ protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
1567+ return connectionFactory.open(host);
1568+ }
1569+
1570+ protected void onReconnection(Connection connection) {
1571+ // We don't use that first connection so close it.
1572+ // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1573+ // we use it for the first HostConnectionPool created
1574+ connection.closeAsync();
1575+ // Make sure we have up-to-date infos on that host before adding it (so we typically
1576+ // catch that an upgraded node uses a new cassandra version).
1577+ if (controlConnection.refreshNodeInfo(host)) {
1578+ logger.debug("Successful reconnection to {}, setting host UP", host);
1579+ try {
1580+ onUp(host);
1581+ } catch (InterruptedException e) {
1582+ Thread.currentThread().interrupt();
1583+ } catch (Exception e) {
1584+ logger.error("Unexpected error while setting node up", e);
1585+ }
1586+ } else {
1587+ logger.debug("Not enough info for {}, ignoring host", host);
1588+ }
1589+ }
1590+
1591+ protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
1592+ if (logger.isDebugEnabled())
1593+ logger.debug("Failed one-time reconnection to {} ({})", host, e.getMessage());
1594+ return false;
1595+ }
1596+
1597+ protected boolean onUnknownException(Exception e, long nextDelayMs) {
1598+ logger.error(String.format("Unknown error during one-time reconnection to %s", host), e);
1599+ return false;
1600+ }
1601+
1602+ protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) {
1603+ logger.error(String.format("Authentication error during one-time reconnection to %s", host), e);
1604+ return false;
1605+ }
15471606 }.start();
15481607 }
15491608
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +42 −1
@@ -41,6 +41,7 @@
4141 volatile State state;
4242
4343 private final ConvictionPolicy policy;
44+ private final Cluster.Manager manager;
4445
4546 // Tracks the first "immediate" reconnection attempt when a node get suspected.
4647 final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null));
@@ -63,12 +64,13 @@
6364 // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely,
6465 // we rely on the fact that we can use Object equality as a valid equality), so don't use
6566 // that constructor but ClusterMetadata.getHost instead.
66- Host(InetSocketAddress address, ConvictionPolicy.Factory policy) {
67+ Host(InetSocketAddress address, ConvictionPolicy.Factory policy, Cluster.Manager manager) {
6768 if (address == null || policy == null)
6869 throw new NullPointerException();
6970
7071 this.address = address;
7172 this.policy = policy.create(this);
73+ this.manager = manager;
7274 this.defaultExecutionInfo = new ExecutionInfo(ImmutableList.of(this));
7375 this.state = State.ADDED;
7476 }
@@ -170,10 +172,49 @@
170172 return state == State.UP || state == State.SUSPECT;
171173 }
172174
175+ /**
176+ * Returns a {@code ListenableFuture} representing the completion of the first
177+ * reconnection attempt after a node has been suspected.
178+ * <p>
179+ * This is useful in load balancing policies when there are no more live nodes and
180+ * we are trying suspected nodes.
181+ *
182+ * @return the future.
183+ */
173184 public ListenableFuture<?> getInitialReconnectionAttemptFuture() {
174185 return initialReconnectionAttempt.get();
175186 }
176187
188+ /**
189+ * Returns a {@code ListenableFuture} representing the completion of the reconnection
190+ * attempts scheduled after a host is marked {@code DOWN}.
191+ * <p>
192+ * <b>If the caller cancels this future,</b> the driver will not try to reconnect to
193+ * this host until it receives an UP event for it. Note that this could mean never, if
194+ * the node was marked down because of a driver-side error (e.g. read timeout) but no
195+ * failure was detected by Cassandra. The caller might decide to trigger an explicit
196+ * reconnection attempt at a later point with {@link #tryReconnectOnce()}.
197+ *
198+ * @return the future, or {@code null} if no reconnection attempt was in progress.
199+ */
200+ public ListenableFuture<?> getReconnectionAttemptFuture() {
201+ return reconnectionAttempt.get();
202+ }
203+
204+ /**
205+ * Triggers an asynchronous one-time reconnection attempt to this host.
206+ * <p>
207+ * If reconnection succeeds, the host will be marked {@code UP} and its connection pool(s)
208+ * will be initialized (unless the load balancing policy returns {@link HostDistance#IGNORED}
209+ * for it). If reconnection fails, no further attempts will be scheduled.
210+ * <p>
211+ * This method has no effect if the node is already {@code UP}, or if a reconnection attempt
212+ * is already in progress.
213+ */
214+ public void tryReconnectOnce() {
215+ this.manager.tryReconnectOnce(this);
216+ }
217+
177218 @Override
178219 public boolean equals(Object other) {
179220 if (other instanceof Host) {
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +1 −1
@@ -171,7 +171,7 @@
171171 }
172172
173173 Host add(InetSocketAddress address) {
174- Host newHost = new Host(address, cluster.convictionPolicyFactory);
174+ Host newHost = new Host(address, cluster.convictionPolicyFactory, cluster);
175175 Host previous = hosts.putIfAbsent(address, newHost);
176176 return previous == null ? newHost : null;
177177 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +1 −1
@@ -39,7 +39,7 @@
3939 private final String address;
4040
4141 private HostMock(String address) throws UnknownHostException {
42- super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory());
42+ super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory(), null);
4343 this.address = address;
4444 }
4545
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +85 −2
@@ -1,11 +1,16 @@
11 package com.datastax.driver.core;
22
3+import java.util.concurrent.TimeUnit;
4+import java.util.concurrent.atomic.AtomicBoolean;
5+
6+import static org.assertj.core.api.Assertions.fail;
7+import org.assertj.core.api.AbstractAssert;
38 import static org.assertj.core.api.Assertions.assertThat;
49
10+import com.datastax.driver.core.Host.State;
11+import com.datastax.driver.core.Host.StateListener;
512 import com.datastax.driver.core.policies.LoadBalancingPolicy;
613
7-import org.assertj.core.api.AbstractAssert;
8-
914 public class HostAssert extends AbstractAssert<HostAssert, Host> {
1015
1116 private final Cluster cluster;
@@ -25,4 +30,82 @@
2530 assertThat(loadBalancingPolicy.distance(actual)).isEqualTo(expected);
2631 return this;
2732 }
33+
34+ public HostAssert comesUpWithin(long duration, TimeUnit unit) {
35+ final AtomicBoolean notification = new AtomicBoolean();
36+ StateListener upListener = new StateListenerBase() {
37+ public void onUp(Host host) {
38+ notification.set(true);
39+ };
40+ };
41+ cluster.register(upListener);
42+ try {
43+ // Make sure the host did not come up while we were installing the listener
44+ if (actual.isUp())
45+ return this;
46+
47+ long maxTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(duration, unit);
48+ do {
49+ TimeUnit.SECONDS.sleep(10);
50+ if (notification.get())
51+ return this;
52+ } while (System.nanoTime() < maxTime);
53+ } catch (InterruptedException e) {
54+ fail("Got interrupted while waiting for host to come up");
55+ } finally {
56+ cluster.unregister(upListener);
57+ }
58+ fail(actual + " did not come up within " + duration + " " + unit);
59+ return this;
60+ }
61+
62+ public HostAssert goesDownWithin(long duration, TimeUnit unit) {
63+ final AtomicBoolean notification = new AtomicBoolean();
64+ StateListener upListener = new StateListenerBase() {
65+ public void onDown(Host host) {
66+ notification.set(true);
67+ };
68+ };
69+ cluster.register(upListener);
70+ try {
71+ // Make sure the host did not go down while we were installing the listener
72+ if (actual.state == State.DOWN)
73+ return this;
74+
75+ long maxTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(duration, unit);
76+ do {
77+ TimeUnit.SECONDS.sleep(10);
78+ if (notification.get())
79+ return this;
80+ } while (System.nanoTime() < maxTime);
81+ } catch (InterruptedException e) {
82+ fail("Got interrupted while waiting for host to go down");
83+ } finally {
84+ cluster.unregister(upListener);
85+ }
86+ fail(actual + " did not go down within " + duration + " " + unit);
87+ return this;
88+ }
89+
90+ public static class StateListenerBase implements StateListener {
91+ @Override
92+ public void onAdd(Host host) {
93+ }
94+
95+ @Override
96+ public void onUp(Host host) {
97+ }
98+
99+ @Override
100+ public void onSuspected(Host host) {
101+ }
102+
103+ @Override
104+ public void onDown(Host host) {
105+ }
106+
107+ @Override
108+ public void onRemove(Host host) {
109+ }
110+ }
28111 }
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +139 −14
@@ -1,18 +1,22 @@
11 package com.datastax.driver.core;
22
3+import java.io.IOException;
34 import java.net.InetSocketAddress;
5+import java.util.Collections;
6+import java.util.Iterator;
47 import java.util.Map;
58 import java.util.concurrent.TimeUnit;
69 import java.util.concurrent.atomic.AtomicInteger;
710
11+import static java.util.concurrent.TimeUnit.SECONDS;
12+
813 import com.google.common.base.Charsets;
914 import com.google.common.collect.ImmutableMap;
1015 import org.testng.annotations.Test;
11-
1216 import static org.assertj.core.api.Assertions.assertThat;
1317
14-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
15-import com.datastax.driver.core.policies.ReconnectionPolicy;
18+import com.datastax.driver.core.Host.State;
19+import com.datastax.driver.core.policies.*;
1620
1721 import static com.datastax.driver.core.Assertions.assertThat;
1822
@@ -21,15 +25,16 @@
2125 */
2226 public class ReconnectionTest {
2327
24- @Test(groups = "short")
25- public void should_reconnect_after_full_connectivity_lost() {
28+ @Test(groups = "long")
29+ public void should_reconnect_after_full_connectivity_loss() throws InterruptedException {
2630 CCMBridge ccm = null;
2731 Cluster cluster = null;
2832 try {
2933 ccm = CCMBridge.create("test", 2);
34+ int reconnectionDelay = 1000;
3035 cluster = Cluster.builder()
3136 .addContactPoint(CCMBridge.ipOfNode(1))
32- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
37+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
3338 .build();
3439 cluster.connect();
3540
@@ -44,7 +49,10 @@
4449 ccm.start(2);
4550 ccm.waitForUp(2);
4651
47- TestUtils.waitFor(CCMBridge.ipOfNode(2), cluster);
52+ assertThat(cluster).host(2).comesUpWithin(120, SECONDS);
53+
54+ // Give the control connection a few moments to reconnect
55+ TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2);
4856 assertThat(cluster).usesControlHost(2);
4957 } finally {
5058 if (cluster != null)
@@ -54,7 +62,7 @@
5462 }
5563 }
5664
57- @Test(groups = "short")
65+ @Test(groups = "long")
5866 public void should_keep_reconnecting_on_authentication_error() throws InterruptedException {
5967 CCMBridge ccm = null;
6068 Cluster cluster = null;
@@ -70,11 +78,11 @@
7078 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
7179
7280 cluster = Cluster.builder()
73- .addContactPoint(CCMBridge.ipOfNode(1))
74- // Start with the correct auth so that we can initialize the server
75- .withAuthProvider(authProvider)
76- .withReconnectionPolicy(reconnectionPolicy)
77- .build();
81+ .addContactPoint(CCMBridge.ipOfNode(1))
82+ // Start with the correct auth so that we can initialize the server
83+ .withAuthProvider(authProvider)
84+ .withReconnectionPolicy(reconnectionPolicy)
85+ .build();
7886
7987 cluster.init();
8088 assertThat(cluster).usesControlHost(1);
@@ -100,7 +108,104 @@
100108 authProvider.password = "cassandra";
101109
102110 // The driver should eventually reconnect to the node
103- TestUtils.waitFor(CCMBridge.ipOfNode(1), cluster);
111+ assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
112+ } finally {
113+ if (cluster != null)
114+ cluster.close();
115+ if (ccm != null)
116+ ccm.remove();
117+ }
118+ }
119+
120+ @Test(groups = "long")
121+ public void should_cancel_reconnection_attempts() throws InterruptedException {
122+ CCMBridge ccm = null;
123+ Cluster cluster = null;
124+
125+ long reconnectionDelayMillis = 1 * 1000;
126+ CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
127+
128+ try {
129+ ccm = CCMBridge.create("test", 2);
130+ cluster = Cluster.builder()
131+ .addContactPoint(CCMBridge.ipOfNode(1))
132+ .withReconnectionPolicy(reconnectionPolicy)
133+ .build();
134+ cluster.connect();
135+
136+ // Stop a node and cancel the reconnection attempts to it
137+ ccm.stop(2);
138+ Host host2 = TestUtils.findHost(cluster, 2);
139+ host2.getReconnectionAttemptFuture().cancel(false);
140+
141+ // The reconnection count should not vary over time anymore
142+ int initialCount = reconnectionPolicy.count.get();
143+ TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
144+ assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount);
145+
146+ // Restart the node, which will trigger an UP notification
147+ ccm.start(2);
148+ ccm.waitForUp(2);
149+
150+ // The driver should now see the node as UP again
151+ assertThat(cluster).host(2).comesUpWithin(120, SECONDS);
152+
153+ } finally {
154+ if (cluster != null)
155+ cluster.close();
156+ if (ccm != null)
157+ ccm.remove();
158+ }
159+ }
160+
161+ @Test(groups = "long")
162+ public void should_trigger_one_time_reconnect() throws InterruptedException, IOException {
163+ CCMBridge ccm = null;
164+ Cluster cluster = null;
165+
166+ long reconnectionDelayMillis = 1 * 1000;
167+ TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
168+
169+ try {
170+ ccm = CCMBridge.create("test", 1);
171+ cluster = Cluster.builder()
172+ .addContactPoint(CCMBridge.ipOfNode(1))
173+ .withLoadBalancingPolicy(loadBalancingPolicy)
174+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
175+ .build();
176+ cluster.connect();
177+
178+ // Tweak the LBP so that the control connection never reconnects, otherwise
179+ // it would interfere with the rest of the test (this is a bit of a hack)
180+ loadBalancingPolicy.returnEmptyQueryPlan = true;
181+
182+ // Stop the node and cancel the reconnection attempts to it
183+ ccm.stop(1);
184+ ccm.waitForDown(1);
185+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
186+ Host host1 = TestUtils.findHost(cluster, 1);
187+ host1.getReconnectionAttemptFuture().cancel(false);
188+
189+ // Trigger a one-time reconnection attempt (this will fail)
190+ host1.tryReconnectOnce();
191+
192+ // Wait for a few reconnection cycles before checking
193+ TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2);
194+ assertThat(cluster).host(1).hasState(State.DOWN);
195+
196+ // Restart the node (this will not trigger an UP notification thanks to our
197+ // hack to disable the control connection reconnects). The host should stay
198+ // down for the driver.
199+ ccm.start(1);
200+ ccm.waitForUp(1);
201+
202+ TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
203+ assertThat(cluster).host(1).hasState(State.DOWN);
204+
205+ // Trigger another one-time reconnection attempt (this will succeed). The
206+ // host should be back up.
207+ host1.tryReconnectOnce();
208+ assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
104209 } finally {
105210 if (cluster != null)
106211 cluster.close();
@@ -191,4 +296,24 @@
191296 }
192297 }
193298 }
299+
300+ /**
301+ * A load balancing policy that can be "disabled" by having its query plan return no hosts.
302+ */
303+ public static class TogglabePolicy extends DelegatingLoadBalancingPolicy {
304+
305+ volatile boolean returnEmptyQueryPlan;
306+
307+ public TogglabePolicy(LoadBalancingPolicy delegate) {
308+ super(delegate);
309+ }
310+
311+ @Override
312+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
313+ if (returnEmptyQueryPlan)
314+ return Collections.<Host>emptyList().iterator();
315+ else
316+ return super.newQueryPlan(loggedKeyspace, statement);
317+ }
318+ }
194319 }