Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changesetddeff16a1cf411cadee3aa8cc382c65700496a28bb7229d5cdff92117dbbb4d4
Authorolim7t <omichallat+github@gmail.com> · 2014-12-10 16:34 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-12-10 16:34 +01:00
Parents194efecc5f37, 125b3d45cbd8

Browse the files at this changeset

15 files changed

modified .gitignore +2 −0
@@ -10,3 +10,5 @@
1010
1111 /.idea
1212 *.iml
13+
14+/driver-core/dependency-reduced-pom.xml
modified driver-core/CHANGELOG.rst +15 −0
@@ -1,6 +1,21 @@
11 CHANGELOG
22 =========
33
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+
419 2.1.3:
520 ------
621
modified driver-core/pom.xml +23 −0
@@ -207,6 +207,29 @@
207207 <showDeprecation>true</showDeprecation>
208208 </configuration>
209209 </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>
210233 </plugins>
211234 </build>
212235 </profile>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +68 −38
@@ -20,17 +20,14 @@
2020 import java.net.InetSocketAddress;
2121 import java.net.UnknownHostException;
2222 import java.util.*;
23+import java.util.Map.Entry;
2324 import java.util.concurrent.*;
2425 import java.util.concurrent.atomic.AtomicInteger;
2526 import java.util.concurrent.atomic.AtomicReference;
2627
2728 import com.google.common.annotations.VisibleForTesting;
2829 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.*;
3431 import com.google.common.util.concurrent.*;
3532
3633 import org.slf4j.Logger;
@@ -1959,18 +1956,18 @@
19591956 }
19601957 }
19611958
1962- public void submitSchemaRefresh(final String keyspace, final String table) {
1959+ public void submitSchemaRefresh(final String keyspace, final String table, final String udt) {
19631960 logger.trace("Submitting schema refresh");
19641961 executor.submit(new ExceptionCatchingRunnable() {
19651962 @Override
19661963 public void runMayThrow() throws InterruptedException, ExecutionException {
1967- controlConnection.refreshSchema(keyspace, table);
1964+ controlConnection.refreshSchema(keyspace, table, udt);
19681965 }
19691966 });
19701967 }
19711968
19721969 // 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) {
19741971 if (logger.isDebugEnabled())
19751972 logger.debug("Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table);
19761973
@@ -1982,10 +1979,10 @@
19821979 // that querying a table just after having created it don't fail.
19831980 if (!ControlConnection.waitForSchemaAgreement(connection, Cluster.Manager.this))
19841981 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);
19861983 } catch (Exception e) {
19871984 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);
19891986 } finally {
19901987 // Always sets the result
19911988 future.setResult(rs);
@@ -2104,22 +2101,54 @@
21042101 ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
21052102 switch (scc.change) {
21062103 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+ }
21112115 break;
21122116 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+ }
21172139 break;
21182140 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+ }
21232152 break;
21242153 }
21252154 break;
@@ -2217,45 +2246,46 @@
22172246 * This is normally done when the connection errors out, or when the last request is processed; this class acts as
22182247 * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection,
22192248 * this indicates a bug; warnings are logged so that this can be reported.
2249+ *
2250+ * @see Connection#tryTerminate(boolean)
22202251 */
22212252 static class ConnectionReaper {
22222253 private static final int INTERVAL_MS = 15000;
22232254
22242255 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>();
22262257
22272258 private volatile boolean shutdown;
22282259
22292260 private final Runnable reaperTask = new Runnable() {
22302261 @Override
22312262 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();
22392265 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+ }
22442274 }
22452275 }
22462276 };
22472277
22482278 ConnectionReaper() {
2249- executor.schedule(reaperTask, INTERVAL_MS, TimeUnit.MILLISECONDS);
2279+ executor.scheduleWithFixedDelay(reaperTask, INTERVAL_MS, INTERVAL_MS, TimeUnit.MILLISECONDS);
22502280 }
22512281
2252- void register(Connection connection) {
2282+ void register(Connection connection, long terminateTime) {
22532283 if (shutdown) {
22542284 // This should not happen since the reaper is shut down after all sessions.
22552285 logger.warn("Connection registered after reaper shutdown: {}", connection);
2256- connection.terminate(true, true);
2286+ connection.tryTerminate(true);
22572287 } else {
2258- connections.add(connection);
2288+ connections.put(connection, terminateTime);
22592289 }
22602290 }
22612291
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +41 −24
@@ -71,8 +71,6 @@
7171
7272 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
7373
74- private final Object terminationLock = new Object();
75-
7674 /**
7775 * Create a new connection to a Cassandra node.
7876 *
@@ -388,13 +386,24 @@
388386 // twice (we will fail that method already)
389387 dispatcher.removeHandler(handler.streamId, true);
390388
391- ConnectionException ce;
389+ final ConnectionException ce;
392390 if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) {
393391 ce = new TransportException(address, "Error writing: Closed channel");
394392 } else {
395393 ce = new TransportException(address, "Error writing", writeFuture.getCause());
396394 }
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+ });
398407 } else {
399408 logger.trace("{} request sent successfully", Connection.this);
400409 }
@@ -415,7 +424,7 @@
415424 *
416425 * @return a future that will complete once the connection has terminated.
417426 *
418- * @see #terminate(boolean, boolean)
427+ * @see #tryTerminate(boolean)
419428 */
420429 public CloseFuture closeAsync() {
421430
@@ -427,16 +436,28 @@
427436
428437 logger.debug("{} closing connection", this);
429438
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+ }
433447 return future;
434448 }
435449
436450 /**
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()
438459 */
439- boolean terminate(boolean evenIfPending, boolean logWarnings) {
460+ boolean tryTerminate(boolean force) {
440461 assert isClosed();
441462 ConnectionCloseFuture future = closeFuture.get();
442463
@@ -444,18 +465,14 @@
444465 logger.debug("{} has already terminated", this);
445466 return true;
446467 } 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;
459476 }
460477 }
461478 }
@@ -626,7 +643,7 @@
626643 streamIdHandler.release(streamId);
627644
628645 if (isClosed())
629- terminate(false, false);
646+ tryTerminate(false);
630647 }
631648
632649 @Override
@@ -670,7 +687,7 @@
670687 // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
671688 // (note: this is racy as the signaling can be called more than once, but that's not a problem)
672689 if (isClosed())
673- terminate(false, false);
690+ tryTerminate(false);
674691 }
675692 }
676693
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +30 −12
@@ -260,7 +260,7 @@
260260 // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces
261261 // to be loaded.
262262 logger.debug("[Control connection] Refreshing schema");
263- refreshSchema(connection, null, null, cluster, isInitialConnection);
263+ refreshSchema(connection, null, null, null, cluster, isInitialConnection);
264264 return connection;
265265 } catch (BusyConnectionException e) {
266266 connection.closeAsync().get();
@@ -271,14 +271,16 @@
271271 }
272272 }
273273
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)");
276278 try {
277279 Connection c = connectionRef.get();
278280 // At startup, when we add the initial nodes, this will be null, which is ok
279281 if (c == null)
280282 return;
281- refreshSchema(c, keyspace, table, cluster, false);
283+ refreshSchema(c, keyspace, table, udt, cluster, false);
282284 } catch (ConnectionException e) {
283285 logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage());
284286 signalError();
@@ -293,7 +295,7 @@
293295 }
294296 }
295297
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 {
297299 Host host = cluster.metadata.getHost(connection.address);
298300 // 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
299301 // 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 @@
313315 whereClause = " WHERE keyspace_name = '" + keyspace + '\'';
314316 if (table != null)
315317 whereClause += " AND columnfamily_name = '" + table + '\'';
318+ else if (udt != null)
319+ whereClause += " AND type_name = '" + udt + '\'';
316320 }
317321
318- DefaultResultSetFuture ksFuture = table == null
322+ DefaultResultSetFuture ksFuture = (table == null && udt == null)
319323 ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_KEYSPACES + whereClause))
320324 : null;
321325 DefaultResultSetFuture udtFuture = table == null && (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1))
322326 ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_USERTYPES + whereClause))
323327 : 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;
326334
327335 if (ksFuture != null)
328336 connection.write(ksFuture);
329337 if (udtFuture != null)
330338 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);
333343
334344 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);
336351 } catch (RuntimeException e) {
337352 // Failure to parse the schema is definitively wrong so log a full-on error, but this won't generally prevent queries to
338353 // 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 @@
451466 logger.error("No row found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress());
452467 return false;
453468 }
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) {
455473 logger.error("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress());
456474 return false;
457475 }
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +47 −17
@@ -71,29 +71,59 @@
7171 ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement);
7272 switch (scc.change) {
7373 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;
7884 }
7985 break;
8086 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;
90113 }
114+ this.setResult(rs);
91115 break;
92116 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;
97127 }
98128 break;
99129 default:
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +16 −4
@@ -60,10 +60,7 @@
6060 if (udtRows == null)
6161 return ksm;
6262
63- for (Row r : udtRows) {
64- UserType def = UserType.build(r);
65- ksm.userTypes.put(def.getTypeName(), def);
66- }
63+ ksm.addUserTypes(udtRows);
6764
6865 return ksm;
6966 }
@@ -107,6 +104,10 @@
107104 return tables.get(Metadata.handleId(name));
108105 }
109106
107+ void removeTable(String table) {
108+ tables.remove(table);
109+ }
110+
110111 /**
111112 * Returns the tables defined in this keyspace.
112113 *
@@ -138,6 +139,17 @@
138139 return Collections.<UserType>unmodifiableCollection(userTypes.values());
139140 }
140141
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+
141153 /**
142154 * Returns a {@code String} containing CQL queries representing this
143155 * 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 @@
4949 }
5050
5151 // 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) {
5353
5454 Map<String, List<Row>> cfDefs = new HashMap<String, List<Row>>();
5555 Map<String, List<Row>> udtDefs = new HashMap<String, List<Row>>();
5656 Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
5757
5858 // 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);
6568 }
66- l.add(row);
6769 }
6870
6971 // Gather udt defs
@@ -80,24 +82,26 @@
8082 }
8183
8284 // 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);
95101 }
96- ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion);
97- l.put(c.name, c);
98102 }
99103
100- if (table == null) {
104+ if (tableName == null && udtName == null) { // Refresh one or all keyspaces
101105 assert ks != null;
102106 Set<String> addedKs = new HashSet<String>();
103107 for (Row ksRow : ks) {
@@ -113,27 +117,39 @@
113117
114118 // If keyspace is null, it means we're rebuilding from scratch, so
115119 // remove anything that was not just added as it means it's a dropped keyspace
116- if (keyspace == null) {
120+ if (keyspaceName == null) {
117121 Iterator<String> iter = keyspaces.keySet().iterator();
118122 while (iter.hasNext()) {
119123 if (!addedKs.contains(iter.next()))
120124 iter.remove();
121125 }
122126 }
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);
126130
127131 // If we update a keyspace we don't know about, something went
128132 // wrong. Log an error an schedule a full schema rebuilt.
129133 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);
132148 return;
133149 }
134150
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));
137153 }
138154 }
139155
@@ -312,6 +328,11 @@
312328 return keyspaces.get(handleId(keyspace));
313329 }
314330
331+ void removeKeyspace(String keyspace) {
332+ keyspaces.remove(keyspace);
333+ tokenMap.tokenToHosts.remove(keyspace);
334+ }
335+
315336 /**
316337 * Returns a list of all the defined keyspaces.
317338 *
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java +54 −15
@@ -15,7 +15,8 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import java.net.InetAddress;
18+import java.io.PrintWriter;
19+import java.io.StringWriter;
1920 import java.net.InetSocketAddress;
2021 import java.util.HashMap;
2122 import java.util.Map;
@@ -37,10 +38,12 @@
3738
3839 private static final long serialVersionUID = 0;
3940
41+ private static final int MAX_ERRORS_IN_DEFAULT_MESSAGE = 3;
42+
4043 private final Map<InetSocketAddress, Throwable> errors;
4144
4245 public NoHostAvailableException(Map<InetSocketAddress, Throwable> errors) {
43- super(makeMessage(errors));
46+ super(makeMessage(errors, MAX_ERRORS_IN_DEFAULT_MESSAGE, false, false));
4447 this.errors = errors;
4548 }
4649
@@ -60,28 +63,64 @@
6063 return new HashMap<InetSocketAddress, Throwable>(errors);
6164 }
6265
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+
6382 @Override
6483 public DriverException copy() {
6584 return new NoHostAvailableException(getMessage(), this, errors);
6685 }
6786
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) {
7188 if (errors.size() == 0)
7289 return "All host(s) tried for query failed (no host was tried)";
7390
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;
82113 }
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);
84119 }
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();
86125 }
87126 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +4 −0
@@ -98,6 +98,10 @@
9898 * <p>
9999 * The default load balancing policy is {@link DCAwareRoundRobinPolicy} with token
100100 * 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.
101105 *
102106 * @return the default load balancing policy.
103107 */
modified driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java +11 −6
@@ -55,10 +55,15 @@
5555 /**
5656 * Creates a new {@code TokenAware} policy.
5757 *
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+ *
6267 */
6368 public TokenAwarePolicy(LoadBalancingPolicy childPolicy, boolean shuffleReplicas) {
6469 this.childPolicy = childPolicy;
@@ -66,7 +71,7 @@
6671 }
6772
6873 /**
69- * Creates a new {@code TokenAware} policy with no shuffling of replicas.
74+ * Creates a new {@code TokenAware} policy with shuffling of replicas.
7075 *
7176 * @param childPolicy the load balancing policy to wrap with token
7277 * awareness.
@@ -74,7 +79,7 @@
7479 * @see #TokenAwarePolicy(LoadBalancingPolicy, boolean)
7580 */
7681 public TokenAwarePolicy(LoadBalancingPolicy childPolicy) {
77- this(childPolicy, false);
82+ this(childPolicy, true);
7883 }
7984
8085 @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 @@
316316 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
317317 // the detection by forcing a request.
318318 if (waitForDead || waitForOut)
319- cluster.manager.submitSchemaRefresh(null, null);
319+ cluster.manager.submitSchemaRefresh(null, null, null);
320320
321321 InetAddress address;
322322 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