Wraps a client operation that can be retried according to the set
    :attr:`RiakClient.retries`. Used internally.
328872
def retryable(fn, protocol=None):
    
    def wrapper(self, *args, **kwargs):
        pool = self._choose_pool(protocol)

        def thunk(transport):
            return fn(self, transport, *args, **kwargs)

        return self._with_retries(pool, thunk)

    wrapper.__doc__ = fn.__doc__
    wrapper.__repr__ = fn.__repr__

    return wrapper
1132880
def retry_and_reset(fn):
    
    @wraps(fn)
    def retry_and_reset_decorator(*args, **kwargs):
        obj = kwargs.get("self", None)

        if not obj:
            obj = args[0]

        try:
            return fn(*args, **kwargs)
        except ConnectionStateError:
            obj._on_close_callback()

        return fn(*args, **kwargs)

    return retry_and_reset_decorator
801004
def reap_client?(clnt)
      rc = false
      if @reap_client
        begin
          rc = perform_action(clnt,@reap_client)
        rescue => e
          HotTub.logger.error "[HotTub] There was an error reaping one of your #{self.class.name} clients: #{e}" if HotTub.logger
        end
      end
      rc
    end
917323
private static <E extends Throwable> E wrapIfNecessary(Throwable throwable)
			throws RetryException {
		if (throwable instanceof Error) {
			throw (Error) throwable;
		}
		else if (throwable instanceof Exception) {
			@SuppressWarnings("unchecked")
			E rethrow = (E) throwable;
			return rethrow;
		}
		else {
			throw new RetryException("Exception in retry", throwable);
		}
	}
330849
def _retry_get(self, uri):
        
        for i in six.moves.range(DEFAULT_RETRY):
            resp, body = self.api.method_get(uri)
            if body:
                return resp, body
        # Tried too many times
        raise exc.ServiceResponseFailure("The Cloud DNS service failed to "
                "respond to the request.")
405443
def call_with_retry(func: Callable, exceptions, max_retries: int,
                    logger: Logger, *args, **kwargs):
    """"""
    attempt = 0
    while True:
        try:
            return func(*args, **kwargs)
        except exceptions as e:
            attempt += 1
            if attempt >= max_retries:
                raise

            delay = exponential_backoff(attempt, cap=60)
            logger.warning('%s: retrying in %s', e, delay)
            time.sleep(delay.total_seconds())
92185
def retry(ExceptionToCheck, tries=10, timeout_secs=1.0, logger=None, callback_by_exception=None):
    
    def deco_retry(f):
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, timeout_secs
            run_one_last_time = True
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except ExceptionToCheck as e:
                    # check if this exception is something the caller wants special handling for
                    callback_errors = callback_by_exception or {}
                    for error_type in callback_errors:
                        if isinstance(e, error_type):
                            callback_logic = callback_by_exception[error_type]
                            should_break_out = run_one_last_time = False
                            if isinstance(callback_logic, (list, tuple)):
                                callback_logic, should_break_out = callback_logic
                                if isinstance(should_break_out, (list, tuple)):
                                    should_break_out, run_one_last_time = should_break_out
                            callback_logic()
                            if should_break_out:  # caller requests we stop handling this exception
                                break
                    # traceback.print_exc()
                    half_interval = mdelay * 0.10  # interval size
                    actual_delay = random.uniform(mdelay - half_interval, mdelay + half_interval)
                    msg = "Retrying in %.2f seconds ..." % actual_delay
                    if logger is None:
                        logging.exception(msg)
                    else:
                        logger.exception(msg)
                    time.sleep(actual_delay)
                    mtries -= 1
                    mdelay *= 2
            if run_one_last_time:  # one exception may be all the caller wanted in certain cases
                return f(*args, **kwargs)
        return f_retry  # true decorator
    return deco_retry
698464
def retry_func_accept_retry_state(retry_func):
    """"""
    if not six.callable(retry_func):
        return retry_func

    if func_takes_retry_state(retry_func):
        return retry_func

    @_utils.wraps(retry_func)
    def wrapped_retry_func(retry_state):
        warn_about_non_retry_state_deprecation(
            'retry', retry_func, stacklevel=4)
        return retry_func(retry_state.outcome)
    return wrapped_retry_func
