Ensure connection to DynamoDB

    :type retries: int
    :param retries: Number of times to retry to connect to DynamoDB
979783
def __get_connection_dynamodb(retries=3):
    
    connected = False
    region = get_global_option('region')

    while not connected:
        if (get_global_option('aws_access_key_id') and
                get_global_option('aws_secret_access_key')):
            logger.debug(
                'Authenticating to DynamoDB using '
                'credentials in configuration file')
            connection = dynamodb2.connect_to_region(
                region,
                aws_access_key_id=get_global_option('aws_access_key_id'),
                aws_secret_access_key=get_global_option(
                    'aws_secret_access_key'))
        else:
            logger.debug(
                'Authenticating using boto\'s authentication handler')
            connection = dynamodb2.connect_to_region(region)

        if not connection:
            if retries == 0:
                logger.error('Failed to connect to DynamoDB. Giving up.')
                raise
            else:
                logger.error(
                    'Failed to connect to DynamoDB. Retrying in 5 seconds')
                retries -= 1
                time.sleep(5)
        else:
            connected = True
            logger.debug('Connected to DynamoDB in {0}'.format(region))

    return connection
1210863
def _show_retry_warning(host):
        
        sys.stderr.write("\nConnection to {} failed. Retrying.\n".format(host))
        sys.stderr.flush()
396484
def is_retryable(err):
    
    if isinstance(err, ConnectionClosed):
        # NB: only retryable if we're not mid-streaming
        if err.mid_stream:
            return False
        else:
            return True
    elif isinstance(err, socket.error):
        code = err.args[0]
        return code in CONN_CLOSED_ERRORS
    else:
        return False
459908
def reconnect(self, conn_retries=None):
        '''  '''
        if conn_retries is None:
            conn_retries = self.conn_retries

        count = 0
        if self.logger:
            self.logger.info('Connecting to Redis..')
        while count < conn_retries:
            super(redis.client.Redis, self).__init__(*self.args, **self.kwargs)

            if self.ping():
                if self.logger:
                    self.logger.info('Connected to Redis!')
                return True
            else:
                sl = min(3 ** count, self.max_sleep)
                if self.logger:
                    self.logger.info('Connecting failed, retrying in {0} seconds'.format(sl))
                time.sleep(sl)
                count += 1
        raise ConnectionError
905326
def retry_timeout(api, retries=3):
    """"""
    @wraps(api)
    def retry_api(*args, **kwargs):
        """Retrying API."""
        for i in range(1, retries + 1):
            try:
                return api(*args, **kwargs)
            except RequestTimeout:
                if i == retries:
                    raise

    return retry_api
729865
def connect(self, *args, **kwargs):
        
        self.connection = DynamoDBConnection.connect(*args, **kwargs)
        self._session = kwargs.get("session")
        if self._session is None:
            self._session = botocore.session.get_session()
