Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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`.
Expand Down
9 changes: 9 additions & 0 deletions docs/driver.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -137,6 +140,12 @@ There are three equivalent ways to specify the connection target:

The connection string format is ``<protocol>://<host>:<port>/?database=<path>``.

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
----------------------------------
Expand Down
11 changes: 11 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions tests/aio/test_discovery_detect_local_dc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
18 changes: 17 additions & 1 deletion tests/test_discovery_detect_local_dc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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 = []
Expand All @@ -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
120 changes: 75 additions & 45 deletions ydb/aio/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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

Expand All @@ -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",
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -226,32 +234,33 @@ 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__"):
# NOTE(vgvoleg): for stream results we should also be able to handle disconnects
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:
"""
Expand All @@ -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)

Expand All @@ -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
Expand Down
Loading
Loading