|
| 1 | +"""Provides function wrappers that implement retrying.""" |
| 2 | +import random |
| 3 | +import time |
| 4 | +import six |
| 5 | +import sys |
| 6 | + |
| 7 | +from google.cloud._helpers import _to_bytes |
| 8 | +from google.cloud.bigtable._generated import ( |
| 9 | + bigtable_pb2 as data_messages_v2_pb2) |
| 10 | +from google.gax import config, errors |
| 11 | +from grpc import RpcError |
| 12 | + |
| 13 | + |
| 14 | +_MILLIS_PER_SECOND = 1000 |
| 15 | + |
| 16 | + |
| 17 | +class ReadRowsIterator(object): |
| 18 | + """Creates an iterator equivalent to a_iter, but that retries on certain |
| 19 | + exceptions. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, client, name, start_key, end_key, filter_, limit, |
| 23 | + retry_options, **kwargs): |
| 24 | + self.client = client |
| 25 | + self.retry_options = retry_options |
| 26 | + self.name = name |
| 27 | + self.start_key = start_key |
| 28 | + self.start_key_closed = True |
| 29 | + self.end_key = end_key |
| 30 | + self.filter_ = filter_ |
| 31 | + self.limit = limit |
| 32 | + self.delay_mult = retry_options.backoff_settings.retry_delay_multiplier |
| 33 | + self.max_delay_millis = \ |
| 34 | + retry_options.backoff_settings.max_retry_delay_millis |
| 35 | + self.timeout_mult = \ |
| 36 | + retry_options.backoff_settings.rpc_timeout_multiplier |
| 37 | + self.max_timeout = \ |
| 38 | + (retry_options.backoff_settings.max_rpc_timeout_millis / |
| 39 | + _MILLIS_PER_SECOND) |
| 40 | + self.total_timeout = \ |
| 41 | + (retry_options.backoff_settings.total_timeout_millis / |
| 42 | + _MILLIS_PER_SECOND) |
| 43 | + self.set_stream() |
| 44 | + |
| 45 | + def set_start_key(self, start_key): |
| 46 | + """ |
| 47 | + Sets the row key at which this iterator will begin reading. |
| 48 | + """ |
| 49 | + self.start_key = start_key |
| 50 | + self.start_key_closed = False |
| 51 | + |
| 52 | + def set_stream(self): |
| 53 | + """ |
| 54 | + Resets the read stream by making an RPC on the 'ReadRows' endpoint. |
| 55 | + """ |
| 56 | + req_pb = _create_row_request(self.name, start_key=self.start_key, |
| 57 | + start_key_closed=self.start_key_closed, |
| 58 | + end_key=self.end_key, |
| 59 | + filter_=self.filter_, limit=self.limit) |
| 60 | + self.stream = self.client._data_stub.ReadRows(req_pb) |
| 61 | + |
| 62 | + def next(self, *args, **kwargs): |
| 63 | + """ |
| 64 | + Read and return the next row from the stream. |
| 65 | + Retry on idempotent failure. |
| 66 | + """ |
| 67 | + delay = self.retry_options.backoff_settings.initial_retry_delay_millis |
| 68 | + exc = errors.RetryError('Retry total timeout exceeded before any' |
| 69 | + 'response was received') |
| 70 | + timeout = (self.retry_options.backoff_settings |
| 71 | + .initial_rpc_timeout_millis / |
| 72 | + _MILLIS_PER_SECOND) |
| 73 | + |
| 74 | + now = time.time() |
| 75 | + deadline = now + self.total_timeout |
| 76 | + while deadline is None or now < deadline: |
| 77 | + try: |
| 78 | + return six.next(self.stream) |
| 79 | + except StopIteration as stop: |
| 80 | + raise stop |
| 81 | + except RpcError as error: # pylint: disable=broad-except |
| 82 | + code = config.exc_to_code(error) |
| 83 | + if code not in self.retry_options.retry_codes: |
| 84 | + six.reraise(type(error), error) |
| 85 | + |
| 86 | + # pylint: disable=redefined-variable-type |
| 87 | + exc = errors.RetryError( |
| 88 | + 'Retry total timeout exceeded with exception', error) |
| 89 | + |
| 90 | + # Sleep a random number which will, on average, equal the |
| 91 | + # expected delay. |
| 92 | + to_sleep = random.uniform(0, delay * 2) |
| 93 | + time.sleep(to_sleep / _MILLIS_PER_SECOND) |
| 94 | + delay = min(delay * self.delay_mult, self.max_delay_millis) |
| 95 | + now = time.time() |
| 96 | + timeout = min( |
| 97 | + timeout * self.timeout_mult, self.max_timeout, |
| 98 | + deadline - now) |
| 99 | + self.set_stream() |
| 100 | + |
| 101 | + six.reraise(errors.RetryError, exc, sys.exc_info()[2]) |
| 102 | + |
| 103 | + def __next__(self, *args, **kwargs): |
| 104 | + return self.next(*args, **kwargs) |
| 105 | + |
| 106 | + |
| 107 | +def _create_row_request(table_name, row_key=None, start_key=None, |
| 108 | + start_key_closed=True, end_key=None, filter_=None, |
| 109 | + limit=None): |
| 110 | + """Creates a request to read rows in a table. |
| 111 | +
|
| 112 | + :type table_name: str |
| 113 | + :param table_name: The name of the table to read from. |
| 114 | +
|
| 115 | + :type row_key: bytes |
| 116 | + :param row_key: (Optional) The key of a specific row to read from. |
| 117 | +
|
| 118 | + :type start_key: bytes |
| 119 | + :param start_key: (Optional) The beginning of a range of row keys to |
| 120 | + read from. The range will include ``start_key``. If |
| 121 | + left empty, will be interpreted as the empty string. |
| 122 | +
|
| 123 | + :type end_key: bytes |
| 124 | + :param end_key: (Optional) The end of a range of row keys to read from. |
| 125 | + The range will not include ``end_key``. If left empty, |
| 126 | + will be interpreted as an infinite string. |
| 127 | +
|
| 128 | + :type filter_: :class:`.RowFilter` |
| 129 | + :param filter_: (Optional) The filter to apply to the contents of the |
| 130 | + specified row(s). If unset, reads the entire table. |
| 131 | +
|
| 132 | + :type limit: int |
| 133 | + :param limit: (Optional) The read will terminate after committing to N |
| 134 | + rows' worth of results. The default (zero) is to return |
| 135 | + all results. |
| 136 | +
|
| 137 | + :rtype: :class:`data_messages_v2_pb2.ReadRowsRequest` |
| 138 | + :returns: The ``ReadRowsRequest`` protobuf corresponding to the inputs. |
| 139 | + :raises: :class:`ValueError <exceptions.ValueError>` if both |
| 140 | + ``row_key`` and one of ``start_key`` and ``end_key`` are set |
| 141 | + """ |
| 142 | + request_kwargs = {'table_name': table_name} |
| 143 | + if (row_key is not None and |
| 144 | + (start_key is not None or end_key is not None)): |
| 145 | + raise ValueError('Row key and row range cannot be ' |
| 146 | + 'set simultaneously') |
| 147 | + range_kwargs = {} |
| 148 | + if start_key is not None or end_key is not None: |
| 149 | + if start_key is not None: |
| 150 | + if start_key_closed: |
| 151 | + range_kwargs['start_key_closed'] = _to_bytes(start_key) |
| 152 | + else: |
| 153 | + range_kwargs['start_key_open'] = _to_bytes(start_key) |
| 154 | + if end_key is not None: |
| 155 | + range_kwargs['end_key_open'] = _to_bytes(end_key) |
| 156 | + if filter_ is not None: |
| 157 | + request_kwargs['filter'] = filter_.to_pb() |
| 158 | + if limit is not None: |
| 159 | + request_kwargs['rows_limit'] = limit |
| 160 | + |
| 161 | + message = data_messages_v2_pb2.ReadRowsRequest(**request_kwargs) |
| 162 | + |
| 163 | + if row_key is not None: |
| 164 | + message.rows.row_keys.append(_to_bytes(row_key)) |
| 165 | + |
| 166 | + if range_kwargs: |
| 167 | + message.rows.row_ranges.add(**range_kwargs) |
| 168 | + |
| 169 | + return message |
0 commit comments