def _typed_randrange(lo, hi, type): if type == 'sint8': return pywbem.Sint8( random.randrange(pywbem.Sint8(lo), pywbem.Sint8(hi))) elif type == 'sint16': return pywbem.Sint16( random.randrange(pywbem.Sint16(lo), pywbem.Sint16(hi))) elif type == 'sint32': return pywbem.Sint32( random.randrange(pywbem.Sint32(lo), pywbem.Sint32(hi))) elif type == 'sint64': return pywbem.Sint64( random.randrange(pywbem.Sint64(lo), pywbem.Sint64(hi))) elif type == 'uint8': return pywbem.Uint8( random.randrange(pywbem.Uint8(lo), pywbem.Uint8(hi))) elif type == 'uint16': return pywbem.Uint16( random.randrange(pywbem.Uint16(lo), pywbem.Uint16(hi))) elif type == 'uint32': return pywbem.Uint32( random.randrange(pywbem.Uint32(lo), pywbem.Uint32(hi))) elif type == 'uint64': return pywbem.Uint64( random.randrange(pywbem.Uint64(lo), pywbem.Uint64(hi))) elif type == 'real32': return pywbem.Real32( random.randrange(pywbem.Real32(lo), pywbem.Real32(hi))) elif type == 'real64': return pywbem.Real64( random.randrange(pywbem.Real64(lo), pywbem.Real64(hi)))
def __init__(self, Ip, userName, password): TestSetUp.__init__(self, Ip, userName, password, True, True) self.pv_vssd = CIMInstance("Xen_ComputerSystemSettingData") self.pv_vssd['Caption'] = "pv_create_new_VM" self.pv_vssd["ElementName"] = "pv_create_new_VM" self.pv_vssd["VirtualSystemType"] = "DMTF:xen:PV" self.pv_vssd["PV_Bootloader"] = "pygrub" self.pv_vssd["PV_Args"] = "Term=xterm" self.local_hvm_vssd = CIMInstance("Xen_ComputerSystemSettingData") self.local_hvm_vssd["Caption"] = "hvm_create_new_VM" self.local_hvm_vssd["ElementName"] = "hvm_create_new_VM" self.local_hvm_vssd["VirtualSystemType"] = "DMTF:xen:HVM" self.local_hvm_vssd["HVM_Boot_Params"] = ["order=dc"] self.local_hvm_vssd["HVM_Boot_Policy"] = "BIOS order" self.local_hvm_vssd["Platform"] = [ "acpi=true", "apic=true", "pae=true" ] # A VSSD with incorrect property types self.invalid_pv_vssd = self.pv_vssd.copy() self.invalid_pv_vssd['VirtualSystemType'] = pywbem.Uint8( 10) # bad type, integer instead of string self.invalid_pv_vssd['PV_Bootloader'] = pywbem.Uint8( 20) # bad boot loader, integer instead of string self.invalid_pv_vssd[ 'AutomaticShutdownAction'] = '2' # bad shutdown action type, string instead of integer self.invalid_pv_vssd['PV_Args'] = 'Blah' # bad PV_Args self.no_pv_vssd = CIMInstance("Xen_ComputerSystemSettingData") self.no_pv_vssd[ 'VirtualSystemIdentifier'] = '20904d23-8a89-1d63-134c-d2606f2fcc47' self.no_pv_vssd['Description'] = 'test-pv-vm'
def test2 (self): vsms = self.conn.EnumerateInstanceNames("Xen_VirtualSystemManagementService") vssd = CIMInstance('Xen_VirtualSystemSettingData') vssd['ElementName'] = 'Shashi & Kiran' vssd['VirtualSystemType'] = 'DMTF:xen:PV' vssd['PV_Bootloader'] = 'pygrub' vssd['AutomaticShutdownAction'] = pywbem.Uint8(2) vssd['AutomaticStartupAction'] = pywbem.Uint8(3) vssd['AutomaticRecoveryAction'] = pywbem.Uint8(3) vssd['PV_Args'] = 'Term=xterm' vssd['Other_Config'] = ['HideFromXenCenter=false'] vssd['Description'] = "Test & vm created by the network test" in_params = {'SystemSettings': vssd} (rval, out_params) = self.conn.InvokeMethod('DefineSystem', vsms[0], **in_params)
def modifySystemSetting_UnModifyableCaption(self): self.TestBegin() pv_vssd = CIMInstance('Xen_ComputerSystemSettingData') pv_vssd['Caption'] = "modify-pv-vm" pv_vssd['ElementName'] = sys._getframe(0).f_code.co_name pv_vssd['Description'] = "Test VM" pv_vssd['VirtualSystemType'] = "DMTF:xen:PV" pv_vssd['PV_Bootloader'] = "pygrub" pv_vssd['PV_BootloaderOptions'] = "" pv_vssd['OnPoweroff'] = pywbem.Uint8(0) pv_vssd['OnReboot'] = pywbem.Uint8(1) pv_vssd['OnCrash'] = pywbem.Uint8(2) pv_vssd['KernelOptions'] = "Term=xterm" isSuccess = 0 rasds = [self.proc_rasd, self.mem_rasd, self.disk0_rasd, self.nic_rasd] in_params = {'SystemSettings': pv_vssd, 'ResourceSettings': rasds} new_vm = CreateVM(self.conn, self.vsms[0], in_params) time.sleep(3) pv_vssd['Caption'] = 'Changed_VM' pv_vssd['InstanceID'] = 'Xen:' + new_vm['Name'] print pv_vssd in_params = {'SystemSettings': pv_vssd} n = ModifyVM(self.conn, self.vsms[0], in_params) time.sleep(2) vssds = GetVSSDsForVM(self.conn, new_vm) if vssds == None: print 'Couldnt find VSSD for PV VM after modify' isSuccess = 0 for vssd in vssds: vssd_inst = self.conn.GetInstance(vssd) if (vssd_inst['VirtualSystemIdentifier'] == self.get_vm_id(new_vm) ): print "Current caption : " + vssd_inst['Caption'] print "Caption desired : Changed_VM" testCap = str(vssd_inst['Caption']) print testCap index = testCap.find("Changed_VM") if (index == -1): isSuccess = 1 pv_val = DeleteVM(self.conn, self.vsms[0], new_vm) self.TestEnd(isSuccess)
def getnum(num, datatype): try: result = { '8': pywbem.Uint8(num), '16': pywbem.Uint16(num), '32': pywbem.Uint32(num), '64': pywbem.Uint64(num) } result = result.get(datatype, num) except NameError: result = num return result
def __SetManagementInterface(self, nic_rasd_orig, mode, ip, mask, purpose): result = 0 try: # BUGBUG Using the nic_rasd_orig directly results in pegasus complaining about XML validataion errors # because it finds LOCALINSTANCEPATH in the XML instead of serialized XML nic_rasd = CIMInstance('Xen_HostNetworkPortSettingData') nic_rasd['IPConfigurationMode'] = pywbem.Uint8( mode) # 0=None,1=DHCP,2=static,3=undefined nic_rasd['IPAddress'] = ip nic_rasd['IPSubnetMask'] = mask nic_rasd['ManagementPurpose'] = purpose nic_rasd['InstanceID'] = nic_rasd_orig['InstanceID'] rasds = [nic_rasd] in_params = {'ResourceSettings': rasds} (rval, out_params) = self.conn.InvokeMethod('ModifyResourceSettings', self.vsms, **in_params) if rval == 0: query_str = "SELECT * FROM Xen_HostNetworkPortSettingData WHERE InstanceID = \"" + nic_rasd[ 'InstanceID'] + "\"" new_rasds = self.conn.ExecQuery("WQL", query_str, "root/cimv2") print 'Checking interface %d(%d), %s(%s), %s(%s), %s(%s)' % ( new_rasds[0]['IPConfigurationMode'], mode, new_rasds[0]['IPAddress'], ip, new_rasds[0]['IPSubnetMask'], mask, new_rasds[0]['ManagementPurpose'], purpose) if mode != 0: if new_rasds[0][ 'IPConfigurationMode'] == mode and new_rasds[0][ 'IPAddress'] == ip and new_rasds[0][ 'IPSubnetMask'] == mask and new_rasds[0][ 'ManagementPurpose'] == purpose: print 'interface has been updated' result = 1 else: if new_rasds[0]['IPConfigurationMode'] == 0 and new_rasds[ 0]['IPAddress'] == ip and new_rasds[0][ 'IPSubnetMask'] == mask and new_rasds[0][ 'ManagementPurpose'] == None: print 'interface has been updated' result = 1 except pywbem.CIMError, arg: result = 0 print 'Caught exception when calling %s' % (__name__) if arg[0] != pywbem.CIM_ERR_NOT_SUPPORTED: print 'InvokeMethod(instancename): %s' % arg[1]
def get_num(self, numStr, datatype): """Get the ecom int from the number. :param numStr: the number in string format :param datatype: the type to convert it to :returns: result """ try: result = { '8': pywbem.Uint8(numStr), '16': pywbem.Uint16(numStr), '32': pywbem.Uint32(numStr), '64': pywbem.Uint64(numStr) } result = result.get(datatype, numStr) except NameError: result = numStr return result
def CreateDiskImage(conn, spms, sr_to_use, size_in_bytes, name): print sr_to_use.items() [system_id, sep, pool_id] = sr_to_use['InstanceID'].partition('/') print 'PoolID - %s' % pool_id new_disk_sasd = CIMInstance('Xen_DiskSettingData') new_disk_sasd['ElementName'] = name new_disk_sasd['ResourceType'] = pywbem.Uint16(19) new_disk_sasd['ResourceSubType'] = "Disk" new_disk_sasd['VirtualQuantity'] = pywbem.Uint64(size_in_bytes) new_disk_sasd['AllocationUnits'] = "Bytes" new_disk_sasd['Bootable'] = False new_disk_sasd['Access'] = pywbem.Uint8(3) new_disk_sasd['PoolID'] = pool_id in_params = {"ResourceSetting": new_disk_sasd} [rc, out_params] = conn.InvokeMethod("CreateDiskImage", spms, **in_params) new_disk = out_params["ResultingDiskImage"] print "Created Disk" print new_disk.items() return [rc, new_disk]
def _create_disk_image (self, sr_to_use): print sr_to_use.items() [system_id, sep, pool_id] = sr_to_use['InstanceID'].partition('/') print 'PoolID - %s' % pool_id new_disk_sasd = CIMInstance('Xen_DiskSettingData') new_disk_sasd['ElementName'] = sys._getframe(0).f_code.co_name new_disk_sasd['ResourceType'] = pywbem.Uint16(19) new_disk_sasd['ResourceSubType'] = "Disk" new_disk_sasd['VirtualQuantity'] = pywbem.Uint64(2048) new_disk_sasd['AllocationUnits'] = "MegaBytes" new_disk_sasd['Bootable'] = False new_disk_sasd['Access'] = pywbem.Uint8(3) new_disk_sasd['PoolID'] = pool_id in_params = {"ResourceSetting": new_disk_sasd} [rc, out_params] = self.conn.InvokeMethod("CreateDiskImage", self.spms[0], **in_params) new_disk = out_params["ResultingDiskImage"] print "Created Disk" print new_disk.items() return [rc, new_disk]
def create_disk_image_error_tests(self): self.TestBegin() result = 1 print 'Creating a disk image with bad disk RASD' try: [system_id, sep, pool_id] = self.sr_to_use['InstanceID'].partition('/') new_disk_sasd = CIMInstance('Xen_DiskSettingData') new_disk_rasd['PoolID'] = pool_id new_disk_rasd['ResourceType'] = "19" new_disk_rasd['ResourceSubType'] = pywbem.Uint8(123) new_disk_rasd['VirtualQuantity'] = "2048" new_disk_rasd['AllocationUnits'] = pywbem.Uint16(1234) new_disk_rasd['Bootable'] = "False" new_disk_rasd['Access'] = '3' in_params = {"ResourceSetting": new_disk_sasd} [rc, out_params] = self.conn.InvokeMethod("CreateDiskImage", self.spms[0], **in_params) if rc == 0: print 'Disk was created when it shouldnt have been' result = 0 except Exception, e: print 'Exception thrown %s' % str(e)
def get_value(string): vtype, value = string.split(',', 1) if vtype == 'str': return str(value) elif vtype == 'uint8': return pywbem.Uint8(value) elif vtype == 'sint8': return pywbem.Sint8(value) elif vtype == 'uint16': return pywbem.Uint16(value) elif vtype == 'sint16': return pywbem.Sint16(value) elif vtype == 'uint32': return pywbem.Uint32(value) elif vtype == 'sint32': return pywbem.Sint32(value) elif vtype == 'uint64': return pywbem.Uint64(value) elif vtype == 'sint64': return pywbem.Sint64(value) else: print "Input value is invalid : %s" % string sys.exit(1)
def add_vm_resources (conn, vsms, vm_ref): try: print '*** Adding processor and CD resources to VM %s ' % vm_ref['Name'] # AddResourceSettings requires the Xen_ComputerSystemSettingData reference, find it # We'll use the association class for that association_class = 'CIM_SettingsDefineState' # association to traverse via Xen_ComputerSystem result_class = 'CIM_VirtualSystemSettingData' # result class we are looking for in_params = {'ResultClass': result_class, 'AssocClass': association_class } affected_config_arr = conn.AssociatorNames(vm_ref, **in_params) affected_config = affected_config_arr[0] cd_drive = pywbem.CIMInstance('Xen_DiskSettingData') cd_drive['Elementname'] = 'my_cd_drive' cd_drive['ResourceType'] = pywbem.Uint16(15) cd_drive['VirtualQuantity'] = pywbem.Uint64(1) cd_drive['AllocationUnits'] = "count" cd_drive['Access'] = pywbem.Uint8(1) cd_drive['Bootable'] = True more_mem = pywbem.CIMInstance('CIM_ResourceAllocationSettingData') more_mem['ResourceType'] = pywbem.Uint16(4) more_mem['VirtualQuantity'] = pywbem.Uint64(512) more_mem['AllocationUnits'] = 'byte*2^20' rasds = [cd_drive, more_mem] in_params = {'ResourceSettings': rasds, 'AffectedConfiguration':affected_config} [rval, out_params] = conn.InvokeMethod('AddResourceSettings', vsms, **in_params) if rval != 4096: sys.stderr.write('%s returned error: %s\n' % (sys._getframe(0).f_code.co_name, rval)) return 0 job_ref = out_params['Job'] job = wait_for_job_to_complete(conn, job_ref) conn.DeleteInstance(job_ref) except Exception, e: sys.stderr.write('Exception caught in %s: %s\n' % (sys._getframe(0).f_code.co_name, e)) return 0
def add_management_network(self, host): self.TestBegin() result = 0 try: nic_to_change = None nics = self.conn.EnumerateInstances( "Xen_HostNetworkPortSettingData") for nic in nics: if nic['Connection'][0] == self.management_interface and nic[ 'ElementName'] == host['Name']: nic['IPConfigurationMode'] = pywbem.Uint8(2) # Static nic['IPAddress'] = self.management_ip nic['IPSubnetMask'] = self.management_ip_mask nic['ManagementPurpose'] = self.management_purpose nic_to_change = nic.tomof() break in_params = {"ResourceSettings": nic_to_change} (rval, out_params) = self.conn.InvokeMethod('ModifyResourceSettings', self.vsms, **in_params) if rval == 0: result = 1 except Exception, e: sys.stderr.write('Exception caught in %s: %s\n' % (__name__, e))
class TestMethods(unittest.TestCase): limits = { 'sint8_min': pywbem.Sint8(-128), 'sint8_max': pywbem.Sint8(127), 'sint16_min': pywbem.Sint16(-32768), 'sint16_max': pywbem.Sint16(32767), 'sint32_min': pywbem.Sint32(-2147483648), 'sint32_max': pywbem.Sint32(2147483647), 'sint64_min': pywbem.Sint64(-92233736854775808L), 'sint64_max': pywbem.Sint64(9223372036854775807L), 'uint8_min': pywbem.Uint8(0), 'uint8_max': pywbem.Uint8(0xFF), 'uint16_min': pywbem.Uint16(0), 'uint16_max': pywbem.Uint16(0xFFFF), 'uint32_min': pywbem.Uint32(0), 'uint32_max': pywbem.Uint32(0xFFFFFFFF), 'uint64_min': pywbem.Uint64(0L), 'uint64_max': pywbem.Uint64(0x7FFFFFFFFFFFFFFFL), 'real32_min': pywbem.Real32(-123456.78), 'real32_max': pywbem.Real32(123456.78), 'real64_min': pywbem.Real64(-12345678987654.32), 'real64_max': pywbem.Real64(12345678987654.32) } # note: the last Uint64 value should be 0xFFFFFFFFFFFFFFFF but there is a bug somewhere... inttypes = [ 'sint8', 'sint16', 'sint32', 'sint64', 'uint8', 'uint16', 'uint32', 'uint64' ] realtypes = ['real32', 'real64'] zeros = { 'sint8': pywbem.Sint8(0), 'sint16': pywbem.Sint16(0), 'sint32': pywbem.Sint32(0), 'sint64': pywbem.Sint64(0), 'uint8': pywbem.Uint8(0), 'uint16': pywbem.Uint16(0), 'uint32': pywbem.Uint32(0), 'uint64': pywbem.Uint64(0), 'real32': pywbem.Real32(0), 'real64': pywbem.Real64(0) } ones = { 'sint8': pywbem.Sint8(1), 'sint16': pywbem.Sint16(1), 'sint32': pywbem.Sint32(1), 'sint64': pywbem.Sint64(1), 'uint8': pywbem.Uint8(1), 'uint16': pywbem.Uint16(1), 'uint32': pywbem.Uint32(1), 'uint64': pywbem.Uint64(1), 'real32': pywbem.Real32(0), 'real64': pywbem.Real64(0) } tens = { 'sint8': pywbem.Sint8(10), 'sint16': pywbem.Sint16(10), 'sint32': pywbem.Sint32(10), 'sint64': pywbem.Sint64(10), 'uint8': pywbem.Uint8(10), 'uint16': pywbem.Uint16(10), 'uint32': pywbem.Uint32(10), 'uint64': pywbem.Uint64(10), 'real32': pywbem.Real32(10), 'real64': pywbem.Real64(10) } twenties = { 'sint8': pywbem.Sint8(20), 'sint16': pywbem.Sint16(20), 'sint32': pywbem.Sint32(20), 'sint64': pywbem.Sint64(20), 'uint8': pywbem.Uint8(20), 'uint16': pywbem.Uint16(20), 'uint32': pywbem.Uint32(20), 'uint64': pywbem.Uint64(20), 'real32': pywbem.Real32(20), 'real64': pywbem.Real64(20) } numlists = { 'sint8': [ pywbem.Sint8(8), pywbem.Sint8(2), pywbem.Sint8(5), pywbem.Sint8(6), pywbem.Sint8(3), pywbem.Sint8(9), pywbem.Sint8(7), pywbem.Sint8(1), pywbem.Sint8(4) ], 'sint16': [ pywbem.Sint16(8), pywbem.Sint16(2), pywbem.Sint16(5), pywbem.Sint16(6), pywbem.Sint16(3), pywbem.Sint16(9), pywbem.Sint16(7), pywbem.Sint16(1), pywbem.Sint16(4) ], 'sint32': [ pywbem.Sint32(8), pywbem.Sint32(2), pywbem.Sint32(5), pywbem.Sint32(6), pywbem.Sint32(3), pywbem.Sint32(9), pywbem.Sint32(7), pywbem.Sint32(1), pywbem.Sint32(4) ], 'sint64': [ pywbem.Sint64(8), pywbem.Sint64(2), pywbem.Sint64(5), pywbem.Sint64(6), pywbem.Sint64(3), pywbem.Sint64(9), pywbem.Sint64(7), pywbem.Sint64(1), pywbem.Sint64(4) ], 'uint8': [ pywbem.Uint8(8), pywbem.Uint8(2), pywbem.Uint8(5), pywbem.Uint8(6), pywbem.Uint8(3), pywbem.Uint8(9), pywbem.Uint8(7), pywbem.Uint8(1), pywbem.Uint8(4) ], 'uint16': [ pywbem.Uint16(8), pywbem.Uint16(2), pywbem.Uint16(5), pywbem.Uint16(6), pywbem.Uint16(3), pywbem.Uint16(9), pywbem.Uint16(7), pywbem.Uint16(1), pywbem.Uint16(4) ], 'uint32': [ pywbem.Uint32(8), pywbem.Uint32(2), pywbem.Uint32(5), pywbem.Uint32(6), pywbem.Uint32(3), pywbem.Uint32(9), pywbem.Uint32(7), pywbem.Uint32(1), pywbem.Uint32(4) ], 'uint64': [ pywbem.Uint64(8), pywbem.Uint64(2), pywbem.Uint64(5), pywbem.Uint64(6), pywbem.Uint64(3), pywbem.Uint64(9), pywbem.Uint64(7), pywbem.Uint64(1), pywbem.Uint64(4) ], 'real32': [ pywbem.Real32(8), pywbem.Real32(2), pywbem.Real32(5), pywbem.Real32(6), pywbem.Real32(3), pywbem.Real32(9), pywbem.Real32(7), pywbem.Real32(1), pywbem.Real32(4) ], 'real64': [ pywbem.Real64(8), pywbem.Real64(2), pywbem.Real64(5), pywbem.Real64(6), pywbem.Real64(3), pywbem.Real64(9), pywbem.Real64(7), pywbem.Real64(1), pywbem.Real64(4) ] } def _dbgPrint(self, msg=''): if self._verbose: if len(msg): print('\t -- %s --' % msg) else: print('') def setUp(self): unittest.TestCase.setUp(self) wconn = wbem_connection.wbem_connection() self.conn = wconn._WBEMConnFromOptions(_g_opts) for iname in self.conn.EnumerateInstanceNames('TestMethod'): self.conn.DeleteInstance(iname) self._verbose = _g_opts.verbose self._dbgPrint() def tearDown(self): unittest.TestCase.tearDown(self) for iname in self.conn.EnumerateInstanceNames('TestMethod'): self.conn.DeleteInstance(iname) def _run_and_validate_getrand(self, type, methodName, min, max, expectedReturnValue=None, minReturnValue=None, maxReturnValue=None): isRealType = False if type.startswith('real'): isRealType = True if isRealType: self._dbgPrint('Testing %s invocation with min=%f, max=%f' % (methodName, min, max)) else: self._dbgPrint('Testing %s invocation with min=%d, max=%d' % (methodName, min, max)) (rv, oparams) = self.conn.InvokeMethod(methodName, 'TestMethod', min=min, max=max) if not oparams['success']: self.fail( '"Success" reported as false for invocation of method %s' % methodName) if expectedReturnValue is not None: if isRealType: self._dbgPrint( 'Verifying return value (%f) equal to expected return value %f...' % (rv, expectedReturnValue)) if abs(expectedReturnValue - rv) > real_tolerance: self.fail( 'Return value not as expected for invocation of method %s' % methodName) else: self._dbgPrint( 'Verifying return value (%d) equal to expected return value %d...' % (rv, expectedReturnValue)) if expectedReturnValue != rv: self.fail( 'Return value not as expected for invocation of method %s' % methodName) self._dbgPrint('Return value is as expected.') if minReturnValue is not None: if isRealType: self._dbgPrint('Verifying return value (%f) >= %f' % (rv, minReturnValue)) else: self._dbgPrint('Verifying return value (%d) >= %d' % (rv, minReturnValue)) if rv < minReturnValue: self.fail( 'Return value less than expected for invocation of method %s' % methodName) self._dbgPrint('Return value is as expected.') if maxReturnValue is not None: if isRealType: self._dbgPrint('Verifying return value (%f) <= %f' % (rv, maxReturnValue)) else: self._dbgPrint('Verifying return value (%d) <= %d' % (rv, maxReturnValue)) if rv > maxReturnValue: self.fail( 'Return value greater than expected for invocation of method %s' % methodName) self._dbgPrint('Return value is as expected.') def _run_and_validate_getrandlist(self, type, methodName, min, max, nelems): isRealType = False if type.startswith('real'): isRealType = True if isRealType: self._dbgPrint('Testing %s invocation with min=%f, max=%f' % (methodName, min, max)) else: self._dbgPrint('Testing %s invocation with min=%d, max=%d' % (methodName, min, max)) (rv, oparams) = self.conn.InvokeMethod(methodName, 'TestMethod', lo=min, hi=max, nelems=nelems) if not rv: self.fail('Invocation of %s returned false success value.' % methodName) self._dbgPrint('Invocation of %s returned successfully.' % methodName) if isRealType: self._dbgPrint('Validating lo (%f) and hi (%f) outparams...' % (min, max)) if abs(oparams['lo'] - min) > real_tolerance: self.fail( 'Returned low range value (%f) not equal to specified value (%f).' % (oparams['lo'], min)) if abs(oparams['hi'] - max) > real_tolerance: self.fail( 'Returned high range value (%f) not equal to specified value (%f).' % (oparams['hi'], max)) else: self._dbgPrint('Validating lo (%d) and hi (%d) outparams...' % (min, max)) if oparams['lo'] != min: self.fail( 'Returned low range value (%d) not equal to specified value (%d).' % (oparams['lo'], min)) if oparams['hi'] != max: self.fail( 'Returned high range value (%d) not equal to specified value (%d).' % (oparams['hi'], max)) self._dbgPrint('Lo and hi outparams validated successfully.') self._dbgPrint('Validating random list values...') if oparams['nlist'] is None: self.fail('Expected a list of values but got none.') if len(oparams['nlist']) != nelems: self.fail('Expected a list of %d items but got %d items instead.' % (nelems, len(oparams['nlist']))) minkey = '%s_min' % type maxkey = '%s_max' % type for num in oparams['nlist']: if num < TestMethods.limits[minkey] or \ num > TestMethods.limits[maxkey]: if isRealType: self.fail( 'List element %f not in expected range for type %s.' % (num, type)) else: self.fail( 'List element %d not in expected range for type %s.' % (num, type)) self._dbgPrint('Random list values validated successfully.') def _run_and_validate_minmedmax(self, type, methodName, numlist): self._dbgPrint('Testing %s invocation' % methodName) (rv, oparams) = self.conn.InvokeMethod(methodName, 'TestMethod', numlist=numlist) if not rv: self.fail('Invocation of %s returned false success value.' % methodName) self._dbgPrint('Invocation of %s returned successfully.' % methodName) self._dbgPrint('Validating min, median, and max outparams...') if oparams['min'] != 1: self.fail('Expected min of 1 but instead got %d' % oparams['min']) if oparams['max'] != 9: self.fail('Expected max of 9 but instead got %d' % oparams['max']) if oparams['med'] != 5: self.fail('Expected median of 5 but instead got %d' % oparams['med']) self._dbgPrint('Min, median, and max values validated successfully.') def _run_numeric_type_tests(self, typelist): gr = self._run_and_validate_getrand grl = self._run_and_validate_getrandlist mmm = self._run_and_validate_minmedmax for type in typelist: method = 'genRand_%s' % type minkey = '%s_min' % type maxkey = '%s_max' % type min = TestMethods.limits[minkey] max = TestMethods.limits[maxkey] gr(type, method, min, max, None, min, max) gr(type, method, min, min, min) gr(type, method, max, max, max) if min != 0: gr(type, method, TestMethods.zeros[type], TestMethods.zeros[type], TestMethods.zeros[type]) gr(type, method, TestMethods.tens[type], TestMethods.twenties[type], None, TestMethods.tens[type], TestMethods.twenties[type]) # the next two should cause exceptions; getting a TypeError exception is not an error in this case. try: gr(type, method, min - 1, min - 1, min - 1) except TypeError: pass try: gr(type, method, max + 1, max + 1, max + 1) except TypeError: pass method = 'genRandList_%s' % type nelems = _typed_randrange(TestMethods.tens[type], TestMethods.twenties[type], type) grl(type, method, min, max, nelems) grl(type, method, min, max, TestMethods.ones[type]) grl(type, method, min, max, TestMethods.zeros[type]) if min != 0: grl(type, method, TestMethods.zeros[type], max, nelems) else: grl(type, method, min, TestMethods.zeros[type], nelems) grl(type, method, TestMethods.tens[type], TestMethods.twenties[type], nelems) grl(type, method, TestMethods.tens[type], TestMethods.twenties[type], TestMethods.ones[type]) grl(type, method, TestMethods.tens[type], TestMethods.twenties[type], TestMethods.zeros[type]) method = 'minmedmax_%s' % type mmm(type, method, TestMethods.numlists[type]) def test_integer_types(self): self._run_numeric_type_tests(TestMethods.inttypes) def test_real_types(self): self._run_numeric_type_tests(TestMethods.realtypes) 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 test_mkUniStr_sint8(self): s = 'Scrum Rocks!' l = [pywbem.Sint8(ord(x)) for x in s] rv, outs = self.conn.InvokeMethod('mkUniStr_sint8', 'TestMethod', cArr=l) self.assertFalse(outs) self.assertEquals(rv, s) rv, outs = self.conn.InvokeMethod('mkUniStr_sint8', 'TestMethod', cArr=[]) self.assertEquals(rv, '') def test_strCat(self): ra = ['one', 'two', 'three', 'four'] rv, outs = self.conn.InvokeMethod('strCat', 'TestMethod', strs=ra, sep=',') self.assertEquals(rv, ','.join(ra)) self.assertFalse(outs) def test_strSplit(self): ra = 'one,two,three,four' rv, outs = self.conn.InvokeMethod('strSplit', 'TestMethod', str=ra, sep=',') self.assertEquals(outs['elems'], ra.split(',')) self.assertTrue(ra) def test_getDate(self): dt = pywbem.CIMDateTime.now() rv, outs = self.conn.InvokeMethod('getDate', 'TestMethod', datestr=str(dt)) self.assertFalse(outs) self.assertEquals(rv, dt) self.assertEquals(str(rv), str(dt)) self.assertTrue(isinstance(rv, pywbem.CIMDateTime)) def test_getDates(self): dt = pywbem.CIMDateTime.now() s1 = str(dt) ra = [s1] dt = pywbem.CIMDateTime(pywbem.datetime.now() + \ pywbem.timedelta(seconds=10)) s2 = str(dt) ra.append(s2) dt = pywbem.CIMDateTime(pywbem.datetime.now() + \ pywbem.timedelta(seconds=10)) s3 = str(dt) ra.append(s3) rv, outs = self.conn.InvokeMethod('getDates', 'TestMethod', datestrs=ra) self.assertTrue(rv) self.assertTrue(isinstance(rv, bool)) self.assertEquals(outs['nelems'], len(ra)) self.assertTrue(isinstance(outs['nelems'], pywbem.Sint32)) for i in range(0, len(ra)): self.assertTrue(isinstance(outs['elems'][i], pywbem.CIMDateTime)) self.assertEquals(str(outs['elems'][i]), ra[i]) def test_minmedmax(self): for tstr in [ 'Sint8', 'Uint8', 'Sint16', 'Uint16', 'Sint32', 'Uint32', 'Sint64', 'Uint64', 'Real32', 'Real64' ]: dt = getattr(pywbem, tstr) method = 'minmedmax_%s' % tstr numlist = [ dt(2), dt(5), dt(8), dt(1), dt(9), dt(6), dt(4), dt(7), dt(3), ] rv, outs = self.conn.InvokeMethod(method, 'TestMethod', numlist=numlist) self.assertTrue(rv) self.assertTrue(isinstance(rv, bool)) self.assertTrue(isinstance(outs['min'], dt)) self.assertTrue(isinstance(outs['med'], dt)) self.assertTrue(isinstance(outs['max'], dt)) self.assertEquals(outs['min'], 1) self.assertEquals(outs['max'], 9) self.assertEquals(outs['med'], 5)
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 _compare_values(conn, instance, time): types = {'boolProp': 'boolean', 'dateProp': 'datetime', 'real32Prop': 'real32', 'real32Propa': 'real32', 'real64Prop': 'real64', 'real64Propa': 'real64', 'sint16Prop': 'sint16', 'sint16Propa': 'sint16', 'sint32Prop': 'sint32', 'sint32Propa': 'sint32', 'sint64Prop': 'sint64', 'sint64Propa': 'sint64', 'sint8prop': 'sint8', 'sint8propa': 'sint8', 'stringProp': 'string', 'stringPropa': 'string', 'uint16Prop': 'uint16', 'uint16Propa': 'uint16', 'uint32Prop': 'uint32', 'uint32Propa': 'uint32', 'uint64Prop': 'uint64', 'uint64Propa': 'uint64', 'uint8Prop' : 'uint8', 'uint8Propa' : 'uint8' } if instance['Name'] in _atoms: #print instance['Name'] atoms_value = _atoms.get(instance['Name']) atoms_weight = _atomic_weights[instance['Name']] for prop,value in instance.items(): #print "Property=%s"%str(prop) #Char and Char_array if prop == 'char16Prop' or prop == 'char16Propa': pass #Date Property elif prop == 'dateProp': if str(instance[prop]) != str(time): raise "DateProp NOT EQUAL" #Name or stringProp elif prop == 'Name' or prop == 'stringProp': if instance['Name'] not in _atoms or \ instance['stringProp'] not in _atoms: raise "Atom Name NOT FOUND: %s" & instance['Name'] #boolProp elif prop == 'boolProp': if instance[prop] != False: raise "False NOT EQUAL False" #All values not in lists #real64Prop fails this check elif (instance.properties[prop].type == types.get(prop)) and \ type(instance.properties[prop].value) != type([]): if prop == 'uint8Prop': if pywbem.Uint8(atoms_value) != instance[prop]: raise "%s Error: %s" % (prop, instance[prop]) elif prop.startswith("real"): if _atomic_weights[instance['Name']] != atoms_weight: raise "%s == %s"%(_atomic_weights[instance['Name']],atoms_weight) elif atoms_value != value: raise "%s == %s"%(atoms_value,value) #All list values elif type(instance.properties[prop].value) == type([]) and \ instance.properties[prop].type == types.get(prop): if prop == 'stringPropa': if value[0] != 'proton' and value[1] != 'electron' \ and value[2] != 'neutron': raise "String Array NOT EQUAL" elif prop == 'uint8Propa': for val in instance.properties[prop].value: if pywbem.Uint8(atoms_value) != val: raise ("Uint8 Values NOT EQUAL") else: #print "\n" #print "instance.properties[prop]=%s"%str(prop) #print "atoms_value=%s"%str(atoms_value) for a_prop in instance.properties[prop].value: #print "a_prop=%s"%str(a_prop) #print "value=%s"%str(value) for num in value: #Array #print "Checking a_prop=%s with num=%s" % (str(a_prop),str(num)) #print "startswith=%s"%str(prop.startswith("real")) #if str(instance.properties[prop]).startswith("real"): if prop.startswith("real"): #print "Checking num=%s with atoms_weight=%s"%(str(num),str(atoms_weight)) if math.fabs(num - atoms_weight) > _tolerance: raise "%s NOT EQUAL %s" % (str(num), str(atoms_weight)) elif a_prop != num: raise "%s NOT EQUAL %s" % (atoms_value, num) else: raise "%s NOT EQUAL %s" % (atoms_value, value) else: raise "Instance of TestAtom not Found: %s" % (instance['Name'])
[rc, out_params] = self.conn.InvokeMethod("CreateDiskImage", self.spms[0], **in_params) if rc == 0: print 'Disk was created when it shouldnt have been' result = 0 except Exception, e: print 'Exception thrown %s' % str(e) print 'Creating a disk image with disk RASD containing wrong poolid' try: new_disk_sasd = CIMInstance('Xen_DiskSettingData') new_disk_rasd['PoolID'] = "bad_reference" new_disk_rasd['ResourceType'] = pywbem.Uint16(19) new_disk_rasd['ResourceSubType'] = "Disk" new_disk_rasd['VirtualQuantity'] = pywbem.Uint64(2048) new_disk_rasd['AllocationUnits'] = "MegaBytes" new_disk_rasd['Bootable'] = False new_disk_rasd['Access'] = pywbem.Uint8(3) in_params = {"ResourceSetting": new_disk_sasd} [rc, out_params] = self.conn.InvokeMethod("CreateDiskImage", self.spms[0], **in_params) if rc == 0: print 'Disk was created when it shouldnt have been' result = 0 except Exception, e: print 'Exception thrown %s' % str(e) print 'Creating a disk image with empty disk RASD' try: new_disk_sasd = '' in_params = {"ResourceSetting": new_disk_sasd} [rc, out_params] = self.conn.InvokeMethod("CreateDiskImage", self.spms[0], **in_params) if rc == 0: print 'Disk was created when it shouldnt have been' result = 0
def __init__(self, Ip, userName, password, need_shared_storage=False, create_vms=True, logfile=None): dir = os.getcwd() if logfile == None: self.logfilename = sys._getframe(2).f_code.co_filename + ".log" else: self.logfilename = logfile print "Location of result log : " + self.logfilename self.oldstdout = sys.stdout self.oldstderr = sys.stderr self.logfile = open(self.logfilename, 'w') sys.stdout = self.logfile sys.stderr = self.logfile print 'TestSetup...' verbose = "false" for arg in sys.argv: if arg == "verbose": verbose = "true" # some useful counters self.TestsPassed = 0 self.TestsFailed = 0 self.TestFailedDescriptions = "" #self.inputMsg = ">" self.IPAddress = Ip self.UserName = userName self.Password = password self.hvmname = 'test-hvm-vm' self.pvname = 'test-pv-vm' self.pv_test_vm = None self.hvm_test_vm = None # create a CIM connection to the server self.conn = pywbem.WBEMConnection('http://' + self.IPAddress, (self.UserName, self.Password)) # Enumerate the Xen Pool my_pool = None pools = self.conn.EnumerateInstances("Xen_HostPool") if len(pools) != 0: my_pool = pools[0] # Enumerate all networks and pick an appropriate network to use network_to_use = None networks = self.conn.EnumerateInstances("Xen_NetworkConnectionPool") for network in networks: network_to_use = network # pick the first one ? this will be what the VM will be connected on break print "Using Network: %s (%s)" % (network_to_use['PoolID'], network_to_use['Name']) # Pick an appropriate SR for use in tests self.sr_to_use = None sr_to_use_local = None if my_pool != None: # Try the default storage of the host pool, if available if my_pool['DefaultStoragePoolID'] != None and my_pool[ 'DefaultStoragePoolID'] != '': print 'default storage pool id %s' % my_pool[ 'DefaultStoragePoolID'] #query_str = "SELECT * FROM Xen_StoragePool WHERE InstanceID = \""+my_pool['DefaultStoragePoolID']+"\"" query_str = "SELECT * FROM Xen_StoragePool WHERE InstanceID LIKE \"%" + my_pool[ 'DefaultStoragePoolID'] + "%\"" print 'Executing query: %s' % query_str defsrs = self.conn.ExecQuery("WQL", query_str, "root/cimv2") sr_to_use_local = defsrs[0] #sr_ref = CIMInstanceName(classname="Xen_StoragePool", keybindings={"InstanceID":'Xen:Shared\\'+my_pool["DefaultStoragePoolID"]}) #sr_to_use_local = self.conn.GetInstance(sr_ref) if sr_to_use_local == None: # No default SR is available srs = self.conn.EnumerateInstances("Xen_StoragePool") for sr in srs: if sr['ResourceSubType'] == 'nfs' or sr[ 'ResourceSubType'] == 'lvmoiscsi': sr_to_use_local = sr break elif need_shared_storage == False and sr[ 'Name'] == 'Local storage': sr_to_use_local = sr break print "Using SR: %s (%s)" % (sr_to_use_local["PoolID"], sr_to_use_local['Name']) # create CIM reference out of CIM instance self.sr_to_use = CIMInstanceName( classname=sr_to_use_local.classname, keybindings={"InstanceID": sr_to_use_local["InstanceID"]}) self.DiskPoolID = sr_to_use_local['PoolID'] # Get instance of Virtual System Management Service self.vsms = self.conn.EnumerateInstanceNames( "Xen_VirtualSystemManagementService") ################ Virtual System Setting Data (VSSD) ################ # VSSD for a PV VM type self.pv_vssd = CIMInstance("Xen_ComputerSystemSettingData") self.pv_vssd['Description'] = 'Test PV VM' self.pv_vssd['ElementName'] = self.__class__.__name__ + '_PV' self.pv_vssd['VirtualSystemType'] = 'DMTF:xen:PV' self.pv_vssd['PV_Bootloader'] = 'pygrub' self.pv_vssd['AutomaticShutdownAction'] = pywbem.Uint8(2) self.pv_vssd['AutomaticStartupAction'] = pywbem.Uint8(3) self.pv_vssd['AutomaticRecoveryAction'] = pywbem.Uint8(3) self.pv_vssd['PV_Args'] = 'Term=xterm' self.pv_vssd['Other_Config'] = ['HideFromXenCenter=false'] # Virtual System setting data for an HVM type self.hvm_vssd = CIMInstance("Xen_ComputerSystemSettingData") self.hvm_vssd['Description'] = 'Test HVM VM' self.hvm_vssd['ElementName'] = self.__class__.__name__ + '_HVM' self.hvm_vssd['VirtualSystemType'] = 'DMTF:xen:HVM' self.hvm_vssd['HVM_Boot_Params'] = ['order=dc'] self.hvm_vssd['HVM_Boot_Policy'] = 'BIOS order' self.hvm_vssd['Platform'] = ['acpi=true', 'apic=true', 'pae=true'] ####################################################################### # define all the Virtual System Resource Allocation Setting Data (RASD) ####################################################################### ####################################################################### # RASD to specify processor allocation for the VM # Processor RASD self.proc_rasd = CIMInstance('CIM_ResourceAllocationSettingData') self.proc_rasd['ResourceType'] = pywbem.Uint16(3) self.proc_rasd['VirtualQuantity'] = pywbem.Uint64(1) self.proc_rasd['AllocationUnits'] = 'count' # Another processor RASD with different limit/weight values self.proc1_rasd = self.proc_rasd.copy() self.proc1_rasd['VirtualQuantity'] = pywbem.Uint64(1) self.proc1_rasd['Limit'] = pywbem.Uint32( 95) # max host CPU it could take up in % self.proc1_rasd['Weight'] = pywbem.Uint32( 512) # relative weight between VCPUs (1-65536) # Processor RASD with wrong resource type self.invalid_proc_rasd = self.proc_rasd.copy() self.invalid_proc_rasd['ResourceType'] = pywbem.Uint32(10000) # processor RASD with no resource type specified, the classname has to be base class self.nort_proc_rasd = CIMInstance('CIM_ResourceAllocationSettingData') self.nort_proc_rasd['VirtualQuantity'] = pywbem.Uint64(1) self.nort_proc_rasd['AllocationUnits'] = 'count' # processor RASD with invalid quantity specified self.invalid_vq_proc_rasd = self.proc_rasd.copy() self.invalid_vq_proc_rasd['VirtualQuantity'] = pywbem.Uint64(10000) # plain old bad processor rasd - mixed types for properties self.bad_proc_rasd = self.proc_rasd.copy() self.bad_proc_rasd['ResourceType'] = '3' # string instead of integer self.bad_proc_rasd['VirtualQuantity'] = '1' self.bad_proc_rasd['AllocationUnits'] = pywbem.Uint8( 1) # integer instead of string self.bad_proc_rasd['Limit'] = '100' # string instead of integer ####################################################################### # memory RASD to specify memory allocation settings for a VM self.mem_rasd = CIMInstance('Xen_MemorySettingData') self.mem_rasd['ResourceType'] = pywbem.Uint16(4) self.mem_rasd['VirtualQuantity'] = pywbem.Uint64(512) self.mem_rasd['AllocationUnits'] = 'byte*2^20' # 2nd RASD to specify more memory self.mem1_rasd = self.mem_rasd.copy() self.mem1_rasd['VirtualQuantity'] = pywbem.Uint64(1024) # mix in wrong types (integers for strings, and strings for integers) self.bad_mem_rasd = self.mem_rasd.copy() self.bad_mem_rasd['AllocationUnits'] = pywbem.Uint32(20) self.bad_mem_rasd['VirtualQuantity'] = "1024" self.bad_mem_rasd['ResourceType'] = "4" ####################################################################### # Resource Allocation Settings to specify Virtual Disk allocation # Start off with a CD drive self.disk0_rasd = CIMInstance('Xen_DiskSettingData') self.disk0_rasd['ElementName'] = self.__class__.__name__ + '_CDRom' self.disk0_rasd['ResourceType'] = pywbem.Uint16(15) # DVD Drive self.disk0_rasd['ResourceSubType'] = 'CD' # self.disk1_rasd['PoolID'] = '<SR ID>' # (No need to specify a SR or VDI, should create an empty DVD # self.disk1_rasd['HostResource'] = '<VDI ID>' # (No need to specify a SR or VDI, should create an empty DVD self.disk0_rasd['Bootable'] = True self.disk0_rasd['Access'] = pywbem.Uint8(1) # A virtual disk of 2 GB size self.disk1_rasd = self.disk0_rasd.copy() self.disk1_rasd['PoolID'] = sr_to_use_local['PoolID'] self.disk1_rasd['ElementName'] = self.__class__.__name__ + '_Disk1' self.disk1_rasd['ResourceType'] = pywbem.Uint16(19) # Storage extent self.disk1_rasd['ResourceSubType'] = 'Disk' self.disk1_rasd['VirtualQuantity'] = pywbem.Uint64(2147483648) # 2GB self.disk1_rasd['AllocationUnits'] = 'byte' # Another virtual disk of 2 GB size self.disk2_rasd = self.disk0_rasd.copy() self.disk2_rasd['PoolID'] = sr_to_use_local['PoolID'] self.disk2_rasd['ResourceType'] = pywbem.Uint16(19) # Storage extent self.disk2_rasd['ResourceSubType'] = 'Disk' self.disk2_rasd['ElementName'] = self.__class__.__name__ + '_Disk2' self.disk2_rasd['VirtualQuantity'] = pywbem.Uint64(2147483648) # 2GB self.disk2_rasd['AllocationUnits'] = 'byte' # mix in wrong types (integers for strings, and strings for integers) self.bad_disk_rasd = self.disk0_rasd.copy() self.bad_disk_rasd['PoolID'] = sr_to_use_local['PoolID'] self.bad_disk_rasd['ElementName'] = pywbem.Uint8(1) self.bad_disk_rasd['ResourceType'] = '15' self.bad_disk_rasd['HostResource'] = pywbem.Uint16(12345) self.bad_disk_rasd['Bootable'] = pywbem.Uint8(1) # create a disk out of a non-existent SR self.invalid_poolId_rasd = self.disk0_rasd.copy() self.invalid_poolId_rasd[ 'PoolId'] = 'ed1bd47e-1ab8-d80a-aecf-06447871211c' # Specify bad allocation units self.invalid_aunits_rasd = self.disk0_rasd.copy() self.invalid_aunits_rasd['PoolID'] = sr_to_use_local['PoolID'] self.invalid_poolId_rasd['AllocationUnits'] = 'KiloMeters' ####################################################################### # Specify the network connection resource allocation setting data # The system will create a virtual NIC for each resource # self.nic_rasd = CIMInstance('Xen_NetworkPortSettingData') self.nic_rasd['ResourceType'] = pywbem.Uint16( 33) # ethernet connection type self.nic_rasd[ 'Address'] = '00:13:72:24:32:f4' # manually generated MAC self.nic_rasd['PoolID'] = network_to_use['PoolID'] # NIC RASD With no mac address - generate one # NIC RASD with no ElementName either - pick next available address self.nic1_rasd = self.nic_rasd.copy() del self.nic1_rasd['Address'] # RASD with no resource type self.nort_nic_rasd = self.nic_rasd.copy() del self.nort_nic_rasd['ResourceType'] # RASD with bad MAC address specified self.invalid_nic_rasd = self.nic_rasd.copy() self.invalid_nic_rasd['Address'] = '00:13:72:24:32:rr' # mixed types for properties (strings for integers and vice versa) self.bad_nic_rasd = self.nic_rasd.copy() self.bad_nic_rasd['ResourceType'] = '33' # supposed to be a int self.bad_nic_rasd['ElementName'] = pywbem.Uint8( 0) # supposed to be a string self.bad_nic_rasd['Address'] = pywbem.Uint64( 001372243245) # supposed to be a string ####################################################################### # Create the test VMs if requested during the test # # Create the PV VM from the Demo Linux VM template (previously the Debian Etch Template) try: pv_template_list = self.conn.ExecQuery( "WQL", "SELECT * FROM Xen_ComputerSystemTemplate WHERE ElementName LIKE \"%XenServer Transfer VM%\"", "root/cimv2") self.pv_template = CIMInstanceName( classname=pv_template_list[0].classname, keybindings={"InstanceID": pv_template_list[0]["InstanceID"]}) self.rasds = [ self.proc_rasd, self.mem_rasd, self.disk0_rasd, self.disk1_rasd, self.nic_rasd ] self.hvm_params = { 'SystemSettings': self.hvm_vssd, 'ResourceSettings': self.rasds } self.pv_params = { 'SystemSettings': self.pv_vssd, 'ResourceSettings': self.rasds, 'ReferenceConfiguration': self.pv_template } self.pv_test_vm = None self.hvm_test_vm = None if create_vms: #print 'using template %s to create PV vm: ' % str(debian_template) print 'Creating PV vm' self.pv_test_vm = CreateVM(self.conn, self.vsms[0], self.pv_params) print 'Creating HVM vm' self.hvm_test_vm = CreateVM(self.conn, self.vsms[0], self.hvm_params) except Exception, e: print "Exception: %s. Has the TVM template been installed?" % e
def _compare_values(instance, time, logger): log = "Entering _compare_values: " types = { 'boolprop': 'boolean', 'dateprop': 'datetime', 'real32prop': 'real32', 'real32propa': 'real32', 'real64prop': 'real64', 'real64propa': 'real64', 'sint16prop': 'sint16', 'sint16propa': 'sint16', 'sint32prop': 'sint32', 'sint32propa': 'sint32', 'sint64prop': 'sint64', 'sint64propa': 'sint64', 'sint8prop': 'sint8', 'sint8propa': 'sint8', 'stringprop': 'string', 'stringpropa': 'string', 'uint16prop': 'uint16', 'uint16propa': 'uint16', 'uint32prop': 'uint32', 'uint32propa': 'uint32', 'uint64prop': 'uint64', 'uint64propa': 'uint64', 'uint8prop': 'uint8', 'uint8propa': 'uint8' } print '#### _compare_values called. Name:', instance['Name'] if instance['Name'] in _atoms: #print instance['Name'] atoms_value = _atoms.get(instance['Name']) for pname, value in instance.items(): prop = pname.lower() print '### Checking prop:', prop print '### types.get(prop)', str(types.get(prop)) #Char and Char_array if prop == 'char16prop' or prop == 'char16propa': pass #Date Property elif prop == 'dateprop': if str(instance[prop]) != str(time): logger.log_debug("DateProp NOT EQUAL") return false #Name or stringProp elif prop == 'name' or prop == 'stringprop': if instance['name'] not in _atoms or \ instance['stringProp'] not in _atoms: logger.log_debug("Atom name NOT FOUND: %s" & instance['name']) return false #boolProp elif prop == 'boolprop': if instance[prop] != False: logger.log_debug("False NOT EQUAL False") return false #All values not in lists elif (instance.properties[prop].type == types.get(prop)) and \ value == atoms_value and \ type(instance.properties[prop].value) != type([]): if prop == 'uint8prop': if pywbem.Uint8(atoms_value) != instance[prop]: logger.log_debug("%s Error: %s" % (prop, instance[prop])) return false elif atoms_value != value: logger.log_debug("%s == %s" % (atoms_value, value)) return false #All list values elif type(instance.properties[prop].value) == type([]) and \ instance.properties[prop].type == types.get(prop): if prop == 'stringpropa': if value[0] != 'proton' and value[1] != 'electron' \ and value[2] != 'neutron': logger.log_debug("String Array NOT EQUAL") return false elif prop == 'uint8': for val in instance.properties[prop].value: if pywbem.uint8(atoms_value) != val: logger.log_debug("Uint8 Values NOT EQUAL") return false else: for a_prop in instance.properties[prop].value: if a_prop != atoms_value: logger.log_debug("%s NOT EQUAL %s" % (atoms_value\ , value)) return false else: print '!! instance.properties[prop].type:', str( instance.properties[prop].type) print '!! types.get(prop):', str(types.get(prop)) print '!! type(instance.properties[prop].value):', str( type(instance.properties[prop].value)) print "!! prop:", prop print "!! Test Atom %s NOT EQUAL %s" % (atoms_value, value) logger.log_debug("%s NOT EQUAL %s" % (atoms_value, value)) return False else: logger.log_debug("Instance of TestAtom not Found: %s" % (instance['Name'])) return false return True
def _create_test_instance(ch, name_of_atom, number, time): """ Create a TestAtom instance. """ global _inst_paths new_instance = pywbem.CIMInstance('TestAtom') new_instance['Name'] = name_of_atom new_instance['boolProp'] = False #new_instance['char16Prop'] = #new_instance['char16Propa'] = Null new_instance['dateProp'] = time new_instance['real32Prop'] = pywbem.Real32(number) #new_instance['real32Propa'] = pywbem.CIMProperty('Real32Propa', \ type='Real32', is_array=True, value=None) new_instance['real32Propa'] = [pywbem.Real32(number), \ pywbem.Real32(number), \ pywbem.Real32(number)] new_instance['real64Prop'] = pywbem.Real64(number) new_instance['real64Propa'] = [pywbem.Real64(number), \ pywbem.Real64(number), \ pywbem.Real64(number)] new_instance['sint16Prop'] = pywbem.Sint16(number) new_instance['sint16Propa'] = [pywbem.Sint16(number), \ pywbem.Sint16(number), \ pywbem.Sint16(number)] new_instance['sint32Prop'] = pywbem.Sint32(number) new_instance['sint32Propa'] = [pywbem.Sint32(number), \ pywbem.Sint32(number), \ pywbem.Sint32(number)] new_instance['sint64Prop'] = pywbem.Sint64(number) new_instance['sint64Propa'] = [pywbem.Sint64(number), \ pywbem.Sint64(number), \ pywbem.Sint64(number)] new_instance['sint8prop'] = pywbem.Sint8(number) new_instance['sint8Propa'] = [pywbem.Sint8(number), \ pywbem.Sint8(number), \ pywbem.Sint8(number)] new_instance['stringProp'] = name_of_atom new_instance['stringPropa'] = ['proton', 'electron', 'neutron'] new_instance['uint16Prop'] = pywbem.Uint16(number) new_instance['uint16Propa'] = [pywbem.Uint16(number), \ pywbem.Uint16(number), \ pywbem.Uint16(number)] new_instance['uint32Prop'] = pywbem.Uint32(number) new_instance['uint32Propa'] = [pywbem.Uint32(number), \ pywbem.Uint32(number), \ pywbem.Uint32(number)] new_instance['uint64Prop'] = pywbem.Uint64(number) new_instance['uint64Propa'] = [pywbem.Uint64(number), \ pywbem.Uint64(number), \ pywbem.Uint64(number)] new_instance['uint8Prop'] = pywbem.Uint8(number) new_instance['uint8Propa'] = [pywbem.Uint8(number), \ pywbem.Uint8(number), \ pywbem.Uint8(number)] try: msg = '' cipath = ch.CreateInstance(new_instance) new_instance.path = cipath _inst_paths.append(cipath) except pywbem.CIMError, arg: raise
class RunMonth(object): January = pywbem.Uint8(0) February = pywbem.Uint8(1) March = pywbem.Uint8(2) April = pywbem.Uint8(3) May = pywbem.Uint8(4) June = pywbem.Uint8(5) July = pywbem.Uint8(6) August = pywbem.Uint8(7) September = pywbem.Uint8(8) October = pywbem.Uint8(9) November = pywbem.Uint8(10) December = pywbem.Uint8(11) _reverse_map = { 0: 'January', 1: 'February', 2: 'March', 3: 'April', 4: 'May', 5: 'June', 6: 'July', 7: 'August', 8: 'September', 9: 'October', 10: 'November', 11: 'December' }
def Delete_VM(self): self.TestBegin() # In addition to 1 hard drive and a NIC, add a 3rd ISO CDrom and make sure the ISO file is not deleted at the end disk2_rasd = CIMInstance('Xen_DiskSettingData') disk2_rasd['ElementName'] = "testcdrom_via_iso" disk2_rasd['ResourceType'] = pywbem.Uint16(15) disk2_rasd['ResourceSubType'] = "CD" disk2_rasd['Device'] = "0" disk2_rasd['Bootable'] = False disk2_rasd['Access'] = pywbem.Uint8(1) # Specify Physical ISO file to use xen_tools_iso = self.conn.ExecQuery("WQL", "SELECT * FROM Xen_DiskImage WHERE ElementName = \"xs-tools.iso\"", "root/cimv2") num_isos = len(xen_tools_iso) disk2_rasd['HostResource'] = ["root/cimv2:Xen_DiskImage.DeviceID=\""+xen_tools_iso[0]['DeviceID']+"\""] rasds = [self.proc_rasd, self.mem_rasd, disk2_rasd, self.disk1_rasd, self.nic_rasd] hvm_vssd = self.hvm_vssd.copy() hvm_vssd['ElementName'] = sys._getframe(0).f_code.co_name + '_HVM' pv_vssd = self.pv_vssd.copy() pv_vssd['ElementName'] = sys._getframe(0).f_code.co_name + '_PV' hvm_params = {'SystemSettings': hvm_vssd, 'ResourceSettings': rasds} pv_params = {'SystemSettings': pv_vssd, 'ResourceSettings': rasds} print 'create vm test' new_pv_vm = CreateVM(self.conn, self.vsms[0], pv_params) new_hvm_vm = CreateVM(self.conn, self.vsms[0], hvm_params) if ((new_pv_vm == None) and (new_hvm_vm == None)): print "VMs are not created" self.publish_result(0) print "VMs are created" # Keep track of all the resources to check for, once deleted disk_list = GetDisksForVM(self.conn, new_pv_vm) hvm_cd_list = GetDiskDrivesForVM(self.conn, new_hvm_vm) pv_cd_list = GetDiskDrivesForVM(self.conn, new_pv_vm) hvm_disk_list = GetDisksForVM(self.conn, new_hvm_vm) pv_net_list = GetNetworkPortsForVM(self.conn, new_pv_vm) rasdlist = [] print "Network in rasd" for net in pv_net_list: pv_net_rasd_list = GetNetworkPortRASDs(self.conn, net) print len(pv_net_rasd_list) for pv_net_rasd in pv_net_rasd_list: print pv_net_rasd['InstanceID'] rasdlist.append([str(pv_net_rasd['InstanceID'])]) hvm_net_list = GetNetworkPortsForVM(self.conn, new_hvm_vm) for net in hvm_net_list: hvm_net_rasd_list = GetNetworkPortRASDs(self.conn, net) for hvm_net_rasd in hvm_net_rasd_list: print hvm_net_rasd['InstanceID'] rasdlist.append([str(hvm_net_rasd['InstanceID'])]) All_Disk_List = self.conn.EnumerateInstanceNames("Xen_Disk") for disk in All_Disk_List: for this_disk in hvm_disk_list: if (disk['DeviceID'] == this_disk['DeviceID']): print "HVM_Disk is found before deletion" for this_disk in disk_list: if (disk['DeviceID'] == this_disk['DeviceID']): print "PV_Disk is found before deletion" for disk_drive_ref in pv_cd_list: disk_drive = self.conn.GetInstance(disk_drive_ref) if disk_drive['ElementName'] != 'xs-tools.iso': print "PV_DiskDrive %s found. failure" % disk_drive['ElementName'] self.publish_result(0) for disk_drive_ref in hvm_cd_list: disk_drive = self.conn.GetInstance(disk_drive_ref) if disk_drive['ElementName'] != 'xs-tools.iso': print "HVM DiskDrive %s found. failure" % disk_drive['ElementName'] self.publish_result(0) # Now delete the VM pv_val = DeleteVM(self.conn, self.vsms[0], new_pv_vm) hvm_val = DeleteVM(self.conn, self.vsms[0], new_hvm_vm) # Verify that the virtual resuorces are all gone (except the physical ISO file) xen_tools_iso = self.conn.ExecQuery("WQL", "SELECT * FROM Xen_DiskImage WHERE ElementName = \"xs-tools.iso\"", "root/cimv2") num_isos_left = len(xen_tools_iso) All_net_List = self.conn.EnumerateInstanceNames("Xen_NetworkPortSettingData") netNotFound = 1 for net in All_net_List: #print "Network" #print net.items() net_instance_id = str(net['InstanceID']) print net_instance_id for rasd_net in rasdlist: if (net_instance_id == rasd_net): print "Network rasd found after deletion" netNotFound = 0 All_Disk_List = self.conn.EnumerateInstanceNames("Xen_Disk") pv_notFound = 1 hvm_notFound = 1 for disk in All_Disk_List: for this_disk in hvm_disk_list: if (disk['DeviceID'] == this_disk['DeviceID']): print "HVM_Disk is found after deletion %s" % disk['DeviceID'] hvm_notFound = 0 for this_disk in disk_list: if (disk['DeviceID'] == this_disk['DeviceID']): print "Disk is found after deletion %s " % disk['DeviceID'] pv_notFound = 0 result = 0 if ((pv_notFound == 1) and (hvm_notFound == 1) and (netNotFound == 1) and (pv_val == 1) and (hvm_val ==1) and (num_isos_left == num_isos)): result = 1 else: print "%d %d %d %d %d %d %d" % (pv_notFound, hvm_notFound, netNotFound, pv_val, hvm_val, num_isos_left, num_isos) result = 0 self.TestEnd(result)