def __init__(self, cluster={}, db=0, mastersonly=False): # raise exception when wrong server hash if 'nodes' not in cluster: raise Exception( "rediscluster: Please set a correct array of redis cluster.") self.cluster = cluster have_master_of = 'master_of' in self.cluster self.no_servers = len( self.cluster['master_of']) if have_master_of else len( self.cluster['nodes']) self.redises = {} redises_cons = {} self.cluster['slaves'] = {} # connect to all servers for alias, server in iteritems(self.cluster['nodes']): if have_master_of and alias not in self.cluster['master_of']: continue server_str = str(server) if server_str in redises_cons: self.redises[alias] = redises_cons[server_str]['master'] self.redises[alias + '_slave'] = redises_cons[server_str]['slave'] self.cluster['slaves'][ alias + '_slave'] = redises_cons[server_str]['slave_node'] else: try: # connect to master self.__redis = redis.StrictRedis(db=db, **server) if not mastersonly and not have_master_of: info = self.__redis.info() if info['role'] != 'master': raise redis.DataError( "rediscluster: server %s is not a master." % (server, )) self.redises[alias] = self.__redis redises_cons[server_str] = {} redises_cons[server_str]['master'] = self.redises[alias] # connect to slave slave_connected = False slave = {} if not mastersonly: if have_master_of: slave = self.cluster['nodes'][ self.cluster['master_of'][alias]] elif 'connected_slaves' in info and info[ 'connected_slaves'] > 0: slave_host, slave_port, slave_online = info[ 'slave0'].split(',') if slave_online == 'online': slave = { 'host': slave_host, 'port': slave_port } if slave: try: redis_slave = redis.StrictRedis(host=slave['host'], port=int( slave['port']), db=db) self.redises[alias + '_slave'] = redis_slave self.cluster['slaves'][alias + '_slave'] = { 'host': slave['host'], 'port': slave['port'] } redises_cons[server_str]['slave'] = self.redises[ alias + '_slave'] redises_cons[server_str][ 'slave_node'] = self.cluster['slaves'][ alias + '_slave'] slave_connected = True except redis.RedisError as e: pass # "RedisCluster cannot connect to: " + slave_host +':'+ slave_port if not slave_connected: self.redises[alias + '_slave'] = self.redises[alias] self.cluster['slaves'][alias + '_slave'] = server redises_cons[server_str]['slave'] = self.redises[ alias + '_slave'] redises_cons[server_str]['slave_node'] = self.cluster[ 'slaves'][alias + '_slave'] except redis.RedisError as e: raise redis.ConnectionError( "rediscluster cannot connect to: %s %s" % (server, e))
def _raise(self): raise redis.ConnectionError()
def _is_redis_server_running(self): try: self.redis.ping() except redis.ConnectionError: raise redis.ConnectionError('Redis server is not responding')
def raise_exception(): raise redis.ConnectionError()
def test_redis_available_fails_when_ping_throws_exception( self, redis_mock): redis_mock.from_url.return_value.ping.side_effect = \ redis.ConnectionError() results = redis_available() assert results[0] is False