kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | ddeff16a1cf411cadee3aa8cc382c65700496a28bb7229d5cdff92117dbbb4d4 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2014-12-10 16:34 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2014-12-10 16:34 +01:00 |
| Parents | 194efecc5f37, 125b3d45cbd8 |
15 files changed
modified .gitignore +2 −0
| @@ -10,3 +10,5 @@ | ||
| 10 | 10 | |
| 11 | 11 | /.idea |
| 12 | 12 | *.iml |
| 13 | + | |
| 14 | +/driver-core/dependency-reduced-pom.xml |
modified driver-core/CHANGELOG.rst +15 −0
| @@ -1,6 +1,21 @@ | ||
| 1 | 1 | CHANGELOG |
| 2 | 2 | ========= |
| 3 | 3 | |
| 4 | +2.1.4: | |
| 5 | +------ | |
| 6 | + | |
| 7 | +Merged from 2.0 branch: | |
| 8 | + | |
| 9 | +- [improvement] Shade Netty dependency (JAVA-538) | |
| 10 | +- [improvement] Target schema refreshes more precisely (JAVA-543) | |
| 11 | +- [bug] Don't check rpc_address for control host (JAVA-546) | |
| 12 | +- [improvement] Improve message of NoHostAvailableException (JAVA-409) | |
| 13 | +- [bug] Rework connection reaper to avoid deadlock (JAVA-556) | |
| 14 | +- [bug] Avoid deadlock when multiple connections to the same host get write | |
| 15 | + errors (JAVA-557) | |
| 16 | +- [improvement] Make shuffle=true the default for TokenAwarePolicy (JAVA-504) | |
| 17 | + | |
| 18 | + | |
| 4 | 19 | 2.1.3: |
| 5 | 20 | ------ |
| 6 | 21 |
modified driver-core/pom.xml +23 −0
| @@ -207,6 +207,29 @@ | ||
| 207 | 207 | <showDeprecation>true</showDeprecation> |
| 208 | 208 | </configuration> |
| 209 | 209 | </plugin> |
| 210 | + <plugin> | |
| 211 | + <artifactId>maven-shade-plugin</artifactId> | |
| 212 | + <version>2.3</version> | |
| 213 | + <executions> | |
| 214 | + <execution> | |
| 215 | + <phase>package</phase> | |
| 216 | + <goals><goal>shade</goal></goals> | |
| 217 | + <configuration> | |
| 218 | + <artifactSet> | |
| 219 | + <includes> | |
| 220 | + <include>io.netty:netty</include> | |
| 221 | + </includes> | |
| 222 | + </artifactSet> | |
| 223 | + <relocations> | |
| 224 | + <relocation> | |
| 225 | + <pattern>org.jboss.netty</pattern> | |
| 226 | + <shadedPattern>com.datastax.shaded.netty</shadedPattern> | |
| 227 | + </relocation> | |
| 228 | + </relocations> | |
| 229 | + </configuration> | |
| 230 | + </execution> | |
| 231 | + </executions> | |
| 232 | + </plugin> | |
| 210 | 233 | </plugins> |
| 211 | 234 | </build> |
| 212 | 235 | </profile> |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +68 −38
| @@ -20,17 +20,14 @@ | ||
| 20 | 20 | import java.net.InetSocketAddress; |
| 21 | 21 | import java.net.UnknownHostException; |
| 22 | 22 | import java.util.*; |
| 23 | +import java.util.Map.Entry; | |
| 23 | 24 | import java.util.concurrent.*; |
| 24 | 25 | import java.util.concurrent.atomic.AtomicInteger; |
| 25 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 26 | 27 | |
| 27 | 28 | import com.google.common.annotations.VisibleForTesting; |
| 28 | 29 | import com.google.common.base.Predicates; |
| 29 | -import com.google.common.collect.HashMultimap; | |
| 30 | -import com.google.common.collect.Iterables; | |
| 31 | -import com.google.common.collect.MapMaker; | |
| 32 | -import com.google.common.collect.SetMultimap; | |
| 33 | -import com.google.common.collect.Sets; | |
| 30 | +import com.google.common.collect.*; | |
| 34 | 31 | import com.google.common.util.concurrent.*; |
| 35 | 32 | |
| 36 | 33 | import org.slf4j.Logger; |
| @@ -1959,18 +1956,18 @@ | ||
| 1959 | 1956 | } |
| 1960 | 1957 | } |
| 1961 | 1958 | |
| 1962 | - public void submitSchemaRefresh(final String keyspace, final String table) { | |
| 1959 | + public void submitSchemaRefresh(final String keyspace, final String table, final String udt) { | |
| 1963 | 1960 | logger.trace("Submitting schema refresh"); |
| 1964 | 1961 | executor.submit(new ExceptionCatchingRunnable() { |
| 1965 | 1962 | @Override |
| 1966 | 1963 | public void runMayThrow() throws InterruptedException, ExecutionException { |
| 1967 | - controlConnection.refreshSchema(keyspace, table); | |
| 1964 | + controlConnection.refreshSchema(keyspace, table, udt); | |
| 1968 | 1965 | } |
| 1969 | 1966 | }); |
| 1970 | 1967 | } |
| 1971 | 1968 | |
| 1972 | 1969 | // refresh the schema using the provided connection, and notice the future with the provided resultset once done |
| 1973 | - public void refreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { | |
| 1970 | + public void refreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table, final String udt) { | |
| 1974 | 1971 | if (logger.isDebugEnabled()) |
| 1975 | 1972 | logger.debug("Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); |
| 1976 | 1973 | |
| @@ -1982,10 +1979,10 @@ | ||
| 1982 | 1979 | // that querying a table just after having created it don't fail. |
| 1983 | 1980 | if (!ControlConnection.waitForSchemaAgreement(connection, Cluster.Manager.this)) |
| 1984 | 1981 | logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); |
| 1985 | - ControlConnection.refreshSchema(connection, keyspace, table, Cluster.Manager.this, false); | |
| 1982 | + ControlConnection.refreshSchema(connection, keyspace, table, udt, Cluster.Manager.this, false); | |
| 1986 | 1983 | } catch (Exception e) { |
| 1987 | 1984 | logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage()); |
| 1988 | - submitSchemaRefresh(keyspace, table); | |
| 1985 | + submitSchemaRefresh(keyspace, table, udt); | |
| 1989 | 1986 | } finally { |
| 1990 | 1987 | // Always sets the result |
| 1991 | 1988 | future.setResult(rs); |
| @@ -2104,22 +2101,54 @@ | ||
| 2104 | 2101 | ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event; |
| 2105 | 2102 | switch (scc.change) { |
| 2106 | 2103 | case CREATED: |
| 2107 | - if (scc.name.isEmpty()) | |
| 2108 | - submitSchemaRefresh(null, null); | |
| 2109 | - else | |
| 2110 | - submitSchemaRefresh(scc.keyspace, null); | |
| 2104 | + switch (scc.target) { | |
| 2105 | + case KEYSPACE: | |
| 2106 | + submitSchemaRefresh(scc.keyspace, null, null); | |
| 2107 | + break; | |
| 2108 | + case TABLE: | |
| 2109 | + submitSchemaRefresh(scc.keyspace, scc.name, null); | |
| 2110 | + break; | |
| 2111 | + case TYPE: | |
| 2112 | + submitSchemaRefresh(scc.keyspace, null, scc.name); | |
| 2113 | + break; | |
| 2114 | + } | |
| 2111 | 2115 | break; |
| 2112 | 2116 | case DROPPED: |
| 2113 | - if (scc.name.isEmpty()) | |
| 2114 | - submitSchemaRefresh(null, null); | |
| 2115 | - else | |
| 2116 | - submitSchemaRefresh(scc.keyspace, null); | |
| 2117 | + KeyspaceMetadata keyspace; | |
| 2118 | + switch (scc.target) { | |
| 2119 | + case KEYSPACE: | |
| 2120 | + manager.metadata.removeKeyspace(scc.keyspace); | |
| 2121 | + break; | |
| 2122 | + case TABLE: | |
| 2123 | + keyspace = manager.metadata.getKeyspace(scc.keyspace); | |
| 2124 | + if (keyspace == null) | |
| 2125 | + logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata", | |
| 2126 | + scc.keyspace, scc.name); | |
| 2127 | + else | |
| 2128 | + keyspace.removeTable(scc.name); | |
| 2129 | + break; | |
| 2130 | + case TYPE: | |
| 2131 | + keyspace = manager.metadata.getKeyspace(scc.keyspace); | |
| 2132 | + if (keyspace == null) | |
| 2133 | + logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata", | |
| 2134 | + scc.keyspace, scc.name); | |
| 2135 | + else | |
| 2136 | + keyspace.removeUserType(scc.name); | |
| 2137 | + break; | |
| 2138 | + } | |
| 2117 | 2139 | break; |
| 2118 | 2140 | case UPDATED: |
| 2119 | - if (scc.name.isEmpty()) | |
| 2120 | - submitSchemaRefresh(scc.keyspace, null); | |
| 2121 | - else | |
| 2122 | - submitSchemaRefresh(scc.keyspace, scc.name); | |
| 2141 | + switch (scc.target) { | |
| 2142 | + case KEYSPACE: | |
| 2143 | + submitSchemaRefresh(scc.keyspace, null, null); | |
| 2144 | + break; | |
| 2145 | + case TABLE: | |
| 2146 | + submitSchemaRefresh(scc.keyspace, scc.name, null); | |
| 2147 | + break; | |
| 2148 | + case TYPE: | |
| 2149 | + submitSchemaRefresh(scc.keyspace, null, scc.name); | |
| 2150 | + break; | |
| 2151 | + } | |
| 2123 | 2152 | break; |
| 2124 | 2153 | } |
| 2125 | 2154 | break; |
| @@ -2217,45 +2246,46 @@ | ||
| 2217 | 2246 | * This is normally done when the connection errors out, or when the last request is processed; this class acts as |
| 2218 | 2247 | * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection, |
| 2219 | 2248 | * this indicates a bug; warnings are logged so that this can be reported. |
| 2249 | + * | |
| 2250 | + * @see Connection#tryTerminate(boolean) | |
| 2220 | 2251 | */ |
| 2221 | 2252 | static class ConnectionReaper { |
| 2222 | 2253 | private static final int INTERVAL_MS = 15000; |
| 2223 | 2254 | |
| 2224 | 2255 | private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory("Reaper-%d")); |
| 2225 | - private final Set<Connection> connections = Sets.newSetFromMap(new ConcurrentHashMap<Connection, Boolean>()); | |
| 2256 | + private final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>(); | |
| 2226 | 2257 | |
| 2227 | 2258 | private volatile boolean shutdown; |
| 2228 | 2259 | |
| 2229 | 2260 | private final Runnable reaperTask = new Runnable() { |
| 2230 | 2261 | @Override |
| 2231 | 2262 | public void run() { |
| 2232 | - reapConnections(); | |
| 2233 | - if (!executor.isShutdown()) | |
| 2234 | - executor.schedule(this, INTERVAL_MS, TimeUnit.MILLISECONDS); | |
| 2235 | - } | |
| 2236 | - | |
| 2237 | - private final void reapConnections() { | |
| 2238 | - Iterator<Connection> iterator = connections.iterator(); | |
| 2263 | + long now = System.currentTimeMillis(); | |
| 2264 | + Iterator<Entry<Connection, Long>> iterator = connections.entrySet().iterator(); | |
| 2239 | 2265 | while (iterator.hasNext()) { |
| 2240 | - Connection connection = iterator.next(); | |
| 2241 | - boolean terminated = connection.terminate(false, true); | |
| 2242 | - if (terminated) | |
| 2243 | - iterator.remove(); | |
| 2266 | + Entry<Connection, Long> entry = iterator.next(); | |
| 2267 | + Connection connection = entry.getKey(); | |
| 2268 | + Long terminateTime = entry.getValue(); | |
| 2269 | + if (terminateTime <= now) { | |
| 2270 | + boolean terminated = connection.tryTerminate(true); | |
| 2271 | + if (terminated) | |
| 2272 | + iterator.remove(); | |
| 2273 | + } | |
| 2244 | 2274 | } |
| 2245 | 2275 | } |
| 2246 | 2276 | }; |
| 2247 | 2277 | |
| 2248 | 2278 | ConnectionReaper() { |
| 2249 | - executor.schedule(reaperTask, INTERVAL_MS, TimeUnit.MILLISECONDS); | |
| 2279 | + executor.scheduleWithFixedDelay(reaperTask, INTERVAL_MS, INTERVAL_MS, TimeUnit.MILLISECONDS); | |
| 2250 | 2280 | } |
| 2251 | 2281 | |
| 2252 | - void register(Connection connection) { | |
| 2282 | + void register(Connection connection, long terminateTime) { | |
| 2253 | 2283 | if (shutdown) { |
| 2254 | 2284 | // This should not happen since the reaper is shut down after all sessions. |
| 2255 | 2285 | logger.warn("Connection registered after reaper shutdown: {}", connection); |
| 2256 | - connection.terminate(true, true); | |
| 2286 | + connection.tryTerminate(true); | |
| 2257 | 2287 | } else { |
| 2258 | - connections.add(connection); | |
| 2288 | + connections.put(connection, terminateTime); | |
| 2259 | 2289 | } |
| 2260 | 2290 | } |
| 2261 | 2291 |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +41 −24
| @@ -71,8 +71,6 @@ | ||
| 71 | 71 | |
| 72 | 72 | private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>(); |
| 73 | 73 | |
| 74 | - private final Object terminationLock = new Object(); | |
| 75 | - | |
| 76 | 74 | /** |
| 77 | 75 | * Create a new connection to a Cassandra node. |
| 78 | 76 | * |
| @@ -388,13 +386,24 @@ | ||
| 388 | 386 | // twice (we will fail that method already) |
| 389 | 387 | dispatcher.removeHandler(handler.streamId, true); |
| 390 | 388 | |
| 391 | - ConnectionException ce; | |
| 389 | + final ConnectionException ce; | |
| 392 | 390 | if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) { |
| 393 | 391 | ce = new TransportException(address, "Error writing: Closed channel"); |
| 394 | 392 | } else { |
| 395 | 393 | ce = new TransportException(address, "Error writing", writeFuture.getCause()); |
| 396 | 394 | } |
| 397 | - handler.callback.onException(Connection.this, defunct(ce), System.nanoTime() - handler.startTime, handler.retryCount); | |
| 395 | + final long latency = System.nanoTime() - handler.startTime; | |
| 396 | + // This handler is executed while holding the writeLock of the channel. | |
| 397 | + // defunct might close the pool, which will close all of its connections; closing a connection also | |
| 398 | + // requires its writeLock. | |
| 399 | + // Therefore if multiple connections in the same pool get a write error, they could deadlock; | |
| 400 | + // we run defunct on a separate thread to avoid that. | |
| 401 | + factory.manager.executor.execute(new Runnable() { | |
| 402 | + @Override | |
| 403 | + public void run() { | |
| 404 | + handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount); | |
| 405 | + } | |
| 406 | + }); | |
| 398 | 407 | } else { |
| 399 | 408 | logger.trace("{} request sent successfully", Connection.this); |
| 400 | 409 | } |
| @@ -415,7 +424,7 @@ | ||
| 415 | 424 | * |
| 416 | 425 | * @return a future that will complete once the connection has terminated. |
| 417 | 426 | * |
| 418 | - * @see #terminate(boolean, boolean) | |
| 427 | + * @see #tryTerminate(boolean) | |
| 419 | 428 | */ |
| 420 | 429 | public CloseFuture closeAsync() { |
| 421 | 430 | |
| @@ -427,16 +436,28 @@ | ||
| 427 | 436 | |
| 428 | 437 | logger.debug("{} closing connection", this); |
| 429 | 438 | |
| 430 | - boolean terminated = terminate(false, false); | |
| 431 | - if (!terminated) | |
| 432 | - factory.reaper.register(this); | |
| 439 | + boolean terminated = tryTerminate(false); | |
| 440 | + if (!terminated) { | |
| 441 | + // The time by which all pending requests should have normally completed (use twice the read timeout for a generous | |
| 442 | + // estimate -- note that this does not cover the eventuality that read timeout is updated dynamically, but we can live | |
| 443 | + // with that). | |
| 444 | + long terminateTime = System.currentTimeMillis() + 2 * factory.getReadTimeoutMillis(); | |
| 445 | + factory.reaper.register(this, terminateTime); | |
| 446 | + } | |
| 433 | 447 | return future; |
| 434 | 448 | } |
| 435 | 449 | |
| 436 | 450 | /** |
| 437 | - * @return whether the connection has actually terminated | |
| 451 | + * Tries to terminate a closed connection, i.e. release system resources. | |
| 452 | + * | |
| 453 | + * This is called both by "normal" code and by {@link Cluster.ConnectionReaper}. | |
| 454 | + * | |
| 455 | + * @param force whether to proceed if there are still outstanding requests. | |
| 456 | + * @return whether the connection has actually terminated. | |
| 457 | + * | |
| 458 | + * @see #closeAsync() | |
| 438 | 459 | */ |
| 439 | - boolean terminate(boolean evenIfPending, boolean logWarnings) { | |
| 460 | + boolean tryTerminate(boolean force) { | |
| 440 | 461 | assert isClosed(); |
| 441 | 462 | ConnectionCloseFuture future = closeFuture.get(); |
| 442 | 463 | |
| @@ -444,18 +465,14 @@ | ||
| 444 | 465 | logger.debug("{} has already terminated", this); |
| 445 | 466 | return true; |
| 446 | 467 | } else { |
| 447 | - // This method is used both by normal code and by ConnectionReaper. Since the latter is a bug detection | |
| 448 | - // mechanism and logs warnings when it runs, we synchronize to avoid false warnings if they race. | |
| 449 | - synchronized (terminationLock) { | |
| 450 | - if (evenIfPending || dispatcher.pending.isEmpty()) { | |
| 451 | - if (logWarnings) | |
| 452 | - logger.warn("Forcing termination of {}. This should not happen and is likely a bug, please report.", this); | |
| 453 | - future.force(); | |
| 454 | - return true; | |
| 455 | - } else { | |
| 456 | - logger.debug("Not terminating {}: there are still pending requests", this); | |
| 457 | - return false; | |
| 458 | - } | |
| 468 | + if (force || dispatcher.pending.isEmpty()) { | |
| 469 | + if (force) | |
| 470 | + logger.warn("Forcing termination of {}. This should not happen and is likely a bug, please report.", this); | |
| 471 | + future.force(); | |
| 472 | + return true; | |
| 473 | + } else { | |
| 474 | + logger.debug("Not terminating {}: there are still pending requests", this); | |
| 475 | + return false; | |
| 459 | 476 | } |
| 460 | 477 | } |
| 461 | 478 | } |
| @@ -626,7 +643,7 @@ | ||
| 626 | 643 | streamIdHandler.release(streamId); |
| 627 | 644 | |
| 628 | 645 | if (isClosed()) |
| 629 | - terminate(false, false); | |
| 646 | + tryTerminate(false); | |
| 630 | 647 | } |
| 631 | 648 | |
| 632 | 649 | @Override |
| @@ -670,7 +687,7 @@ | ||
| 670 | 687 | // If we happen to be closed and we're the last outstanding request, we need to terminate the connection |
| 671 | 688 | // (note: this is racy as the signaling can be called more than once, but that's not a problem) |
| 672 | 689 | if (isClosed()) |
| 673 | - terminate(false, false); | |
| 690 | + tryTerminate(false); | |
| 674 | 691 | } |
| 675 | 692 | } |
| 676 | 693 |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +30 −12
| @@ -260,7 +260,7 @@ | ||
| 260 | 260 | // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces |
| 261 | 261 | // to be loaded. |
| 262 | 262 | logger.debug("[Control connection] Refreshing schema"); |
| 263 | - refreshSchema(connection, null, null, cluster, isInitialConnection); | |
| 263 | + refreshSchema(connection, null, null, null, cluster, isInitialConnection); | |
| 264 | 264 | return connection; |
| 265 | 265 | } catch (BusyConnectionException e) { |
| 266 | 266 | connection.closeAsync().get(); |
| @@ -271,14 +271,16 @@ | ||
| 271 | 271 | } |
| 272 | 272 | } |
| 273 | 273 | |
| 274 | - public void refreshSchema(String keyspace, String table) throws InterruptedException { | |
| 275 | - logger.debug("[Control connection] Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); | |
| 274 | + public void refreshSchema(String keyspace, String table, String udt) throws InterruptedException { | |
| 275 | + logger.debug("[Control connection] Refreshing schema for {}{}", | |
| 276 | + keyspace == null ? "everything" : keyspace, | |
| 277 | + table == null ? (udt == null ? "" : '.' + udt + " (UDT)") : '.' + table + " (table)"); | |
| 276 | 278 | try { |
| 277 | 279 | Connection c = connectionRef.get(); |
| 278 | 280 | // At startup, when we add the initial nodes, this will be null, which is ok |
| 279 | 281 | if (c == null) |
| 280 | 282 | return; |
| 281 | - refreshSchema(c, keyspace, table, cluster, false); | |
| 283 | + refreshSchema(c, keyspace, table, udt, cluster, false); | |
| 282 | 284 | } catch (ConnectionException e) { |
| 283 | 285 | logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage()); |
| 284 | 286 | signalError(); |
| @@ -293,7 +295,7 @@ | ||
| 293 | 295 | } |
| 294 | 296 | } |
| 295 | 297 | |
| 296 | - static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 298 | + static void refreshSchema(Connection connection, String keyspace, String table, String udt, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 297 | 299 | Host host = cluster.metadata.getHost(connection.address); |
| 298 | 300 | // Neither host, nor it's version should be null. But instead of dying if there is a race or something, we can kind of try to infer |
| 299 | 301 | // a Cassandra version from the protocol version (this is not full proof, we can have the protocol 1 against C* 2.0+, but it's worth |
| @@ -313,26 +315,39 @@ | ||
| 313 | 315 | whereClause = " WHERE keyspace_name = '" + keyspace + '\''; |
| 314 | 316 | if (table != null) |
| 315 | 317 | whereClause += " AND columnfamily_name = '" + table + '\''; |
| 318 | + else if (udt != null) | |
| 319 | + whereClause += " AND type_name = '" + udt + '\''; | |
| 316 | 320 | } |
| 317 | 321 | |
| 318 | - DefaultResultSetFuture ksFuture = table == null | |
| 322 | + DefaultResultSetFuture ksFuture = (table == null && udt == null) | |
| 319 | 323 | ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_KEYSPACES + whereClause)) |
| 320 | 324 | : null; |
| 321 | 325 | DefaultResultSetFuture udtFuture = table == null && (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) |
| 322 | 326 | ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_USERTYPES + whereClause)) |
| 323 | 327 | : null; |
| 324 | - DefaultResultSetFuture cfFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause)); | |
| 325 | - DefaultResultSetFuture colsFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMNS + whereClause)); | |
| 328 | + DefaultResultSetFuture cfFuture = udt == null | |
| 329 | + ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause)) | |
| 330 | + : null; | |
| 331 | + DefaultResultSetFuture colsFuture = udt == null | |
| 332 | + ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMNS + whereClause)) | |
| 333 | + : null; | |
| 326 | 334 | |
| 327 | 335 | if (ksFuture != null) |
| 328 | 336 | connection.write(ksFuture); |
| 329 | 337 | if (udtFuture != null) |
| 330 | 338 | connection.write(udtFuture); |
| 331 | - connection.write(cfFuture); | |
| 332 | - connection.write(colsFuture); | |
| 339 | + if (cfFuture != null) | |
| 340 | + connection.write(cfFuture); | |
| 341 | + if (colsFuture != null) | |
| 342 | + connection.write(colsFuture); | |
| 333 | 343 | |
| 334 | 344 | try { |
| 335 | - cluster.metadata.rebuildSchema(keyspace, table, ksFuture == null ? null : ksFuture.get(), udtFuture == null ? null : udtFuture.get(), cfFuture.get(), colsFuture.get(), cassandraVersion); | |
| 345 | + cluster.metadata.rebuildSchema(keyspace, table, udt, | |
| 346 | + ksFuture == null ? null : ksFuture.get(), | |
| 347 | + udtFuture == null ? null : udtFuture.get(), | |
| 348 | + cfFuture == null ? null : cfFuture.get(), | |
| 349 | + colsFuture == null ? null : colsFuture.get(), | |
| 350 | + cassandraVersion); | |
| 336 | 351 | } catch (RuntimeException e) { |
| 337 | 352 | // Failure to parse the schema is definitively wrong so log a full-on error, but this won't generally prevent queries to |
| 338 | 353 | // work and this can happen when new Cassandra versions modify stuff in the schema and the driver hasn't yet be modified. |
| @@ -451,7 +466,10 @@ | ||
| 451 | 466 | logger.error("No row found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); |
| 452 | 467 | return false; |
| 453 | 468 | } |
| 454 | - } else if (row.getInet("rpc_address") == null) { | |
| 469 | + // Ignore hosts with a null rpc_address, as this is most likely a phantom row in system.peers (JAVA-428). | |
| 470 | + // Don't test this for the control host since we're already connected to it anyway, and we read the info from system.local | |
| 471 | + // which doesn't have an rpc_address column (JAVA-546). | |
| 472 | + } else if (!c.address.equals(host.getSocketAddress()) && row.getInet("rpc_address") == null) { | |
| 455 | 473 | logger.error("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); |
| 456 | 474 | return false; |
| 457 | 475 | } |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +47 −17
| @@ -71,29 +71,59 @@ | ||
| 71 | 71 | ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement); |
| 72 | 72 | switch (scc.change) { |
| 73 | 73 | case CREATED: |
| 74 | - if (scc.name.isEmpty()) { | |
| 75 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, null, null); | |
| 76 | - } else { | |
| 77 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null); | |
| 74 | + switch (scc.target) { | |
| 75 | + case KEYSPACE: | |
| 76 | + session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null, null); | |
| 77 | + break; | |
| 78 | + case TABLE: | |
| 79 | + session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.name, null); | |
| 80 | + break; | |
| 81 | + case TYPE: | |
| 82 | + session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null, scc.name); | |
| 83 | + break; | |
| 78 | 84 | } |
| 79 | 85 | break; |
| 80 | 86 | case DROPPED: |
| 81 | - if (scc.name.isEmpty()) { | |
| 82 | - // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...) | |
| 83 | - // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements. | |
| 84 | - // We'll add it back if CASSANDRA-5358 changes that behavior | |
| 85 | - //if (scc.keyspace.equals(session.poolsState.keyspace)) | |
| 86 | - // session.poolsState.setKeyspace(null); | |
| 87 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, null, null); | |
| 88 | - } else { | |
| 89 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null); | |
| 87 | + KeyspaceMetadata keyspace; | |
| 88 | + switch (scc.target) { | |
| 89 | + case KEYSPACE: | |
| 90 | + // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...) | |
| 91 | + // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements. | |
| 92 | + // We'll add it back if CASSANDRA-5358 changes that behavior | |
| 93 | + //if (scc.keyspace.equals(session.poolsState.keyspace)) | |
| 94 | + // session.poolsState.setKeyspace(null); | |
| 95 | + session.cluster.manager.metadata.removeKeyspace(scc.keyspace); | |
| 96 | + break; | |
| 97 | + case TABLE: | |
| 98 | + keyspace = session.cluster.manager.metadata.getKeyspace(scc.keyspace); | |
| 99 | + if (keyspace == null) | |
| 100 | + logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata", | |
| 101 | + scc.keyspace, scc.name); | |
| 102 | + else | |
| 103 | + keyspace.removeTable(scc.name); | |
| 104 | + break; | |
| 105 | + case TYPE: | |
| 106 | + keyspace = session.cluster.manager.metadata.getKeyspace(scc.keyspace); | |
| 107 | + if (keyspace == null) | |
| 108 | + logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata", | |
| 109 | + scc.keyspace, scc.name); | |
| 110 | + else | |
| 111 | + keyspace.removeUserType(scc.name); | |
| 112 | + break; | |
| 90 | 113 | } |
| 114 | + this.setResult(rs); | |
| 91 | 115 | break; |
| 92 | 116 | case UPDATED: |
| 93 | - if (scc.name.isEmpty()) { | |
| 94 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null); | |
| 95 | - } else { | |
| 96 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.name); | |
| 117 | + switch (scc.target) { | |
| 118 | + case KEYSPACE: | |
| 119 | + session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null, null); | |
| 120 | + break; | |
| 121 | + case TABLE: | |
| 122 | + session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.name, null); | |
| 123 | + break; | |
| 124 | + case TYPE: | |
| 125 | + session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null, scc.name); | |
| 126 | + break; | |
| 97 | 127 | } |
| 98 | 128 | break; |
| 99 | 129 | default: |
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +16 −4
| @@ -60,10 +60,7 @@ | ||
| 60 | 60 | if (udtRows == null) |
| 61 | 61 | return ksm; |
| 62 | 62 | |
| 63 | - for (Row r : udtRows) { | |
| 64 | - UserType def = UserType.build(r); | |
| 65 | - ksm.userTypes.put(def.getTypeName(), def); | |
| 66 | - } | |
| 63 | + ksm.addUserTypes(udtRows); | |
| 67 | 64 | |
| 68 | 65 | return ksm; |
| 69 | 66 | } |
| @@ -107,6 +104,10 @@ | ||
| 107 | 104 | return tables.get(Metadata.handleId(name)); |
| 108 | 105 | } |
| 109 | 106 | |
| 107 | + void removeTable(String table) { | |
| 108 | + tables.remove(table); | |
| 109 | + } | |
| 110 | + | |
| 110 | 111 | /** |
| 111 | 112 | * Returns the tables defined in this keyspace. |
| 112 | 113 | * |
| @@ -138,6 +139,17 @@ | ||
| 138 | 139 | return Collections.<UserType>unmodifiableCollection(userTypes.values()); |
| 139 | 140 | } |
| 140 | 141 | |
| 142 | + void addUserTypes(List<Row> udtRows) { | |
| 143 | + for (Row r : udtRows) { | |
| 144 | + UserType def = UserType.build(r); | |
| 145 | + userTypes.put(def.getTypeName(), def); | |
| 146 | + } | |
| 147 | + } | |
| 148 | + | |
| 149 | + void removeUserType(String userType) { | |
| 150 | + userTypes.remove(userType); | |
| 151 | + } | |
| 152 | + | |
| 141 | 153 | /** |
| 142 | 154 | * Returns a {@code String} containing CQL queries representing this |
| 143 | 155 | * keyspace and the user types and tables it contains. |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +52 −31
| @@ -49,21 +49,23 @@ | ||
| 49 | 49 | } |
| 50 | 50 | |
| 51 | 51 | // Synchronized to make it easy to detect dropped keyspaces |
| 52 | - synchronized void rebuildSchema(String keyspace, String table, ResultSet ks, ResultSet udts, ResultSet cfs, ResultSet cols, VersionNumber cassandraVersion) { | |
| 52 | + synchronized void rebuildSchema(String keyspaceName, String tableName, String udtName, ResultSet ks, ResultSet udts, ResultSet cfs, ResultSet cols, VersionNumber cassandraVersion) { | |
| 53 | 53 | |
| 54 | 54 | Map<String, List<Row>> cfDefs = new HashMap<String, List<Row>>(); |
| 55 | 55 | Map<String, List<Row>> udtDefs = new HashMap<String, List<Row>>(); |
| 56 | 56 | Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>(); |
| 57 | 57 | |
| 58 | 58 | // Gather cf defs |
| 59 | - for (Row row : cfs) { | |
| 60 | - String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 61 | - List<Row> l = cfDefs.get(ksName); | |
| 62 | - if (l == null) { | |
| 63 | - l = new ArrayList<Row>(); | |
| 64 | - cfDefs.put(ksName, l); | |
| 59 | + if (cfs != null) { | |
| 60 | + for (Row row : cfs) { | |
| 61 | + String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 62 | + List<Row> l = cfDefs.get(ksName); | |
| 63 | + if (l == null) { | |
| 64 | + l = new ArrayList<Row>(); | |
| 65 | + cfDefs.put(ksName, l); | |
| 66 | + } | |
| 67 | + l.add(row); | |
| 65 | 68 | } |
| 66 | - l.add(row); | |
| 67 | 69 | } |
| 68 | 70 | |
| 69 | 71 | // Gather udt defs |
| @@ -80,24 +82,26 @@ | ||
| 80 | 82 | } |
| 81 | 83 | |
| 82 | 84 | // Gather columns per Cf |
| 83 | - for (Row row : cols) { | |
| 84 | - String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 85 | - String cfName = row.getString(TableMetadata.CF_NAME); | |
| 86 | - Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = colsDefs.get(ksName); | |
| 87 | - if (colsByCf == null) { | |
| 88 | - colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>(); | |
| 89 | - colsDefs.put(ksName, colsByCf); | |
| 90 | - } | |
| 91 | - Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName); | |
| 92 | - if (l == null) { | |
| 93 | - l = new HashMap<String, ColumnMetadata.Raw>(); | |
| 94 | - colsByCf.put(cfName, l); | |
| 85 | + if (cols != null) { | |
| 86 | + for (Row row : cols) { | |
| 87 | + String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 88 | + String cfName = row.getString(TableMetadata.CF_NAME); | |
| 89 | + Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = colsDefs.get(ksName); | |
| 90 | + if (colsByCf == null) { | |
| 91 | + colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>(); | |
| 92 | + colsDefs.put(ksName, colsByCf); | |
| 93 | + } | |
| 94 | + Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName); | |
| 95 | + if (l == null) { | |
| 96 | + l = new HashMap<String, ColumnMetadata.Raw>(); | |
| 97 | + colsByCf.put(cfName, l); | |
| 98 | + } | |
| 99 | + ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion); | |
| 100 | + l.put(c.name, c); | |
| 95 | 101 | } |
| 96 | - ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion); | |
| 97 | - l.put(c.name, c); | |
| 98 | 102 | } |
| 99 | 103 | |
| 100 | - if (table == null) { | |
| 104 | + if (tableName == null && udtName == null) { // Refresh one or all keyspaces | |
| 101 | 105 | assert ks != null; |
| 102 | 106 | Set<String> addedKs = new HashSet<String>(); |
| 103 | 107 | for (Row ksRow : ks) { |
| @@ -113,27 +117,39 @@ | ||
| 113 | 117 | |
| 114 | 118 | // If keyspace is null, it means we're rebuilding from scratch, so |
| 115 | 119 | // remove anything that was not just added as it means it's a dropped keyspace |
| 116 | - if (keyspace == null) { | |
| 120 | + if (keyspaceName == null) { | |
| 117 | 121 | Iterator<String> iter = keyspaces.keySet().iterator(); |
| 118 | 122 | while (iter.hasNext()) { |
| 119 | 123 | if (!addedKs.contains(iter.next())) |
| 120 | 124 | iter.remove(); |
| 121 | 125 | } |
| 122 | 126 | } |
| 123 | - } else { | |
| 124 | - assert keyspace != null; | |
| 125 | - KeyspaceMetadata ksm = keyspaces.get(keyspace); | |
| 127 | + } else if (tableName != null) { | |
| 128 | + assert keyspaceName != null; | |
| 129 | + KeyspaceMetadata ksm = keyspaces.get(keyspaceName); | |
| 126 | 130 | |
| 127 | 131 | // If we update a keyspace we don't know about, something went |
| 128 | 132 | // wrong. Log an error an schedule a full schema rebuilt. |
| 129 | 133 | if (ksm == null) { |
| 130 | - logger.error(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", keyspace, table, keyspace)); | |
| 131 | - cluster.submitSchemaRefresh(null, null); | |
| 134 | + logger.error(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", keyspaceName, tableName, keyspaceName)); | |
| 135 | + cluster.submitSchemaRefresh(null, null, null); | |
| 136 | + return; | |
| 137 | + } | |
| 138 | + | |
| 139 | + if (cfDefs.containsKey(keyspaceName)) | |
| 140 | + buildTableMetadata(ksm, cfDefs.get(keyspaceName), colsDefs.get(keyspaceName), cassandraVersion); | |
| 141 | + } else { // udtName != null | |
| 142 | + assert keyspaceName != null; | |
| 143 | + KeyspaceMetadata ksm = keyspaces.get(keyspaceName); | |
| 144 | + | |
| 145 | + if (ksm == null) { | |
| 146 | + logger.error(String.format("Asked to rebuild type %s.%s but I don't know keyspace %s", keyspaceName, udtName, keyspaceName)); | |
| 147 | + cluster.submitSchemaRefresh(null, null, null); | |
| 132 | 148 | return; |
| 133 | 149 | } |
| 134 | 150 | |
| 135 | - if (cfDefs.containsKey(keyspace)) | |
| 136 | - buildTableMetadata(ksm, cfDefs.get(keyspace), colsDefs.get(keyspace), cassandraVersion); | |
| 151 | + if (udtDefs.containsKey(keyspaceName)) | |
| 152 | + ksm.addUserTypes(udtDefs.get(keyspaceName)); | |
| 137 | 153 | } |
| 138 | 154 | } |
| 139 | 155 | |
| @@ -312,6 +328,11 @@ | ||
| 312 | 328 | return keyspaces.get(handleId(keyspace)); |
| 313 | 329 | } |
| 314 | 330 | |
| 331 | + void removeKeyspace(String keyspace) { | |
| 332 | + keyspaces.remove(keyspace); | |
| 333 | + tokenMap.tokenToHosts.remove(keyspace); | |
| 334 | + } | |
| 335 | + | |
| 315 | 336 | /** |
| 316 | 337 | * Returns a list of all the defined keyspaces. |
| 317 | 338 | * |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java +54 −15
| @@ -15,7 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | -import java.net.InetAddress; | |
| 18 | +import java.io.PrintWriter; | |
| 19 | +import java.io.StringWriter; | |
| 19 | 20 | import java.net.InetSocketAddress; |
| 20 | 21 | import java.util.HashMap; |
| 21 | 22 | import java.util.Map; |
| @@ -37,10 +38,12 @@ | ||
| 37 | 38 | |
| 38 | 39 | private static final long serialVersionUID = 0; |
| 39 | 40 | |
| 41 | + private static final int MAX_ERRORS_IN_DEFAULT_MESSAGE = 3; | |
| 42 | + | |
| 40 | 43 | private final Map<InetSocketAddress, Throwable> errors; |
| 41 | 44 | |
| 42 | 45 | public NoHostAvailableException(Map<InetSocketAddress, Throwable> errors) { |
| 43 | - super(makeMessage(errors)); | |
| 46 | + super(makeMessage(errors, MAX_ERRORS_IN_DEFAULT_MESSAGE, false, false)); | |
| 44 | 47 | this.errors = errors; |
| 45 | 48 | } |
| 46 | 49 | |
| @@ -60,28 +63,64 @@ | ||
| 60 | 63 | return new HashMap<InetSocketAddress, Throwable>(errors); |
| 61 | 64 | } |
| 62 | 65 | |
| 66 | + /** | |
| 67 | + * Builds a custom message for this exception. | |
| 68 | + * | |
| 69 | + * @param maxErrors the maximum number of errors displayed (useful to limit the size of the message for big clusters). Beyond this limit, | |
| 70 | + * host names are still displayed, but not the associated errors. Set to {@code Integer.MAX_VALUE} to display all hosts. | |
| 71 | + * @param formatted whether to format the output (line break between each host). | |
| 72 | + * @param includeStackTraces whether to include the full stacktrace of each host error. Note that this automatically implies | |
| 73 | + * {@code formatted}. | |
| 74 | + * @return the message. | |
| 75 | + */ | |
| 76 | + public String getCustomMessage(int maxErrors, boolean formatted, boolean includeStackTraces) { | |
| 77 | + if (includeStackTraces) | |
| 78 | + formatted = true; | |
| 79 | + return makeMessage(errors, maxErrors, formatted, includeStackTraces); | |
| 80 | + } | |
| 81 | + | |
| 63 | 82 | @Override |
| 64 | 83 | public DriverException copy() { |
| 65 | 84 | return new NoHostAvailableException(getMessage(), this, errors); |
| 66 | 85 | } |
| 67 | 86 | |
| 68 | - private static String makeMessage(Map<InetSocketAddress, Throwable> errors) { | |
| 69 | - // For small cluster, ship the whole error detail in the error message. | |
| 70 | - // This is helpful when debugging on a localhost/test cluster in particular. | |
| 87 | + private static String makeMessage(Map<InetSocketAddress, Throwable> errors, int maxErrorsInMessage, boolean formatted, boolean includeStackTraces) { | |
| 71 | 88 | if (errors.size() == 0) |
| 72 | 89 | return "All host(s) tried for query failed (no host was tried)"; |
| 73 | 90 | |
| 74 | - if (errors.size() <= 3) { | |
| 75 | - StringBuilder sb = new StringBuilder(); | |
| 76 | - sb.append("All host(s) tried for query failed (tried: "); | |
| 77 | - int n = 0; | |
| 78 | - for (Map.Entry<InetSocketAddress, Throwable> entry : errors.entrySet()) | |
| 79 | - { | |
| 80 | - if (n++ > 0) sb.append(", "); | |
| 81 | - sb.append(entry.getKey()).append(" (").append(entry.getValue()).append(')'); | |
| 91 | + StringWriter stringWriter = new StringWriter(); | |
| 92 | + PrintWriter out = new PrintWriter(stringWriter); | |
| 93 | + | |
| 94 | + out.print("All host(s) tried for query failed (tried:"); | |
| 95 | + out.print(formatted ? "\n" : " "); | |
| 96 | + | |
| 97 | + int n = 0; | |
| 98 | + boolean truncated = false; | |
| 99 | + for (Map.Entry<InetSocketAddress, Throwable> entry : errors.entrySet()) | |
| 100 | + { | |
| 101 | + if (n > 0) out.print(formatted ? "\n" : ", "); | |
| 102 | + out.print(entry.getKey()); | |
| 103 | + if (n < maxErrorsInMessage) { | |
| 104 | + if (includeStackTraces) { | |
| 105 | + out.print("\n"); | |
| 106 | + entry.getValue().printStackTrace(out); | |
| 107 | + out.print("\n"); | |
| 108 | + } else { | |
| 109 | + out.printf(" (%s)", entry.getValue()); | |
| 110 | + } | |
| 111 | + } else { | |
| 112 | + truncated = true; | |
| 82 | 113 | } |
| 83 | - return sb.append(')').toString(); | |
| 114 | + n += 1; | |
| 115 | + } | |
| 116 | + if (truncated) { | |
| 117 | + out.print(formatted ? "\n" : " "); | |
| 118 | + out.printf("[only showing errors of first %d hosts, use getErrors() for more details]", maxErrorsInMessage); | |
| 84 | 119 | } |
| 85 | - return String.format("All host(s) tried for query failed (tried: %s - use getErrors() for details)", errors.keySet()); | |
| 120 | + if (formatted && !includeStackTraces) | |
| 121 | + out.print("\n"); | |
| 122 | + out.print(")"); | |
| 123 | + out.close(); | |
| 124 | + return stringWriter.toString(); | |
| 86 | 125 | } |
| 87 | 126 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +4 −0
| @@ -98,6 +98,10 @@ | ||
| 98 | 98 | * <p> |
| 99 | 99 | * The default load balancing policy is {@link DCAwareRoundRobinPolicy} with token |
| 100 | 100 | * awareness (so {@code new TokenAwarePolicy(new DCAwareRoundRobinPolicy())}). |
| 101 | + * <p> | |
| 102 | + * Note that this policy shuffles the replicas when token awareness is used, see | |
| 103 | + * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy,boolean)} for an | |
| 104 | + * explanation of the tradeoffs. | |
| 101 | 105 | * |
| 102 | 106 | * @return the default load balancing policy. |
| 103 | 107 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java +11 −6
| @@ -55,10 +55,15 @@ | ||
| 55 | 55 | /** |
| 56 | 56 | * Creates a new {@code TokenAware} policy. |
| 57 | 57 | * |
| 58 | - * @param childPolicy the load balancing policy to wrap with token | |
| 59 | - * awareness. | |
| 60 | - * @param shuffleReplicas whether to shuffle the replicas returned | |
| 61 | - * by {@code getRoutingKey}. | |
| 58 | + * @param childPolicy the load balancing policy to wrap with token awareness. | |
| 59 | + * @param shuffleReplicas whether to shuffle the replicas returned by {@code getRoutingKey}. | |
| 60 | + * Note that setting this parameter to {@code true} might decrease the | |
| 61 | + * effectiveness of caching (especially at consistency level ONE), since | |
| 62 | + * the same row will be retrieved from any replica (instead of only the | |
| 63 | + * "primary" replica without shuffling). | |
| 64 | + * On the other hand, shuffling will better distribute writes, and can | |
| 65 | + * alleviate hotspots caused by "fat" partitions. | |
| 66 | + * | |
| 62 | 67 | */ |
| 63 | 68 | public TokenAwarePolicy(LoadBalancingPolicy childPolicy, boolean shuffleReplicas) { |
| 64 | 69 | this.childPolicy = childPolicy; |
| @@ -66,7 +71,7 @@ | ||
| 66 | 71 | } |
| 67 | 72 | |
| 68 | 73 | /** |
| 69 | - * Creates a new {@code TokenAware} policy with no shuffling of replicas. | |
| 74 | + * Creates a new {@code TokenAware} policy with shuffling of replicas. | |
| 70 | 75 | * |
| 71 | 76 | * @param childPolicy the load balancing policy to wrap with token |
| 72 | 77 | * awareness. |
| @@ -74,7 +79,7 @@ | ||
| 74 | 79 | * @see #TokenAwarePolicy(LoadBalancingPolicy, boolean) |
| 75 | 80 | */ |
| 76 | 81 | public TokenAwarePolicy(LoadBalancingPolicy childPolicy) { |
| 77 | - this(childPolicy, false); | |
| 82 | + this(childPolicy, true); | |
| 78 | 83 | } |
| 79 | 84 | |
| 80 | 85 | @Override |
added driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +143 −0
| @@ -0,0 +1,143 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.Collection; | |
| 4 | +import java.util.List; | |
| 5 | + | |
| 6 | +import com.google.common.collect.Lists; | |
| 7 | +import org.testng.annotations.AfterClass; | |
| 8 | +import org.testng.annotations.AfterMethod; | |
| 9 | +import org.testng.annotations.BeforeClass; | |
| 10 | +import org.testng.annotations.Test; | |
| 11 | + | |
| 12 | +import com.datastax.driver.core.utils.Bytes; | |
| 13 | + | |
| 14 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 15 | + | |
| 16 | +public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 17 | + | |
| 18 | + // Create a second cluster to check that other clients also get notified | |
| 19 | + Cluster cluster2; | |
| 20 | + // The metadatas of the two clusters should be kept in sync | |
| 21 | + List<Metadata> metadatas; | |
| 22 | + | |
| 23 | + @Override | |
| 24 | + protected Collection<String> getTableDefinitions() { | |
| 25 | + return Lists.newArrayList(); | |
| 26 | + } | |
| 27 | + | |
| 28 | + @BeforeClass(groups = "short") | |
| 29 | + public void setup() { | |
| 30 | + cluster2 = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 31 | + metadatas = Lists.newArrayList(cluster.getMetadata(), cluster2.getMetadata()); | |
| 32 | + } | |
| 33 | + | |
| 34 | + @Test(groups = "short") | |
| 35 | + public void should_notify_of_table_creation() { | |
| 36 | + session.execute("CREATE TABLE ks.table1(i int primary key)"); | |
| 37 | + | |
| 38 | + for (Metadata m : metadatas) | |
| 39 | + assertThat(m.getKeyspace("ks").getTable("table1")) | |
| 40 | + .isNotNull(); | |
| 41 | + } | |
| 42 | + | |
| 43 | + @Test(groups = "short") | |
| 44 | + public void should_notify_of_table_update() { | |
| 45 | + session.execute("CREATE TABLE ks.table1(i int primary key)"); | |
| 46 | + session.execute("ALTER TABLE ks.table1 ADD j int"); | |
| 47 | + | |
| 48 | + for (Metadata m : metadatas) | |
| 49 | + assertThat(m.getKeyspace("ks").getTable("table1").getColumn("j")) | |
| 50 | + .isNotNull(); | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Test(groups = "short") | |
| 54 | + public void should_notify_of_table_drop() { | |
| 55 | + session.execute("CREATE TABLE ks.table1(i int primary key)"); | |
| 56 | + session.execute("DROP TABLE ks.table1"); | |
| 57 | + | |
| 58 | + for (Metadata m : metadatas) | |
| 59 | + assertThat(m.getKeyspace("ks").getTable("table1")) | |
| 60 | + .isNull(); | |
| 61 | + } | |
| 62 | + | |
| 63 | + @Test(groups = "short") | |
| 64 | + public void should_notify_of_udt_creation() { | |
| 65 | + session.execute("CREATE TYPE ks.type1(i int)"); | |
| 66 | + | |
| 67 | + for (Metadata m : metadatas) | |
| 68 | + assertThat(m.getKeyspace("ks").getUserType("type1")) | |
| 69 | + .isNotNull(); | |
| 70 | + } | |
| 71 | + | |
| 72 | + @Test(groups = "short") | |
| 73 | + public void should_notify_of_udt_update() { | |
| 74 | + session.execute("CREATE TYPE ks.type1(i int)"); | |
| 75 | + session.execute("ALTER TYPE ks.type1 ADD j int"); | |
| 76 | + | |
| 77 | + for (Metadata m : metadatas) | |
| 78 | + assertThat(m.getKeyspace("ks").getUserType("type1").getFieldType("j")) | |
| 79 | + .isNotNull(); | |
| 80 | + } | |
| 81 | + | |
| 82 | + @Test(groups = "short") | |
| 83 | + public void should_notify_of_udt_drop() { | |
| 84 | + session.execute("CREATE TYPE ks.type1(i int)"); | |
| 85 | + session.execute("DROP TYPE ks.type1"); | |
| 86 | + | |
| 87 | + for (Metadata m : metadatas) | |
| 88 | + assertThat(m.getKeyspace("ks").getUserType("type1")) | |
| 89 | + .isNull(); | |
| 90 | + } | |
| 91 | + | |
| 92 | + @Test(groups = "short") | |
| 93 | + public void should_notify_of_keyspace_creation() { | |
| 94 | + session.execute("CREATE KEYSPACE ks2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 95 | + | |
| 96 | + for (Metadata m : metadatas) | |
| 97 | + assertThat(m.getKeyspace("ks2")) | |
| 98 | + .isNotNull(); | |
| 99 | + } | |
| 100 | + | |
| 101 | + @Test(groups = "short") | |
| 102 | + public void should_notify_of_keyspace_update() { | |
| 103 | + session.execute("CREATE KEYSPACE ks2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 104 | + for (Metadata m : metadatas) | |
| 105 | + assertThat(m.getKeyspace("ks2").isDurableWrites()) | |
| 106 | + .isTrue(); | |
| 107 | + | |
| 108 | + session.execute("ALTER KEYSPACE ks2 WITH durable_writes = false"); | |
| 109 | + for (Metadata m : metadatas) | |
| 110 | + assertThat(m.getKeyspace("ks2").isDurableWrites()) | |
| 111 | + .isFalse(); | |
| 112 | + } | |
| 113 | + | |
| 114 | + @Test(groups = "short") | |
| 115 | + public void should_notify_of_keyspace_drop() { | |
| 116 | + session.execute("CREATE KEYSPACE ks2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 117 | + for (Metadata m : metadatas) | |
| 118 | + assertThat(m.getReplicas("ks2", Bytes.fromHexString("0xCAFEBABE"))) | |
| 119 | + .isNotEmpty(); | |
| 120 | + | |
| 121 | + session.execute("DROP KEYSPACE ks2"); | |
| 122 | + | |
| 123 | + for (Metadata m : metadatas) { | |
| 124 | + assertThat(m.getKeyspace("ks2")) | |
| 125 | + .isNull(); | |
| 126 | + assertThat(m.getReplicas("ks2", Bytes.fromHexString("0xCAFEBABE"))) | |
| 127 | + .isEmpty(); | |
| 128 | + } | |
| 129 | + } | |
| 130 | + | |
| 131 | + @AfterMethod(groups = "short") | |
| 132 | + public void cleanup() { | |
| 133 | + session.execute("DROP TABLE IF EXISTS ks.table1"); | |
| 134 | + session.execute("DROP TYPE IF EXISTS ks.type1"); | |
| 135 | + session.execute("DROP KEYSPACE IF EXISTS ks2"); | |
| 136 | + } | |
| 137 | + | |
| 138 | + @AfterClass(groups = "short") | |
| 139 | + public void teardown() { | |
| 140 | + if (cluster2 != null) | |
| 141 | + cluster2.close(); | |
| 142 | + } | |
| 143 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +1 −1
| @@ -316,7 +316,7 @@ | ||
| 316 | 316 | // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force |
| 317 | 317 | // the detection by forcing a request. |
| 318 | 318 | if (waitForDead || waitForOut) |
| 319 | - cluster.manager.submitSchemaRefresh(null, null); | |
| 319 | + cluster.manager.submitSchemaRefresh(null, null, null); | |
| 320 | 320 | |
| 321 | 321 | InetAddress address; |
| 322 | 322 | try { |
added driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java +86 −0
| @@ -0,0 +1,86 @@ | ||
| 1 | +package com.datastax.driver.core.exceptions; | |
| 2 | + | |
| 3 | +import java.io.PrintWriter; | |
| 4 | +import java.net.InetSocketAddress; | |
| 5 | +import java.util.Map; | |
| 6 | + | |
| 7 | +import com.beust.jcommander.internal.Maps; | |
| 8 | +import org.testng.annotations.Test; | |
| 9 | + | |
| 10 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 11 | + | |
| 12 | +public class NoHostAvailableExceptionTest { | |
| 13 | + @Test(groups = "unit") | |
| 14 | + public void should_build_default_message_when_less_than_3_errors() { | |
| 15 | + NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3)); | |
| 16 | + assertThat(e.getMessage()) | |
| 17 | + .isEqualTo("All host(s) tried for query failed (tried: " | |
| 18 | + + "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1), " | |
| 19 | + + "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3), " | |
| 20 | + + "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)" | |
| 21 | + + ")" | |
| 22 | + ); | |
| 23 | + } | |
| 24 | + | |
| 25 | + @Test(groups = "unit") | |
| 26 | + public void should_build_default_message_when_more_than_3_errors() { | |
| 27 | + NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(4)); | |
| 28 | + assertThat(e.getMessage()) | |
| 29 | + .isEqualTo("All host(s) tried for query failed (tried: " | |
| 30 | + + "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1), " | |
| 31 | + + "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3), " | |
| 32 | + + "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2), " | |
| 33 | + + "/127.0.0.4:9042 " | |
| 34 | + + "[only showing errors of first 3 hosts, use getErrors() for more details]" | |
| 35 | + + ")" | |
| 36 | + ); | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Test(groups = "unit") | |
| 40 | + public void should_build_formatted_message_without_stack_traces() { | |
| 41 | + NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3)); | |
| 42 | + assertThat(e.getCustomMessage(3, true, false)) | |
| 43 | + .isEqualTo("All host(s) tried for query failed (tried:\n" | |
| 44 | + + "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)\n" | |
| 45 | + + "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)\n" | |
| 46 | + + "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)\n" | |
| 47 | + + ")" | |
| 48 | + ); | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Test(groups = "unit") | |
| 52 | + public void should_build_formatted_message_with_stack_traces() { | |
| 53 | + NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3)); | |
| 54 | + assertThat(e.getCustomMessage(3, true, true)) | |
| 55 | + .isEqualTo("All host(s) tried for query failed (tried:\n" | |
| 56 | + + "/127.0.0.1:9042\n" | |
| 57 | + + "mock stack trace 1\n\n" | |
| 58 | + + "/127.0.0.3:9042\n" | |
| 59 | + + "mock stack trace 3\n\n" | |
| 60 | + + "/127.0.0.2:9042\n" | |
| 61 | + + "mock stack trace 2\n" | |
| 62 | + + ")" | |
| 63 | + ); | |
| 64 | + } | |
| 65 | + | |
| 66 | + private static Map<InetSocketAddress, Throwable> buildMockErrors(int count) { | |
| 67 | + Map<InetSocketAddress, Throwable> errors = Maps.newHashMap(); | |
| 68 | + for (int i = 1; i <= count; i++) { | |
| 69 | + errors.put(new InetSocketAddress("127.0.0." + i, 9042), new MockError(i)); | |
| 70 | + } | |
| 71 | + return errors; | |
| 72 | + } | |
| 73 | + | |
| 74 | + static class MockError extends Exception { | |
| 75 | + private final int i; | |
| 76 | + | |
| 77 | + MockError(int i) { | |
| 78 | + super("mock error " + i); | |
| 79 | + this.i = i; | |
| 80 | + } | |
| 81 | + | |
| 82 | + @Override public void printStackTrace(PrintWriter writer) { | |
| 83 | + writer.printf("mock stack trace %d", i); | |
| 84 | + } | |
| 85 | + } | |
| 86 | +} | |
| No newline at the end of the file |