Elffuss BraidHub

kikocis/java-driver public

Merge pull request #505 from datastax/java966

JAVA-966: Count uninitialized connections in conviction policy.
Changeset659a94ae9fceb4612a6e0a7a6aee3f81f35f96ee1e94b90b5a7121f2038060ea
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-11-04 20:56 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-11-04 20:56 +01:00
Parentscf1dd0d04822, c9a4a61b56a1

Browse the files at this changeset

7 files changed

modified changelog/README.md +1 −0
@@ -10,6 +10,7 @@
1010 - [bug] JAVA-901: Move call to connection.release() out of cancelHandler.
1111 - [bug] JAVA-960: Avoid race in control connection shutdown.
1212 - [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo.
13+- [bug] JAVA-966: Count uninitialized connections in conviction policy.
1314
1415
1516 ### 2.0.11
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +5 −4
@@ -2024,14 +2024,15 @@
20242024 }
20252025 }
20262026
2027- public boolean signalConnectionFailure(Host host, ConnectionException exception,
2028- boolean connectionInitialized, boolean isHostAddition) {
2029- // Don't signal failure until we've fully initialized the controlConnection as this might mess up with
2027+ public boolean signalConnectionFailure(Host host, Connection connection,
2028+ boolean isHostAddition) {
2029+ boolean isDown = host.convictionPolicy.signalConnectionFailure(connection);
2030+
2031+ // Don't mark the node down until we've fully initialized the controlConnection as this might mess up with
20302032 // the protocol detection
20312033 if (!isFullyInit || isClosed())
20322034 return true;
20332035
2034- boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized);
20352036 if (isDown)
20362037 triggerOnDown(host, isHostAddition, true);
20372038 return isDown;
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +53 −51
@@ -19,6 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.HashSet;
2121 import java.util.Iterator;
22+import java.util.List;
2223 import java.util.Queue;
2324 import java.util.concurrent.*;
2425 import java.util.concurrent.atomic.AtomicBoolean;
@@ -26,6 +27,7 @@
2627 import java.util.concurrent.atomic.AtomicReference;
2728
2829 import com.google.common.annotations.VisibleForTesting;
30+import com.google.common.collect.Lists;
2931 import com.google.common.collect.MapMaker;
3032 import com.google.common.util.concurrent.*;
3133 import io.netty.bootstrap.Bootstrap;
@@ -158,7 +160,7 @@
158160 logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause())));
159161 channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause()));
160162 } else {
161- logger.debug("{} Connection opened successfully", Connection.this);
163+ logger.debug("{} Connection established, initializing transport", Connection.this);
162164 channel.closeFuture().addListener(new ChannelCloseListener());
163165 channelReadyFuture.set(null);
164166 }
@@ -175,6 +177,7 @@
175177 ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
176178 onChannelReady(protocolVersion, initExecutor), initExecutor);
177179
180+
178181 // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
179182 ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() {
180183 @Override
@@ -198,16 +201,8 @@
198201 }
199202 }, initExecutor);
200203
201- // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel.
202- Futures.addCallback(initFuture, new FutureCallback<Void>() {
203- @Override
204- public void onSuccess(Void result) {
205- Host host = factory.manager.metadata.getHost(address);
206- if (host != null)
207- host.convictionPolicy.signalConnectionCreated();
208- isInitialized = true;
209- }
210-
204+ // Ensure the connection gets closed if the caller cancels the returned future.
205+ Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() {
211206 @Override
212207 public void onFailure(Throwable t) {
213208 if (!isClosed()) {
@@ -279,8 +274,10 @@
279274 final String expected = factory.manager.metadata.clusterName;
280275
281276 // At initialization, the cluster is not known yet
282- if (expected == null)
277+ if (expected == null) {
278+ markInitialized();
283279 return MoreFutures.VOID_SUCCESS;
280+ }
284281
285282 DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
286283 try {
@@ -293,6 +290,7 @@
293290 String actual = row.getString("cluster_name");
294291 if (!expected.equals(actual))
295292 throw new ClusterNameMismatchException(address, actual, expected);
293+ markInitialized();
296294 return MoreFutures.VOID_SUCCESS;
297295 }
298296 }, executor);
@@ -301,6 +299,11 @@
301299 }
302300 }
303301
302+ private void markInitialized() {
303+ isInitialized = true;
304+ Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", address, this);
305+ }
306+
304307 private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final Executor executor) {
305308 Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
306309 try {
@@ -390,33 +393,18 @@
390393 }
391394
392395 <E extends Exception> E defunct(E e) {
393- if (!isDefunct.compareAndSet(false, true))
394- return e;
395-
396- if (Host.statesLogger.isTraceEnabled())
397- Host.statesLogger.trace("Defuncting " + this, e);
398- else if (Host.statesLogger.isDebugEnabled())
399- Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
400-
401- ConnectionException ce = e instanceof ConnectionException
402- ? (ConnectionException)e
403- : new ConnectionException(address, "Connection problem", e);
404-
405- Host host = factory.manager.metadata.getHost(address);
406- if (host != null) {
407- boolean isDown = factory.manager.signalConnectionFailure(host, ce, isInitialized, host.wasJustAdded());
408-
409- if (!isDown)
410- notifyOwnerWhenDefunct();
411- // else the driver will destroy all pools and notify the control connection as part of marking the host down,
412- // so no need to notify
396+ if (isDefunct.compareAndSet(false, true)) {
397+
398+ if (Host.statesLogger.isTraceEnabled())
399+ Host.statesLogger.trace("Defuncting " + this, e);
400+ else if (Host.statesLogger.isDebugEnabled())
401+ Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
402+
403+ // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
404+ // threads will wait on the future forever.
405+ // (this also errors out pending handlers)
406+ closeAsync().force();
413407 }
414-
415- // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
416- // threads will wait on the future forever.
417- // (this also errors out pending handlers)
418- closeAsync().force();
419-
420408 return e;
421409 }
422410
@@ -625,10 +613,18 @@
625613
626614 logger.debug("{} closing connection", this);
627615
628- if (isInitialized && !isDefunct.get()) {
629- Host host = factory.manager.metadata.getHost(address);
630- if(host != null)
631- host.convictionPolicy.signalConnectionClosed();
616+ Host host = factory.manager.metadata.getHost(address);
617+ if (host != null) {
618+ if (isDefunct.get()) {
619+ boolean isDown = factory.manager.signalConnectionFailure(host, this, host.wasJustAdded());
620+
621+ if (!isDown)
622+ notifyOwnerWhenDefunct();
623+ // else the driver will destroy all pools and notify the control connection as part of marking the host down,
624+ // so no need to notify
625+ } else {
626+ host.convictionPolicy.signalConnectionClosed(this);
627+ }
632628 }
633629
634630 boolean terminated = tryTerminate(false);
@@ -728,8 +724,8 @@
728724 if (isShutdown)
729725 throw new ConnectionException(address, "Connection factory is shut down");
730726
731- String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement();
732- Connection connection = new Connection(name, address, this);
727+ host.convictionPolicy.signalConnectionsOpening(1);
728+ Connection connection = new Connection(buildConnectionName(host), address, this);
733729 // This method opens the connection synchronously, so wait until it's initialized
734730 try {
735731 connection.initAsync().get();
@@ -743,8 +739,9 @@
743739 * Same as open, but associate the created connection to the provided connection pool.
744740 */
745741 public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
742+ pool.host.convictionPolicy.signalConnectionsOpening(1);
743+ Connection connection = new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool);
746744 try {
747- Connection connection = newConnection(pool);
748745 connection.initAsync().get();
749746 return connection;
750747 } catch (ExecutionException e) {
@@ -753,13 +750,18 @@
753750 }
754751
755752 /**
756- * Creates a new connection and associates it to the provided connection pool, but does not start it.
753+ * Creates new connections and associate them to the provided connection pool, but does not start them.
757754 */
758- public Connection newConnection(HostConnectionPool pool) {
759- InetSocketAddress address = pool.host.getSocketAddress();
760- String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
761-
762- return new Connection(name, address, this, pool);
755+ public List<Connection> newConnections(HostConnectionPool pool, int count) {
756+ pool.host.convictionPolicy.signalConnectionsOpening(count);
757+ List<Connection> connections = Lists.newArrayListWithCapacity(count);
758+ for (int i = 0; i < count; i++)
759+ connections.add(new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool));
760+ return connections;
761+ }
762+
763+ private String buildConnectionName(Host host) {
764+ return host.getSocketAddress().toString() + '-' + getIdGenerator(host).getAndIncrement();
763765 }
764766
765767 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +16 −33
@@ -33,31 +33,26 @@
3333 abstract class ConvictionPolicy {
3434
3535 /**
36- * Called when a new connection to the host has been successfully opened.
36+ * Called when new connections to the host are about to be created.
37+ *
38+ * @param count the number of connections
3739 */
38- abstract void signalConnectionCreated();
40+ abstract void signalConnectionsOpening(int count);
3941
4042 /**
4143 * Called when a connection closed normally.
4244 */
43- abstract void signalConnectionClosed();
45+ abstract void signalConnectionClosed(Connection connection);
4446
4547 /**
4648 * Called when a connection error occurs on a connection to the host this policy applies to.
4749 *
48- * @param exception the connection error that occurred.
49- * @param connectionInitialized whether the connection was initialized.
5050 * @return whether the host should be considered down.
5151 */
52- abstract boolean signalConnectionFailure(ConnectionException exception, boolean connectionInitialized);
52+ abstract boolean signalConnectionFailure(Connection connection);
5353
5454 abstract boolean canReconnectNow();
5555
56- /**
57- * Called when the host goes down.
58- */
59- abstract void reset();
60-
6156 /**
6257 * Simple factory interface to allow creating {@link ConvictionPolicy} instances.
6358 */
@@ -86,33 +81,27 @@
8681 }
8782
8883 @Override
89- void signalConnectionCreated() {
90- int newCount = openConnections.incrementAndGet();
91- Host.statesLogger.debug("[{}] new connection created, total = {}", host, newCount);
84+ void signalConnectionsOpening(int count) {
85+ int newTotal = openConnections.addAndGet(count);
86+ Host.statesLogger.debug("[{}] preparing to open {} new connections, total = {}", host, count, newTotal);
9287 resetReconnectionTime();
9388 }
9489
9590 @Override
96- void signalConnectionClosed() {
97- if (host.state == Host.State.DOWN)
98- return;
91+ void signalConnectionClosed(Connection connection) {
9992 int remaining = openConnections.decrementAndGet();
10093 assert remaining >= 0;
101- Host.statesLogger.debug("[{}] connection closed, remaining = {}", host, remaining);
94+ Host.statesLogger.debug("[{}] {} closed, remaining = {}", host, connection, remaining);
10295 }
10396
10497 @Override
105- boolean signalConnectionFailure(ConnectionException exception, boolean wasFullyInitialized) {
106- if (host.state == Host.State.DOWN)
107- return false;
108-
109- updateReconnectionTime();
110- int remaining = (wasFullyInitialized)
111- ? openConnections.decrementAndGet()
112- : openConnections.get();
98+ boolean signalConnectionFailure(Connection connection) {
99+ if (host.state != Host.State.DOWN)
100+ updateReconnectionTime();
113101
102+ int remaining = openConnections.decrementAndGet();
114103 assert remaining >= 0;
115- Host.statesLogger.debug("[{}] remaining connections = {}", host, remaining);
104+ Host.statesLogger.debug("[{}] {} failed, remaining = {}", host, connection, remaining);
116105 return remaining == 0;
117106 }
118107
@@ -141,12 +130,6 @@
141130 System.nanoTime() >= nextReconnectionTime;
142131 }
143132
144- @Override
145- synchronized void reset() {
146- openConnections.set(0);
147- resetReconnectionTime();
148- }
149-
150133 static class Factory implements ConvictionPolicy.Factory {
151134
152135 @Override
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +0 −1
@@ -275,7 +275,6 @@
275275
276276 void setDown() {
277277 state = State.DOWN;
278- convictionPolicy.reset();
279278 }
280279
281280 void setUp() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +13 −13
@@ -106,19 +106,19 @@
106106 final int coreSize = options().getCoreConnectionsPerHost(hostDistance);
107107 final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize);
108108 final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(coreSize);
109- for (int i = 0; i < coreSize; i++) {
110- Connection connection;
111- ListenableFuture<Void> connectionFuture;
112- // reuse the existing connection only once
113- if (reusedConnection != null && reusedConnection.setOwner(this)) {
114- connection = reusedConnection;
115- connectionFuture = MoreFutures.VOID_SUCCESS;
116- } else {
117- connection = manager.connectionFactory().newConnection(this);
118- connectionFuture = connection.initAsync();
119- }
120- reusedConnection = null;
121- connections.add(connection);
109+
110+ int toCreate = coreSize;
111+
112+ if (reusedConnection != null && reusedConnection.setOwner(this)) {
113+ toCreate -= 1;
114+ connections.add(reusedConnection);
115+ connectionFutures.add(MoreFutures.VOID_SUCCESS);
116+ }
117+
118+ List<Connection> newConnections = manager.connectionFactory().newConnections(this, toCreate);
119+ connections.addAll(newConnections);
120+ for (Connection connection : newConnections) {
121+ ListenableFuture<Void> connectionFuture = connection.initAsync();
122122 connectionFutures.add(handleErrors(connectionFuture, initExecutor));
123123 }
124124
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +1 −1
@@ -530,7 +530,7 @@
530530 // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
531531 verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
532532 // 7 attempts for core connections after first initial connection.
533- verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class));
533+ verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7));
534534
535535 // Wait some reasonable amount of time for connection to reestablish.
536536 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);