diff --git a/CHANGELOG.md b/CHANGELOG.md index 96594912..35f7c4ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +* Add `grpc_channel_shutdown_timeout` for graceful shutdown of channels removed by discovery in both drivers. + ## 3.37.0 ## * Add `topic_client.multiwriter()` for synchronous and asynchronous writes by key across partition splits and merges. * Wait for session status tasks to finish when closing an async `QuerySessionPool`. diff --git a/docs/driver.rst b/docs/driver.rst index 02d92cf6..a292202b 100644 --- a/docs/driver.rst +++ b/docs/driver.rst @@ -48,6 +48,9 @@ DriverConfig * - ``discovery_request_timeout`` - ``10`` - Timeout in seconds for each discovery request. + * - ``grpc_channel_shutdown_timeout`` + - ``60`` + - Maximum time in seconds for active RPCs, including streams, to finish on an endpoint removed by discovery. Set to ``0`` to close the channel immediately. The maximum accepted value is ``threading.TIMEOUT_MAX``. * - ``use_all_nodes`` - ``True`` - During ordinary discovery, shuffle endpoints across all datacenters. Set to ``False`` to try endpoints in the server-reported local datacenter first. @@ -137,6 +140,12 @@ There are three equivalent ways to specify the connection target: The connection string format is ``://:/?database=``. +After a successful discovery update, the synchronous and asynchronous drivers stop +routing new RPCs to removed endpoints. If a removed channel still has active RPCs +when ``grpc_channel_shutdown_timeout`` elapses, the driver closes the channel and +interrupts those RPCs. Set this option on ``DriverConfig`` or pass it directly +as a keyword argument when creating either driver. + Waiting for the Driver to Connect ---------------------------------- diff --git a/examples/README.md b/examples/README.md index 2896a66a..6fae85ea 100644 --- a/examples/README.md +++ b/examples/README.md @@ -34,6 +34,17 @@ export YDB_DATABASE=/local python3 __main__.py -e $YDB_ENDPOINT -d $YDB_DATABASE -p python-examples/$EXAMPLE ``` +To shorten the time spent draining channels after a discovery update, pass +`grpc_channel_shutdown_timeout` to the driver. This example gives active RPCs +on removed endpoints up to one second to finish. + +```python +import ydb + +with ydb.Driver(endpoint="grpc://localhost:2136", database="/local", grpc_channel_shutdown_timeout=1) as driver: + driver.wait(timeout=5, fail_fast=True) +``` + ## Running the examples on the self-hosted YDB cluster (1) Obtain the credentials for the self-hosted YDB cluster diff --git a/tests/aio/test_discovery_detect_local_dc.py b/tests/aio/test_discovery_detect_local_dc.py index ccf1bddf..8249f2d6 100644 --- a/tests/aio/test_discovery_detect_local_dc.py +++ b/tests/aio/test_discovery_detect_local_dc.py @@ -164,10 +164,17 @@ def add_cleanup_callback(self, callback): self.callbacks.append(callback) async def close(self, grace=30): + self._close() + + def _close(self): self.closed = True for callback in self.callbacks: callback(self) + def begin_retirement(self): + self._close() + return False + def primary_result(states, nodes=((1, "A"), (2, "B"))): message = _apis.ydb_discovery.ListEndpointsResult(self_location="local") diff --git a/tests/test_discovery_detect_local_dc.py b/tests/test_discovery_detect_local_dc.py index 25d128c7..5725394d 100644 --- a/tests/test_discovery_detect_local_dc.py +++ b/tests/test_discovery_detect_local_dc.py @@ -138,6 +138,10 @@ def close(self): for callback in self.callbacks: callback(self) + def begin_retirement(self): + self.close() + return False + def primary_response(states, nodes): message = _apis.ydb_discovery.ListEndpointsResult(self_location="local") @@ -379,7 +383,7 @@ def test_primary_connection_retirement_preserves_other_address_node_affinity(): assert cache.get(connection.EndpointKey(None, 1)) is new -def test_driver_uses_primary_pile_preference_from_config(monkeypatch): +def test_driver_applies_config_and_shutdown_timeout_keyword(monkeypatch): from ydb import topic, table, scheme, coordination seen = [] @@ -394,3 +398,15 @@ def test_driver_uses_primary_pile_preference_from_config(monkeypatch): config = driver.DriverConfig("grpc://test:2135", "/local", prefer_primary_pile=True) driver.Driver(config) assert seen[-1].prefer_primary_pile + assert seen[-1].grpc_channel_shutdown_timeout == 60 + + driver.Driver(endpoint="grpc://test:2135", database="/local", grpc_channel_shutdown_timeout=1) + assert seen[-1].grpc_channel_shutdown_timeout == 1 + + driver.Driver(config, database="/override", grpc_channel_shutdown_timeout=0) + assert seen[-1].grpc_channel_shutdown_timeout == 0 + assert seen[-1].database == "/override" + + with pytest.raises(ValueError, match="grpc_channel_shutdown_timeout"): + driver.Driver(config, grpc_channel_shutdown_timeout=-1) + assert config.grpc_channel_shutdown_timeout == 0 diff --git a/ydb/aio/connection.py b/ydb/aio/connection.py index 3bc72f92..c641b2d3 100644 --- a/ydb/aio/connection.py +++ b/ydb/aio/connection.py @@ -2,6 +2,7 @@ import logging import asyncio +import weakref from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING import collections import grpc @@ -81,22 +82,9 @@ async def _construct_metadata( class _RpcState(RpcState): - __slots__ = ( - "rpc", - "request_id", - "rendezvous", - "result_future", - "rpc_name", - "endpoint", - "metadata_kv", - "_trailing_metadata", - ) - - def __init__(self, stub_instance: Any, rpc_name: str, endpoint: str, endpoint_key): - super().__init__(stub_instance, rpc_name, endpoint, endpoint_key) + __slots__ = ("_trailing_metadata",) - async def __call__(self, *args, **kwargs): - resp = self.rpc(*args, **kwargs) + async def response(self, resp): if hasattr(resp, "__await__"): # Check to support async iterators from streams response = await resp self._trailing_metadata = await resp.trailing_metadata() @@ -131,9 +119,13 @@ def __aiter__(self): async def __anext__(self): try: return await self.it.__anext__() + except asyncio.CancelledError as error: + if self.rpc_state.channel_retired and self.resp.cancelled(): + raise issues.ConnectionLost("Endpoint removed by discovery") from error + raise except grpc.RpcError as rpc_error: ydb_error = _rpc_error_handler(self.rpc_state, rpc_error, use_unavailable=True) - if _is_disconnect_needed(ydb_error): + if _is_disconnect_needed(ydb_error) and not self.rpc_state.channel_retired: await self.on_disconnected_callback() raise ydb_error @@ -145,14 +137,13 @@ class Connection: __slots__ = ( "endpoint", "_channel", - "_call_states", + "_active_calls", "_stub_instances", "_driver_config", "_cleanup_callbacks", "__weakref__", - "lock", - "calls", "closing", + "_retiring", "endpoint_key", "node_id", "peer_address", @@ -180,8 +171,11 @@ def __init__( for stub in _stubs_list: self._stub_instances[stub] = stub(self._channel) - self.calls: Dict[Any, asyncio.Future[Any]] = {} + self._active_calls: Dict[ + _RpcState, Tuple[Optional[weakref.ReferenceType[grpc.aio.Call]], asyncio.Future[None]] + ] = {} self.closing = False + self._retiring = False def _prepare_stub_instance(self, stub: Any) -> None: if stub not in self._stub_instances: @@ -192,17 +186,31 @@ async def _prepare_call( ) -> Tuple[_RpcState, float, List[Tuple[str, str]]]: timeout, metadata = _get_request_timeout(settings), await _construct_metadata(self._driver_config, settings) # type: ignore[arg-type] _set_server_timeouts(request, settings, timeout) - self._prepare_stub_instance(stub) - rpc_state = _RpcState(self._stub_instances[stub], rpc_name, self.endpoint, self.endpoint_key) - logger.debug("%s: creating call state", rpc_state) - if self.closing: raise issues.ConnectionLost("Couldn't start call") - # Call successfully prepared and registered + self._prepare_stub_instance(stub) + rpc_state = _RpcState(self._stub_instances[stub], rpc_name, self.endpoint, self.endpoint_key) + logger.debug("%s: creating call state", rpc_state) _log_request(rpc_state, request) return rpc_state, timeout, metadata + def _track_call(self, rpc_state: _RpcState, call: Any) -> None: + def done(_call: Any) -> None: + self._finish_call(rpc_state) + + native = isinstance(call, grpc.aio.Call) + rpc_state.streaming = native and hasattr(call, "__aiter__") + ref = weakref.ref(call, done if rpc_state.streaming else None) if native else None + self._active_calls[rpc_state] = (ref, asyncio.get_running_loop().create_future()) + if rpc_state.streaming: + call.add_done_callback(done) + + def _finish_call(self, rpc_state: _RpcState) -> None: + entry = self._active_calls.pop(rpc_state, None) + if entry is not None: + entry[1].set_result(None) + async def __call__( self, request: Any, @@ -226,13 +234,11 @@ async def __call__( :return: A result of computation """ rpc_state, timeout, metadata = await self._prepare_call(stub, rpc_name, request, settings) + call = None try: - feature = asyncio.ensure_future(rpc_state(request, timeout=timeout, metadata=metadata)) - - # Add feature to dict to wait until it finished when close called - self.calls[rpc_state.request_id] = feature - - response = await feature + call = rpc_state.rpc(request, timeout=timeout, metadata=metadata) + self._track_call(rpc_state, call) + response = await rpc_state.response(call) _log_response(rpc_state, response) if hasattr(response, "__aiter__"): @@ -240,18 +246,21 @@ async def __call__( response = _SafeAsyncIterator(response, rpc_state, on_disconnected) return response if wrap_result is None else wrap_result(rpc_state, response, *wrap_args) + except asyncio.CancelledError as error: + if rpc_state.channel_retired and call is not None and call.cancelled(): + raise issues.ConnectionLost("Endpoint removed by discovery") from error + raise except grpc.RpcError as rpc_error: - if on_disconnected: + self._finish_call(rpc_state) + if on_disconnected and not rpc_state.channel_retired: coro = on_disconnected() if asyncio.iscoroutine(coro): await coro on_disconnected = None raise _rpc_error_handler(rpc_state, rpc_error, on_disconnected) finally: - self._finish_call(rpc_state) - - def _finish_call(self, call_state: _RpcState) -> None: - self.calls.pop(call_state.request_id, None) + if not rpc_state.streaming: + self._finish_call(rpc_state) async def destroy(self, grace: float = 0) -> None: """ @@ -260,13 +269,17 @@ async def destroy(self, grace: float = 0) -> None: :param grace: :return: None """ - channel = getattr(self, "_channel", None) + channel, self._channel = self._channel, None + self._stub_instances.clear() + if channel is not None and self._retiring: + for rpc_state, (call_ref, _) in list(self._active_calls.items()): + call = call_ref() if call_ref is not None else None + if call is not None and not call.done(): + rpc_state.channel_retired = True + call.cancel() if channel is not None and hasattr(channel, "close"): await channel.close(grace) - self._stub_instances.clear() - self._channel = None - def add_cleanup_callback(self, callback: Callable[["Connection"], None]) -> None: self._cleanup_callbacks.append(callback) @@ -286,17 +299,34 @@ async def close(self, grace: float = 30) -> None: been terminated are cancelled. If grace is None, this method will wait until all tasks are finished. :return: None """ + if self._start_close(): + try: + pending = [done for state, (_, done) in self._active_calls.items() if not state.streaming] + if pending: + await asyncio.wait(pending, timeout=grace) + finally: + await self.destroy() + + def _start_close(self, *, retiring: bool = False) -> bool: + if self.closing: + return False logger.debug("Closing channel for endpoint %s", self.endpoint) - self.closing = True - + self._retiring = retiring for callback in self._cleanup_callbacks: callback(self) + return True - if self.calls: - await asyncio.wait(self.calls.values(), timeout=grace) + def begin_retirement(self) -> bool: + return self._start_close(retiring=True) - await self.destroy() + async def finish_retirement(self, deadline: float) -> None: + pending = [completion for _, completion in self._active_calls.values()] + try: + if pending: + await asyncio.wait(pending, timeout=max(0, deadline - asyncio.get_running_loop().time())) + finally: + await self.destroy() async def __aenter__(self): return self diff --git a/ydb/aio/pool.py b/ydb/aio/pool.py index cf367891..1b2fcc16 100644 --- a/ydb/aio/pool.py +++ b/ydb/aio/pool.py @@ -8,7 +8,7 @@ from ydb import issues from ydb.observability.tracing import SpanName, create_ydb_span -from ydb.pool import ConnectionsCache as _ConnectionsCache, IConnectionPool +from ydb.pool import ConnectionsCache as _ConnectionsCache, IConnectionPool, _discovered_endpoint_maps from .connection import Connection, EndpointKey @@ -28,6 +28,7 @@ def __init__(self, use_all_nodes: bool = False) -> None: self._event: asyncio.Event = asyncio.Event() self._fast_fail_event: asyncio.Event = asyncio.Event() self._fast_fail_error: Optional[Exception] = None + self._retirement_tasks: dict[asyncio.Task[None], Connection] = {} async def get( # async version with different Connection type self, @@ -76,19 +77,39 @@ def complete_discovery(self, error: Optional[Exception]) -> None: def remove(self, connection: Connection) -> None: # type: ignore[override] # async Connection type if cast(Any, self.connections_by_node_id.get(connection.node_id)) is connection: self.connections_by_node_id.pop(connection.node_id, None) - self.preferred.pop(connection.endpoint, None) - self.connections.pop(connection.endpoint, None) - self.outdated.pop(connection.endpoint, None) + for connections in (self.preferred, self.connections, self.outdated): + if cast(Any, connections.get(connection.endpoint)) is connection: + connections.pop(connection.endpoint, None) if len(self.connections) == 0: self._event.clear() if not self._fast_fail_error: self._fast_fail_event.clear() async def cleanup(self) -> None: # type: ignore[override] # async override of sync method + retiring = self._retirement_tasks.copy() + for task in retiring: + task.cancel() + if retiring: + await asyncio.gather(*retiring, return_exceptions=True) + await asyncio.gather(*(connection.destroy() for connection in retiring.values())) actual_connections = list(self.connections.values()) for connection in actual_connections: await connection.close() + def retire(self, connection: Connection, grace: float) -> None: # type: ignore[override] # async Connection type + loop = asyncio.get_running_loop() + deadline = loop.time() + grace + if not connection.begin_retirement(): + return + task = loop.create_task(connection.finish_retirement(deadline)) + self._retirement_tasks[task] = connection + task.add_done_callback(self._retirement_done) + + def _retirement_done(self, task: asyncio.Task[None]) -> None: + connection = self._retirement_tasks.pop(task) + if not task.cancelled() and (error := task.exception()) is not None: + self.logger.error("Failed to close retired channel for endpoint %s", connection.endpoint, exc_info=error) + async def cleanup_outdated(self) -> "ConnectionsCache": # type: ignore[override] # async override of sync method outdated_connections = list(self.outdated.values()) for outdated_connection in outdated_connections: @@ -131,14 +152,10 @@ async def execute_discovery(self) -> bool: if resolve_details is None: return False - endpoint_locations = { - endpoint: resolved_endpoint.location - for resolved_endpoint in resolve_details.endpoints - for endpoint, endpoint_options in resolved_endpoint.endpoints_with_options() - } + endpoint_locations, node_ids = _discovered_endpoint_maps(resolve_details.endpoints) for cached_endpoint in self._cache.values(): - if cached_endpoint.endpoint not in endpoint_locations: - self._cache.make_outdated(cached_endpoint) + if cached_endpoint.node_id not in node_ids.get(cached_endpoint.endpoint, ()): + self._cache.retire(cast(Connection, cached_endpoint), self._driver_config.grpc_channel_shutdown_timeout) local_dc = resolve_details.self_location priorities = resolve_details.bridge_priorities(True) if self._driver_config.prefer_primary_pile else None @@ -225,29 +242,25 @@ def stop(self) -> None: self._wake_up_event.set() async def run(self) -> None: - while True: - try: - successful = await self.execute_discovery() - except Exception: - successful = False - if successful: - self._cache.complete_discovery(None) - else: - self._cache.complete_discovery(issues.ConnectionFailure(str(self.discovery_debug_details()))) - - interval = self._discovery_interval() if successful else self._emergency_retry_interval() - - try: - await asyncio.wait_for(self._wake_up_event.wait(), timeout=interval) - if self._should_stop: - break + try: + while not self._should_stop: + try: + successful = await self.execute_discovery() + except Exception: + successful = False + if successful: + self._cache.complete_discovery(None) else: - self._wake_up_event.clear() - continue - except asyncio.TimeoutError: - continue + self._cache.complete_discovery(issues.ConnectionFailure(str(self.discovery_debug_details()))) - await self._cache.cleanup() + interval = self._discovery_interval() if successful else self._emergency_retry_interval() + try: + await asyncio.wait_for(self._wake_up_event.wait(), timeout=interval) + except asyncio.TimeoutError: + pass + self._wake_up_event.clear() + finally: + await self._cache.cleanup() self.logger.info("Successfully terminated discovery process") diff --git a/ydb/aio/query/pool_test.py b/ydb/aio/query/pool_test.py index 3ae79ca5..611a3f29 100644 --- a/ydb/aio/query/pool_test.py +++ b/ydb/aio/query/pool_test.py @@ -2,10 +2,15 @@ import asyncio import unittest + +import grpc from unittest.mock import AsyncMock, MagicMock, patch -from ydb import _apis, issues +from ydb import _apis, issues, resolver from ydb.aio import _utilities as aio_utilities +from ydb.aio import connection as aio_connection +from ydb.aio import pool as aio_pool +from ydb.aio.driver import DriverConfig from ydb.aio.query.pool import QuerySessionPool from ydb.aio.query.session import QuerySession from ydb.aio.query.transaction import QueryTxContext @@ -38,6 +43,85 @@ async def _wait_signalled(event: asyncio.Event) -> None: await asyncio.wait_for(event.wait(), timeout=5) +class TestDiscoveryChannelRetirement(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.config = DriverConfig("localhost:2135", "/local") + self.cache = aio_pool.ConnectionsCache() + self.channel = MagicMock() + self.channel.close = AsyncMock() + with patch.object(aio_connection, "channel_factory", return_value=self.channel): + self.connection = aio_connection.Connection(self.config.endpoint, self.config) + self.cache.add(self.connection) + self.addAsyncCleanup(self.cache.cleanup) + + async def test_cleanup_closes_channel_before_retirement_task_starts(self): + self.cache.retire(self.connection, self.config.grpc_channel_shutdown_timeout) + self.cache.retire(self.connection, self.config.grpc_channel_shutdown_timeout) + self.assertEqual(len(self.cache._retirement_tasks), 1) + self.assertEqual(self.cache.size, 0) + + await self.cache.cleanup() + + self.channel.close.assert_awaited_once() + self.assertFalse(self.cache._retirement_tasks) + + async def test_failed_channel_close_releases_retirement_task(self): + self.channel.close.side_effect = RuntimeError("close failed") + with self.assertLogs("ydb.pool", level="ERROR") as logs: + self.cache.retire(self.connection, 0) + await asyncio.gather(*self.cache._retirement_tasks, return_exceptions=True) + + self.assertIn("Failed to close retired channel", logs.output[0]) + self.assertFalse(self.cache._retirement_tasks) + + async def test_discovery_cancellation_closes_retired_channel(self): + discovery = aio_pool.Discovery(self.cache, self.config) + discovery._base_emergency_retry_interval = 0 + resolving_again = asyncio.Event() + + async def resolve(): + if discovery._resolver.resolve.await_count == 1: + return resolver.DiscoveryResult("local", []) + resolving_again.set() + await asyncio.Future() + + discovery._resolver.resolve = AsyncMock(side_effect=resolve) + call = MagicMock(spec=grpc.aio.Call) + call.done.return_value = False + self.connection._track_call(MagicMock(), call) + + task = asyncio.create_task(discovery.run()) + try: + await _wait_signalled(resolving_again) + self.assertEqual(self.cache.size, 0) + self.channel.close.assert_not_awaited() + finally: + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + + call.cancel.assert_called_once() + self.channel.close.assert_awaited_once() + self.assertFalse(self.cache._retirement_tasks) + + async def test_discovery_can_stop_after_recovering_from_a_failed_round(self): + discovery = aio_pool.Discovery(self.cache, self.config) + discovery._base_emergency_retry_interval = 0 + + async def execute(): + if discovery.execute_discovery.await_count == 1: + raise RuntimeError("discovery unavailable") + discovery.stop() + return True + + discovery.execute_discovery = AsyncMock(side_effect=execute) + await asyncio.wait_for(discovery.run(), timeout=3) + + self.assertEqual(discovery.execute_discovery.await_count, 2) + self.assertIsNone(self.cache._fast_fail_error) + self.channel.close.assert_awaited_once() + + class TestAcquireTimeout(unittest.IsolatedAsyncioTestCase): async def test_acquire_returns_session_when_available(self): pool = _make_pool(size=2) diff --git a/ydb/connection.py b/ydb/connection.py index 052b563e..9bf716f9 100644 --- a/ydb/connection.py +++ b/ydb/connection.py @@ -3,8 +3,10 @@ import copy from concurrent import futures import uuid +import weakref import threading import collections +import time from typing import ( Any, Callable, @@ -99,6 +101,8 @@ def _rpc_error_handler( elif rpc_error.code() == grpc.StatusCode.UNIMPLEMENTED: return issues.Unimplemented("Method or feature is not implemented on server!") elif rpc_error.code() == grpc.StatusCode.CANCELLED: + if isinstance(rpc_state, _RpcState) and rpc_state.channel_retired: + return issues.ConnectionLost("Endpoint removed by discovery") return issues.Cancelled(rpc_error.details()) elif rpc_error.code() == grpc.StatusCode.RESOURCE_EXHAUSTED: if "Sent message larger than max" in rpc_error.details(): @@ -154,8 +158,8 @@ def _on_response_callback(rpc_state, call_state_unref, wrap_result=None, on_disc except Exception as e: logger.error("%s: received exception, %s", rpc_state, str(e)) rpc_state.result_future.set_exception(issues.ConnectionLost(str(e))) - - call_state_unref() + finally: + call_state_unref() def _construct_metadata(driver_config, settings): @@ -239,6 +243,8 @@ def _construct_channel_options(driver_config, endpoint_options=None): ) if endpoint_options is not None: + # A replacement channel must not reuse a retired channel's transport. + _default_connect_options.append(("grpc.use_local_subchannel_pool", 1)) if endpoint_options.ssl_target_name_override: _default_connect_options.append( ( @@ -265,6 +271,8 @@ class _RpcState: "rendezvous", "metadata_kv", "endpoint_key", + "channel_retired", + "streaming", ) rpc: Any @@ -285,6 +293,8 @@ def __init__(self, stub_instance: Any, rpc_name: str, endpoint: str, endpoint_ke self.rendezvous = None self.metadata_kv = None self.endpoint_key = endpoint_key + self.channel_retired = False + self.streaming = False def __str__(self) -> str: return "RpcState(%s, %s, %s)" % (self.rpc_name, self.request_id, self.endpoint) @@ -292,11 +302,19 @@ def __str__(self) -> str: def __call__(self, *args: Any, **kwargs: Any) -> Any: """Execute a RPC.""" try: - response, rendezvous = self.rpc.with_call(*args, **kwargs) + response, rendezvous = self._start_rpc(self.rpc.with_call, *args, **kwargs) self.rendezvous = rendezvous return response except AttributeError: - return self.rpc(*args, **kwargs) + return self._start_rpc(self.rpc, *args, **kwargs) + + def _start_rpc(self, start: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + try: + return start(*args, **kwargs) + except ValueError as error: + if self.channel_retired: + raise issues.ConnectionLost("Endpoint removed by discovery") from error + raise def trailing_metadata(self) -> Dict[str, set]: """Trailing metadata of the call.""" @@ -308,7 +326,7 @@ def trailing_metadata(self) -> Dict[str, set]: return self.metadata_kv def future(self, *args: Any, **kwargs: Any) -> Tuple[Any, "futures.Future[Any]"]: - self.rendezvous = self.rpc.future(*args, **kwargs) + self.rendezvous = self._start_rpc(self.rpc.future, *args, **kwargs) self.result_future = futures.Future() def _cancel_callback(f: Any) -> None: @@ -374,27 +392,40 @@ def __init__(self, endpoint, node_id): class _SafeSyncIterator: - def __init__(self, resp, rpc_state, on_disconnected_callback): + def __init__(self, resp, rpc_state, on_disconnected_callback, on_finished=None): self.resp = resp - self.it = resp.__iter__() + self.it = iter(resp) self.rpc_state = rpc_state self.on_disconnected_callback = on_disconnected_callback + self._finish = weakref.finalize(self, on_finished) if on_finished is not None else None def cancel(self): - self.resp.cancel() + cancel = getattr(self.resp, "cancel", None) or self.resp.close + cancel() + if self._finish is not None: + self._finish() return self + def close(self): + self.cancel() + def __iter__(self): return self def __next__(self): try: - return self.it.__next__() - except grpc.RpcError as rpc_error: - ydb_error = _rpc_error_handler(self.rpc_state, rpc_error, use_unavailable=True) - if _is_disconnect_needed(ydb_error): - self.on_disconnected_callback() - raise ydb_error + return next(self.it) + except BaseException as error: + if self._finish is not None: + self._finish() + if isinstance(error, ValueError) and self.rpc_state.channel_retired: + raise issues.ConnectionLost("Endpoint removed by discovery") from error + if isinstance(error, grpc.RpcError): + ydb_error = _rpc_error_handler(self.rpc_state, error, use_unavailable=True) + if _is_disconnect_needed(ydb_error) and not self.rpc_state.channel_retired: + self.on_disconnected_callback() + raise ydb_error + raise def __getattr__(self, item): return getattr(self.resp, item) @@ -404,14 +435,14 @@ class Connection(object): __slots__ = ( "endpoint", "_channel", - "_call_states", + "_active_calls", "_stub_instances", "_driver_config", "_cleanup_callbacks", "__weakref__", "lock", - "calls", "closing", + "_retiring", "endpoint_key", "node_id", "peer_address", @@ -439,15 +470,15 @@ def __init__( self.endpoint_key = EndpointKey(endpoint, getattr(endpoint_options, "node_id", None)) self._channel = channel_factory(self.endpoint, driver_config, endpoint_options=endpoint_options) self._driver_config = driver_config - self._call_states: Dict[Any, "_RpcState"] = {} + self._active_calls: set[_RpcState] = set() self._stub_instances: Dict[Any, Any] = {} self._cleanup_callbacks: List[Callable[["Connection"], None]] = [] # pre-initialize stubs for stub in _stubs_list: self._stub_instances[stub] = stub(self._channel) - self.lock = threading.RLock() - self.calls = 0 + self.lock = threading.Condition() self.closing = False + self._retiring = False def _prepare_stub_instance(self, stub): if stub not in self._stub_instances: @@ -459,26 +490,36 @@ def add_cleanup_callback(self, callback): def _prepare_call(self, stub, rpc_name, request, settings): timeout, metadata = _get_request_timeout(settings), _construct_metadata(self._driver_config, settings) _set_server_timeouts(request, settings, timeout) - self._prepare_stub_instance(stub) - rpc_state = _RpcState(self._stub_instances[stub], rpc_name, self.endpoint, self.endpoint_key) - logger.debug("%s: creating call state", rpc_state) with self.lock: if self.closing: raise issues.ConnectionLost("Couldn't start call") - self.calls += 1 - self._call_states[rpc_state.request_id] = rpc_state + self._prepare_stub_instance(stub) + rpc_state = _RpcState(self._stub_instances[stub], rpc_name, self.endpoint, self.endpoint_key) + logger.debug("%s: creating call state", rpc_state) + self._active_calls.add(rpc_state) # Call successfully prepared and registered _log_request(rpc_state, request) return rpc_state, timeout, metadata - def _finish_call(self, call_state): + def _finish_call(self, state: _RpcState, *, streaming: bool = False) -> None: with self.lock: - self.calls -= 1 - self._call_states.pop(call_state.request_id, None) - # Call successfully finished - if self.closing and self.calls == 0: - # Channel is closing and we have to destroy channel - self.destroy() + state.streaming = streaming + if not streaming: + self._active_calls.discard(state) + self.lock.notify_all() + close_channel = self.closing and not self._retiring and all(call.streaming for call in self._active_calls) + if close_channel: + self.destroy() + + def _wrap_stream(self, response, state, on_disconnected): + def done(): + self._finish_call(state) + + if isinstance(response, grpc.Call): + if not response.add_callback(done): + done() + return _SafeSyncIterator(response, state, on_disconnected) + return _SafeSyncIterator(response, state, on_disconnected, on_finished=done) def future( self, @@ -503,12 +544,16 @@ def future( :return: A future of computation """ rpc_state, timeout, metadata = self._prepare_call(stub, rpc_name, request, settings) - rendezvous, result_future = rpc_state.future( - request, - timeout, - metadata, - compression=getattr(settings, "compression", None), - ) + try: + rendezvous, result_future = rpc_state.future( + request, + timeout, + metadata, + compression=getattr(settings, "compression", None), + ) + except BaseException: + self._finish_call(rpc_state) + raise rendezvous.add_done_callback( lambda resp_future: _on_response_callback( rpc_state, @@ -543,6 +588,7 @@ def __call__( :return: A result of computation """ rpc_state, timeout, metadata = self._prepare_call(stub, rpc_name, request, settings) + streaming = False try: response = rpc_state( request, @@ -552,15 +598,17 @@ def __call__( ) _log_response(rpc_state, response) - if hasattr(response, "__iter__"): - # NOTE(vgvoleg): for stream results we should also be able to handle disconnects + if hasattr(response, "__next__"): + response = self._wrap_stream(response, rpc_state, on_disconnected) + streaming = True + elif hasattr(response, "__iter__"): response = _SafeSyncIterator(response, rpc_state, on_disconnected) return response if wrap_result is None else wrap_result(rpc_state, response, *wrap_args) except grpc.RpcError as rpc_error: raise _rpc_error_handler(rpc_state, rpc_error, on_disconnected) finally: - self._finish_call(rpc_state) + self._finish_call(rpc_state, streaming=streaming) @classmethod def ready_factory(cls, endpoint, driver_config, ready_timeout=10, endpoint_options=None): @@ -584,33 +632,47 @@ def __enter__(self): def __exit__(self, exc_type, exc_val, exc_tb): self.close() - def close(self): - """ - Closes the underlying gRPC channel - :return: None - """ - logger.debug("Closing channel for endpoint %s", self.endpoint) + def _start_close(self, *, retiring: bool = False) -> bool: with self.lock: + if self.closing: + return False self.closing = True + self._retiring = retiring + logger.debug("Closing channel for endpoint %s", self.endpoint) - for callback in self._cleanup_callbacks: - callback(self) - - # potentially we should cancel in-flight calls here but currently - # it is not required since gRPC can successfully cancel these calls manually. + for callback in self._cleanup_callbacks: + callback(self) + return True - if self.calls == 0: - # everything is cancelled/completed and channel can be destroyed + def close(self): + if self._start_close(): + with self.lock: + idle = all(call.streaming for call in self._active_calls) + if idle: self.destroy() + def begin_retirement(self) -> bool: + return self._start_close(retiring=True) + + def finish_retirement(self, deadline: float) -> None: + with self.lock: + self.lock.wait_for( + lambda: self._channel is None or not self._active_calls, + timeout=max(0, deadline - time.monotonic()), + ) + self.destroy() + def destroy(self): - channel = getattr(self, "_channel", None) + with self.lock: + channel, self._channel = self._channel, None + if channel is not None and self._retiring: + for rpc_state in self._active_calls: + rpc_state.channel_retired = True + self._stub_instances.clear() + self.lock.notify_all() if channel is not None and hasattr(channel, "close"): channel.close() - self._stub_instances.clear() - self._channel = None - def ready_future(self): """ Creates a future that tracks underlying gRPC channel is ready diff --git a/ydb/driver.py b/ydb/driver.py index 51afa9b1..30c6f8d4 100644 --- a/ydb/driver.py +++ b/ydb/driver.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import grpc import logging +import threading import os from typing import Any, List, Optional, Tuple, Type, TYPE_CHECKING @@ -17,6 +18,11 @@ logger = logging.getLogger(__name__) +def _validate_grpc_channel_shutdown_timeout(timeout: float) -> None: + if not 0 <= timeout <= threading.TIMEOUT_MAX: + raise ValueError(f"grpc_channel_shutdown_timeout must be between 0 and {threading.TIMEOUT_MAX} seconds") + + class RPCCompression: """Indicates the compression method to be used for an RPC.""" @@ -110,6 +116,7 @@ class DriverConfig(object): "tracer", "grpc_lb_policy_name", "discovery_request_timeout", + "grpc_channel_shutdown_timeout", "compression", "disable_discovery", "detect_local_dc", @@ -143,6 +150,7 @@ def __init__( detect_local_dc: bool = False, *, prefer_primary_pile: bool = False, + grpc_channel_shutdown_timeout: float = 60, _additional_sdk_headers: Tuple[str, ...] = (), ) -> None: """ @@ -164,6 +172,8 @@ def __init__( If tracing aio ScopeManager must be ContextVarsScopeManager :param grpc_lb_policy_name: A load balancing policy to be used for discovery channel construction. Default value is `round_robin` :param discovery_request_timeout: A default timeout to complete the discovery. The default value is 10 seconds. + :param grpc_channel_shutdown_timeout: Seconds to let active RPCs finish after discovery removes + their endpoint. Defaults to 60. Set to 0 to close removed channels immediately. :param disable_discovery: If True, endpoint discovery is disabled and only the start endpoint is used for all requests. :param detect_local_dc: If True, detect nearest datacenter using TCP latency measurement instead of using\ server-provided self_location. **Note**: This option only affects endpoint selection when use_all_nodes=False.\ @@ -198,6 +208,8 @@ def __init__( self.tracer = tracer if tracer is not None else tracing.Tracer(None) self.grpc_lb_policy_name = grpc_lb_policy_name self.discovery_request_timeout = discovery_request_timeout + _validate_grpc_channel_shutdown_timeout(grpc_channel_shutdown_timeout) + self.grpc_channel_shutdown_timeout = grpc_channel_shutdown_timeout self.compression = compression self.disable_discovery = disable_discovery self.detect_local_dc = detect_local_dc @@ -249,6 +261,8 @@ def set_grpc_keep_alive_timeout(self, timeout: int) -> "DriverConfig": def _update_attrs_by_kwargs(self, **kwargs: Any) -> None: for key, value in kwargs.items(): if value is not None: + if key == "grpc_channel_shutdown_timeout": + _validate_grpc_channel_shutdown_timeout(value) if getattr(self, key) is not None: logger.warning( f"Arg {key} was used in both DriverConfig and Driver. Value from Driver will be used." @@ -267,8 +281,13 @@ def get_config( root_certificates: Optional[bytes] = None, credentials: Optional["Credentials"] = None, config_class: Type[DriverConfig] = DriverConfig, + *, + grpc_channel_shutdown_timeout: Optional[float] = None, **kwargs: Any, ) -> DriverConfig: + if grpc_channel_shutdown_timeout is not None: + kwargs["grpc_channel_shutdown_timeout"] = grpc_channel_shutdown_timeout + if driver_config is None: if connection_string is not None: driver_config = config_class.default_from_connection_string( @@ -307,6 +326,8 @@ def __init__( database: Optional[str] = None, root_certificates: Optional[bytes] = None, credentials: Optional["Credentials"] = None, + *, + grpc_channel_shutdown_timeout: Optional[float] = None, **kwargs: Any, ) -> None: """ @@ -319,6 +340,7 @@ def __init__( :param endpoint: An endpoint specified in the following format: ://: :param database: A database path :param credentials: A credentials. If not specified credentials constructed by default. + :param grpc_channel_shutdown_timeout: Maximum time in seconds to drain channels removed by discovery. """ from . import topic # local import for prevent cycle import error from . import coordination # local import for prevent cycle import error @@ -330,6 +352,7 @@ def __init__( database, root_certificates, credentials, + grpc_channel_shutdown_timeout=grpc_channel_shutdown_timeout, ) super(Driver, self).__init__(driver_config) diff --git a/ydb/pool.py b/ydb/pool.py index 6e362c83..77a3d944 100644 --- a/ydb/pool.py +++ b/ydb/pool.py @@ -7,7 +7,8 @@ from concurrent import futures import collections import random -from typing import Any, Callable, ContextManager, Dict, List, Optional, Set, Tuple, TYPE_CHECKING +import time +from typing import Any, Callable, ContextManager, Dict, Iterable, List, Optional, Set, Tuple, TYPE_CHECKING from . import connection as connection_impl, issues, resolver, _utilities, tracing from .observability.tracing import SpanName, create_ydb_span @@ -22,6 +23,18 @@ logger = logging.getLogger(__name__) +def _discovered_endpoint_maps( + endpoints: Iterable[resolver.EndpointInfo], +) -> Tuple[Dict[str, str], Dict[str, Set[int]]]: + locations: Dict[str, str] = {} + node_ids: Dict[str, Set[int]] = collections.defaultdict(set) + for info in endpoints: + for address, _ in info.endpoints_with_options(): + locations[address] = info.location + node_ids[address].add(info.node_id) + return locations, node_ids + + class ConnectionsCache: lock: ContextManager[Any] @@ -31,6 +44,7 @@ def __init__(self, use_all_nodes: bool = False, tracer: tracing.Tracer = tracing self.connections: collections.OrderedDict[str, Connection] = collections.OrderedDict() self.connections_by_node_id: collections.OrderedDict[Optional[int], Connection] = collections.OrderedDict() self.outdated: collections.OrderedDict[str, Connection] = collections.OrderedDict() + self._retiring: Set[Connection] = set() self.subscriptions: Set["futures.Future[None]"] = set() self.preferred: collections.OrderedDict[str, Connection] = collections.OrderedDict() self.logger = logging.getLogger(__name__) @@ -141,15 +155,37 @@ def make_outdated(self, connection: Connection) -> "ConnectionsCache": def cleanup_outdated(self) -> "ConnectionsCache": with self.lock: outdated_connections = list(self.outdated.values()) - for outdated_connection in outdated_connections: - outdated_connection.close() + for outdated_connection in outdated_connections: + outdated_connection.close() return self + def retire(self, connection: Connection, grace: float) -> None: + deadline = time.monotonic() + grace + if not connection.begin_retirement(): + return + with self.lock: + self._retiring.add(connection) + try: + threading.Thread(target=self._finish_retirement, args=(connection, deadline), daemon=True).start() + except RuntimeError: + self.logger.warning("Cannot start channel retirement thread for %s", connection.endpoint, exc_info=True) + self._finish_retirement(connection, time.monotonic()) + + def _finish_retirement(self, connection: Connection, deadline: float) -> None: + try: + connection.finish_retirement(deadline) + finally: + with self.lock: + self._retiring.discard(connection) + def cleanup(self) -> None: with self.lock: actual_connections = list(self.connections.values()) - for connection in actual_connections: - connection.close() + retiring_connections = list(self._retiring) + for connection in retiring_connections: + connection.destroy() + for connection in actual_connections: + connection.close() def complete_discovery(self, error: Optional[Exception]) -> None: with self.lock: @@ -198,9 +234,9 @@ def remove(self, connection: Connection) -> None: with self.lock: if self.connections_by_node_id.get(connection.node_id) is connection: self.connections_by_node_id.pop(connection.node_id, None) - self.preferred.pop(connection.endpoint, None) - self.connections.pop(connection.endpoint, None) - self.outdated.pop(connection.endpoint, None) + for connections in (self.preferred, self.connections, self.outdated): + if connections.get(connection.endpoint) is connection: + connections.pop(connection.endpoint, None) def get_connection_by_node_id(self, node_id: Optional[int]) -> Optional[Connection]: with self.lock: @@ -270,14 +306,10 @@ def execute_discovery(self) -> bool: if resolve_details is None: return False - endpoint_locations = { - endpoint: resolved_endpoint.location - for resolved_endpoint in resolve_details.endpoints - for endpoint, endpoint_options in resolved_endpoint.endpoints_with_options() - } + endpoint_locations, node_ids = _discovered_endpoint_maps(resolve_details.endpoints) for cached_endpoint in self._cache.values(): - if cached_endpoint.endpoint not in endpoint_locations: - self._cache.make_outdated(cached_endpoint) + if cached_endpoint.node_id not in node_ids.get(cached_endpoint.endpoint, ()): + self._cache.retire(cached_endpoint, self._driver_config.grpc_channel_shutdown_timeout) local_dc = resolve_details.self_location priorities = resolve_details.bridge_priorities(True) if self._driver_config.prefer_primary_pile else None @@ -367,23 +399,25 @@ def stop(self) -> None: self._send_wake_up() def run(self) -> None: - with self.condition: - while True: - if self._should_stop.is_set(): - break - - successful = self.execute_discovery() - if successful: - self._cache.complete_discovery(None) - else: - self._cache.complete_discovery(issues.ConnectionFailure(str(self.discovery_debug_details()))) - - if self._should_stop.is_set(): - break - - interval = self._discovery_interval() if successful else self._emergency_retry_interval() - self.condition.wait(interval) - + try: + with self.condition: + while not self._should_stop.is_set(): + try: + successful = self.execute_discovery() + except Exception: + self.logger.exception("Endpoint discovery failed") + successful = False + if successful: + self._cache.complete_discovery(None) + else: + self._cache.complete_discovery(issues.ConnectionFailure(str(self.discovery_debug_details()))) + + if self._should_stop.is_set(): + break + + interval = self._discovery_interval() if successful else self._emergency_retry_interval() + self.condition.wait(interval) + finally: self._cache.cleanup() self.logger.info("Successfully terminated discovery process") diff --git a/ydb/query/pool_test.py b/ydb/query/pool_test.py index 6dd1677b..a061d59a 100644 --- a/ydb/query/pool_test.py +++ b/ydb/query/pool_test.py @@ -2,14 +2,17 @@ import asyncio import concurrent.futures +import inspect import threading import time import unittest -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock, patch -from unittest.mock import patch +import grpc +import pytest -from ydb import _utilities, issues +from ydb import _apis, _utilities, connection, driver, issues, pool, resolver +from ydb.aio import pool as aio_pool from ydb.convert import _ResultSet, aggregate_result_sets_by_index, aggregate_result_sets_by_index_async from ydb.query.base import create_execute_query_request from ydb.query.pool import QuerySessionPool @@ -416,3 +419,410 @@ def fake_execute_call(**kwargs): tx.execute("SELECT 1") self.assertIsNone(captured.get("pool_id")) + + +@pytest.fixture +def grpc_stream_server(): + release = threading.Event() + finished = threading.Event() + started = threading.Event() + + def stream(request, context): + context.add_callback(finished.set) + yield context.peer().encode() + if release.wait(5) and context.is_active(): + if request == b"unavailable": + context.abort(grpc.StatusCode.UNAVAILABLE, "test connection loss") + if request == b"cancelled": + context.abort(grpc.StatusCode.CANCELLED, "test cancellation") + yield b"last response" + + def unary(request, context): + context.add_callback(finished.set) + started.set() + release.wait(5) + if request == b"unavailable": + context.abort(grpc.StatusCode.UNAVAILABLE, "test connection loss") + return b"unary response" + + with concurrent.futures.ThreadPoolExecutor() as executor: + server = grpc.server(executor) + server.add_generic_rpc_handlers( + ( + grpc.method_handlers_generic_handler( + "Test", + { + "Stream": grpc.unary_stream_rpc_method_handler(stream), + "BidiStream": grpc.stream_stream_rpc_method_handler(stream), + "Peer": grpc.unary_unary_rpc_method_handler(lambda _request, context: context.peer().encode()), + "Unary": grpc.unary_unary_rpc_method_handler(unary), + }, + ), + ) + ) + port = server.add_insecure_port("127.0.0.1:0") + server.start() + try: + yield port, release, finished, started + finally: + release.set() + server.stop(0).wait(5) + + +class StreamStub: + def __init__(self, channel): + self.Stream = channel.unary_stream("/Test/Stream") + self.BidiStream = channel.stream_stream("/Test/BidiStream") + self.Peer = channel.unary_unary("/Test/Peer") + self.Unary = channel.unary_unary("/Test/Unary") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize( + "timeout,method,finish", + [(0, "Stream", "deadline"), (0.5, "BidiStream", "deadline"), (60, "Stream", "drain"), (60, "Stream", "shutdown")], + ids=["immediate", "force-bidi", "drain", "shutdown"], +) +async def test_discovery_drains_live_channel(grpc_stream_server, is_async, timeout, method, finish): + port, release, finished, _ = grpc_stream_server + config = driver.DriverConfig(f"grpc://127.0.0.1:{port}", "/local", grpc_channel_shutdown_timeout=timeout) + module = aio_pool if is_async else pool + cache = module.ConnectionsCache() + discovery = module.Discovery(cache, config) + + def publish(*node_ids): + endpoints = _apis.ydb_discovery.ListEndpointsResult(self_location="local") + for node_id in node_ids: + endpoints.endpoints.add(address="127.0.0.1", port=port, node_id=node_id, location="local") + response = _apis.ydb_discovery.ListEndpointsResponse() + response.operation.status = _apis.StatusIds.SUCCESS + response.operation.result.Pack(endpoints) + result = resolver.DiscoveryResult.from_response(None, response) + assert sorted(endpoint.node_id for endpoint in result.endpoints) == sorted(set(node_ids)) + result.endpoints.sort(key=lambda endpoint: endpoint.node_id) + if is_async: + discovery._resolver.resolve = AsyncMock(return_value=result) + else: + discovery._resolver.context_resolve = MagicMock() + discovery._resolver.context_resolve.return_value.__enter__.return_value = result + + async def call(fn, *args): + result = fn(*args) + return await result if inspect.isawaitable(result) else result + + async def read(stream): + return await anext(stream) if is_async else next(stream) + + async def wait_for_close(connection): + while connection._channel is not None: + await asyncio.sleep(0.01) + + try: + publish(1) + assert await call(discovery.execute_discovery) + old = await call(cache.get) + stream = await call(old, iter(()) if method == "BidiStream" else b"", StreamStub, method) + old_peer = await read(stream) + + publish(1, 1, 2) + assert await call(discovery.execute_discovery) + assert await call(cache.get) is old + + publish(2) + assert await call(discovery.execute_discovery) + replacement = await call(cache.get, connection.EndpointKey(old.endpoint, 1)) + assert replacement is not old and replacement.node_id == 2 + with pytest.raises(issues.ConnectionLost): + await call(old, b"", StreamStub, "Peer") + + if timeout: + assert not finished.is_set() + + # The node is still reachable, and the replacement has its own transport. + replacement_peer = await call(replacement, b"", StreamStub, "Peer") + assert bytes(replacement_peer) != old_peer + if finish == "drain": + release.set() + assert await read(stream) == b"last response" + else: + if finish == "shutdown": + await call(cache.cleanup) + assert await asyncio.to_thread(finished.wait, 3) + with pytest.raises(issues.ConnectionLost): + await read(stream) + + await asyncio.wait_for(wait_for_close(old), timeout=3) + if finish != "shutdown": + assert await call(cache.get) is replacement + finally: + await call(cache.cleanup) + + +@pytest.mark.parametrize("timeout", [-1, float("inf"), float("nan"), threading.TIMEOUT_MAX * 2]) +def test_shutdown_timeout_rejects_invalid_values(timeout): + with pytest.raises(ValueError, match="grpc_channel_shutdown_timeout"): + driver.DriverConfig("localhost:2135", grpc_channel_shutdown_timeout=timeout) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call_style", ["sync", "future", "async"]) +async def test_retiring_channel_interrupts_pending_unary_rpc(grpc_stream_server, call_style): + port, _, finished, started = grpc_stream_server + is_async = call_style == "async" + module = aio_pool if is_async else pool + cache = module.ConnectionsCache() + endpoint = f"127.0.0.1:{port}" + conn = module.Connection(endpoint, driver.DriverConfig(endpoint, "/local")) + cache.add(conn) + try: + if is_async: + response = asyncio.create_task(conn(b"", StreamStub, "Unary")) + elif call_style == "future": + response = asyncio.wrap_future(conn.future(b"", StreamStub, "Unary")) + else: + response = asyncio.create_task(asyncio.to_thread(conn, b"", StreamStub, "Unary")) + assert await asyncio.to_thread(started.wait, 3) + + cache.retire(conn, 0) + with pytest.raises(issues.ConnectionLost): + await asyncio.wait_for(response, timeout=3) + assert await asyncio.to_thread(finished.wait, 3) + finally: + if is_async: + await cache.cleanup() + else: + cache.cleanup() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["Stream", "Unary"]) +async def test_caller_cancellation_does_not_retire_channel(grpc_stream_server, method): + port, _, _, started = grpc_stream_server + endpoint = f"127.0.0.1:{port}" + async with aio_pool.Connection(endpoint, driver.DriverConfig(endpoint, "/local")) as conn: + if method == "Stream": + stream = await conn(b"", StreamStub, method) + peer = await anext(stream) + stream.cancel() + with pytest.raises(asyncio.CancelledError): + await anext(stream) + assert await conn(b"", StreamStub, "Peer") == peer + else: + response = asyncio.create_task(conn(b"", StreamStub, method)) + assert await asyncio.to_thread(started.wait, 3) + response.cancel() + with pytest.raises(asyncio.CancelledError): + await response + assert await conn(b"", StreamStub, "Peer") + + +def test_failed_future_start_does_not_keep_retired_channel_busy(): + endpoint = "127.0.0.1:1" + stub = MagicMock() + stub.Unary.future.side_effect = ValueError("invalid request") + with connection.Connection(endpoint, driver.DriverConfig(endpoint, "/local")) as conn: + with pytest.raises(ValueError, match="invalid request"): + conn.future(b"", lambda _: stub, "Unary") + assert not conn._active_calls + assert conn.begin_retirement() + conn.finish_retirement(time.monotonic()) + assert conn._channel is None + + +@pytest.mark.parametrize("use_future", [False, True]) +def test_rpc_start_after_retirement_reports_connection_loss(use_future): + endpoint = "127.0.0.1:1" + with connection.Connection(endpoint, driver.DriverConfig(endpoint, "/local")) as conn: + prepare_call = conn._prepare_call + + def prepare_and_retire(*args): + call = prepare_call(*args) + assert conn.begin_retirement() + conn.finish_retirement(time.monotonic()) + return call + + call = conn.future if use_future else conn + with patch.object(connection.Connection, "_prepare_call", side_effect=prepare_and_retire): + with pytest.raises(issues.ConnectionLost, match="Endpoint removed by discovery") as error: + call(b"", StreamStub, "Unary") + assert isinstance(error.value.__cause__, ValueError) + assert not conn._active_calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +async def test_close_lets_pending_unary_rpc_finish(grpc_stream_server, is_async): + port, release, _, started = grpc_stream_server + endpoint = f"127.0.0.1:{port}" + config = driver.DriverConfig(endpoint, "/local") + if is_async: + conn = aio_pool.Connection(endpoint, config) + response = asyncio.create_task(conn(b"", StreamStub, "Unary")) + else: + conn = connection.Connection(endpoint, config) + response = asyncio.wrap_future(conn.future(b"", StreamStub, "Unary")) + + try: + assert await asyncio.to_thread(started.wait, 3) + if is_async: + closing = asyncio.create_task(conn.close()) + await asyncio.sleep(0) + assert not closing.done() + else: + conn.close() + assert conn.closing + assert conn._channel is not None + + release.set() + assert await asyncio.wait_for(response, timeout=3) == b"unary response" + if is_async: + await asyncio.wait_for(closing, timeout=3) + finally: + release.set() + if is_async: + await conn.close() + else: + conn.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("request_body,error", [(b"unavailable", issues.Unavailable), (b"cancelled", issues.Cancelled)]) +async def test_stream_reports_transport_failure_before_retirement(grpc_stream_server, is_async, request_body, error): + port, release, _, _ = grpc_stream_server + endpoint = f"127.0.0.1:{port}" + config = driver.DriverConfig(endpoint, "/local") + if is_async: + callback = AsyncMock() + async with aio_pool.Connection(endpoint, config) as conn: + stream = await conn(request_body, StreamStub, "Stream", on_disconnected=callback) + assert await anext(stream) + release.set() + with pytest.raises(error): + await anext(stream) + else: + callback = MagicMock() + with connection.Connection(endpoint, config) as conn: + stream = conn(request_body, StreamStub, "Stream", on_disconnected=callback) + assert next(stream) + release.set() + with pytest.raises(error): + next(stream) + + if error is issues.Unavailable: + callback.assert_called_once() + else: + callback.assert_not_called() + + +@pytest.mark.asyncio +async def test_unary_reports_transport_failure_before_retirement(grpc_stream_server): + port, release, _, _ = grpc_stream_server + endpoint = f"127.0.0.1:{port}" + callback = AsyncMock() + async with aio_pool.Connection(endpoint, driver.DriverConfig(endpoint, "/local")) as conn: + release.set() + with pytest.raises(issues.ConnectionLost): + await conn(b"unavailable", StreamStub, "Unary", on_disconnected=callback) + callback.assert_awaited_once() + + +class _GeneratorInterceptor(grpc.UnaryStreamClientInterceptor): + def intercept_unary_stream(self, continuation, client_call_details, request): + yield from continuation(client_call_details, request) + + +@pytest.mark.parametrize("finish", ["exhaust", "cancel", "close", "abandon", "deadline", "lazy-deadline"]) +def test_discovery_drains_intercepted_stream(grpc_stream_server, finish): + port, release, finished, _ = grpc_stream_server + endpoint = f"127.0.0.1:{port}" + channel = grpc.intercept_channel(grpc.insecure_channel(endpoint), _GeneratorInterceptor()) + with patch.object(connection, "channel_factory", return_value=channel): + conn = connection.Connection(endpoint, driver.DriverConfig(endpoint)) + cache = pool.ConnectionsCache() + cache.add(conn) + try: + stream = conn(b"", StreamStub, "Stream") + if finish != "lazy-deadline": + assert next(stream) + cache.retire(conn, 0.5 if finish.endswith("deadline") else 60) + assert not finished.wait(0.05) + if finish == "exhaust": + release.set() + assert list(stream) == [b"last response"] + elif finish == "abandon": + del stream + elif finish.endswith("deadline"): + with conn.lock: + assert conn.lock.wait_for(lambda: conn._channel is None, timeout=3) + if finish == "deadline": + assert finished.wait(3) + with pytest.raises(issues.ConnectionLost): + next(stream) + else: + getattr(stream, finish)() + with conn.lock: + assert conn.lock.wait_for(lambda: conn._channel is None, timeout=3) + finally: + cache.cleanup() + + +def test_stream_finished_before_registration_does_not_delay_retirement(grpc_stream_server): + port, release, _, _ = grpc_stream_server + endpoint = f"127.0.0.1:{port}" + with connection.Connection(endpoint, driver.DriverConfig(endpoint, "/local")) as conn: + stub = StreamStub(conn._channel) + state = connection._RpcState(stub, "Stream", endpoint, conn.endpoint_key) + release.set() + stream = stub.Stream(b"", timeout=5) + assert len(list(stream)) == 2 + assert stream.code() is grpc.StatusCode.OK + conn._active_calls.add(state) + conn._wrap_stream(stream, state, None) + assert not conn._active_calls + + +def test_discovery_can_stop_after_recovering_from_a_failed_round(): + config = driver.DriverConfig("localhost:2135", "/local") + cache = pool.ConnectionsCache() + discovery = pool.Discovery(cache, config) + discovery._base_emergency_retry_interval = 0 + discovery._base_discovery_interval = 0 + conn = connection.Connection(config.endpoint, config) + cache.add(conn) + + outcomes = iter(["exception", "empty", "recovered", "stop"]) + + def execute_round(): + outcome = next(outcomes) + if outcome == "exception": + raise RuntimeError("discovery unavailable") + if outcome == "stop": + discovery.stop() + return outcome != "empty" + + with patch.object(discovery, "execute_discovery", side_effect=execute_round) as execute, patch.object( + cache, "complete_discovery", wraps=cache.complete_discovery + ) as complete: + discovery.run() + + assert execute.call_count == 4 + assert isinstance(complete.call_args_list[0].args[0], issues.ConnectionFailure) + assert isinstance(complete.call_args_list[1].args[0], issues.ConnectionFailure) + assert complete.call_args_list[2].args == (None,) + assert conn._channel is None + + +def test_retirement_closes_channel_if_thread_cannot_start(): + config = driver.DriverConfig("localhost:2135", "/local") + cache = pool.ConnectionsCache() + conn = connection.Connection(config.endpoint, config) + cache.add(conn) + + with patch.object(threading.Thread, "start", side_effect=RuntimeError("threads exhausted")): + cache.retire(conn, config.grpc_channel_shutdown_timeout) + + assert cache.size == 0 + assert not cache._retiring + assert conn._channel is None diff --git a/ydb/resolver.py b/ydb/resolver.py index ab5eff4c..3588bdaa 100644 --- a/ydb/resolver.py +++ b/ydb/resolver.py @@ -83,13 +83,12 @@ def __repr__(self): return self.__str__() def __hash__(self): - return hash(self.endpoint) + return hash((self.endpoint, self.node_id)) def __eq__(self, other): - if not hasattr(other, "endpoint"): - return False - - return self.endpoint == other.endpoint + if not isinstance(other, EndpointInfo): + return NotImplemented + return (self.endpoint, self.node_id) == (other.endpoint, other.node_id) def _list_endpoints_request_factory(connection_params: driver.DriverConfig) -> _apis.ydb_discovery.ListEndpointsRequest: