<s> '''<STR_LIT>''' <EOL> from utils import ROLE_MASTER , ROLE_SLAVE , REDIS_STATUS_OK , REDIS_STATUS_KO <EOL> class Cluster ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self ) : <EOL> self . _map = { } <EOL> def add_node ( self , host , port , role = ROLE_SLAVE , status = REDIS_STATUS_OK ) : <EOL> key = self . _make_key ( host , port ) <EOL> node = Node ( host , port , role , status ) <EOL> self . _map [ key ] = node <EOL> return node <EOL> def get_master ( self ) : <EOL> for k in self . _map : <EOL> node = self . _map [ k ] <EOL> if node . is_master ( ) : <EOL> return node <EOL> return None <EOL> def promote_new_master ( self , old_master ) : <EOL> old_master . set_slave ( ) <EOL> old_master . setKO ( ) <EOL> for k in self . _map : <EOL> node = self . _map [ k ] <EOL> if node . is_alive ( ) : <EOL> self . _set_role ( node . host , node . port , ROLE_MASTER ) <EOL> return node <EOL> old_master . set_master ( ) <EOL> return old_master <EOL> def filtered_list ( self , roles = ( ROLE_MASTER , ROLE_SLAVE ) , status = ( REDIS_STATUS_OK , REDIS_STATUS_KO ) ) : <EOL> return_list = [ ] <EOL> for k in self . _map : <EOL> node = self . _map [ k ] <EOL> if node . status in status and node . role in roles : <EOL> return_list . append ( node ) <EOL> return return_list <EOL> def get_node ( self , host , port ) : <EOL> key = self . _make_key ( host , port ) <EOL> return self . _map [ key ] <EOL> def __len__ ( self ) : <EOL> return len ( self . _map ) <EOL> def _set_role ( self , host , port , role ) : <EOL> key = self . _make_key ( host , port ) <EOL> self . _map [ key ] . _role = role <EOL> def _make_key ( self , host , port ) : <EOL> return "<STR_LIT>" % ( host , port ) <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT:U+002C>" . join ( [ str ( k ) for k in self . _map . values ( ) ] ) <EOL> class Node ( object ) : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , host , port , role , status ) : <EOL> self . _host = host <EOL> self . _port = int ( port ) <EOL> self . _role = role <EOL> self . _status = status <EOL> @ property <EOL> def host ( self ) : <EOL> return self . _host <EOL> @ property <EOL> def port ( self ) : <EOL> return self . _port <EOL> @ property <EOL> def role ( self ) : <EOL> return self . _role <EOL> @ property <EOL> def status ( self ) : <EOL> return self . _status <EOL> def is_master ( self ) : <EOL> return self . _role == ROLE_MASTER <EOL> def is_slave ( self ) : <EOL> return self . _role == ROLE_SLAVE <EOL> def is_alive ( self ) : <EOL> return self . _status == REDIS_STATUS_OK <EOL> def setOK ( self ) : <EOL> self . _status = REDIS_STATUS_OK <EOL> def setKO ( self ) : <EOL> self . _status = REDIS_STATUS_KO <EOL> def set_master ( self ) : <EOL> self . _role = ROLE_MASTER <EOL> def set_slave ( self ) : <EOL> self . _role = ROLE_SLAVE <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" % ( self . host , self . port , self . role , self . status ) </s>
