kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 0af82488f2070915f2d3b7b869d6be04237a6d4aace81d0f74830e6acc99bd99 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-04-17 22:49 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-04-17 22:49 +02:00 |
| Parents | a5bd5b316c2f, e646d782bb18 |
25 files changed
modified driver-core/CHANGELOG.rst +2 −0
| @@ -38,6 +38,8 @@ | ||
| 38 | 38 | (JAVA-619) |
| 39 | 39 | - [new feature] Expose an API to check for schema agreement after a |
| 40 | 40 | schema-altering statement (JAVA-669) |
| 41 | +- [improvement] Make connection and pool creation fully async (JAVA-692) | |
| 42 | +- [improvement] Optimize connection use after reconnection (JAVA-505) | |
| 41 | 43 | |
| 42 | 44 | Merged from 2.0.9_fixes branch: |
| 43 | 45 |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +3 −3
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | import java.util.concurrent.ExecutionException; |
| 22 | 22 | import java.util.concurrent.LinkedBlockingDeque; |
| 23 | 23 | |
| 24 | -import com.google.common.util.concurrent.Futures; | |
| 25 | 24 | import com.google.common.util.concurrent.ListenableFuture; |
| 26 | 25 | import com.google.common.util.concurrent.SettableFuture; |
| 27 | 26 | import com.google.common.util.concurrent.Uninterruptibles; |
| @@ -29,6 +28,7 @@ | ||
| 29 | 28 | import org.slf4j.LoggerFactory; |
| 30 | 29 | |
| 31 | 30 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 31 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 32 | 32 | |
| 33 | 33 | /** |
| 34 | 34 | * Default implementation of a result set, backed by an ArrayDeque of ArrayList. |
| @@ -178,7 +178,7 @@ | ||
| 178 | 178 | } |
| 179 | 179 | |
| 180 | 180 | public ListenableFuture<Void> fetchMoreResults() { |
| 181 | - return Futures.immediateFuture(null); | |
| 181 | + return MoreFutures.VOID_SUCCESS; | |
| 182 | 182 | } |
| 183 | 183 | |
| 184 | 184 | public ExecutionInfo getExecutionInfo() { |
| @@ -287,7 +287,7 @@ | ||
| 287 | 287 | |
| 288 | 288 | private ListenableFuture<Void> fetchMoreResults(FetchingState fetchState) { |
| 289 | 289 | if (fetchState == null) |
| 290 | - return Futures.immediateFuture(null); | |
| 290 | + return MoreFutures.VOID_SUCCESS; | |
| 291 | 291 | |
| 292 | 292 | if (fetchState.inProgress != null) |
| 293 | 293 | return fetchState.inProgress; |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +194 −185
| @@ -1404,21 +1404,13 @@ | ||
| 1404 | 1404 | return executor.submit(new ExceptionCatchingRunnable() { |
| 1405 | 1405 | @Override |
| 1406 | 1406 | public void runMayThrow() throws InterruptedException, ExecutionException { |
| 1407 | - onUp(host); | |
| 1407 | + onUp(host, null); | |
| 1408 | 1408 | } |
| 1409 | 1409 | }); |
| 1410 | 1410 | } |
| 1411 | 1411 | |
| 1412 | - private void onUp(final Host host) throws InterruptedException, ExecutionException { | |
| 1413 | - // Note that in generalize we can parallelize the pool creation on | |
| 1414 | - // each session, but we shouldn't use executor since we're already | |
| 1415 | - // running on it most probably (and so we could deadlock). Use the | |
| 1416 | - // blockingExecutor instead, that's why it's for. | |
| 1417 | - onUp(host, blockingExecutor); | |
| 1418 | - } | |
| 1419 | - | |
| 1420 | 1412 | // Use triggerOnUp unless you're sure you want to run this on the current thread. |
| 1421 | - private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException { | |
| 1413 | + private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { | |
| 1422 | 1414 | logger.debug("Host {} is UP", host); |
| 1423 | 1415 | |
| 1424 | 1416 | if (isClosed()) |
| @@ -1429,59 +1421,61 @@ | ||
| 1429 | 1421 | return; |
| 1430 | 1422 | } |
| 1431 | 1423 | |
| 1432 | - boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); | |
| 1433 | - if (!locked) { | |
| 1434 | - logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); | |
| 1435 | - return; | |
| 1436 | - } | |
| 1437 | 1424 | try { |
| 1438 | 1425 | |
| 1439 | - // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts | |
| 1440 | - if (host.state == Host.State.UP) | |
| 1426 | + boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); | |
| 1427 | + if (!locked) { | |
| 1428 | + logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); | |
| 1441 | 1429 | return; |
| 1442 | - | |
| 1443 | - // If there is a reconnection attempt scheduled for that node, cancel it | |
| 1444 | - Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null); | |
| 1445 | - if (scheduledAttempt != null) { | |
| 1446 | - logger.debug("Cancelling reconnection attempt since node is UP"); | |
| 1447 | - scheduledAttempt.cancel(false); | |
| 1448 | 1430 | } |
| 1449 | - | |
| 1450 | 1431 | try { |
| 1451 | - prepareAllQueries(host); | |
| 1452 | - } catch (InterruptedException e) { | |
| 1453 | - Thread.currentThread().interrupt(); | |
| 1454 | - // Don't propagate because we don't want to prevent other listener to run | |
| 1455 | - } catch (UnsupportedProtocolVersionException e) { | |
| 1456 | - logUnsupportedVersionProtocol(host); | |
| 1457 | - return; | |
| 1458 | - } catch (ClusterNameMismatchException e) { | |
| 1459 | - logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 1460 | - return; | |
| 1461 | - } | |
| 1462 | 1432 | |
| 1463 | - // Session#onUp() expects the load balancing policy to have been updated first, so that | |
| 1464 | - // Host distances are up to date. This mean the policy could return the node before the | |
| 1465 | - // new pool have been created. This is harmless if there is no prior pool since RequestHandler | |
| 1466 | - // will ignore the node, but we do want to make sure there is no prior pool so we don't | |
| 1467 | - // query from a pool we will shutdown right away. | |
| 1468 | - for (SessionManager s : sessions) | |
| 1469 | - s.removePool(host); | |
| 1470 | - loadBalancingPolicy().onUp(host); | |
| 1471 | - controlConnection.onUp(host); | |
| 1433 | + // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts | |
| 1434 | + if (host.state == Host.State.UP) | |
| 1435 | + return; | |
| 1436 | + | |
| 1437 | + // If there is a reconnection attempt scheduled for that node, cancel it | |
| 1438 | + Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null); | |
| 1439 | + if (scheduledAttempt != null) { | |
| 1440 | + logger.debug("Cancelling reconnection attempt since node is UP"); | |
| 1441 | + scheduledAttempt.cancel(false); | |
| 1442 | + } | |
| 1472 | 1443 | |
| 1473 | - logger.trace("Adding/renewing host pools for newly UP host {}", host); | |
| 1444 | + try { | |
| 1445 | + reusedConnection = prepareAllQueries(host, reusedConnection); | |
| 1446 | + } catch (InterruptedException e) { | |
| 1447 | + Thread.currentThread().interrupt(); | |
| 1448 | + // Don't propagate because we don't want to prevent other listener to run | |
| 1449 | + } catch (UnsupportedProtocolVersionException e) { | |
| 1450 | + logUnsupportedVersionProtocol(host); | |
| 1451 | + return; | |
| 1452 | + } catch (ClusterNameMismatchException e) { | |
| 1453 | + logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 1454 | + return; | |
| 1455 | + } | |
| 1456 | + | |
| 1457 | + // Session#onUp() expects the load balancing policy to have been updated first, so that | |
| 1458 | + // Host distances are up to date. This mean the policy could return the node before the | |
| 1459 | + // new pool have been created. This is harmless if there is no prior pool since RequestHandler | |
| 1460 | + // will ignore the node, but we do want to make sure there is no prior pool so we don't | |
| 1461 | + // query from a pool we will shutdown right away. | |
| 1462 | + for (SessionManager s : sessions) | |
| 1463 | + s.removePool(host); | |
| 1464 | + loadBalancingPolicy().onUp(host); | |
| 1465 | + controlConnection.onUp(host); | |
| 1466 | + | |
| 1467 | + logger.trace("Adding/renewing host pools for newly UP host {}", host); | |
| 1468 | + | |
| 1469 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1470 | + for (SessionManager s : sessions) | |
| 1471 | + futures.add(s.forceRenewPool(host, reusedConnection)); | |
| 1472 | + | |
| 1473 | + try { | |
| 1474 | + // Only mark the node up once all session have re-added their pool (if the load-balancing | |
| 1475 | + // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1476 | + // to the node. | |
| 1477 | + List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); | |
| 1474 | 1478 | |
| 1475 | - List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size()); | |
| 1476 | - for (SessionManager s : sessions) | |
| 1477 | - futures.add(s.forceRenewPool(host, poolCreationExecutor)); | |
| 1478 | - | |
| 1479 | - // Only mark the node up once all session have re-added their pool (if the load-balancing | |
| 1480 | - // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1481 | - // to the node. | |
| 1482 | - ListenableFuture<List<Boolean>> f = Futures.allAsList(futures); | |
| 1483 | - Futures.addCallback(f, new FutureCallback<List<Boolean>>() { | |
| 1484 | - public void onSuccess(List<Boolean> poolCreationResults) { | |
| 1485 | 1479 | // If any of the creation failed, they will have signaled a connection failure |
| 1486 | 1480 | // which will trigger a reconnection to the node. So don't bother marking UP. |
| 1487 | 1481 | if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { |
| @@ -1493,24 +1487,26 @@ | ||
| 1493 | 1487 | |
| 1494 | 1488 | for (Host.StateListener listener : listeners) |
| 1495 | 1489 | listener.onUp(host); |
| 1496 | - } | |
| 1497 | 1490 | |
| 1498 | - public void onFailure(Throwable t) { | |
| 1491 | + } catch (ExecutionException e) { | |
| 1492 | + Throwable t = e.getCause(); | |
| 1499 | 1493 | // That future is not really supposed to throw unexpected exceptions |
| 1500 | 1494 | if (!(t instanceof InterruptedException)) |
| 1501 | 1495 | logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t); |
| 1502 | 1496 | } |
| 1503 | - }); | |
| 1504 | 1497 | |
| 1505 | - f.get(); | |
| 1498 | + // Now, check if there isn't pools to create/remove following the addition. | |
| 1499 | + // We do that now only so that it's not called before we've set the node up. | |
| 1500 | + for (SessionManager s : sessions) | |
| 1501 | + s.updateCreatedPools(); | |
| 1506 | 1502 | |
| 1507 | - // Now, check if there isn't pools to create/remove following the addition. | |
| 1508 | - // We do that now only so that it's not called before we've set the node up. | |
| 1509 | - for (SessionManager s : sessions) | |
| 1510 | - s.updateCreatedPools(blockingExecutor); | |
| 1503 | + } finally { | |
| 1504 | + host.notificationsLock.unlock(); | |
| 1505 | + } | |
| 1511 | 1506 | |
| 1512 | 1507 | } finally { |
| 1513 | - host.notificationsLock.unlock(); | |
| 1508 | + if (reusedConnection != null && !reusedConnection.hasPool()) | |
| 1509 | + reusedConnection.closeAsync(); | |
| 1514 | 1510 | } |
| 1515 | 1511 | } |
| 1516 | 1512 | |
| @@ -1563,11 +1559,10 @@ | ||
| 1563 | 1559 | public void runMayThrow() throws InterruptedException, ExecutionException { |
| 1564 | 1560 | boolean success; |
| 1565 | 1561 | try { |
| 1566 | - // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection | |
| 1567 | - connectionFactory.open(host).closeAsync(); | |
| 1562 | + Connection connection = connectionFactory.open(host); | |
| 1568 | 1563 | // Note that we want to do the pool creation on this thread because we want that |
| 1569 | 1564 | // when onUp return, the host is ready for querying |
| 1570 | - onUp(host, MoreExecutors.sameThreadExecutor()); | |
| 1565 | + onUp(host, connection); | |
| 1571 | 1566 | // If one of the connections in onUp failed, it signaled the error and triggerd onDown, |
| 1572 | 1567 | // but onDown aborted because this reconnection attempt was in progress (JAVA-577). |
| 1573 | 1568 | // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was |
| @@ -1649,7 +1644,6 @@ | ||
| 1649 | 1644 | if (distance == HostDistance.IGNORED || !startReconnection) |
| 1650 | 1645 | return; |
| 1651 | 1646 | |
| 1652 | - // Note: we basically waste the first successful reconnection, but it's probably not a big deal | |
| 1653 | 1647 | logger.debug("{} is down, scheduling connection retries", host); |
| 1654 | 1648 | startPeriodicReconnectionAttempt(host, isHostAddition); |
| 1655 | 1649 | } finally { |
| @@ -1665,19 +1659,15 @@ | ||
| 1665 | 1659 | } |
| 1666 | 1660 | |
| 1667 | 1661 | protected void onReconnection(Connection connection) { |
| 1668 | - // We don't use that first connection so close it. | |
| 1669 | - // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so | |
| 1670 | - // we use it for the first HostConnectionPool created | |
| 1671 | - connection.closeAsync(); | |
| 1672 | 1662 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 1673 | 1663 | // catch that an upgraded node uses a new cassandra version). |
| 1674 | 1664 | if (controlConnection.refreshNodeInfo(host)) { |
| 1675 | 1665 | logger.debug("Successful reconnection to {}, setting host UP", host); |
| 1676 | 1666 | try { |
| 1677 | 1667 | if (isHostAddition) |
| 1678 | - onAdd(host); | |
| 1668 | + onAdd(host, connection); | |
| 1679 | 1669 | else |
| 1680 | - onUp(host); | |
| 1670 | + onUp(host, connection); | |
| 1681 | 1671 | } catch (InterruptedException e) { |
| 1682 | 1672 | Thread.currentThread().interrupt(); |
| 1683 | 1673 | } catch (Exception e) { |
| @@ -1685,6 +1675,7 @@ | ||
| 1685 | 1675 | } |
| 1686 | 1676 | } else { |
| 1687 | 1677 | logger.debug("Not enough info for {}, ignoring host", host); |
| 1678 | + connection.closeAsync(); | |
| 1688 | 1679 | } |
| 1689 | 1680 | } |
| 1690 | 1681 | |
| @@ -1721,16 +1712,12 @@ | ||
| 1721 | 1712 | } |
| 1722 | 1713 | |
| 1723 | 1714 | protected void onReconnection(Connection connection) { |
| 1724 | - // We don't use that first connection so close it. | |
| 1725 | - // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so | |
| 1726 | - // we use it for the first HostConnectionPool created | |
| 1727 | - connection.closeAsync(); | |
| 1728 | 1715 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 1729 | 1716 | // catch that an upgraded node uses a new cassandra version). |
| 1730 | 1717 | if (controlConnection.refreshNodeInfo(host)) { |
| 1731 | 1718 | logger.debug("Successful reconnection to {}, setting host UP", host); |
| 1732 | 1719 | try { |
| 1733 | - onUp(host); | |
| 1720 | + onUp(host, connection); | |
| 1734 | 1721 | } catch (InterruptedException e) { |
| 1735 | 1722 | Thread.currentThread().interrupt(); |
| 1736 | 1723 | } catch (Exception e) { |
| @@ -1738,6 +1725,7 @@ | ||
| 1738 | 1725 | } |
| 1739 | 1726 | } else { |
| 1740 | 1727 | logger.debug("Not enough info for {}, ignoring host", host); |
| 1728 | + connection.closeAsync(); | |
| 1741 | 1729 | } |
| 1742 | 1730 | } |
| 1743 | 1731 | |
| @@ -1763,13 +1751,13 @@ | ||
| 1763 | 1751 | return executor.submit(new ExceptionCatchingRunnable() { |
| 1764 | 1752 | @Override |
| 1765 | 1753 | public void runMayThrow() throws InterruptedException, ExecutionException { |
| 1766 | - onAdd(host); | |
| 1754 | + onAdd(host, null); | |
| 1767 | 1755 | } |
| 1768 | 1756 | }); |
| 1769 | 1757 | } |
| 1770 | 1758 | |
| 1771 | 1759 | // Use triggerOnAdd unless you're sure you want to run this on the current thread. |
| 1772 | - private void onAdd(final Host host) throws InterruptedException, ExecutionException { | |
| 1760 | + private void onAdd(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { | |
| 1773 | 1761 | if (isClosed()) |
| 1774 | 1762 | return; |
| 1775 | 1763 | |
| @@ -1780,55 +1768,57 @@ | ||
| 1780 | 1768 | return; |
| 1781 | 1769 | } |
| 1782 | 1770 | |
| 1783 | - boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); | |
| 1784 | - if (!locked) { | |
| 1785 | - logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); | |
| 1786 | - return; | |
| 1787 | - } | |
| 1788 | 1771 | try { |
| 1789 | 1772 | |
| 1790 | - // Adds to the load balancing first and foremost, as doing so might change the decision | |
| 1791 | - // it will make for distance() on that node (not likely but we leave that possibility). | |
| 1792 | - // This does mean the policy may start returning that node for query plan, but as long | |
| 1793 | - // as no pools have been created (below) this will be ignored by RequestHandler so it's fine. | |
| 1794 | - loadBalancingPolicy().onAdd(host); | |
| 1795 | - | |
| 1796 | - // Next, if the host should be ignored, well, ignore it. | |
| 1797 | - if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) { | |
| 1798 | - // We still mark the node UP though as it should be (and notifiy the listeners). | |
| 1799 | - // We'll mark it down if we have a notification anyway and we've documented that especially | |
| 1800 | - // for IGNORED hosts, the isUp() method was a best effort guess | |
| 1801 | - host.setUp(); | |
| 1802 | - for (Host.StateListener listener : listeners) | |
| 1803 | - listener.onAdd(host); | |
| 1773 | + boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); | |
| 1774 | + if (!locked) { | |
| 1775 | + logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); | |
| 1804 | 1776 | return; |
| 1805 | 1777 | } |
| 1806 | - | |
| 1807 | 1778 | try { |
| 1808 | - prepareAllQueries(host); | |
| 1809 | - } catch (InterruptedException e) { | |
| 1810 | - Thread.currentThread().interrupt(); | |
| 1811 | - // Don't propagate because we don't want to prevent other listener to run | |
| 1812 | - } catch (UnsupportedProtocolVersionException e) { | |
| 1813 | - logUnsupportedVersionProtocol(host); | |
| 1814 | - return; | |
| 1815 | - } catch (ClusterNameMismatchException e) { | |
| 1816 | - logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 1817 | - return; | |
| 1818 | - } | |
| 1819 | 1779 | |
| 1820 | - controlConnection.onAdd(host); | |
| 1780 | + // Adds to the load balancing first and foremost, as doing so might change the decision | |
| 1781 | + // it will make for distance() on that node (not likely but we leave that possibility). | |
| 1782 | + // This does mean the policy may start returning that node for query plan, but as long | |
| 1783 | + // as no pools have been created (below) this will be ignored by RequestHandler so it's fine. | |
| 1784 | + loadBalancingPolicy().onAdd(host); | |
| 1785 | + | |
| 1786 | + // Next, if the host should be ignored, well, ignore it. | |
| 1787 | + if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) { | |
| 1788 | + // We still mark the node UP though as it should be (and notifiy the listeners). | |
| 1789 | + // We'll mark it down if we have a notification anyway and we've documented that especially | |
| 1790 | + // for IGNORED hosts, the isUp() method was a best effort guess | |
| 1791 | + host.setUp(); | |
| 1792 | + for (Host.StateListener listener : listeners) | |
| 1793 | + listener.onAdd(host); | |
| 1794 | + return; | |
| 1795 | + } | |
| 1796 | + | |
| 1797 | + try { | |
| 1798 | + reusedConnection = prepareAllQueries(host, reusedConnection); | |
| 1799 | + } catch (InterruptedException e) { | |
| 1800 | + Thread.currentThread().interrupt(); | |
| 1801 | + // Don't propagate because we don't want to prevent other listener to run | |
| 1802 | + } catch (UnsupportedProtocolVersionException e) { | |
| 1803 | + logUnsupportedVersionProtocol(host); | |
| 1804 | + return; | |
| 1805 | + } catch (ClusterNameMismatchException e) { | |
| 1806 | + logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 1807 | + return; | |
| 1808 | + } | |
| 1809 | + | |
| 1810 | + controlConnection.onAdd(host); | |
| 1811 | + | |
| 1812 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1813 | + for (SessionManager s : sessions) | |
| 1814 | + futures.add(s.maybeAddPool(host, reusedConnection)); | |
| 1815 | + | |
| 1816 | + try { | |
| 1817 | + // Only mark the node up once all session have added their pool (if the load-balancing | |
| 1818 | + // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1819 | + // to the node. | |
| 1820 | + List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); | |
| 1821 | 1821 | |
| 1822 | - List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size()); | |
| 1823 | - for (SessionManager s : sessions) | |
| 1824 | - futures.add(s.maybeAddPool(host, blockingExecutor)); | |
| 1825 | - | |
| 1826 | - // Only mark the node up once all session have added their pool (if the load-balancing | |
| 1827 | - // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1828 | - // to the node. | |
| 1829 | - ListenableFuture<List<Boolean>> f = Futures.allAsList(futures); | |
| 1830 | - Futures.addCallback(f, new FutureCallback<List<Boolean>>() { | |
| 1831 | - public void onSuccess(List<Boolean> poolCreationResults) { | |
| 1832 | 1822 | // If any of the creation failed, they will have signaled a connection failure |
| 1833 | 1823 | // which will trigger a reconnection to the node. So don't bother marking UP. |
| 1834 | 1824 | if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { |
| @@ -1840,24 +1830,26 @@ | ||
| 1840 | 1830 | |
| 1841 | 1831 | for (Host.StateListener listener : listeners) |
| 1842 | 1832 | listener.onAdd(host); |
| 1843 | - } | |
| 1844 | 1833 | |
| 1845 | - public void onFailure(Throwable t) { | |
| 1834 | + } catch (ExecutionException e) { | |
| 1835 | + Throwable t = e.getCause(); | |
| 1846 | 1836 | // That future is not really supposed to throw unexpected exceptions |
| 1847 | 1837 | if (!(t instanceof InterruptedException)) |
| 1848 | 1838 | logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t); |
| 1849 | 1839 | } |
| 1850 | - }); | |
| 1851 | 1840 | |
| 1852 | - f.get(); | |
| 1841 | + // Now, check if there isn't pools to create/remove following the addition. | |
| 1842 | + // We do that now only so that it's not called before we've set the node up. | |
| 1843 | + for (SessionManager s : sessions) | |
| 1844 | + s.updateCreatedPools(); | |
| 1853 | 1845 | |
| 1854 | - // Now, check if there isn't pools to create/remove following the addition. | |
| 1855 | - // We do that now only so that it's not called before we've set the node up. | |
| 1856 | - for (SessionManager s : sessions) | |
| 1857 | - s.updateCreatedPools(blockingExecutor); | |
| 1846 | + } finally { | |
| 1847 | + host.notificationsLock.unlock(); | |
| 1848 | + } | |
| 1858 | 1849 | |
| 1859 | 1850 | } finally { |
| 1860 | - host.notificationsLock.unlock(); | |
| 1851 | + if (reusedConnection != null && !reusedConnection.hasPool()) | |
| 1852 | + reusedConnection.closeAsync(); | |
| 1861 | 1853 | } |
| 1862 | 1854 | } |
| 1863 | 1855 | |
| @@ -1956,69 +1948,85 @@ | ||
| 1956 | 1948 | return stmt; |
| 1957 | 1949 | } |
| 1958 | 1950 | |
| 1959 | - private void prepareAllQueries(Host host) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 1951 | + /** | |
| 1952 | + * @param reusedConnection an existing connection (from a reconnection attempt) that we want to | |
| 1953 | + * reuse to prepare the statements (might be null). | |
| 1954 | + * @return a connection that the rest of the initialization process can use (it will be made part | |
| 1955 | + * of a connection pool). Can be reusedConnection, or one that was open in the method. | |
| 1956 | + */ | |
| 1957 | + private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 1960 | 1958 | if (preparedQueries.isEmpty()) |
| 1961 | - return; | |
| 1959 | + return reusedConnection; | |
| 1962 | 1960 | |
| 1963 | 1961 | logger.debug("Preparing {} prepared queries on newly up node {}", preparedQueries.size(), host); |
| 1962 | + Connection connection = null; | |
| 1964 | 1963 | try { |
| 1965 | - Connection connection = connectionFactory.open(host); | |
| 1964 | + connection = (reusedConnection == null) | |
| 1965 | + ? connectionFactory.open(host) | |
| 1966 | + : reusedConnection; | |
| 1966 | 1967 | |
| 1967 | - try | |
| 1968 | - { | |
| 1969 | - try { | |
| 1970 | - ControlConnection.waitForSchemaAgreement(connection, this); | |
| 1971 | - } catch (ExecutionException e) { | |
| 1972 | - // As below, just move on | |
| 1973 | - } | |
| 1968 | + try { | |
| 1969 | + ControlConnection.waitForSchemaAgreement(connection, this); | |
| 1970 | + } catch (ExecutionException e) { | |
| 1971 | + // As below, just move on | |
| 1972 | + } | |
| 1974 | 1973 | |
| 1975 | - // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation | |
| 1976 | - // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the | |
| 1977 | - // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is | |
| 1978 | - // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed. | |
| 1979 | - | |
| 1980 | - // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally | |
| 1981 | - // used for preparing it. However, since we are likely that all prepared query belong to only a handful | |
| 1982 | - // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed, | |
| 1983 | - // we first sort the query per keyspace. | |
| 1984 | - SetMultimap<String, String> perKeyspace = HashMultimap.create(); | |
| 1985 | - for (PreparedStatement ps : preparedQueries.values()) { | |
| 1986 | - // It's possible for a query to not have a current keyspace. But since null doesn't work well as | |
| 1987 | - // map keys, we use the empty string instead (that is not a valid keyspace name). | |
| 1988 | - String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace(); | |
| 1989 | - perKeyspace.put(keyspace, ps.getQueryString()); | |
| 1990 | - } | |
| 1974 | + // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation | |
| 1975 | + // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the | |
| 1976 | + // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is | |
| 1977 | + // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed. | |
| 1978 | + | |
| 1979 | + // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally | |
| 1980 | + // used for preparing it. However, since we are likely that all prepared query belong to only a handful | |
| 1981 | + // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed, | |
| 1982 | + // we first sort the query per keyspace. | |
| 1983 | + SetMultimap<String, String> perKeyspace = HashMultimap.create(); | |
| 1984 | + for (PreparedStatement ps : preparedQueries.values()) { | |
| 1985 | + // It's possible for a query to not have a current keyspace. But since null doesn't work well as | |
| 1986 | + // map keys, we use the empty string instead (that is not a valid keyspace name). | |
| 1987 | + String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace(); | |
| 1988 | + perKeyspace.put(keyspace, ps.getQueryString()); | |
| 1989 | + } | |
| 1991 | 1990 | |
| 1992 | - for (String keyspace : perKeyspace.keySet()) | |
| 1993 | - { | |
| 1994 | - // Empty string mean no particular keyspace to set | |
| 1995 | - if (!keyspace.isEmpty()) | |
| 1996 | - connection.setKeyspace(keyspace); | |
| 1997 | - | |
| 1998 | - List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size()); | |
| 1999 | - for (String query : perKeyspace.get(keyspace)) { | |
| 2000 | - futures.add(connection.write(new Requests.Prepare(query))); | |
| 2001 | - } | |
| 2002 | - for (Connection.Future future : futures) { | |
| 2003 | - try { | |
| 2004 | - future.get(); | |
| 2005 | - } catch (ExecutionException e) { | |
| 2006 | - // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do | |
| 2007 | - // currently). It's not a big deal however as if it's a more serious problem it'll show up later when | |
| 2008 | - // the query is tried for execution. | |
| 2009 | - logger.debug("Unexpected error while preparing queries on new/newly up host", e); | |
| 2010 | - } | |
| 1991 | + for (String keyspace : perKeyspace.keySet()) { | |
| 1992 | + // Empty string mean no particular keyspace to set | |
| 1993 | + if (!keyspace.isEmpty()) | |
| 1994 | + connection.setKeyspace(keyspace); | |
| 1995 | + | |
| 1996 | + List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size()); | |
| 1997 | + for (String query : perKeyspace.get(keyspace)) { | |
| 1998 | + futures.add(connection.write(new Requests.Prepare(query))); | |
| 1999 | + } | |
| 2000 | + for (Connection.Future future : futures) { | |
| 2001 | + try { | |
| 2002 | + future.get(); | |
| 2003 | + } catch (ExecutionException e) { | |
| 2004 | + // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do | |
| 2005 | + // currently). It's not a big deal however as if it's a more serious problem it'll show up later when | |
| 2006 | + // the query is tried for execution. | |
| 2007 | + logger.debug("Unexpected error while preparing queries on new/newly up host", e); | |
| 2011 | 2008 | } |
| 2012 | 2009 | } |
| 2013 | - } finally { | |
| 2014 | - connection.closeAsync(); | |
| 2015 | 2010 | } |
| 2011 | + | |
| 2012 | + return connection; | |
| 2016 | 2013 | } catch (ConnectionException e) { |
| 2017 | 2014 | // Ignore, not a big deal |
| 2015 | + if (connection != null) | |
| 2016 | + connection.closeAsync(); | |
| 2017 | + return null; | |
| 2018 | 2018 | } catch (AuthenticationException e) { |
| 2019 | 2019 | // That's a bad news, but ignore at this point |
| 2020 | + if (connection != null) | |
| 2021 | + connection.closeAsync(); | |
| 2022 | + return null; | |
| 2020 | 2023 | } catch (BusyConnectionException e) { |
| 2021 | 2024 | // Ignore, not a big deal |
| 2025 | + // In theory the problem is transient so the connection could be reused later, but if the core pool size is 1 | |
| 2026 | + // it's better to close this one so that we start with a fresh connection. | |
| 2027 | + if (connection != null) | |
| 2028 | + connection.closeAsync(); | |
| 2029 | + return null; | |
| 2022 | 2030 | } |
| 2023 | 2031 | } |
| 2024 | 2032 | |
| @@ -2107,7 +2115,7 @@ | ||
| 2107 | 2115 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 2108 | 2116 | // catch that an upgraded node uses a new cassandra version). |
| 2109 | 2117 | if (controlConnection.refreshNodeInfo(newHost)) { |
| 2110 | - onAdd(newHost); | |
| 2118 | + onAdd(newHost, null); | |
| 2111 | 2119 | } else { |
| 2112 | 2120 | logger.debug("Not enough info for {}, ignoring host", newHost); |
| 2113 | 2121 | } |
| @@ -2149,7 +2157,7 @@ | ||
| 2149 | 2157 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 2150 | 2158 | // catch that an upgraded node uses a new cassandra version). |
| 2151 | 2159 | if (controlConnection.refreshNodeInfo(h)) { |
| 2152 | - onAdd(h); | |
| 2160 | + onAdd(h, null); | |
| 2153 | 2161 | } else { |
| 2154 | 2162 | logger.debug("Not enough info for {}, ignoring host", h); |
| 2155 | 2163 | } |
| @@ -2162,7 +2170,7 @@ | ||
| 2162 | 2170 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 2163 | 2171 | // catch that an upgraded node uses a new cassandra version). |
| 2164 | 2172 | if (controlConnection.refreshNodeInfo(hostUp)) { |
| 2165 | - onUp(hostUp); | |
| 2173 | + onUp(hostUp, null); | |
| 2166 | 2174 | } else { |
| 2167 | 2175 | logger.debug("Not enough info for {}, ignoring host", hostUp); |
| 2168 | 2176 | } |
| @@ -2221,7 +2229,7 @@ | ||
| 2221 | 2229 | controlConnection.reconnect(); |
| 2222 | 2230 | |
| 2223 | 2231 | for (SessionManager s : sessions) |
| 2224 | - s.updateCreatedPools(executor); | |
| 2232 | + s.updateCreatedPools(); | |
| 2225 | 2233 | } |
| 2226 | 2234 | |
| 2227 | 2235 | void refreshConnectedHost(Host host) { |
| @@ -2231,7 +2239,7 @@ | ||
| 2231 | 2239 | controlConnection.reconnect(); |
| 2232 | 2240 | |
| 2233 | 2241 | for (SessionManager s : sessions) |
| 2234 | - s.updateCreatedPools(host, executor); | |
| 2242 | + s.updateCreatedPools(host); | |
| 2235 | 2243 | } |
| 2236 | 2244 | |
| 2237 | 2245 | private class ClusterCloseFuture extends CloseFuture.Forwarding { |
| @@ -2311,7 +2319,8 @@ | ||
| 2311 | 2319 | private static final int INTERVAL_MS = 15000; |
| 2312 | 2320 | |
| 2313 | 2321 | private final ScheduledExecutorService executor; |
| 2314 | - private final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>(); | |
| 2322 | + @VisibleForTesting | |
| 2323 | + final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>(); | |
| 2315 | 2324 | |
| 2316 | 2325 | private volatile boolean shutdown; |
| 2317 | 2326 |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +329 −152
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.lang.ref.WeakReference; | |
| 18 | 19 | import java.net.InetSocketAddress; |
| 19 | 20 | import java.util.HashSet; |
| 20 | 21 | import java.util.Iterator; |
| @@ -26,8 +27,8 @@ | ||
| 26 | 27 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 28 | |
| 28 | 29 | import com.google.common.collect.Lists; |
| 29 | -import com.google.common.util.concurrent.AbstractFuture; | |
| 30 | -import com.google.common.util.concurrent.Uninterruptibles; | |
| 30 | +import com.google.common.collect.MapMaker; | |
| 31 | +import com.google.common.util.concurrent.*; | |
| 31 | 32 | import io.netty.bootstrap.Bootstrap; |
| 32 | 33 | import io.netty.channel.*; |
| 33 | 34 | import io.netty.channel.group.ChannelGroup; |
| @@ -47,7 +48,8 @@ | ||
| 47 | 48 | import static io.netty.handler.timeout.IdleState.ALL_IDLE; |
| 48 | 49 | |
| 49 | 50 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 50 | -import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 51 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 52 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 51 | 53 | |
| 52 | 54 | // For LoggingHandler |
| 53 | 55 | //import org.jboss.netty.handler.logging.LoggingHandler; |
| @@ -63,10 +65,16 @@ | ||
| 63 | 65 | |
| 64 | 66 | private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false); |
| 65 | 67 | |
| 68 | + enum State {OPEN, TRASHED, RESURRECTING, GONE } | |
| 69 | + | |
| 70 | + final AtomicReference<State> state = new AtomicReference<State>(State.OPEN); | |
| 71 | + | |
| 72 | + volatile long maxIdleTime; | |
| 73 | + | |
| 66 | 74 | public final InetSocketAddress address; |
| 67 | 75 | private final String name; |
| 68 | 76 | |
| 69 | - private final Channel channel; | |
| 77 | + private volatile Channel channel; | |
| 70 | 78 | private final Factory factory; |
| 71 | 79 | |
| 72 | 80 | private final Dispatcher dispatcher = new Dispatcher(); |
| @@ -82,23 +90,42 @@ | ||
| 82 | 90 | |
| 83 | 91 | private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>(); |
| 84 | 92 | |
| 93 | + private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>(); | |
| 94 | + | |
| 85 | 95 | /** |
| 86 | - * Create a new connection to a Cassandra node. | |
| 87 | - * | |
| 88 | - * The connection is open and initialized by the constructor. | |
| 96 | + /** | |
| 97 | + * Create a new connection to a Cassandra node and associate it with the given pool. | |
| 89 | 98 | * |
| 90 | - * @throws ConnectionException if the connection attempts fails or is | |
| 91 | - * refused by the server. | |
| 99 | + * @param name the connection name | |
| 100 | + * @param address the remote address | |
| 101 | + * @param factory the connection factory to use | |
| 102 | + * @param pool the pool this connection belongs to. May be null if this connection does not belong to a pool. | |
| 103 | + * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}. | |
| 92 | 104 | */ |
| 93 | - protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 105 | + protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) { | |
| 94 | 106 | this.address = address; |
| 95 | 107 | this.factory = factory; |
| 96 | 108 | this.name = name; |
| 109 | + this.poolRef.set(pool); | |
| 110 | + } | |
| 111 | + | |
| 112 | + /** | |
| 113 | + * Create a new connection to a Cassandra node. | |
| 114 | + */ | |
| 115 | + Connection(String name, InetSocketAddress address, Factory factory) { | |
| 116 | + this(name, address, factory, null); | |
| 117 | + } | |
| 118 | + | |
| 119 | + public ListenableFuture<Void> initAsync() { | |
| 120 | + if (factory.isShutdown) | |
| 121 | + return Futures.immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down")); | |
| 122 | + | |
| 123 | + int protocolVersion = factory.protocolVersion == 1 ? 1 : 2; | |
| 124 | + final SettableFuture<Void> channelReadyFuture = SettableFuture.create(); | |
| 97 | 125 | |
| 98 | 126 | try { |
| 99 | 127 | Bootstrap bootstrap = factory.newBootstrap(); |
| 100 | 128 | ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions(); |
| 101 | - int protocolVersion = factory.protocolVersion == 1 ? 1 : 2; | |
| 102 | 129 | bootstrap.handler( |
| 103 | 130 | new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(), |
| 104 | 131 | factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), |
| @@ -107,41 +134,81 @@ | ||
| 107 | 134 | ChannelFuture future = bootstrap.connect(address); |
| 108 | 135 | |
| 109 | 136 | writer.incrementAndGet(); |
| 110 | - try { | |
| 111 | - // Wait until the connection attempt succeeds or fails. | |
| 112 | - this.channel = future.awaitUninterruptibly().channel(); | |
| 113 | - this.factory.allChannels.add(this.channel); | |
| 114 | - if (!future.isSuccess()) { | |
| 115 | - if (logger.isDebugEnabled()) | |
| 116 | - logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.cause()))); | |
| 117 | - throw defunct(new TransportException(address, "Cannot connect", future.cause())); | |
| 137 | + future.addListener(new ChannelFutureListener() { | |
| 138 | + @Override | |
| 139 | + public void operationComplete(ChannelFuture future) throws Exception { | |
| 140 | + writer.decrementAndGet(); | |
| 141 | + channel = future.channel(); | |
| 142 | + if (isClosed()) { | |
| 143 | + channel.close().addListener(new ChannelFutureListener() { | |
| 144 | + @Override | |
| 145 | + public void operationComplete(ChannelFuture future) throws Exception { | |
| 146 | + channelReadyFuture.setException(new TransportException(Connection.this.address, "Connection closed during initialization.")); | |
| 147 | + } | |
| 148 | + }); | |
| 149 | + } else { | |
| 150 | + Connection.this.factory.allChannels.add(channel); | |
| 151 | + if (!future.isSuccess()) { | |
| 152 | + if (logger.isDebugEnabled()) | |
| 153 | + logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause()))); | |
| 154 | + channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause())); | |
| 155 | + } else { | |
| 156 | + logger.debug("{} Connection opened successfully", Connection.this); | |
| 157 | + channel.closeFuture().addListener(new ChannelCloseListener()); | |
| 158 | + channelReadyFuture.set(null); | |
| 159 | + } | |
| 160 | + } | |
| 118 | 161 | } |
| 119 | - channel.closeFuture().addListener(new ChannelCloseListener()); | |
| 120 | - } finally { | |
| 121 | - writer.decrementAndGet(); | |
| 122 | - } | |
| 123 | - | |
| 124 | - logger.trace("{} Connection opened successfully", this); | |
| 125 | - initializeTransport(protocolVersion, factory.manager.metadata.clusterName); | |
| 126 | - logger.debug("{} Transport initialized and ready", this); | |
| 127 | - isInitialized = true; | |
| 128 | - | |
| 129 | - } catch (ConnectionException e) { | |
| 130 | - closeAsync().force(); | |
| 131 | - throw e; | |
| 132 | - } catch (ClusterNameMismatchException e) { | |
| 133 | - closeAsync().force(); | |
| 134 | - throw e; | |
| 135 | - } catch (UnsupportedProtocolVersionException e) { | |
| 136 | - closeAsync().force(); | |
| 137 | - throw e; | |
| 138 | - } catch (InterruptedException e) { | |
| 139 | - closeAsync().force(); | |
| 140 | - throw e; | |
| 162 | + }); | |
| 141 | 163 | } catch (RuntimeException e) { |
| 142 | 164 | closeAsync().force(); |
| 143 | 165 | throw e; |
| 144 | 166 | } |
| 167 | + | |
| 168 | + Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 169 | + | |
| 170 | + ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture, | |
| 171 | + onChannelReady(protocolVersion, initExecutor), initExecutor); | |
| 172 | + | |
| 173 | + // Fallback on initializeTransportFuture so we can properly propagate specific exceptions. | |
| 174 | + ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() { | |
| 175 | + @Override | |
| 176 | + public ListenableFuture<Void> create(Throwable t) throws Exception { | |
| 177 | + SettableFuture<Void> future = SettableFuture.create(); | |
| 178 | + // Make sure the connection gets properly closed. | |
| 179 | + if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) { | |
| 180 | + // These exceptions cause the node to be ignored, so just propagate | |
| 181 | + closeAsync().force(); | |
| 182 | + future.setException(t); | |
| 183 | + } else { | |
| 184 | + // Defunct to ensure that the error will be signaled (marking the host down) | |
| 185 | + ConnectionException ce = (t instanceof ConnectionException) | |
| 186 | + ? (ConnectionException)t | |
| 187 | + : new ConnectionException(Connection.this.address, | |
| 188 | + String.format("Unexpected error during transport initialization (%s)", t), | |
| 189 | + t); | |
| 190 | + future.setException(defunct(ce)); | |
| 191 | + } | |
| 192 | + return future; | |
| 193 | + } | |
| 194 | + }, initExecutor); | |
| 195 | + | |
| 196 | + // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel. | |
| 197 | + Futures.addCallback(initFuture, new FutureCallback<Void>() { | |
| 198 | + @Override | |
| 199 | + public void onSuccess(Void result) { | |
| 200 | + isInitialized = true; | |
| 201 | + } | |
| 202 | + | |
| 203 | + @Override | |
| 204 | + public void onFailure(Throwable t) { | |
| 205 | + if (!isClosed()) { | |
| 206 | + closeAsync().force(); | |
| 207 | + } | |
| 208 | + } | |
| 209 | + }, initExecutor); | |
| 210 | + | |
| 211 | + return initFuture; | |
| 145 | 212 | } |
| 146 | 213 | |
| 147 | 214 | private static String extractMessage(Throwable t) { |
| @@ -153,119 +220,157 @@ | ||
| 153 | 220 | return " (" + msg + ')'; |
| 154 | 221 | } |
| 155 | 222 | |
| 156 | - private void initializeTransport(int version, String clusterName) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 157 | - try { | |
| 158 | - ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression(); | |
| 159 | - Message.Response response = write(new Requests.Startup(compression)).get(); | |
| 160 | - switch (response.type) { | |
| 161 | - case READY: | |
| 162 | - break; | |
| 163 | - case ERROR: | |
| 164 | - Responses.Error error = (Responses.Error)response; | |
| 165 | - // Testing for a specific string is a tad fragile but well, we don't have much choice | |
| 166 | - if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version")) | |
| 167 | - throw unsupportedProtocolVersionException(version); | |
| 168 | - throw defunct(new TransportException(address, String.format("Error initializing connection: %s", error.message))); | |
| 169 | - case AUTHENTICATE: | |
| 170 | - Authenticator authenticator = factory.authProvider.newAuthenticator(address); | |
| 171 | - if (version == 1) | |
| 172 | - { | |
| 173 | - if (authenticator instanceof ProtocolV1Authenticator) | |
| 174 | - authenticateV1(authenticator); | |
| 175 | - else | |
| 176 | - // DSE 3.x always uses SASL authentication backported from protocol v2 | |
| 177 | - authenticateV2(authenticator); | |
| 178 | - } | |
| 179 | - else | |
| 180 | - authenticateV2(authenticator); | |
| 181 | - break; | |
| 182 | - default: | |
| 183 | - throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type))); | |
| 223 | + private AsyncFunction<Void, Void> onChannelReady(final int protocolVersion, final Executor initExecutor) { | |
| 224 | + return new AsyncFunction<Void, Void>() { | |
| 225 | + @Override | |
| 226 | + public ListenableFuture<Void> apply(Void input) throws Exception { | |
| 227 | + ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression(); | |
| 228 | + Future startupResponseFuture = write(new Requests.Startup(compression)); | |
| 229 | + return Futures.transform(startupResponseFuture, | |
| 230 | + onStartupResponse(protocolVersion, initExecutor), initExecutor); | |
| 184 | 231 | } |
| 232 | + }; | |
| 233 | + } | |
| 185 | 234 | |
| 186 | - checkClusterName(clusterName); | |
| 187 | - } catch (BusyConnectionException e) { | |
| 188 | - throw defunct(new DriverInternalError("Newly created connection should not be busy")); | |
| 189 | - } catch (ExecutionException e) { | |
| 190 | - throw defunct(new ConnectionException(address, String.format("Unexpected error during transport initialization (%s)", e.getCause()), e.getCause())); | |
| 191 | - } | |
| 235 | + private AsyncFunction<Message.Response, Void> onStartupResponse(final int protocolVersion, final Executor initExecutor) { | |
| 236 | + return new AsyncFunction<Message.Response, Void>() { | |
| 237 | + @Override | |
| 238 | + public ListenableFuture<Void> apply(Message.Response response) throws Exception { | |
| 239 | + switch (response.type) { | |
| 240 | + case READY: | |
| 241 | + return checkClusterName(initExecutor); | |
| 242 | + case ERROR: | |
| 243 | + Responses.Error error = (Responses.Error)response; | |
| 244 | + // Testing for a specific string is a tad fragile but well, we don't have much choice | |
| 245 | + if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version")) | |
| 246 | + throw unsupportedProtocolVersionException(protocolVersion); | |
| 247 | + throw new TransportException(address, String.format("Error initializing connection: %s", error.message)); | |
| 248 | + case AUTHENTICATE: | |
| 249 | + Authenticator authenticator = factory.authProvider.newAuthenticator(address); | |
| 250 | + if (protocolVersion == 1) | |
| 251 | + { | |
| 252 | + if (authenticator instanceof ProtocolV1Authenticator) | |
| 253 | + return authenticateV1(authenticator, initExecutor); | |
| 254 | + else | |
| 255 | + // DSE 3.x always uses SASL authentication backported from protocol v2 | |
| 256 | + return authenticateV2(authenticator, initExecutor); | |
| 257 | + } | |
| 258 | + else | |
| 259 | + return authenticateV2(authenticator, initExecutor); | |
| 260 | + default: | |
| 261 | + throw new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)); | |
| 262 | + } | |
| 263 | + } | |
| 264 | + }; | |
| 192 | 265 | } |
| 193 | 266 | |
| 194 | - private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) { | |
| 195 | - logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion); | |
| 196 | - return new UnsupportedProtocolVersionException(address, triedVersion); | |
| 267 | + // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster. | |
| 268 | + // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting | |
| 269 | + // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397). | |
| 270 | + private ListenableFuture<Void> checkClusterName(final Executor executor) { | |
| 271 | + final String expected = factory.manager.metadata.clusterName; | |
| 272 | + | |
| 273 | + // At initialization, the cluster is not known yet | |
| 274 | + if (expected == null) | |
| 275 | + return MoreFutures.VOID_SUCCESS; | |
| 276 | + | |
| 277 | + DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local")); | |
| 278 | + try { | |
| 279 | + write(clusterNameFuture); | |
| 280 | + return Futures.transform(clusterNameFuture, | |
| 281 | + new AsyncFunction<ResultSet, Void>() { | |
| 282 | + @Override | |
| 283 | + public ListenableFuture<Void> apply(ResultSet rs) throws Exception { | |
| 284 | + Row row = rs.one(); | |
| 285 | + String actual = row.getString("cluster_name"); | |
| 286 | + if (!expected.equals(actual)) | |
| 287 | + throw new ClusterNameMismatchException(address, actual, expected); | |
| 288 | + return MoreFutures.VOID_SUCCESS; | |
| 289 | + } | |
| 290 | + }, executor); | |
| 291 | + } catch (Exception e) { | |
| 292 | + return Futures.immediateFailedFuture(e); | |
| 293 | + } | |
| 197 | 294 | } |
| 198 | 295 | |
| 199 | - private void authenticateV1(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 296 | + private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final Executor executor) { | |
| 200 | 297 | Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials()); |
| 201 | - Message.Response authResponse = write(creds).get(); | |
| 202 | - switch (authResponse.type) { | |
| 203 | - case READY: | |
| 204 | - break; | |
| 205 | - case ERROR: | |
| 206 | - throw defunct(new AuthenticationException(address, ((Responses.Error)authResponse).message)); | |
| 207 | - default: | |
| 208 | - throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type))); | |
| 298 | + try { | |
| 299 | + Future authResponseFuture = write(creds); | |
| 300 | + return Futures.transform(authResponseFuture, | |
| 301 | + new AsyncFunction<Message.Response, Void>() { | |
| 302 | + @Override | |
| 303 | + public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception { | |
| 304 | + switch (authResponse.type) { | |
| 305 | + case READY: | |
| 306 | + return checkClusterName(executor); | |
| 307 | + case ERROR: | |
| 308 | + throw new AuthenticationException(address, ((Responses.Error)authResponse).message); | |
| 309 | + default: | |
| 310 | + throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)); | |
| 311 | + } | |
| 312 | + } | |
| 313 | + }, executor); | |
| 314 | + } catch (Exception e) { | |
| 315 | + return Futures.immediateFailedFuture(e); | |
| 209 | 316 | } |
| 210 | 317 | } |
| 211 | 318 | |
| 212 | - private void authenticateV2(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 319 | + private ListenableFuture<Void> authenticateV2(final Authenticator authenticator, final Executor executor) { | |
| 213 | 320 | byte[] initialResponse = authenticator.initialResponse(); |
| 214 | 321 | if (null == initialResponse) |
| 215 | 322 | initialResponse = EMPTY_BYTE_ARRAY; |
| 216 | 323 | |
| 217 | - Message.Response authResponse = write(new Requests.AuthResponse(initialResponse)).get(); | |
| 218 | - waitForAuthCompletion(authResponse, authenticator); | |
| 219 | - } | |
| 220 | - | |
| 221 | - private void waitForAuthCompletion(Message.Response authResponse, Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 222 | - switch (authResponse.type) { | |
| 223 | - case AUTH_SUCCESS: | |
| 224 | - logger.trace("{} Authentication complete", this); | |
| 225 | - authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token); | |
| 226 | - break; | |
| 227 | - case AUTH_CHALLENGE: | |
| 228 | - byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token); | |
| 229 | - if (responseToServer == null) { | |
| 230 | - // If we generate a null response, then authentication has completed, return without | |
| 231 | - // sending a further response back to the server. | |
| 232 | - logger.trace("{} Authentication complete (No response to server)", this); | |
| 233 | - return; | |
| 234 | - } else { | |
| 235 | - // Otherwise, send the challenge response back to the server | |
| 236 | - logger.trace("{} Sending Auth response to challenge", this); | |
| 237 | - waitForAuthCompletion(write(new Requests.AuthResponse(responseToServer)).get(), authenticator); | |
| 238 | - } | |
| 239 | - break; | |
| 240 | - case ERROR: | |
| 241 | - // This is not very nice, but we're trying to identify if we | |
| 242 | - // attempted v2 auth against a server which only supports v1 | |
| 243 | - // The AIOOBE indicates that the server didn't recognise the | |
| 244 | - // initial AuthResponse message | |
| 245 | - String message = ((Responses.Error)authResponse).message; | |
| 246 | - if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15")) | |
| 247 | - message = String.format("Cannot use authenticator %s with protocol version 1, " | |
| 248 | - + "only plain text authentication is supported with this protocol version", authenticator); | |
| 249 | - throw defunct(new AuthenticationException(address, message)); | |
| 250 | - default: | |
| 251 | - throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type))); | |
| 324 | + try { | |
| 325 | + Future authResponseFuture = write(new Requests.AuthResponse(initialResponse)); | |
| 326 | + return Futures.transform(authResponseFuture, onV2AuthResponse(authenticator, executor), executor); | |
| 327 | + } catch (Exception e) { | |
| 328 | + return Futures.immediateFailedFuture(e); | |
| 252 | 329 | } |
| 253 | 330 | } |
| 254 | 331 | |
| 255 | - // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster. | |
| 256 | - // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting | |
| 257 | - // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397). | |
| 258 | - private void checkClusterName(String expected) throws ClusterNameMismatchException, ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 259 | - // At initialization, the cluster is not known yet | |
| 260 | - if (expected == null) | |
| 261 | - return; | |
| 332 | + private AsyncFunction<Message.Response, Void> onV2AuthResponse(final Authenticator authenticator, final Executor executor) { | |
| 333 | + return new AsyncFunction<Message.Response, Void>() { | |
| 334 | + @Override | |
| 335 | + public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception { | |
| 336 | + switch (authResponse.type) { | |
| 337 | + case AUTH_SUCCESS: | |
| 338 | + logger.trace("{} Authentication complete", this); | |
| 339 | + authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token); | |
| 340 | + return checkClusterName(executor); | |
| 341 | + case AUTH_CHALLENGE: | |
| 342 | + byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token); | |
| 343 | + if (responseToServer == null) { | |
| 344 | + // If we generate a null response, then authentication has completed, proceed without | |
| 345 | + // sending a further response back to the server. | |
| 346 | + logger.trace("{} Authentication complete (No response to server)", this); | |
| 347 | + return checkClusterName(executor); | |
| 348 | + } else { | |
| 349 | + // Otherwise, send the challenge response back to the server | |
| 350 | + logger.trace("{} Sending Auth response to challenge", this); | |
| 351 | + Future nextResponseFuture = write(new Requests.AuthResponse(responseToServer)); | |
| 352 | + return Futures.transform(nextResponseFuture, onV2AuthResponse(authenticator, executor), executor); | |
| 353 | + } | |
| 354 | + case ERROR: | |
| 355 | + // This is not very nice, but we're trying to identify if we | |
| 356 | + // attempted v2 auth against a server which only supports v1 | |
| 357 | + // The AIOOBE indicates that the server didn't recognise the | |
| 358 | + // initial AuthResponse message | |
| 359 | + String message = ((Responses.Error)authResponse).message; | |
| 360 | + if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15")) | |
| 361 | + message = String.format("Cannot use authenticator %s with protocol version 1, " | |
| 362 | + + "only plain text authentication is supported with this protocol version", authenticator); | |
| 363 | + throw new AuthenticationException(address, message); | |
| 364 | + default: | |
| 365 | + throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type)); | |
| 366 | + } | |
| 367 | + } | |
| 368 | + }; | |
| 369 | + } | |
| 262 | 370 | |
| 263 | - DefaultResultSetFuture future = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local")); | |
| 264 | - write(future); | |
| 265 | - Row row = future.get().one(); | |
| 266 | - String actual = row.getString("cluster_name"); | |
| 267 | - if (!expected.equals(actual)) | |
| 268 | - throw new ClusterNameMismatchException(address, actual, expected); | |
| 371 | + private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) { | |
| 372 | + logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion); | |
| 373 | + return new UnsupportedProtocolVersionException(address, triedVersion); | |
| 269 | 374 | } |
| 270 | 375 | |
| 271 | 376 | public boolean isDefunct() { |
| @@ -293,9 +398,9 @@ | ||
| 293 | 398 | // If the host was reconnecting, and this error happens right after we opened a connection pool, but |
| 294 | 399 | // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can |
| 295 | 400 | // lead to a race condition that leaves the node UP with a closed pool. |
| 401 | + HostConnectionPool pool = this.poolRef.get(); | |
| 296 | 402 | boolean belongsToReconnectingPool = host.state != Host.State.UP && |
| 297 | - this instanceof PooledConnection && | |
| 298 | - (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed()); | |
| 403 | + (pool == null || !pool.isClosed()); | |
| 299 | 404 | |
| 300 | 405 | boolean markSuspected = isInitialized && !belongsToReconnectingPool; |
| 301 | 406 | |
| @@ -314,6 +419,19 @@ | ||
| 314 | 419 | } |
| 315 | 420 | |
| 316 | 421 | protected void notifyOwnerWhenDefunct(boolean hostIsDown) { |
| 422 | + // If an error happens during initialization, the owner will detect it and take appropriate action | |
| 423 | + if (!isInitialized) | |
| 424 | + return; | |
| 425 | + | |
| 426 | + HostConnectionPool pool = this.poolRef.get(); | |
| 427 | + if (pool == null) | |
| 428 | + return; | |
| 429 | + | |
| 430 | + if (hostIsDown) { | |
| 431 | + pool.closeAsync().force(); | |
| 432 | + } else { | |
| 433 | + pool.replaceDefunctConnection(this); | |
| 434 | + } | |
| 317 | 435 | } |
| 318 | 436 | |
| 319 | 437 | public String keyspace() { |
| @@ -462,6 +580,25 @@ | ||
| 462 | 580 | }; |
| 463 | 581 | } |
| 464 | 582 | |
| 583 | + boolean hasPool() { | |
| 584 | + return this.poolRef.get() != null; | |
| 585 | + } | |
| 586 | + | |
| 587 | + /** @return whether the connection was already associated with a pool */ | |
| 588 | + boolean setPool(HostConnectionPool pool) { | |
| 589 | + return poolRef.compareAndSet(null, pool); | |
| 590 | + } | |
| 591 | + | |
| 592 | + /** | |
| 593 | + * If the connection is part of a pool, return it to the pool. | |
| 594 | + * The connection should generally not be reused after that. | |
| 595 | + */ | |
| 596 | + void release() { | |
| 597 | + HostConnectionPool pool = poolRef.get(); | |
| 598 | + if (pool != null) | |
| 599 | + pool.returnConnection(this); | |
| 600 | + } | |
| 601 | + | |
| 465 | 602 | public boolean isClosed() { |
| 466 | 603 | return closeFuture.get() != null; |
| 467 | 604 | } |
| @@ -585,20 +722,53 @@ | ||
| 585 | 722 | throw new ConnectionException(address, "Connection factory is shut down"); |
| 586 | 723 | |
| 587 | 724 | String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement(); |
| 588 | - return new Connection(name, address, this); | |
| 725 | + Connection connection = new Connection(name, address, this); | |
| 726 | + // This method opens the connection synchronously, so wait until it's initialized | |
| 727 | + try { | |
| 728 | + connection.initAsync().get(); | |
| 729 | + return connection; | |
| 730 | + } catch (ExecutionException e) { | |
| 731 | + throw launderAsyncInitException(e); | |
| 732 | + } | |
| 589 | 733 | } |
| 590 | 734 | |
| 591 | 735 | /** |
| 592 | 736 | * Same as open, but associate the created connection to the provided connection pool. |
| 593 | 737 | */ |
| 594 | - public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 738 | + public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 739 | + try { | |
| 740 | + Connection connection = newConnection(pool); | |
| 741 | + connection.initAsync().get(); | |
| 742 | + return connection; | |
| 743 | + } catch (ExecutionException e) { | |
| 744 | + throw launderAsyncInitException(e); | |
| 745 | + } | |
| 746 | + } | |
| 747 | + | |
| 748 | + /** | |
| 749 | + * Creates a new connection and associates it to the provided connection pool, but does not start it. | |
| 750 | + */ | |
| 751 | + public Connection newConnection(HostConnectionPool pool) { | |
| 595 | 752 | InetSocketAddress address = pool.host.getSocketAddress(); |
| 753 | + String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement(); | |
| 596 | 754 | |
| 597 | - if (isShutdown) | |
| 598 | - throw new ConnectionException(address, "Connection factory is shut down"); | |
| 755 | + return new Connection(name, address, this, pool); | |
| 756 | + } | |
| 599 | 757 | |
| 600 | - String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement(); | |
| 601 | - return new PooledConnection(name, address, this, pool); | |
| 758 | + static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 759 | + Throwable t = e.getCause(); | |
| 760 | + if (t instanceof ConnectionException) | |
| 761 | + throw (ConnectionException)t; | |
| 762 | + if (t instanceof InterruptedException) | |
| 763 | + throw (InterruptedException)t; | |
| 764 | + if (t instanceof UnsupportedProtocolVersionException) | |
| 765 | + throw (UnsupportedProtocolVersionException)t; | |
| 766 | + if (t instanceof ClusterNameMismatchException) | |
| 767 | + throw (ClusterNameMismatchException)t; | |
| 768 | + if (t instanceof DriverException) | |
| 769 | + throw (DriverException)t; | |
| 770 | + | |
| 771 | + return new RuntimeException("Unexpected exception during connection initialization", t); | |
| 602 | 772 | } |
| 603 | 773 | |
| 604 | 774 | private AtomicInteger getIdGenerator(Host host) { |
| @@ -665,7 +835,7 @@ | ||
| 665 | 835 | } |
| 666 | 836 | |
| 667 | 837 | private static final class Flusher implements Runnable { |
| 668 | - final EventLoop eventLoop; | |
| 838 | + final WeakReference<EventLoop> eventLoopRef; | |
| 669 | 839 | final Queue<FlushItem> queued = new ConcurrentLinkedQueue<FlushItem>(); |
| 670 | 840 | final AtomicBoolean running = new AtomicBoolean(false); |
| 671 | 841 | final HashSet<Channel> channels = new HashSet<Channel>(); |
| @@ -674,12 +844,14 @@ | ||
| 674 | 844 | int runsWithNoWork = 0; |
| 675 | 845 | |
| 676 | 846 | private Flusher(EventLoop eventLoop) { |
| 677 | - this.eventLoop = eventLoop; | |
| 847 | + this.eventLoopRef = new WeakReference<EventLoop>(eventLoop); | |
| 678 | 848 | } |
| 679 | 849 | |
| 680 | 850 | void start() { |
| 681 | 851 | if (!running.get() && running.compareAndSet(false, true)) { |
| 682 | - this.eventLoop.execute(this); | |
| 852 | + EventLoop eventLoop = eventLoopRef.get(); | |
| 853 | + if (eventLoop != null) | |
| 854 | + eventLoop.execute(this); | |
| 683 | 855 | } |
| 684 | 856 | } |
| 685 | 857 | |
| @@ -717,11 +889,17 @@ | ||
| 717 | 889 | } |
| 718 | 890 | } |
| 719 | 891 | |
| 720 | - eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS); | |
| 892 | + EventLoop eventLoop = eventLoopRef.get(); | |
| 893 | + if(eventLoop != null) { | |
| 894 | + eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS); | |
| 895 | + } | |
| 721 | 896 | } |
| 722 | 897 | } |
| 723 | 898 | |
| 724 | - private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new ConcurrentHashMap<EventLoop, Flusher>(); | |
| 899 | + private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker() | |
| 900 | + .concurrencyLevel(16) | |
| 901 | + .weakKeys() | |
| 902 | + .makeMap(); | |
| 725 | 903 | |
| 726 | 904 | private static class FlushItem { |
| 727 | 905 | final Channel channel; |
| @@ -925,7 +1103,7 @@ | ||
| 925 | 1103 | public ConnectionCloseFuture force() { |
| 926 | 1104 | // Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared |
| 927 | 1105 | |
| 928 | - // This method can be thrown during Connection ctor, at which point channel is not yet set. This is ok. | |
| 1106 | + // This method can be thrown during initialization, at which point channel is not yet set. This is ok. | |
| 929 | 1107 | if (channel == null) { |
| 930 | 1108 | set(null); |
| 931 | 1109 | return this; |
| @@ -1056,8 +1234,7 @@ | ||
| 1056 | 1234 | // were, a new request could reuse that ID but get the answer to the request we just gave up on instead |
| 1057 | 1235 | // of its own answer, and we would have no way to detect that. |
| 1058 | 1236 | connection.dispatcher.removeHandler(this, false); |
| 1059 | - if (connection instanceof PooledConnection) | |
| 1060 | - ((PooledConnection)connection).release(); | |
| 1237 | + connection.release(); | |
| 1061 | 1238 | } |
| 1062 | 1239 | |
| 1063 | 1240 | private TimerTask onTimeoutTask() { |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +3 −1
| @@ -249,7 +249,9 @@ | ||
| 249 | 249 | if (!super.cancel(mayInterruptIfRunning)) |
| 250 | 250 | return false; |
| 251 | 251 | |
| 252 | - handler.cancel(); | |
| 252 | + if(handler != null) { | |
| 253 | + handler.cancel(); | |
| 254 | + } | |
| 253 | 255 | return true; |
| 254 | 256 | } |
| 255 | 257 |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +3 −1
| @@ -27,6 +27,8 @@ | ||
| 27 | 27 | import org.slf4j.Logger; |
| 28 | 28 | import org.slf4j.LoggerFactory; |
| 29 | 29 | |
| 30 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 31 | + | |
| 30 | 32 | /** |
| 31 | 33 | * A Cassandra node. |
| 32 | 34 | * |
| @@ -48,7 +50,7 @@ | ||
| 48 | 50 | private final Cluster.Manager manager; |
| 49 | 51 | |
| 50 | 52 | // Tracks the first "immediate" reconnection attempt when a node get suspected. |
| 51 | - final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null)); | |
| 53 | + final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(MoreFutures.VOID_SUCCESS); | |
| 52 | 54 | |
| 53 | 55 | // Tracks later reconnection attempts to that host so we avoid adding multiple tasks. |
| 54 | 56 | final AtomicReference<ListenableFuture<?>> reconnectionAttempt = new AtomicReference<ListenableFuture<?>>(); |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +101 −64
| @@ -15,14 +15,10 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | - | |
| 19 | 18 | import java.util.ArrayList; |
| 20 | 19 | import java.util.List; |
| 21 | 20 | import java.util.Set; |
| 22 | -import java.util.concurrent.CopyOnWriteArrayList; | |
| 23 | -import java.util.concurrent.CopyOnWriteArraySet; | |
| 24 | -import java.util.concurrent.TimeUnit; | |
| 25 | -import java.util.concurrent.TimeoutException; | |
| 21 | +import java.util.concurrent.*; | |
| 26 | 22 | import java.util.concurrent.atomic.AtomicInteger; |
| 27 | 23 | import java.util.concurrent.atomic.AtomicReference; |
| 28 | 24 | import java.util.concurrent.locks.Condition; |
| @@ -30,13 +26,17 @@ | ||
| 30 | 26 | import java.util.concurrent.locks.ReentrantLock; |
| 31 | 27 | |
| 32 | 28 | import com.google.common.collect.Lists; |
| 33 | -import com.google.common.util.concurrent.MoreExecutors; | |
| 29 | +import com.google.common.util.concurrent.*; | |
| 34 | 30 | import org.slf4j.Logger; |
| 35 | 31 | import org.slf4j.LoggerFactory; |
| 36 | 32 | |
| 37 | 33 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 34 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 38 | 35 | |
| 39 | -import static com.datastax.driver.core.PooledConnection.State.*; | |
| 36 | +import static com.datastax.driver.core.Connection.State.GONE; | |
| 37 | +import static com.datastax.driver.core.Connection.State.OPEN; | |
| 38 | +import static com.datastax.driver.core.Connection.State.RESURRECTING; | |
| 39 | +import static com.datastax.driver.core.Connection.State.TRASHED; | |
| 40 | 40 | |
| 41 | 41 | class HostConnectionPool { |
| 42 | 42 | |
| @@ -53,13 +53,13 @@ | ||
| 53 | 53 | public volatile HostDistance hostDistance; |
| 54 | 54 | private final SessionManager manager; |
| 55 | 55 | |
| 56 | - final List<PooledConnection> connections; | |
| 56 | + final List<Connection> connections; | |
| 57 | 57 | private final AtomicInteger open; |
| 58 | 58 | /** The total number of in-flight requests on all connections of this pool. */ |
| 59 | 59 | final AtomicInteger totalInFlight = new AtomicInteger(); |
| 60 | 60 | /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/ |
| 61 | 61 | private final AtomicInteger maxTotalInFlight = new AtomicInteger(); |
| 62 | - final Set<PooledConnection> trash = new CopyOnWriteArraySet<PooledConnection>(); | |
| 62 | + final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); | |
| 63 | 63 | |
| 64 | 64 | private volatile int waiter = 0; |
| 65 | 65 | private final Lock waitLock = new ReentrantLock(true); |
| @@ -69,10 +69,12 @@ | ||
| 69 | 69 | |
| 70 | 70 | private final AtomicInteger scheduledForCreation = new AtomicInteger(); |
| 71 | 71 | |
| 72 | - private volatile boolean isClosing; | |
| 73 | 72 | private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 74 | 73 | |
| 75 | - public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 74 | + private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING } | |
| 75 | + private volatile Phase phase = Phase.INITIALIZING; | |
| 76 | + | |
| 77 | + public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager){ | |
| 76 | 78 | assert hostDistance != HostDistance.IGNORED; |
| 77 | 79 | this.host = host; |
| 78 | 80 | this.hostDistance = hostDistance; |
| @@ -86,37 +88,70 @@ | ||
| 86 | 88 | } |
| 87 | 89 | }; |
| 88 | 90 | |
| 91 | + this.connections = new CopyOnWriteArrayList<Connection>(); | |
| 92 | + this.open = new AtomicInteger(); | |
| 93 | + } | |
| 94 | + | |
| 95 | + /** | |
| 96 | + * @param reusedConnection an existing connection (from a reconnection attempt) that we want to | |
| 97 | + * reuse as part of this pool. Might be null or already used by another | |
| 98 | + * pool. | |
| 99 | + */ | |
| 100 | + public ListenableFuture<Void> initAsync(Connection reusedConnection) { | |
| 89 | 101 | // Create initial core connections |
| 90 | - List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance)); | |
| 91 | - try { | |
| 92 | - for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) | |
| 93 | - l.add(manager.connectionFactory().open(this)); | |
| 94 | - } catch (InterruptedException e) { | |
| 95 | - Thread.currentThread().interrupt(); | |
| 96 | - // If asked to interrupt, we can skip opening core connections, the pool will still work. | |
| 97 | - // But we ignore otherwise cause I'm not sure we can do much better currently. | |
| 98 | - } catch (ConnectionException e) { | |
| 99 | - forceClose(l); | |
| 100 | - throw e; | |
| 101 | - } catch (UnsupportedProtocolVersionException e) { | |
| 102 | - forceClose(l); | |
| 103 | - throw e; | |
| 104 | - } catch (ClusterNameMismatchException e) { | |
| 105 | - forceClose(l); | |
| 106 | - throw e; | |
| 107 | - } catch (RuntimeException e) { | |
| 108 | - forceClose(l); | |
| 109 | - throw e; | |
| 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 | + Connection connection; | |
| 107 | + ListenableFuture<Void> connectionFuture; | |
| 108 | + // reuse the existing connection only once | |
| 109 | + if (reusedConnection != null && reusedConnection.setPool(this)) { | |
| 110 | + connection = reusedConnection; | |
| 111 | + connectionFuture = MoreFutures.VOID_SUCCESS; | |
| 112 | + } else { | |
| 113 | + connection = manager.connectionFactory().newConnection(this); | |
| 114 | + connectionFuture = connection.initAsync(); | |
| 115 | + } | |
| 116 | + reusedConnection = null; | |
| 117 | + connections.add(connection); | |
| 118 | + connectionFutures.add(connectionFuture); | |
| 110 | 119 | } |
| 111 | - this.connections = new CopyOnWriteArrayList<PooledConnection>(l); | |
| 112 | - this.open = new AtomicInteger(connections.size()); | |
| 113 | 120 | |
| 114 | - logger.trace("Created connection pool to host {}", host); | |
| 121 | + Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 122 | + | |
| 123 | + ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures); | |
| 124 | + | |
| 125 | + final SettableFuture<Void> initFuture = SettableFuture.create(); | |
| 126 | + Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() { | |
| 127 | + @Override | |
| 128 | + public void onSuccess(List<Void> l) { | |
| 129 | + HostConnectionPool.this.connections.addAll(connections); | |
| 130 | + open.set(l.size()); | |
| 131 | + if (isClosed()) { | |
| 132 | + initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization")); | |
| 133 | + // we're not sure if closeAsync() saw the connections, so ensure they get closed | |
| 134 | + forceClose(connections); | |
| 135 | + } else { | |
| 136 | + logger.trace("Created connection pool to host {}", host); | |
| 137 | + phase = Phase.READY; | |
| 138 | + initFuture.set(null); | |
| 139 | + } | |
| 140 | + } | |
| 141 | + | |
| 142 | + @Override | |
| 143 | + public void onFailure(Throwable t) { | |
| 144 | + phase = Phase.INIT_FAILED; | |
| 145 | + forceClose(connections); | |
| 146 | + initFuture.setException(t); | |
| 147 | + } | |
| 148 | + }, initExecutor); | |
| 149 | + return initFuture; | |
| 115 | 150 | } |
| 116 | 151 | |
| 117 | 152 | // Clean up if we got an error at construction time but still created part of the core connections |
| 118 | - private void forceClose(List<PooledConnection> l) { | |
| 119 | - for (PooledConnection connection : l) { | |
| 153 | + private void forceClose(List<Connection> connections) { | |
| 154 | + for (Connection connection : connections) { | |
| 120 | 155 | connection.closeAsync().force(); |
| 121 | 156 | } |
| 122 | 157 | } |
| @@ -125,11 +160,14 @@ | ||
| 125 | 160 | return manager.configuration().getPoolingOptions(); |
| 126 | 161 | } |
| 127 | 162 | |
| 128 | - public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 129 | - if (isClosed()) | |
| 163 | + public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 164 | + if (phase == Phase.INITIALIZING) | |
| 165 | + throw new ConnectionException(host.getSocketAddress(), "Pool is initializing."); | |
| 166 | + | |
| 167 | + if (phase != Phase.READY) | |
| 130 | 168 | // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host. |
| 131 | 169 | // That being said, maybe having a specific exception could be cleaner. |
| 132 | - throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); | |
| 170 | + throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase); | |
| 133 | 171 | |
| 134 | 172 | if (connections.isEmpty()) { |
| 135 | 173 | for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) { |
| @@ -138,15 +176,15 @@ | ||
| 138 | 176 | scheduledForCreation.incrementAndGet(); |
| 139 | 177 | manager.blockingExecutor().submit(newConnectionTask); |
| 140 | 178 | } |
| 141 | - PooledConnection c = waitForConnection(timeout, unit); | |
| 179 | + Connection c = waitForConnection(timeout, unit); | |
| 142 | 180 | totalInFlight.incrementAndGet(); |
| 143 | 181 | c.setKeyspace(manager.poolsState.keyspace); |
| 144 | 182 | return c; |
| 145 | 183 | } |
| 146 | 184 | |
| 147 | 185 | int minInFlight = Integer.MAX_VALUE; |
| 148 | - PooledConnection leastBusy = null; | |
| 149 | - for (PooledConnection connection : connections) { | |
| 186 | + Connection leastBusy = null; | |
| 187 | + for (Connection connection : connections) { | |
| 150 | 188 | int inFlight = connection.inFlight.get(); |
| 151 | 189 | if (inFlight < minInFlight) { |
| 152 | 190 | minInFlight = inFlight; |
| @@ -234,7 +272,7 @@ | ||
| 234 | 272 | } |
| 235 | 273 | } |
| 236 | 274 | |
| 237 | - private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 275 | + private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 238 | 276 | if (timeout == 0) |
| 239 | 277 | throw new TimeoutException(); |
| 240 | 278 | |
| @@ -253,8 +291,8 @@ | ||
| 253 | 291 | throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); |
| 254 | 292 | |
| 255 | 293 | int minInFlight = Integer.MAX_VALUE; |
| 256 | - PooledConnection leastBusy = null; | |
| 257 | - for (PooledConnection connection : connections) { | |
| 294 | + Connection leastBusy = null; | |
| 295 | + for (Connection connection : connections) { | |
| 258 | 296 | int inFlight = connection.inFlight.get(); |
| 259 | 297 | if (inFlight < minInFlight) { |
| 260 | 298 | minInFlight = inFlight; |
| @@ -282,7 +320,7 @@ | ||
| 282 | 320 | throw new TimeoutException(); |
| 283 | 321 | } |
| 284 | 322 | |
| 285 | - public void returnConnection(PooledConnection connection) { | |
| 323 | + public void returnConnection(Connection connection) { | |
| 286 | 324 | connection.inFlight.decrementAndGet(); |
| 287 | 325 | totalInFlight.decrementAndGet(); |
| 288 | 326 | |
| @@ -308,7 +346,7 @@ | ||
| 308 | 346 | |
| 309 | 347 | // Trash the connection and create a new one, but we don't call trashConnection |
| 310 | 348 | // directly because we want to make sure the connection is always trashed. |
| 311 | - private void replaceConnection(PooledConnection connection) { | |
| 349 | + private void replaceConnection(Connection connection) { | |
| 312 | 350 | if (!connection.state.compareAndSet(OPEN, TRASHED)) |
| 313 | 351 | return; |
| 314 | 352 | open.decrementAndGet(); |
| @@ -317,7 +355,7 @@ | ||
| 317 | 355 | doTrashConnection(connection); |
| 318 | 356 | } |
| 319 | 357 | |
| 320 | - private boolean trashConnection(PooledConnection connection) { | |
| 358 | + private boolean trashConnection(Connection connection) { | |
| 321 | 359 | if (!connection.state.compareAndSet(OPEN, TRASHED)) |
| 322 | 360 | return true; |
| 323 | 361 | |
| @@ -338,7 +376,7 @@ | ||
| 338 | 376 | return true; |
| 339 | 377 | } |
| 340 | 378 | |
| 341 | - private void doTrashConnection(PooledConnection connection) { | |
| 379 | + private void doTrashConnection(Connection connection) { | |
| 342 | 380 | connections.remove(connection); |
| 343 | 381 | trash.add(connection); |
| 344 | 382 | } |
| @@ -355,14 +393,14 @@ | ||
| 355 | 393 | break; |
| 356 | 394 | } |
| 357 | 395 | |
| 358 | - if (isClosing) { | |
| 396 | + if (phase != Phase.READY) { | |
| 359 | 397 | open.decrementAndGet(); |
| 360 | 398 | return false; |
| 361 | 399 | } |
| 362 | 400 | |
| 363 | 401 | // Now really open the connection |
| 364 | 402 | try { |
| 365 | - PooledConnection newConnection = tryResurrectFromTrash(); | |
| 403 | + Connection newConnection = tryResurrectFromTrash(); | |
| 366 | 404 | if (newConnection == null) { |
| 367 | 405 | logger.debug("Creating new connection on busy pool to {}", host); |
| 368 | 406 | newConnection = manager.connectionFactory().open(this); |
| @@ -372,7 +410,7 @@ | ||
| 372 | 410 | newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN |
| 373 | 411 | |
| 374 | 412 | // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it. |
| 375 | - if (isClosing && !newConnection.isClosed()) { | |
| 413 | + if (phase != Phase.READY && !newConnection.isClosed()) { | |
| 376 | 414 | close(newConnection); |
| 377 | 415 | open.decrementAndGet(); |
| 378 | 416 | return false; |
| @@ -406,12 +444,12 @@ | ||
| 406 | 444 | } |
| 407 | 445 | } |
| 408 | 446 | |
| 409 | - private PooledConnection tryResurrectFromTrash() { | |
| 447 | + private Connection tryResurrectFromTrash() { | |
| 410 | 448 | long highestMaxIdleTime = System.currentTimeMillis(); |
| 411 | - PooledConnection chosen = null; | |
| 449 | + Connection chosen = null; | |
| 412 | 450 | |
| 413 | 451 | while (true) { |
| 414 | - for (PooledConnection connection : trash) | |
| 452 | + for (Connection connection : trash) | |
| 415 | 453 | if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) { |
| 416 | 454 | chosen = connection; |
| 417 | 455 | highestMaxIdleTime = connection.maxIdleTime; |
| @@ -439,7 +477,7 @@ | ||
| 439 | 477 | manager.blockingExecutor().submit(newConnectionTask); |
| 440 | 478 | } |
| 441 | 479 | |
| 442 | - void replaceDefunctConnection(final PooledConnection connection) { | |
| 480 | + void replaceDefunctConnection(final Connection connection) { | |
| 443 | 481 | if (connection.state.compareAndSet(OPEN, GONE)) |
| 444 | 482 | open.decrementAndGet(); |
| 445 | 483 | if (connections.remove(connection)) |
| @@ -477,7 +515,7 @@ | ||
| 477 | 515 | if (toTrash <= 0) |
| 478 | 516 | return; |
| 479 | 517 | |
| 480 | - for (PooledConnection connection : connections) | |
| 518 | + for (Connection connection : connections) | |
| 481 | 519 | if (trashConnection(connection)) { |
| 482 | 520 | toTrash -= 1; |
| 483 | 521 | if (toTrash == 0) |
| @@ -487,7 +525,7 @@ | ||
| 487 | 525 | |
| 488 | 526 | /** Close connections that have been sitting in the trash for too long */ |
| 489 | 527 | private void cleanupTrash(long now) { |
| 490 | - for (PooledConnection connection : trash) { | |
| 528 | + for (Connection connection : trash) { | |
| 491 | 529 | if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) { |
| 492 | 530 | if (connection.inFlight.get() == 0) { |
| 493 | 531 | logger.trace("Cleaning up {}", connection); |
| @@ -517,7 +555,7 @@ | ||
| 517 | 555 | if (future != null) |
| 518 | 556 | return future; |
| 519 | 557 | |
| 520 | - isClosing = true; | |
| 558 | + phase = Phase.CLOSING; | |
| 521 | 559 | |
| 522 | 560 | // Wake up all threads that wait |
| 523 | 561 | signalAllAvailableConnection(); |
| @@ -538,13 +576,12 @@ | ||
| 538 | 576 | } |
| 539 | 577 | |
| 540 | 578 | private List<CloseFuture> discardAvailableConnections() { |
| 541 | - // This can happen if creating the connections in the constructor fails | |
| 542 | - if (connections == null) | |
| 543 | - return Lists.newArrayList(CloseFuture.immediateFuture()); | |
| 579 | + // Note: if this gets called before initialization has completed, both connections and trash will be empty, | |
| 580 | + // so this will return an empty list | |
| 544 | 581 | |
| 545 | 582 | List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size()); |
| 546 | 583 | |
| 547 | - for (final PooledConnection connection : connections) { | |
| 584 | + for (final Connection connection : connections) { | |
| 548 | 585 | CloseFuture future = connection.closeAsync(); |
| 549 | 586 | future.addListener(new Runnable() { |
| 550 | 587 | public void run() { |
| @@ -556,7 +593,7 @@ | ||
| 556 | 593 | } |
| 557 | 594 | |
| 558 | 595 | // Some connections in the trash might still be open if they hadn't reached their idle timeout |
| 559 | - for (PooledConnection connection : trash) | |
| 596 | + for (Connection connection : trash) | |
| 560 | 597 | futures.add(connection.closeAsync()); |
| 561 | 598 | |
| 562 | 599 | return futures; |
deleted driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +0 −66
| @@ -1,66 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.core; | |
| 17 | - | |
| 18 | -import java.net.InetSocketAddress; | |
| 19 | -import java.util.concurrent.atomic.AtomicReference; | |
| 20 | - | |
| 21 | -/** | |
| 22 | - * A connection that is associated to a pool. | |
| 23 | - */ | |
| 24 | -class PooledConnection extends Connection { | |
| 25 | - | |
| 26 | - final HostConnectionPool pool; | |
| 27 | - | |
| 28 | - enum State {OPEN, TRASHED, RESURRECTING, GONE } | |
| 29 | - | |
| 30 | - final AtomicReference<State> state = new AtomicReference<State>(State.OPEN); | |
| 31 | - | |
| 32 | - volatile long maxIdleTime; | |
| 33 | - | |
| 34 | - PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 35 | - super(name, address, factory); | |
| 36 | - this.pool = pool; | |
| 37 | - } | |
| 38 | - | |
| 39 | - /** | |
| 40 | - * Return the pooled connection to its pool. | |
| 41 | - * The connection should generally not be reused after that. | |
| 42 | - */ | |
| 43 | - public void release() { | |
| 44 | - // This can happen if the query to initialize the transport in the | |
| 45 | - // parent constructor times out. In that case the pool will handle | |
| 46 | - // it itself. | |
| 47 | - if (pool == null) | |
| 48 | - return; | |
| 49 | - | |
| 50 | - pool.returnConnection(this); | |
| 51 | - } | |
| 52 | - | |
| 53 | - @Override | |
| 54 | - protected void notifyOwnerWhenDefunct(boolean hostIsDown) { | |
| 55 | - // This can happen if an exception is thrown at construction time. In | |
| 56 | - // that case the pool will handle it itself. | |
| 57 | - if (pool == null) | |
| 58 | - return; | |
| 59 | - | |
| 60 | - if (hostIsDown) { | |
| 61 | - pool.closeAsync().force(); | |
| 62 | - } else { | |
| 63 | - pool.replaceDefunctConnection(this); | |
| 64 | - } | |
| 65 | - } | |
| 66 | -} |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +45 −0
| @@ -15,6 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.util.concurrent.Executor; | |
| 19 | + | |
| 20 | +import com.google.common.base.Preconditions; | |
| 21 | +import com.google.common.util.concurrent.MoreExecutors; | |
| 22 | + | |
| 18 | 23 | /** |
| 19 | 24 | * Options related to connection pooling. |
| 20 | 25 | * <p> |
| @@ -53,6 +58,8 @@ | ||
| 53 | 58 | private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 54 | 59 | private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30; |
| 55 | 60 | |
| 61 | + private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor(); | |
| 62 | + | |
| 56 | 63 | private volatile Cluster.Manager manager; |
| 57 | 64 | |
| 58 | 65 | private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 }; |
| @@ -64,6 +71,8 @@ | ||
| 64 | 71 | private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; |
| 65 | 72 | private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; |
| 66 | 73 | |
| 74 | + private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR; | |
| 75 | + | |
| 67 | 76 | public PoolingOptions() {} |
| 68 | 77 | |
| 69 | 78 | void register(Cluster.Manager manager) { |
| @@ -308,6 +317,42 @@ | ||
| 308 | 317 | return this; |
| 309 | 318 | } |
| 310 | 319 | |
| 320 | + /** | |
| 321 | + * Returns the executor to use for connection initialization. | |
| 322 | + * | |
| 323 | + * @return the executor. | |
| 324 | + * @see #setInitializationExecutor(java.util.concurrent.Executor) | |
| 325 | + */ | |
| 326 | + public Executor getInitializationExecutor() { | |
| 327 | + return initializationExecutor; | |
| 328 | + } | |
| 329 | + | |
| 330 | + /** | |
| 331 | + * Sets the executor to use for connection initialization. | |
| 332 | + * <p> | |
| 333 | + * Connections are open in a completely asynchronous manner. Since initializing the transport | |
| 334 | + * requires separate CQL queries, the futures representing the completion of these queries are | |
| 335 | + * transformed and chained. This executor is where these transformations happen. | |
| 336 | + * <p> | |
| 337 | + * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to | |
| 338 | + * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations | |
| 339 | + * on the network I/O threads; this is fine if the transformations are fast and not I/O bound | |
| 340 | + * (which is the case by default). | |
| 341 | + * One reason why you might want to provide a custom executor is if you use authentication with | |
| 342 | + * a custom {@link com.datastax.driver.core.Authenticator} implementation that performs blocking | |
| 343 | + * calls. | |
| 344 | + * | |
| 345 | + * @param initializationExecutor the executor to use | |
| 346 | + * @return this {@code PoolingOptions} | |
| 347 | + * | |
| 348 | + * @throws java.lang.NullPointerException if the executor is null | |
| 349 | + */ | |
| 350 | + public PoolingOptions setInitializationExecutor(Executor initializationExecutor) { | |
| 351 | + Preconditions.checkNotNull(initializationExecutor); | |
| 352 | + this.initializationExecutor = initializationExecutor; | |
| 353 | + return this; | |
| 354 | + } | |
| 355 | + | |
| 311 | 356 | /** |
| 312 | 357 | * Requests the driver to re-evaluate the {@link HostDistance} (through the configured |
| 313 | 358 | * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −9
| @@ -111,7 +111,7 @@ | ||
| 111 | 111 | if (currentPool == null || currentPool.isClosed()) |
| 112 | 112 | return false; |
| 113 | 113 | |
| 114 | - PooledConnection connection = null; | |
| 114 | + Connection connection = null; | |
| 115 | 115 | try { |
| 116 | 116 | connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS); |
| 117 | 117 | if (current != null) { |
| @@ -157,8 +157,7 @@ | ||
| 157 | 157 | while (true) { |
| 158 | 158 | QueryState previous = queryStateRef.get(); |
| 159 | 159 | if (previous.isCancelled()) { |
| 160 | - if (connection instanceof PooledConnection) | |
| 161 | - ((PooledConnection)connection).release(); | |
| 160 | + connection.release(); | |
| 162 | 161 | return; |
| 163 | 162 | } |
| 164 | 163 | if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext())) |
| @@ -472,8 +471,7 @@ | ||
| 472 | 471 | exceptionToReport = e; |
| 473 | 472 | setFinalException(connection, e); |
| 474 | 473 | } finally { |
| 475 | - if (releaseConnection && connection instanceof PooledConnection) | |
| 476 | - ((PooledConnection)connection).release(); | |
| 474 | + connection.release(); | |
| 477 | 475 | if (queriedHost != null && statement != Statement.DEFAULT) |
| 478 | 476 | manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency); |
| 479 | 477 | } |
| @@ -502,8 +500,7 @@ | ||
| 502 | 500 | return; |
| 503 | 501 | } |
| 504 | 502 | |
| 505 | - if (connection instanceof PooledConnection) | |
| 506 | - ((PooledConnection)connection).release(); | |
| 503 | + connection.release(); | |
| 507 | 504 | |
| 508 | 505 | // TODO should we check the response ? |
| 509 | 506 | switch (response.type) { |
| @@ -562,8 +559,7 @@ | ||
| 562 | 559 | |
| 563 | 560 | Host queriedHost = current; |
| 564 | 561 | try { |
| 565 | - if (connection instanceof PooledConnection) | |
| 566 | - ((PooledConnection)connection).release(); | |
| 562 | + connection.release(); | |
| 567 | 563 | |
| 568 | 564 | if (exception instanceof ConnectionException) { |
| 569 | 565 | if (metricsEnabled()) |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +124 −116
| @@ -20,10 +20,10 @@ | ||
| 20 | 20 | import java.util.*; |
| 21 | 21 | import java.util.concurrent.*; |
| 22 | 22 | import java.util.concurrent.atomic.AtomicReference; |
| 23 | -import java.util.concurrent.locks.Lock; | |
| 24 | 23 | |
| 25 | 24 | import com.google.common.base.Function; |
| 26 | 25 | import com.google.common.collect.ImmutableList; |
| 26 | +import com.google.common.collect.Lists; | |
| 27 | 27 | import com.google.common.util.concurrent.*; |
| 28 | 28 | import org.slf4j.Logger; |
| 29 | 29 | import org.slf4j.LoggerFactory; |
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 34 | 34 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| 35 | 35 | import com.datastax.driver.core.policies.ReconnectionPolicy; |
| 36 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 36 | 37 | |
| 37 | 38 | /** |
| 38 | 39 | * Driver implementation of the Session interface. |
| @@ -46,8 +47,6 @@ | ||
| 46 | 47 | final HostConnectionPool.PoolState poolsState; |
| 47 | 48 | final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 48 | 49 | |
| 49 | - private final Striped<Lock> poolCreationLocks = Striped.lazyWeakLock(5); | |
| 50 | - | |
| 51 | 50 | private volatile boolean isInit; |
| 52 | 51 | private volatile boolean isClosing; |
| 53 | 52 | |
| @@ -67,50 +66,28 @@ | ||
| 67 | 66 | |
| 68 | 67 | // Create pools to initial nodes (and wait for them to be created) |
| 69 | 68 | Collection<Host> hosts = cluster.getMetadata().allHosts(); |
| 70 | - if (cluster.manager.sessions.size() == 1) { | |
| 71 | - // We only do it in parallel if this is the first session (meaning that the cluster just initialized). | |
| 72 | - createPoolsInParallel(hosts); | |
| 73 | - } else { | |
| 74 | - // Otherwise, we don't want to fill executor() because this is also where up/down notifications are processed, | |
| 75 | - // it's important that existing sessions get them in a timely manner. So we create the pools one by one: | |
| 76 | - createPoolsSequentially(hosts); | |
| 77 | - } | |
| 69 | + createPoolsInParallel(hosts); | |
| 78 | 70 | |
| 79 | 71 | isInit = true; |
| 80 | - updateCreatedPools(executor()); | |
| 72 | + updateCreatedPools(); | |
| 81 | 73 | return this; |
| 82 | 74 | } |
| 83 | 75 | |
| 84 | 76 | private void createPoolsInParallel(Collection<Host> hosts) { |
| 85 | - List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size()); | |
| 77 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size()); | |
| 86 | 78 | for (Host host : hosts) |
| 87 | 79 | if (host.state != Host.State.DOWN) |
| 88 | - futures.add(maybeAddPool(host, executor())); | |
| 89 | - ListenableFuture<List<Boolean>> f = Futures.allAsList(futures); | |
| 80 | + futures.add(maybeAddPool(host, null)); | |
| 90 | 81 | try { |
| 91 | - f.get(); | |
| 82 | + Futures.successfulAsList(futures).get(); | |
| 92 | 83 | } catch (ExecutionException e) { |
| 93 | - // This is not supposed to happen | |
| 94 | - throw new DriverInternalError(e); | |
| 84 | + // Won't happen because we used successfulAsList | |
| 85 | + // And if a particular pool failed, maybeAddPool already handled it | |
| 95 | 86 | } catch (InterruptedException e) { |
| 96 | 87 | Thread.currentThread().interrupt(); |
| 97 | 88 | } |
| 98 | 89 | } |
| 99 | 90 | |
| 100 | - private void createPoolsSequentially(Collection<Host> hosts) { | |
| 101 | - for (Host host : cluster.getMetadata().allHosts()) { | |
| 102 | - try { | |
| 103 | - if (host.state != Host.State.DOWN) | |
| 104 | - maybeAddPool(host, executor()).get(); | |
| 105 | - } catch (ExecutionException e) { | |
| 106 | - // This is not supposed to happen | |
| 107 | - throw new DriverInternalError(e); | |
| 108 | - } catch (InterruptedException e) { | |
| 109 | - Thread.currentThread().interrupt(); | |
| 110 | - } | |
| 111 | - } | |
| 112 | - } | |
| 113 | - | |
| 114 | 91 | public String getLoggedKeyspace() { |
| 115 | 92 | return poolsState.keyspace; |
| 116 | 93 | } |
| @@ -215,77 +192,94 @@ | ||
| 215 | 192 | } |
| 216 | 193 | |
| 217 | 194 | // Returns whether there was problem creating the pool |
| 218 | - ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) { | |
| 195 | + ListenableFuture<Boolean> forceRenewPool(final Host host, Connection reusedConnection) { | |
| 219 | 196 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 220 | 197 | if (distance == HostDistance.IGNORED) |
| 221 | 198 | return Futures.immediateFuture(true); |
| 222 | 199 | |
| 223 | - // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously. | |
| 224 | - return executor.submit(new Callable<Boolean>() { | |
| 225 | - public Boolean call() { | |
| 226 | - while (true) { | |
| 227 | - try { | |
| 228 | - if (isClosing) | |
| 229 | - return true; | |
| 230 | - | |
| 231 | - HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this); | |
| 232 | - HostConnectionPool previous = pools.put(host, newPool); | |
| 233 | - if (previous == null) { | |
| 234 | - logger.debug("Added connection pool for {}", host); | |
| 235 | - } else { | |
| 236 | - logger.debug("Renewed connection pool for {}", host); | |
| 237 | - previous.closeAsync(); | |
| 238 | - } | |
| 200 | + if (isClosing) | |
| 201 | + return Futures.immediateFuture(false); | |
| 202 | + | |
| 203 | + final HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this); | |
| 204 | + ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection); | |
| 205 | + | |
| 206 | + final SettableFuture<Boolean> future = SettableFuture.create(); | |
| 207 | + | |
| 208 | + Futures.addCallback(poolInitFuture, new FutureCallback<Void>() { | |
| 209 | + @Override | |
| 210 | + public void onSuccess(Void result) { | |
| 211 | + // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 212 | + HostConnectionPool previous = pools.put(host, newPool); | |
| 213 | + if (previous == null) { | |
| 214 | + logger.debug("Added connection pool for {}", host); | |
| 215 | + } else { | |
| 216 | + logger.debug("Renewed connection pool for {}", host); | |
| 217 | + previous.closeAsync(); | |
| 218 | + } | |
| 239 | 219 | |
| 240 | - // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 241 | - if (isClosing) | |
| 242 | - newPool.closeAsync(); | |
| 243 | - | |
| 244 | - return true; | |
| 245 | - } catch (Exception e) { | |
| 246 | - logger.error("Error creating pool to " + host, e); | |
| 247 | - return false; | |
| 248 | - } | |
| 220 | + // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 221 | + if (isClosing) { | |
| 222 | + newPool.closeAsync(); | |
| 223 | + pools.remove(host); | |
| 224 | + future.set(false); | |
| 225 | + } else { | |
| 226 | + future.set(true); | |
| 249 | 227 | } |
| 250 | 228 | } |
| 229 | + | |
| 230 | + @Override | |
| 231 | + public void onFailure(Throwable t) { | |
| 232 | + logger.error("Error creating pool to " + host, t); | |
| 233 | + future.set(false); | |
| 234 | + } | |
| 251 | 235 | }); |
| 236 | + | |
| 237 | + return future; | |
| 252 | 238 | } |
| 253 | 239 | |
| 254 | - // Replace pool for a given only if it's the given previous value (which can be null) | |
| 255 | - // Note that the goal of this function is to make sure that 2 concurrent thread calling | |
| 256 | - // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools | |
| 257 | - // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we | |
| 258 | - // want to avoid | |
| 259 | - private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 240 | + // Replace pool for a given host only if it's the given previous value (which can be null) | |
| 241 | + // This returns a future if the replacement was successful, or null if we raced. | |
| 242 | + private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous, Connection reusedConnection) { | |
| 260 | 243 | if (isClosing) |
| 261 | - return true; | |
| 262 | - | |
| 263 | - Lock l = poolCreationLocks.get(host); | |
| 264 | - l.lock(); | |
| 265 | - try { | |
| 266 | - HostConnectionPool previous = pools.get(host); | |
| 267 | - if (previous != condition) | |
| 268 | - return false; | |
| 269 | - | |
| 270 | - HostConnectionPool newPool = new HostConnectionPool(host, distance, this); | |
| 271 | - previous = pools.put(host, newPool); | |
| 272 | - if (previous != null && !previous.isClosed()) { | |
| 244 | + return MoreFutures.VOID_SUCCESS; | |
| 245 | + | |
| 246 | + final HostConnectionPool newPool = new HostConnectionPool(host, distance, this); | |
| 247 | + if (previous == null) { | |
| 248 | + if (pools.putIfAbsent(host, newPool) != null) { | |
| 249 | + return null; | |
| 250 | + } | |
| 251 | + } else { | |
| 252 | + if (!pools.replace(host, previous, newPool)) { | |
| 253 | + return null; | |
| 254 | + } | |
| 255 | + if (!previous.isClosed()) { | |
| 273 | 256 | logger.warn("Replacing a pool that wasn't closed. Closing it now, but this was not expected."); |
| 274 | 257 | previous.closeAsync(); |
| 275 | 258 | } |
| 259 | + } | |
| 276 | 260 | |
| 277 | - // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 278 | - if (isClosing) | |
| 279 | - newPool.closeAsync(); | |
| 261 | + ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection); | |
| 262 | + | |
| 263 | + Futures.addCallback(poolInitFuture, new FutureCallback<Void>() { | |
| 264 | + @Override | |
| 265 | + public void onSuccess(Void result) { | |
| 266 | + // If we raced with a session shutdown, ensure that the pool will be closed. | |
| 267 | + if (isClosing) { | |
| 268 | + newPool.closeAsync(); | |
| 269 | + pools.remove(host); | |
| 270 | + } | |
| 271 | + } | |
| 280 | 272 | |
| 281 | - return true; | |
| 282 | - } finally { | |
| 283 | - l.unlock(); | |
| 284 | - } | |
| 273 | + @Override | |
| 274 | + public void onFailure(Throwable t) { | |
| 275 | + pools.remove(host); | |
| 276 | + } | |
| 277 | + }); | |
| 278 | + return poolInitFuture; | |
| 285 | 279 | } |
| 286 | 280 | |
| 287 | 281 | // Returns whether there was problem creating the pool |
| 288 | - ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) { | |
| 282 | + ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) { | |
| 289 | 283 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 290 | 284 | if (distance == HostDistance.IGNORED) |
| 291 | 285 | return Futures.immediateFuture(true); |
| @@ -294,34 +288,39 @@ | ||
| 294 | 288 | if (previous != null && !previous.isClosed()) |
| 295 | 289 | return Futures.immediateFuture(true); |
| 296 | 290 | |
| 297 | - // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously. | |
| 298 | - return executor.submit(new Callable<Boolean>() { | |
| 299 | - public Boolean call() { | |
| 300 | - try { | |
| 301 | - while (true) { | |
| 302 | - HostConnectionPool previous = pools.get(host); | |
| 303 | - if (previous != null && !previous.isClosed()) | |
| 304 | - return true; | |
| 305 | - | |
| 306 | - if (replacePool(host, distance, previous)) { | |
| 307 | - logger.debug("Added connection pool for {}", host); | |
| 308 | - return true; | |
| 291 | + while (true) { | |
| 292 | + previous = pools.get(host); | |
| 293 | + if (previous != null && !previous.isClosed()) | |
| 294 | + return Futures.immediateFuture(true); | |
| 295 | + | |
| 296 | + final SettableFuture<Boolean> future = SettableFuture.create(); | |
| 297 | + ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous, reusedConnection); | |
| 298 | + if (newPoolInit != null) { | |
| 299 | + Futures.addCallback(newPoolInit, new FutureCallback<Void>() { | |
| 300 | + @Override | |
| 301 | + public void onSuccess(Void result) { | |
| 302 | + logger.debug("Added connection pool for {}", host); | |
| 303 | + future.set(true); | |
| 304 | + } | |
| 305 | + | |
| 306 | + @Override | |
| 307 | + public void onFailure(Throwable t) { | |
| 308 | + if (t instanceof UnsupportedProtocolVersionException) { | |
| 309 | + cluster.manager.logUnsupportedVersionProtocol(host); | |
| 310 | + cluster.manager.triggerOnDown(host, false); | |
| 311 | + } else if (t instanceof ClusterNameMismatchException) { | |
| 312 | + ClusterNameMismatchException e = (ClusterNameMismatchException)t; | |
| 313 | + cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 314 | + cluster.manager.triggerOnDown(host, false); | |
| 315 | + } else { | |
| 316 | + logger.error("Error creating pool to " + host, t); | |
| 309 | 317 | } |
| 318 | + future.set(false); | |
| 310 | 319 | } |
| 311 | - } catch (UnsupportedProtocolVersionException e) { | |
| 312 | - cluster.manager.logUnsupportedVersionProtocol(host); | |
| 313 | - cluster.manager.triggerOnDown(host, false); | |
| 314 | - return false; | |
| 315 | - } catch (ClusterNameMismatchException e) { | |
| 316 | - cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 317 | - cluster.manager.triggerOnDown(host, false); | |
| 318 | - return false; | |
| 319 | - } catch (Exception e) { | |
| 320 | - logger.error("Error creating pool to " + host, e); | |
| 321 | - return false; | |
| 322 | - } | |
| 320 | + }); | |
| 321 | + return future; | |
| 323 | 322 | } |
| 324 | - }); | |
| 323 | + } | |
| 325 | 324 | } |
| 326 | 325 | |
| 327 | 326 | CloseFuture removePool(Host host) { |
| @@ -340,7 +339,7 @@ | ||
| 340 | 339 | * This method ensures that all hosts for which a pool should exist |
| 341 | 340 | * have one, and hosts that shouldn't don't. |
| 342 | 341 | */ |
| 343 | - void updateCreatedPools(ListeningExecutorService executor) { | |
| 342 | + void updateCreatedPools() { | |
| 344 | 343 | // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if |
| 345 | 344 | // we execute the code below we would try to create their pool over and over again. |
| 346 | 345 | // It's called explicitly at the end of init(), once isInit has been set to true. |
| @@ -359,7 +358,7 @@ | ||
| 359 | 358 | |
| 360 | 359 | if (pool == null) { |
| 361 | 360 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 362 | - poolCreationFutures.add(maybeAddPool(h, executor)); | |
| 361 | + poolCreationFutures.add(maybeAddPool(h, null)); | |
| 363 | 362 | } else if (dist != pool.hostDistance) { |
| 364 | 363 | if (dist == HostDistance.IGNORED) { |
| 365 | 364 | toRemove.add(h); |
| @@ -371,7 +370,12 @@ | ||
| 371 | 370 | } |
| 372 | 371 | |
| 373 | 372 | // Wait pool creation before removing, so we don't lose connectivity |
| 374 | - Futures.allAsList(poolCreationFutures).get(); | |
| 373 | + try { | |
| 374 | + Futures.successfulAsList(poolCreationFutures).get(); | |
| 375 | + } catch (ExecutionException e) { | |
| 376 | + // Won't happen because we used successfulAsList | |
| 377 | + // And if a particular pool failed, maybeAddPool already handled it | |
| 378 | + } | |
| 375 | 379 | |
| 376 | 380 | List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size()); |
| 377 | 381 | for (Host h : toRemove) |
| @@ -385,14 +389,18 @@ | ||
| 385 | 389 | } |
| 386 | 390 | } |
| 387 | 391 | |
| 388 | - void updateCreatedPools(Host h, ListeningExecutorService executor) { | |
| 392 | + void updateCreatedPools(Host h) { | |
| 389 | 393 | HostDistance dist = loadBalancingPolicy().distance(h); |
| 390 | 394 | HostConnectionPool pool = pools.get(h); |
| 391 | 395 | |
| 392 | 396 | try { |
| 393 | 397 | if (pool == null) { |
| 394 | 398 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 395 | - maybeAddPool(h, executor).get(); | |
| 399 | + try { | |
| 400 | + maybeAddPool(h, null).get(); | |
| 401 | + } catch (ExecutionException e) { | |
| 402 | + // Ignore, maybeAddPool has already handled the error | |
| 403 | + } | |
| 396 | 404 | } else if (dist != pool.hostDistance) { |
| 397 | 405 | if (dist == HostDistance.IGNORED) { |
| 398 | 406 | removePool(h).get(); |
| @@ -412,7 +420,7 @@ | ||
| 412 | 420 | // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary |
| 413 | 421 | // since updateCreatedPools should take care of it. But better protect against non well behaving policies. |
| 414 | 422 | removePool(host).force().get(); |
| 415 | - updateCreatedPools(MoreExecutors.sameThreadExecutor()); | |
| 423 | + updateCreatedPools(); | |
| 416 | 424 | } |
| 417 | 425 | |
| 418 | 426 | void onSuspected(Host host) { |
| @@ -532,7 +540,7 @@ | ||
| 532 | 540 | |
| 533 | 541 | // Let's not wait too long if we can't get a connection. Things |
| 534 | 542 | // will fix themselves once the user tries a query anyway. |
| 535 | - PooledConnection c = null; | |
| 543 | + Connection c = null; | |
| 536 | 544 | boolean timedOut = false; |
| 537 | 545 | try { |
| 538 | 546 | c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS); |
added driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java +46 −0
| @@ -0,0 +1,46 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.utils; | |
| 17 | + | |
| 18 | +import com.google.common.util.concurrent.FutureCallback; | |
| 19 | +import com.google.common.util.concurrent.Futures; | |
| 20 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * Helpers to work with Guava's {@link ListenableFuture}. | |
| 24 | + */ | |
| 25 | +public class MoreFutures { | |
| 26 | + /** | |
| 27 | + * An immediate successful {@code ListenableFuture<Void>}. | |
| 28 | + */ | |
| 29 | + public static final ListenableFuture<Void> VOID_SUCCESS = Futures.immediateFuture(null); | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * A {@link FutureCallback} that does nothing on failure. | |
| 33 | + */ | |
| 34 | + public static abstract class SuccessCallback<V> implements FutureCallback<V> { | |
| 35 | + @Override | |
| 36 | + public void onFailure(Throwable t) { /* nothing */ } | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * A {@link FutureCallback} that does nothing on success. | |
| 41 | + */ | |
| 42 | + public static abstract class FailureCallback<V> implements FutureCallback<V> { | |
| 43 | + @Override | |
| 44 | + public void onSuccess(V result) { /* nothing */ } | |
| 45 | + } | |
| 46 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +1 −1
| @@ -489,7 +489,7 @@ | ||
| 489 | 489 | |
| 490 | 490 | ports = new int[5]; |
| 491 | 491 | for (int i = 0; i < 5; i++) { |
| 492 | - ports[i] = TestUtils.findAvailablePort(10000 + i); | |
| 492 | + ports[i] = TestUtils.findAvailablePort(11000 + i); | |
| 493 | 493 | } |
| 494 | 494 | |
| 495 | 495 | ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4]); |
added driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +228 −0
| @@ -0,0 +1,228 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.utils.SocketChannelMonitor; | |
| 19 | +import com.google.common.collect.Lists; | |
| 20 | +import org.slf4j.Logger; | |
| 21 | +import org.slf4j.LoggerFactory; | |
| 22 | +import org.testng.annotations.Test; | |
| 23 | + | |
| 24 | +import java.net.InetSocketAddress; | |
| 25 | +import java.util.ArrayList; | |
| 26 | +import java.util.Collection; | |
| 27 | +import java.util.Collections; | |
| 28 | +import java.util.List; | |
| 29 | +import java.util.concurrent.*; | |
| 30 | + | |
| 31 | +import static org.testng.Assert.assertEquals; | |
| 32 | + | |
| 33 | +public class ClusterStressTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 34 | + private static final Logger logger = LoggerFactory.getLogger(ClusterStressTest.class); | |
| 35 | + | |
| 36 | + private ExecutorService executorService; | |
| 37 | + | |
| 38 | + public ClusterStressTest() { | |
| 39 | + // 8 threads should be enough so that we stress the driver and not the OS thread scheduler | |
| 40 | + executorService = Executors.newFixedThreadPool(8); | |
| 41 | + } | |
| 42 | + | |
| 43 | + @Override | |
| 44 | + protected Collection<String> getTableDefinitions() { | |
| 45 | + return new ArrayList<String>(0); | |
| 46 | + } | |
| 47 | + | |
| 48 | + @Test(groups = "long") | |
| 49 | + public void clusters_should_not_leak_connections() { | |
| 50 | + int numberOfClusters = 10; | |
| 51 | + int numberOfIterations = 500; | |
| 52 | + for (int i = 1; i < numberOfIterations; i++) { | |
| 53 | + logger.info("On iteration {}/{}.", i, numberOfIterations); | |
| 54 | + logger.info("Creating {} clusters", numberOfClusters); | |
| 55 | + List<CreateClusterAndCheckConnections> actions = | |
| 56 | + waitForCreates(createClustersConcurrently(numberOfClusters)); | |
| 57 | + waitForCloses(closeClustersConcurrently(actions)); | |
| 58 | + logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size()); | |
| 59 | + } | |
| 60 | + } | |
| 61 | + | |
| 62 | + private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters) { | |
| 63 | + final CountDownLatch countDownLatch = new CountDownLatch(1); | |
| 64 | + return createClustersConcurrently(numberOfClusters, countDownLatch); | |
| 65 | + } | |
| 66 | + | |
| 67 | + private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters, | |
| 68 | + CountDownLatch countDownLatch) { | |
| 69 | + List<Future<CreateClusterAndCheckConnections>> clusterFutures = | |
| 70 | + Lists.newArrayListWithCapacity(numberOfClusters); | |
| 71 | + for (int i = 0; i < numberOfClusters; i++) { | |
| 72 | + clusterFutures.add(executorService.submit(new CreateClusterAndCheckConnections(countDownLatch))); | |
| 73 | + } | |
| 74 | + countDownLatch.countDown(); | |
| 75 | + return clusterFutures; | |
| 76 | + } | |
| 77 | + | |
| 78 | + private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions) { | |
| 79 | + final CountDownLatch countDownLatch = new CountDownLatch(1); | |
| 80 | + return closeClustersConcurrently(actions, countDownLatch); | |
| 81 | + } | |
| 82 | + | |
| 83 | + private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions, | |
| 84 | + CountDownLatch startSignal) { | |
| 85 | + List<Future<Void>> closeFutures = Lists.newArrayListWithCapacity(actions.size()); | |
| 86 | + for (CreateClusterAndCheckConnections action : actions) { | |
| 87 | + closeFutures.add(executorService.submit(new CloseCluster(action.cluster, action.channelMonitor, | |
| 88 | + startSignal))); | |
| 89 | + } | |
| 90 | + startSignal.countDown(); | |
| 91 | + return closeFutures; | |
| 92 | + } | |
| 93 | + | |
| 94 | + private List<CreateClusterAndCheckConnections> waitForCreates( | |
| 95 | + List<Future<CreateClusterAndCheckConnections>> futures) { | |
| 96 | + List<CreateClusterAndCheckConnections> actions = Lists.newArrayListWithCapacity(futures.size()); | |
| 97 | + // If an error occurs, we will abort the test, but we still want to close all the clusters | |
| 98 | + // that were opened successfully, so we iterate over the whole list no matter what. | |
| 99 | + AssertionError error = null; | |
| 100 | + for (Future<CreateClusterAndCheckConnections> future : futures) { | |
| 101 | + try { | |
| 102 | + actions.add(future.get()); | |
| 103 | + } catch (InterruptedException e) { | |
| 104 | + Thread.currentThread().interrupt(); | |
| 105 | + if (error == null) | |
| 106 | + error = assertionError("Interrupted while waiting for future creation", e); | |
| 107 | + } catch (ExecutionException e) { | |
| 108 | + if (error == null) { | |
| 109 | + Throwable cause = e.getCause(); | |
| 110 | + if (cause instanceof AssertionError) | |
| 111 | + error = (AssertionError)cause; | |
| 112 | + else | |
| 113 | + error = assertionError("Error while creating a cluster", cause); | |
| 114 | + } | |
| 115 | + } | |
| 116 | + } | |
| 117 | + if (error != null) { | |
| 118 | + for (CreateClusterAndCheckConnections action : actions) | |
| 119 | + action.cluster.close(); | |
| 120 | + throw error; | |
| 121 | + } else | |
| 122 | + return actions; | |
| 123 | + } | |
| 124 | + | |
| 125 | + private List<Void> waitForCloses(List<Future<Void>> futures) { | |
| 126 | + List<Void> result = new ArrayList<Void>(futures.size()); | |
| 127 | + AssertionError error = null; | |
| 128 | + for (Future<Void> future : futures) { | |
| 129 | + try { | |
| 130 | + result.add(future.get()); | |
| 131 | + } catch (InterruptedException e) { | |
| 132 | + Thread.currentThread().interrupt(); | |
| 133 | + if (error == null) | |
| 134 | + error = assertionError("Interrupted while waiting for future", e); | |
| 135 | + } catch (ExecutionException e) { | |
| 136 | + if (error == null) { | |
| 137 | + Throwable cause = e.getCause(); | |
| 138 | + if (cause instanceof AssertionError) | |
| 139 | + error = (AssertionError)cause; | |
| 140 | + else | |
| 141 | + error = assertionError("Error while closing a cluster", cause); | |
| 142 | + } | |
| 143 | + } | |
| 144 | + } | |
| 145 | + if (error != null) | |
| 146 | + throw error; | |
| 147 | + else | |
| 148 | + return result; | |
| 149 | + } | |
| 150 | + | |
| 151 | + private static class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> { | |
| 152 | + private final CountDownLatch startSignal; | |
| 153 | + private final Cluster cluster; | |
| 154 | + private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); | |
| 155 | + private final List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress); | |
| 156 | + | |
| 157 | + CreateClusterAndCheckConnections(CountDownLatch startSignal) { | |
| 158 | + this.startSignal = startSignal; | |
| 159 | + this.cluster = Cluster.builder().addContactPointsWithPorts(contactPoints) | |
| 160 | + .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) | |
| 161 | + .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 162 | + } | |
| 163 | + | |
| 164 | + @Override | |
| 165 | + public CreateClusterAndCheckConnections call() throws Exception { | |
| 166 | + startSignal.await(); | |
| 167 | + | |
| 168 | + try { | |
| 169 | + // There should be 1 control connection after initializing. | |
| 170 | + cluster.init(); | |
| 171 | + assertEquals(cluster.manager.sessions.size(), 0); | |
| 172 | + assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 173 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 174 | + | |
| 175 | + // The first session initializes the cluster and its control connection | |
| 176 | + Session session = cluster.connect(); | |
| 177 | + assertEquals(cluster.manager.sessions.size(), 1); | |
| 178 | + assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster)); | |
| 179 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster)); | |
| 180 | + | |
| 181 | + // Closing the session keeps the control connection opened | |
| 182 | + session.close(); | |
| 183 | + assertEquals(cluster.manager.sessions.size(), 0); | |
| 184 | + assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 185 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 186 | + | |
| 187 | + return this; | |
| 188 | + } catch (AssertionError e) { | |
| 189 | + // If an assertion fails, close the cluster now, because it's the last time we | |
| 190 | + // have a reference to it. | |
| 191 | + cluster.close(); | |
| 192 | + throw e; | |
| 193 | + } finally { | |
| 194 | + channelMonitor.stop(); | |
| 195 | + } | |
| 196 | + } | |
| 197 | + } | |
| 198 | + | |
| 199 | + private static class CloseCluster implements Callable<Void> { | |
| 200 | + private final Cluster cluster; | |
| 201 | + private final SocketChannelMonitor channelMonitor; | |
| 202 | + private final CountDownLatch startSignal; | |
| 203 | + | |
| 204 | + CloseCluster(Cluster cluster, SocketChannelMonitor channelMonitor, CountDownLatch startSignal) { | |
| 205 | + this.cluster = cluster; | |
| 206 | + this.channelMonitor = channelMonitor; | |
| 207 | + this.startSignal = startSignal; | |
| 208 | + } | |
| 209 | + | |
| 210 | + @Override | |
| 211 | + public Void call() throws Exception { | |
| 212 | + startSignal.await(); | |
| 213 | + | |
| 214 | + cluster.close(); | |
| 215 | + assertEquals(cluster.manager.sessions.size(), 0); | |
| 216 | + assertEquals(channelMonitor.openChannels(Collections.singletonList(hostAddress)).size(), 0); | |
| 217 | + channelMonitor.stop(); | |
| 218 | + | |
| 219 | + return null; | |
| 220 | + } | |
| 221 | + } | |
| 222 | + | |
| 223 | + private static AssertionError assertionError(String message, Throwable cause) { | |
| 224 | + AssertionError error = new AssertionError(message); | |
| 225 | + error.initCause(cause); | |
| 226 | + return error; | |
| 227 | + } | |
| 228 | +} | |
| No newline at the end of the file |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +14 −14
| @@ -56,10 +56,10 @@ | ||
| 56 | 56 | HostConnectionPool pool = createPool(2, 2); |
| 57 | 57 | |
| 58 | 58 | assertThat(pool.connections.size()).isEqualTo(2); |
| 59 | - List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections); | |
| 59 | + List<Connection> coreConnections = Lists.newArrayList(pool.connections); | |
| 60 | 60 | |
| 61 | 61 | for (int i = 0; i < 256; i++) { |
| 62 | - PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 62 | + Connection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 63 | 63 | assertThat(coreConnections).contains(connection); |
| 64 | 64 | } |
| 65 | 65 | |
| @@ -85,17 +85,17 @@ | ||
| 85 | 85 | HostConnectionPool pool = createPool(1, 2); |
| 86 | 86 | |
| 87 | 87 | assertThat(pool.connections.size()).isEqualTo(1); |
| 88 | - List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections); | |
| 88 | + List<Connection> coreConnections = Lists.newArrayList(pool.connections); | |
| 89 | 89 | |
| 90 | 90 | // |
| 91 | 91 | for (int i = 0; i < 128; i++) { |
| 92 | - PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 92 | + Connection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 93 | 93 | assertThat(coreConnections).contains(connection); |
| 94 | 94 | } |
| 95 | 95 | |
| 96 | 96 | // Borrow more and ensure the connection returned is a non-core connection. |
| 97 | 97 | for (int i = 0; i < 128; i++) { |
| 98 | - PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 98 | + Connection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 99 | 99 | assertThat(coreConnections).doesNotContain(connection); |
| 100 | 100 | } |
| 101 | 101 | |
| @@ -121,7 +121,7 @@ | ||
| 121 | 121 | .setIdleTimeoutSeconds(20); |
| 122 | 122 | |
| 123 | 123 | HostConnectionPool pool = createPool(1, 2); |
| 124 | - PooledConnection core = pool.connections.get(0); | |
| 124 | + Connection core = pool.connections.get(0); | |
| 125 | 125 | |
| 126 | 126 | // Fill core connection |
| 127 | 127 | for (int i = 0; i < 128; i++) |
| @@ -148,14 +148,14 @@ | ||
| 148 | 148 | .setIdleTimeoutSeconds(20); |
| 149 | 149 | |
| 150 | 150 | HostConnectionPool pool = createPool(1, 2); |
| 151 | - PooledConnection connection1 = pool.connections.get(0); | |
| 151 | + Connection connection1 = pool.connections.get(0); | |
| 152 | 152 | |
| 153 | 153 | for (int i = 0; i < 101; i++) |
| 154 | 154 | assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1); |
| 155 | 155 | |
| 156 | 156 | TimeUnit.MILLISECONDS.sleep(100); |
| 157 | 157 | assertThat(pool.connections).hasSize(2); |
| 158 | - PooledConnection connection2 = pool.connections.get(1); | |
| 158 | + Connection connection2 = pool.connections.get(1); | |
| 159 | 159 | |
| 160 | 160 | assertThat(connection1.inFlight.get()).isEqualTo(101); |
| 161 | 161 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| @@ -205,14 +205,14 @@ | ||
| 205 | 205 | .setIdleTimeoutSeconds(20); |
| 206 | 206 | |
| 207 | 207 | HostConnectionPool pool = createPool(1, 2); |
| 208 | - PooledConnection connection1 = pool.connections.get(0); | |
| 208 | + Connection connection1 = pool.connections.get(0); | |
| 209 | 209 | |
| 210 | 210 | for (int i = 0; i < 101; i++) |
| 211 | 211 | assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1); |
| 212 | 212 | |
| 213 | 213 | TimeUnit.MILLISECONDS.sleep(100); |
| 214 | 214 | assertThat(pool.connections).hasSize(2); |
| 215 | - PooledConnection connection2 = pool.connections.get(1); | |
| 215 | + Connection connection2 = pool.connections.get(1); | |
| 216 | 216 | |
| 217 | 217 | assertThat(connection1.inFlight.get()).isEqualTo(101); |
| 218 | 218 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| @@ -247,7 +247,7 @@ | ||
| 247 | 247 | TimeUnit.MILLISECONDS.sleep(100); |
| 248 | 248 | |
| 249 | 249 | // Borrow again to get the new connection |
| 250 | - PooledConnection connection3 = pool.borrowConnection(100, MILLISECONDS); | |
| 250 | + Connection connection3 = pool.borrowConnection(100, MILLISECONDS); | |
| 251 | 251 | assertThat(connection3) |
| 252 | 252 | .isNotEqualTo(connection2) // should not be the full connection |
| 253 | 253 | .isNotEqualTo(connection1); // should not be the previously trashed one |
| @@ -267,7 +267,7 @@ | ||
| 267 | 267 | .setIdleTimeoutSeconds(20); |
| 268 | 268 | |
| 269 | 269 | HostConnectionPool pool = createPool(1, 2); |
| 270 | - PooledConnection connection1 = pool.connections.get(0); | |
| 270 | + Connection connection1 = pool.connections.get(0); | |
| 271 | 271 | |
| 272 | 272 | // Fill core connection enough to trigger creation of another one |
| 273 | 273 | for (int i = 0; i < 110; i++) |
| @@ -314,7 +314,7 @@ | ||
| 314 | 314 | public void should_trash_on_returning_connection_with_insufficient_streams() |
| 315 | 315 | throws ConnectionException, TimeoutException, InterruptedException { |
| 316 | 316 | HostConnectionPool pool = createPool(1, 2); |
| 317 | - PooledConnection core = pool.connections.get(0); | |
| 317 | + Connection core = pool.connections.get(0); | |
| 318 | 318 | |
| 319 | 319 | for (int i = 0; i < 128; i++) |
| 320 | 320 | assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core); |
| @@ -323,7 +323,7 @@ | ||
| 323 | 323 | assertThat(pool.connections).hasSize(2); |
| 324 | 324 | |
| 325 | 325 | // Grab the new non-core connection and replace it with a spy. |
| 326 | - PooledConnection extra1 = spy(pool.connections.get(1)); | |
| 326 | + Connection extra1 = spy(pool.connections.get(1)); | |
| 327 | 327 | pool.connections.set(1, extra1); |
| 328 | 328 | |
| 329 | 329 | // Borrow 10 times to ensure pool is utilized. |
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +54 −79
| @@ -15,98 +15,73 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import static java.util.concurrent.TimeUnit.SECONDS; | |
| 19 | - | |
| 20 | -import org.mockito.Mockito; | |
| 21 | 18 | import org.testng.annotations.Test; |
| 22 | 19 | |
| 23 | -import com.datastax.driver.core.Host.State; | |
| 24 | -import com.datastax.driver.core.policies.ConstantReconnectionPolicy; | |
| 25 | -import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy; | |
| 26 | -import com.datastax.driver.core.policies.RoundRobinPolicy; | |
| 20 | +import java.util.Collection; | |
| 21 | +import java.util.Collections; | |
| 22 | +import java.util.concurrent.*; | |
| 27 | 23 | |
| 28 | -import static com.datastax.driver.core.Assertions.assertThat; | |
| 24 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 25 | +import static org.mockito.Matchers.any; | |
| 26 | +import static org.mockito.Mockito.*; | |
| 29 | 27 | |
| 30 | -public class PoolingOptionsTest { | |
| 28 | +public class PoolingOptionsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | + @Override | |
| 30 | + protected Collection<String> getTableDefinitions() { | |
| 31 | + return Collections.emptyList(); | |
| 32 | + } | |
| 31 | 33 | |
| 32 | 34 | /** |
| 33 | - * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy. | |
| 35 | + * <p> | |
| 36 | + * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it | |
| 37 | + * is used to create and tear down connections. | |
| 38 | + * </p> | |
| 39 | + * | |
| 40 | + * @test_category connection:connection_pool | |
| 41 | + * @expected_result executor is used and successfully able to connect and tear down connections. | |
| 42 | + * @jira_ticket JAVA-692 | |
| 43 | + * @since 2.0.10, 2.1.6 | |
| 34 | 44 | */ |
| 35 | - @Test(groups = "long") | |
| 36 | - public void should_refresh_single_connected_host() { | |
| 37 | - CCMBridge ccm = null; | |
| 38 | - Cluster cluster = null; | |
| 45 | + @Test(groups = "short") | |
| 46 | + public void should_be_able_to_use_custom_initialization_executor() { | |
| 47 | + ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, | |
| 48 | + new LinkedBlockingQueue<Runnable>())); | |
| 49 | + | |
| 50 | + PoolingOptions poolingOptions = new PoolingOptions(); | |
| 51 | + poolingOptions.setInitializationExecutor(executor); | |
| 52 | + | |
| 53 | + Cluster cluster = Cluster.builder() | |
| 54 | + .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 55 | + .withPoolingOptions(poolingOptions).build(); | |
| 39 | 56 | try { |
| 40 | - // This will make the driver use at most 2 hosts, the others will be ignored | |
| 41 | - LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1); | |
| 42 | - | |
| 43 | - // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use | |
| 44 | - ccm = CCMBridge.create("test"); | |
| 45 | - ccm.populate(3); | |
| 46 | - ccm.start(1); | |
| 47 | - ccm.start(2); | |
| 48 | - ccm.waitForUp(1); | |
| 49 | - ccm.waitForUp(2); | |
| 50 | - | |
| 51 | - PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions()); | |
| 52 | - cluster = Cluster.builder() | |
| 53 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 54 | - .withPoolingOptions(poolingOptions) | |
| 55 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 56 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) | |
| 57 | - .build(); | |
| 57 | + cluster.init(); | |
| 58 | + // Ensure executor used. | |
| 59 | + verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 60 | + | |
| 61 | + // Reset invocation count. | |
| 62 | + reset(); | |
| 58 | 63 | |
| 59 | 64 | Session session = cluster.connect(); |
| 60 | 65 | |
| 61 | - assertThat(cluster).usesControlHost(1); | |
| 62 | - assertThat(cluster).host(1) | |
| 63 | - .hasState(State.UP) | |
| 64 | - .isAtDistance(HostDistance.LOCAL); | |
| 65 | - // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line | |
| 66 | - // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up | |
| 67 | - assertThat(cluster).host(2) | |
| 68 | - .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) | |
| 69 | - .isAtDistance(HostDistance.LOCAL); | |
| 70 | - | |
| 71 | - // Bring host 3 up, its presence should be acknowledged but it should be ignored | |
| 72 | - ccm.start(3); | |
| 73 | - ccm.waitForUp(3); | |
| 74 | - | |
| 75 | - assertThat(cluster).host(1) | |
| 76 | - .hasState(State.UP) | |
| 77 | - .isAtDistance(HostDistance.LOCAL); | |
| 78 | - assertThat(cluster).host(2) | |
| 79 | - .hasState(State.UP) | |
| 80 | - .isAtDistance(HostDistance.LOCAL); | |
| 81 | - assertThat(cluster).host(3) | |
| 82 | - .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) | |
| 83 | - .isAtDistance(HostDistance.IGNORED); | |
| 84 | - assertThat(session).hasNoPoolFor(3); | |
| 85 | - | |
| 86 | - // Kill host 2, host 3 should take its place | |
| 87 | - ccm.stop(2); | |
| 88 | - TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster); | |
| 89 | - | |
| 90 | - assertThat(cluster).host(1) | |
| 91 | - .hasState(State.UP) | |
| 92 | - .isAtDistance(HostDistance.LOCAL); | |
| 93 | - assertThat(cluster).host(2) | |
| 94 | - .hasState(State.DOWN); | |
| 95 | - assertThat(cluster).host(3) | |
| 96 | - .hasState(State.UP) | |
| 97 | - .isAtDistance(HostDistance.LOCAL); | |
| 98 | - assertThat(session).hasPoolFor(3); | |
| 99 | - | |
| 100 | - // This is when refreshConnectedHost should have been invoked, it triggers pool creation when | |
| 101 | - // we switch the node from IGNORED to UP: | |
| 102 | - Mockito.verify(poolingOptions) | |
| 103 | - .refreshConnectedHost(TestUtils.findHost(cluster, 3)); | |
| 66 | + // Ensure executor used again to establish core connections. | |
| 67 | + verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 68 | + | |
| 69 | + // Expect core connections + control connection. | |
| 70 | + assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo( | |
| 71 | + TestUtils.numberOfLocalCoreConnections(cluster) + 1); | |
| 72 | + | |
| 73 | + reset(); | |
| 74 | + | |
| 75 | + session.close(); | |
| 76 | + | |
| 77 | + // Executor should have been used to close connections associated with the session. | |
| 78 | + verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 104 | 79 | |
| 80 | + // Only the control connection should remain. | |
| 81 | + assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1); | |
| 105 | 82 | } finally { |
| 106 | - if (cluster != null) | |
| 107 | - cluster.close(); | |
| 108 | - if (ccm != null) | |
| 109 | - ccm.remove(); | |
| 83 | + cluster.close(); | |
| 84 | + executor.shutdown(); | |
| 110 | 85 | } |
| 111 | 86 | } |
| 112 | 87 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +65 −2
| @@ -33,6 +33,10 @@ | ||
| 33 | 33 | import org.testng.annotations.Test; |
| 34 | 34 | |
| 35 | 35 | import static org.assertj.core.api.Assertions.assertThat; |
| 36 | +import static org.mockito.Mockito.reset; | |
| 37 | +import static org.mockito.Mockito.spy; | |
| 38 | +import static org.mockito.Mockito.times; | |
| 39 | +import static org.mockito.Mockito.verify; | |
| 36 | 40 | |
| 37 | 41 | import com.datastax.driver.core.Host.State; |
| 38 | 42 | import com.datastax.driver.core.policies.*; |
| @@ -141,7 +145,7 @@ | ||
| 141 | 145 | CCMBridge ccm = null; |
| 142 | 146 | Cluster cluster = null; |
| 143 | 147 | |
| 144 | - long reconnectionDelayMillis = 1 * 1000; | |
| 148 | + long reconnectionDelayMillis = 1000; | |
| 145 | 149 | CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)); |
| 146 | 150 | |
| 147 | 151 | try { |
| @@ -182,7 +186,7 @@ | ||
| 182 | 186 | CCMBridge ccm = null; |
| 183 | 187 | Cluster cluster = null; |
| 184 | 188 | |
| 185 | - long reconnectionDelayMillis = 1 * 1000; | |
| 189 | + long reconnectionDelayMillis = 1000; | |
| 186 | 190 | TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy()); |
| 187 | 191 | |
| 188 | 192 | try { |
| @@ -220,6 +224,7 @@ | ||
| 220 | 224 | // down for the driver. |
| 221 | 225 | ccm.start(1); |
| 222 | 226 | ccm.waitForUp(1); |
| 227 | + assertThat(cluster).host(1).hasState(State.DOWN); | |
| 223 | 228 | |
| 224 | 229 | TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS); |
| 225 | 230 | assertThat(cluster).host(1).hasState(State.DOWN); |
| @@ -236,6 +241,64 @@ | ||
| 236 | 241 | } |
| 237 | 242 | } |
| 238 | 243 | |
| 244 | + /** | |
| 245 | + * The connection established by a successful reconnection attempt should be reused in one of the | |
| 246 | + * connection pools (JAVA-505). | |
| 247 | + */ | |
| 248 | + @Test(groups = "long") | |
| 249 | + public void should_use_connection_from_reconnection_in_pool() { | |
| 250 | + CCMBridge ccm = null; | |
| 251 | + Cluster cluster = null; | |
| 252 | + | |
| 253 | + TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy()); | |
| 254 | + | |
| 255 | + // Spy SocketOptions.getKeepAlive to count how many connections were instantiated. | |
| 256 | + SocketOptions socketOptions = spy(new SocketOptions()); | |
| 257 | + | |
| 258 | + try { | |
| 259 | + ccm = CCMBridge.create("test", 1); | |
| 260 | + cluster = Cluster.builder() | |
| 261 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 262 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(5000)) | |
| 263 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 264 | + .withSocketOptions(socketOptions) | |
| 265 | + .build(); | |
| 266 | + // Create two sessions to have multiple pools | |
| 267 | + cluster.connect(); | |
| 268 | + cluster.connect(); | |
| 269 | + | |
| 270 | + // Right after init, 1 connection has been opened by the control connection, and 2 (core size) for each pool. | |
| 271 | + verify(socketOptions, times(5)).getKeepAlive(); | |
| 272 | + | |
| 273 | + // Tweak the LBP so that the control connection never reconnects. This makes it easier | |
| 274 | + // to reason about the number of connection attempts. | |
| 275 | + loadBalancingPolicy.returnEmptyQueryPlan = true; | |
| 276 | + | |
| 277 | + // Stop the node and cancel the reconnection attempts to it | |
| 278 | + ccm.stop(1); | |
| 279 | + ccm.waitForDown(1); | |
| 280 | + assertThat(cluster).host(1).goesDownWithin(20, SECONDS); | |
| 281 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 282 | + host1.getReconnectionAttemptFuture().cancel(false); | |
| 283 | + | |
| 284 | + ccm.start(1); | |
| 285 | + ccm.waitForUp(1); | |
| 286 | + | |
| 287 | + // Reset the spy and count the number of connections attempts for 1 reconnect | |
| 288 | + reset(socketOptions); | |
| 289 | + host1.tryReconnectOnce(); | |
| 290 | + assertThat(cluster).host(1).comesUpWithin(120, SECONDS); | |
| 291 | + // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4 | |
| 292 | + // but the one from the reconnection attempt gets reused). | |
| 293 | + verify(socketOptions, times(4)).getKeepAlive(); | |
| 294 | + } finally { | |
| 295 | + if (cluster != null) | |
| 296 | + cluster.close(); | |
| 297 | + if (ccm != null) | |
| 298 | + ccm.remove(); | |
| 299 | + } | |
| 300 | + } | |
| 301 | + | |
| 239 | 302 | /** |
| 240 | 303 | * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested. |
| 241 | 304 | */ |
added driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +112 −0
| @@ -0,0 +1,112 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import static java.util.concurrent.TimeUnit.SECONDS; | |
| 19 | + | |
| 20 | +import org.mockito.Mockito; | |
| 21 | +import org.testng.annotations.Test; | |
| 22 | + | |
| 23 | +import com.datastax.driver.core.Host.State; | |
| 24 | +import com.datastax.driver.core.policies.ConstantReconnectionPolicy; | |
| 25 | +import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy; | |
| 26 | +import com.datastax.driver.core.policies.RoundRobinPolicy; | |
| 27 | + | |
| 28 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 29 | + | |
| 30 | +public class RefreshConnectedHostTest { | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy. | |
| 34 | + */ | |
| 35 | + @Test(groups = "long") | |
| 36 | + public void should_refresh_single_connected_host() { | |
| 37 | + CCMBridge ccm = null; | |
| 38 | + Cluster cluster = null; | |
| 39 | + try { | |
| 40 | + // This will make the driver use at most 2 hosts, the others will be ignored | |
| 41 | + LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1); | |
| 42 | + | |
| 43 | + // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use | |
| 44 | + ccm = CCMBridge.create("test"); | |
| 45 | + ccm.populate(3); | |
| 46 | + ccm.start(1); | |
| 47 | + ccm.start(2); | |
| 48 | + ccm.waitForUp(1); | |
| 49 | + ccm.waitForUp(2); | |
| 50 | + | |
| 51 | + PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions()); | |
| 52 | + cluster = Cluster.builder() | |
| 53 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 54 | + .withPoolingOptions(poolingOptions) | |
| 55 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 56 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) | |
| 57 | + .build(); | |
| 58 | + | |
| 59 | + Session session = cluster.connect(); | |
| 60 | + | |
| 61 | + assertThat(cluster).usesControlHost(1); | |
| 62 | + assertThat(cluster).host(1) | |
| 63 | + .hasState(State.UP) | |
| 64 | + .isAtDistance(HostDistance.LOCAL); | |
| 65 | + // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line | |
| 66 | + // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up | |
| 67 | + assertThat(cluster).host(2) | |
| 68 | + .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) | |
| 69 | + .isAtDistance(HostDistance.LOCAL); | |
| 70 | + | |
| 71 | + // Bring host 3 up, its presence should be acknowledged but it should be ignored | |
| 72 | + ccm.start(3); | |
| 73 | + ccm.waitForUp(3); | |
| 74 | + | |
| 75 | + assertThat(cluster).host(1) | |
| 76 | + .hasState(State.UP) | |
| 77 | + .isAtDistance(HostDistance.LOCAL); | |
| 78 | + assertThat(cluster).host(2) | |
| 79 | + .hasState(State.UP) | |
| 80 | + .isAtDistance(HostDistance.LOCAL); | |
| 81 | + assertThat(cluster).host(3) | |
| 82 | + .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) | |
| 83 | + .isAtDistance(HostDistance.IGNORED); | |
| 84 | + assertThat(session).hasNoPoolFor(3); | |
| 85 | + | |
| 86 | + // Kill host 2, host 3 should take its place | |
| 87 | + ccm.stop(2); | |
| 88 | + TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster); | |
| 89 | + | |
| 90 | + assertThat(cluster).host(1) | |
| 91 | + .hasState(State.UP) | |
| 92 | + .isAtDistance(HostDistance.LOCAL); | |
| 93 | + assertThat(cluster).host(2) | |
| 94 | + .hasState(State.DOWN); | |
| 95 | + assertThat(cluster).host(3) | |
| 96 | + .hasState(State.UP) | |
| 97 | + .isAtDistance(HostDistance.LOCAL); | |
| 98 | + assertThat(session).hasPoolFor(3); | |
| 99 | + | |
| 100 | + // This is when refreshConnectedHost should have been invoked, it triggers pool creation when | |
| 101 | + // we switch the node from IGNORED to UP: | |
| 102 | + Mockito.verify(poolingOptions) | |
| 103 | + .refreshConnectedHost(TestUtils.findHost(cluster, 3)); | |
| 104 | + | |
| 105 | + } finally { | |
| 106 | + if (cluster != null) | |
| 107 | + cluster.close(); | |
| 108 | + if (ccm != null) | |
| 109 | + ccm.remove(); | |
| 110 | + } | |
| 111 | + } | |
| 112 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +2 −2
| @@ -72,7 +72,7 @@ | ||
| 72 | 72 | } |
| 73 | 73 | } |
| 74 | 74 | |
| 75 | - PooledConnection connection = getSingleConnection(session); | |
| 75 | + Connection connection = getSingleConnection(session); | |
| 76 | 76 | assertThat(connection.inFlight.get()).isEqualTo(0); |
| 77 | 77 | } finally { |
| 78 | 78 | if (cluster != null) |
| @@ -81,7 +81,7 @@ | ||
| 81 | 81 | } |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | - private PooledConnection getSingleConnection(Session session) { | |
| 84 | + private Connection getSingleConnection(Session session) { | |
| 85 | 85 | HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next(); |
| 86 | 86 | return pool.connections.get(0); |
| 87 | 87 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +25 −1
| @@ -15,9 +15,14 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.utils.SocketChannelMonitor; | |
| 19 | +import com.google.common.collect.Lists; | |
| 18 | 20 | import org.testng.annotations.Test; |
| 19 | 21 | |
| 22 | +import java.net.InetSocketAddress; | |
| 20 | 23 | import java.util.Collections; |
| 24 | +import java.util.List; | |
| 25 | +import java.util.concurrent.TimeUnit; | |
| 21 | 26 | |
| 22 | 27 | import static org.testng.Assert.assertEquals; |
| 23 | 28 | |
| @@ -31,9 +36,18 @@ | ||
| 31 | 36 | CCMBridge ccmBridge; |
| 32 | 37 | ccmBridge = CCMBridge.create("test", 1); |
| 33 | 38 | Cluster cluster = null; |
| 39 | + SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); | |
| 40 | + channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); | |
| 41 | + | |
| 42 | + List<InetSocketAddress> nodes = Lists.newArrayList( | |
| 43 | + new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042), | |
| 44 | + new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042)); | |
| 34 | 45 | try { |
| 35 | 46 | // create a new cluster object and ensure 0 sessions and connections |
| 36 | - cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build(); | |
| 47 | + cluster = Cluster.builder() | |
| 48 | + .addContactPointsWithPorts(Collections.singletonList( | |
| 49 | + new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042))) | |
| 50 | + .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 37 | 51 | cluster.init(); |
| 38 | 52 | |
| 39 | 53 | int corePoolSize = cluster.getConfiguration() |
| @@ -43,21 +57,25 @@ | ||
| 43 | 57 | assertEquals(cluster.manager.sessions.size(), 0); |
| 44 | 58 | // Should be 1 control connection after initialization. |
| 45 | 59 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 60 | + assertEquals(channelMonitor.openChannels(nodes).size(), 1); | |
| 46 | 61 | |
| 47 | 62 | // ensure sessions.size() returns with 1 control connection + core pool size. |
| 48 | 63 | Session session = cluster.connect(); |
| 49 | 64 | assertEquals(cluster.manager.sessions.size(), 1); |
| 50 | 65 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize); |
| 66 | + assertEquals(channelMonitor.openChannels(nodes).size(), 1 + corePoolSize); | |
| 51 | 67 | |
| 52 | 68 | // ensure sessions.size() returns to 0 with only 1 active connection (the control connection) |
| 53 | 69 | session.close(); |
| 54 | 70 | assertEquals(cluster.manager.sessions.size(), 0); |
| 55 | 71 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 72 | + assertEquals(channelMonitor.openChannels(nodes).size(), 1); | |
| 56 | 73 | |
| 57 | 74 | // ensure bootstrapping a node does not create additional connections |
| 58 | 75 | ccmBridge.bootstrapNode(2); |
| 59 | 76 | assertEquals(cluster.manager.sessions.size(), 0); |
| 60 | 77 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 78 | + assertEquals(channelMonitor.openChannels(nodes).size(), 1); | |
| 61 | 79 | |
| 62 | 80 | // ensure a new session gets registered and core connections are established |
| 63 | 81 | // there should be corePoolSize more connections to accommodate for the new host. |
| @@ -65,12 +83,14 @@ | ||
| 65 | 83 | assertEquals(cluster.manager.sessions.size(), 1); |
| 66 | 84 | |
| 67 | 85 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + (corePoolSize * 2)); |
| 86 | + assertEquals(channelMonitor.openChannels(nodes).size(), 1 + (corePoolSize * 2)); | |
| 68 | 87 | |
| 69 | 88 | // ensure bootstrapping a node does not create additional connections that won't get cleaned up |
| 70 | 89 | thisSession.close(); |
| 71 | 90 | |
| 72 | 91 | assertEquals(cluster.manager.sessions.size(), 0); |
| 73 | 92 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 93 | + assertEquals(channelMonitor.openChannels(nodes).size(), 1); | |
| 74 | 94 | } finally { |
| 75 | 95 | if(cluster != null){ |
| 76 | 96 | cluster.close(); |
| @@ -78,6 +98,10 @@ | ||
| 78 | 98 | if (ccmBridge != null) { |
| 79 | 99 | ccmBridge.remove(); |
| 80 | 100 | } |
| 101 | + // Ensure no channels remain open. | |
| 102 | + channelMonitor.stop(); | |
| 103 | + channelMonitor.report(); | |
| 104 | + assertEquals(channelMonitor.openChannels(nodes).size(), 0); | |
| 81 | 105 | } |
| 82 | 106 | } |
| 83 | 107 | } |
added driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +262 −0
| @@ -0,0 +1,262 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.utils.SocketChannelMonitor; | |
| 19 | +import com.google.common.collect.Lists; | |
| 20 | +import com.google.common.util.concurrent.*; | |
| 21 | +import org.slf4j.Logger; | |
| 22 | +import org.slf4j.LoggerFactory; | |
| 23 | +import org.testng.annotations.Test; | |
| 24 | + | |
| 25 | +import java.net.InetSocketAddress; | |
| 26 | +import java.util.*; | |
| 27 | +import java.util.concurrent.*; | |
| 28 | + | |
| 29 | +import static org.testng.Assert.assertEquals; | |
| 30 | +import static org.testng.Assert.fail; | |
| 31 | + | |
| 32 | +public class SessionStressTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 33 | + | |
| 34 | + private static final Logger logger = LoggerFactory.getLogger(SessionStressTest.class); | |
| 35 | + | |
| 36 | + private ListeningExecutorService executorService; | |
| 37 | + | |
| 38 | + public SessionStressTest() { | |
| 39 | + // 8 threads should be enough so that we stress the driver and not the OS thread scheduler | |
| 40 | + executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8)); | |
| 41 | + } | |
| 42 | + | |
| 43 | + @Override | |
| 44 | + protected Collection<String> getTableDefinitions() { | |
| 45 | + return new ArrayList<String>(0); | |
| 46 | + } | |
| 47 | + | |
| 48 | + | |
| 49 | + /** | |
| 50 | + * Stress test on opening/closing sessions. | |
| 51 | + * <p/> | |
| 52 | + * This test opens and closes {@code Session} in a multithreaded environment and makes sure that there is not | |
| 53 | + * connection leak. More specifically, this test performs the following steps: | |
| 54 | + * <p/> | |
| 55 | + * <ul> | |
| 56 | + * <li>Open 2000 {@code Session} concurrently</li> | |
| 57 | + * <li>Verify that 2000 sessions are reported as open by the {@code Cluster}</li> | |
| 58 | + * <li>Verify that 4001 connections are reported as open by the {@code Cluster}</li> | |
| 59 | + * <li>Close 1000 {@code Session} concurrently</li> | |
| 60 | + * <li>Verify that 1000 sessions are reported as open by the {@code Cluster}</li> | |
| 61 | + * <li>Verify that 2001 connections are reported as open by the {@code Cluster}</li> | |
| 62 | + * <li>Open concurrently 1000 {@code Session} while 1000 other {@code Session} are closed concurrently</li> | |
| 63 | + * <li>Verify that 1000 sessions are reported as open by the {@code Cluster}</li> | |
| 64 | + * <li>Verify that 2001 connections are reported as open by the {@code Cluster}</li> | |
| 65 | + * <li>Close 1000 {@code Session} concurrently</li> | |
| 66 | + * <li>Verify that 0 sessions are reported as open by the {@code Cluster}</li> | |
| 67 | + * <li>Verify that 1 connection is reported as open by the {@code Cluster}</li> | |
| 68 | + * </ul> | |
| 69 | + * <p/> | |
| 70 | + * This test is linked to JAVA-432. | |
| 71 | + */ | |
| 72 | + @Test(groups = "long") | |
| 73 | + public void sessions_should_not_leak_connections() { | |
| 74 | + // override inherited field with a new cluster object and ensure 0 sessions and connections | |
| 75 | + SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); | |
| 76 | + channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); | |
| 77 | + List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress); | |
| 78 | + cluster = Cluster.builder().addContactPointsWithPorts(contactPoints) | |
| 79 | + .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) | |
| 80 | + .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 81 | + cluster.init(); | |
| 82 | + | |
| 83 | + // The cluster has been initialized, we should have 1 connection. | |
| 84 | + assertEquals(cluster.manager.sessions.size(), 0); | |
| 85 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 86 | + | |
| 87 | + // The first session initializes the cluster and its control connection | |
| 88 | + // This is a local cluster so we also have 2 connections per session | |
| 89 | + Session session = cluster.connect(); | |
| 90 | + assertEquals(cluster.manager.sessions.size(), 1); | |
| 91 | + int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster); | |
| 92 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections); | |
| 93 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections); | |
| 94 | + | |
| 95 | + // Closing the session keeps the control connection opened | |
| 96 | + session.close(); | |
| 97 | + assertEquals(cluster.manager.sessions.size(), 0); | |
| 98 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 99 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 100 | + | |
| 101 | + try { | |
| 102 | + int nbOfSessions = 2000; | |
| 103 | + int halfOfTheSessions = nbOfSessions / 2; | |
| 104 | + int nbOfIterations = 5; | |
| 105 | + int sleepTime = 20; | |
| 106 | + | |
| 107 | + for (int iteration = 1; iteration <= nbOfIterations; iteration++) { | |
| 108 | + logger.info("On iteration {}/{}.", iteration, nbOfIterations); | |
| 109 | + logger.info("Creating {} sessions.", nbOfSessions); | |
| 110 | + waitFor(openSessionsConcurrently(nbOfSessions)); | |
| 111 | + | |
| 112 | + // We should see the exact number of opened sessions | |
| 113 | + // Since we have 2 connections per session, we should see 2 * sessions + control connection | |
| 114 | + assertEquals(cluster.manager.sessions.size(), nbOfSessions); | |
| 115 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), | |
| 116 | + coreConnections * nbOfSessions + 1); | |
| 117 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1); | |
| 118 | + | |
| 119 | + // Close half of the sessions asynchronously | |
| 120 | + logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions); | |
| 121 | + waitFor(closeSessionsConcurrently(halfOfTheSessions)); | |
| 122 | + | |
| 123 | + // Check that we have the right number of sessions and connections | |
| 124 | + assertEquals(cluster.manager.sessions.size(), halfOfTheSessions); | |
| 125 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), | |
| 126 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 127 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 128 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 129 | + | |
| 130 | + // Close and open the same number of sessions concurrently | |
| 131 | + logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions); | |
| 132 | + CountDownLatch startSignal = new CountDownLatch(2); | |
| 133 | + List<ListenableFuture<Session>> openSessionFutures = | |
| 134 | + openSessionsConcurrently(halfOfTheSessions, startSignal); | |
| 135 | + List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions, | |
| 136 | + startSignal); | |
| 137 | + startSignal.countDown(); | |
| 138 | + waitFor(openSessionFutures); | |
| 139 | + waitFor(closeSessionsFutures); | |
| 140 | + | |
| 141 | + // Check that we have the same number of sessions and connections | |
| 142 | + assertEquals(cluster.manager.sessions.size(), halfOfTheSessions); | |
| 143 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), | |
| 144 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 145 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 146 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 147 | + | |
| 148 | + // Close the remaining sessions | |
| 149 | + logger.info("Closing remaining {} sessions.", halfOfTheSessions); | |
| 150 | + waitFor(closeSessionsConcurrently(halfOfTheSessions)); | |
| 151 | + | |
| 152 | + // Check that we have a clean state | |
| 153 | + assertEquals(cluster.manager.sessions.size(), 0); | |
| 154 | + assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 155 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 156 | + | |
| 157 | + // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl) | |
| 158 | + logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime); | |
| 159 | + Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS); | |
| 160 | + } | |
| 161 | + } finally { | |
| 162 | + cluster.close(); | |
| 163 | + | |
| 164 | + // Ensure no channels remain open. | |
| 165 | + channelMonitor.stop(); | |
| 166 | + channelMonitor.report(); | |
| 167 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 0); | |
| 168 | + } | |
| 169 | + } | |
| 170 | + | |
| 171 | + private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations) { | |
| 172 | + final CountDownLatch countDownLatch = new CountDownLatch(1); | |
| 173 | + return openSessionsConcurrently(iterations, countDownLatch); | |
| 174 | + } | |
| 175 | + | |
| 176 | + private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations, CountDownLatch countDownLatch) { | |
| 177 | + // Open new sessions once all tasks have been created | |
| 178 | + List<ListenableFuture<Session>> sessionFutures = Lists.newArrayListWithCapacity(iterations); | |
| 179 | + for (int i = 0; i < iterations; i++) { | |
| 180 | + sessionFutures.add(executorService.submit(new OpenSession(cluster, countDownLatch))); | |
| 181 | + } | |
| 182 | + countDownLatch.countDown(); | |
| 183 | + return sessionFutures; | |
| 184 | + } | |
| 185 | + | |
| 186 | + private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations) { | |
| 187 | + final CountDownLatch countDownLatch = new CountDownLatch(1); | |
| 188 | + return closeSessionsConcurrently(iterations, countDownLatch); | |
| 189 | + } | |
| 190 | + | |
| 191 | + private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) { | |
| 192 | + // Get a reference to every session we want to close | |
| 193 | + Stack<Session> sessionsToClose = new Stack<Session>(); | |
| 194 | + Iterator<? extends Session> iterator = cluster.manager.sessions.iterator(); | |
| 195 | + for (int i = 0; i < iterations; i++) { | |
| 196 | + sessionsToClose.push(iterator.next()); | |
| 197 | + } | |
| 198 | + | |
| 199 | + // Close sessions asynchronously once all tasks have been created | |
| 200 | + List<ListenableFuture<CloseFuture>> closeFutures = Lists.newArrayListWithCapacity(iterations); | |
| 201 | + for (int i = 0; i < iterations; i++) { | |
| 202 | + closeFutures.add(executorService.submit(new CloseSession(sessionsToClose.pop(), countDownLatch))); | |
| 203 | + } | |
| 204 | + countDownLatch.countDown(); | |
| 205 | + | |
| 206 | + // Immediately wait for CloseFutures, this should be very quick since all this work does is call closeAsync. | |
| 207 | + List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(iterations); | |
| 208 | + for(ListenableFuture<CloseFuture> closeFuture : closeFutures) { | |
| 209 | + try { | |
| 210 | + futures.add(closeFuture.get()); | |
| 211 | + } catch(Exception e) { | |
| 212 | + logger.error("Got interrupted exception while waiting on closeFuture.", e); | |
| 213 | + } | |
| 214 | + } | |
| 215 | + return futures; | |
| 216 | + } | |
| 217 | + | |
| 218 | + private <E> void waitFor(List<ListenableFuture<E>> futures) { | |
| 219 | + for (Future<E> future : futures) { | |
| 220 | + try { | |
| 221 | + future.get(); | |
| 222 | + } catch (InterruptedException e) { | |
| 223 | + throw new RuntimeException("Interrupted while waiting for future", e); | |
| 224 | + } catch (ExecutionException e) { | |
| 225 | + e.printStackTrace(); | |
| 226 | + fail(e.getMessage()); | |
| 227 | + } | |
| 228 | + } | |
| 229 | + } | |
| 230 | + | |
| 231 | + private static class OpenSession implements Callable<Session> { | |
| 232 | + private final Cluster cluster; | |
| 233 | + private final CountDownLatch startSignal; | |
| 234 | + | |
| 235 | + OpenSession(Cluster cluster, CountDownLatch startSignal) { | |
| 236 | + this.cluster = cluster; | |
| 237 | + this.startSignal = startSignal; | |
| 238 | + } | |
| 239 | + | |
| 240 | + @Override | |
| 241 | + public Session call() throws Exception { | |
| 242 | + startSignal.await(); | |
| 243 | + return cluster.connect(); | |
| 244 | + } | |
| 245 | + } | |
| 246 | + | |
| 247 | + private static class CloseSession implements Callable<CloseFuture> { | |
| 248 | + private final Session session; | |
| 249 | + private final CountDownLatch startSignal; | |
| 250 | + | |
| 251 | + CloseSession(Session session, CountDownLatch startSignal) { | |
| 252 | + this.session = session; | |
| 253 | + this.startSignal = startSignal; | |
| 254 | + } | |
| 255 | + | |
| 256 | + @Override | |
| 257 | + public CloseFuture call() throws Exception { | |
| 258 | + startSignal.await(); | |
| 259 | + return session.closeAsync(); | |
| 260 | + } | |
| 261 | + } | |
| 262 | +} | |
| No newline at the end of the file |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +22 −1
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.net.InetSocketAddress; | |
| 18 | 19 | import java.util.*; |
| 19 | 20 | import java.util.concurrent.CountDownLatch; |
| 20 | 21 | import java.util.concurrent.ExecutorService; |
| @@ -22,6 +23,10 @@ | ||
| 22 | 23 | import java.util.concurrent.TimeUnit; |
| 23 | 24 | |
| 24 | 25 | import com.datastax.driver.core.utils.CassandraVersion; |
| 26 | +import com.datastax.driver.core.utils.SocketChannelMonitor; | |
| 27 | +import io.netty.channel.socket.SocketChannel; | |
| 28 | +import org.slf4j.Logger; | |
| 29 | +import org.slf4j.LoggerFactory; | |
| 25 | 30 | import org.testng.annotations.Test; |
| 26 | 31 | |
| 27 | 32 | import static org.testng.Assert.assertEquals; |
| @@ -35,6 +40,8 @@ | ||
| 35 | 40 | */ |
| 36 | 41 | public class SessionTest extends CCMBridge.PerClassSingleNodeCluster { |
| 37 | 42 | |
| 43 | + private static final Logger logger = LoggerFactory.getLogger(SessionTest.class); | |
| 44 | + | |
| 38 | 45 | private static final String TABLE1 = "test1"; |
| 39 | 46 | private static final String TABLE2 = "test2"; |
| 40 | 47 | private static final String TABLE3 = "test3"; |
| @@ -173,11 +180,15 @@ | ||
| 173 | 180 | |
| 174 | 181 | // create a new cluster object and ensure 0 sessions and connections |
| 175 | 182 | int corePoolSize = 2; |
| 183 | + SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); | |
| 184 | + channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); | |
| 176 | 185 | PoolingOptions poolingOptions = new PoolingOptions() |
| 177 | 186 | .setCoreConnectionsPerHost(HostDistance.LOCAL, corePoolSize); |
| 187 | + Collection<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress); | |
| 178 | 188 | Cluster cluster = Cluster.builder() |
| 179 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 189 | + .addContactPointsWithPorts(contactPoints) | |
| 180 | 190 | .withPoolingOptions(poolingOptions) |
| 191 | + .withNettyOptions(channelMonitor.nettyOptions()) | |
| 181 | 192 | .build(); |
| 182 | 193 | |
| 183 | 194 | try { |
| @@ -185,15 +196,18 @@ | ||
| 185 | 196 | |
| 186 | 197 | assertEquals(cluster.manager.sessions.size(), 0); |
| 187 | 198 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 199 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 188 | 200 | |
| 189 | 201 | Session session = cluster.connect(); |
| 190 | 202 | assertEquals(cluster.manager.sessions.size(), 1); |
| 191 | 203 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize); |
| 204 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + corePoolSize); | |
| 192 | 205 | |
| 193 | 206 | // ensure sessions.size() returns to 0 with only 1 active connection |
| 194 | 207 | session.close(); |
| 195 | 208 | assertEquals(cluster.manager.sessions.size(), 0); |
| 196 | 209 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 210 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 197 | 211 | |
| 198 | 212 | // give the driver time to close sessions |
| 199 | 213 | Thread.sleep(10); |
| @@ -202,11 +216,13 @@ | ||
| 202 | 216 | // ensure 0 sessions with a single control connection |
| 203 | 217 | assertEquals(cluster.manager.sessions.size(), 0); |
| 204 | 218 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 219 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 205 | 220 | |
| 206 | 221 | // ensure a new session gets registered and control connections are established |
| 207 | 222 | session = cluster.connect(); |
| 208 | 223 | assertEquals(cluster.manager.sessions.size(), 1); |
| 209 | 224 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize); |
| 225 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + corePoolSize); | |
| 210 | 226 | session.close(); |
| 211 | 227 | |
| 212 | 228 | // give the driver time to close sessions |
| @@ -215,9 +231,14 @@ | ||
| 215 | 231 | // ensure sessions.size() always returns to 0 with only 1 active connection |
| 216 | 232 | assertEquals(cluster.manager.sessions.size(), 0); |
| 217 | 233 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 234 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 218 | 235 | } |
| 219 | 236 | } finally { |
| 220 | 237 | cluster.close(); |
| 238 | + // Ensure no channels remain open. | |
| 239 | + channelMonitor.stop(); | |
| 240 | + channelMonitor.report(); | |
| 241 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 0); | |
| 221 | 242 | } |
| 222 | 243 | } |
| 223 | 244 |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +4 −0
| @@ -393,6 +393,10 @@ | ||
| 393 | 393 | return null; // never reached |
| 394 | 394 | } |
| 395 | 395 | |
| 396 | + public static int numberOfLocalCoreConnections(Cluster cluster) { | |
| 397 | + Configuration configuration = cluster.getConfiguration(); | |
| 398 | + return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL); | |
| 399 | + } | |
| 396 | 400 | /** |
| 397 | 401 | * @return A Scassandra instance with an arbitrarily chosen binary port from 8042-8142 and admin port from |
| 398 | 402 | * 8052-8152. |
added driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +279 −0
| @@ -0,0 +1,279 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 19 | +import com.datastax.driver.core.utils.SocketChannelMonitor; | |
| 20 | +import com.google.common.collect.Lists; | |
| 21 | +import com.google.common.util.concurrent.FutureCallback; | |
| 22 | +import com.google.common.util.concurrent.Futures; | |
| 23 | +import com.google.common.util.concurrent.ThreadFactoryBuilder; | |
| 24 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 25 | +import io.netty.channel.socket.SocketChannel; | |
| 26 | +import org.slf4j.Logger; | |
| 27 | +import org.slf4j.LoggerFactory; | |
| 28 | +import org.testng.annotations.AfterClass; | |
| 29 | +import org.testng.annotations.BeforeClass; | |
| 30 | +import org.testng.annotations.Test; | |
| 31 | + | |
| 32 | +import java.net.InetSocketAddress; | |
| 33 | +import java.util.Collection; | |
| 34 | +import java.util.List; | |
| 35 | +import java.util.concurrent.*; | |
| 36 | +import java.util.concurrent.atomic.AtomicBoolean; | |
| 37 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 38 | + | |
| 39 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 40 | + | |
| 41 | +public class TimeoutStressTest { | |
| 42 | + | |
| 43 | + static final Logger logger = LoggerFactory.getLogger(TimeoutStressTest.class); | |
| 44 | + | |
| 45 | + // Maximum number of concurrent queries running at a given time. | |
| 46 | + static final int CONCURRENT_QUERIES = 25; | |
| 47 | + | |
| 48 | + // How long the test should run for, may want to consider running for longer periods to time to check for leaks | |
| 49 | + // that could occur over very tiny timing windows. | |
| 50 | + static final long DURATION = 60000; | |
| 51 | + | |
| 52 | + // Configured read timeout - this may need to be tuned to the host system running the test. | |
| 53 | + static final int READ_TIMEOUT_IN_MS = 50; | |
| 54 | + | |
| 55 | + // Configured connection timeout - this may need to be tuned to the host system running the test. | |
| 56 | + static final int CONNECTION_TIMEOUT_IN_MS = 20; | |
| 57 | + | |
| 58 | + // Keyspace to use. | |
| 59 | + static final String KEYSPACE = "testks"; | |
| 60 | + | |
| 61 | + static Cluster cluster; | |
| 62 | + | |
| 63 | + static CCMBridge ccmBridge; | |
| 64 | + | |
| 65 | + static SocketChannelMonitor channelMonitor; | |
| 66 | + | |
| 67 | + static AtomicInteger executedQueries = new AtomicInteger(0); | |
| 68 | + | |
| 69 | + static List<InetSocketAddress> nodes; | |
| 70 | + | |
| 71 | + static PreparedStatement statement; | |
| 72 | + | |
| 73 | + @BeforeClass(groups = "long") | |
| 74 | + public void beforeClass() throws Exception { | |
| 75 | + ccmBridge = CCMBridge.create("test", 3); | |
| 76 | + channelMonitor = new SocketChannelMonitor(); | |
| 77 | + nodes = Lists.newArrayList( | |
| 78 | + new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042), | |
| 79 | + new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042), | |
| 80 | + new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042) | |
| 81 | + ); | |
| 82 | + | |
| 83 | + PoolingOptions poolingOptions = new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 8); | |
| 84 | + | |
| 85 | + cluster = Cluster.builder() | |
| 86 | + .addContactPointsWithPorts(nodes) | |
| 87 | + .withPoolingOptions(poolingOptions) | |
| 88 | + .withNettyOptions(channelMonitor.nettyOptions()) | |
| 89 | + .build(); | |
| 90 | + Session session = cluster.connect(); | |
| 91 | + setupSchema(session); | |
| 92 | + session.close(); | |
| 93 | + } | |
| 94 | + | |
| 95 | + @AfterClass(groups = "long") | |
| 96 | + public void afterClass() { | |
| 97 | + if(ccmBridge != null) { | |
| 98 | + ccmBridge.stop(); | |
| 99 | + } | |
| 100 | + if(channelMonitor != null) { | |
| 101 | + channelMonitor.stop(); | |
| 102 | + } | |
| 103 | + if(cluster != null) { | |
| 104 | + cluster.close(); | |
| 105 | + } | |
| 106 | + } | |
| 107 | + | |
| 108 | + /** | |
| 109 | + * <p> | |
| 110 | + * Validates that under extreme timeout conditions the driver is able to properly maintain connection pools in | |
| 111 | + * addition to not leaking connections. | |
| 112 | + * | |
| 113 | + * <p> | |
| 114 | + * Does the following: | |
| 115 | + * <ol> | |
| 116 | + * <li>Creates a table and loads 30k rows in a single partition.</li> | |
| 117 | + * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li> | |
| 118 | + * <li>Spawns workers that concurrently execute queries.</li> | |
| 119 | + * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li> | |
| 120 | + * <li>After a duration, resets {@link SocketOptions} to defaults.</li> | |
| 121 | + * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li> | |
| 122 | + * <li>Ensure pools are restored.</li> | |
| 123 | + * <li>Shutdown session and ensure that there remains only 1 open connection.</li> | |
| 124 | + * </ol> | |
| 125 | + * | |
| 126 | + * @test_category connection:connection_pool | |
| 127 | + * @expected_result no connections leak and all host pools are maintained. | |
| 128 | + * @jira_ticket JAVA-692 | |
| 129 | + * @since 2.0.10, 2.1.6 | |
| 130 | + */ | |
| 131 | + @Test(groups = "long") | |
| 132 | + public void host_state_should_be_maintained_with_timeouts() { | |
| 133 | + // Set very low timeouts. | |
| 134 | + cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS); | |
| 135 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS); | |
| 136 | + Session session = cluster.connect(); | |
| 137 | + | |
| 138 | + int workers = Runtime.getRuntime().availableProcessors(); | |
| 139 | + ExecutorService workerPool = Executors.newFixedThreadPool(workers, | |
| 140 | + new ThreadFactoryBuilder().setNameFormat("timeout-stress-test-worker-%d").setDaemon(true).build()); | |
| 141 | + | |
| 142 | + AtomicBoolean stopped = new AtomicBoolean(false); | |
| 143 | + | |
| 144 | + // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection. | |
| 145 | + int maxConnections = cluster.getConfiguration() | |
| 146 | + .getPoolingOptions().getMaxConnectionsPerHost(HostDistance.LOCAL) * nodes.size() + 1; | |
| 147 | + | |
| 148 | + try { | |
| 149 | + Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES); | |
| 150 | + for (int i = 0; i < workers; i++) { | |
| 151 | + workerPool.submit(new TimeoutStressWorker(session, concurrentQueries, stopped)); | |
| 152 | + } | |
| 153 | + | |
| 154 | + long startTime = System.currentTimeMillis(); | |
| 155 | + while (System.currentTimeMillis() - startTime < DURATION) { | |
| 156 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 157 | + channelMonitor.report(); | |
| 158 | + // Some connections that are being closed may have had active requests which are delegated to the | |
| 159 | + // reaper for cleanup later. | |
| 160 | + Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes); | |
| 161 | + | |
| 162 | + // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing | |
| 163 | + // factor between retrieving open connections and checking the reaper. | |
| 164 | + if(openChannels.size() > maxConnections) { | |
| 165 | + logger.warn("{} of open channels: {} exceeds maximum expected: {}. " + | |
| 166 | + "This could be because there are connections to be cleaned up in the reaper.", | |
| 167 | + openChannels.size(), maxConnections, openChannels); | |
| 168 | + } | |
| 169 | + } | |
| 170 | + } finally { | |
| 171 | + stopped.set(true); | |
| 172 | + | |
| 173 | + // Reset socket timeouts to allow pool to recover. | |
| 174 | + cluster.getConfiguration().getSocketOptions() | |
| 175 | + .setConnectTimeoutMillis(SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS); | |
| 176 | + cluster.getConfiguration().getSocketOptions() | |
| 177 | + .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 178 | + | |
| 179 | + logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " + | |
| 180 | + "and for the pools to recover."); | |
| 181 | + Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS); | |
| 182 | + | |
| 183 | + Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes); | |
| 184 | + assertThat(openChannels.size()) | |
| 185 | + .as("Number of open connections does not meet expected: %s", openChannels) | |
| 186 | + .isEqualTo(maxConnections); | |
| 187 | + | |
| 188 | + session.close(); | |
| 189 | + | |
| 190 | + openChannels = channelMonitor.openChannels(nodes); | |
| 191 | + assertThat(openChannels.size()) | |
| 192 | + .as("Number of open connections does not meet expected: %s", openChannels) | |
| 193 | + .isEqualTo(1); | |
| 194 | + | |
| 195 | + workerPool.shutdown(); | |
| 196 | + } | |
| 197 | + } | |
| 198 | + | |
| 199 | + /** | |
| 200 | + * Creates the testks schema with a 'record' table and preloads 30k records. | |
| 201 | + */ | |
| 202 | + private static void setupSchema(Session session) throws InterruptedException, ExecutionException, TimeoutException { | |
| 203 | + logger.debug("Creating keyspace"); | |
| 204 | + session.execute("create KEYSPACE if not exists " + KEYSPACE + | |
| 205 | + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}"); | |
| 206 | + session.execute("use " + KEYSPACE); | |
| 207 | + | |
| 208 | + logger.debug("Creating table"); | |
| 209 | + session.execute("create table if NOT EXISTS record (\n" | |
| 210 | + + " name text,\n" | |
| 211 | + + " phone text,\n" | |
| 212 | + + " value text,\n" | |
| 213 | + + " PRIMARY KEY (name, phone)\n" | |
| 214 | + + ");"); | |
| 215 | + | |
| 216 | + int records = 30000; | |
| 217 | + List<ResultSetFuture> futures = Lists.newArrayListWithExpectedSize(records); | |
| 218 | + | |
| 219 | + for (int i = 0; i < records; i++) { | |
| 220 | + if (i % 1000 == 0) | |
| 221 | + logger.debug("Inserting record {}.", i); | |
| 222 | + futures.add(session.executeAsync( | |
| 223 | + "insert into record (name, phone, value) values (?, ?, ?)", "0", Integer.toString(i), "test")); | |
| 224 | + } | |
| 225 | + | |
| 226 | + statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;"); | |
| 227 | + | |
| 228 | + logger.debug("Completed inserting data. Waiting up to 30 for inserts to complete seconds before proceeding."); | |
| 229 | + Futures.allAsList(futures).get(30, TimeUnit.SECONDS); | |
| 230 | + logger.debug("Inserts complete."); | |
| 231 | + } | |
| 232 | + | |
| 233 | + public static class TimeoutStressWorker implements Runnable { | |
| 234 | + | |
| 235 | + private final Semaphore concurrentQueries; | |
| 236 | + private final AtomicBoolean stopped; | |
| 237 | + private final Session session; | |
| 238 | + | |
| 239 | + public TimeoutStressWorker(Session session, Semaphore concurrentQueries, AtomicBoolean stopped) { | |
| 240 | + this.session = session; | |
| 241 | + this.concurrentQueries = concurrentQueries; | |
| 242 | + this.stopped = stopped; | |
| 243 | + } | |
| 244 | + | |
| 245 | + | |
| 246 | + @Override | |
| 247 | + public void run() { | |
| 248 | + | |
| 249 | + while(!stopped.get()) { | |
| 250 | + try { | |
| 251 | + concurrentQueries.acquire(); | |
| 252 | + ResultSetFuture future = session.executeAsync(statement.bind("0")); | |
| 253 | + Futures.addCallback(future, new FutureCallback<ResultSet>() { | |
| 254 | + | |
| 255 | + @Override | |
| 256 | + public void onSuccess(ResultSet result) { | |
| 257 | + concurrentQueries.release(); | |
| 258 | + if(executedQueries.incrementAndGet() % 1000 == 0) | |
| 259 | + logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching()); | |
| 260 | + } | |
| 261 | + | |
| 262 | + @Override | |
| 263 | + public void onFailure(Throwable t) { | |
| 264 | + concurrentQueries.release(); | |
| 265 | + if(t instanceof NoHostAvailableException) { | |
| 266 | + //logger.error("NHAE: {}", t.getMessage()); | |
| 267 | + } else { | |
| 268 | + //logger.error("Exception", t); | |
| 269 | + } | |
| 270 | + } | |
| 271 | + }); | |
| 272 | + } catch(Exception e) { | |
| 273 | + logger.error("Failure while submitting query.", e); | |
| 274 | + } | |
| 275 | + } | |
| 276 | + | |
| 277 | + } | |
| 278 | + } | |
| 279 | +} |
added driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.utils; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.NettyOptions; | |
| 19 | +import com.google.common.base.Predicate; | |
| 20 | +import com.google.common.base.Predicates; | |
| 21 | +import com.google.common.collect.Iterables; | |
| 22 | +import com.google.common.collect.Lists; | |
| 23 | +import com.google.common.collect.MapMaker; | |
| 24 | +import com.google.common.util.concurrent.ThreadFactoryBuilder; | |
| 25 | +import io.netty.channel.socket.SocketChannel; | |
| 26 | +import org.slf4j.Logger; | |
| 27 | +import org.slf4j.LoggerFactory; | |
| 28 | + | |
| 29 | +import java.net.InetSocketAddress; | |
| 30 | +import java.net.Socket; | |
| 31 | +import java.net.SocketAddress; | |
| 32 | +import java.util.*; | |
| 33 | +import java.util.concurrent.Executors; | |
| 34 | +import java.util.concurrent.ScheduledExecutorService; | |
| 35 | +import java.util.concurrent.TimeUnit; | |
| 36 | +import java.util.concurrent.atomic.AtomicLong; | |
| 37 | + | |
| 38 | +/** | |
| 39 | + * Utility that observes {@link SocketChannel}s. Helpful for ensuring that Sockets are actually closed | |
| 40 | + * when they should be. Utilizes {@link NettyOptions} to monitor created {@link SocketChannel}s. | |
| 41 | + */ | |
| 42 | +public class SocketChannelMonitor implements Runnable { | |
| 43 | + | |
| 44 | + private static final Logger logger = LoggerFactory.getLogger(SocketChannelMonitor.class); | |
| 45 | + | |
| 46 | + private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, | |
| 47 | + new ThreadFactoryBuilder().setDaemon(true).setNameFormat("SocketMonitor-%d").build()); | |
| 48 | + | |
| 49 | + // use a weak set so channels may be garbage collected. | |
| 50 | + private final Collection<SocketChannel> channels = Collections.newSetFromMap( | |
| 51 | + new MapMaker().weakKeys().<SocketChannel, Boolean>makeMap()); | |
| 52 | + | |
| 53 | + private final AtomicLong channelsCreated = new AtomicLong(0); | |
| 54 | + | |
| 55 | + private final NettyOptions nettyOptions = new NettyOptions() { | |
| 56 | + public void afterChannelInitialized(SocketChannel channel) throws Exception { | |
| 57 | + channels.add(channel); | |
| 58 | + channelsCreated.incrementAndGet(); | |
| 59 | + } | |
| 60 | + }; | |
| 61 | + | |
| 62 | + @Override | |
| 63 | + public void run() { | |
| 64 | + try { | |
| 65 | + report(); | |
| 66 | + } catch(Exception e) { | |
| 67 | + logger.error("Error countered.", e); | |
| 68 | + } | |
| 69 | + } | |
| 70 | + | |
| 71 | + public void stop() { | |
| 72 | + executor.shutdown(); | |
| 73 | + try { | |
| 74 | + executor.awaitTermination(1, TimeUnit.SECONDS); | |
| 75 | + } catch (InterruptedException e) { | |
| 76 | + } | |
| 77 | + } | |
| 78 | + | |
| 79 | + /** | |
| 80 | + * @return A custom {@link NettyOptions} instance that hooks into afterChannelInitialized added channels may be | |
| 81 | + * monitored. | |
| 82 | + */ | |
| 83 | + public NettyOptions nettyOptions() { | |
| 84 | + return nettyOptions; | |
| 85 | + } | |
| 86 | + | |
| 87 | + public static Predicate<SocketChannel> openChannels = new Predicate<SocketChannel>() { | |
| 88 | + @Override | |
| 89 | + public boolean apply(SocketChannel input) { | |
| 90 | + return input.isOpen(); | |
| 91 | + } | |
| 92 | + }; | |
| 93 | + | |
| 94 | + /** | |
| 95 | + * Schedules a {@link #report()} to be called every configured interval. | |
| 96 | + * @param interval how often to report. | |
| 97 | + * @param timeUnit at what time precision to report at. | |
| 98 | + */ | |
| 99 | + public void reportAtFixedInterval(int interval, TimeUnit timeUnit) { | |
| 100 | + executor.scheduleAtFixedRate(this, interval, interval, timeUnit); | |
| 101 | + } | |
| 102 | + | |
| 103 | + /** | |
| 104 | + * Reports for all sockets. | |
| 105 | + */ | |
| 106 | + public void report() { | |
| 107 | + report(Predicates.<SocketChannel>alwaysTrue()); | |
| 108 | + } | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * <p> | |
| 112 | + * Report for all sockets matching the given predicate. The report format reflects the number of open, closed, | |
| 113 | + * live and total sockets created. This is logged at DEBUG if enabled. | |
| 114 | + * | |
| 115 | + * <p> | |
| 116 | + * If TRACE is enabled, each individual socket will be logged as well. | |
| 117 | + * | |
| 118 | + * @param channelFilter used to determine which sockets to report on. | |
| 119 | + */ | |
| 120 | + public void report(Predicate<SocketChannel> channelFilter) { | |
| 121 | + if(logger.isDebugEnabled()) { | |
| 122 | + Iterable<SocketChannel> channels = matchingChannels(channelFilter); | |
| 123 | + Iterable<SocketChannel> open = Iterables.filter(channels, openChannels); | |
| 124 | + Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels)); | |
| 125 | + | |
| 126 | + logger.debug("Channel states: {} open, {} closed, live {}, total sockets created " + | |
| 127 | + "(including those that don't match filter) {}.", | |
| 128 | + Iterables.size(open), | |
| 129 | + Iterables.size(closed), | |
| 130 | + Iterables.size(channels), | |
| 131 | + channelsCreated.get()); | |
| 132 | + | |
| 133 | + if(logger.isTraceEnabled()) { | |
| 134 | + logger.trace("Open channels {}.", open); | |
| 135 | + logger.trace("Closed channels {}.", closed); | |
| 136 | + } | |
| 137 | + } | |
| 138 | + } | |
| 139 | + | |
| 140 | + private static Comparator<SocketChannel> BY_REMOTE_ADDRESS = new Comparator<SocketChannel>() { | |
| 141 | + @Override | |
| 142 | + public int compare(SocketChannel t0, SocketChannel t1) { | |
| 143 | + // Should not be null as these are filtered previously in matchingChannels. | |
| 144 | + assert t0 != null && t0.remoteAddress() != null; | |
| 145 | + assert t1 != null && t1.remoteAddress() != null;; | |
| 146 | + return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString()); | |
| 147 | + } | |
| 148 | + }; | |
| 149 | + | |
| 150 | + /** | |
| 151 | + * @param addresses The addresses to include. | |
| 152 | + * @return Open channels matching the given socket addresses. | |
| 153 | + */ | |
| 154 | + public Collection<SocketChannel> openChannels(final Collection<InetSocketAddress> addresses) { | |
| 155 | + List<SocketChannel> channels = Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() { | |
| 156 | + @Override | |
| 157 | + public boolean apply(SocketChannel input) { | |
| 158 | + return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress()); | |
| 159 | + } | |
| 160 | + })); | |
| 161 | + | |
| 162 | + Collections.sort(channels, BY_REMOTE_ADDRESS); | |
| 163 | + | |
| 164 | + return channels; | |
| 165 | + } | |
| 166 | + | |
| 167 | + /** | |
| 168 | + * @param channelFilter {@link Predicate} to use to determine whether or not a socket shall be considered. | |
| 169 | + * @return Channels matching the given {@link Predicate}. | |
| 170 | + */ | |
| 171 | + public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) { | |
| 172 | + return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter)); | |
| 173 | + } | |
| 174 | +} |