connect_forwarder

    :param forward_host: host for receiving forwarded packets
    :param forward_port: port for the forwarded packets
    :param max_retries: retries, -1 = infinite
    :param sleep_interval: how often to retry in this loop
502088
def connect_forwarder(forward_host=None,
                      forward_port=None,
                      max_retries=-1,
                      sleep_interval=1.0):
    

    forward_skt = None
    retry_count = 0
    if max_retries == -1:
        retry_count = -2

    if forward_host and forward_port:
        while not forward_skt and \
              retry_count < max_retries:
            try:
                forward_skt = socket.socket()
                log.info(("connecting to forward={}:{}")
                         .format(forward_host,
                                 forward_port))
                forward_skt.connect((forward_host,
                                     forward_port))
                log.debug(("connected to forward={}:{}")
                          .format(forward_host,
                                  forward_port))
            except Exception as s:
                forward_skt = None
                log.error(("Failed to connect forward address={}:{} "
                           "with ex={}")
                          .format(forward_host,
                                  forward_port,
                                  s))
                if max_retries == -1:
                    retry_count = -2
                else:
                    retry_count += 1
            # end of try/ex
            time.sleep(sleep_interval)
        # end of setting up forward
    # end forward_host and forward_port

    return forward_skt
1210863
def _show_retry_warning(host):
        
        sys.stderr.write("\nConnection to {} failed. Retrying.\n".format(host))
        sys.stderr.flush()
636528
def repeater(call, args=None, kwargs=None, retries=4):
    
    args = args or ()
    kwargs = kwargs or {}
    t = 1.0
    for x in range(retries):
        try:
            return call(*args, **kwargs)
        except APIError as ex:
            logger.error("query #%d: docker returned an error: %r", x, ex)
        except Exception as ex:
            # this may be pretty bad
            log_last_traceback()
            logger.error("query #%d: generic error: %r", x, ex)
        t *= 2
        time.sleep(t)
