Return the Redis server connection details from the __opts__.
420154
def _get_redis_cache_opts():
    '''
    
    '''
    return {
        'host': __opts__.get('cache.redis.host', 'localhost'),
        'port': __opts__.get('cache.redis.port', 6379),
        'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None),
        'db': __opts__.get('cache.redis.db', '0'),
        'password': __opts__.get('cache.redis.password', ''),
        'cluster_mode': __opts__.get('cache.redis.cluster_mode', False),
        'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}),
        'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False),
    }
375012
def _getaddrinfo(self, host: str, family: int=socket.AF_UNSPEC) \
            -> List[tuple]:
        '''
        '''
        event_loop = asyncio.get_event_loop()
        query = event_loop.getaddrinfo(host, 0, family=family,
                                       proto=socket.IPPROTO_TCP)

        if self._timeout:
            query = asyncio.wait_for(query, self._timeout)

        try:
            results = yield from query
        except socket.error as error:
            if error.errno in (
                    socket.EAI_FAIL,
                    socket.EAI_NODATA,
                    socket.EAI_NONAME):
                raise DNSNotFound(
                    'DNS resolution failed: {error}'.format(error=error)
                ) from error
            else:
                raise NetworkError(
                    'DNS resolution error: {error}'.format(error=error)
                ) from error
        except asyncio.TimeoutError as error:
            raise NetworkError('DNS resolve timed out.') from error
        else:
            return results
865332
def get_default_connection_info(self, provider_name):
        
        provider = self._provider_client.get_by_name(provider_name)
        if provider:
            return provider['defaultConnectionInfo']
        else:
            return {}
459902
def get_connection(self):
        "  "
        app = get_app()
        for connection, client_state in self._client_states.items():
            if client_state.app == app:
                return connection

        raise ValueError('Connection for app %r not found' % (app, ))
1131008
def redis_client(address=None, connection_pool=None, timeout=None,
                 parser=None, **kwargs):
    '''
    '''
    if not connection_pool:
        if timeout == 0:
            if not async:
                raise ImportError('Asynchronous connection requires async '
                                  'bindings installed.')
            return async.pool.redis(address, **kwargs)
        else:
            kwargs['socket_timeout'] = timeout
            return Redis(address[0], address[1], **kwargs)
    else:
        return Redis(connection_pool=connection_pool)
1085354
def get_redis_connection(config, use_strict_redis=False):
    
    redis_cls = redis.StrictRedis if use_strict_redis else redis.Redis

    if 'URL' in config:
        return redis_cls.from_url(config['URL'], db=config.get('DB'))

    if 'USE_REDIS_CACHE' in config.keys():

        try:
            # Assume that we're using django-redis
            from django_redis import get_redis_connection as get_redis
            return get_redis(config['USE_REDIS_CACHE'])
        except ImportError:
            pass

        from django.core.cache import caches
        cache = caches[config['USE_REDIS_CACHE']]
        # We're using django-redis-cache
        try:
            return cache._client
        except AttributeError:
            # For django-redis-cache > 0.13.1
            return cache.get_master_client()

    if 'UNIX_SOCKET_PATH' in config:
        return redis_cls(unix_socket_path=config['UNIX_SOCKET_PATH'], db=config['DB'])

    if 'SENTINELS' in config:
        sentinel_kwargs = {
            'db': config.get('DB'),
            'password': config.get('PASSWORD'),
            'socket_timeout': config.get('SOCKET_TIMEOUT'),
        }
        sentinel_kwargs.update(config.get('CONNECTION_KWARGS', {}))
        sentinel = Sentinel(config['SENTINELS'], **sentinel_kwargs)
        return sentinel.master_for(
            service_name=config['MASTER_NAME'], redis_class=redis_cls,
        )

    return redis_cls(host=config['HOST'], port=config['PORT'], db=config['DB'], password=config.get('PASSWORD'), ssl=config.get('SSL', False))
682798
def check_redis_connected(app_configs, **kwargs):
    
    import redis
    from django_redis import get_redis_connection
    errors = []

    try:
        connection = get_redis_connection('default')
    except redis.ConnectionError as e:
        msg = 'Could not connect to redis: {!s}'.format(e)
        errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
    except NotImplementedError as e:
        msg = 'Redis client not available: {!s}'.format(e)
        errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT))
    except ImproperlyConfigured as e:
        msg = 'Redis misconfigured: "{!s}"'.format(e)
        errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS))
    else:
        result = connection.ping()
        if not result:
            msg = 'Redis ping failed'
            errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED))
    return errors
