def TestHotPlugCpu(vm1, add, positive, opLabel): Log("Testing CPU hot " + opLabel + " for VM " + vm1.GetConfig().GetName()) curCpu = vm1.GetConfig().GetHardware().GetNumCPU() newCpu = curCpu if add: newCpu += 1 else: newCpu -= 1 # Check for a valid CPU count if newCpu == 0: raise Exception("Cpu count cannot be zero") Log("Current cpu count : " + str(curCpu)) # Making sure that hot plug cpu is not enabled Log("Powering off VM") vm.PowerOff(vm1) cspec = Vim.Vm.ConfigSpec() if add: cspec.SetCpuHotAddEnabled(False) else: cspec.SetCpuHotRemoveEnabled(False) vm.Reconfigure(vm1, cspec) Log("Powering on the VM") vm.PowerOn(vm1) # Negative test case - changing CPU count when not allowed Log("Attempting to change CPUs without setting enabled flag") ChangeCpu(vm1, newCpu, False) # Enabling CPU hot add/remove on the VM Log("Powering off VM") vm.PowerOff(vm1) Log("Enabling cpu hot plug") cspec = Vim.Vm.ConfigSpec() if add: cspec.SetCpuHotAddEnabled(True) else: cspec.SetCpuHotRemoveEnabled(True) vm.Reconfigure(vm1, cspec) Log("Powering on the VM") vm.PowerOn(vm1) # Verify reported CPU hot-plug enabled settings Log("Verifying if cpu hot plug enabled is populated") cfgInfo = vm1.GetConfig() if add and cfgInfo.GetCpuHotAddEnabled() != True or \ (not add and cfgInfo.GetCpuHotRemoveEnabled() != True) : raise Exception("Cpu hot plug enabled not set correctly!") # Test CPU hot-plug ChangeCpu(vm1, newCpu, positive) if not positive: return curCpu = vm1.GetConfig().GetHardware().GetNumCPU() if curCpu != newCpu: raise Exception("Cpu count " + str(curCpu) + " not equal to " + str(newCpu))
def normalScene(vm1, numdisks, ctlrKeys, storage): AddDisks(vm1, 15, ctlrKeys) Log("Added 15 disks successfully") try: AddDisks(vm1, 16, ctlrKeys[:1]) except Exception as e: Log("Hit an exception on add more than 15 disks as expected" + str(e)) else: raise Exception( "Error: should not allow more than 15 disks by default") numCtlrs = len(ctlrKeys) for i in range(numCtlrs): advCfgKey = "scsi" + str(i) + ".maxTargets" SetExtraConfig(vm1, advCfgKey, "255") Log("Update maxTargets successfully") if numdisks < 16: numdisk = 1 # add one more disks for fun else: numdisks = numdisks - 15 AddDisks(vm1, numdisks, ctlrKeys, 16, datastore=storage) if vm1.runtime.powerState != Vim.VirtualMachine.PowerState.poweredOn: vm.PowerOn(vm1) Log("Successfully added all disks") vm.PowerOff(vm1)
def cleanup(): try: for vm1 in vmRefs: vm.PowerOff(vm1) vm.Destroy(vm1) except Exception: pass
def cleanup(dvsUuidList): """ Remove the dvs created as part of the setup phase. Assumes no clients are connected. """ if options.nocleanup: print("Not doing cleanup as requested") return vm1 = folder.Find(options.vmName) if vm1 != None: try: vm.PowerOff(vm1) except Exception as e: pass vm.Destroy(vm1) dvsManager = si.RetrieveInternalContent( ).hostDistributedVirtualSwitchManager # If list is None, script collapses here if dvsUuidList != None: for dvsUuid in dvsUuidList: try: dvsManager.RemoveDistributedVirtualSwitch(dvsUuid) except Exception as e: print(e) del dvsUuidList[:] try: dvsManager.RemoveDistributedVirtualSwitch(options.uuid) except Exception as e: print(e)
def powerOffVM(virtualMachine): vm.PowerOff(virtualMachine); while True: Log("Waiting for VM to get powered off"); if virtualMachine.GetRuntime().GetPowerState() == Vim.VirtualMachine.PowerState.poweredOff: break time.sleep(3)
def CleanupVm(vmname, useLlpm=False): with LogSelfOp() as logOp: if isinstance(vmname, vim.VirtualMachine): Log("Cleaning up VMs with name %s" % vmname.name) oldVms = [vmname] else: Log("Cleaning up VMs with name %s" % vmname) oldVms = folder.FindPrefix(vmname) for oldVm in oldVms: if oldVm.GetRuntime().GetPowerState() == PowerState.poweredOn: vm.PowerOff(oldVm) ftInfo = oldVm.config.ftInfo if ftInfo and ftInfo.role == 1: # If the VM is a primary, unregister all secondaries # before deleting the VM. ftMgr = host.GetFaultToleranceMgr(connect.GetSi()) WaitForTask(ftMgr.UnregisterSecondary(oldVm, None)) Log("Destroying VM") if useLlpm == True: vmConfig = oldVm.GetConfig() hw = vmConfig.GetHardware() if vmConfig.flags.faultToleranceType and \ vmConfig.flags.faultToleranceType == "recordReplay": hw.SetDevice([]) vmConfig.SetHardware(hw) llpm = invt.GetLLPM() llpm.DeleteVm(vmConfig) else: vm.Destroy(oldVm)
def TestVQATReconfig(vm1): """ Test add and remove for VQAT controller """ Log("Adding VQAT") cspec = vim.vm.ConfigSpec() for i in range(MAX_QAT_DEV): AddVQAT(cspec) vm.Reconfigure(vm1, cspec) CheckQATPresent(vm1, MAX_QAT_DEV) TestAdd5thQAT(vm1) TestVQATRemoveInvalid(vm1) CheckQATPresent(vm1, MAX_QAT_DEV) TestVQATMove(vm1, -1) TestVQATMove(vm1, QAT_DEV_KEY) TestVQATMove(vm1, 100) vm.PowerOn(vm1) try: TestVQATRemoveInvalid(vm1) TestVQATHotRemove(vm1) finally: vm.PowerOff(vm1) # Remove QAT controller from VM Log("Removing QAT devices from VM") for i in range(MAX_QAT_DEV): RemoveDev(vm1, CreateVQAT(QAT_DEV_KEY + i)) CheckQATNotPresent(vm1)
def main(): """ Simple command-line program for creating virtual machines on a system managed by hostd. """ options = GetOptions() Connect(host=options.host, user=options.user, pwd=options.password) # Create vms envBrowser = GetEnv() cfgOption = envBrowser.QueryConfigOption(None, None) cfgTarget = envBrowser.QueryConfigTarget(None) for i in range(int(options.num_iterations)): vm1 = vm.CreateQuickDummy(options.vm_name + "_" + str(i), options.num_scsi_disks, options.num_ide_disks, datastoreName=options.datastore_name, cfgOption=cfgOption, cfgTarget=cfgTarget) for _ in range(int(options.num_power_cycles)): clock = StopWatch() vm.PowerOn(vm1) clock.finish("PowerOn done") clock = StopWatch() vm.PowerOff(vm1) clock.finish("PowerOff done") # Delete the vm as cleanup if not options.dont_delete: task = vm1.Destroy() WaitForTask(task)
def PowerCycle(vm1): Log("Powercycle (on)") vm.PowerOn(vm1) time.sleep(2) Log("Powercycle (off)") vm.PowerOff(vm1) time.sleep(2)
def CleanupVm(self, vmname): oldVms = folder.FindPrefix(vmname) for oldVm in oldVms: if oldVm.GetRuntime().GetPowerState() == \ Vim.VirtualMachine.PowerState.poweredOn: vm.PowerOff(oldVm) vm.Destroy(oldVm)
def TestVTPMReconfig(vm1): """ Test add and remove for vTPM controller """ Log("Adding vTPM") cspec = vim.vm.ConfigSpec() AddVTPM(cspec) vm.Reconfigure(vm1, cspec) CheckTPMPresent(vm1) TestAdd2ndTPM(vm1) TestVTPMRemoveInvalid(vm1) CheckTPMPresent(vm1) TestVTPMMove(vm1, -1) TestVTPMMove(vm1, TPM_DEV_KEY) TestVTPMMove(vm1, 100) TestVTPMProps(vm1) vm.PowerOn(vm1) try: TestVTPMProps(vm1) TestVTPMRemoveInvalid(vm1) TestVTPMHotRemove(vm1) finally: vm.PowerOff(vm1) # Remove TPM controller from VM Log("Removing TPM device from VM") TestVTPMRemoveDev(vm1, CreateVTPM(TPM_DEV_KEY))
def TestEditSataCdrom(vm1): """ Test reconfigures of SATA cdroms """ cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddSataCtlr(cspec) vm.Reconfigure(vm1, cspec) Log("Add SATA cdrom.") AddSataCdrom(vm1) Log("Reconfigure cdrom backing.") TestReconfigCdromBacking(vm1) Log("Snapshot VM and revert to snapshot.") TestSnapshotCdrom(vm1) Log("Moving cdrom from SATA to IDE controller.") ideCtlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualIDEController) cdrom = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualCdrom)[0] TestMoveDevice(vm1, cdrom, ideCtlrs[0]) Log("Remove cdrom.") RemoveSataCdrom(vm1) Log("Testing hot-add and hot-remove of SATA cdrom.") vm.PowerOn(vm1) AddSataCdrom(vm1) RemoveSataCdrom(vm1) vm.PowerOff(vm1) ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualSATAController) vm.RemoveDevice(vm1, ctlrs[0])
def TestSataCtlrReconfig(vm1): """ Test add and remove for SATA controller """ Log("Adding SATA controller to VM") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddSataCtlr(cspec, cfgInfo = vm1.config) vm.Reconfigure(vm1, cspec) # Check for controller presence in VM's config ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualAHCIController) if len(ctlrs) != 1: raise Exception("Failed to find added SATA controller :" + str(len(ctlrs))) Log("Powering on VM " + vm1.config.GetName()) vm.PowerOn(vm1) Log("Hot-add SATA controller to VM") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddSataCtlr(cspec, cfgInfo = vm1.config) vm.Reconfigure(vm1, cspec) ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualAHCIController) if len(ctlrs) != 2: raise Exception("Failed to find added SATA controller :" + str(len(ctlrs))) vm.PowerOff(vm1) # Remove SATA controller from VM Log("Removing SATA controllers from VM") cspec = Vim.Vm.ConfigSpec() vmconfig.AddDeviceToSpec(cspec, ctlrs[0], Vim.Vm.Device.VirtualDeviceSpec.Operation.remove) vmconfig.AddDeviceToSpec(cspec, ctlrs[1], Vim.Vm.Device.VirtualDeviceSpec.Operation.remove) vm.Reconfigure(vm1, cspec)
def TestVWDTReconfig(vm1): """ Test add and remove for vWDT controller """ Log("Adding vWDT") cspec = vim.vm.ConfigSpec() AddVWDT(cspec) vm.Reconfigure(vm1, cspec) CheckWDTPresent(vm1) TestAdd2ndWDT(vm1) TestVWDTRemoveInvalid(vm1) CheckWDTPresent(vm1) TestVWDTReplaceKey(vm1, -1) TestVWDTReplaceKey(vm1, WATCHDOGTIMER_DEV_KEY) TestVWDTReplaceKey(vm1, 100) vm.PowerOn(vm1) try: TestVWDTRemoveInvalid(vm1) TestVWDTHotRemove(vm1) finally: vm.PowerOff(vm1) # Remove vWDT controller from VM Log("Removing watchdog timer from VM") TestVWDTRemoveDev(vm1, CreateVWDT(WATCHDOGTIMER_DEV_KEY))
def RunCreateTest(name): vm1 = vm.CreateQuickDummy(name) vm.PowerOn(vm1) vm.PowerOff(vm1) cfgPath = vm1.GetConfig().GetFiles().GetVmPathName() vm1.Unregister() folder.Register(cfgPath) vm.Destroy(vm1)
def off(self): try: for vmIter in self.vmList: vm.PowerOff(vmIter) self.success = True print self.getClientId() + " off successful" except: self.success = False print self.getClientId() + " off failed"
def TestVmMigrate(self): self.banner(self.TestVmMigrate) if len(self._hosts) <= 1: VerboseLog(logInfo,"not enough hosts..skipping") vmname = "test_migrate_vvol_vm" self.CleanupVm(vmname) host1 = self._hosts[0] host2 = self._hosts[1] scId = self._sc spec = Vim.Host.DatastoreSystem.VvolDatastoreSpec() spec.SetScId(scId) spec.SetName("vvol-test-ds:%s" % random.randint(1,1000)) ret=True try: VerboseLog(logTrivia, "{ Creating bulk: ") create_task = self._vasaMgr.CreateVVolDatastore(spec, self._hosts) task.WaitForTask(create_task) VerboseLog(logVerbose, create_task.info.result) for result in create_task.info.result : if result.result == 'fail': VerboseLog(logInfo, "create failed for host " + result.hostKey) raise Exception("unexpected failure") ds = create_task.info.result[0].ds; testvm = vm.CreateQuickDummy(vmname, host=host1, datastoreName=ds.name, dc=self._dc.name, numScsiDisks=1, memory=12) vm.PowerOn(testvm) migrate_task = testvm.Migrate(host2.parent.resourcePool, host2, Vim.VirtualMachine.MovePriority.highPriority, None) task.WaitForTask(migrate_task) vm.PowerOff(testvm) vm.Destroy(testvm) VerboseLog(logTrivia, "{ Removing bulk: ") delete_task = self._vasaMgr.RemoveVVolDatastore(ds, self._hosts) task.WaitForTask(delete_task) VerboseLog(logVerbose, delete_task.info.result) for result in delete_task.info.result : if result.result == 'fail': VerboseLog(logInfo, "remove failed for host " + result.hostKey) raise Exception("unexpected failure in bulk remove") except: VerboseLog(logTrivia, traceback.format_exc()) ret=False VerboseLog(logInfo, "passed" if ret else "failed");
def destroyTestVM(self, vmname): """ Powers down the VM if needed and then destroys it. """ existing_vm = folder.Find(vmname) if existing_vm is not None: if vm.VM(existing_vm, None, None).IsRunning(): vm.PowerOff(existing_vm) existing_vm.Destroy() self._vm = None
def poweredOnScene(vm1, numdisks, ctlrKeys, storage): if numdisks > 15: numCtlrs = len(ctlrKeys) for i in range(numCtlrs): advCfgKey = "scsi" + str(i) + ".maxTargets" SetExtraConfig(vm1, advCfgKey, "255") Log("Update maxTargets successfully") vm.PowerOn(vm1) AddDisks(vm1, numdisks, ctlrKeys, -1, datastore=storage) vm.PowerOff(vm1)
def testPowerCycle(self): vm.PowerOn(self.v1) time.sleep(2) vm.Suspend(self.v1) time.sleep(2) vm.PowerOn(self.v1) time.sleep(2) vm.Reset(self.v1) time.sleep(2) vm.PowerOff(self.v1) time.sleep(2)
def TestNoVTPM(vm1): """ Test that hot-add of vTPM fails """ CheckTPMNotPresent(vm1) TestNoVTPMRemove(vm1) vm.PowerOn(vm1) try: TestNoVTPMRunning(vm1) finally: vm.PowerOff(vm1)
def TestNoVQAT(vm1): """ Test that hot-add of VQAT fails """ CheckQATNotPresent(vm1) TestNoVQATRemove(vm1) vm.PowerOn(vm1) try: TestNoVQATRunning(vm1) finally: vm.PowerOff(vm1)
def getObjMapping(vmName, desc): Log("\nCreating VM object ID map on %s\n" % (desc)) vmRef = CreateQuickDummy(vmName, datastoreName=vvolDsName, \ vmxVersion="vmx-13") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddScsiCtlr(cspec, cfgInfo=vmRef.config) capacityKB = 5 * 1024 vmconfig.AddScsiDisk(cspec, cfgInfo=vmRef.config, capacity=capacityKB, datastorename=vvolDsName, thin=True, scrub=False) InvokeAndTrack(vmRef.Reconfigure, cspec) vmRefs.append(vmRef) vm.PowerOn(vmRef) ssName = ("ss-%s" % random.randint(1, 1000)) vm.CreateSnapshot(vmRef, ssName, "snaphost", memory=True, quiesce=False) global dstVmxId dstVmxId = [] vmMap = {} for f1 in vmRef.layoutEx.file: if f1.type == "config": lastIdx = f1.name.rfind(".") lastIdx1 = f1.name.rfind("/") uuid = f1.name[f1.name.rfind("rfc4122."):lastIdx1] elif f1.backingObjectId: lastIdx = f1.name.rfind(".") uuid = f1.backingObjectId else: continue fname = vmName + f1.name[lastIdx:] vmMap[fname] = uuid Log("\n adding %s - %s\n" % (fname, uuid)) if fname.find(".vmx") != -1: dstVmxId.append(uuid) # Unregister VM to assume only vvol objects exists vm.PowerOff(vmRef) vmRef.Unregister() return vmMap
def cleanupvm(vmName): print("cleaning up vm:'" + vmName + "'") vm1 = folder.Find(vmName) if vm1 is not None: try: vm.PowerOff(vm1) except Exception as e: print(e) try: vm.Destroy(vm1) except Exception as e: print(e)
def Cleanup(vmName, sessions, doCleanup): for hostName, si in sessions.iteritems(): SetSi(si) oldVms = folder.FindPrefix(vmName) if oldVms: if doCleanup: Log("Cleaning up old vms with name: " + vmName) for oldVm in oldVms: if oldVm.GetRuntime().GetPowerState( ) == Vim.VirtualMachine.PowerState.poweredOn: vm.PowerOff(oldVm) oldVm.Destroy()
def TestHotPlugMemory(vm1, positive): Log("Testing memory hot add for VM " + vm1.GetConfig().GetName()) curMB = vm1.GetConfig().GetHardware().GetMemoryMB() newMB = curMB + 30 Log("Current memory: " + str(curMB) + " MB.") # Negative test case - changes memory when not allowed Log("Attempting to hot-add memory without setting enabled flag") ChangeMemory(vm1, newMB, False) # Enable memory hot add on VM Log("Powering off VM") vm.PowerOff(vm1) Log("Enabling memory hot add") cspec = Vim.Vm.ConfigSpec() cspec.SetMemoryHotAddEnabled(True) vm.Reconfigure(vm1, cspec) Log("Powering on the VM") vm.PowerOn(vm1) # Verify if memory values are reported correctly for the VM if positive: Log("Verifying if maxMemory and increment size are populated") cfgInfo = vm1.GetConfig() curMB = cfgInfo.GetHardware().GetMemoryMB() memGrow = cfgInfo.GetHotPlugMemoryIncrementSize() memLimit = cfgInfo.GetHotPlugMemoryLimit() memEnabled = cfgInfo.GetMemoryHotAddEnabled() Log("Memory enabled: " + str(memEnabled) + " Memory limit: " + str(memLimit) + " Memory grow step: " + str(memGrow)) if not memEnabled or memLimit == None or memGrow == None: raise Exception("Memory values not being populated correctly.") newMB = curMB + memGrow # Test memory hot add Log("Testing hot add of memory") ChangeMemory(vm1, newMB, positive) if not positive: return curMB = vm1.GetConfig().GetHardware().GetMemoryMB() if curMB != newMB: raise Exception("Memory after hot-add: " + str(curMB) + " MB.") # Test some negative test cases Log("Testing invalid grow step") ChangeMemory(vm1, newMB + memGrow + 1, False) Log("Testing add of memory beyond published maximum") ChangeMemory(vm1, memLimit + 1, False)
def Cleanup(vmName, doCleanup): if options.vcHost: return oldVms = folder.FindPrefix(vmName) if oldVms: if doCleanup: Log("Cleaning up old vms with name: " + vmName) for oldVm in oldVms: if oldVm.GetRuntime().GetPowerState( ) == Vim.VirtualMachine.PowerState.poweredOn: vm.PowerOff(oldVm) oldVm.Destroy() else: Log("Please cleanup unit test vms from previous runs") sys.exit(-1)
def CleanupVm(vmname, useLlpm = False): Log("Cleaning up VMs with name " + vmname) oldVms = folder.FindPrefix(vmname) for oldVm in oldVms: if oldVm.GetRuntime().GetPowerState() == \ Vim.VirtualMachine.PowerState.poweredOn: vm.PowerOff(oldVm) Log("Destroying VM") if useLlpm == True: vmConfig = oldVm.GetConfig() hw = vmConfig.GetHardware() hw.SetDevice([]) vmConfig.SetHardware(hw) llpm = invt.GetLLPM() llpm.DeleteVm(vmConfig) else: vm.Destroy(oldVm)
def CleanupVm(vmname, useLlpm=False): if isinstance(vmname, vim.VirtualMachine): Log("Cleaning up VMs with name %s" % vmname.name) oldVms = [vmname] else: Log("Cleaning up VMs with name %s" % vmname) oldVms = folder.FindPrefix(vmname) for oldVm in oldVms: if oldVm.GetRuntime().GetPowerState() == PowerState.poweredOn: vm.PowerOff(oldVm) Log("Destroying VM") if useLlpm == True: vmConfig = oldVm.GetConfig() llpm = invt.GetLLPM() llpm.DeleteVm(vmConfig) else: vm.Destroy(oldVm)
def main(): """ Simple command-line program for creating virtual machines on a system managed by hostd. """ options = GetOptions() Connect(host=options.host, user=options.user, namespace=newestVersions.GetNamespace('vim'), pwd=options.password) # Create vms envBrowser = GetEnv() cfgOption = envBrowser.QueryConfigOption(None, None) cfgTarget = envBrowser.QueryConfigTarget(None) for i in range(int(options.num_iterations)): vm1 = vm.CreateQuickDummy(options.vm_name + "_" + str(i), options.num_scsi_disks, options.num_ide_disks, datastoreName=options.datastore_name, cfgOption=cfgOption, cfgTarget=cfgTarget) if options.opaquenetwork_id: config = Vim.Vm.ConfigSpec() config = vmconfig.AddOpaqueNetwork(config, cfgOption, opaqueNetworkId=options.opaquenetwork_id, \ opaqueNetworkType=options.opaquenetwork_type, \ externalId=options.externalID) vm.Reconfigure(vm1, config) for _ in range(int(options.num_power_cycles)): clock = StopWatch() vm.PowerOn(vm1) clock.finish("PowerOn done") clock = StopWatch() vm.PowerOff(vm1) clock.finish("PowerOff done") # Delete the vm as cleanup if not options.dont_delete: task = vm1.Destroy() WaitForTask(task)