idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
247,900 | def macro_tpm_sbs ( self , state_by_state_micro_tpm ) : validate . tpm ( state_by_state_micro_tpm , check_independence = False ) mapping = self . make_mapping ( ) num_macro_states = 2 ** len ( self . macro_indices ) macro_tpm = np . zeros ( ( num_macro_states , num_macro_states ) ) micro_states = range ( 2 ** len ( self . micro_indices ) ) micro_state_transitions = itertools . product ( micro_states , repeat = 2 ) # For every possible micro-state transition, get the corresponding # previous and next macro-state using the mapping and add that # probability to the state-by-state macro TPM. for previous_state , current_state in micro_state_transitions : macro_tpm [ mapping [ previous_state ] , mapping [ current_state ] ] += ( state_by_state_micro_tpm [ previous_state , current_state ] ) # Re-normalize each row because we're going from larger to smaller TPM return np . array ( [ distribution . normalize ( row ) for row in macro_tpm ] ) | Create a state - by - state coarse - grained macro TPM . | 272 | 15 |
247,901 | def macro_tpm ( self , micro_tpm , check_independence = True ) : if not is_state_by_state ( micro_tpm ) : micro_tpm = convert . state_by_node2state_by_state ( micro_tpm ) macro_tpm = self . macro_tpm_sbs ( micro_tpm ) if check_independence : validate . conditionally_independent ( macro_tpm ) return convert . state_by_state2state_by_node ( macro_tpm ) | Create a coarse - grained macro TPM . | 117 | 10 |
247,902 | def hidden_indices ( self ) : return tuple ( sorted ( set ( self . micro_indices ) - set ( self . output_indices ) ) ) | All elements hidden inside the blackboxes . | 35 | 8 |
247,903 | def outputs_of ( self , partition_index ) : partition = self . partition [ partition_index ] outputs = set ( partition ) . intersection ( self . output_indices ) return tuple ( sorted ( outputs ) ) | The outputs of the partition at partition_index . | 46 | 10 |
247,904 | def reindex ( self ) : _map = dict ( zip ( self . micro_indices , reindex ( self . micro_indices ) ) ) partition = tuple ( tuple ( _map [ index ] for index in group ) for group in self . partition ) output_indices = tuple ( _map [ i ] for i in self . output_indices ) return Blackbox ( partition , output_indices ) | Squeeze the indices of this blackboxing to 0 .. n . | 89 | 14 |
247,905 | def macro_state ( self , micro_state ) : assert len ( micro_state ) == len ( self . micro_indices ) reindexed = self . reindex ( ) return utils . state_of ( reindexed . output_indices , micro_state ) | Compute the macro - state of this blackbox . | 60 | 11 |
247,906 | def in_same_box ( self , a , b ) : assert a in self . micro_indices assert b in self . micro_indices for part in self . partition : if a in part and b in part : return True return False | Return True if nodes a and b are in the same box . | 52 | 13 |
247,907 | def hidden_from ( self , a , b ) : return a in self . hidden_indices and not self . in_same_box ( a , b ) | Return True if a is hidden in a different box than b . | 35 | 13 |
247,908 | def irreducible_purviews ( cm , direction , mechanism , purviews ) : def reducible ( purview ) : """Return ``True`` if purview is trivially reducible.""" _from , to = direction . order ( mechanism , purview ) return connectivity . block_reducible ( cm , _from , to ) return [ purview for purview in purviews if not reducible ( purview ) ] | Return all purviews which are irreducible for the mechanism . | 91 | 14 |
247,909 | def _build_tpm ( tpm ) : tpm = np . array ( tpm ) validate . tpm ( tpm ) # Convert to multidimensional state-by-node form if is_state_by_state ( tpm ) : tpm = convert . state_by_state2state_by_node ( tpm ) else : tpm = convert . to_multidimensional ( tpm ) utils . np_immutable ( tpm ) return ( tpm , utils . np_hash ( tpm ) ) | Validate the TPM passed by the user and convert to multidimensional form . | 117 | 17 |
247,910 | def _build_cm ( self , cm ) : if cm is None : # Assume all are connected. cm = np . ones ( ( self . size , self . size ) ) else : cm = np . array ( cm ) utils . np_immutable ( cm ) return ( cm , utils . np_hash ( cm ) ) | Convert the passed CM to the proper format or construct the unitary CM if none was provided . | 73 | 20 |
247,911 | def potential_purviews ( self , direction , mechanism ) : all_purviews = utils . powerset ( self . _node_indices ) return irreducible_purviews ( self . cm , direction , mechanism , all_purviews ) | All purviews which are not clearly reducible for mechanism . | 54 | 12 |
247,912 | def _loadable_models ( ) : classes = [ pyphi . Direction , pyphi . Network , pyphi . Subsystem , pyphi . Transition , pyphi . labels . NodeLabels , pyphi . models . Cut , pyphi . models . KCut , pyphi . models . NullCut , pyphi . models . Part , pyphi . models . Bipartition , pyphi . models . KPartition , pyphi . models . Tripartition , pyphi . models . RepertoireIrreducibilityAnalysis , pyphi . models . MaximallyIrreducibleCauseOrEffect , pyphi . models . MaximallyIrreducibleCause , pyphi . models . MaximallyIrreducibleEffect , pyphi . models . Concept , pyphi . models . CauseEffectStructure , pyphi . models . SystemIrreducibilityAnalysis , pyphi . models . ActualCut , pyphi . models . AcRepertoireIrreducibilityAnalysis , pyphi . models . CausalLink , pyphi . models . Account , pyphi . models . AcSystemIrreducibilityAnalysis ] return { cls . __name__ : cls for cls in classes } | A dictionary of loadable PyPhi models . | 255 | 10 |
247,913 | def jsonify ( obj ) : # pylint: disable=too-many-return-statements # Call the `to_json` method if available and add metadata. if hasattr ( obj , 'to_json' ) : d = obj . to_json ( ) _push_metadata ( d , obj ) return jsonify ( d ) # If we have a numpy array, convert it to a list. if isinstance ( obj , np . ndarray ) : return obj . tolist ( ) # If we have NumPy datatypes, convert them to native types. if isinstance ( obj , ( np . int32 , np . int64 ) ) : return int ( obj ) if isinstance ( obj , np . float64 ) : return float ( obj ) # Recurse over dictionaries. if isinstance ( obj , dict ) : return _jsonify_dict ( obj ) # Recurse over object dictionaries. if hasattr ( obj , '__dict__' ) : return _jsonify_dict ( obj . __dict__ ) # Recurse over lists and tuples. if isinstance ( obj , ( list , tuple ) ) : return [ jsonify ( item ) for item in obj ] # Otherwise, give up and hope it's serializable. return obj | Return a JSON - encodable representation of an object recursively using any available to_json methods converting NumPy arrays and datatypes to native lists and types along the way . | 273 | 38 |
247,914 | def _check_version ( version ) : if version != pyphi . __version__ : raise pyphi . exceptions . JSONVersionError ( 'Cannot load JSON from a different version of PyPhi. ' 'JSON version = {0}, current version = {1}.' . format ( version , pyphi . __version__ ) ) | Check whether the JSON version matches the PyPhi version . | 71 | 12 |
247,915 | def _load_object ( self , obj ) : if isinstance ( obj , dict ) : obj = { k : self . _load_object ( v ) for k , v in obj . items ( ) } # Load a serialized PyPhi model if _is_model ( obj ) : return self . _load_model ( obj ) elif isinstance ( obj , list ) : return tuple ( self . _load_object ( item ) for item in obj ) return obj | Recursively load a PyPhi object . | 102 | 10 |
247,916 | def _load_model ( self , dct ) : classname , version , _ = _pop_metadata ( dct ) _check_version ( version ) cls = self . _models [ classname ] # Use `from_json` if available if hasattr ( cls , 'from_json' ) : return cls . from_json ( dct ) # Default to object constructor return cls ( * * dct ) | Load a serialized PyPhi model . | 93 | 9 |
247,917 | def _compute_hamming_matrix ( N ) : possible_states = np . array ( list ( utils . all_states ( ( N ) ) ) ) return cdist ( possible_states , possible_states , 'hamming' ) * N | Compute and store a Hamming matrix for |N| nodes . | 56 | 14 |
247,918 | def effect_emd ( d1 , d2 ) : return sum ( abs ( marginal_zero ( d1 , i ) - marginal_zero ( d2 , i ) ) for i in range ( d1 . ndim ) ) | Compute the EMD between two effect repertoires . | 50 | 11 |
247,919 | def entropy_difference ( d1 , d2 ) : d1 , d2 = flatten ( d1 ) , flatten ( d2 ) return abs ( entropy ( d1 , base = 2.0 ) - entropy ( d2 , base = 2.0 ) ) | Return the difference in entropy between two distributions . | 59 | 9 |
247,920 | def psq2 ( d1 , d2 ) : d1 , d2 = flatten ( d1 ) , flatten ( d2 ) def f ( p ) : return sum ( ( p ** 2 ) * np . nan_to_num ( np . log ( p * len ( p ) ) ) ) return abs ( f ( d1 ) - f ( d2 ) ) | Compute the PSQ2 measure . | 82 | 8 |
247,921 | def mp2q ( p , q ) : p , q = flatten ( p ) , flatten ( q ) entropy_dist = 1 / len ( p ) return sum ( entropy_dist * np . nan_to_num ( ( p ** 2 ) / q * np . log ( p / q ) ) ) | Compute the MP2Q measure . | 68 | 8 |
247,922 | def klm ( p , q ) : p , q = flatten ( p ) , flatten ( q ) return max ( abs ( p * np . nan_to_num ( np . log ( p / q ) ) ) ) | Compute the KLM divergence . | 51 | 7 |
247,923 | def directional_emd ( direction , d1 , d2 ) : if direction == Direction . CAUSE : func = hamming_emd elif direction == Direction . EFFECT : func = effect_emd else : # TODO: test that ValueError is raised validate . direction ( direction ) return round ( func ( d1 , d2 ) , config . PRECISION ) | Compute the EMD between two repertoires for a given direction . | 81 | 14 |
247,924 | def repertoire_distance ( direction , r1 , r2 ) : if config . MEASURE == 'EMD' : dist = directional_emd ( direction , r1 , r2 ) else : dist = measures [ config . MEASURE ] ( r1 , r2 ) return round ( dist , config . PRECISION ) | Compute the distance between two repertoires for the given direction . | 71 | 13 |
247,925 | def system_repertoire_distance ( r1 , r2 ) : if config . MEASURE in measures . asymmetric ( ) : raise ValueError ( '{} is asymmetric and cannot be used as a system-level ' 'irreducibility measure.' . format ( config . MEASURE ) ) return measures [ config . MEASURE ] ( r1 , r2 ) | Compute the distance between two repertoires of a system . | 84 | 12 |
247,926 | def register ( self , name , asymmetric = False ) : def register_func ( func ) : if asymmetric : self . _asymmetric . append ( name ) self . store [ name ] = func return func return register_func | Decorator for registering a measure with PyPhi . | 50 | 12 |
247,927 | def partitions ( collection ) : collection = list ( collection ) # Special cases if not collection : return if len ( collection ) == 1 : yield [ collection ] return first = collection [ 0 ] for smaller in partitions ( collection [ 1 : ] ) : for n , subset in enumerate ( smaller ) : yield smaller [ : n ] + [ [ first ] + subset ] + smaller [ n + 1 : ] yield [ [ first ] ] + smaller | Generate all set partitions of a collection . | 92 | 9 |
247,928 | def bipartition_indices ( N ) : result = [ ] if N <= 0 : return result for i in range ( 2 ** ( N - 1 ) ) : part = [ [ ] , [ ] ] for n in range ( N ) : bit = ( i >> n ) & 1 part [ bit ] . append ( n ) result . append ( ( tuple ( part [ 1 ] ) , tuple ( part [ 0 ] ) ) ) return result | Return indices for undirected bipartitions of a sequence . | 95 | 13 |
247,929 | def bipartition ( seq ) : return [ ( tuple ( seq [ i ] for i in part0_idx ) , tuple ( seq [ j ] for j in part1_idx ) ) for part0_idx , part1_idx in bipartition_indices ( len ( seq ) ) ] | Return a list of bipartitions for a sequence . | 69 | 11 |
247,930 | def directed_bipartition ( seq , nontrivial = False ) : bipartitions = [ ( tuple ( seq [ i ] for i in part0_idx ) , tuple ( seq [ j ] for j in part1_idx ) ) for part0_idx , part1_idx in directed_bipartition_indices ( len ( seq ) ) ] if nontrivial : # The first and last partitions have a part that is empty; skip them. # NOTE: This depends on the implementation of # `directed_partition_indices`. return bipartitions [ 1 : - 1 ] return bipartitions | Return a list of directed bipartitions for a sequence . | 138 | 12 |
247,931 | def bipartition_of_one ( seq ) : seq = list ( seq ) for i , elt in enumerate ( seq ) : yield ( ( elt , ) , tuple ( seq [ : i ] + seq [ ( i + 1 ) : ] ) ) | Generate bipartitions where one part is of length 1 . | 57 | 13 |
247,932 | def directed_bipartition_of_one ( seq ) : bipartitions = list ( bipartition_of_one ( seq ) ) return chain ( bipartitions , reverse_elements ( bipartitions ) ) | Generate directed bipartitions where one part is of length 1 . | 49 | 14 |
247,933 | def directed_tripartition_indices ( N ) : result = [ ] if N <= 0 : return result base = [ 0 , 1 , 2 ] for key in product ( base , repeat = N ) : part = [ [ ] , [ ] , [ ] ] for i , location in enumerate ( key ) : part [ location ] . append ( i ) result . append ( tuple ( tuple ( p ) for p in part ) ) return result | Return indices for directed tripartitions of a sequence . | 95 | 11 |
247,934 | def directed_tripartition ( seq ) : for a , b , c in directed_tripartition_indices ( len ( seq ) ) : yield ( tuple ( seq [ i ] for i in a ) , tuple ( seq [ j ] for j in b ) , tuple ( seq [ k ] for k in c ) ) | Generator over all directed tripartitions of a sequence . | 70 | 12 |
247,935 | def k_partitions ( collection , k ) : collection = list ( collection ) n = len ( collection ) # Special cases if n == 0 or k < 1 : return [ ] if k == 1 : return [ [ collection ] ] a = [ 0 ] * ( n + 1 ) for j in range ( 1 , k + 1 ) : a [ n - k + j ] = j - 1 return _f ( k , n , 0 , n , a , k , collection ) | Generate all k - partitions of a collection . | 102 | 10 |
247,936 | def mip_partitions ( mechanism , purview , node_labels = None ) : func = partition_types [ config . PARTITION_TYPE ] return func ( mechanism , purview , node_labels ) | Return a generator over all mechanism - purview partitions based on the current configuration . | 46 | 16 |
247,937 | def mip_bipartitions ( mechanism , purview , node_labels = None ) : numerators = bipartition ( mechanism ) denominators = directed_bipartition ( purview ) for n , d in product ( numerators , denominators ) : if ( n [ 0 ] or d [ 0 ] ) and ( n [ 1 ] or d [ 1 ] ) : yield Bipartition ( Part ( n [ 0 ] , d [ 0 ] ) , Part ( n [ 1 ] , d [ 1 ] ) , node_labels = node_labels ) | r Return an generator of all |small_phi| bipartitions of a mechanism over a purview . | 125 | 22 |
247,938 | def wedge_partitions ( mechanism , purview , node_labels = None ) : numerators = bipartition ( mechanism ) denominators = directed_tripartition ( purview ) yielded = set ( ) def valid ( factoring ) : """Return whether the factoring should be considered.""" # pylint: disable=too-many-boolean-expressions numerator , denominator = factoring return ( ( numerator [ 0 ] or denominator [ 0 ] ) and ( numerator [ 1 ] or denominator [ 1 ] ) and ( ( numerator [ 0 ] and numerator [ 1 ] ) or not denominator [ 0 ] or not denominator [ 1 ] ) ) for n , d in filter ( valid , product ( numerators , denominators ) ) : # Normalize order of parts to remove duplicates. tripart = Tripartition ( Part ( n [ 0 ] , d [ 0 ] ) , Part ( n [ 1 ] , d [ 1 ] ) , Part ( ( ) , d [ 2 ] ) , node_labels = node_labels ) . normalize ( ) # pylint: disable=bad-whitespace def nonempty ( part ) : """Check that the part is not empty.""" return part . mechanism or part . purview def compressible ( tripart ) : """Check if the tripartition can be transformed into a causally equivalent partition by combing two of its parts; e.g., A/∅ × B/∅ × ∅/CD is equivalent to AB/∅ × ∅/CD so we don't include it. """ pairs = [ ( tripart [ 0 ] , tripart [ 1 ] ) , ( tripart [ 0 ] , tripart [ 2 ] ) , ( tripart [ 1 ] , tripart [ 2 ] ) ] for x , y in pairs : if ( nonempty ( x ) and nonempty ( y ) and ( x . mechanism + y . mechanism == ( ) or x . purview + y . purview == ( ) ) ) : return True return False if not compressible ( tripart ) and tripart not in yielded : yielded . add ( tripart ) yield tripart | Return an iterator over all wedge partitions . | 466 | 8 |
247,939 | def all_partitions ( mechanism , purview , node_labels = None ) : for mechanism_partition in partitions ( mechanism ) : mechanism_partition . append ( [ ] ) n_mechanism_parts = len ( mechanism_partition ) max_purview_partition = min ( len ( purview ) , n_mechanism_parts ) for n_purview_parts in range ( 1 , max_purview_partition + 1 ) : n_empty = n_mechanism_parts - n_purview_parts for purview_partition in k_partitions ( purview , n_purview_parts ) : purview_partition = [ tuple ( _list ) for _list in purview_partition ] # Extend with empty tuples so purview partition has same size # as mechanism purview purview_partition . extend ( [ ( ) ] * n_empty ) # Unique permutations to avoid duplicates empties for purview_permutation in set ( permutations ( purview_partition ) ) : parts = [ Part ( tuple ( m ) , tuple ( p ) ) for m , p in zip ( mechanism_partition , purview_permutation ) ] # Must partition the mechanism, unless the purview is fully # cut away from the mechanism. if parts [ 0 ] . mechanism == mechanism and parts [ 0 ] . purview : continue yield KPartition ( * parts , node_labels = node_labels ) | Return all possible partitions of a mechanism and purview . | 320 | 11 |
247,940 | def naturalize_string ( key ) : return [ int ( text ) if text . isdigit ( ) else text . lower ( ) for text in re . split ( numregex , key ) ] | Analyzes string in a human way to enable natural sort | 42 | 11 |
247,941 | def fetch_sel ( self , ipmicmd , clear = False ) : records = [ ] # First we do a fetch all without reservation, reducing the risk # of having a long lived reservation that gets canceled in the middle endat = self . _fetch_entries ( ipmicmd , 0 , records ) if clear and records : # don't bother clearing if there were no records # To do clear, we make a reservation first... rsp = ipmicmd . xraw_command ( netfn = 0xa , command = 0x42 ) rsvid = struct . unpack_from ( '<H' , rsp [ 'data' ] ) [ 0 ] # Then we refetch the tail with reservation (check for change) del records [ - 1 ] # remove the record that's about to be duplicated self . _fetch_entries ( ipmicmd , endat , records , rsvid ) # finally clear the SEL # 0XAA means start initiate, 0x524c43 is 'RCL' or 'CLR' backwards clrdata = bytearray ( struct . pack ( '<HI' , rsvid , 0xAA524C43 ) ) ipmicmd . xraw_command ( netfn = 0xa , command = 0x47 , data = clrdata ) # Now to fixup the record timestamps... first we need to get the BMC # opinion of current time _fix_sel_time ( records , ipmicmd ) return records | Fetch SEL entries | 318 | 5 |
247,942 | def oem_init ( self ) : if self . _oemknown : return self . _oem , self . _oemknown = get_oem_handler ( self . _get_device_id ( ) , self ) | Initialize the command object for OEM capabilities | 51 | 8 |
247,943 | def reset_bmc ( self ) : response = self . raw_command ( netfn = 6 , command = 2 ) if 'error' in response : raise exc . IpmiException ( response [ 'error' ] ) | Do a cold reset in BMC | 48 | 6 |
247,944 | def xraw_command ( self , netfn , command , bridge_request = ( ) , data = ( ) , delay_xmit = None , retry = True , timeout = None ) : rsp = self . ipmi_session . raw_command ( netfn = netfn , command = command , bridge_request = bridge_request , data = data , delay_xmit = delay_xmit , retry = retry , timeout = timeout ) if 'error' in rsp : raise exc . IpmiException ( rsp [ 'error' ] , rsp [ 'code' ] ) rsp [ 'data' ] = buffer ( rsp [ 'data' ] ) return rsp | Send raw ipmi command to BMC raising exception on error | 151 | 11 |
247,945 | def raw_command ( self , netfn , command , bridge_request = ( ) , data = ( ) , delay_xmit = None , retry = True , timeout = None ) : rsp = self . ipmi_session . raw_command ( netfn = netfn , command = command , bridge_request = bridge_request , data = data , delay_xmit = delay_xmit , retry = retry , timeout = timeout ) if 'data' in rsp : rsp [ 'data' ] = list ( rsp [ 'data' ] ) return rsp | Send raw ipmi command to BMC | 126 | 7 |
247,946 | def get_power ( self ) : response = self . raw_command ( netfn = 0 , command = 1 ) if 'error' in response : raise exc . IpmiException ( response [ 'error' ] ) assert ( response [ 'command' ] == 1 and response [ 'netfn' ] == 1 ) powerstate = 'on' if ( response [ 'data' ] [ 0 ] & 1 ) else 'off' return { 'powerstate' : powerstate } | Get current power state of the managed system | 102 | 8 |
247,947 | def get_event_log ( self , clear = False ) : self . oem_init ( ) return sel . EventHandler ( self . init_sdr ( ) , self ) . fetch_sel ( self , clear ) | Retrieve the log of events optionally clearing | 49 | 8 |
247,948 | def decode_pet ( self , specifictrap , petdata ) : self . oem_init ( ) return sel . EventHandler ( self . init_sdr ( ) , self ) . decode_pet ( specifictrap , petdata ) | Decode PET to an event | 55 | 6 |
247,949 | def get_inventory_descriptions ( self ) : yield "System" self . init_sdr ( ) for fruid in sorted ( self . _sdr . fru ) : yield self . _sdr . fru [ fruid ] . fru_name self . oem_init ( ) for compname in self . _oem . get_oem_inventory_descriptions ( ) : yield compname | Retrieve list of things that could be inventoried | 89 | 10 |
247,950 | def get_inventory_of_component ( self , component ) : self . oem_init ( ) if component == 'System' : return self . _get_zero_fru ( ) self . init_sdr ( ) for fruid in self . _sdr . fru : if self . _sdr . fru [ fruid ] . fru_name == component : return self . _oem . process_fru ( fru . FRU ( ipmicmd = self , fruid = fruid , sdr = self . _sdr . fru [ fruid ] ) . info , component ) return self . _oem . get_inventory_of_component ( component ) | Retrieve inventory of a component | 146 | 6 |
247,951 | def get_inventory ( self ) : self . oem_init ( ) yield ( "System" , self . _get_zero_fru ( ) ) self . init_sdr ( ) for fruid in sorted ( self . _sdr . fru ) : fruinf = fru . FRU ( ipmicmd = self , fruid = fruid , sdr = self . _sdr . fru [ fruid ] ) . info if fruinf is not None : fruinf = self . _oem . process_fru ( fruinf , self . _sdr . fru [ fruid ] . fru_name ) yield ( self . _sdr . fru [ fruid ] . fru_name , fruinf ) for componentpair in self . _oem . get_oem_inventory ( ) : yield componentpair | Retrieve inventory of system | 177 | 5 |
247,952 | def get_health ( self ) : summary = { 'badreadings' : [ ] , 'health' : const . Health . Ok } fallbackreadings = [ ] try : self . oem_init ( ) fallbackreadings = self . _oem . get_health ( summary ) for reading in self . get_sensor_data ( ) : if reading . health != const . Health . Ok : summary [ 'health' ] |= reading . health summary [ 'badreadings' ] . append ( reading ) except exc . BypassGenericBehavior : pass if not summary [ 'badreadings' ] : summary [ 'badreadings' ] = fallbackreadings return summary | Summarize health of managed system | 149 | 7 |
247,953 | def get_sensor_reading ( self , sensorname ) : self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : if self . _sdr . sensors [ sensor ] . name == sensorname : rsp = self . raw_command ( command = 0x2d , netfn = 4 , data = ( sensor , ) ) if 'error' in rsp : raise exc . IpmiException ( rsp [ 'error' ] , rsp [ 'code' ] ) return self . _sdr . sensors [ sensor ] . decode_sensor_reading ( rsp [ 'data' ] ) self . oem_init ( ) return self . _oem . get_sensor_reading ( sensorname ) | Get a sensor reading by name | 173 | 6 |
247,954 | def _fetch_lancfg_param ( self , channel , param , prefixlen = False ) : fetchcmd = bytearray ( ( channel , param , 0 , 0 ) ) fetched = self . xraw_command ( 0xc , 2 , data = fetchcmd ) fetchdata = fetched [ 'data' ] if ord ( fetchdata [ 0 ] ) != 17 : return None if len ( fetchdata ) == 5 : # IPv4 address if prefixlen : return _mask_to_cidr ( fetchdata [ 1 : ] ) else : ip = socket . inet_ntoa ( fetchdata [ 1 : ] ) if ip == '0.0.0.0' : return None return ip elif len ( fetchdata ) == 7 : # MAC address mac = '{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}' . format ( * bytearray ( fetchdata [ 1 : ] ) ) if mac == '00:00:00:00:00:00' : return None return mac elif len ( fetchdata ) == 2 : return ord ( fetchdata [ 1 ] ) else : raise Exception ( "Unrecognized data format " + repr ( fetchdata ) ) | Internal helper for fetching lan cfg parameters | 284 | 9 |
247,955 | def set_net_configuration ( self , ipv4_address = None , ipv4_configuration = None , ipv4_gateway = None , channel = None ) : if channel is None : channel = self . get_network_channel ( ) if ipv4_configuration is not None : cmddata = [ channel , 4 , 0 ] if ipv4_configuration . lower ( ) == 'dhcp' : cmddata [ - 1 ] = 2 elif ipv4_configuration . lower ( ) == 'static' : cmddata [ - 1 ] = 1 else : raise Exception ( 'Unrecognized ipv4cfg parameter {0}' . format ( ipv4_configuration ) ) self . xraw_command ( netfn = 0xc , command = 1 , data = cmddata ) if ipv4_address is not None : netmask = None if '/' in ipv4_address : ipv4_address , prefix = ipv4_address . split ( '/' ) netmask = _cidr_to_mask ( int ( prefix ) ) cmddata = bytearray ( ( channel , 3 ) ) + socket . inet_aton ( ipv4_address ) self . xraw_command ( netfn = 0xc , command = 1 , data = cmddata ) if netmask is not None : cmddata = bytearray ( ( channel , 6 ) ) + netmask self . xraw_command ( netfn = 0xc , command = 1 , data = cmddata ) if ipv4_gateway is not None : cmddata = bytearray ( ( channel , 12 ) ) + socket . inet_aton ( ipv4_gateway ) self . xraw_command ( netfn = 0xc , command = 1 , data = cmddata ) | Set network configuration data . | 407 | 5 |
247,956 | def get_net_configuration ( self , channel = None , gateway_macs = True ) : if channel is None : channel = self . get_network_channel ( ) retdata = { } v4addr = self . _fetch_lancfg_param ( channel , 3 ) if v4addr is None : retdata [ 'ipv4_address' ] = None else : v4masklen = self . _fetch_lancfg_param ( channel , 6 , prefixlen = True ) retdata [ 'ipv4_address' ] = '{0}/{1}' . format ( v4addr , v4masklen ) v4cfgmethods = { 0 : 'Unspecified' , 1 : 'Static' , 2 : 'DHCP' , 3 : 'BIOS' , 4 : 'Other' , } retdata [ 'ipv4_configuration' ] = v4cfgmethods [ self . _fetch_lancfg_param ( channel , 4 ) ] retdata [ 'mac_address' ] = self . _fetch_lancfg_param ( channel , 5 ) retdata [ 'ipv4_gateway' ] = self . _fetch_lancfg_param ( channel , 12 ) retdata [ 'ipv4_backup_gateway' ] = self . _fetch_lancfg_param ( channel , 14 ) if gateway_macs : retdata [ 'ipv4_gateway_mac' ] = self . _fetch_lancfg_param ( channel , 13 ) retdata [ 'ipv4_backup_gateway_mac' ] = self . _fetch_lancfg_param ( channel , 15 ) self . oem_init ( ) self . _oem . add_extra_net_configuration ( retdata ) return retdata | Get network configuration data | 408 | 4 |
247,957 | def get_sensor_data ( self ) : self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : rsp = self . raw_command ( command = 0x2d , netfn = 4 , data = ( sensor , ) ) if 'error' in rsp : if rsp [ 'code' ] == 203 : # Sensor does not exist, optional dev continue raise exc . IpmiException ( rsp [ 'error' ] , code = rsp [ 'code' ] ) yield self . _sdr . sensors [ sensor ] . decode_sensor_reading ( rsp [ 'data' ] ) self . oem_init ( ) for reading in self . _oem . get_sensor_data ( ) : yield reading | Get sensor reading objects | 175 | 4 |
247,958 | def get_sensor_descriptions ( self ) : self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : yield { 'name' : self . _sdr . sensors [ sensor ] . name , 'type' : self . _sdr . sensors [ sensor ] . sensor_type } self . oem_init ( ) for sensor in self . _oem . get_sensor_descriptions ( ) : yield sensor | Get available sensor names | 108 | 4 |
247,959 | def get_network_channel ( self ) : if self . _netchannel is None : for channel in chain ( ( 0xe , ) , range ( 1 , 0xc ) ) : try : rsp = self . xraw_command ( netfn = 6 , command = 0x42 , data = ( channel , ) ) except exc . IpmiException as ie : if ie . ipmicode == 0xcc : # We have hit an invalid channel, move on to next # candidate continue else : raise chantype = ord ( rsp [ 'data' ] [ 1 ] ) & 0b1111111 if chantype in ( 4 , 6 ) : try : # Some implementations denote an inactive channel # by refusing to do parameter retrieval if channel != 0xe : # skip checking if channel is active if we are # actively using the channel self . xraw_command ( netfn = 0xc , command = 2 , data = ( channel , 5 , 0 , 0 ) ) # If still here, the channel seems serviceable... # However some implementations may still have # ambiguous channel info, that will need to be # picked up on an OEM extension... self . _netchannel = ord ( rsp [ 'data' ] [ 0 ] ) & 0b1111 break except exc . IpmiException as ie : # This means the attempt to fetch parameter 5 failed, # therefore move on to next candidate channel continue return self . _netchannel | Get a reasonable default network channel . | 301 | 7 |
247,960 | def get_alert_destination_count ( self , channel = None ) : if channel is None : channel = self . get_network_channel ( ) rqdata = ( channel , 0x11 , 0 , 0 ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = rqdata ) return ord ( rsp [ 'data' ] [ 1 ] ) | Get the number of supported alert destinations | 88 | 7 |
247,961 | def get_alert_destination ( self , destination = 0 , channel = None ) : destinfo = { } if channel is None : channel = self . get_network_channel ( ) rqdata = ( channel , 18 , destination , 0 ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = rqdata ) dtype , acktimeout , retries = struct . unpack ( 'BBB' , rsp [ 'data' ] [ 2 : ] ) destinfo [ 'acknowledge_required' ] = dtype & 0b10000000 == 0b10000000 # Ignore destination type for now... if destinfo [ 'acknowledge_required' ] : destinfo [ 'acknowledge_timeout' ] = acktimeout destinfo [ 'retries' ] = retries rqdata = ( channel , 19 , destination , 0 ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = rqdata ) if ord ( rsp [ 'data' ] [ 2 ] ) & 0b11110000 == 0 : destinfo [ 'address_format' ] = 'ipv4' destinfo [ 'address' ] = socket . inet_ntoa ( rsp [ 'data' ] [ 4 : 8 ] ) elif ord ( rsp [ 'data' ] [ 2 ] ) & 0b11110000 == 0b10000 : destinfo [ 'address_format' ] = 'ipv6' destinfo [ 'address' ] = socket . inet_ntop ( socket . AF_INET6 , rsp [ 'data' ] [ 3 : ] ) return destinfo | Get alert destination | 365 | 3 |
247,962 | def clear_alert_destination ( self , destination = 0 , channel = None ) : if channel is None : channel = self . get_network_channel ( ) self . set_alert_destination ( '0.0.0.0' , False , 0 , 0 , destination , channel ) | Clear an alert destination | 64 | 4 |
247,963 | def set_alert_community ( self , community , channel = None ) : if channel is None : channel = self . get_network_channel ( ) community = community . encode ( 'utf-8' ) community += b'\x00' * ( 18 - len ( community ) ) cmddata = bytearray ( ( channel , 16 ) ) cmddata += community self . xraw_command ( netfn = 0xc , command = 1 , data = cmddata ) | Set the community string for alerts | 104 | 6 |
247,964 | def _assure_alert_policy ( self , channel , destination ) : # First we do a get PEF configuration parameters to get the count # of entries. We have no guarantee that the meaningful data will # be contiguous rsp = self . xraw_command ( netfn = 4 , command = 0x13 , data = ( 8 , 0 , 0 ) ) numpol = ord ( rsp [ 'data' ] [ 1 ] ) desiredchandest = ( channel << 4 ) | destination availpolnum = None for polnum in range ( 1 , numpol + 1 ) : currpol = self . xraw_command ( netfn = 4 , command = 0x13 , data = ( 9 , polnum , 0 ) ) polidx , chandest = struct . unpack_from ( '>BB' , currpol [ 'data' ] [ 2 : 4 ] ) if not polidx & 0b1000 : if availpolnum is None : availpolnum = polnum continue if chandest == desiredchandest : return True # If chandest did not equal desiredchandest ever, we need to use a slot if availpolnum is None : raise Exception ( "No available alert policy entry" ) # 24 = 1 << 4 | 8 # 1 == set to which this rule belongs # 8 == 0b1000, in other words, enable this policy, always send to # indicated destination self . xraw_command ( netfn = 4 , command = 0x12 , data = ( 9 , availpolnum , 24 , desiredchandest , 0 ) ) | Make sure an alert policy exists | 347 | 6 |
247,965 | def get_alert_community ( self , channel = None ) : if channel is None : channel = self . get_network_channel ( ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = ( channel , 16 , 0 , 0 ) ) return rsp [ 'data' ] [ 1 : ] . partition ( '\x00' ) [ 0 ] | Get the current community string for alerts | 86 | 7 |
247,966 | def set_alert_destination ( self , ip = None , acknowledge_required = None , acknowledge_timeout = None , retries = None , destination = 0 , channel = None ) : if channel is None : channel = self . get_network_channel ( ) if ip is not None : destdata = bytearray ( ( channel , 19 , destination ) ) try : parsedip = socket . inet_aton ( ip ) destdata . extend ( ( 0 , 0 ) ) destdata . extend ( parsedip ) destdata . extend ( b'\x00\x00\x00\x00\x00\x00' ) except socket . error : if self . _supports_standard_ipv6 : parsedip = socket . inet_pton ( socket . AF_INET6 , ip ) destdata . append ( 0b10000000 ) destdata . extend ( parsedip ) else : destdata = None self . oem_init ( ) self . _oem . set_alert_ipv6_destination ( ip , destination , channel ) if destdata : self . xraw_command ( netfn = 0xc , command = 1 , data = destdata ) if ( acknowledge_required is not None or retries is not None or acknowledge_timeout is not None ) : currtype = self . xraw_command ( netfn = 0xc , command = 2 , data = ( channel , 18 , destination , 0 ) ) if currtype [ 'data' ] [ 0 ] != b'\x11' : raise exc . PyghmiException ( "Unknown parameter format" ) currtype = bytearray ( currtype [ 'data' ] [ 1 : ] ) if acknowledge_required is not None : if acknowledge_required : currtype [ 1 ] |= 0b10000000 else : currtype [ 1 ] &= 0b1111111 if acknowledge_timeout is not None : currtype [ 2 ] = acknowledge_timeout if retries is not None : currtype [ 3 ] = retries destreq = bytearray ( ( channel , 18 ) ) destreq . extend ( currtype ) self . xraw_command ( netfn = 0xc , command = 1 , data = destreq ) if not ip == '0.0.0.0' : self . _assure_alert_policy ( channel , destination ) | Configure one or more parameters of an alert destination | 515 | 10 |
247,967 | def get_hostname ( self ) : self . oem_init ( ) try : return self . _oem . get_hostname ( ) except exc . UnsupportedFunctionality : # Use the DCMI MCI field as a fallback, since it's the closest # thing in the IPMI Spec for this return self . get_mci ( ) | Get the hostname used by the BMC in various contexts | 76 | 11 |
247,968 | def set_hostname ( self , hostname ) : self . oem_init ( ) try : return self . _oem . set_hostname ( hostname ) except exc . UnsupportedFunctionality : return self . set_mci ( hostname ) | Set the hostname to be used by the BMC in various contexts . | 56 | 14 |
247,969 | def get_channel_access ( self , channel = None , read_mode = 'volatile' ) : if channel is None : channel = self . get_network_channel ( ) data = [ ] data . append ( channel & 0b00001111 ) b = 0 read_modes = { 'non_volatile' : 1 , 'volatile' : 2 , } b |= ( read_modes [ read_mode ] << 6 ) & 0b11000000 data . append ( b ) response = self . raw_command ( netfn = 0x06 , command = 0x41 , data = data ) if 'error' in response : raise Exception ( response [ 'error' ] ) data = response [ 'data' ] if len ( data ) != 2 : raise Exception ( 'expecting 2 data bytes' ) r = { } r [ 'alerting' ] = data [ 0 ] & 0b10000000 > 0 r [ 'per_msg_auth' ] = data [ 0 ] & 0b01000000 > 0 r [ 'user_level_auth' ] = data [ 0 ] & 0b00100000 > 0 access_modes = { 0 : 'disabled' , 1 : 'pre_boot' , 2 : 'always' , 3 : 'shared' } r [ 'access_mode' ] = access_modes [ data [ 0 ] & 0b00000011 ] privilege_levels = { 0 : 'reserved' , 1 : 'callback' , 2 : 'user' , 3 : 'operator' , 4 : 'administrator' , 5 : 'proprietary' , # 0x0F: 'no_access' } r [ 'privilege_level' ] = privilege_levels [ data [ 1 ] & 0b00001111 ] return r | Get channel access | 383 | 3 |
247,970 | def get_channel_info ( self , channel = None ) : if channel is None : channel = self . get_network_channel ( ) data = [ ] data . append ( channel & 0b00001111 ) response = self . raw_command ( netfn = 0x06 , command = 0x42 , data = data ) if 'error' in response : raise Exception ( response [ 'error' ] ) data = response [ 'data' ] if len ( data ) != 9 : raise Exception ( 'expecting 10 data bytes got: {0}' . format ( data ) ) r = { } r [ 'Actual channel' ] = data [ 0 ] & 0b00000111 channel_medium_types = { 0 : 'reserved' , 1 : 'IPMB' , 2 : 'ICMB v1.0' , 3 : 'ICMB v0.9' , 4 : '802.3 LAN' , 5 : 'Asynch. Serial/Modem (RS-232)' , 6 : 'Other LAN' , 7 : 'PCI SMBus' , 8 : 'SMBus v1.0/1.1' , 9 : 'SMBus v2.0' , 0x0a : 'reserved for USB 1.x' , 0x0b : 'reserved for USB 2.x' , 0x0c : 'System Interface (KCS, SMIC, or BT)' , # 60h-7Fh: OEM # all other reserved } t = data [ 1 ] & 0b01111111 if t in channel_medium_types : r [ 'Channel Medium type' ] = channel_medium_types [ t ] else : r [ 'Channel Medium type' ] = 'OEM {:02X}' . format ( t ) r [ '5-bit Channel IPMI Messaging Protocol Type' ] = data [ 2 ] & 0b00001111 session_supports = { 0 : 'no_session' , 1 : 'single' , 2 : 'multi' , 3 : 'auto' } r [ 'session_support' ] = session_supports [ ( data [ 3 ] & 0b11000000 ) >> 6 ] r [ 'active_session_count' ] = data [ 3 ] & 0b00111111 r [ 'Vendor ID' ] = [ data [ 4 ] , data [ 5 ] , data [ 6 ] ] r [ 'Auxiliary Channel Info' ] = [ data [ 7 ] , data [ 8 ] ] return r | Get channel info | 540 | 3 |
247,971 | def get_firmware ( self , components = ( ) ) : self . oem_init ( ) mcinfo = self . xraw_command ( netfn = 6 , command = 1 ) bmcver = '{0}.{1}' . format ( ord ( mcinfo [ 'data' ] [ 2 ] ) , hex ( ord ( mcinfo [ 'data' ] [ 3 ] ) ) [ 2 : ] ) return self . _oem . get_oem_firmware ( bmcver , components ) | Retrieve OEM Firmware information | 114 | 6 |
247,972 | def update_firmware ( self , file , data = None , progress = None , bank = None ) : self . oem_init ( ) if progress is None : progress = lambda x : True return self . _oem . update_firmware ( file , data , progress , bank ) | Send file to BMC to perform firmware update | 64 | 8 |
247,973 | def attach_remote_media ( self , url , username = None , password = None ) : self . oem_init ( ) return self . _oem . attach_remote_media ( url , username , password ) | Attach remote media by url | 47 | 5 |
247,974 | def upload_media ( self , filename , progress = None ) : self . oem_init ( ) return self . _oem . upload_media ( filename , progress ) | Upload a file to be hosted on the target BMC | 37 | 10 |
247,975 | def process_event ( self , event , ipmicmd , seldata ) : event [ 'oem_handler' ] = None evdata = event [ 'event_data_bytes' ] if evdata [ 0 ] & 0b11000000 == 0b10000000 : event [ 'oem_byte2' ] = evdata [ 1 ] if evdata [ 0 ] & 0b110000 == 0b100000 : event [ 'oem_byte3' ] = evdata [ 2 ] | Modify an event according with OEM understanding . | 108 | 9 |
247,976 | def _got_cons_input ( self , handle ) : self . _addpendingdata ( handle . read ( ) ) if not self . awaitingack : self . _sendpendingoutput ( ) | Callback for handle events detected by ipmi session | 43 | 9 |
247,977 | def close ( self ) : if self . ipmi_session : self . ipmi_session . unregister_keepalive ( self . keepaliveid ) if self . activated : try : self . ipmi_session . raw_command ( netfn = 6 , command = 0x49 , data = ( 1 , 1 , 0 , 0 , 0 , 0 ) ) except exc . IpmiException : # if underlying ipmi session is not working, then # run with the implicit success pass | Shut down an SOL session | 106 | 5 |
247,978 | def _got_sol_payload ( self , payload ) : # TODO(jbjohnso) test cases to throw some likely scenarios at functions # for example, retry with new data, retry with no new data # retry with unexpected sequence number if type ( payload ) == dict : # we received an error condition self . activated = False self . _print_error ( payload ) return newseq = payload [ 0 ] & 0b1111 ackseq = payload [ 1 ] & 0b1111 ackcount = payload [ 2 ] nacked = payload [ 3 ] & 0b1000000 breakdetected = payload [ 3 ] & 0b10000 # for now, ignore overrun. I assume partial NACK for this reason or # for no reason would be treated the same, new payload with partial # data. remdata = "" remdatalen = 0 flag = 0 if not self . poweredon : flag |= 0b1100000 if not self . activated : flag |= 0b1010000 if newseq != 0 : # this packet at least has some data to send to us.. if len ( payload ) > 4 : remdatalen = len ( payload [ 4 : ] ) # store remote len before dupe # retry logic, we must ack *this* many even if it is # a retry packet with new partial data remdata = bytes ( payload [ 4 : ] ) if newseq == self . remseq : # it is a retry, but could have new data if remdatalen > self . lastsize : remdata = bytes ( remdata [ 4 + self . lastsize : ] ) else : # no new data... remdata = "" else : # TODO(jbjohnso) what if remote sequence number is wrong?? self . remseq = newseq self . lastsize = remdatalen ackpayload = bytearray ( ( 0 , self . remseq , remdatalen , flag ) ) # Why not put pending data into the ack? because it's rare # and might be hard to decide what to do in the context of # retry situation try : self . send_payload ( ackpayload , retry = False ) except exc . IpmiException : # if the session is broken, then close the SOL session self . close ( ) if remdata : # Do not subject callers to empty data self . _print_data ( remdata ) if self . myseq != 0 and ackseq == self . myseq : # the bmc has something # to say about last xmit self . awaitingack = False if nacked and not breakdetected : # the BMC was in some way unhappy newtext = self . lastpayload [ 4 + ackcount : ] with self . outputlock : if ( self . pendingoutput and not isinstance ( self . pendingoutput [ 0 ] , dict ) ) : self . pendingoutput [ 0 ] = newtext + self . pendingoutput [ 0 ] else : self . pendingoutput = [ newtext ] + self . pendingoutput # self._sendpendingoutput() checks len(self._sendpendingoutput) self . _sendpendingoutput ( ) elif ackseq != 0 and self . awaitingack : # if an ack packet came in, but did not match what we # expected, retry our payload now. # the situation that was triggered was a senseless retry # when data came in while we xmitted. In theory, a BMC # should handle a retry correctly, but some do not, so # try to mitigate by avoiding overeager retries # occasional retry of a packet # sooner than timeout suggests is evidently a big deal self . send_payload ( payload = self . lastpayload ) | SOL payload callback | 795 | 4 |
247,979 | def is_fpc ( self ) : if self . has_imm or self . has_xcc : return None if self . _fpc_variant is not None : return self . _fpc_variant fpc_ids = ( ( 19046 , 32 , 1063 ) , ( 20301 , 32 , 462 ) ) smm_id = ( 19046 , 32 , 1180 ) currid = ( self . oemid [ 'manufacturer_id' ] , self . oemid [ 'device_id' ] , self . oemid [ 'product_id' ] ) if currid in fpc_ids : self . _fpc_variant = 6 elif currid == smm_id : self . _fpc_variant = 2 return self . _fpc_variant | True if the target is a Lenovo nextscale fan power controller | 179 | 12 |
247,980 | def has_tsm ( self ) : if ( self . oemid [ 'manufacturer_id' ] == 19046 and self . oemid [ 'device_id' ] == 32 ) : try : self . ipmicmd . xraw_command ( netfn = 0x3a , command = 0xf ) except pygexc . IpmiException as ie : if ie . ipmicode == 193 : return False raise return True return False | True if this particular server have a TSM based service processor | 98 | 12 |
247,981 | def set_oem_capping_enabled ( self , enable ) : # 1 - Enable power capping(default) if enable : statecode = 1 # 0 - Disable power capping else : statecode = 0 if self . has_tsm : self . ipmicmd . xraw_command ( netfn = 0x3a , command = 0x1a , data = ( 3 , statecode ) ) return True | Set PSU based power capping | 91 | 6 |
247,982 | def decode_wireformat_uuid ( rawguid ) : if isinstance ( rawguid , list ) : rawguid = bytearray ( rawguid ) lebytes = struct . unpack_from ( '<IHH' , buffer ( rawguid [ : 8 ] ) ) bebytes = struct . unpack_from ( '>HHI' , buffer ( rawguid [ 8 : ] ) ) return '{0:08X}-{1:04X}-{2:04X}-{3:04X}-{4:04X}{5:08X}' . format ( lebytes [ 0 ] , lebytes [ 1 ] , lebytes [ 2 ] , bebytes [ 0 ] , bebytes [ 1 ] , bebytes [ 2 ] ) | Decode a wire format UUID | 173 | 7 |
247,983 | def urlsplit ( url ) : proto , rest = url . split ( ':' , 1 ) host = '' if rest [ : 2 ] == '//' : host , rest = rest [ 2 : ] . split ( '/' , 1 ) rest = '/' + rest return proto , host , rest | Split an arbitrary url into protocol host rest | 65 | 8 |
247,984 | def get_ipv4 ( hostname ) : addrinfo = socket . getaddrinfo ( hostname , None , socket . AF_INET , socket . SOCK_STREAM ) return [ addrinfo [ x ] [ 4 ] [ 0 ] for x in range ( len ( addrinfo ) ) ] | Get list of ipv4 addresses for hostname | 65 | 10 |
247,985 | def _aespad ( data ) : currlen = len ( data ) + 1 # need to count the pad length field as well neededpad = currlen % 16 if neededpad : # if it happens to be zero, hurray, but otherwise invert the # sense of the padding neededpad = 16 - neededpad padval = 1 pad = bytearray ( neededpad ) while padval <= neededpad : pad [ padval - 1 ] = padval padval += 1 pad . append ( neededpad ) return pad | ipmi demands a certain pad scheme per table 13 - 20 AES - CBC encrypted payload fields . | 113 | 19 |
247,986 | def _make_bridge_request_msg ( self , channel , netfn , command ) : head = bytearray ( ( constants . IPMI_BMC_ADDRESS , constants . netfn_codes [ 'application' ] << 2 ) ) check_sum = _checksum ( * head ) # NOTE(fengqian): according IPMI Figure 14-11, rqSWID is set to 81h boday = bytearray ( ( 0x81 , self . seqlun , constants . IPMI_SEND_MESSAGE_CMD , 0x40 | channel ) ) # NOTE(fengqian): Track request self . _add_request_entry ( ( constants . netfn_codes [ 'application' ] + 1 , self . seqlun , constants . IPMI_SEND_MESSAGE_CMD ) ) return head + bytearray ( ( check_sum , ) ) + boday | This function generate message for bridge request . It is a part of ipmi payload . | 208 | 17 |
247,987 | def wait_for_rsp ( cls , timeout = None , callout = True ) : global iosockets # Assume: # Instance A sends request to packet B # Then Instance C sends request to BMC D # BMC D was faster, so data comes back before BMC B # Instance C gets to go ahead of Instance A, because # Instance C can get work done, but instance A cannot curtime = _monotonic_time ( ) # There ar a number of parties that each has their own timeout # The caller can specify a deadline in timeout argument # each session with active outbound payload has callback to # handle retry/timout error # each session that is 'alive' wants to send a keepalive ever so often. # We want to make sure the most strict request is honored and block for # no more time than that, so that whatever part(ies) need to service in # a deadline, will be honored if timeout != 0 : with util . protect ( WAITING_SESSIONS ) : for session , parms in dictitems ( cls . waiting_sessions ) : if parms [ 'timeout' ] <= curtime : timeout = 0 # exit after one guaranteed pass break if ( timeout is not None and timeout < parms [ 'timeout' ] - curtime ) : continue # timeout smaller than the current session # needs timeout = parms [ 'timeout' ] - curtime # set new timeout # value with util . protect ( KEEPALIVE_SESSIONS ) : for session , parms in dictitems ( cls . keepalive_sessions ) : if parms [ 'timeout' ] <= curtime : timeout = 0 break if ( timeout is not None and timeout < parms [ 'timeout' ] - curtime ) : continue timeout = parms [ 'timeout' ] - curtime # If the loop above found no sessions wanting *and* the caller had no # timeout, exit function. In this case there is no way a session # could be waiting so we can always return 0 while cls . iterwaiters : waiter = cls . iterwaiters . pop ( ) waiter ( { 'success' : True } ) # cause a quick exit from the event loop iteration for calling code # to be able to reasonably set up for the next iteration before # a long select comes along if timeout is not None : timeout = 0 if timeout is None : return 0 if _poller ( timeout = timeout ) : while sessionqueue : relsession = sessionqueue . popleft ( ) relsession . process_pktqueue ( ) sessionstodel = [ ] sessionstokeepalive = [ ] with util . protect ( KEEPALIVE_SESSIONS ) : for session , parms in dictitems ( cls . keepalive_sessions ) : # if the session is busy inside a command, defer invoking # keepalive until incommand is no longer the case if parms [ 'timeout' ] < curtime and not session . _isincommand ( ) : cls . keepalive_sessions [ session ] [ 'timeout' ] = _monotonic_time ( ) + MAX_IDLE - ( random . random ( ) * 4.9 ) sessionstokeepalive . append ( session ) for session in sessionstokeepalive : session . _keepalive ( ) with util . protect ( WAITING_SESSIONS ) : for session , parms in dictitems ( cls . waiting_sessions ) : if parms [ 'timeout' ] < curtime : # timeout has expired, time to # give up on it and trigger timeout # response in the respective session # defer deletion until after loop sessionstodel . append ( session ) # to avoid confusing the for loop for session in sessionstodel : cls . waiting_sessions . pop ( session , None ) # one loop iteration to make sure recursion doesn't induce # redundant timeouts for session in sessionstodel : session . _timedout ( ) return len ( cls . waiting_sessions ) | IPMI Session Event loop iteration | 869 | 6 |
247,988 | def register_keepalive ( self , cmd , callback ) : regid = random . random ( ) if self . _customkeepalives is None : self . _customkeepalives = { regid : ( cmd , callback ) } else : while regid in self . _customkeepalives : regid = random . random ( ) self . _customkeepalives [ regid ] = ( cmd , callback ) return regid | Register custom keepalive IPMI command | 93 | 8 |
247,989 | def _keepalive ( self ) : try : keptalive = False if self . _customkeepalives : kaids = list ( self . _customkeepalives . keys ( ) ) for keepalive in kaids : try : cmd , callback = self . _customkeepalives [ keepalive ] except TypeError : # raw_command made customkeepalives None break except KeyError : # raw command ultimately caused a keepalive to # deregister continue if callable ( cmd ) : cmd ( ) continue keptalive = True cmd [ 'callback' ] = self . _keepalive_wrapper ( callback ) self . raw_command ( * * cmd ) if not keptalive : if self . incommand : # if currently in command, no cause to keepalive return self . raw_command ( netfn = 6 , command = 1 , callback = self . _keepalive_wrapper ( None ) ) except exc . IpmiException : self . _mark_broken ( ) | Performs a keepalive to avoid idle disconnect | 218 | 10 |
247,990 | def download ( self , url , file ) : if isinstance ( file , str ) or isinstance ( file , unicode ) : file = open ( file , 'wb' ) webclient = self . dupe ( ) webclient . request ( 'GET' , url ) rsp = webclient . getresponse ( ) self . _currdl = rsp self . _dlfile = file for chunk in iter ( lambda : rsp . read ( 16384 ) , '' ) : file . write ( chunk ) self . _currdl = None file . close ( ) | Download a file to filename or file object | 123 | 8 |
247,991 | def upload ( self , url , filename , data = None , formname = None , otherfields = ( ) ) : if data is None : data = open ( filename , 'rb' ) self . _upbuffer = StringIO . StringIO ( get_upload_form ( filename , data , formname , otherfields ) ) ulheaders = self . stdheaders . copy ( ) ulheaders [ 'Content-Type' ] = 'multipart/form-data; boundary=' + BND ulheaders [ 'Content-Length' ] = len ( uploadforms [ filename ] ) self . ulsize = len ( uploadforms [ filename ] ) webclient = self . dupe ( ) webclient . request ( 'POST' , url , self . _upbuffer , ulheaders ) rsp = webclient . getresponse ( ) # peer updates in progress should already have pointers, # subsequent transactions will cause memory to needlessly double, # but easiest way to keep memory relatively low try : del uploadforms [ filename ] except KeyError : # something could have already deleted it pass self . rspstatus = rsp . status if rsp . status != 200 : raise Exception ( 'Unexpected response in file upload: ' + rsp . read ( ) ) return rsp . read ( ) | Upload a file to the url | 270 | 6 |
247,992 | def parse_inventory_category_entry ( raw , fields ) : r = raw obj = { } bytes_read = 0 discard = False for field in fields : value = struct . unpack_from ( field . fmt , r ) [ 0 ] read = struct . calcsize ( field . fmt ) bytes_read += read r = r [ read : ] # If this entry is not actually present, just parse and then discard it if field . presence and not bool ( value ) : discard = True if not field . include : continue if ( field . fmt [ - 1 ] == "s" ) : value = value . rstrip ( "\x00" ) if ( field . mapper and value in field . mapper ) : value = field . mapper [ value ] if ( field . valuefunc ) : value = field . valuefunc ( value ) if not field . multivaluefunc : obj [ field . name ] = value else : for key in value : obj [ key ] = value [ key ] if discard : obj = None return bytes_read , obj | Parses one entry in an inventory category . | 225 | 10 |
247,993 | def sessionless_data ( self , data , sockaddr ) : if len ( data ) < 22 : return data = bytearray ( data ) if not ( data [ 0 ] == 6 and data [ 2 : 4 ] == b'\xff\x07' ) : # not ipmi return if data [ 4 ] == 6 : # ipmi 2 payload... payloadtype = data [ 5 ] if payloadtype not in ( 0 , 16 ) : return if payloadtype == 16 : # new session to handle conversation ServerSession ( self . authdata , self . kg , sockaddr , self . serversocket , data [ 16 : ] , self . uuid , bmc = self ) return # ditch two byte, because ipmi2 header is two # bytes longer than ipmi1 (payload type added, payload length 2). data = data [ 2 : ] myaddr , netfnlun = struct . unpack ( '2B' , bytes ( data [ 14 : 16 ] ) ) netfn = ( netfnlun & 0b11111100 ) >> 2 mylun = netfnlun & 0b11 if netfn == 6 : # application request if data [ 19 ] == 0x38 : # cmd = get channel auth capabilities verchannel , level = struct . unpack ( '2B' , bytes ( data [ 20 : 22 ] ) ) version = verchannel & 0b10000000 if version != 0b10000000 : return channel = verchannel & 0b1111 if channel != 0xe : return ( clientaddr , clientlun ) = struct . unpack ( 'BB' , bytes ( data [ 17 : 19 ] ) ) clientseq = clientlun >> 2 clientlun &= 0b11 # Lun is only the least significant bits level &= 0b1111 self . send_auth_cap ( myaddr , mylun , clientaddr , clientlun , clientseq , sockaddr ) | Examines unsolocited packet and decides appropriate action . | 408 | 12 |
247,994 | def set_kg ( self , kg ) : try : self . kg = kg . encode ( 'utf-8' ) except AttributeError : self . kg = kg | Sets the Kg for the BMC to use | 36 | 10 |
247,995 | def source_debianize_name ( name ) : name = name . replace ( '_' , '-' ) name = name . replace ( '.' , '-' ) name = name . lower ( ) return name | make name acceptable as a Debian source package name | 45 | 9 |
247,996 | def get_date_822 ( ) : cmd = '/bin/date' if not os . path . exists ( cmd ) : raise ValueError ( '%s command does not exist.' % cmd ) args = [ cmd , '-R' ] result = get_cmd_stdout ( args ) . strip ( ) result = normstr ( result ) return result | return output of 822 - date command | 77 | 8 |
247,997 | def make_tarball ( tarball_fname , directory , cwd = None ) : if tarball_fname . endswith ( '.gz' ) : opts = 'czf' else : opts = 'cf' args = [ '/bin/tar' , opts , tarball_fname , directory ] process_command ( args , cwd = cwd ) | create a tarball from a directory | 83 | 7 |
247,998 | def expand_tarball ( tarball_fname , cwd = None ) : if tarball_fname . endswith ( '.gz' ) : opts = 'xzf' elif tarball_fname . endswith ( '.bz2' ) : opts = 'xjf' else : opts = 'xf' args = [ '/bin/tar' , opts , tarball_fname ] process_command ( args , cwd = cwd ) | expand a tarball | 107 | 5 |
247,999 | def expand_zip ( zip_fname , cwd = None ) : unzip_path = '/usr/bin/unzip' if not os . path . exists ( unzip_path ) : log . error ( 'ERROR: {} does not exist' . format ( unzip_path ) ) sys . exit ( 1 ) args = [ unzip_path , zip_fname ] # Does it have a top dir res = subprocess . Popen ( [ args [ 0 ] , '-l' , args [ 1 ] ] , cwd = cwd , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) contents = [ ] for line in res . stdout . readlines ( ) [ 3 : - 2 ] : contents . append ( line . split ( ) [ - 1 ] ) commonprefix = os . path . commonprefix ( contents ) if not commonprefix : extdir = os . path . join ( cwd , os . path . basename ( zip_fname [ : - 4 ] ) ) args . extend ( [ '-d' , os . path . abspath ( extdir ) ] ) process_command ( args , cwd = cwd ) | expand a zip | 261 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.