533334
def retry(max_retries=1):
    

    def retry_func(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            num_retries = 0
            while num_retries <= max_retries:
                try:
                    ret = func(*args, **kwargs)
                    break
                except HTTPError:
                    if num_retries == max_retries:
                        raise
                    num_retries += 1
                    time.sleep(5)
            return ret

        return wrapper

    return retry_func
1304088
def _connect(self):
        """"""
        while self.protocol:
            _LOGGER.info('Trying to connect to %s', self.server_address)
            try:
                sock = socket.create_connection(
                    self.server_address, self.reconnect_timeout)
            except socket.timeout:
                _LOGGER.error(
                    'Connecting to socket timed out for %s',
                    self.server_address)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            except OSError:
                _LOGGER.error(
                    'Failed to connect to socket at %s', self.server_address)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            else:
                self.tcp_check_timer = time.time()
                self.tcp_disconnect_timer = time.time()
                transport = TCPTransport(
                    sock, lambda: self.protocol, self._check_connection)
                poll_thread = threading.Thread(target=self._poll_queue)
                self._stop_event.clear()
                poll_thread.start()
                transport.start()
                transport.connect()
                return
60651
def retry(method):
    

    def inner(self, *args, **kwargs):
        attempt_number = 1
        while attempt_number < self.retries:
            try:
                return method(self, *args, **kwargs)
            except HasOffersException as exc:
                if 'API usage exceeded rate limit' not in str(exc):
                    raise exc
                self.logger.debug('Retrying due: %s', exc)
                time.sleep(self.retry_timeout)
            except requests.exceptions.ConnectionError:
                # This happens when the session gets expired
                self.logger.debug('Recreating session due to ConnectionError')
                self._session = requests.Session()
            attempt_number += 1
        raise MaxRetriesExceeded

    return inner
1283907
def ida_connect(host='localhost', port=18861, retry=10):
    
    for i in range(retry):
        try:
            LOG.debug('Connectint to %s:%d, try %d...', host, port, i + 1)
            link = rpyc_classic.connect(host, port)
            link.eval('2 + 2')
        except socket.error:
            time.sleep(1)
            continue
        else:
            LOG.debug('Connected to %s:%d', host, port)
            return link

    raise IDALinkError("Could not connect to %s:%d after %d tries" % (host, port, retry))
194716
def await_connection(host, port):
    """"""
    for i in range(CONNECT_ATTEMPTS):
        try:
            conn = socket.create_connection((host, port), CONNECT_TIMEOUT)
            conn.close()
            return True
        except (IOError, socket.error):
            time.sleep(1)
    return False
612102
def check_webserver_running(url="http://localhost:8800", max_retries=30):
    

    retry = 0
    response = ''
    success = False

    while response != requests.codes.ok and retry < max_retries:
        try:
            response = requests.head(url, allow_redirects=True).status_code
            success = True
        except:
            sleep(1)

        retry += 1

    if not success:
        logging.warning('Unable to connect to %s within %s retries'
                     % (url, max_retries))
    return success
1096166
def reconnect
      tries = 0
      begin
        redis.synchronize do |client|
          client.reconnect
        end
      rescue Redis::BaseConnectionError
        if (tries += 1) <= 3
          log "Error reconnecting to Redis; retrying"
          sleep(tries)
          retry
        else
          log "Error reconnecting to Redis; quitting"
          raise
        end
      end
    end
246553
def _ssh_forward_accept(ssh_session, timeout_ms):
    

    ssh_channel = c_ssh_forward_accept(c_void_p(ssh_session), 
                                       c_int(timeout_ms))

    if ssh_channel is None:
        raise SshTimeoutException()

    return ssh_channel
708328
def HandleExceptionsAndRebuildHttpConnections(retry_args):
    
    # If the server indicates how long to wait, use that value.  Otherwise,
    # calculate the wait time on our own.
    retry_after = None

    # Transport failures
    if isinstance(retry_args.exc, (http_client.BadStatusLine,
                                   http_client.IncompleteRead,
                                   http_client.ResponseNotReady)):
        logging.debug('Caught HTTP error %s, retrying: %s',
                      type(retry_args.exc).__name__, retry_args.exc)
    elif isinstance(retry_args.exc, socket.error):
        logging.debug('Caught socket error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.gaierror):
        logging.debug(
            'Caught socket address error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.timeout):
        logging.debug(
            'Caught socket timeout error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, httplib2.ServerNotFoundError):
        logging.debug(
            'Caught server not found error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, ValueError):
        # oauth2client tries to JSON-decode the response, which can result
        # in a ValueError if the response was invalid. Until that is fixed in
        # oauth2client, need to handle it here.
        logging.debug('Response content was invalid (%s), retrying',
                      retry_args.exc)
    elif (isinstance(retry_args.exc, TokenRefreshError) and
          hasattr(retry_args.exc, 'status') and
          (retry_args.exc.status == TOO_MANY_REQUESTS or
           retry_args.exc.status >= 500)):
        logging.debug(
            'Caught transient credential refresh error (%s), retrying',
            retry_args.exc)
    elif isinstance(retry_args.exc, exceptions.RequestError):
        logging.debug('Request returned no response, retrying')
    # API-level failures
    elif isinstance(retry_args.exc, exceptions.BadStatusCodeError):
        logging.debug('Response returned status %s, retrying',
                      retry_args.exc.status_code)
    elif isinstance(retry_args.exc, exceptions.RetryAfterError):
        logging.debug('Response returned a retry-after header, retrying')
        retry_after = retry_args.exc.retry_after
    else:
        raise retry_args.exc
    RebuildHttpConnections(retry_args.http)
    logging.debug('Retrying request to url %s after exception %s',
                  retry_args.http_request.url, retry_args.exc)
    time.sleep(
        retry_after or util.CalculateWaitForRetry(
            retry_args.num_retries, max_wait=retry_args.max_retry_wait))
385490
private boolean pauseIfRetryNeeded(int retries) {
        if (retries >= connection.getMaxErrorRetry()) {
            return false;
        }
        long delay = (long) (Math.random() * Math.pow(4, retries) * 125);
        try {
            Thread.sleep(delay);
        } catch (Exception e) {
            throw MwsUtl.wrap(e);
        }
        return true;
    }
689812
def retrier(*, max_attempts, sleeptime, max_sleeptime, sleepscale=1.5, jitter=0.2):
  
  assert(max_attempts > 1)
  assert(sleeptime >= 0)
  assert(0 <= jitter <= sleeptime)
  assert(sleepscale >= 1)

  cur_sleeptime = min(max_sleeptime, sleeptime)

  for attempt in range(max_attempts):
    cur_jitter = random.randint(int(-jitter * 1000), int(jitter * 1000)) / 1000
    yield max(0, cur_sleeptime + cur_jitter)
    cur_sleeptime = min(max_sleeptime, cur_sleeptime * sleepscale)
610855
def connect_hostport(hostport, timeout=RPC_DEFAULT_TIMEOUT, my_hostport=None):
    
    host, port = url_to_host_port(hostport)

    assert host is not None and port is not None

    protocol = url_protocol(hostport)
    if protocol is None:
        log.warning("No scheme given in {}. Guessing by port number".format(hostport))
        if port == RPC_SERVER_PORT or port == RPC_SERVER_TEST_PORT:
            protocol = 'http'
        else:
            protocol = 'https'

    proxy = BlockstackRPCClient(host, port, timeout=timeout, src=my_hostport, protocol=protocol)
    return proxy
806060
def _connect(self, target, listen, udp, ipv6, retry):
        
        ty = socket.SOCK_DGRAM if udp else socket.SOCK_STREAM
        fam = socket.AF_INET6 if ipv6 else socket.AF_INET
        self.sock = socket.socket(fam, ty)
        if listen:
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.bind(target)
            if not udp:
                self.sock.listen(1)
                conn, addr = self.sock.accept()
                self.sock.close()
                self.sock = conn
                self.peer = addr
            else:
                self.buf, self.peer = self.sock.recvfrom(1024)
                self.sock.connect(self.peer)
                self._log_recv(self.buf, False)
            if self.verbose:
                self._print_verbose('Connection from %s accepted' % str(self.peer))
        else:
            while True:
                try:
                    self.sock.connect(target)
                except (socket.gaierror, socket.herror) as exc:
                    raise NetcatError('Could not connect to %r: %r' \
                            % (target, exc))
                except socket.error as exc:
                    if retry:
                        time.sleep(0.2)
                    else:
                        raise NetcatError('Could not connect to %r: %r' \
                                % (target, exc))
                else:
                    break
            self.peer = target
1353152
def create_connection(self):
        
        attempts = 0
        while True:
            attempts += 1
            try:
                self.connection = Connection('127.0.0.1', 'guest', 'guest')
                break
            except amqpstorm.AMQPError as why:
                LOGGER.exception(why)
                if self.max_retries and attempts > self.max_retries:
                    break
                time.sleep(min(attempts * 2, 30))
            except KeyboardInterrupt:
                break