539617
def initialize_connection(self):  # noqa: E501 pylint:disable=too-many-statements, too-many-branches
        """"""
        tries = self.tries

        if self.socket is not None:
            self.socket.close()
            self.socket = None

        # Make sure nobody is blocking.
        for callback in self._request_callbacks.values():
            callback['event'].set()

        self.app_namespaces = []
        self.destination_id = None
        self.session_id = None
        self._request_id = 0
        self._request_callbacks = {}
        self._open_channels = []

        self.connecting = True
        retry_log_fun = self.logger.error

        # Dict keeping track of individual retry delay for each named service
        retries = {}

        def mdns_backoff(service, retry):
            """Exponentional backoff for service name mdns lookups."""
            now = time.time()
            retry['next_retry'] = now + retry['delay']
            retry['delay'] = min(retry['delay']*2, 300)
            retries[service] = retry

        while not self.stop.is_set() and (tries is None or tries > 0):  # noqa: E501 pylint:disable=too-many-nested-blocks
            # Prune retries dict
            retries = {key: retries[key] for key in self.services if (
                key is not None and key in retries)}

            for service in self.services.copy():
                now = time.time()
                retry = retries.get(
                    service, {'delay': self.retry_wait, 'next_retry': now})
                # If we're connecting to a named service, check if it's time
                if service and now < retry['next_retry']:
                    continue
                try:
                    self.socket = new_socket()
                    self.socket.settimeout(self.timeout)
                    self._report_connection_status(
                        ConnectionStatus(CONNECTION_STATUS_CONNECTING,
                                         NetworkAddress(self.host, self.port)))
                    # Resolve the service name. If service is None, we're
                    # connecting directly to a host name or IP-address
                    if service:
                        host = None
                        port = None
                        service_info = get_info_from_service(service,
                                                             self.zconf)
                        host, port = get_host_from_service_info(service_info)
                        if host and port:
                            try:
                                self.fn = service_info.properties[b'fn']\
                                    .decode('utf-8')
                            except (AttributeError, KeyError, UnicodeError):
                                pass
                            self.logger.debug(
                                "[%s:%s] Resolved service %s to %s:%s",
                                self.fn or self.host, self.port, service, host,
                                port)
                            self.host = host
                            self.port = port
                        else:
                            self.logger.debug(
                                "[%s:%s] Failed to resolve service %s",
                                self.fn or self.host, self.port, service)
                            self._report_connection_status(
                                ConnectionStatus(
                                    CONNECTION_STATUS_FAILED_RESOLVE,
                                    NetworkAddress(service, None)))
                            mdns_backoff(service, retry)
                            # If zeroconf fails to receive the necessary data,
                            # try next service
                            continue

                    self.logger.debug("[%s:%s] Connecting to %s:%s",
                                      self.fn or self.host, self.port,
                                      self.host, self.port)
                    self.socket.connect((self.host, self.port))
                    self.socket = ssl.wrap_socket(self.socket)
                    self.connecting = False
                    self._force_recon = False
                    self._report_connection_status(
                        ConnectionStatus(CONNECTION_STATUS_CONNECTED,
                                         NetworkAddress(self.host, self.port)))
                    self.receiver_controller.update_status()
                    self.heartbeat_controller.ping()
                    self.heartbeat_controller.reset()

                    self.logger.debug("[%s:%s] Connected!",
                                      self.fn or self.host, self.port)
                    return
                except OSError as err:
                    self.connecting = True
                    if self.stop.is_set():
                        self.logger.error(
                            "[%s:%s] Failed to connect: %s. "
                            "aborting due to stop signal.",
                            self.fn or self.host, self.port, err)
                        raise ChromecastConnectionError("Failed to connect")

                    self._report_connection_status(
                        ConnectionStatus(CONNECTION_STATUS_FAILED,
                                         NetworkAddress(self.host, self.port)))
                    if service is not None:
                        retry_log_fun(
                            "[%s:%s] Failed to connect to service %s"
                            ", retrying in %.1fs",
                            self.fn or self.host, self.port,
                            service, retry['delay'])
                        mdns_backoff(service, retry)
                    else:
                        retry_log_fun(
                            "[%s:%s] Failed to connect, retrying in %.1fs",
                            self.fn or self.host, self.port, self.retry_wait)
                    retry_log_fun = self.logger.debug

            # Only sleep if we have another retry remaining
            if tries is None or tries > 1:
                self.logger.debug(
                    "[%s:%s] Not connected, sleeping for %.1fs. Services: %s",
                    self.fn or self.host, self.port,
                    self.retry_wait, self.services)
                time.sleep(self.retry_wait)

            if tries:
                tries -= 1

        self.stop.set()
        self.logger.error("[%s:%s] Failed to connect. No retries.",
                          self.fn or self.host, self.port)
        raise ChromecastConnectionError("Failed to connect")
