|
| 1 | +# ------------------------------------------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License.txt in the project root for |
| 4 | +# license information. |
| 5 | +# ------------------------------------------------------------------------- |
| 6 | + |
| 7 | +import datetime |
| 8 | +import logging |
| 9 | +import threading |
| 10 | +import time |
| 11 | +from concurrent.futures import ThreadPoolExecutor |
| 12 | +from typing import TYPE_CHECKING |
| 13 | + |
| 14 | +from .._servicebus_session import ServiceBusSession |
| 15 | +from ..exceptions import AutoLockRenewFailed, AutoLockRenewTimeout, ServiceBusError |
| 16 | +from .utils import renewable_start_time, utc_now |
| 17 | + |
| 18 | +if TYPE_CHECKING: |
| 19 | + from typing import Callable, Union, Optional, Awaitable |
| 20 | + from .message import ReceivedMessage |
| 21 | + LockRenewFailureCallback = Callable[[Union[ServiceBusSession, ReceivedMessage], |
| 22 | + Optional[Exception]], None] |
| 23 | + |
| 24 | +_log = logging.getLogger(__name__) |
| 25 | + |
| 26 | +class AutoLockRenew(object): |
| 27 | + """Auto renew locks for messages and sessions using a background thread pool. |
| 28 | +
|
| 29 | + :param executor: A user-specified thread pool. This cannot be combined with |
| 30 | + setting `max_workers`. |
| 31 | + :type executor: ~concurrent.futures.ThreadPoolExecutor |
| 32 | + :param max_workers: Specify the maximum workers in the thread pool. If not |
| 33 | + specified the number used will be derived from the core count of the environment. |
| 34 | + This cannot be combined with `executor`. |
| 35 | + :type max_workers: int |
| 36 | +
|
| 37 | + .. admonition:: Example: |
| 38 | +
|
| 39 | + .. literalinclude:: ../samples/sync_samples/sample_code_servicebus.py |
| 40 | + :start-after: [START auto_lock_renew_message_sync] |
| 41 | + :end-before: [END auto_lock_renew_message_sync] |
| 42 | + :language: python |
| 43 | + :dedent: 4 |
| 44 | + :caption: Automatically renew a message lock |
| 45 | +
|
| 46 | + .. literalinclude:: ../samples/sync_samples/sample_code_servicebus.py |
| 47 | + :start-after: [START auto_lock_renew_session_sync] |
| 48 | + :end-before: [END auto_lock_renew_session_sync] |
| 49 | + :language: python |
| 50 | + :dedent: 4 |
| 51 | + :caption: Automatically renew a session lock |
| 52 | +
|
| 53 | + """ |
| 54 | + |
| 55 | + def __init__(self, executor=None, max_workers=None): |
| 56 | + self._executor = executor or ThreadPoolExecutor(max_workers=max_workers) |
| 57 | + self._shutdown = threading.Event() |
| 58 | + self._sleep_time = 1 |
| 59 | + self._renew_period = 10 |
| 60 | + |
| 61 | + def __enter__(self): |
| 62 | + if self._shutdown.is_set(): |
| 63 | + raise ServiceBusError("The AutoLockRenew has already been shutdown. Please create a new instance for" |
| 64 | + " auto lock renewing.") |
| 65 | + return self |
| 66 | + |
| 67 | + def __exit__(self, *args): |
| 68 | + self.close() |
| 69 | + |
| 70 | + def _renewable(self, renewable): |
| 71 | + # pylint: disable=protected-access |
| 72 | + if self._shutdown.is_set(): |
| 73 | + return False |
| 74 | + if hasattr(renewable, '_settled') and renewable._settled: |
| 75 | + return False |
| 76 | + if not renewable._receiver._running: |
| 77 | + return False |
| 78 | + if renewable._lock_expired: |
| 79 | + return False |
| 80 | + return True |
| 81 | + |
| 82 | + def _auto_lock_renew(self, renewable, starttime, timeout, on_lock_renew_failure=None): |
| 83 | + # pylint: disable=protected-access |
| 84 | + _log.debug("Running lock auto-renew thread for %r seconds", timeout) |
| 85 | + error = None |
| 86 | + clean_shutdown = False # Only trigger the on_lock_renew_failure if halting was not expected (shutdown, etc) |
| 87 | + try: |
| 88 | + while self._renewable(renewable): |
| 89 | + if (utc_now() - starttime) >= datetime.timedelta(seconds=timeout): |
| 90 | + _log.debug("Reached auto lock renew timeout - letting lock expire.") |
| 91 | + raise AutoLockRenewTimeout("Auto-renew period ({} seconds) elapsed.".format(timeout)) |
| 92 | + if (renewable.locked_until_utc - utc_now()) <= datetime.timedelta(seconds=self._renew_period): |
| 93 | + _log.debug("%r seconds or less until lock expires - auto renewing.", self._renew_period) |
| 94 | + renewable.renew_lock() |
| 95 | + time.sleep(self._sleep_time) |
| 96 | + clean_shutdown = not renewable._lock_expired |
| 97 | + except AutoLockRenewTimeout as e: |
| 98 | + error = e |
| 99 | + renewable.auto_renew_error = e |
| 100 | + clean_shutdown = not renewable._lock_expired |
| 101 | + except Exception as e: # pylint: disable=broad-except |
| 102 | + _log.debug("Failed to auto-renew lock: %r. Closing thread.", e) |
| 103 | + error = AutoLockRenewFailed( |
| 104 | + "Failed to auto-renew lock", |
| 105 | + inner_exception=e) |
| 106 | + renewable.auto_renew_error = error |
| 107 | + finally: |
| 108 | + if on_lock_renew_failure and not clean_shutdown: |
| 109 | + on_lock_renew_failure(renewable, error) |
| 110 | + |
| 111 | + def register(self, renewable, timeout=300, on_lock_renew_failure=None): |
| 112 | + """Register a renewable entity for automatic lock renewal. |
| 113 | +
|
| 114 | + :param renewable: A locked entity that needs to be renewed. |
| 115 | + :type renewable: ~azure.servicebus.ReceivedMessage or |
| 116 | + ~azure.servicebus.ServiceBusSession |
| 117 | + :param float timeout: A time in seconds that the lock should be maintained for. |
| 118 | + Default value is 300 (5 minutes). |
| 119 | + :param Optional[LockRenewFailureCallback] on_lock_renew_failure: |
| 120 | + A callback may be specified to be called when the lock is lost on the renewable that is being registered. |
| 121 | + Default value is None (no callback). |
| 122 | + """ |
| 123 | + if self._shutdown.is_set(): |
| 124 | + raise ServiceBusError("The AutoLockRenew has already been shutdown. Please create a new instance for" |
| 125 | + " auto lock renewing.") |
| 126 | + starttime = renewable_start_time(renewable) |
| 127 | + self._executor.submit(self._auto_lock_renew, renewable, starttime, timeout, on_lock_renew_failure) |
| 128 | + |
| 129 | + def close(self, wait=True): |
| 130 | + """Cease autorenewal by shutting down the thread pool to clean up any remaining lock renewal threads. |
| 131 | +
|
| 132 | + :param wait: Whether to block until thread pool has shutdown. Default is `True`. |
| 133 | + :type wait: bool |
| 134 | + """ |
| 135 | + self._shutdown.set() |
| 136 | + self._executor.shutdown(wait=wait) |
0 commit comments