Get Redis that user might be using or instantiate
 a new one
489313
def redis
      if defined?($redis) && $redis
        Redis.new($redis.client.options)
      elsif defined?(REDIS) && REDIS
        Redis.new(REDIS.client.options)
      else
        Redis.new
      end
    end
1056756
function(err, results) {

        if (!err) {

          self.sessionSubscriber = new SessionSubscriber(
            self.conf && self.conf.redis && self.conf.redis ? self.conf.redis : undefined,
            self.serverName,
            function(err) {
              if (!err) {

                console.info(' (init) REDIS     is connected  (for pub/sub)');
                console.info('        REDIS     is subscribed (C-' + self.serverName + ')');

                self._startup(server, io);

                if (cb) cb();

              } else {
                console.error(err);
                process.exit(1);
              }
            }
          );

        } else {

          for (var errNum in results) {
            if (results.hasOwnProperty(errNum) && results[errNum]) {
              console.error('  - ' + results[errNum] + '\n');
            }
          }
          process.exit(1);
        }
      }
327867
def _init_redis(redis_spec):
        
        if not redis_spec:
            return
        if isinstance(redis_spec, six.string_types):
            return redis.StrictRedis.from_url(redis_spec)
        # assume any other value is a valid instance
        return redis_spec
79369
def get_redis_storage(data_type, full_name, args = {})
      self.class.redis_ping!
      case data_type.to_sym
      when :array
        Redis::List.new(full_name, {:marshal => true}.merge(args))
      when :hash
        Redis::HashKey.new(full_name)
      when :value
        Redis::Value.new(full_name, {:marshal => true}.merge(args))
      when :lock
        Redis::Lock.new(full_name, {:expiration => 60, :timeout => 0.1}.merge(args))
      when :stamped
        Stamped.new(full_name.sub("#{key}_", "").to_sym, get_redis_storage(:value, full_name), self)
      else
        raise TypeError.new("Unsupported caching data type encountered: #{data_type}")
      end
    end
1369657
def collect_instance(self, nick, host, port, unix_socket, auth):
        

        # Connect to redis and get the info
        info = self._get_info(host, port, unix_socket, auth)
        if info is None:
            return

        # The structure should include the port for multiple instances per
        # server
        data = dict()

        # Role needs to be handled outside the the _KEYS dict
        # since the value is a string, not a int / float
        # Also, master_sync_in_progress is only available if the
        # redis instance is a slave, so default it here so that
        # the metric is cleared if the instance flips from slave
        # to master
        if 'role' in info:
            if info['role'] == "master":
                data['replication.master'] = 1
                data['replication.master_sync_in_progress'] = 0
            else:
                data['replication.master'] = 0

        # Connect to redis and get the maxmemory config value
        # Then calculate the % maxmemory of memory used
        maxmemory_config = self._get_config(host, port, unix_socket, auth,
                                            'maxmemory')
        if maxmemory_config and 'maxmemory' in maxmemory_config.keys():
            maxmemory = float(maxmemory_config['maxmemory'])

            # Only report % used if maxmemory is a non zero value
            if maxmemory == 0:
                maxmemory_percent = 0.0
            else:
                maxmemory_percent = info['used_memory'] / maxmemory * 100
                maxmemory_percent = round(maxmemory_percent, 2)
            data['memory.used_percent'] = float("%.2f" % maxmemory_percent)

        # Iterate over the top level keys
        for key in self._KEYS:
            if self._KEYS[key] in info:
                data[key] = info[self._KEYS[key]]

        # Iterate over renamed keys for 2.6 support
        for key in self._RENAMED_KEYS:
            if self._RENAMED_KEYS[key] in info:
                data[key] = info[self._RENAMED_KEYS[key]]

        # Look for databaase speific stats
        for dbnum in range(0, int(self.config.get('databases',
                                                  self._DATABASE_COUNT))):
            db = 'db%i' % dbnum
            if db in info:
                for key in info[db]:
                    data['%s.%s' % (db, key)] = info[db][key]

        # Time since last save
        for key in ['last_save_time', 'rdb_last_save_time']:
            if key in info:
                data['last_save.time_since'] = int(time.time()) - info[key]

        # Publish the data to graphite
        for key in data:
            self.publish(self._publish_key(nick, key),
                         data[key],
                         precision=self._precision(data[key]),
                         metric_type='GAUGE')