114035
async def create_pool(settings: RedisSettings = None, *, _retry: int = 0) -> ArqRedis:
    
    settings = settings or RedisSettings()
    addr = settings.host, settings.port
    try:
        pool = await aioredis.create_redis_pool(
            addr,
            db=settings.database,
            password=settings.password,
            timeout=settings.conn_timeout,
            encoding='utf8',
            commands_factory=ArqRedis,
        )
    except (ConnectionError, OSError, aioredis.RedisError, asyncio.TimeoutError) as e:
        if _retry < settings.conn_retries:
            logger.warning(
                'redis connection error %s:%s %s %s, %d retries remaining...',
                settings.host,
                settings.port,
                e.__class__.__name__,
                e,
                settings.conn_retries - _retry,
            )
            await asyncio.sleep(settings.conn_retry_delay)
        else:
            raise
    else:
        if _retry > 0:
            logger.info('redis connection successful')
        return pool

    # recursively attempt to create the pool outside the except block to avoid
    # "During handling of the above exception..." madness
    return await create_pool(settings, _retry=_retry + 1)
1246678
def _should_retry(self, context):
        # type: (ExponentialRetryWithMaxWait,
        #        azure.storage.common.models.RetryContext) -> bool
        
        # do not retry if max attempts equal or exceeded
        if context.count >= self.max_attempts:
            return False

        # get response status
        status = None
        if context.response and context.response.status:
            status = context.response.status

        # if there is no response status, then handle the exception
        # appropriately from the lower layer
        if status is None:
            exc = context.exception
            # default to not retry in unknown/unhandled exception case
            ret = False
            # requests timeout, retry
            if isinstance(exc, requests.Timeout):
                ret = True
            elif isinstance(exc, requests.exceptions.ContentDecodingError):
                ret = True
            elif (isinstance(exc, requests.exceptions.ConnectionError) or
                  isinstance(exc, requests.exceptions.ChunkedEncodingError)):
                # newer versions of requests do not expose errno on the
                # args[0] reason object; manually string parse
                if isinstance(exc.args[0], urllib3.exceptions.MaxRetryError):
                    try:
                        msg = exc.args[0].reason.args[0]
                    except (AttributeError, IndexError):
                        # unexpected/malformed exception hierarchy, don't retry
                        pass
                    else:
                        if any(x in msg for x in _RETRYABLE_ERRNO_MAXRETRY):
                            ret = True
                elif isinstance(exc.args[0], urllib3.exceptions.ProtocolError):
                    try:
                        msg = exc.args[0].args[0]
                    except (AttributeError, IndexError):
                        # unexpected/malformed exception hierarchy, don't retry
                        pass
                    else:
                        if any(x in msg for x in _RETRYABLE_ERRNO_PROTOCOL):
                            ret = True
            # fallback to string search
            if not ret:
                msg = str(exc).lower()
                if any(x in msg for x in _RETRYABLE_STRING_FALLBACK):
                    ret = True
            return ret
        elif 200 <= status < 300:
            # failure during respond body download or parsing, so success
            # codes should be retried
            return True
        elif 300 <= status < 500:
            # response code 404 should be retried if secondary was used
            if (status == 404 and
                    context.location_mode ==
                    azure.storage.common.models.LocationMode.SECONDARY):
                return True
            # response code 408 is a timeout and should be retried
            # response code 429 is too many requests (throttle)
            # TODO use "Retry-After" header for backoff amount
            if status == 408 or status == 429:
                return True
            return False
        elif status >= 500:
            # response codes above 500 should be retried except for
            # 501 (not implemented) and 505 (version not supported)
            if status == 501 or status == 505:
                return False
            return True
        else:  # noqa
            # this should be unreachable, retry anyway
            return True
28722
def authenticate(self, retries=3):
        

        username = self.username or self._getuser(self.base)
        password = self.password

        while retries > 0:
            if password is None:
                password = self._getpass(self.base, username)

            try:
                resp = self.post(self.base+'/authenticate', params={'username': username, 'password': password})

                schema = UserSchema()
                u = self.decode(schema, resp)

                if u.token is not None:
                    self.lock.acquire()
                    self.token = u.token
                    self.lock.release()
                    break
            except CDRouterError as cde:
                password = None
                retries -= 1
                if retries == 0:
                    raise cde

        return self.token