401144
function retry(fn) {

  return function retried() {

    var args = arguments.length ? Array.prototype.slice.call(arguments, 0, arguments.length - 1) : [];
    var done = arguments.length ? arguments[arguments.length - 1] : noop;

    var cfn = null;
    var canceled = false;

    function exec() {
      var err = arguments[0];
      if (!err || canceled) {
        done.apply(null, arguments);
      } else {
        cfn = fn.apply(null, args);
      }
    }

    args.push(exec);
    exec(true);

    return function cancel() {
      canceled = true;
      cfn.apply(null, arguments);
    };

  };

}
891427
def session_retry(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
    
    session = session or Session()
    retries = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    # mount all https requests
    session.mount('https://', adapters.HTTPAdapter(max_retries=retries))
    return session
853907
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None, expected_errors=None):
        '''
        
        '''
        operation_context = operation_context or _OperationContext()
        retry_context = RetryContext()
        retry_context.is_emulated = self.is_emulated

        # if request body is a stream, we need to remember its current position in case retries happen
        if hasattr(request.body, 'read'):
            try:
                retry_context.body_position = request.body.tell()
            except (AttributeError, UnsupportedOperation):
                # if body position cannot be obtained, then retries will not work
                pass

        # Apply the appropriate host based on the location mode
        self._apply_host(request, operation_context, retry_context)

        # Apply common settings to the request
        _update_request(request, self._X_MS_VERSION, self._USER_AGENT_STRING)
        client_request_id_prefix = str.format("Client-Request-ID={0}", request.headers['x-ms-client-request-id'])

        while True:
            try:
                try:
                    # Execute the request callback 
                    if self.request_callback:
                        self.request_callback(request)

                    # Add date and auth after the callback so date doesn't get too old and 
                    # authentication is still correct if signed headers are added in the request 
                    # callback. This also ensures retry policies with long back offs 
                    # will work as it resets the time sensitive headers.
                    _add_date_header(request)

                    try:
                        # request can be signed individually
                        self.authentication.sign_request(request)
                    except AttributeError:
                        # session can also be signed
                        self.request_session = self.authentication.signed_session(self.request_session)

                    # Set the request context
                    retry_context.request = request

                    # Log the request before it goes out
                    # Avoid unnecessary scrubbing if the logger is not on
                    if logger.isEnabledFor(logging.INFO):
                        logger.info("%s Outgoing request: Method=%s, Path=%s, Query=%s, Headers=%s.",
                                    client_request_id_prefix,
                                    request.method,
                                    request.path,
                                    self._scrub_query_parameters(request.query),
                                    str(self._scrub_headers(request.headers)).replace('\n', ''))

                    # Perform the request
                    response = self._httpclient.perform_request(request)

                    # Execute the response callback
                    if self.response_callback:
                        self.response_callback(response)

                    # Set the response context
                    retry_context.response = response

                    # Log the response when it comes back
                    logger.info("%s Receiving Response: "
                                "%s, HTTP Status Code=%s, Message=%s, Headers=%s.",
                                client_request_id_prefix,
                                self.extract_date_and_request_id(retry_context),
                                response.status,
                                response.message,
                                str(response.headers).replace('\n', ''))

                    # Parse and wrap HTTP errors in AzureHttpError which inherits from AzureException
                    if response.status >= 300:
                        # This exception will be caught by the general error handler
                        # and raised as an azure http exception
                        _http_error_handler(
                            HTTPError(response.status, response.message, response.headers, response.body))

                    # Parse the response
                    if parser:
                        if parser_args:
                            args = [response]
                            args.extend(parser_args)
                            return parser(*args)
                        else:
                            return parser(response)
                    else:
                        return
                except AzureException as ex:
                    retry_context.exception = ex
                    raise ex
                except Exception as ex:
                    retry_context.exception = ex
                    raise _wrap_exception(ex, AzureException)

            except AzureException as ex:
                # only parse the strings used for logging if logging is at least enabled for CRITICAL
                exception_str_in_one_line = ''
                status_code = ''
                timestamp_and_request_id = ''
                if logger.isEnabledFor(logging.CRITICAL):
                    exception_str_in_one_line = str(ex).replace('\n', '')
                    status_code = retry_context.response.status if retry_context.response is not None else 'Unknown'
                    timestamp_and_request_id = self.extract_date_and_request_id(retry_context)

                # if the http error was expected, we should short-circuit
                if isinstance(ex, AzureHttpError) and expected_errors is not None and ex.error_code in expected_errors:
                    logger.info("%s Received expected http error: "
                                "%s, HTTP status code=%s, Exception=%s.",
                                client_request_id_prefix,
                                timestamp_and_request_id,
                                status_code,
                                exception_str_in_one_line)
                    raise ex
                elif isinstance(ex, AzureSigningError):
                    logger.info("%s Unable to sign the request: Exception=%s.",
                                client_request_id_prefix,
                                exception_str_in_one_line)
                    raise ex

                logger.info("%s Operation failed: checking if the operation should be retried. "
                            "Current retry count=%s, %s, HTTP status code=%s, Exception=%s.",
                            client_request_id_prefix,
                            retry_context.count if hasattr(retry_context, 'count') else 0,
                            timestamp_and_request_id,
                            status_code,
                            exception_str_in_one_line)

                # Decryption failures (invalid objects, invalid algorithms, data unencrypted in strict mode, etc)
                # will not be resolved with retries.
                if str(ex) == _ERROR_DECRYPTION_FAILURE:
                    logger.error("%s Encountered decryption failure: this cannot be retried. "
                                 "%s, HTTP status code=%s, Exception=%s.",
                                 client_request_id_prefix,
                                 timestamp_and_request_id,
                                 status_code,
                                 exception_str_in_one_line)
                    raise ex

                # Determine whether a retry should be performed and if so, how 
                # long to wait before performing retry.
                retry_interval = self.retry(retry_context)
                if retry_interval is not None:
                    # Execute the callback
                    if self.retry_callback:
                        self.retry_callback(retry_context)

                    logger.info(
                        "%s Retry policy is allowing a retry: Retry count=%s, Interval=%s.",
                        client_request_id_prefix,
                        retry_context.count,
                        retry_interval)

                    # Sleep for the desired retry interval
                    sleep(retry_interval)
                else:
                    logger.error("%s Retry policy did not allow for a retry: "
                                 "%s, HTTP status code=%s, Exception=%s.",
                                 client_request_id_prefix,
                                 timestamp_and_request_id,
                                 status_code,
                                 exception_str_in_one_line)
                    raise ex
            finally:
                # If this is a location locked operation and the location is not set, 
                # this is the first request of that operation. Set the location to 
                # be used for subsequent requests in the operation.
                if operation_context.location_lock and not operation_context.host_location:
                    # note: to cover the emulator scenario, the host_location is grabbed
                    # from request.host_locations(which includes the dev account name)
                    # instead of request.host(which at this point no longer includes the dev account name)
                    operation_context.host_location = {
                        retry_context.location_mode: request.host_locations[retry_context.location_mode]}
