idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
44,600 | def from_model_files ( cls , limits , input_model , investigation_time = 1.0 , simple_mesh_spacing = 1.0 , complex_mesh_spacing = 5.0 , mfd_width = 0.1 , area_discretisation = 10.0 ) : converter = SourceConverter ( investigation_time , simple_mesh_spacing , complex_mesh_spacing , mfd_width , area_discretisation ) sources = [ ] for grp in nrml . to_python ( input_model , converter ) : sources . extend ( grp . sources ) return cls ( limits , sources , area_discretisation ) | Reads the hazard model from a file |
44,601 | def get_rates ( self , mmin , mmax = np . inf ) : nsrcs = self . number_sources ( ) for iloc , source in enumerate ( self . source_model ) : print ( "Source Number %s of %s, Name = %s, Typology = %s" % ( iloc + 1 , nsrcs , source . name , source . __class__ . __name__ ) ) if isinstance ( source , CharacteristicFaultSource ) : self . _get_fault_rates ( source , mmin , mmax ) elif isinstance ( source , ComplexFaultSource ) : self . _get_fault_rates ( source , mmin , mmax ) elif isinstance ( source , SimpleFaultSource ) : self . _get_fault_rates ( source , mmin , mmax ) elif isinstance ( source , AreaSource ) : self . _get_area_rates ( source , mmin , mmax ) elif isinstance ( source , PointSource ) : self . _get_point_rates ( source , mmin , mmax ) else : print ( "Source type %s not recognised - skipping!" % source ) continue | Returns the cumulative rates greater than Mmin |
44,602 | def _get_point_location ( self , location ) : if ( location . longitude < self . xlim [ 0 ] ) or ( location . longitude > self . xlim [ - 1 ] ) : return None , None xloc = int ( ( ( location . longitude - self . xlim [ 0 ] ) / self . xspc ) + 1E-7 ) if ( location . latitude < self . ylim [ 0 ] ) or ( location . latitude > self . ylim [ - 1 ] ) : return None , None yloc = int ( ( ( location . latitude - self . ylim [ 0 ] ) / self . yspc ) + 1E-7 ) return xloc , yloc | Returns the location in the output grid corresponding to the cell in which the epicentre lays |
44,603 | def _get_area_rates ( self , source , mmin , mmax = np . inf ) : points = list ( source ) for point in points : self . _get_point_rates ( point , mmin , mmax ) | Adds the rates from the area source by discretising the source to a set of point sources |
44,604 | def _get_distance_scaling ( self , C , mag , rhypo ) : return ( C [ "a3" ] * np . log ( rhypo ) ) + ( C [ "a4" ] + C [ "a5" ] * mag ) * rhypo | Returns the distance scalig term |
44,605 | def _get_distance_scaling_term ( self , C , rjb , mag ) : rval = np . sqrt ( rjb ** 2.0 + C [ "c11" ] ** 2.0 ) f_0 , f_1 , f_2 = self . _get_distance_segment_coefficients ( rval ) return ( ( C [ "c4" ] + C [ "c5" ] * mag ) * f_0 + ( C [ "c6" ] + C [ "c7" ] * mag ) * f_1 + ( C [ "c8" ] + C [ "c9" ] * mag ) * f_2 + ( C [ "c10" ] * rval ) ) | Returns the distance scaling component of the model Equation 10 Page 63 |
44,606 | def _get_distance_segment_coefficients ( self , rval ) : nsites = len ( rval ) f_0 = np . log10 ( self . CONSTS [ "r0" ] / rval ) f_0 [ rval > self . CONSTS [ "r0" ] ] = 0.0 f_1 = np . log10 ( rval ) f_1 [ rval > self . CONSTS [ "r1" ] ] = np . log10 ( self . CONSTS [ "r1" ] ) f_2 = np . log10 ( rval / self . CONSTS [ "r2" ] ) f_2 [ rval <= self . CONSTS [ "r2" ] ] = 0.0 return f_0 , f_1 , f_2 | Returns the coefficients describing the distance attenuation shape for three different distance bins equations 12a - 12c |
44,607 | def collect_files ( dirpath , cond = lambda fullname : True ) : files = [ ] for fname in os . listdir ( dirpath ) : fullname = os . path . join ( dirpath , fname ) if os . path . isdir ( fullname ) : files . extend ( collect_files ( fullname ) ) else : if cond ( fullname ) : files . append ( fullname ) return files | Recursively collect the files contained inside dirpath . |
44,608 | def extract_from_zip ( path , candidates ) : temp_dir = tempfile . mkdtemp ( ) with zipfile . ZipFile ( path ) as archive : archive . extractall ( temp_dir ) return [ f for f in collect_files ( temp_dir ) if os . path . basename ( f ) in candidates ] | Given a zip archive and a function to detect the presence of a given filename unzip the archive into a temporary directory and return the full path of the file . Raise an IOError if the file cannot be found within the archive . |
44,609 | def get_params ( job_inis , ** kw ) : input_zip = None if len ( job_inis ) == 1 and job_inis [ 0 ] . endswith ( '.zip' ) : input_zip = job_inis [ 0 ] job_inis = extract_from_zip ( job_inis [ 0 ] , [ 'job_hazard.ini' , 'job_haz.ini' , 'job.ini' , 'job_risk.ini' ] ) not_found = [ ini for ini in job_inis if not os . path . exists ( ini ) ] if not_found : raise IOError ( 'File not found: %s' % not_found [ 0 ] ) cp = configparser . ConfigParser ( ) cp . read ( job_inis ) job_ini = os . path . abspath ( job_inis [ 0 ] ) base_path = decode ( os . path . dirname ( job_ini ) ) params = dict ( base_path = base_path , inputs = { 'job_ini' : job_ini } ) if input_zip : params [ 'inputs' ] [ 'input_zip' ] = os . path . abspath ( input_zip ) for sect in cp . sections ( ) : _update ( params , cp . items ( sect ) , base_path ) _update ( params , kw . items ( ) , base_path ) if params [ 'inputs' ] . get ( 'reqv' ) : params [ 'pointsource_distance' ] = '0' return params | Parse one or more INI - style config files . |
44,610 | def get_oqparam ( job_ini , pkg = None , calculators = None , hc_id = None , validate = 1 , ** kw ) : from openquake . calculators import base OqParam . calculation_mode . validator . choices = tuple ( calculators or base . calculators ) if not isinstance ( job_ini , dict ) : basedir = os . path . dirname ( pkg . __file__ ) if pkg else '' job_ini = get_params ( [ os . path . join ( basedir , job_ini ) ] ) if hc_id : job_ini . update ( hazard_calculation_id = str ( hc_id ) ) job_ini . update ( kw ) oqparam = OqParam ( ** job_ini ) if validate : oqparam . validate ( ) return oqparam | Parse a dictionary of parameters from an INI - style config file . |
44,611 | def get_site_model ( oqparam ) : req_site_params = get_gsim_lt ( oqparam ) . req_site_params arrays = [ ] for fname in oqparam . inputs [ 'site_model' ] : if isinstance ( fname , str ) and fname . endswith ( '.csv' ) : sm = read_csv ( fname ) if 'site_id' in sm . dtype . names : raise InvalidFile ( '%s: you passed a sites.csv file instead of ' 'a site_model.csv file!' % fname ) z = numpy . zeros ( len ( sm ) , sorted ( sm . dtype . descr ) ) for name in z . dtype . names : z [ name ] = sm [ name ] arrays . append ( z ) continue nodes = nrml . read ( fname ) . siteModel params = [ valid . site_param ( node . attrib ) for node in nodes ] missing = req_site_params - set ( params [ 0 ] ) if 'vs30measured' in missing : missing -= { 'vs30measured' } for param in params : param [ 'vs30measured' ] = False if 'backarc' in missing : missing -= { 'backarc' } for param in params : param [ 'backarc' ] = False if missing : raise InvalidFile ( '%s: missing parameter %s' % ( oqparam . inputs [ 'site_model' ] , ', ' . join ( missing ) ) ) site_model_dt = numpy . dtype ( [ ( p , site . site_param_dt [ p ] ) for p in sorted ( params [ 0 ] ) ] ) sm = numpy . array ( [ tuple ( param [ name ] for name in site_model_dt . names ) for param in params ] , site_model_dt ) arrays . append ( sm ) return numpy . concatenate ( arrays ) | Convert the NRML file into an array of site parameters . |
44,612 | def get_site_collection ( oqparam ) : mesh = get_mesh ( oqparam ) req_site_params = get_gsim_lt ( oqparam ) . req_site_params if oqparam . inputs . get ( 'site_model' ) : sm = get_site_model ( oqparam ) try : depth = sm [ 'depth' ] except ValueError : depth = None sitecol = site . SiteCollection . from_points ( sm [ 'lon' ] , sm [ 'lat' ] , depth , sm , req_site_params ) if oqparam . region_grid_spacing : logging . info ( 'Reducing the grid sites to the site ' 'parameters within the grid spacing' ) sitecol , params , _ = geo . utils . assoc ( sm , sitecol , oqparam . region_grid_spacing * 1.414 , 'filter' ) sitecol . make_complete ( ) else : params = sm for name in req_site_params : if name in ( 'vs30measured' , 'backarc' ) and name not in params . dtype . names : sitecol . _set ( name , 0 ) else : sitecol . _set ( name , params [ name ] ) elif mesh is None and oqparam . ground_motion_fields : raise InvalidFile ( 'You are missing sites.csv or site_model.csv in %s' % oqparam . inputs [ 'job_ini' ] ) elif mesh is None : return else : sitecol = site . SiteCollection . from_points ( mesh . lons , mesh . lats , mesh . depths , oqparam , req_site_params ) ss = os . environ . get ( 'OQ_SAMPLE_SITES' ) if ss : sitecol . array = numpy . array ( random_filter ( sitecol . array , float ( ss ) ) ) sitecol . make_complete ( ) return sitecol | Returns a SiteCollection instance by looking at the points and the site model defined by the configuration parameters . |
44,613 | def get_rupture ( oqparam ) : rup_model = oqparam . inputs [ 'rupture_model' ] [ rup_node ] = nrml . read ( rup_model ) conv = sourceconverter . RuptureConverter ( oqparam . rupture_mesh_spacing , oqparam . complex_fault_mesh_spacing ) rup = conv . convert_node ( rup_node ) rup . tectonic_region_type = '*' rup . serial = oqparam . random_seed return rup | Read the rupture_model file and by filter the site collection |
44,614 | def get_composite_source_model ( oqparam , monitor = None , in_memory = True , srcfilter = SourceFilter ( None , { } ) ) : ucerf = oqparam . calculation_mode . startswith ( 'ucerf' ) source_model_lt = get_source_model_lt ( oqparam , validate = not ucerf ) trts = source_model_lt . tectonic_region_types trts_lower = { trt . lower ( ) for trt in trts } reqv = oqparam . inputs . get ( 'reqv' , { } ) for trt in reqv : if trt not in trts_lower : raise ValueError ( 'Unknown TRT=%s in %s [reqv]' % ( trt , oqparam . inputs [ 'job_ini' ] ) ) gsim_lt = get_gsim_lt ( oqparam , trts or [ '*' ] ) p = source_model_lt . num_paths * gsim_lt . get_num_paths ( ) if oqparam . number_of_logic_tree_samples : logging . info ( 'Considering {:,d} logic tree paths out of {:,d}' . format ( oqparam . number_of_logic_tree_samples , p ) ) else : if oqparam . is_event_based ( ) and p > oqparam . max_potential_paths : raise ValueError ( 'There are too many potential logic tree paths (%d) ' 'use sampling instead of full enumeration' % p ) logging . info ( 'Potential number of logic tree paths = {:,d}' . format ( p ) ) if source_model_lt . on_each_source : logging . info ( 'There is a logic tree on each source' ) if monitor is None : monitor = performance . Monitor ( ) smodels = [ ] for source_model in get_source_models ( oqparam , gsim_lt , source_model_lt , monitor , in_memory , srcfilter ) : for src_group in source_model . src_groups : src_group . sources = sorted ( src_group , key = getid ) for src in src_group : if isinstance ( src , Node ) : continue smodels . append ( source_model ) csm = source . CompositeSourceModel ( gsim_lt , source_model_lt , smodels , oqparam . optimize_same_id_sources ) for sm in csm . source_models : counter = collections . Counter ( ) for sg in sm . src_groups : for srcid in map ( getid , sg ) : counter [ srcid ] += 1 dupl = [ srcid for srcid in counter if counter [ srcid ] > 1 ] if dupl : raise nrml . DuplicatedID ( 'Found duplicated source IDs in %s: %s' % ( sm , dupl ) ) if not in_memory : return csm if oqparam . is_event_based ( ) : csm . init_serials ( oqparam . ses_seed ) if oqparam . disagg_by_src : csm = csm . grp_by_src ( ) csm . info . gsim_lt . check_imts ( oqparam . imtls ) parallel . Starmap . shutdown ( ) return csm | Parse the XML and build a complete composite source model in memory . |
44,615 | def get_mesh_hcurves ( oqparam ) : imtls = oqparam . imtls lon_lats = set ( ) data = AccumDict ( ) ncols = len ( imtls ) + 1 csvfile = oqparam . inputs [ 'hazard_curves' ] for line , row in enumerate ( csv . reader ( csvfile ) , 1 ) : try : if len ( row ) != ncols : raise ValueError ( 'Expected %d columns, found %d' % ncols , len ( row ) ) x , y = row [ 0 ] . split ( ) lon_lat = valid . longitude ( x ) , valid . latitude ( y ) if lon_lat in lon_lats : raise DuplicatedPoint ( lon_lat ) lon_lats . add ( lon_lat ) for i , imt_ in enumerate ( imtls , 1 ) : values = valid . decreasing_probabilities ( row [ i ] ) if len ( values ) != len ( imtls [ imt_ ] ) : raise ValueError ( 'Found %d values, expected %d' % ( len ( values ) , len ( imtls ( [ imt_ ] ) ) ) ) data += { imt_ : [ numpy . array ( values ) ] } except ( ValueError , DuplicatedPoint ) as err : raise err . __class__ ( '%s: file %s, line %d' % ( err , csvfile , line ) ) lons , lats = zip ( * sorted ( lon_lats ) ) mesh = geo . Mesh ( numpy . array ( lons ) , numpy . array ( lats ) ) return mesh , { imt : numpy . array ( lst ) for imt , lst in data . items ( ) } | Read CSV data in the format lon lat v1 - vN w1 - wN ... . |
44,616 | def reduce_source_model ( smlt_file , source_ids , remove = True ) : found = 0 to_remove = [ ] for paths in logictree . collect_info ( smlt_file ) . smpaths . values ( ) : for path in paths : logging . info ( 'Reading %s' , path ) root = nrml . read ( path ) model = Node ( 'sourceModel' , root [ 0 ] . attrib ) origmodel = root [ 0 ] if root [ 'xmlns' ] == 'http://openquake.org/xmlns/nrml/0.4' : for src_node in origmodel : if src_node [ 'id' ] in source_ids : model . nodes . append ( src_node ) else : for src_group in origmodel : sg = copy . copy ( src_group ) sg . nodes = [ ] weights = src_group . get ( 'srcs_weights' ) if weights : assert len ( weights ) == len ( src_group . nodes ) else : weights = [ 1 ] * len ( src_group . nodes ) src_group [ 'srcs_weights' ] = reduced_weigths = [ ] for src_node , weight in zip ( src_group , weights ) : if src_node [ 'id' ] in source_ids : found += 1 sg . nodes . append ( src_node ) reduced_weigths . append ( weight ) if sg . nodes : model . nodes . append ( sg ) shutil . copy ( path , path + '.bak' ) if model : with open ( path , 'wb' ) as f : nrml . write ( [ model ] , f , xmlns = root [ 'xmlns' ] ) elif remove : to_remove . append ( path ) if found : for path in to_remove : os . remove ( path ) | Extract sources from the composite source model |
44,617 | def get_checksum32 ( oqparam , hazard = False ) : checksum = 0 for fname in get_input_files ( oqparam , hazard ) : checksum = _checksum ( fname , checksum ) if hazard : hazard_params = [ ] for key , val in vars ( oqparam ) . items ( ) : if key in ( 'rupture_mesh_spacing' , 'complex_fault_mesh_spacing' , 'width_of_mfd_bin' , 'area_source_discretization' , 'random_seed' , 'ses_seed' , 'truncation_level' , 'maximum_distance' , 'investigation_time' , 'number_of_logic_tree_samples' , 'imtls' , 'ses_per_logic_tree_path' , 'minimum_magnitude' , 'prefilter_sources' , 'sites' , 'pointsource_distance' , 'filter_distance' ) : hazard_params . append ( '%s = %s' % ( key , val ) ) data = '\n' . join ( hazard_params ) . encode ( 'utf8' ) checksum = zlib . adler32 ( data , checksum ) & 0xffffffff return checksum | Build an unsigned 32 bit integer from the input files of a calculation . |
44,618 | def smart_save ( dbpath , archive , calc_id ) : tmpdir = tempfile . mkdtemp ( ) newdb = os . path . join ( tmpdir , os . path . basename ( dbpath ) ) shutil . copy ( dbpath , newdb ) try : with sqlite3 . connect ( newdb ) as conn : conn . execute ( 'DELETE FROM job WHERE status != "complete"' ) if calc_id : conn . execute ( 'DELETE FROM job WHERE id != %d' % calc_id ) except : safeprint ( 'Please check the copy of the db in %s' % newdb ) raise zipfiles ( [ newdb ] , archive , 'a' , safeprint ) shutil . rmtree ( tmpdir ) | Make a copy of the db remove the incomplete jobs and add the copy to the archive |
44,619 | def dump ( archive , calc_id = 0 , user = None ) : t0 = time . time ( ) assert archive . endswith ( '.zip' ) , archive getfnames = 'select ds_calc_dir || ".hdf5" from job where ?A' param = dict ( status = 'complete' ) if calc_id : param [ 'id' ] = calc_id if user : param [ 'user_name' ] = user fnames = [ f for f , in db ( getfnames , param ) if os . path . exists ( f ) ] zipfiles ( fnames , archive , 'w' , safeprint ) pending_jobs = db ( 'select id, status, description from job ' 'where status="executing"' ) if pending_jobs : safeprint ( 'WARNING: there were calculations executing during the dump,' ' they have been not copied' ) for job_id , status , descr in pending_jobs : safeprint ( '%d %s %s' % ( job_id , status , descr ) ) smart_save ( db . path , archive , calc_id ) dt = time . time ( ) - t0 safeprint ( 'Archived %d calculations into %s in %d seconds' % ( len ( fnames ) , archive , dt ) ) | Dump the openquake database and all the complete calculations into a zip file . In a multiuser installation must be run as administrator . |
44,620 | def load_version ( ) : filename = os . path . abspath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , "cpt" , "__init__.py" ) ) with open ( filename , "rt" ) as version_file : conan_init = version_file . read ( ) version = re . search ( "__version__ = '([0-9a-z.-]+)'" , conan_init ) . group ( 1 ) return version | Loads a file content |
44,621 | def builds ( self , confs ) : self . _named_builds = { } self . _builds = [ ] for values in confs : if len ( values ) == 2 : self . _builds . append ( BuildConf ( values [ 0 ] , values [ 1 ] , { } , { } , self . reference ) ) elif len ( values ) == 4 : self . _builds . append ( BuildConf ( values [ 0 ] , values [ 1 ] , values [ 2 ] , values [ 3 ] , self . reference ) ) elif len ( values ) != 5 : raise Exception ( "Invalid build configuration, has to be a tuple of " "(settings, options, env_vars, build_requires, reference)" ) else : self . _builds . append ( BuildConf ( * values ) ) | For retro compatibility directly assigning builds |
44,622 | def patch_default_base_profile ( conan_api , profile_abs_path ) : text = tools . load ( profile_abs_path ) if "include(default)" in text : if Version ( conan_version ) < Version ( "1.12.0" ) : cache = conan_api . _client_cache else : cache = conan_api . _cache default_profile_name = os . path . basename ( cache . default_profile_path ) if not os . path . exists ( cache . default_profile_path ) : conan_api . create_profile ( default_profile_name , detect = True ) if default_profile_name != "default" : text = text . replace ( "include(default)" , "include(%s)" % default_profile_name ) tools . save ( profile_abs_path , text ) | If we have a profile including default but the users default in config is that the default is other we have to change the include |
44,623 | def get_user_if_exists ( strategy , details , user = None , * args , ** kwargs ) : if user : return { 'is_new' : False } try : username = details . get ( 'username' ) return { 'is_new' : False , 'user' : User . objects . get ( username = username ) } except User . DoesNotExist : pass return { } | Return a User with the given username iff the User exists . |
44,624 | def update_email ( strategy , details , user = None , * args , ** kwargs ) : if user : email = details . get ( 'email' ) if email and user . email != email : user . email = email strategy . storage . user . changed ( user ) | Update the user s email address using data from provider . |
44,625 | def get_user_claims ( self , access_token , claims = None , token_type = 'Bearer' ) : data = self . get_json ( self . USER_INFO_URL , headers = { 'Authorization' : '{token_type} {token}' . format ( token_type = token_type , token = access_token ) } ) if claims : claims_names = set ( claims ) data = { k : v for ( k , v ) in six . iteritems ( data ) if k in claims_names } return data | Returns a dictionary with the values for each claim requested . |
44,626 | def _setup_ipc ( self ) : log . debug ( 'Setting up the server IPC puller to receive from the listener' ) self . ctx = zmq . Context ( ) self . sub = self . ctx . socket ( zmq . PULL ) self . sub . bind ( LST_IPC_URL ) try : self . sub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . sub . setsockopt ( zmq . RCVHWM , self . opts [ 'hwm' ] ) log . debug ( 'Creating the router ICP on the server' ) self . pub = self . ctx . socket ( zmq . ROUTER ) self . pub . bind ( DEV_IPC_URL ) try : self . pub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . pub . setsockopt ( zmq . SNDHWM , self . opts [ 'hwm' ] ) self . publisher_pub = self . ctx . socket ( zmq . PUB ) self . publisher_pub . connect ( PUB_PX_IPC_URL ) try : self . publisher_pub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . publisher_pub . setsockopt ( zmq . SNDHWM , self . opts [ 'hwm' ] ) | Setup the IPC pub and sub . Subscript to the listener IPC and publish to the device specific IPC . |
44,627 | def _cleanup_buffer ( self ) : if not self . _buffer : return while True : time . sleep ( 60 ) log . debug ( 'Cleaning up buffer' ) items = self . _buffer . items ( ) log . debug ( 'Collected items' ) log . debug ( list ( items ) ) | Periodically cleanup the buffer . |
44,628 | def _compile_prefixes ( self ) : self . compiled_prefixes = { } for dev_os , os_config in self . config . items ( ) : if not os_config : continue self . compiled_prefixes [ dev_os ] = [ ] for prefix in os_config . get ( 'prefixes' , [ ] ) : values = prefix . get ( 'values' , { } ) line = prefix . get ( 'line' , '' ) if prefix . get ( '__python_fun__' ) : self . compiled_prefixes [ dev_os ] . append ( { '__python_fun__' : prefix [ '__python_fun__' ] , '__python_mod__' : prefix [ '__python_mod__' ] } ) continue line = '{{pri}}{}{{message}}' . format ( line ) values [ 'pri' ] = r'\<(\d+)\>' values [ 'message' ] = '(.*)' position = { } for key in values . keys ( ) : position [ line . find ( '{' + key + '}' ) ] = key sorted_position = { } for i , elem in enumerate ( sorted ( position . items ( ) ) ) : sorted_position [ elem [ 1 ] ] = i + 1 escaped = re . escape ( line ) . replace ( r'\{' , '{' ) . replace ( r'\}' , '}' ) escaped = escaped . replace ( r'\ ' , r'\s+' ) self . compiled_prefixes [ dev_os ] . append ( { 'prefix' : re . compile ( escaped . format ( ** values ) ) , 'prefix_positions' : sorted_position , 'raw_prefix' : escaped . format ( ** values ) , 'values' : values } ) | Create a dict of all OS prefixes and their compiled regexs |
44,629 | def _identify_prefix ( self , msg , data ) : prefix_id = - 1 for prefix in data : msg_dict = { } prefix_id += 1 match = None if '__python_fun__' in prefix : log . debug ( 'Trying to match using the %s custom python profiler' , prefix [ '__python_mod__' ] ) try : match = prefix [ '__python_fun__' ] ( msg ) except Exception : log . error ( 'Exception while parsing %s with the %s python profiler' , msg , prefix [ '__python_mod__' ] , exc_info = True ) else : log . debug ( 'Matching using YAML-defined profiler:' ) log . debug ( prefix [ 'raw_prefix' ] ) match = prefix [ 'prefix' ] . search ( msg ) if not match : log . debug ( 'Match not found' ) continue if '__python_fun__' in prefix : log . debug ( '%s matched using the custom python profiler %s' , msg , prefix [ '__python_mod__' ] ) msg_dict = match else : positions = prefix . get ( 'prefix_positions' , { } ) values = prefix . get ( 'values' ) msg_dict = { } for key in values . keys ( ) : msg_dict [ key ] = match . group ( positions . get ( key ) ) msg_dict [ '__prefix_id__' ] = prefix_id msg_dict [ 'message' ] = msg_dict [ 'message' ] . strip ( ) if 'pri' in msg_dict : msg_dict [ 'facility' ] = int ( int ( msg_dict [ 'pri' ] ) / 8 ) msg_dict [ 'severity' ] = int ( int ( msg_dict [ 'pri' ] ) - ( msg_dict [ 'facility' ] * 8 ) ) return msg_dict | Check the message again each OS prefix and if matched return the message dict |
44,630 | def _identify_os ( self , msg ) : ret = [ ] for dev_os , data in self . compiled_prefixes . items ( ) : log . debug ( 'Matching under %s' , dev_os ) msg_dict = self . _identify_prefix ( msg , data ) if msg_dict : log . debug ( 'Adding %s to list of matched OS' , dev_os ) ret . append ( ( dev_os , msg_dict ) ) else : log . debug ( 'No match found for %s' , dev_os ) if not ret : log . debug ( 'Not matched any OS, returning original log' ) msg_dict = { 'message' : msg } ret . append ( ( None , msg_dict ) ) return ret | Using the prefix of the syslog message we are able to identify the operating system and then continue parsing . |
44,631 | def _setup_ipc ( self ) : self . ctx = zmq . Context ( ) log . debug ( 'Creating the dealer IPC for %s' , self . _name ) self . sub = self . ctx . socket ( zmq . DEALER ) if six . PY2 : self . sub . setsockopt ( zmq . IDENTITY , self . _name ) elif six . PY3 : self . sub . setsockopt ( zmq . IDENTITY , bytes ( self . _name , 'utf-8' ) ) try : self . sub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . sub . setsockopt ( zmq . RCVHWM , self . opts [ 'hwm' ] ) self . sub . connect ( DEV_IPC_URL ) self . pub = self . ctx . socket ( zmq . PUB ) self . pub . connect ( PUB_PX_IPC_URL ) try : self . pub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . pub . setsockopt ( zmq . SNDHWM , self . opts [ 'hwm' ] ) | Subscribe to the right topic in the device IPC and publish to the publisher proxy . |
44,632 | def _compile_messages ( self ) : self . compiled_messages = [ ] if not self . _config : return for message_dict in self . _config . get ( 'messages' , { } ) : error = message_dict [ 'error' ] tag = message_dict [ 'tag' ] model = message_dict [ 'model' ] match_on = message_dict . get ( 'match_on' , 'tag' ) if '__python_fun__' in message_dict : self . compiled_messages . append ( { 'error' : error , 'tag' : tag , 'match_on' : match_on , 'model' : model , '__python_fun__' : message_dict [ '__python_fun__' ] } ) continue values = message_dict [ 'values' ] line = message_dict [ 'line' ] mapping = message_dict [ 'mapping' ] position = { } replace = { } for key in values . keys ( ) : if '|' in key : new_key , replace [ new_key ] = key . replace ( ' ' , '' ) . split ( '|' ) values [ new_key ] = values . pop ( key ) key = new_key position [ line . find ( '{' + key + '}' ) ] = key sorted_position = { } for i , elem in enumerate ( sorted ( position . items ( ) ) ) : sorted_position [ elem [ 1 ] ] = i + 1 escaped = re . escape ( line ) . replace ( r'\{' , '{' ) . replace ( r'\}' , '}' ) escaped = escaped . replace ( r'\ ' , r'\s+' ) self . compiled_messages . append ( { 'error' : error , 'tag' : tag , 'match_on' : match_on , 'line' : re . compile ( escaped . format ( ** values ) ) , 'positions' : sorted_position , 'values' : values , 'replace' : replace , 'model' : model , 'mapping' : mapping } ) log . debug ( 'Compiled messages:' ) log . debug ( self . compiled_messages ) | Create a list of all OS messages and their compiled regexs |
44,633 | def _parse ( self , msg_dict ) : error_present = False for message in self . compiled_messages : match_on = message [ 'match_on' ] if match_on not in msg_dict : continue if message [ 'tag' ] != msg_dict [ match_on ] : continue if '__python_fun__' in message : return { 'model' : message [ 'model' ] , 'error' : message [ 'error' ] , '__python_fun__' : message [ '__python_fun__' ] } error_present = True match = message [ 'line' ] . search ( msg_dict [ 'message' ] ) if not match : continue positions = message . get ( 'positions' , { } ) values = message . get ( 'values' ) ret = { 'model' : message [ 'model' ] , 'mapping' : message [ 'mapping' ] , 'replace' : message [ 'replace' ] , 'error' : message [ 'error' ] } for key in values . keys ( ) : if key in message [ 'replace' ] : result = napalm_logs . utils . cast ( match . group ( positions . get ( key ) ) , message [ 'replace' ] [ key ] ) else : result = match . group ( positions . get ( key ) ) ret [ key ] = result return ret if error_present is True : log . info ( 'Configured regex did not match for os: %s tag %s' , self . _name , msg_dict . get ( 'tag' , '' ) ) else : log . info ( 'Syslog message not configured for os: %s tag %s' , self . _name , msg_dict . get ( 'tag' , '' ) ) | Parse a syslog message and check what OpenConfig object should be generated . |
44,634 | def _emit ( self , ** kwargs ) : oc_dict = { } for mapping , result_key in kwargs [ 'mapping' ] [ 'variables' ] . items ( ) : result = kwargs [ result_key ] oc_dict = napalm_logs . utils . setval ( mapping . format ( ** kwargs ) , result , oc_dict ) for mapping , result in kwargs [ 'mapping' ] [ 'static' ] . items ( ) : oc_dict = napalm_logs . utils . setval ( mapping . format ( ** kwargs ) , result , oc_dict ) return oc_dict | Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy . |
44,635 | def _publish ( self , obj ) : bin_obj = umsgpack . packb ( obj ) self . pub . send ( bin_obj ) | Publish the OC object . |
44,636 | def _handshake ( self , conn , addr ) : msg = conn . recv ( len ( MAGIC_REQ ) ) log . debug ( 'Received message %s from %s' , msg , addr ) if msg != MAGIC_REQ : log . warning ( '%s is not a valid REQ message from %s' , msg , addr ) return log . debug ( 'Sending the private key' ) conn . send ( self . __key ) log . debug ( 'Waiting for the client to confirm' ) msg = conn . recv ( len ( MAGIC_ACK ) ) if msg != MAGIC_ACK : return log . debug ( 'Sending the signature key' ) conn . send ( self . __sgn ) log . debug ( 'Waiting for the client to confirm' ) msg = conn . recv ( len ( MAGIC_ACK ) ) if msg != MAGIC_ACK : return log . info ( '%s is now authenticated' , addr ) self . keep_alive ( conn ) | Ensures that the client receives the AES key . |
44,637 | def keep_alive ( self , conn ) : while self . __up : msg = conn . recv ( len ( AUTH_KEEP_ALIVE ) ) if msg != AUTH_KEEP_ALIVE : log . error ( 'Received something other than %s' , AUTH_KEEP_ALIVE ) conn . close ( ) return try : conn . send ( AUTH_KEEP_ALIVE_ACK ) except ( IOError , socket . error ) as err : log . error ( 'Unable to send auth keep alive: %s' , err ) conn . close ( ) return | Maintains auth sessions |
44,638 | def verify_cert ( self ) : log . debug ( 'Verifying the %s certificate, keyfile: %s' , self . certificate , self . keyfile ) try : ssl . create_default_context ( ) . load_cert_chain ( self . certificate , keyfile = self . keyfile ) except ssl . SSLError : error_string = 'SSL certificate and key do not match' log . error ( error_string ) raise SSLMismatchException ( error_string ) except IOError : log . error ( 'Unable to open either certificate or key file' ) raise log . debug ( 'Certificate looks good.' ) | Checks that the provided cert and key are valid and usable |
44,639 | def _create_skt ( self ) : log . debug ( 'Creating the auth socket' ) if ':' in self . auth_address : self . socket = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM ) else : self . socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) try : self . socket . bind ( ( self . auth_address , self . auth_port ) ) except socket . error as msg : error_string = 'Unable to bind (auth) to port {} on {}: {}' . format ( self . auth_port , self . auth_address , msg ) log . error ( error_string , exc_info = True ) raise BindException ( error_string ) | Create the authentication socket . |
44,640 | def start ( self ) : log . debug ( 'Starting the auth process' ) self . verify_cert ( ) self . _create_skt ( ) log . debug ( 'The auth process can receive at most %d parallel connections' , AUTH_MAX_CONN ) self . socket . listen ( AUTH_MAX_CONN ) thread = threading . Thread ( target = self . _suicide_when_without_parent , args = ( os . getppid ( ) , ) ) thread . start ( ) signal . signal ( signal . SIGTERM , self . _exit_gracefully ) self . __up = True while self . __up : try : ( clientsocket , address ) = self . socket . accept ( ) wrapped_auth_skt = ssl . wrap_socket ( clientsocket , server_side = True , certfile = self . certificate , keyfile = self . keyfile ) except ssl . SSLError : log . exception ( 'SSL error' , exc_info = True ) continue except socket . error as error : if self . __up is False : return else : msg = 'Received auth socket error: {}' . format ( error ) log . error ( msg , exc_info = True ) raise NapalmLogsExit ( msg ) log . info ( '%s connected' , address ) log . debug ( 'Starting the handshake' ) client_thread = threading . Thread ( target = self . _handshake , args = ( wrapped_auth_skt , address ) ) client_thread . start ( ) | Listen to auth requests and send the AES key . Each client connection starts a new thread . |
44,641 | def stop ( self ) : log . info ( 'Stopping auth process' ) self . __up = False self . socket . close ( ) | Stop the auth proc . |
44,642 | def start ( self ) : log . debug ( 'Creating the consumer using the bootstrap servers: %s and the group ID: %s' , self . bootstrap_servers , self . group_id ) try : self . consumer = kafka . KafkaConsumer ( bootstrap_servers = self . bootstrap_servers , group_id = self . group_id ) except kafka . errors . NoBrokersAvailable as err : log . error ( err , exc_info = True ) raise ListenerException ( err ) log . debug ( 'Subscribing to the %s topic' , self . topic ) self . consumer . subscribe ( topics = [ self . topic ] ) | Startup the kafka consumer . |
44,643 | def stop ( self ) : log . info ( 'Stopping te kafka listener class' ) self . consumer . unsubscribe ( ) self . consumer . close ( ) | Shutdown kafka consumer . |
44,644 | def get_transport ( name ) : try : log . debug ( 'Using %s as transport' , name ) return TRANSPORT_LOOKUP [ name ] except KeyError : msg = 'Transport {} is not available. Are the dependencies installed?' . format ( name ) log . error ( msg , exc_info = True ) raise InvalidTransportException ( msg ) | Return the transport class . |
44,645 | def start ( self ) : zmq_uri = '{protocol}://{address}:{port}' . format ( protocol = self . protocol , address = self . address , port = self . port ) if self . port else '{protocol}://{address}' . format ( protocol = self . protocol , address = self . address ) log . debug ( 'ZMQ URI: %s' , zmq_uri ) self . ctx = zmq . Context ( ) if hasattr ( zmq , self . type ) : skt_type = getattr ( zmq , self . type ) else : skt_type = zmq . PULL self . sub = self . ctx . socket ( skt_type ) self . sub . connect ( zmq_uri ) if self . hwm is not None : try : self . sub . setsockopt ( zmq . HWM , self . hwm ) except AttributeError : self . sub . setsockopt ( zmq . RCVHWM , self . hwm ) if self . recvtimeout is not None : log . debug ( 'Setting RCVTIMEO to %d' , self . recvtimeout ) self . sub . setsockopt ( zmq . RCVTIMEO , self . recvtimeout ) if self . keepalive is not None : log . debug ( 'Setting TCP_KEEPALIVE to %d' , self . keepalive ) self . sub . setsockopt ( zmq . TCP_KEEPALIVE , self . keepalive ) if self . keepalive_idle is not None : log . debug ( 'Setting TCP_KEEPALIVE_IDLE to %d' , self . keepalive_idle ) self . sub . setsockopt ( zmq . TCP_KEEPALIVE_IDLE , self . keepalive_idle ) if self . keepalive_interval is not None : log . debug ( 'Setting TCP_KEEPALIVE_INTVL to %d' , self . keepalive_interval ) self . sub . setsockopt ( zmq . TCP_KEEPALIVE_INTVL , self . keepalive_interval ) | Startup the zmq consumer . |
44,646 | def receive ( self ) : try : msg = self . sub . recv ( ) except zmq . Again as error : log . error ( 'Unable to receive messages: %s' , error , exc_info = True ) raise ListenerException ( error ) log . debug ( '[%s] Received %s' , time . time ( ) , msg ) return msg , '' | Return the message received . |
44,647 | def stop ( self ) : log . info ( 'Stopping the zmq listener class' ) self . sub . close ( ) self . ctx . term ( ) | Shutdown zmq listener . |
44,648 | def start ( self ) : if ':' in self . address : self . skt = socket . socket ( socket . AF_INET6 , socket . SOCK_DGRAM ) else : self . skt = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) if self . reuse_port : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) if hasattr ( socket , 'SO_REUSEPORT' ) : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEPORT , 1 ) else : log . error ( 'SO_REUSEPORT not supported' ) try : self . skt . bind ( ( self . address , int ( self . port ) ) ) except socket . error as msg : error_string = 'Unable to bind to port {} on {}: {}' . format ( self . port , self . address , msg ) log . error ( error_string , exc_info = True ) raise BindException ( error_string ) | Create the UDP listener socket . |
44,649 | def _suicide_when_without_parent ( self , parent_pid ) : while True : time . sleep ( 5 ) try : os . kill ( parent_pid , 0 ) except OSError : self . stop ( ) log . warning ( 'The parent is not alive, exiting.' ) os . _exit ( 999 ) | Kill this process when the parent died . |
44,650 | def _setup_buffer ( self ) : if not self . _buffer_cfg or not isinstance ( self . _buffer_cfg , dict ) : return buffer_name = list ( self . _buffer_cfg . keys ( ) ) [ 0 ] buffer_class = napalm_logs . buffer . get_interface ( buffer_name ) log . debug ( 'Setting up buffer interface "%s"' , buffer_name ) if 'expire_time' not in self . _buffer_cfg [ buffer_name ] : self . _buffer_cfg [ buffer_name ] [ 'expire_time' ] = CONFIG . BUFFER_EXPIRE_TIME self . _buffer = buffer_class ( ** self . _buffer_cfg [ buffer_name ] ) | Setup the buffer subsystem . |
44,651 | def _setup_metrics ( self ) : path = os . environ . get ( "prometheus_multiproc_dir" ) if not os . path . exists ( self . metrics_dir ) : try : log . info ( "Creating metrics directory" ) os . makedirs ( self . metrics_dir ) except OSError : log . error ( "Failed to create metrics directory!" ) raise ConfigurationException ( "Failed to create metrics directory!" ) path = self . metrics_dir elif path != self . metrics_dir : path = self . metrics_dir os . environ [ 'prometheus_multiproc_dir' ] = path log . info ( "Cleaning metrics collection directory" ) log . debug ( "Metrics directory set to: {}" . format ( path ) ) files = os . listdir ( path ) for f in files : if f . endswith ( ".db" ) : os . remove ( os . path . join ( path , f ) ) log . debug ( "Starting metrics exposition" ) if self . metrics_enabled : registry = CollectorRegistry ( ) multiprocess . MultiProcessCollector ( registry ) start_http_server ( port = self . metrics_port , addr = self . metrics_address , registry = registry ) | Start metric exposition |
44,652 | def _setup_log ( self ) : logging_level = CONFIG . LOGGING_LEVEL . get ( self . log_level . lower ( ) ) logging . basicConfig ( format = self . log_format , level = logging_level ) | Setup the log object . |
44,653 | def _whitelist_blacklist ( self , os_name ) : return napalm_logs . ext . check_whitelist_blacklist ( os_name , whitelist = self . device_whitelist , blacklist = self . device_blacklist ) | Determines if the OS should be ignored depending on the whitelist - blacklist logic configured by the user . |
44,654 | def _extract_yaml_docstring ( stream ) : comment_lines = [ ] lines = stream . read ( ) . splitlines ( ) for line in lines : line_strip = line . strip ( ) if not line_strip : continue if line_strip . startswith ( '#' ) : comment_lines . append ( line_strip . replace ( '#' , '' , 1 ) . strip ( ) ) else : break return ' ' . join ( comment_lines ) | Extract the comments at the top of the YAML file from the stream handler . Return the extracted comment as string . |
44,655 | def _verify_config_dict ( self , valid , config , dev_os , key_path = None ) : if not key_path : key_path = [ ] for key , value in valid . items ( ) : self . _verify_config_key ( key , value , valid , config , dev_os , key_path ) | Verify if the config dict is valid . |
44,656 | def _verify_config ( self ) : if not self . config_dict : self . _raise_config_exception ( 'No config found' ) for dev_os , dev_config in self . config_dict . items ( ) : if not dev_config : log . warning ( 'No config found for %s' , dev_os ) continue self . _verify_config_dict ( CONFIG . VALID_CONFIG , dev_config , dev_os ) log . debug ( 'Read the config without error' ) | Verify that the config is correct |
44,657 | def _build_config ( self ) : if not self . config_dict : if not self . config_path : self . config_path = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , 'config' ) log . info ( 'Reading the configuration from %s' , self . config_path ) self . config_dict = self . _load_config ( self . config_path ) if not self . extension_config_dict and self . extension_config_path and os . path . normpath ( self . extension_config_path ) != os . path . normpath ( self . config_path ) : log . info ( 'Reading extension configuration from %s' , self . extension_config_path ) self . extension_config_dict = self . _load_config ( self . extension_config_path ) if self . extension_config_dict : napalm_logs . utils . dictupdate ( self . config_dict , self . extension_config_dict ) | Build the config of the napalm syslog parser . |
44,658 | def _start_auth_proc ( self ) : log . debug ( 'Computing the signing key hex' ) verify_key = self . __signing_key . verify_key sgn_verify_hex = verify_key . encode ( encoder = nacl . encoding . HexEncoder ) log . debug ( 'Starting the authenticator subprocess' ) auth = NapalmLogsAuthProc ( self . certificate , self . keyfile , self . __priv_key , sgn_verify_hex , self . auth_address , self . auth_port ) proc = Process ( target = auth . start ) proc . start ( ) proc . description = 'Auth process' log . debug ( 'Started auth process as %s with PID %s' , proc . _name , proc . pid ) return proc | Start the authenticator process . |
44,659 | def _start_lst_proc ( self , listener_type , listener_opts ) : log . debug ( 'Starting the listener process for %s' , listener_type ) listener = NapalmLogsListenerProc ( self . opts , self . address , self . port , listener_type , listener_opts = listener_opts ) proc = Process ( target = listener . start ) proc . start ( ) proc . description = 'Listener process' log . debug ( 'Started listener process as %s with PID %s' , proc . _name , proc . pid ) return proc | Start the listener process . |
44,660 | def _start_srv_proc ( self , started_os_proc ) : log . debug ( 'Starting the server process' ) server = NapalmLogsServerProc ( self . opts , self . config_dict , started_os_proc , buffer = self . _buffer ) proc = Process ( target = server . start ) proc . start ( ) proc . description = 'Server process' log . debug ( 'Started server process as %s with PID %s' , proc . _name , proc . pid ) return proc | Start the server process . |
44,661 | def _start_pub_proc ( self , publisher_type , publisher_opts , pub_id ) : log . debug ( 'Starting the publisher process for %s' , publisher_type ) publisher = NapalmLogsPublisherProc ( self . opts , self . publish_address , self . publish_port , publisher_type , self . serializer , self . __priv_key , self . __signing_key , publisher_opts , disable_security = self . disable_security , pub_id = pub_id ) proc = Process ( target = publisher . start ) proc . start ( ) proc . description = 'Publisher process' log . debug ( 'Started publisher process as %s with PID %s' , proc . _name , proc . pid ) return proc | Start the publisher process . |
44,662 | def _start_dev_proc ( self , device_os , device_config ) : log . info ( 'Starting the child process for %s' , device_os ) dos = NapalmLogsDeviceProc ( device_os , self . opts , device_config ) os_proc = Process ( target = dos . start ) os_proc . start ( ) os_proc . description = '%s device process' % device_os log . debug ( 'Started process %s for %s, having PID %s' , os_proc . _name , device_os , os_proc . pid ) return os_proc | Start the device worker process . |
44,663 | def _check_children ( self ) : while self . up : time . sleep ( 1 ) for process in self . _processes : if process . is_alive ( ) is True : continue log . debug ( '%s is dead. Stopping the napalm-logs engine.' , process . description ) self . stop_engine ( ) | Check all of the child processes are still running |
44,664 | def _setup_ipc ( self ) : log . debug ( 'Setting up the internal IPC proxy' ) self . ctx = zmq . Context ( ) self . sub = self . ctx . socket ( zmq . SUB ) self . sub . bind ( PUB_PX_IPC_URL ) self . sub . setsockopt ( zmq . SUBSCRIBE , b'' ) log . debug ( 'Setting HWM for the proxy frontend: %d' , self . hwm ) try : self . sub . setsockopt ( zmq . HWM , self . hwm ) except AttributeError : self . sub . setsockopt ( zmq . SNDHWM , self . hwm ) self . pub = self . ctx . socket ( zmq . PUB ) self . pub . bind ( PUB_IPC_URL ) log . debug ( 'Setting HWM for the proxy backend: %d' , self . hwm ) try : self . pub . setsockopt ( zmq . HWM , self . hwm ) except AttributeError : self . pub . setsockopt ( zmq . SNDHWM , self . hwm ) | Setup the IPC PUB and SUB sockets for the proxy . |
44,665 | def _setup_ipc ( self ) : self . ctx = zmq . Context ( ) log . debug ( 'Setting up the %s publisher subscriber #%d' , self . _transport_type , self . pub_id ) self . sub = self . ctx . socket ( zmq . SUB ) self . sub . connect ( PUB_IPC_URL ) self . sub . setsockopt ( zmq . SUBSCRIBE , b'' ) try : self . sub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . sub . setsockopt ( zmq . RCVHWM , self . opts [ 'hwm' ] ) | Subscribe to the pub IPC and publish the messages on the right transport . |
44,666 | def _prepare ( self , serialized_obj ) : nonce = nacl . utils . random ( nacl . secret . SecretBox . NONCE_SIZE ) encrypted = self . __safe . encrypt ( serialized_obj , nonce ) signed = self . __signing_key . sign ( encrypted ) return signed | Prepare the object to be sent over the untrusted channel . |
44,667 | def get_listener ( name ) : try : log . debug ( 'Using %s as listener' , name ) return LISTENER_LOOKUP [ name ] except KeyError : msg = 'Listener {} is not available. Are the dependencies installed?' . format ( name ) log . error ( msg , exc_info = True ) raise InvalidListenerException ( msg ) | Return the listener class . |
44,668 | def _start_keep_alive ( self ) : keep_alive_thread = threading . Thread ( target = self . keep_alive ) keep_alive_thread . daemon = True keep_alive_thread . start ( ) | Start the keep alive thread as a daemon |
44,669 | def keep_alive ( self ) : self . ssl_skt . settimeout ( defaults . AUTH_KEEP_ALIVE_INTERVAL ) while self . __up : try : log . debug ( 'Sending keep-alive message to the server' ) self . ssl_skt . send ( defaults . AUTH_KEEP_ALIVE ) except socket . error : log . error ( 'Unable to send keep-alive message to the server.' ) log . error ( 'Re-init the SSL socket.' ) self . reconnect ( ) log . debug ( 'Trying to re-send the keep-alive message to the server.' ) self . ssl_skt . send ( defaults . AUTH_KEEP_ALIVE ) msg = self . ssl_skt . recv ( len ( defaults . AUTH_KEEP_ALIVE_ACK ) ) log . debug ( 'Received %s from the keep-alive server' , msg ) if msg != defaults . AUTH_KEEP_ALIVE_ACK : log . error ( 'Received %s instead of %s form the auth keep-alive server' , msg , defaults . AUTH_KEEP_ALIVE_ACK ) log . error ( 'Re-init the SSL socket.' ) self . reconnect ( ) time . sleep ( defaults . AUTH_KEEP_ALIVE_INTERVAL ) | Send a keep alive request periodically to make sure that the server is still alive . If not then try to reconnect . |
44,670 | def reconnect ( self ) : log . debug ( 'Closing the SSH socket.' ) try : self . ssl_skt . close ( ) except socket . error : log . error ( 'The socket seems to be closed already.' ) log . debug ( 'Re-opening the SSL socket.' ) self . authenticate ( ) | Try to reconnect and re - authenticate with the server . |
44,671 | def authenticate ( self ) : log . debug ( 'Authenticate to %s:%d, using the certificate %s' , self . address , self . port , self . certificate ) if ':' in self . address : skt_ver = socket . AF_INET6 else : skt_ver = socket . AF_INET skt = socket . socket ( skt_ver , socket . SOCK_STREAM ) self . ssl_skt = ssl . wrap_socket ( skt , ca_certs = self . certificate , cert_reqs = ssl . CERT_REQUIRED ) try : self . ssl_skt . connect ( ( self . address , self . port ) ) self . auth_try_id = 0 except socket . error as err : log . error ( 'Unable to open the SSL socket.' ) self . auth_try_id += 1 if not self . max_try or self . auth_try_id < self . max_try : log . error ( 'Trying to authenticate again in %d seconds' , self . timeout ) time . sleep ( self . timeout ) self . authenticate ( ) log . critical ( 'Giving up, unable to authenticate to %s:%d using the certificate %s' , self . address , self . port , self . certificate ) raise ClientConnectException ( err ) self . ssl_skt . write ( defaults . MAGIC_REQ ) private_key = self . ssl_skt . recv ( defaults . BUFFER_SIZE ) self . ssl_skt . write ( defaults . MAGIC_ACK ) verify_key_hex = self . ssl_skt . recv ( defaults . BUFFER_SIZE ) self . ssl_skt . write ( defaults . MAGIC_ACK ) self . priv_key = nacl . secret . SecretBox ( private_key ) self . verify_key = nacl . signing . VerifyKey ( verify_key_hex , encoder = nacl . encoding . HexEncoder ) | Authenticate the client and return the private and signature keys . |
44,672 | def decrypt ( self , binary ) : try : encrypted = self . verify_key . verify ( binary ) except BadSignatureError : log . error ( 'Signature was forged or corrupt' , exc_info = True ) raise BadSignatureException ( 'Signature was forged or corrupt' ) try : packed = self . priv_key . decrypt ( encrypted ) except CryptoError : log . error ( 'Unable to decrypt' , exc_info = True ) raise CryptoException ( 'Unable to decrypt' ) return umsgpack . unpackb ( packed ) | Decrypt and unpack the original OpenConfig object serialized using MessagePack . Raise BadSignatureException when the signature was forged or corrupted . |
44,673 | def _client_connection ( self , conn , addr ) : log . debug ( 'Established connection with %s:%d' , addr [ 0 ] , addr [ 1 ] ) conn . settimeout ( self . socket_timeout ) try : while self . __up : msg = conn . recv ( self . buffer_size ) if not msg : continue log . debug ( '[%s] Received %s from %s. Adding in the queue' , time . time ( ) , msg , addr ) self . buffer . put ( ( msg , '{}:{}' . format ( addr [ 0 ] , addr [ 1 ] ) ) ) except socket . timeout : if not self . __up : return log . debug ( 'Connection %s:%d timed out' , addr [ 1 ] , addr [ 0 ] ) raise ListenerException ( 'Connection %s:%d timed out' % addr ) finally : log . debug ( 'Closing connection with %s' , addr ) conn . close ( ) | Handle the connecition with one client . |
44,674 | def _serve_clients ( self ) : self . __up = True while self . __up : log . debug ( 'Waiting for a client to connect' ) try : conn , addr = self . skt . accept ( ) log . debug ( 'Received connection from %s:%d' , addr [ 0 ] , addr [ 1 ] ) except socket . error as error : if not self . __up : return msg = 'Received listener socket error: {}' . format ( error ) log . error ( msg , exc_info = True ) raise ListenerException ( msg ) client_thread = threading . Thread ( target = self . _client_connection , args = ( conn , addr , ) ) client_thread . start ( ) | Accept cients and serve one separate thread per client . |
44,675 | def start ( self ) : log . debug ( 'Creating the TCP server' ) if ':' in self . address : self . skt = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM ) else : self . skt = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) if self . reuse_port : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) if hasattr ( socket , 'SO_REUSEPORT' ) : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEPORT , 1 ) else : log . error ( 'SO_REUSEPORT not supported' ) try : self . skt . bind ( ( self . address , int ( self . port ) ) ) except socket . error as msg : error_string = 'Unable to bind to port {} on {}: {}' . format ( self . port , self . address , msg ) log . error ( error_string , exc_info = True ) raise BindException ( error_string ) log . debug ( 'Accepting max %d parallel connections' , self . max_clients ) self . skt . listen ( self . max_clients ) self . thread_serve = threading . Thread ( target = self . _serve_clients ) self . thread_serve . start ( ) | Start listening for messages . |
44,676 | def receive ( self ) : while self . buffer . empty ( ) and self . __up : sleep_ms = random . randint ( 0 , 1000 ) time . sleep ( sleep_ms / 1000.0 ) if not self . buffer . empty ( ) : return self . buffer . get ( block = False ) return '' , '' | Return one message dequeued from the listen buffer . |
44,677 | def stop ( self ) : log . info ( 'Stopping the TCP listener' ) self . __up = False try : self . skt . shutdown ( socket . SHUT_RDWR ) except socket . error : log . error ( 'The following error may not be critical:' , exc_info = True ) self . skt . close ( ) | Closing the socket . |
44,678 | def _setup_ipc ( self ) : log . debug ( 'Setting up the listener IPC pusher' ) self . ctx = zmq . Context ( ) self . pub = self . ctx . socket ( zmq . PUSH ) self . pub . connect ( LST_IPC_URL ) log . debug ( 'Setting HWM for the listener: %d' , self . opts [ 'hwm' ] ) try : self . pub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . pub . setsockopt ( zmq . SNDHWM , self . opts [ 'hwm' ] ) | Setup the listener ICP pusher . |
44,679 | def make_update_loop ( thread , update_func ) : while not thread . should_stop ( ) : if thread . should_pause ( ) : thread . wait_to_resume ( ) start = time . time ( ) if hasattr ( thread , '_updated' ) : thread . _updated . clear ( ) update_func ( ) if hasattr ( thread , '_updated' ) : thread . _updated . set ( ) end = time . time ( ) dt = thread . period - ( end - start ) if dt > 0 : time . sleep ( dt ) | Makes a run loop which calls an update function at a predefined frequency . |
44,680 | def start ( self ) : if self . running : self . stop ( ) self . _thread = threading . Thread ( target = self . _wrapped_target ) self . _thread . daemon = True self . _thread . start ( ) | Start the run method as a new thread . |
44,681 | def wait_to_start ( self , allow_failure = False ) : self . _started . wait ( ) if self . _crashed and not allow_failure : self . _thread . join ( ) raise RuntimeError ( 'Setup failed, see {} Traceback' 'for details.' . format ( self . _thread . name ) ) | Wait for the thread to actually starts . |
44,682 | def from_vrep ( config , vrep_host = '127.0.0.1' , vrep_port = 19997 , scene = None , tracked_objects = [ ] , tracked_collisions = [ ] , id = None , shared_vrep_io = None ) : if shared_vrep_io is None : vrep_io = VrepIO ( vrep_host , vrep_port ) else : vrep_io = shared_vrep_io vreptime = vrep_time ( vrep_io ) pypot_time . time = vreptime . get_time pypot_time . sleep = vreptime . sleep if isinstance ( config , basestring ) : with open ( config ) as f : config = json . load ( f , object_pairs_hook = OrderedDict ) motors = [ motor_from_confignode ( config , name ) for name in config [ 'motors' ] . keys ( ) ] vc = VrepController ( vrep_io , scene , motors , id = id ) vc . _init_vrep_streaming ( ) sensor_controllers = [ ] if tracked_objects : sensors = [ ObjectTracker ( name ) for name in tracked_objects ] vot = VrepObjectTracker ( vrep_io , sensors ) sensor_controllers . append ( vot ) if tracked_collisions : sensors = [ VrepCollisionDetector ( name ) for name in tracked_collisions ] vct = VrepCollisionTracker ( vrep_io , sensors ) sensor_controllers . append ( vct ) robot = Robot ( motor_controllers = [ vc ] , sensor_controllers = sensor_controllers ) for m in robot . motors : m . goto_behavior = 'minjerk' init_pos = { m : m . goal_position for m in robot . motors } make_alias ( config , robot ) def start_simu ( ) : vrep_io . start_simulation ( ) for m , p in init_pos . iteritems ( ) : m . goal_position = p vc . start ( ) if tracked_objects : vot . start ( ) if tracked_collisions : vct . start ( ) while vrep_io . get_simulation_current_time ( ) < 1. : sys_time . sleep ( 0.1 ) def stop_simu ( ) : if tracked_objects : vot . stop ( ) if tracked_collisions : vct . stop ( ) vc . stop ( ) vrep_io . stop_simulation ( ) def reset_simu ( ) : stop_simu ( ) sys_time . sleep ( 0.5 ) start_simu ( ) robot . start_simulation = start_simu robot . stop_simulation = stop_simu robot . reset_simulation = reset_simu def current_simulation_time ( robot ) : return robot . _controllers [ 0 ] . io . get_simulation_current_time ( ) Robot . current_simulation_time = property ( lambda robot : current_simulation_time ( robot ) ) def get_object_position ( robot , object , relative_to_object = None ) : return vrep_io . get_object_position ( object , relative_to_object ) Robot . get_object_position = partial ( get_object_position , robot ) def get_object_orientation ( robot , object , relative_to_object = None ) : return vrep_io . get_object_orientation ( object , relative_to_object ) Robot . get_object_orientation = partial ( get_object_orientation , robot ) return robot | Create a robot from a V - REP instance . |
44,683 | def set_wheel_mode ( self , ids ) : self . set_control_mode ( dict ( zip ( ids , itertools . repeat ( 'wheel' ) ) ) ) | Sets the specified motors to wheel mode . |
44,684 | def set_joint_mode ( self , ids ) : self . set_control_mode ( dict ( zip ( ids , itertools . repeat ( 'joint' ) ) ) ) | Sets the specified motors to joint mode . |
44,685 | def set_angle_limit ( self , limit_for_id , ** kwargs ) : convert = kwargs [ 'convert' ] if 'convert' in kwargs else self . _convert if 'wheel' in self . get_control_mode ( limit_for_id . keys ( ) ) : raise ValueError ( 'can not change the angle limit of a motor in wheel mode' ) if ( 0 , 0 ) in limit_for_id . values ( ) : raise ValueError ( 'can not set limit to (0, 0)' ) self . _set_angle_limit ( limit_for_id , convert = convert ) | Sets the angle limit to the specified motors . |
44,686 | def close ( self ) : self . stop_sync ( ) [ c . io . close ( ) for c in self . _controllers if c . io is not None ] | Cleans the robot by stopping synchronization and all controllers . |
44,687 | def goto_position ( self , position_for_motors , duration , control = None , wait = False ) : for i , ( motor_name , position ) in enumerate ( position_for_motors . iteritems ( ) ) : w = False if i < len ( position_for_motors ) - 1 else wait m = getattr ( self , motor_name ) m . goto_position ( position , duration , control , wait = w ) | Moves a subset of the motors to a position within a specific duration . |
44,688 | def power_up ( self ) : for m in self . motors : m . compliant = False m . moving_speed = 0 m . torque_limit = 100.0 | Changes all settings to guarantee the motors will be used at their maximum power . |
44,689 | def to_config ( self ) : from . . dynamixel . controller import DxlController dxl_controllers = [ c for c in self . _controllers if isinstance ( c , DxlController ) ] config = { } config [ 'controllers' ] = { } for i , c in enumerate ( dxl_controllers ) : name = 'dxl_controller_{}' . format ( i ) config [ 'controllers' ] [ name ] = { 'port' : c . io . port , 'sync_read' : c . io . _sync_read , 'attached_motors' : [ m . name for m in c . motors ] , } config [ 'motors' ] = { } for m in self . motors : config [ 'motors' ] [ m . name ] = { 'id' : m . id , 'type' : m . model , 'offset' : m . offset , 'orientation' : 'direct' if m . direct else 'indirect' , 'angle_limit' : m . angle_limit , } if m . angle_limit == ( 0 , 0 ) : config [ 'motors' ] [ 'wheel_mode' ] = True config [ 'motorgroups' ] = { } return config | Generates the config for the current robot . |
44,690 | def update ( self ) : h , _ , l , _ = self . io . call_remote_api ( 'simxGetObjectGroupData' , remote_api . sim_object_joint_type , 16 , streaming = True ) limits4handle = { hh : ( ll , lr ) for hh , ll , lr in zip ( h , l [ : : 2 ] , l [ 1 : : 2 ] ) } for m in self . motors : tmax = torque_max [ m . model ] p = round ( rad2deg ( self . io . get_motor_position ( motor_name = self . _motor_name ( m ) ) ) , 1 ) m . __dict__ [ 'present_position' ] = p l = 100. * self . io . get_motor_force ( motor_name = self . _motor_name ( m ) ) / tmax m . __dict__ [ 'present_load' ] = l m . __dict__ [ '_load_fifo' ] . append ( abs ( l ) ) m . __dict__ [ 'present_temperature' ] = 25 + round ( 2.5 * sum ( m . __dict__ [ '_load_fifo' ] ) / len ( m . __dict__ [ '_load_fifo' ] ) , 1 ) ll , lr = limits4handle [ self . io . _object_handles [ self . _motor_name ( m ) ] ] m . __dict__ [ 'lower_limit' ] = rad2deg ( ll ) m . __dict__ [ 'upper_limit' ] = rad2deg ( ll ) + rad2deg ( lr ) p = deg2rad ( round ( m . __dict__ [ 'goal_position' ] , 1 ) ) self . io . set_motor_position ( motor_name = self . _motor_name ( m ) , position = p ) t = m . __dict__ [ 'torque_limit' ] * tmax / 100. if m . __dict__ [ 'compliant' ] : t = 0. self . io . set_motor_force ( motor_name = self . _motor_name ( m ) , force = t ) | Synchronization update loop . |
44,691 | def update ( self ) : for s in self . sensors : s . position = self . io . get_object_position ( object_name = s . name ) s . orientation = self . io . get_object_orientation ( object_name = s . name ) | Updates the position and orientation of the tracked objects . |
44,692 | def update ( self ) : for s in self . sensors : s . colliding = self . io . get_collision_state ( collision_name = s . name ) | Update the state of the collision detectors . |
44,693 | def get_transformation_matrix ( self , theta ) : ct = numpy . cos ( theta + self . theta ) st = numpy . sin ( theta + self . theta ) ca = numpy . cos ( self . alpha ) sa = numpy . sin ( self . alpha ) return numpy . matrix ( ( ( ct , - st * ca , st * sa , self . a * ct ) , ( st , ct * ca , - ct * sa , self . a * st ) , ( 0 , sa , ca , self . d ) , ( 0 , 0 , 0 , 1 ) ) ) | Computes the homogeneous transformation matrix for this link . |
44,694 | def forward_kinematics ( self , q ) : q = numpy . array ( q ) . flatten ( ) if len ( q ) != len ( self . links ) : raise ValueError ( 'q must contain as element as the number of links' ) tr = self . base . copy ( ) l = [ ] for link , theta in zip ( self . links , q ) : tr = tr * link . get_transformation_matrix ( theta ) l . append ( tr ) tr = tr * self . tool l . append ( tr ) return tr , numpy . asarray ( l ) | Computes the homogeneous transformation matrix of the end effector of the chain . |
44,695 | def inverse_kinematics ( self , end_effector_transformation , q = None , max_iter = 1000 , tolerance = 0.05 , mask = numpy . ones ( 6 ) , use_pinv = False ) : if q is None : q = numpy . zeros ( ( len ( self . links ) , 1 ) ) q = numpy . matrix ( q . reshape ( - 1 , 1 ) ) best_e = numpy . ones ( 6 ) * numpy . inf best_q = None alpha = 1.0 for _ in range ( max_iter ) : e = numpy . multiply ( transform_difference ( self . forward_kinematics ( q ) [ 0 ] , end_effector_transformation ) , mask ) d = numpy . linalg . norm ( e ) if d < numpy . linalg . norm ( best_e ) : best_e = e . copy ( ) best_q = q . copy ( ) alpha *= 2.0 ** ( 1.0 / 8.0 ) else : q = best_q . copy ( ) e = best_e . copy ( ) alpha *= 0.5 if use_pinv : dq = numpy . linalg . pinv ( self . _jacob0 ( q ) ) * e . reshape ( ( - 1 , 1 ) ) else : dq = self . _jacob0 ( q ) . T * e . reshape ( ( - 1 , 1 ) ) q += alpha * dq if d < tolerance : return q else : raise ValueError ( 'could not converge d={}' . format ( numpy . linalg . norm ( best_e ) ) ) | Computes the joint angles corresponding to the end effector transformation . |
44,696 | def _get_available_ports ( ) : if platform . system ( ) == 'Darwin' : return glob . glob ( '/dev/tty.usb*' ) elif platform . system ( ) == 'Linux' : return glob . glob ( '/dev/ttyACM*' ) + glob . glob ( '/dev/ttyUSB*' ) + glob . glob ( '/dev/ttyAMA*' ) elif sys . platform . lower ( ) == 'cygwin' : return glob . glob ( '/dev/com*' ) elif platform . system ( ) == 'Windows' : import _winreg import itertools ports = [ ] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg . OpenKey ( _winreg . HKEY_LOCAL_MACHINE , path ) for i in itertools . count ( ) : try : ports . append ( str ( _winreg . EnumValue ( key , i ) [ 1 ] ) ) except WindowsError : return ports else : raise EnvironmentError ( '{} is an unsupported platform, cannot find serial ports !' . format ( platform . system ( ) ) ) return [ ] | Tries to find the available serial ports on your system . |
44,697 | def find_port ( ids , strict = True ) : ids_founds = [ ] for port in get_available_ports ( ) : for DxlIOCls in ( DxlIO , Dxl320IO ) : try : with DxlIOCls ( port ) as dxl : _ids_founds = dxl . scan ( ids ) ids_founds += _ids_founds if strict and len ( _ids_founds ) == len ( ids ) : return port if not strict and len ( _ids_founds ) >= len ( ids ) / 2 : logger . warning ( 'Missing ids: {}' . format ( ids , list ( set ( ids ) - set ( _ids_founds ) ) ) ) return port if len ( ids_founds ) > 0 : logger . warning ( 'Port:{} ids found:{}' . format ( port , _ids_founds ) ) except DxlError : logger . warning ( 'DxlError on port {}' . format ( port ) ) continue raise IndexError ( 'No suitable port found for ids {}. These ids are missing {} !' . format ( ids , list ( set ( ids ) - set ( ids_founds ) ) ) ) | Find the port with the specified attached motor ids . |
44,698 | def _filter ( self , data ) : filtered_data = [ ] for queue , data in zip ( self . _raw_data_queues , data ) : queue . append ( data ) filtered_data . append ( numpy . median ( queue ) ) return filtered_data | Apply a filter to reduce noisy data . |
44,699 | def setup ( self ) : [ c . start ( ) for c in self . controllers ] [ c . wait_to_start ( ) for c in self . controllers ] | Starts all the synchronization loops . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.