985316
def _create_connection(self):
        
        attempts = 0
        while True:
            attempts += 1
            if self._stopped.is_set():
                break
            try:
                self._connection = Connection(self.hostname,
                                              self.username,
                                              self.password)
                break
            except amqpstorm.AMQPError as why:
                LOGGER.warning(why)
                if self.max_retries and attempts > self.max_retries:
                    raise Exception('max number of retries reached')
                time.sleep(min(attempts * 2, 30))
            except KeyboardInterrupt:
                break
151317
def run_query(conn, query, retries=3):
    '''
    
    '''
    try:
        cur = conn.cursor()
        out = cur.execute(query)
        return cur, out
    except (AttributeError, OperationalError) as e:
        if retries == 0:
            raise
        # reconnect creating new client
        sleep(_RECONNECT_INTERVAL_SEC)
        if conn is None:
            log.debug("mysql_cache: creating db connection")
        else:
            log.info("mysql_cache: recreating db connection due to: %r", e)
        global client
        client = MySQLdb.connect(**_mysql_kwargs)
        return run_query(client, query, retries - 1)
    except Exception as e:
        if len(query) > 150:
            query = query[:150] + "<...>"
        raise SaltCacheError("Error running {0}: {1}".format(query, e))
666199
def fw_retry_failures_create(self):
        
        for tenant_id in self.fwid_attr:
            try:
                with self.fwid_attr[tenant_id].mutex_lock:
                    if self.fwid_attr[tenant_id].is_fw_drvr_create_needed():
                        fw_dict = self.fwid_attr[tenant_id].get_fw_dict()
                        if fw_dict:
                            fw_obj, fw_data = self.get_fw(fw_dict.get('fw_id'))
                            self.retry_failure_fab_dev_create(tenant_id,
                                                              fw_data,
                                                              fw_dict)
                        else:
                            LOG.error("FW data not found for tenant %s",
                                      tenant_id)
            except Exception as exc:
                LOG.error("Exception in retry failure create %s",
                          str(exc))
586909
async def retry_async(self, func, partition_id, retry_message,
                          final_failure_message, max_retries, host_id):
        
        created_okay = False
        retry_count = 0
        while not created_okay and retry_count <= max_retries:
            try:
                await func(partition_id)
                created_okay = True
            except Exception as err:  # pylint: disable=broad-except
                _logger.error("%r %r %r %r", retry_message, host_id, partition_id, err)
                retry_count += 1
        if not created_okay:
            raise Exception(host_id, final_failure_message)
804922
def _check_with_retry(self):
        
        # According to the spec, if an ismaster call fails we reset the
        # server's pool. If a server was once connected, change its type
        # to Unknown only after retrying once.
        address = self._server_description.address
        retry = True
        if self._server_description.server_type == SERVER_TYPE.Unknown:
            retry = False

        start = _time()
        try:
            return self._check_once()
        except ReferenceError:
            raise
        except Exception as error:
            error_time = _time() - start
            if self._publish:
                self._listeners.publish_server_heartbeat_failed(
                    address, error_time, error)
            self._topology.reset_pool(address)
            default = ServerDescription(address, error=error)
            if not retry:
                self._avg_round_trip_time.reset()
                # Server type defaults to Unknown.
                return default

            # Try a second and final time. If it fails return original error.
            # Always send metadata: this is a new connection.
            start = _time()
            try:
                return self._check_once()
            except ReferenceError:
                raise
            except Exception as error:
                error_time = _time() - start
                if self._publish:
                    self._listeners.publish_server_heartbeat_failed(
                        address, error_time, error)
                self._avg_round_trip_time.reset()
                return default
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
1287232
def connect_with_retry(self) -> None:
        
        if self.is_connected():
            log.debug('Already connected to the Slack API')
            return

        for retry in range(1, self.retries + 1):
            self.connect()
            if self.is_connected():
                log.debug('Connected to the Slack API')
                return
            else:
                interval = self.backoff(retry)
                log.debug("Waiting %.3fs before retrying", interval)
                time.sleep(interval)

        raise FailedConnection('Failed to connect to the Slack API')