kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 0e7ff2256dc1d0fa02a5adf3dd8408b2ac787df827db83d13981eb4842e8f5d5 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-04-03 18:02 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-04-17 20:19 +02:00 |
| Parents | a5bd5b316c2f |
11 files changed
modified driver-core/CHANGELOG.rst +1 −0
| @@ -38,6 +38,7 @@ | ||
| 38 | 38 | (JAVA-619) |
| 39 | 39 | - [new feature] Expose an API to check for schema agreement after a |
| 40 | 40 | schema-altering statement (JAVA-669) |
| 41 | +- [improvement] Make connection and pool creation fully async (JAVA-692) | |
| 41 | 42 | |
| 42 | 43 | Merged from 2.0.9_fixes branch: |
| 43 | 44 |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +3 −3
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | import java.util.concurrent.ExecutionException; |
| 22 | 22 | import java.util.concurrent.LinkedBlockingDeque; |
| 23 | 23 | |
| 24 | -import com.google.common.util.concurrent.Futures; | |
| 25 | 24 | import com.google.common.util.concurrent.ListenableFuture; |
| 26 | 25 | import com.google.common.util.concurrent.SettableFuture; |
| 27 | 26 | import com.google.common.util.concurrent.Uninterruptibles; |
| @@ -29,6 +28,7 @@ | ||
| 29 | 28 | import org.slf4j.LoggerFactory; |
| 30 | 29 | |
| 31 | 30 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 31 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 32 | 32 | |
| 33 | 33 | /** |
| 34 | 34 | * Default implementation of a result set, backed by an ArrayDeque of ArrayList. |
| @@ -178,7 +178,7 @@ | ||
| 178 | 178 | } |
| 179 | 179 | |
| 180 | 180 | public ListenableFuture<Void> fetchMoreResults() { |
| 181 | - return Futures.immediateFuture(null); | |
| 181 | + return MoreFutures.VOID_SUCCESS; | |
| 182 | 182 | } |
| 183 | 183 | |
| 184 | 184 | public ExecutionInfo getExecutionInfo() { |
| @@ -287,7 +287,7 @@ | ||
| 287 | 287 | |
| 288 | 288 | private ListenableFuture<Void> fetchMoreResults(FetchingState fetchState) { |
| 289 | 289 | if (fetchState == null) |
| 290 | - return Futures.immediateFuture(null); | |
| 290 | + return MoreFutures.VOID_SUCCESS; | |
| 291 | 291 | |
| 292 | 292 | if (fetchState.inProgress != null) |
| 293 | 293 | return fetchState.inProgress; |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +52 −66
| @@ -1409,16 +1409,8 @@ | ||
| 1409 | 1409 | }); |
| 1410 | 1410 | } |
| 1411 | 1411 | |
| 1412 | - private void onUp(final Host host) throws InterruptedException, ExecutionException { | |
| 1413 | - // Note that in generalize we can parallelize the pool creation on | |
| 1414 | - // each session, but we shouldn't use executor since we're already | |
| 1415 | - // running on it most probably (and so we could deadlock). Use the | |
| 1416 | - // blockingExecutor instead, that's why it's for. | |
| 1417 | - onUp(host, blockingExecutor); | |
| 1418 | - } | |
| 1419 | - | |
| 1420 | 1412 | // Use triggerOnUp unless you're sure you want to run this on the current thread. |
| 1421 | - private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException { | |
| 1413 | + private void onUp(final Host host) throws InterruptedException, ExecutionException { | |
| 1422 | 1414 | logger.debug("Host {} is UP", host); |
| 1423 | 1415 | |
| 1424 | 1416 | if (isClosed()) |
| @@ -1472,42 +1464,39 @@ | ||
| 1472 | 1464 | |
| 1473 | 1465 | logger.trace("Adding/renewing host pools for newly UP host {}", host); |
| 1474 | 1466 | |
| 1475 | - List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size()); | |
| 1467 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1476 | 1468 | for (SessionManager s : sessions) |
| 1477 | - futures.add(s.forceRenewPool(host, poolCreationExecutor)); | |
| 1478 | - | |
| 1479 | - // Only mark the node up once all session have re-added their pool (if the load-balancing | |
| 1480 | - // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1481 | - // to the node. | |
| 1482 | - ListenableFuture<List<Boolean>> f = Futures.allAsList(futures); | |
| 1483 | - Futures.addCallback(f, new FutureCallback<List<Boolean>>() { | |
| 1484 | - public void onSuccess(List<Boolean> poolCreationResults) { | |
| 1485 | - // If any of the creation failed, they will have signaled a connection failure | |
| 1486 | - // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1487 | - if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1488 | - logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 1489 | - return; | |
| 1490 | - } | |
| 1469 | + futures.add(s.forceRenewPool(host)); | |
| 1491 | 1470 | |
| 1492 | - host.setUp(); | |
| 1493 | - | |
| 1494 | - for (Host.StateListener listener : listeners) | |
| 1495 | - listener.onUp(host); | |
| 1471 | + try { | |
| 1472 | + // Only mark the node up once all session have re-added their pool (if the load-balancing | |
| 1473 | + // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1474 | + // to the node. | |
| 1475 | + List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); | |
| 1476 | + | |
| 1477 | + // If any of the creation failed, they will have signaled a connection failure | |
| 1478 | + // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1479 | + if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1480 | + logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 1481 | + return; | |
| 1496 | 1482 | } |
| 1497 | 1483 | |
| 1498 | - public void onFailure(Throwable t) { | |
| 1499 | - // That future is not really supposed to throw unexpected exceptions | |
| 1500 | - if (!(t instanceof InterruptedException)) | |
| 1501 | - logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t); | |
| 1502 | - } | |
| 1503 | - }); | |
| 1484 | + host.setUp(); | |
| 1504 | 1485 | |
| 1505 | - f.get(); | |
| 1486 | + for (Host.StateListener listener : listeners) | |
| 1487 | + listener.onUp(host); | |
| 1488 | + | |
| 1489 | + } catch (ExecutionException e) { | |
| 1490 | + Throwable t = e.getCause(); | |
| 1491 | + // That future is not really supposed to throw unexpected exceptions | |
| 1492 | + if (!(t instanceof InterruptedException)) | |
| 1493 | + logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t); | |
| 1494 | + } | |
| 1506 | 1495 | |
| 1507 | 1496 | // Now, check if there isn't pools to create/remove following the addition. |
| 1508 | 1497 | // We do that now only so that it's not called before we've set the node up. |
| 1509 | 1498 | for (SessionManager s : sessions) |
| 1510 | - s.updateCreatedPools(blockingExecutor); | |
| 1499 | + s.updateCreatedPools(); | |
| 1511 | 1500 | |
| 1512 | 1501 | } finally { |
| 1513 | 1502 | host.notificationsLock.unlock(); |
| @@ -1567,7 +1556,7 @@ | ||
| 1567 | 1556 | connectionFactory.open(host).closeAsync(); |
| 1568 | 1557 | // Note that we want to do the pool creation on this thread because we want that |
| 1569 | 1558 | // when onUp return, the host is ready for querying |
| 1570 | - onUp(host, MoreExecutors.sameThreadExecutor()); | |
| 1559 | + onUp(host); | |
| 1571 | 1560 | // If one of the connections in onUp failed, it signaled the error and triggerd onDown, |
| 1572 | 1561 | // but onDown aborted because this reconnection attempt was in progress (JAVA-577). |
| 1573 | 1562 | // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was |
| @@ -1819,42 +1808,39 @@ | ||
| 1819 | 1808 | |
| 1820 | 1809 | controlConnection.onAdd(host); |
| 1821 | 1810 | |
| 1822 | - List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size()); | |
| 1811 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1823 | 1812 | for (SessionManager s : sessions) |
| 1824 | - futures.add(s.maybeAddPool(host, blockingExecutor)); | |
| 1825 | - | |
| 1826 | - // Only mark the node up once all session have added their pool (if the load-balancing | |
| 1827 | - // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1828 | - // to the node. | |
| 1829 | - ListenableFuture<List<Boolean>> f = Futures.allAsList(futures); | |
| 1830 | - Futures.addCallback(f, new FutureCallback<List<Boolean>>() { | |
| 1831 | - public void onSuccess(List<Boolean> poolCreationResults) { | |
| 1832 | - // If any of the creation failed, they will have signaled a connection failure | |
| 1833 | - // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1834 | - if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1835 | - logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 1836 | - return; | |
| 1837 | - } | |
| 1813 | + futures.add(s.maybeAddPool(host)); | |
| 1838 | 1814 | |
| 1839 | - host.setUp(); | |
| 1840 | - | |
| 1841 | - for (Host.StateListener listener : listeners) | |
| 1842 | - listener.onAdd(host); | |
| 1815 | + try { | |
| 1816 | + // Only mark the node up once all session have added their pool (if the load-balancing | |
| 1817 | + // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1818 | + // to the node. | |
| 1819 | + List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); | |
| 1820 | + | |
| 1821 | + // If any of the creation failed, they will have signaled a connection failure | |
| 1822 | + // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1823 | + if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1824 | + logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 1825 | + return; | |
| 1843 | 1826 | } |
| 1844 | 1827 | |
| 1845 | - public void onFailure(Throwable t) { | |
| 1846 | - // That future is not really supposed to throw unexpected exceptions | |
| 1847 | - if (!(t instanceof InterruptedException)) | |
| 1848 | - logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t); | |
| 1849 | - } | |
| 1850 | - }); | |
| 1828 | + host.setUp(); | |
| 1829 | + | |
| 1830 | + for (Host.StateListener listener : listeners) | |
| 1831 | + listener.onAdd(host); | |
| 1851 | 1832 | |
| 1852 | - f.get(); | |
| 1833 | + } catch (ExecutionException e) { | |
| 1834 | + Throwable t = e.getCause(); | |
| 1835 | + // That future is not really supposed to throw unexpected exceptions | |
| 1836 | + if (!(t instanceof InterruptedException)) | |
| 1837 | + logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t); | |
| 1838 | + } | |
| 1853 | 1839 | |
| 1854 | 1840 | // Now, check if there isn't pools to create/remove following the addition. |
| 1855 | 1841 | // We do that now only so that it's not called before we've set the node up. |
| 1856 | 1842 | for (SessionManager s : sessions) |
| 1857 | - s.updateCreatedPools(blockingExecutor); | |
| 1843 | + s.updateCreatedPools(); | |
| 1858 | 1844 | |
| 1859 | 1845 | } finally { |
| 1860 | 1846 | host.notificationsLock.unlock(); |
| @@ -2221,7 +2207,7 @@ | ||
| 2221 | 2207 | controlConnection.reconnect(); |
| 2222 | 2208 | |
| 2223 | 2209 | for (SessionManager s : sessions) |
| 2224 | - s.updateCreatedPools(executor); | |
| 2210 | + s.updateCreatedPools(); | |
| 2225 | 2211 | } |
| 2226 | 2212 | |
| 2227 | 2213 | void refreshConnectedHost(Host host) { |
| @@ -2231,7 +2217,7 @@ | ||
| 2231 | 2217 | controlConnection.reconnect(); |
| 2232 | 2218 | |
| 2233 | 2219 | for (SessionManager s : sessions) |
| 2234 | - s.updateCreatedPools(host, executor); | |
| 2220 | + s.updateCreatedPools(host); | |
| 2235 | 2221 | } |
| 2236 | 2222 | |
| 2237 | 2223 | private class ClusterCloseFuture extends CloseFuture.Forwarding { |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +254 −139
| @@ -26,8 +26,7 @@ | ||
| 26 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 27 | |
| 28 | 28 | import com.google.common.collect.Lists; |
| 29 | -import com.google.common.util.concurrent.AbstractFuture; | |
| 30 | -import com.google.common.util.concurrent.Uninterruptibles; | |
| 29 | +import com.google.common.util.concurrent.*; | |
| 31 | 30 | import io.netty.bootstrap.Bootstrap; |
| 32 | 31 | import io.netty.channel.*; |
| 33 | 32 | import io.netty.channel.group.ChannelGroup; |
| @@ -47,7 +46,8 @@ | ||
| 47 | 46 | import static io.netty.handler.timeout.IdleState.ALL_IDLE; |
| 48 | 47 | |
| 49 | 48 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 50 | -import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 49 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 50 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 51 | 51 | |
| 52 | 52 | // For LoggingHandler |
| 53 | 53 | //import org.jboss.netty.handler.logging.LoggingHandler; |
| @@ -66,7 +66,7 @@ | ||
| 66 | 66 | public final InetSocketAddress address; |
| 67 | 67 | private final String name; |
| 68 | 68 | |
| 69 | - private final Channel channel; | |
| 69 | + private volatile Channel channel; | |
| 70 | 70 | private final Factory factory; |
| 71 | 71 | |
| 72 | 72 | private final Dispatcher dispatcher = new Dispatcher(); |
| @@ -86,19 +86,23 @@ | ||
| 86 | 86 | * Create a new connection to a Cassandra node. |
| 87 | 87 | * |
| 88 | 88 | * The connection is open and initialized by the constructor. |
| 89 | - * | |
| 90 | - * @throws ConnectionException if the connection attempts fails or is | |
| 91 | - * refused by the server. | |
| 92 | 89 | */ |
| 93 | - protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 90 | + protected Connection(String name, InetSocketAddress address, Factory factory) { | |
| 94 | 91 | this.address = address; |
| 95 | 92 | this.factory = factory; |
| 96 | 93 | this.name = name; |
| 94 | + } | |
| 95 | + | |
| 96 | + public ListenableFuture<Void> initAsync() { | |
| 97 | + if (factory.isShutdown) | |
| 98 | + return Futures.immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down")); | |
| 99 | + | |
| 100 | + int protocolVersion = factory.protocolVersion == 1 ? 1 : 2; | |
| 101 | + final SettableFuture<Void> channelReadyFuture = SettableFuture.create(); | |
| 97 | 102 | |
| 98 | 103 | try { |
| 99 | 104 | Bootstrap bootstrap = factory.newBootstrap(); |
| 100 | 105 | ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions(); |
| 101 | - int protocolVersion = factory.protocolVersion == 1 ? 1 : 2; | |
| 102 | 106 | bootstrap.handler( |
| 103 | 107 | new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(), |
| 104 | 108 | factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), |
| @@ -107,41 +111,81 @@ | ||
| 107 | 111 | ChannelFuture future = bootstrap.connect(address); |
| 108 | 112 | |
| 109 | 113 | writer.incrementAndGet(); |
| 110 | - try { | |
| 111 | - // Wait until the connection attempt succeeds or fails. | |
| 112 | - this.channel = future.awaitUninterruptibly().channel(); | |
| 113 | - this.factory.allChannels.add(this.channel); | |
| 114 | - if (!future.isSuccess()) { | |
| 115 | - if (logger.isDebugEnabled()) | |
| 116 | - logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.cause()))); | |
| 117 | - throw defunct(new TransportException(address, "Cannot connect", future.cause())); | |
| 114 | + future.addListener(new ChannelFutureListener() { | |
| 115 | + @Override | |
| 116 | + public void operationComplete(ChannelFuture future) throws Exception { | |
| 117 | + writer.decrementAndGet(); | |
| 118 | + channel = future.channel(); | |
| 119 | + if (isClosed()) { | |
| 120 | + channel.close().addListener(new ChannelFutureListener() { | |
| 121 | + @Override | |
| 122 | + public void operationComplete(ChannelFuture future) throws Exception { | |
| 123 | + channelReadyFuture.setException(new TransportException(Connection.this.address, "Connection closed during initialization.")); | |
| 124 | + } | |
| 125 | + }); | |
| 126 | + } else { | |
| 127 | + Connection.this.factory.allChannels.add(channel); | |
| 128 | + if (!future.isSuccess()) { | |
| 129 | + if (logger.isDebugEnabled()) | |
| 130 | + logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause()))); | |
| 131 | + channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause())); | |
| 132 | + } else { | |
| 133 | + logger.debug("{} Connection opened successfully", Connection.this); | |
| 134 | + channel.closeFuture().addListener(new ChannelCloseListener()); | |
| 135 | + channelReadyFuture.set(null); | |
| 136 | + } | |
| 137 | + } | |
| 118 | 138 | } |
| 119 | - channel.closeFuture().addListener(new ChannelCloseListener()); | |
| 120 | - } finally { | |
| 121 | - writer.decrementAndGet(); | |
| 122 | - } | |
| 123 | - | |
| 124 | - logger.trace("{} Connection opened successfully", this); | |
| 125 | - initializeTransport(protocolVersion, factory.manager.metadata.clusterName); | |
| 126 | - logger.debug("{} Transport initialized and ready", this); | |
| 127 | - isInitialized = true; | |
| 128 | - | |
| 129 | - } catch (ConnectionException e) { | |
| 130 | - closeAsync().force(); | |
| 131 | - throw e; | |
| 132 | - } catch (ClusterNameMismatchException e) { | |
| 133 | - closeAsync().force(); | |
| 134 | - throw e; | |
| 135 | - } catch (UnsupportedProtocolVersionException e) { | |
| 136 | - closeAsync().force(); | |
| 137 | - throw e; | |
| 138 | - } catch (InterruptedException e) { | |
| 139 | - closeAsync().force(); | |
| 140 | - throw e; | |
| 139 | + }); | |
| 141 | 140 | } catch (RuntimeException e) { |
| 142 | 141 | closeAsync().force(); |
| 143 | 142 | throw e; |
| 144 | 143 | } |
| 144 | + | |
| 145 | + Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 146 | + | |
| 147 | + ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture, | |
| 148 | + onChannelReady(protocolVersion, initExecutor), initExecutor); | |
| 149 | + | |
| 150 | + // Fallback on initializeTransportFuture so we can properly propagate specific exceptions. | |
| 151 | + ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() { | |
| 152 | + @Override | |
| 153 | + public ListenableFuture<Void> create(Throwable t) throws Exception { | |
| 154 | + SettableFuture<Void> future = SettableFuture.create(); | |
| 155 | + // Make sure the connection gets properly closed. | |
| 156 | + if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) { | |
| 157 | + // These exceptions cause the node to be ignored, so just propagate | |
| 158 | + closeAsync().force(); | |
| 159 | + future.setException(t); | |
| 160 | + } else { | |
| 161 | + // Defunct to ensure that the error will be signaled (marking the host down) | |
| 162 | + ConnectionException ce = (t instanceof ConnectionException) | |
| 163 | + ? (ConnectionException)t | |
| 164 | + : new ConnectionException(Connection.this.address, | |
| 165 | + String.format("Unexpected error during transport initialization (%s)", t), | |
| 166 | + t); | |
| 167 | + future.setException(defunct(ce)); | |
| 168 | + } | |
| 169 | + return future; | |
| 170 | + } | |
| 171 | + }, initExecutor); | |
| 172 | + | |
| 173 | + // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel. | |
| 174 | + Futures.addCallback(initFuture, new FutureCallback<Void>() { | |
| 175 | + @Override | |
| 176 | + public void onSuccess(Void result) { | |
| 177 | + isInitialized = true; | |
| 178 | + } | |
| 179 | + | |
| 180 | + @Override | |
| 181 | + public void onFailure(Throwable t) { | |
| 182 | + if (!isClosed()) { | |
| 183 | + closeAsync().force(); | |
| 184 | + } | |
| 185 | + } | |
| 186 | + }, initExecutor); | |
| 187 | + | |
| 188 | + return initFuture; | |
| 145 | 189 | } |
| 146 | 190 | |
| 147 | 191 | private static String extractMessage(Throwable t) { |
| @@ -153,119 +197,157 @@ | ||
| 153 | 197 | return " (" + msg + ')'; |
| 154 | 198 | } |
| 155 | 199 | |
| 156 | - private void initializeTransport(int version, String clusterName) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 157 | - try { | |
| 158 | - ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression(); | |
| 159 | - Message.Response response = write(new Requests.Startup(compression)).get(); | |
| 160 | - switch (response.type) { | |
| 161 | - case READY: | |
| 162 | - break; | |
| 163 | - case ERROR: | |
| 164 | - Responses.Error error = (Responses.Error)response; | |
| 165 | - // Testing for a specific string is a tad fragile but well, we don't have much choice | |
| 166 | - if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version")) | |
| 167 | - throw unsupportedProtocolVersionException(version); | |
| 168 | - throw defunct(new TransportException(address, String.format("Error initializing connection: %s", error.message))); | |
| 169 | - case AUTHENTICATE: | |
| 170 | - Authenticator authenticator = factory.authProvider.newAuthenticator(address); | |
| 171 | - if (version == 1) | |
| 172 | - { | |
| 173 | - if (authenticator instanceof ProtocolV1Authenticator) | |
| 174 | - authenticateV1(authenticator); | |
| 175 | - else | |
| 176 | - // DSE 3.x always uses SASL authentication backported from protocol v2 | |
| 177 | - authenticateV2(authenticator); | |
| 178 | - } | |
| 179 | - else | |
| 180 | - authenticateV2(authenticator); | |
| 181 | - break; | |
| 182 | - default: | |
| 183 | - throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type))); | |
| 200 | + private AsyncFunction<Void, Void> onChannelReady(final int protocolVersion, final Executor initExecutor) { | |
| 201 | + return new AsyncFunction<Void, Void>() { | |
| 202 | + @Override | |
| 203 | + public ListenableFuture<Void> apply(Void input) throws Exception { | |
| 204 | + ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression(); | |
| 205 | + Future startupResponseFuture = write(new Requests.Startup(compression)); | |
| 206 | + return Futures.transform(startupResponseFuture, | |
| 207 | + onStartupResponse(protocolVersion, initExecutor), initExecutor); | |
| 184 | 208 | } |
| 209 | + }; | |
| 210 | + } | |
| 185 | 211 | |
| 186 | - checkClusterName(clusterName); | |
| 187 | - } catch (BusyConnectionException e) { | |
| 188 | - throw defunct(new DriverInternalError("Newly created connection should not be busy")); | |
| 189 | - } catch (ExecutionException e) { | |
| 190 | - throw defunct(new ConnectionException(address, String.format("Unexpected error during transport initialization (%s)", e.getCause()), e.getCause())); | |
| 191 | - } | |
| 212 | + private AsyncFunction<Message.Response, Void> onStartupResponse(final int protocolVersion, final Executor initExecutor) { | |
| 213 | + return new AsyncFunction<Message.Response, Void>() { | |
| 214 | + @Override | |
| 215 | + public ListenableFuture<Void> apply(Message.Response response) throws Exception { | |
| 216 | + switch (response.type) { | |
| 217 | + case READY: | |
| 218 | + return checkClusterName(initExecutor); | |
| 219 | + case ERROR: | |
| 220 | + Responses.Error error = (Responses.Error)response; | |
| 221 | + // Testing for a specific string is a tad fragile but well, we don't have much choice | |
| 222 | + if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version")) | |
| 223 | + throw unsupportedProtocolVersionException(protocolVersion); | |
| 224 | + throw new TransportException(address, String.format("Error initializing connection: %s", error.message)); | |
| 225 | + case AUTHENTICATE: | |
| 226 | + Authenticator authenticator = factory.authProvider.newAuthenticator(address); | |
| 227 | + if (protocolVersion == 1) | |
| 228 | + { | |
| 229 | + if (authenticator instanceof ProtocolV1Authenticator) | |
| 230 | + return authenticateV1(authenticator, initExecutor); | |
| 231 | + else | |
| 232 | + // DSE 3.x always uses SASL authentication backported from protocol v2 | |
| 233 | + return authenticateV2(authenticator, initExecutor); | |
| 234 | + } | |
| 235 | + else | |
| 236 | + return authenticateV2(authenticator, initExecutor); | |
| 237 | + default: | |
| 238 | + throw new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)); | |
| 239 | + } | |
| 240 | + } | |
| 241 | + }; | |
| 192 | 242 | } |
| 193 | 243 | |
| 194 | - private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) { | |
| 195 | - logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion); | |
| 196 | - return new UnsupportedProtocolVersionException(address, triedVersion); | |
| 244 | + // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster. | |
| 245 | + // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting | |
| 246 | + // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397). | |
| 247 | + private ListenableFuture<Void> checkClusterName(final Executor executor) { | |
| 248 | + final String expected = factory.manager.metadata.clusterName; | |
| 249 | + | |
| 250 | + // At initialization, the cluster is not known yet | |
| 251 | + if (expected == null) | |
| 252 | + return MoreFutures.VOID_SUCCESS; | |
| 253 | + | |
| 254 | + DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local")); | |
| 255 | + try { | |
| 256 | + write(clusterNameFuture); | |
| 257 | + return Futures.transform(clusterNameFuture, | |
| 258 | + new AsyncFunction<ResultSet, Void>() { | |
| 259 | + @Override | |
| 260 | + public ListenableFuture<Void> apply(ResultSet rs) throws Exception { | |
| 261 | + Row row = rs.one(); | |
| 262 | + String actual = row.getString("cluster_name"); | |
| 263 | + if (!expected.equals(actual)) | |
| 264 | + throw new ClusterNameMismatchException(address, actual, expected); | |
| 265 | + return MoreFutures.VOID_SUCCESS; | |
| 266 | + } | |
| 267 | + }, executor); | |
| 268 | + } catch (Exception e) { | |
| 269 | + return Futures.immediateFailedFuture(e); | |
| 270 | + } | |
| 197 | 271 | } |
| 198 | 272 | |
| 199 | - private void authenticateV1(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 273 | + private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final Executor executor) { | |
| 200 | 274 | Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials()); |
| 201 | - Message.Response authResponse = write(creds).get(); | |
| 202 | - switch (authResponse.type) { | |
| 203 | - case READY: | |
| 204 | - break; | |
| 205 | - case ERROR: | |
| 206 | - throw defunct(new AuthenticationException(address, ((Responses.Error)authResponse).message)); | |
| 207 | - default: | |
| 208 | - throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type))); | |
| 275 | + try { | |
| 276 | + Future authResponseFuture = write(creds); | |
| 277 | + return Futures.transform(authResponseFuture, | |
| 278 | + new AsyncFunction<Message.Response, Void>() { | |
| 279 | + @Override | |
| 280 | + public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception { | |
| 281 | + switch (authResponse.type) { | |
| 282 | + case READY: | |
| 283 | + return checkClusterName(executor); | |
| 284 | + case ERROR: | |
| 285 | + throw new AuthenticationException(address, ((Responses.Error)authResponse).message); | |
| 286 | + default: | |
| 287 | + throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)); | |
| 288 | + } | |
| 289 | + } | |
| 290 | + }, executor); | |
| 291 | + } catch (Exception e) { | |
| 292 | + return Futures.immediateFailedFuture(e); | |
| 209 | 293 | } |
| 210 | 294 | } |
| 211 | 295 | |
| 212 | - private void authenticateV2(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 296 | + private ListenableFuture<Void> authenticateV2(final Authenticator authenticator, final Executor executor) { | |
| 213 | 297 | byte[] initialResponse = authenticator.initialResponse(); |
| 214 | 298 | if (null == initialResponse) |
| 215 | 299 | initialResponse = EMPTY_BYTE_ARRAY; |
| 216 | 300 | |
| 217 | - Message.Response authResponse = write(new Requests.AuthResponse(initialResponse)).get(); | |
| 218 | - waitForAuthCompletion(authResponse, authenticator); | |
| 301 | + try { | |
| 302 | + Future authResponseFuture = write(new Requests.AuthResponse(initialResponse)); | |
| 303 | + return Futures.transform(authResponseFuture, onV2AuthResponse(authenticator, executor), executor); | |
| 304 | + } catch (Exception e) { | |
| 305 | + return Futures.immediateFailedFuture(e); | |
| 306 | + } | |
| 219 | 307 | } |
| 220 | 308 | |
| 221 | - private void waitForAuthCompletion(Message.Response authResponse, Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 222 | - switch (authResponse.type) { | |
| 223 | - case AUTH_SUCCESS: | |
| 224 | - logger.trace("{} Authentication complete", this); | |
| 225 | - authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token); | |
| 226 | - break; | |
| 227 | - case AUTH_CHALLENGE: | |
| 228 | - byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token); | |
| 229 | - if (responseToServer == null) { | |
| 230 | - // If we generate a null response, then authentication has completed, return without | |
| 231 | - // sending a further response back to the server. | |
| 232 | - logger.trace("{} Authentication complete (No response to server)", this); | |
| 233 | - return; | |
| 234 | - } else { | |
| 235 | - // Otherwise, send the challenge response back to the server | |
| 236 | - logger.trace("{} Sending Auth response to challenge", this); | |
| 237 | - waitForAuthCompletion(write(new Requests.AuthResponse(responseToServer)).get(), authenticator); | |
| 309 | + private AsyncFunction<Message.Response, Void> onV2AuthResponse(final Authenticator authenticator, final Executor executor) { | |
| 310 | + return new AsyncFunction<Message.Response, Void>() { | |
| 311 | + @Override | |
| 312 | + public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception { | |
| 313 | + switch (authResponse.type) { | |
| 314 | + case AUTH_SUCCESS: | |
| 315 | + logger.trace("{} Authentication complete", this); | |
| 316 | + authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token); | |
| 317 | + return checkClusterName(executor); | |
| 318 | + case AUTH_CHALLENGE: | |
| 319 | + byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token); | |
| 320 | + if (responseToServer == null) { | |
| 321 | + // If we generate a null response, then authentication has completed, proceed without | |
| 322 | + // sending a further response back to the server. | |
| 323 | + logger.trace("{} Authentication complete (No response to server)", this); | |
| 324 | + return checkClusterName(executor); | |
| 325 | + } else { | |
| 326 | + // Otherwise, send the challenge response back to the server | |
| 327 | + logger.trace("{} Sending Auth response to challenge", this); | |
| 328 | + Future nextResponseFuture = write(new Requests.AuthResponse(responseToServer)); | |
| 329 | + return Futures.transform(nextResponseFuture, onV2AuthResponse(authenticator, executor), executor); | |
| 330 | + } | |
| 331 | + case ERROR: | |
| 332 | + // This is not very nice, but we're trying to identify if we | |
| 333 | + // attempted v2 auth against a server which only supports v1 | |
| 334 | + // The AIOOBE indicates that the server didn't recognise the | |
| 335 | + // initial AuthResponse message | |
| 336 | + String message = ((Responses.Error)authResponse).message; | |
| 337 | + if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15")) | |
| 338 | + message = String.format("Cannot use authenticator %s with protocol version 1, " | |
| 339 | + + "only plain text authentication is supported with this protocol version", authenticator); | |
| 340 | + throw new AuthenticationException(address, message); | |
| 341 | + default: | |
| 342 | + throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type)); | |
| 238 | 343 | } |
| 239 | - break; | |
| 240 | - case ERROR: | |
| 241 | - // This is not very nice, but we're trying to identify if we | |
| 242 | - // attempted v2 auth against a server which only supports v1 | |
| 243 | - // The AIOOBE indicates that the server didn't recognise the | |
| 244 | - // initial AuthResponse message | |
| 245 | - String message = ((Responses.Error)authResponse).message; | |
| 246 | - if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15")) | |
| 247 | - message = String.format("Cannot use authenticator %s with protocol version 1, " | |
| 248 | - + "only plain text authentication is supported with this protocol version", authenticator); | |
| 249 | - throw defunct(new AuthenticationException(address, message)); | |
| 250 | - default: | |
| 251 | - throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type))); | |
| 252 | - } | |
| 344 | + } | |
| 345 | + }; | |
| 253 | 346 | } |
| 254 | 347 | |
| 255 | - // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster. | |
| 256 | - // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting | |
| 257 | - // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397). | |
| 258 | - private void checkClusterName(String expected) throws ClusterNameMismatchException, ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 259 | - // At initialization, the cluster is not known yet | |
| 260 | - if (expected == null) | |
| 261 | - return; | |
| 262 | - | |
| 263 | - DefaultResultSetFuture future = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local")); | |
| 264 | - write(future); | |
| 265 | - Row row = future.get().one(); | |
| 266 | - String actual = row.getString("cluster_name"); | |
| 267 | - if (!expected.equals(actual)) | |
| 268 | - throw new ClusterNameMismatchException(address, actual, expected); | |
| 348 | + private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) { | |
| 349 | + logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion); | |
| 350 | + return new UnsupportedProtocolVersionException(address, triedVersion); | |
| 269 | 351 | } |
| 270 | 352 | |
| 271 | 353 | public boolean isDefunct() { |
| @@ -585,22 +667,55 @@ | ||
| 585 | 667 | throw new ConnectionException(address, "Connection factory is shut down"); |
| 586 | 668 | |
| 587 | 669 | String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement(); |
| 588 | - return new Connection(name, address, this); | |
| 670 | + Connection connection = new Connection(name, address, this); | |
| 671 | + // This method opens the connection synchronously, so wait until it's initialized | |
| 672 | + try { | |
| 673 | + connection.initAsync().get(); | |
| 674 | + return connection; | |
| 675 | + } catch (ExecutionException e) { | |
| 676 | + throw launderAsyncInitException(e); | |
| 677 | + } | |
| 589 | 678 | } |
| 590 | 679 | |
| 591 | 680 | /** |
| 592 | 681 | * Same as open, but associate the created connection to the provided connection pool. |
| 593 | 682 | */ |
| 594 | 683 | public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 595 | - InetSocketAddress address = pool.host.getSocketAddress(); | |
| 596 | - | |
| 597 | - if (isShutdown) | |
| 598 | - throw new ConnectionException(address, "Connection factory is shut down"); | |
| 684 | + try { | |
| 685 | + PooledConnection connection = newConnection(pool); | |
| 686 | + connection.initAsync().get(); | |
| 687 | + return connection; | |
| 688 | + } catch (ExecutionException e) { | |
| 689 | + throw launderAsyncInitException(e); | |
| 690 | + } | |
| 691 | + } | |
| 599 | 692 | |
| 693 | + /** | |
| 694 | + * Creates a new connection and associates it to the provided connection pool, but does not start it. | |
| 695 | + */ | |
| 696 | + public PooledConnection newConnection(HostConnectionPool pool) { | |
| 697 | + InetSocketAddress address = pool.host.getSocketAddress(); | |
| 600 | 698 | String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement(); |
| 699 | + | |
| 601 | 700 | return new PooledConnection(name, address, this, pool); |
| 602 | 701 | } |
| 603 | 702 | |
| 703 | + static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 704 | + Throwable t = e.getCause(); | |
| 705 | + if (t instanceof ConnectionException) | |
| 706 | + throw (ConnectionException)t; | |
| 707 | + if (t instanceof InterruptedException) | |
| 708 | + throw (InterruptedException)t; | |
| 709 | + if (t instanceof UnsupportedProtocolVersionException) | |
| 710 | + throw (UnsupportedProtocolVersionException)t; | |
| 711 | + if (t instanceof ClusterNameMismatchException) | |
| 712 | + throw (ClusterNameMismatchException)t; | |
| 713 | + if (t instanceof DriverException) | |
| 714 | + throw (DriverException)t; | |
| 715 | + | |
| 716 | + return new RuntimeException("Unexpected exception during connection initialization", t); | |
| 717 | + } | |
| 718 | + | |
| 604 | 719 | private AtomicInteger getIdGenerator(Host host) { |
| 605 | 720 | AtomicInteger g = idGenerators.get(host); |
| 606 | 721 | if (g == null) { |
| @@ -925,7 +1040,7 @@ | ||
| 925 | 1040 | public ConnectionCloseFuture force() { |
| 926 | 1041 | // Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared |
| 927 | 1042 | |
| 928 | - // This method can be thrown during Connection ctor, at which point channel is not yet set. This is ok. | |
| 1043 | + // This method can be thrown during initialization, at which point channel is not yet set. This is ok. | |
| 929 | 1044 | if (channel == null) { |
| 930 | 1045 | set(null); |
| 931 | 1046 | return this; |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +3 −1
| @@ -249,7 +249,9 @@ | ||
| 249 | 249 | if (!super.cancel(mayInterruptIfRunning)) |
| 250 | 250 | return false; |
| 251 | 251 | |
| 252 | - handler.cancel(); | |
| 252 | + if(handler != null) { | |
| 253 | + handler.cancel(); | |
| 254 | + } | |
| 253 | 255 | return true; |
| 254 | 256 | } |
| 255 | 257 |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +3 −1
| @@ -27,6 +27,8 @@ | ||
| 27 | 27 | import org.slf4j.Logger; |
| 28 | 28 | import org.slf4j.LoggerFactory; |
| 29 | 29 | |
| 30 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 31 | + | |
| 30 | 32 | /** |
| 31 | 33 | * A Cassandra node. |
| 32 | 34 | * |
| @@ -48,7 +50,7 @@ | ||
| 48 | 50 | private final Cluster.Manager manager; |
| 49 | 51 | |
| 50 | 52 | // Tracks the first "immediate" reconnection attempt when a node get suspected. |
| 51 | - final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null)); | |
| 53 | + final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(MoreFutures.VOID_SUCCESS); | |
| 52 | 54 | |
| 53 | 55 | // Tracks later reconnection attempts to that host so we avoid adding multiple tasks. |
| 54 | 56 | final AtomicReference<ListenableFuture<?>> reconnectionAttempt = new AtomicReference<ListenableFuture<?>>(); |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +63 −42
| @@ -15,14 +15,10 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | - | |
| 19 | 18 | import java.util.ArrayList; |
| 20 | 19 | import java.util.List; |
| 21 | 20 | import java.util.Set; |
| 22 | -import java.util.concurrent.CopyOnWriteArrayList; | |
| 23 | -import java.util.concurrent.CopyOnWriteArraySet; | |
| 24 | -import java.util.concurrent.TimeUnit; | |
| 25 | -import java.util.concurrent.TimeoutException; | |
| 21 | +import java.util.concurrent.*; | |
| 26 | 22 | import java.util.concurrent.atomic.AtomicInteger; |
| 27 | 23 | import java.util.concurrent.atomic.AtomicReference; |
| 28 | 24 | import java.util.concurrent.locks.Condition; |
| @@ -30,13 +26,16 @@ | ||
| 30 | 26 | import java.util.concurrent.locks.ReentrantLock; |
| 31 | 27 | |
| 32 | 28 | import com.google.common.collect.Lists; |
| 33 | -import com.google.common.util.concurrent.MoreExecutors; | |
| 29 | +import com.google.common.util.concurrent.*; | |
| 34 | 30 | import org.slf4j.Logger; |
| 35 | 31 | import org.slf4j.LoggerFactory; |
| 36 | 32 | |
| 37 | 33 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 38 | 34 | |
| 39 | -import static com.datastax.driver.core.PooledConnection.State.*; | |
| 35 | +import static com.datastax.driver.core.PooledConnection.State.GONE; | |
| 36 | +import static com.datastax.driver.core.PooledConnection.State.OPEN; | |
| 37 | +import static com.datastax.driver.core.PooledConnection.State.RESURRECTING; | |
| 38 | +import static com.datastax.driver.core.PooledConnection.State.TRASHED; | |
| 40 | 39 | |
| 41 | 40 | class HostConnectionPool { |
| 42 | 41 | |
| @@ -69,10 +68,12 @@ | ||
| 69 | 68 | |
| 70 | 69 | private final AtomicInteger scheduledForCreation = new AtomicInteger(); |
| 71 | 70 | |
| 72 | - private volatile boolean isClosing; | |
| 73 | 71 | private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 74 | 72 | |
| 75 | - public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 73 | + private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING } | |
| 74 | + private volatile Phase phase = Phase.INITIALIZING; | |
| 75 | + | |
| 76 | + public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager) { | |
| 76 | 77 | assert hostDistance != HostDistance.IGNORED; |
| 77 | 78 | this.host = host; |
| 78 | 79 | this.hostDistance = hostDistance; |
| @@ -86,37 +87,55 @@ | ||
| 86 | 87 | } |
| 87 | 88 | }; |
| 88 | 89 | |
| 90 | + this.connections = new CopyOnWriteArrayList<PooledConnection>(); | |
| 91 | + this.open = new AtomicInteger(); | |
| 92 | + } | |
| 93 | + | |
| 94 | + public ListenableFuture<Void> initAsync() { | |
| 89 | 95 | // Create initial core connections |
| 90 | - List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance)); | |
| 91 | - try { | |
| 92 | - for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) | |
| 93 | - l.add(manager.connectionFactory().open(this)); | |
| 94 | - } catch (InterruptedException e) { | |
| 95 | - Thread.currentThread().interrupt(); | |
| 96 | - // If asked to interrupt, we can skip opening core connections, the pool will still work. | |
| 97 | - // But we ignore otherwise cause I'm not sure we can do much better currently. | |
| 98 | - } catch (ConnectionException e) { | |
| 99 | - forceClose(l); | |
| 100 | - throw e; | |
| 101 | - } catch (UnsupportedProtocolVersionException e) { | |
| 102 | - forceClose(l); | |
| 103 | - throw e; | |
| 104 | - } catch (ClusterNameMismatchException e) { | |
| 105 | - forceClose(l); | |
| 106 | - throw e; | |
| 107 | - } catch (RuntimeException e) { | |
| 108 | - forceClose(l); | |
| 109 | - throw e; | |
| 96 | + int capacity = options().getCoreConnectionsPerHost(hostDistance); | |
| 97 | + final List<PooledConnection> connections = Lists.newArrayListWithCapacity(capacity); | |
| 98 | + final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity); | |
| 99 | + for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) { | |
| 100 | + PooledConnection connection = manager.connectionFactory().newConnection(this); | |
| 101 | + connections.add(connection); | |
| 102 | + connectionFutures.add(connection.initAsync()); | |
| 110 | 103 | } |
| 111 | - this.connections = new CopyOnWriteArrayList<PooledConnection>(l); | |
| 112 | - this.open = new AtomicInteger(connections.size()); | |
| 113 | 104 | |
| 114 | - logger.trace("Created connection pool to host {}", host); | |
| 105 | + Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 106 | + | |
| 107 | + ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures); | |
| 108 | + | |
| 109 | + final SettableFuture<Void> initFuture = SettableFuture.create(); | |
| 110 | + Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() { | |
| 111 | + @Override | |
| 112 | + public void onSuccess(List<Void> l) { | |
| 113 | + HostConnectionPool.this.connections.addAll(connections); | |
| 114 | + open.set(l.size()); | |
| 115 | + if (isClosed()) { | |
| 116 | + initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization")); | |
| 117 | + // we're not sure if closeAsync() saw the connections, so ensure they get closed | |
| 118 | + forceClose(connections); | |
| 119 | + } else { | |
| 120 | + logger.trace("Created connection pool to host {}", host); | |
| 121 | + phase = Phase.READY; | |
| 122 | + initFuture.set(null); | |
| 123 | + } | |
| 124 | + } | |
| 125 | + | |
| 126 | + @Override | |
| 127 | + public void onFailure(Throwable t) { | |
| 128 | + phase = Phase.INIT_FAILED; | |
| 129 | + forceClose(connections); | |
| 130 | + initFuture.setException(t); | |
| 131 | + } | |
| 132 | + }, initExecutor); | |
| 133 | + return initFuture; | |
| 115 | 134 | } |
| 116 | 135 | |
| 117 | 136 | // Clean up if we got an error at construction time but still created part of the core connections |
| 118 | - private void forceClose(List<PooledConnection> l) { | |
| 119 | - for (PooledConnection connection : l) { | |
| 137 | + private void forceClose(List<PooledConnection> connections) { | |
| 138 | + for (PooledConnection connection : connections) { | |
| 120 | 139 | connection.closeAsync().force(); |
| 121 | 140 | } |
| 122 | 141 | } |
| @@ -126,10 +145,13 @@ | ||
| 126 | 145 | } |
| 127 | 146 | |
| 128 | 147 | public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { |
| 129 | - if (isClosed()) | |
| 148 | + if (phase == Phase.INITIALIZING) | |
| 149 | + throw new ConnectionException(host.getSocketAddress(), "Pool is initializing."); | |
| 150 | + | |
| 151 | + if (phase != Phase.READY) | |
| 130 | 152 | // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host. |
| 131 | 153 | // That being said, maybe having a specific exception could be cleaner. |
| 132 | - throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); | |
| 154 | + throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase); | |
| 133 | 155 | |
| 134 | 156 | if (connections.isEmpty()) { |
| 135 | 157 | for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) { |
| @@ -355,7 +377,7 @@ | ||
| 355 | 377 | break; |
| 356 | 378 | } |
| 357 | 379 | |
| 358 | - if (isClosing) { | |
| 380 | + if (phase != Phase.READY) { | |
| 359 | 381 | open.decrementAndGet(); |
| 360 | 382 | return false; |
| 361 | 383 | } |
| @@ -372,7 +394,7 @@ | ||
| 372 | 394 | newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN |
| 373 | 395 | |
| 374 | 396 | // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it. |
| 375 | - if (isClosing && !newConnection.isClosed()) { | |
| 397 | + if (phase != Phase.READY && !newConnection.isClosed()) { | |
| 376 | 398 | close(newConnection); |
| 377 | 399 | open.decrementAndGet(); |
| 378 | 400 | return false; |
| @@ -517,7 +539,7 @@ | ||
| 517 | 539 | if (future != null) |
| 518 | 540 | return future; |
| 519 | 541 | |
| 520 | - isClosing = true; | |
| 542 | + phase = Phase.CLOSING; | |
| 521 | 543 | |
| 522 | 544 | // Wake up all threads that wait |
| 523 | 545 | signalAllAvailableConnection(); |
| @@ -538,9 +560,8 @@ | ||
| 538 | 560 | } |
| 539 | 561 | |
| 540 | 562 | private List<CloseFuture> discardAvailableConnections() { |
| 541 | - // This can happen if creating the connections in the constructor fails | |
| 542 | - if (connections == null) | |
| 543 | - return Lists.newArrayList(CloseFuture.immediateFuture()); | |
| 563 | + // Note: if this gets called before initialization has completed, both connections and trash will be empty, | |
| 564 | + // so this will return an empty list | |
| 544 | 565 | |
| 545 | 566 | List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size()); |
| 546 | 567 |
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +1 −1
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | |
| 32 | 32 | volatile long maxIdleTime; |
| 33 | 33 | |
| 34 | - PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 34 | + PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) { | |
| 35 | 35 | super(name, address, factory); |
| 36 | 36 | this.pool = pool; |
| 37 | 37 | } |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +45 −0
| @@ -15,6 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.util.concurrent.Executor; | |
| 19 | + | |
| 20 | +import com.google.common.base.Preconditions; | |
| 21 | +import com.google.common.util.concurrent.MoreExecutors; | |
| 22 | + | |
| 18 | 23 | /** |
| 19 | 24 | * Options related to connection pooling. |
| 20 | 25 | * <p> |
| @@ -53,6 +58,8 @@ | ||
| 53 | 58 | private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 54 | 59 | private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30; |
| 55 | 60 | |
| 61 | + private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor(); | |
| 62 | + | |
| 56 | 63 | private volatile Cluster.Manager manager; |
| 57 | 64 | |
| 58 | 65 | private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 }; |
| @@ -64,6 +71,8 @@ | ||
| 64 | 71 | private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; |
| 65 | 72 | private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; |
| 66 | 73 | |
| 74 | + private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR; | |
| 75 | + | |
| 67 | 76 | public PoolingOptions() {} |
| 68 | 77 | |
| 69 | 78 | void register(Cluster.Manager manager) { |
| @@ -308,6 +317,42 @@ | ||
| 308 | 317 | return this; |
| 309 | 318 | } |
| 310 | 319 | |
| 320 | + /** | |
| 321 | + * Returns the executor to use for connection initialization. | |
| 322 | + * | |
| 323 | + * @return the executor. | |
| 324 | + * @see #setInitializationExecutor(java.util.concurrent.Executor) | |
| 325 | + */ | |
| 326 | + public Executor getInitializationExecutor() { | |
| 327 | + return initializationExecutor; | |
| 328 | + } | |
| 329 | + | |
| 330 | + /** | |
| 331 | + * Sets the executor to use for connection initialization. | |
| 332 | + * <p> | |
| 333 | + * Connections are open in a completely asynchronous manner. Since initializing the transport | |
| 334 | + * requires separate CQL queries, the futures representing the completion of these queries are | |
| 335 | + * transformed and chained. This executor is where these transformations happen. | |
| 336 | + * <p> | |
| 337 | + * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to | |
| 338 | + * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations | |
| 339 | + * on the network I/O threads; this is fine if the transformations are fast and not I/O bound | |
| 340 | + * (which is the case by default). | |
| 341 | + * One reason why you might want to provide a custom executor is if you use authentication with | |
| 342 | + * a custom {@link com.datastax.driver.core.Authenticator} implementation that performs blocking | |
| 343 | + * calls. | |
| 344 | + * | |
| 345 | + * @param initializationExecutor the executor to use | |
| 346 | + * @return this {@code PoolingOptions} | |
| 347 | + * | |
| 348 | + * @throws java.lang.NullPointerException if the executor is null | |
| 349 | + */ | |
| 350 | + public PoolingOptions setInitializationExecutor(Executor initializationExecutor) { | |
| 351 | + Preconditions.checkNotNull(initializationExecutor); | |
| 352 | + this.initializationExecutor = initializationExecutor; | |
| 353 | + return this; | |
| 354 | + } | |
| 355 | + | |
| 311 | 356 | /** |
| 312 | 357 | * Requests the driver to re-evaluate the {@link HostDistance} (through the configured |
| 313 | 358 | * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +123 −115
| @@ -20,10 +20,10 @@ | ||
| 20 | 20 | import java.util.*; |
| 21 | 21 | import java.util.concurrent.*; |
| 22 | 22 | import java.util.concurrent.atomic.AtomicReference; |
| 23 | -import java.util.concurrent.locks.Lock; | |
| 24 | 23 | |
| 25 | 24 | import com.google.common.base.Function; |
| 26 | 25 | import com.google.common.collect.ImmutableList; |
| 26 | +import com.google.common.collect.Lists; | |
| 27 | 27 | import com.google.common.util.concurrent.*; |
| 28 | 28 | import org.slf4j.Logger; |
| 29 | 29 | import org.slf4j.LoggerFactory; |
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 34 | 34 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| 35 | 35 | import com.datastax.driver.core.policies.ReconnectionPolicy; |
| 36 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 36 | 37 | |
| 37 | 38 | /** |
| 38 | 39 | * Driver implementation of the Session interface. |
| @@ -46,8 +47,6 @@ | ||
| 46 | 47 | final HostConnectionPool.PoolState poolsState; |
| 47 | 48 | final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 48 | 49 | |
| 49 | - private final Striped<Lock> poolCreationLocks = Striped.lazyWeakLock(5); | |
| 50 | - | |
| 51 | 50 | private volatile boolean isInit; |
| 52 | 51 | private volatile boolean isClosing; |
| 53 | 52 | |
| @@ -67,50 +66,28 @@ | ||
| 67 | 66 | |
| 68 | 67 | // Create pools to initial nodes (and wait for them to be created) |
| 69 | 68 | Collection<Host> hosts = cluster.getMetadata().allHosts(); |
| 70 | - if (cluster.manager.sessions.size() == 1) { | |
| 71 | - // We only do it in parallel if this is the first session (meaning that the cluster just initialized). | |
| 72 | - createPoolsInParallel(hosts); | |
| 73 | - } else { | |
| 74 | - // Otherwise, we don't want to fill executor() because this is also where up/down notifications are processed, | |
| 75 | - // it's important that existing sessions get them in a timely manner. So we create the pools one by one: | |
| 76 | - createPoolsSequentially(hosts); | |
| 77 | - } | |
| 69 | + createPoolsInParallel(hosts); | |
| 78 | 70 | |
| 79 | 71 | isInit = true; |
| 80 | - updateCreatedPools(executor()); | |
| 72 | + updateCreatedPools(); | |
| 81 | 73 | return this; |
| 82 | 74 | } |
| 83 | 75 | |
| 84 | 76 | private void createPoolsInParallel(Collection<Host> hosts) { |
| 85 | - List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size()); | |
| 77 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size()); | |
| 86 | 78 | for (Host host : hosts) |
| 87 | 79 | if (host.state != Host.State.DOWN) |
| 88 | - futures.add(maybeAddPool(host, executor())); | |
| 89 | - ListenableFuture<List<Boolean>> f = Futures.allAsList(futures); | |
| 80 | + futures.add(maybeAddPool(host)); | |
| 90 | 81 | try { |
| 91 | - f.get(); | |
| 82 | + Futures.successfulAsList(futures).get(); | |
| 92 | 83 | } catch (ExecutionException e) { |
| 93 | - // This is not supposed to happen | |
| 94 | - throw new DriverInternalError(e); | |
| 84 | + // Won't happen because we used successfulAsList | |
| 85 | + // And if a particular pool failed, maybeAddPool already handled it | |
| 95 | 86 | } catch (InterruptedException e) { |
| 96 | 87 | Thread.currentThread().interrupt(); |
| 97 | 88 | } |
| 98 | 89 | } |
| 99 | 90 | |
| 100 | - private void createPoolsSequentially(Collection<Host> hosts) { | |
| 101 | - for (Host host : cluster.getMetadata().allHosts()) { | |
| 102 | - try { | |
| 103 | - if (host.state != Host.State.DOWN) | |
| 104 | - maybeAddPool(host, executor()).get(); | |
| 105 | - } catch (ExecutionException e) { | |
| 106 | - // This is not supposed to happen | |
| 107 | - throw new DriverInternalError(e); | |
| 108 | - } catch (InterruptedException e) { | |
| 109 | - Thread.currentThread().interrupt(); | |
| 110 | - } | |
| 111 | - } | |
| 112 | - } | |
| 113 | - | |
| 114 | 91 | public String getLoggedKeyspace() { |
| 115 | 92 | return poolsState.keyspace; |
| 116 | 93 | } |
| @@ -215,77 +192,94 @@ | ||
| 215 | 192 | } |
| 216 | 193 | |
| 217 | 194 | // Returns whether there was problem creating the pool |
| 218 | - ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) { | |
| 195 | + ListenableFuture<Boolean> forceRenewPool(final Host host) { | |
| 219 | 196 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 220 | 197 | if (distance == HostDistance.IGNORED) |
| 221 | 198 | return Futures.immediateFuture(true); |
| 222 | 199 | |
| 223 | - // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously. | |
| 224 | - return executor.submit(new Callable<Boolean>() { | |
| 225 | - public Boolean call() { | |
| 226 | - while (true) { | |
| 227 | - try { | |
| 228 | - if (isClosing) | |
| 229 | - return true; | |
| 230 | - | |
| 231 | - HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this); | |
| 232 | - HostConnectionPool previous = pools.put(host, newPool); | |
| 233 | - if (previous == null) { | |
| 234 | - logger.debug("Added connection pool for {}", host); | |
| 235 | - } else { | |
| 236 | - logger.debug("Renewed connection pool for {}", host); | |
| 237 | - previous.closeAsync(); | |
| 238 | - } | |
| 200 | + if (isClosing) | |
| 201 | + return Futures.immediateFuture(false); | |
| 202 | + | |
| 203 | + final HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this); | |
| 204 | + ListenableFuture<Void> poolInitFuture = newPool.initAsync(); | |
| 205 | + | |
| 206 | + final SettableFuture<Boolean> future = SettableFuture.create(); | |
| 207 | + | |
| 208 | + Futures.addCallback(poolInitFuture, new FutureCallback<Void>() { | |
| 209 | + @Override | |
| 210 | + public void onSuccess(Void result) { | |
| 211 | + // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 212 | + HostConnectionPool previous = pools.put(host, newPool); | |
| 213 | + if (previous == null) { | |
| 214 | + logger.debug("Added connection pool for {}", host); | |
| 215 | + } else { | |
| 216 | + logger.debug("Renewed connection pool for {}", host); | |
| 217 | + previous.closeAsync(); | |
| 218 | + } | |
| 239 | 219 | |
| 240 | - // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 241 | - if (isClosing) | |
| 242 | - newPool.closeAsync(); | |
| 243 | - | |
| 244 | - return true; | |
| 245 | - } catch (Exception e) { | |
| 246 | - logger.error("Error creating pool to " + host, e); | |
| 247 | - return false; | |
| 248 | - } | |
| 220 | + // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 221 | + if (isClosing) { | |
| 222 | + newPool.closeAsync(); | |
| 223 | + pools.remove(host); | |
| 224 | + future.set(false); | |
| 225 | + } else { | |
| 226 | + future.set(true); | |
| 249 | 227 | } |
| 250 | 228 | } |
| 229 | + | |
| 230 | + @Override | |
| 231 | + public void onFailure(Throwable t) { | |
| 232 | + logger.error("Error creating pool to " + host, t); | |
| 233 | + future.set(false); | |
| 234 | + } | |
| 251 | 235 | }); |
| 236 | + | |
| 237 | + return future; | |
| 252 | 238 | } |
| 253 | 239 | |
| 254 | - // Replace pool for a given only if it's the given previous value (which can be null) | |
| 255 | - // Note that the goal of this function is to make sure that 2 concurrent thread calling | |
| 256 | - // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools | |
| 257 | - // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we | |
| 258 | - // want to avoid | |
| 259 | - private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 240 | + // Replace pool for a given host only if it's the given previous value (which can be null) | |
| 241 | + // This returns a future if the replacement was successful, or null if we raced. | |
| 242 | + private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous) { | |
| 260 | 243 | if (isClosing) |
| 261 | - return true; | |
| 262 | - | |
| 263 | - Lock l = poolCreationLocks.get(host); | |
| 264 | - l.lock(); | |
| 265 | - try { | |
| 266 | - HostConnectionPool previous = pools.get(host); | |
| 267 | - if (previous != condition) | |
| 268 | - return false; | |
| 269 | - | |
| 270 | - HostConnectionPool newPool = new HostConnectionPool(host, distance, this); | |
| 271 | - previous = pools.put(host, newPool); | |
| 272 | - if (previous != null && !previous.isClosed()) { | |
| 244 | + return MoreFutures.VOID_SUCCESS; | |
| 245 | + | |
| 246 | + final HostConnectionPool newPool = new HostConnectionPool(host, distance, this); | |
| 247 | + if (previous == null) { | |
| 248 | + if (pools.putIfAbsent(host, newPool) != null) { | |
| 249 | + return null; | |
| 250 | + } | |
| 251 | + } else { | |
| 252 | + if (!pools.replace(host, previous, newPool)) { | |
| 253 | + return null; | |
| 254 | + } | |
| 255 | + if (!previous.isClosed()) { | |
| 273 | 256 | logger.warn("Replacing a pool that wasn't closed. Closing it now, but this was not expected."); |
| 274 | 257 | previous.closeAsync(); |
| 275 | 258 | } |
| 259 | + } | |
| 276 | 260 | |
| 277 | - // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 278 | - if (isClosing) | |
| 279 | - newPool.closeAsync(); | |
| 261 | + ListenableFuture<Void> poolInitFuture = newPool.initAsync(); | |
| 262 | + | |
| 263 | + Futures.addCallback(poolInitFuture, new FutureCallback<Void>() { | |
| 264 | + @Override | |
| 265 | + public void onSuccess(Void result) { | |
| 266 | + // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 267 | + if (isClosing) { | |
| 268 | + newPool.closeAsync(); | |
| 269 | + pools.remove(host); | |
| 270 | + } | |
| 271 | + } | |
| 280 | 272 | |
| 281 | - return true; | |
| 282 | - } finally { | |
| 283 | - l.unlock(); | |
| 284 | - } | |
| 273 | + @Override | |
| 274 | + public void onFailure(Throwable t) { | |
| 275 | + pools.remove(host); | |
| 276 | + } | |
| 277 | + }); | |
| 278 | + return poolInitFuture; | |
| 285 | 279 | } |
| 286 | 280 | |
| 287 | 281 | // Returns whether there was problem creating the pool |
| 288 | - ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) { | |
| 282 | + ListenableFuture<Boolean> maybeAddPool(final Host host) { | |
| 289 | 283 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 290 | 284 | if (distance == HostDistance.IGNORED) |
| 291 | 285 | return Futures.immediateFuture(true); |
| @@ -294,34 +288,39 @@ | ||
| 294 | 288 | if (previous != null && !previous.isClosed()) |
| 295 | 289 | return Futures.immediateFuture(true); |
| 296 | 290 | |
| 297 | - // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously. | |
| 298 | - return executor.submit(new Callable<Boolean>() { | |
| 299 | - public Boolean call() { | |
| 300 | - try { | |
| 301 | - while (true) { | |
| 302 | - HostConnectionPool previous = pools.get(host); | |
| 303 | - if (previous != null && !previous.isClosed()) | |
| 304 | - return true; | |
| 305 | - | |
| 306 | - if (replacePool(host, distance, previous)) { | |
| 307 | - logger.debug("Added connection pool for {}", host); | |
| 308 | - return true; | |
| 291 | + while (true) { | |
| 292 | + previous = pools.get(host); | |
| 293 | + if (previous != null && !previous.isClosed()) | |
| 294 | + return Futures.immediateFuture(true); | |
| 295 | + | |
| 296 | + final SettableFuture<Boolean> future = SettableFuture.create(); | |
| 297 | + ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous); | |
| 298 | + if (newPoolInit != null) { | |
| 299 | + Futures.addCallback(newPoolInit, new FutureCallback<Void>() { | |
| 300 | + @Override | |
| 301 | + public void onSuccess(Void result) { | |
| 302 | + logger.debug("Added connection pool for {}", host); | |
| 303 | + future.set(true); | |
| 304 | + } | |
| 305 | + | |
| 306 | + @Override | |
| 307 | + public void onFailure(Throwable t) { | |
| 308 | + if (t instanceof UnsupportedProtocolVersionException) { | |
| 309 | + cluster.manager.logUnsupportedVersionProtocol(host); | |
| 310 | + cluster.manager.triggerOnDown(host, false); | |
| 311 | + } else if (t instanceof ClusterNameMismatchException) { | |
| 312 | + ClusterNameMismatchException e = (ClusterNameMismatchException)t; | |
| 313 | + cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 314 | + cluster.manager.triggerOnDown(host, false); | |
| 315 | + } else { | |
| 316 | + logger.error("Error creating pool to " + host, t); | |
| 309 | 317 | } |
| 318 | + future.set(false); | |
| 310 | 319 | } |
| 311 | - } catch (UnsupportedProtocolVersionException e) { | |
| 312 | - cluster.manager.logUnsupportedVersionProtocol(host); | |
| 313 | - cluster.manager.triggerOnDown(host, false); | |
| 314 | - return false; | |
| 315 | - } catch (ClusterNameMismatchException e) { | |
| 316 | - cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 317 | - cluster.manager.triggerOnDown(host, false); | |
| 318 | - return false; | |
| 319 | - } catch (Exception e) { | |
| 320 | - logger.error("Error creating pool to " + host, e); | |
| 321 | - return false; | |
| 322 | - } | |
| 320 | + }); | |
| 321 | + return future; | |
| 323 | 322 | } |
| 324 | - }); | |
| 323 | + } | |
| 325 | 324 | } |
| 326 | 325 | |
| 327 | 326 | CloseFuture removePool(Host host) { |
| @@ -340,7 +339,7 @@ | ||
| 340 | 339 | * This method ensures that all hosts for which a pool should exist |
| 341 | 340 | * have one, and hosts that shouldn't don't. |
| 342 | 341 | */ |
| 343 | - void updateCreatedPools(ListeningExecutorService executor) { | |
| 342 | + void updateCreatedPools() { | |
| 344 | 343 | // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if |
| 345 | 344 | // we execute the code below we would try to create their pool over and over again. |
| 346 | 345 | // It's called explicitly at the end of init(), once isInit has been set to true. |
| @@ -359,7 +358,7 @@ | ||
| 359 | 358 | |
| 360 | 359 | if (pool == null) { |
| 361 | 360 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 362 | - poolCreationFutures.add(maybeAddPool(h, executor)); | |
| 361 | + poolCreationFutures.add(maybeAddPool(h)); | |
| 363 | 362 | } else if (dist != pool.hostDistance) { |
| 364 | 363 | if (dist == HostDistance.IGNORED) { |
| 365 | 364 | toRemove.add(h); |
| @@ -371,7 +370,12 @@ | ||
| 371 | 370 | } |
| 372 | 371 | |
| 373 | 372 | // Wait pool creation before removing, so we don't lose connectivity |
| 374 | - Futures.allAsList(poolCreationFutures).get(); | |
| 373 | + try { | |
| 374 | + Futures.successfulAsList(poolCreationFutures).get(); | |
| 375 | + } catch (ExecutionException e) { | |
| 376 | + // Won't happen because we used successfulAsList | |
| 377 | + // And if a particular pool failed, maybeAddPool already handled it | |
| 378 | + } | |
| 375 | 379 | |
| 376 | 380 | List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size()); |
| 377 | 381 | for (Host h : toRemove) |
| @@ -385,14 +389,18 @@ | ||
| 385 | 389 | } |
| 386 | 390 | } |
| 387 | 391 | |
| 388 | - void updateCreatedPools(Host h, ListeningExecutorService executor) { | |
| 392 | + void updateCreatedPools(Host h) { | |
| 389 | 393 | HostDistance dist = loadBalancingPolicy().distance(h); |
| 390 | 394 | HostConnectionPool pool = pools.get(h); |
| 391 | 395 | |
| 392 | 396 | try { |
| 393 | 397 | if (pool == null) { |
| 394 | 398 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 395 | - maybeAddPool(h, executor).get(); | |
| 399 | + try { | |
| 400 | + maybeAddPool(h).get(); | |
| 401 | + } catch (ExecutionException e) { | |
| 402 | + // Ignore, maybeAddPool has already handled the error | |
| 403 | + } | |
| 396 | 404 | } else if (dist != pool.hostDistance) { |
| 397 | 405 | if (dist == HostDistance.IGNORED) { |
| 398 | 406 | removePool(h).get(); |
| @@ -412,7 +420,7 @@ | ||
| 412 | 420 | // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary |
| 413 | 421 | // since updateCreatedPools should take care of it. But better protect against non well behaving policies. |
| 414 | 422 | removePool(host).force().get(); |
| 415 | - updateCreatedPools(MoreExecutors.sameThreadExecutor()); | |
| 423 | + updateCreatedPools(); | |
| 416 | 424 | } |
| 417 | 425 | |
| 418 | 426 | void onSuspected(Host host) { |
added driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java +46 −0
| @@ -0,0 +1,46 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 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.utils; | |
| 17 | + | |
| 18 | +import com.google.common.util.concurrent.FutureCallback; | |
| 19 | +import com.google.common.util.concurrent.Futures; | |
| 20 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * Helpers to work with Guava's {@link ListenableFuture}. | |
| 24 | + */ | |
| 25 | +public class MoreFutures { | |
| 26 | + /** | |
| 27 | + * An immediate successful {@code ListenableFuture<Void>}. | |
| 28 | + */ | |
| 29 | + public static final ListenableFuture<Void> VOID_SUCCESS = Futures.immediateFuture(null); | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * A {@link FutureCallback} that does nothing on failure. | |
| 33 | + */ | |
| 34 | + public static abstract class SuccessCallback<V> implements FutureCallback<V> { | |
| 35 | + @Override | |
| 36 | + public void onFailure(Throwable t) { /* nothing */ } | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * A {@link FutureCallback} that does nothing on success. | |
| 41 | + */ | |
| 42 | + public static abstract class FailureCallback<V> implements FutureCallback<V> { | |
| 43 | + @Override | |
| 44 | + public void onSuccess(V result) { /* nothing */ } | |
| 45 | + } | |
| 46 | +} |