def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): if object_name.classname.lower() == 'pytut_foo': # The target object for the association related call is a PyTut_Foo # object. model['TheFoo'] = object_name for k, v in _FooComps.items(): if v == object_name['FooKey']: model['TheFooComp'] = pywbem.CIMInstanceName( classname='PyTut_FooComponent', namespace=object_name.namespace, keybindings={'FooCompKey': k}) yield model elif object_name.classname.lower() == 'pytut_foocomponent': # The target object for the association related call is a # PyTut_FooComponent object model['TheFoo'] = object_name thekey = object_name['FooCompKey'] if not thekey in _FooComps: return model['TheFooComp'] = object_name thevalue = _FooComps[thekey] for k, v in _FooInsts.items(): if k == thevalue: model['TheFoo'] = pywbem.CIMInstanceName( classname='PyTut_Foo', namespace=object_name.namespace, keybindings={'FooKey': k}) yield model
def enum_instances(self, env, model, keys_only): """Enumerate instances. The WBEM operations EnumerateInstances and EnumerateInstanceNames are both mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) model -- A template of the pywbem.CIMInstances to be generated. The properties of the model are already filtered according to the PropertyList from the request. Only properties present in the model need to be given values. If you prefer, you can always set all of the values, and the instance will be filtered for you. keys_only -- A boolean. True if only the key properties should be set on the generated instances. Possible Errors: CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.enum_instances()' \ % self.__class__.__name__) if POLLUPDATE: poll_updater.updatePollFile(logger) # Prime model.path with knowledge of the keys, so key values on # the CIMInstanceName (model.path) will automatically be set when # we set property values on the model. model.path.update({'Dependent': None, 'Antecedent': None}) systemCreationClassName, systemName = self.getComputerSystemName(env) self._populateTroveCache() for troveId in sorted(self._conarySoftwareMap): # We need to specify the namespace, otherwise sfcb segfaults. model['Dependent'] = pywbem.CIMInstanceName( classname=systemCreationClassName, keybindings=dict(Name=systemName, CreationClassName=systemCreationClassName), namespace="root/cimv2") model['Antecedent'] = pywbem.CIMInstanceName( classname='VAMI_SoftwareIdentity', keybindings=dict(InstanceID=troveId), namespace="root/cimv2", ) if keys_only: yield model else: try: yield self.get_instance(env, model, withCleanup=False) except pywbem.CIMError, (num, msg): if num not in (pywbem.CIM_ERR_NOT_FOUND, pywbem.CIM_ERR_ACCESS_DENIED): raise
def enum_instances(self, env, model, cim_class, keys_only): for k, v in _FooComps.items(): if v in _FooInsts: model['TheFoo'] = pywbem.CIMInstanceName( classname='PyTut_Foo', namespace=model.path.namespace, keybindings={'FooKey': v}) model['TheFooComp'] = pywbem.CIMInstanceName( classname='PyTut_FooComponent', namespace=model.path.namespace, keybindings={'FooCompKey': k}) yield model
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): """Instrument PyFooAssociation Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment object_name -- A CIMInstanceName that defines the source CIM Object whose associated Objects are to be returned. model -- A template CIMInstance of PyFooAssociation to serve as a model of the objects to be returned. Only properties present on this model need to be returned. assoc_class -- The CIMClass PyFooAssociation result_class_name -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be either an Instance of this Class (or one of its subclasses) or be this Class (or one of its subclasses). role -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be associated to the source Object via an Association in which the source Object plays the specified role (i.e. the name of the Property in the Association Class that refers to the source Object MUST match the value of this parameter). result_role -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be associated to the source Object via an Association in which the returned Object plays the specified role (i.e. the name of the Property in the Association Class that refers to the returned Object MUST match the value of this parameter). """ if object_name.classname.lower() == 'pyfoo': model['ThePyFoo'] = object_name for k, v in _PyFooComps.items(): if v == object_name['FooKey']: model['TheComp'] = pywbem.CIMInstanceName( classname='PyFooComponent', namespace=object_name.namespace, keybindings={'TheKey': k}) yield model elif object_name.classname.lower() == 'pyfoocomponent': model['TheComp'] = object_name try: model['ThePyFoo'] = pywbem.CIMInstanceName( classname='PyFoo', namespace=object_name.namespace, keybindings={'FooKey': _PyFooComps[object_name['TheKey']]}) yield model except KeyError: pass else: raise pywbem.CIMError(pywbem.CIM_ERR_FAILED, '')
def _createFilter(query, ns, querylang='WQL', src_ns='root/cimv2', in_name=None): name = in_name or 'cimfilter%s' % time.time() filterinst = pywbem.CIMInstance('CIM_IndicationFilter') filterinst['CreationClassName'] = 'CIM_IndicationFilter' filterinst['SystemCreationClassName'] = 'CIM_ComputerSystem' filterinst['SystemName'] = getfqdn() filterinst['Name'] = name filterinst['Query'] = query filterinst['QueryLanguage'] = querylang filterinst['SourceNamespace'] = src_ns cop = pywbem.CIMInstanceName('CIM_IndicationFilter') cop.keybindings = { 'CreationClassName': 'CIM_IndicationFilter', 'SystemClassName': 'CIM_ComputerSystem', 'SystemName': getfqdn(), 'Name': name } cop.namespace = ns filterinst.path = cop filtercop = conn.CreateInstance(filterinst) return filtercop
def path_str_to_cim_path(path_str): """ Convert a string into CIMInstanceName. Args: path_str: String to convert into a CIMInstanceName """ path_dict = json.loads(path_str) return pywbem.CIMInstanceName(**path_dict)
def getinstancename(classname, bindings): instancename = None try: instancename = pywbem.CIMInstanceName(classname, namespace=EMC_ROOT, keybindings=bindings) except NameError: instancename = None return instancename
def _createSubscription(ns, handler, indfilter): subinst = pywbem.CIMInstance('CIM_IndicationSubscription') subinst['Filter'] = indfilter subinst['Handler'] = indhandler cop = pywbem.CIMInstanceName('CIM_IndicationSubscription') cop.keybindings = {'Filter': indfilter, 'Handler': indhandler} cop.namespace = ns subinst.path = cop subcop = conn.CreateInstance(subinst) return subcop
def get_instance(conn, keybindings, propertylist=None): if propertylist is None: propertylist = [] inst = None try: iname = pywbem.CIMInstanceName(classname='TestAtom', \ keybindings=(keybindings), namespace='root/cimv2') inst = conn.GetInstance(iname, PropertyList=propertylist) except pywbem.CIMError, arg: raise (arg)
def cim_method_scan(self, env, object_name, param_desiredpackages=None): """Implements RPATH_SystemSurveyService.Scan() Check for updates Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName specifying the object on which the method Scan() should be invoked. param_desiredpackages-- The input parameter DesiredPackages (type [unicode,]) A list of packages against which a preview will be computed Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.Scan) and a list of CIMParameter objects representing the output parameters Output parameters: Job -- (type REF (pywbem.CIMInstanceName(classname='CIM_ConcreteJob', ...)) Reference to the job (may be null if job completed). Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_NOT_FOUND (the target CIM Class or instance does not exist in the specified namespace) CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor the invocation request) CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.cim_method_scan()' \ % self.__class__.__name__) # Create update job sserv = concrete_job.SurveyJob() job = sserv.scan(param_desiredpackages) jobInstanceID = RPATH_SurveyConcreteJob.RPATH_SurveyConcreteJob.createInstanceID( job.get_job_id()) job = pywbem.CIMInstanceName( classname='RPATH_SurveyConcreteJob', keybindings=dict(InstanceID=jobInstanceID), namespace="root/cimv2") out_params = [] out_params.append( pywbem.CIMParameter('job', type='reference', value=job)) rval = self.Values.Scan.Method_Parameters_Checked___Job_Started return (rval, out_params)
def enum_instances(self, env, model, cim_class, keys_only): """ Enumerate instances of PyFooAssociation The WBEM operations EnumerateInstances and EnumerateInstanceNames are both mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment model -- A template of the CIMInstances to be generated. The properties of the model are already filtered according to the PropertyList from the request. cim_class -- The CIMClass PyFooAssociation keys_only -- A boolean. True if only the key properties should be set on the generated instances. """ for comp_k, foo_k in _PyFooComps.items(): # TODO fetch system resource # Key properties model['ThePyFoo'] = pywbem.CIMInstanceName( classname='PyFoo', namespace=model.path.namespace, keybindings={'FooKey': foo_k}) model['TheComp'] = pywbem.CIMInstanceName( classname='PyFooComponent', namespace=model.path.namespace, keybindings={'TheKey': comp_k}) if keys_only: yield model else: try: yield self.get_instance(env, model, cim_class) except pywbem.CIMError, (num, msg): if num in (pywbem.CIM_ERR_NOT_FOUND, pywbem.CIM_ERR_ACCESS_DENIED): pass # EnumerateInstances shouldn't return these else: raise
def create_instancename(string): ''' create CIMinstanceName from string ''' instancename_info = eval(string.replace(ESC_SPACE, ' ')) try: instancename = pywbem.CIMInstanceName( instancename_info['classname'], namespace=instancename_info['namespace'], keybindings=instancename_info['keybindings']) except NameError as ex: print ex sys.exit(1) return instancename
def _enum(self, ns, classname, keys_only=True): if (ns, classname) not in self.instances: raise Exception("Mock me! %s" % classname) for className, keybindings, props in self.instances[(ns, classname)]: op = pywbem.CIMInstanceName(className, keybindings=keybindings, namespace=ns) if keys_only: yield op else: inst = pywbem.CIMInstance(className, properties=props, path=op) inst.update(keybindings) yield inst
def _get_volume_instance(self, volume): try: pl = eval(volume.provider_location) except (SyntaxError, ValueError, TypeError): LOG.warning("Invalid provider location for volume '%s'", volume.id) return None try: return pywbem.CIMInstanceName(classname=pl['classname'], namespace=EMC_ROOT, keybindings=pl['keybindings']) except NameError: LOG.warning("Unable to get volume instance from EMC ECOM") return None
def cim_method_getobjectpaths(self, env, object_name, method): logger = env.get_logger() logger.log_debug('Entering %s.cim_method_getobjectpaths()' \ % self.__class__.__name__) paths = [] for key in g_insts.keys(): paths.append( pywbem.CIMInstanceName('TestMethod', namespace=object_name.namespace, keybindings={'id': key})) out_params = {} out_params['paths'] = paths rval = pywbem.Sint32(0) return (rval, out_params)
def run(self): log = self.env.get_logger() log.log_debug('##### IndicationThread.run entered...') self.shuttingdown = False ch = self.env.get_cimom_handle() while not self.shuttingdown: # Acquire the lock on the condition variable before we wait on it self._cond.acquire() # We'll wait on the condition for 5 seconds. Then we'll # wake up and generate an indication l = self._cond.wait(5.0) self._cond.release() # If we're shutting down, just break out of this loop if self.shuttingdown: break # Modify 'Key2' of _PyFooInsts and generate a CIM_InstModification # life cycle indication k = 'Key2' v = _PyFooInsts[k] cipath = pywbem.CIMInstanceName('PyIndFoo', {'TheKey': k}, namespace='root/cimv2') pci = pywbem.CIMInstance('PyIndFoo', { 'TheKey': k, 'TheValue': pywbem.Sint32(v) }, path=cipath) v += 1 _PyFooInsts[k] = v sci = pywbem.CIMInstance('PyIndFoo', { 'TheKey': k, 'TheValue': pywbem.Sint32(v) }, path=cipath) self.count += 1 ci = pywbem.CIMInstance('CIM_InstModification') ci['PreviousInstance'] = pci ci['SourceInstance'] = sci ci['SourceInstanceModelPath'] = cipath ci['IndicationIdentifier'] = 'PyTestInd:%s' % self.count ci['IndicationTime'] = pywbem.CIMDateTime.now() ci['PerceivedSeverity'] = pywbem.Uint16(2) ch.export_indication(ci, 'root/cimv2') log.log_debug('##### IndicationThread.run returning')
def cim_method_getobjectpath(self, env, object_name, method): logger = env.get_logger() logger.log_debug('Entering %s.cim_method_getobjectpath()' \ % self.__class__.__name__) if not g_insts: path = None rval = pywbem.Sint32(pywbem.CIM_ERR_NOT_FOUND) else: path = pywbem.CIMInstanceName( 'TestMethod', namespace=object_name.namespace, keybindings={'id': g_insts.keys()[0]}) rval = pywbem.Sint32(0) out_params = {} out_params['path'] = path return (rval, out_params)
def WbemNoQueryOneInst( conn, className, splitMonik, nameSpace ): try: keyBnds = pywbem.cim_obj.NocaseDict( splitMonik ) # FIXME: Problem with parameters: msgExcFirst=CIMError: header-mismatch, PGErrorDetail: # Empty CIMObject value. wbemInstName=root/CIMv2:CIM_ComputerSystem.Name="rchateau-HP". # ns=. Caught:(4, u'CIM_ERR_INVALID_PARAMETER: Wrong number of keys') # wbemInstName = pywbem.CIMInstanceName( className, keybindings = keyBnds, host = cimomUrl, namespace = nameSpace ) wbemInstName = pywbem.CIMInstanceName( className, keybindings = keyBnds, namespace = "root/CIMv2" ) DEBUG("keyBnds=%s wbemInstName=%s", str(keyBnds),str(wbemInstName)) wbemInstObj = conn.GetInstance( wbemInstName ) return [ wbemInstObj ] except: exc = sys.exc_info()[1] # lib_common.ErrorMessageHtml("msgExcFirst="+msgExcFirst+" wbemInstName=" + str(wbemInstName) + ". ns="+nameSpace+". Caught:"+str(exc)) WARNING("WbemNoQueryOneInst className=" + str(className) + ". ns="+nameSpace+".\nCaught:"+str(exc)) return None
def get_instance_name(self, classname, bindings): """Get the instance from the classname and bindings. NOTE: This exists in common too...will be moving it to other file where both common and masking can access it :param classname: connection to the ecom server :param bindings: volume created from job :returns: foundVolumeInstance - the volume instance """ instanceName = None try: instanceName = pywbem.CIMInstanceName(classname, namespace=EMC_ROOT, keybindings=bindings) except NameError: instanceName = None return instanceName
def createDest(self, destination, ns, in_name=None): name = in_name or 'cimlistener%d'%time.time() destinst=pywbem.CIMInstance('CIM_ListenerDestinationCIMXML') destinst['CreationClassName']='CIM_ListenerDestinationCIMXML' destinst['SystemCreationClassName']='CIM_ComputerSystem' destinst['SystemName']=getfqdn() destinst['Name']=name destinst['Destination']=destination cop = pywbem.CIMInstanceName('CIM_ListenerDestinationCIMXML') cop.keybindings = { 'CreationClassName':'CIM_ListenerDestinationCIMXML', 'SystemCreationClassName':'CIM_ComputerSystem', 'SystemName':getfqdn(), 'Name':name } cop.namespace=ns destinst.path = cop destcop = self._conn.CreateInstance(destinst) return destcop
def WbemNoQueryOneInst(conn, class_name, split_monik, name_space): try: key_bnds = pywbem.cim_obj.NocaseDict(split_monik) # FIXME: Problem with parameters: msgExcFirst=CIMError: header-mismatch, PGErrorDetail: # Empty CIMObject value. wbem_inst_name=root/CIMv2:CIM_ComputerSystem.Name="mymachine". # ns=. Caught:(4, u'CIM_ERR_INVALID_PARAMETER: Wrong number of keys') wbem_inst_name = pywbem.CIMInstanceName(class_name, keybindings=key_bnds, namespace="root/CIMv2") logging.debug("key_bnds=%s wbem_inst_name=%s", str(key_bnds), str(wbem_inst_name)) wbem_inst_obj = conn.GetInstance(wbem_inst_name) return [wbem_inst_obj] except Exception as exc: logging.warning("class_name=" + str(class_name) + ". ns=" + name_space + ". Caught:" + str(exc)) return None
def createFilter(self, query, ns, in_name=None): name = in_name or 'cimfilter%d'%time.time() filterinst=pywbem.CIMInstance('CIM_IndicationFilter') filterinst['CreationClassName']='CIM_IndicationFilter' filterinst['SystemCreationClassName']='CIM_ComputerSystem' filterinst['SystemName']=getfqdn() filterinst['Name']=name filterinst['Query']=query filterinst['QueryLanguage']='WQL' cop = pywbem.CIMInstanceName('CIM_IndicationFilter') cop.keybindings = { 'CreationClassName':'CIM_IndicationFilter', 'SystemCreationClassName':'CIM_ComputerSystem', 'SystemName':getfqdn(), 'Name':name } cop.namespace=ns filterinst.path = cop filtercop = self._conn.CreateInstance(filterinst) return filtercop
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): logger = env.get_logger() if object_name.classname.lower() == 'pytut_foo': if role and role.lower() != 'thefoo': logger.log_debug('PyTut_FooAssociation. Invalid role: %s' % role) return if result_role and result_role.lower() != 'thefoocomp': logger.log_debug('PyTut_FooAssociation. Invalid result_role: ' '%s' % result_role) return if result_class_name and result_class_name.lower( ) != 'pytut_foocomponent': logger.log_debug('PyTut_FooAssociation. Invalid ' 'result_class_name: %s' % result_class_name) return fk = 'FooKey' in object_name.keybindings and object_name[ 'FooKey'] or None if not fk: logger.log_error('PyTut_FooAssociation. No key value given ' 'for PyTut_Foo object') return # Get all instances of PyTut_FooComponent that have a FooCompValue # property that matches the key to this PyTut_Foo object ch = env.get_cimom_handle() ilist = [] try: ch.EnumerateInstances('PyTut_FooComponent', object_name.namespace, LocalOnly=False, IncludeQualifiers=False, Handler=lambda inst: inst['FooCompValue'] == fk and ilist.append(inst)) except: logger.log_error('PyTut_FooAssociation. Got error enumerating ' 'instances of PyTut_FooComponent') return # All instances of PyTut_FooComponent that refer to the given # PyTut_Foo should be in ilist at this point for inst in ilist: if 'TheFooComp' in model: model['TheFooComp'] = inst.path if 'TheFoo' in model: model['TheFoo'] = object_name yield model elif object_name.classname.lower() == 'pytut_foocomponent': if role and role.lower() != 'thefoocomp': logger.log_debug('PyTut_FooAssociation. Invalid role: %s' % role) return if result_role and result_role.lower() != 'thefoo': logger.log_debug('PyTut_FooAssociation. Invalid result_role: ' '%s' % result_role) return if result_class_name and result_class_name.lower() != 'pytut_foo': logger.log_debug('PyTut_FooAssociation. Invalid ' 'result_class_name: %s' % result_class_name) return ch = env.get_cimom_handle() try: # Get the instance of the PyTut_FooComponent in order to get # its FooCompValue property inst = ch.GetInstance(object_name, LocalOnly=False, IncludeQualifiers=False, IncludeClassOrigin=False) fooname = pywbem.CIMInstanceName( 'PyFoo', {'FooKey': inst['FooCompValue']}, namespace=object_name.namespace) fooinst = ch.GetInstance(fooname, LocalOnly=False, IncludeQualifiers=False, IncludeClassOrigin=False) if 'TheFooComp' in model: model['TheFooComp'] = object_name if 'TheFoo' in model: model['TheFoo'] = fooinst.path yield model except: pass
def cim_method_methodtest(self, env, object_name, method, param_paths, param_embedded, param_nullparam, param_uint8array, param_s, param_embedded_a, param_io16): """Implements Py_LotsOfDataTypes.MethodTest() Keyword arguments: env -- Provider Environment object_name -- A CIMInstanceName or CIMCLassName specifying the object on which the method %(mname)s should be invoked method -- A CIMMethod representing the method meta-data param_paths -- The input parameter paths (type REF CIM_System (CIMInstanceName)[]) param_embedded -- The input parameter embedded (type string) param_nullparam -- The input parameter nullParam (type datetime) param_uint8array -- The input parameter uint8array (type uint8[]) param_s -- The input parameter s (type string) (Required) param_embedded_a -- The input parameter embedded_a (type string[]) param_io16 -- The input parameter io16 (type sint16) Returns a two-tuple containing the return value (type string) and a dictionary with the out-parameters Output parameters: paths -- (type REF CIM_System (CIMInstanceName)[]) b -- (type boolean) embedded -- (type string) nullParam -- (type datetime) embedded_a -- (type string[]) io16 -- (type sint16) r64 -- (type real64) msg -- (type string) """ # TODO do something insts = [ pywbem.CIMInstance(classname='PyFoo', properties={ 'FooValue': pywbem.Sint32(3), 'FooKey': 'Key3' }, path=pywbem.CIMInstanceName( classname='PyFoo', namespace='root/cimv2')), pywbem.CIMInstance(classname='PyFoo', properties={ 'FooValue': pywbem.Sint32(2), 'FooKey': 'Key2' }, path=pywbem.CIMInstanceName( classname='PyFoo', namespace='root/cimv2')) ] out_params = {} out_params['paths'] = param_paths out_params['b'] = True if param_embedded is not None: out_params['embedded'] = param_embedded else: out_params['embedded'] = insts[0] out_params['nullparam'] = None if param_embedded_a is not None: out_params['embedded_a'] = param_embedded_a else: out_params['embedded_a'] = insts out_params['io16'] = pywbem.Sint16(16) out_params['r64'] = pywbem.Real64(3.14159) out_params['msg'] = 'A message' rval = 'Return' + ` out_params ` return (rval, out_params)
def create_new_PV_and_HVM_vms (conn, vsms): # # the metadata for a XenServer Paravirtualized VM we are going to create pv_virtualsystemsettingdata = pywbem.CIMInstance ("Xen_ComputerSystemSettingData") pv_virtualsystemsettingdata['Caption'] = "This is a PV VM" pv_virtualsystemsettingdata['ElementName'] = "test-pv-vm" pv_virtualsystemsettingdata['VirtualSystemType'] = "DMTF:xen:PV" pv_virtualsystemsettingdata['AutomaticShutdownAction'] = pywbem.Uint8(0) pv_virtualsystemsettingdata['AutomaticStarupAction'] = pywbem.Uint8(1) pv_virtualsystemsettingdata['AutomaticRecoveryAction'] = pywbem.Uint8(2) # the following are XenServer specific CIM extensions pv_virtualsystemsettingdata['PV_Bootloader'] = "pygrub" # use pygrub as the bootloader pv_virtualsystemsettingdata['PV_Bootloader_Args'] = "" pv_virtualsystemsettingdata['PV_Args'] = "Term=xterm" # We shall also base the PV VM on an existing XenServer template # This automatically allocates default proc/mem/disk/network resources specified by the template pv_template_list = conn.ExecQuery("WQL", "SELECT * FROM Xen_ComputerSystemTemplate WHERE ElementName LIKE \"%Debian Lenny%\"", "root/cimv2") reference_configuration = pywbem.CIMInstanceName(classname=pv_template_list[0].classname, keybindings={"InstanceID":pv_template_list[0]["InstanceID"]}) # The metadata settings for a XenServer HVM VM (Hardware Virtualized) we will create hvm_virtualsystemsettingdata = pywbem.CIMInstance("Xen_ComputerSystemSettingData") hvm_virtualsystemsettingdata['Caption'] = 'This is an HVM VM' hvm_virtualsystemsettingdata['ElementName'] = 'test-hvm-vm' hvm_virtualsystemsettingdata['VirtualSystemType'] = 'DMTF:xen:HVM' hvm_virtualsystemsettingdata['AutomaticShutdownAction'] = pywbem.Uint8(0) hvm_virtualsystemsettingdata['AutomaticStarupAction'] = pywbem.Uint8(1) hvm_virtualsystemsettingdata['AutomaticRecoveryAction'] = pywbem.Uint8(2) # the following are XenServer specific CIM extensions hvm_virtualsystemsettingdata['HVM_Boot_Params'] = ['order=dc'] # boot order is cd drive and then hard drive hvm_virtualsystemsettingdata['HVM_Boot_Policy'] = 'BIOS order' # boot based on the BIOS boot order specified above hvm_virtualsystemsettingdata['Platform'] = ['acpi=true','apic=true','pae=true'] # use ACPI, APIC, PAE emulation # # define all the resource settings (processor, memory, disk, network) # via ResourceAllocationSettingData instances # # processor proc_resource = pywbem.CIMInstance('CIM_ResourceAllocationSettingData') proc_resource['ResourceType'] = pywbem.Uint16(3) proc_resource['VirtualQuantity'] = pywbem.Uint64(1) proc_resource['AllocationUnits'] = "count" proc_resource['Limit'] = pywbem.Uint32(100) proc_resource['Weight'] = pywbem.Uint32(512) # memory mem_resource = pywbem.CIMInstance('CIM_ResourceAllocationSettingData') mem_resource['ResourceType'] = pywbem.Uint16(4) mem_resource['VirtualQuantity'] = pywbem.Uint64(512) mem_resource['AllocationUnits'] = 'byte*2^20' # DMTF way of specifying MegaBytes # disks sr_to_use = None # find all SRs available to us srs = conn.EnumerateInstances("Xen_StoragePool") for sr in srs: if sr['Name'] == 'Local storage': sr_to_use = sr disk_resource = pywbem.CIMInstance('Xen_DiskSettingData') disk_resource['Elementname'] = 'my_vm_disk' disk_resource['ResourceType'] = pywbem.Uint16(19) disk_resource['ResourceSubType'] = "Disk" # as opposed to "CD" disk_resource['VirtualQuantity'] = pywbem.Uint64(2048) disk_resource['AllocationUnits'] = "byte*2^20" # DMTF way of specifying MegaBytes disk_resource['Access'] = pywbem.Uint8(3) disk_resource['Bootable'] = False disk_resource['PoolID'] = sr_to_use['PoolID']# XenServer SR to allocate the disk out of # nic network_to_use = None # find all network switch connection pools available to us networks = conn.EnumerateInstances("Xen_NetworkConnectionPool") for network in networks: if network['Name'].find('eth0') != -1: network_to_use = network # only RASDs of type NetworkConnection (33) are supported nic_resource = pywbem.CIMInstance('Xen_NetworkPortSettingData') nic_resource['ResourceType'] = pywbem.Uint16(33) nic_resource['ElementName'] = "0" nic_resource['PoolID'] = network_to_use['PoolID']# Virtual Switch to connect to rasds = [proc_resource, mem_resource, disk_resource, nic_resource] hvm_params = {'SystemSettings': hvm_virtualsystemsettingdata, 'ResourceSettings': rasds } pv_params = {'SystemSettings': pv_virtualsystemsettingdata, 'ReferenceConfiguration': reference_configuration} print '*** Creating PV VM %s' % (pv_virtualsystemsettingdata['ElementName']) new_pv_vm_reference = create_vm_helper(conn, vsms, pv_params) print '*** Creating HVM VM %s' % (hvm_virtualsystemsettingdata['ElementName']) new_hvm_vm_reference = create_vm_helper(conn, vsms, hvm_params) if new_pv_vm_reference == None: print 'PV VM was not created' sys.exit(1) if new_hvm_vm_reference == None: print 'HVM VM was not created' sys.exit(1) return [new_pv_vm_reference, new_hvm_vm_reference]
def test_refs(self): inst = pywbem.CIMInstance('TestMethod', properties={ 'id': 'one', 'p_str': 'One', 'p_sint32': pywbem.Sint32(1) }) self.conn.CreateInstance(inst) iname = pywbem.CIMInstanceName('TestMethod', namespace='root/cimv2', keybindings={'id': 'one'}) rv, outs = self.conn.InvokeMethod('getStrProp', iname) self.assertEquals(rv, 'One') rv, outs = self.conn.InvokeMethod('setStrProp', iname, value='won') self.assertFalse(outs) self.assertEquals(rv, 'One') rv, outs = self.conn.InvokeMethod('getStrProp', iname) self.assertEquals(rv, 'won') inst = self.conn.GetInstance(iname) self.assertEquals(inst['p_str'], 'won') rv, outs = self.conn.InvokeMethod('getIntProp', iname) self.assertEquals(rv, 1) self.assertTrue(isinstance(rv, pywbem.Sint32)) self.assertEquals(inst['p_sint32'], 1) rv, outs = self.conn.InvokeMethod('setIntProp', iname, value=pywbem.Sint32(2)) self.assertTrue(isinstance(rv, pywbem.Sint32)) self.assertEquals(rv, 1) self.assertFalse(outs) rv, outs = self.conn.InvokeMethod('getIntProp', iname) self.assertEquals(rv, 2) self.assertTrue(isinstance(rv, pywbem.Sint32)) inst = self.conn.GetInstance(iname) self.assertEquals(inst['p_sint32'], 2) rv, outs = self.conn.InvokeMethod('getObjectPath', 'TestMethod') self.assertTrue(isinstance(outs['path'], pywbem.CIMInstanceName)) self.assertEquals(outs['path']['id'], 'one') inst = pywbem.CIMInstance('TestMethod', properties={ 'id': 'two', 'p_str': 'Two', 'p_sint32': pywbem.Sint32(2) }) self.conn.CreateInstance(inst) rv, outs = self.conn.InvokeMethod('getObjectPaths', 'TestMethod') self.assertEquals(len(outs['paths']), 2) self.assertTrue(isinstance(outs['paths'][0], pywbem.CIMInstanceName)) to_delete = outs['paths'] inst = pywbem.CIMInstance('TestMethod', properties={ 'id': 'three', 'p_str': 'Three', 'p_sint32': pywbem.Sint32(3) }) self.conn.CreateInstance(inst) iname = pywbem.CIMInstanceName('TestMethod', namespace='root/cimv2', keybindings={'id': 'three'}) inames = self.conn.EnumerateInstanceNames('TestMethod') self.assertEquals(len(inames), 3) rv, outs = self.conn.InvokeMethod('delObject', 'TestMethod', path=iname) inames = self.conn.EnumerateInstanceNames('TestMethod') self.assertEquals(len(inames), 2) self.conn.CreateInstance(inst) ''' # OpenWBEM is broken! uncomment this for Pegasus. ''' rv, outs = self.conn.InvokeMethod('delObjects', 'TestMethod', paths=to_delete) inames = self.conn.EnumerateInstanceNames('TestMethod') self.assertEquals(len(inames), 1) self.assertEquals(inames[0]['id'], 'three')
def getProvider(self, module): """Given a module, return the provider and an object path""" cimClassName, prov = sorted(module.get_providers(self.env).items())[0] objPath = pywbem.CIMInstanceName(cimClassName) return prov, objPath
nameSpace = cgiVal elif cgiKey == "url": cgiUrl = cgiVal else: keyBindings[cgiKey] = cgiVal # http://127.0.0.1/Survol/wbem/EnumInstanceNames.py?classname=TUT_UnixProcess&ns=root/cimv2&url=http://192.168.1.88 print("Objects of class " + wbem_utils.HrefClassName(className, nameSpace, cgiUrl) + "<br>") conn = wbem_utils.WbemConnection(cgiUrl) DisplayClass(conn, className) try: instanceNameObject = pywbem.CIMInstanceName(className, keyBindings, None, nameSpace) except Exception: exc = sys.exc_info()[1] print("CIMInstanceName nameSpace=" + nameSpace + " className=" + className + ". Caught:" + str(exc) + "<br>") try: instObj = conn.GetInstance(instanceNameObject) wbem_utils.PrintObjToHtml([list(instObj.items())]) print("<br>") except Exception: exc = sys.exc_info()[1] print("nameSpace=" + str(nameSpace) + " className=" + str(className) + " inst=" + str(instanceNameObject) + ". Caught:" + str(exc) + "<br>") # Pas la peine d afficher les infos comme ca mais plutot
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): """Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment object_name -- A CIMInstanceName that defines the source CIM Object whose associated Objects are to be returned. model -- A template CIMInstance to serve as a model of the objects to be returned. Only properties present on this model need to be returned. assoc_class -- The CIMClass result_class_name -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be either an Instance of this Class (or one of its subclasses) or be this Class (or one of its subclasses). role -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be associated to the source Object via an Association in which the source Object plays the specified role (i.e. the name of the Property in the Association Class that refers to the source Object MUST match the value of this parameter). result_role -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be associated to the source Object via an Association in which the returned Object plays the specified role (i.e. the name of the Property in the Association Class that refers to the returned Object MUST match the value of this parameter). keys_only -- A boolean. True if only the key properties should be set on the generated instances. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_NAMESPACE CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_FAILED (some other unspecified error occurred) """ _scanmounts() objname = object_name['name'] if (not role or role.lower() == 'partcomponent') \ and objname != '/': model['partcomponent'] = object_name kbs = {} get_keys(os.path.dirname(objname), kbs) model['groupcomponent'] = pywbem.CIMInstanceName( classname=kbs['CreationClassName'], namespace=object_name.namespace, keybindings=kbs) yield model if (not role or role.lower() == 'groupcomponent') \ and object_name.classname.lower() == 'py_linuxdirectory': model['groupcomponent'] = object_name for dirent in os.listdir(objname): fname = objname if fname[-1] != '/': fname += '/' fname = os.path.abspath(fname + dirent) kbs = {} get_keys(fname, kbs) model['partcomponent'] = pywbem.CIMInstanceName( classname=kbs['CreationClassName'], namespace=object_name.namespace, keybindings=kbs) yield model
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): """Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment object_name -- A CIMInstanceName that defines the source CIM Object whose associated Objects are to be returned. model -- A template CIMInstance to serve as a model of the objects to be returned. Only properties present on this model need to be returned. assoc_class -- The CIMClass result_class_name -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be either an Instance of this Class (or one of its subclasses) or be this Class (or one of its subclasses). role -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be associated to the source Object via an Association in which the source Object plays the specified role (i.e. the name of the Property in the Association Class that refers to the source Object MUST match the value of this parameter). result_role -- If not None, acts as a filter on the returned set of Objects by mandating that each returned Object MUST be associated to the source Object via an Association in which the returned Object plays the specified role (i.e. the name of the Property in the Association Class that refers to the returned Object MUST match the value of this parameter). keys_only -- A boolean. True if only the key properties should be set on the generated instances. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_NAMESPACE CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_FAILED (some other unspecified error occurred) """ if object_name.classname.lower() == 'py_linuxfile': model['SameElement'] = object_name model['SystemElement'] = pywbem.CIMInstanceName( classname=object_name['LFCreationClassName'], namespace=object_name.namespace, keybindings={ 'Name': object_name['LFName'], 'FSName': object_name['FSName'], 'FSCreationClassName': object_name['FSCreationClassName'], 'CSName': getfqdn(), 'CSCreationClassName': object_name['CSCreationClassName'], 'CreationClassName': object_name['LFCreationClassName'] }) yield model else: model['SystemElement'] = object_name model['SameElement'] = pywbem.CIMInstanceName( classname='Py_LinuxFile', namespace=object_name.namespace, keybindings={ 'LFName': object_name['Name'], 'FSName': object_name['FSName'], 'FSCreationClassName': object_name['FSCreationClassName'], 'CSName': getfqdn(), 'CSCreationClassName': object_name['CSCreationClassName'], 'LFCreationClassName': object_name['CreationClassName'] }) yield model