kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | e646d782bb182fb22523ed34073bfca7642a79fc5e82946c9519276fe6c7ce08 |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2015-04-10 10:22 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-04-17 22:48 +02:00 |
| Parents | 0a8f5175c6b1 |
10 files changed
modified driver-core/CHANGELOG.rst +1 −0
| @@ -39,6 +39,7 @@ | ||
| 39 | 39 | - [new feature] Expose an API to check for schema agreement after a |
| 40 | 40 | schema-altering statement (JAVA-669) |
| 41 | 41 | - [improvement] Make connection and pool creation fully async (JAVA-692) |
| 42 | +- [improvement] Optimize connection use after reconnection (JAVA-505) | |
| 42 | 43 | |
| 43 | 44 | Merged from 2.0.9_fixes branch: |
| 44 | 45 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +214 −192
| @@ -1404,13 +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 | 1412 | // Use triggerOnUp unless you're sure you want to run this on the current thread. |
| 1413 | - private void onUp(final Host host) throws InterruptedException, ExecutionException { | |
| 1413 | + private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { | |
| 1414 | 1414 | logger.debug("Host {} is UP", host); |
| 1415 | 1415 | |
| 1416 | 1416 | if (isClosed()) |
| @@ -1421,85 +1421,92 @@ | ||
| 1421 | 1421 | return; |
| 1422 | 1422 | } |
| 1423 | 1423 | |
| 1424 | - boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); | |
| 1425 | - if (!locked) { | |
| 1426 | - logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); | |
| 1427 | - return; | |
| 1428 | - } | |
| 1429 | 1424 | try { |
| 1430 | 1425 | |
| 1431 | - // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts | |
| 1432 | - 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); | |
| 1433 | 1429 | return; |
| 1434 | - | |
| 1435 | - // If there is a reconnection attempt scheduled for that node, cancel it | |
| 1436 | - Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null); | |
| 1437 | - if (scheduledAttempt != null) { | |
| 1438 | - logger.debug("Cancelling reconnection attempt since node is UP"); | |
| 1439 | - scheduledAttempt.cancel(false); | |
| 1440 | 1430 | } |
| 1441 | - | |
| 1442 | 1431 | try { |
| 1443 | - prepareAllQueries(host); | |
| 1444 | - } catch (InterruptedException e) { | |
| 1445 | - Thread.currentThread().interrupt(); | |
| 1446 | - // Don't propagate because we don't want to prevent other listener to run | |
| 1447 | - } catch (UnsupportedProtocolVersionException e) { | |
| 1448 | - logUnsupportedVersionProtocol(host); | |
| 1449 | - return; | |
| 1450 | - } catch (ClusterNameMismatchException e) { | |
| 1451 | - logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 1452 | - return; | |
| 1453 | - } | |
| 1454 | - | |
| 1455 | - // Session#onUp() expects the load balancing policy to have been updated first, so that | |
| 1456 | - // Host distances are up to date. This mean the policy could return the node before the | |
| 1457 | - // new pool have been created. This is harmless if there is no prior pool since RequestHandler | |
| 1458 | - // will ignore the node, but we do want to make sure there is no prior pool so we don't | |
| 1459 | - // query from a pool we will shutdown right away. | |
| 1460 | - for (SessionManager s : sessions) | |
| 1461 | - s.removePool(host); | |
| 1462 | - loadBalancingPolicy().onUp(host); | |
| 1463 | - controlConnection.onUp(host); | |
| 1464 | 1432 | |
| 1465 | - logger.trace("Adding/renewing host pools for newly UP host {}", 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; | |
| 1466 | 1436 | |
| 1467 | - List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1468 | - for (SessionManager s : sessions) | |
| 1469 | - futures.add(s.forceRenewPool(host)); | |
| 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 | + } | |
| 1470 | 1443 | |
| 1471 | - try { | |
| 1472 | - // Only mark the node up once all session have re-added their pool (if the load-balancing | |
| 1473 | - // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1474 | - // to the node. | |
| 1475 | - List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); | |
| 1476 | - | |
| 1477 | - // If any of the creation failed, they will have signaled a connection failure | |
| 1478 | - // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1479 | - if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1480 | - logger.debug("Connection pool cannot be created, not marking {} UP", 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); | |
| 1481 | 1454 | return; |
| 1482 | 1455 | } |
| 1483 | 1456 | |
| 1484 | - host.setUp(); | |
| 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)); | |
| 1485 | 1472 | |
| 1486 | - for (Host.StateListener listener : listeners) | |
| 1487 | - listener.onUp(host); | |
| 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(); | |
| 1478 | + | |
| 1479 | + // If any of the creation failed, they will have signaled a connection failure | |
| 1480 | + // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1481 | + if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1482 | + logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 1483 | + return; | |
| 1484 | + } | |
| 1488 | 1485 | |
| 1489 | - } catch (ExecutionException e) { | |
| 1490 | - Throwable t = e.getCause(); | |
| 1491 | - // That future is not really supposed to throw unexpected exceptions | |
| 1492 | - if (!(t instanceof InterruptedException)) | |
| 1493 | - logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t); | |
| 1494 | - } | |
| 1486 | + host.setUp(); | |
| 1495 | 1487 | |
| 1496 | - // Now, check if there isn't pools to create/remove following the addition. | |
| 1497 | - // We do that now only so that it's not called before we've set the node up. | |
| 1498 | - for (SessionManager s : sessions) | |
| 1499 | - s.updateCreatedPools(); | |
| 1488 | + for (Host.StateListener listener : listeners) | |
| 1489 | + listener.onUp(host); | |
| 1490 | + | |
| 1491 | + } catch (ExecutionException e) { | |
| 1492 | + Throwable t = e.getCause(); | |
| 1493 | + // That future is not really supposed to throw unexpected exceptions | |
| 1494 | + if (!(t instanceof InterruptedException)) | |
| 1495 | + logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t); | |
| 1496 | + } | |
| 1497 | + | |
| 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(); | |
| 1502 | + | |
| 1503 | + } finally { | |
| 1504 | + host.notificationsLock.unlock(); | |
| 1505 | + } | |
| 1500 | 1506 | |
| 1501 | 1507 | } finally { |
| 1502 | - host.notificationsLock.unlock(); | |
| 1508 | + if (reusedConnection != null && !reusedConnection.hasPool()) | |
| 1509 | + reusedConnection.closeAsync(); | |
| 1503 | 1510 | } |
| 1504 | 1511 | } |
| 1505 | 1512 | |
| @@ -1552,11 +1559,10 @@ | ||
| 1552 | 1559 | public void runMayThrow() throws InterruptedException, ExecutionException { |
| 1553 | 1560 | boolean success; |
| 1554 | 1561 | try { |
| 1555 | - // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection | |
| 1556 | - connectionFactory.open(host).closeAsync(); | |
| 1562 | + Connection connection = connectionFactory.open(host); | |
| 1557 | 1563 | // Note that we want to do the pool creation on this thread because we want that |
| 1558 | 1564 | // when onUp return, the host is ready for querying |
| 1559 | - onUp(host); | |
| 1565 | + onUp(host, connection); | |
| 1560 | 1566 | // If one of the connections in onUp failed, it signaled the error and triggerd onDown, |
| 1561 | 1567 | // but onDown aborted because this reconnection attempt was in progress (JAVA-577). |
| 1562 | 1568 | // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was |
| @@ -1638,7 +1644,6 @@ | ||
| 1638 | 1644 | if (distance == HostDistance.IGNORED || !startReconnection) |
| 1639 | 1645 | return; |
| 1640 | 1646 | |
| 1641 | - // Note: we basically waste the first successful reconnection, but it's probably not a big deal | |
| 1642 | 1647 | logger.debug("{} is down, scheduling connection retries", host); |
| 1643 | 1648 | startPeriodicReconnectionAttempt(host, isHostAddition); |
| 1644 | 1649 | } finally { |
| @@ -1654,19 +1659,15 @@ | ||
| 1654 | 1659 | } |
| 1655 | 1660 | |
| 1656 | 1661 | protected void onReconnection(Connection connection) { |
| 1657 | - // We don't use that first connection so close it. | |
| 1658 | - // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so | |
| 1659 | - // we use it for the first HostConnectionPool created | |
| 1660 | - connection.closeAsync(); | |
| 1661 | 1662 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 1662 | 1663 | // catch that an upgraded node uses a new cassandra version). |
| 1663 | 1664 | if (controlConnection.refreshNodeInfo(host)) { |
| 1664 | 1665 | logger.debug("Successful reconnection to {}, setting host UP", host); |
| 1665 | 1666 | try { |
| 1666 | 1667 | if (isHostAddition) |
| 1667 | - onAdd(host); | |
| 1668 | + onAdd(host, connection); | |
| 1668 | 1669 | else |
| 1669 | - onUp(host); | |
| 1670 | + onUp(host, connection); | |
| 1670 | 1671 | } catch (InterruptedException e) { |
| 1671 | 1672 | Thread.currentThread().interrupt(); |
| 1672 | 1673 | } catch (Exception e) { |
| @@ -1674,6 +1675,7 @@ | ||
| 1674 | 1675 | } |
| 1675 | 1676 | } else { |
| 1676 | 1677 | logger.debug("Not enough info for {}, ignoring host", host); |
| 1678 | + connection.closeAsync(); | |
| 1677 | 1679 | } |
| 1678 | 1680 | } |
| 1679 | 1681 | |
| @@ -1710,16 +1712,12 @@ | ||
| 1710 | 1712 | } |
| 1711 | 1713 | |
| 1712 | 1714 | protected void onReconnection(Connection connection) { |
| 1713 | - // We don't use that first connection so close it. | |
| 1714 | - // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so | |
| 1715 | - // we use it for the first HostConnectionPool created | |
| 1716 | - connection.closeAsync(); | |
| 1717 | 1715 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 1718 | 1716 | // catch that an upgraded node uses a new cassandra version). |
| 1719 | 1717 | if (controlConnection.refreshNodeInfo(host)) { |
| 1720 | 1718 | logger.debug("Successful reconnection to {}, setting host UP", host); |
| 1721 | 1719 | try { |
| 1722 | - onUp(host); | |
| 1720 | + onUp(host, connection); | |
| 1723 | 1721 | } catch (InterruptedException e) { |
| 1724 | 1722 | Thread.currentThread().interrupt(); |
| 1725 | 1723 | } catch (Exception e) { |
| @@ -1727,6 +1725,7 @@ | ||
| 1727 | 1725 | } |
| 1728 | 1726 | } else { |
| 1729 | 1727 | logger.debug("Not enough info for {}, ignoring host", host); |
| 1728 | + connection.closeAsync(); | |
| 1730 | 1729 | } |
| 1731 | 1730 | } |
| 1732 | 1731 | |
| @@ -1752,13 +1751,13 @@ | ||
| 1752 | 1751 | return executor.submit(new ExceptionCatchingRunnable() { |
| 1753 | 1752 | @Override |
| 1754 | 1753 | public void runMayThrow() throws InterruptedException, ExecutionException { |
| 1755 | - onAdd(host); | |
| 1754 | + onAdd(host, null); | |
| 1756 | 1755 | } |
| 1757 | 1756 | }); |
| 1758 | 1757 | } |
| 1759 | 1758 | |
| 1760 | 1759 | // Use triggerOnAdd unless you're sure you want to run this on the current thread. |
| 1761 | - private void onAdd(final Host host) throws InterruptedException, ExecutionException { | |
| 1760 | + private void onAdd(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { | |
| 1762 | 1761 | if (isClosed()) |
| 1763 | 1762 | return; |
| 1764 | 1763 | |
| @@ -1769,81 +1768,88 @@ | ||
| 1769 | 1768 | return; |
| 1770 | 1769 | } |
| 1771 | 1770 | |
| 1772 | - boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); | |
| 1773 | - if (!locked) { | |
| 1774 | - logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); | |
| 1775 | - return; | |
| 1776 | - } | |
| 1777 | 1771 | try { |
| 1778 | 1772 | |
| 1779 | - // Adds to the load balancing first and foremost, as doing so might change the decision | |
| 1780 | - // it will make for distance() on that node (not likely but we leave that possibility). | |
| 1781 | - // This does mean the policy may start returning that node for query plan, but as long | |
| 1782 | - // as no pools have been created (below) this will be ignored by RequestHandler so it's fine. | |
| 1783 | - loadBalancingPolicy().onAdd(host); | |
| 1784 | - | |
| 1785 | - // Next, if the host should be ignored, well, ignore it. | |
| 1786 | - if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) { | |
| 1787 | - // We still mark the node UP though as it should be (and notifiy the listeners). | |
| 1788 | - // We'll mark it down if we have a notification anyway and we've documented that especially | |
| 1789 | - // for IGNORED hosts, the isUp() method was a best effort guess | |
| 1790 | - host.setUp(); | |
| 1791 | - for (Host.StateListener listener : listeners) | |
| 1792 | - 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); | |
| 1793 | 1776 | return; |
| 1794 | 1777 | } |
| 1795 | - | |
| 1796 | 1778 | try { |
| 1797 | - prepareAllQueries(host); | |
| 1798 | - } catch (InterruptedException e) { | |
| 1799 | - Thread.currentThread().interrupt(); | |
| 1800 | - // Don't propagate because we don't want to prevent other listener to run | |
| 1801 | - } catch (UnsupportedProtocolVersionException e) { | |
| 1802 | - logUnsupportedVersionProtocol(host); | |
| 1803 | - return; | |
| 1804 | - } catch (ClusterNameMismatchException e) { | |
| 1805 | - logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); | |
| 1806 | - return; | |
| 1807 | - } | |
| 1808 | - | |
| 1809 | - controlConnection.onAdd(host); | |
| 1810 | 1779 | |
| 1811 | - List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1812 | - for (SessionManager s : sessions) | |
| 1813 | - futures.add(s.maybeAddPool(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 | + } | |
| 1814 | 1796 | |
| 1815 | - try { | |
| 1816 | - // Only mark the node up once all session have added their pool (if the load-balancing | |
| 1817 | - // policy says it should), so that Host.isUp() don't return true before we're reconnected | |
| 1818 | - // to the node. | |
| 1819 | - List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); | |
| 1820 | - | |
| 1821 | - // If any of the creation failed, they will have signaled a connection failure | |
| 1822 | - // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1823 | - if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1824 | - logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 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); | |
| 1825 | 1807 | return; |
| 1826 | 1808 | } |
| 1827 | 1809 | |
| 1828 | - host.setUp(); | |
| 1810 | + controlConnection.onAdd(host); | |
| 1829 | 1811 | |
| 1830 | - for (Host.StateListener listener : listeners) | |
| 1831 | - listener.onAdd(host); | |
| 1812 | + List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); | |
| 1813 | + for (SessionManager s : sessions) | |
| 1814 | + futures.add(s.maybeAddPool(host, reusedConnection)); | |
| 1832 | 1815 | |
| 1833 | - } catch (ExecutionException e) { | |
| 1834 | - Throwable t = e.getCause(); | |
| 1835 | - // That future is not really supposed to throw unexpected exceptions | |
| 1836 | - if (!(t instanceof InterruptedException)) | |
| 1837 | - logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t); | |
| 1838 | - } | |
| 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 | + | |
| 1822 | + // If any of the creation failed, they will have signaled a connection failure | |
| 1823 | + // which will trigger a reconnection to the node. So don't bother marking UP. | |
| 1824 | + if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { | |
| 1825 | + logger.debug("Connection pool cannot be created, not marking {} UP", host); | |
| 1826 | + return; | |
| 1827 | + } | |
| 1839 | 1828 | |
| 1840 | - // Now, check if there isn't pools to create/remove following the addition. | |
| 1841 | - // We do that now only so that it's not called before we've set the node up. | |
| 1842 | - for (SessionManager s : sessions) | |
| 1843 | - s.updateCreatedPools(); | |
| 1829 | + host.setUp(); | |
| 1830 | + | |
| 1831 | + for (Host.StateListener listener : listeners) | |
| 1832 | + listener.onAdd(host); | |
| 1833 | + | |
| 1834 | + } catch (ExecutionException e) { | |
| 1835 | + Throwable t = e.getCause(); | |
| 1836 | + // That future is not really supposed to throw unexpected exceptions | |
| 1837 | + if (!(t instanceof InterruptedException)) | |
| 1838 | + logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t); | |
| 1839 | + } | |
| 1840 | + | |
| 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(); | |
| 1845 | + | |
| 1846 | + } finally { | |
| 1847 | + host.notificationsLock.unlock(); | |
| 1848 | + } | |
| 1844 | 1849 | |
| 1845 | 1850 | } finally { |
| 1846 | - host.notificationsLock.unlock(); | |
| 1851 | + if (reusedConnection != null && !reusedConnection.hasPool()) | |
| 1852 | + reusedConnection.closeAsync(); | |
| 1847 | 1853 | } |
| 1848 | 1854 | } |
| 1849 | 1855 | |
| @@ -1942,69 +1948,85 @@ | ||
| 1942 | 1948 | return stmt; |
| 1943 | 1949 | } |
| 1944 | 1950 | |
| 1945 | - 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 { | |
| 1946 | 1958 | if (preparedQueries.isEmpty()) |
| 1947 | - return; | |
| 1959 | + return reusedConnection; | |
| 1948 | 1960 | |
| 1949 | 1961 | logger.debug("Preparing {} prepared queries on newly up node {}", preparedQueries.size(), host); |
| 1962 | + Connection connection = null; | |
| 1950 | 1963 | try { |
| 1951 | - Connection connection = connectionFactory.open(host); | |
| 1964 | + connection = (reusedConnection == null) | |
| 1965 | + ? connectionFactory.open(host) | |
| 1966 | + : reusedConnection; | |
| 1952 | 1967 | |
| 1953 | - try | |
| 1954 | - { | |
| 1955 | - try { | |
| 1956 | - ControlConnection.waitForSchemaAgreement(connection, this); | |
| 1957 | - } catch (ExecutionException e) { | |
| 1958 | - // As below, just move on | |
| 1959 | - } | |
| 1968 | + try { | |
| 1969 | + ControlConnection.waitForSchemaAgreement(connection, this); | |
| 1970 | + } catch (ExecutionException e) { | |
| 1971 | + // As below, just move on | |
| 1972 | + } | |
| 1960 | 1973 | |
| 1961 | - // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation | |
| 1962 | - // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the | |
| 1963 | - // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is | |
| 1964 | - // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed. | |
| 1965 | - | |
| 1966 | - // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally | |
| 1967 | - // used for preparing it. However, since we are likely that all prepared query belong to only a handful | |
| 1968 | - // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed, | |
| 1969 | - // we first sort the query per keyspace. | |
| 1970 | - SetMultimap<String, String> perKeyspace = HashMultimap.create(); | |
| 1971 | - for (PreparedStatement ps : preparedQueries.values()) { | |
| 1972 | - // It's possible for a query to not have a current keyspace. But since null doesn't work well as | |
| 1973 | - // map keys, we use the empty string instead (that is not a valid keyspace name). | |
| 1974 | - String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace(); | |
| 1975 | - perKeyspace.put(keyspace, ps.getQueryString()); | |
| 1976 | - } | |
| 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 | + } | |
| 1977 | 1990 | |
| 1978 | - for (String keyspace : perKeyspace.keySet()) | |
| 1979 | - { | |
| 1980 | - // Empty string mean no particular keyspace to set | |
| 1981 | - if (!keyspace.isEmpty()) | |
| 1982 | - connection.setKeyspace(keyspace); | |
| 1983 | - | |
| 1984 | - List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size()); | |
| 1985 | - for (String query : perKeyspace.get(keyspace)) { | |
| 1986 | - futures.add(connection.write(new Requests.Prepare(query))); | |
| 1987 | - } | |
| 1988 | - for (Connection.Future future : futures) { | |
| 1989 | - try { | |
| 1990 | - future.get(); | |
| 1991 | - } catch (ExecutionException e) { | |
| 1992 | - // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do | |
| 1993 | - // currently). It's not a big deal however as if it's a more serious problem it'll show up later when | |
| 1994 | - // the query is tried for execution. | |
| 1995 | - logger.debug("Unexpected error while preparing queries on new/newly up host", e); | |
| 1996 | - } | |
| 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); | |
| 1997 | 2008 | } |
| 1998 | 2009 | } |
| 1999 | - } finally { | |
| 2000 | - connection.closeAsync(); | |
| 2001 | 2010 | } |
| 2011 | + | |
| 2012 | + return connection; | |
| 2002 | 2013 | } catch (ConnectionException e) { |
| 2003 | 2014 | // Ignore, not a big deal |
| 2015 | + if (connection != null) | |
| 2016 | + connection.closeAsync(); | |
| 2017 | + return null; | |
| 2004 | 2018 | } catch (AuthenticationException e) { |
| 2005 | 2019 | // That's a bad news, but ignore at this point |
| 2020 | + if (connection != null) | |
| 2021 | + connection.closeAsync(); | |
| 2022 | + return null; | |
| 2006 | 2023 | } catch (BusyConnectionException e) { |
| 2007 | 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; | |
| 2008 | 2030 | } |
| 2009 | 2031 | } |
| 2010 | 2032 | |
| @@ -2093,7 +2115,7 @@ | ||
| 2093 | 2115 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 2094 | 2116 | // catch that an upgraded node uses a new cassandra version). |
| 2095 | 2117 | if (controlConnection.refreshNodeInfo(newHost)) { |
| 2096 | - onAdd(newHost); | |
| 2118 | + onAdd(newHost, null); | |
| 2097 | 2119 | } else { |
| 2098 | 2120 | logger.debug("Not enough info for {}, ignoring host", newHost); |
| 2099 | 2121 | } |
| @@ -2135,7 +2157,7 @@ | ||
| 2135 | 2157 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 2136 | 2158 | // catch that an upgraded node uses a new cassandra version). |
| 2137 | 2159 | if (controlConnection.refreshNodeInfo(h)) { |
| 2138 | - onAdd(h); | |
| 2160 | + onAdd(h, null); | |
| 2139 | 2161 | } else { |
| 2140 | 2162 | logger.debug("Not enough info for {}, ignoring host", h); |
| 2141 | 2163 | } |
| @@ -2148,7 +2170,7 @@ | ||
| 2148 | 2170 | // Make sure we have up-to-date infos on that host before adding it (so we typically |
| 2149 | 2171 | // catch that an upgraded node uses a new cassandra version). |
| 2150 | 2172 | if (controlConnection.refreshNodeInfo(hostUp)) { |
| 2151 | - onUp(hostUp); | |
| 2173 | + onUp(hostUp, null); | |
| 2152 | 2174 | } else { |
| 2153 | 2175 | logger.debug("Not enough info for {}, ignoring host", hostUp); |
| 2154 | 2176 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +64 −12
| @@ -65,6 +65,12 @@ | ||
| 65 | 65 | |
| 66 | 66 | private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false); |
| 67 | 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 | + | |
| 68 | 74 | public final InetSocketAddress address; |
| 69 | 75 | private final String name; |
| 70 | 76 | |
| @@ -84,15 +90,30 @@ | ||
| 84 | 90 | |
| 85 | 91 | private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>(); |
| 86 | 92 | |
| 93 | + private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>(); | |
| 94 | + | |
| 87 | 95 | /** |
| 88 | - * Create a new connection to a Cassandra node. | |
| 96 | + /** | |
| 97 | + * Create a new connection to a Cassandra node and associate it with the given pool. | |
| 89 | 98 | * |
| 90 | - * The connection is open and initialized by the constructor. | |
| 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)}. | |
| 91 | 104 | */ |
| 92 | - protected Connection(String name, InetSocketAddress address, Factory factory) { | |
| 105 | + protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) { | |
| 93 | 106 | this.address = address; |
| 94 | 107 | this.factory = factory; |
| 95 | 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); | |
| 96 | 117 | } |
| 97 | 118 | |
| 98 | 119 | public ListenableFuture<Void> initAsync() { |
| @@ -377,9 +398,9 @@ | ||
| 377 | 398 | // If the host was reconnecting, and this error happens right after we opened a connection pool, but |
| 378 | 399 | // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can |
| 379 | 400 | // lead to a race condition that leaves the node UP with a closed pool. |
| 401 | + HostConnectionPool pool = this.poolRef.get(); | |
| 380 | 402 | boolean belongsToReconnectingPool = host.state != Host.State.UP && |
| 381 | - this instanceof PooledConnection && | |
| 382 | - (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed()); | |
| 403 | + (pool == null || !pool.isClosed()); | |
| 383 | 404 | |
| 384 | 405 | boolean markSuspected = isInitialized && !belongsToReconnectingPool; |
| 385 | 406 | |
| @@ -398,6 +419,19 @@ | ||
| 398 | 419 | } |
| 399 | 420 | |
| 400 | 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 | + } | |
| 401 | 435 | } |
| 402 | 436 | |
| 403 | 437 | public String keyspace() { |
| @@ -546,6 +580,25 @@ | ||
| 546 | 580 | }; |
| 547 | 581 | } |
| 548 | 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 | + | |
| 549 | 602 | public boolean isClosed() { |
| 550 | 603 | return closeFuture.get() != null; |
| 551 | 604 | } |
| @@ -682,9 +735,9 @@ | ||
| 682 | 735 | /** |
| 683 | 736 | * Same as open, but associate the created connection to the provided connection pool. |
| 684 | 737 | */ |
| 685 | - public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 738 | + public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 686 | 739 | try { |
| 687 | - PooledConnection connection = newConnection(pool); | |
| 740 | + Connection connection = newConnection(pool); | |
| 688 | 741 | connection.initAsync().get(); |
| 689 | 742 | return connection; |
| 690 | 743 | } catch (ExecutionException e) { |
| @@ -695,11 +748,11 @@ | ||
| 695 | 748 | /** |
| 696 | 749 | * Creates a new connection and associates it to the provided connection pool, but does not start it. |
| 697 | 750 | */ |
| 698 | - public PooledConnection newConnection(HostConnectionPool pool) { | |
| 751 | + public Connection newConnection(HostConnectionPool pool) { | |
| 699 | 752 | InetSocketAddress address = pool.host.getSocketAddress(); |
| 700 | 753 | String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement(); |
| 701 | 754 | |
| 702 | - return new PooledConnection(name, address, this, pool); | |
| 755 | + return new Connection(name, address, this, pool); | |
| 703 | 756 | } |
| 704 | 757 | |
| 705 | 758 | static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| @@ -844,7 +897,7 @@ | ||
| 844 | 897 | } |
| 845 | 898 | |
| 846 | 899 | private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker() |
| 847 | - .concurrencyLevel(16) | |
| 900 | + .concurrencyLevel(16) | |
| 848 | 901 | .weakKeys() |
| 849 | 902 | .makeMap(); |
| 850 | 903 | |
| @@ -1181,8 +1234,7 @@ | ||
| 1181 | 1234 | // were, a new request could reuse that ID but get the answer to the request we just gave up on instead |
| 1182 | 1235 | // of its own answer, and we would have no way to detect that. |
| 1183 | 1236 | connection.dispatcher.removeHandler(this, false); |
| 1184 | - if (connection instanceof PooledConnection) | |
| 1185 | - ((PooledConnection)connection).release(); | |
| 1237 | + connection.release(); | |
| 1186 | 1238 | } |
| 1187 | 1239 | |
| 1188 | 1240 | private TimerTask onTimeoutTask() { |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +51 −35
| @@ -31,11 +31,12 @@ | ||
| 31 | 31 | import org.slf4j.LoggerFactory; |
| 32 | 32 | |
| 33 | 33 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 34 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 34 | 35 | |
| 35 | -import static com.datastax.driver.core.PooledConnection.State.GONE; | |
| 36 | -import static com.datastax.driver.core.PooledConnection.State.OPEN; | |
| 37 | -import static com.datastax.driver.core.PooledConnection.State.RESURRECTING; | |
| 38 | -import static com.datastax.driver.core.PooledConnection.State.TRASHED; | |
| 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; | |
| 39 | 40 | |
| 40 | 41 | class HostConnectionPool { |
| 41 | 42 | |
| @@ -52,13 +53,13 @@ | ||
| 52 | 53 | public volatile HostDistance hostDistance; |
| 53 | 54 | private final SessionManager manager; |
| 54 | 55 | |
| 55 | - final List<PooledConnection> connections; | |
| 56 | + final List<Connection> connections; | |
| 56 | 57 | private final AtomicInteger open; |
| 57 | 58 | /** The total number of in-flight requests on all connections of this pool. */ |
| 58 | 59 | final AtomicInteger totalInFlight = new AtomicInteger(); |
| 59 | 60 | /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/ |
| 60 | 61 | private final AtomicInteger maxTotalInFlight = new AtomicInteger(); |
| 61 | - final Set<PooledConnection> trash = new CopyOnWriteArraySet<PooledConnection>(); | |
| 62 | + final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); | |
| 62 | 63 | |
| 63 | 64 | private volatile int waiter = 0; |
| 64 | 65 | private final Lock waitLock = new ReentrantLock(true); |
| @@ -73,7 +74,7 @@ | ||
| 73 | 74 | private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING } |
| 74 | 75 | private volatile Phase phase = Phase.INITIALIZING; |
| 75 | 76 | |
| 76 | - public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager) { | |
| 77 | + public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager){ | |
| 77 | 78 | assert hostDistance != HostDistance.IGNORED; |
| 78 | 79 | this.host = host; |
| 79 | 80 | this.hostDistance = hostDistance; |
| @@ -87,19 +88,34 @@ | ||
| 87 | 88 | } |
| 88 | 89 | }; |
| 89 | 90 | |
| 90 | - this.connections = new CopyOnWriteArrayList<PooledConnection>(); | |
| 91 | + this.connections = new CopyOnWriteArrayList<Connection>(); | |
| 91 | 92 | this.open = new AtomicInteger(); |
| 92 | 93 | } |
| 93 | 94 | |
| 94 | - public ListenableFuture<Void> initAsync() { | |
| 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) { | |
| 95 | 101 | // Create initial core connections |
| 96 | 102 | int capacity = options().getCoreConnectionsPerHost(hostDistance); |
| 97 | - final List<PooledConnection> connections = Lists.newArrayListWithCapacity(capacity); | |
| 103 | + final List<Connection> connections = Lists.newArrayListWithCapacity(capacity); | |
| 98 | 104 | final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity); |
| 99 | - for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) { | |
| 100 | - PooledConnection connection = manager.connectionFactory().newConnection(this); | |
| 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; | |
| 101 | 117 | connections.add(connection); |
| 102 | - connectionFutures.add(connection.initAsync()); | |
| 118 | + connectionFutures.add(connectionFuture); | |
| 103 | 119 | } |
| 104 | 120 | |
| 105 | 121 | Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); |
| @@ -134,8 +150,8 @@ | ||
| 134 | 150 | } |
| 135 | 151 | |
| 136 | 152 | // Clean up if we got an error at construction time but still created part of the core connections |
| 137 | - private void forceClose(List<PooledConnection> connections) { | |
| 138 | - for (PooledConnection connection : connections) { | |
| 153 | + private void forceClose(List<Connection> connections) { | |
| 154 | + for (Connection connection : connections) { | |
| 139 | 155 | connection.closeAsync().force(); |
| 140 | 156 | } |
| 141 | 157 | } |
| @@ -144,7 +160,7 @@ | ||
| 144 | 160 | return manager.configuration().getPoolingOptions(); |
| 145 | 161 | } |
| 146 | 162 | |
| 147 | - public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 163 | + public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 148 | 164 | if (phase == Phase.INITIALIZING) |
| 149 | 165 | throw new ConnectionException(host.getSocketAddress(), "Pool is initializing."); |
| 150 | 166 | |
| @@ -160,15 +176,15 @@ | ||
| 160 | 176 | scheduledForCreation.incrementAndGet(); |
| 161 | 177 | manager.blockingExecutor().submit(newConnectionTask); |
| 162 | 178 | } |
| 163 | - PooledConnection c = waitForConnection(timeout, unit); | |
| 179 | + Connection c = waitForConnection(timeout, unit); | |
| 164 | 180 | totalInFlight.incrementAndGet(); |
| 165 | 181 | c.setKeyspace(manager.poolsState.keyspace); |
| 166 | 182 | return c; |
| 167 | 183 | } |
| 168 | 184 | |
| 169 | 185 | int minInFlight = Integer.MAX_VALUE; |
| 170 | - PooledConnection leastBusy = null; | |
| 171 | - for (PooledConnection connection : connections) { | |
| 186 | + Connection leastBusy = null; | |
| 187 | + for (Connection connection : connections) { | |
| 172 | 188 | int inFlight = connection.inFlight.get(); |
| 173 | 189 | if (inFlight < minInFlight) { |
| 174 | 190 | minInFlight = inFlight; |
| @@ -256,7 +272,7 @@ | ||
| 256 | 272 | } |
| 257 | 273 | } |
| 258 | 274 | |
| 259 | - private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 275 | + private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 260 | 276 | if (timeout == 0) |
| 261 | 277 | throw new TimeoutException(); |
| 262 | 278 | |
| @@ -275,8 +291,8 @@ | ||
| 275 | 291 | throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); |
| 276 | 292 | |
| 277 | 293 | int minInFlight = Integer.MAX_VALUE; |
| 278 | - PooledConnection leastBusy = null; | |
| 279 | - for (PooledConnection connection : connections) { | |
| 294 | + Connection leastBusy = null; | |
| 295 | + for (Connection connection : connections) { | |
| 280 | 296 | int inFlight = connection.inFlight.get(); |
| 281 | 297 | if (inFlight < minInFlight) { |
| 282 | 298 | minInFlight = inFlight; |
| @@ -304,7 +320,7 @@ | ||
| 304 | 320 | throw new TimeoutException(); |
| 305 | 321 | } |
| 306 | 322 | |
| 307 | - public void returnConnection(PooledConnection connection) { | |
| 323 | + public void returnConnection(Connection connection) { | |
| 308 | 324 | connection.inFlight.decrementAndGet(); |
| 309 | 325 | totalInFlight.decrementAndGet(); |
| 310 | 326 | |
| @@ -330,7 +346,7 @@ | ||
| 330 | 346 | |
| 331 | 347 | // Trash the connection and create a new one, but we don't call trashConnection |
| 332 | 348 | // directly because we want to make sure the connection is always trashed. |
| 333 | - private void replaceConnection(PooledConnection connection) { | |
| 349 | + private void replaceConnection(Connection connection) { | |
| 334 | 350 | if (!connection.state.compareAndSet(OPEN, TRASHED)) |
| 335 | 351 | return; |
| 336 | 352 | open.decrementAndGet(); |
| @@ -339,7 +355,7 @@ | ||
| 339 | 355 | doTrashConnection(connection); |
| 340 | 356 | } |
| 341 | 357 | |
| 342 | - private boolean trashConnection(PooledConnection connection) { | |
| 358 | + private boolean trashConnection(Connection connection) { | |
| 343 | 359 | if (!connection.state.compareAndSet(OPEN, TRASHED)) |
| 344 | 360 | return true; |
| 345 | 361 | |
| @@ -360,7 +376,7 @@ | ||
| 360 | 376 | return true; |
| 361 | 377 | } |
| 362 | 378 | |
| 363 | - private void doTrashConnection(PooledConnection connection) { | |
| 379 | + private void doTrashConnection(Connection connection) { | |
| 364 | 380 | connections.remove(connection); |
| 365 | 381 | trash.add(connection); |
| 366 | 382 | } |
| @@ -384,7 +400,7 @@ | ||
| 384 | 400 | |
| 385 | 401 | // Now really open the connection |
| 386 | 402 | try { |
| 387 | - PooledConnection newConnection = tryResurrectFromTrash(); | |
| 403 | + Connection newConnection = tryResurrectFromTrash(); | |
| 388 | 404 | if (newConnection == null) { |
| 389 | 405 | logger.debug("Creating new connection on busy pool to {}", host); |
| 390 | 406 | newConnection = manager.connectionFactory().open(this); |
| @@ -428,12 +444,12 @@ | ||
| 428 | 444 | } |
| 429 | 445 | } |
| 430 | 446 | |
| 431 | - private PooledConnection tryResurrectFromTrash() { | |
| 447 | + private Connection tryResurrectFromTrash() { | |
| 432 | 448 | long highestMaxIdleTime = System.currentTimeMillis(); |
| 433 | - PooledConnection chosen = null; | |
| 449 | + Connection chosen = null; | |
| 434 | 450 | |
| 435 | 451 | while (true) { |
| 436 | - for (PooledConnection connection : trash) | |
| 452 | + for (Connection connection : trash) | |
| 437 | 453 | if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) { |
| 438 | 454 | chosen = connection; |
| 439 | 455 | highestMaxIdleTime = connection.maxIdleTime; |
| @@ -461,7 +477,7 @@ | ||
| 461 | 477 | manager.blockingExecutor().submit(newConnectionTask); |
| 462 | 478 | } |
| 463 | 479 | |
| 464 | - void replaceDefunctConnection(final PooledConnection connection) { | |
| 480 | + void replaceDefunctConnection(final Connection connection) { | |
| 465 | 481 | if (connection.state.compareAndSet(OPEN, GONE)) |
| 466 | 482 | open.decrementAndGet(); |
| 467 | 483 | if (connections.remove(connection)) |
| @@ -499,7 +515,7 @@ | ||
| 499 | 515 | if (toTrash <= 0) |
| 500 | 516 | return; |
| 501 | 517 | |
| 502 | - for (PooledConnection connection : connections) | |
| 518 | + for (Connection connection : connections) | |
| 503 | 519 | if (trashConnection(connection)) { |
| 504 | 520 | toTrash -= 1; |
| 505 | 521 | if (toTrash == 0) |
| @@ -509,7 +525,7 @@ | ||
| 509 | 525 | |
| 510 | 526 | /** Close connections that have been sitting in the trash for too long */ |
| 511 | 527 | private void cleanupTrash(long now) { |
| 512 | - for (PooledConnection connection : trash) { | |
| 528 | + for (Connection connection : trash) { | |
| 513 | 529 | if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) { |
| 514 | 530 | if (connection.inFlight.get() == 0) { |
| 515 | 531 | logger.trace("Cleaning up {}", connection); |
| @@ -565,7 +581,7 @@ | ||
| 565 | 581 | |
| 566 | 582 | List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size()); |
| 567 | 583 | |
| 568 | - for (final PooledConnection connection : connections) { | |
| 584 | + for (final Connection connection : connections) { | |
| 569 | 585 | CloseFuture future = connection.closeAsync(); |
| 570 | 586 | future.addListener(new Runnable() { |
| 571 | 587 | public void run() { |
| @@ -577,7 +593,7 @@ | ||
| 577 | 593 | } |
| 578 | 594 | |
| 579 | 595 | // Some connections in the trash might still be open if they hadn't reached their idle timeout |
| 580 | - for (PooledConnection connection : trash) | |
| 596 | + for (Connection connection : trash) | |
| 581 | 597 | futures.add(connection.closeAsync()); |
| 582 | 598 | |
| 583 | 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) { | |
| 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/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 +10 −10
| @@ -77,7 +77,7 @@ | ||
| 77 | 77 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size()); |
| 78 | 78 | for (Host host : hosts) |
| 79 | 79 | if (host.state != Host.State.DOWN) |
| 80 | - futures.add(maybeAddPool(host)); | |
| 80 | + futures.add(maybeAddPool(host, null)); | |
| 81 | 81 | try { |
| 82 | 82 | Futures.successfulAsList(futures).get(); |
| 83 | 83 | } catch (ExecutionException e) { |
| @@ -192,7 +192,7 @@ | ||
| 192 | 192 | } |
| 193 | 193 | |
| 194 | 194 | // Returns whether there was problem creating the pool |
| 195 | - ListenableFuture<Boolean> forceRenewPool(final Host host) { | |
| 195 | + ListenableFuture<Boolean> forceRenewPool(final Host host, Connection reusedConnection) { | |
| 196 | 196 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 197 | 197 | if (distance == HostDistance.IGNORED) |
| 198 | 198 | return Futures.immediateFuture(true); |
| @@ -201,7 +201,7 @@ | ||
| 201 | 201 | return Futures.immediateFuture(false); |
| 202 | 202 | |
| 203 | 203 | final HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this); |
| 204 | - ListenableFuture<Void> poolInitFuture = newPool.initAsync(); | |
| 204 | + ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection); | |
| 205 | 205 | |
| 206 | 206 | final SettableFuture<Boolean> future = SettableFuture.create(); |
| 207 | 207 | |
| @@ -239,7 +239,7 @@ | ||
| 239 | 239 | |
| 240 | 240 | // Replace pool for a given host only if it's the given previous value (which can be null) |
| 241 | 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) { | |
| 242 | + private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous, Connection reusedConnection) { | |
| 243 | 243 | if (isClosing) |
| 244 | 244 | return MoreFutures.VOID_SUCCESS; |
| 245 | 245 | |
| @@ -258,7 +258,7 @@ | ||
| 258 | 258 | } |
| 259 | 259 | } |
| 260 | 260 | |
| 261 | - ListenableFuture<Void> poolInitFuture = newPool.initAsync(); | |
| 261 | + ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection); | |
| 262 | 262 | |
| 263 | 263 | Futures.addCallback(poolInitFuture, new FutureCallback<Void>() { |
| 264 | 264 | @Override |
| @@ -279,7 +279,7 @@ | ||
| 279 | 279 | } |
| 280 | 280 | |
| 281 | 281 | // Returns whether there was problem creating the pool |
| 282 | - ListenableFuture<Boolean> maybeAddPool(final Host host) { | |
| 282 | + ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) { | |
| 283 | 283 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 284 | 284 | if (distance == HostDistance.IGNORED) |
| 285 | 285 | return Futures.immediateFuture(true); |
| @@ -294,7 +294,7 @@ | ||
| 294 | 294 | return Futures.immediateFuture(true); |
| 295 | 295 | |
| 296 | 296 | final SettableFuture<Boolean> future = SettableFuture.create(); |
| 297 | - ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous); | |
| 297 | + ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous, reusedConnection); | |
| 298 | 298 | if (newPoolInit != null) { |
| 299 | 299 | Futures.addCallback(newPoolInit, new FutureCallback<Void>() { |
| 300 | 300 | @Override |
| @@ -358,7 +358,7 @@ | ||
| 358 | 358 | |
| 359 | 359 | if (pool == null) { |
| 360 | 360 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 361 | - poolCreationFutures.add(maybeAddPool(h)); | |
| 361 | + poolCreationFutures.add(maybeAddPool(h, null)); | |
| 362 | 362 | } else if (dist != pool.hostDistance) { |
| 363 | 363 | if (dist == HostDistance.IGNORED) { |
| 364 | 364 | toRemove.add(h); |
| @@ -397,7 +397,7 @@ | ||
| 397 | 397 | if (pool == null) { |
| 398 | 398 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 399 | 399 | try { |
| 400 | - maybeAddPool(h).get(); | |
| 400 | + maybeAddPool(h, null).get(); | |
| 401 | 401 | } catch (ExecutionException e) { |
| 402 | 402 | // Ignore, maybeAddPool has already handled the error |
| 403 | 403 | } |
| @@ -540,7 +540,7 @@ | ||
| 540 | 540 | |
| 541 | 541 | // Let's not wait too long if we can't get a connection. Things |
| 542 | 542 | // will fix themselves once the user tries a query anyway. |
| 543 | - PooledConnection c = null; | |
| 543 | + Connection c = null; | |
| 544 | 544 | boolean timedOut = false; |
| 545 | 545 | try { |
| 546 | 546 | c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS); |
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/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 | */ |
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 | } |