idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
25,600
def __unify_unique_identities ( self , uidentities , matcher , fast_matching , interactive ) : self . total = len ( uidentities ) self . matched = 0 if self . recovery and self . recovery_file . exists ( ) : print ( "Loading matches from recovery file: %s" % self . recovery_file . location ( ) ) matched = self . recove...
Unify unique identities looking for similar identities .
25,601
def __merge ( self , matched , interactive ) : for m in matched : identities = m [ 'identities' ] uuid = identities [ 0 ] try : for c in identities [ 1 : ] : if self . __merge_unique_identities ( c , uuid , interactive ) : self . matched += 1 if interactive : uuid = api . unique_identities ( self . db , uuid = uuid ) [...
Merge a lists of matched unique identities
25,602
def __display_stats ( self ) : self . display ( 'unify.tmpl' , processed = self . total , matched = self . matched , unified = self . total - self . matched )
Display some stats regarding unify process
25,603
def __marshal_matches ( matched ) : json_matches = [ ] for m in matched : identities = [ i . uuid for i in m ] if len ( identities ) == 1 : continue json_match = { 'identities' : identities , 'processed' : False } json_matches . append ( json_match ) return json_matches
Convert matches to JSON format .
25,604
def load_matches ( self ) : if not self . exists ( ) : return [ ] matches = [ ] with open ( self . location ( ) , 'r' ) as f : for line in f . readlines ( ) : match_obj = json . loads ( line . strip ( "\n" ) ) if match_obj [ 'processed' ] : continue matches . append ( match_obj ) return matches
Load matches of the previous failed execution from the recovery file .
25,605
def save_matches ( self , matches ) : if not os . path . exists ( os . path . dirname ( self . location ( ) ) ) : os . makedirs ( os . path . dirname ( self . location ( ) ) ) with open ( self . location ( ) , "w+" ) as f : matches = [ m for m in matches if not m [ 'processed' ] ] for m in matches : match_obj = json . ...
Save matches of a failed execution to the log .
25,606
def __uuid ( * args ) : s = '-' . join ( args ) sha1 = hashlib . sha1 ( s . encode ( 'utf-8' , errors = 'surrogateescape' ) ) uuid_sha1 = sha1 . hexdigest ( ) return uuid_sha1
Generate a UUID based on the given parameters .
25,607
def __parse ( self , identities_stream , organizations_stream ) : if organizations_stream : self . __parse_organizations ( organizations_stream ) if identities_stream : self . __parse_identities ( identities_stream )
Parse GrimoireLab stream
25,608
def __parse_identities ( self , stream ) : def __create_sh_identities ( name , emails , yaml_entry ) : ids = [ ] ids . append ( Identity ( name = name , source = self . source ) ) if emails : for m in emails : ids . append ( Identity ( email = m , source = self . source ) ) for pb in PERCEVAL_BACKENDS : if pb not in ya...
Parse identities using GrimoireLab format .
25,609
def __parse_organizations ( self , stream ) : if not stream : return yaml_file = self . __load_yml ( stream ) try : for element in yaml_file : name = self . __encode ( element [ 'organization' ] ) if not name : error = "Empty organization name" msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise Invalid...
Parse GrimoireLab organizations .
25,610
def __parse_affiliations_yml ( self , affiliations ) : enrollments = [ ] for aff in affiliations : name = self . __encode ( aff [ 'organization' ] ) if not name : error = "Empty organization name" msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) elif name . lower ( ...
Parse identity s affiliations from a yaml dict .
25,611
def __force_datetime ( self , obj ) : if isinstance ( obj , datetime . datetime ) : return obj t = datetime . time ( 0 , 0 ) return datetime . datetime . combine ( obj , t )
Converts ojb to time . datetime . datetime
25,612
def __load_yml ( self , stream ) : try : return yaml . load ( stream , Loader = yaml . SafeLoader ) except ValueError as e : cause = "invalid yml format. %s" % str ( e ) raise InvalidFormatError ( cause = cause )
Load yml stream into a dict object
25,613
def __validate_email ( self , email ) : e = re . match ( self . EMAIL_ADDRESS_REGEX , email , re . UNICODE ) if e : return email else : error = "Invalid email address: " + str ( email ) msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg )
Checks if a string looks like an email address
25,614
def __validate_enrollment_periods ( self , enrollments ) : for a , b in itertools . combinations ( enrollments , 2 ) : max_start = max ( a . start , b . start ) min_end = min ( a . end , b . end ) if max_start < min_end : msg = "invalid GrimoireLab enrollment dates. " "Organization dates overlap." raise InvalidFormatEr...
Check for overlapped periods in the enrollments
25,615
def __parse ( self , stream ) : if not stream : raise InvalidFormatError ( cause = "stream cannot be empty or None" ) json = self . __load_json ( stream ) self . __parse_organizations ( json ) self . __parse_identities ( json ) self . __parse_blacklist ( json )
Parse Sorting Hat stream
25,616
def __parse_blacklist ( self , json ) : try : for entry in json [ 'blacklist' ] : if not entry : msg = "invalid json format. Blacklist entries cannot be null or empty" raise InvalidFormatError ( cause = msg ) excluded = self . __encode ( entry ) bl = self . _blacklist . get ( excluded , None ) if not bl : bl = Matching...
Parse blacklist entries using Sorting Hat format .
25,617
def __parse_organizations ( self , json ) : try : for organization in json [ 'organizations' ] : name = self . __encode ( organization ) org = self . _organizations . get ( name , None ) if not org : org = Organization ( name = name ) self . _organizations [ name ] = org domains = json [ 'organizations' ] [ organizatio...
Parse organizations using Sorting Hat format .
25,618
def run ( self , * args ) : params = self . parser . parse_args ( args ) with params . infile as infile : try : stream = self . __read_file ( infile ) parser = SortingHatParser ( stream ) except InvalidFormatError as e : self . error ( str ( e ) ) return e . code except ( IOError , TypeError , AttributeError ) as e : r...
Import data on the registry .
25,619
def import_blacklist ( self , parser ) : blacklist = parser . blacklist self . log ( "Loading blacklist..." ) n = 0 for entry in blacklist : try : api . add_to_matching_blacklist ( self . db , entry . excluded ) self . display ( 'load_blacklist.tmpl' , entry = entry . excluded ) n += 1 except ValueError as e : raise Ru...
Import blacklist .
25,620
def import_organizations ( self , parser , overwrite = False ) : orgs = parser . organizations for org in orgs : try : api . add_organization ( self . db , org . name ) except ValueError as e : raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : pass for dom in org . domains : try : api . add_domain ( sel...
Import organizations .
25,621
def import_identities ( self , parser , matching = None , match_new = False , no_strict_matching = False , reset = False , verbose = False ) : matcher = None if matching : strict = not no_strict_matching try : blacklist = api . blacklist ( self . db ) matcher = create_identity_matcher ( matching , blacklist , strict = ...
Import identities information on the registry .
25,622
def __load_unique_identities ( self , uidentities , matcher , match_new , reset , verbose ) : self . new_uids . clear ( ) n = 0 if reset : self . __reset_unique_identities ( ) self . log ( "Loading unique identities..." ) for uidentity in uidentities : self . log ( "\n=====" , verbose ) self . log ( "+ Processing %s" %...
Load unique identities
25,623
def __reset_unique_identities ( self ) : self . log ( "Reseting unique identities..." ) self . log ( "Clearing identities relationships" ) nids = 0 uidentities = api . unique_identities ( self . db ) for uidentity in uidentities : for identity in uidentity . identities : api . move_identity ( self . db , identity . id ...
Clear identities relationships and enrollments data
25,624
def __load_unique_identity ( self , uidentity , verbose ) : uuid = uidentity . uuid if uuid : try : api . unique_identities ( self . db , uuid ) self . log ( "-- %s already exists." % uuid , verbose ) return uuid except NotFoundError as e : self . log ( "-- %s not found. Generating a new UUID." % uuid , debug = verbose...
Seek or store unique identity
25,625
def __load_profile ( self , profile , uuid , verbose ) : def is_empty_profile ( prf ) : return not ( prf . name or prf . email or prf . gender or prf . gender_acc or prf . is_bot or prf . country_code ) uid = api . unique_identities ( self . db , uuid ) [ 0 ] if profile : self . __create_profile ( profile , uuid , verb...
Create a new profile when the unique identity does not have any .
25,626
def __create_profile ( self , profile , uuid , verbose ) : kw = profile . to_dict ( ) kw [ 'country_code' ] = profile . country_code kw . pop ( 'uuid' ) kw . pop ( 'country' ) api . edit_profile ( self . db , uuid , ** kw ) self . log ( "-- profile %s updated" % uuid , verbose )
Create profile information from a profile object
25,627
def __create_profile_from_identities ( self , identities , uuid , verbose ) : import re EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$" NAME_REGEX = r"^\w+\s\w+" name = None email = None username = None for identity in identities : if not name and identity . name : m = re . match ( NAME_REGEX , identity...
Create a profile using the data from the identities
25,628
def _merge_on_matching ( self , uuid , matcher , verbose ) : matches = api . match_identities ( self . db , uuid , matcher ) new_uuid = uuid u = api . unique_identities ( self . db , uuid ) [ 0 ] for m in matches : if m . uuid == uuid : continue self . _merge ( u , m , verbose ) new_uuid = m . uuid u = api . unique_ide...
Merge unique identity with uuid when a match is found
25,629
def _merge ( self , from_uid , to_uid , verbose ) : if verbose : self . display ( 'match.tmpl' , uid = from_uid , match = to_uid ) api . merge_unique_identities ( self . db , from_uid . uuid , to_uid . uuid ) if verbose : self . display ( 'merge.tmpl' , from_uuid = from_uid . uuid , to_uuid = to_uid . uuid )
Merge unique identity uid on match
25,630
def __parse ( self , aliases , email_to_employer , domain_to_employer ) : self . __parse_organizations ( domain_to_employer ) self . __parse_identities ( aliases , email_to_employer )
Parse Gitdm streams
25,631
def __parse_identities ( self , aliases , email_to_employer ) : self . __parse_aliases_stream ( aliases ) self . __parse_email_to_employer_stream ( email_to_employer ) for alias , email in self . __raw_aliases . items ( ) : uid = self . _identities . get ( email , None ) if not uid : uid = UniqueIdentity ( uuid = email...
Parse Gitdm identities
25,632
def __parse_organizations ( self , domain_to_employer ) : self . __parse_domain_to_employer_stream ( domain_to_employer ) for org in self . __raw_orgs : o = Organization ( name = org ) for dom in self . __raw_orgs [ org ] : d = Domain ( domain = dom , is_top_domain = False ) o . domains . append ( d ) self . _organizat...
Parse Gitdm organizations
25,633
def __parse_aliases_stream ( self , stream ) : if not stream : return f = self . __parse_aliases_line for alias_entries in self . __parse_stream ( stream , f ) : alias = alias_entries [ 0 ] username = alias_entries [ 1 ] self . __raw_aliases [ alias ] = username
Parse aliases stream .
25,634
def __parse_email_to_employer_stream ( self , stream ) : if not stream : return f = self . __parse_email_to_employer_line for rol in self . __parse_stream ( stream , f ) : email = rol [ 0 ] org = rol [ 1 ] rol_date = rol [ 2 ] if org not in self . __raw_orgs : self . __raw_orgs [ org ] = [ ] if email not in self . __ra...
Parse email to employer stream .
25,635
def __parse_domain_to_employer_stream ( self , stream ) : if not stream : return f = self . __parse_domain_to_employer_line for o in self . __parse_stream ( stream , f ) : org = o [ 0 ] dom = o [ 1 ] if org not in self . __raw_orgs : self . __raw_orgs [ org ] = [ ] self . __raw_orgs [ org ] . append ( dom )
Parse domain to employer stream .
25,636
def __parse_stream ( self , stream , parse_line ) : if not stream : raise InvalidFormatError ( cause = 'stream cannot be empty or None' ) nline = 0 lines = stream . split ( '\n' ) for line in lines : nline += 1 m = re . match ( self . LINES_TO_IGNORE_REGEX , line , re . UNICODE ) if m : continue m = re . match ( self ....
Generic method to parse gitdm streams
25,637
def __parse_aliases_line ( self , raw_alias , raw_username ) : alias = self . __encode ( raw_alias ) username = self . __encode ( raw_username ) return alias , username
Parse aliases lines
25,638
def __parse_email_to_employer_line ( self , raw_email , raw_enrollment ) : e = re . match ( self . EMAIL_ADDRESS_REGEX , raw_email , re . UNICODE ) if not e and self . email_validation : cause = "invalid email format: '%s'" % raw_email raise InvalidFormatError ( cause = cause ) if self . email_validation : email = e . ...
Parse email to employer lines
25,639
def __parse_domain_to_employer_line ( self , raw_domain , raw_org ) : d = re . match ( self . DOMAIN_REGEX , raw_domain , re . UNICODE ) if not d : cause = "invalid domain format: '%s'" % raw_domain raise InvalidFormatError ( cause = cause ) dom = d . group ( 'domain' ) . strip ( ) o = re . match ( self . ORGANIZATION_...
Parse domain to employer lines
25,640
def log ( self , uuid = None , organization = None , from_date = None , to_date = None ) : try : enrollments = api . enrollments ( self . db , uuid , organization , from_date , to_date ) self . display ( 'log.tmpl' , enrollments = enrollments ) except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ...
List enrollment information available in the registry .
25,641
def run ( self , * args ) : params = self . parser . parse_args ( args ) code = self . initialize ( name = params . name , reuse = params . reuse ) return code
Initialize a registry .
25,642
def initialize ( self , name , reuse = False ) : user = self . _kwargs [ 'user' ] password = self . _kwargs [ 'password' ] host = self . _kwargs [ 'host' ] port = self . _kwargs [ 'port' ] if '-' in name : self . error ( "dabase name '%s' cannot contain '-' characters" % name ) return CODE_VALUE_ERROR try : Database . ...
Create an empty Sorting Hat registry .
25,643
def __load_countries ( self , db ) : try : countries = self . __read_countries_file ( ) except IOError as e : raise LoadError ( str ( e ) ) try : with db . connect ( ) as session : for country in countries : session . add ( country ) except Exception as e : raise LoadError ( str ( e ) )
Load the list of countries
25,644
def __read_countries_file ( self ) : import csv import pkg_resources filename = pkg_resources . resource_filename ( 'sortinghat' , 'data/countries.csv' ) with open ( filename , 'r' ) as f : reader = csv . DictReader ( f , fieldnames = [ 'name' , 'code' , 'alpha3' ] ) countries = [ Country ( ** c ) for c in reader ] ret...
Read countries from a CSV file
25,645
def run ( self , * args ) : params = self . parser . parse_args ( args ) identifier = params . identifier identity = params . identity code = self . remove ( identifier , identity ) return code
Remove unique identities or identities from the registry .
25,646
def merge_date_ranges ( dates ) : if not dates : return sorted_dates = sorted ( [ sorted ( t ) for t in dates ] ) saved = list ( sorted_dates [ 0 ] ) for st , en in sorted_dates : if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE : raise ValueError ( "start date %s is out of bounds" % str ( st ) ) if en < MIN_PERIOD_DATE...
Merge date ranges .
25,647
def uuid ( source , email = None , name = None , username = None ) : if source is None : raise ValueError ( "source cannot be None" ) if source == '' : raise ValueError ( "source cannot be an empty string" ) if not ( email or name or username ) : raise ValueError ( "identity data cannot be None or empty" ) s = ':' . jo...
Get the UUID related to the identity data .
25,648
def create_database_engine ( user , password , database , host , port ) : driver = 'mysql+pymysql' url = URL ( driver , user , password , host , port , database , query = { 'charset' : 'utf8mb4' } ) return create_engine ( url , poolclass = QueuePool , pool_size = 25 , pool_pre_ping = True , echo = False )
Create a database engine
25,649
def create_database_session ( engine ) : try : Session = sessionmaker ( bind = engine ) return Session ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )
Connect to the database
25,650
def close_database_session ( session ) : try : session . close ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )
Close connection with the database
25,651
def reflect_table ( engine , klass ) : try : meta = MetaData ( ) meta . reflect ( bind = engine ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] ) table = None for tb in klass . tables ( ) : if tb in meta . tables : table = meta . tables [ tb ] break if...
Inspect and reflect objects
25,652
def find_model_by_table_name ( name ) : for model in ModelBase . _decl_class_registry . values ( ) : if hasattr ( model , '__table__' ) and model . __table__ . fullname == name : return model return None
Find a model reference by its table name
25,653
def handle_database_error ( cls , session , exception ) : session . rollback ( ) if isinstance ( exception , IntegrityError ) : cls . handle_integrity_error ( exception ) elif isinstance ( exception , FlushError ) : cls . handle_flush_error ( exception ) else : raise exception
Rollback changes made and handle any type of error raised by the DBMS .
25,654
def handle_integrity_error ( cls , exception ) : m = re . match ( cls . MYSQL_INSERT_ERROR_REGEX , exception . statement ) if not m : raise exception model = find_model_by_table_name ( m . group ( 'table' ) ) if not model : raise exception m = re . match ( cls . MYSQL_DUPLICATE_ENTRY_ERROR_REGEX , exception . orig . ar...
Handle integrity error exceptions .
25,655
def handle_flush_error ( cls , exception ) : trace = exception . args [ 0 ] m = re . match ( cls . MYSQL_FLUSH_ERROR_REGEX , trace ) if not m : raise exception entity = m . group ( 'entity' ) eid = m . group ( 'eid' ) raise AlreadyExistsError ( entity = entity , eid = eid )
Handle flush error exceptions .
25,656
def run ( self , * args ) : self . parser . parse_args ( args ) code = self . affiliate ( ) return code
Affiliate unique identities to organizations .
25,657
def affiliate ( self ) : try : uidentities = api . unique_identities ( self . db ) for uid in uidentities : uid . identities . sort ( key = lambda x : x . id ) for identity in uid . identities : if not identity . email : continue if not EMAIL_ADDRESS_PATTERN . match ( identity . email ) : continue domain = identity . e...
Affiliate unique identities .
25,658
def run ( self , * args ) : params = self . parser . parse_args ( args ) ct = params . code_or_term if ct and len ( ct ) < 2 : self . error ( 'Code country or term must have 2 or more characters length' ) return CODE_INVALID_FORMAT_ERROR code = ct if ct and len ( ct ) == 2 else None term = ct if ct and len ( ct ) > 2 e...
Show information about countries .
25,659
async def _call_async ( self , method_name : str , * args , ** kwargs ) : request = utils . rpc_request ( method_name , * args , ** kwargs ) _log . debug ( "Sending request: %s" , request ) self . _events [ request . id ] = asyncio . Event ( ) asyncio . ensure_future ( self . _recv_reply ( ) ) await self . _async_socke...
Sends a request to the socket and then wait for the reply .
25,660
async def _recv_reply ( self ) : raw_reply , = await self . _async_socket . recv_multipart ( ) reply = from_msgpack ( raw_reply ) _log . debug ( "Received reply: %s" , reply ) self . _replies [ reply . id ] = reply self . _events . pop ( reply . id ) . set ( )
Helper task to recieve a reply store the result and trigger the associated event .
25,661
def call ( self , method_name : str , * args , rpc_timeout : float = None , ** kwargs ) : request = utils . rpc_request ( method_name , * args , ** kwargs ) _log . debug ( "Sending request: %s" , request ) self . _socket . send_multipart ( [ to_msgpack ( request ) ] ) if rpc_timeout is None : rpc_timeout = self . rpc_t...
Send JSON RPC request to a backend socket and receive reply Note that this uses the default event loop to run in a blocking manner . If you would rather run in an async fashion or provide your own event loop then use . async_call instead
25,662
def close ( self ) : self . _socket . close ( ) if self . _async_socket_cache : self . _async_socket_cache . close ( ) self . _async_socket_cache = None
Close the sockets
25,663
def _connect_to_socket ( self , context : zmq . Context , endpoint : str ) : socket = context . socket ( zmq . DEALER ) socket . connect ( endpoint ) socket . setsockopt ( zmq . LINGER , 0 ) _log . debug ( "Client connected to endpoint %s" , self . endpoint ) return socket
Connect to a DEALER socket at endpoint and turn off lingering .
25,664
def _async_socket ( self ) : if not self . _async_socket_cache : self . _async_socket_cache = self . _connect_to_socket ( zmq . asyncio . Context ( ) , self . endpoint ) return self . _async_socket_cache
Creates a new async socket if one doesn t already exist for this Client
25,665
def run ( self , endpoint : str , loop : AbstractEventLoop = None ) : if not loop : loop = asyncio . get_event_loop ( ) try : loop . run_until_complete ( self . run_async ( endpoint ) ) except KeyboardInterrupt : self . _shutdown ( )
Run server main task .
25,666
def _shutdown ( self ) : for exit_handler in self . _exit_handlers : exit_handler ( ) if self . _socket : self . _socket . close ( ) self . _socket = None
Shut down the server .
25,667
def _connect ( self , endpoint : str ) : if self . _socket : raise RuntimeError ( 'Cannot run multiple Servers on the same socket' ) context = zmq . asyncio . Context ( ) self . _socket = context . socket ( zmq . ROUTER ) self . _socket . bind ( endpoint ) _log . info ( "Starting server, listening on endpoint {}" . for...
Connect the server to an endpoint . Creates a ZMQ ROUTER socket for the given endpoint .
25,668
async def _process_request ( self , identity : bytes , empty_frame : list , request : RPCRequest ) : try : _log . debug ( "Client %s sent request: %s" , identity , request ) start_time = datetime . now ( ) reply = await self . rpc_spec . run_handler ( request ) if self . announce_timing : _log . info ( "Request {} for ...
Executes the method specified in a JSON RPC request and then sends the reply to the socket .
25,669
def add_handler ( self , f ) : if f . __name__ . startswith ( 'rpc_' ) : raise ValueError ( "Server method names cannot start with rpc_." ) self . _json_rpc_methods [ f . __name__ ] = f return f
Adds the function f to a dictionary of JSON RPC methods .
25,670
def get_handler ( self , request ) : try : f = self . _json_rpc_methods [ request . method ] except ( AttributeError , KeyError ) : raise RPCMethodError ( "Received invalid method '{}'" . format ( request . method ) ) return f
Get callable from JSON RPC request
25,671
async def run_handler ( self , request : RPCRequest ) -> Union [ RPCReply , RPCError ] : with catch_warnings ( record = True ) as warnings : try : rpc_handler = self . get_handler ( request ) except RPCMethodError as e : return rpc_error ( request . id , str ( e ) , warnings = warnings ) try : args , kwargs = get_input...
Process a JSON RPC request
25,672
def rpc_request ( method_name : str , * args , ** kwargs ) -> rpcq . messages . RPCRequest : if args : kwargs [ '*args' ] = args return rpcq . messages . RPCRequest ( jsonrpc = '2.0' , id = str ( uuid . uuid4 ( ) ) , method = method_name , params = kwargs )
Create RPC request
25,673
def rpc_reply ( id : Union [ str , int ] , result : Optional [ object ] , warnings : Optional [ List [ Warning ] ] = None ) -> rpcq . messages . RPCReply : warnings = warnings or [ ] return rpcq . messages . RPCReply ( jsonrpc = '2.0' , id = id , result = result , warnings = [ rpc_warning ( warning ) for warning in war...
Create RPC reply
25,674
def rpc_error ( id : Union [ str , int ] , error_msg : str , warnings : List [ Any ] = [ ] ) -> rpcq . messages . RPCError : return rpcq . messages . RPCError ( jsonrpc = '2.0' , id = id , error = error_msg , warnings = [ rpc_warning ( warning ) for warning in warnings ] )
Create RPC error
25,675
def get_input ( params : Union [ dict , list ] ) -> Tuple [ list , dict ] : if isinstance ( params , list ) : args = params kwargs = { } elif isinstance ( params , dict ) : args = params . pop ( '*args' , [ ] ) kwargs = params else : raise TypeError ( 'Unknown type {} of params, must be list or dict' . format ( type ( ...
Get positional or keyword arguments from JSON RPC params
25,676
def repr_value ( value ) : if isinstance ( value , list ) and len ( value ) > REPR_LIST_TRUNCATION : return "[{},...]" . format ( ", " . join ( map ( repr , value [ : REPR_LIST_TRUNCATION ] ) ) ) else : return repr ( value )
Represent a value in human readable form . For long list s this truncates the printed representation .
25,677
def get ( cls , reactor , source = 'graphite' , ** options ) : acls = cls . alerts [ source ] return acls ( reactor , ** options )
Get Alert Class by source .
25,678
def convert ( self , value ) : try : return convert_to_format ( value , self . _format ) except ( ValueError , TypeError ) : return value
Convert self value .
25,679
def check ( self , records ) : for value , target in records : LOGGER . info ( "%s [%s]: %s" , self . name , target , value ) if value is None : self . notify ( self . no_data , value , target ) continue for rule in self . rules : if self . evaluate_rule ( rule , value , target ) : self . notify ( rule [ 'level' ] , va...
Check current value .
25,680
def evaluate_rule ( self , rule , value , target ) : def evaluate ( expr ) : if expr in LOGICAL_OPERATORS . values ( ) : return expr rvalue = self . get_value_for_expr ( expr , target ) if rvalue is None : return False return expr [ 'op' ] ( value , rvalue ) evaluated = [ evaluate ( expr ) for expr in rule [ 'exprs' ] ...
Calculate the value .
25,681
def get_value_for_expr ( self , expr , target ) : if expr in LOGICAL_OPERATORS . values ( ) : return None rvalue = expr [ 'value' ] if rvalue == HISTORICAL : history = self . history [ target ] if len ( history ) < self . history_size : return None rvalue = sum ( history ) / float ( len ( history ) ) rvalue = expr [ 'm...
I have no idea .
25,682
def notify ( self , level , value , target = None , ntype = None , rule = None ) : if target in self . state and level == self . state [ target ] : return False if target not in self . state and level == 'normal' and not self . reactor . options [ 'send_initial' ] : return False self . state [ target ] = level return s...
Notify main reactor about event .
25,683
def load ( self ) : LOGGER . debug ( '%s: start checking: %s' , self . name , self . query ) if self . waiting : self . notify ( 'warning' , 'Process takes too much time' , target = 'waiting' , ntype = 'common' ) else : self . waiting = True try : response = yield self . client . fetch ( self . url , auth_username = se...
Load data from Graphite .
25,684
def get_graph_url ( self , target , graphite_url = None ) : return self . _graphite_url ( target , graphite_url = graphite_url , raw_data = False )
Get Graphite URL .
25,685
def _graphite_url ( self , query , raw_data = False , graphite_url = None ) : query = escape . url_escape ( query ) graphite_url = graphite_url or self . reactor . options . get ( 'public_graphite_url' ) url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}" . format ( base = graphite_url , query = quer...
Build Graphite URL .
25,686
def load ( self ) : LOGGER . debug ( '%s: start checking: %s' , self . name , self . query ) if self . waiting : self . notify ( 'warning' , 'Process takes too much time' , target = 'waiting' , ntype = 'common' ) else : self . waiting = True try : response = yield self . client . fetch ( self . query , method = self . ...
Load URL .
25,687
def _get_loader ( config ) : if config . endswith ( '.yml' ) or config . endswith ( '.yaml' ) : if not yaml : LOGGER . error ( "pyyaml must be installed to use the YAML loader" ) return None , None return 'yaml' , yaml . load else : return 'json' , json . loads
Determine which config file type and loader to use based on a filename .
25,688
def start ( self , start_loop = True ) : self . start_alerts ( ) if self . options . get ( 'pidfile' ) : with open ( self . options . get ( 'pidfile' ) , 'w' ) as fpid : fpid . write ( str ( os . getpid ( ) ) ) self . callback . start ( ) LOGGER . info ( 'Reactor starts' ) if start_loop : self . loop . start ( )
Start all the things .
25,689
def notify ( self , level , alert , value , target = None , ntype = None , rule = None ) : LOGGER . info ( 'Notify %s:%s:%s:%s' , level , alert , value , target or "" ) if ntype is None : ntype = alert . source for handler in self . handlers . get ( level , [ ] ) : handler . notify ( level , alert , value , target = ta...
Provide the event to the handlers .
25,690
def write_to_file ( chats , chatfile ) : with open ( chatfile , 'w' ) as handler : handler . write ( '\n' . join ( ( str ( id_ ) for id_ in chats ) ) )
called every time chats are modified
25,691
def get_chatlist ( chatfile ) : if not chatfile : return set ( ) try : with open ( chatfile ) as file_contents : return set ( int ( chat ) for chat in file_contents ) except ( OSError , IOError ) as exc : LOGGER . error ( 'could not load saved chats:\n%s' , exc ) return set ( )
Try reading ids of saved chats from file . If we fail return empty set
25,692
def get_data ( upd , bot_ident ) : update_content = json . loads ( upd . decode ( ) ) result = update_content [ 'result' ] data = ( get_fields ( update , bot_ident ) for update in result ) return ( dt for dt in data if dt is not None )
Parse telegram update .
25,693
def get_fields ( upd , bot_ident ) : msg = upd . get ( 'message' , { } ) text = msg . get ( 'text' ) if not text : return chat_id = msg [ 'chat' ] [ 'id' ] command = filter_commands ( text , chat_id , bot_ident ) if not command : return return ( upd [ 'update_id' ] , chat_id , msg [ 'message_id' ] , command )
In telegram api not every update has message field and not every message has update field . We skip those cases . Rest of fields are mandatory . We also skip if text is not a valid command to handler .
25,694
def _listen_commands ( self ) : self . _last_update = None update_body = { 'timeout' : 2 } while True : latest = self . _last_update update_body . update ( { 'offset' : latest + 1 } if latest else { } ) update_resp = self . client . get_updates ( update_body ) update_resp . add_done_callback ( self . _respond_commands ...
Monitor new updates and send them further to self . _respond_commands where bot actions are decided .
25,695
def _respond_commands ( self , update_response ) : chatfile = self . chatfile chats = self . chats exc , upd = update_response . exception ( ) , update_response . result ( ) . body if exc : LOGGER . error ( str ( exc ) ) if not upd : return data = get_data ( upd , self . bot_ident ) for update_id , chat_id , message_id...
Extract commands to bot from update and act accordingly . For description of commands see HELP_MESSAGE variable on top of this module .
25,696
def notify ( self , level , * args , ** kwargs ) : LOGGER . debug ( 'Handler (%s) %s' , self . name , level ) notify_text = self . get_message ( level , * args , ** kwargs ) for chat in self . chats . copy ( ) : data = { "chat_id" : chat , "text" : notify_text } yield self . client . send_message ( data )
Sends alerts to telegram chats . This method is called from top level module . Do not rename it .
25,697
def get_message ( self , level , alert , value , ** kwargs ) : target , ntype = kwargs . get ( 'target' ) , kwargs . get ( 'ntype' ) msg_type = 'telegram' if ntype == 'graphite' else 'short' tmpl = TEMPLATES [ ntype ] [ msg_type ] generated = tmpl . generate ( level = level , reactor = self . reactor , alert = alert , ...
Standart alert message . Same format across all graphite - beacon handlers .
25,698
def fetchmaker ( self , telegram_api_method ) : fetch = self . client . fetch request = self . url ( telegram_api_method ) def _fetcher ( body , method = 'POST' , headers = None ) : body = json . dumps ( body ) if not headers : headers = { } headers . update ( { 'Content-Type' : 'application/json' } ) return fetch ( re...
Receives api method as string and returns wrapper around AsyncHTTPClient s fetch method
25,699
def _normalize_value_ms ( cls , value ) : value = round ( value / 1000 ) * 1000 sorted_units = sorted ( cls . UNITS_IN_MILLISECONDS . items ( ) , key = lambda x : x [ 1 ] , reverse = True ) for unit , unit_in_ms in sorted_units : unit_value = value / unit_in_ms if unit_value . is_integer ( ) : return int ( unit_value )...
Normalize a value in ms to the largest unit possible without decimal places .