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