kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 793eeb4d04484f4e5738615bfdb5ba646c298b9291a87e37134c66ee451c1ab0 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2014-10-28 18:31 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2014-10-28 21:48 +01:00 |
| Parents | bfcc7c8134a2, 5eeeaae8a97f |
22 files changed
modified driver-core/CHANGELOG.rst +14 −0
| @@ -25,6 +25,13 @@ | ||
| 25 | 25 | - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504) |
| 26 | 26 | - [improvement] Make schema agreement wait tuneable (JAVA-507) |
| 27 | 27 | - [improvement] Document how to inject the driver metrics into another registry (JAVA-494) |
| 28 | +- [improvement] Add idle timeout to the connection pool (JAVA-419) | |
| 29 | +- [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516) | |
| 30 | +- [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with | |
| 31 | + an explicit but null or empty local datacenter (JAVA-451). | |
| 32 | +- [bug] Fix check for local contact points in DCAware policy's init (JAVA-511) | |
| 33 | +- [improvement] Make timeout on saturated pool customizable (JAVA-457) | |
| 34 | +- [improvement] Downgrade Guava to 14.0.1 (JAVA-521) | |
| 28 | 35 | |
| 29 | 36 | |
| 30 | 37 | 2.1.2: |
| @@ -133,6 +140,13 @@ | ||
| 133 | 140 | - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504) |
| 134 | 141 | - [improvement] Make schema agreement wait tuneable (JAVA-507) |
| 135 | 142 | - [improvement] Document how to inject the driver metrics into another registry (JAVA-494) |
| 143 | +- [improvement] Add idle timeout to the connection pool (JAVA-419) | |
| 144 | +- [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516) | |
| 145 | +- [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with | |
| 146 | + an explicit but null or empty local datacenter (JAVA-451). | |
| 147 | +- [bug] Fix check for local contact points in DCAware policy's init (JAVA-511) | |
| 148 | +- [improvement] Make timeout on saturated pool customizable (JAVA-457) | |
| 149 | +- [improvement] Downgrade Guava to 14.0.1 (JAVA-521) | |
| 136 | 150 | |
| 137 | 151 | |
| 138 | 152 | 2.0.6: |
modified driver-core/pom.xml +5 −1
| @@ -36,7 +36,11 @@ | ||
| 36 | 36 | <dependency> |
| 37 | 37 | <groupId>com.google.guava</groupId> |
| 38 | 38 | <artifactId>guava</artifactId> |
| 39 | - <version>16.0.1</version> | |
| 39 | + <!-- | |
| 40 | + We use an old version of Guava to be compatible with Spark 1.1. | |
| 41 | + Check with the spark-cassandra-connector team before upgrading this. | |
| 42 | + --> | |
| 43 | + <version>14.0.1</version> | |
| 40 | 44 | </dependency> |
| 41 | 45 | |
| 42 | 46 | <dependency> |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +22 −14
| @@ -26,6 +26,16 @@ | ||
| 26 | 26 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 27 | 27 | import com.datastax.driver.core.policies.ReconnectionPolicy; |
| 28 | 28 | |
| 29 | +/** | |
| 30 | + * Manages periodic reconnection attempts after a host has been marked down. | |
| 31 | + * <p> | |
| 32 | + * Concurrent attempts are handled via the {@link #currentAttempt} reference passed to the constructor. | |
| 33 | + * For a given reference, only one handler will run at a given time. Additional handlers will cancel | |
| 34 | + * themselves if they find a previous handler running. | |
| 35 | + * <p> | |
| 36 | + * This class is designed for concurrency, but instances must not be shared: each thread creates and | |
| 37 | + * starts its own private handler, all interactions happen through {@link #currentAttempt}. | |
| 38 | + */ | |
| 29 | 39 | abstract class AbstractReconnectionHandler implements Runnable { |
| 30 | 40 | |
| 31 | 41 | private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandler.class); |
| @@ -41,7 +51,7 @@ | ||
| 41 | 51 | |
| 42 | 52 | private final long initialDelayMs; |
| 43 | 53 | |
| 44 | - private volatile boolean isActive; | |
| 54 | + private final CountDownLatch ready = new CountDownLatch(1); | |
| 45 | 55 | |
| 46 | 56 | public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt) { |
| 47 | 57 | this(executor, schedule, currentAttempt, -1); |
| @@ -79,14 +89,14 @@ | ||
| 79 | 89 | if (previous != null && !previous.isCancelled()) { |
| 80 | 90 | logger.debug("Found another already active handler, cancelling"); |
| 81 | 91 | handlerFuture.cancel(false); |
| 82 | - return; | |
| 92 | + break; | |
| 83 | 93 | } |
| 84 | 94 | if (currentAttempt.compareAndSet(previous, handlerFuture)) { |
| 85 | 95 | logger.debug("Becoming the active handler"); |
| 86 | 96 | break; |
| 87 | 97 | } |
| 88 | 98 | } |
| 89 | - isActive = true; | |
| 99 | + ready.countDown(); | |
| 90 | 100 | } catch (RejectedExecutionException e) { |
| 91 | 101 | // The executor has been shutdown, fair enough, just ignore |
| 92 | 102 | logger.debug("Aborting reconnection handling since the cluster is shutting down"); |
| @@ -95,23 +105,21 @@ | ||
| 95 | 105 | |
| 96 | 106 | @Override |
| 97 | 107 | public void run() { |
| 108 | + // Just make sure we don't start the first try too fast, in case we find out in start() that we need to cancel ourselves | |
| 109 | + try { | |
| 110 | + ready.await(); | |
| 111 | + } catch (InterruptedException e) { | |
| 112 | + // This can happen at shutdown | |
| 113 | + Thread.currentThread().interrupt(); | |
| 114 | + return; | |
| 115 | + } | |
| 116 | + | |
| 98 | 117 | if (handlerFuture.isCancelled()) { |
| 99 | 118 | logger.debug("Got cancelled, stopping"); |
| 100 | 119 | currentAttempt.compareAndSet(handlerFuture, null); |
| 101 | 120 | return; |
| 102 | 121 | } |
| 103 | 122 | |
| 104 | - // Just make sure we don't start the first try too fast, in case we find out in start() that we need to cancel ourselves | |
| 105 | - while (!isActive && !Thread.currentThread().isInterrupted()) { | |
| 106 | - try { | |
| 107 | - TimeUnit.MILLISECONDS.sleep(5); | |
| 108 | - } catch (InterruptedException e) { | |
| 109 | - // This can happen at shutdown | |
| 110 | - Thread.currentThread().interrupt(); | |
| 111 | - return; | |
| 112 | - } | |
| 113 | - } | |
| 114 | - | |
| 115 | 123 | try { |
| 116 | 124 | onReconnection(tryReconnect()); |
| 117 | 125 | handlerFuture.markAsDone(); |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +27 −13
| @@ -1208,12 +1208,9 @@ | ||
| 1208 | 1208 | metadata.add(address); |
| 1209 | 1209 | } |
| 1210 | 1210 | |
| 1211 | - // Make a copy of the hosts - which only contain the contact points at this stage - before we initialize the | |
| 1212 | - // control connection. We use a set with guaranteed insertion order, so that the contact points will remain | |
| 1213 | - // first, before any other host discovered by the control connection. | |
| 1214 | - // This is important if the load balancing policy is the DCAware one, because it needs to see the contact points | |
| 1215 | - // first for the local DC detection to work properly. | |
| 1216 | - Set<Host> hosts = Sets.newLinkedHashSet(metadata.allHosts()); | |
| 1211 | + // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init(). | |
| 1212 | + // But the control connection will initialize first and discover more hosts, so make a copy. | |
| 1213 | + Set<Host> contactPointHosts = Sets.newHashSet(metadata.allHosts()); | |
| 1217 | 1214 | |
| 1218 | 1215 | try { |
| 1219 | 1216 | try { |
| @@ -1229,21 +1226,25 @@ | ||
| 1229 | 1226 | } |
| 1230 | 1227 | } |
| 1231 | 1228 | |
| 1232 | - // metadata now also contains other hosts discovered by the connection, update our copy | |
| 1233 | - hosts.addAll(metadata.allHosts()); | |
| 1234 | - | |
| 1235 | 1229 | // Now that the control connection is ready, we have all the information we need about the nodes (datacenter, |
| 1236 | 1230 | // rack...) to initialize the load balancing policy |
| 1237 | - loadBalancingPolicy().init(Cluster.this, hosts); | |
| 1238 | - | |
| 1231 | + loadBalancingPolicy().init(Cluster.this, contactPointHosts); | |
| 1232 | + // Add the remaining hosts that were discovered by the control connection: | |
| 1233 | + for (Host host : metadata.allHosts()) { | |
| 1234 | + if (!contactPointHosts.contains(host)) | |
| 1235 | + loadBalancingPolicy().onAdd(host); | |
| 1236 | + } | |
| 1239 | 1237 | isFullyInit = true; |
| 1240 | 1238 | |
| 1241 | - for (Host host : hosts) | |
| 1239 | + for (Host host : metadata.allHosts()) | |
| 1242 | 1240 | triggerOnAdd(host); |
| 1243 | 1241 | } catch (NoHostAvailableException e) { |
| 1244 | 1242 | close(); |
| 1245 | 1243 | throw e; |
| 1246 | 1244 | } |
| 1245 | + | |
| 1246 | + if (connectionFactory.protocolVersion.compareTo(ProtocolVersion.V3) < 0) | |
| 1247 | + this.scheduledTasksExecutor.scheduleWithFixedDelay(new TrashIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1247 | 1248 | } |
| 1248 | 1249 | |
| 1249 | 1250 | ProtocolVersion protocolVersion() { |
| @@ -2140,6 +2141,19 @@ | ||
| 2140 | 2141 | }).start(); |
| 2141 | 2142 | } |
| 2142 | 2143 | } |
| 2144 | + | |
| 2145 | + private class TrashIdleConnectionsTask implements Runnable { | |
| 2146 | + @Override public void run() { | |
| 2147 | + try { | |
| 2148 | + long now = System.currentTimeMillis(); | |
| 2149 | + for (SessionManager session : sessions) { | |
| 2150 | + session.trashIdleConnections(now); | |
| 2151 | + } | |
| 2152 | + } catch (Exception e) { | |
| 2153 | + logger.warn("Error while trashing idle connections", e); | |
| 2154 | + } | |
| 2155 | + } | |
| 2156 | + } | |
| 2143 | 2157 | } |
| 2144 | 2158 | |
| 2145 | 2159 | /** |
| @@ -2153,7 +2167,7 @@ | ||
| 2153 | 2167 | private static final int INTERVAL_MS = 15000; |
| 2154 | 2168 | |
| 2155 | 2169 | private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory("Reaper-%d")); |
| 2156 | - private final Set<Connection> connections = Sets.newConcurrentHashSet(); | |
| 2170 | + private final Set<Connection> connections = Sets.newSetFromMap(new ConcurrentHashMap<Connection, Boolean>()); | |
| 2157 | 2171 | |
| 2158 | 2172 | private volatile boolean shutdown; |
| 2159 | 2173 |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +2 −2
| @@ -74,6 +74,7 @@ | ||
| 74 | 74 | if (isShutdown) |
| 75 | 75 | return; |
| 76 | 76 | |
| 77 | + // NB: at this stage, allHosts() only contains the initial contact points | |
| 77 | 78 | setNewConnection(reconnectInternal(cluster.metadata.allHosts().iterator(), true)); |
| 78 | 79 | } |
| 79 | 80 | |
| @@ -160,8 +161,7 @@ | ||
| 160 | 161 | Connection connection = connectionRef.get(); |
| 161 | 162 | if (connection != null && connection.isDefunct()) { |
| 162 | 163 | // If the connection was marked as defunct, this already reported the |
| 163 | - // node down, which will trigger a reconnect. Otherwise, just reconnect | |
| 164 | - // manually | |
| 164 | + // node down, which will trigger a reconnect. | |
| 165 | 165 | return; |
| 166 | 166 | } |
| 167 | 167 | // If the connection is not defunct, or the host has left, just reconnect manually |
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +18 −8
| @@ -188,6 +188,9 @@ | ||
| 188 | 188 | } |
| 189 | 189 | |
| 190 | 190 | private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { |
| 191 | + if (timeout == 0) | |
| 192 | + throw new TimeoutException(); | |
| 193 | + | |
| 191 | 194 | long start = System.nanoTime(); |
| 192 | 195 | long remaining = timeout; |
| 193 | 196 | do { |
| @@ -252,15 +255,25 @@ | ||
| 252 | 255 | close(connection); |
| 253 | 256 | } else { |
| 254 | 257 | if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) { |
| 255 | - trashConnection(connection); | |
| 258 | + connection.setTrashTimeIn(options().getIdleTimeoutSeconds()); | |
| 256 | 259 | } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) { |
| 257 | 260 | replaceConnection(connection); |
| 258 | 261 | } else { |
| 262 | + connection.cancelTrashTime(); | |
| 259 | 263 | signalAvailableConnection(); |
| 260 | 264 | } |
| 261 | 265 | } |
| 262 | 266 | } |
| 263 | 267 | |
| 268 | + @Override | |
| 269 | + void trashIdleConnections(long now) { | |
| 270 | + for (PooledConnection connection : connections) { | |
| 271 | + if (connection.getTrashTime() < now) { | |
| 272 | + trashConnection(connection); | |
| 273 | + } | |
| 274 | + } | |
| 275 | + } | |
| 276 | + | |
| 264 | 277 | // Trash the connection and create a new one, but we don't call trashConnection |
| 265 | 278 | // directly because we want to make sure the connection is always trashed. |
| 266 | 279 | private void replaceConnection(PooledConnection connection) { |
| @@ -277,6 +290,7 @@ | ||
| 277 | 290 | int opened = open.get(); |
| 278 | 291 | if (opened <= options().getCoreConnectionsPerHost(hostDistance)) { |
| 279 | 292 | connection.markForTrash.set(false); |
| 293 | + connection.cancelTrashTime(); | |
| 280 | 294 | return false; |
| 281 | 295 | } |
| 282 | 296 | |
| @@ -286,13 +300,9 @@ | ||
| 286 | 300 | |
| 287 | 301 | doTrashConnection(connection); |
| 288 | 302 | } |
| 289 | - // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection. | |
| 290 | - // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do | |
| 291 | - // it: | |
| 292 | - // - the current thread decremented inFlight in returnConnection | |
| 293 | - // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))` | |
| 294 | - // in returnConnection and not arrived here. | |
| 295 | - // - so the other thread will see the up-to-date value of inFlight and take appropriate action. | |
| 303 | + // If compareAndSet failed, it means we raced with another thread that will execute doTrashConnection. | |
| 304 | + // Since trashConnection is called from a scheduled task, we're sure that the current thread did not modify | |
| 305 | + // inFlight, so the other thread will take care of closing the connection if necessary (i.e. if inFlight == 0). | |
| 296 | 306 | return true; |
| 297 | 307 | } |
| 298 | 308 |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +2 −0
| @@ -59,6 +59,8 @@ | ||
| 59 | 59 | |
| 60 | 60 | abstract void replaceDefunctConnection(final PooledConnection connection); |
| 61 | 61 | |
| 62 | + abstract void trashIdleConnections(long now); | |
| 63 | + | |
| 62 | 64 | abstract int opened(); |
| 63 | 65 | |
| 64 | 66 | abstract int inFlightQueriesCount(); |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +1 −1
| @@ -93,7 +93,7 @@ | ||
| 93 | 93 | * com.codahale.metrics.CsvReporter.forRegistry(metrics.getRegistry()).build(new File("measurements/")).start(1, TimeUnit.SECONDS); |
| 94 | 94 | * </pre> |
| 95 | 95 | * <p> |
| 96 | - * If you already have a {@code MetricRegistry} in your application and which to | |
| 96 | + * If you already have a {@code MetricRegistry} in your application and wish to | |
| 97 | 97 | * add the driver's metrics to it, the recommended approach is to use a listener: |
| 98 | 98 | * <pre> |
| 99 | 99 | * // Your existing registry: |
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +15 −0
| @@ -25,6 +25,9 @@ | ||
| 25 | 25 | |
| 26 | 26 | private final HostConnectionPool pool; |
| 27 | 27 | |
| 28 | + /** The instant when the connection should be trashed after being idle for too long */ | |
| 29 | + private volatile long trashTime = Long.MAX_VALUE; | |
| 30 | + | |
| 28 | 31 | /** Used in {@link DynamicConnectionPool} to handle races between two threads trying to trash the same connection */ |
| 29 | 32 | final AtomicBoolean markForTrash = new AtomicBoolean(); |
| 30 | 33 | |
| @@ -60,4 +63,16 @@ | ||
| 60 | 63 | pool.replaceDefunctConnection(this); |
| 61 | 64 | } |
| 62 | 65 | } |
| 66 | + | |
| 67 | + long getTrashTime() { | |
| 68 | + return trashTime; | |
| 69 | + } | |
| 70 | + | |
| 71 | + void cancelTrashTime() { | |
| 72 | + trashTime = Long.MAX_VALUE; | |
| 73 | + } | |
| 74 | + | |
| 75 | + void setTrashTimeIn(int timeoutSeconds) { | |
| 76 | + trashTime = System.currentTimeMillis() + 1000 * timeoutSeconds; | |
| 77 | + } | |
| 63 | 78 | } |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +64 −0
| @@ -58,6 +58,9 @@ | ||
| 58 | 58 | private static final int DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL = 1024; |
| 59 | 59 | private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256; |
| 60 | 60 | |
| 61 | + private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; | |
| 62 | + private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; | |
| 63 | + | |
| 61 | 64 | private volatile Cluster.Manager manager; |
| 62 | 65 | |
| 63 | 66 | private final int[] minSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MIN_REQUESTS_PER_CONNECTION, DEFAULT_MIN_REQUESTS_PER_CONNECTION, 0 }; |
| @@ -70,6 +73,9 @@ | ||
| 70 | 73 | private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE; |
| 71 | 74 | |
| 72 | 75 | |
| 76 | + private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS; | |
| 77 | + private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; | |
| 78 | + | |
| 73 | 79 | public PoolingOptions() {} |
| 74 | 80 | |
| 75 | 81 | void register(Cluster.Manager manager) { |
| @@ -244,6 +250,64 @@ | ||
| 244 | 250 | return this; |
| 245 | 251 | } |
| 246 | 252 | |
| 253 | + /** | |
| 254 | + * Returns the timeout before an idle connection is removed. | |
| 255 | + * | |
| 256 | + * @return the timeout. | |
| 257 | + */ | |
| 258 | + public int getIdleTimeoutSeconds() { | |
| 259 | + return idleTimeoutSeconds; | |
| 260 | + } | |
| 261 | + | |
| 262 | + /** | |
| 263 | + * Sets the timeout before an idle connection is removed. | |
| 264 | + * <p> | |
| 265 | + * The order of magnitude should be a few minutes (the default is 120 seconds). The | |
| 266 | + * timeout that triggers the removal has a granularity of 10 seconds. | |
| 267 | + * <p> | |
| 268 | + * This option is only used with {@code ProtocolVersion#V2} or below. | |
| 269 | + | |
| 270 | + * @param idleTimeoutSeconds the new timeout in seconds. | |
| 271 | + * @return this {@code PoolingOptions}. | |
| 272 | + * | |
| 273 | + * @throws IllegalArgumentException if the timeout is negative. | |
| 274 | + */ | |
| 275 | + public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) { | |
| 276 | + if (idleTimeoutSeconds < 0) | |
| 277 | + throw new IllegalArgumentException("Idle timeout must be positive"); | |
| 278 | + this.idleTimeoutSeconds = idleTimeoutSeconds; | |
| 279 | + return this; | |
| 280 | + } | |
| 281 | + | |
| 282 | + /** | |
| 283 | + * Returns the timeout when trying to acquire a connection from a host's pool. | |
| 284 | + * | |
| 285 | + * @return the timeout. | |
| 286 | + */ | |
| 287 | + public int getPoolTimeoutMillis() { | |
| 288 | + return poolTimeoutMillis; | |
| 289 | + } | |
| 290 | + | |
| 291 | + /** | |
| 292 | + * Sets the timeout when trying to acquire a connection from a host's pool. | |
| 293 | + * <p> | |
| 294 | + * If no connection is available within that time, the driver will try the | |
| 295 | + * next host from the query plan. | |
| 296 | + * <p> | |
| 297 | + * If this option is set to zero, the driver won't wait at all. | |
| 298 | + * | |
| 299 | + * @param poolTimeoutMillis the new value in milliseconds. | |
| 300 | + * @return this {@code PoolingOptions} | |
| 301 | + * | |
| 302 | + * @throws IllegalArgumentException if the timeout is negative. | |
| 303 | + */ | |
| 304 | + public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) { | |
| 305 | + if (poolTimeoutMillis < 0) | |
| 306 | + throw new IllegalArgumentException("Pool timeout must be positive"); | |
| 307 | + this.poolTimeoutMillis = poolTimeoutMillis; | |
| 308 | + return this; | |
| 309 | + } | |
| 310 | + | |
| 247 | 311 | /** |
| 248 | 312 | * Returns the maximum number of requests per host. |
| 249 | 313 | * <p> |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +13 −9
| @@ -57,6 +57,12 @@ | ||
| 57 | 57 | private volatile HostConnectionPool currentPool; |
| 58 | 58 | private final AtomicReference<QueryState> queryStateRef; |
| 59 | 59 | |
| 60 | + // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from | |
| 61 | + // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an | |
| 62 | + // OVERLOADED error). | |
| 63 | + // This is incremented by one writer at a time, so volatile is good enough. | |
| 64 | + private volatile int retriesByPolicy; | |
| 65 | + | |
| 60 | 66 | private volatile ConsistencyLevel retryConsistencyLevel; |
| 61 | 67 | |
| 62 | 68 | private volatile Map<InetSocketAddress, Throwable> errors; |
| @@ -113,9 +119,7 @@ | ||
| 113 | 119 | |
| 114 | 120 | PooledConnection connection = null; |
| 115 | 121 | try { |
| 116 | - // Note: this is not perfectly correct to use getConnectTimeoutMillis(), but | |
| 117 | - // until we provide a more fancy to control query timeouts, it's not a bad solution either | |
| 118 | - connection = currentPool.borrowConnection(manager.configuration().getSocketOptions().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS); | |
| 122 | + connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS); | |
| 119 | 123 | if (current != null) { |
| 120 | 124 | if (triedHosts == null) |
| 121 | 125 | triedHosts = new ArrayList<Host>(); |
| @@ -134,8 +138,7 @@ | ||
| 134 | 138 | return false; |
| 135 | 139 | } catch (BusyConnectionException e) { |
| 136 | 140 | // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host. |
| 137 | - if (connection != null) | |
| 138 | - connection.release(); | |
| 141 | + connection.release(); | |
| 139 | 142 | logError(host.getSocketAddress(), e); |
| 140 | 143 | return false; |
| 141 | 144 | } catch (TimeoutException e) { |
| @@ -295,7 +298,7 @@ | ||
| 295 | 298 | rte.getRequiredAcknowledgements(), |
| 296 | 299 | rte.getReceivedAcknowledgements(), |
| 297 | 300 | rte.wasDataRetrieved(), |
| 298 | - retryCount); | |
| 301 | + retriesByPolicy); | |
| 299 | 302 | |
| 300 | 303 | if (metricsEnabled()) { |
| 301 | 304 | if (retry.getType() == Type.RETRY) |
| @@ -315,7 +318,7 @@ | ||
| 315 | 318 | wte.getWriteType(), |
| 316 | 319 | wte.getRequiredAcknowledgements(), |
| 317 | 320 | wte.getReceivedAcknowledgements(), |
| 318 | - retryCount); | |
| 321 | + retriesByPolicy); | |
| 319 | 322 | |
| 320 | 323 | if (metricsEnabled()) { |
| 321 | 324 | if (retry.getType() == Type.RETRY) |
| @@ -334,7 +337,7 @@ | ||
| 334 | 337 | ue.getConsistencyLevel(), |
| 335 | 338 | ue.getRequiredReplicas(), |
| 336 | 339 | ue.getAliveReplicas(), |
| 337 | - retryCount); | |
| 340 | + retriesByPolicy); | |
| 338 | 341 | |
| 339 | 342 | if (metricsEnabled()) { |
| 340 | 343 | if (retry.getType() == Type.RETRY) |
| @@ -419,8 +422,9 @@ | ||
| 419 | 422 | else { |
| 420 | 423 | switch (retry.getType()) { |
| 421 | 424 | case RETRY: |
| 425 | + ++retriesByPolicy; | |
| 422 | 426 | if (logger.isDebugEnabled()) |
| 423 | - logger.debug("Doing retry {} for query {} at consistency {}", retryCount, statement, retry.getRetryConsistencyLevel()); | |
| 427 | + logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel()); | |
| 424 | 428 | if (metricsEnabled()) |
| 425 | 429 | metrics().getErrorMetrics().getRetries().inc(); |
| 426 | 430 | retry(true, retry.getRetryConsistencyLevel()); |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +6 −0
| @@ -521,6 +521,12 @@ | ||
| 521 | 521 | return future; |
| 522 | 522 | } |
| 523 | 523 | |
| 524 | + void trashIdleConnections(long now) { | |
| 525 | + for (HostConnectionPool pool : pools.values()) { | |
| 526 | + pool.trashIdleConnections(now); | |
| 527 | + } | |
| 528 | + } | |
| 529 | + | |
| 524 | 530 | private static class State implements Session.State { |
| 525 | 531 | |
| 526 | 532 | private final SessionManager session; |
modified driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +7 −0
| @@ -156,6 +156,9 @@ | ||
| 156 | 156 | } |
| 157 | 157 | |
| 158 | 158 | private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { |
| 159 | + if (timeout == 0) | |
| 160 | + throw new TimeoutException(); | |
| 161 | + | |
| 159 | 162 | long start = System.nanoTime(); |
| 160 | 163 | long remaining = timeout; |
| 161 | 164 | do { |
| @@ -338,6 +341,10 @@ | ||
| 338 | 341 | } |
| 339 | 342 | } |
| 340 | 343 | |
| 344 | + @Override void trashIdleConnections(long now) { | |
| 345 | + // Nothing to do | |
| 346 | + } | |
| 347 | + | |
| 341 | 348 | @Override |
| 342 | 349 | public int opened() { |
| 343 | 350 | return open.get() ? 1 : 0; |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +3 −1
| @@ -200,6 +200,8 @@ | ||
| 200 | 200 | } else if (!dc.equals(localDc)) |
| 201 | 201 | notInLocalDC.add(String.format("%s (%s)", host.toString(), dc)); |
| 202 | 202 | |
| 203 | + if (!dc.equals(localDc)) notInLocalDC.add(String.format("%s (%s)", host.toString(), host.getDatacenter())); | |
| 204 | + | |
| 203 | 205 | CopyOnWriteArrayList<Host> prev = perDcLiveHosts.get(dc); |
| 204 | 206 | if (prev == null) |
| 205 | 207 | perDcLiveHosts.put(dc, new CopyOnWriteArrayList<Host>(Collections.singletonList(host))); |
| @@ -209,7 +211,7 @@ | ||
| 209 | 211 | |
| 210 | 212 | if (notInLocalDC.size() > 0) { |
| 211 | 213 | String nonLocalHosts = Joiner.on(",").join(notInLocalDC); |
| 212 | - logger.warn("Some contact points don't match specified local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts); | |
| 214 | + logger.warn("Some contact points don't match local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts); | |
| 213 | 215 | } |
| 214 | 216 | } |
| 215 | 217 |
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +12 −7
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | // Since we don't open any session from our Cluster, only the control connection reattempts are calling this |
| 24 | 24 | // method, therefore the invocation count is equal to the number of attempts. |
| 25 | 25 | QueryPlanCountingPolicy loadBalancingPolicy = new QueryPlanCountingPolicy(Policies.defaultLoadBalancingPolicy()); |
| 26 | + AtomicInteger reconnectionAttempts = loadBalancingPolicy.counter; | |
| 26 | 27 | |
| 27 | 28 | // Custom reconnection policy with a very large delay (longer than the test duration), to make sure we count |
| 28 | 29 | // only the first reconnection attempt of each reconnection handler. |
| @@ -39,18 +40,23 @@ | ||
| 39 | 40 | }; |
| 40 | 41 | |
| 41 | 42 | try { |
| 42 | - ccm = CCMBridge.create("test", 1); | |
| 43 | + ccm = CCMBridge.create("test", 2); | |
| 44 | + // We pass only the first host as contact point, so we know the control connection will be on this host | |
| 43 | 45 | cluster = Cluster.builder() |
| 44 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 45 | - .withReconnectionPolicy(reconnectionPolicy) | |
| 46 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 47 | - .build(); | |
| 46 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 47 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 48 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 49 | + .build(); | |
| 48 | 50 | cluster.init(); |
| 49 | 51 | |
| 52 | + // Kill the control connection host, there should be exactly one reconnection attempt | |
| 50 | 53 | ccm.stop(1); |
| 54 | + TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing | |
| 55 | + assertThat(reconnectionAttempts.get()).isEqualTo(1); | |
| 51 | 56 | |
| 52 | - // Sleep for a while to make sure our final count is not the result of lucky timing | |
| 57 | + ccm.stop(2); | |
| 53 | 58 | TimeUnit.SECONDS.sleep(1); |
| 59 | + assertThat(reconnectionAttempts.get()).isEqualTo(2); | |
| 54 | 60 | |
| 55 | 61 | } finally { |
| 56 | 62 | if (cluster != null) |
| @@ -58,7 +64,6 @@ | ||
| 58 | 64 | if (ccm != null) |
| 59 | 65 | ccm.remove(); |
| 60 | 66 | } |
| 61 | - assertThat(loadBalancingPolicy.counter.get()).isEqualTo(1); | |
| 62 | 67 | } |
| 63 | 68 | |
| 64 | 69 | /** |
added driver-core/src/test/java/com/datastax/driver/core/DynamicConnectionPoolTimeoutTest.java +183 −0
| @@ -0,0 +1,183 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.net.InetSocketAddress; | |
| 4 | +import java.util.HashSet; | |
| 5 | +import java.util.Set; | |
| 6 | +import java.util.concurrent.TimeUnit; | |
| 7 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 8 | + | |
| 9 | +import com.codahale.metrics.Gauge; | |
| 10 | +import org.testng.annotations.Test; | |
| 11 | + | |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 13 | + | |
| 14 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 15 | +import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 16 | + | |
| 17 | +public class DynamicConnectionPoolTimeoutTest { | |
| 18 | + @Test(groups = "long") | |
| 19 | + public void should_wait_for_idle_timeout_before_trashing_connections() throws Exception { | |
| 20 | + CCMBridge ccm = null; | |
| 21 | + Cluster cluster = null; | |
| 22 | + try { | |
| 23 | + ccm = CCMBridge.create("test"); | |
| 24 | + ccm.populate(1); | |
| 25 | + ccm.updateConfig("authenticator", "PasswordAuthenticator"); | |
| 26 | + ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0"); | |
| 27 | + | |
| 28 | + // Hijack the auth provider to be notified each time a connection instance is built | |
| 29 | + CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra"); | |
| 30 | + AtomicInteger createdConnections = authProvider.newAuthenticatorCount; | |
| 31 | + | |
| 32 | + cluster = Cluster.builder() | |
| 33 | + .withProtocolVersion(ProtocolVersion.V2) // force v2 to use dynamic pool | |
| 34 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 35 | + .withAuthProvider(authProvider) | |
| 36 | + .build(); | |
| 37 | + | |
| 38 | + PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); | |
| 39 | + poolingOptions.setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 1); | |
| 40 | + // Set to the max, which makes it slightly easier to reason about when new connections will be created: | |
| 41 | + poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 128); | |
| 42 | + int idleTimeoutSeconds = 10; | |
| 43 | + poolingOptions.setIdleTimeoutSeconds(idleTimeoutSeconds); | |
| 44 | + | |
| 45 | + Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections(); | |
| 46 | + | |
| 47 | + Session session = cluster.connect(); | |
| 48 | + | |
| 49 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 50 | + HostConnectionPool pool = ((SessionManager)session).pools.get(host1); | |
| 51 | + | |
| 52 | + Set<PooledConnection> coreConnections = new HashSet<PooledConnection>(); | |
| 53 | + | |
| 54 | + // Idle pool: 2 core connections + control connection | |
| 55 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 56 | + assertThat(createdConnections.get()).isEqualTo(3); | |
| 57 | + | |
| 58 | + // Max out the two core connections | |
| 59 | + for (int i = 0; i < 2 * 128; i++) { | |
| 60 | + PooledConnection connection = pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 61 | + coreConnections.add(connection); | |
| 62 | + } | |
| 63 | + | |
| 64 | + assertThat(coreConnections).hasSize(2); | |
| 65 | + | |
| 66 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 67 | + assertThat(createdConnections.get()).isEqualTo(3); | |
| 68 | + | |
| 69 | + // Borrow one more stream, which should spawn a new connection | |
| 70 | + PooledConnection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 71 | + assertThat(coreConnections).doesNotContain(nonCoreConnection); | |
| 72 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 73 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 74 | + | |
| 75 | + // Return the connection, it should not be trashed immediately | |
| 76 | + pool.returnConnection(nonCoreConnection); | |
| 77 | + TimeUnit.SECONDS.sleep(idleTimeoutSeconds / 2); | |
| 78 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 79 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 80 | + | |
| 81 | + // If we borrow again at this point, it should return the same connection | |
| 82 | + PooledConnection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 83 | + assertThat(nonCoreConnection2).isSameAs(nonCoreConnection); | |
| 84 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 85 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 86 | + | |
| 87 | + // Borrow two more and return 1 to reach inFlight = 2 (above the min). The connection should not be trashed. | |
| 88 | + assertThat(pool.borrowConnection(1, TimeUnit.SECONDS)).isSameAs(nonCoreConnection2); | |
| 89 | + assertThat(pool.borrowConnection(1, TimeUnit.SECONDS)).isSameAs(nonCoreConnection2); | |
| 90 | + pool.returnConnection(nonCoreConnection2); // (we need to return one because we cancel the timeout on return) | |
| 91 | + TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2); | |
| 92 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 93 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 94 | + | |
| 95 | + // Return everything for the non-core connection and wait long enough, it should eventually get trashed | |
| 96 | + pool.returnConnection(nonCoreConnection); | |
| 97 | + pool.returnConnection(nonCoreConnection); | |
| 98 | + TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2); | |
| 99 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 100 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 101 | + | |
| 102 | + // Return all the streams of the core connections, they should not get trashed | |
| 103 | + for (PooledConnection coreConnection : coreConnections) | |
| 104 | + for (int i = 0; i < 128; i++) | |
| 105 | + pool.returnConnection(coreConnection); | |
| 106 | + assertThat(session.getState().getInFlightQueries(host1)).isEqualTo(0); | |
| 107 | + | |
| 108 | + TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2); | |
| 109 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 110 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 111 | + | |
| 112 | + } finally { | |
| 113 | + if (cluster != null) | |
| 114 | + cluster.close(); | |
| 115 | + if (ccm != null) | |
| 116 | + ccm.remove(); | |
| 117 | + } | |
| 118 | + } | |
| 119 | + | |
| 120 | + @Test(groups = "short") | |
| 121 | + public void should_timeout_immediately_if_pool_timeout_is_zero() throws Exception { | |
| 122 | + CCMBridge ccm = null; | |
| 123 | + Cluster cluster = null; | |
| 124 | + try { | |
| 125 | + ccm = CCMBridge.create("test", 1); | |
| 126 | + cluster = Cluster.builder() | |
| 127 | + .withProtocolVersion(ProtocolVersion.V2) // force v2 to use dynamic pool | |
| 128 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 129 | + .build(); | |
| 130 | + | |
| 131 | + cluster.getConfiguration().getPoolingOptions() | |
| 132 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) | |
| 133 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 1) | |
| 134 | + .setPoolTimeoutMillis(0); | |
| 135 | + | |
| 136 | + Session session = cluster.connect(); | |
| 137 | + | |
| 138 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 139 | + | |
| 140 | + // Borrow all streams to simulate a busy pool (the timeout doesn't matter here) | |
| 141 | + HostConnectionPool pool = ((SessionManager)session).pools.get(host1); | |
| 142 | + for (int i = 0; i < 128; i++) | |
| 143 | + pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 144 | + | |
| 145 | + boolean threw = false; | |
| 146 | + long beforeQuery = System.nanoTime(); | |
| 147 | + try { | |
| 148 | + session.execute("select release_version from system.local"); | |
| 149 | + } catch (NoHostAvailableException e) { | |
| 150 | + long afterQuery = System.nanoTime(); | |
| 151 | + // This is a bit arbitrary, but we can expect that the time to find out there is no available connection | |
| 152 | + // is less than 20 ms | |
| 153 | + assertThat(afterQuery - beforeQuery).isLessThan(20 * 1000 * 1000); | |
| 154 | + Throwable host1Error = e.getErrors().get(host1.getSocketAddress()); | |
| 155 | + assertThat(host1Error).isInstanceOf(DriverException.class); | |
| 156 | + assertThat(host1Error.getMessage()).contains("Timeout while trying to acquire available connection"); | |
| 157 | + threw = true; | |
| 158 | + } | |
| 159 | + assertThat(threw).isTrue(); | |
| 160 | + } finally { | |
| 161 | + if (cluster != null) | |
| 162 | + cluster.close(); | |
| 163 | + if (ccm != null) | |
| 164 | + ccm.remove(); | |
| 165 | + } | |
| 166 | + } | |
| 167 | + | |
| 168 | + /** | |
| 169 | + * An auth provider that counts how many authenticators it has returned. | |
| 170 | + */ | |
| 171 | + static class CountingAuthProvider extends PlainTextAuthProvider { | |
| 172 | + final AtomicInteger newAuthenticatorCount = new AtomicInteger(); | |
| 173 | + | |
| 174 | + public CountingAuthProvider(String username, String password) { | |
| 175 | + super(username, password); | |
| 176 | + } | |
| 177 | + | |
| 178 | + @Override public Authenticator newAuthenticator(InetSocketAddress host) { | |
| 179 | + newAuthenticatorCount.incrementAndGet(); | |
| 180 | + return super.newAuthenticator(host); | |
| 181 | + } | |
| 182 | + } | |
| 183 | +} | |
| No newline at the end of the file |
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +12 −24
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | package com.datastax.driver.core; |
| 2 | 2 | |
| 3 | +import java.util.concurrent.CountDownLatch; | |
| 3 | 4 | import java.util.concurrent.TimeUnit; |
| 4 | 5 | import java.util.concurrent.atomic.AtomicBoolean; |
| 5 | 6 | |
| @@ -32,24 +33,18 @@ | ||
| 32 | 33 | } |
| 33 | 34 | |
| 34 | 35 | public HostAssert comesUpWithin(long duration, TimeUnit unit) { |
| 35 | - final AtomicBoolean notification = new AtomicBoolean(); | |
| 36 | + final CountDownLatch upSignal = new CountDownLatch(1); | |
| 36 | 37 | StateListener upListener = new StateListenerBase() { |
| 37 | 38 | public void onUp(Host host) { |
| 38 | - notification.set(true); | |
| 39 | - }; | |
| 39 | + upSignal.countDown(); | |
| 40 | + } | |
| 40 | 41 | }; |
| 41 | 42 | cluster.register(upListener); |
| 42 | 43 | try { |
| 43 | - // Make sure the host did not come up while we were installing the listener | |
| 44 | - if (actual.isUp()) | |
| 44 | + // If the host is already up or if we receive the UP signal within given time | |
| 45 | + if (actual.isUp() || upSignal.await(duration, unit)) { | |
| 45 | 46 | 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); | |
| 47 | + } | |
| 53 | 48 | } catch (InterruptedException e) { |
| 54 | 49 | fail("Got interrupted while waiting for host to come up"); |
| 55 | 50 | } finally { |
| @@ -60,24 +55,17 @@ | ||
| 60 | 55 | } |
| 61 | 56 | |
| 62 | 57 | public HostAssert goesDownWithin(long duration, TimeUnit unit) { |
| 63 | - final AtomicBoolean notification = new AtomicBoolean(); | |
| 58 | + final CountDownLatch downSignal = new CountDownLatch(1); | |
| 64 | 59 | StateListener upListener = new StateListenerBase() { |
| 65 | 60 | public void onDown(Host host) { |
| 66 | - notification.set(true); | |
| 67 | - }; | |
| 61 | + downSignal.countDown(); | |
| 62 | + } | |
| 68 | 63 | }; |
| 69 | 64 | cluster.register(upListener); |
| 70 | 65 | try { |
| 71 | - // Make sure the host did not go down while we were installing the listener | |
| 72 | - if (actual.state == State.DOWN) | |
| 66 | + // If the host is already down or if we receive the DOWN signal within given time | |
| 67 | + if (actual.state == State.DOWN || downSignal.await(duration, unit)) | |
| 73 | 68 | 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 | 69 | } catch (InterruptedException e) { |
| 82 | 70 | fail("Got interrupted while waiting for host to go down"); |
| 83 | 71 | } finally { |
added driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +25 −0
| @@ -0,0 +1,25 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.io.StringWriter; | |
| 4 | + | |
| 5 | +import org.apache.log4j.PatternLayout; | |
| 6 | +import org.apache.log4j.WriterAppender; | |
| 7 | + | |
| 8 | +/** | |
| 9 | + * Simple Log4J appender that captures logs to memory in order to inspect them in unit tests. | |
| 10 | + * <p> | |
| 11 | + * There is no purging mechanism, so make sure it doesn't stay enabled for too long (this is best | |
| 12 | + * done with an {@code @After} method that removes it). | |
| 13 | + */ | |
| 14 | +public class MemoryAppender extends WriterAppender { | |
| 15 | + public final StringWriter writer = new StringWriter(); | |
| 16 | + | |
| 17 | + public MemoryAppender() { | |
| 18 | + setWriter(writer); | |
| 19 | + setLayout(new PatternLayout("%m%n")); | |
| 20 | + } | |
| 21 | + | |
| 22 | + public String get() { | |
| 23 | + return writer.toString(); | |
| 24 | + } | |
| 25 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +1 −1
| @@ -69,7 +69,7 @@ | ||
| 69 | 69 | |
| 70 | 70 | // Kill host 2, host 3 should take its place |
| 71 | 71 | ccm.stop(2); |
| 72 | - TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster); | |
| 72 | + TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster, 120); | |
| 73 | 73 | |
| 74 | 74 | assertThat(cluster).host(1) |
| 75 | 75 | .hasState(State.UP) |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +162 −18
| @@ -1,42 +1,186 @@ | ||
| 1 | 1 | package com.datastax.driver.core.policies; |
| 2 | 2 | |
| 3 | -import org.testng.annotations.Test; | |
| 3 | +import java.util.Collection; | |
| 4 | +import java.util.Set; | |
| 5 | +import java.util.concurrent.CopyOnWriteArraySet; | |
| 6 | + | |
| 7 | +import org.apache.log4j.Level; | |
| 8 | +import org.apache.log4j.Logger; | |
| 9 | +import org.testng.annotations.*; | |
| 10 | + | |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 4 | 12 | import static org.testng.Assert.assertEquals; |
| 5 | 13 | |
| 6 | -import com.datastax.driver.core.CCMBridge; | |
| 7 | -import com.datastax.driver.core.Cluster; | |
| 8 | -import com.datastax.driver.core.Host; | |
| 9 | -import com.datastax.driver.core.TestUtils; | |
| 14 | +import com.datastax.driver.core.*; | |
| 10 | 15 | |
| 11 | 16 | public class DCAwareRoundRobinPolicyTest { |
| 17 | + MemoryAppender logs; | |
| 18 | + CCMBridge ccm; | |
| 19 | + | |
| 20 | + @BeforeClass(groups = "short") | |
| 21 | + public void createCcm() { | |
| 22 | + // Two-DC cluster with one host in each DC | |
| 23 | + ccm = CCMBridge.create("test", 1, 1); | |
| 24 | + } | |
| 25 | + | |
| 26 | + @AfterClass(groups = "short") | |
| 27 | + public void deleteCcm() { | |
| 28 | + if (ccm != null) | |
| 29 | + ccm.remove(); | |
| 30 | + } | |
| 31 | + | |
| 32 | + @BeforeMethod(groups = "short") | |
| 33 | + public void startRecordingLogs() { | |
| 34 | + Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class); | |
| 35 | + assertThat(Level.WARN.isGreaterOrEqual(policyLogger.getEffectiveLevel())) | |
| 36 | + .isTrue() | |
| 37 | + .as("Log level must be at least WARN for this test to work"); | |
| 38 | + | |
| 39 | + logs = new MemoryAppender(); | |
| 40 | + policyLogger.addAppender(logs); | |
| 41 | + } | |
| 42 | + | |
| 43 | + @AfterMethod(groups = "short") | |
| 44 | + public void stopRecordingLogs() { | |
| 45 | + Logger.getLogger(DCAwareRoundRobinPolicy.class).removeAppender(logs); | |
| 46 | + } | |
| 12 | 47 | |
| 13 | 48 | @Test(groups = "short") |
| 14 | - public void should_pick_local_dc_from_contact_points() { | |
| 15 | - CCMBridge ccm = null; | |
| 49 | + public void should_use_local_dc_from_contact_points_when_not_explicitly_specified() { | |
| 16 | 50 | Cluster cluster = null; |
| 17 | - DCAwareRoundRobinPolicy policy; | |
| 51 | + CountingDCAwarePolicy policy = new CountingDCAwarePolicy(); | |
| 18 | 52 | |
| 19 | 53 | try { |
| 20 | - // Create two-DC cluster with one host in each DC | |
| 21 | - ccm = CCMBridge.create("test", 1, 1); | |
| 22 | - policy = new DCAwareRoundRobinPolicy(); | |
| 23 | - | |
| 24 | 54 | // Pass host1 as contact point |
| 25 | 55 | cluster = Cluster.builder() |
| 26 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 27 | - .withLoadBalancingPolicy(policy) | |
| 28 | - .build(); | |
| 56 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 57 | + .withLoadBalancingPolicy(policy) | |
| 58 | + .build(); | |
| 29 | 59 | cluster.init(); |
| 30 | 60 | |
| 61 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 62 | + | |
| 31 | 63 | // Policy's localDC should be the one from the contact point |
| 64 | + assertThat(policy.getLocalDc()).isEqualTo(host1.getDatacenter()); | |
| 65 | + | |
| 66 | + assertThat(policy.initHosts).containsExactly(host1); | |
| 67 | + | |
| 68 | + assertThat(logs.get()) | |
| 69 | + .doesNotContain("Some contact points don't match local data center"); | |
| 70 | + | |
| 71 | + } finally { | |
| 72 | + if (cluster != null) | |
| 73 | + cluster.close(); | |
| 74 | + } | |
| 75 | + } | |
| 76 | + | |
| 77 | + @Test(groups = "short") | |
| 78 | + public void should_warn_if_contact_points_have_different_dcs_when_not_explicitly_specified() { | |
| 79 | + Cluster cluster = null; | |
| 80 | + CountingDCAwarePolicy policy = new CountingDCAwarePolicy(); | |
| 81 | + | |
| 82 | + try { | |
| 83 | + // Pass both hosts as contact points, they have different DCs | |
| 84 | + cluster = Cluster.builder() | |
| 85 | + .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2)) | |
| 86 | + .withLoadBalancingPolicy(policy) | |
| 87 | + .build(); | |
| 88 | + cluster.init(); | |
| 89 | + | |
| 90 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 91 | + Host host2 = TestUtils.findHost(cluster, 2); | |
| 92 | + | |
| 93 | + assertThat(policy.initHosts).containsOnly(host1, host2); | |
| 94 | + | |
| 95 | + assertThat(logs.get()) | |
| 96 | + .contains("Some contact points don't match local data center"); | |
| 97 | + | |
| 98 | + } finally { | |
| 99 | + if (cluster != null) | |
| 100 | + cluster.close(); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + | |
| 104 | + @Test(groups = "short") | |
| 105 | + public void should_use_provided_local_dc_and_not_warn_if_contact_points_match() { | |
| 106 | + Cluster cluster = null; | |
| 107 | + String providedLocalDc = "dc1"; | |
| 108 | + CountingDCAwarePolicy policy = new CountingDCAwarePolicy(providedLocalDc); | |
| 109 | + | |
| 110 | + try { | |
| 111 | + cluster = Cluster.builder() | |
| 112 | + .addContactPoints(CCMBridge.ipOfNode(1)) | |
| 113 | + .withLoadBalancingPolicy(policy) | |
| 114 | + .build(); | |
| 115 | + cluster.init(); | |
| 116 | + | |
| 117 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 118 | + | |
| 119 | + assertEquals(policy.getLocalDc(), providedLocalDc); | |
| 120 | + | |
| 121 | + assertThat(policy.initHosts).containsExactly(host1); | |
| 122 | + | |
| 123 | + assertThat(logs.get()) | |
| 124 | + .doesNotContain("Some contact points don't match local data center"); | |
| 125 | + | |
| 126 | + } finally { | |
| 127 | + if (cluster != null) | |
| 128 | + cluster.close(); | |
| 129 | + } | |
| 130 | + } | |
| 131 | + | |
| 132 | + @Test(groups = "short") | |
| 133 | + public void should_use_provided_local_dc_and_warn_if_contact_points_dont_match() { | |
| 134 | + Cluster cluster = null; | |
| 135 | + // Provide non-existent DC to make sure none of the contact points matches | |
| 136 | + String providedLocalDc = "dc3"; | |
| 137 | + CountingDCAwarePolicy policy = new CountingDCAwarePolicy(providedLocalDc); | |
| 138 | + | |
| 139 | + try { | |
| 140 | + cluster = Cluster.builder() | |
| 141 | + .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2)) | |
| 142 | + .withLoadBalancingPolicy(policy) | |
| 143 | + .build(); | |
| 144 | + cluster.init(); | |
| 145 | + | |
| 32 | 146 | Host host1 = TestUtils.findHost(cluster, 1); |
| 33 | - assertEquals(policy.localDc, host1.getDatacenter()); | |
| 147 | + Host host2 = TestUtils.findHost(cluster, 2); | |
| 148 | + | |
| 149 | + assertEquals(policy.getLocalDc(), providedLocalDc); | |
| 150 | + | |
| 151 | + assertThat(policy.initHosts).containsOnly(host1, host2); | |
| 152 | + | |
| 153 | + assertThat(logs.get()) | |
| 154 | + .contains("Some contact points don't match local data center"); | |
| 34 | 155 | |
| 35 | 156 | } finally { |
| 36 | 157 | if (cluster != null) |
| 37 | 158 | cluster.close(); |
| 38 | - if (ccm != null) | |
| 39 | - ccm.remove(); | |
| 159 | + } | |
| 160 | + } | |
| 161 | + | |
| 162 | + /** | |
| 163 | + * Wraps the policy under test to spy the calls to init. | |
| 164 | + */ | |
| 165 | + static class CountingDCAwarePolicy extends DelegatingLoadBalancingPolicy { | |
| 166 | + Set<Host> initHosts = new CopyOnWriteArraySet<Host>(); | |
| 167 | + | |
| 168 | + CountingDCAwarePolicy() { | |
| 169 | + super(new DCAwareRoundRobinPolicy()); | |
| 170 | + } | |
| 171 | + | |
| 172 | + CountingDCAwarePolicy(String localDc) { | |
| 173 | + super(new DCAwareRoundRobinPolicy(localDc)); | |
| 174 | + } | |
| 175 | + | |
| 176 | + String getLocalDc() { | |
| 177 | + return ((DCAwareRoundRobinPolicy) delegate).localDc; | |
| 178 | + } | |
| 179 | + | |
| 180 | + @Override public void init(Cluster cluster, Collection<Host> hosts) { | |
| 181 | + System.out.println("init " + hosts); | |
| 182 | + initHosts.addAll(hosts); | |
| 183 | + super.init(cluster, hosts); | |
| 40 | 184 | } |
| 41 | 185 | } |
| 42 | 186 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java +3 −2
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | package com.datastax.driver.core.policies; |
| 2 | 2 | |
| 3 | 3 | import java.util.*; |
| 4 | +import java.util.concurrent.ConcurrentHashMap; | |
| 4 | 5 | import java.util.concurrent.locks.Lock; |
| 5 | 6 | import java.util.concurrent.locks.ReentrantLock; |
| 6 | 7 | |
| @@ -25,8 +26,8 @@ | ||
| 25 | 26 | public class LimitingLoadBalancingPolicy extends DelegatingLoadBalancingPolicy { |
| 26 | 27 | private final int maxHosts; |
| 27 | 28 | private final int threshold; |
| 28 | - private final Set<Host> liveHosts = Sets.newConcurrentHashSet(); | |
| 29 | - private final Set<Host> chosenHosts = Sets.newConcurrentHashSet(); | |
| 29 | + private final Set<Host> liveHosts = Sets.newSetFromMap(new ConcurrentHashMap<Host, Boolean>()); | |
| 30 | + private final Set<Host> chosenHosts = Sets.newSetFromMap(new ConcurrentHashMap<Host, Boolean>()); | |
| 30 | 31 | private final Lock updateLock = new ReentrantLock(); |
| 31 | 32 | |
| 32 | 33 | private volatile Cluster cluster; |
modified src/main/config/ide/intellij-code-style.jar +0 −0
Binary content is not shown. View the file.