Elffuss BraidHub

kikocis/java-driver public

Merge pull request #406 from datastax/java657

JAVA-657: Debounce control connection queries.
Changeseta9c3f7efad0e97371d6ad96dece85cb772ac0197413cf5e261d064c667d4ac22
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-14 19:10 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-14 19:10 +02:00
Parentsdc07c7b283df, 0648dd431f7f

Browse the files at this changeset

30 files changed

modified changelog/README.md +3 −0
@@ -35,6 +35,9 @@
3535 - [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658)
3636 - [improvement] Customizable creation of netty timer (JAVA-853)
3737 - [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859)
38+- [improvement] Debounce control connection queries (JAVA-657)
39+- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784)
40+- [new feature] Make driver-side metadata optional (JAVA-828)
3841
3942 Merged from 2.0.10_fixes branch:
4043
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +321 −90
@@ -37,6 +37,7 @@
3737 import com.datastax.driver.core.exceptions.DriverInternalError;
3838 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3939 import com.datastax.driver.core.policies.*;
40+import com.datastax.driver.core.utils.MoreFutures;
4041
4142 /**
4243 * Information and known state of a Cassandra cluster.
@@ -1243,6 +1244,10 @@
12431244 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
12441245 final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
12451246
1247+ EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
1248+ EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer;
1249+ EventDebouncer<SchemaRefreshRequest> schemaRefreshRequestDebouncer;
1250+
12461251 private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) {
12471252 this.clusterName = clusterName == null ? generateClusterName() : clusterName;
12481253 this.configuration = configuration;
@@ -1278,8 +1283,28 @@
12781283 this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
12791284 this.preparedQueries = new MapMaker().weakValues().makeMap();
12801285
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());
12821306
1307+ this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
12831308
12841309 for (InetSocketAddress address : contactPoints) {
12851310 // We don't want to signal -- call onAdd() -- because nothing is ready
@@ -1353,6 +1378,12 @@
13531378 for (Host.StateListener listener : listeners)
13541379 listener.onAdd(host);
13551380 }
1381+
1382+ // start debouncers
1383+ this.nodeListRefreshRequestDebouncer.start();
1384+ this.schemaRefreshRequestDebouncer.start();
1385+ this.nodeRefreshRequestDebouncer.start();
1386+
13561387 isFullyInit = true;
13571388
13581389 return;
@@ -1442,6 +1473,11 @@
14421473 if (isInit) {
14431474 logger.debug("Shutting down");
14441475
1476+ // stop debouncers
1477+ nodeListRefreshRequestDebouncer.stop();
1478+ nodeRefreshRequestDebouncer.stop();
1479+ schemaRefreshRequestDebouncer.stop();
1480+
14451481 // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
14461482 // delivery or blocking tasks so we use shutdownNow
14471483 shutdownNow(reconnectionExecutor);
@@ -1994,7 +2030,7 @@
19942030 : reusedConnection;
19952031
19962032 try {
1997- ControlConnection.waitForSchemaAgreement(connection, this);
2033+ controlConnection.waitForSchemaAgreement();
19982034 } catch (ExecutionException e) {
19992035 // As below, just move on
20002036 }
@@ -2058,14 +2094,21 @@
20582094 }
20592095 }
20602096
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);
20692112 }
20702113
20712114 // refresh the schema using the provided connection, and notice the future with the provided resultset once done
@@ -2090,20 +2133,23 @@
20902133 try {
20912134 // Before refreshing the schema, wait for schema agreement so
20922135 // that querying a table just after having created it don't fail.
2093- schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this);
2136+ schemaInAgreement = controlConnection.waitForSchemaAgreement();
20942137 if (!schemaInAgreement)
20952138 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+
20982150 } 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
21072153 rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement);
21082154 future.setResult(rs);
21092155 }
@@ -2131,36 +2177,13 @@
21312177 InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress());
21322178 switch (tpc.change) {
21332179 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);
21532181 break;
21542182 case REMOVED_NODE:
2155- removeHost(metadata.getHost(tpAddr), false);
2183+ submitNodeRefresh(tpAddr, HostEvent.REMOVED);
21562184 break;
21572185 case MOVED_NODE:
2158- executor.submit(new ExceptionCatchingRunnable() {
2159- @Override
2160- public void runMayThrow() {
2161- controlConnection.refreshNodeListAndTokenMap();
2162- }
2163- });
2186+ submitNodeListRefresh();
21642187 break;
21652188 }
21662189 break;
@@ -2169,55 +2192,17 @@
21692192 InetSocketAddress stAddr = translateAddress(stc.node.getAddress());
21702193 switch (stc.status) {
21712194 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);
22082196 break;
22092197 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);
22172199 break;
22182200 }
22192201 break;
22202202 case SCHEMA_CHANGE:
2203+ if (!configuration.getQueryOptions().isMetadataEnabled())
2204+ return;
2205+
22212206 ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
22222207 switch (scc.change) {
22232208 case CREATED:
@@ -2349,6 +2334,252 @@
23492334 }
23502335 }
23512336 }
2337+
2338+ private class SchemaRefreshRequest {
2339+
2340+ private final String keyspace;
2341+
2342+ private final String table;
2343+
2344+ SchemaRefreshRequest(String keyspace, String table) {
2345+ this.keyspace = keyspace;
2346+ this.table = table;
2347+ }
2348+
2349+ /**
2350+ * Coalesce schema refresh requests.
2351+ * The algorithm is simple: if more than 2 keyspaces
2352+ * need refresh, then refresh the entire schema;
2353+ * otherwise if more than 2 tables in the same keyspace
2354+ * need refresh, then refresh the entire keyspace.
2355+ *
2356+ * @param that the other request to merge with the current one.
2357+ * @return A coalesced request
2358+ */
2359+ SchemaRefreshRequest coalesce(SchemaRefreshRequest that) {
2360+ if(this.keyspace == null || that.keyspace == null)
2361+ return new SchemaRefreshRequest(null, null);
2362+ if(!this.keyspace.equals(that.keyspace))
2363+ return new SchemaRefreshRequest(null, null);
2364+ if(this.table == null || that.table == null)
2365+ return new SchemaRefreshRequest(keyspace, null);
2366+ if(!this.table.equals(that.table))
2367+ return new SchemaRefreshRequest(keyspace, null);
2368+ return this;
2369+ }
2370+
2371+ @Override
2372+ public String toString() {
2373+ if(this.keyspace == null)
2374+ return "Refresh ALL";
2375+ if(this.table == null)
2376+ return "Refresh keyspace " + keyspace;
2377+ return "Refresh keyspace " + keyspace + " table " + table;
2378+ }
2379+ }
2380+
2381+ private class SchemaRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<SchemaRefreshRequest> {
2382+
2383+ @Override
2384+ public ListenableFuture<?> deliver(final List<SchemaRefreshRequest> events) {
2385+ return executor.submit(new ExceptionCatchingRunnable() {
2386+ @Override
2387+ public void runMayThrow() throws InterruptedException, ExecutionException {
2388+ SchemaRefreshRequest coalesced = null;
2389+ for (SchemaRefreshRequest request : events) {
2390+ coalesced = coalesced == null ? request : coalesced.coalesce(request);
2391+ }
2392+ assert coalesced != null;
2393+ logger.trace("Coalesced schema refresh request: {}", coalesced);
2394+ controlConnection.refreshSchema(coalesced.keyspace, coalesced.table);
2395+ }
2396+ });
2397+ }
2398+
2399+ }
2400+
2401+ private class NodeRefreshRequest {
2402+
2403+ private final InetSocketAddress address;
2404+
2405+ private final HostEvent eventType;
2406+
2407+ private NodeRefreshRequest(InetSocketAddress address, HostEvent eventType) {
2408+ this.address = address;
2409+ this.eventType = eventType;
2410+ }
2411+
2412+ @Override
2413+ public String toString() {
2414+ return address + " " + eventType;
2415+ }
2416+
2417+ }
2418+
2419+ private class NodeRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeRefreshRequest> {
2420+
2421+ @Override
2422+ public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) {
2423+ Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>();
2424+ // only keep the last event for each host
2425+ for (NodeRefreshRequest req : events) {
2426+ hosts.put(req.address, req.eventType);
2427+ }
2428+ List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size());
2429+ for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) {
2430+ InetSocketAddress address = entry.getKey();
2431+ HostEvent eventType = entry.getValue();
2432+ switch (eventType) {
2433+ case UP:
2434+ Host upHost = metadata.getHost(address);
2435+ if (upHost == null) {
2436+ upHost = metadata.add(address);
2437+ // If upHost is still null, it means we didn't know about it the line before but
2438+ // got beaten at adding it to the metadata by another thread. In that case, it's
2439+ // fine to let the other thread win and ignore the notification here
2440+ if (upHost == null)
2441+ continue;
2442+ futures.add(schedule(hostAdded(upHost)));
2443+ } else {
2444+ futures.add(schedule(hostUp(upHost)));
2445+ }
2446+ break;
2447+ case ADDED:
2448+ Host newHost = metadata.add(address);
2449+ if (newHost != null)
2450+ futures.add(schedule(hostAdded(newHost)));
2451+ break;
2452+ case DOWN:
2453+ // Note that there is a slight risk we can receive the event late and thus
2454+ // mark the host down even though we already had reconnected successfully.
2455+ // But it is unlikely, and don't have too much consequence since we'll try reconnecting
2456+ // right away, so we favor the detection to make the Host.isUp method more reliable.
2457+ Host downHost = metadata.getHost(address);
2458+ if (downHost != null)
2459+ futures.add(execute(hostDown(downHost)));
2460+ break;
2461+ case REMOVED:
2462+ Host removedHost = metadata.getHost(address);
2463+ if (removedHost != null)
2464+ futures.add(execute(hostRemoved(removedHost)));
2465+ break;
2466+ }
2467+ }
2468+ return Futures.allAsList(futures);
2469+ }
2470+
2471+ private ListenableFuture<?> execute(ExceptionCatchingRunnable task) {
2472+ return executor.submit(task);
2473+ }
2474+
2475+ private ListenableFuture<?> schedule(final ExceptionCatchingRunnable task) {
2476+ // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once
2477+ // gossip is up, but that is before the client-side server is up), so we add a delay
2478+ // (otherwise the connection will likely fail and have to be retry which is wasteful). This
2479+ // probably should be fixed C* side, after which we'll be able to remove this.
2480+ final SettableFuture<?> future = SettableFuture.create();
2481+ scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() {
2482+ public void runMayThrow() throws Exception {
2483+ ListenableFuture<?> f = execute(task);
2484+ Futures.addCallback(f, new FutureCallback<Object>() {
2485+ @Override
2486+ public void onSuccess(Object result) {
2487+ future.set(null);
2488+ }
2489+
2490+ @Override
2491+ public void onFailure(Throwable t) {
2492+ future.setException(t);
2493+ }
2494+ });
2495+ }
2496+ }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
2497+ return future;
2498+ }
2499+
2500+ // Make sure we call controlConnection.refreshNodeInfo(host)
2501+ // so that we have up-to-date infos on that host before adding it (so we typically
2502+ // catch that an upgraded node uses a new cassandra version).
2503+
2504+ private ExceptionCatchingRunnable hostAdded(final Host host) {
2505+ return new ExceptionCatchingRunnable() {
2506+ @Override
2507+ public void runMayThrow() throws Exception {
2508+ if (controlConnection.refreshNodeInfo(host)) {
2509+ onAdd(host, null);
2510+ } else {
2511+ logger.debug("Not enough info for {}, ignoring host", host);
2512+ }
2513+ }
2514+ };
2515+ }
2516+
2517+ private ExceptionCatchingRunnable hostUp(final Host host) {
2518+ return new ExceptionCatchingRunnable() {
2519+ @Override
2520+ public void runMayThrow() throws Exception {
2521+ if (controlConnection.refreshNodeInfo(host)) {
2522+ onUp(host, null);
2523+ } else {
2524+ logger.debug("Not enough info for {}, ignoring host", host);
2525+ }
2526+ }
2527+ };
2528+ }
2529+
2530+ private ExceptionCatchingRunnable hostDown(final Host host) {
2531+ return new ExceptionCatchingRunnable() {
2532+ @Override
2533+ public void runMayThrow() throws Exception {
2534+ if (controlConnection.refreshNodeInfo(host)) {
2535+ onDown(host, false, true);
2536+ } else {
2537+ logger.debug("Not enough info for {}, ignoring host", host);
2538+ }
2539+ }
2540+ };
2541+ }
2542+
2543+ private ExceptionCatchingRunnable hostRemoved(final Host host) {
2544+ return new ExceptionCatchingRunnable() {
2545+ @Override
2546+ public void runMayThrow() throws Exception {
2547+ if (metadata.remove(host)) {
2548+ logger.info("Cassandra host {} removed", host);
2549+ onRemove(host);
2550+ }
2551+ }
2552+ };
2553+ }
2554+
2555+ }
2556+
2557+ private class NodeListRefreshRequest {
2558+ @Override
2559+ public String toString() {
2560+ return "Refresh node list and token map";
2561+ }
2562+ }
2563+
2564+ private class NodeListRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeListRefreshRequest> {
2565+
2566+ @Override
2567+ public ListenableFuture<?> deliver(List<NodeListRefreshRequest> events) {
2568+ // The number of received requests does not matter
2569+ // as long as one request is made, refresh the entire node list
2570+ return executor.submit(new ExceptionCatchingRunnable() {
2571+ @Override
2572+ public void runMayThrow() throws InterruptedException, ExecutionException {
2573+ controlConnection.refreshNodeListAndTokenMap();
2574+ }
2575+ });
2576+ }
2577+ }
2578+
2579+ }
2580+
2581+ private enum HostEvent {
2582+ UP, DOWN, ADDED, REMOVED
23522583 }
23532584
23542585 /**
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +41 −37
@@ -19,8 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.net.UnknownHostException;
2121 import java.util.*;
22-import java.util.concurrent.ExecutionException;
23-import java.util.concurrent.TimeUnit;
22+import java.util.concurrent.*;
2423 import java.util.concurrent.atomic.AtomicReference;
2524
2625 import com.google.common.base.Objects;
@@ -258,11 +257,14 @@
258257 // the node we're connecting to.
259258 refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true);
260259
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.
264260 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+
266268 return connection;
267269 } catch (BusyConnectionException e) {
268270 connection.closeAsync().force();
@@ -283,13 +285,22 @@
283285 }
284286
285287 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+ }
287293 try {
288294 Connection c = connectionRef.get();
289295 // At startup, when we add the initial nodes, this will be null, which is ok
290296 if (c == null)
291297 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+ }
293304 } catch (ConnectionException e) {
294305 logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage());
295306 signalError();
@@ -304,7 +315,7 @@
304315 }
305316 }
306317
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 {
308319 // Make sure we're up to date on schema
309320 String whereClause = "";
310321 if (keyspace != null) {
@@ -345,11 +356,6 @@
345356 // So log, but let things go otherwise.
346357 logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e);
347358 }
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);
353359 }
354360
355361 public void refreshNodeListAndTokenMap() {
@@ -358,7 +364,6 @@
358364 if (c == null)
359365 return;
360366
361- logger.debug("[Control connection] Refreshing node list and token map");
362367 try {
363368 refreshNodeListAndTokenMap(c, cluster, false, true);
364369 } catch (ConnectionException e) {
@@ -507,6 +512,8 @@
507512 private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logMissingRpcAddresses) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
508513 logger.debug("[Control connection] Refreshing node list and token map");
509514
515+ boolean metadataEnabled = cluster.configuration.getQueryOptions().isMetadataEnabled();
516+
510517 // Make sure we're up to date on nodes and tokens
511518
512519 DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_LOCAL));
@@ -535,9 +542,11 @@
535542 logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address);
536543 } else {
537544 updateInfo(host, localRow, cluster, isInitialConnection);
538- Set<String> tokens = localRow.getSet("tokens", String.class);
539- if (partitioner != null && !tokens.isEmpty())
540- tokenMap.put(host, tokens);
545+ if (metadataEnabled) {
546+ Set<String> tokens = localRow.getSet("tokens", String.class);
547+ if (partitioner != null && !tokens.isEmpty())
548+ tokenMap.put(host, tokens);
549+ }
541550 }
542551 }
543552
@@ -558,7 +567,8 @@
558567 racks.add(row.getString("rack"));
559568 cassandraVersions.add(row.getString("release_version"));
560569 listenAddresses.add(row.getInet("peer"));
561- allTokens.add(row.getSet("tokens", String.class));
570+ if (metadataEnabled)
571+ allTokens.add(row.getSet("tokens", String.class));
562572 }
563573
564574 for (int i = 0; i < foundHosts.size(); i++) {
@@ -575,7 +585,7 @@
575585 if (cassandraVersions.get(i) != null)
576586 host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i));
577587
578- if (partitioner != null && !allTokens.get(i).isEmpty())
588+ if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty())
579589 tokenMap.put(host, allTokens.get(i));
580590
581591 if (isNew && !isInitialConnection)
@@ -588,17 +598,17 @@
588598 if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress()))
589599 cluster.removeHost(host, isInitialConnection);
590600
591- cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
601+ if (metadataEnabled)
602+ cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
592603 }
593604
594- static boolean waitForSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
595-
605+ boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
596606 long start = System.nanoTime();
597607 long elapsed = 0;
598608 int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds();
599609 while (elapsed < maxSchemaAgreementWaitSeconds * 1000) {
600610
601- if (checkSchemaAgreement(connection, cluster))
611+ if (checkSchemaAgreement())
602612 return true;
603613
604614 // let's not flood the node too much
@@ -610,7 +620,11 @@
610620 return false;
611621 }
612622
613- private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException {
623+ boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException {
624+ Connection connection = connectionRef.get();
625+ if (connection == null || connection.isClosed())
626+ return false;
627+
614628 DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_PEERS));
615629 DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_LOCAL));
616630 connection.write(peersFuture);
@@ -636,16 +650,6 @@
636650 return versions.size() <= 1;
637651 }
638652
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-
649653 boolean isOpen() {
650654 Connection c = connectionRef.get();
651655 return c != null && !c.isClosed();
@@ -679,7 +683,7 @@
679683 // or it's not part of our computed token map
680684 Metadata.TokenMap tkmap = cluster.metadata.tokenMap;
681685 if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host))
682- refreshNodeListAndTokenMap();
686+ cluster.submitNodeListRefresh();
683687 }
684688
685689 @Override
@@ -693,6 +697,6 @@
693697 backgroundReconnect(0);
694698 }
695699
696- refreshNodeListAndTokenMap();
700+ cluster.submitNodeListRefresh();
697701 }
698702 }
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +51 −47
@@ -65,62 +65,66 @@
6565 set(ArrayBackedResultSet.fromMessage(rm, session, info, statement));
6666 break;
6767 case SCHEMA_CHANGE:
68- Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
6968 ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, info, statement);
70- switch (scc.change) {
71- case CREATED:
72- if (scc.columnFamily.isEmpty()) {
73- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
74- } else {
75- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
76- }
77- break;
78- case DROPPED:
79- if (scc.columnFamily.isEmpty()) {
80- // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
81- // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
82- // We'll add it back if CASSANDRA-5358 changes that behavior
83- //if (scc.keyspace.equals(session.poolsState.keyspace))
84- // session.poolsState.setKeyspace(null);
85- final KeyspaceMetadata removed = session.cluster.manager.metadata.removeKeyspace(scc.keyspace);
86- if(removed != null) {
87- session.cluster.manager.executor.submit(new Runnable() {
88- @Override
89- public void run() {
90- session.cluster.manager.metadata.triggerOnKeyspaceRemoved(removed);
91- }
92- });
69+ final Cluster.Manager cluster = session.cluster.manager;
70+ if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) {
71+ cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
72+ } else {
73+ Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
74+ switch (scc.change) {
75+ case CREATED:
76+ if (scc.columnFamily.isEmpty()) {
77+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
78+ } else {
79+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
9380 }
94-
95- } else {
96- KeyspaceMetadata keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.keyspace);
97- if (keyspace == null)
98- logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata",
99- scc.keyspace, scc.columnFamily);
100- else {
101- final TableMetadata removed = keyspace.removeTable(scc.columnFamily);
81+ break;
82+ case DROPPED:
83+ if (scc.columnFamily.isEmpty()) {
84+ // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
85+ // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
86+ // We'll add it back if CASSANDRA-5358 changes that behavior
87+ //if (scc.keyspace.equals(session.poolsState.keyspace))
88+ // session.poolsState.setKeyspace(null);
89+ final KeyspaceMetadata removed = cluster.metadata.removeKeyspace(scc.keyspace);
10290 if (removed != null) {
103- session.cluster.manager.executor.submit(new Runnable() {
91+ cluster.executor.submit(new Runnable() {
10492 @Override
10593 public void run() {
106- session.cluster.manager.metadata.triggerOnTableRemoved(removed);
94+ cluster.metadata.triggerOnKeyspaceRemoved(removed);
10795 }
10896 });
10997 }
98+ } else {
99+ KeyspaceMetadata keyspace = cluster.metadata.getKeyspaceInternal(scc.keyspace);
100+ if (keyspace == null)
101+ logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata",
102+ scc.keyspace, scc.columnFamily);
103+ else {
104+ final TableMetadata removed = keyspace.removeTable(scc.columnFamily);
105+ if (removed != null) {
106+ cluster.executor.submit(new Runnable() {
107+ @Override
108+ public void run() {
109+ cluster.metadata.triggerOnTableRemoved(removed);
110+ }
111+ });
112+ }
113+ }
114+ }
115+ cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
116+ break;
117+ case UPDATED:
118+ if (scc.columnFamily.isEmpty()) {
119+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
120+ } else {
121+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
110122 }
111- }
112- session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs);
113- break;
114- case UPDATED:
115- if (scc.columnFamily.isEmpty()) {
116- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
117- } else {
118- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
119- }
120- break;
121- default:
122- logger.info("Ignoring unknown schema change result");
123- break;
123+ break;
124+ default:
125+ logger.info("Ignoring unknown schema change result");
126+ break;
127+ }
124128 }
125129 break;
126130 default:
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 +31 −10
@@ -28,8 +28,6 @@
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
3030
31-import com.datastax.driver.core.exceptions.DriverInternalError;
32-
3331 /**
3432 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
3533 */
@@ -355,7 +353,8 @@
355353 * connection, when schema or ring topology changes. It might occasionally
356354 * be stale.
357355 *
358- * @return the token ranges.
356+ * @return the token ranges. Note that the result might be stale or empty if
357+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
359358 */
360359 public Set<TokenRange> getTokenRanges() {
361360 TokenMap current = tokenMap;
@@ -373,7 +372,8 @@
373372 * @param keyspace the name of the keyspace to get token ranges for.
374373 * @param host the host.
375374 * @return the (immutable) set of token ranges for {@code host} as known
376- * by the driver.
375+ * by the driver. Note that the result might be stale or empty if metadata
376+ * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
377377 */
378378 public Set<TokenRange> getTokenRanges(String keyspace, Host host) {
379379 keyspace = handleId(keyspace);
@@ -402,7 +402,8 @@
402402 * @param partitionKey the partition key for which to find the set of
403403 * replica.
404404 * @return the (immutable) set of replicas for {@code partitionKey} as known
405- * by the driver.
405+ * by the driver. Note that the result might be stale or empty if metadata was
406+ * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
406407 */
407408 public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) {
408409 keyspace = handleId(keyspace);
@@ -425,6 +426,8 @@
425426 * @param keyspace the name of the keyspace to get replicas for.
426427 * @param range the token range.
427428 * @return the (immutable) set of replicas for {@code range} as known by the driver.
429+ * Note that the result might be stale or empty if metadata was explicitly disabled
430+ * with {@link QueryOptions#setMetadataEnabled(boolean)}.
428431 */
429432 public Set<Host> getReplicas(String keyspace, TokenRange range) {
430433 keyspace = handleId(keyspace);
@@ -474,7 +477,12 @@
474477 * (for example, if the control connection is down).
475478 */
476479 public boolean checkSchemaAgreement() {
477- return cluster.controlConnection.checkSchemaAgreement();
480+ try {
481+ return cluster.controlConnection.checkSchemaAgreement();
482+ } catch (Exception e) {
483+ logger.warn("Error while checking schema agreement", e);
484+ return false;
485+ }
478486 }
479487
480488 /**
@@ -483,7 +491,8 @@
483491 * @param keyspace the name of the keyspace for which metadata should be
484492 * returned.
485493 * @return the metadata of the requested keyspace or {@code null} if {@code
486- * keyspace} is not a known keyspace.
494+ * keyspace} is not a known keyspace. Note that the result might be stale or null if
495+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
487496 */
488497 public KeyspaceMetadata getKeyspace(String keyspace) {
489498 return keyspaces.get(handleId(keyspace));
@@ -507,7 +516,8 @@
507516 /**
508517 * Returns a list of all the defined keyspaces.
509518 *
510- * @return a list of all the defined keyspaces.
519+ * @return a list of all the defined keyspaces. Note that the result might be stale or empty if
520+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
511521 */
512522 public List<KeyspaceMetadata> getKeyspaces() {
513523 return new ArrayList<KeyspaceMetadata>(keyspaces.values());
@@ -523,6 +533,9 @@
523533 * Note that the returned String is formatted to be human readable (for
524534 * some definition of human readable at least).
525535 *
536+ * It might be stale or empty if metadata was explicitly disabled with
537+ * {@link QueryOptions#setMetadataEnabled(boolean)}.
538+ *
526539 * @return the CQL queries representing this cluster schema as a {code
527540 * String}.
528541 */
@@ -541,11 +554,15 @@
541554 *
542555 * @param tokenStr the string representation.
543556 * @return the token.
557+ *
558+ * @throws IllegalStateException if the token factory was not initialized. This would typically
559+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
560+ * before startup.
544561 */
545562 public Token newToken(String tokenStr) {
546563 TokenMap current = tokenMap;
547564 if (current == null)
548- throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
565+ throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled");
549566
550567 return current.factory.fromString(tokenStr);
551568 }
@@ -556,11 +573,15 @@
556573 * @param start the start token.
557574 * @param end the end token.
558575 * @return the range.
576+ *
577+ * @throws IllegalStateException if the token factory was not initialized. This would typically
578+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
579+ * before startup.
559580 */
560581 public TokenRange newTokenRange(Token start, Token end) {
561582 TokenMap current = tokenMap;
562583 if (current == null)
563- throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
584+ throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled");
564585
565586 return new TokenRange(start, end, current.factory);
566587 }
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +224 −0
@@ -42,10 +42,33 @@
4242 */
4343 public static final boolean DEFAULT_IDEMPOTENCE = false;
4444
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+
4557 private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL;
4658 private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL;
4759 private volatile int fetchSize = DEFAULT_FETCH_SIZE;
4860 private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE;
61+
62+ private volatile boolean metadataEnabled = true;
63+
64+ private volatile int maxPendingRefreshNodeListRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS;
65+ private volatile int maxPendingRefreshNodeRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS;
66+ private volatile int maxPendingRefreshSchemaRequests = DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS;
67+
68+ private volatile int refreshNodeListIntervalMillis = DEFAULT_REFRESH_NODE_LIST_INTERVAL_MILLIS;
69+ private volatile int refreshNodeIntervalMillis = DEFAULT_REFRESH_NODE_INTERVAL_MILLIS;
70+ private volatile int refreshSchemaIntervalMillis = DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS;
71+
4972 private volatile boolean reprepareOnUp = true;
5073 private volatile Cluster.Manager manager;
5174 private volatile boolean prepareOnAllHosts = true;
@@ -249,4 +272,205 @@
249272 public boolean isReprepareOnUp() {
250273 return this.reprepareOnUp;
251274 }
275+
276+ /**
277+ * Toggle client-side token and schema metadata.
278+ * <p>
279+ * This feature is enabled by default. Some applications might wish to disable it
280+ * in order to eliminate the overhead of querying the metadata and building its
281+ * client-side representation. However, take note that doing so will have important
282+ * consequences:
283+ * <ul>
284+ * <li>most schema- or token-related methods in {@link Metadata} will return stale
285+ * or null/empty results (see the javadoc of each method for details);</li>
286+ * <li>{@link Metadata#newToken(String)} and
287+ * {@link Metadata#newTokenRange(Token, Token)} will throw an exception if metadata
288+ * was disabled before startup;</li>
289+ * <li>token-aware routing will not work properly: if metadata was never initialized,
290+ * {@link com.datastax.driver.core.policies.TokenAwarePolicy} will always delegate
291+ * to its child policy. Otherwise, it might not pick the best coordinator (i.e. chose
292+ * a host that is not a replica for the statement's routing key). In addition, statements
293+ * prepared while the metadata was disabled might also be sent to a non-optimal coordinator,
294+ * even if metadata was re-enabled later.</li>
295+ * </ul>
296+ *
297+ * @param enabled whether metadata is enabled.
298+ * @return this {@code QueryOptions} instance.
299+ */
300+ public QueryOptions setMetadataEnabled(boolean enabled) {
301+ boolean wasEnabled = this.metadataEnabled;
302+ this.metadataEnabled = enabled;
303+ if (!wasEnabled && enabled && manager != null) {
304+ manager.submitSchemaRefresh(null, null); // will also refresh token map
305+ }
306+ return this;
307+ }
308+
309+ /**
310+ * Whether client-side token and schema metadata is enabled.
311+ *
312+ * @return the value.
313+ *
314+ * @see #setMetadataEnabled(boolean)
315+ */
316+ public boolean isMetadataEnabled() {
317+ return metadataEnabled;
318+ }
319+
320+ /**
321+ * Sets the default window size in milliseconds used to debounce node list refresh requests.
322+ * <p>
323+ * When the control connection receives a new schema refresh request,
324+ * it puts it on hold and starts a timer, cancelling any previous running timer;
325+ * when a timer expires, then the pending requests are coalesced and executed
326+ * as a single request.
327+ *
328+ * @param refreshSchemaIntervalMillis The default window size in milliseconds used to debounce schema refresh requests.
329+ */
330+ public QueryOptions setRefreshSchemaIntervalMillis(int refreshSchemaIntervalMillis) {
331+ this.refreshSchemaIntervalMillis = refreshSchemaIntervalMillis;
332+ return this;
333+ }
334+
335+ /**
336+ * The default window size in milliseconds used to debounce schema refresh requests.
337+ *
338+ * @return The default window size in milliseconds used to debounce schema refresh requests.
339+ */
340+ public int getRefreshSchemaIntervalMillis() {
341+ return refreshSchemaIntervalMillis;
342+ }
343+
344+ /**
345+ * Sets the maximum number of schema refresh requests that the control connection can accumulate
346+ * before executing them.
347+ * <p>
348+ * When the control connection receives a new schema refresh request,
349+ * it puts it on hold and starts a timer, cancelling any previous running timer;
350+ * if the control connection receives too many events, is parameter allows to trigger
351+ * execution of pending requests, event if the last timer is still running.
352+ *
353+ * @param maxPendingRefreshSchemaRequests The maximum number of schema refresh requests that the control connection can accumulate
354+ * before executing them.
355+ */
356+ public QueryOptions setMaxPendingRefreshSchemaRequests(int maxPendingRefreshSchemaRequests) {
357+ this.maxPendingRefreshSchemaRequests = maxPendingRefreshSchemaRequests;
358+ return this;
359+ }
360+
361+ /**
362+ * The maximum number of schema refresh requests that the control connection can accumulate
363+ * before executing them.
364+ *
365+ * @return The maximum number of schema refresh requests that the control connection can accumulate
366+ * before executing them.
367+ */
368+ public int getMaxPendingRefreshSchemaRequests() {
369+ return maxPendingRefreshSchemaRequests;
370+ }
371+
372+ /**
373+ * Sets the default window size in milliseconds used to debounce node list refresh requests.
374+ * <p>
375+ * When the control connection receives a new node list refresh request,
376+ * it puts it on hold and starts a timer, cancelling any previous running timer;
377+ * when a timer expires, then the pending requests are coalesced and executed
378+ * as a single request.
379+ *
380+ * @param refreshNodeListIntervalMillis The default window size in milliseconds used to debounce node list refresh requests.
381+ */
382+ public QueryOptions setRefreshNodeListIntervalMillis(int refreshNodeListIntervalMillis) {
383+ this.refreshNodeListIntervalMillis = refreshNodeListIntervalMillis;
384+ return this;
385+ }
386+
387+ /**
388+ * The default window size in milliseconds used to debounce node list refresh requests.
389+ *
390+ * @return The default window size in milliseconds used to debounce node list refresh requests.
391+ */
392+ public int getRefreshNodeListIntervalMillis() {
393+ return refreshNodeListIntervalMillis;
394+ }
395+
396+ /**
397+ * Sets the maximum number of node list refresh requests that the control connection can accumulate
398+ * before executing them.
399+ * <p>
400+ * When the control connection receives a new node list refresh request,
401+ * it puts it on hold and starts a timer, cancelling any previous running timer;
402+ * if the control connection receives too many events, is parameter allows to trigger
403+ * execution of pending requests, event if the last timer is still running.
404+ *
405+ * @param maxPendingRefreshNodeListRequests The maximum number of node list refresh requests that the control connection can accumulate
406+ * before executing them.
407+ */
408+ public QueryOptions setMaxPendingRefreshNodeListRequests(int maxPendingRefreshNodeListRequests) {
409+ this.maxPendingRefreshNodeListRequests = maxPendingRefreshNodeListRequests;
410+ return this;
411+ }
412+
413+ /**
414+ * Sets the maximum number of node list refresh requests that the control connection can accumulate
415+ * before executing them.
416+ *
417+ * @return The maximum number of node list refresh requests that the control connection can accumulate
418+ * before executing them.
419+ */
420+ public int getMaxPendingRefreshNodeListRequests() {
421+ return maxPendingRefreshNodeListRequests;
422+ }
423+
424+ /**
425+ * Sets the default window size in milliseconds used to debounce node refresh requests.
426+ * <p>
427+ * When the control connection receives a new node refresh request,
428+ * it puts it on hold and starts a timer, cancelling any previous running timer;
429+ * when a timer expires, then the pending requests are coalesced and executed
430+ * as a single request.
431+ *
432+ * @param refreshNodeIntervalMillis The default window size in milliseconds used to debounce node refresh requests.
433+ */
434+ public QueryOptions setRefreshNodeIntervalMillis(int refreshNodeIntervalMillis) {
435+ this.refreshNodeIntervalMillis = refreshNodeIntervalMillis;
436+ return this;
437+ }
438+
439+ /**
440+ * The default window size in milliseconds used to debounce node refresh requests.
441+ *
442+ * @return The default window size in milliseconds used to debounce node refresh requests.
443+ */
444+ public int getRefreshNodeIntervalMillis() {
445+ return refreshNodeIntervalMillis;
446+ }
447+
448+ /**
449+ * Sets the maximum number of node refresh requests that the control connection can accumulate
450+ * before executing them.
451+ * <p>
452+ * When the control connection receives a new node refresh request,
453+ * it puts it on hold and starts a timer, cancelling any previous running timer;
454+ * if the control connection receives too many events, is parameter allows to trigger
455+ * execution of pending requests, event if the last timer is still running.
456+ *
457+ * @param maxPendingRefreshNodeRequests The maximum number of node refresh requests that the control connection can accumulate
458+ * before executing them.
459+ */
460+ public QueryOptions setMaxPendingRefreshNodeRequests(int maxPendingRefreshNodeRequests) {
461+ this.maxPendingRefreshNodeRequests = maxPendingRefreshNodeRequests;
462+ return this;
463+ }
464+
465+ /**
466+ * The maximum number of node refresh requests that the control connection can accumulate
467+ * before executing them.
468+ *
469+ * @return The maximum number of node refresh requests that the control connection can accumulate
470+ * before executing them.
471+ */
472+ public int getMaxPendingRefreshNodeRequests() {
473+ return maxPendingRefreshNodeRequests;
474+ }
475+
252476 }
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +19 −6
@@ -15,12 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import org.testng.annotations.Test;
21-import static org.testng.Assert.*;
2219
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;
2425
2526 public class CaseSensitivityTest {
2627
@@ -36,7 +37,13 @@
3637
3738 @Test(groups = "short")
3839 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+ );
4047 Session s = c.session;
4148 try {
4249 String ksName = "MyKeyspace";
@@ -56,7 +63,13 @@
5663
5764 @Test(groups = "short")
5865 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+ );
6073 Session s = c.session;
6174 try {
6275 String ksName = "\"MyKeyspace\"";
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +4 −2
@@ -47,6 +47,7 @@
4747 import static com.datastax.driver.core.Host.State.DOWN;
4848 import static com.datastax.driver.core.Host.State.UP;
4949 import static com.datastax.driver.core.HostDistance.LOCAL;
50+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
5051
5152 public class ClusterInitTest {
5253 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -66,7 +67,7 @@
6667 // - 1 is an actual Scassandra instance that will accept connections:
6768 scassandra = TestUtils.createScassandraServer();
6869 scassandra.start();
69- String realHostAddress = "localhost";
70+ String realHostAddress = "127.0.0.1";
7071 int port = scassandra.getBinaryPort();
7172
7273 // - the remaining 4 are fake servers that will throw connect timeouts:
@@ -108,6 +109,7 @@
108109 .withReconnectionPolicy(reconnectionPolicy)
109110 .withPoolingOptions(poolingOptions)
110111 .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
112+ .withQueryOptions(nonDebouncingQueryOptions())
111113 .build();
112114 cluster.connect();
113115
@@ -124,7 +126,7 @@
124126 verify(socketOptions, atLeast(6)).getKeepAlive();
125127 verify(socketOptions, atMost(7)).getKeepAlive();
126128
127- assertThat(cluster).host(realHostAddress).hasState(UP);
129+ assertThat(cluster).host(realHostAddress).isNotNull().hasState(UP);
128130 for (FakeHost failingHost : failingHosts)
129131 assertThat(cluster).host(failingHost.address).hasState(DOWN);
130132 assertThat(cluster).host(missingHostAddress).isNull();
added driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +135 −0
@@ -0,0 +1,135 @@
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.Collection;
19+import java.util.concurrent.CountDownLatch;
20+import java.util.concurrent.CyclicBarrier;
21+import java.util.concurrent.TimeUnit;
22+
23+import org.testng.annotations.Test;
24+
25+import static org.assertj.core.api.Assertions.assertThat;
26+import static org.assertj.core.api.Fail.fail;
27+
28+import static com.datastax.driver.core.CCMBridge.ipOfNode;
29+
30+public class EventDebouncerIntegrationTest {
31+
32+ /**
33+ * Tests that DOWN, UP, REMOVE or ADD events will not be delivered to
34+ * load balancing policy nor host state listeners
35+ * before the cluster is fully initialized.
36+ *
37+ * @throws InterruptedException
38+ * @jira_ticket JAVA-784
39+ * @since 2.0.11
40+ */
41+ @Test(groups = "long")
42+ public void should_wait_until_load_balancing_policy_is_fully_initialized() throws InterruptedException {
43+ TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy();
44+ CCMBridge ccm = CCMBridge.builder("main").withNodes(3).build();
45+ final Cluster cluster = new Cluster.Builder()
46+ .addContactPoints(ipOfNode(1))
47+ .withLoadBalancingPolicy(policy)
48+ .withQueryOptions(new QueryOptions()
49+ .setRefreshNodeIntervalMillis(0)
50+ .setRefreshNodeListIntervalMillis(0)
51+ .setRefreshSchemaIntervalMillis(0)
52+ ).build();
53+ try {
54+ new Thread() {
55+ @Override
56+ public void run() {
57+ cluster.init();
58+ }
59+ }.start();
60+ // stop cluster initialization in the middle of LBP initialization
61+ policy.stop();
62+ // generate a DOWN event - will not be delivered immediately
63+ // because the debouncers are not started
64+ // note: a graceful stop notify other nodes which send a topology change event to the driver right away
65+ // while forceStop kills the node so other nodes take much more time to detect node failure
66+ ccm.stop(3);
67+ ccm.waitForDown(3);
68+ // finish cluster initialization and deliver the DOWN event
69+ policy.proceed();
70+ assertThat(policy.onDownCalledBeforeInit).isFalse();
71+ assertThat(policy.onDownCalled()).isTrue();
72+ assertThat(policy.hosts).doesNotContain(TestUtils.findHost(cluster, 3));
73+ } finally {
74+ if (cluster != null)
75+ cluster.close();
76+ ccm.remove("main");
77+ }
78+ }
79+
80+ private class TestLoadBalancingPolicy extends SortingLoadBalancingPolicy {
81+
82+ CyclicBarrier stop = new CyclicBarrier(2);
83+
84+ CyclicBarrier proceed = new CyclicBarrier(2);
85+
86+ CountDownLatch onDownCalled = new CountDownLatch(1);
87+
88+ volatile boolean init = false;
89+
90+ volatile boolean onDownCalledBeforeInit = false;
91+
92+ @Override
93+ public void init(Cluster cluster, Collection<Host> hosts) {
94+ try {
95+ stop.await(1, TimeUnit.MINUTES);
96+ proceed.await(1, TimeUnit.MINUTES);
97+ } catch (Exception e) {
98+ fail(e.getMessage());
99+ }
100+ super.init(cluster, hosts);
101+ init = true;
102+ }
103+
104+ @Override
105+ public void onDown(Host host) {
106+ if (!init)
107+ onDownCalledBeforeInit = true;
108+ super.onDown(host);
109+ if (host.getAddress().toString().contains(ipOfNode(3)))
110+ onDownCalled.countDown();
111+ }
112+
113+ void stop() throws InterruptedException {
114+ try {
115+ stop.await(1, TimeUnit.MINUTES);
116+ } catch (Exception e) {
117+ fail(e.getMessage());
118+ }
119+ }
120+
121+ void proceed() throws InterruptedException {
122+ try {
123+ proceed.await(1, TimeUnit.MINUTES);
124+ } catch (Exception e) {
125+ fail(e.getMessage());
126+ }
127+ }
128+
129+ boolean onDownCalled() throws InterruptedException {
130+ return onDownCalled.await(1, TimeUnit.MINUTES);
131+ }
132+
133+ }
134+
135+}
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/MetadataTest.java +2 −0
@@ -21,6 +21,7 @@
2121 import org.testng.annotations.Test;
2222
2323 import static com.datastax.driver.core.Assertions.assertThat;
24+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2425 import static com.datastax.driver.core.TestUtils.waitFor;
2526
2627 public class MetadataTest {
@@ -58,6 +59,7 @@
5859
5960 cluster = Cluster.builder()
6061 .addContactPoint(CCMBridge.ipOfNode(1))
62+ .withQueryOptions(nonDebouncingQueryOptions())
6163 .build();
6264 Session session = cluster.connect();
6365
added driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +121 −0
@@ -0,0 +1,121 @@
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.Collection;
19+
20+import org.testng.annotations.*;
21+
22+import static com.google.common.collect.Lists.newArrayList;
23+import static org.mockito.Mockito.reset;
24+import static org.mockito.Mockito.spy;
25+import static org.mockito.Mockito.timeout;
26+import static org.mockito.Mockito.times;
27+import static org.mockito.Mockito.verify;
28+
29+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
30+
31+public class NodeListRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
32+
33+ private static final int DEBOUNCE_TIME = 2000;
34+
35+ QueryOptions queryOptions;
36+
37+ Cluster cluster2;
38+
39+ Session session2;
40+
41+ // Control Connection to be spied.
42+ private ControlConnection controlConnection;
43+
44+ // Keyspaces to drop after test completes.
45+ private Collection<String> keyspaces = newArrayList();
46+
47+ @Override
48+ protected Collection<String> getTableDefinitions() {
49+ return newArrayList();
50+ }
51+
52+ @BeforeClass(groups = "short")
53+ public void setup() {
54+ queryOptions = new QueryOptions();
55+ queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME);
56+ queryOptions.setMaxPendingRefreshNodeListRequests(5);
57+ // Create a separate cluster that will receive the schema events on its control connection.
58+ cluster2 = this.configure(Cluster.builder())
59+ .addContactPointsWithPorts(newArrayList(hostAddress))
60+ .withQueryOptions(queryOptions)
61+ .build();
62+ session2 = cluster2.connect();
63+
64+ // Create a spy of the Cluster's control connection and replace it with the spy.
65+ controlConnection = spy(cluster2.manager.controlConnection);
66+ cluster2.manager.controlConnection = controlConnection;
67+ reset(controlConnection);
68+ }
69+
70+ @AfterMethod(groups = "short")
71+ public void beforeMethod() {
72+ reset(controlConnection);
73+ }
74+
75+ @AfterClass(groups = "short")
76+ public void teardown() {
77+ cluster2.close();
78+ // drop all keyspaces
79+ for(String keyspace : keyspaces) {
80+ session.execute("DROP KEYSPACE " + keyspace);
81+ }
82+ }
83+
84+ /**
85+ * Ensures that when a keyspace is created that refresh node list request
86+ * is debounced and processed within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
87+ * + {@link QueryOptions#getRefreshNodeListIntervalMillis()}.
88+ *
89+ * @jira_ticket JAVA-657
90+ * @since 2.0.11
91+ */
92+ @Test(groups = "short")
93+ public void should_debounce_refresh_when_keyspace_created() {
94+ String keyspace = "sdrwkc";
95+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
96+ keyspaces.add(keyspace);
97+
98+ verify(controlConnection, timeout(DEBOUNCE_TIME + queryOptions.getRefreshSchemaIntervalMillis())).refreshNodeListAndTokenMap();
99+ }
100+
101+ /**
102+ * Ensures that when enough refreshNodeList requests have been received
103+ * to reach {@link QueryOptions#getMaxPendingRefreshNodeListRequests()} that a
104+ * node list refresh is submitted right away.
105+ *
106+ * @jira_ticket JAVA-657
107+ * @since 2.0.11
108+ */
109+ @Test(groups = "short")
110+ public void should_refresh_when_max_pending_requests_reached() {
111+ // Enable and disable schema management 5 times to cause
112+ // refreshNodeListAndTokenMap to be called.
113+ for(int i = 0; i < 5; i++) {
114+ queryOptions.setMetadataEnabled(false);
115+ queryOptions.setMetadataEnabled(true);
116+ }
117+
118+ // add a 1 second delay to account for executor submit.
119+ verify(controlConnection, timeout(1000).times(1)).refreshNodeListAndTokenMap();
120+ }
121+}
added driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +81 −0
@@ -0,0 +1,81 @@
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.Collection;
19+import java.util.concurrent.TimeUnit;
20+
21+import org.mockito.ArgumentCaptor;
22+import org.testng.annotations.Test;
23+
24+import static com.google.common.collect.Lists.newArrayList;
25+import static org.mockito.ArgumentCaptor.forClass;
26+import static org.mockito.Mockito.mock;
27+import static org.mockito.Mockito.timeout;
28+import static org.mockito.Mockito.verify;
29+
30+import static com.datastax.driver.core.Assertions.assertThat;
31+
32+public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ @Override
35+ protected Collection<String> getTableDefinitions() {
36+ return newArrayList();
37+ }
38+
39+ /**
40+ * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently
41+ * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)} that an 'onAdd' event
42+ * event is the only one processed and that the {@link Host} is marked up.
43+ * <p>
44+ * Since NEW_NODE_DELAY_SECONDS is typically configured with a high value (60 seconds default
45+ * in the maven profile) this test can take a very long time.
46+ *
47+ * @jira_ticket JAVA-657
48+ * @since 2.0.11
49+ */
50+ @Test(groups="long")
51+ public void should_call_onAdd_with_bootstrap_stop_start() {
52+ int refreshNodeInterval = 10000;
53+ QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval);
54+ CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build();
55+ Cluster cluster = Cluster.builder()
56+ .addContactPoint(CCMBridge.ipOfNode(1))
57+ .withQueryOptions(queryOptions)
58+ .build();
59+
60+ try {
61+ cluster.connect();
62+ Host.StateListener listener = mock(Host.StateListener.class);
63+ cluster.register(listener);
64+ ccm.bootstrapNode(2);
65+ ccm.stop(2);
66+ ccm.start(2);
67+
68+ ArgumentCaptor<Host> captor = forClass(Host.class);
69+
70+ // Only onAdd should be called, since stop and start should be discarded.
71+ verify(listener, timeout(refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS)).only()).onAdd(captor.capture());
72+
73+ // The hosts state should be UP.
74+ assertThat(captor.getValue().getState()).isEqualTo("UP");
75+ assertThat(cluster).host(2).hasState(Host.State.UP);
76+ } finally {
77+ cluster.close();
78+ ccm.remove();
79+ }
80+ }
81+}
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +16 −7
@@ -108,6 +108,11 @@
108108 return defs;
109109 }
110110
111+ @Override
112+ protected Cluster.Builder configure(Cluster.Builder builder) {
113+ return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions());
114+ }
115+
111116 @Test(groups = "short")
112117 public void preparedNativeTest() {
113118 // Test preparing/bounding for all native types
@@ -322,12 +327,12 @@
322327 }
323328 }
324329
325- @Test(groups = "long")
330+ @Test(groups = "long", priority = Integer.MAX_VALUE)
326331 public void reprepareOnNewlyUpNodeTest() throws Exception {
327332 reprepareOnNewlyUpNodeTest(null, session);
328333 }
329334
330- @Test(groups = "long")
335+ @Test(groups = "long", priority = Integer.MAX_VALUE)
331336 public void reprepareOnNewlyUpNodeNoKeyspaceTest() throws Exception {
332337
333338 // This is the same test than reprepareOnNewlyUpNodeTest, except that the
@@ -442,10 +447,14 @@
442447 Cluster otherCluster = Cluster.builder()
443448 .addContactPointsWithPorts(ImmutableList.of(hostAddress))
444449 .build();
445- PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
446- BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
447-
448- // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
449- session.executeAsync(bs);
450+ try {
451+ PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
452+ BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
453+
454+ // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
455+ session.executeAsync(bs);
456+ } finally {
457+ otherCluster.close();
458+ }
450459 }
451460 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +9 −5
@@ -28,7 +28,7 @@
2828 import static com.datastax.driver.core.Assertions.*;
2929 import static com.datastax.driver.core.Host.State.DOWN;
3030 import static com.datastax.driver.core.Host.State.UP;
31-
31+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3232
3333 /**
3434 * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
@@ -50,7 +50,8 @@
5050 mainCcm.waitForDown(1);
5151
5252 // Now start the driver that will connect to node2 and node3, and consider node1 down
53- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
53+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
54+ .withQueryOptions(nonDebouncingQueryOptions()).build();
5455 mainCluster.connect();
5556 waitForCountUpHosts(mainCluster, 2);
5657 // From that point, reconnections to node1 have been scheduled.
@@ -72,7 +73,8 @@
7273 mainCcm.waitForDown(1);
7374
7475 // Start the driver, the control connection will be on node2
75- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
76+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
77+ .withQueryOptions(nonDebouncingQueryOptions()).build();
7678 mainCluster.connect();
7779 waitForCountUpHosts(mainCluster, 1);
7880
@@ -99,7 +101,8 @@
99101 otherCcm.waitForUp(1);
100102
101103 // Start the driver, it should only connect to node 2
102- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
104+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
105+ .withQueryOptions(nonDebouncingQueryOptions()).build();
103106
104107 // When we first initialize the Cluster, all hosts are marked UP
105108 assertThat(mainCluster).host(2).hasState(UP);
@@ -127,7 +130,8 @@
127130 otherCcm.waitForUp(1);
128131
129132 // Start the driver, it should only connect to node 2
130- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
133+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
134+ .withQueryOptions(nonDebouncingQueryOptions()).build();
131135
132136 // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
133137 mainCluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +1 −0
@@ -53,6 +53,7 @@
5353 .withPoolingOptions(poolingOptions)
5454 .withLoadBalancingPolicy(loadBalancingPolicy)
5555 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
56+ .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
5657 .build();
5758
5859 Session session = cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +149 −5
@@ -25,15 +25,14 @@
2525 import org.mockito.ArgumentCaptor;
2626 import org.testng.annotations.*;
2727
28-import static org.mockito.Mockito.mock;
29-import static org.mockito.Mockito.reset;
30-import static org.mockito.Mockito.timeout;
31-import static org.mockito.Mockito.verify;
28+import static org.mockito.Matchers.any;
29+import static org.mockito.Mockito.*;
3230
3331 import com.datastax.driver.core.utils.Bytes;
3432
3533 import static com.datastax.driver.core.Assertions.assertThat;
3634 import static com.datastax.driver.core.Metadata.handleId;
35+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3736
3837 public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
3938
@@ -50,17 +49,23 @@
5049
5150 Cluster cluster1;
5251 Cluster cluster2; // a second cluster to check that other clients also get notified
52+ Cluster schemaDisabledCluster; // a cluster with schema metadata disabled.
5353
5454 // The metadatas of the two clusters (we'll test that they're kept in sync)
5555 List<Metadata> metadatas;
5656
5757 Session session1;
5858
59+ Session schemaDisabledSession;
60+
5961 SchemaChangeListener listener1;
6062 SchemaChangeListener listener2;
63+ SchemaChangeListener schemaDisabledListener;
6164
6265 List<SchemaChangeListener> listeners;
6366
67+ ControlConnection schemaDisabledControlConnection;
68+
6469 @Override
6570 protected Collection<String> getTableDefinitions() {
6671 return Lists.newArrayList();
@@ -68,9 +73,22 @@
6873
6974 @BeforeClass(groups = "short")
7075 public void setup() throws InterruptedException {
71- Cluster.Builder builder = configure(Cluster.builder()).addContactPointsWithPorts(Collections.singletonList(hostAddress));
76+ Cluster.Builder builder = configure(Cluster.builder())
77+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
78+ .withQueryOptions(nonDebouncingQueryOptions());
7279 cluster1 = builder.build();
7380 cluster2 = builder.build();
81+ schemaDisabledCluster = spy(configure(Cluster.builder())
82+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
83+ .withClusterName("schema-disabled")
84+ .withQueryOptions(nonDebouncingQueryOptions()
85+ .setMetadataEnabled(false)
86+ ).build());
87+
88+ schemaDisabledSession = schemaDisabledCluster.connect();
89+
90+ schemaDisabledControlConnection = spy(schemaDisabledCluster.manager.controlConnection);
91+ schemaDisabledCluster.manager.controlConnection = schemaDisabledControlConnection;
7492
7593 metadatas = Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
7694
@@ -80,6 +98,9 @@
8098 cluster1.register(listener2 = mock(SchemaChangeListener.class));
8199 listeners = Lists.newArrayList(listener1, listener2);
82100
101+ schemaDisabledCluster.register(schemaDisabledListener = mock(SchemaChangeListener.class));
102+ verify(schemaDisabledListener, times(1)).onRegister(schemaDisabledCluster);
103+
83104 execute(CREATE_KEYSPACE, "lowercase");
84105 execute(CREATE_KEYSPACE, "\"CaseSensitive\"");
85106 }
@@ -90,6 +111,8 @@
90111 cluster1.close();
91112 if (cluster2 != null)
92113 cluster2.close();
114+ if (schemaDisabledCluster != null)
115+ schemaDisabledCluster.close();
93116 }
94117
95118 @DataProvider(name = "existingKeyspaceName")
@@ -107,6 +130,19 @@
107130 for (SchemaChangeListener listener : listeners) {
108131 reset(listener);
109132 }
133+ reset(schemaDisabledControlConnection);
134+ }
135+
136+ /**
137+ * Ensures that a listener registered on a Cluster that has schema metadata disabled
138+ * is never invoked with schema change events.
139+ *
140+ * @jira_ticket JAVA-858
141+ * @since 2.0.11
142+ */
143+ @AfterMethod(groups = "short")
144+ public void verifyNoMoreInteractionsWithListener() {
145+ verifyNoMoreInteractions(schemaDisabledListener);
110146 }
111147
112148 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -119,6 +155,7 @@
119155 .isInKeyspace(handleId(keyspace))
120156 .hasName("table1");
121157 }
158+
122159 for (Metadata m : metadatas)
123160 assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull();
124161 }
@@ -237,6 +274,113 @@
237274 }
238275 }
239276
277+
278+ /**
279+ * Ensures that calling {@link Metadata#newToken(String)} on a Cluster that has schema
280+ * metadata disabled will throw a {@link IllegalStateException}.
281+ *
282+ * @jira_ticket JAVA-858
283+ * @since 2.0.11
284+ */
285+ @Test(groups = "short", expectedExceptions = IllegalStateException.class)
286+ public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
287+ Cluster cluster = configure(Cluster.builder())
288+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
289+ .withQueryOptions(nonDebouncingQueryOptions()
290+ .setMetadataEnabled(false)
291+ ).build();
292+
293+ try {
294+ cluster.init();
295+ cluster.getMetadata().newToken("0x00");
296+ } finally {
297+ cluster.close();
298+ }
299+ }
300+
301+
302+ /**
303+ * Ensures that calling {@link Metadata#newTokenRange(Token, Token)} on a Cluster that has schema
304+ * metadata disabled will throw a {@link IllegalStateException}.
305+ *
306+ * @jira_ticket JAVA-858
307+ * @since 2.0.11
308+ */
309+ @Test(groups = "short", expectedExceptions = IllegalStateException.class)
310+ public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
311+ Cluster cluster = configure(Cluster.builder())
312+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
313+ .withQueryOptions(nonDebouncingQueryOptions()
314+ .setMetadataEnabled(false)
315+ ).build();
316+
317+ try {
318+ cluster.init();
319+ Token.Factory factory = Token.getFactory("Murmur3Partitioner");
320+ Token token = factory.fromString(Long.toString(1));
321+ cluster.getMetadata().newTokenRange(token, token);
322+ } finally {
323+ cluster.close();
324+ }
325+ }
326+
327+ /**
328+ * Ensures that executing a query causing a schema change with a Cluster that has schema metadata
329+ * disabled will still wait on schema agreement, but not refresh the schema.
330+ *
331+ * @jira_ticket JAVA-858
332+ * @since 2.0.11
333+ */
334+ @Test(groups = "short")
335+ public void should_not_refresh_schema_on_schema_change_response() throws InterruptedException {
336+ ResultSet rs = schemaDisabledSession.execute(String.format(CREATE_TABLE, keyspace));
337+
338+ // Should still wait on schema agreement.
339+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
340+ assertThat(schemaDisabledCluster.getMetadata().checkSchemaAgreement()).isTrue();
341+
342+ // Wait up to 1 second (since refreshSchema submitted in an executor) and check that refreshSchema never called.
343+ verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(any(String.class), any(String.class));
344+ }
345+
346+ /**
347+ * Ensures that when schema metadata is enabled using {@link QueryOptions#setMetadataEnabled(boolean)}
348+ * that a schema and nodelist refresh is submitted, but only if schema metadata is currently disabled.
349+ *
350+ * @jira_ticket JAVA-858
351+ * @since 2.0.11
352+ */
353+ @Test(groups = "short")
354+ public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled() throws Exception {
355+ try {
356+ schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
357+
358+ verify(schemaDisabledControlConnection, after(1000)).refreshSchema(null, null);
359+ // TODO: Remove atLeastOnce() if submitNodeRefresh removed from setMetadataEnabled.
360+ verify(schemaDisabledControlConnection, atLeastOnce()).refreshNodeListAndTokenMap();
361+
362+ // Ensure that there is schema metadata.
363+ assertThat(schemaDisabledCluster.getMetadata().getKeyspace(keyspace)).isNotNull();
364+ Token token1 = schemaDisabledCluster.getMetadata().newToken("0");
365+ Token token2 = schemaDisabledCluster.getMetadata().newToken("111111");
366+ assertThat(token1).isNotNull();
367+ assertThat(token2).isNotNull();
368+ assertThat(schemaDisabledCluster.getMetadata().newTokenRange(token1, token2)).isNotNull();
369+
370+ assertThat(schemaDisabledCluster.getMetadata().getTokenRanges()).isNotNull().isNotEmpty();
371+
372+ // Try enabling again and ensure schema is not refreshed again.
373+ reset(schemaDisabledControlConnection);
374+ schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
375+ verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(null, null);
376+ verify(schemaDisabledControlConnection, never()).refreshNodeListAndTokenMap();
377+ } finally {
378+ // Reset listener mock to not count it's interactions in this test.
379+ reset(schemaDisabledListener);
380+ schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(false);
381+ }
382+ }
383+
240384 @AfterMethod(groups = "short")
241385 public void cleanup() throws InterruptedException {
242386 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
added driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +313 −0
@@ -0,0 +1,313 @@
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.Collection;
19+
20+import org.mockito.ArgumentCaptor;
21+import org.testng.annotations.AfterClass;
22+import org.testng.annotations.AfterMethod;
23+import org.testng.annotations.BeforeClass;
24+import org.testng.annotations.Test;
25+
26+import static com.google.common.collect.Lists.newArrayList;
27+import static org.mockito.ArgumentCaptor.forClass;
28+import static org.mockito.Mockito.*;
29+
30+import static com.datastax.driver.core.Assertions.assertThat;
31+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
32+import static com.datastax.driver.core.TestUtils.CREATE_TABLE_SIMPLE_FORMAT;
33+
34+public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ // This may need to be tweaked depending on the reliability of the test environment.
37+ private static final int DEBOUNCE_TIME = 5000;
38+
39+ // Control Connection to be spied.
40+ private ControlConnection controlConnection;
41+
42+ // Schema Listener to be mocked.
43+ private SchemaChangeListener listener;
44+
45+ // Separate session/clusters to observe schema events on.
46+ private Session session2;
47+ private Cluster cluster2;
48+
49+ // Keyspaces to drop after test completes.
50+ private Collection<String> keyspaces = newArrayList();
51+
52+ @Override
53+ protected Collection<String> getTableDefinitions() {
54+ return newArrayList();
55+ }
56+
57+ @BeforeClass(groups = "short")
58+ public void setup() {
59+ QueryOptions queryOptions = new QueryOptions();
60+ queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME);
61+ queryOptions.setMaxPendingRefreshSchemaRequests(5);
62+ // Create a separate cluster that will receive the schema events on its control connection.
63+ cluster2 = this.configure(Cluster.builder())
64+ .addContactPointsWithPorts(newArrayList(hostAddress))
65+ .withQueryOptions(queryOptions)
66+ .build();
67+ session2 = cluster2.connect();
68+
69+ // Create a spy of the Cluster's control connection and replace it with the spy.
70+ controlConnection = spy(cluster2.manager.controlConnection);
71+ cluster2.manager.controlConnection = controlConnection;
72+
73+ // Create a mock of SchemaChangeListener to use for signalling events.
74+ listener = mock(SchemaChangeListener.class);
75+ cluster2.register(listener);
76+
77+ reset(listener);
78+ reset(controlConnection);
79+ }
80+
81+ @AfterMethod(groups = "short")
82+ public void beforeMethod() {
83+ reset(listener);
84+ reset(controlConnection);
85+ }
86+
87+ @AfterClass(groups = "short")
88+ public void teardown() {
89+ cluster2.close();
90+ // drop all keyspaces
91+ for(String keyspace : keyspaces) {
92+ session.execute("DROP KEYSPACE " + keyspace);
93+ }
94+ }
95+
96+ /**
97+ * Ensures that when a CREATED and UPDATED schema_change events are received on a control
98+ * connection for the same keyspace within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
99+ * that the schema refresh is debounced and coalesced into a single schema refresh for that keyspace only.
100+ *
101+ * @throws Exception
102+ * @jira_ticket JAVA-657
103+ * @since 2.0.11
104+ */
105+ @Test(groups = "short")
106+ public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception {
107+ String keyspace = "sdaccaak";
108+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
109+ keyspaces.add(keyspace);
110+ session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
111+
112+ ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class);
113+ verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onKeyspaceAdded(captor.capture());
114+ assertThat(captor.getValue()).hasName(keyspace).isNotDurableWrites();
115+
116+ // Verify that the schema refresh was debounced and coalesced when a keyspace creation
117+ // and update event occur for the same keyspace.
118+ verify(controlConnection, times(1)).refreshSchema(keyspace, null);
119+
120+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
121+ // By ensuring durable writes is false, we know that the single schema refresh occurred
122+ // after the alter event.
123+ assertThat(ksm).isNotNull().hasName(keyspace).isNotDurableWrites();
124+ }
125+
126+
127+ /**
128+ * Ensures that when a CREATED (keyspace) and CREATED (table) schema_change events are received
129+ * on a control connection with that table belonging to that keyspace within
130+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
131+ * and coalesced into a single schema refresh for that keyspace only.
132+ *
133+ * @throws Exception
134+ * @jira_ticket JAVA-657
135+ * @since 2.0.11
136+ */
137+ @Test(groups = "short")
138+ public void should_debounce_and_coalesce_create_keyspace_and_table_into_refresh_keyspace() throws Exception {
139+ String keyspace = "sdacckt";
140+ String table = "tbl1";
141+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
142+ keyspaces.add(keyspace);
143+ session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table));
144+
145+ ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class);
146+ verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onKeyspaceAdded(keyspaceCaptor.capture());
147+ assertThat(keyspaceCaptor.getValue()).hasName(keyspace);
148+
149+ ArgumentCaptor<TableMetadata> tableCaptor = forClass(TableMetadata.class);
150+ verify(listener, times(1)).onTableAdded(tableCaptor.capture());
151+ assertThat(tableCaptor.getValue()).hasName(table);
152+
153+ // Verify the schema refresh was debounced and coalesced when a keyspace event and table event
154+ // in that keyspace is detected.
155+ verify(controlConnection).refreshSchema(keyspace, null);
156+ verify(controlConnection, never()).refreshSchema(keyspace, table);
157+
158+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
159+ assertThat(ksm).isNotNull();
160+ assertThat(ksm.getTable(table)).isNotNull();
161+ }
162+
163+ /**
164+ * Ensures that when multiple CREATED schema_change events are received
165+ * on a control connection for tables belonging to the same keyspace within
166+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
167+ * and coalesced into a single schema refresh for that keyspace only.
168+ *
169+ * @throws Exception
170+ * @jira_ticket JAVA-657
171+ * @since 2.0.11
172+ */
173+ @Test(groups = "short")
174+ public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception {
175+ String keyspace = "sdactisk";
176+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
177+ keyspaces.add(keyspace);
178+ // Reset invocations as creating keyspace causes a keyspace refresh.
179+ reset(controlConnection);
180+ reset(listener);
181+
182+ int tableCount = 3;
183+ for(int i =0 ; i < tableCount; i++) {
184+ session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + "tbl" + i));
185+ }
186+
187+ verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onTableAdded(any(TableMetadata.class));
188+
189+ // Verify a refresh of the keyspace was executed, but not individually on the
190+ // tables since those events were coalesced.
191+ verify(controlConnection).refreshSchema(keyspace, null);
192+
193+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
194+ assertThat(ksm).isNotNull();
195+ // metadata is present for each table.
196+ for(int i = 0; i < tableCount; i++) {
197+ String table = "tbl" + i;
198+ // Should have never been a refreshSchema on the table.
199+ verify(controlConnection, never()).refreshSchema(keyspace, table);
200+ assertThat(ksm.getTable(table)).isNotNull();
201+ }
202+ }
203+
204+ /**
205+ * Ensures that when multiple UPDATED schema_change events are received
206+ * on a control connection for for the same table within
207+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
208+ * and coalesced into a single schema refresh for that table only.
209+ *
210+ * @throws Exception
211+ * @jira_ticket JAVA-657
212+ * @since 2.0.11
213+ */
214+ @Test(groups = "short")
215+ public void should_debounce_and_coalesce_multiple_alter_events_on_same_table_into_refresh_table() throws Exception {
216+ String keyspace = "sdacmaeost";
217+ String table = "tbl1";
218+ String comment = "I am changing this table.";
219+ String columnName = "added_column";
220+ // Execute on session 2 which refreshes schema as part of processing responses.
221+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
222+ keyspaces.add(keyspace);
223+ session2.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table));
224+ reset(controlConnection);
225+ reset(listener);
226+
227+ session.execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment));
228+ session.execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName));
229+
230+ ArgumentCaptor<TableMetadata> original = forClass(TableMetadata.class);
231+ ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
232+ verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onTableChanged(captor.capture(), original.capture());
233+ assertThat(captor.getValue())
234+ .hasName(table)
235+ .isInKeyspace(keyspace)
236+ .hasColumn(columnName)
237+ .hasComment(comment);
238+
239+ assertThat(original.getValue())
240+ .hasName(table)
241+ .isInKeyspace(keyspace)
242+ .hasNoColumn(columnName)
243+ .doesNotHaveComment(comment);
244+
245+ // Verify a refresh of the table was executed, but only once.
246+ verify(controlConnection, times(1)).refreshSchema(keyspace, table);
247+
248+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
249+ assertThat(ksm).isNotNull();
250+ TableMetadata tm = ksm.getTable(table);
251+ assertThat(tm)
252+ .hasName(table)
253+ .isInKeyspace(keyspace)
254+ .hasColumn(columnName)
255+ .hasComment(comment);
256+ }
257+
258+ /**
259+ * Ensures that when a CREATED (keyspace) and CREATED (keyspace) schema_change events are received
260+ * on a control connection for different keyspaces within
261+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
262+ * and coalesced into a single full schema refresh.
263+ *
264+ * @throws Exception
265+ * @jira_ticket JAVA-657
266+ * @since 2.0.11
267+ */
268+ @Test(groups = "short")
269+ public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
270+ String prefix = "sdacmkc";
271+ for(int i = 0; i < 3; i++) {
272+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
273+ keyspaces.add(prefix + i);
274+ }
275+
276+ verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
277+ // Verify a complete schema refresh was executed, but only once.
278+ verify(controlConnection, times(1)).refreshSchema(null, null);
279+
280+ for(int i = 0; i < 3; i++) {
281+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
282+ assertThat(ksm).isNotNull().hasName(prefix + i);
283+ }
284+ }
285+
286+ /**
287+ * Ensures that when enough schema changes have been received on a control connection to
288+ * reach {@link QueryOptions#getMaxPendingRefreshSchemaRequests()} that a schema refresh
289+ * is submitted right away.
290+ *
291+ * @throws Exception
292+ * @jira_ticket JAVA-657
293+ * @since 2.0.11
294+ */
295+ @Test(groups = "short")
296+ public void should_refresh_when_max_pending_requests_reached() throws Exception {
297+ String prefix = "srwmprr";
298+ for(int i = 0; i < 5; i++) {
299+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
300+ keyspaces.add(prefix + i);
301+ }
302+
303+ // Event should be processed immediately as we hit our threshold.
304+ verify(listener, times(5)).onKeyspaceAdded(any(KeyspaceMetadata.class));
305+ // Verify a complete schema refresh was executed, but only once.
306+ verify(controlConnection, times(1)).refreshSchema(null, null);
307+
308+ for(int i = 0; i < 5; i++) {
309+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
310+ assertThat(ksm).isNotNull().hasName(prefix + i);
311+ }
312+ }
313+}
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +9 −0
@@ -30,6 +30,15 @@
3030
3131 private static String withOptions;
3232
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+
3342 @Override
3443 protected Collection<String> getTableDefinitions() {
3544
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +4 −2
@@ -32,7 +32,7 @@
3232 import com.datastax.driver.core.exceptions.InvalidQueryException;
3333
3434 import static com.datastax.driver.core.Assertions.assertThat;
35-
35+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3636
3737 public class SessionLeakTest {
3838
@@ -53,7 +53,9 @@
5353 cluster = Cluster.builder()
5454 .addContactPointsWithPorts(Collections.singletonList(
5555 new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
56- .withNettyOptions(channelMonitor.nettyOptions()).build();
56+ .withNettyOptions(channelMonitor.nettyOptions())
57+ .withQueryOptions(nonDebouncingQueryOptions())
58+ .build();
5759
5860 cluster.init();
5961
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +8 −1
@@ -39,7 +39,14 @@
3939 .withCassandraConfiguration("initial_token", "1")
4040 .build();
4141
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();
4350
4451 Session session = cluster.connect();
4552 session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
modified driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +1 −1
@@ -31,7 +31,7 @@
3131 */
3232 public class SortingLoadBalancingPolicy implements LoadBalancingPolicy {
3333
34- private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
34+ final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
3535 @Override
3636 public int compare(Host host1, Host host2) {
3737 byte[] address1 = host1.getAddress().getAddress();
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +10 −0
@@ -50,4 +50,14 @@
5050 assertThat(actual.getColumn(columnName)).isNull();
5151 return this;
5252 }
53+
54+ public TableMetadataAssert hasComment(String comment) {
55+ assertThat(actual.getOptions().getComment()).isEqualTo(comment);
56+ return this;
57+ }
58+
59+ public TableMetadataAssert doesNotHaveComment(String comment) {
60+ assertThat(actual.getOptions().getComment()).isNotEqualTo(comment);
61+ return this;
62+ }
5363 }
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +10 −1
@@ -32,9 +32,18 @@
3232 );
3333 }
3434
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+
3544 @Test(groups = "short")
3645 public void should_escape_single_quote_table_comment() {
3746 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote");
3847 assertThat(table.asCQLQuery()).contains("comment with single quote '' should work");
3948 }
40-}
No newline at the end of the file
49+}
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +13 −2
@@ -24,6 +24,7 @@
2424 import java.nio.ByteBuffer;
2525 import java.util.*;
2626
27+import com.google.common.util.concurrent.Futures;
2728 import org.scassandra.Scassandra;
2829 import org.scassandra.ScassandraFactory;
2930 import org.slf4j.Logger;
@@ -323,8 +324,9 @@
323324 // tried doing an actual query, the driver won't realize that last node is dead until
324325 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
325326 // 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+ }
328330
329331 InetAddress address;
330332 try {
@@ -454,4 +456,13 @@
454456 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
455457 .build();
456458 }
459+
460+ /**
461+ * @return a {@QueryOptions} that disables debouncing by setting intervals to 0ms.
462+ */
463+ public static QueryOptions nonDebouncingQueryOptions() {
464+ return new QueryOptions().setRefreshNodeIntervalMillis(0)
465+ .setRefreshNodeListIntervalMillis(0)
466+ .setRefreshSchemaIntervalMillis(0);
467+ }
457468 }
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +5 −0
@@ -81,6 +81,11 @@
8181 cluster = Cluster.builder()
8282 .addContactPoints(CCMBridge.ipOfNode(1))
8383 .withLoadBalancingPolicy(lbp)
84+ .withQueryOptions(new QueryOptions()
85+ .setRefreshNodeIntervalMillis(0)
86+ .setRefreshNodeListIntervalMillis(0)
87+ .setRefreshSchemaIntervalMillis(0)
88+ )
8489 .build();
8590 cluster.init();
8691 session = cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +3 −0
@@ -25,6 +25,8 @@
2525 import com.datastax.driver.core.*;
2626 import com.datastax.driver.core.utils.Bytes;
2727
28+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
29+
2830 public class TokenAwarePolicyTest {
2931 @Test(groups = "long")
3032 public void should_shuffle_replicas_when_requested() {
@@ -46,6 +48,7 @@
4648 cluster = Cluster.builder()
4749 .addContactPoint(CCMBridge.ipOfNode(1))
4850 .withLoadBalancingPolicy(loadBalancingPolicy)
51+ .withQueryOptions(nonDebouncingQueryOptions())
4952 .build();
5053
5154 String keyspace = "ks";
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +9 −0
@@ -40,6 +40,15 @@
4040 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4141 }
4242
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+
4352 @Test(groups = "short")
4453 public void remainingDeleteTests() throws Exception {
4554
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +9 −0
@@ -39,6 +39,15 @@
3939 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4040 }
4141
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+
4251 @Test(groups = "short")
4352 public void textRoutingKeyTest() throws Exception {
4453