Elffuss BraidHub

kikocis/java-driver public

Allow hosts to remain partially up (JAVA-544).
Changesete866af248367c0bfd09a20fe52529c1af4ec0eb4fc21a9c9a9137c2e22b2a073
Authorolim7t <omichallat+github@gmail.com> · 2015-07-30 12:44 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-08-20 15:18 +02:00
Parentsa49b95c49f8d

Browse the files at this changeset

12 files changed

modified changelog/README.md +1 −0
@@ -38,6 +38,7 @@
3838 - [improvement] Debounce control connection queries (JAVA-657)
3939 - [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784)
4040 - [new feature] Make driver-side metadata optional (JAVA-828)
41+- [improvement] Allow hosts to remain partially up (JAVA-544)
4142
4243 Merged from 2.0.10_fixes branch:
4344
modified clirr-ignores.xml +17 −1
@@ -6,4 +6,20 @@
66 * check the reports in `<module>/target/site/clirr-report.html`
77 * add new differences if needed. Difference types are explained at http://www.mojohaus.org/clirr-maven-plugin/examples/ignored-differences.html
88 -->
9-<differences/>
No newline at the end of the file
9+<differences>
10+ <difference>
11+ <differenceType>1001</differenceType> <!-- decreased visibility -->
12+ <className>com/datastax/driver/core/ConvictionPolicy$Factory</className>
13+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
14+ </difference>
15+ <difference>
16+ <differenceType>8001</differenceType> <!-- class removed -->
17+ <className>com/datastax/driver/core/ConvictionPolicy$Simple</className>
18+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
19+ </difference>
20+ <difference>
21+ <differenceType>8001</differenceType> <!-- class removed -->
22+ <className>com/datastax/driver/core/ConvictionPolicy$Simple$Factory</className>
23+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
24+ </difference>
25+</differences>
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +7 −4
@@ -40,6 +40,7 @@
4040
4141 private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandler.class);
4242
43+ private final String name;
4344 private final ScheduledExecutorService executor;
4445 private final ReconnectionPolicy.ReconnectionSchedule schedule;
4546 /**
@@ -53,11 +54,12 @@
5354
5455 private final CountDownLatch ready = new CountDownLatch(1);
5556
56- public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt) {
57- this(executor, schedule, currentAttempt, -1);
57+ public AbstractReconnectionHandler(String name, ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt) {
58+ this(name, executor, schedule, currentAttempt, -1);
5859 }
5960
60- public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt, long initialDelayMs) {
61+ public AbstractReconnectionHandler(String name, ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt, long initialDelayMs) {
62+ this.name = name;
6163 this.executor = executor;
6264 this.schedule = schedule;
6365 this.currentAttempt = currentAttempt;
@@ -92,7 +94,7 @@
9294 break;
9395 }
9496 if (currentAttempt.compareAndSet(previous, handlerFuture)) {
95- logger.debug("Becoming the active handler");
97+ Host.statesLogger.debug("[{}] starting reconnection attempt", name);
9698 break;
9799 }
98100 }
@@ -176,6 +178,7 @@
176178 return;
177179 }
178180
181+ Host.statesLogger.debug("[{}] next reconnection attempt in {} ms", name, nextDelay);
179182 handlerFuture.nextTry = executor.schedule(this, nextDelay, TimeUnit.MILLISECONDS);
180183 }
181184
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +19 −17
@@ -1213,7 +1213,7 @@
12131213 Connection.Factory connectionFactory;
12141214 ControlConnection controlConnection;
12151215
1216- final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.Simple.Factory();
1216+ final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.DefaultConvictionPolicy.Factory();
12171217
12181218 ScheduledThreadPoolExecutor reconnectionExecutor;
12191219 ScheduledThreadPoolExecutor scheduledTasksExecutor;
@@ -1555,8 +1555,6 @@
15551555
15561556 // Use triggerOnUp unless you're sure you want to run this on the current thread.
15571557 private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
1558- logger.debug("Host {} is UP", host);
1559-
15601558 if (isClosed())
15611559 return;
15621560
@@ -1578,6 +1576,8 @@
15781576 if (host.state == Host.State.UP)
15791577 return;
15801578
1579+ Host.statesLogger.debug("[{}] marking host UP", host);
1580+
15811581 // If there is a reconnection attempt scheduled for that node, cancel it
15821582 Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
15831583 if (scheduledAttempt != null) {
@@ -1650,7 +1650,7 @@
16501650 }
16511651
16521652 } finally {
1653- if (reusedConnection != null && !reusedConnection.hasPool())
1653+ if (reusedConnection != null && !reusedConnection.hasOwner())
16541654 reusedConnection.closeAsync();
16551655 }
16561656 }
@@ -1670,8 +1670,6 @@
16701670
16711671 // Use triggerOnDown unless you're sure you want to run this on the current thread.
16721672 private void onDown(final Host host, final boolean isHostAddition, boolean startReconnection) throws InterruptedException, ExecutionException {
1673- logger.debug("Host {} is DOWN", host);
1674-
16751673 if (isClosed())
16761674 return;
16771675
@@ -1692,6 +1690,8 @@
16921690 return;
16931691 }
16941692
1693+ Host.statesLogger.debug("[{}] marking host DOWN", host);
1694+
16951695 // Remember if we care about this node at all. We must call this before
16961696 // we've signalled the load balancing policy, since most policy will always
16971697 // IGNORE down nodes anyway.
@@ -1717,7 +1717,6 @@
17171717 if (distance == HostDistance.IGNORED || !startReconnection)
17181718 return;
17191719
1720- logger.debug("{} is down, scheduling connection retries", host);
17211720 startPeriodicReconnectionAttempt(host, isHostAddition);
17221721 } finally {
17231722 host.notificationsLock.unlock();
@@ -1725,7 +1724,7 @@
17251724 }
17261725
17271726 void startPeriodicReconnectionAttempt(final Host host, final boolean isHostAddition) {
1728- new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) {
1727+ new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) {
17291728
17301729 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
17311730 return connectionFactory.open(host);
@@ -1778,7 +1777,7 @@
17781777 logger.debug("Scheduling one-time reconnection to {}", host);
17791778
17801779 // Setting an initial delay of 0 to start immediately, and all the exception handlers return false to prevent further attempts
1781- new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) {
1780+ new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) {
17821781
17831782 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
17841783 return connectionFactory.open(host);
@@ -1834,8 +1833,6 @@
18341833 if (isClosed())
18351834 return;
18361835
1837- logger.info("New Cassandra host {} added", host);
1838-
18391836 if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) {
18401837 logUnsupportedVersionProtocol(host);
18411838 return;
@@ -1849,6 +1846,7 @@
18491846 return;
18501847 }
18511848 try {
1849+ Host.statesLogger.debug("[{}] adding host", host);
18521850
18531851 // Adds to the load balancing first and foremost, as doing so might change the decision
18541852 // it will make for distance() on that node (not likely but we leave that possibility).
@@ -1921,7 +1919,7 @@
19211919 }
19221920
19231921 } finally {
1924- if (reusedConnection != null && !reusedConnection.hasPool())
1922+ if (reusedConnection != null && !reusedConnection.hasOwner())
19251923 reusedConnection.closeAsync();
19261924 }
19271925 }
@@ -1949,7 +1947,8 @@
19491947
19501948 host.setDown();
19511949
1952- logger.debug("Removing host {}", host);
1950+ Host.statesLogger.debug("[{}] removing host", host);
1951+
19531952 loadBalancingPolicy().onRemove(host);
19541953 controlConnection.onRemove(host);
19551954 for (SessionManager s : sessions)
@@ -1962,13 +1961,14 @@
19621961 }
19631962 }
19641963
1965- public boolean signalConnectionFailure(Host host, ConnectionException exception, boolean isHostAddition) {
1964+ public boolean signalConnectionFailure(Host host, ConnectionException exception,
1965+ boolean connectionInitialized, boolean isHostAddition) {
19661966 // Don't signal failure until we've fully initialized the controlConnection as this might mess up with
19671967 // the protocol detection
19681968 if (!isFullyInit || isClosed())
19691969 return true;
19701970
1971- boolean isDown = host.signalConnectionFailure(exception);
1971+ boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized);
19721972 if (isDown)
19731973 triggerOnDown(host, isHostAddition, true);
19741974 return isDown;
@@ -2175,6 +2175,7 @@
21752175 case TOPOLOGY_CHANGE:
21762176 ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event;
21772177 InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress());
2178+ Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change);
21782179 switch (tpc.change) {
21792180 case NEW_NODE:
21802181 submitNodeRefresh(tpAddr, HostEvent.ADDED);
@@ -2190,6 +2191,7 @@
21902191 case STATUS_CHANGE:
21912192 ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event;
21922193 InetSocketAddress stAddr = translateAddress(stc.node.getAddress());
2194+ Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status);
21932195 switch (stc.status) {
21942196 case UP:
21952197 submitNodeRefresh(stAddr, HostEvent.UP);
@@ -2256,7 +2258,7 @@
22562258 // reconnecting (thus letting the loadBalancingPolicy pick a better node)
22572259 Host ccHost = controlConnection.connectedHost();
22582260 if (ccHost == null || loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL)
2259- controlConnection.reconnect();
2261+ controlConnection.triggerReconnect();
22602262
22612263 for (SessionManager s : sessions)
22622264 s.updateCreatedPools();
@@ -2266,7 +2268,7 @@
22662268 // Deal with the control connection if it was using this host
22672269 Host ccHost = controlConnection.connectedHost();
22682270 if (ccHost == null || ccHost.equals(host) && loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL)
2269- controlConnection.reconnect();
2271+ controlConnection.triggerReconnect();
22702272
22712273 for (SessionManager s : sessions)
22722274 s.updateCreatedPools(host);
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +48 −34
@@ -85,11 +85,11 @@
8585 private volatile String keyspace;
8686
8787 private volatile boolean isInitialized;
88- private volatile boolean isDefunct;
88+ private final AtomicBoolean isDefunct = new AtomicBoolean();
8989
9090 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
9191
92- private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
92+ private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
9393
9494 /**
9595 /**
@@ -98,14 +98,14 @@
9898 * @param name the connection name
9999 * @param address the remote address
100100 * @param factory the connection factory to use
101- * @param pool the pool this connection belongs to. May be null if this connection does not belong to a pool.
102- * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}.
101+ * @param owner the component owning this connection (may be null).
102+ * Note that an existing connection can also be associated to an owner later with {@link #setOwner(Owner)}.
103103 */
104- protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
104+ protected Connection(String name, InetSocketAddress address, Factory factory, Owner owner) {
105105 this.address = address;
106106 this.factory = factory;
107107 this.name = name;
108- this.poolRef.set(pool);
108+ this.ownerRef.set(owner);
109109 }
110110
111111 /**
@@ -196,6 +196,9 @@
196196 Futures.addCallback(initFuture, new FutureCallback<Void>() {
197197 @Override
198198 public void onSuccess(Void result) {
199+ Host host = factory.manager.metadata.getHost(address);
200+ if(host != null)
201+ host.convictionPolicy.signalConnectionCreated();
199202 isInitialized = true;
200203 }
201204
@@ -373,7 +376,7 @@
373376 }
374377
375378 public boolean isDefunct() {
376- return isDefunct;
379+ return isDefunct.get();
377380 }
378381
379382 public int maxAvailableStreams() {
@@ -381,9 +384,13 @@
381384 }
382385
383386 <E extends Exception> E defunct(E e) {
384- if (logger.isDebugEnabled())
385- logger.debug("Defuncting connection to " + address, e);
386- isDefunct = true;
387+ if (!isDefunct.compareAndSet(false, true))
388+ return e;
389+
390+ if (Host.statesLogger.isTraceEnabled())
391+ Host.statesLogger.trace("Defuncting " + this, e);
392+ else if (Host.statesLogger.isDebugEnabled())
393+ Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
387394
388395 ConnectionException ce = e instanceof ConnectionException
389396 ? (ConnectionException)e
@@ -391,10 +398,12 @@
391398
392399 Host host = factory.manager.metadata.getHost(address);
393400 if (host != null) {
394- // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant.
395- // This is not too much of a problem since calling onDown on a node that is already down has no effect.
396- boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded());
397- notifyOwnerWhenDefunct(isDown);
401+ boolean isDown = factory.manager.signalConnectionFailure(host, ce, isInitialized, host.wasJustAdded());
402+
403+ if (!isDown)
404+ notifyOwnerWhenDefunct();
405+ // else the driver will destroy all pools and notify the control connection as part of marking the host down,
406+ // so no need to notify
398407 }
399408
400409 // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
@@ -405,20 +414,14 @@
405414 return e;
406415 }
407416
408- protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
417+ private void notifyOwnerWhenDefunct() {
409418 // If an error happens during initialization, the owner will detect it and take appropriate action
410419 if (!isInitialized)
411420 return;
412421
413- HostConnectionPool pool = this.poolRef.get();
414- if (pool == null)
415- return;
416-
417- if (hostIsDown) {
418- pool.closeAsync().force();
419- } else {
420- pool.replaceDefunctConnection(this);
421- }
422+ Owner owner = this.ownerRef.get();
423+ if (owner != null)
424+ owner.onConnectionDefunct(this);
422425 }
423426
424427 public String keyspace() {
@@ -505,7 +508,7 @@
505508 * having set the handler, we guarantee that even if we race with defunct/close, we may
506509 * never leave a handler that won't get an answer or be errored out.
507510 */
508- if (isDefunct) {
511+ if (isDefunct.get()) {
509512 dispatcher.removeHandler(handler, true);
510513 throw new ConnectionException(address, "Write attempt on defunct connection");
511514 }
@@ -567,13 +570,13 @@
567570 };
568571 }
569572
570- boolean hasPool() {
571- return this.poolRef.get() != null;
573+ boolean hasOwner() {
574+ return this.ownerRef.get() != null;
572575 }
573576
574- /** @return whether the connection was already associated with a pool */
575- boolean setPool(HostConnectionPool pool) {
576- return poolRef.compareAndSet(null, pool);
577+ /** @return whether the connection was already associated with an owner */
578+ boolean setOwner(Owner owner) {
579+ return ownerRef.compareAndSet(null, owner);
577580 }
578581
579582 /**
@@ -581,9 +584,9 @@
581584 * The connection should generally not be reused after that.
582585 */
583586 void release() {
584- HostConnectionPool pool = poolRef.get();
585- if (pool != null)
586- pool.returnConnection(this);
587+ Owner owner = ownerRef.get();
588+ if (owner instanceof HostConnectionPool)
589+ ((HostConnectionPool)owner).returnConnection(this);
587590 }
588591
589592 public boolean isClosed() {
@@ -611,6 +614,12 @@
611614
612615 logger.debug("{} closing connection", this);
613616
617+ if (isInitialized && !isDefunct.get()) {
618+ Host host = factory.manager.metadata.getHost(address);
619+ if(host != null)
620+ host.convictionPolicy.signalConnectionClosed();
621+ }
622+
614623 boolean terminated = tryTerminate(false);
615624 if (!terminated) {
616625 // The time by which all pending requests should have normally completed (use twice the read timeout for a generous
@@ -981,7 +990,7 @@
981990
982991 @Override
983992 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
984- if (evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
993+ if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
985994 logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
986995 write(HEARTBEAT_CALLBACK);
987996 }
@@ -1286,4 +1295,9 @@
12861295 nettyOptions.afterChannelInitialized(channel);
12871296 }
12881297 }
1298+
1299+ /** A component that "owns" a connection, and should be notified when it dies. */
1300+ interface Owner {
1301+ void onConnectionDefunct(Connection connection);
1302+ }
12891303 }
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +59 −63
@@ -31,13 +31,13 @@
3131 import com.datastax.driver.core.exceptions.DriverInternalError;
3232 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3333
34-class ControlConnection implements Host.StateListener {
34+class ControlConnection implements Host.StateListener, Connection.Owner {
3535
3636 private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class);
3737
3838 private static final InetAddress bindAllAddress;
39- static
40- {
39+
40+ static {
4141 try {
4242 bindAllAddress = InetAddress.getByAddress(new byte[4]);
4343 } catch (UnknownHostException e) {
@@ -68,7 +68,7 @@
6868 }
6969
7070 // Only for the initial connection. Does not schedule retries if it fails
71- public void connect() throws UnsupportedProtocolVersionException {
71+ void connect() throws UnsupportedProtocolVersionException {
7272 if (isShutdown)
7373 return;
7474
@@ -79,7 +79,7 @@
7979 setNewConnection(reconnectInternal(hosts.iterator(), true));
8080 }
8181
82- public CloseFuture closeAsync() {
82+ CloseFuture closeAsync() {
8383 // We don't have to be fancy here. We just set a flag so that we stop trying to reconnect (and thus change the
8484 // connection used) and shutdown the current one.
8585 isShutdown = true;
@@ -95,26 +95,13 @@
9595
9696 Host connectedHost() {
9797 Connection current = connectionRef.get();
98- return cluster.metadata.getHost(current.address);
98+ return (current == null)
99+ ? null
100+ : cluster.metadata.getHost(current.address);
99101 }
100102
101- void reconnect() {
102- if (isShutdown)
103- return;
104-
105- try {
106- setNewConnection(reconnectInternal(queryPlan(), false));
107- } catch (NoHostAvailableException e) {
108- logger.error("[Control connection] Cannot connect to any host, scheduling retry");
109- backgroundReconnect(-1);
110- } catch (UnsupportedProtocolVersionException e) {
111- // reconnectInternal only propagate those if we've not decided on the protocol version yet,
112- // which should only happen on the initial connection and thus in connect() but never here.
113- throw new AssertionError();
114- } catch (Exception e) {
115- logger.error("[Control connection] Unknown error during reconnection, scheduling retry", e);
116- backgroundReconnect(-1);
117- }
103+ void triggerReconnect() {
104+ backgroundReconnect(0);
118105 }
119106
120107 /**
@@ -124,7 +111,14 @@
124111 if (isShutdown)
125112 return;
126113
127- new AbstractReconnectionHandler(cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
114+ // Abort if a reconnection is already in progress. This is not thread-safe: two threads might race through this and both
115+ // schedule a reconnection; in that case AbstractReconnectionHandler knows how to deal with it correctly.
116+ // But this cheap check can help us avoid creating the object unnecessarily.
117+ ListenableFuture<?> reconnection = reconnectionAttempt.get();
118+ if (reconnection != null && !reconnection.isDone())
119+ return;
120+
121+ new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
128122 @Override
129123 protected Connection tryReconnect() throws ConnectionException {
130124 try {
@@ -163,17 +157,17 @@
163157
164158 private void signalError() {
165159 Connection connection = connectionRef.get();
166- if (connection != null && connection.isDefunct() && cluster.metadata.getHost(connection.address) != null) {
167- // If the connection was marked as defunct and the host hadn't left, this already reported the
168- // host down, which will trigger a reconnect.
169- return;
170- }
171- // If the connection is not defunct, or the host has left, just reconnect manually
160+ if (connection != null)
161+ connection.closeAsync();
162+
163+ // If the error caused the host to go down, onDown might have already triggered a reconnect.
164+ // But backgroundReconnect knows how to deal with that.
172165 backgroundReconnect(0);
173166 }
174167
175168 private void setNewConnection(Connection newConnection) {
176- logger.debug("[Control connection] Successfully connected to {}", newConnection.address);
169+ Host.statesLogger.debug("[Control connection] established to {}", newConnection.address);
170+ newConnection.setOwner(this);
177171 Connection old = connectionRef.getAndSet(newConnection);
178172 if (old != null && !old.isClosed())
179173 old.closeAsync();
@@ -187,6 +181,8 @@
187181 try {
188182 while (iter.hasNext()) {
189183 host = iter.next();
184+ if (!host.convictionPolicy.canReconnectNow())
185+ continue;
190186 try {
191187 return tryConnect(host, isInitialConnection);
192188 } catch (ConnectionException e) {
@@ -240,8 +236,7 @@
240236 return errors;
241237 }
242238
243- private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException
244- {
239+ private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
245240 Connection connection = cluster.connectionFactory.open(host);
246241
247242 try {
@@ -284,7 +279,7 @@
284279 }
285280 }
286281
287- public void refreshSchema(String keyspace, String table) throws InterruptedException {
282+ void refreshSchema(String keyspace, String table) throws InterruptedException {
288283 if(keyspace == null && table == null) {
289284 logger.debug("[Control connection] Refreshing schema");
290285 } else {
@@ -293,7 +288,7 @@
293288 try {
294289 Connection c = connectionRef.get();
295290 // At startup, when we add the initial nodes, this will be null, which is ok
296- if (c == null)
291+ if (c == null || c.isClosed())
297292 return;
298293 refreshSchema(c, keyspace, table, cluster);
299294 // If the table is null, we either rebuild all from scratch or have an updated keyspace. In both cases, rebuild the token map
@@ -325,8 +320,8 @@
325320 }
326321
327322 DefaultResultSetFuture ksFuture = table == null
328- ? new DefaultResultSetFuture(null, new Requests.Query(SELECT_KEYSPACES + whereClause))
329- : null;
323+ ? new DefaultResultSetFuture(null, new Requests.Query(SELECT_KEYSPACES + whereClause))
324+ : null;
330325 DefaultResultSetFuture cfFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause));
331326 DefaultResultSetFuture colsFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_COLUMNS + whereClause));
332327
@@ -343,7 +338,7 @@
343338 if (host == null || host.getCassandraVersion() == null) {
344339 cassandraVersion = cluster.protocolVersion() == 1 ? VersionNumber.parse("1.2.0") : VersionNumber.parse("2.0.0");
345340 logger.warn("Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. "
346- + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
341+ + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
347342 } else {
348343 cassandraVersion = host.getCassandraVersion();
349344 }
@@ -358,10 +353,10 @@
358353 }
359354 }
360355
361- public void refreshNodeListAndTokenMap() {
356+ void refreshNodeListAndTokenMap() {
362357 Connection c = connectionRef.get();
363358 // At startup, when we add the initial nodes, this will be null, which is ok
364- if (c == null)
359+ if (c == null || c.isClosed())
365360 return;
366361
367362 try {
@@ -427,11 +422,11 @@
427422 /**
428423 * @return whether we have enough information to bring the node back up
429424 */
430- public boolean refreshNodeInfo(Host host) {
425+ boolean refreshNodeInfo(Host host) {
431426
432427 Connection c = connectionRef.get();
433428 // At startup, when we add the initial nodes, this will be null, which is ok
434- if (c == null)
429+ if (c == null || c.isClosed())
435430 return true;
436431
437432 logger.debug("[Control connection] Refreshing node info on {}", host);
@@ -489,8 +484,8 @@
489484 String version = row.getString("release_version");
490485 // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field.
491486 InetAddress listenAddress = row.getColumnDefinitions().contains("peer")
492- ? row.getInet("peer")
493- : null;
487+ ? row.getInet("peer")
488+ : null;
494489
495490 host.setVersionAndListenAdress(version, listenAddress);
496491 }
@@ -661,18 +656,33 @@
661656
662657 @Override
663658 public void onDown(Host host) {
664- // If that's the host we're connected to, and we haven't yet schedule a reconnection, preemptively start one
659+ onHostGone(host);
660+ }
661+
662+ @Override
663+ public void onRemove(Host host) {
664+ onHostGone(host);
665+ cluster.submitNodeListRefresh();
666+ }
667+
668+ private void onHostGone(Host host) {
665669 Connection current = connectionRef.get();
666- if (logger.isDebugEnabled())
667- logger.debug("[Control connection] {} is down, currently connected to {}", host, current == null ? "nobody" : current.address);
668670
669671 if (current != null && current.address.equals(host.getSocketAddress())) {
670- // This starts an AbstractReconnectionHandler, which will take care of checking if another reconnection is
671- // already in progress
672+ logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect",
673+ current.address);
674+ if (!current.isClosed())
675+ current.closeAsync();
672676 backgroundReconnect(0);
673677 }
674678 }
675679
680+ @Override
681+ public void onConnectionDefunct(Connection connection) {
682+ if (connection == connectionRef.get())
683+ backgroundReconnect(0);
684+ }
685+
676686 @Override
677687 public void onSuspected(Host host) {
678688 }
@@ -685,18 +695,4 @@
685695 if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host))
686696 cluster.submitNodeListRefresh();
687697 }
688-
689- @Override
690- public void onRemove(Host host) {
691- Connection current = connectionRef.get();
692- if (logger.isDebugEnabled())
693- logger.debug("[Control connection] {} has been removed, currently connected to {}", host, current == null ? "nobody" : current.address);
694-
695- // Schedule a reconnection if that was our control host
696- if (current != null && current.address.equals(host.getSocketAddress())) {
697- backgroundReconnect(0);
698- }
699-
700- cluster.submitNodeListRefresh();
701- }
702698 }
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +95 −17
@@ -15,6 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.concurrent.atomic.AtomicInteger;
19+
20+import static java.util.concurrent.TimeUnit.MILLISECONDS;
21+import static java.util.concurrent.TimeUnit.NANOSECONDS;
22+
23+import com.datastax.driver.core.policies.ReconnectionPolicy;
24+
1825 /**
1926 * The policy with which to decide whether a host should be considered down.
2027 *
@@ -25,24 +32,36 @@
2532 */
2633 abstract class ConvictionPolicy {
2734
35+ /**
36+ * Called when a new connection to the host has been successfully opened.
37+ */
38+ abstract void signalConnectionCreated();
39+
40+ /**
41+ * Called when a connection closed normally.
42+ */
43+ abstract void signalConnectionClosed();
44+
2845 /**
2946 * Called when a connection error occurs on a connection to the host this policy applies to.
3047 *
3148 * @param exception the connection error that occurred.
32- *
33- * @return {@code true} if the host should be considered down.
49+ * @param connectionInitialized whether the connection was initialized.
50+ * @return whether the host should be considered down.
3451 */
35- public abstract boolean addFailure(ConnectionException exception);
52+ abstract boolean signalConnectionFailure(ConnectionException exception, boolean connectionInitialized);
53+
54+ abstract boolean canReconnectNow();
3655
3756 /**
38- * Called when the host has been detected up.
57+ * Called when the host goes down.
3958 */
40- public abstract void reset();
59+ abstract void reset();
4160
4261 /**
4362 * Simple factory interface to allow creating {@link ConvictionPolicy} instances.
4463 */
45- public interface Factory {
64+ interface Factory {
4665
4766 /**
4867 * Creates a new ConvictionPolicy instance for {@code host}.
@@ -50,30 +69,89 @@
5069 * @param host the host this policy applies to
5170 * @return the newly created {@link ConvictionPolicy} instance.
5271 */
53- public ConvictionPolicy create(Host host);
72+ ConvictionPolicy create(Host host, ReconnectionPolicy reconnectionPolicy);
5473 }
5574
56- public static class Simple extends ConvictionPolicy {
57- private Simple(Host host) {
75+ static class DefaultConvictionPolicy extends ConvictionPolicy {
76+ private final Host host;
77+ private final ReconnectionPolicy reconnectionPolicy;
78+ private final AtomicInteger openConnections = new AtomicInteger();
79+
80+ private volatile long nextReconnectionTime = Long.MIN_VALUE;
81+ private ReconnectionPolicy.ReconnectionSchedule reconnectionSchedule;
82+
83+ private DefaultConvictionPolicy(Host host, ReconnectionPolicy reconnectionPolicy) {
84+ this.host = host;
85+ this.reconnectionPolicy = reconnectionPolicy;
86+ }
87+
88+ @Override
89+ void signalConnectionCreated() {
90+ int newCount = openConnections.incrementAndGet();
91+ Host.statesLogger.debug("[{}] new connection created, total = {}", host, newCount);
92+ resetReconnectionTime();
93+ }
94+
95+ @Override
96+ void signalConnectionClosed() {
97+ if (host.state == Host.State.DOWN)
98+ return;
99+ int remaining = openConnections.decrementAndGet();
100+ assert remaining >= 0;
101+ Host.statesLogger.debug("[{}] connection closed, remaining = {}", host, remaining);
58102 }
59103
60104 @Override
61- public boolean addFailure(ConnectionException exception) {
62- return true;
105+ boolean signalConnectionFailure(ConnectionException exception, boolean wasFullyInitialized) {
106+ if (host.state == Host.State.DOWN)
107+ return false;
108+
109+ updateReconnectionTime();
110+ int remaining = (wasFullyInitialized)
111+ ? openConnections.decrementAndGet()
112+ : openConnections.get();
113+
114+ assert remaining >= 0;
115+ Host.statesLogger.debug("[{}] remaining connections = {}", host, remaining);
116+ return remaining == 0;
63117 }
64118
65- public boolean addFailureFromExternalDetector() {
66- return true;
119+ private synchronized void updateReconnectionTime() {
120+ long now = System.nanoTime();
121+ if (nextReconnectionTime > now)
122+ // Someone else updated the time before us
123+ return;
124+
125+ if (reconnectionSchedule == null)
126+ reconnectionSchedule = reconnectionPolicy.newSchedule();
127+
128+ long nextDelayMs = reconnectionSchedule.nextDelayMs();
129+ Host.statesLogger.debug("[{}] preventing new connections for the next {} ms", host, nextDelayMs);
130+ nextReconnectionTime = now + NANOSECONDS.convert(nextDelayMs, MILLISECONDS);
131+ }
132+
133+ private synchronized void resetReconnectionTime() {
134+ reconnectionSchedule = null;
135+ nextReconnectionTime = Long.MIN_VALUE;
67136 }
68137
69138 @Override
70- public void reset() {}
139+ boolean canReconnectNow() {
140+ return nextReconnectionTime == Long.MIN_VALUE ||
141+ System.nanoTime() >= nextReconnectionTime;
142+ }
143+
144+ @Override
145+ synchronized void reset() {
146+ openConnections.set(0);
147+ resetReconnectionTime();
148+ }
71149
72- public static class Factory implements ConvictionPolicy.Factory {
150+ static class Factory implements ConvictionPolicy.Factory {
73151
74152 @Override
75- public ConvictionPolicy create(Host host) {
76- return new Simple(host);
153+ public ConvictionPolicy create(Host host, ReconnectionPolicy reconnectionPolicy) {
154+ return new DefaultConvictionPolicy(host, reconnectionPolicy);
77155 }
78156 }
79157 }
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +7 −31
@@ -27,8 +27,6 @@
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
30-import com.datastax.driver.core.utils.MoreFutures;
31-
3230 /**
3331 * A Cassandra node.
3432 *
@@ -38,6 +36,7 @@
3836
3937 private static final Logger logger = LoggerFactory.getLogger(Host.class);
4038
39+ static final Logger statesLogger = LoggerFactory.getLogger(Host.class.getName() + ".STATES");
4140
4241 private final InetSocketAddress address;
4342
@@ -46,7 +45,7 @@
4645 /** Ensures state change notifications for that host are handled serially */
4746 final ReentrantLock notificationsLock = new ReentrantLock(true);
4847
49- private final ConvictionPolicy policy;
48+ final ConvictionPolicy convictionPolicy;
5049 private final Cluster.Manager manager;
5150
5251 // Tracks later reconnection attempts to that host so we avoid adding multiple tasks.
@@ -69,12 +68,12 @@
6968 // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely,
7069 // we rely on the fact that we can use Object equality as a valid equality), so don't use
7170 // that constructor but ClusterMetadata.getHost instead.
72- Host(InetSocketAddress address, ConvictionPolicy.Factory policy, Cluster.Manager manager) {
73- if (address == null || policy == null)
71+ Host(InetSocketAddress address, ConvictionPolicy.Factory convictionPolicyFactory, Cluster.Manager manager) {
72+ if (address == null || convictionPolicyFactory == null)
7473 throw new NullPointerException();
7574
7675 this.address = address;
77- this.policy = policy.create(this);
76+ this.convictionPolicy = convictionPolicyFactory.create(this, manager.reconnectionPolicy());
7877 this.manager = manager;
7978 this.defaultExecutionInfo = new ExecutionInfo(ImmutableList.of(this));
8079 this.state = State.ADDED;
@@ -276,17 +275,13 @@
276275
277276 void setDown() {
278277 state = State.DOWN;
278+ convictionPolicy.reset();
279279 }
280280
281281 void setUp() {
282- policy.reset();
283282 state = State.UP;
284283 }
285284
286- boolean signalConnectionFailure(ConnectionException exception) {
287- return policy.addFailure(exception);
288- }
289-
290285 /**
291286 * Interface for listeners that are interested in hosts added, up, down and
292287 * removed events.
@@ -314,26 +309,7 @@
314309 public void onUp(Host host);
315310
316311 /**
317- * Called when a node is suspected to be dead.
318- * <p>
319- * A node is suspected to be dead when an error occurs on one of it's
320- * opened connection. As soon as an host is suspected, a connection attempt
321- * to that host is immediately tried. If this succeed, then it means that
322- * the connection was disfunctional but that the node was not really down.
323- * If this fails however, this means the node is truly dead, onDown() is
324- * called and further reconnection attempts are scheduled according to the
325- * {@link ReconnectionPolicy} in place.
326- * <p>
327- * When this event is triggered, it is possible to call the host
328- * {@link getInitialReconnectionAttemptFuture} method to wait until the
329- * initial and immediate reconnection attempt succeed or fail.
330- * <p>
331- * Note that some StateListener may ignore that event. If a node that
332- * that is suspected down turns out to be truly down (that is, the driver
333- * cannot successfully connect to it right away), then {@link onDown} will
334- * be called.
335- *
336- * @deprecated the suspicion mechanism has been disabled. This will never
312+ * @deprecated the "suspicion" mechanism has been deprecated. This will never
337313 * get called.
338314 */
339315 @Deprecated
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +64 −39
@@ -17,6 +17,7 @@
1717
1818 import java.util.ArrayList;
1919 import java.util.List;
20+import java.util.ListIterator;
2021 import java.util.Set;
2122 import java.util.concurrent.*;
2223 import java.util.concurrent.atomic.AtomicInteger;
@@ -26,7 +27,10 @@
2627 import java.util.concurrent.locks.ReentrantLock;
2728
2829 import com.google.common.collect.Lists;
29-import com.google.common.util.concurrent.*;
30+import com.google.common.util.concurrent.Futures;
31+import com.google.common.util.concurrent.ListenableFuture;
32+import com.google.common.util.concurrent.MoreExecutors;
33+import com.google.common.util.concurrent.SettableFuture;
3034 import org.slf4j.Logger;
3135 import org.slf4j.LoggerFactory;
3236
@@ -38,7 +42,7 @@
3842 import static com.datastax.driver.core.Connection.State.RESURRECTING;
3943 import static com.datastax.driver.core.Connection.State.TRASHED;
4044
41-class HostConnectionPool {
45+class HostConnectionPool implements Connection.Owner {
4246
4347 private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class);
4448
@@ -99,14 +103,14 @@
99103 */
100104 public ListenableFuture<Void> initAsync(Connection reusedConnection) {
101105 // Create initial core connections
102- int capacity = options().getCoreConnectionsPerHost(hostDistance);
103- final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
104- final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
105- for (int i = 0; i < capacity; i++) {
106+ final int coreSize = options().getCoreConnectionsPerHost(hostDistance);
107+ final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize);
108+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(coreSize);
109+ for (int i = 0; i < coreSize; i++) {
106110 Connection connection;
107111 ListenableFuture<Void> connectionFuture;
108112 // reuse the existing connection only once
109- if (reusedConnection != null && reusedConnection.setPool(this)) {
113+ if (reusedConnection != null && reusedConnection.setOwner(this)) {
110114 connection = reusedConnection;
111115 connectionFuture = MoreFutures.VOID_SUCCESS;
112116 } else {
@@ -120,31 +124,33 @@
120124
121125 Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
122126
123- ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
127+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.successfulAsList(connectionFutures);
124128
125129 final SettableFuture<Void> initFuture = SettableFuture.create();
126- Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
130+ Futures.addCallback(allConnectionsFuture, new MoreFutures.SuccessCallback<List<Void>>() {
127131 @Override
128132 public void onSuccess(List<Void> l) {
133+ // Some of the connections might have failed, keep only the successful ones
134+ ListIterator<Connection> it = connections.listIterator();
135+ while (it.hasNext()) {
136+ if (it.next().isClosed())
137+ it.remove();
138+ }
139+
129140 HostConnectionPool.this.connections.addAll(connections);
130- open.set(l.size());
141+ open.set(connections.size());
142+
131143 if (isClosed()) {
132144 initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
133145 // we're not sure if closeAsync() saw the connections, so ensure they get closed
134146 forceClose(connections);
135147 } else {
136- logger.trace("Created connection pool to host {}", host);
148+ logger.debug("Created connection pool to host {} ({} connections needed, {} successfully opened)",
149+ host, coreSize, connections.size());
137150 phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
138151 initFuture.set(null);
139152 }
140153 }
141-
142- @Override
143- public void onFailure(Throwable t) {
144- phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
145- forceClose(connections);
146- initFuture.setException(t);
147- }
148154 }, initExecutor);
149155 return initFuture;
150156 }
@@ -168,16 +174,25 @@
168174 throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
169175
170176 if (connections.isEmpty()) {
171- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
172- // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
173- // protect against creating connection in excess of core too quickly
174- scheduledForCreation.incrementAndGet();
175- manager.blockingExecutor().submit(newConnectionTask);
177+ if (!host.convictionPolicy.canReconnectNow())
178+ throw new TimeoutException("Connection pool is empty, currently trying to reestablish connections");
179+ else {
180+ int coreSize = options().getCoreConnectionsPerHost(hostDistance);
181+ if (coreSize == 0) {
182+ maybeSpawnNewConnection();
183+ } else {
184+ for (int i = 0; i < coreSize; i++) {
185+ // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
186+ // protect against creating connection in excess of core too quickly
187+ scheduledForCreation.incrementAndGet();
188+ manager.blockingExecutor().submit(newConnectionTask);
189+ }
190+ }
191+ Connection c = waitForConnection(timeout, unit);
192+ totalInFlight.incrementAndGet();
193+ c.setKeyspace(manager.poolsState.keyspace);
194+ return c;
176195 }
177- Connection c = waitForConnection(timeout, unit);
178- totalInFlight.incrementAndGet();
179- c.setKeyspace(manager.poolsState.keyspace);
180- return c;
181196 }
182197
183198 int minInFlight = Integer.MAX_VALUE;
@@ -221,7 +236,9 @@
221236 }
222237
223238 int connectionCount = open.get() + scheduledForCreation.get();
224- if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
239+ if (connectionCount < options().getCoreConnectionsPerHost(hostDistance)) {
240+ maybeSpawnNewConnection();
241+ } else if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
225242 // Add a connection if we fill the first n-1 connections and almost fill the last one
226243 int currentCapacity = (connectionCount - 1) * StreamIdGenerator.MAX_STREAM_PER_CONNECTION
227244 + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance);
@@ -272,7 +289,7 @@
272289
273290 private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
274291 if (timeout == 0)
275- throw new TimeoutException();
292+ throw new TimeoutException("All connections are busy and pool timeout is 0");
276293
277294 long start = System.nanoTime();
278295 long remaining = timeout;
@@ -315,7 +332,7 @@
315332 remaining = timeout - Cluster.timeSince(start, unit);
316333 } while (remaining > 0);
317334
318- throw new TimeoutException();
335+ throw new TimeoutException("All connections are busy");
319336 }
320337
321338 public void returnConnection(Connection connection) {
@@ -400,6 +417,10 @@
400417 try {
401418 Connection newConnection = tryResurrectFromTrash();
402419 if (newConnection == null) {
420+ if (!host.convictionPolicy.canReconnectNow()) {
421+ open.decrementAndGet();
422+ return false;
423+ }
403424 logger.debug("Creating new connection on busy pool to {}", host);
404425 newConnection = manager.connectionFactory().open(this);
405426 }
@@ -464,6 +485,9 @@
464485 }
465486
466487 private void maybeSpawnNewConnection() {
488+ if (!host.convictionPolicy.canReconnectNow())
489+ return;
490+
467491 while (true) {
468492 int inCreation = scheduledForCreation.get();
469493 if (inCreation >= MAX_SIMULTANEOUS_CREATION)
@@ -475,17 +499,15 @@
475499 manager.blockingExecutor().submit(newConnectionTask);
476500 }
477501
478- void replaceDefunctConnection(final Connection connection) {
502+ @Override
503+ public void onConnectionDefunct(final Connection connection) {
479504 if (connection.state.compareAndSet(OPEN, GONE))
480505 open.decrementAndGet();
481- if (connections.remove(connection))
482- manager.blockingExecutor().submit(new Runnable() {
483- @Override
484- public void run() {
485- addConnectionIfUnderMaximum();
486- }
487- });
488- connection.closeAsync();
506+ connections.remove(connection);
507+
508+ // Don't try to replace the connection now. Connection.defunct already signaled the failure,
509+ // and either the host will be marked DOWN (which destroys all pools), or we want to prevent
510+ // new connections for some time
489511 }
490512
491513 void cleanupIdleConnections(long now) {
@@ -603,6 +625,9 @@
603625 if (isClosed())
604626 return;
605627
628+ if (!host.convictionPolicy.canReconnectNow())
629+ return;
630+
606631 // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create
607632 // more connection than maximum (and if we create more than core connection due to a race but this isn't
608633 // justified by the load, the connection in excess will be quickly trashed anyway)
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +1 −1
@@ -313,7 +313,7 @@
313313 return false;
314314 } catch (TimeoutException e) {
315315 // We timeout, log it but move to the next node.
316- logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)"));
316+ logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)", e));
317317 return false;
318318 } catch (RuntimeException e) {
319319 if (connection != null)
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +2 −2
@@ -52,7 +52,7 @@
5252 schedule = new MockReconnectionSchedule();
5353 work = new MockReconnectionWork();
5454 future.set(null);
55- handler = new AbstractReconnectionHandler(executor, schedule, future) {
55+ handler = new AbstractReconnectionHandler("test", executor, schedule, future) {
5656 @Override
5757 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
5858 return work.tryReconnect();
@@ -330,7 +330,7 @@
330330 private void waitForCompletion() {
331331 executor.shutdown();
332332 try {
333- boolean shutdown = executor.awaitTermination(10, TimeUnit.SECONDS);
333+ boolean shutdown = executor.awaitTermination(30, TimeUnit.SECONDS);
334334 if (!shutdown)
335335 fail("executor ran for longer than expected");
336336 } catch (InterruptedException e) {
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +11 −6
@@ -25,8 +25,13 @@
2525
2626 import com.google.common.collect.ImmutableList;
2727 import com.google.common.collect.ImmutableList.Builder;
28+import org.mockito.Mockito;
29+
30+import static org.mockito.Mockito.mock;
2831 import static org.testng.Assert.*;
2932
33+import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
34+
3035 /**
3136 * Base class for replication strategy tests. Currently only supports testing
3237 * using the default Murmur3Partitioner.
@@ -38,13 +43,13 @@
3843 protected static class HostMock extends Host {
3944 private final String address;
4045
41- private HostMock(String address) throws UnknownHostException {
42- super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory(), null);
46+ private HostMock(String address, Cluster.Manager manager) throws UnknownHostException {
47+ super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager);
4348 this.address = address;
4449 }
4550
46- private HostMock(String address, String dc, String rack) throws UnknownHostException {
47- this(address);
51+ private HostMock(String address, String dc, String rack, Cluster.Manager manager) throws UnknownHostException {
52+ this(address, manager);
4853 this.setLocationInfo(dc, rack);
4954 }
5055
@@ -81,7 +86,7 @@
8186 */
8287 protected static HostMock host(String address) {
8388 try {
84- return new HostMock(address);
89+ return new HostMock(address, mock(Cluster.Manager.class));
8590 } catch (UnknownHostException ex) {
8691 throw new RuntimeException(ex); //wrap to avoid declarations
8792 }
@@ -93,7 +98,7 @@
9398 */
9499 protected static HostMock host(String address, String dc, String rack) {
95100 try {
96- return new HostMock(address, dc, rack);
101+ return new HostMock(address, dc, rack, mock(Cluster.Manager.class));
97102 } catch (UnknownHostException ex) {
98103 throw new RuntimeException(ex); //wrap to avoid declarations
99104 }