kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | e742462cc4ae21289352bdf2500a7198eadba80fb5344c63d80fce4570ddc71d |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2015-07-13 16:23 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-08-14 18:54 +02:00 |
| Parents | dc07c7b283df |
17 files changed
modified changelog/README.md +1 −0
| @@ -35,6 +35,7 @@ | ||
| 35 | 35 | - [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658) |
| 36 | 36 | - [improvement] Customizable creation of netty timer (JAVA-853) |
| 37 | 37 | - [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859) |
| 38 | +- [improvement] Debounce control connection queries (JAVA-657) | |
| 38 | 39 | |
| 39 | 40 | Merged from 2.0.10_fixes branch: |
| 40 | 41 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +318 −90
| @@ -37,6 +37,7 @@ | ||
| 37 | 37 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 38 | 38 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 39 | 39 | import com.datastax.driver.core.policies.*; |
| 40 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 40 | 41 | |
| 41 | 42 | /** |
| 42 | 43 | * Information and known state of a Cassandra cluster. |
| @@ -1243,6 +1244,10 @@ | ||
| 1243 | 1244 | final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>(); |
| 1244 | 1245 | final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>(); |
| 1245 | 1246 | |
| 1247 | + EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer; | |
| 1248 | + EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer; | |
| 1249 | + EventDebouncer<SchemaRefreshRequest> schemaRefreshRequestDebouncer; | |
| 1250 | + | |
| 1246 | 1251 | private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) { |
| 1247 | 1252 | this.clusterName = clusterName == null ? generateClusterName() : clusterName; |
| 1248 | 1253 | this.configuration = configuration; |
| @@ -1278,8 +1283,28 @@ | ||
| 1278 | 1283 | this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this); |
| 1279 | 1284 | this.preparedQueries = new MapMaker().weakValues().makeMap(); |
| 1280 | 1285 | |
| 1281 | - this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1286 | + // create debouncers - at this stage, they are not running yet | |
| 1287 | + QueryOptions queryOptions = configuration.getQueryOptions(); | |
| 1288 | + this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>( | |
| 1289 | + "Node list refresh", | |
| 1290 | + scheduledTasksExecutor, | |
| 1291 | + new NodeListRefreshRequestDeliveryCallback(), | |
| 1292 | + queryOptions.getRefreshNodeListIntervalMillis(), | |
| 1293 | + queryOptions.getMaxPendingRefreshNodeListRequests()); | |
| 1294 | + this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>( | |
| 1295 | + "Node refresh", | |
| 1296 | + scheduledTasksExecutor, | |
| 1297 | + new NodeRefreshRequestDeliveryCallback(), | |
| 1298 | + queryOptions.getRefreshNodeIntervalMillis(), | |
| 1299 | + queryOptions.getMaxPendingRefreshNodeRequests()); | |
| 1300 | + this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>( | |
| 1301 | + "Schema refresh", | |
| 1302 | + scheduledTasksExecutor, | |
| 1303 | + new SchemaRefreshRequestDeliveryCallback(), | |
| 1304 | + queryOptions.getRefreshSchemaIntervalMillis(), | |
| 1305 | + queryOptions.getMaxPendingRefreshSchemaRequests()); | |
| 1282 | 1306 | |
| 1307 | + this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1283 | 1308 | |
| 1284 | 1309 | for (InetSocketAddress address : contactPoints) { |
| 1285 | 1310 | // We don't want to signal -- call onAdd() -- because nothing is ready |
| @@ -1353,6 +1378,12 @@ | ||
| 1353 | 1378 | for (Host.StateListener listener : listeners) |
| 1354 | 1379 | listener.onAdd(host); |
| 1355 | 1380 | } |
| 1381 | + | |
| 1382 | + // start debouncers | |
| 1383 | + this.nodeListRefreshRequestDebouncer.start(); | |
| 1384 | + this.schemaRefreshRequestDebouncer.start(); | |
| 1385 | + this.nodeRefreshRequestDebouncer.start(); | |
| 1386 | + | |
| 1356 | 1387 | isFullyInit = true; |
| 1357 | 1388 | |
| 1358 | 1389 | return; |
| @@ -1442,6 +1473,11 @@ | ||
| 1442 | 1473 | if (isInit) { |
| 1443 | 1474 | logger.debug("Shutting down"); |
| 1444 | 1475 | |
| 1476 | + // stop debouncers | |
| 1477 | + nodeListRefreshRequestDebouncer.stop(); | |
| 1478 | + nodeRefreshRequestDebouncer.stop(); | |
| 1479 | + schemaRefreshRequestDebouncer.stop(); | |
| 1480 | + | |
| 1445 | 1481 | // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications |
| 1446 | 1482 | // delivery or blocking tasks so we use shutdownNow |
| 1447 | 1483 | shutdownNow(reconnectionExecutor); |
| @@ -1994,7 +2030,7 @@ | ||
| 1994 | 2030 | : reusedConnection; |
| 1995 | 2031 | |
| 1996 | 2032 | try { |
| 1997 | - ControlConnection.waitForSchemaAgreement(connection, this); | |
| 2033 | + controlConnection.waitForSchemaAgreement(); | |
| 1998 | 2034 | } catch (ExecutionException e) { |
| 1999 | 2035 | // As below, just move on |
| 2000 | 2036 | } |
| @@ -2058,14 +2094,21 @@ | ||
| 2058 | 2094 | } |
| 2059 | 2095 | } |
| 2060 | 2096 | |
| 2061 | - public void submitSchemaRefresh(final String keyspace, final String table) { | |
| 2062 | - logger.trace("Submitting schema refresh"); | |
| 2063 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2064 | - @Override | |
| 2065 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2066 | - controlConnection.refreshSchema(keyspace, table); | |
| 2067 | - } | |
| 2068 | - }); | |
| 2097 | + ListenableFuture<Void> submitSchemaRefresh(String keyspace, String table) { | |
| 2098 | + SchemaRefreshRequest request = new SchemaRefreshRequest(keyspace, table); | |
| 2099 | + logger.trace("Submitting schema refresh: {}", request); | |
| 2100 | + return schemaRefreshRequestDebouncer.eventReceived(request); | |
| 2101 | + } | |
| 2102 | + | |
| 2103 | + void submitNodeListRefresh() { | |
| 2104 | + logger.trace("Submitting node list and token map refresh"); | |
| 2105 | + nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest()); | |
| 2106 | + } | |
| 2107 | + | |
| 2108 | + void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) { | |
| 2109 | + NodeRefreshRequest request = new NodeRefreshRequest(address, eventType); | |
| 2110 | + logger.trace("Submitting node refresh: {}", request); | |
| 2111 | + nodeRefreshRequestDebouncer.eventReceived(request); | |
| 2069 | 2112 | } |
| 2070 | 2113 | |
| 2071 | 2114 | // refresh the schema using the provided connection, and notice the future with the provided resultset once done |
| @@ -2090,20 +2133,23 @@ | ||
| 2090 | 2133 | try { |
| 2091 | 2134 | // Before refreshing the schema, wait for schema agreement so |
| 2092 | 2135 | // that querying a table just after having created it don't fail. |
| 2093 | - schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this); | |
| 2136 | + schemaInAgreement = controlConnection.waitForSchemaAgreement(); | |
| 2094 | 2137 | if (!schemaInAgreement) |
| 2095 | 2138 | logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); |
| 2096 | - if (refreshSchema) | |
| 2097 | - ControlConnection.refreshSchema(connection, keyspace, table, Manager.this, false); | |
| 2139 | + | |
| 2140 | + ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(keyspace, table) : MoreFutures.VOID_SUCCESS; | |
| 2141 | + final boolean finalSchemaInAgreement = schemaInAgreement; | |
| 2142 | + schemaReady.addListener(new Runnable() { | |
| 2143 | + @Override | |
| 2144 | + public void run() { | |
| 2145 | + rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement); | |
| 2146 | + future.setResult(rs); | |
| 2147 | + } | |
| 2148 | + }, MoreExecutors.sameThreadExecutor()); | |
| 2149 | + | |
| 2098 | 2150 | } catch (Exception e) { |
| 2099 | - if (refreshSchema) { | |
| 2100 | - logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage()); | |
| 2101 | - submitSchemaRefresh(keyspace, table); | |
| 2102 | - } else { | |
| 2103 | - logger.warn("Error while waiting for schema agreement", e); | |
| 2104 | - } | |
| 2105 | - } finally { | |
| 2106 | - // Always sets the result, but remember if we reached schema agreement | |
| 2151 | + logger.warn("Error while waiting for schema agreement", e); | |
| 2152 | + // This is not fatal, complete the future anyway | |
| 2107 | 2153 | rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); |
| 2108 | 2154 | future.setResult(rs); |
| 2109 | 2155 | } |
| @@ -2131,36 +2177,13 @@ | ||
| 2131 | 2177 | InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress()); |
| 2132 | 2178 | switch (tpc.change) { |
| 2133 | 2179 | case NEW_NODE: |
| 2134 | - final Host newHost = metadata.add(tpAddr); | |
| 2135 | - if (newHost != null) { | |
| 2136 | - // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once | |
| 2137 | - // gossip is up, but that is before the client-side server is up), so we add a delay | |
| 2138 | - // (otherwise the connection will likely fail and have to be retry which is wasteful). This | |
| 2139 | - // probably should be fixed C* side, after which we'll be able to remove this. | |
| 2140 | - scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2141 | - @Override | |
| 2142 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2143 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2144 | - // catch that an upgraded node uses a new cassandra version). | |
| 2145 | - if (controlConnection.refreshNodeInfo(newHost)) { | |
| 2146 | - onAdd(newHost, null); | |
| 2147 | - } else { | |
| 2148 | - logger.debug("Not enough info for {}, ignoring host", newHost); | |
| 2149 | - } | |
| 2150 | - } | |
| 2151 | - }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2152 | - } | |
| 2180 | + submitNodeRefresh(tpAddr, HostEvent.ADDED); | |
| 2153 | 2181 | break; |
| 2154 | 2182 | case REMOVED_NODE: |
| 2155 | - removeHost(metadata.getHost(tpAddr), false); | |
| 2183 | + submitNodeRefresh(tpAddr, HostEvent.REMOVED); | |
| 2156 | 2184 | break; |
| 2157 | 2185 | case MOVED_NODE: |
| 2158 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2159 | - @Override | |
| 2160 | - public void runMayThrow() { | |
| 2161 | - controlConnection.refreshNodeListAndTokenMap(); | |
| 2162 | - } | |
| 2163 | - }); | |
| 2186 | + submitNodeListRefresh(); | |
| 2164 | 2187 | break; |
| 2165 | 2188 | } |
| 2166 | 2189 | break; |
| @@ -2169,51 +2192,10 @@ | ||
| 2169 | 2192 | InetSocketAddress stAddr = translateAddress(stc.node.getAddress()); |
| 2170 | 2193 | switch (stc.status) { |
| 2171 | 2194 | case UP: |
| 2172 | - final Host hostUp = metadata.getHost(stAddr); | |
| 2173 | - if (hostUp == null) { | |
| 2174 | - final Host h = metadata.add(stAddr); | |
| 2175 | - // If hostUp is still null, it means we didn't knew about it the line before but | |
| 2176 | - // got beaten at adding it to the metadata by another thread. In that case, it's | |
| 2177 | - // fine to let the other thread win and ignore the notification here | |
| 2178 | - if (h == null) | |
| 2179 | - return; | |
| 2180 | - | |
| 2181 | - // See NEW_NODE above | |
| 2182 | - scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2183 | - @Override | |
| 2184 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2185 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2186 | - // catch that an upgraded node uses a new cassandra version). | |
| 2187 | - if (controlConnection.refreshNodeInfo(h)) { | |
| 2188 | - onAdd(h, null); | |
| 2189 | - } else { | |
| 2190 | - logger.debug("Not enough info for {}, ignoring host", h); | |
| 2191 | - } | |
| 2192 | - } | |
| 2193 | - }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2194 | - } else { | |
| 2195 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2196 | - @Override | |
| 2197 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2198 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2199 | - // catch that an upgraded node uses a new cassandra version). | |
| 2200 | - if (controlConnection.refreshNodeInfo(hostUp)) { | |
| 2201 | - onUp(hostUp, null); | |
| 2202 | - } else { | |
| 2203 | - logger.debug("Not enough info for {}, ignoring host", hostUp); | |
| 2204 | - } | |
| 2205 | - } | |
| 2206 | - }); | |
| 2207 | - } | |
| 2195 | + submitNodeRefresh(stAddr, HostEvent.UP); | |
| 2208 | 2196 | break; |
| 2209 | 2197 | case DOWN: |
| 2210 | - // Note that there is a slight risk we can receive the event late and thus | |
| 2211 | - // mark the host down even though we already had reconnected successfully. | |
| 2212 | - // But it is unlikely, and don't have too much consequence since we'll try reconnecting | |
| 2213 | - // right away, so we favor the detection to make the Host.isUp method more reliable. | |
| 2214 | - Host hostDown = metadata.getHost(stAddr); | |
| 2215 | - if (hostDown != null) | |
| 2216 | - triggerOnDown(hostDown, true); | |
| 2198 | + submitNodeRefresh(stAddr, HostEvent.DOWN); | |
| 2217 | 2199 | break; |
| 2218 | 2200 | } |
| 2219 | 2201 | break; |
| @@ -2349,6 +2331,252 @@ | ||
| 2349 | 2331 | } |
| 2350 | 2332 | } |
| 2351 | 2333 | } |
| 2334 | + | |
| 2335 | + private class SchemaRefreshRequest { | |
| 2336 | + | |
| 2337 | + private final String keyspace; | |
| 2338 | + | |
| 2339 | + private final String table; | |
| 2340 | + | |
| 2341 | + SchemaRefreshRequest(String keyspace, String table) { | |
| 2342 | + this.keyspace = keyspace; | |
| 2343 | + this.table = table; | |
| 2344 | + } | |
| 2345 | + | |
| 2346 | + /** | |
| 2347 | + * Coalesce schema refresh requests. | |
| 2348 | + * The algorithm is simple: if more than 2 keyspaces | |
| 2349 | + * need refresh, then refresh the entire schema; | |
| 2350 | + * otherwise if more than 2 tables in the same keyspace | |
| 2351 | + * need refresh, then refresh the entire keyspace. | |
| 2352 | + * | |
| 2353 | + * @param that the other request to merge with the current one. | |
| 2354 | + * @return A coalesced request | |
| 2355 | + */ | |
| 2356 | + SchemaRefreshRequest coalesce(SchemaRefreshRequest that) { | |
| 2357 | + if(this.keyspace == null || that.keyspace == null) | |
| 2358 | + return new SchemaRefreshRequest(null, null); | |
| 2359 | + if(!this.keyspace.equals(that.keyspace)) | |
| 2360 | + return new SchemaRefreshRequest(null, null); | |
| 2361 | + if(this.table == null || that.table == null) | |
| 2362 | + return new SchemaRefreshRequest(keyspace, null); | |
| 2363 | + if(!this.table.equals(that.table)) | |
| 2364 | + return new SchemaRefreshRequest(keyspace, null); | |
| 2365 | + return this; | |
| 2366 | + } | |
| 2367 | + | |
| 2368 | + @Override | |
| 2369 | + public String toString() { | |
| 2370 | + if(this.keyspace == null) | |
| 2371 | + return "Refresh ALL"; | |
| 2372 | + if(this.table == null) | |
| 2373 | + return "Refresh keyspace " + keyspace; | |
| 2374 | + return "Refresh keyspace " + keyspace + " table " + table; | |
| 2375 | + } | |
| 2376 | + } | |
| 2377 | + | |
| 2378 | + private class SchemaRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<SchemaRefreshRequest> { | |
| 2379 | + | |
| 2380 | + @Override | |
| 2381 | + public ListenableFuture<?> deliver(final List<SchemaRefreshRequest> events) { | |
| 2382 | + return executor.submit(new ExceptionCatchingRunnable() { | |
| 2383 | + @Override | |
| 2384 | + public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2385 | + SchemaRefreshRequest coalesced = null; | |
| 2386 | + for (SchemaRefreshRequest request : events) { | |
| 2387 | + coalesced = coalesced == null ? request : coalesced.coalesce(request); | |
| 2388 | + } | |
| 2389 | + assert coalesced != null; | |
| 2390 | + logger.trace("Coalesced schema refresh request: {}", coalesced); | |
| 2391 | + controlConnection.refreshSchema(coalesced.keyspace, coalesced.table); | |
| 2392 | + } | |
| 2393 | + }); | |
| 2394 | + } | |
| 2395 | + | |
| 2396 | + } | |
| 2397 | + | |
| 2398 | + private class NodeRefreshRequest { | |
| 2399 | + | |
| 2400 | + private final InetSocketAddress address; | |
| 2401 | + | |
| 2402 | + private final HostEvent eventType; | |
| 2403 | + | |
| 2404 | + private NodeRefreshRequest(InetSocketAddress address, HostEvent eventType) { | |
| 2405 | + this.address = address; | |
| 2406 | + this.eventType = eventType; | |
| 2407 | + } | |
| 2408 | + | |
| 2409 | + @Override | |
| 2410 | + public String toString() { | |
| 2411 | + return address + " " + eventType; | |
| 2412 | + } | |
| 2413 | + | |
| 2414 | + } | |
| 2415 | + | |
| 2416 | + private class NodeRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeRefreshRequest> { | |
| 2417 | + | |
| 2418 | + @Override | |
| 2419 | + public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { | |
| 2420 | + Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>(); | |
| 2421 | + // only keep the last event for each host | |
| 2422 | + for (NodeRefreshRequest req : events) { | |
| 2423 | + hosts.put(req.address, req.eventType); | |
| 2424 | + } | |
| 2425 | + List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); | |
| 2426 | + for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) { | |
| 2427 | + InetSocketAddress address = entry.getKey(); | |
| 2428 | + HostEvent eventType = entry.getValue(); | |
| 2429 | + switch (eventType) { | |
| 2430 | + case UP: | |
| 2431 | + Host upHost = metadata.getHost(address); | |
| 2432 | + if (upHost == null) { | |
| 2433 | + upHost = metadata.add(address); | |
| 2434 | + // If upHost is still null, it means we didn't know about it the line before but | |
| 2435 | + // got beaten at adding it to the metadata by another thread. In that case, it's | |
| 2436 | + // fine to let the other thread win and ignore the notification here | |
| 2437 | + if (upHost == null) | |
| 2438 | + continue; | |
| 2439 | + futures.add(schedule(hostAdded(upHost))); | |
| 2440 | + } else { | |
| 2441 | + futures.add(schedule(hostUp(upHost))); | |
| 2442 | + } | |
| 2443 | + break; | |
| 2444 | + case ADDED: | |
| 2445 | + Host newHost = metadata.add(address); | |
| 2446 | + if (newHost != null) | |
| 2447 | + futures.add(schedule(hostAdded(newHost))); | |
| 2448 | + break; | |
| 2449 | + case DOWN: | |
| 2450 | + // Note that there is a slight risk we can receive the event late and thus | |
| 2451 | + // mark the host down even though we already had reconnected successfully. | |
| 2452 | + // But it is unlikely, and don't have too much consequence since we'll try reconnecting | |
| 2453 | + // right away, so we favor the detection to make the Host.isUp method more reliable. | |
| 2454 | + Host downHost = metadata.getHost(address); | |
| 2455 | + if (downHost != null) | |
| 2456 | + futures.add(execute(hostDown(downHost))); | |
| 2457 | + break; | |
| 2458 | + case REMOVED: | |
| 2459 | + Host removedHost = metadata.getHost(address); | |
| 2460 | + if (removedHost != null) | |
| 2461 | + futures.add(execute(hostRemoved(removedHost))); | |
| 2462 | + break; | |
| 2463 | + } | |
| 2464 | + } | |
| 2465 | + return Futures.allAsList(futures); | |
| 2466 | + } | |
| 2467 | + | |
| 2468 | + private ListenableFuture<?> execute(ExceptionCatchingRunnable task) { | |
| 2469 | + return executor.submit(task); | |
| 2470 | + } | |
| 2471 | + | |
| 2472 | + private ListenableFuture<?> schedule(final ExceptionCatchingRunnable task) { | |
| 2473 | + // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once | |
| 2474 | + // gossip is up, but that is before the client-side server is up), so we add a delay | |
| 2475 | + // (otherwise the connection will likely fail and have to be retry which is wasteful). This | |
| 2476 | + // probably should be fixed C* side, after which we'll be able to remove this. | |
| 2477 | + final SettableFuture<?> future = SettableFuture.create(); | |
| 2478 | + scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2479 | + public void runMayThrow() throws Exception { | |
| 2480 | + ListenableFuture<?> f = execute(task); | |
| 2481 | + Futures.addCallback(f, new FutureCallback<Object>() { | |
| 2482 | + @Override | |
| 2483 | + public void onSuccess(Object result) { | |
| 2484 | + future.set(null); | |
| 2485 | + } | |
| 2486 | + | |
| 2487 | + @Override | |
| 2488 | + public void onFailure(Throwable t) { | |
| 2489 | + future.setException(t); | |
| 2490 | + } | |
| 2491 | + }); | |
| 2492 | + } | |
| 2493 | + }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2494 | + return future; | |
| 2495 | + } | |
| 2496 | + | |
| 2497 | + // Make sure we call controlConnection.refreshNodeInfo(host) | |
| 2498 | + // so that we have up-to-date infos on that host before adding it (so we typically | |
| 2499 | + // catch that an upgraded node uses a new cassandra version). | |
| 2500 | + | |
| 2501 | + private ExceptionCatchingRunnable hostAdded(final Host host) { | |
| 2502 | + return new ExceptionCatchingRunnable() { | |
| 2503 | + @Override | |
| 2504 | + public void runMayThrow() throws Exception { | |
| 2505 | + if (controlConnection.refreshNodeInfo(host)) { | |
| 2506 | + onAdd(host, null); | |
| 2507 | + } else { | |
| 2508 | + logger.debug("Not enough info for {}, ignoring host", host); | |
| 2509 | + } | |
| 2510 | + } | |
| 2511 | + }; | |
| 2512 | + } | |
| 2513 | + | |
| 2514 | + private ExceptionCatchingRunnable hostUp(final Host host) { | |
| 2515 | + return new ExceptionCatchingRunnable() { | |
| 2516 | + @Override | |
| 2517 | + public void runMayThrow() throws Exception { | |
| 2518 | + if (controlConnection.refreshNodeInfo(host)) { | |
| 2519 | + onUp(host, null); | |
| 2520 | + } else { | |
| 2521 | + logger.debug("Not enough info for {}, ignoring host", host); | |
| 2522 | + } | |
| 2523 | + } | |
| 2524 | + }; | |
| 2525 | + } | |
| 2526 | + | |
| 2527 | + private ExceptionCatchingRunnable hostDown(final Host host) { | |
| 2528 | + return new ExceptionCatchingRunnable() { | |
| 2529 | + @Override | |
| 2530 | + public void runMayThrow() throws Exception { | |
| 2531 | + if (controlConnection.refreshNodeInfo(host)) { | |
| 2532 | + onDown(host, false, true); | |
| 2533 | + } else { | |
| 2534 | + logger.debug("Not enough info for {}, ignoring host", host); | |
| 2535 | + } | |
| 2536 | + } | |
| 2537 | + }; | |
| 2538 | + } | |
| 2539 | + | |
| 2540 | + private ExceptionCatchingRunnable hostRemoved(final Host host) { | |
| 2541 | + return new ExceptionCatchingRunnable() { | |
| 2542 | + @Override | |
| 2543 | + public void runMayThrow() throws Exception { | |
| 2544 | + if (metadata.remove(host)) { | |
| 2545 | + logger.info("Cassandra host {} removed", host); | |
| 2546 | + onRemove(host); | |
| 2547 | + } | |
| 2548 | + } | |
| 2549 | + }; | |
| 2550 | + } | |
| 2551 | + | |
| 2552 | + } | |
| 2553 | + | |
| 2554 | + private class NodeListRefreshRequest { | |
| 2555 | + @Override | |
| 2556 | + public String toString() { | |
| 2557 | + return "Refresh node list and token map"; | |
| 2558 | + } | |
| 2559 | + } | |
| 2560 | + | |
| 2561 | + private class NodeListRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeListRefreshRequest> { | |
| 2562 | + | |
| 2563 | + @Override | |
| 2564 | + public ListenableFuture<?> deliver(List<NodeListRefreshRequest> events) { | |
| 2565 | + // The number of received requests does not matter | |
| 2566 | + // as long as one request is made, refresh the entire node list | |
| 2567 | + return executor.submit(new ExceptionCatchingRunnable() { | |
| 2568 | + @Override | |
| 2569 | + public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2570 | + controlConnection.refreshNodeListAndTokenMap(); | |
| 2571 | + } | |
| 2572 | + }); | |
| 2573 | + } | |
| 2574 | + } | |
| 2575 | + | |
| 2576 | + } | |
| 2577 | + | |
| 2578 | + private enum HostEvent { | |
| 2579 | + UP, DOWN, ADDED, REMOVED | |
| 2352 | 2580 | } |
| 2353 | 2581 | |
| 2354 | 2582 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +29 −31
| @@ -19,8 +19,7 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.net.UnknownHostException; |
| 21 | 21 | import java.util.*; |
| 22 | -import java.util.concurrent.ExecutionException; | |
| 23 | -import java.util.concurrent.TimeUnit; | |
| 22 | +import java.util.concurrent.*; | |
| 24 | 23 | import java.util.concurrent.atomic.AtomicReference; |
| 25 | 24 | |
| 26 | 25 | import com.google.common.base.Objects; |
| @@ -258,11 +257,14 @@ | ||
| 258 | 257 | // the node we're connecting to. |
| 259 | 258 | refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true); |
| 260 | 259 | |
| 261 | - // Note that refreshing the schema will trigger refreshNodeListAndTokenMap since table == null | |
| 262 | - // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces | |
| 263 | - // to be loaded. | |
| 264 | 260 | logger.debug("[Control connection] Refreshing schema"); |
| 265 | - refreshSchema(connection, null, null, cluster, isInitialConnection); | |
| 261 | + refreshSchema(connection, null, null, cluster); | |
| 262 | + | |
| 263 | + // We need to refresh the node list again; | |
| 264 | + // We want that because the token map was not properly initialized by the first call above, | |
| 265 | + // since it requires the list of keyspaces to be loaded. | |
| 266 | + refreshNodeListAndTokenMap(connection, cluster, false, true); | |
| 267 | + | |
| 266 | 268 | return connection; |
| 267 | 269 | } catch (BusyConnectionException e) { |
| 268 | 270 | connection.closeAsync().force(); |
| @@ -283,13 +285,22 @@ | ||
| 283 | 285 | } |
| 284 | 286 | |
| 285 | 287 | public void refreshSchema(String keyspace, String table) throws InterruptedException { |
| 286 | - logger.debug("[Control connection] Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); | |
| 288 | + if(keyspace == null && table == null) { | |
| 289 | + logger.debug("[Control connection] Refreshing schema"); | |
| 290 | + } else { | |
| 291 | + logger.debug("[Control connection] Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); | |
| 292 | + } | |
| 287 | 293 | try { |
| 288 | 294 | Connection c = connectionRef.get(); |
| 289 | 295 | // At startup, when we add the initial nodes, this will be null, which is ok |
| 290 | 296 | if (c == null) |
| 291 | 297 | return; |
| 292 | - refreshSchema(c, keyspace, table, cluster, false); | |
| 298 | + refreshSchema(c, keyspace, table, cluster); | |
| 299 | + // If the table is null, we either rebuild all from scratch or have an updated keyspace. In both cases, rebuild the token map | |
| 300 | + // since some replication on some keyspace may have changed | |
| 301 | + if (table == null) { | |
| 302 | + cluster.submitNodeListRefresh(); | |
| 303 | + } | |
| 293 | 304 | } catch (ConnectionException e) { |
| 294 | 305 | logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage()); |
| 295 | 306 | signalError(); |
| @@ -304,7 +315,7 @@ | ||
| 304 | 315 | } |
| 305 | 316 | } |
| 306 | 317 | |
| 307 | - static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 318 | + static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 308 | 319 | // Make sure we're up to date on schema |
| 309 | 320 | String whereClause = ""; |
| 310 | 321 | if (keyspace != null) { |
| @@ -345,11 +356,6 @@ | ||
| 345 | 356 | // So log, but let things go otherwise. |
| 346 | 357 | logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e); |
| 347 | 358 | } |
| 348 | - | |
| 349 | - // If the table is null, we either rebuild all from scratch or have an updated keyspace. In both case, rebuild the token map | |
| 350 | - // since some replication on some keyspace may have changed | |
| 351 | - if (table == null) | |
| 352 | - refreshNodeListAndTokenMap(connection, cluster, false, false); | |
| 353 | 359 | } |
| 354 | 360 | |
| 355 | 361 | public void refreshNodeListAndTokenMap() { |
| @@ -358,7 +364,6 @@ | ||
| 358 | 364 | if (c == null) |
| 359 | 365 | return; |
| 360 | 366 | |
| 361 | - logger.debug("[Control connection] Refreshing node list and token map"); | |
| 362 | 367 | try { |
| 363 | 368 | refreshNodeListAndTokenMap(c, cluster, false, true); |
| 364 | 369 | } catch (ConnectionException e) { |
| @@ -591,14 +596,13 @@ | ||
| 591 | 596 | cluster.metadata.rebuildTokenMap(partitioner, tokenMap); |
| 592 | 597 | } |
| 593 | 598 | |
| 594 | - static boolean waitForSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 595 | - | |
| 599 | + boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 596 | 600 | long start = System.nanoTime(); |
| 597 | 601 | long elapsed = 0; |
| 598 | 602 | int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds(); |
| 599 | 603 | while (elapsed < maxSchemaAgreementWaitSeconds * 1000) { |
| 600 | 604 | |
| 601 | - if (checkSchemaAgreement(connection, cluster)) | |
| 605 | + if (checkSchemaAgreement()) | |
| 602 | 606 | return true; |
| 603 | 607 | |
| 604 | 608 | // let's not flood the node too much |
| @@ -610,7 +614,11 @@ | ||
| 610 | 614 | return false; |
| 611 | 615 | } |
| 612 | 616 | |
| 613 | - private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { | |
| 617 | + boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { | |
| 618 | + Connection connection = connectionRef.get(); | |
| 619 | + if (connection == null || connection.isClosed()) | |
| 620 | + return false; | |
| 621 | + | |
| 614 | 622 | DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_PEERS)); |
| 615 | 623 | DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_LOCAL)); |
| 616 | 624 | connection.write(peersFuture); |
| @@ -636,16 +644,6 @@ | ||
| 636 | 644 | return versions.size() <= 1; |
| 637 | 645 | } |
| 638 | 646 | |
| 639 | - boolean checkSchemaAgreement() { | |
| 640 | - Connection c = connectionRef.get(); | |
| 641 | - try { | |
| 642 | - return c != null && checkSchemaAgreement(c, cluster); | |
| 643 | - } catch (Exception e) { | |
| 644 | - logger.warn("Error while checking schema agreement", e); | |
| 645 | - return false; | |
| 646 | - } | |
| 647 | - } | |
| 648 | - | |
| 649 | 647 | boolean isOpen() { |
| 650 | 648 | Connection c = connectionRef.get(); |
| 651 | 649 | return c != null && !c.isClosed(); |
| @@ -679,7 +677,7 @@ | ||
| 679 | 677 | // or it's not part of our computed token map |
| 680 | 678 | Metadata.TokenMap tkmap = cluster.metadata.tokenMap; |
| 681 | 679 | if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host)) |
| 682 | - refreshNodeListAndTokenMap(); | |
| 680 | + cluster.submitNodeListRefresh(); | |
| 683 | 681 | } |
| 684 | 682 | |
| 685 | 683 | @Override |
| @@ -693,6 +691,6 @@ | ||
| 693 | 691 | backgroundReconnect(0); |
| 694 | 692 | } |
| 695 | 693 | |
| 696 | - refreshNodeListAndTokenMap(); | |
| 694 | + cluster.submitNodeListRefresh(); | |
| 697 | 695 | } |
| 698 | 696 | } |
added driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java +289 −0
| @@ -0,0 +1,289 @@ | ||
| 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; | |
| 17 | + | |
| 18 | +import java.util.List; | |
| 19 | +import java.util.Queue; | |
| 20 | +import java.util.concurrent.*; | |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 22 | +import java.util.concurrent.atomic.AtomicReference; | |
| 23 | + | |
| 24 | +import static java.util.concurrent.TimeUnit.NANOSECONDS; | |
| 25 | +import static java.util.concurrent.TimeUnit.SECONDS; | |
| 26 | + | |
| 27 | +import com.google.common.collect.Lists; | |
| 28 | +import com.google.common.util.concurrent.FutureCallback; | |
| 29 | +import com.google.common.util.concurrent.Futures; | |
| 30 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 31 | +import com.google.common.util.concurrent.SettableFuture; | |
| 32 | +import org.slf4j.Logger; | |
| 33 | +import org.slf4j.LoggerFactory; | |
| 34 | + | |
| 35 | +import static com.google.common.base.Preconditions.checkNotNull; | |
| 36 | + | |
| 37 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * A helper class to debounce events received by the Control Connection. | |
| 41 | + * | |
| 42 | + * This class accumulates received events, and delivers them when either: | |
| 43 | + * - no events have been received for delayMs | |
| 44 | + * - maxPendingEvents have been received | |
| 45 | + */ | |
| 46 | +class EventDebouncer<T> { | |
| 47 | + | |
| 48 | + private static final Logger logger = LoggerFactory.getLogger(EventDebouncer.class); | |
| 49 | + | |
| 50 | + private static final int MAX_QUEUED_EVENTS = 10000; | |
| 51 | + | |
| 52 | + private final String name; | |
| 53 | + | |
| 54 | + private final AtomicReference<DeliveryAttempt> immediateDelivery = new AtomicReference<DeliveryAttempt>(null); | |
| 55 | + private final AtomicReference<DeliveryAttempt> delayedDelivery = new AtomicReference<DeliveryAttempt>(null); | |
| 56 | + | |
| 57 | + private final ScheduledExecutorService executor; | |
| 58 | + | |
| 59 | + private final DeliveryCallback<T> callback; | |
| 60 | + | |
| 61 | + private final long delayMs; | |
| 62 | + private final int maxPendingEvents; | |
| 63 | + | |
| 64 | + private final Queue<Entry<T>> events; | |
| 65 | + private final AtomicInteger eventCount; | |
| 66 | + | |
| 67 | + private enum State {NEW, RUNNING, STOPPED} | |
| 68 | + | |
| 69 | + private volatile State state; | |
| 70 | + | |
| 71 | + private static final long OVERFLOW_WARNING_INTERVAL = NANOSECONDS.convert(5, SECONDS); | |
| 72 | + private volatile long lastOverflowWarning = Long.MIN_VALUE; | |
| 73 | + | |
| 74 | + EventDebouncer(String name, ScheduledExecutorService executor, DeliveryCallback<T> callback, long delayMs, int maxPendingEvents) { | |
| 75 | + this.name = name; | |
| 76 | + this.executor = executor; | |
| 77 | + this.callback = callback; | |
| 78 | + this.delayMs = delayMs; | |
| 79 | + this.maxPendingEvents = maxPendingEvents; | |
| 80 | + this.events = new ConcurrentLinkedQueue<Entry<T>>(); | |
| 81 | + this.eventCount = new AtomicInteger(); | |
| 82 | + this.state = State.NEW; | |
| 83 | + } | |
| 84 | + | |
| 85 | + void start() { | |
| 86 | + logger.trace("Starting {} debouncer...", name); | |
| 87 | + state = State.RUNNING; | |
| 88 | + if (!events.isEmpty()) { | |
| 89 | + logger.trace("{} debouncer: {} events were accumulated before the debouncer started: delivering now", | |
| 90 | + name, eventCount.get()); | |
| 91 | + scheduleImmediateDelivery(); | |
| 92 | + } | |
| 93 | + } | |
| 94 | + | |
| 95 | + void stop() { | |
| 96 | + logger.trace("Stopping {} debouncer...", name); | |
| 97 | + state = State.STOPPED; | |
| 98 | + while (true) { | |
| 99 | + DeliveryAttempt previous = cancelDelayedDelivery(); | |
| 100 | + if (delayedDelivery.compareAndSet(previous, null)) { | |
| 101 | + break; | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + completeAllPendingFutures(); | |
| 106 | + | |
| 107 | + logger.trace("{} debouncer stopped", name); | |
| 108 | + } | |
| 109 | + | |
| 110 | + private void completeAllPendingFutures() { | |
| 111 | + Entry<T> entry; | |
| 112 | + while ((entry = this.events.poll()) != null) { | |
| 113 | + entry.future.set(null); | |
| 114 | + } | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** @return a future that will complete once the event has been processed */ | |
| 118 | + ListenableFuture<Void> eventReceived(T event) { | |
| 119 | + if (state == State.STOPPED) { | |
| 120 | + logger.trace("{} debouncer is stopped, rejecting event: {}", name, event); | |
| 121 | + return MoreFutures.VOID_SUCCESS; | |
| 122 | + } | |
| 123 | + checkNotNull(event); | |
| 124 | + logger.trace("{} debouncer: event received {}", name, event); | |
| 125 | + | |
| 126 | + int count = eventCount.incrementAndGet(); | |
| 127 | + | |
| 128 | + // Safeguard against the queue filling up faster than we can process it | |
| 129 | + long now; | |
| 130 | + if (count > MAX_QUEUED_EVENTS && (now = System.nanoTime()) > lastOverflowWarning + OVERFLOW_WARNING_INTERVAL) { | |
| 131 | + lastOverflowWarning = now; | |
| 132 | + logger.warn("{} debouncer enqueued more than {} events, rejecting new events. " | |
| 133 | + + "This should not happen and is likely a sign that something is wrong.", | |
| 134 | + name, MAX_QUEUED_EVENTS); | |
| 135 | + return MoreFutures.VOID_SUCCESS; | |
| 136 | + } | |
| 137 | + | |
| 138 | + Entry<T> entry = new Entry<T>(event); | |
| 139 | + try { | |
| 140 | + events.add(entry); | |
| 141 | + } catch (RuntimeException e) { | |
| 142 | + eventCount.decrementAndGet(); | |
| 143 | + throw e; | |
| 144 | + } | |
| 145 | + | |
| 146 | + if (state == State.RUNNING) { | |
| 147 | + if (count < maxPendingEvents) { | |
| 148 | + scheduleDelayedDelivery(); | |
| 149 | + } else if (count == maxPendingEvents) { | |
| 150 | + scheduleImmediateDelivery(); | |
| 151 | + } | |
| 152 | + } else if (state == State.STOPPED) { | |
| 153 | + // If we race with stop() since the check at the beginning, ensure the future | |
| 154 | + // gets completed (no-op if the future was already set). | |
| 155 | + entry.future.set(null); | |
| 156 | + } | |
| 157 | + return entry.future; | |
| 158 | + } | |
| 159 | + | |
| 160 | + private void scheduleImmediateDelivery() { | |
| 161 | + cancelDelayedDelivery(); | |
| 162 | + | |
| 163 | + while (state == State.RUNNING) { | |
| 164 | + DeliveryAttempt previous = immediateDelivery.get(); | |
| 165 | + if (previous != null && !previous.isDone()) | |
| 166 | + return; | |
| 167 | + | |
| 168 | + DeliveryAttempt current = new DeliveryAttempt(); | |
| 169 | + if (immediateDelivery.compareAndSet(previous, current)) { | |
| 170 | + current.executeNow(); | |
| 171 | + return; | |
| 172 | + } | |
| 173 | + } | |
| 174 | + } | |
| 175 | + | |
| 176 | + private void scheduleDelayedDelivery() { | |
| 177 | + while (state == State.RUNNING) { | |
| 178 | + DeliveryAttempt previous = cancelDelayedDelivery(); | |
| 179 | + DeliveryAttempt next = new DeliveryAttempt(); | |
| 180 | + if (delayedDelivery.compareAndSet(previous, next)) { | |
| 181 | + next.scheduleAfterDelay(); | |
| 182 | + break; | |
| 183 | + } | |
| 184 | + } | |
| 185 | + } | |
| 186 | + | |
| 187 | + private DeliveryAttempt cancelDelayedDelivery() { | |
| 188 | + DeliveryAttempt previous = delayedDelivery.get(); | |
| 189 | + if (previous != null) { | |
| 190 | + previous.cancel(); | |
| 191 | + } | |
| 192 | + return previous; | |
| 193 | + } | |
| 194 | + | |
| 195 | + void deliverEvents() { | |
| 196 | + if (state == State.STOPPED) { | |
| 197 | + completeAllPendingFutures(); | |
| 198 | + return; | |
| 199 | + } | |
| 200 | + final List<T> toDeliver = Lists.newArrayList(); | |
| 201 | + final List<SettableFuture<Void>> futures = Lists.newArrayList(); | |
| 202 | + | |
| 203 | + Entry<T> entry; | |
| 204 | + // Limit the number of events we dequeue, to avoid an infinite loop if the queue starts filling faster than we can consume it. | |
| 205 | + int count = 0; | |
| 206 | + while (++count <= MAX_QUEUED_EVENTS && (entry = this.events.poll()) != null) { | |
| 207 | + toDeliver.add(entry.event); | |
| 208 | + futures.add(entry.future); | |
| 209 | + } | |
| 210 | + eventCount.addAndGet(-toDeliver.size()); | |
| 211 | + | |
| 212 | + if (toDeliver.isEmpty()) { | |
| 213 | + logger.trace("{} debouncer: no events to deliver", name); | |
| 214 | + } else { | |
| 215 | + logger.trace("{} debouncer: delivering {} events", name, toDeliver.size()); | |
| 216 | + ListenableFuture<?> delivered = callback.deliver(toDeliver); | |
| 217 | + Futures.addCallback(delivered, new FutureCallback<Object>() { | |
| 218 | + @Override | |
| 219 | + public void onSuccess(Object result) { | |
| 220 | + for (SettableFuture<Void> future : futures) | |
| 221 | + future.set(null); | |
| 222 | + } | |
| 223 | + | |
| 224 | + @Override | |
| 225 | + public void onFailure(Throwable t) { | |
| 226 | + for (SettableFuture<Void> future : futures) | |
| 227 | + future.setException(t); | |
| 228 | + } | |
| 229 | + }); | |
| 230 | + } | |
| 231 | + | |
| 232 | + // If we didn't dequeue all events (or new ones arrived since we did), make sure we eventually | |
| 233 | + // process the remaining events, because eventReceived might have skipped the delivery | |
| 234 | + if (!events.isEmpty()) | |
| 235 | + scheduleDelayedDelivery(); | |
| 236 | + } | |
| 237 | + | |
| 238 | + class DeliveryAttempt extends ExceptionCatchingRunnable { | |
| 239 | + | |
| 240 | + volatile Future<?> deliveryFuture; | |
| 241 | + | |
| 242 | + boolean isDone() { | |
| 243 | + return deliveryFuture != null && deliveryFuture.isDone(); | |
| 244 | + } | |
| 245 | + | |
| 246 | + void cancel() { | |
| 247 | + if (deliveryFuture != null) | |
| 248 | + deliveryFuture.cancel(true); | |
| 249 | + } | |
| 250 | + | |
| 251 | + void executeNow() { | |
| 252 | + if (state != State.STOPPED) | |
| 253 | + deliveryFuture = executor.submit(this); | |
| 254 | + } | |
| 255 | + | |
| 256 | + void scheduleAfterDelay() { | |
| 257 | + if (state != State.STOPPED) | |
| 258 | + deliveryFuture = executor.schedule(this, delayMs, TimeUnit.MILLISECONDS); | |
| 259 | + } | |
| 260 | + | |
| 261 | + @Override | |
| 262 | + public void runMayThrow() throws Exception { | |
| 263 | + deliverEvents(); | |
| 264 | + } | |
| 265 | + } | |
| 266 | + | |
| 267 | + interface DeliveryCallback<T> { | |
| 268 | + | |
| 269 | + /** | |
| 270 | + * Deliver the given list of events. | |
| 271 | + * The given list is a private copy and any modification made to it | |
| 272 | + * has no side-effect; it is also guaranteed not to be null nor empty. | |
| 273 | + * | |
| 274 | + * @param events the events to deliver | |
| 275 | + */ | |
| 276 | + ListenableFuture<?> deliver(List<T> events); | |
| 277 | + | |
| 278 | + } | |
| 279 | + | |
| 280 | + static class Entry<T> { | |
| 281 | + final T event; | |
| 282 | + final SettableFuture<Void> future; | |
| 283 | + | |
| 284 | + Entry(T event) { | |
| 285 | + this.event = event; | |
| 286 | + this.future = SettableFuture.create(); | |
| 287 | + } | |
| 288 | + } | |
| 289 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +6 −1
| @@ -474,7 +474,12 @@ | ||
| 474 | 474 | * (for example, if the control connection is down). |
| 475 | 475 | */ |
| 476 | 476 | public boolean checkSchemaAgreement() { |
| 477 | - return cluster.controlConnection.checkSchemaAgreement(); | |
| 477 | + try { | |
| 478 | + return cluster.controlConnection.checkSchemaAgreement(); | |
| 479 | + } catch (Exception e) { | |
| 480 | + logger.warn("Error while checking schema agreement", e); | |
| 481 | + return false; | |
| 482 | + } | |
| 478 | 483 | } |
| 479 | 484 | |
| 480 | 485 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +179 −0
| @@ -42,10 +42,32 @@ | ||
| 42 | 42 | */ |
| 43 | 43 | public static final boolean DEFAULT_IDEMPOTENCE = false; |
| 44 | 44 | |
| 45 | + public static final int DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS = 20; | |
| 46 | + | |
| 47 | + public static final int DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS = 20; | |
| 48 | + | |
| 49 | + public static final int DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS = 20; | |
| 50 | + | |
| 51 | + public static final int DEFAULT_REFRESH_NODE_LIST_INTERVAL_MILLIS = 1000; | |
| 52 | + | |
| 53 | + public static final int DEFAULT_REFRESH_NODE_INTERVAL_MILLIS = 1000; | |
| 54 | + | |
| 55 | + public static final int DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS = 1000; | |
| 56 | + | |
| 57 | + | |
| 45 | 58 | private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL; |
| 46 | 59 | private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL; |
| 47 | 60 | private volatile int fetchSize = DEFAULT_FETCH_SIZE; |
| 48 | 61 | private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE; |
| 62 | + | |
| 63 | + private volatile int maxPendingRefreshNodeListRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS; | |
| 64 | + private volatile int maxPendingRefreshNodeRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS; | |
| 65 | + private volatile int maxPendingRefreshSchemaRequests = DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS; | |
| 66 | + | |
| 67 | + private volatile int refreshNodeListIntervalMillis = DEFAULT_REFRESH_NODE_LIST_INTERVAL_MILLIS; | |
| 68 | + private volatile int refreshNodeIntervalMillis = DEFAULT_REFRESH_NODE_INTERVAL_MILLIS; | |
| 69 | + private volatile int refreshSchemaIntervalMillis = DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS; | |
| 70 | + | |
| 49 | 71 | private volatile boolean reprepareOnUp = true; |
| 50 | 72 | private volatile Cluster.Manager manager; |
| 51 | 73 | private volatile boolean prepareOnAllHosts = true; |
| @@ -249,4 +271,161 @@ | ||
| 249 | 271 | public boolean isReprepareOnUp() { |
| 250 | 272 | return this.reprepareOnUp; |
| 251 | 273 | } |
| 274 | + | |
| 275 | + /** | |
| 276 | + * Sets the default window size in milliseconds used to debounce node list refresh requests. | |
| 277 | + * <p> | |
| 278 | + * When the control connection receives a new schema refresh request, | |
| 279 | + * it puts it on hold and starts a timer, cancelling any previous running timer; | |
| 280 | + * when a timer expires, then the pending requests are coalesced and executed | |
| 281 | + * as a single request. | |
| 282 | + * | |
| 283 | + * @param refreshSchemaIntervalMillis The default window size in milliseconds used to debounce schema refresh requests. | |
| 284 | + */ | |
| 285 | + public QueryOptions setRefreshSchemaIntervalMillis(int refreshSchemaIntervalMillis) { | |
| 286 | + this.refreshSchemaIntervalMillis = refreshSchemaIntervalMillis; | |
| 287 | + return this; | |
| 288 | + } | |
| 289 | + | |
| 290 | + /** | |
| 291 | + * The default window size in milliseconds used to debounce schema refresh requests. | |
| 292 | + * | |
| 293 | + * @return The default window size in milliseconds used to debounce schema refresh requests. | |
| 294 | + */ | |
| 295 | + public int getRefreshSchemaIntervalMillis() { | |
| 296 | + return refreshSchemaIntervalMillis; | |
| 297 | + } | |
| 298 | + | |
| 299 | + /** | |
| 300 | + * Sets the maximum number of schema refresh requests that the control connection can accumulate | |
| 301 | + * before executing them. | |
| 302 | + * <p> | |
| 303 | + * When the control connection receives a new schema refresh request, | |
| 304 | + * it puts it on hold and starts a timer, cancelling any previous running timer; | |
| 305 | + * if the control connection receives too many events, is parameter allows to trigger | |
| 306 | + * execution of pending requests, event if the last timer is still running. | |
| 307 | + * | |
| 308 | + * @param maxPendingRefreshSchemaRequests The maximum number of schema refresh requests that the control connection can accumulate | |
| 309 | + * before executing them. | |
| 310 | + */ | |
| 311 | + public QueryOptions setMaxPendingRefreshSchemaRequests(int maxPendingRefreshSchemaRequests) { | |
| 312 | + this.maxPendingRefreshSchemaRequests = maxPendingRefreshSchemaRequests; | |
| 313 | + return this; | |
| 314 | + } | |
| 315 | + | |
| 316 | + /** | |
| 317 | + * The maximum number of schema refresh requests that the control connection can accumulate | |
| 318 | + * before executing them. | |
| 319 | + * | |
| 320 | + * @return The maximum number of schema refresh requests that the control connection can accumulate | |
| 321 | + * before executing them. | |
| 322 | + */ | |
| 323 | + public int getMaxPendingRefreshSchemaRequests() { | |
| 324 | + return maxPendingRefreshSchemaRequests; | |
| 325 | + } | |
| 326 | + | |
| 327 | + /** | |
| 328 | + * Sets the default window size in milliseconds used to debounce node list refresh requests. | |
| 329 | + * <p> | |
| 330 | + * When the control connection receives a new node list refresh request, | |
| 331 | + * it puts it on hold and starts a timer, cancelling any previous running timer; | |
| 332 | + * when a timer expires, then the pending requests are coalesced and executed | |
| 333 | + * as a single request. | |
| 334 | + * | |
| 335 | + * @param refreshNodeListIntervalMillis The default window size in milliseconds used to debounce node list refresh requests. | |
| 336 | + */ | |
| 337 | + public QueryOptions setRefreshNodeListIntervalMillis(int refreshNodeListIntervalMillis) { | |
| 338 | + this.refreshNodeListIntervalMillis = refreshNodeListIntervalMillis; | |
| 339 | + return this; | |
| 340 | + } | |
| 341 | + | |
| 342 | + /** | |
| 343 | + * The default window size in milliseconds used to debounce node list refresh requests. | |
| 344 | + * | |
| 345 | + * @return The default window size in milliseconds used to debounce node list refresh requests. | |
| 346 | + */ | |
| 347 | + public int getRefreshNodeListIntervalMillis() { | |
| 348 | + return refreshNodeListIntervalMillis; | |
| 349 | + } | |
| 350 | + | |
| 351 | + /** | |
| 352 | + * Sets the maximum number of node list refresh requests that the control connection can accumulate | |
| 353 | + * before executing them. | |
| 354 | + * <p> | |
| 355 | + * When the control connection receives a new node list refresh request, | |
| 356 | + * it puts it on hold and starts a timer, cancelling any previous running timer; | |
| 357 | + * if the control connection receives too many events, is parameter allows to trigger | |
| 358 | + * execution of pending requests, event if the last timer is still running. | |
| 359 | + * | |
| 360 | + * @param maxPendingRefreshNodeListRequests The maximum number of node list refresh requests that the control connection can accumulate | |
| 361 | + * before executing them. | |
| 362 | + */ | |
| 363 | + public QueryOptions setMaxPendingRefreshNodeListRequests(int maxPendingRefreshNodeListRequests) { | |
| 364 | + this.maxPendingRefreshNodeListRequests = maxPendingRefreshNodeListRequests; | |
| 365 | + return this; | |
| 366 | + } | |
| 367 | + | |
| 368 | + /** | |
| 369 | + * Sets the maximum number of node list refresh requests that the control connection can accumulate | |
| 370 | + * before executing them. | |
| 371 | + * | |
| 372 | + * @return The maximum number of node list refresh requests that the control connection can accumulate | |
| 373 | + * before executing them. | |
| 374 | + */ | |
| 375 | + public int getMaxPendingRefreshNodeListRequests() { | |
| 376 | + return maxPendingRefreshNodeListRequests; | |
| 377 | + } | |
| 378 | + | |
| 379 | + /** | |
| 380 | + * Sets the default window size in milliseconds used to debounce node refresh requests. | |
| 381 | + * <p> | |
| 382 | + * When the control connection receives a new node refresh request, | |
| 383 | + * it puts it on hold and starts a timer, cancelling any previous running timer; | |
| 384 | + * when a timer expires, then the pending requests are coalesced and executed | |
| 385 | + * as a single request. | |
| 386 | + * | |
| 387 | + * @param refreshNodeIntervalMillis The default window size in milliseconds used to debounce node refresh requests. | |
| 388 | + */ | |
| 389 | + public QueryOptions setRefreshNodeIntervalMillis(int refreshNodeIntervalMillis) { | |
| 390 | + this.refreshNodeIntervalMillis = refreshNodeIntervalMillis; | |
| 391 | + return this; | |
| 392 | + } | |
| 393 | + | |
| 394 | + /** | |
| 395 | + * The default window size in milliseconds used to debounce node refresh requests. | |
| 396 | + * | |
| 397 | + * @return The default window size in milliseconds used to debounce node refresh requests. | |
| 398 | + */ | |
| 399 | + public int getRefreshNodeIntervalMillis() { | |
| 400 | + return refreshNodeIntervalMillis; | |
| 401 | + } | |
| 402 | + | |
| 403 | + /** | |
| 404 | + * Sets the maximum number of node refresh requests that the control connection can accumulate | |
| 405 | + * before executing them. | |
| 406 | + * <p> | |
| 407 | + * When the control connection receives a new node refresh request, | |
| 408 | + * it puts it on hold and starts a timer, cancelling any previous running timer; | |
| 409 | + * if the control connection receives too many events, is parameter allows to trigger | |
| 410 | + * execution of pending requests, event if the last timer is still running. | |
| 411 | + * | |
| 412 | + * @param maxPendingRefreshNodeRequests The maximum number of node refresh requests that the control connection can accumulate | |
| 413 | + * before executing them. | |
| 414 | + */ | |
| 415 | + public QueryOptions setMaxPendingRefreshNodeRequests(int maxPendingRefreshNodeRequests) { | |
| 416 | + this.maxPendingRefreshNodeRequests = maxPendingRefreshNodeRequests; | |
| 417 | + return this; | |
| 418 | + } | |
| 419 | + | |
| 420 | + /** | |
| 421 | + * The maximum number of node refresh requests that the control connection can accumulate | |
| 422 | + * before executing them. | |
| 423 | + * | |
| 424 | + * @return The maximum number of node refresh requests that the control connection can accumulate | |
| 425 | + * before executing them. | |
| 426 | + */ | |
| 427 | + public int getMaxPendingRefreshNodeRequests() { | |
| 428 | + return maxPendingRefreshNodeRequests; | |
| 429 | + } | |
| 430 | + | |
| 252 | 431 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +19 −6
| @@ -15,12 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.util.*; | |
| 19 | - | |
| 20 | 18 | import org.testng.annotations.Test; |
| 21 | -import static org.testng.Assert.*; | |
| 22 | 19 | |
| 23 | -import static com.datastax.driver.core.TestUtils.*; | |
| 20 | +import static org.testng.Assert.assertEquals; | |
| 21 | +import static org.testng.Assert.assertNotNull; | |
| 22 | +import static org.testng.Assert.assertNull; | |
| 23 | + | |
| 24 | +import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 24 | 25 | |
| 25 | 26 | public class CaseSensitivityTest { |
| 26 | 27 | |
| @@ -36,7 +37,13 @@ | ||
| 36 | 37 | |
| 37 | 38 | @Test(groups = "short") |
| 38 | 39 | public void testCaseInsensitiveKeyspace() throws Throwable { |
| 39 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); | |
| 40 | + CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder() | |
| 41 | + .withQueryOptions(new QueryOptions() | |
| 42 | + .setRefreshNodeIntervalMillis(0) | |
| 43 | + .setRefreshNodeListIntervalMillis(0) | |
| 44 | + .setRefreshSchemaIntervalMillis(0) | |
| 45 | + ) | |
| 46 | + ); | |
| 40 | 47 | Session s = c.session; |
| 41 | 48 | try { |
| 42 | 49 | String ksName = "MyKeyspace"; |
| @@ -56,7 +63,13 @@ | ||
| 56 | 63 | |
| 57 | 64 | @Test(groups = "short") |
| 58 | 65 | public void testCaseSensitiveKeyspace() throws Throwable { |
| 59 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); | |
| 66 | + CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder() | |
| 67 | + .withQueryOptions(new QueryOptions() | |
| 68 | + .setRefreshNodeIntervalMillis(0) | |
| 69 | + .setRefreshNodeListIntervalMillis(0) | |
| 70 | + .setRefreshSchemaIntervalMillis(0) | |
| 71 | + ) | |
| 72 | + ); | |
| 60 | 73 | Session s = c.session; |
| 61 | 74 | try { |
| 62 | 75 | String ksName = "\"MyKeyspace\""; |
added driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java +259 −0
| @@ -0,0 +1,259 @@ | ||
| 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; | |
| 17 | + | |
| 18 | +import java.util.ArrayList; | |
| 19 | +import java.util.List; | |
| 20 | +import java.util.concurrent.*; | |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 22 | +import java.util.concurrent.locks.Condition; | |
| 23 | +import java.util.concurrent.locks.Lock; | |
| 24 | +import java.util.concurrent.locks.ReentrantLock; | |
| 25 | + | |
| 26 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 27 | +import static java.util.concurrent.TimeUnit.SECONDS; | |
| 28 | + | |
| 29 | +import com.google.common.util.concurrent.Futures; | |
| 30 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 31 | +import org.testng.annotations.AfterMethod; | |
| 32 | +import org.testng.annotations.BeforeMethod; | |
| 33 | +import org.testng.annotations.Test; | |
| 34 | + | |
| 35 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 36 | + | |
| 37 | +import com.datastax.driver.core.EventDebouncer.DeliveryCallback; | |
| 38 | + | |
| 39 | +public class EventDebouncerTest { | |
| 40 | + | |
| 41 | + private ScheduledExecutorService executor; | |
| 42 | + | |
| 43 | + private MockDeliveryCallback callback; | |
| 44 | + | |
| 45 | + @BeforeMethod(groups = "unit") | |
| 46 | + public void setup() { | |
| 47 | + executor = Executors.newScheduledThreadPool(1); | |
| 48 | + callback = new MockDeliveryCallback(); | |
| 49 | + } | |
| 50 | + | |
| 51 | + @AfterMethod(groups = "unit") | |
| 52 | + public void tearDown() { | |
| 53 | + executor.shutdownNow(); | |
| 54 | + } | |
| 55 | + | |
| 56 | + @Test(groups = "unit") | |
| 57 | + public void should_deliver_single_event() throws InterruptedException { | |
| 58 | + EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50); | |
| 59 | + debouncer.start(); | |
| 60 | + MockEvent event = new MockEvent(0); | |
| 61 | + debouncer.eventReceived(event); | |
| 62 | + callback.awaitEvents(1); | |
| 63 | + assertThat(callback.getEvents()).containsOnly(event); | |
| 64 | + } | |
| 65 | + | |
| 66 | + @Test(groups = "unit") | |
| 67 | + public void should_deliver_n_events_in_order() throws InterruptedException { | |
| 68 | + EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50); | |
| 69 | + debouncer.start(); | |
| 70 | + List<MockEvent> events = new ArrayList<MockEvent>(); | |
| 71 | + for (int i = 0; i < 50; i++) { | |
| 72 | + MockEvent event = new MockEvent(i); | |
| 73 | + events.add(event); | |
| 74 | + debouncer.eventReceived(event); | |
| 75 | + } | |
| 76 | + callback.awaitEvents(50); | |
| 77 | + assertThat(callback.getEvents()).isEqualTo(events); | |
| 78 | + assertThat(callback.getInvocations()).isEqualTo(1); | |
| 79 | + } | |
| 80 | + | |
| 81 | + @Test(groups = "unit") | |
| 82 | + public void should_deliver_n_events_in_order_even_if_queue_full() throws InterruptedException { | |
| 83 | + EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 1); | |
| 84 | + debouncer.start(); | |
| 85 | + List<MockEvent> events = new ArrayList<MockEvent>(); | |
| 86 | + for (int i = 0; i < 50; i++) { | |
| 87 | + MockEvent event = new MockEvent(i); | |
| 88 | + events.add(event); | |
| 89 | + debouncer.eventReceived(event); | |
| 90 | + } | |
| 91 | + callback.awaitEvents(50); | |
| 92 | + assertThat(callback.getEvents()).isEqualTo(events); | |
| 93 | + } | |
| 94 | + | |
| 95 | + @Test(groups = "unit") | |
| 96 | + public void should_accumulate_events_if_not_ready() throws InterruptedException { | |
| 97 | + EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50); | |
| 98 | + List<MockEvent> events = new ArrayList<MockEvent>(); | |
| 99 | + for (int i = 0; i < 50; i++) { | |
| 100 | + MockEvent event = new MockEvent(i); | |
| 101 | + events.add(event); | |
| 102 | + debouncer.eventReceived(event); | |
| 103 | + } | |
| 104 | + // simulate late start | |
| 105 | + debouncer.start(); | |
| 106 | + callback.awaitEvents(50); | |
| 107 | + assertThat(callback.getEvents()).hasSize(50); | |
| 108 | + assertThat(callback.getEvents()).isEqualTo(events); | |
| 109 | + } | |
| 110 | + | |
| 111 | + @Test(groups = "unit") | |
| 112 | + public void should_accumulate_all_events_until_start() throws InterruptedException { | |
| 113 | + final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 25); | |
| 114 | + final List<MockEvent> events = new ArrayList<MockEvent>(); | |
| 115 | + | |
| 116 | + for (int i = 0; i < 50; i++) { | |
| 117 | + MockEvent event = new MockEvent(i); | |
| 118 | + events.add(event); | |
| 119 | + debouncer.eventReceived(event); | |
| 120 | + } | |
| 121 | + | |
| 122 | + debouncer.start(); | |
| 123 | + | |
| 124 | + callback.awaitEvents(50); | |
| 125 | + assertThat(callback.getEvents()).isEqualTo(events); | |
| 126 | + assertThat(callback.getInvocations()).isEqualTo(1); | |
| 127 | + } | |
| 128 | + | |
| 129 | + @Test(groups = "unit") | |
| 130 | + public void should_reset_timer_if_n_events_received_within_same_window() throws InterruptedException { | |
| 131 | + final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 50, 50); | |
| 132 | + debouncer.start(); | |
| 133 | + final CountDownLatch latch = new CountDownLatch(50); | |
| 134 | + ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); | |
| 135 | + pool.scheduleAtFixedRate(new Runnable() { | |
| 136 | + @Override | |
| 137 | + public void run() { | |
| 138 | + if (latch.getCount() > 0) { | |
| 139 | + MockEvent event = new MockEvent(0); | |
| 140 | + debouncer.eventReceived(event); | |
| 141 | + latch.countDown(); | |
| 142 | + } | |
| 143 | + } | |
| 144 | + }, 0, 5, MILLISECONDS); | |
| 145 | + latch.await(); | |
| 146 | + pool.shutdownNow(); | |
| 147 | + callback.awaitEvents(50); | |
| 148 | + assertThat(callback.getEvents()).hasSize(50); | |
| 149 | + assertThat(callback.getInvocations()).isEqualTo(1); | |
| 150 | + } | |
| 151 | + | |
| 152 | + @Test(groups = "unit") | |
| 153 | + public void should_stop_receiving_events() throws InterruptedException { | |
| 154 | + final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50); | |
| 155 | + debouncer.start(); | |
| 156 | + for (int i = 0; i < 50; i++) { | |
| 157 | + MockEvent event = new MockEvent(i); | |
| 158 | + debouncer.eventReceived(event); | |
| 159 | + } | |
| 160 | + callback.awaitEvents(50); | |
| 161 | + debouncer.stop(); | |
| 162 | + MockEvent event = new MockEvent(0); | |
| 163 | + debouncer.eventReceived(event); | |
| 164 | + assertThat(callback.getEvents()).hasSize(50); | |
| 165 | + assertThat(callback.getInvocations()).isEqualTo(1); | |
| 166 | + } | |
| 167 | + | |
| 168 | + private static class MockDeliveryCallback implements DeliveryCallback<MockEvent> { | |
| 169 | + | |
| 170 | + final List<MockEvent> events = new CopyOnWriteArrayList<MockEvent>(); | |
| 171 | + | |
| 172 | + final Lock lock = new ReentrantLock(); | |
| 173 | + | |
| 174 | + final Condition cond = lock.newCondition(); | |
| 175 | + | |
| 176 | + final AtomicInteger invocations = new AtomicInteger(0); | |
| 177 | + | |
| 178 | + @Override | |
| 179 | + public ListenableFuture<?> deliver(List<MockEvent> events) { | |
| 180 | + lock.lock(); | |
| 181 | + try { | |
| 182 | + this.events.addAll(events); | |
| 183 | + invocations.incrementAndGet(); | |
| 184 | + cond.signal(); | |
| 185 | + } finally { | |
| 186 | + lock.unlock(); | |
| 187 | + } | |
| 188 | + return Futures.immediateFuture(null); | |
| 189 | + } | |
| 190 | + | |
| 191 | + void awaitEvents(int expected) throws InterruptedException { | |
| 192 | + long nanos = SECONDS.toNanos(10); | |
| 193 | + lock.lock(); | |
| 194 | + try { | |
| 195 | + while (events.size() < expected) { | |
| 196 | + if (nanos <= 0L) | |
| 197 | + break; // timeout | |
| 198 | + nanos = cond.awaitNanos(nanos); | |
| 199 | + } | |
| 200 | + } finally { | |
| 201 | + lock.unlock(); | |
| 202 | + } | |
| 203 | + } | |
| 204 | + | |
| 205 | + void awaitInvocations(int expected) throws InterruptedException { | |
| 206 | + long nanos = SECONDS.toNanos(10); | |
| 207 | + lock.lock(); | |
| 208 | + try { | |
| 209 | + while (invocations.get() < expected) { | |
| 210 | + if (nanos <= 0L) | |
| 211 | + break; // timeout | |
| 212 | + nanos = cond.awaitNanos(nanos); | |
| 213 | + } | |
| 214 | + } finally { | |
| 215 | + lock.unlock(); | |
| 216 | + } | |
| 217 | + } | |
| 218 | + | |
| 219 | + public List<MockEvent> getEvents() { | |
| 220 | + return events; | |
| 221 | + } | |
| 222 | + | |
| 223 | + public int getInvocations() { | |
| 224 | + return invocations.get(); | |
| 225 | + } | |
| 226 | + } | |
| 227 | + | |
| 228 | + private class MockEvent { | |
| 229 | + | |
| 230 | + private final int i; | |
| 231 | + | |
| 232 | + private MockEvent(int i) { | |
| 233 | + this.i = i; | |
| 234 | + } | |
| 235 | + | |
| 236 | + @Override | |
| 237 | + public boolean equals(Object o) { | |
| 238 | + if (this == o) | |
| 239 | + return true; | |
| 240 | + if (o == null || getClass() != o.getClass()) | |
| 241 | + return false; | |
| 242 | + | |
| 243 | + MockEvent mockEvent = (MockEvent)o; | |
| 244 | + | |
| 245 | + return i == mockEvent.i; | |
| 246 | + | |
| 247 | + } | |
| 248 | + | |
| 249 | + @Override | |
| 250 | + public int hashCode() { | |
| 251 | + return i; | |
| 252 | + } | |
| 253 | + | |
| 254 | + @Override | |
| 255 | + public String toString() { | |
| 256 | + return "MockEvent" + i; | |
| 257 | + } | |
| 258 | + } | |
| 259 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +9 −0
| @@ -108,6 +108,15 @@ | ||
| 108 | 108 | return defs; |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | + @Override | |
| 112 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 113 | + return builder.withQueryOptions(new QueryOptions() | |
| 114 | + .setRefreshNodeIntervalMillis(0) | |
| 115 | + .setRefreshNodeListIntervalMillis(0) | |
| 116 | + .setRefreshSchemaIntervalMillis(0) | |
| 117 | + ); | |
| 118 | + } | |
| 119 | + | |
| 111 | 120 | @Test(groups = "short") |
| 112 | 121 | public void preparedNativeTest() { |
| 113 | 122 | // Test preparing/bounding for all native types |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +7 −1
| @@ -68,7 +68,13 @@ | ||
| 68 | 68 | |
| 69 | 69 | @BeforeClass(groups = "short") |
| 70 | 70 | public void setup() throws InterruptedException { |
| 71 | - Cluster.Builder builder = configure(Cluster.builder()).addContactPointsWithPorts(Collections.singletonList(hostAddress)); | |
| 71 | + Cluster.Builder builder = configure(Cluster.builder()) | |
| 72 | + .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 73 | + .withQueryOptions(new QueryOptions() | |
| 74 | + .setRefreshNodeIntervalMillis(0) | |
| 75 | + .setRefreshNodeListIntervalMillis(0) | |
| 76 | + .setRefreshSchemaIntervalMillis(0) | |
| 77 | + ); | |
| 72 | 78 | cluster1 = builder.build(); |
| 73 | 79 | cluster2 = builder.build(); |
| 74 | 80 |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +9 −0
| @@ -30,6 +30,15 @@ | ||
| 30 | 30 | |
| 31 | 31 | private static String withOptions; |
| 32 | 32 | |
| 33 | + @Override | |
| 34 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 35 | + return builder.withQueryOptions(new QueryOptions() | |
| 36 | + .setRefreshNodeIntervalMillis(0) | |
| 37 | + .setRefreshNodeListIntervalMillis(0) | |
| 38 | + .setRefreshSchemaIntervalMillis(0) | |
| 39 | + ); | |
| 40 | + } | |
| 41 | + | |
| 33 | 42 | @Override |
| 34 | 43 | protected Collection<String> getTableDefinitions() { |
| 35 | 44 |
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +8 −1
| @@ -39,7 +39,14 @@ | ||
| 39 | 39 | .withCassandraConfiguration("initial_token", "1") |
| 40 | 40 | .build(); |
| 41 | 41 | |
| 42 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 42 | + cluster = Cluster.builder() | |
| 43 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 44 | + .withQueryOptions(new QueryOptions() | |
| 45 | + .setRefreshNodeIntervalMillis(0) | |
| 46 | + .setRefreshNodeListIntervalMillis(0) | |
| 47 | + .setRefreshSchemaIntervalMillis(0) | |
| 48 | + ) | |
| 49 | + .build(); | |
| 43 | 50 | |
| 44 | 51 | Session session = cluster.connect(); |
| 45 | 52 | session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); |
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +10 −1
| @@ -32,9 +32,18 @@ | ||
| 32 | 32 | ); |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | + @Override | |
| 36 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 37 | + return builder.withQueryOptions(new QueryOptions() | |
| 38 | + .setRefreshNodeIntervalMillis(0) | |
| 39 | + .setRefreshNodeListIntervalMillis(0) | |
| 40 | + .setRefreshSchemaIntervalMillis(0) | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 35 | 44 | @Test(groups = "short") |
| 36 | 45 | public void should_escape_single_quote_table_comment() { |
| 37 | 46 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote"); |
| 38 | 47 | assertThat(table.asCQLQuery()).contains("comment with single quote '' should work"); |
| 39 | 48 | } |
| 40 | -} | |
| No newline at the end of the file | ||
| 49 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +4 −2
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | import java.nio.ByteBuffer; |
| 25 | 25 | import java.util.*; |
| 26 | 26 | |
| 27 | +import com.google.common.util.concurrent.Futures; | |
| 27 | 28 | import org.scassandra.Scassandra; |
| 28 | 29 | import org.scassandra.ScassandraFactory; |
| 29 | 30 | import org.slf4j.Logger; |
| @@ -323,8 +324,9 @@ | ||
| 323 | 324 | // tried doing an actual query, the driver won't realize that last node is dead until |
| 324 | 325 | // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force |
| 325 | 326 | // the detection by forcing a request. |
| 326 | - if (waitForDead || waitForOut) | |
| 327 | - cluster.manager.submitSchemaRefresh(null, null); | |
| 327 | + if (waitForDead || waitForOut) { | |
| 328 | + Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null)); | |
| 329 | + } | |
| 328 | 330 | |
| 329 | 331 | InetAddress address; |
| 330 | 332 | try { |
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +5 −0
| @@ -81,6 +81,11 @@ | ||
| 81 | 81 | cluster = Cluster.builder() |
| 82 | 82 | .addContactPoints(CCMBridge.ipOfNode(1)) |
| 83 | 83 | .withLoadBalancingPolicy(lbp) |
| 84 | + .withQueryOptions(new QueryOptions() | |
| 85 | + .setRefreshNodeIntervalMillis(0) | |
| 86 | + .setRefreshNodeListIntervalMillis(0) | |
| 87 | + .setRefreshSchemaIntervalMillis(0) | |
| 88 | + ) | |
| 84 | 89 | .build(); |
| 85 | 90 | cluster.init(); |
| 86 | 91 | session = cluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +9 −0
| @@ -40,6 +40,15 @@ | ||
| 40 | 40 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | + @Override | |
| 44 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 45 | + return builder.withQueryOptions(new QueryOptions() | |
| 46 | + .setRefreshNodeIntervalMillis(0) | |
| 47 | + .setRefreshNodeListIntervalMillis(0) | |
| 48 | + .setRefreshSchemaIntervalMillis(0) | |
| 49 | + ); | |
| 50 | + } | |
| 51 | + | |
| 43 | 52 | @Test(groups = "short") |
| 44 | 53 | public void remainingDeleteTests() throws Exception { |
| 45 | 54 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +9 −0
| @@ -39,6 +39,15 @@ | ||
| 39 | 39 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | + @Override | |
| 43 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 44 | + return builder.withQueryOptions(new QueryOptions() | |
| 45 | + .setRefreshNodeIntervalMillis(0) | |
| 46 | + .setRefreshNodeListIntervalMillis(0) | |
| 47 | + .setRefreshSchemaIntervalMillis(0) | |
| 48 | + ); | |
| 49 | + } | |
| 50 | + | |
| 42 | 51 | @Test(groups = "short") |
| 43 | 52 | public void textRoutingKeyTest() throws Exception { |
| 44 | 53 |