idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,900
def kernel_initrds ( self ) : kernels = [ ] initrds = [ ] name_values = [ ( k , v ) for k , v in self . data . get ( 'configs' , [ ] ) ] for value in self . data . get ( 'title' , [ ] ) + self . data . get ( 'menuentry' , [ ] ) : name_values . extend ( value ) for name , value in name_values : if name . startswith ( 'm...
Get the kernel and initrd files referenced in GRUB configuration files
31,901
def serializer ( _type ) : def inner ( func ) : name = dr . get_name ( _type ) if name in SERIALIZERS : msg = "%s already has a serializer registered: %s" raise Exception ( msg % ( name , dr . get_name ( SERIALIZERS [ name ] ) ) ) SERIALIZERS [ name ] = func return func return inner
Decorator for serializers .
31,902
def deserializer ( _type ) : def inner ( func ) : name = dr . get_name ( _type ) if name in DESERIALIZERS : msg = "%s already has a deserializer registered: %s" raise Exception ( msg % ( dr . get_name ( name ) , dr . get_name ( DESERIALIZERS [ name ] ) ) ) DESERIALIZERS [ name ] = ( _type , func ) return func return in...
Decorator for deserializers .
31,903
def hydrate ( self , broker = None ) : broker = broker or dr . Broker ( ) for path in glob ( os . path . join ( self . meta_data , "*" ) ) : try : with open ( path ) as f : doc = ser . load ( f ) res = self . _hydrate_one ( doc ) comp , results , exec_time , ser_time = res if results : broker [ comp ] = results broker ...
Loads a Broker from a previously saved one . A Broker is created if one isn t provided .
31,904
def dehydrate ( self , comp , broker ) : if not self . meta_data : raise Exception ( "Hydration meta_path not set. Can't dehydrate." ) if not self . created : fs . ensure_path ( self . meta_data , mode = 0o770 ) if self . data : fs . ensure_path ( self . data , mode = 0o770 ) self . created = True c = comp doc = None t...
Saves a component in the given broker to the file system .
31,905
def make_persister ( self , to_persist ) : if not self . meta_data : raise Exception ( "Root not set. Can't create persister." ) def persister ( c , broker ) : if c in to_persist : self . dehydrate ( c , broker ) return persister
Returns a function that hydrates components as they are evaluated . The function should be registered as an observer on a Broker just before execution .
31,906
def map_keys ( pvs , keys ) : rs = [ ] for pv in pvs : r = dict ( ( v , None ) for k , v in keys . items ( ) ) for k , v in pv . items ( ) : if k in keys : r [ keys [ k ] ] = v r [ k ] = v rs . append ( r ) return rs
Add human readable key names to dictionary while leaving any existing key names .
31,907
def from_dict ( dct ) : def inner ( d ) : results = [ ] for name , v in d . items ( ) : if isinstance ( v , dict ) : results . append ( Section ( name = name , children = from_dict ( v ) ) ) elif isinstance ( v , list ) : if not any ( isinstance ( i , dict ) for i in v ) : results . append ( Directive ( name = name , a...
Convert a dictionary into a configtree .
31,908
def __or ( funcs , args ) : results = [ ] for f in funcs : result = f ( args ) if result : results . extend ( result ) return results
Support list sugar for or of two predicates . Used inside select .
31,909
def BinaryBool ( pred ) : class Predicate ( Bool ) : def __init__ ( self , value , ignore_case = False ) : self . value = caseless ( value ) if ignore_case else value self . ignore_case = ignore_case def __call__ ( self , data ) : if not isinstance ( data , list ) : data = [ data ] for d in data : try : if pred ( casel...
Lifts predicates that take an argument into the DSL .
31,910
def select ( * queries , ** kwargs ) : def make_query ( * args ) : def simple_query ( nodes ) : if len ( args ) == 0 : return nodes pred = args [ 0 ] results = [ ] if isinstance ( pred , list ) : funcs = [ make_query ( q ) for q in pred ] return __or ( funcs , nodes ) elif isinstance ( pred , tuple ) : name , attrs = p...
Builds a function that will execute the specified queries against a list of Nodes .
31,911
def find ( self , * queries , ** kwargs ) : kwargs [ "deep" ] = True kwargs [ "roots" ] = False if "one" not in kwargs : kwargs [ "one" ] = first return self . select ( * queries , ** kwargs )
Finds the first result found anywhere in the configuration . Pass one = last for the last result . Returns None if no results are found .
31,912
def find_all ( self , * queries ) : return self . select ( * queries , deep = True , roots = False )
Find all results matching the query anywhere in the configuration . Returns an empty SearchResult if no results are found .
31,913
def pad_version ( left , right ) : pair = vcmp ( left ) , vcmp ( right ) mn , mx = min ( pair , key = len ) , max ( pair , key = len ) for idx , c in enumerate ( mx ) : try : a = mx [ idx ] b = mn [ idx ] if type ( a ) != type ( b ) : mn . insert ( idx , 0 ) except IndexError : if type ( c ) is int : mn . append ( 0 ) ...
Returns two sequences of the same length so that they can be compared . The shorter of the two arguments is lengthened by inserting extra zeros before non - integer components . The algorithm attempts to align character components .
31,914
def _parse_package ( cls , package_string ) : pkg , arch = rsplit ( package_string , cls . _arch_sep ( package_string ) ) if arch not in KNOWN_ARCHITECTURES : pkg , arch = ( package_string , None ) pkg , release = rsplit ( pkg , '-' ) name , version = rsplit ( pkg , '-' ) epoch , version = version . split ( ':' , 1 ) i...
Helper method for parsing package string .
31,915
def _parse_line ( cls , line ) : try : pkg , rest = line . split ( None , 1 ) except ValueError : rpm = cls . _parse_package ( line . strip ( ) ) return rpm rpm = cls . _parse_package ( pkg ) rest = rest . split ( '\t' ) for i , value in enumerate ( rest ) : rpm [ cls . SOSREPORT_KEYS [ i ] ] = value return rpm
Helper method for parsing package line with or without SOS report information .
31,916
def _resolve_name ( name , package , level ) : if not hasattr ( package , 'rindex' ) : raise ValueError ( "'package' not set to a string" ) dot = len ( package ) for x in xrange ( level , 1 , - 1 ) : try : dot = package . rindex ( '.' , 0 , dot ) except ValueError : raise ValueError ( "attempted relative import beyond ...
Return the absolute name of the module to be imported .
31,917
def _handle_key_value ( t_dict , key , value ) : if key in t_dict : val = t_dict [ key ] if isinstance ( val , str ) : val = [ val ] val . append ( value ) return val return value
Function to handle key has multi value and return the values as list .
31,918
def get_formatter ( name ) : for k in sorted ( _FORMATTERS ) : if k . startswith ( name ) : return _FORMATTERS [ k ]
Looks up a formatter class given a prefix to it . The names are sorted and the first matching class is returned .
31,919
def all_options ( self ) : items = chain . from_iterable ( hosts . values ( ) for hosts in self . data . values ( ) ) return set ( chain . from_iterable ( items ) )
Returns the set of all options used in all export entries
31,920
def _init_session ( self ) : session = requests . Session ( ) session . headers = { 'User-Agent' : self . user_agent , 'Accept' : 'application/json' } if self . systemid is not None : session . headers . update ( { 'systemid' : self . systemid } ) if self . authmethod == "BASIC" : session . auth = ( self . username , s...
Set up the session auth is handled here
31,921
def handle_fail_rcs ( self , req ) : try : logger . debug ( "HTTP Status Code: %s" , req . status_code ) logger . debug ( "HTTP Response Text: %s" , req . text ) logger . debug ( "HTTP Response Reason: %s" , req . reason ) logger . debug ( "HTTP Response Content: %s" , req . content ) except : logger . error ( "Malform...
Bail out if we get a 401 and leave a message
31,922
def get_satellite5_info ( self , branch_info ) : logger . debug ( "Remote branch not -1 but remote leaf is -1, must be Satellite 5" ) if os . path . isfile ( '/etc/sysconfig/rhn/systemid' ) : logger . debug ( "Found systemid file" ) sat5_conf = ET . parse ( '/etc/sysconfig/rhn/systemid' ) . getroot ( ) leaf_id = None f...
Get remote_leaf for Satellite 5 Managed box
31,923
def get_branch_info ( self ) : branch_info = None if os . path . exists ( constants . cached_branch_info ) : logger . debug ( u'Reading branch info from cached file.' ) ctime = datetime . utcfromtimestamp ( os . path . getctime ( constants . cached_branch_info ) ) if datetime . utcnow ( ) < ( ctime + timedelta ( minute...
Retrieve branch_info from Satellite Server
31,924
def create_system ( self , new_machine_id = False ) : client_hostname = determine_hostname ( ) machine_id = generate_machine_id ( new_machine_id ) branch_info = self . branch_info if not branch_info : return False remote_branch = branch_info [ 'remote_branch' ] remote_leaf = branch_info [ 'remote_leaf' ] data = { 'mach...
Create the machine via the API
31,925
def group_systems ( self , group_name , systems ) : api_group_id = None headers = { 'Content-Type' : 'application/json' } group_path = self . api_url + '/v1/groups' group_get_path = group_path + ( '?display_name=%s' % quote ( group_name ) ) logger . debug ( "GET group: %s" , group_get_path ) net_logger . info ( "GET %s...
Adds an array of systems to specified group
31,926
def do_group ( self ) : group_id = self . config . group systems = { 'machine_id' : generate_machine_id ( ) } self . group_systems ( group_id , systems )
Do grouping on register
31,927
def _legacy_api_registration_check ( self ) : logger . debug ( 'Checking registration status...' ) machine_id = generate_machine_id ( ) try : url = self . api_url + '/v1/systems/' + machine_id net_logger . info ( "GET %s" , url ) res = self . session . get ( url , timeout = self . config . http_timeout ) except request...
Check registration status through API
31,928
def _fetch_system_by_machine_id ( self ) : machine_id = generate_machine_id ( ) try : url = self . api_url + '/inventory/v1/hosts?insights_id=' + machine_id net_logger . info ( "GET %s" , url ) res = self . session . get ( url , timeout = self . config . http_timeout ) except ( requests . ConnectionError , requests . T...
Get a system by machine ID Returns dict system exists in inventory False system does not exist in inventory None error connection or parsing response
31,929
def api_registration_check ( self ) : if self . config . legacy_upload : return self . _legacy_api_registration_check ( ) logger . debug ( 'Checking registration status...' ) results = self . _fetch_system_by_machine_id ( ) if not results : return results logger . debug ( 'System found.' ) logger . debug ( 'Machine ID:...
Reach out to the inventory API to check whether a machine exists .
31,930
def unregister ( self ) : machine_id = generate_machine_id ( ) try : logger . debug ( "Unregistering %s" , machine_id ) url = self . api_url + "/v1/systems/" + machine_id net_logger . info ( "DELETE %s" , url ) self . session . delete ( url ) logger . info ( "Successfully unregistered from the Red Hat Insights Service"...
Unregister this system from the insights service
31,931
def register ( self ) : client_hostname = determine_hostname ( ) logger . debug ( "API: Create system" ) system = self . create_system ( new_machine_id = False ) if system is False : return ( 'Could not reach the Insights service to register.' , '' , '' , '' ) if system . status_code == 409 : system = self . create_sys...
Register this machine
31,932
def _legacy_upload_archive ( self , data_collected , duration ) : file_name = os . path . basename ( data_collected ) try : from insights . contrib import magic m = magic . open ( magic . MAGIC_MIME ) m . load ( ) mime_type = m . file ( data_collected ) except ImportError : magic = None logger . debug ( 'python-magic n...
Do an HTTPS upload of the archive
31,933
def upload_archive ( self , data_collected , content_type , duration ) : if self . config . legacy_upload : return self . _legacy_upload_archive ( data_collected , duration ) file_name = os . path . basename ( data_collected ) upload_url = self . upload_url c_facts = { } try : c_facts = get_canonical_facts ( ) except E...
Do an HTTPS Upload of the archive
31,934
def set_display_name ( self , display_name ) : if self . config . legacy_upload : return self . _legacy_set_display_name ( display_name ) system = self . _fetch_system_by_machine_id ( ) if not system : return system inventory_id = system [ 0 ] [ 'id' ] req_url = self . base_url + '/inventory/v1/hosts/' + inventory_id t...
Set display name of a system independently of upload .
31,935
def _update_dict ( self , dict_ ) : dict_ = dict ( ( k , v ) for k , v in dict_ . items ( ) if ( k not in self . _init_attrs ) ) if 'no_gpg' in dict_ and dict_ [ 'no_gpg' ] : dict_ [ 'gpg' ] = False unknown_opts = set ( dict_ . keys ( ) ) . difference ( set ( DEFAULT_OPTS . keys ( ) ) ) if unknown_opts and self . _prin...
Update without allowing undefined options or overwrite of class methods
31,936
def _load_config_file ( self , fname = None ) : parsedconfig = ConfigParser . RawConfigParser ( ) try : parsedconfig . read ( fname or self . conf ) except ConfigParser . Error : if self . _print_errors : sys . stdout . write ( 'ERROR: Could not read configuration file, ' 'using defaults\n' ) return try : if parsedconf...
Load config from config file . If fname is not specified config is loaded from the file named by InsightsConfig . conf
31,937
def load_all ( self ) : self . _load_command_line ( conf_only = True ) self . _load_config_file ( ) self . _load_env ( ) self . _load_command_line ( ) self . _imply_options ( ) self . _validate_options ( ) return self
Helper function for actual Insights client use
31,938
def _validate_options ( self ) : if self . obfuscate_hostname and not self . obfuscate : raise ValueError ( 'Option `obfuscate_hostname` requires `obfuscate`' ) if self . analyze_image_id is not None and len ( self . analyze_image_id ) < 12 : raise ValueError ( 'Image/Container ID must be at least twelve characters lon...
Make sure there are no conflicting or invalid options
31,939
def _imply_options ( self ) : self . no_upload = self . no_upload or self . to_stdout or self . offline self . auto_update = self . auto_update and not self . offline if ( self . analyze_container or self . analyze_file or self . analyze_mountpoint or self . analyze_image_id ) : self . analyze_container = True self . t...
Some options enable others automatically
31,940
def dict_deep_merge ( tgt , src ) : for k , v in src . items ( ) : if k in tgt : if isinstance ( tgt [ k ] , dict ) and isinstance ( v , dict ) : dict_deep_merge ( tgt [ k ] , v ) else : tgt [ k ] . extend ( deepcopy ( v ) ) else : tgt [ k ] = deepcopy ( v )
Utility function to merge the source dictionary src to the target dictionary recursively
31,941
def _activate_thin_device ( name , dm_id , size , pool ) : table = '0 %d thin /dev/mapper/%s %s' % ( int ( size ) // 512 , pool , dm_id ) cmd = [ 'dmsetup' , 'create' , name , '--table' , table ] r = util . subp ( cmd ) if r . return_code != 0 : raise MountError ( 'Failed to create thin device: %s' % r . stderr . decod...
Provisions an LVM device - mapper thin device reflecting DM device id dm_id in the docker pool .
31,942
def remove_thin_device ( name , force = False ) : cmd = [ 'dmsetup' , 'remove' , '--retry' , name ] r = util . subp ( cmd ) if not force : if r . return_code != 0 : raise MountError ( 'Could not remove thin device:\n%s' % r . stderr . decode ( sys . getdefaultencoding ( ) ) . split ( "\n" ) [ 0 ] )
Destroys a thin device via subprocess call .
31,943
def _is_device_active ( device ) : cmd = [ 'dmsetup' , 'info' , device ] dmsetup_info = util . subp ( cmd ) for dm_line in dmsetup_info . stdout . split ( "\n" ) : line = dm_line . split ( ':' ) if ( 'State' in line [ 0 ] . strip ( ) ) and ( 'ACTIVE' in line [ 1 ] . strip ( ) ) : return True return False
Checks dmsetup to see if a device is already active
31,944
def mount_path ( source , target , bind = False ) : cmd = [ 'mount' ] if bind : cmd . append ( '--bind' ) cmd . append ( source ) cmd . append ( target ) r = util . subp ( cmd ) if r . return_code != 0 : raise MountError ( 'Could not mount docker container:\n' + ' ' . join ( cmd ) + '\n%s' % r . stderr . decode ( sys ....
Subprocess call to mount dev at path .
31,945
def get_dev_at_mountpoint ( mntpoint ) : results = util . subp ( [ 'findmnt' , '-o' , 'SOURCE' , mntpoint ] ) if results . return_code != 0 : raise MountError ( 'No device mounted at %s' % mntpoint ) stdout = results . stdout . decode ( sys . getdefaultencoding ( ) ) return stdout . replace ( 'SOURCE\n' , '' ) . strip ...
Retrieves the device mounted at mntpoint or raises MountError if none .
31,946
def unmount_path ( path , force = False ) : r = util . subp ( [ 'umount' , path ] ) if not force : if r . return_code != 0 : raise ValueError ( r . stderr )
Unmounts the directory specified by path .
31,947
def _create_temp_container ( self , iid ) : try : return self . client . create_container ( image = iid , command = '/bin/true' , environment = [ '_ATOMIC_TEMP_CONTAINER' ] , detach = True , network_disabled = True ) [ 'Id' ] except docker . errors . APIError as ex : raise MountError ( 'Error creating temporary contain...
Create a temporary container from a given iid .
31,948
def _clone ( self , cid ) : try : iid = self . client . commit ( container = cid , conf = { 'Labels' : { 'io.projectatomic.Temporary' : 'true' } } ) [ 'Id' ] except docker . errors . APIError as ex : raise MountError ( str ( ex ) ) self . tmp_image = iid return self . _create_temp_container ( iid )
Create a temporary image snapshot from a given cid .
31,949
def _identifier_as_cid ( self , identifier ) : def __cname_matches ( container , identifier ) : return any ( [ n for n in ( container [ 'Names' ] or [ ] ) if matches ( n , '/' + identifier ) ] ) containers = [ c [ 'Id' ] for c in self . client . containers ( all = True ) if ( __cname_matches ( c , identifier ) or match...
Returns a container uuid for identifier .
31,950
def mount ( self , identifier ) : driver = self . client . info ( ) [ 'Driver' ] driver_mount_fn = getattr ( self , "_mount_" + driver , self . _unsupported_backend ) cid = driver_mount_fn ( identifier ) return self . mountpoint , cid
Mounts a container or image referred to by identifier to the host filesystem .
31,951
def _mount_devicemapper ( self , identifier ) : info = self . client . info ( ) cid = self . _identifier_as_cid ( identifier ) cinfo = self . client . inspect_container ( cid ) dm_dev_name , dm_dev_id , dm_dev_size = '' , '' , '' dm_pool = info [ 'DriverStatus' ] [ 0 ] [ 1 ] try : dm_dev_name = cinfo [ 'GraphDriver' ] ...
Devicemapper mount backend .
31,952
def _mount_overlay ( self , identifier ) : cid = self . _identifier_as_cid ( identifier ) cinfo = self . client . inspect_container ( cid ) ld , ud , wd = '' , '' , '' try : ld = cinfo [ 'GraphDriver' ] [ 'Data' ] [ 'lowerDir' ] ud = cinfo [ 'GraphDriver' ] [ 'Data' ] [ 'upperDir' ] wd = cinfo [ 'GraphDriver' ] [ 'Data...
OverlayFS mount backend .
31,953
def _cleanup_container ( self , cinfo ) : env = cinfo [ 'Config' ] [ 'Env' ] if ( env and '_ATOMIC_TEMP_CONTAINER' not in env ) or not env : return iid = cinfo [ 'Image' ] self . client . remove_container ( cinfo [ 'Id' ] ) try : labels = self . client . inspect_image ( iid ) [ 'Config' ] [ 'Labels' ] except TypeError ...
Remove a container and clean up its image if necessary .
31,954
def _unmount_devicemapper ( self , cid ) : mountpoint = self . mountpoint Mount . unmount_path ( mountpoint ) cinfo = self . client . inspect_container ( cid ) dev_name = cinfo [ 'GraphDriver' ] [ 'Data' ] [ 'DeviceName' ] Mount . remove_thin_device ( dev_name ) self . _cleanup_container ( cinfo )
Devicemapper unmount backend .
31,955
def _unmount_overlay ( self , cid ) : mountpoint = self . mountpoint Mount . unmount_path ( mountpoint ) self . _cleanup_container ( self . client . inspect_container ( cid ) )
OverlayFS unmount backend .
31,956
def jboss_standalone_conf_file ( broker ) : log_files = broker [ JDRSpecs . jboss_standalone_server_log ] if log_files : log_content = log_files [ - 1 ] . content results = [ ] for line in log_content : if "sun.java.command =" in line and ".jdr" not in line and "-Djboss.server.base.dir" in line : results . append ( lin...
Get which jboss standalone conf file is using from server log
31,957
def parse_bool ( s , default = False ) : if s is None : return default return TRUTH . get ( s . lower ( ) , default )
Return the boolean value of an English string or default if it can t be determined .
31,958
def defaults ( default = None ) : def _f ( func ) : @ functools . wraps ( func ) def __f ( self , * args , ** kwargs ) : try : return func ( self , * args , ** kwargs ) except Exception : return default return __f return _f
Catches any exception thrown by the wrapped function and returns default instead .
31,959
def keys_in ( items , * args ) : found = dict ( ( key , False ) for key in items ) for d in args : for item in items : if not found [ item ] and item in d : found [ item ] = True return all ( found . values ( ) )
Use this utility function to ensure multiple keys are in one or more dicts . Returns True if all keys are present in at least one of the given dicts otherwise returns False .
31,960
def deprecated ( func , solution ) : def get_name_line ( src ) : for line in src : if "@" not in line : return line . strip ( ) path = inspect . getsourcefile ( func ) src , line_no = inspect . getsourcelines ( func ) name = get_name_line ( src ) or "Unknown" the_msg = "<{c}> at {p}:{l} is deprecated: {s}" . format ( c...
Mark a parser or combiner as deprecated and give a message of how to fix this . This will emit a warning in the logs when the function is used . When combined with modifications to conftest this causes deprecations to become fatal errors when testing so they get fixed .
31,961
def parse_keypair_lines ( content , delim = '|' , kv_sep = '=' ) : r = [ ] if content : for row in [ line for line in content if line ] : item_dict = { } for item in row . split ( delim ) : key , value = [ i . strip ( "'\"" ) . strip ( ) for i in item . strip ( ) . split ( kv_sep ) ] item_dict [ key ] = value r . appen...
Parses a set of entities where each entity is a set of key - value pairs contained all on one line . Each entity is parsed into a dictionary and added to the list returned from this function .
31,962
def rsplit ( _str , seps ) : for idx , ch in enumerate ( reversed ( _str ) ) : if ch in seps : return _str [ 0 : - idx - 1 ] , _str [ - idx : ]
Splits _str by the first sep in seps that is found from the right side . Returns a tuple without the separator .
31,963
def progress_bar ( self , c , broker ) : v = broker . get ( c ) if v and isinstance ( v , dict ) and len ( v ) > 0 and 'type' in v : if v [ "type" ] in self . responses : print ( self . responses [ v [ "type" ] ] . color + self . responses [ v [ "type" ] ] . intl + Style . RESET_ALL , end = "" , file = self . stream ) ...
Print the formated progress information for the processed return types
31,964
def show_dropped ( self ) : ctx = _find_context ( self . broker ) if ctx and ctx . all_files : ds = self . broker . get_by_type ( datasource ) vals = [ ] for v in ds . values ( ) : if isinstance ( v , list ) : vals . extend ( d . path for d in v ) else : vals . append ( v . path ) dropped = set ( ctx . all_files ) - se...
Show dropped files
31,965
def register ( config , pconn ) : username = config . username password = config . password authmethod = config . authmethod auto_config = config . auto_config if not username and not password and not auto_config and authmethod == 'BASIC' : logger . debug ( 'Username and password must be defined in configuration file w...
Do registration using basic auth
31,966
def validate_gpg_sig ( self , path , sig = None ) : logger . debug ( "Verifying GPG signature of Insights configuration" ) if sig is None : sig = path + ".asc" command = ( "/usr/bin/gpg --no-default-keyring " "--keyring " + constants . pub_gpg_path + " --verify " + sig + " " + path ) if not six . PY3 : command = comman...
Validate the collection rules
31,967
def try_disk ( self , path , gpg = True ) : if not os . path . isfile ( path ) : return if not gpg or self . validate_gpg_sig ( path ) : stream = open ( path , 'r' ) json_stream = stream . read ( ) if len ( json_stream ) : try : json_config = json . loads ( json_stream ) return json_config except ValueError : logger . ...
Try to load json off disk
31,968
def get_collection_rules ( self , raw = False ) : logger . debug ( "Attemping to download collection rules from %s" , self . collection_rules_url ) net_logger . info ( "GET %s" , self . collection_rules_url ) try : req = self . conn . session . get ( self . collection_rules_url , headers = ( { 'accept' : 'text/plain' }...
Download the collection rules
31,969
def get_collection_rules_gpg ( self , collection_rules ) : sig_text = self . fetch_gpg ( ) sig_response = NamedTemporaryFile ( suffix = ".asc" ) sig_response . write ( sig_text . encode ( 'utf-8' ) ) sig_response . file . flush ( ) self . validate_gpg_sig ( collection_rules . name , sig_response . name ) self . write_c...
Download the collection rules gpg signature
31,970
def write_collection_data ( self , path , data ) : flags = os . O_WRONLY | os . O_CREAT | os . O_TRUNC fd = os . open ( path , flags , 0o600 ) with os . fdopen ( fd , 'w' ) as dyn_conf_file : dyn_conf_file . write ( data )
Write collections rules to disk
31,971
def get_conf_file ( self ) : for conf_file in [ self . collection_rules_file , self . fallback_file ] : logger . debug ( "trying to read conf from: " + conf_file ) conf = self . try_disk ( conf_file , self . gpg ) if not conf : continue version = conf . get ( 'version' , None ) if version is None : raise ValueError ( "...
Get config from local config file first try cache then fallback .
31,972
def get_conf_update ( self ) : dyn_conf = self . get_collection_rules ( ) if not dyn_conf : return self . get_conf_file ( ) version = dyn_conf . get ( 'version' , None ) if version is None : raise ValueError ( "ERROR: Could not find version in json" ) dyn_conf [ 'file' ] = self . collection_rules_file logger . debug ( ...
Get updated config from URL fallback to local file if download fails .
31,973
def get_rm_conf ( self ) : if not os . path . isfile ( self . remove_file ) : return None parsedconfig = ConfigParser . RawConfigParser ( ) parsedconfig . read ( self . remove_file ) rm_conf = { } for item , value in parsedconfig . items ( 'remove' ) : if six . PY3 : rm_conf [ item ] = value . strip ( ) . encode ( 'utf...
Get excluded files config from remove_file .
31,974
def stream ( command , stdin = None , env = os . environ , timeout = None ) : if not isinstance ( command , list ) : command = shlex . split ( command ) cmd = which ( command [ 0 ] ) if cmd is None : path = env . get ( "PATH" , "" ) raise Exception ( "Command [%s] not in PATH [%s]" % ( command [ 0 ] , path ) ) command ...
Yields a generator of a command s output . For line oriented commands only .
31,975
def connect ( * cmds , ** kwargs ) : stdin = kwargs . get ( "stdin" ) env = kwargs . get ( "env" , os . environ ) timeout = kwargs . get ( "timeout" ) end = len ( cmds ) - 1 @ contextmanager def inner ( idx , inp ) : with stream ( cmds [ idx ] , stdin = inp , env = env , timeout = timeout ) as s : if idx == end : yield...
Connects multiple command streams together and yields the final stream .
31,976
def parse_non_selinux ( parts ) : links , owner , group , last = parts result = { "links" : int ( links ) , "owner" : owner , "group" : group , } if "," in last [ : 4 ] : major , minor , rest = last . split ( None , 2 ) result [ "major" ] = int ( major . rstrip ( "," ) ) result [ "minor" ] = int ( minor ) else : size ,...
Parse part of an ls output line that isn t selinux .
31,977
def parse_selinux ( parts ) : owner , group = parts [ : 2 ] selinux = parts [ 2 ] . split ( ":" ) lsel = len ( selinux ) path , link = parse_path ( parts [ - 1 ] ) result = { "owner" : owner , "group" : group , "se_user" : selinux [ 0 ] , "se_role" : selinux [ 1 ] if lsel > 1 else None , "se_type" : selinux [ 2 ] if ls...
Parse part of an ls output line that is selinux .
31,978
def parse ( lines , root = None ) : doc = { } entries = [ ] name = None total = None for line in lines : line = line . strip ( ) if not line : continue if line and line [ 0 ] == "/" and line [ - 1 ] == ":" : if name is None : name = line [ : - 1 ] if entries : d = Directory ( name , total or len ( entries ) , entries )...
Parses a list of lines from ls into dictionaries representing their components .
31,979
def get_active_lines ( lines , comment_char = "#" ) : return list ( filter ( None , ( line . split ( comment_char , 1 ) [ 0 ] . strip ( ) for line in lines ) ) )
Returns lines or parts of lines from content that are not commented out or completely empty . The resulting lines are all individually stripped .
31,980
def optlist_to_dict ( optlist , opt_sep = ',' , kv_sep = '=' , strip_quotes = False ) : def make_kv ( opt ) : if kv_sep is not None and kv_sep in opt : k , v = opt . split ( kv_sep , 1 ) k = k . strip ( ) if strip_quotes and v [ 0 ] in ( '"' , "'" ) and v [ - 1 ] == v [ 0 ] : return k , v [ 1 : - 1 ] else : return k , ...
Parse an option list into a dictionary .
31,981
def unsplit_lines ( lines , cont_char = '\\' , keep_cont_char = False ) : unsplit_lines = [ ] for line in lines : line = line . rstrip ( ) if line . endswith ( cont_char ) : unsplit_lines . append ( line if keep_cont_char else line [ : - 1 ] ) else : yield '' . join ( unsplit_lines ) + line unsplit_lines = [ ] if unspl...
Recombine lines having a continuation character at end .
31,982
def calc_offset ( lines , target , invert_search = False ) : if target and target [ 0 ] is not None : for offset , line in enumerate ( l . strip ( ) for l in lines ) : found_any = any ( [ line . startswith ( t ) for t in target ] ) if not invert_search and found_any : return offset elif invert_search and not ( line == ...
Function to search for a line in a list starting with a target string . If target is None or an empty string then 0 is returned . This allows checking target here instead of having to check for an empty target in the calling function . Each line is stripped of leading spaces prior to comparison with each target however...
31,983
def parse_fixed_table ( table_lines , heading_ignore = [ ] , header_substitute = [ ] , trailing_ignore = [ ] ) : def calc_column_indices ( line , headers ) : idx = [ ] for h in headers : i = idx [ - 1 ] + 1 if idx else 0 idx . append ( line . index ( h , i ) ) return idx first_line = calc_offset ( table_lines , heading...
Function to parse table data containing column headings in the first row and data in fixed positions in each remaining row of table data . Table columns must not contain spaces within the column name . Column headings are assumed to be left justified and the column data width is the width of the heading label plus all ...
31,984
def keyword_search ( rows , ** kwargs ) : results = [ ] if not kwargs : return results matchers = { 'default' : lambda s , v : s == v , 'contains' : lambda s , v : v in s , 'startswith' : lambda s , v : s . startswith ( v ) , 'lower_value' : lambda s , v : s . lower ( ) == v . lower ( ) , } def key_match ( row , key , ...
Takes a list of dictionaries and finds all the dictionaries where the keys and values match those found in the keyword arguments .
31,985
def count_exceptions ( self , c , broker ) : if c in broker . exceptions : self . counts [ 'exception' ] += len ( broker . exceptions [ c ] ) return self
Count exceptions as processing proceeds
31,986
def bash_rule ( bash , hostnames ) : if isinstance ( bash , dict ) : return make_fail ( 'bash_rule' , error_message = "Run this rule with a cluster archive" ) return make_pass ( 'bash_rule' , bash = bash , hostname = hostnames )
Cluster rule to process bash and hostname info
31,987
def marshal ( self , o , use_value_list = False ) : if o is None : return elif isinstance ( o , dict ) : if use_value_list : for k , v in o . items ( ) : o [ k ] = [ v ] return o elif isinstance ( o , six . string_types ) : if use_value_list : return { o : [ True ] } else : return { o : True } else : raise TypeError ( ...
Packages the return from a parser for easy use in a rule .
31,988
def load_manifest ( data ) : if isinstance ( data , dict ) : return data doc = yaml . safe_load ( data ) if not isinstance ( doc , dict ) : raise Exception ( "Manifest didn't result in dict." ) return doc
Helper for loading a manifest yaml doc .
31,989
def create_context ( ctx ) : ctx_cls_name = ctx . get ( "class" , "insights.core.context.HostContext" ) if "." not in ctx_cls_name : ctx_cls_name = "insights.core.context." + ctx_cls_name ctx_cls = dr . get_component ( ctx_cls_name ) ctx_args = ctx . get ( "args" , { } ) return ctx_cls ( ** ctx_args )
Loads and constructs the specified context with the specified arguments . If a . isn t in the class name the insights . core . context package is assumed .
31,990
def get_to_persist ( persisters ) : def specs ( ) : for p in persisters : if isinstance ( p , dict ) : yield p [ "name" ] , p . get ( "enabled" , True ) else : yield p , True components = sorted ( dr . DELEGATES , key = dr . get_name ) names = dict ( ( c , dr . get_name ( c ) ) for c in components ) results = set ( ) f...
Given a specification of what to persist generates the corresponding set of components .
31,991
def create_archive ( path , remove_path = True ) : root_path = os . path . dirname ( path ) relative_path = os . path . basename ( path ) archive_path = path + ".tar.gz" cmd = [ [ "tar" , "-C" , root_path , "-czf" , archive_path , relative_path ] ] call ( cmd , env = SAFE_ENV ) if remove_path : fs . remove ( path ) ret...
Creates a tar . gz of the path using the path basename + tar . gz The resulting file is in the parent directory of the original path and the original path is removed .
31,992
def collect ( manifest = default_manifest , tmp_path = None , compress = False ) : manifest = load_manifest ( manifest ) client = manifest . get ( "client" , { } ) plugins = manifest . get ( "plugins" , { } ) run_strategy = client . get ( "run_strategy" , { "name" : "parallel" } ) apply_default_enabled ( plugins . get ...
This is the collection entry point . It accepts a manifest a temporary directory in which to store output and a boolean for optional compression .
31,993
def _run ( broker , graph = None , root = None , context = None , inventory = None ) : if not root : context = context or HostContext broker [ context ] = context ( ) return dr . run ( graph , broker = broker ) if os . path . isdir ( root ) : return process_dir ( broker , root , graph , context , inventory = inventory ...
run is a general interface that is meant for stand alone scripts to use when executing insights components .
31,994
def apply_default_enabled ( default_enabled ) : for k in dr . ENABLED : dr . ENABLED [ k ] = default_enabled enabled = defaultdict ( lambda : default_enabled ) enabled . update ( dr . ENABLED ) dr . ENABLED = enabled
Configures dr and already loaded components with a default enabled value .
31,995
def apply_configs ( config ) : default_enabled = config . get ( 'default_component_enabled' , False ) delegate_keys = sorted ( dr . DELEGATES , key = dr . get_name ) for comp_cfg in config . get ( 'configs' , [ ] ) : name = comp_cfg . get ( "name" ) for c in delegate_keys : delegate = dr . DELEGATES [ c ] cname = dr . ...
Configures components . They can be enabled or disabled have timeouts set if applicable and have metadata customized . Valid keys are name enabled metadata and timeout .
31,996
def _read ( self , fp , fpname ) : cursect = None optname = None lineno = 0 e = None while True : line = fp . readline ( ) if not line : break lineno = lineno + 1 if line . strip ( ) == '' or line [ 0 ] in '#;' : continue if line . split ( None , 1 ) [ 0 ] . lower ( ) == 'rem' and line [ 0 ] in "rR" : continue if line ...
Parse a sectioned setup file .
31,997
def determine_hostname ( display_name = None ) : if display_name : return display_name else : socket_gethostname = socket . gethostname ( ) socket_fqdn = socket . getfqdn ( ) try : socket_ex = socket . gethostbyname_ex ( socket_gethostname ) [ 0 ] except ( LookupError , socket . gaierror ) : socket_ex = '' gethostname_...
Find fqdn if we can
31,998
def write_unregistered_file ( date = None ) : delete_registered_file ( ) if date is None : date = get_time ( ) for f in constants . unregistered_files : if os . path . lexists ( f ) : if os . path . islink ( f ) : os . remove ( f ) write_to_disk ( f , content = str ( date ) ) else : write_to_disk ( f , content = str ( ...
Write . unregistered out to disk
31,999
def write_to_disk ( filename , delete = False , content = get_time ( ) ) : if not os . path . exists ( os . path . dirname ( filename ) ) : return if delete : if os . path . lexists ( filename ) : os . remove ( filename ) else : with open ( filename , 'wb' ) as f : f . write ( content . encode ( 'utf-8' ) )
Write filename out to disk