|
| 1 | +# Copyright 2017, Google Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Abstract and helper bases for Future implementations.""" |
| 16 | + |
| 17 | +import abc |
| 18 | +import concurrent.futures |
| 19 | +import functools |
| 20 | +import operator |
| 21 | + |
| 22 | +import six |
| 23 | +import tenacity |
| 24 | + |
| 25 | +from google.cloud.future import _helpers |
| 26 | +from google.cloud.future import base |
| 27 | + |
| 28 | + |
| 29 | +class PollingFuture(base.Future): |
| 30 | + """A Future that needs to poll some service to check its status. |
| 31 | +
|
| 32 | + The :meth:`done` method should be implemented by subclasses. The polling |
| 33 | + behavior will repeatedly call ``done`` until it returns True. |
| 34 | +
|
| 35 | + .. note: Privacy here is intended to prevent the final class from |
| 36 | + overexposing, not to prevent subclasses from accessing methods. |
| 37 | + """ |
| 38 | + def __init__(self): |
| 39 | + super(PollingFuture, self).__init__() |
| 40 | + self._result = None |
| 41 | + self._exception = None |
| 42 | + self._result_set = False |
| 43 | + """bool: Set to True when the result has been set via set_result or |
| 44 | + set_exception.""" |
| 45 | + self._polling_thread = None |
| 46 | + self._done_callbacks = [] |
| 47 | + |
| 48 | + @abc.abstractmethod |
| 49 | + def done(self): |
| 50 | + """Checks to see if the operation is complete. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + bool: True if the operation is complete, False otherwise. |
| 54 | + """ |
| 55 | + # pylint: disable=redundant-returns-doc, missing-raises-doc |
| 56 | + raise NotImplementedError() |
| 57 | + |
| 58 | + def running(self): |
| 59 | + """True if the operation is currently running.""" |
| 60 | + return not self.done() |
| 61 | + |
| 62 | + def _blocking_poll(self, timeout=None): |
| 63 | + """Poll and wait for the Future to be resolved. |
| 64 | +
|
| 65 | + Args: |
| 66 | + timeout (int): How long to wait for the operation to complete. |
| 67 | + If None, wait indefinitely. |
| 68 | + """ |
| 69 | + if self._result_set: |
| 70 | + return |
| 71 | + |
| 72 | + retry_on = tenacity.retry_if_result( |
| 73 | + functools.partial(operator.is_not, True)) |
| 74 | + # Use exponential backoff with jitter. |
| 75 | + wait_on = ( |
| 76 | + tenacity.wait_exponential(multiplier=1, max=10) + |
| 77 | + tenacity.wait_random(0, 1)) |
| 78 | + |
| 79 | + if timeout is None: |
| 80 | + retry = tenacity.retry(retry=retry_on, wait=wait_on) |
| 81 | + else: |
| 82 | + retry = tenacity.retry( |
| 83 | + retry=retry_on, |
| 84 | + wait=wait_on, |
| 85 | + stop=tenacity.stop_after_delay(timeout)) |
| 86 | + |
| 87 | + try: |
| 88 | + retry(self.done)() |
| 89 | + except tenacity.RetryError as exc: |
| 90 | + six.raise_from( |
| 91 | + concurrent.futures.TimeoutError( |
| 92 | + 'Operation did not complete within the designated ' |
| 93 | + 'timeout.'), |
| 94 | + exc) |
| 95 | + |
| 96 | + def result(self, timeout=None): |
| 97 | + """Get the result of the operation, blocking if necessary. |
| 98 | +
|
| 99 | + Args: |
| 100 | + timeout (int): How long to wait for the operation to complete. |
| 101 | + If None, wait indefinitely. |
| 102 | +
|
| 103 | + Returns: |
| 104 | + google.protobuf.Message: The Operation's result. |
| 105 | +
|
| 106 | + Raises: |
| 107 | + google.gax.GaxError: If the operation errors or if the timeout is |
| 108 | + reached before the operation completes. |
| 109 | + """ |
| 110 | + self._blocking_poll(timeout=timeout) |
| 111 | + |
| 112 | + if self._exception is not None: |
| 113 | + # pylint: disable=raising-bad-type |
| 114 | + # Pylint doesn't recognize that this is valid in this case. |
| 115 | + raise self._exception |
| 116 | + |
| 117 | + return self._result |
| 118 | + |
| 119 | + def exception(self, timeout=None): |
| 120 | + """Get the exception from the operation, blocking if necessary. |
| 121 | +
|
| 122 | + Args: |
| 123 | + timeout (int): How long to wait for the operation to complete. |
| 124 | + If None, wait indefinitely. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + Optional[google.gax.GaxError]: The operation's error. |
| 128 | + """ |
| 129 | + self._blocking_poll() |
| 130 | + return self._exception |
| 131 | + |
| 132 | + def add_done_callback(self, fn): |
| 133 | + """Add a callback to be executed when the operation is complete. |
| 134 | +
|
| 135 | + If the operation is not already complete, this will start a helper |
| 136 | + thread to poll for the status of the operation in the background. |
| 137 | +
|
| 138 | + Args: |
| 139 | + fn (Callable[Future]): The callback to execute when the operation |
| 140 | + is complete. |
| 141 | + """ |
| 142 | + if self._result_set: |
| 143 | + _helpers.safe_invoke_callback(fn, self) |
| 144 | + return |
| 145 | + |
| 146 | + self._done_callbacks.append(fn) |
| 147 | + |
| 148 | + if self._polling_thread is None: |
| 149 | + # The polling thread will exit on its own as soon as the operation |
| 150 | + # is done. |
| 151 | + self._polling_thread = _helpers.start_daemon_thread( |
| 152 | + target=self._blocking_poll) |
| 153 | + |
| 154 | + def _invoke_callbacks(self, *args, **kwargs): |
| 155 | + """Invoke all done callbacks.""" |
| 156 | + for callback in self._done_callbacks: |
| 157 | + _helpers.safe_invoke_callback(callback, *args, **kwargs) |
| 158 | + |
| 159 | + def set_result(self, result): |
| 160 | + """Set the Future's result.""" |
| 161 | + self._result = result |
| 162 | + self._result_set = True |
| 163 | + self._invoke_callbacks(self) |
| 164 | + |
| 165 | + def set_exception(self, exception): |
| 166 | + """Set the Future's exception.""" |
| 167 | + self._exception = exception |
| 168 | + self._result_set = True |
| 169 | + self._invoke_callbacks(self) |
0 commit comments