kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | a9c3f7efad0e97371d6ad96dece85cb772ac0197413cf5e261d064c667d4ac22 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-08-14 19:10 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-08-14 19:10 +02:00 |
| Parents | dc07c7b283df, 0648dd431f7f |
30 files changed
modified changelog/README.md +3 −0
| @@ -35,6 +35,9 @@ | ||
| 35 | 35 | - [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658) |
| 36 | 36 | - [improvement] Customizable creation of netty timer (JAVA-853) |
| 37 | 37 | - [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859) |
| 38 | +- [improvement] Debounce control connection queries (JAVA-657) | |
| 39 | +- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784) | |
| 40 | +- [new feature] Make driver-side metadata optional (JAVA-828) | |
| 38 | 41 | |
| 39 | 42 | Merged from 2.0.10_fixes branch: |
| 40 | 43 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +321 −90
| @@ -37,6 +37,7 @@ | ||
| 37 | 37 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 38 | 38 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 39 | 39 | import com.datastax.driver.core.policies.*; |
| 40 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 40 | 41 | |
| 41 | 42 | /** |
| 42 | 43 | * Information and known state of a Cassandra cluster. |
| @@ -1243,6 +1244,10 @@ | ||
| 1243 | 1244 | final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>(); |
| 1244 | 1245 | final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>(); |
| 1245 | 1246 | |
| 1247 | + EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer; | |
| 1248 | + EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer; | |
| 1249 | + EventDebouncer<SchemaRefreshRequest> schemaRefreshRequestDebouncer; | |
| 1250 | + | |
| 1246 | 1251 | private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) { |
| 1247 | 1252 | this.clusterName = clusterName == null ? generateClusterName() : clusterName; |
| 1248 | 1253 | this.configuration = configuration; |
| @@ -1278,8 +1283,28 @@ | ||
| 1278 | 1283 | this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this); |
| 1279 | 1284 | this.preparedQueries = new MapMaker().weakValues().makeMap(); |
| 1280 | 1285 | |
| 1281 | - this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1286 | + // create debouncers - at this stage, they are not running yet | |
| 1287 | + QueryOptions queryOptions = configuration.getQueryOptions(); | |
| 1288 | + this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>( | |
| 1289 | + "Node list refresh", | |
| 1290 | + scheduledTasksExecutor, | |
| 1291 | + new NodeListRefreshRequestDeliveryCallback(), | |
| 1292 | + queryOptions.getRefreshNodeListIntervalMillis(), | |
| 1293 | + queryOptions.getMaxPendingRefreshNodeListRequests()); | |
| 1294 | + this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>( | |
| 1295 | + "Node refresh", | |
| 1296 | + scheduledTasksExecutor, | |
| 1297 | + new NodeRefreshRequestDeliveryCallback(), | |
| 1298 | + queryOptions.getRefreshNodeIntervalMillis(), | |
| 1299 | + queryOptions.getMaxPendingRefreshNodeRequests()); | |
| 1300 | + this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>( | |
| 1301 | + "Schema refresh", | |
| 1302 | + scheduledTasksExecutor, | |
| 1303 | + new SchemaRefreshRequestDeliveryCallback(), | |
| 1304 | + queryOptions.getRefreshSchemaIntervalMillis(), | |
| 1305 | + queryOptions.getMaxPendingRefreshSchemaRequests()); | |
| 1282 | 1306 | |
| 1307 | + this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1283 | 1308 | |
| 1284 | 1309 | for (InetSocketAddress address : contactPoints) { |
| 1285 | 1310 | // We don't want to signal -- call onAdd() -- because nothing is ready |
| @@ -1353,6 +1378,12 @@ | ||
| 1353 | 1378 | for (Host.StateListener listener : listeners) |
| 1354 | 1379 | listener.onAdd(host); |
| 1355 | 1380 | } |
| 1381 | + | |
| 1382 | + // start debouncers | |
| 1383 | + this.nodeListRefreshRequestDebouncer.start(); | |
| 1384 | + this.schemaRefreshRequestDebouncer.start(); | |
| 1385 | + this.nodeRefreshRequestDebouncer.start(); | |
| 1386 | + | |
| 1356 | 1387 | isFullyInit = true; |
| 1357 | 1388 | |
| 1358 | 1389 | return; |
| @@ -1442,6 +1473,11 @@ | ||
| 1442 | 1473 | if (isInit) { |
| 1443 | 1474 | logger.debug("Shutting down"); |
| 1444 | 1475 | |
| 1476 | + // stop debouncers | |
| 1477 | + nodeListRefreshRequestDebouncer.stop(); | |
| 1478 | + nodeRefreshRequestDebouncer.stop(); | |
| 1479 | + schemaRefreshRequestDebouncer.stop(); | |
| 1480 | + | |
| 1445 | 1481 | // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications |
| 1446 | 1482 | // delivery or blocking tasks so we use shutdownNow |
| 1447 | 1483 | shutdownNow(reconnectionExecutor); |
| @@ -1994,7 +2030,7 @@ | ||
| 1994 | 2030 | : reusedConnection; |
| 1995 | 2031 | |
| 1996 | 2032 | try { |
| 1997 | - ControlConnection.waitForSchemaAgreement(connection, this); | |
| 2033 | + controlConnection.waitForSchemaAgreement(); | |
| 1998 | 2034 | } catch (ExecutionException e) { |
| 1999 | 2035 | // As below, just move on |
| 2000 | 2036 | } |
| @@ -2058,14 +2094,21 @@ | ||
| 2058 | 2094 | } |
| 2059 | 2095 | } |
| 2060 | 2096 | |
| 2061 | - public void submitSchemaRefresh(final String keyspace, final String table) { | |
| 2062 | - logger.trace("Submitting schema refresh"); | |
| 2063 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2064 | - @Override | |
| 2065 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2066 | - controlConnection.refreshSchema(keyspace, table); | |
| 2067 | - } | |
| 2068 | - }); | |
| 2097 | + ListenableFuture<Void> submitSchemaRefresh(String keyspace, String table) { | |
| 2098 | + SchemaRefreshRequest request = new SchemaRefreshRequest(keyspace, table); | |
| 2099 | + logger.trace("Submitting schema refresh: {}", request); | |
| 2100 | + return schemaRefreshRequestDebouncer.eventReceived(request); | |
| 2101 | + } | |
| 2102 | + | |
| 2103 | + void submitNodeListRefresh() { | |
| 2104 | + logger.trace("Submitting node list and token map refresh"); | |
| 2105 | + nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest()); | |
| 2106 | + } | |
| 2107 | + | |
| 2108 | + void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) { | |
| 2109 | + NodeRefreshRequest request = new NodeRefreshRequest(address, eventType); | |
| 2110 | + logger.trace("Submitting node refresh: {}", request); | |
| 2111 | + nodeRefreshRequestDebouncer.eventReceived(request); | |
| 2069 | 2112 | } |
| 2070 | 2113 | |
| 2071 | 2114 | // refresh the schema using the provided connection, and notice the future with the provided resultset once done |
| @@ -2090,20 +2133,23 @@ | ||
| 2090 | 2133 | try { |
| 2091 | 2134 | // Before refreshing the schema, wait for schema agreement so |
| 2092 | 2135 | // that querying a table just after having created it don't fail. |
| 2093 | - schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this); | |
| 2136 | + schemaInAgreement = controlConnection.waitForSchemaAgreement(); | |
| 2094 | 2137 | if (!schemaInAgreement) |
| 2095 | 2138 | logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); |
| 2096 | - if (refreshSchema) | |
| 2097 | - ControlConnection.refreshSchema(connection, keyspace, table, Manager.this, false); | |
| 2139 | + | |
| 2140 | + ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(keyspace, table) : MoreFutures.VOID_SUCCESS; | |
| 2141 | + final boolean finalSchemaInAgreement = schemaInAgreement; | |
| 2142 | + schemaReady.addListener(new Runnable() { | |
| 2143 | + @Override | |
| 2144 | + public void run() { | |
| 2145 | + rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement); | |
| 2146 | + future.setResult(rs); | |
| 2147 | + } | |
| 2148 | + }, MoreExecutors.sameThreadExecutor()); | |
| 2149 | + | |
| 2098 | 2150 | } catch (Exception e) { |
| 2099 | - if (refreshSchema) { | |
| 2100 | - logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage()); | |
| 2101 | - submitSchemaRefresh(keyspace, table); | |
| 2102 | - } else { | |
| 2103 | - logger.warn("Error while waiting for schema agreement", e); | |
| 2104 | - } | |
| 2105 | - } finally { | |
| 2106 | - // Always sets the result, but remember if we reached schema agreement | |
| 2151 | + logger.warn("Error while waiting for schema agreement", e); | |
| 2152 | + // This is not fatal, complete the future anyway | |
| 2107 | 2153 | rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); |
| 2108 | 2154 | future.setResult(rs); |
| 2109 | 2155 | } |
| @@ -2131,36 +2177,13 @@ | ||
| 2131 | 2177 | InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress()); |
| 2132 | 2178 | switch (tpc.change) { |
| 2133 | 2179 | case NEW_NODE: |
| 2134 | - final Host newHost = metadata.add(tpAddr); | |
| 2135 | - if (newHost != null) { | |
| 2136 | - // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once | |
| 2137 | - // gossip is up, but that is before the client-side server is up), so we add a delay | |
| 2138 | - // (otherwise the connection will likely fail and have to be retry which is wasteful). This | |
| 2139 | - // probably should be fixed C* side, after which we'll be able to remove this. | |
| 2140 | - scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2141 | - @Override | |
| 2142 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2143 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2144 | - // catch that an upgraded node uses a new cassandra version). | |
| 2145 | - if (controlConnection.refreshNodeInfo(newHost)) { | |
| 2146 | - onAdd(newHost, null); | |
| 2147 | - } else { | |
| 2148 | - logger.debug("Not enough info for {}, ignoring host", newHost); | |
| 2149 | - } | |
| 2150 | - } | |
| 2151 | - }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2152 | - } | |
| 2180 | + submitNodeRefresh(tpAddr, HostEvent.ADDED); | |
| 2153 | 2181 | break; |
| 2154 | 2182 | case REMOVED_NODE: |
| 2155 | - removeHost(metadata.getHost(tpAddr), false); | |
| 2183 | + submitNodeRefresh(tpAddr, HostEvent.REMOVED); | |
| 2156 | 2184 | break; |
| 2157 | 2185 | case MOVED_NODE: |
| 2158 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2159 | - @Override | |
| 2160 | - public void runMayThrow() { | |
| 2161 | - controlConnection.refreshNodeListAndTokenMap(); | |
| 2162 | - } | |
| 2163 | - }); | |
| 2186 | + submitNodeListRefresh(); | |
| 2164 | 2187 | break; |
| 2165 | 2188 | } |
| 2166 | 2189 | break; |
| @@ -2169,55 +2192,17 @@ | ||
| 2169 | 2192 | InetSocketAddress stAddr = translateAddress(stc.node.getAddress()); |
| 2170 | 2193 | switch (stc.status) { |
| 2171 | 2194 | case UP: |
| 2172 | - final Host hostUp = metadata.getHost(stAddr); | |
| 2173 | - if (hostUp == null) { | |
| 2174 | - final Host h = metadata.add(stAddr); | |
| 2175 | - // If hostUp is still null, it means we didn't knew about it the line before but | |
| 2176 | - // got beaten at adding it to the metadata by another thread. In that case, it's | |
| 2177 | - // fine to let the other thread win and ignore the notification here | |
| 2178 | - if (h == null) | |
| 2179 | - return; | |
| 2180 | - | |
| 2181 | - // See NEW_NODE above | |
| 2182 | - scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2183 | - @Override | |
| 2184 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2185 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2186 | - // catch that an upgraded node uses a new cassandra version). | |
| 2187 | - if (controlConnection.refreshNodeInfo(h)) { | |
| 2188 | - onAdd(h, null); | |
| 2189 | - } else { | |
| 2190 | - logger.debug("Not enough info for {}, ignoring host", h); | |
| 2191 | - } | |
| 2192 | - } | |
| 2193 | - }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2194 | - } else { | |
| 2195 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2196 | - @Override | |
| 2197 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2198 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2199 | - // catch that an upgraded node uses a new cassandra version). | |
| 2200 | - if (controlConnection.refreshNodeInfo(hostUp)) { | |
| 2201 | - onUp(hostUp, null); | |
| 2202 | - } else { | |
| 2203 | - logger.debug("Not enough info for {}, ignoring host", hostUp); | |
| 2204 | - } | |
| 2205 | - } | |
| 2206 | - }); | |
| 2207 | - } | |
| 2195 | + submitNodeRefresh(stAddr, HostEvent.UP); | |
| 2208 | 2196 | break; |
| 2209 | 2197 | case DOWN: |
| 2210 | - // Note that there is a slight risk we can receive the event late and thus | |
| 2211 | - // mark the host down even though we already had reconnected successfully. | |
| 2212 | - // But it is unlikely, and don't have too much consequence since we'll try reconnecting | |
| 2213 | - // right away, so we favor the detection to make the Host.isUp method more reliable. | |
| 2214 | - Host hostDown = metadata.getHost(stAddr); | |
| 2215 | - if (hostDown != null) | |
| 2216 | - triggerOnDown(hostDown, true); | |
| 2198 | + submitNodeRefresh(stAddr, HostEvent.DOWN); | |
| 2217 | 2199 | break; |
| 2218 | 2200 | } |
| 2219 | 2201 | break; |
| 2220 | 2202 | case SCHEMA_CHANGE: |
| 2203 | + if (!configuration.getQueryOptions().isMetadataEnabled()) | |
| 2204 | + return; | |
| 2205 | + | |
| 2221 | 2206 | ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event; |
| 2222 | 2207 | switch (scc.change) { |
| 2223 | 2208 | case CREATED: |
| @@ -2349,6 +2334,252 @@ | ||
| 2349 | 2334 | } |
| 2350 | 2335 | } |
| 2351 | 2336 | } |
| 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 | |
| 2352 | 2583 | } |
| 2353 | 2584 | |
| 2354 | 2585 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +41 −37
| @@ -19,8 +19,7 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.net.UnknownHostException; |
| 21 | 21 | import java.util.*; |
| 22 | -import java.util.concurrent.ExecutionException; | |
| 23 | -import java.util.concurrent.TimeUnit; | |
| 22 | +import java.util.concurrent.*; | |
| 24 | 23 | import java.util.concurrent.atomic.AtomicReference; |
| 25 | 24 | |
| 26 | 25 | import com.google.common.base.Objects; |
| @@ -258,11 +257,14 @@ | ||
| 258 | 257 | // the node we're connecting to. |
| 259 | 258 | refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true); |
| 260 | 259 | |
| 261 | - // Note that refreshing the schema will trigger refreshNodeListAndTokenMap since table == null | |
| 262 | - // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces | |
| 263 | - // to be loaded. | |
| 264 | 260 | logger.debug("[Control connection] Refreshing schema"); |
| 265 | - refreshSchema(connection, null, null, cluster, isInitialConnection); | |
| 261 | + refreshSchema(connection, null, null, cluster); | |
| 262 | + | |
| 263 | + // We need to refresh the node list again; | |
| 264 | + // We want that because the token map was not properly initialized by the first call above, | |
| 265 | + // since it requires the list of keyspaces to be loaded. | |
| 266 | + refreshNodeListAndTokenMap(connection, cluster, false, true); | |
| 267 | + | |
| 266 | 268 | return connection; |
| 267 | 269 | } catch (BusyConnectionException e) { |
| 268 | 270 | connection.closeAsync().force(); |
| @@ -283,13 +285,22 @@ | ||
| 283 | 285 | } |
| 284 | 286 | |
| 285 | 287 | public void refreshSchema(String keyspace, String table) throws InterruptedException { |
| 286 | - logger.debug("[Control connection] Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); | |
| 288 | + if(keyspace == null && table == null) { | |
| 289 | + logger.debug("[Control connection] Refreshing schema"); | |
| 290 | + } else { | |
| 291 | + logger.debug("[Control connection] Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); | |
| 292 | + } | |
| 287 | 293 | try { |
| 288 | 294 | Connection c = connectionRef.get(); |
| 289 | 295 | // At startup, when we add the initial nodes, this will be null, which is ok |
| 290 | 296 | if (c == null) |
| 291 | 297 | return; |
| 292 | - refreshSchema(c, keyspace, table, cluster, false); | |
| 298 | + refreshSchema(c, keyspace, table, cluster); | |
| 299 | + // If the table is null, we either rebuild all from scratch or have an updated keyspace. In both cases, rebuild the token map | |
| 300 | + // since some replication on some keyspace may have changed | |
| 301 | + if (table == null) { | |
| 302 | + cluster.submitNodeListRefresh(); | |
| 303 | + } | |
| 293 | 304 | } catch (ConnectionException e) { |
| 294 | 305 | logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage()); |
| 295 | 306 | signalError(); |
| @@ -304,7 +315,7 @@ | ||
| 304 | 315 | } |
| 305 | 316 | } |
| 306 | 317 | |
| 307 | - static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 318 | + static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 308 | 319 | // Make sure we're up to date on schema |
| 309 | 320 | String whereClause = ""; |
| 310 | 321 | if (keyspace != null) { |
| @@ -345,11 +356,6 @@ | ||
| 345 | 356 | // So log, but let things go otherwise. |
| 346 | 357 | logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e); |
| 347 | 358 | } |
| 348 | - | |
| 349 | - // If the table is null, we either rebuild all from scratch or have an updated keyspace. In both case, rebuild the token map | |
| 350 | - // since some replication on some keyspace may have changed | |
| 351 | - if (table == null) | |
| 352 | - refreshNodeListAndTokenMap(connection, cluster, false, false); | |
| 353 | 359 | } |
| 354 | 360 | |
| 355 | 361 | public void refreshNodeListAndTokenMap() { |
| @@ -358,7 +364,6 @@ | ||
| 358 | 364 | if (c == null) |
| 359 | 365 | return; |
| 360 | 366 | |
| 361 | - logger.debug("[Control connection] Refreshing node list and token map"); | |
| 362 | 367 | try { |
| 363 | 368 | refreshNodeListAndTokenMap(c, cluster, false, true); |
| 364 | 369 | } catch (ConnectionException e) { |
| @@ -507,6 +512,8 @@ | ||
| 507 | 512 | private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logMissingRpcAddresses) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { |
| 508 | 513 | logger.debug("[Control connection] Refreshing node list and token map"); |
| 509 | 514 | |
| 515 | + boolean metadataEnabled = cluster.configuration.getQueryOptions().isMetadataEnabled(); | |
| 516 | + | |
| 510 | 517 | // Make sure we're up to date on nodes and tokens |
| 511 | 518 | |
| 512 | 519 | DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_LOCAL)); |
| @@ -535,9 +542,11 @@ | ||
| 535 | 542 | logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address); |
| 536 | 543 | } else { |
| 537 | 544 | 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 | + } | |
| 541 | 550 | } |
| 542 | 551 | } |
| 543 | 552 | |
| @@ -558,7 +567,8 @@ | ||
| 558 | 567 | racks.add(row.getString("rack")); |
| 559 | 568 | cassandraVersions.add(row.getString("release_version")); |
| 560 | 569 | listenAddresses.add(row.getInet("peer")); |
| 561 | - allTokens.add(row.getSet("tokens", String.class)); | |
| 570 | + if (metadataEnabled) | |
| 571 | + allTokens.add(row.getSet("tokens", String.class)); | |
| 562 | 572 | } |
| 563 | 573 | |
| 564 | 574 | for (int i = 0; i < foundHosts.size(); i++) { |
| @@ -575,7 +585,7 @@ | ||
| 575 | 585 | if (cassandraVersions.get(i) != null) |
| 576 | 586 | host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i)); |
| 577 | 587 | |
| 578 | - if (partitioner != null && !allTokens.get(i).isEmpty()) | |
| 588 | + if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty()) | |
| 579 | 589 | tokenMap.put(host, allTokens.get(i)); |
| 580 | 590 | |
| 581 | 591 | if (isNew && !isInitialConnection) |
| @@ -588,17 +598,17 @@ | ||
| 588 | 598 | if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress())) |
| 589 | 599 | cluster.removeHost(host, isInitialConnection); |
| 590 | 600 | |
| 591 | - cluster.metadata.rebuildTokenMap(partitioner, tokenMap); | |
| 601 | + if (metadataEnabled) | |
| 602 | + cluster.metadata.rebuildTokenMap(partitioner, tokenMap); | |
| 592 | 603 | } |
| 593 | 604 | |
| 594 | - static boolean waitForSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 595 | - | |
| 605 | + boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 596 | 606 | long start = System.nanoTime(); |
| 597 | 607 | long elapsed = 0; |
| 598 | 608 | int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds(); |
| 599 | 609 | while (elapsed < maxSchemaAgreementWaitSeconds * 1000) { |
| 600 | 610 | |
| 601 | - if (checkSchemaAgreement(connection, cluster)) | |
| 611 | + if (checkSchemaAgreement()) | |
| 602 | 612 | return true; |
| 603 | 613 | |
| 604 | 614 | // let's not flood the node too much |
| @@ -610,7 +620,11 @@ | ||
| 610 | 620 | return false; |
| 611 | 621 | } |
| 612 | 622 | |
| 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 | + | |
| 614 | 628 | DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_PEERS)); |
| 615 | 629 | DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_LOCAL)); |
| 616 | 630 | connection.write(peersFuture); |
| @@ -636,16 +650,6 @@ | ||
| 636 | 650 | return versions.size() <= 1; |
| 637 | 651 | } |
| 638 | 652 | |
| 639 | - boolean checkSchemaAgreement() { | |
| 640 | - Connection c = connectionRef.get(); | |
| 641 | - try { | |
| 642 | - return c != null && checkSchemaAgreement(c, cluster); | |
| 643 | - } catch (Exception e) { | |
| 644 | - logger.warn("Error while checking schema agreement", e); | |
| 645 | - return false; | |
| 646 | - } | |
| 647 | - } | |
| 648 | - | |
| 649 | 653 | boolean isOpen() { |
| 650 | 654 | Connection c = connectionRef.get(); |
| 651 | 655 | return c != null && !c.isClosed(); |
| @@ -679,7 +683,7 @@ | ||
| 679 | 683 | // or it's not part of our computed token map |
| 680 | 684 | Metadata.TokenMap tkmap = cluster.metadata.tokenMap; |
| 681 | 685 | if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host)) |
| 682 | - refreshNodeListAndTokenMap(); | |
| 686 | + cluster.submitNodeListRefresh(); | |
| 683 | 687 | } |
| 684 | 688 | |
| 685 | 689 | @Override |
| @@ -693,6 +697,6 @@ | ||
| 693 | 697 | backgroundReconnect(0); |
| 694 | 698 | } |
| 695 | 699 | |
| 696 | - refreshNodeListAndTokenMap(); | |
| 700 | + cluster.submitNodeListRefresh(); | |
| 697 | 701 | } |
| 698 | 702 | } |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +51 −47
| @@ -65,62 +65,66 @@ | ||
| 65 | 65 | set(ArrayBackedResultSet.fromMessage(rm, session, info, statement)); |
| 66 | 66 | break; |
| 67 | 67 | case SCHEMA_CHANGE: |
| 68 | - Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm; | |
| 69 | 68 | 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); | |
| 93 | 80 | } |
| 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); | |
| 102 | 90 | if (removed != null) { |
| 103 | - session.cluster.manager.executor.submit(new Runnable() { | |
| 91 | + cluster.executor.submit(new Runnable() { | |
| 104 | 92 | @Override |
| 105 | 93 | public void run() { |
| 106 | - session.cluster.manager.metadata.triggerOnTableRemoved(removed); | |
| 94 | + cluster.metadata.triggerOnKeyspaceRemoved(removed); | |
| 107 | 95 | } |
| 108 | 96 | }); |
| 109 | 97 | } |
| 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); | |
| 110 | 122 | } |
| 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 | + } | |
| 124 | 128 | } |
| 125 | 129 | break; |
| 126 | 130 | 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 @@ | ||
| 28 | 28 | import org.slf4j.Logger; |
| 29 | 29 | import org.slf4j.LoggerFactory; |
| 30 | 30 | |
| 31 | -import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 32 | - | |
| 33 | 31 | /** |
| 34 | 32 | * Keeps metadata on the connected cluster, including known nodes and schema definitions. |
| 35 | 33 | */ |
| @@ -355,7 +353,8 @@ | ||
| 355 | 353 | * connection, when schema or ring topology changes. It might occasionally |
| 356 | 354 | * be stale. |
| 357 | 355 | * |
| 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)}. | |
| 359 | 358 | */ |
| 360 | 359 | public Set<TokenRange> getTokenRanges() { |
| 361 | 360 | TokenMap current = tokenMap; |
| @@ -373,7 +372,8 @@ | ||
| 373 | 372 | * @param keyspace the name of the keyspace to get token ranges for. |
| 374 | 373 | * @param host the host. |
| 375 | 374 | * @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)}. | |
| 377 | 377 | */ |
| 378 | 378 | public Set<TokenRange> getTokenRanges(String keyspace, Host host) { |
| 379 | 379 | keyspace = handleId(keyspace); |
| @@ -402,7 +402,8 @@ | ||
| 402 | 402 | * @param partitionKey the partition key for which to find the set of |
| 403 | 403 | * replica. |
| 404 | 404 | * @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)}. | |
| 406 | 407 | */ |
| 407 | 408 | public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) { |
| 408 | 409 | keyspace = handleId(keyspace); |
| @@ -425,6 +426,8 @@ | ||
| 425 | 426 | * @param keyspace the name of the keyspace to get replicas for. |
| 426 | 427 | * @param range the token range. |
| 427 | 428 | * @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)}. | |
| 428 | 431 | */ |
| 429 | 432 | public Set<Host> getReplicas(String keyspace, TokenRange range) { |
| 430 | 433 | keyspace = handleId(keyspace); |
| @@ -474,7 +477,12 @@ | ||
| 474 | 477 | * (for example, if the control connection is down). |
| 475 | 478 | */ |
| 476 | 479 | 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 | + } | |
| 478 | 486 | } |
| 479 | 487 | |
| 480 | 488 | /** |
| @@ -483,7 +491,8 @@ | ||
| 483 | 491 | * @param keyspace the name of the keyspace for which metadata should be |
| 484 | 492 | * returned. |
| 485 | 493 | * @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)}. | |
| 487 | 496 | */ |
| 488 | 497 | public KeyspaceMetadata getKeyspace(String keyspace) { |
| 489 | 498 | return keyspaces.get(handleId(keyspace)); |
| @@ -507,7 +516,8 @@ | ||
| 507 | 516 | /** |
| 508 | 517 | * Returns a list of all the defined keyspaces. |
| 509 | 518 | * |
| 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)}. | |
| 511 | 521 | */ |
| 512 | 522 | public List<KeyspaceMetadata> getKeyspaces() { |
| 513 | 523 | return new ArrayList<KeyspaceMetadata>(keyspaces.values()); |
| @@ -523,6 +533,9 @@ | ||
| 523 | 533 | * Note that the returned String is formatted to be human readable (for |
| 524 | 534 | * some definition of human readable at least). |
| 525 | 535 | * |
| 536 | + * It might be stale or empty if metadata was explicitly disabled with | |
| 537 | + * {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 538 | + * | |
| 526 | 539 | * @return the CQL queries representing this cluster schema as a {code |
| 527 | 540 | * String}. |
| 528 | 541 | */ |
| @@ -541,11 +554,15 @@ | ||
| 541 | 554 | * |
| 542 | 555 | * @param tokenStr the string representation. |
| 543 | 556 | * @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. | |
| 544 | 561 | */ |
| 545 | 562 | public Token newToken(String tokenStr) { |
| 546 | 563 | TokenMap current = tokenMap; |
| 547 | 564 | 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"); | |
| 549 | 566 | |
| 550 | 567 | return current.factory.fromString(tokenStr); |
| 551 | 568 | } |
| @@ -556,11 +573,15 @@ | ||
| 556 | 573 | * @param start the start token. |
| 557 | 574 | * @param end the end token. |
| 558 | 575 | * @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. | |
| 559 | 580 | */ |
| 560 | 581 | public TokenRange newTokenRange(Token start, Token end) { |
| 561 | 582 | TokenMap current = tokenMap; |
| 562 | 583 | 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"); | |
| 564 | 585 | |
| 565 | 586 | return new TokenRange(start, end, current.factory); |
| 566 | 587 | } |
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +224 −0
| @@ -42,10 +42,33 @@ | ||
| 42 | 42 | */ |
| 43 | 43 | public static final boolean DEFAULT_IDEMPOTENCE = false; |
| 44 | 44 | |
| 45 | + public static final int DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS = 20; | |
| 46 | + | |
| 47 | + public static final int DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS = 20; | |
| 48 | + | |
| 49 | + public static final int DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS = 20; | |
| 50 | + | |
| 51 | + public static final int DEFAULT_REFRESH_NODE_LIST_INTERVAL_MILLIS = 1000; | |
| 52 | + | |
| 53 | + public static final int DEFAULT_REFRESH_NODE_INTERVAL_MILLIS = 1000; | |
| 54 | + | |
| 55 | + public static final int DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS = 1000; | |
| 56 | + | |
| 45 | 57 | private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL; |
| 46 | 58 | private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL; |
| 47 | 59 | private volatile int fetchSize = DEFAULT_FETCH_SIZE; |
| 48 | 60 | 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 | + | |
| 49 | 72 | private volatile boolean reprepareOnUp = true; |
| 50 | 73 | private volatile Cluster.Manager manager; |
| 51 | 74 | private volatile boolean prepareOnAllHosts = true; |
| @@ -249,4 +272,205 @@ | ||
| 249 | 272 | public boolean isReprepareOnUp() { |
| 250 | 273 | return this.reprepareOnUp; |
| 251 | 274 | } |
| 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 | + | |
| 252 | 476 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +19 −6
| @@ -15,12 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.util.*; | |
| 19 | - | |
| 20 | 18 | import org.testng.annotations.Test; |
| 21 | -import static org.testng.Assert.*; | |
| 22 | 19 | |
| 23 | -import static com.datastax.driver.core.TestUtils.*; | |
| 20 | +import static org.testng.Assert.assertEquals; | |
| 21 | +import static org.testng.Assert.assertNotNull; | |
| 22 | +import static org.testng.Assert.assertNull; | |
| 23 | + | |
| 24 | +import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 24 | 25 | |
| 25 | 26 | public class CaseSensitivityTest { |
| 26 | 27 | |
| @@ -36,7 +37,13 @@ | ||
| 36 | 37 | |
| 37 | 38 | @Test(groups = "short") |
| 38 | 39 | public void testCaseInsensitiveKeyspace() throws Throwable { |
| 39 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); | |
| 40 | + CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder() | |
| 41 | + .withQueryOptions(new QueryOptions() | |
| 42 | + .setRefreshNodeIntervalMillis(0) | |
| 43 | + .setRefreshNodeListIntervalMillis(0) | |
| 44 | + .setRefreshSchemaIntervalMillis(0) | |
| 45 | + ) | |
| 46 | + ); | |
| 40 | 47 | Session s = c.session; |
| 41 | 48 | try { |
| 42 | 49 | String ksName = "MyKeyspace"; |
| @@ -56,7 +63,13 @@ | ||
| 56 | 63 | |
| 57 | 64 | @Test(groups = "short") |
| 58 | 65 | public void testCaseSensitiveKeyspace() throws Throwable { |
| 59 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); | |
| 66 | + CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder() | |
| 67 | + .withQueryOptions(new QueryOptions() | |
| 68 | + .setRefreshNodeIntervalMillis(0) | |
| 69 | + .setRefreshNodeListIntervalMillis(0) | |
| 70 | + .setRefreshSchemaIntervalMillis(0) | |
| 71 | + ) | |
| 72 | + ); | |
| 60 | 73 | Session s = c.session; |
| 61 | 74 | try { |
| 62 | 75 | String ksName = "\"MyKeyspace\""; |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +4 −2
| @@ -47,6 +47,7 @@ | ||
| 47 | 47 | import static com.datastax.driver.core.Host.State.DOWN; |
| 48 | 48 | import static com.datastax.driver.core.Host.State.UP; |
| 49 | 49 | import static com.datastax.driver.core.HostDistance.LOCAL; |
| 50 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 50 | 51 | |
| 51 | 52 | public class ClusterInitTest { |
| 52 | 53 | private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class); |
| @@ -66,7 +67,7 @@ | ||
| 66 | 67 | // - 1 is an actual Scassandra instance that will accept connections: |
| 67 | 68 | scassandra = TestUtils.createScassandraServer(); |
| 68 | 69 | scassandra.start(); |
| 69 | - String realHostAddress = "localhost"; | |
| 70 | + String realHostAddress = "127.0.0.1"; | |
| 70 | 71 | int port = scassandra.getBinaryPort(); |
| 71 | 72 | |
| 72 | 73 | // - the remaining 4 are fake servers that will throw connect timeouts: |
| @@ -108,6 +109,7 @@ | ||
| 108 | 109 | .withReconnectionPolicy(reconnectionPolicy) |
| 109 | 110 | .withPoolingOptions(poolingOptions) |
| 110 | 111 | .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) |
| 112 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 111 | 113 | .build(); |
| 112 | 114 | cluster.connect(); |
| 113 | 115 | |
| @@ -124,7 +126,7 @@ | ||
| 124 | 126 | verify(socketOptions, atLeast(6)).getKeepAlive(); |
| 125 | 127 | verify(socketOptions, atMost(7)).getKeepAlive(); |
| 126 | 128 | |
| 127 | - assertThat(cluster).host(realHostAddress).hasState(UP); | |
| 129 | + assertThat(cluster).host(realHostAddress).isNotNull().hasState(UP); | |
| 128 | 130 | for (FakeHost failingHost : failingHosts) |
| 129 | 131 | assertThat(cluster).host(failingHost.address).hasState(DOWN); |
| 130 | 132 | 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 @@ | ||
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | 23 | import static com.datastax.driver.core.Assertions.assertThat; |
| 24 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 24 | 25 | import static com.datastax.driver.core.TestUtils.waitFor; |
| 25 | 26 | |
| 26 | 27 | public class MetadataTest { |
| @@ -58,6 +59,7 @@ | ||
| 58 | 59 | |
| 59 | 60 | cluster = Cluster.builder() |
| 60 | 61 | .addContactPoint(CCMBridge.ipOfNode(1)) |
| 62 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 61 | 63 | .build(); |
| 62 | 64 | Session session = cluster.connect(); |
| 63 | 65 |
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 @@ | ||
| 108 | 108 | return defs; |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | + @Override | |
| 112 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 113 | + return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions()); | |
| 114 | + } | |
| 115 | + | |
| 111 | 116 | @Test(groups = "short") |
| 112 | 117 | public void preparedNativeTest() { |
| 113 | 118 | // Test preparing/bounding for all native types |
| @@ -322,12 +327,12 @@ | ||
| 322 | 327 | } |
| 323 | 328 | } |
| 324 | 329 | |
| 325 | - @Test(groups = "long") | |
| 330 | + @Test(groups = "long", priority = Integer.MAX_VALUE) | |
| 326 | 331 | public void reprepareOnNewlyUpNodeTest() throws Exception { |
| 327 | 332 | reprepareOnNewlyUpNodeTest(null, session); |
| 328 | 333 | } |
| 329 | 334 | |
| 330 | - @Test(groups = "long") | |
| 335 | + @Test(groups = "long", priority = Integer.MAX_VALUE) | |
| 331 | 336 | public void reprepareOnNewlyUpNodeNoKeyspaceTest() throws Exception { |
| 332 | 337 | |
| 333 | 338 | // This is the same test than reprepareOnNewlyUpNodeTest, except that the |
| @@ -442,10 +447,14 @@ | ||
| 442 | 447 | Cluster otherCluster = Cluster.builder() |
| 443 | 448 | .addContactPointsWithPorts(ImmutableList.of(hostAddress)) |
| 444 | 449 | .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 | + } | |
| 450 | 459 | } |
| 451 | 460 | } |
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +9 −5
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | import static com.datastax.driver.core.Assertions.*; |
| 29 | 29 | import static com.datastax.driver.core.Host.State.DOWN; |
| 30 | 30 | import static com.datastax.driver.core.Host.State.UP; |
| 31 | - | |
| 31 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 32 | 32 | |
| 33 | 33 | /** |
| 34 | 34 | * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster. |
| @@ -50,7 +50,8 @@ | ||
| 50 | 50 | mainCcm.waitForDown(1); |
| 51 | 51 | |
| 52 | 52 | // 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(); | |
| 54 | 55 | mainCluster.connect(); |
| 55 | 56 | waitForCountUpHosts(mainCluster, 2); |
| 56 | 57 | // From that point, reconnections to node1 have been scheduled. |
| @@ -72,7 +73,8 @@ | ||
| 72 | 73 | mainCcm.waitForDown(1); |
| 73 | 74 | |
| 74 | 75 | // 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(); | |
| 76 | 78 | mainCluster.connect(); |
| 77 | 79 | waitForCountUpHosts(mainCluster, 1); |
| 78 | 80 | |
| @@ -99,7 +101,8 @@ | ||
| 99 | 101 | otherCcm.waitForUp(1); |
| 100 | 102 | |
| 101 | 103 | // 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(); | |
| 103 | 106 | |
| 104 | 107 | // When we first initialize the Cluster, all hosts are marked UP |
| 105 | 108 | assertThat(mainCluster).host(2).hasState(UP); |
| @@ -127,7 +130,8 @@ | ||
| 127 | 130 | otherCcm.waitForUp(1); |
| 128 | 131 | |
| 129 | 132 | // 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(); | |
| 131 | 135 | |
| 132 | 136 | // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version. |
| 133 | 137 | mainCluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +1 −0
| @@ -53,6 +53,7 @@ | ||
| 53 | 53 | .withPoolingOptions(poolingOptions) |
| 54 | 54 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 55 | 55 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) |
| 56 | + .withQueryOptions(TestUtils.nonDebouncingQueryOptions()) | |
| 56 | 57 | .build(); |
| 57 | 58 | |
| 58 | 59 | Session session = cluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +149 −5
| @@ -25,15 +25,14 @@ | ||
| 25 | 25 | import org.mockito.ArgumentCaptor; |
| 26 | 26 | import org.testng.annotations.*; |
| 27 | 27 | |
| 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.*; | |
| 32 | 30 | |
| 33 | 31 | import com.datastax.driver.core.utils.Bytes; |
| 34 | 32 | |
| 35 | 33 | import static com.datastax.driver.core.Assertions.assertThat; |
| 36 | 34 | import static com.datastax.driver.core.Metadata.handleId; |
| 35 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 37 | 36 | |
| 38 | 37 | public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster { |
| 39 | 38 | |
| @@ -50,17 +49,23 @@ | ||
| 50 | 49 | |
| 51 | 50 | Cluster cluster1; |
| 52 | 51 | Cluster cluster2; // a second cluster to check that other clients also get notified |
| 52 | + Cluster schemaDisabledCluster; // a cluster with schema metadata disabled. | |
| 53 | 53 | |
| 54 | 54 | // The metadatas of the two clusters (we'll test that they're kept in sync) |
| 55 | 55 | List<Metadata> metadatas; |
| 56 | 56 | |
| 57 | 57 | Session session1; |
| 58 | 58 | |
| 59 | + Session schemaDisabledSession; | |
| 60 | + | |
| 59 | 61 | SchemaChangeListener listener1; |
| 60 | 62 | SchemaChangeListener listener2; |
| 63 | + SchemaChangeListener schemaDisabledListener; | |
| 61 | 64 | |
| 62 | 65 | List<SchemaChangeListener> listeners; |
| 63 | 66 | |
| 67 | + ControlConnection schemaDisabledControlConnection; | |
| 68 | + | |
| 64 | 69 | @Override |
| 65 | 70 | protected Collection<String> getTableDefinitions() { |
| 66 | 71 | return Lists.newArrayList(); |
| @@ -68,9 +73,22 @@ | ||
| 68 | 73 | |
| 69 | 74 | @BeforeClass(groups = "short") |
| 70 | 75 | 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()); | |
| 72 | 79 | cluster1 = builder.build(); |
| 73 | 80 | 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; | |
| 74 | 92 | |
| 75 | 93 | metadatas = Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata()); |
| 76 | 94 | |
| @@ -80,6 +98,9 @@ | ||
| 80 | 98 | cluster1.register(listener2 = mock(SchemaChangeListener.class)); |
| 81 | 99 | listeners = Lists.newArrayList(listener1, listener2); |
| 82 | 100 | |
| 101 | + schemaDisabledCluster.register(schemaDisabledListener = mock(SchemaChangeListener.class)); | |
| 102 | + verify(schemaDisabledListener, times(1)).onRegister(schemaDisabledCluster); | |
| 103 | + | |
| 83 | 104 | execute(CREATE_KEYSPACE, "lowercase"); |
| 84 | 105 | execute(CREATE_KEYSPACE, "\"CaseSensitive\""); |
| 85 | 106 | } |
| @@ -90,6 +111,8 @@ | ||
| 90 | 111 | cluster1.close(); |
| 91 | 112 | if (cluster2 != null) |
| 92 | 113 | cluster2.close(); |
| 114 | + if (schemaDisabledCluster != null) | |
| 115 | + schemaDisabledCluster.close(); | |
| 93 | 116 | } |
| 94 | 117 | |
| 95 | 118 | @DataProvider(name = "existingKeyspaceName") |
| @@ -107,6 +130,19 @@ | ||
| 107 | 130 | for (SchemaChangeListener listener : listeners) { |
| 108 | 131 | reset(listener); |
| 109 | 132 | } |
| 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); | |
| 110 | 146 | } |
| 111 | 147 | |
| 112 | 148 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| @@ -119,6 +155,7 @@ | ||
| 119 | 155 | .isInKeyspace(handleId(keyspace)) |
| 120 | 156 | .hasName("table1"); |
| 121 | 157 | } |
| 158 | + | |
| 122 | 159 | for (Metadata m : metadatas) |
| 123 | 160 | assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull(); |
| 124 | 161 | } |
| @@ -237,6 +274,113 @@ | ||
| 237 | 274 | } |
| 238 | 275 | } |
| 239 | 276 | |
| 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 | + | |
| 240 | 384 | @AfterMethod(groups = "short") |
| 241 | 385 | public void cleanup() throws InterruptedException { |
| 242 | 386 | 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 @@ | ||
| 30 | 30 | |
| 31 | 31 | private static String withOptions; |
| 32 | 32 | |
| 33 | + @Override | |
| 34 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 35 | + return builder.withQueryOptions(new QueryOptions() | |
| 36 | + .setRefreshNodeIntervalMillis(0) | |
| 37 | + .setRefreshNodeListIntervalMillis(0) | |
| 38 | + .setRefreshSchemaIntervalMillis(0) | |
| 39 | + ); | |
| 40 | + } | |
| 41 | + | |
| 33 | 42 | @Override |
| 34 | 43 | protected Collection<String> getTableDefinitions() { |
| 35 | 44 |
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +4 −2
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 33 | 33 | |
| 34 | 34 | import static com.datastax.driver.core.Assertions.assertThat; |
| 35 | - | |
| 35 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 36 | 36 | |
| 37 | 37 | public class SessionLeakTest { |
| 38 | 38 | |
| @@ -53,7 +53,9 @@ | ||
| 53 | 53 | cluster = Cluster.builder() |
| 54 | 54 | .addContactPointsWithPorts(Collections.singletonList( |
| 55 | 55 | new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042))) |
| 56 | - .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 56 | + .withNettyOptions(channelMonitor.nettyOptions()) | |
| 57 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 58 | + .build(); | |
| 57 | 59 | |
| 58 | 60 | cluster.init(); |
| 59 | 61 |
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +8 −1
| @@ -39,7 +39,14 @@ | ||
| 39 | 39 | .withCassandraConfiguration("initial_token", "1") |
| 40 | 40 | .build(); |
| 41 | 41 | |
| 42 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 42 | + cluster = Cluster.builder() | |
| 43 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 44 | + .withQueryOptions(new QueryOptions() | |
| 45 | + .setRefreshNodeIntervalMillis(0) | |
| 46 | + .setRefreshNodeListIntervalMillis(0) | |
| 47 | + .setRefreshSchemaIntervalMillis(0) | |
| 48 | + ) | |
| 49 | + .build(); | |
| 43 | 50 | |
| 44 | 51 | Session session = cluster.connect(); |
| 45 | 52 | session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); |
modified driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +1 −1
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | */ |
| 32 | 32 | public class SortingLoadBalancingPolicy implements LoadBalancingPolicy { |
| 33 | 33 | |
| 34 | - private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 34 | + final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 35 | 35 | @Override |
| 36 | 36 | public int compare(Host host1, Host host2) { |
| 37 | 37 | byte[] address1 = host1.getAddress().getAddress(); |
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +10 −0
| @@ -50,4 +50,14 @@ | ||
| 50 | 50 | assertThat(actual.getColumn(columnName)).isNull(); |
| 51 | 51 | return this; |
| 52 | 52 | } |
| 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 | + } | |
| 53 | 63 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +10 −1
| @@ -32,9 +32,18 @@ | ||
| 32 | 32 | ); |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | + @Override | |
| 36 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 37 | + return builder.withQueryOptions(new QueryOptions() | |
| 38 | + .setRefreshNodeIntervalMillis(0) | |
| 39 | + .setRefreshNodeListIntervalMillis(0) | |
| 40 | + .setRefreshSchemaIntervalMillis(0) | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 35 | 44 | @Test(groups = "short") |
| 36 | 45 | public void should_escape_single_quote_table_comment() { |
| 37 | 46 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote"); |
| 38 | 47 | assertThat(table.asCQLQuery()).contains("comment with single quote '' should work"); |
| 39 | 48 | } |
| 40 | -} | |
| No newline at the end of the file | ||
| 49 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +13 −2
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | import java.nio.ByteBuffer; |
| 25 | 25 | import java.util.*; |
| 26 | 26 | |
| 27 | +import com.google.common.util.concurrent.Futures; | |
| 27 | 28 | import org.scassandra.Scassandra; |
| 28 | 29 | import org.scassandra.ScassandraFactory; |
| 29 | 30 | import org.slf4j.Logger; |
| @@ -323,8 +324,9 @@ | ||
| 323 | 324 | // tried doing an actual query, the driver won't realize that last node is dead until |
| 324 | 325 | // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force |
| 325 | 326 | // the detection by forcing a request. |
| 326 | - if (waitForDead || waitForOut) | |
| 327 | - cluster.manager.submitSchemaRefresh(null, null); | |
| 327 | + if (waitForDead || waitForOut) { | |
| 328 | + Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null)); | |
| 329 | + } | |
| 328 | 330 | |
| 329 | 331 | InetAddress address; |
| 330 | 332 | try { |
| @@ -454,4 +456,13 @@ | ||
| 454 | 456 | .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress)) |
| 455 | 457 | .build(); |
| 456 | 458 | } |
| 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 | + } | |
| 457 | 468 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +5 −0
| @@ -81,6 +81,11 @@ | ||
| 81 | 81 | cluster = Cluster.builder() |
| 82 | 82 | .addContactPoints(CCMBridge.ipOfNode(1)) |
| 83 | 83 | .withLoadBalancingPolicy(lbp) |
| 84 | + .withQueryOptions(new QueryOptions() | |
| 85 | + .setRefreshNodeIntervalMillis(0) | |
| 86 | + .setRefreshNodeListIntervalMillis(0) | |
| 87 | + .setRefreshSchemaIntervalMillis(0) | |
| 88 | + ) | |
| 84 | 89 | .build(); |
| 85 | 90 | cluster.init(); |
| 86 | 91 | session = cluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +3 −0
| @@ -25,6 +25,8 @@ | ||
| 25 | 25 | import com.datastax.driver.core.*; |
| 26 | 26 | import com.datastax.driver.core.utils.Bytes; |
| 27 | 27 | |
| 28 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 29 | + | |
| 28 | 30 | public class TokenAwarePolicyTest { |
| 29 | 31 | @Test(groups = "long") |
| 30 | 32 | public void should_shuffle_replicas_when_requested() { |
| @@ -46,6 +48,7 @@ | ||
| 46 | 48 | cluster = Cluster.builder() |
| 47 | 49 | .addContactPoint(CCMBridge.ipOfNode(1)) |
| 48 | 50 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 51 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 49 | 52 | .build(); |
| 50 | 53 | |
| 51 | 54 | String keyspace = "ks"; |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +9 −0
| @@ -40,6 +40,15 @@ | ||
| 40 | 40 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | + @Override | |
| 44 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 45 | + return builder.withQueryOptions(new QueryOptions() | |
| 46 | + .setRefreshNodeIntervalMillis(0) | |
| 47 | + .setRefreshNodeListIntervalMillis(0) | |
| 48 | + .setRefreshSchemaIntervalMillis(0) | |
| 49 | + ); | |
| 50 | + } | |
| 51 | + | |
| 43 | 52 | @Test(groups = "short") |
| 44 | 53 | public void remainingDeleteTests() throws Exception { |
| 45 | 54 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +9 −0
| @@ -39,6 +39,15 @@ | ||
| 39 | 39 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | + @Override | |
| 43 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 44 | + return builder.withQueryOptions(new QueryOptions() | |
| 45 | + .setRefreshNodeIntervalMillis(0) | |
| 46 | + .setRefreshNodeListIntervalMillis(0) | |
| 47 | + .setRefreshSchemaIntervalMillis(0) | |
| 48 | + ); | |
| 49 | + } | |
| 50 | + | |
| 42 | 51 | @Test(groups = "short") |
| 43 | 52 | public void textRoutingKeyTest() throws Exception { |
| 44 | 53 |