817505
def retry_count(self, retries):
        
        if not isinstance(retries, int):
            raise TypeError("retries must be an integer")

        old_retries, self.retries = self.retries, retries
        try:
            yield
        finally:
            self.retries = old_retries
39830
def initialize(self, client, initial_response, deserialization_callback):
        
        self._client = client
        self._response = initial_response
        self._operation = LongRunningOperation(initial_response, deserialization_callback, self._lro_options)
        try:
            self._operation.set_initial_status(initial_response)
        except BadStatus:
            self._operation.status = 'Failed'
            raise CloudError(initial_response)
        except BadResponse as err:
            self._operation.status = 'Failed'
            raise CloudError(initial_response, str(err))
        except OperationFailed:
            raise CloudError(initial_response)
900974
def __send_retry_requests(self, last_send_failure_time):
        """"""
        # make sure multiple failures having set multiple times do not run concurrently
        with self.__send_retry_requests_lock:
            with self.__requests:
                # produce list instead of generator as requests mapping can change during subsequent loop
                retry_reqs = [req for req in self.__requests.values()
                              if req._sent_without_response(last_send_failure_time)]

            retry_req_count = 0
            # don't continue if another network failure has occured (which will trigger this function again)
            while retry_reqs and self.__amqplink.last_send_exc_time <= last_send_failure_time:
                req = retry_reqs.pop()
                # lock individuallly so incoming request handling does not 'pause' for too long
                with self.__requests:
                    # might have received a response (or finished since)
                    if not (req.id_ in self.__requests and req._sent_without_response(last_send_failure_time)):
                        logger.debug('Not resending request %s (finished or has received response)', req.id_)
                        continue
                logger.debug('Resending request %s', req.id_)
                if not self.__retry_enqueue(PreparedMessage(req._inner_msg_out, req.id_)):
                    # client shutdown
                    break
                retry_req_count += 1

        if retry_req_count:
            logger.debug('Resending of %d request(s) complete (before %s)', retry_req_count, last_send_failure_time)
86162
def _retry(function):
        

        def inner(self, **kwargs):
            last_exception = None
            #for host in self.router.get_hosts(**kwargs):
            for host in self.host:
                try:
                    return function(self, host, **kwargs)
                except SolrError as e:
                    self.logger.exception(e)
                    raise
                except ConnectionError as e:
                    self.logger.exception("Tried connecting to Solr, but couldn't because of the following exception.")
                    if '401' in e.__str__():
                        raise
                    last_exception = e
            # raise the last exception after contacting all hosts instead of returning None
            if last_exception is not None:
                raise last_exception
        return inner
709198
def _can_retry(self, batch, error):
        
        return (batch.attempts < self.config['retries']
                and getattr(error, 'retriable', False))
881021
def exception_retry_middleware(make_request, web3, errors, retries=5):
    
    def middleware(method, params):
        if check_if_retry_on_failure(method):
            for i in range(retries):
                try:
                    return make_request(method, params)
                except errors:
                    if i < retries - 1:
                        continue
                    else:
                        raise
        else:
            return make_request(method, params)
    return middleware