Repository navigation
[https://nvbugs/7162735][fix] Detect expired etcd leases and recover cached leases in Etcd3ClusterStorage #23327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -700,6 +700,15 @@ def _rejects_token(error: grpc.RpcError) -> bool: | |
| and error.details() in _REJECTED_TOKEN_DETAILS) | ||
|
|
||
|
|
||
| # gRPC status codes that etcd returns before applying a KV write (excluding | ||
| # rejected login tokens, where revoking with the same token cannot succeed | ||
| # and handle_etcd_error reconnects instead). | ||
| _PRE_APPLY_WRITE_REJECTION_CODES = frozenset({ | ||
| grpc.StatusCode.INVALID_ARGUMENT, | ||
| grpc.StatusCode.PERMISSION_DENIED, | ||
| }) | ||
|
|
||
|
|
||
| def _describe_error(error: Exception) -> str: | ||
| """Describe ``error`` for a log message. | ||
|
|
||
|
|
@@ -713,6 +722,16 @@ def _describe_error(error: Exception) -> str: | |
| return repr(error) | ||
|
|
||
|
|
||
| def _handle_rejected_token(storage: "Etcd3ClusterStorage", op_name: str, | ||
| error: grpc.RpcError) -> bool: | ||
| if not storage.logs_in or not _rejects_token(error): | ||
| return False | ||
| logger.warning(f"Etcd rejected the login token in {op_name}, logging " | ||
| f"in again on the next call: {_describe_error(error)}") | ||
| storage.reconnect() | ||
| return True | ||
|
|
||
|
|
||
| def handle_etcd_error(return_on_error: bool | None): | ||
|
|
||
| def decorator(f): | ||
|
|
@@ -736,12 +755,8 @@ async def wrap(*args, **kwargs): | |
| storage.reconnect() | ||
| return return_on_error | ||
| except grpc.RpcError as e: | ||
| if not storage.logs_in or not _rejects_token(e): | ||
| if not _handle_rejected_token(storage, f.__name__, e): | ||
| raise | ||
| logger.warning( | ||
| f"Etcd rejected the login token in {f.__name__}, logging " | ||
| f"in again on the next call: {_describe_error(e)}") | ||
| storage.reconnect() | ||
| return return_on_error | ||
|
|
||
| return wrap | ||
|
|
@@ -811,14 +826,37 @@ def __del__(self): | |
| if self._client is not None: | ||
| self._client.close() | ||
|
|
||
| def _get_lease(self, key: str, ttl: int = -1) -> etcd3.Lease: | ||
| def _acquire_lease(self, | ||
| key: str, | ||
| ttl: int = -1) -> Tuple[Optional[etcd3.Lease], bool]: | ||
| if ttl <= 0: | ||
| return None | ||
| return None, False | ||
| if self._one_single_lease: | ||
| return self._instance_lease | ||
| if key not in self._leases: | ||
| self._leases[key] = self.client.lease(ttl) | ||
| return self._leases[key] | ||
| return self._instance_lease, False | ||
| if key in self._leases: | ||
| return self._leases[key], False | ||
| return self.client.lease(ttl), True | ||
|
|
||
| def _drop_lease(self, | ||
| key: str, | ||
| lease: Optional[etcd3.Lease] = None) -> None: | ||
| if not self._one_single_lease and (lease is None | ||
| or self._leases.get(key) is lease): | ||
| self._leases.pop(key, None) | ||
|
|
||
| def _revoke_unused_lease(self, lease: etcd3.Lease) -> None: | ||
| try: | ||
| self.client.revoke_lease(lease.id) | ||
| except grpc.RpcError as e: | ||
| if e.code() == grpc.StatusCode.NOT_FOUND: | ||
| return | ||
| if _handle_rejected_token(self, "revoke_lease", e): | ||
| return | ||
| logger.debug(f"Could not revoke unused etcd lease {lease.id}: " | ||
| f"{_describe_error(e)}") | ||
| except etcd3.Etcd3Exception as e: | ||
| logger.debug(f"Could not revoke unused etcd lease {lease.id}: " | ||
| f"{_describe_error(e)}") | ||
|
Comment on lines
+857
to
+859
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reconnect when lease cleanup invalidates the client. If a conditional write returns Invalidate the client here for SDK errors that mark the endpoint failed. Preserve the conditional write's
|
||
|
|
||
| @property | ||
| def client(self) -> Optional[etcd3.MultiEndpointEtcd3Client]: | ||
|
|
@@ -908,13 +946,36 @@ async def set(self, | |
| value: str, | ||
| overwrite_if_exists: bool = False, | ||
| ttl: int = -1) -> bool: | ||
| lease = self._get_lease(key, ttl) | ||
| value = self._encode_record(key, value) | ||
| if not overwrite_if_exists: | ||
| return self.client.put_if_not_exists(key, value, lease=lease) | ||
| else: | ||
| self.client.put(key, value, lease=lease) | ||
| return True | ||
| encoded_value = self._encode_record(key, value) | ||
| for attempt in range(2): | ||
| lease, newly_granted = self._acquire_lease(key, ttl) | ||
| try: | ||
| if not overwrite_if_exists: | ||
| result = self.client.put_if_not_exists(key, | ||
| encoded_value, | ||
| lease=lease) | ||
| else: | ||
| self.client.put(key, encoded_value, lease=lease) | ||
| result = True | ||
| except grpc.RpcError as e: | ||
| if lease is not None and e.code() == grpc.StatusCode.NOT_FOUND: | ||
| self._drop_lease(key, lease) | ||
| if attempt == 0: | ||
| continue | ||
| elif (newly_granted and lease is not None | ||
| and e.code() in _PRE_APPLY_WRITE_REJECTION_CODES | ||
| and not (self.logs_in and _rejects_token(e))): | ||
|
Comment on lines
+966
to
+967
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Test both meanings of The existing token tests inject the error into As per path instructions, flag “A new or changed validation rule, error path, fallback, retry, configuration option, API contract, serialization behavior, runtime behavior, scheduler behavior, quantization behavior, distributed behavior, or observable output with no meaningful test.”
|
||
| self._revoke_unused_lease(lease) | ||
| raise | ||
| if result: | ||
| if lease is None: | ||
| self._drop_lease(key) | ||
| elif not self._one_single_lease: | ||
| self._leases[key] = lease | ||
| elif newly_granted and lease is not None: | ||
| self._revoke_unused_lease(lease) | ||
| return result | ||
| return False | ||
|
|
||
| @handle_etcd_error(return_on_error=None) | ||
| async def get(self, key: str) -> str: | ||
|
|
@@ -924,16 +985,37 @@ async def get(self, key: str) -> str: | |
| @handle_etcd_error(return_on_error=False) | ||
| async def delete(self, key: str) -> bool: | ||
| self.client.delete(key) | ||
| self._drop_lease(key) | ||
|
|
||
| @handle_etcd_error(return_on_error=False) | ||
| async def expire(self, key: str, ttl: int) -> bool: | ||
| if ttl <= 0: | ||
| logger.error(f"TTL must be greater than 0, got {ttl}") | ||
| return False | ||
| lease = self._get_lease(key, ttl) | ||
| assert lease is not None, "Lease must be created" | ||
| if self._one_single_lease: | ||
| lease = self._instance_lease | ||
| assert lease is not None, "Lease must be created" | ||
| else: | ||
| lease = self._leases.get(key) | ||
| if lease is None: | ||
| return False | ||
| # TTL will be ignored since it can only be set when creating a lease | ||
| next(self.client.refresh_lease(lease_id=lease.id), None) | ||
| try: | ||
| stream = self.client.refresh_lease(lease_id=lease.id) | ||
| try: | ||
| resp = next(stream, None) | ||
| finally: | ||
| close = getattr(stream, "close", None) | ||
| if callable(close): | ||
| close() | ||
| except grpc.RpcError as e: | ||
| if e.code() == grpc.StatusCode.NOT_FOUND: | ||
| self._drop_lease(key, lease) | ||
| return False | ||
| raise | ||
| if resp is None or getattr(resp, "TTL", 0) <= 0: | ||
| self._drop_lease(key, lease) | ||
| return False | ||
| return True | ||
|
|
||
| @handle_etcd_error(return_on_error={}) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The revoke in
set()cleanup blocks the event loop.The cleanup branches in
set()call_revoke_unused_lease()synchronously at lines 968 and 976. The revoke is a blocking etcd RPC with a 10-second timeout. Tasks on the same event loop cannot run during that time, including a heartbeat that callsexpire()on the same storage. The added revoke also doubles the worst-case blocking time ofset()on these rare branches, because the existing write RPC already blocks the loop.The impact depends on the configured lease TTL and heartbeat interval, which are not set in the inspected code. Separate worker processes are not affected.
Run the revoke off the loop, as
connect()and_start_watch()already do withasyncio.to_thread. Token-rejection handling must remain safe on that path, because_handle_rejected_token()can reset the shared client. Choose how to synchronize that reset with concurrent calls before making this change.