46932
def one_instance(function=None, key='', timeout=DEFAULT_ONE_INSTANCE_TIMEOUT):
    
    def _dec(run_func):
        def _caller(*args, **kwargs):
            ret_value = None
            have_lock = False
            # Use Redis AOF for persistent lock.
            if REDIS_CLIENT.config_get('appendonly').values()[0] == 'no':
                REDIS_CLIENT.config_set('appendonly', 'yes')
            lock = REDIS_CLIENT.lock(key, timeout=timeout)
            try:
                logger.debug(
                    '%s: trying to acquire lock (PID %d).'
                    % (key, os.getpid()))
                have_lock = lock.acquire(blocking=False)
                if have_lock:
                    logger.debug(
                        '%s: acquired lock (PID %d).' % (key, os.getpid()))
                    ret_value = run_func(*args, **kwargs)
                else:
                    logger.error(
                        '%s: did not acquire lock (PID %d).'
                        % (key, os.getpid()))
            finally:
                if have_lock:
                    lock.release()
                    logger.debug(
                        '%s: released lock (PID %d).' % (key, os.getpid()))
            return ret_value
        return _caller
    return _dec(function) if function is not None else _dec
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
537800
function init(){
    self.type = config.type || 'redis';
    if(config.redisMock){
      self.db = config.redisMock;
    }
    else{
      if(config.redisUrl){
        self.redisData = config.redisUrl || null;
      }
      else if(config.redisEnv){
        self.redisData = process.env[config.redisEnv] || null;
      }
      else if(config.redisData){
        self.redisData = config.redisData;
      }
      self.readOnly = (typeof config.readOnly === 'boolean') ? config.readOnly : false;
      try {
        if (self.redisData) {
          if(typeof self.redisData === 'string'){
            self.db = redis.createClient(self.redisData,
              {'no_ready_check': true,
              retry_strategy: retryStrategy});
          } else {
            self.db = redis.createClient(self.redisData.port,
              self.redisData.hostname, {'no_ready_check': true,
              retry_strategy: retryStrategy});

            // don't call redis auth method if no auth info passed
            if (self.redisData.auth) {
              self.db.auth(self.redisData.auth);
            }
          }
          self.db.on('error', function(err) {
            console.log('Error ' + err);
          });
          process.on('SIGTERM', function() {
            self.db.quit();
          });
          log(false, 'Redis client created with the following defaults:', {expiration: self.defaultExpiration, verbose: self.verbose, readOnly: self.readOnly});
        } else {
          self.db = false;
          log(false, 'Redis client not created: no redis config provided');
        }
      } catch (err) {
        self.db = false;
        log(true, 'Redis client not created:', err);
      }
    }
  }
870237
def get_redis(**options):
    
    from uliweb import settings
    from uliweb.utils.common import log
    import redis
        
    options = (options or {})
    options.update(settings.REDIS)
    if 'unix_socket_path' in options:
        client = redis.Redis(unix_socket_path=options['unix_socket_path'])
    else:
        global __connection_pool__
    
        if not __connection_pool__ or __connection_pool__[0] != options['connection_pool']:
            d = {'host':'localhost', 'port':6379}
            d.update(options['connection_pool'])
            __connection_pool__ = (d, redis.ConnectionPool(**d))
        client = redis.Redis(connection_pool=__connection_pool__[1])
        
    if settings.REDIS.test_first:
        try:
            client.info()
        except Exception as e:
            log.exception(e)
            client = None
    return client
233800
def clone(client):
        ''''''
        kwargs = client.redis.connection_pool.connection_kwargs
        kwargs['parser_class'] = redis.connection.PythonParser
        pool = redis.connection.ConnectionPool(**kwargs)
        return redis.Redis(connection_pool=pool)
904576
def created_by(self):
        
        if self.api and self.created_by_id:
            return self.api._get_user(self.created_by_id)
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
153529
def redis_version(self):
        """"""
        if not hasattr(self, '_redis_version'):
            self._redis_version = tuple(
                map(int, self.connection.info().get('redis_version').split('.')[:3])
            )
        return self._redis_version
1319580
def ext_pillar(minion_id, pillar, function, **kwargs):
    '''
    
    '''
    if function.startswith('_') or function not in globals():
        return {}
    # Call specified function to pull redis data
    return globals()[function](minion_id, pillar, **kwargs)
22562
function isUserLocked(username, path, callback) {
  var key = SyncLock.generateKey(username);
  redis.hget(key, path, function(err, value) {
    if(err) {
      log.error(err, 'Error getting redis lock key %s.', key);
      return callback(err);
    }

    callback(null, !!value);
  });
}
315497
def create_connection():
    """"""

    global _cached_connection
    settings = oz.settings

    if settings["redis_cache_connections"] and _cached_connection != None:
        return _cached_connection
    else:
        conn = redis.StrictRedis(
            host=settings["redis_host"],
            port=settings["redis_port"],
            db=settings["redis_db"],
            password=settings["redis_password"],
            decode_responses=settings["redis_decode_responses"],
            ssl=settings["redis_use_ssl"],
            ssl_keyfile=settings["redis_ssl_keyfile"],
            ssl_certfile=settings["redis_ssl_certfile"],
            ssl_cert_reqs=settings["redis_ssl_cert_reqs"],
            ssl_ca_certs=settings["redis_ssl_ca_certs"]
        )

        if settings["redis_cache_connections"]:
            _cached_connection = conn

        return conn
1267792
def _callback_factory(callback_imp):
    """"""
    if callback_imp is None:
        try:
            pkg_resources.get_distribution('flask-login')
            from flask_login import current_user
            return lambda: current_user.is_authenticated
        except pkg_resources.DistributionNotFound:
            return lambda: False
    elif isinstance(callback_imp, string_types):
        return import_string(callback_imp)
    else:
        return callback_imp