980917
def _get_connection_info():
    """"""

    info = 'Connection: %s,' % CONN.url
    if CONN.creds is not None:
        info += ' userid=%s,' % CONN.creds[0]
    else:
        info += ' no creds,'

    info += ' cacerts=%s,' % ('sys-default' if CONN.ca_certs is None
                              else CONN.ca_certs)

    info += ' verifycert=%s,' % ('off' if CONN.no_verification else 'on')

    info += ' default-namespace=%s' % CONN.default_namespace
    if CONN.x509 is not None:
        info += ', client-cert=%s' % CONN.x509['cert_file']
        try:
            kf = CONN.x509['key_file']
        except KeyError:
            kf = "none"
        info += ":%s" % kf

    if CONN.timeout is not None:
        info += ', timeout=%s' % CONN.timeout

    # pylint: disable=protected-access
    info += ' stats=%s, ' % ('on' if CONN._statistics else 'off')

    info += 'log=%s' % ('on' if CONN._operation_recorders else 'off')

    if isinstance(CONN, FakedWBEMConnection):
        info += ', mock-server'

    return fill(info, 78, subsequent_indent='    ')
606016
def poll(self):
        """"""
        if self.redis_connected:
            json_item = request.get_json()
            result = None
            try:
                key = "rest:poll:{u}".format(u=json_item['poll_id'])
                result = self.redis_conn.get(key)

                if result is not None:
                    result = json.loads(result)
                    self.logger.debug("Found previous poll")
                    self.redis_conn.delete(key)
                    return self._create_ret_object(self.SUCCESS, result)
                else:
                    self.logger.debug("poll key does not exist")
                    return self._create_ret_object(self.FAILURE, None, True,
                                       "Could not find matching poll_id"), 404
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
            except ValueError:
                extras = {
                    "value": result
                }
                self.logger.warning('Unparseable JSON Received from redis',
                                                extra=extras)
                self.redis_conn.delete(key)
                return self._create_ret_object(self.FAILURE, None, True,
                                               "Unparseable JSON Received "
                                               "from redis"), 500
        self.logger.warn("Unable to poll redis, not connected")
        return self._create_ret_object(self.FAILURE, None, True,
                                       "Unable to connect to Redis"), 500
826990
def get_connection_params(self):
        
        return {
            'uri': self.settings_dict['NAME'],
            'tls': self.settings_dict.get('TLS', False),
            'bind_dn': self.settings_dict['USER'],
            'bind_pw': self.settings_dict['PASSWORD'],
            'retry_max': self.settings_dict.get('RETRY_MAX', 1),
            'retry_delay': self.settings_dict.get('RETRY_DELAY', 60.0),
            'options': {
                k if isinstance(k, int) else k.lower(): v
                for k, v in self.settings_dict.get('CONNECTION_OPTIONS', {}).items()
            },
        }
681498
def _redis_client(opts):
    '''
    
    '''
    redis_host = opts.get("eauth_redis_host", "localhost")
    redis_port = opts.get("eauth_redis_port", 6379)
    try:
        return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)
    except rediscluster.exceptions.RedisClusterException as err:
        log.warning(
            'Failed to connect to redis at %s:%s - %s',
            redis_host, redis_port, err
        )
        return None
641862
def get_connections_by_dests(self, dests):
        ''''''
        with self._mutex:
            res = []
            for c in self.connections:
                if not c.has_port(self):
                    continue
                has_dest = False
                for d in dests:
                    if c.has_port(d):
                        has_dest = True
                        break
                if has_dest:
                    res.append(c)
            return res
63006
def get_connection(self, internal=False):
        
        # Determine the connection string to use.
        connect_string = self.connect_string
        if internal:
            connect_string = self.internal_connect_string

        # Stripe Redis protocol prefix coming from the API.
        connect_string = connect_string.strip('redis://')
        host, port = connect_string.split(':')

        # Build and return the redis client.
        return redis.StrictRedis(host=host, port=port, password=self._password)
193186
def _final_redis_call(self, final_set, sort_options):
        

        conn = self.cls.get_connection()
        if sort_options is not None:
            # a sort, or values, call the SORT command on the set
            return conn.sort(final_set, **sort_options)
        else:
            # no sort, nor values, simply return the full set
            return conn.smembers(final_set)
195357
def _get_redis_server(opts=None):
    '''
    
    '''
    global REDIS_SERVER
    if REDIS_SERVER:
        return REDIS_SERVER
    if not opts:
        opts = _get_redis_cache_opts()

    if opts['cluster_mode']:
        REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],
                                          skip_full_coverage_check=opts['skip_full_coverage_check'])
    else:
        REDIS_SERVER = redis.StrictRedis(opts['host'],
                                   opts['port'],
                                   unix_socket_path=opts['unix_socket_path'],
                                   db=opts['db'],
                                   password=opts['password'])
    return REDIS_SERVER
1368829
def _sconnect(host=None, port=None, password=None):
    '''
    
    '''
    if host is None:
        host = __salt__['config.option']('redis_sentinel.host', 'localhost')
    if port is None:
        port = __salt__['config.option']('redis_sentinel.port', 26379)
    if password is None:
        password = __salt__['config.option']('redis_sentinel.password')

    return redis.StrictRedis(host, port, password=password, decode_responses=True)
801044
def redis(self):
        
        redis_url = current_app.config.get("SSE_REDIS_URL")
        if not redis_url:
            redis_url = current_app.config.get("REDIS_URL")
        if not redis_url:
            raise KeyError("Must set a redis connection URL in app config.")
        return StrictRedis.from_url(redis_url)