def TestNegVMCIDevice(vm1, isVMCIDefault): if not isVMCIDefault: devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualVMCIDevice) if len(devices) != 0: raise Exception("VMCI device found by default in VM") return failure = False Log("Adding new VMCI device to a VM") try: cspec = Vim.Vm.ConfigSpec() cpsec = vmconfig.AddVMCI(cspec) task = vm1.Reconfigure(cspec) WaitForTask(task) except Exception as e: Log("Verified request was rejected as expected.") failure = True if not failure: raise Exception("Adding VMCI device to VM was allowed!") Log("Attempt to remove VMCI device from VM") devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualVMCIDevice) cspec = Vim.Vm.ConfigSpec() cpsec = vmconfig.RemoveDeviceFromSpec(cspec, devices[0]) try: task = vm1.Reconfigure(cspec) WaitForTask(task) except Exception as e: Log("Verified request was rejected as expected.") return raise Exception("Did not hit an exception as expected")
def RemoveSataDisk(vm1): disk = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)[0] cspec = Vim.Vm.ConfigSpec() fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy vmconfig.RemoveDeviceFromSpec(cspec, disk, fileOp) vm.Reconfigure(vm1, cspec) devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk) if len(devices) != 0: raise Exception("Found disk after delete")
def TestHotPlugDevice( vm1, func, label, devType, positive, testRemove=True, leaveInVm=False, fileOp=None, ): Log("Testing " + label + " hot plug for VM " + vm1.GetConfig().GetName()) failed = False Log("Add a new " + label + " to the VM") cspec = Vim.Vm.ConfigSpec() cspec = func(cspec, cfgInfo=vm1.GetConfig()) devicesBefore = vmconfig.CheckDevice(vm1.GetConfig(), devType) # Hot-add the device try: vm.Reconfigure(vm1, cspec) except Exception as e: failed = True if not positive: Log("Caught exception as expected") return else: raise if not positive and not failed: raise Exception("Did not hit an exception as expected") # Check for device presence in VM's config devicesAfter = vmconfig.CheckDevice(vm1.GetConfig(), devType) if len(devicesAfter) == len(devicesBefore): raise Exception("Failed to find added " + label) if not testRemove: return # Hot-remove the device newDev = devicesAfter[len(devicesAfter) - 1] Log("Removing " + label + " from the VM") cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, newDev, fileOp) vm.Reconfigure(vm1, cspec) devicesAfter = vmconfig.CheckDevice(vm1.GetConfig(), devType) # Check for device absence in the VM's config if len(devicesAfter) != len(devicesBefore): raise Exception(label + " still found in the VM") # Add device back into the VM if necessary if leaveInVm: cspec = Vim.Vm.ConfigSpec() cspec = func(cspec) vm.Reconfigure(vm1, cspec)
def TestDeviceRemove(vm1, devType, devLabel): devices = vmconfig.CheckDevice(vm1.GetConfig(), devType) if len(devices) != 1: raise Exception("Failed to find " + devLabel + " device.") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.RemoveDeviceFromSpec(cspec, devices[0]) task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), devType) if len(devices) != 0: raise Exception("Found " + devLabel + " device even after delete.")
def TestRemoveDevice(vm1, device): Log("Testing removing of device '" + device.description + "' for VM " + vm1.GetConfig().GetName()) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualUSB) cspec = Vim.Vm.ConfigSpec() for dev in devices: if dev.backing.deviceName == device.name: cspec = vmconfig.RemoveDeviceFromSpec(cspec, dev) # Hot-remove the devices vm.Reconfigure(vm1, cspec) # Check for device absence from VM's config CheckNoDevice(vm1, Vim.Vm.Device.VirtualUSB, "USB device")
def TestCreateDisk(vm1): """ Creating disk with various combination of capacityInBytes and capacityInKB. """ Log("Add a new disk with capacityInKB greater than capacityInBytes.") # server must consider capacityInBytes cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddScsiCtlr(cspec, cfgInfo = vm1.config) capacityKB = 4 * 1024 vmconfig.AddScsiDisk(cspec, cfgInfo = vm1.config, capacity = capacityKB) vm.Reconfigure(vm1, cspec) # Server must always return "capacityInBytes" devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk, {"capacityInKB": capacityKB, "capacityInBytes": (capacityKB * 1024)}) if len(devices) != 1: raise Exception("Failed to find new disk!") Log("Add a new disk with capacityInBytes bigger than capacityInKB.") cspec = Vim.Vm.ConfigSpec() capacityBytes = (capacityKB * 1024) + SECTOR_SIZE vmconfig.AddScsiDisk(cspec, cfgInfo = vm1.GetConfig(), capacity = capacityKB, capacityInBytes = capacityBytes) vm.Reconfigure(vm1, cspec) devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk, {"capacityInKB": capacityKB, "capacityInBytes": capacityBytes}) if len(devices) != 1: raise Exception("Capacity did not match expected values!") cspec = Vim.Vm.ConfigSpec() # server must consider capacityInBytes capacityBytes = 2*capacityKB*1024 - SECTOR_SIZE vmconfig.AddScsiDisk(cspec, cfgInfo = vm1.config, capacity = capacityKB, capacityInBytes = capacityBytes) vm.Reconfigure(vm1, cspec) devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk, {"capacityInKB": (2 * capacityKB)-1, "capacityInBytes": capacityBytes}) if len(devices) != 1: raise Exception("Capacity did not match expected values!") Log("Removing virtual disks from VM.") devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk) fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy cspec = Vim.Vm.ConfigSpec() for device in devices: vmconfig.RemoveDeviceFromSpec(cspec, device, fileOp) vm.Reconfigure(vm1, cspec)
def BasicCreateDelete(vm1): ## Test 1. Create and delete a basic floppy cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddFloppy(cspec) task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), VF) if len(devices) != 1: raise "Failed to find added floppy" cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.RemoveDeviceFromSpec(cspec, devices[0]) task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), VF) if len(devices) != 0: raise "Found floppy even after delete" print("Basic create and delete of floppy works!")
def TestEditDisk(vm1): """ Test reconfigures of capacityInBytes and capacityInKB when both are set and differ. """ Log("Adding a new disk.") cspec = Vim.Vm.ConfigSpec() vmconfig.AddScsiDisk(cspec, cfgInfo = vm1.config) vm.Reconfigure(vm1, cspec) devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk) if len(devices) != 1: raise Exception("Failed to find new disk!") disk = devices[0] Log("Increase disk size by 4MB setting capacityInBytes") cspec = Vim.Vm.ConfigSpec() newCapacity = disk.capacityInBytes + 4 * 1024 * 1024 + SECTOR_SIZE newCapacityKB = (newCapacity - SECTOR_SIZE) / 1024 disk.capacityInBytes = newCapacity vmconfig.AddDeviceToSpec(cspec, disk, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit) vm.Reconfigure(vm1, cspec) devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk, {"capacityInBytes": newCapacity, "capacityInKB": newCapacityKB}) if len(devices) != 1: raise Exception("Failed to find the disk with updated capacity: " + str(len(devices))) Log("Atempt to increase only capacityInKB.") newCapacityKB = newCapacityKB + 4*1024 disk.capacityInKB = newCapacityKB cspec = Vim.Vm.ConfigSpec() vmconfig.AddDeviceToSpec(cspec, disk, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit) vm.Reconfigure(vm1, cspec) devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk, {"capacityInKB": newCapacityKB}) if len(devices) != 1: raise Exception("Failed to find the disk with updated capacity: " + str(len(devices))) Log("Removing virtual disk from VM") cspec = Vim.Vm.ConfigSpec() fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy vmconfig.RemoveDeviceFromSpec(cspec, devices[0], fileOp) vm.Reconfigure(vm1, cspec)
def BasicCreateDelete(vm1): ## Test 1. Create and delete a basic sound card cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddSoundCard(cspec) task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualSoundCard) if len(devices) != 1: raise "Failed to find added sound card" cspec2 = Vim.Vm.ConfigSpec() cspec2 = vmconfig.RemoveDeviceFromSpec(cspec2, devices[0]) task2 = vm1.Reconfigure(cspec2) WaitForTask(task2) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualSoundCard) if len(devices) != 0: raise "Found sound card even after delete" print("Basic create and delete of sound card works!")
def CreateSB16WithAutoDetect(vm1): ## Test 4. Create an SB16 with autodetect enabled and delete it. cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddSoundCard(cspec, autodetect=True, type="sb16") task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualSoundBlaster16, {"backing.useAutoDetect": True}) if len(devices) != 1: raise "Failed to find added sound card" cspec2 = Vim.Vm.ConfigSpec() cspec2 = vmconfig.RemoveDeviceFromSpec(cspec2, devices[0]) task2 = vm1.Reconfigure(cspec2) WaitForTask(task2) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualSoundCard) if len(devices) != 0: raise "Found sound card even after delete" print("Creating sb16 with autodetect works!")
def CreateFloppyRemoteWithAutoDetect(vm1, autodetectVal): ## Test 3. Create floppy remote backing with auto detect set as specified and delete it cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddFloppy(cspec, autodetect=autodetectVal, type="remote") task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), VF, { "backing": VFREMOTE, "backing.useAutoDetect": autodetectVal }) if len(devices) != 1: raise "Failed to find added floppy" cspec2 = Vim.Vm.ConfigSpec() cspec2 = vmconfig.RemoveDeviceFromSpec(cspec2, devices[0]) task2 = vm1.Reconfigure(cspec2) WaitForTask(task2) devices = vmconfig.CheckDevice(vm1.GetConfig(), VF) if len(devices) != 0: raise "Found floppy even after delete" print("Creating floppy (remote) with no autodetect works!")
def CreateEnsoniqWithNoAutoDetect(vm1): ## Test 3. Create an ensoniq with auto detect enabled and delete it cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddSoundCard(cspec, autodetect=False, type="ensoniq") task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualEnsoniq1371, {"backing.useAutoDetect": False}) if len(devices) != 1: raise "Failed to find added sound card" cspec2 = Vim.Vm.ConfigSpec() cspec2 = vmconfig.RemoveDeviceFromSpec(cspec2, devices[0]) task2 = vm1.Reconfigure(cspec2) WaitForTask(task2) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualSoundCard) if len(devices) != 0: raise "Found sound card even after delete" print("Creating ensoniq with no autodetect works!")
def CreateFloppyWithNoDeviceAndAutoDetect(vm1): ## Test 7. Create a floppy with autodetect and no device name specified cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddFloppy(cspec, autodetect=True, backingName="") task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualFloppy, { "backing.useAutoDetect": True, "backing.deviceName": "" }) if len(devices) != 1: raise "Failed to find added flopppy" cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, devices[0]) task = vm1.Reconfigure(cspec) WaitForTask(task) devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualFloppy) if len(devices) != 0: raise "Found floppy even after delete" print("Creating floppy with no device name and autodetect works")
def main(): supportedArgs = [ (["h:", "host="], "localhost", "Host name", "host"), (["u:", "user="******"root", "User name", "user"), (["p:", "pwd="], "ca$hc0w", "Password", "pwd"), (["v:", "vmname="], "CreateTest", "Name of the virtual machine", "vmname")] supportedToggles = [(["usage", "help"], False, "Show usage information", "usage")] args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles) if args.GetKeyValue("usage") == True: args.Usage() sys.exit(0) # Connect si = Connect(args.GetKeyValue("host"), 443, args.GetKeyValue("user"), args.GetKeyValue("pwd")) atexit.register(Disconnect, si) # Process command line vmname = args.GetKeyValue("vmname") # Cleanup from previous runs. vm1 = folder.Find(vmname) if vm1 != None: vm1.Destroy() # Create vms envBrowser = invt.GetEnv() config = vm.CreateQuickDummySpec(vmname) cfgOption = envBrowser.QueryConfigOption(None, None) cfgTarget = envBrowser.QueryConfigTarget(None) NIC_DIFFERENCE = 7 config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 0) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 2) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 3) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 4) config = vmconfig.AddNic(config, cfgOption, cfgTarget) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 6) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 7) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 8) config = vmconfig.AddNic(config, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE + 9) config = vmconfig.AddScsiCtlr(config, cfgOption, cfgTarget, unitNumber = 3) config = vmconfig.AddScsiDisk(config, cfgOption, cfgTarget, unitNumber = 0) isofile = "[] /usr/lib/vmware/isoimages/linux.iso" config = vmconfig.AddCdrom(config, cfgOption, cfgTarget, unitNumber = 0, isoFilePath=isofile) image = "[] /vmimages/floppies/vmscsi.flp" config = vmconfig.AddFloppy(config, cfgOption, cfgTarget, unitNumber = 0, type="image", backingName=image) config = vmconfig.AddFloppy(config, cfgOption, cfgTarget, unitNumber = 1, type="image", backingName=image) backing = Vim.Vm.Device.VirtualSerialPort.FileBackingInfo() backing.SetFileName("[]") config = vmconfig.AddSerial(config, backing) try: vmFolder = invt.GetVmFolder() vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None) except Exception as e: raise vm1 = folder.Find(vmname) printNicUnitNumbers(vm1, "Test 1: Creating a vm with lots of nics") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddNic(cspec, cfgOption, cfgTarget) task = vm1.Reconfigure(cspec) WaitForTask(task) printNicUnitNumbers(vm1, "Test 2: Added a nic") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddNic(cspec, cfgOption, cfgTarget) task = vm1.Reconfigure(cspec) try: WaitForTask(task) except Vim.Fault.TooManyDevices as e: print("Caught too many devices as expected") nics = printNicUnitNumbers(vm1, "Test 3: Added too many nics") cspec = Vim.Vm.ConfigSpec() uni = nics[4].GetUnitNumber() cspec = vmconfig.RemoveDeviceFromSpec(cspec, nics[0]) cspec = vmconfig.RemoveDeviceFromSpec(cspec, nics[2]) cspec = vmconfig.RemoveDeviceFromSpec(cspec, nics[4]) cspec = vmconfig.RemoveDeviceFromSpec(cspec, nics[5]) cspec = vmconfig.RemoveDeviceFromSpec(cspec, nics[6]) cspec = vmconfig.AddNic(cspec, cfgOption, cfgTarget) task = vm1.Reconfigure(cspec) WaitForTask(task) printNicUnitNumbers(vm1, "Test 4: Removed a bunch of nics") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddNic(cspec, cfgOption, cfgTarget, unitNumber = NIC_DIFFERENCE - 2) task = vm1.Reconfigure(cspec) WaitForTask(task) printNicUnitNumbers(vm1, "Test 5: Added a nic with slot incorrectly specified") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddNic(cspec, cfgOption, cfgTarget, unitNumber = uni) cspec = vmconfig.AddScsiCtlr(cspec, cfgOption, cfgTarget, unitNumber = 4) cspec = vmconfig.AddScsiDisk(cspec, cfgOption, cfgTarget, unitNumber = 1) task = vm1.Reconfigure(cspec) WaitForTask(task) printNicUnitNumbers(vm1, "Test 6: Added a nic with a slot correctly specified") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddNic(cspec, cfgOption, cfgTarget, unitNumber = uni) task = vm1.Reconfigure(cspec) try: WaitForTask(task) except Vim.Fault.InvalidDeviceSpec as e: print("Exception caught for adding same nic twice") printNicUnitNumbers(vm1, "Test 7: Added a nic with s slot specified to be an occupied slot") vm1.Destroy()
def TestInitialFilePolicy(vm1, datastore=None): # Basic dummy VM should at least have permission for its home directory domainName = 'hostd' + str(vm1._GetMoId()) vm.PowerOn(vm1) vmxPath = vm1.GetSummary().GetConfig().GetVmPathName() vmdir = os.path.dirname(ResolveDsPath(vm1, vmxPath)) found = CheckInPolicy(domainName, [(vmdir, 3)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find VM home directory policy after power-on') vm.PowerOff(vm1) if FindDomain(domainName): raise Exception('Domain %s has not been cleaned up' % domainName) Log('Test setting nvram_default in global config') globalConf = '/etc/vmware/config' nvramPath = '/vmfs/volumes/testVol1/non_existent_nvram' shutil.copy2(globalConf, globalConf + '.backup') with open(globalConf, 'a') as f: f.write('nvram_default = "' + nvramPath + '"' + '\n') vm.PowerOn(vm1) shutil.move(globalConf + '.backup', globalConf) found = CheckInPolicy(domainName, [(nvramPath, 1)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find permission for nvram_default path') vm.PowerOff(vm1) toolsIso = '/vmimages/tools-isoimages/linux.iso' if os.path.isfile(toolsIso): Log('Test CDROM image config option') cdromDev, ctlr = AddCdromISO(vm1, toolsIso) vm.PowerOn(vm1) toolsIsoRP = os.path.realpath(toolsIso) found = CheckInPolicy(domainName, [(toolsIsoRP, 1)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find cdrom image permission') vm.PowerOff(vm1) # Remove cdrom device cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, cdromDev) vmconfig.RemoveDeviceFromSpec(cspec, ctlr) vm.Reconfigure(vm1, cspec) Log('Test symlink serial backing file') pathBase = os.path.dirname(vmxPath) serialDev, fullPath, symlink = AddEditSerialSymlinkFile(vm1, pathBase) vm.PowerOn(vm1) found = CheckInPolicy(domainName, [(fullPath, 3)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find serial log permission') vm.PowerOff(vm1) # Remove serial device cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, serialDev) vm.Reconfigure(vm1, cspec) os.unlink(symlink) Log('Test log file path with environment variables') logDir = pathBase + '-root' CreateDirectory(logDir) logDirPath = ResolveDsPath(vm1, logDir) logFullPath = re.sub(r'-root', '-$USER', logDirPath) + 'vmx-$PID.log' vmxLogOpt = Vim.Option.OptionValue(key='vmx.fileTrack.logFile', value=logFullPath) cspec = Vim.Vm.ConfigSpec(extraConfig=[vmxLogOpt]) vm.Reconfigure(vm1, cspec) vm.PowerOn(vm1) found = CheckInPolicy(domainName, [(logDirPath, 3)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find log file permission') vm.PowerOff(vm1) vmxLogOpt = Vim.Option.OptionValue(key='vmx.fileTrack.logFile', value='') cspec = Vim.Vm.ConfigSpec(extraConfig=[vmxLogOpt]) vm.Reconfigure(vm1, cspec) fileManager = GetSi().RetrieveContent().GetFileManager() vimutil.InvokeAndTrack(fileManager.Delete, datastorePath=logDir, fileType=Vim.FileManager.FileType.File) Log('Test setting workingDir') workingDir = pathBase + '-workingDir' workingDirFullPath = ResolveDsPath(vm1, workingDir) workingDirSymPath = ResolveDsPath(vm1, workingDir, True) CreateDirectory(workingDir) vmxFullPath = ResolveDsPath(vm1, vmxPath) shutil.copy2(vmxFullPath, vmxFullPath + '.backup') vmxOut = codecs.open(vmxFullPath, mode='w+', encoding='utf_8') with codecs.open(vmxFullPath + '.backup', encoding='utf_8') as vmxIn: for line in vmxIn: if 'migrate.hostlog' not in line: vmxOut.write(line) vmxOut.write('workingDir = "%s"\n' % workingDirSymPath) vmxOut.close() vm.PowerOn(vm1) found = CheckInPolicy(domainName, [(workingDirFullPath, 3)]) filesFound = os.listdir(workingDirFullPath) if len(filesFound) == 0: raise Exception('No files found in working directory %s' % workingDirFullPath) vm.PowerOff(vm1) # Power cycle to verify VM is still in a valid state vm.PowerOn(vm1) vm.PowerOff(vm1) shutil.move(vmxFullPath + '.backup', vmxFullPath) fileManager = GetSi().RetrieveContent().GetFileManager() vimutil.InvokeAndTrack(fileManager.Delete, datastorePath=workingDir, fileType=Vim.FileManager.FileType.File) vm.PowerOn(vm1) vm.PowerOff(vm1) # Create suspend directory, additional disk directory Log('Test setting suspend directory and adding a new disk') suspendDir = AddSuspendDirectory(vm1, pathBase) diskDev, diskDir = AddDiskExternalDir(vm1, pathBase, datastore) Log('Set suspend directory to %s and added disk in %s' % (suspendDir, diskDir)) vm.PowerOn(vm1) suspendFullPath = ResolveDsPath(vm1, suspendDir) diskFullPath = ResolveDsPath(vm1, diskDir) found = CheckInPolicy(domainName, [(suspendFullPath, 3), (diskFullPath, 3)]) if len(found) != 2: raise Exception('Did not find all expected permissions. Found: %s' % ', '.join(found)) Log('Suspending VM') vm.Suspend(vm1) suspendFiles = os.listdir(suspendFullPath) if len(suspendFiles) == 0: raise Exception('Did not find suspend image in %s' % suspendFullPath) Log('Resume VM, power off and clean up') vm.PowerOn(vm1) vm.PowerOff(vm1) # Reset suspend directory, remove added disk and clean up directories cspec = Vim.Vm.ConfigSpec() files = Vim.Vm.FileInfo() files.SetSuspendDirectory('ds://') cspec.SetFiles(files) fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy vmconfig.RemoveDeviceFromSpec(cspec, diskDev, fileOp) vm.Reconfigure(vm1, cspec) for directory in (suspendDir, diskDir): try: vimutil.InvokeAndTrack(fileManager.Delete, datastorePath=directory, fileType=Vim.FileManager.FileType.File) except Vim.fault.FileNotFound: pass
def TestOnlineReconfigure(vm1, datastore=None): domainName = 'hostd' + str(vm1._GetMoId()) vmxPath = vm1.GetSummary().GetConfig().GetVmPathName() toolsIso = '/vmimages/tools-isoimages/linux.iso' if os.path.isfile(toolsIso): Log('Test hot-adding a CDROM backed by an ISO') toolsIsoRP = os.path.realpath(toolsIso) assert (not CheckInPolicy(domainName, [(toolsIsoRP, 1)])) vm.PowerOn(vm1) cdromDev, ctlr = AddCdromISO(vm1, toolsIso) found = CheckInPolicy(domainName, [(toolsIsoRP, 1)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find cdrom image permission') # Remove cdrom device cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, cdromDev) vm.Reconfigure(vm1, cspec) found = CheckInPolicy(domainName, [(toolsIsoRP, 1)], True) if len(found) > 0: DumpFilePolicy(domainName) raise Exception('Found unexpected cdrom image permission') vm.PowerOff(vm1) cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, ctlr) vm.Reconfigure(vm1, cspec) Log('Test hot-adding a serial device backed by a symlink') pathBase = os.path.dirname(vmxPath) serialDev = AddSerialPipeBacked(vm1) vm.PowerOn(vm1) origPolicy = RetrieveFilePolicy(domainName) serialDev, serialPath, symlink = AddEditSerialSymlinkFile( vm1, pathBase, serialDev) assert (serialPath not in origPolicy) found = CheckInPolicy(domainName, [(serialPath, 3)]) if len(found) != 1: DumpFilePolicy(domainName) raise Exception('Did not find serial log permission') # Change backing of serial device cspec = Vim.Vm.ConfigSpec() backing = Vim.Vm.Device.VirtualSerialPort.FileBackingInfo() backing.SetFileName(pathBase + "/newSerial.log") serialDev.SetBacking(backing) vmconfig.AddDeviceToSpec(cspec, serialDev, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit) vm.Reconfigure(vm1, cspec) found = CheckInPolicy(domainName, [(serialPath, 3)], True) if len(found) > 0: DumpFilePolicy(domainName) raise Exception('Found unexpected serial log permission') vm.PowerOff(vm1) # Remove serial device cspec = Vim.Vm.ConfigSpec() vmconfig.RemoveDeviceFromSpec(cspec, serialDev) vm.Reconfigure(vm1, cspec) os.unlink(symlink) try: os.unlink(serialPath) except OSError as e: if e.errno == errno.ENOENT: pass Log('Test hot adding a new disk in a different directory') vm.PowerOn(vm1) origPolicy = RetrieveFilePolicy(domainName) diskDev, diskDir = AddDiskExternalDir(vm1, pathBase, datastore) diskFullPath = ResolveDsPath(vm1, diskDir) assert (diskFullPath not in origPolicy) found = CheckInPolicy(domainName, [(diskFullPath, 3)]) if len(found) != 1: raise Exception('Did not find all expected permissions. Found: %s' % ', '.join(found)) # Remove added disk and clean up directory cspec = Vim.Vm.ConfigSpec() fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy vmconfig.RemoveDeviceFromSpec(cspec, diskDev, fileOp) vm.Reconfigure(vm1, cspec) found = CheckInPolicy(domainName, [(diskFullPath, 3)]) if len(found) > 0: DumpFilePolicy(domainName) raise Exception('Found unexpected disk path permission', True) vm.PowerOff(vm1) fileManager = GetSi().RetrieveContent().GetFileManager() try: vimutil.InvokeAndTrack(fileManager.Delete, datastorePath=diskDir, fileType=Vim.FileManager.FileType.File) except Vim.fault.FileNotFound: pass
def main(): supportedArgs = [(["h:", "host="], "localhost", "Host name", "host"), (["u:", "user="******"root", "User name", "user"), (["p:", "pwd="], "ca$hc0w", "Password", "pwd"), (["v:", "vmname="], "HotPlugTest", "Name of the virtual machine", "vmname"), (["i:", "numiter="], "1", "Number of iterations", "iter")] supportedToggles = [ (["usage", "help"], False, "Show usage information", "usage"), (["runall", "r"], True, "Run all the tests", "runall"), (["nodelete"], False, "Dont delete vm on completion", "nodelete") ] args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles) if args.GetKeyValue("usage") == True: args.Usage() sys.exit(0) # Connect si = SmartConnect(host=args.GetKeyValue("host"), user=args.GetKeyValue("user"), pwd=args.GetKeyValue("pwd")) atexit.register(Disconnect, si) # Process command line vmname = args.GetKeyValue("vmname") numiter = int(args.GetKeyValue("iter")) runall = args.GetKeyValue("runall") noDelete = args.GetKeyValue("nodelete") status = "PASS" # Find a USB device on the host to passthrough envBrowser = invt.GetEnv() cfgTarget = envBrowser.QueryConfigTarget(None) if len(cfgTarget.usb) < 1: Log("No USB devices available for passthrough on " + args.GetKeyValue("host")) return device = cfgTarget.usb[0] for i in range(numiter): bigClock = StopWatch() vm1 = None try: vmname7 = vmname + "_HwV7" vmname8 = vmname + "_HwV8" Log("Cleaning up VMs from previous runs...") vm.Delete(vmname7, True) vm.Delete(vmname8, True) ## Positive tests on a hwVersion 7 VM Log("Creating Hw7 VM..") vm1 = vm.CreateQuickDummy(vmname7, vmxVersion="vmx-07", memory=4, guest="rhel5Guest") Log("Add a new USB controller to the VM") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddUSBCtlr(cspec) vm.Reconfigure(vm1, cspec) DoPlugTests(vm1, device, Vim.Vm.Device.VirtualUSBController, True) vm.Delete(vm1.name, True) ## Positive tests on a hwVersion 8 VM Log("Creating Hw8 VM..") vm1 = vm.CreateQuickDummy(vmname8, vmxVersion="vmx-08", memory=4, guest="rhel5Guest") Log("Add a new xHCI USB controller to the VM") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddUSBXHCICtlr(cspec) vm.Reconfigure(vm1, cspec) xhciCtlr = CheckDevice(vm1, Vim.Vm.Device.VirtualUSBXHCIController, "xHCI controller") DoPlugTests(vm1, device, Vim.Vm.Device.VirtualUSBXHCIController, True) Log("Add a new USB controller to the VM") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.AddUSBCtlr(cspec) vm.Reconfigure(vm1, cspec) usbCtlr = CheckDevice(vm1, Vim.Vm.Device.VirtualUSBController, "USB controller") DoPlugTests(vm1, device, Vim.Vm.Device.VirtualUSBController, True) Log("Remove xHCI USB controller from the VM") cspec = vmconfig.RemoveDeviceFromSpec(Vim.Vm.ConfigSpec(), xhciCtlr) vm.Reconfigure(vm1, cspec) CheckNoDevice(vm1, Vim.Vm.Device.VirtualUSBXHCIController, "xHCI controller") Log("Remove USB controller from the VM") cspec = vmconfig.RemoveDeviceFromSpec(Vim.Vm.ConfigSpec(), usbCtlr) vm.Reconfigure(vm1, cspec) CheckNoDevice(vm1, Vim.Vm.Device.VirtualUSBController, "USB controller") vm.Delete(vm1.name, True) Log("Tests completed.") bigClock.finish("iteration " + str(i)) except Exception as e: status = "FAIL" Log("Caught exception : " + str(e)) Log("TEST RUN COMPLETE: " + status)
def TestLinkedClone(vm1, datastore=None): if datastore is None: vm1Path = vm1.GetSummary().GetConfig().GetVmPathName() m = re.search(r'\[(.+)\]', vm1Path) datastore = m.group(1) baseName = vm1.GetConfig().GetName() parentName = 'LinkedParent_' + baseName vmP = folder.Find(parentName) if vmP != None: Log('Destroying old parent VM %s' % parentName) vmP.Destroy() # Create parent VM vmP = vm.CreateQuickDummy(parentName, numScsiDisks=2, datastoreName=datastore, diskSizeInMB=1) # Create snapshots # S1 -> S1C1 -> S1C1C1 # `-> S1C2 S1Snapshot = TakeSnapshot(vmP, 'S1', 'S1 is the first snaphost') Log('Create Snapshot S1 for parent VM') S1C1Snapshot = TakeSnapshot(vmP, 'S1-C1', 'S1-C1 is the first child of S1') Log('Create Snapshot S1C1 for parent VM') S1C1C1Snapshot = TakeSnapshot(vmP, 'S1-C1-C1', 'S1-C1-C1 is the grand child of S1') Log('Create Snapshot S1C1C1 for parent VM') # Revert to S1 vimutil.InvokeAndTrack(S1Snapshot.Revert) Log('Reverted parent VM to Snapshot S1') S1C2Snapshot = TakeSnapshot(vmP, 'S1-C2', 'S1-C2 is the second child of S1') Log('Create Snapshot S1C2 for parent VM') # Revert to S1C1C1, so it is the current snapshot vimutil.InvokeAndTrack(S1C1C1Snapshot.Revert) Log('Reverted parent VM to Snapshot S1C1C1') # Get the name of the parent disks disks = vmconfig.CheckDevice(S1C2Snapshot.GetConfig(), Vim.Vm.Device.VirtualDisk) if len(disks) != 2: raise Exception('Failed to find parent disk1') parentDisk1 = disks[0].GetBacking().GetFileName() disks = vmconfig.CheckDevice(S1C1C1Snapshot.GetConfig(), Vim.Vm.Device.VirtualDisk) if len(disks) != 2: raise Exception('Failed to find parent disk2') parentDisk2 = disks[1].GetBacking().GetFileName() # Create a VMC1 whose first disk is linked off S1C2 child1Name = 'LinkedChild1_' + baseName vmC1 = folder.Find(child1Name) if vmC1 != None: Log('Destroying old child VM %s' % child1Name) vmC1.Destroy() configSpec = vmconfig.CreateDefaultSpec(name=child1Name, datastoreName=datastore) configSpec = vmconfig.AddScsiCtlr(configSpec) configSpec = vmconfig.AddScsiDisk(configSpec, datastorename=datastore, capacity=1024) SetDeltaDiskBacking(configSpec, 1, parentDisk1) resPool = invt.GetResourcePool() vmFolder = invt.GetVmFolder() vimutil.InvokeAndTrack(vmFolder.CreateVm, configSpec, resPool) vmC1 = folder.Find(child1Name) vmC1DirName = vmC1.config.files.snapshotDirectory Log('Created child VM %s' % child1Name) # Create a VMC2 that is linked off S1C1C1 child2Name = 'LinkedChild2_' + baseName vmC2 = folder.Find(child2Name) if vmC2 != None: Log('Destroying old child VM %s' % child2Name) vmC2.Destroy() configSpec.SetName(child2Name) SetDeltaDiskBacking(configSpec, 1, parentDisk2) vimutil.InvokeAndTrack(vmFolder.CreateVm, configSpec, resPool) vmC2 = folder.Find(child2Name) vmC2DirName = vmC2.config.files.snapshotDirectory Log('Created child VM %s' % child2Name) # Create snapshot VMC2S1 for VMC2 TakeSnapshot(vmC2, 'VMC2S1', 'VMC2S1 is VMC2 snaphost') Log('Create Snapshot VMC2S1 for VMC2') # Create snapshot VMC2S2 for VMC2 VMC2S2Snapshot = TakeSnapshot(vmC2, 'VMC2S2', 'VMC2S2 is VMC2 snaphost') Log('Create Snapshot VMC2S2 for VMC2') # Get the disk name of VMC2S2 to use it a parent disk for VMC1 disks = vmconfig.CheckDevice(VMC2S2Snapshot.GetConfig(), Vim.Vm.Device.VirtualDisk) if len(disks) != 1: raise Exception('Failed to find parent disk2') parentDisk3 = disks[0].GetBacking().GetFileName() # Create a delta disk off VMC2S2 on VMC1 Log('Adding delta disk off VMC2S2 to VMC1') configSpec = Vim.Vm.ConfigSpec() configSpec = vmconfig.AddScsiDisk(configSpec, datastorename=datastore, cfgInfo=vmC1.GetConfig()) SetDeltaDiskBacking(configSpec, 0, parentDisk3) vm.Reconfigure(vmC1, configSpec) # Final picture # vmP: S1 -> S1C1 -> S1C1C1 (disk1, disk2) # `-> S1C2 | # vmC2: | `-> vmC2S1 -> vmC2S2 (disk1, disk2) # vmC1: `- (disk1) `- (disk2) Log('Verify parent VM domain policy') domainP = 'hostd' + str(vmP._GetMoId()) vmPdir = GetVMHomeDir(vmP) vm.PowerOn(vmP) found = CheckInPolicy(domainP, [(vmPdir, 3)]) if len(found) != 1: DumpFilePolicy(domainP) raise Exception('Did not find parent VM home directory in policy') vm.PowerOff(vmP) Log('Verify linked child 2 has permission to the parent VM') domainC2 = 'hostd' + str(vmC2._GetMoId()) vmC2dir = GetVMHomeDir(vmC2) vm.PowerOn(vmC2) found = CheckInPolicy(domainC2, [(vmC2dir, 3), (vmPdir, 1)]) if len(found) != 2: raise Exception('Did not find all expected permission in child 2. ' + 'Found: %s' % ', '.join(found)) vm.PowerOff(vmC2) Log('Verify linked child 1 has permission to the parent VM and child 2') domainC1 = 'hostd' + str(vmC1._GetMoId()) vmC1dir = GetVMHomeDir(vmC1) vm.PowerOn(vmC1) found = CheckInPolicy(domainC1, [(vmC1dir, 3), (vmPdir, 1), (vmC2dir, 1)]) if len(found) != 3: raise Exception('Did not find all expected permission in child 1. ' + 'Found: %s' % ', '.join(found)) vm.PowerOff(vmC1) Log('Delete S1C2. Linked child 1 should not be affected.') vimutil.InvokeAndTrack(S1C2Snapshot.Remove, True) vm.PowerOn(vmC1) found = CheckInPolicy(domainC1, [(vmC1dir, 3), (vmPdir, 1), (vmC2dir, 1)]) if len(found) != 3: raise Exception('Did not find all expected permission in child 1. ' + 'Found: %s' % ', '.join(found)) vm.PowerOff(vmC1) Log('Remove disk1 from linked child 1. Verify policy does not change.') disks = vmconfig.CheckDevice(vmC1.GetConfig(), Vim.Vm.Device.VirtualDisk) disk1 = None for disk in disks: if disk.backing.parent.fileName == parentDisk1: disk1 = disk if disk1 is None: raise Exception('Did not find disk based on %s' % parentDisk1) configSpec = Vim.Vm.ConfigSpec() fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy vmconfig.RemoveDeviceFromSpec(configSpec, disk1, fileOp) vm.Reconfigure(vmC1, configSpec) vm.PowerOn(vmC1) found = CheckInPolicy(domainC1, [(vmC1dir, 3), (vmPdir, 1), (vmC2dir, 1)]) if len(found) != 3: raise Exception('Did not find all expected permission in child 1. ' + 'Found: %s' % ', '.join(found)) vm.PowerOff(vmC1) Log('Destroy linked child 2. Verify policy of linked child 1.') vm.Destroy(vmC2) vm.PowerOn(vmC1) found = CheckInPolicy(domainC1, [(vmC1dir, 3), (vmPdir, 1), (vmC2dir, 1)]) if len(found) != 3: raise Exception('Did not find all expected permission in child 1. ' + 'Found: %s' % ', '.join(found)) vm.PowerOff(vmC1) Log('Re-create linked child 2 by hot-adding disks based off S1C1C1.') configSpec = vmconfig.CreateDefaultSpec(name=child2Name, datastoreName=datastore) configSpec = vmconfig.AddScsiCtlr(configSpec) configSpec = vmconfig.AddScsiDisk(configSpec, datastorename=datastore, capacity=1024) vimutil.InvokeAndTrack(vmFolder.CreateVm, configSpec, resPool) vmC2 = folder.Find(child2Name) domainC2 = 'hostd' + str(vmC2._GetMoId()) vmC2dir = GetVMHomeDir(vmC2) vm.PowerOn(vmC2) found = CheckInPolicy(domainC2, [(vmC2dir, 3)]) if len(found) != 1: DumpFilePolicy(domainC2) raise Exception( 'Did not find expected permission in recreated child 2.') configSpec = Vim.Vm.ConfigSpec() configSpec = vmconfig.AddScsiDisk(configSpec, datastorename=datastore, capacity=1024, cfgInfo=vmC2.GetConfig()) SetDeltaDiskBacking(configSpec, 0, parentDisk2) vimutil.InvokeAndTrack(vmC2.Reconfigure, configSpec) found = CheckInPolicy(domainC2, [(vmC2dir, 3), (vmPdir, 1)]) if len(found) != 2: raise Exception('Did not find all expected permission in recreated ' + 'child 2. Found: %s' % ', '.join(found)) Log('Hot-remove newly added delta disk') disks = vmconfig.CheckDevice(vmC2.GetConfig(), Vim.Vm.Device.VirtualDisk) deltaDisk = None for disk in disks: if disk.backing.parent and disk.backing.parent.fileName == parentDisk2: deltaDisk = disk break assert (deltaDisk is not None) configSpec = Vim.Vm.ConfigSpec() fileOp = Vim.Vm.Device.VirtualDeviceSpec.FileOperation.destroy vmconfig.RemoveDeviceFromSpec(configSpec, deltaDisk, fileOp) vimutil.InvokeAndTrack(vmC2.Reconfigure, configSpec) found = CheckInPolicy(domainC2, [(vmPdir, 1)], True) if len(found) > 0: DumpFilePolicy(domainC2) raise Exception('Found unexpected parent disk dir permission') vm.PowerOff(vmC2) # Clean up VMs vm.Destroy(vmC1) vm.Destroy(vmC2) vm.Destroy(vmP) shutil.rmtree(vmC2dir, ignore_errors=True) shutil.rmtree(vmC1dir, ignore_errors=True) shutil.rmtree(vmPdir, ignore_errors=True)
def testLinkedClone(si, numiter, deltaDiskFormat, backingType, vmxVersion, ds1, ds2, status, resultsArray): for i in range(numiter): bigClock = StopWatch() try: try: vm1Name = "LinkedParent_" + str(i) vm1 = folder.Find(vm1Name) if vm1 != None: Log("Cleaning up old vm with name: " + vm1Name) vm1.Destroy() # Create a simple vm with nothing but two disk on ds1 vm1 = vm.CreateQuickDummy(vm1Name, numScsiDisks=2, \ datastoreName=ds1, diskSizeInMB=1, \ vmxVersion=vmxVersion, \ backingType=backingType) Log("Created parent VM1 --" + vm1Name + "with Native snapshotting" + " capability set to " + str(vm1.IsNativeSnapshotCapable())) vm1DirName = vm1.config.files.snapshotDirectory # Create snapshots # S1, S1C1, S1C1C1 and S1C2 vm.CreateSnapshot(vm1, "S1", "S1 is the first snaphost", \ False, False) snapshotInfo = vm1.GetSnapshot() S1Snapshot = snapshotInfo.GetCurrentSnapshot() Log("Create Snapshot S1 for VM1") vm.CreateSnapshot(vm1, "S1-C1", "S1-C1 is the first child of S1",\ False, False) snapshotInfo = vm1.GetSnapshot() S1C1Snapshot = snapshotInfo.GetCurrentSnapshot() Log("Create Snapshot S1C1 for VM1") vm.CreateSnapshot(vm1, "S1-C1-C1", \ "S1-C1-C1 is the grand child of S1", \ False, False) snapshotInfo = vm1.GetSnapshot() S1C1C1Snapshot = snapshotInfo.GetCurrentSnapshot() Log("Create Snapshot S1C1C1 for VM1") # revert to S1 vimutil.InvokeAndTrack(S1Snapshot.Revert) Log("Reverted VM1 to Snapshot S1C1") vm.CreateSnapshot(vm1, "S1-C2", \ "S1-C2 is the second child of S1", False, False) snapshotInfo = vm1.GetSnapshot() S1C2Snapshot = snapshotInfo.GetCurrentSnapshot() Log("Create Snapshot S1C2 for VM1") # revert to S1C1C1, so it is the current snapshot vimutil.InvokeAndTrack(S1C1C1Snapshot.Revert) Log("Reverted VM1 to Snapshot S1C1C1") # Get the name of the parent disks disks = vmconfig.CheckDevice(S1C2Snapshot.GetConfig(), \ Vim.Vm.Device.VirtualDisk) if len(disks) != 2: raise Exception("Failed to find parent disk1") parentDisk1 = disks[0].GetBacking().GetFileName() disks = vmconfig.CheckDevice(S1C1C1Snapshot.GetConfig(), Vim.Vm.Device.VirtualDisk) if len(disks) != 2: raise Exception("Failed to find parent disk2") parentDisk2 = disks[1].GetBacking().GetFileName() # Create a VM2 on ds2 that is linked off S1C2 vm2Name = "LinkedChild1_" + str(i) configSpec = vmconfig.CreateDefaultSpec(name = vm2Name, datastoreName = ds2) configSpec = vmconfig.AddScsiCtlr(configSpec) configSpec = vmconfig.AddScsiDisk(configSpec, datastorename = ds2, capacity = 1024, backingType = backingType) configSpec.SetVersion(vmxVersion) childDiskBacking = configSpec.GetDeviceChange()[1].GetDevice().GetBacking() parentBacking = GetBackingInfo(backingType) parentBacking.SetFileName(parentDisk1) childDiskBacking.SetParent(parentBacking) childDiskBacking.SetDeltaDiskFormat(deltaDiskFormat) resPool = invt.GetResourcePool() vmFolder = invt.GetVmFolder() vimutil.InvokeAndTrack(vmFolder.CreateVm, configSpec, resPool) vm2 = folder.Find(vm2Name) Log("Created child VM2 --" + vm2Name) vm2DirName = vm2.config.files.snapshotDirectory # Create a VM3 on ds2 that is linked off S1C1C1 vm3Name = "LinkedChild2_" + str(i) configSpec.SetName(vm3Name) parentBacking.SetFileName(parentDisk2) vimutil.InvokeAndTrack(vmFolder.CreateVm, configSpec, resPool) vm3 = folder.Find(vm3Name) Log("Created child VM3 --" + vm3Name) vm3DirName = vm3.config.files.snapshotDirectory # Create snapshot VM3S1 for VM3 vm.CreateSnapshot(vm3, "VM3S1", "VM3S1 is VM3 snaphost", False, False) Log("Create Snapshot VM3S1 for VM3") # Create snapshot VM3S2 for VM3 vm.CreateSnapshot(vm3, "VM3S2", "VM3S2 is VM3 snaphost", False, False) Log("Create Snapshot VM3S2 for VM3") snapshotInfo = vm3.GetSnapshot() VM3S2Snapshot = snapshotInfo.GetCurrentSnapshot() # get the disk name of VM3S2 so it can be configured as a # parent disk for VM2 disks = vmconfig.CheckDevice(VM3S2Snapshot.GetConfig(), Vim.Vm.Device.VirtualDisk) if len(disks) != 1: raise Exception("Failed to find parent disk2") parentDisk3 = disks[0].GetBacking().GetFileName() # create a delta disk off VM3S2 on VM2 Log("Adding delta disk off VM3S2 to VM2") configSpec = Vim.Vm.ConfigSpec() configSpec = vmconfig.AddScsiDisk(configSpec, \ datastorename = ds2, \ cfgInfo = vm2.GetConfig(), \ backingType = backingType) childDiskBacking = configSpec.GetDeviceChange()[0].GetDevice().GetBacking() parentBacking = GetBackingInfo(backingType) parentBacking.SetFileName(parentDisk3) childDiskBacking.SetParent(parentBacking) childDiskBacking.SetDeltaDiskFormat(deltaDiskFormat) vimutil.InvokeAndTrack(vm2.Reconfigure, configSpec) Log("Power cycle VM1...") PowerCycle(vm1) Log("Power cycle VM2...") PowerCycle(vm2) Log("Power cycle VM3...") PowerCycle(vm3) Log("OP1: delete VM1.S1C2, then power cycle VM2") vimutil.InvokeAndTrack(S1C2Snapshot.Remove, True) PowerCycle(vm2) Log("OP2: destroy VM2, power cycle VM1") vimutil.InvokeAndTrack(vm2.Destroy) PowerCycle(vm1) Log("then recreate VM2 with just disk1") configSpec = vmconfig.CreateDefaultSpec(name = vm2Name, \ datastoreName = ds2) configSpec = vmconfig.AddScsiCtlr(configSpec) configSpec = vmconfig.AddScsiDisk(configSpec, datastorename = ds2, \ capacity = 1024, \ backingType = backingType) configSpec.SetVersion(vmxVersion) childDiskBacking = configSpec.GetDeviceChange()[1].GetDevice().GetBacking() parentBacking = GetBackingInfo(backingType) parentBacking.SetFileName(parentDisk1) childDiskBacking.SetParent(parentBacking) childDiskBacking.SetDeltaDiskFormat(deltaDiskFormat) resPool = invt.GetResourcePool() vmFolder = invt.GetVmFolder() vimutil.InvokeAndTrack(vmFolder.CreateVm, configSpec, resPool) vm2 = folder.Find(vm2Name) Log("ReCreated child VM2 --" + vm2Name) Log("OP3: delete VM3S2, power cycle VM1, revert to S1C1") vimutil.InvokeAndTrack(VM3S2Snapshot.Remove, True) vimutil.InvokeAndTrack(S1C1Snapshot.Revert) PowerCycle(vm1) llpm = si.RetrieveInternalContent().GetLlProvisioningManager() Log("OP4: refresh VM2 disk and destroy the disk and its parent") llpm.ReloadDisks(vm2, ['currentConfig', 'snapshotConfig']) disks = vmconfig.CheckDevice(vm2.GetConfig(), \ Vim.Vm.Device.VirtualDisk) diskChain1 = disks[0] diskChain1.backing.parent.parent = None configSpec = Vim.Vm.ConfigSpec() configSpec = vmconfig.RemoveDeviceFromSpec(configSpec, \ diskChain1, "destroy") configSpec.files = vm2.config.files llpm.ReconfigVM(configSpec) Log("verify only the immediate parent is deleted") PowerCycle(vm1) Log("OP5: destroy VM1, power cycle VM3") vimutil.InvokeAndTrack(vm1.Destroy) PowerCycle(vm3) Log("OP6: Consolidate VM3 disk chain") disks = vmconfig.CheckDevice(vm3.GetConfig(), \ Vim.Vm.Device.VirtualDisk) shouldHaveFailed = 0 try: task = llpm.ConsolidateDisks(vm3, disks) WaitForTask(task) except Exception as e: shouldHaveFailed = 1 Log("Hit an exception when trying to consolidate cross " \ "snapshot point.") if shouldHaveFailed != 1: raise Exception("Error: allowed consolidation to merge snapshot") diskchain1 = disks[0] diskchain1.backing.parent.parent = None disks = vmconfig.CheckDevice(vm3.GetConfig(), \ Vim.Vm.Device.VirtualDisk) diskchain2 = disks[0] diskchain2.backing = diskchain2.backing.parent.parent disks = [] disks.append(diskchain1) disks.append(diskchain2) vimutil.InvokeAndTrack(llpm.ConsolidateDisks, vm3, disks) PowerCycle(vm3) Log("OP7: destroy VM2, no orphaned disks/files should have left") vimutil.InvokeAndTrack(vm2.Destroy) Log("Delete snapshot of VM3, and delete the disk with all parent." "then destroy vM3, no orphaned disks/files should have left") disks = vmconfig.CheckDevice(vm3.GetConfig(), \ Vim.Vm.Device.VirtualDisk) diskChain1 = disks[0] configSpec = Vim.Vm.ConfigSpec() configSpec = vmconfig.RemoveDeviceFromSpec(configSpec, \ diskChain1, "destroy") configSpec.files = vm3.config.files vimutil.InvokeAndTrack(llpm.ReconfigVM, configSpec) vimutil.InvokeAndTrack(vm3.Destroy) hostSystem = host.GetHostSystem(si) b = hostSystem.GetDatastoreBrowser() shouldHaveFailed = 0 try: vimutil.InvokeAndTrack(b.Search, vm1DirName) except Vim.Fault.FileNotFound: Log("Caught " + vm1DirName + "Not found as expected") shouldHaveFailed += 1 try: vimutil.InvokeAndTrack(b.Search, vm2DirName) except Vim.Fault.FileNotFound: Log("Caught " + vm2DirName + "Not found as expected") shouldHaveFailed += 1 try: vimutil.InvokeAndTrack(b.Search, vm3DirName) except Vim.Fault.FileNotFound: Log("Caught " + vm3DirName + "Not found as expected") shouldHaveFailed += 1 if shouldHaveFailed != 3: Log("Failed, orphaned disks left") raise Exception("orphaned disks") status = "PASS" finally: bigClock.finish("iteration " + str(i)) except Exception as e: Log("Caught exception : " + str(e)) status = "FAIL" Log("TEST RUN COMPLETE: " + status) resultsArray.append(status) Log("Results for each iteration: ") for i in range(len(resultsArray)): Log("Iteration " + str(i) + ": " + resultsArray[i])
def TestPCIPassthroughDevice(vm1, positive): failed = False # Test adding PCI passthrough device to VM Log("Adding PCI passthrough device to VM") cspec = Vim.Vm.ConfigSpec() curMem = vm1.GetConfig().GetHardware().GetMemoryMB() memAlloc = Vim.ResourceAllocationInfo() memAlloc.SetReservation(long(curMem)) memAlloc.SetLimit(long(curMem)) cspec = vmconfig.AddPCIPassthrough(cspec) try: task = vm.Reconfigure(vm1, cspec) except Vim.Fault.DeviceUnsupportedForVmVersion as e: if not positive: Log("Caught version exception adding PCI Passthrough device as expected" ) return raise if not positive: raise Exception("Did not hit exception adding PCI Passthrough device") Log("Checking for presencec of PCI Passthrough device in VM") devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualPCIPassthrough) if len(devices) != 1: raise Exception("VM has " + str(len(devices)) + \ "PCI passthrough devices. Expected 1.") # Power on VM Log("Powering on the VM") vm.PowerOn(vm1) # Suspend VM with PCI passthru Log("Attempting to suspend the VM") TestNegOpOnVm("suspending VM", vm.Suspend, vm1) # Hot-add a device to VM with PCI passthru Log("Attempting to hot add a NIC to the VM") cspec = Vim.Vm.ConfigSpec() vmconfig.AddNic(cspec) TestNegOpOnVm("hot-adding a nic to the VM", vm.Reconfigure, vm1, cspec) # Change memory reservataion of VM with PCI passthru Log("Attempting to change memory reservation of the VM") curMem = vm1.GetConfig().GetHardware().GetMemoryMB() cspec = Vim.Vm.ConfigSpec() memAlloc = Vim.ResourceAllocationInfo() memAlloc.SetReservation(long(curMem - 1)) cspec.SetMemoryAllocation(memAlloc) TestNegOpOnVm("changing mem reservataion of VM", vm.Reconfigure, vm1, cspec) Log("Powering off VM") vm.PowerOff(vm1) # Remove PCI passthru device. Log("Removing PCI Passthrough device from VM") cspec = Vim.Vm.ConfigSpec() cspec = vmconfig.RemoveDeviceFromSpec(cspec, devices[0]) vm.Reconfigure(vm1, cspec) Log("Checking that device was removed") devices = vmconfig.CheckDevice(vm1.GetConfig(), Vim.Vm.Device.VirtualPCIPassthrough) if len(devices) != 0: raise Exception("PCI passthrough device not removed from VM!") Log("Done with PCI passthrough tests")