Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset08e9c06527316cfbaad332f0ac7e2eb81ddf7ad0b04b0c5005070ee47c61d792
Authorolim7t <omichallat+github@gmail.com> · 2014-12-20 20:06 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-12-20 20:06 +01:00
Parents0ffa4fe1cebc, 5ae6590a9129

Browse the files at this changeset

11 files changed

modified driver-core/CHANGELOG.rst +28 −0
@@ -18,6 +18,11 @@
1818 connections fails while bringing the node back up (JAVA-577)
1919 - [bug] Prevent faulty control connection from ignoring reconnecting hosts
2020 (JAVA-587)
21+- temporarily revert "Add idle timeout to the connection pool" (JAVA-419)
22+- [bug] Ensure updateCreatedPools does not add pools for suspected hosts
23+ (JAVA-593)
24+- [bug] Ensure state change notifications for a given host are handled serially
25+ (JAVA-594)
2126
2227
2328 2.1.3:
@@ -142,6 +147,28 @@
142147 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
143148
144149
150+2.0.9:
151+------
152+
153+- [improvement] Shade Netty dependency (JAVA-538)
154+- [improvement] Target schema refreshes more precisely (JAVA-543)
155+- [bug] Don't check rpc_address for control host (JAVA-546)
156+- [improvement] Improve message of NoHostAvailableException (JAVA-409)
157+- [bug] Rework connection reaper to avoid deadlock (JAVA-556)
158+- [bug] Avoid deadlock when multiple connections to the same host get write
159+ errors (JAVA-557)
160+- [improvement] Make shuffle=true the default for TokenAwarePolicy (JAVA-504)
161+- [bug] Fix bug when SUSPECT reconnection succeeds, but one of the pooled
162+ connections fails while bringing the node back up (JAVA-577)
163+- [bug] Prevent faulty control connection from ignoring reconnecting hosts
164+ (JAVA-587)
165+- temporarily revert "Add idle timeout to the connection pool" (JAVA-419)
166+- [bug] Ensure updateCreatedPools does not add pools for suspected hosts
167+ (JAVA-593)
168+- [bug] Ensure state change notifications for a given host are handled serially
169+ (JAVA-594)
170+
171+
145172 2.0.8:
146173 ------
147174
@@ -171,6 +198,7 @@
171198 - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504)
172199 - [improvement] Make schema agreement wait tuneable (JAVA-507)
173200 - [improvement] Document how to inject the driver metrics into another registry (JAVA-494)
201+- [improvement] Add idle timeout to the connection pool (JAVA-419)
174202 - [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516)
175203 - [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with
176204 an explicit but null or empty local datacenter (JAVA-451).
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +209 −166
@@ -26,7 +26,6 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.annotations.VisibleForTesting;
29-import com.google.common.base.Function;
3029 import com.google.common.base.Predicates;
3130 import com.google.common.collect.*;
3231 import com.google.common.util.concurrent.*;
@@ -75,6 +74,8 @@
7574
7675 private static final int DEFAULT_THREAD_KEEP_ALIVE = 30;
7776
77+ private static final int NOTIF_LOCK_TIMEOUT_SECONDS = 60;
78+
7879 final Manager manager;
7980
8081 /**
@@ -1411,83 +1412,94 @@
14111412 if (isClosed())
14121413 return;
14131414
1414- // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1415- if (host.state == Host.State.UP)
1416- return;
1417-
14181415 if (!connectionFactory.protocolVersion.isSupportedBy(host)) {
14191416 logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion);
14201417 return;
14211418 }
14221419
1423- // If there is a reconnection attempt scheduled for that node, cancel it
1424- Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1425- if (scheduledAttempt != null) {
1426- logger.debug("Cancelling reconnection attempt since node is UP");
1427- scheduledAttempt.cancel(false);
1420+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1421+ if (!locked) {
1422+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1423+ return;
14281424 }
1429-
14301425 try {
1431- prepareAllQueries(host);
1432- } catch (InterruptedException e) {
1433- Thread.currentThread().interrupt();
1434- // Don't propagate because we don't want to prevent other listener to run
1435- } catch (UnsupportedProtocolVersionException e) {
1436- logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1426+
1427+ // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1428+ if (host.state == Host.State.UP)
14371429 return;
1438- } catch (ClusterNameMismatchException e) {
1439- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1440- return;
1441- }
14421430
1443- // Session#onUp() expects the load balancing policy to have been updated first, so that
1444- // Host distances are up to date. This mean the policy could return the node before the
1445- // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1446- // will ignore the node, but we do want to make sure there is no prior pool so we don't
1447- // query from a pool we will shutdown right away.
1448- for (SessionManager s : sessions)
1449- s.removePool(host);
1450- loadBalancingPolicy().onUp(host);
1451- controlConnection.onUp(host);
1431+ // If there is a reconnection attempt scheduled for that node, cancel it
1432+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1433+ if (scheduledAttempt != null) {
1434+ logger.debug("Cancelling reconnection attempt since node is UP");
1435+ scheduledAttempt.cancel(false);
1436+ }
14521437
1453- logger.trace("Adding/renewing host pools for newly UP host {}", host);
1438+ try {
1439+ prepareAllQueries(host);
1440+ } catch (InterruptedException e) {
1441+ Thread.currentThread().interrupt();
1442+ // Don't propagate because we don't want to prevent other listener to run
1443+ } catch (UnsupportedProtocolVersionException e) {
1444+ logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1445+ return;
1446+ } catch (ClusterNameMismatchException e) {
1447+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1448+ return;
1449+ }
14541450
1455- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1456- for (SessionManager s : sessions)
1457- futures.add(s.forceRenewPool(host, poolCreationExecutor));
1458-
1459- // Only mark the node up once all session have re-added their pool (if the load-balancing
1460- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1461- // to the node.
1462- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1463- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1464- public void onSuccess(List<Boolean> poolCreationResults) {
1465- // If any of the creation failed, they will have signaled a connection failure
1466- // which will trigger a reconnection to the node. So don't bother marking UP.
1467- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1468- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1469- return;
1470- }
1451+ // Session#onUp() expects the load balancing policy to have been updated first, so that
1452+ // Host distances are up to date. This mean the policy could return the node before the
1453+ // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1454+ // will ignore the node, but we do want to make sure there is no prior pool so we don't
1455+ // query from a pool we will shutdown right away.
1456+ for (SessionManager s : sessions)
1457+ s.removePool(host);
1458+ loadBalancingPolicy().onUp(host);
1459+ controlConnection.onUp(host);
1460+
1461+ logger.trace("Adding/renewing host pools for newly UP host {}", host);
1462+
1463+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1464+ for (SessionManager s : sessions)
1465+ futures.add(s.forceRenewPool(host, poolCreationExecutor));
1466+
1467+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1468+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1469+ // to the node.
1470+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1471+ Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1472+ public void onSuccess(List<Boolean> poolCreationResults) {
1473+ // If any of the creation failed, they will have signaled a connection failure
1474+ // which will trigger a reconnection to the node. So don't bother marking UP.
1475+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1476+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1477+ return;
1478+ }
14711479
1472- host.setUp();
1480+ host.setUp();
14731481
1474- for (Host.StateListener listener : listeners)
1475- listener.onUp(host);
1476- }
1482+ for (Host.StateListener listener : listeners)
1483+ listener.onUp(host);
1484+ }
14771485
1478- public void onFailure(Throwable t) {
1479- // That future is not really supposed to throw unexpected exceptions
1480- if (!(t instanceof InterruptedException))
1481- logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1482- }
1483- });
1486+ public void onFailure(Throwable t) {
1487+ // That future is not really supposed to throw unexpected exceptions
1488+ if (!(t instanceof InterruptedException))
1489+ logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1490+ }
1491+ });
14841492
1485- f.get();
1493+ f.get();
14861494
1487- // Now, check if there isn't pools to create/remove following the addition.
1488- // We do that now only so that it's not called before we've set the node up.
1489- for (SessionManager s : sessions)
1490- s.updateCreatedPools(blockingExecutor);
1495+ // Now, check if there isn't pools to create/remove following the addition.
1496+ // We do that now only so that it's not called before we've set the node up.
1497+ for (SessionManager s : sessions)
1498+ s.updateCreatedPools(blockingExecutor);
1499+
1500+ } finally {
1501+ host.notificationsLock.unlock();
1502+ }
14911503 }
14921504
14931505 public ListenableFuture<?> triggerOnDown(final Host host) {
@@ -1529,7 +1541,7 @@
15291541 // the loadbalancing policy has been informed (otherwise those threads won't
15301542 // consider the host suspect but simply ignore it). So we synchronize.
15311543 synchronized (host) {
1532- // If we've already mark the node down/suspected, ignore this
1544+ // If we've already marked the node down/suspected, ignore this
15331545 if (!host.setSuspected() || host.reconnectionAttempt.get() != null)
15341546 return;
15351547
@@ -1575,52 +1587,62 @@
15751587 if (isClosed())
15761588 return;
15771589
1578- // If we're SUSPECT and not the task validating the suspicion, then some other task is
1579- // already checking to verify if the node is really down (or if it's simply that the
1580- // connections where broken). So just skip this in that case.
1581- if (!isSuspectedVerification && host.state == Host.State.SUSPECT) {
1582- logger.debug("Aborting onDown because a reconnection is running on SUSPECT host {}", host);
1583- return;
1584- }
1585-
1586- // Note: we don't want to skip that method if !host.isUp() because we set isUp
1587- // late in onUp, and so we can rely on isUp if there is an error during onUp.
1588- // But if there is a reconnection attempt in progress already, then we know
1589- // we've already gone through that method since the last successful onUp(), so
1590- // we're good skipping it.
1591- if (host.reconnectionAttempt.get() != null) {
1592- logger.debug("Aborting onDown because a reconnection is running on DOWN host {}", host);
1590+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1591+ if (!locked) {
1592+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring DOWN notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
15931593 return;
15941594 }
1595+ try {
15951596
1596- // Remember if we care about this node at all. We must call this before
1597- // we've signalled the load balancing policy, since most policy will always
1598- // IGNORE down nodes anyway.
1599- HostDistance distance = loadBalancingPolicy().distance(host);
1597+ // If we're SUSPECT and not the task validating the suspicion, then some other task is
1598+ // already checking to verify if the node is really down (or if it's simply that the
1599+ // connections where broken). So just skip this in that case.
1600+ if (!isSuspectedVerification && host.state == Host.State.SUSPECT) {
1601+ logger.debug("Aborting onDown because a reconnection is running on SUSPECT host {}", host);
1602+ return;
1603+ }
16001604
1601- boolean wasUp = host.isUp();
1602- host.setDown();
1605+ // Note: we don't want to skip that method if !host.isUp() because we set isUp
1606+ // late in onUp, and so we can rely on isUp if there is an error during onUp.
1607+ // But if there is a reconnection attempt in progress already, then we know
1608+ // we've already gone through that method since the last successful onUp(), so
1609+ // we're good skipping it.
1610+ if (host.reconnectionAttempt.get() != null) {
1611+ logger.debug("Aborting onDown because a reconnection is running on DOWN host {}", host);
1612+ return;
1613+ }
16031614
1604- loadBalancingPolicy().onDown(host);
1605- controlConnection.onDown(host);
1606- for (SessionManager s : sessions)
1607- s.onDown(host);
1608-
1609- // Contrarily to other actions of that method, there is no reason to notify listeners
1610- // unless the host was UP at the beginning of this function since even if a onUp fail
1611- // mid-method, listeners won't have been notified of the UP.
1612- if (wasUp) {
1613- for (Host.StateListener listener : listeners)
1614- listener.onDown(host);
1615- }
1615+ // Remember if we care about this node at all. We must call this before
1616+ // we've signalled the load balancing policy, since most policy will always
1617+ // IGNORE down nodes anyway.
1618+ HostDistance distance = loadBalancingPolicy().distance(host);
1619+
1620+ boolean wasUp = host.isUp();
1621+ host.setDown();
1622+
1623+ loadBalancingPolicy().onDown(host);
1624+ controlConnection.onDown(host);
1625+ for (SessionManager s : sessions)
1626+ s.onDown(host);
1627+
1628+ // Contrarily to other actions of that method, there is no reason to notify listeners
1629+ // unless the host was UP at the beginning of this function since even if a onUp fail
1630+ // mid-method, listeners won't have been notified of the UP.
1631+ if (wasUp) {
1632+ for (Host.StateListener listener : listeners)
1633+ listener.onDown(host);
1634+ }
16161635
1617- // Don't start a reconnection if we ignore the node anyway (JAVA-314)
1618- if (distance == HostDistance.IGNORED)
1619- return;
1636+ // Don't start a reconnection if we ignore the node anyway (JAVA-314)
1637+ if (distance == HostDistance.IGNORED)
1638+ return;
16201639
1621- // Note: we basically waste the first successful reconnection, but it's probably not a big deal
1622- logger.debug("{} is down, scheduling connection retries", host);
1623- startPeriodicReconnectionAttempt(host, isHostAddition);
1640+ // Note: we basically waste the first successful reconnection, but it's probably not a big deal
1641+ logger.debug("{} is down, scheduling connection retries", host);
1642+ startPeriodicReconnectionAttempt(host, isHostAddition);
1643+ } finally {
1644+ host.notificationsLock.unlock();
1645+ }
16241646 }
16251647
16261648 void startPeriodicReconnectionAttempt(final Host host, final boolean isHostAddition) {
@@ -1746,74 +1768,85 @@
17461768 return;
17471769 }
17481770
1749- // Adds to the load balancing first and foremost, as doing so might change the decision
1750- // it will make for distance() on that node (not likely but we leave that possibility).
1751- // This does mean the policy may start returning that node for query plan, but as long
1752- // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1753- loadBalancingPolicy().onAdd(host);
1754-
1755- // Next, if the host should be ignored, well, ignore it.
1756- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1757- // We still mark the node UP though as it should be (and notifiy the listeners).
1758- // We'll mark it down if we have a notification anyway and we've documented that especially
1759- // for IGNORED hosts, the isUp() method was a best effort guess
1760- host.setUp();
1761- for (Host.StateListener listener : listeners)
1762- listener.onAdd(host);
1771+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1772+ if (!locked) {
1773+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
17631774 return;
17641775 }
1765-
17661776 try {
1767- prepareAllQueries(host);
1768- } catch (InterruptedException e) {
1769- Thread.currentThread().interrupt();
1770- // Don't propagate because we don't want to prevent other listener to run
1771- } catch (UnsupportedProtocolVersionException e) {
1772- logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1773- return;
1774- } catch (ClusterNameMismatchException e) {
1775- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1776- return;
1777- }
1778-
1779- controlConnection.onAdd(host);
1780-
1781- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1782- for (SessionManager s : sessions)
1783- futures.add(s.maybeAddPool(host, blockingExecutor));
1784-
1785- // Only mark the node up once all session have added their pool (if the load-balancing
1786- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1787- // to the node.
1788- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1789- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1790- public void onSuccess(List<Boolean> poolCreationResults) {
1791- // If any of the creation failed, they will have signaled a connection failure
1792- // which will trigger a reconnection to the node. So don't bother marking UP.
1793- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1794- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1795- return;
1796- }
17971777
1778+ // Adds to the load balancing first and foremost, as doing so might change the decision
1779+ // it will make for distance() on that node (not likely but we leave that possibility).
1780+ // This does mean the policy may start returning that node for query plan, but as long
1781+ // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1782+ loadBalancingPolicy().onAdd(host);
1783+
1784+ // Next, if the host should be ignored, well, ignore it.
1785+ if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1786+ // We still mark the node UP though as it should be (and notifiy the listeners).
1787+ // We'll mark it down if we have a notification anyway and we've documented that especially
1788+ // for IGNORED hosts, the isUp() method was a best effort guess
17981789 host.setUp();
1799-
18001790 for (Host.StateListener listener : listeners)
18011791 listener.onAdd(host);
1792+ return;
18021793 }
18031794
1804- public void onFailure(Throwable t) {
1805- // That future is not really supposed to throw unexpected exceptions
1806- if (!(t instanceof InterruptedException))
1807- logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1795+ try {
1796+ prepareAllQueries(host);
1797+ } catch (InterruptedException e) {
1798+ Thread.currentThread().interrupt();
1799+ // Don't propagate because we don't want to prevent other listener to run
1800+ } catch (UnsupportedProtocolVersionException e) {
1801+ logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1802+ return;
1803+ } catch (ClusterNameMismatchException e) {
1804+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1805+ return;
18081806 }
1809- });
18101807
1811- f.get();
1808+ controlConnection.onAdd(host);
1809+
1810+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1811+ for (SessionManager s : sessions)
1812+ futures.add(s.maybeAddPool(host, blockingExecutor));
1813+
1814+ // Only mark the node up once all session have added their pool (if the load-balancing
1815+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1816+ // to the node.
1817+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1818+ Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1819+ public void onSuccess(List<Boolean> poolCreationResults) {
1820+ // If any of the creation failed, they will have signaled a connection failure
1821+ // which will trigger a reconnection to the node. So don't bother marking UP.
1822+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1823+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1824+ return;
1825+ }
18121826
1813- // Now, check if there isn't pools to create/remove following the addition.
1814- // We do that now only so that it's not called before we've set the node up.
1815- for (SessionManager s : sessions)
1816- s.updateCreatedPools(blockingExecutor);
1827+ host.setUp();
1828+
1829+ for (Host.StateListener listener : listeners)
1830+ listener.onAdd(host);
1831+ }
1832+
1833+ public void onFailure(Throwable t) {
1834+ // That future is not really supposed to throw unexpected exceptions
1835+ if (!(t instanceof InterruptedException))
1836+ logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1837+ }
1838+ });
1839+
1840+ f.get();
1841+
1842+ // Now, check if there isn't pools to create/remove following the addition.
1843+ // We do that now only so that it's not called before we've set the node up.
1844+ for (SessionManager s : sessions)
1845+ s.updateCreatedPools(blockingExecutor);
1846+
1847+ } finally {
1848+ host.notificationsLock.unlock();
1849+ }
18171850 }
18181851
18191852 public ListenableFuture<?> triggerOnRemove(final Host host) {
@@ -1830,16 +1863,26 @@
18301863 if (isClosed())
18311864 return;
18321865
1833- host.setDown();
1866+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1867+ if (!locked) {
1868+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring REMOVE notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1869+ return;
1870+ }
1871+ try {
1872+
1873+ host.setDown();
18341874
1835- logger.debug("Removing host {}", host);
1836- loadBalancingPolicy().onRemove(host);
1837- controlConnection.onRemove(host);
1838- for (SessionManager s : sessions)
1839- s.onRemove(host);
1875+ logger.debug("Removing host {}", host);
1876+ loadBalancingPolicy().onRemove(host);
1877+ controlConnection.onRemove(host);
1878+ for (SessionManager s : sessions)
1879+ s.onRemove(host);
18401880
1841- for (Host.StateListener listener : listeners)
1842- listener.onRemove(host);
1881+ for (Host.StateListener listener : listeners)
1882+ listener.onRemove(host);
1883+ } finally {
1884+ host.notificationsLock.unlock();
1885+ }
18431886 }
18441887
18451888 public boolean signalConnectionFailure(Host host, ConnectionException exception, boolean isHostAddition, boolean markSuspected) {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +46 −25
@@ -85,32 +85,49 @@
8585 this.dispatcher = new Dispatcher();
8686 this.name = name;
8787
88- ClientBootstrap bootstrap = factory.newBootstrap();
89- ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
90- ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED : factory.protocolVersion;
91- bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions()));
92-
93- ChannelFuture future = bootstrap.connect(address);
94-
95- writer.incrementAndGet();
9688 try {
97- // Wait until the connection attempt succeeds or fails.
98- this.channel = future.awaitUninterruptibly().getChannel();
99- this.factory.allChannels.add(this.channel);
100- if (!future.isSuccess())
101- {
102- if (logger.isDebugEnabled())
103- logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.getCause())));
104- throw defunct(new TransportException(address, "Cannot connect", future.getCause()));
89+ ClientBootstrap bootstrap = factory.newBootstrap();
90+ ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
91+ ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED : factory.protocolVersion;
92+ bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions()));
93+
94+ ChannelFuture future = bootstrap.connect(address);
95+
96+ writer.incrementAndGet();
97+ try {
98+ // Wait until the connection attempt succeeds or fails.
99+ this.channel = future.awaitUninterruptibly().getChannel();
100+ this.factory.allChannels.add(this.channel);
101+ if (!future.isSuccess()) {
102+ if (logger.isDebugEnabled())
103+ logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.getCause())));
104+ throw defunct(new TransportException(address, "Cannot connect", future.getCause()));
105+ }
106+ } finally {
107+ writer.decrementAndGet();
105108 }
106- } finally {
107- writer.decrementAndGet();
108- }
109109
110- logger.trace("{} Connection opened successfully", this);
111- initializeTransport(protocolVersion, factory.manager.metadata.clusterName);
112- logger.debug("{} Transport initialized and ready", this);
113- isInitialized = true;
110+ logger.trace("{} Connection opened successfully", this);
111+ initializeTransport(protocolVersion, factory.manager.metadata.clusterName);
112+ logger.debug("{} Transport initialized and ready", this);
113+ isInitialized = true;
114+
115+ } catch (ConnectionException e) {
116+ closeAsync().force();
117+ throw e;
118+ } catch (ClusterNameMismatchException e) {
119+ closeAsync().force();
120+ throw e;
121+ } catch (UnsupportedProtocolVersionException e) {
122+ closeAsync().force();
123+ throw e;
124+ } catch (InterruptedException e) {
125+ closeAsync().force();
126+ throw e;
127+ } catch (RuntimeException e) {
128+ closeAsync().force();
129+ throw e;
130+ }
114131 }
115132
116133 private static String extractMessage(Throwable t) {
@@ -265,6 +282,8 @@
265282 // sure the "suspected" mechanism work as expected
266283 Host host = factory.manager.metadata.getHost(address);
267284 if (host != null) {
285+ // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant.
286+ // This is not too much of a problem since calling onDown on a node that is already down has no effect.
268287 boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized);
269288 notifyOwnerWhenDefunct(isDown);
270289 }
@@ -752,9 +771,11 @@
752771 ChannelFuture future = channel.close();
753772 future.addListener(new ChannelFutureListener() {
754773 public void operationComplete(ChannelFuture future) {
755- if (future.getCause() != null)
774+ factory.allChannels.remove(channel);
775+ if (future.getCause() != null) {
776+ logger.warn("Error closing channel", future.getCause());
756777 ConnectionCloseFuture.this.setException(future.getCause());
757- else
778+ } else
758779 ConnectionCloseFuture.this.set(null);
759780 }
760781 });
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +13 −3
@@ -236,7 +236,8 @@
236236 return errors;
237237 }
238238
239- private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
239+ private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException
240+ {
240241 Connection connection = cluster.connectionFactory.open(host);
241242
242243 // If no protocol version was specified, set the default as soon as a connection succeeds (it's needed to parse UDTs in refreshSchema)
@@ -263,10 +264,19 @@
263264 refreshSchema(connection, null, null, null, cluster, isInitialConnection);
264265 return connection;
265266 } catch (BusyConnectionException e) {
266- connection.closeAsync().get();
267+ connection.closeAsync().force();
267268 throw new DriverInternalError("Newly created connection should not be busy");
269+ } catch (InterruptedException e) {
270+ connection.closeAsync().force();
271+ throw e;
272+ } catch (ConnectionException e) {
273+ connection.closeAsync().force();
274+ throw e;
275+ } catch (ExecutionException e) {
276+ connection.closeAsync().force();
277+ throw e;
268278 } catch (RuntimeException e) {
269- connection.closeAsync().get();
279+ connection.closeAsync().force();
270280 throw e;
271281 }
272282 }
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +17 −4
@@ -76,11 +76,17 @@
7676 Thread.currentThread().interrupt();
7777 // If asked to interrupt, we can skip opening core connections, the pool will still work.
7878 // But we ignore otherwise cause I'm not sure we can do much better currently.
79+ } catch (ConnectionException e) {
80+ forceClose(l);
81+ throw e;
82+ } catch (UnsupportedProtocolVersionException e) {
83+ forceClose(l);
84+ throw e;
85+ } catch (ClusterNameMismatchException e) {
86+ forceClose(l);
87+ throw e;
7988 } catch (RuntimeException e) {
80- // Rethrow but make sure to properly close the connections in our temporary list.
81- for (PooledConnection connection : l) {
82- connection.closeAsync().force();
83- }
89+ forceClose(l);
8490 throw e;
8591 }
8692 this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
@@ -89,6 +95,13 @@
8995 logger.trace("Created connection pool to host {}", host);
9096 }
9197
98+ // Clean up if we got an error at construction time but still created part of the core connections
99+ private void forceClose(List<PooledConnection> l) {
100+ for (PooledConnection connection : l) {
101+ connection.closeAsync().force();
102+ }
103+ }
104+
92105 private PoolingOptions options() {
93106 return manager.configuration().getPoolingOptions();
94107 }
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +3 −0
@@ -18,6 +18,7 @@
1818 import java.net.InetAddress;
1919 import java.net.InetSocketAddress;
2020 import java.util.concurrent.atomic.AtomicReference;
21+import java.util.concurrent.locks.ReentrantLock;
2122
2223 import com.google.common.collect.ImmutableList;
2324 import com.google.common.util.concurrent.Futures;
@@ -41,6 +42,8 @@
4142
4243 enum State { ADDED, DOWN, SUSPECT, UP }
4344 volatile State state;
45+ /** Ensures state change notifications for that host are handled serially */
46+ final ReentrantLock notificationsLock = new ReentrantLock(true);
4447
4548 private final ConvictionPolicy policy;
4649 private final Cluster.Manager manager;
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +2 −1
@@ -330,7 +330,8 @@
330330
331331 void removeKeyspace(String keyspace) {
332332 keyspaces.remove(keyspace);
333- tokenMap.tokenToHosts.remove(keyspace);
333+ if (tokenMap != null)
334+ tokenMap.tokenToHosts.remove(keyspace);
334335 }
335336
336337 /**
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +7 −5
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
1918 import java.net.InetSocketAddress;
2019 import java.nio.ByteBuffer;
2120 import java.util.*;
@@ -30,7 +29,6 @@
3029 import org.slf4j.LoggerFactory;
3130
3231
33-import com.datastax.driver.core.exceptions.AuthenticationException;
3432 import com.datastax.driver.core.exceptions.DriverInternalError;
3533 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3634 import com.datastax.driver.core.policies.LoadBalancingPolicy;
@@ -272,7 +270,11 @@
272270
273271 HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, SessionManager.this,
274272 cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
275- pools.put(host, newPool);
273+ previous = pools.put(host, newPool);
274+ if (previous != null && !previous.isClosed()) {
275+ logger.warn("Replacing a pool that wasn't closed. Closing it now, but this was not expected.");
276+ previous.closeAsync();
277+ }
276278
277279 // If we raced with a session shutdown, ensure that the pool will be closed.
278280 if (isClosing)
@@ -350,7 +352,7 @@
350352 HostConnectionPool pool = pools.get(h);
351353
352354 if (pool == null) {
353- if (dist != HostDistance.IGNORED && h.isUp())
355+ if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
354356 poolCreationFutures.add(maybeAddPool(h, executor));
355357 } else if (dist != pool.hostDistance) {
356358 if (dist == HostDistance.IGNORED) {
@@ -383,7 +385,7 @@
383385
384386 try {
385387 if (pool == null) {
386- if (dist != HostDistance.IGNORED && h.isUp())
388+ if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
387389 maybeAddPool(h, executor).get();
388390 } else if (dist != pool.hostDistance) {
389391 if (dist == HostDistance.IGNORED) {
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +1 −2
@@ -113,8 +113,7 @@
113113 * <li>the timeout settings used on the Cassandra side ({@code *_request_timeout_in_ms}
114114 * in {@code cassandra.yaml}) should be taken into account when picking a value for this
115115 * read timeout. In particular, if this read timeout option is lower than Cassandra's
116- * timeout, the driver will try another host before it has had the time to receive the
117- * Cassandra timeout. This might be counter-productive.</li>
116+ * timeout, <b>the driver might assume that the host is not responsive and mark it down.</b></li>
118117 * <li>the read timeout is only approximate and only control the timeout to one Cassandra
119118 * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
120119 * high level of precision on the timeout to a request is required, you should use
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +1 −1
@@ -373,7 +373,7 @@
373373 throw new AssertionError(e);
374374 } catch (TimeoutException e) {
375375 // Shouldn't really happen but isn't really a huge deal
376- logger.debug("Timeout while waiting only host initial reconnection future", e);
376+ logger.debug("Timeout while waiting on initial reconnection future for " + h, e);
377377 }
378378 }
379379
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +1 −1
@@ -63,7 +63,7 @@
6363 .hasState(State.UP)
6464 .isAtDistance(HostDistance.LOCAL);
6565 assertThat(cluster).host(3)
66- .hasState(State.UP)
66+ .comesUpWithin(120, SECONDS)
6767 .isAtDistance(HostDistance.IGNORED);
6868 assertThat(session).hasNoPoolFor(3);
6969