idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
28,200 | def compile_mof_string ( self , mof_str , namespace = None , search_paths = None , verbose = None ) : namespace = namespace or self . default_namespace # if not self._validate_namespace(namespace): TODO # self.add_namespace(namespace) self . _validate_namespace ( namespace ) mofcomp = MOFCompiler ( _MockMOFWBEMConnection ( self ) , search_paths = search_paths , verbose = verbose ) mofcomp . compile_string ( mof_str , namespace ) | Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the mock repository . | 132 | 28 |
28,201 | def compile_dmtf_schema ( self , schema_version , schema_root_dir , class_names , use_experimental = False , namespace = None , verbose = False ) : schema = DMTFCIMSchema ( schema_version , schema_root_dir , use_experimental = use_experimental , verbose = verbose ) schema_mof = schema . build_schema_mof ( class_names ) search_paths = schema . schema_mof_dir self . compile_mof_string ( schema_mof , namespace = namespace , search_paths = [ search_paths ] , verbose = verbose ) | Compile the classes defined by class_names and their dependent classes from the DMTF CIM schema version defined by schema_version and keep the downloaded DMTF CIM schema in the directory defined by schema_dir . | 146 | 44 |
28,202 | def add_method_callback ( self , classname , methodname , method_callback , namespace = None , ) : if namespace is None : namespace = self . default_namespace # Validate namespace method_repo = self . _get_method_repo ( namespace ) if classname not in method_repo : method_repo [ classname ] = NocaseDict ( ) if methodname in method_repo [ classname ] : raise ValueError ( "Duplicate method specification" ) method_repo [ classname ] [ methodname ] = method_callback | Register a callback function for a CIM method that will be called when the CIM method is invoked via InvokeMethod . | 126 | 25 |
28,203 | def display_repository ( self , namespaces = None , dest = None , summary = False , output_format = 'mof' ) : if output_format == 'mof' : cmt_begin = '# ' cmt_end = '' elif output_format == 'xml' : cmt_begin = '<!-- ' cmt_end = ' ->' else : cmt_begin = '' cmt_end = '' if output_format not in OUTPUT_FORMATS : raise ValueError ( _format ( "Invalid output format definition {0!A}. " "{1!A} are valid." , output_format , OUTPUT_FORMATS ) ) _uprint ( dest , _format ( u"{0}========Mock Repo Display fmt={1} " u"namespaces={2} ========={3}\n" , cmt_begin , output_format , ( 'all' if namespaces is None else _format ( "{0!A}" , namespaces ) ) , cmt_end ) ) # get all namespaces repo_ns_set = set ( self . namespaces . keys ( ) ) if namespaces : if isinstance ( namespaces , six . string_types ) : namespaces = [ namespaces ] repo_ns_set = repo_ns_set . intersection ( set ( namespaces ) ) repo_ns_list = sorted ( list ( repo_ns_set ) ) for ns in repo_ns_list : _uprint ( dest , _format ( u"\n{0}NAMESPACE {1!A}{2}\n" , cmt_begin , ns , cmt_end ) ) self . _display_objects ( 'Qualifier Declarations' , self . qualifiers , ns , cmt_begin , cmt_end , dest = dest , summary = summary , output_format = output_format ) self . _display_objects ( 'Classes' , self . classes , ns , cmt_begin , cmt_end , dest = dest , summary = summary , output_format = output_format ) self . _display_objects ( 'Instances' , self . instances , ns , cmt_begin , cmt_end , dest = dest , summary = summary , output_format = output_format ) self . _display_objects ( 'Methods' , self . methods , ns , cmt_begin , cmt_end , dest = dest , summary = summary , output_format = output_format ) _uprint ( dest , u'============End Repository=================' ) | Display the namespaces and objects in the mock repository in one of multiple formats to a destination . | 554 | 19 |
28,204 | def _get_inst_repo ( self , namespace = None ) : if namespace is None : namespace = self . default_namespace return self . instances [ namespace ] | Test support method that returns instances from the repository with no processing . It uses the default namespace if input parameter for namespace is None | 36 | 25 |
28,205 | def _class_exists ( self , classname , namespace ) : class_repo = self . _get_class_repo ( namespace ) return classname in class_repo | Test if class defined by classname parameter exists in repository defined by namespace parameter . | 40 | 16 |
28,206 | def _remove_qualifiers ( obj ) : assert isinstance ( obj , ( CIMInstance , CIMClass ) ) obj . qualifiers = NocaseDict ( ) for prop in obj . properties : obj . properties [ prop ] . qualifiers = NocaseDict ( ) if isinstance ( obj , CIMClass ) : for method in obj . methods : obj . methods [ method ] . qualifiers = NocaseDict ( ) for param in obj . methods [ method ] . parameters : obj . methods [ method ] . parameters [ param ] . qualifiers = NocaseDict ( ) | Remove all qualifiers from the input objectwhere the object may be an CIMInstance or CIMClass . Removes qualifiers from the object and from properties methods and parameters | 127 | 33 |
28,207 | def _remove_classorigin ( obj ) : assert isinstance ( obj , ( CIMInstance , CIMClass ) ) for prop in obj . properties : obj . properties [ prop ] . class_origin = None if isinstance ( obj , CIMClass ) : for method in obj . methods : obj . methods [ method ] . class_origin = None | Remove all ClassOrigin attributes from the input object . The object may be a CIMInstance or CIMClass . | 75 | 23 |
28,208 | def _validate_namespace ( self , namespace ) : if namespace not in self . namespaces : raise CIMError ( CIM_ERR_INVALID_NAMESPACE , _format ( "Namespace does not exist in mock repository: {0!A}" , namespace ) ) | Validate whether a CIM namespace exists in the mock repository . | 64 | 13 |
28,209 | def _get_class_repo ( self , namespace ) : self . _validate_namespace ( namespace ) if namespace not in self . classes : self . classes [ namespace ] = NocaseDict ( ) return self . classes [ namespace ] | Returns the class repository for the specified CIM namespace within the mock repository . This is the original instance variable so any modifications will change the mock repository . | 54 | 30 |
28,210 | def _get_instance_repo ( self , namespace ) : self . _validate_namespace ( namespace ) if namespace not in self . instances : self . instances [ namespace ] = [ ] return self . instances [ namespace ] | Returns the instance repository for the specified CIM namespace within the mock repository . This is the original instance variable so any modifications will change the mock repository . | 49 | 30 |
28,211 | def _get_qualifier_repo ( self , namespace ) : self . _validate_namespace ( namespace ) if namespace not in self . qualifiers : self . qualifiers [ namespace ] = NocaseDict ( ) return self . qualifiers [ namespace ] | Returns the qualifier repository for the specified CIM namespace within the mock repository . This is the original instance variable so any modifications will change the mock repository . | 55 | 30 |
28,212 | def _get_method_repo ( self , namespace = None ) : self . _validate_namespace ( namespace ) if namespace not in self . methods : self . methods [ namespace ] = NocaseDict ( ) return self . methods [ namespace ] | Returns the method repository for the specified CIM namespace within the mock repository . This is the original instance variable so any modifications will change the mock repository . | 56 | 30 |
28,213 | def _get_superclassnames ( self , cn , namespace ) : class_repo = self . _get_class_repo ( namespace ) superclass_names = [ ] if cn is not None : cnwork = cn while cnwork : cnsuper = class_repo [ cnwork ] . superclass if cnsuper : superclass_names . append ( cnsuper ) cnwork = cnsuper superclass_names . reverse ( ) return superclass_names | Get list of superclasses names from the class repository for the defined classname in the namespace . | 110 | 19 |
28,214 | def _get_subclass_names ( self , classname , namespace , deep_inheritance ) : assert classname is None or isinstance ( classname , ( six . string_types , CIMClassName ) ) if isinstance ( classname , CIMClassName ) : classname = classname . classname # retrieve first level of subclasses for which classname is superclass try : classes = self . classes [ namespace ] except KeyError : classes = NocaseDict ( ) if classname is None : rtn_classnames = [ cl . classname for cl in six . itervalues ( classes ) if cl . superclass is None ] else : rtn_classnames = [ cl . classname for cl in six . itervalues ( classes ) if cl . superclass and cl . superclass . lower ( ) == classname . lower ( ) ] # recurse for next level of class hiearchy if deep_inheritance : subclass_names = [ ] if rtn_classnames : for cn in rtn_classnames : subclass_names . extend ( self . _get_subclass_names ( cn , namespace , deep_inheritance ) ) rtn_classnames . extend ( subclass_names ) return rtn_classnames | Get class names that are subclasses of the classname input parameter from the repository . | 277 | 17 |
28,215 | def _get_class ( self , classname , namespace , local_only = None , include_qualifiers = None , include_classorigin = None , property_list = None ) : # pylint: disable=invalid-name class_repo = self . _get_class_repo ( namespace ) # try to get the target class and create a copy for response try : c = class_repo [ classname ] except KeyError : raise CIMError ( CIM_ERR_NOT_FOUND , _format ( "Class {0!A} not found in namespace {1!A}." , classname , namespace ) ) cc = deepcopy ( c ) if local_only : for prop , pvalue in cc . properties . items ( ) : if pvalue . propagated : del cc . properties [ prop ] for method , mvalue in cc . methods . items ( ) : if mvalue . propagated : del cc . methods [ method ] self . _filter_properties ( cc , property_list ) if not include_qualifiers : self . _remove_qualifiers ( cc ) if not include_classorigin : self . _remove_classorigin ( cc ) return cc | Get class from repository . Gets the class defined by classname from the repository creates a copy expands the copied class to include superclass properties if not localonly and filters the class based on propertylist and includeClassOrigin . | 257 | 44 |
28,216 | def _get_association_classes ( self , namespace ) : class_repo = self . _get_class_repo ( namespace ) # associator_classes = [] for cl in six . itervalues ( class_repo ) : if 'Association' in cl . qualifiers : yield cl return | Return iterator of associator classes from the class repo | 67 | 10 |
28,217 | def _find_instance ( iname , instance_repo ) : rtn_inst = None rtn_index = None for index , inst in enumerate ( instance_repo ) : if iname == inst . path : if rtn_inst is not None : # TODO:ks Future Remove dup test since we should be # insuring no dups on instance creation raise CIMError ( CIM_ERR_FAILED , _format ( "Invalid Repository. Multiple instances with " "same path {0!A}." , rtn_inst . path ) ) rtn_inst = inst rtn_index = index return ( rtn_index , rtn_inst ) | Find an instance in the instance repo by iname and return the index of that instance . | 149 | 18 |
28,218 | def _get_instance ( self , iname , namespace , property_list , local_only , include_class_origin , include_qualifiers ) : instance_repo = self . _get_instance_repo ( namespace ) rtn_tup = self . _find_instance ( iname , instance_repo ) inst = rtn_tup [ 1 ] if inst is None : raise CIMError ( CIM_ERR_NOT_FOUND , _format ( "Instance not found in repository namespace {0!A}. " "Path={1!A}" , namespace , iname ) ) rtn_inst = deepcopy ( inst ) # If local_only remove properties where class_origin # differs from class of target instance if local_only : for p in rtn_inst : class_origin = rtn_inst . properties [ p ] . class_origin if class_origin and class_origin != inst . classname : del rtn_inst [ p ] # if not repo_lite test against class properties if not self . _repo_lite and local_only : # gets class propertylist which may be local only or all # superclasses try : cl = self . _get_class ( iname . classname , namespace , local_only = local_only ) except CIMError as ce : if ce . status_code == CIM_ERR_NOT_FOUND : raise CIMError ( CIM_ERR_INVALID_CLASS , _format ( "Class {0!A} not found for instance {1!A} in " "namespace {2!A}." , iname . classname , iname , namespace ) ) class_pl = cl . properties . keys ( ) for p in list ( rtn_inst ) : if p not in class_pl : del rtn_inst [ p ] self . _filter_properties ( rtn_inst , property_list ) if not include_qualifiers : self . _remove_qualifiers ( rtn_inst ) if not include_class_origin : self . _remove_classorigin ( rtn_inst ) return rtn_inst | Local method implements getinstance . This is generally used by other instance methods that need to get an instance from the repository . | 463 | 24 |
28,219 | def _get_subclass_list_for_enums ( self , classname , namespace ) : if self . _repo_lite : return NocaseDict ( { classname : classname } ) if not self . _class_exists ( classname , namespace ) : raise CIMError ( CIM_ERR_INVALID_CLASS , _format ( "Class {0!A} not found in namespace {1!A}." , classname , namespace ) ) if not self . classes : return NocaseDict ( ) clnslist = self . _get_subclass_names ( classname , namespace , True ) clnsdict = NocaseDict ( ) for cln in clnslist : clnsdict [ cln ] = cln clnsdict [ classname ] = classname return clnsdict | Get class list ( i . e names of subclasses for classname for the enumerateinstance methods . If conn . lite returns only classname but no subclasses . | 184 | 35 |
28,220 | def _filter_properties ( obj , property_list ) : if property_list is not None : property_list = [ p . lower ( ) for p in property_list ] for pname in obj . properties . keys ( ) : if pname . lower ( ) not in property_list : del obj . properties [ pname ] | Remove properties from an instance or class that aren t in the plist parameter | 71 | 15 |
28,221 | def _appendpath_unique ( list_ , path ) : for p in list_ : if p == path : return list_ . append ( path ) | Append path to list if not already in list | 32 | 10 |
28,222 | def _return_assoc_tuple ( self , objects ) : if objects : result = [ ( u'OBJECTPATH' , { } , obj ) for obj in objects ] return self . _make_tuple ( result ) return None | Create the property tuple for _imethod return of references referencenames associators and associatornames methods . | 54 | 24 |
28,223 | def _return_assoc_class_tuples ( self , rtn_classnames , namespace , iq , ico , pl ) : rtn_tups = [ ] for cn in rtn_classnames : rtn_tups . append ( ( CIMClassName ( cn , namespace = namespace , host = self . host ) , self . _get_class ( cn , namespace = namespace , include_qualifiers = iq , include_classorigin = ico , property_list = pl ) ) ) return self . _return_assoc_tuple ( rtn_tups ) | Creates the correct tuples of for associator and references class level responses from a list of classnames . This is special because the class level references and associators return a tuple of CIMClassName and CIMClass for every entry . | 133 | 49 |
28,224 | def _classnamedict ( self , classname , namespace ) : clns = self . _classnamelist ( classname , namespace ) rtn_dict = NocaseDict ( ) for cln in clns : rtn_dict [ cln ] = cln return rtn_dict | Get from _classnamelist and cvt to NocaseDict | 64 | 15 |
28,225 | def _ref_prop_matches ( prop , target_classname , ref_classname , resultclass_names , role ) : assert prop . type == 'reference' if prop . reference_class . lower ( ) == target_classname . lower ( ) : if resultclass_names and ref_classname not in resultclass_names : return False if role and prop . name . lower ( ) != role : return False return True return False | Test filters for a reference property Returns True if matches the criteria . | 95 | 13 |
28,226 | def _assoc_prop_matches ( prop , ref_classname , assoc_classes , result_classes , result_role ) : assert prop . type == 'reference' if assoc_classes and ref_classname not in assoc_classes : return False if result_classes and prop . reference_class not in result_classes : return False if result_role and prop . name . lower ( ) != result_role : return False return True | Test filters of a reference property and its associated entity Returns True if matches the criteria . Returns False if it does not match . | 97 | 25 |
28,227 | def _get_reference_classnames ( self , classname , namespace , resultclass_name , role ) : self . _validate_namespace ( namespace ) result_classes = self . _classnamedict ( resultclass_name , namespace ) rtn_classnames_set = set ( ) role = role . lower ( ) if role else role for cl in self . _get_association_classes ( namespace ) : for prop in six . itervalues ( cl . properties ) : if prop . type == 'reference' and self . _ref_prop_matches ( prop , classname , cl . classname , result_classes , role ) : rtn_classnames_set . add ( cl . classname ) return list ( rtn_classnames_set ) | Get list of classnames that are references for which this classname is a target filtered by the result_class and role parameters if they are none . This is a common method used by all of the other reference and associator methods to create a list of reference classnames | 168 | 54 |
28,228 | def _get_associated_classnames ( self , classname , namespace , assoc_class , result_class , result_role , role ) : class_repo = self . _get_class_repo ( namespace ) result_classes = self . _classnamedict ( result_class , namespace ) assoc_classes = self . _classnamedict ( assoc_class , namespace ) rtn_classnames_set = set ( ) role = role . lower ( ) if role else role result_role = result_role . lower ( ) if result_role else result_role ref_clns = self . _get_reference_classnames ( classname , namespace , assoc_class , role ) cls = [ class_repo [ cln ] for cln in ref_clns ] for cl in cls : for prop in six . itervalues ( cl . properties ) : if prop . type == 'reference' : if self . _assoc_prop_matches ( prop , cl . classname , assoc_classes , result_classes , result_role ) : rtn_classnames_set . add ( prop . reference_class ) return list ( rtn_classnames_set ) | Get list of classnames that are associated classes for which this classname is a target filtered by the assoc_class role result_class and result_role parameters if they are none . | 264 | 38 |
28,229 | def _make_pull_imethod_resp ( objs , eos , context_id ) : eos_tup = ( u'EndOfSequence' , None , eos ) enum_ctxt_tup = ( u'EnumerationContext' , None , context_id ) return [ ( "IRETURNVALUE" , { } , objs ) , enum_ctxt_tup , eos_tup ] | Create the correct imethod response for the open and pull methods | 96 | 13 |
28,230 | def _open_response ( self , objects , namespace , pull_type , * * params ) : max_obj_cnt = params [ 'MaxObjectCount' ] if max_obj_cnt is None : max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT default_server_timeout = 40 timeout = default_server_timeout if params [ 'OperationTimeout' ] is None else params [ 'OperationTimeout' ] if len ( objects ) <= max_obj_cnt : eos = u'TRUE' context_id = "" rtn_inst_names = objects else : eos = u'FALSE' context_id = self . _create_contextid ( ) # TODO:ks Future. Use the timeout along with response delay. Then # user could timeout pulls. This means adding timer test to # pulls and close. Timer should be used to close old contexts # also. self . enumeration_contexts [ context_id ] = { 'pull_type' : pull_type , 'data' : objects , 'namespace' : namespace , 'time' : time . clock ( ) , 'interoptimeout' : timeout } rtn_inst_names = objects [ 0 : max_obj_cnt ] del objects [ 0 : max_obj_cnt ] return self . _make_pull_imethod_resp ( rtn_inst_names , eos , context_id ) | Build an open ... response once the objects have been extracted from the repository . | 310 | 15 |
28,231 | def _pull_response ( self , namespace , req_type , * * params ) : self . _validate_namespace ( namespace ) context_id = params [ 'EnumerationContext' ] try : context_data = self . enumeration_contexts [ context_id ] except KeyError : raise CIMError ( CIM_ERR_INVALID_ENUMERATION_CONTEXT , _format ( "EnumerationContext {0!A} not found in mock server " "enumeration contexts." , context_id ) ) if context_data [ 'pull_type' ] != req_type : raise CIMError ( CIM_ERR_INVALID_ENUMERATION_CONTEXT , _format ( "Invalid pull operations {0!A} does not match " "expected {1!A} for EnumerationContext {2!A}" , context_data [ 'pull_type' ] , req_type , context_id ) ) objs_list = context_data [ 'data' ] max_obj_cnt = params [ 'MaxObjectCount' ] if not max_obj_cnt : max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT if len ( objs_list ) <= max_obj_cnt : eos = u'TRUE' rtn_objs_list = objs_list del self . enumeration_contexts [ context_id ] context_id = "" else : eos = u'FALSE' rtn_objs_list = objs_list [ 0 : max_obj_cnt ] del objs_list [ 0 : max_obj_cnt ] return self . _make_pull_imethod_resp ( rtn_objs_list , eos , context_id ) | Common method for all of the Pull methods . Since all of the pull methods operate independent of the type of data this single function severs as common code | 396 | 30 |
28,232 | def _validate_open_params ( * * params ) : if not params [ 'FilterQueryLanguage' ] and params [ 'FilterQuery' ] : raise CIMError ( CIM_ERR_INVALID_PARAMETER , "FilterQuery without FilterQueryLanguage definition is " "invalid" ) if params [ 'FilterQueryLanguage' ] : if params [ 'FilterQueryLanguage' ] != 'DMTF:FQL' : raise CIMError ( CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED , _format ( "FilterQueryLanguage {0!A} not supported" , params [ 'FilterQueryLanguage' ] ) ) ot = params [ 'OperationTimeout' ] if ot : if not isinstance ( ot , six . integer_types ) or ot < 0 or ot > OPEN_MAX_TIMEOUT : raise CIMError ( CIM_ERR_INVALID_PARAMETER , _format ( "OperationTimeout {0!A }must be positive integer " "less than {1!A}" , ot , OPEN_MAX_TIMEOUT ) ) | Validate the fql parameters and if invalid generate exception | 241 | 11 |
28,233 | def _fake_openassociatorinstances ( self , namespace , * * params ) : self . _validate_namespace ( namespace ) self . _validate_open_params ( * * params ) params [ 'ObjectName' ] = params [ 'InstanceName' ] del params [ 'InstanceName' ] result = self . _fake_associators ( namespace , * * params ) objects = [ ] if result is None else [ x [ 2 ] for x in result [ 0 ] [ 2 ] ] return self . _open_response ( objects , namespace , 'PullInstancesWithPath' , * * params ) | Implements WBEM server responder for WBEMConnection . OpenAssociatorInstances with data from the instance repository . | 134 | 26 |
28,234 | def send_http_error ( self , http_code , cim_error = None , cim_error_details = None , headers = None ) : self . send_response ( http_code , http_client . responses . get ( http_code , '' ) ) self . send_header ( "CIMExport" , "MethodResponse" ) if cim_error is not None : self . send_header ( "CIMError" , cim_error ) if cim_error_details is not None : self . send_header ( "CIMErrorDetails" , cim_error_details ) if headers is not None : for header , value in headers : self . send_header ( header , value ) self . end_headers ( ) self . log ( '%s: HTTP status %s; CIMError: %s, CIMErrorDetails: %s' , ( self . _get_log_prefix ( ) , http_code , cim_error , cim_error_details ) , logging . WARNING ) | Send an HTTP response back to the WBEM server that indicates an error at the HTTP level . | 225 | 19 |
28,235 | def send_error_response ( self , msgid , methodname , status_code , status_desc , error_insts = None ) : resp_xml = cim_xml . CIM ( cim_xml . MESSAGE ( cim_xml . SIMPLEEXPRSP ( cim_xml . EXPMETHODRESPONSE ( methodname , cim_xml . ERROR ( str ( status_code ) , status_desc , error_insts ) , ) , # noqa: E123 ) , # noqa: E123 msgid , IMPLEMENTED_PROTOCOL_VERSION ) , IMPLEMENTED_CIM_VERSION , IMPLEMENTED_DTD_VERSION ) resp_body = '<?xml version="1.0" encoding="utf-8" ?>\n' + resp_xml . toxml ( ) if isinstance ( resp_body , six . text_type ) : resp_body = resp_body . encode ( "utf-8" ) http_code = 200 self . send_response ( http_code , http_client . responses . get ( http_code , '' ) ) self . send_header ( "Content-Type" , "text/html" ) self . send_header ( "Content-Length" , str ( len ( resp_body ) ) ) self . send_header ( "CIMExport" , "MethodResponse" ) self . end_headers ( ) self . wfile . write ( resp_body ) self . log ( '%s: HTTP status %s; CIM error response: %s: %s' , ( self . _get_log_prefix ( ) , http_code , _statuscode2name ( status_code ) , status_desc ) , logging . WARNING ) | Send a CIM - XML response message back to the WBEM server that indicates error . | 386 | 18 |
28,236 | def send_success_response ( self , msgid , methodname ) : resp_xml = cim_xml . CIM ( cim_xml . MESSAGE ( cim_xml . SIMPLEEXPRSP ( cim_xml . EXPMETHODRESPONSE ( methodname ) , ) , # noqa: E123 msgid , IMPLEMENTED_PROTOCOL_VERSION ) , IMPLEMENTED_CIM_VERSION , IMPLEMENTED_DTD_VERSION ) resp_body = '<?xml version="1.0" encoding="utf-8" ?>\n' + resp_xml . toxml ( ) if isinstance ( resp_body , six . text_type ) : resp_body = resp_body . encode ( "utf-8" ) http_code = 200 self . send_response ( http_code , http_client . responses . get ( http_code , '' ) ) self . send_header ( "Content-Type" , "text/html" ) self . send_header ( "Content-Length" , str ( len ( resp_body ) ) ) self . send_header ( "CIMExport" , "MethodResponse" ) self . end_headers ( ) self . wfile . write ( resp_body ) | Send a CIM - XML response message back to the WBEM server that indicates success . | 279 | 18 |
28,237 | def log ( self , format_ , args , level = logging . INFO ) : self . server . listener . logger . log ( level , format_ , * args ) | This function is called for anything that needs to get logged . It logs to the logger of this listener . | 35 | 21 |
28,238 | def start ( self ) : if self . _http_port : if not self . _http_server : try : server = ThreadedHTTPServer ( ( self . _host , self . _http_port ) , ListenerRequestHandler ) except Exception as exc : # Linux+py2: socket.error; Linux+py3: OSError; # Windows does not raise any exception. if getattr ( exc , 'errno' , None ) == errno . EADDRINUSE : # Reraise with improved error message msg = _format ( "WBEM listener port {0} already in use" , self . _http_port ) exc_type = OSError six . reraise ( exc_type , exc_type ( errno . EADDRINUSE , msg ) , sys . exc_info ( ) [ 2 ] ) raise # pylint: disable=attribute-defined-outside-init server . listener = self thread = threading . Thread ( target = server . serve_forever ) thread . daemon = True # Exit server thread upon main thread exit self . _http_server = server self . _http_thread = thread thread . start ( ) else : # Just in case someone changed self._http_port after init... self . _http_server = None self . _http_thread = None if self . _https_port : if not self . _https_server : try : server = ThreadedHTTPServer ( ( self . _host , self . _https_port ) , ListenerRequestHandler ) except Exception as exc : # Linux+py2: socket.error; Linux+py3: OSError; # Windows does not raise any exception. if getattr ( exc , 'errno' , None ) == errno . EADDRINUSE : # Reraise with improved error message msg = _format ( "WBEM listener port {0} already in use" , self . _http_port ) exc_type = OSError six . reraise ( exc_type , exc_type ( errno . EADDRINUSE , msg ) , sys . exc_info ( ) [ 2 ] ) raise # pylint: disable=attribute-defined-outside-init server . listener = self server . socket = ssl . wrap_socket ( server . socket , certfile = self . _certfile , keyfile = self . _keyfile , server_side = True ) thread = threading . Thread ( target = server . serve_forever ) thread . daemon = True # Exit server thread upon main thread exit self . _https_server = server self . _https_thread = thread thread . start ( ) else : # Just in case someone changed self._https_port after init... self . _https_server = None self . _https_thread = None | Start the WBEM listener threads if they are not yet running . | 607 | 13 |
28,239 | def stop ( self ) : # Stopping the server will cause its `serve_forever()` method # to return, which will cause the server thread to terminate. # TODO: Describe how the processing threads terminate. if self . _http_server : self . _http_server . shutdown ( ) self . _http_server . server_close ( ) self . _http_server = None self . _http_thread = None if self . _https_server : self . _https_server . shutdown ( ) self . _https_server . server_close ( ) self . _https_server = None self . _https_thread = None | Stop the WBEM listener threads if they are running . | 140 | 11 |
28,240 | def deliver_indication ( self , indication , host ) : for callback in self . _callbacks : try : callback ( indication , host ) except Exception as exc : # pylint: disable=broad-except self . logger . log ( logging . ERROR , "Indication delivery callback " "function raised %s: %s" , exc . __class__ . __name__ , exc ) | This function is called by the listener threads for each received indication . It is not supposed to be called by the user . | 83 | 24 |
28,241 | def add_callback ( self , callback ) : if callback not in self . _callbacks : self . _callbacks . append ( callback ) | Add a callback function to the listener . | 30 | 8 |
28,242 | def cmpname ( name1 , name2 ) : if name1 is None and name2 is None : return 0 if name1 is None : return - 1 if name2 is None : return 1 lower_name1 = name1 . lower ( ) lower_name2 = name2 . lower ( ) if lower_name1 == lower_name2 : return 0 return - 1 if lower_name1 < lower_name2 else 1 | Compare two CIM names for equality and ordering . | 92 | 10 |
28,243 | def _qualifiers_tomof ( qualifiers , indent , maxline = MAX_MOF_LINE ) : if not qualifiers : return u'' mof = [ ] mof . append ( _indent_str ( indent ) ) mof . append ( u'[' ) line_pos = indent + 1 mof_quals = [ ] for q in qualifiers . itervalues ( ) : mof_quals . append ( q . tomof ( indent + 1 + MOF_INDENT , maxline , line_pos ) ) delim = ',\n' + _indent_str ( indent + 1 ) mof . append ( delim . join ( mof_quals ) ) mof . append ( u']\n' ) return u'' . join ( mof ) | Return a MOF string with the qualifier values including the surrounding square brackets . The qualifiers are ordered by their name . | 169 | 23 |
28,244 | def _mof_escaped ( strvalue ) : # Note: This is a raw docstring because it shows many backslashes, and # that avoids having to double them. escaped_str = strvalue # Escape backslash (\) escaped_str = escaped_str . replace ( '\\' , '\\\\' ) # Escape \b, \t, \n, \f, \r # Note, the Python escape sequences happen to be the same as in MOF escaped_str = escaped_str . replace ( '\b' , '\\b' ) . replace ( '\t' , '\\t' ) . replace ( '\n' , '\\n' ) . replace ( '\f' , '\\f' ) . replace ( '\r' , '\\r' ) # Escape remaining control characters (U+0001...U+001F), skipping # U+0008, U+0009, U+000A, U+000C, U+000D that are already handled. # We hard code it to be faster, plus we can easily skip already handled # chars. # The generic code would be (not skipping already handled chars): # for cp in range(1, 32): # c = six.unichr(cp) # esc = '\\x{0:04X}'.format(cp) # escaped_str = escaped_str.replace(c, esc) escaped_str = escaped_str . replace ( u'\u0001' , '\\x0001' ) . replace ( u'\u0002' , '\\x0002' ) . replace ( u'\u0003' , '\\x0003' ) . replace ( u'\u0004' , '\\x0004' ) . replace ( u'\u0005' , '\\x0005' ) . replace ( u'\u0006' , '\\x0006' ) . replace ( u'\u0007' , '\\x0007' ) . replace ( u'\u000B' , '\\x000B' ) . replace ( u'\u000E' , '\\x000E' ) . replace ( u'\u000F' , '\\x000F' ) . replace ( u'\u0010' , '\\x0010' ) . replace ( u'\u0011' , '\\x0011' ) . replace ( u'\u0012' , '\\x0012' ) . replace ( u'\u0013' , '\\x0013' ) . replace ( u'\u0014' , '\\x0014' ) . replace ( u'\u0015' , '\\x0015' ) . replace ( u'\u0016' , '\\x0016' ) . replace ( u'\u0017' , '\\x0017' ) . replace ( u'\u0018' , '\\x0018' ) . replace ( u'\u0019' , '\\x0019' ) . replace ( u'\u001A' , '\\x001A' ) . replace ( u'\u001B' , '\\x001B' ) . replace ( u'\u001C' , '\\x001C' ) . replace ( u'\u001D' , '\\x001D' ) . replace ( u'\u001E' , '\\x001E' ) . replace ( u'\u001F' , '\\x001F' ) # Escape single and double quote escaped_str = escaped_str . replace ( '"' , '\\"' ) escaped_str = escaped_str . replace ( "'" , "\\'" ) return escaped_str | r Return a MOF - escaped string from the input string . | 817 | 13 |
28,245 | def _scalar_value_tomof ( value , type , indent = 0 , maxline = MAX_MOF_LINE , line_pos = 0 , end_space = 0 , avoid_splits = False ) : # pylint: disable=line-too-long,redefined-builtin # noqa: E501 if value is None : return mofval ( u'NULL' , indent , maxline , line_pos , end_space ) if type == 'string' : # pylint: disable=no-else-raise if isinstance ( value , six . string_types ) : return mofstr ( value , indent , maxline , line_pos , end_space , avoid_splits ) if isinstance ( value , ( CIMInstance , CIMClass ) ) : # embedded instance or class return mofstr ( value . tomof ( ) , indent , maxline , line_pos , end_space , avoid_splits ) raise TypeError ( _format ( "Scalar value of CIM type {0} has invalid Python type " "type {1} for conversion to a MOF string" , type , builtin_type ( value ) ) ) elif type == 'char16' : return mofstr ( value , indent , maxline , line_pos , end_space , avoid_splits , quote_char = u"'" ) elif type == 'boolean' : val = u'true' if value else u'false' return mofval ( val , indent , maxline , line_pos , end_space ) elif type == 'datetime' : val = six . text_type ( value ) return mofstr ( val , indent , maxline , line_pos , end_space , avoid_splits ) elif type == 'reference' : val = value . to_wbem_uri ( ) return mofstr ( val , indent , maxline , line_pos , end_space , avoid_splits ) elif isinstance ( value , ( CIMFloat , CIMInt , int , _Longint ) ) : val = six . text_type ( value ) return mofval ( val , indent , maxline , line_pos , end_space ) else : assert isinstance ( value , float ) , _format ( "Scalar value of CIM type {0} has invalid Python type {1} " "for conversion to a MOF string" , type , builtin_type ( value ) ) val = repr ( value ) return mofval ( val , indent , maxline , line_pos , end_space ) | Return a MOF string representing a scalar CIM - typed value . | 566 | 15 |
28,246 | def _infer_type ( value , element_kind , element_name ) : if value is None : raise ValueError ( _format ( "Cannot infer CIM type of {0} {1!A} from its value when " "the value is None" , element_kind , element_name ) ) try : return cimtype ( value ) except TypeError as exc : raise ValueError ( _format ( "Cannot infer CIM type of {0} {1!A} from its value: {2!A}" , element_kind , element_name , exc ) ) | Infer the CIM type name of the value based upon its Python type . | 126 | 16 |
28,247 | def _check_array_parms ( is_array , array_size , value , element_kind , element_name ) : # pylint: disable=unused-argument # The array_size argument is unused. # The following case has been disabled because it cannot happen given # how this check function is used: # if array_size and is_array is False: # raise ValueError( # _format("The array_size parameter of {0} {1!A} is {2!A} but the " # "is_array parameter is False.", # element_kind, element_name, array_size)) if value is not None : value_is_array = isinstance ( value , ( list , tuple ) ) if not is_array and value_is_array : raise ValueError ( _format ( "The is_array parameter of {0} {1!A} is False but " "value {2!A} is an array." , element_kind , element_name , value ) ) if is_array and not value_is_array : raise ValueError ( _format ( "The is_array parameter of {0} {1!A} is True but " "value {2!A} is not an array." , element_kind , element_name , value ) ) | Check whether array - related parameters are ok . | 280 | 9 |
28,248 | def _check_embedded_object ( embedded_object , type , value , element_kind , element_name ) : # pylint: disable=redefined-builtin if embedded_object not in ( 'instance' , 'object' ) : raise ValueError ( _format ( "{0} {1!A} specifies an invalid value for " "embedded_object: {2!A} (must be 'instance' or 'object')" , element_kind , element_name , embedded_object ) ) if type != 'string' : raise ValueError ( _format ( "{0} {1!A} specifies embedded_object {2!A} but its CIM " "type is invalid: {3!A} (must be 'string')" , element_kind , element_name , embedded_object , type ) ) if value is not None : if isinstance ( value , list ) : if value : v0 = value [ 0 ] # Check the first array element if v0 is not None and not isinstance ( v0 , ( CIMInstance , CIMClass ) ) : raise ValueError ( _format ( "Array {0} {1!A} specifies embedded_object " "{2!A} but the Python type of its first array " "value is invalid: {3} (must be CIMInstance " "or CIMClass)" , element_kind , element_name , embedded_object , builtin_type ( v0 ) ) ) else : if not isinstance ( value , ( CIMInstance , CIMClass ) ) : raise ValueError ( _format ( "{0} {1!A} specifies embedded_object {2!A} but " "the Python type of its value is invalid: {3} " "(must be CIMInstance or CIMClass)" , element_kind , element_name , embedded_object , builtin_type ( value ) ) ) | Check whether embedded - object - related parameters are ok . | 409 | 11 |
28,249 | def update ( self , * args , * * kwargs ) : for mapping in args : if hasattr ( mapping , 'items' ) : for key , value in mapping . items ( ) : self [ key ] = value else : for ( key , value ) in mapping : self [ key ] = value for key , value in kwargs . items ( ) : self [ key ] = value | Update the properties of this CIM instance . | 84 | 9 |
28,250 | def update_existing ( self , * args , * * kwargs ) : for mapping in args : if hasattr ( mapping , 'items' ) : for key , value in mapping . items ( ) : try : prop = self . properties [ key ] except KeyError : continue prop . value = value else : for ( key , value ) in mapping : try : prop = self . properties [ key ] except KeyError : continue prop . value = value for key , value in kwargs . items ( ) : try : prop = self . properties [ key ] except KeyError : continue prop . value = value | Update already existing properties of this CIM instance . | 128 | 10 |
28,251 | def get ( self , key , default = None ) : prop = self . properties . get ( key , None ) return default if prop is None else prop . value | Return the value of a particular property of this CIM instance or a default value . | 34 | 17 |
28,252 | def items ( self ) : return [ ( key , v . value ) for key , v in self . properties . items ( ) ] | Return a copied list of the property names and values of this CIM instance . | 28 | 16 |
28,253 | def iteritems ( self ) : for key , val in self . properties . iteritems ( ) : yield ( key , val . value ) | Iterate through the property names and values of this CIM instance . | 29 | 14 |
28,254 | def tomof ( self , indent = 0 , maxline = MAX_MOF_LINE ) : if indent != 0 : msg = "The 'indent' parameter of CIMInstance.tomof() is " "deprecated." if DEBUG_WARNING_ORIGIN : msg += "\nTraceback:\n" + '' . join ( traceback . format_stack ( ) ) warnings . warn ( msg , DeprecationWarning , stacklevel = _stacklevel_above_module ( __name__ ) ) mof = [ ] mof . append ( u'instance of ' ) mof . append ( self . classname ) mof . append ( u' {\n' ) for p in self . properties . itervalues ( ) : mof . append ( p . tomof ( True , MOF_INDENT , maxline ) ) mof . append ( u'};\n' ) return u'' . join ( mof ) | Return a MOF string with the specification of this CIM instance . | 203 | 14 |
28,255 | def tomof ( self , maxline = MAX_MOF_LINE ) : mof = [ ] mof . append ( _qualifiers_tomof ( self . qualifiers , MOF_INDENT , maxline ) ) mof . append ( u'class ' ) mof . append ( self . classname ) mof . append ( u' ' ) if self . superclass is not None : mof . append ( u': ' ) mof . append ( self . superclass ) mof . append ( u' ' ) mof . append ( u'{\n' ) for p in self . properties . itervalues ( ) : mof . append ( u'\n' ) mof . append ( p . tomof ( False , MOF_INDENT , maxline ) ) for m in self . methods . itervalues ( ) : mof . append ( u'\n' ) mof . append ( m . tomof ( MOF_INDENT , maxline ) ) mof . append ( u'\n};\n' ) return u'' . join ( mof ) | Return a MOF string with the declaration of this CIM class . | 240 | 14 |
28,256 | def tomof ( self , is_instance = True , indent = 0 , maxline = MAX_MOF_LINE , line_pos = 0 ) : mof = [ ] if is_instance : # Property value in an instance mof . append ( _indent_str ( indent ) ) mof . append ( self . name ) else : # Property declaration in a class if self . qualifiers : mof . append ( _qualifiers_tomof ( self . qualifiers , indent + MOF_INDENT , maxline ) ) mof . append ( _indent_str ( indent ) ) mof . append ( moftype ( self . type , self . reference_class ) ) mof . append ( u' ' ) mof . append ( self . name ) if self . is_array : mof . append ( u'[' ) if self . array_size is not None : mof . append ( six . text_type ( self . array_size ) ) mof . append ( u']' ) # Generate the property value (nearly common for property values and # property declarations). if self . value is not None or is_instance : mof . append ( u' =' ) if isinstance ( self . value , list ) : mof . append ( u' {' ) mof_str = u'' . join ( mof ) line_pos = len ( mof_str ) - mof_str . rfind ( '\n' ) - 1 # Assume in line_pos that the extra space would be needed val_str , line_pos = _value_tomof ( self . value , self . type , indent + MOF_INDENT , maxline , line_pos + 1 , 1 , True ) # Empty arrays are represented as val_str='' if val_str and val_str [ 0 ] != '\n' : # The extra space was actually needed mof . append ( u' ' ) else : # Adjust by the extra space that was not needed line_pos -= 1 mof . append ( val_str ) mof . append ( u' }' ) else : mof_str = u'' . join ( mof ) line_pos = len ( mof_str ) - mof_str . rfind ( '\n' ) - 1 # Assume in line_pos that the extra space would be needed val_str , line_pos = _value_tomof ( self . value , self . type , indent + MOF_INDENT , maxline , line_pos + 1 , 1 , True ) # Scalars cannot be represented as val_str='' if val_str [ 0 ] != '\n' : # The extra space was actually needed mof . append ( u' ' ) else : # Adjust by the extra space that was not needed line_pos -= 1 mof . append ( val_str ) mof . append ( ';\n' ) return u'' . join ( mof ) | Return a MOF string with the declaration of this CIM property for use in a CIM class or the specification of this CIM property for use in a CIM instance . | 642 | 36 |
28,257 | def tomof ( self , indent = 0 , maxline = MAX_MOF_LINE ) : mof = [ ] if self . qualifiers : mof . append ( _qualifiers_tomof ( self . qualifiers , indent + MOF_INDENT , maxline ) ) mof . append ( _indent_str ( indent ) ) # return_type is ensured not to be None or reference mof . append ( moftype ( self . return_type , None ) ) mof . append ( u' ' ) mof . append ( self . name ) if self . parameters . values ( ) : mof . append ( u'(\n' ) mof_parms = [ ] for p in self . parameters . itervalues ( ) : mof_parms . append ( p . tomof ( indent + MOF_INDENT , maxline ) ) mof . append ( u',\n' . join ( mof_parms ) ) mof . append ( u');\n' ) else : mof . append ( u'();\n' ) return u'' . join ( mof ) | Return a MOF string with the declaration of this CIM method for use in a CIM class declaration . | 242 | 22 |
28,258 | def tomof ( self , indent = 0 , maxline = MAX_MOF_LINE ) : mof = [ ] if self . qualifiers : mof . append ( _qualifiers_tomof ( self . qualifiers , indent + MOF_INDENT , maxline ) ) mof . append ( _indent_str ( indent ) ) mof . append ( moftype ( self . type , self . reference_class ) ) mof . append ( u' ' ) mof . append ( self . name ) if self . is_array : mof . append ( u'[' ) if self . array_size is not None : mof . append ( six . text_type ( self . array_size ) ) mof . append ( u']' ) return u'' . join ( mof ) | Return a MOF string with the declaration of this CIM parameter for use in a CIM method declaration . | 173 | 22 |
28,259 | def tomof ( self , indent = MOF_INDENT , maxline = MAX_MOF_LINE , line_pos = 0 ) : mof = [ ] mof . append ( self . name ) mof . append ( u' ' ) if isinstance ( self . value , list ) : mof . append ( u'{' ) else : mof . append ( u'(' ) line_pos += len ( u'' . join ( mof ) ) # Assume in line_pos that the extra space would be needed val_str , line_pos = _value_tomof ( self . value , self . type , indent , maxline , line_pos + 1 , 3 , True ) # Empty arrays are represented as val_str='' if val_str and val_str [ 0 ] != '\n' : # The extra space was actually needed mof . append ( u' ' ) else : # Adjust by the extra space that was not needed line_pos -= 1 mof . append ( val_str ) if isinstance ( self . value , list ) : mof . append ( u' }' ) else : mof . append ( u' )' ) mof_str = u'' . join ( mof ) return mof_str | Return a MOF string with the specification of this CIM qualifier as a qualifier value . | 273 | 18 |
28,260 | def tomof ( self , maxline = MAX_MOF_LINE ) : mof = [ ] mof . append ( u'Qualifier ' ) mof . append ( self . name ) mof . append ( u' : ' ) mof . append ( self . type ) if self . is_array : mof . append ( u'[' ) if self . array_size is not None : mof . append ( six . text_type ( self . array_size ) ) mof . append ( u']' ) if self . value is not None : mof . append ( u' = ' ) if isinstance ( self . value , list ) : mof . append ( u'{ ' ) mof_str = u'' . join ( mof ) line_pos = len ( mof_str ) - mof_str . rfind ( '\n' ) - 1 val_str , line_pos = _value_tomof ( self . value , self . type , MOF_INDENT , maxline , line_pos , 3 , False ) mof . append ( val_str ) if isinstance ( self . value , list ) : mof . append ( u' }' ) mof . append ( u',\n' ) mof . append ( _indent_str ( MOF_INDENT + 1 ) ) mof . append ( u'Scope(' ) mof_scopes = [ ] for scope in self . _ordered_scopes : if self . scopes . get ( scope , False ) : mof_scopes . append ( scope . lower ( ) ) mof . append ( u', ' . join ( mof_scopes ) ) mof . append ( u')' ) # toinstance flavor not included here because not part of DSP0004 mof_flavors = [ ] if self . overridable is True : mof_flavors . append ( 'EnableOverride' ) elif self . overridable is False : mof_flavors . append ( 'DisableOverride' ) if self . tosubclass is True : mof_flavors . append ( 'ToSubclass' ) elif self . tosubclass is False : mof_flavors . append ( 'Restricted' ) if self . translatable : mof_flavors . append ( 'Translatable' ) if mof_flavors : mof . append ( u',\n' ) mof . append ( _indent_str ( MOF_INDENT + 1 ) ) mof . append ( u'Flavor(' ) mof . append ( u', ' . join ( mof_flavors ) ) mof . append ( u')' ) mof . append ( u';\n' ) return u'' . join ( mof ) | Return a MOF string with the declaration of this CIM qualifier type . | 613 | 15 |
28,261 | def main ( ) : print ( "Python version %s" % sys . version ) print ( "Testing compatibility for function defined with *args" ) test_func_args ( func_old_args ) test_func_args ( func_new ) print ( "Testing compatibility for function defined with **kwargs" ) test_func_kwargs ( func_old_kwargs ) test_func_kwargs ( func_new ) print ( "All tests successful - we can change *args and **kwargs to' \ ' named args." ) return 0 | Main function calls the test functs | 118 | 8 |
28,262 | def _validate_qualifiers ( qualifier_list , qual_repo , new_class , scope ) : for qname , qvalue in qualifier_list . items ( ) : if qname not in qual_repo : raise CIMError ( CIM_ERR_INVALID_PARAMETER , _format ( "Qualifier {0|A} in new_class {1|A} in " "CreateClass not in repository." , ( qname , new_class . classnam ) ) ) q_decl = qual_repo [ qname ] if qvalue . type != q_decl . type : raise CIMError ( CIM_ERR_INVALID_PARAMETER , _format ( "Qualifier {0|A} in new_class {1|A} override type " "mismatch {2|A} with qualifier declaration {3|A}." , ( qname , new_class . classname , qvalue . type , q_decl . type ) ) ) if scope not in q_decl . scopes : raise CIMError ( CIM_ERR_INVALID_PARAMETER , _format ( "Qualifier {0|A} in new class {1|A} scope {2|A} " "invalid. Not in qualifier decl scopes {3}" , ( qname , new_class . classname , scope , q_decl . scopes ) ) ) | Validate a list of qualifiers against the Qualifier decl in the repository . | 315 | 15 |
28,263 | def _init_qualifier ( qualifier , qual_repo ) : qual_dict_entry = qual_repo [ qualifier . name ] qualifier . propagated = False if qualifier . tosubclass is None : if qual_dict_entry . tosubclass is None : qualifier . tosubclass = True else : qualifier . tosubclass = qual_dict_entry . tosubclass if qualifier . overridable is None : if qual_dict_entry . overridable is None : qualifier . overridable = True else : qualifier . overridable = qual_dict_entry . overridable if qualifier . translatable is None : qualifier . translatable = qual_dict_entry . translatable | Initialize the flavors of a qualifier from the qualifier repo and initialize propagated . | 149 | 16 |
28,264 | def _init_qualifier_decl ( qualifier_decl , qual_repo ) : assert qualifier_decl . name not in qual_repo if qualifier_decl . tosubclass is None : qualifier_decl . tosubclass = True if qualifier_decl . overridable is None : qualifier_decl . overridable = True if qualifier_decl . translatable is None : qualifier_decl . translatable = False | Initialize the flavors of a qualifier declaration if they are not already set . | 89 | 15 |
28,265 | def _set_new_object ( self , new_obj , inherited_obj , new_class , superclass , qualifier_repo , propagated , type_str ) : assert isinstance ( new_obj , ( CIMMethod , CIMProperty , CIMParameter ) ) if inherited_obj : inherited_obj_qual = inherited_obj . qualifiers else : inherited_obj_qual = None if propagated : assert superclass is not None new_obj . propagated = propagated if propagated : assert inherited_obj is not None new_obj . class_origin = inherited_obj . class_origin else : assert inherited_obj is None new_obj . class_origin = new_class . classname self . _resolve_qualifiers ( new_obj . qualifiers , inherited_obj_qual , new_class , superclass , new_obj . name , type_str , qualifier_repo , propagate = propagated ) | Set the object attributes for a single object and resolve the qualifiers . This sets attributes for Properties Methods and Parameters . | 200 | 22 |
28,266 | def _resolve_qualifiers ( self , new_quals , inherited_quals , new_class , super_class , obj_name , obj_type , qualifier_repo , propagate = False , verbose = False ) : superclassname = super_class . classname if super_class else None # TODO Diagnostic we will keep until really sure of this code if verbose : print ( "\nRESOLVE sc_name=%s nc_name=%s, obj_name=%s obj_type=%s " " propagate=%s" % ( superclassname , new_class . classname , obj_name , obj_type , propagate ) ) print ( '\nNEW QUAL' ) for q , qv in new_quals . items ( ) : print ( ' %s: %r' % ( q , qv ) ) print ( 'INHERITEDQ:' ) if inherited_quals : for q , qv in inherited_quals . items ( ) : print ( ' %s: %r' % ( q , qv ) ) # If propagate flag not set, initialize the qualfiers # by setting flavor defaults and propagated False if not propagate : for qname , qvalue in new_quals . items ( ) : self . _init_qualifier ( qvalue , qualifier_repo ) return # resolve qualifiers not in inherited object for qname , qvalue in new_quals . items ( ) : if not inherited_quals or qname not in inherited_quals : self . _init_qualifier ( qvalue , qualifier_repo ) # resolve qualifiers from inherited object for inh_qname , inh_qvalue in inherited_quals . items ( ) : if inh_qvalue . tosubclass : if inh_qvalue . overridable : # if not in new quals, copy it to the new quals, else ignore if inh_qname not in new_quals : new_quals [ inh_qname ] = inherited_quals [ inh_qname ] . copy ( ) new_quals [ inh_qname ] . propagated = True else : new_quals [ inh_qname ] . propagated = False self . _init_qualifier ( new_quals [ inh_qname ] , qualifier_repo ) else : # not overridable if inh_qname in new_quals : # allow for same qualifier def in subclass # TODO should more than value match here.?? if new_quals [ inh_qname ] . value != inherited_quals [ inh_qname ] . value : raise CIMError ( CIM_ERR_INVALID_PARAMETER , _format ( "Invalid new_class {0!A}:{1!A} " "qualifier {2!A}. " "in class {3!A}. Not overridable " , obj_type , obj_name , inh_qname , new_class . classname ) ) else : new_quals [ inh_qname ] . propagated = True else : # not in new class, add it new_quals [ inh_qname ] = inherited_quals [ inh_qname ] . copy ( ) new_quals [ inh_qname ] . propagated = True else : # not tosubclass, i.e. restricted. if inh_qname in new_quals : if inh_qvalue . overridable or inh_qvalue . overridable is None : new_quals [ inh_qname ] . propagated = True else : raise CIMError ( CIM_ERR_INVALID_PARAMETER , _format ( "Invalid qualifier object {0!A} qualifier " "{1!A} . Restricted in super class {2!A}" , obj_name , inh_qname , superclassname ) ) | Process the override of qualifiers from the inherited_quals dictionary to the new_quals dict following the override rules in DSP0004 . | 850 | 29 |
28,267 | def _validateIterCommonParams ( MaxObjectCount , OperationTimeout ) : if MaxObjectCount is None or MaxObjectCount <= 0 : raise ValueError ( _format ( "MaxObjectCount must be > 0 but is {0}" , MaxObjectCount ) ) if OperationTimeout is not None and OperationTimeout < 0 : raise ValueError ( _format ( "OperationTimeout must be >= 0 but is {0}" , OperationTimeout ) ) | Validate common parameters for an iter ... operation . | 92 | 10 |
28,268 | def _validatePullParams ( MaxObjectCount , context ) : if ( not isinstance ( MaxObjectCount , six . integer_types ) or MaxObjectCount < 0 ) : raise ValueError ( _format ( "MaxObjectCount parameter must be integer >= 0 but is " "{0!A}" , MaxObjectCount ) ) if context is None or len ( context ) < 2 : raise ValueError ( _format ( "Pull... Context parameter must be valid tuple {0!A}" , context ) ) | Validate the input paramaters for the PullInstances PullInstancesWithPath and PullInstancePaths requests . | 107 | 23 |
28,269 | def is_subclass ( ch , ns , super_class , sub ) : lsuper = super_class . lower ( ) if isinstance ( sub , CIMClass ) : subname = sub . classname subclass = sub else : subname = sub subclass = None if subname . lower ( ) == lsuper : return True if subclass is None : subclass = ch . GetClass ( subname , ns , LocalOnly = True , IncludeQualifiers = False , PropertyList = [ ] , IncludeClassOrigin = False ) while subclass . superclass is not None : if subclass . superclass . lower ( ) == lsuper : return True subclass = ch . GetClass ( subclass . superclass , ns , LocalOnly = True , IncludeQualifiers = False , PropertyList = [ ] , IncludeClassOrigin = False ) return False | Determine if one class is a subclass of another class . | 173 | 13 |
28,270 | def _set_default_namespace ( self , default_namespace ) : if default_namespace is not None : default_namespace = default_namespace . strip ( '/' ) else : default_namespace = DEFAULT_NAMESPACE self . _default_namespace = _ensure_unicode ( default_namespace ) | Internal setter function . | 75 | 5 |
28,271 | def _configure_detail_level ( cls , detail_level ) : # process detail_level if isinstance ( detail_level , six . string_types ) : if detail_level not in LOG_DETAIL_LEVELS : raise ValueError ( _format ( "Invalid log detail level string: {0!A}; must be " "one of: {1!A}" , detail_level , LOG_DETAIL_LEVELS ) ) elif isinstance ( detail_level , int ) : if detail_level < 0 : raise ValueError ( _format ( "Invalid log detail level integer: {0}; must be a " "positive integer." , detail_level ) ) elif detail_level is None : detail_level = DEFAULT_LOG_DETAIL_LEVEL else : raise ValueError ( _format ( "Invalid log detail level: {0!A}; must be one of: " "{1!A}, or a positive integer" , detail_level , LOG_DETAIL_LEVELS ) ) return detail_level | Validate the detail_level parameter and return it . | 229 | 11 |
28,272 | def _configure_logger_handler ( cls , log_dest , log_filename ) : if log_dest is None : return None msg_format = '%(asctime)s-%(name)s-%(message)s' if log_dest == 'stderr' : # Note: sys.stderr is the default stream for StreamHandler handler = logging . StreamHandler ( ) handler . setFormatter ( logging . Formatter ( msg_format ) ) elif log_dest == 'file' : if not log_filename : raise ValueError ( "Log filename is required if log destination " "is 'file'" ) handler = logging . FileHandler ( log_filename , encoding = "UTF-8" ) handler . setFormatter ( logging . Formatter ( msg_format ) ) else : raise ValueError ( _format ( "Invalid log destination: {0!A}; Must be one of: " "{1!A}" , log_dest , LOG_DESTINATIONS ) ) return handler | Return a logging handler for the specified log_dest or None if log_dest is None . | 221 | 19 |
28,273 | def _activate_logger ( cls , logger_name , simple_name , detail_level , handler , connection , propagate ) : if handler is not None : assert isinstance ( handler , logging . Handler ) # Replace existing handlers of the specified logger (e.g. from # previous calls) by the specified handler logger = logging . getLogger ( logger_name ) for hdlr in logger . handlers : logger . removeHandler ( hdlr ) logger . addHandler ( handler ) logger . setLevel ( logging . DEBUG ) logger . propagate = propagate if connection is not None : if isinstance ( connection , bool ) : if connection : # Store the activation and detail level information for # future connections. This information is used in the init # method of WBEMConnection to activate logging at that # point. cls . _activate_logging = True cls . _log_detail_levels [ simple_name ] = detail_level else : cls . _reset_logging_config ( ) else : assert isinstance ( connection , WBEMConnection ) # Activate logging for this existing connection by ensuring # the connection has a log recorder recorder_found = False # pylint: disable=protected-access for recorder in connection . _operation_recorders : if isinstance ( recorder , LogOperationRecorder ) : recorder_found = True break if not recorder_found : recorder = LogOperationRecorder ( conn_id = connection . conn_id ) # Add the log detail level for this logger to the log recorder # of this connection detail_levels = recorder . detail_levels . copy ( ) detail_levels [ simple_name ] = detail_level recorder . set_detail_level ( detail_levels ) if not recorder_found : # This call must be made after the detail levels of the # recorder have been set, because that data is used # for recording the WBEM connection information. connection . add_operation_recorder ( recorder ) | Configure the specified logger and activate logging and set detail level for connections . | 410 | 15 |
28,274 | def _iparam_namespace_from_namespace ( self , obj ) : # pylint: disable=invalid-name, if isinstance ( obj , six . string_types ) : namespace = obj . strip ( '/' ) elif obj is None : namespace = obj else : raise TypeError ( _format ( "The 'namespace' argument of the WBEMConnection " "operation has invalid type {0} (must be None, or a " "string)" , type ( obj ) ) ) if namespace is None : namespace = self . default_namespace return namespace | Determine the namespace from a namespace string or None . The default namespace of the connection object is used if needed . | 124 | 24 |
28,275 | def _iparam_namespace_from_objectname ( self , objectname , arg_name ) : # pylint: disable=invalid-name, if isinstance ( objectname , ( CIMClassName , CIMInstanceName ) ) : namespace = objectname . namespace elif isinstance ( objectname , six . string_types ) : namespace = None elif objectname is None : namespace = objectname else : raise TypeError ( _format ( "The {0!A} argument of the WBEMConnection operation " "has invalid type {1} (must be None, a string, a " "CIMClassName, or a CIMInstanceName)" , arg_name , type ( objectname ) ) ) if namespace is None : namespace = self . default_namespace return namespace | Determine the namespace from an object name that can be a class name string a CIMClassName or CIMInstanceName object or None . The default namespace of the connection object is used if needed . | 171 | 42 |
28,276 | def _get_rslt_params ( self , result , namespace ) : rtn_objects = [ ] end_of_sequence = False enumeration_context = None end_of_sequence_found = False # flag True if found and valid value enumeration_context_found = False # flag True if ec tuple found for p in result : if p [ 0 ] == 'EndOfSequence' : if isinstance ( p [ 2 ] , six . string_types ) : p2 = p [ 2 ] . lower ( ) if p2 in [ 'true' , 'false' ] : # noqa: E125 end_of_sequence = True if p2 == 'true' else False end_of_sequence_found = True else : raise CIMXMLParseError ( _format ( "EndOfSequence output parameter has an " "invalid value: {0!A}" , p [ 2 ] ) , conn_id = self . conn_id ) elif p [ 0 ] == 'EnumerationContext' : enumeration_context_found = True if isinstance ( p [ 2 ] , six . string_types ) : enumeration_context = p [ 2 ] elif p [ 0 ] == "IRETURNVALUE" : rtn_objects = p [ 2 ] if not end_of_sequence_found and not enumeration_context_found : raise CIMXMLParseError ( "Expected EndOfSequence or EnumerationContext output " "parameter in open/pull response, but none received" , conn_id = self . conn_id ) if not end_of_sequence and enumeration_context is None : raise CIMXMLParseError ( "Expected EnumerationContext output parameter because " "EndOfSequence=False, but did not receive it." , conn_id = self . conn_id ) # Drop enumeration_context if eos True # Returns tuple of enumeration context and namespace rtn_ctxt = None if end_of_sequence else ( enumeration_context , namespace ) return ( rtn_objects , end_of_sequence , rtn_ctxt ) | Common processing for pull results to separate end - of - sequence enum - context and entities in IRETURNVALUE . | 464 | 23 |
28,277 | def GetInstance ( self , InstanceName , LocalOnly = None , IncludeQualifiers = None , IncludeClassOrigin = None , PropertyList = None , * * extra ) : # pylint: disable=invalid-name,line-too-long # noqa: E501 exc = None instance = None method_name = 'GetInstance' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , InstanceName = InstanceName , LocalOnly = LocalOnly , IncludeQualifiers = IncludeQualifiers , IncludeClassOrigin = IncludeClassOrigin , PropertyList = PropertyList , * * extra ) try : stats = self . statistics . start_timer ( method_name ) # Strip off host and namespace to make this a "local" object namespace = self . _iparam_namespace_from_objectname ( InstanceName , 'InstanceName' ) instancename = self . _iparam_instancename ( InstanceName ) PropertyList = _iparam_propertylist ( PropertyList ) result = self . _imethodcall ( method_name , namespace , InstanceName = instancename , LocalOnly = LocalOnly , IncludeQualifiers = IncludeQualifiers , IncludeClassOrigin = IncludeClassOrigin , PropertyList = PropertyList , * * extra ) if result is None : raise CIMXMLParseError ( "Expecting a child element below IMETHODRESPONSE, " "got no child elements" , conn_id = self . conn_id ) result = result [ 0 ] [ 2 ] # List of children of IRETURNVALUE if not result : raise CIMXMLParseError ( "Expecting a child element below IRETURNVALUE, " "got no child elements" , conn_id = self . conn_id ) instance = result [ 0 ] # CIMInstance object if not isinstance ( instance , CIMInstance ) : raise CIMXMLParseError ( _format ( "Expecting CIMInstance object in result, got {0} " "object" , instance . __class__ . __name__ ) , conn_id = self . conn_id ) # The GetInstance CIM-XML operation returns the instance as an # INSTANCE element, which does not contain an instance path. We # want to return the instance with a path, so we set it to the # input path. Because the namespace in the input path is optional, # we set it to the effective target namespace (on a copy of the # input path). instance . path = instancename . copy ( ) instance . path . namespace = namespace return instance except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( instance , exc ) | Retrieve an instance . | 701 | 5 |
28,278 | def ModifyInstance ( self , ModifiedInstance , IncludeQualifiers = None , PropertyList = None , * * extra ) : # pylint: disable=invalid-name,line-too-long # noqa: E501 exc = None method_name = 'ModifyInstance' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , ModifiedInstance = ModifiedInstance , IncludeQualifiers = IncludeQualifiers , PropertyList = PropertyList , * * extra ) try : stats = self . statistics . start_timer ( 'ModifyInstance' ) # Must pass a named CIMInstance here (i.e path attribute set) if ModifiedInstance . path is None : raise ValueError ( 'ModifiedInstance parameter must have path attribute set' ) if ModifiedInstance . path . classname is None : raise ValueError ( 'ModifiedInstance parameter must have classname set in ' ' path' ) if ModifiedInstance . classname is None : raise ValueError ( 'ModifiedInstance parameter must have classname set in ' 'instance' ) namespace = self . _iparam_namespace_from_objectname ( ModifiedInstance . path , 'ModifiedInstance.path' ) PropertyList = _iparam_propertylist ( PropertyList ) # Strip off host and namespace to avoid producing an INSTANCEPATH or # LOCALINSTANCEPATH element instead of the desired INSTANCENAME # element. instance = ModifiedInstance . copy ( ) instance . path . namespace = None instance . path . host = None self . _imethodcall ( method_name , namespace , ModifiedInstance = instance , IncludeQualifiers = IncludeQualifiers , PropertyList = PropertyList , has_return_value = False , * * extra ) return except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( None , exc ) | Modify the property values of an instance . | 511 | 9 |
28,279 | def CreateInstance ( self , NewInstance , namespace = None , * * extra ) : # pylint: disable=invalid-name exc = None instancename = None method_name = 'CreateInstance' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , NewInstance = NewInstance , namespace = namespace , * * extra ) try : stats = self . statistics . start_timer ( method_name ) if namespace is None and getattr ( NewInstance . path , 'namespace' , None ) is not None : namespace = NewInstance . path . namespace namespace = self . _iparam_namespace_from_namespace ( namespace ) instance = NewInstance . copy ( ) # Strip off path to avoid producing a VALUE.NAMEDINSTANCE element # instead of the desired INSTANCE element. instance . path = None result = self . _imethodcall ( method_name , namespace , NewInstance = instance , * * extra ) if result is None : raise CIMXMLParseError ( "Expecting a child element below IMETHODRESPONSE, " "got no child elements" , conn_id = self . conn_id ) result = result [ 0 ] [ 2 ] # List of children of IRETURNVALUE if not result : raise CIMXMLParseError ( "Expecting a child element below IRETURNVALUE, " "got no child elements" , conn_id = self . conn_id ) instancename = result [ 0 ] # CIMInstanceName object if not isinstance ( instancename , CIMInstanceName ) : raise CIMXMLParseError ( _format ( "Expecting CIMInstanceName object in result, got " "{0} object" , instancename . __class__ . __name__ ) , conn_id = self . conn_id ) # The CreateInstance CIM-XML operation returns an INSTANCENAME # element, so the resulting CIMInstanceName object does not have # namespace or host. We want to return an instance path with # namespace, so we set it to the effective target namespace. instancename . namespace = namespace return instancename except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( instancename , exc ) | Create an instance in a namespace . | 613 | 7 |
28,280 | def Associators ( self , ObjectName , AssocClass = None , ResultClass = None , Role = None , ResultRole = None , IncludeQualifiers = None , IncludeClassOrigin = None , PropertyList = None , * * extra ) : # pylint: disable=invalid-name, line-too-long # noqa: E501 exc = None objects = None method_name = 'Associators' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , ObjectName = ObjectName , AssocClass = AssocClass , ResultClass = ResultClass , Role = Role , ResultRole = ResultRole , IncludeQualifiers = IncludeQualifiers , IncludeClassOrigin = IncludeClassOrigin , PropertyList = PropertyList , * * extra ) try : stats = self . statistics . start_timer ( method_name ) namespace = self . _iparam_namespace_from_objectname ( ObjectName , 'ObjectName' ) objectname = self . _iparam_objectname ( ObjectName , 'ObjectName' ) PropertyList = _iparam_propertylist ( PropertyList ) result = self . _imethodcall ( method_name , namespace , ObjectName = objectname , AssocClass = self . _iparam_classname ( AssocClass , 'AssocClass' ) , ResultClass = self . _iparam_classname ( ResultClass , 'ResultClass' ) , Role = Role , ResultRole = ResultRole , IncludeQualifiers = IncludeQualifiers , IncludeClassOrigin = IncludeClassOrigin , PropertyList = PropertyList , * * extra ) # instance-level invocation: list of CIMInstance # class-level invocation: list of CIMClass if result is None : objects = [ ] else : objects = [ x [ 2 ] for x in result [ 0 ] [ 2 ] ] if isinstance ( objectname , CIMInstanceName ) : # instance-level invocation for instance in objects : if not isinstance ( instance , CIMInstance ) : raise CIMXMLParseError ( _format ( "Expecting CIMInstance object in result " "list, got {0} object" , instance . __class__ . __name__ ) , conn_id = self . conn_id ) # path and namespace are already set else : # class-level invocation for classpath , klass in objects : if not isinstance ( classpath , CIMClassName ) or not isinstance ( klass , CIMClass ) : raise CIMXMLParseError ( _format ( "Expecting tuple (CIMClassName, CIMClass) " "in result list, got tuple ({0}, {1})" , classpath . __class__ . __name__ , klass . __class__ . __name__ ) , conn_id = self . conn_id ) # path and namespace are already set return objects except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( objects , exc ) | Retrieve the instances associated to a source instance or the classes associated to a source class . | 758 | 18 |
28,281 | def InvokeMethod ( self , MethodName , ObjectName , Params = None , * * params ) : # pylint: disable=invalid-name exc = None result_tuple = None if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = 'InvokeMethod' , MethodName = MethodName , ObjectName = ObjectName , Params = Params , * * params ) try : stats = self . statistics . start_timer ( 'InvokeMethod' ) # Make the method call result = self . _methodcall ( MethodName , ObjectName , Params , * * params ) return result except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( result_tuple , exc ) | Invoke a method on a target instance or on a target class . | 282 | 14 |
28,282 | def ExecQuery ( self , QueryLanguage , Query , namespace = None , * * extra ) : # pylint: disable=invalid-name exc = None instances = None method_name = 'ExecQuery' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , QueryLanguage = QueryLanguage , Query = Query , namespace = namespace , * * extra ) try : stats = self . statistics . start_timer ( method_name ) namespace = self . _iparam_namespace_from_namespace ( namespace ) result = self . _imethodcall ( method_name , namespace , QueryLanguage = QueryLanguage , Query = Query , * * extra ) if result is None : instances = [ ] else : instances = [ x [ 2 ] for x in result [ 0 ] [ 2 ] ] for instance in instances : # The ExecQuery CIM-XML operation returns instances as any of # (VALUE.OBJECT | VALUE.OBJECTWITHLOCALPATH | # VALUE.OBJECTWITHPATH), i.e. classes or instances with or # without path which may or may not contain a namespace. # TODO: Fix current impl. that assumes instance with path. instance . path . namespace = namespace return instances except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( instances , exc ) | Execute a query in a namespace . | 414 | 8 |
28,283 | def OpenAssociatorInstancePaths ( self , InstanceName , AssocClass = None , ResultClass = None , Role = None , ResultRole = None , FilterQueryLanguage = None , FilterQuery = None , OperationTimeout = None , ContinueOnError = None , MaxObjectCount = None , * * extra ) : # pylint: disable=invalid-name exc = None result_tuple = None method_name = 'OpenAssociatorInstancePaths' if self . _operation_recorders : self . operation_recorder_reset ( pull_op = True ) self . operation_recorder_stage_pywbem_args ( method = method_name , InstanceName = InstanceName , AssocClass = AssocClass , ResultClass = ResultClass , Role = Role , ResultRole = ResultRole , FilterQueryLanguage = FilterQueryLanguage , FilterQuery = FilterQuery , OperationTimeout = OperationTimeout , ContinueOnError = ContinueOnError , MaxObjectCount = MaxObjectCount , * * extra ) try : stats = self . statistics . start_timer ( method_name ) namespace = self . _iparam_namespace_from_objectname ( InstanceName , 'InstanceName' ) instancename = self . _iparam_instancename ( InstanceName ) result = self . _imethodcall ( method_name , namespace , InstanceName = instancename , AssocClass = self . _iparam_classname ( AssocClass , 'AssocClass' ) , ResultClass = self . _iparam_classname ( ResultClass , 'ResultClass' ) , Role = Role , ResultRole = ResultRole , FilterQueryLanguage = FilterQueryLanguage , FilterQuery = FilterQuery , OperationTimeout = OperationTimeout , ContinueOnError = ContinueOnError , MaxObjectCount = MaxObjectCount , has_out_params = True , * * extra ) result_tuple = pull_path_result_tuple ( * self . _get_rslt_params ( result , namespace ) ) return result_tuple except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( result_tuple , exc ) | Open an enumeration session to retrieve the instance paths of the instances associated to a source instance . | 567 | 19 |
28,284 | def OpenQueryInstances ( self , FilterQueryLanguage , FilterQuery , namespace = None , ReturnQueryResultClass = None , OperationTimeout = None , ContinueOnError = None , MaxObjectCount = None , * * extra ) : # pylint: disable=invalid-name @ staticmethod def _GetQueryRsltClass ( result ) : """ Get the QueryResultClass and return it or generate exception. """ for p in result : if p [ 0 ] == 'QueryResultClass' : class_obj = p [ 2 ] if not isinstance ( class_obj , CIMClass ) : raise CIMXMLParseError ( _format ( "Expecting CIMClass object in " "QueryResultClass output parameter, got " "{0} object" , class_obj . __class__ . __name__ ) , conn_id = self . conn_id ) return class_obj raise CIMXMLParseError ( "QueryResultClass output parameter is missing" , conn_id = self . conn_id ) exc = None result_tuple = None method_name = 'OpenQueryInstances' if self . _operation_recorders : self . operation_recorder_reset ( pull_op = True ) self . operation_recorder_stage_pywbem_args ( method = method_name , FilterQueryLanguage = FilterQueryLanguage , FilterQuery = FilterQuery , namespace = namespace , ReturnQueryResultClass = ReturnQueryResultClass , OperationTimeout = OperationTimeout , ContinueOnError = ContinueOnError , MaxObjectCount = MaxObjectCount , * * extra ) try : stats = self . statistics . start_timer ( method_name ) namespace = self . _iparam_namespace_from_namespace ( namespace ) result = self . _imethodcall ( method_name , namespace , FilterQuery = FilterQuery , FilterQueryLanguage = FilterQueryLanguage , ReturnQueryResultClass = ReturnQueryResultClass , OperationTimeout = OperationTimeout , ContinueOnError = ContinueOnError , MaxObjectCount = MaxObjectCount , has_out_params = True , * * extra ) insts , eos , enum_ctxt = self . _get_rslt_params ( result , namespace ) query_result_class = _GetQueryRsltClass ( result ) if ReturnQueryResultClass else None result_tuple = pull_query_result_tuple ( insts , eos , enum_ctxt , query_result_class ) return result_tuple except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( result_tuple , exc ) | Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result . | 655 | 22 |
28,285 | def EnumerateClasses ( self , namespace = None , ClassName = None , DeepInheritance = None , LocalOnly = None , IncludeQualifiers = None , IncludeClassOrigin = None , * * extra ) : # pylint: disable=invalid-name,line-too-long exc = None classes = None method_name = 'EnumerateClasses' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , namespace = namespace , ClassName = ClassName , DeepInheritance = DeepInheritance , LocalOnly = LocalOnly , IncludeQualifiers = IncludeQualifiers , IncludeClassOrigin = IncludeClassOrigin , * * extra ) try : stats = self . statistics . start_timer ( method_name ) if namespace is None and isinstance ( ClassName , CIMClassName ) : namespace = ClassName . namespace namespace = self . _iparam_namespace_from_namespace ( namespace ) classname = self . _iparam_classname ( ClassName , 'ClassName' ) result = self . _imethodcall ( method_name , namespace , ClassName = classname , DeepInheritance = DeepInheritance , LocalOnly = LocalOnly , IncludeQualifiers = IncludeQualifiers , IncludeClassOrigin = IncludeClassOrigin , * * extra ) if result is None : classes = [ ] else : classes = result [ 0 ] [ 2 ] for klass in classes : if not isinstance ( klass , CIMClass ) : raise CIMXMLParseError ( _format ( "Expecting CIMClass object in result list, " "got {0} object" , klass . __class__ . __name__ ) , conn_id = self . conn_id ) # The EnumerateClasses CIM-XML operation returns classes # as CLASS elements, which do not contain a class path. # We want to return classes with a path (that has a namespace), # so we create the class path and set its namespace to the # effective target namespace. klass . path = CIMClassName ( classname = klass . classname , host = self . host , namespace = namespace ) return classes except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( classes , exc ) | Enumerate the subclasses of a class or the top - level classes in a namespace . | 612 | 19 |
28,286 | def EnumerateClassNames ( self , namespace = None , ClassName = None , DeepInheritance = None , * * extra ) : # pylint: disable=invalid-name,line-too-long exc = None classnames = None method_name = 'EnumerateClassNames' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , namespace = namespace , ClassName = ClassName , DeepInheritance = DeepInheritance , * * extra ) try : stats = self . statistics . start_timer ( method_name ) if namespace is None and isinstance ( ClassName , CIMClassName ) : namespace = ClassName . namespace namespace = self . _iparam_namespace_from_namespace ( namespace ) classname = self . _iparam_classname ( ClassName , 'ClassName' ) result = self . _imethodcall ( method_name , namespace , ClassName = classname , DeepInheritance = DeepInheritance , * * extra ) if result is None : classpaths = [ ] else : classpaths = result [ 0 ] [ 2 ] classnames = [ ] for classpath in classpaths : if not isinstance ( classpath , CIMClassName ) : raise CIMXMLParseError ( _format ( "Expecting CIMClassName object in result " "list, got {0} object" , classpath . __class__ . __name__ ) , conn_id = self . conn_id ) # The EnumerateClassNames CIM-XML operation returns class # paths as CLASSNAME elements. # We want to return class names as strings. classnames . append ( classpath . classname ) return classnames except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( classnames , exc ) | Enumerate the names of subclasses of a class or of the top - level classes in a namespace . | 520 | 22 |
28,287 | def ModifyClass ( self , ModifiedClass , namespace = None , * * extra ) : # pylint: disable=invalid-name exc = None method_name = 'ModifyClass' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , ModifiedClass = ModifiedClass , namespace = namespace , * * extra ) try : stats = self . statistics . start_timer ( method_name ) namespace = self . _iparam_namespace_from_namespace ( namespace ) klass = ModifiedClass . copy ( ) klass . path = None self . _imethodcall ( method_name , namespace , ModifiedClass = klass , has_return_value = False , * * extra ) return except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( None , exc ) | Modify a class . | 303 | 5 |
28,288 | def DeleteClass ( self , ClassName , namespace = None , * * extra ) : # pylint: disable=invalid-name,line-too-long exc = None method_name = 'DeleteClass' if self . _operation_recorders : self . operation_recorder_reset ( ) self . operation_recorder_stage_pywbem_args ( method = method_name , ClassName = ClassName , namespace = namespace , * * extra ) try : stats = self . statistics . start_timer ( method_name ) if namespace is None and isinstance ( ClassName , CIMClassName ) : namespace = ClassName . namespace namespace = self . _iparam_namespace_from_namespace ( namespace ) classname = self . _iparam_classname ( ClassName , 'ClassName' ) self . _imethodcall ( method_name , namespace , ClassName = classname , has_return_value = False , * * extra ) return except ( CIMXMLParseError , XMLParseError ) as exce : exce . request_data = self . last_raw_request exce . response_data = self . last_raw_reply exc = exce raise except Exception as exce : exc = exce raise finally : self . _last_operation_time = stats . stop_timer ( self . last_request_len , self . last_reply_len , self . last_server_response_time , exc ) if self . _operation_recorders : self . operation_recorder_stage_result ( None , exc ) | Delete a class . | 335 | 4 |
28,289 | def connectionMade ( self ) : self . factory . request_xml = str ( self . factory . payload ) self . sendCommand ( 'POST' , '/cimom' ) self . sendHeader ( 'Host' , '%s:%d' % ( self . transport . addr [ 0 ] , self . transport . addr [ 1 ] ) ) self . sendHeader ( 'User-Agent' , 'pywbem/twisted' ) self . sendHeader ( 'Content-length' , len ( self . factory . payload ) ) self . sendHeader ( 'Content-type' , 'application/xml' ) if self . factory . creds : auth = base64 . b64encode ( '%s:%s' % ( self . factory . creds [ 0 ] , self . factory . creds [ 1 ] ) ) self . sendHeader ( 'Authorization' , 'Basic %s' % auth ) self . sendHeader ( 'CIMOperation' , str ( self . factory . operation ) ) self . sendHeader ( 'CIMMethod' , str ( self . factory . method ) ) self . sendHeader ( 'CIMObject' , str ( self . factory . object ) ) self . endHeaders ( ) # TODO: Figure out why twisted doesn't support unicode. An # exception should be thrown by the str() call if the payload # can't be converted to the current codepage. self . transport . write ( str ( self . factory . payload ) ) | Send a HTTP POST command with the appropriate CIM over HTTP headers and payload . | 320 | 16 |
28,290 | def handleResponse ( self , data ) : self . factory . response_xml = data if self . status == '200' : self . factory . parseErrorAndResponse ( data ) self . factory . deferred = None self . transport . loseConnection ( ) | Called when all response data has been received . | 53 | 10 |
28,291 | def handleStatus ( self , version , status , message ) : self . status = status self . message = message | Save the status code for processing when we get to the end of the headers . | 23 | 16 |
28,292 | def handleHeader ( self , key , value ) : if key == 'CIMError' : self . CIMError = urllib . parse . unquote ( value ) if key == 'PGErrorDetail' : self . PGErrorDetail = urllib . parse . unquote ( value ) | Handle header values . | 67 | 4 |
28,293 | def handleEndHeaders ( self ) : if self . status != '200' : if not hasattr ( self , 'cimerror' ) or not hasattr ( self , 'errordetail' ) : self . factory . deferred . errback ( CIMError ( 0 , 'HTTP error %s: %s' % ( self . status , self . message ) ) ) else : self . factory . deferred . errback ( CIMError ( 0 , '%s: %s' % ( cimerror , errordetail ) ) ) | Check whether the status was OK and raise an error if not using previously saved header information . | 119 | 18 |
28,294 | def imethodcallPayload ( self , methodname , localnsp , * * kwargs ) : param_list = [ pywbem . IPARAMVALUE ( x [ 0 ] , pywbem . tocimxml ( x [ 1 ] ) ) for x in kwargs . items ( ) ] payload = cim_xml . CIM ( cim_xml . MESSAGE ( cim_xml . SIMPLEREQ ( cim_xml . IMETHODCALL ( methodname , cim_xml . LOCALNAMESPACEPATH ( [ cim_xml . NAMESPACE ( ns ) for ns in localnsp . split ( '/' ) ] ) , param_list ) ) , '1001' , '1.0' ) , '2.0' , '2.0' ) return self . xml_header + payload . toxml ( ) | Generate the XML payload for an intrinsic methodcall . | 195 | 11 |
28,295 | def methodcallPayload ( self , methodname , obj , namespace , * * kwargs ) : if isinstance ( obj , CIMInstanceName ) : path = obj . copy ( ) path . host = None path . namespace = None localpath = cim_xml . LOCALINSTANCEPATH ( cim_xml . LOCALNAMESPACEPATH ( [ cim_xml . NAMESPACE ( ns ) for ns in namespace . split ( '/' ) ] ) , path . tocimxml ( ) ) else : localpath = cim_xml . LOCALCLASSPATH ( cim_xml . LOCALNAMESPACEPATH ( [ cim_xml . NAMESPACE ( ns ) for ns in namespace . split ( '/' ) ] ) , obj ) def paramtype ( obj ) : """Return a string to be used as the CIMTYPE for a parameter.""" if isinstance ( obj , cim_types . CIMType ) : return obj . cimtype elif type ( obj ) == bool : return 'boolean' elif isinstance ( obj , six . string_types ) : return 'string' elif isinstance ( obj , ( datetime , timedelta ) ) : return 'datetime' elif isinstance ( obj , ( CIMClassName , CIMInstanceName ) ) : return 'reference' elif isinstance ( obj , ( CIMClass , CIMInstance ) ) : return 'string' elif isinstance ( obj , list ) : return paramtype ( obj [ 0 ] ) raise TypeError ( 'Unsupported parameter type "%s"' % type ( obj ) ) def paramvalue ( obj ) : """Return a cim_xml node to be used as the value for a parameter.""" if isinstance ( obj , ( datetime , timedelta ) ) : obj = CIMDateTime ( obj ) if isinstance ( obj , ( cim_types . CIMType , bool , six . string_types ) ) : return cim_xml . VALUE ( cim_types . atomic_to_cim_xml ( obj ) ) if isinstance ( obj , ( CIMClassName , CIMInstanceName ) ) : return cim_xml . VALUE_REFERENCE ( obj . tocimxml ( ) ) if isinstance ( obj , ( CIMClass , CIMInstance ) ) : return cim_xml . VALUE ( obj . tocimxml ( ) . toxml ( ) ) if isinstance ( obj , list ) : if isinstance ( obj [ 0 ] , ( CIMClassName , CIMInstanceName ) ) : return cim_xml . VALUE_REFARRAY ( [ paramvalue ( x ) for x in obj ] ) return cim_xml . VALUE_ARRAY ( [ paramvalue ( x ) for x in obj ] ) raise TypeError ( 'Unsupported parameter type "%s"' % type ( obj ) ) param_list = [ cim_xml . PARAMVALUE ( x [ 0 ] , paramvalue ( x [ 1 ] ) , paramtype ( x [ 1 ] ) ) for x in kwargs . items ( ) ] payload = cim_xml . CIM ( cim_xml . MESSAGE ( cim_xml . SIMPLEREQ ( cim_xml . METHODCALL ( methodname , localpath , param_list ) ) , '1001' , '1.0' ) , '2.0' , '2.0' ) return self . xml_header + payload . toxml ( ) | Generate the XML payload for an extrinsic methodcall . | 770 | 13 |
28,296 | def parseErrorAndResponse ( self , data ) : xml = fromstring ( data ) error = xml . find ( './/ERROR' ) if error is None : self . deferred . callback ( self . parseResponse ( xml ) ) return try : code = int ( error . attrib [ 'CODE' ] ) except ValueError : code = 0 self . deferred . errback ( CIMError ( code , error . attrib [ 'DESCRIPTION' ] ) ) | Parse returned XML for errors then convert into appropriate Python objects . | 98 | 13 |
28,297 | def start ( self ) : thread = threading . Thread ( target = reactor . run ) thread . start ( ) | doesn t work | 24 | 3 |
28,298 | def MI_associatorNames ( self , env , objectName , assocClassName , resultClassName , role , resultRole ) : # pylint: disable=invalid-name logger = env . get_logger ( ) logger . log_debug ( 'CIMProvider2 MI_associatorNames called. ' 'assocClass: %s' % ( assocClassName ) ) if not assocClassName : raise pywbem . CIMError ( pywbem . CIM_ERR_FAILED , "Empty assocClassName passed to AssociatorNames" ) model = pywbem . CIMInstance ( classname = assocClassName ) model . path = pywbem . CIMInstanceName ( classname = assocClassName , namespace = objectName . namespace ) gen = self . references ( env = env , object_name = objectName , model = model , result_class_name = resultClassName , role = role , result_role = None , keys_only = False ) if gen is None : logger . log_debug ( 'references() returned None instead of ' 'generator object' ) return for inst in gen : for prop in inst . properties . values ( ) : lpname = prop . name . lower ( ) if prop . type != 'reference' : continue if role and role . lower ( ) == lpname : continue if resultRole and resultRole . lower ( ) != lpname : continue if self . paths_equal ( prop . value , objectName ) : continue if resultClassName and resultClassName . lower ( ) != prop . value . classname . lower ( ) : continue if prop . value . namespace is None : prop . value . namespace = objectName . namespace yield prop . value logger . log_debug ( 'CIMProvider2 MI_associatorNames returning' ) | Return instances names associated to a given object . | 401 | 9 |
28,299 | def _get_callable ( self , classname , cname ) : callable = None if classname in self . provregs : provClass = self . provregs [ classname ] if hasattr ( provClass , cname ) : callable = getattr ( provClass , cname ) elif hasattr ( self . provmod , cname ) : callable = getattr ( self . provmod , cname ) if callable is None : raise pywbem . CIMError ( pywbem . CIM_ERR_FAILED , "No provider registered for %s or no callable for %s:%s on " "provider %s" % ( classname , classname , cname , self . provid ) ) return callable | Return a function or method object appropriate to fulfill a request | 167 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.