def CreateMainVm(host, hostSystem, datastore, dc, vmName, vmVersion='vmx-09'): spec = CreateVmSpec(vmName, datastore.GetName(), 'flat', TWOGB_IN_MB, vmVersion) vm1 = VmTest(spec, dc, hostSystem, host.GetResourcePool(), remove=False) vm.CreateSnapshot(vm1, "S1", "snap shot 1 of vm1", False, False) print(vm1.GetName() + " created.") return vm1
def TestWithSnapshot(vm1): """ Verify that it is not possible to extend delta disk by changing capacityInBytes. """ 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!") # attempt to extend a disk with a parent Log("Creating a snapshot on the VM for negative disk extend test.") vm.CreateSnapshot(vm1, "dummy snapshot", "dummy desc", False, False) Log("Attempting to extend disk size of delta disk.") disk = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)[0] cspec = Vim.Vm.ConfigSpec() disk.capacityInBytes = disk.capacityInBytes + 1024 vmconfig.AddDeviceToSpec(cspec, disk, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit) task = vm1.Reconfigure(cspec) try: WaitForTask(task) except Exception as e: Log("Hit an exception extending delta disk as expected" + str(e)) else: raise Exception("Error: Extending delta disk was allowed!") Log("Removing all snapshots on the VM.") vm.RemoveAllSnapshots(vm1)
def DeltaTest(dc, dsName, host, backingType, deltaDiskFormat, diskSize, vmx, positive, test): msg = test + "positive =" + str(positive) + '; ' + \ "backing=" + backingType + '; ' + \ "delta=" + str(deltaDiskFormat) + '; ' + \ "vmx version=" + str(vmx) +'; ' + \ 'diskSize=' + str(diskSize) +'; ' + 'result=' vm1 = None snapshotVm = None try: spec = CreateVmSpec(backingType + "Vm", dsName, backingType, diskSize, vmx) vm1 = VmTest(spec, dc, host, remove=False) vm.CreateSnapshot(vm1, "S1", "snap shot of vm1", False, False) snapshot = vm1.GetSnapshot().GetCurrentSnapshot() disks = vmconfig.CheckDevice(snapshot.GetConfig(), \ Vim.Vm.Device.VirtualDisk) if len(disks) != 1: print(snapshot.GetConfig()) raise AssertionError("Did not find correct number of snapshot") parentDisk = disks[0].GetBacking().GetFileName() spec = CreateVmSpec(backingType + "Vm-Clone", dsName, backingType, diskSize, vmx) childDiskBacking = spec.GetDeviceChange()[1].GetDevice().GetBacking() #print(childDiskBacking) if backingType == 'flat': parentBacking = Vim.Vm.Device.VirtualDisk.FlatVer2BackingInfo() if backingType == 'seSparse': parentBacking = Vim.Vm.Device.VirtualDisk.SeSparseBackingInfo() parentBacking.SetFileName(parentDisk) childDiskBacking.SetParent(parentBacking) childDiskBacking.SetDeltaDiskFormat(deltaDiskFormat) #print(spec) snapshotVm = VmTest(spec, dc, host, remove=False) except Vmodl.MethodFault as e: if not positive: print(msg + 'SUCCESS') print(e) else: print(msg + "FAILURE") raise except Exception: print(msg + "FAILURE") raise else: if positive: print(msg + 'SUCCESS') else: print(msg + "FAILURE, negative test through") raise AssertionError(msg + "FAILURE, negative test through") finally: if vm1: vm.Destroy(vm1) if snapshotVm: vm.Destroy(snapshotVm)
def on(self): try: for vmIter in self.vmList: print "Creating snapshot on vm " + vmIter.GetName() vm.CreateSnapshot(vmIter, "testSnapshot", "a" * 3000, False, False) self.success = True print self.getClientId() + " on successful" except: print self.getClientId() + " on failed" self.success = False
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 SetupOtherHost(self): print(self._host + " " + self._user + " " + self._pwd) siOther = SmartConnect(host=self._host, user=self._user, pwd=self._pwd) self._vm = vm.CreateQuickDummy(self._vmName, numScsiDisks=1, datastoreName=self._ds) if self._vm == None: raise "Failed to create VM with specified video ram size" Log("Other Host: Power On VM") vm.PowerOn(self._vm) Log("Other Host: Take Snapshot (no memory)") vm.CreateSnapshot(self._vm, "pre vdm snap", "Pre VDM snapshot", False, False)
def snapshot(self): Logger("\nVM createSnapshot Start, vm = %s\n" % (self.vm.name)) ssName = ("ss-%s" % random.randint(1, 1000)) vm.CreateSnapshot(self.vm, ssName, "snaphost", False, False) time.sleep(5) devices = vmconfig.CheckDevice(self.vm.config, Vim.Vm.Device.VirtualDisk) newPath = "" for dev in devices: if dev.backing.parent and \ dev.backing.parent.fileName == self.vsobj.config.backing.filePath: newPath = dev.backing.fileName break return newPath
def TestReconfigDeltaDisk(vm1): # attempt to extend a disk with a parent Log("Creating a snapshot on the VM for negative disk extend test") vm.CreateSnapshot(vm1, "dummy snapshot", "dummy desc", False, False) Log("Attempting to extend disk size of delta disk") disk = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)[0] cspec = Vim.Vm.ConfigSpec() disk.capacityInKB = disk.capacityInKB + 4096 vmconfig.AddDeviceToSpec(cspec, disk, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit) task = vm1.Reconfigure(cspec) try: WaitForTask(task) except Exception as e: Log("Hit an exception extending delta disk as expected" + str(e)) else: raise Exception("Error: Extending delta disk was allowed!") Log("Removing all snapshots on the VM") vm.RemoveAllSnapshots(vm1)
def TestSnapshotCdrom(vm1): cdrom = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualCdrom)[0] Log("Creating a snapshot on the VM") vm.CreateSnapshot(vm1, "dummy snapshot", "dummy desc", False, False) snap = vm1.snapshot.currentSnapshot if len(Diff(vm1.config.hardware.device, snap.config.hardware.device)): Log("Mismatch between config and snapshot") raise Exception("Snapshot hardware differ VM hardware list!") Log("Revert to current snapshot") vm.RevertToCurrentSnapshot(vm1) propList = {"key": cdrom.key, "controllerKey": cdrom.controllerKey} Log("Check if cdrom is present after reverting to snapshot.") devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualCdrom, propList) if len(devices) != 1: raise Exception("Failed to find cdrom after revert to snapshot.") Log("Removing all snapshots on the VM.") vm.RemoveAllSnapshots(vm1)
def ToggleSnapshot(toggle): """ Create/Remove Snapshots on a given VM """ vm = GetVmByName(_vmName) if vm == None: print "Unable to find VM", _vmName return(1) if toggle == "on": print "== Creating Snapshot" task = vm.CreateSnapshot("testSnapshot", "M3 stress test snapshot", False, False) if WaitForTask(task) == "error": return(1) return(0) else: print "== Deleting Snapshot" snapshot = vm.GetSnapshot() task = snapshot.GetCurrentSnapshot().Remove(True) if WaitForTask(task) == "error": return(1) return(0)
def TestIllegalOptions(vm1): bldType = os.environ.get('VMBLD', '') or os.environ.get('BLDTYPE', '') if bldType != 'obj': Log('Test require obj build') return vm1 vmname = vm1.GetSummary().GetConfig().GetName() cfg = vm1.GetSummary().GetConfig().GetVmPathName() vm.CreateSnapshot(vm1, "backup", "backup", False, False) for v in ['', ' with reload']: Log('Testing illegal config file modification%s' % v) for i in range(3): illegalOpt = Vim.Option.OptionValue( key='vmx.test.sandbox.illegalOption', value=str(i)) nthWriteOpt = Vim.Option.OptionValue( key='vmx.test.sandbox.nthWrite', value='%d' % (2 + i)) cspec = Vim.Vm.ConfigSpec(extraConfig=[nthWriteOpt, illegalOpt]) task = vm.Reconfigure(vm1, cspec) vm.PowerOn(vm1) if v == ' with reload': try: vm1.Reload() except: Log('Illegal options detected before Reload') pass time.sleep(10) if vm1.runtime.powerState != Vim.VirtualMachine.PowerState.poweredOff: raise Exception( 'VM unexpectedly still powered on (option %d)' % i) try: vm.PowerOn(vm1) raise Exception('PowerOn is allowed unexpectedly (option %d)' % i) except: pass vm1.Unregister() folder.Register(cfg) vm1 = folder.Find(vmname) vm.RevertToCurrentSnapshot(vm1) return vm1
def on(self): try: vmName = "vm" + self.getClientId() print "Creating vm" + vmName self.vm = vm.CreateQuickDummy(vmName, 1) if self.vm == None: print "** Error in creating vm" self.success = False print self.getClientId() + " on failed" return print "Adding VM disk" task = self.vm.Reconfigure(self.addConfigSpec) WaitForTask(task) print "Powering On vm" vm.PowerOn(self.vm) print "Creating snapshot" vm.CreateSnapshot(self.vm, "testSnapshot", "Test snap", False, False) self.success = True print self.getClientId() + " on successful" except: print self.getClientId() + " on failed" self.success = False
def TakeSnapshot(vmH, name, desc): vm.CreateSnapshot(vmH, name, desc, False, False) snapshotInfo = vmH.GetSnapshot() return snapshotInfo.GetCurrentSnapshot()
# Get the vm vm = GetVmByName(vmName) if vm == None: print "Unable to find VM", vmName return (1) task = vm.PowerOn(None) WaitForTask(task) print "Test started on ", now() # Get vms for i in xrange(0, numIterations): print "== iteration ", str(i + 1), " time = ", now() print "Creating Snapshot" task = vm.CreateSnapshot("testSnapshot", "M1 stress test snapshot", False, False) WaitForTask(task) snapshot = vm.GetSnapshot() print "Deleting Snapshot ", vmName task = snapshot.GetCurrentSnapshot().Remove(True) WaitForTask(task) print "== iteration completed ", str(i + 1), " time = ", now() print "## Total number of iterations performed ", str(i + 1) task = vm.PowerOff() WaitForTask(task) return (0)
def testPromoteDisks(si, numDisks, numiter, backingType, vmxVersion, ds1, ds2, status, resultsArray): for i in range(numiter): bigClock = StopWatch() try: try: vm1Name = "Parent" + str(i) vm1 = folder.Find(vm1Name) if vm1 != None: Log("Cleaning up old vm with name: " + vm1Name) vm1.Destroy() # Create a simple vm with numDisks on ds1 vm1 = vm.CreateQuickDummy(vm1Name, numScsiDisks=numDisks, \ datastoreName=ds1, diskSizeInMB=1, \ vmxVersion=vmxVersion, \ backingType=backingType) Log("Created parent VM1 --" + vm1Name) vm1DirName = vm1.config.files.snapshotDirectory # Create snapshot vm.CreateSnapshot(vm1, "S1", "S1 is the first snaphost", \ False, False) snapshotInfo = vm1.GetSnapshot() S1Snapshot = snapshotInfo.GetCurrentSnapshot() Log("Created Snapshot S1 for VM1") # Get the name of the parent disks disks = vmconfig.CheckDevice(S1Snapshot.GetConfig(), \ Vim.Vm.Device.VirtualDisk) if len(disks) != numDisks: raise Exception("Failed to find parent disks") parentDisks = [None] * len(disks) for i in range(len(disks)): parentDisks[i] = disks[i].GetBacking().GetFileName() # Create a VM2 on ds2 that is linked off S1 vm2Name = "LinkedClone" + 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(parentDisks[0]) childDiskBacking.SetParent(parentBacking) childDiskBacking.SetDeltaDiskFormat("redoLogFormat") 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 delta disks off VM1 on VM2 Log("Adding delta disks off VM1 to VM2") configSpec = Vim.Vm.ConfigSpec() for i in range(len(parentDisks)): configSpec = vmconfig.AddScsiDisk(configSpec, \ datastorename = ds2, \ cfgInfo = vm2.GetConfig(), \ backingType = backingType) SetDeltaDiskBacking(configSpec, i, parentDisks[i]) vimutil.InvokeAndTrack(vm2.Reconfigure, configSpec) Log("Power (on) vm1") vm.PowerOn(vm1) time.sleep(5) Log("Power (on) vm2") vm.PowerOn(vm2) time.sleep(5) # prepare promoteDisksSpec diskList = GetVirtualDisks(vm2) promoteDisksSpec = [None] * len(diskList) for i in range(len(diskList)): promoteDisksSpec[i]=vim.host.LowLevelProvisioningManager.\ PromoteDisksSpec() promoteDisksSpec[i].SetNumLinks(1) promoteDisksSpec[i].SetOffsetFromBottom(0) diskId = diskList[i].GetKey() promoteDisksSpec[i].SetDiskId(diskId) Log("Calling LLPM PromoteDisks") llpm = invt.GetLLPM() try: task = llpm.PromoteDisks(vm2, promoteDisksSpec) WaitForTask(task) except Exception as e: print(e) Log("Caught exception : " + str(e)) status = "FAIL" status = "PASS" Log("Destroying VMs") vm.PowerOff(vm2) time.sleep(5) vm.PowerOff(vm1) time.sleep(5) vm2.Destroy() vm1.Destroy() 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 main(): supportedArgs = [(["h:", "host="], "localhost", "Host name", "host"), (["u:", "user="******"root", "User name", "user"), (["p:", "pwd="], "ca$hc0w", "Password", "pwd"), (["v:", "vmname="], "Replay-VM", "Name of the virtual machine", "vmname"), (["i:", "numiter="], "1", "Number of iterations", "iter")] 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(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")) global status for i in range(numiter): vm1 = None # Cleanup from previous runs vm1 = folder.Find(vmname) if vm1 != None: vm1.Destroy() # Create new VM vm1 = vm.CreateQuickDummy(vmname, guest="winXPProGuest") Log("Using VM : " + vm1.GetName()) extraCfgs = vm1.GetConfig().GetExtraConfig() AddExtraConfig(extraCfgs, "replay.allowBTOnly", "TRUE") #AddExtraConfig(extraCfgs, "monitor.needreplay", "TRUE") cSpec = Vim.Vm.ConfigSpec() cSpec.SetFlags(Vim.vm.FlagInfo(recordReplayEnabled=True)) cSpec.SetExtraConfig(extraCfgs) task = vm1.Reconfigure(cSpec) WaitForTask(task) try: Log("Powering on the VM...") vm.PowerOn(vm1) Log("Powering off the VM...") vm.PowerOff(vm1) # StartRecording on a powered-off VM Log("Attempt to record a powered-off VM") try: vm.StartRecording(vm1, "Recording1", "Test recording") status = "FAIL" return except Vim.Fault.InvalidState as e: Log("Received InvalidState exception") # Power on the VM vm.PowerOn(vm1) # Start recording Log("Starting recording...") task = vm1.StartRecording("Recording1", "Test recording") WaitForTask(task) snapshot = task.GetInfo().GetResult() if snapshot == None: raise Exception("Got null result from StartRecording!") CheckState(vm1, Vim.VirtualMachine.RecordReplayState.recording) # Stop recording time.sleep(5) Log("Stopping recording...") vm.StopRecording(vm1) CheckState(vm1, Vim.VirtualMachine.RecordReplayState.inactive) # Check if the VM's snapshot is replayable snapInfo = vm1.GetSnapshot() rootSnapshotList = snapInfo.GetRootSnapshotList() rootSnapshot = rootSnapshotList[0] if rootSnapshot.GetReplaySupported() == False: raise Exception("Recorded Snapshot does not support replay!") Log("Using recorded snapshot " + rootSnapshot.GetName()) # Start replay Log("Initiating replay...") vm.StartReplaying(vm1, rootSnapshot.GetSnapshot()) CheckState(vm1, Vim.VirtualMachine.RecordReplayState.replaying) time.sleep(1) # Stop replay Log("Stopping replay...") vm.StopReplaying(vm1) CheckState(vm1, Vim.VirtualMachine.RecordReplayState.inactive) # Replay an invalid snapshot Log("Creating a dummy snapshot for replay") vm.CreateSnapshot(vm1, "dummySnapshot", "Dummy Snapshot", False, False) snapInfo = vm1.GetSnapshot() curSnap = snapInfo.GetCurrentSnapshot() Log("Attempt to replay dummy snapshot...") try: vm.StartReplaying(vm1, curSnap) except Exception as e: Log("Verified that attempt to replay invalid snapshot was rejected. " ) CheckState(vm1, Vim.VirtualMachine.RecordReplayState.inactive) Log("Powering off...") vm.PowerOff(vm1) # PR 773236, recordReplayEnabled=False means StartRecording should be # rejected. spec = Vim.vm.ConfigSpec(flags=Vim.vm.FlagInfo( recordReplayEnabled=False)) WaitForTask(vm1.Reconfigure(spec)) vm.PowerOn(vm1) try: WaitForTask(vm1.StartRecording("Recording2", "Test recording")) except Vim.Fault.RecordReplayDisabled as e: Log("Verified that attempt to start recording when disabled was rejected." ) Log("%s" % e) else: vm.StopRecording(vm1) vm.PowerOff(vm1) status = "FAIL" Log("StartRecording was allowed") return vm.PowerOff(vm1) except Exception as e: stackTrace = " ".join( traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) Log(stackTrace) status = "FAIL" return try: if vm1.GetRuntime().GetPowerState( ) == Vim.VirtualMachine.PowerState.poweredOn: Log("Powering off VM...") vm.PowerOff(vm1) Log("Deleting VM") vm.Destroy(vm1) except Exception as e: Log("Error deleting VM : " + str(e)) if status == "FAIL": break Log("Test status : " + str(status)) return
def main(): supportedArgs = [(["h:", "host="], "localhost", "Host name", "host"), (["u:", "user="******"root", "User name", "user"), (["p:", "pwd="], "", "Password", "pwd"), (["v:", "vmname="], "t1", "Name of the virtual machine", "vmname"), (["i:", "iter="], "1", "Num of iterations", "iter")] 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 = SmartConnect(host=args.GetKeyValue("host"), port=443, user=args.GetKeyValue("user"), pwd=args.GetKeyValue("pwd")) atexit.register(Disconnect, si) # Process command line vmname = args.GetKeyValue("vmname") numiter = int(args.GetKeyValue("iter")) # Cleanup from previous runs. vm1 = folder.Find(vmname) if vm1 == None: print("VM not found.") sys.exit(0) for i in xrange(numiter): try: Log("Create initial root snapshot") vm.CreateSnapshot(vm1, "gg", "old root", False, False) gg = vm1.snapshot.currentSnapshot Log("Create furture root snapshot R1") vm.CreateSnapshot(vm1, "R1", "new root 1", False, False) s = vm1.snapshot.currentSnapshot task = s.Revert() WaitForTask(task) Log("Create furture root snapshot R2") vm.CreateSnapshot(vm1, "R2", "new root 2", False, False) r2 = vm1.snapshot.currentSnapshot Log("Power On") vm.PowerOn(vm1) Log("Remove initial root snapshot and consolidate") vimutil.InvokeAndTrack(gg.Remove, False) gg = None if vm1.runtime.consolidationNeeded: raise "Consolidation failed while removing gg." Log("Remove the next root snapshot without consolidation") vimutil.InvokeAndTrack(s.Remove, False, False) s = None if vm1.runtime.consolidationNeeded == False: raise "Consolidation flag not raised correctly at 2nd root." Log("Consolidate snapshot") vimutil.InvokeAndTrack(vm1.ConsolidateDisks) if vm1.runtime.consolidationNeeded: raise "Consolidation flag not cleared after consolidate." # time.sleep(5) Log("Remove all snapshots without consolidation") vimutil.InvokeAndTrack(vm1.RemoveAllSnapshots, False) if vm1.runtime.consolidationNeeded == False: raise "Consolidation flag not raised correctly at removeall." Log("Create online snapshot after removeall") vm.CreateSnapshot(vm1, "R3", "new root 3", False, False) Log("Power off") vm.PowerOff(vm1) Log("Remove all snapshots and consolide") vm.RemoveAllSnapshots(vm1) if vm1.runtime.consolidationNeeded: raise "Consolidation flag not cleared after removeall." Log("Success: iter " + str(i)) except Exception as e: Log("Caught exception at iter " + str(i) + ": " + str(e))
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 test(si, delta, backingType, vmxVersion, ds): suffix = ''.join( random.choice(string.letters + string.digits) for i in xrange(8)) vm1Name = '-'.join(['LinkedParent', suffix]) print('Creating %s VM on %s' % (vm1Name, ds)) task.WaitForTasks( [vm1.Destroy() for vm1 in folder.GetVmAll() if vm1.name == vm1Name]) vm1 = vm.CreateQuickDummy(vm1Name, numScsiDisks=1, datastoreName=ds, diskSizeInMB=1, vmxVersion=vmxVersion, backingType=backingType) vm1DirName = vm1.config.files.snapshotDirectory print('Creating Snapshot S1 for %s' % vm1Name) vm.CreateSnapshot(vm1, 'S1', '', False, False) s1 = vm1.snapshot.currentSnapshot disks = vmconfig.CheckDevice(s1.config, vim.vm.Device.VirtualDisk) if len(disks) != 1: raise Exception('Failed to find parent disk from snapshot') parent = disks[0].backing vm2Name = '-'.join(['LinkedChild', suffix]) print('Creating %s VM on %s' % (vm2Name, ds)) task.WaitForTasks( [vm2.Destroy() for vm2 in folder.GetVmAll() if vm2.name == vm2Name]) vm2 = vm.CreateQuickDummy(vm2Name, datastoreName=ds, vmxVersion=vmxVersion) vm2DirName = vm2.config.files.snapshotDirectory configSpec = vim.vm.ConfigSpec() configSpec = vmconfig.AddScsiCtlr(configSpec) configSpec = vmconfig.AddScsiDisk(configSpec, datastorename=ds, capacity=1024, backingType=backingType) child = configSpec.deviceChange[1].device.backing child.parent = parent child.deltaDiskFormat = delta # this edit is expected to fail configSpec = vmconfig.AddFloppy( configSpec, type="image", backingName= "[] /these/are/not/the/floppy/images/you/are/looking/for.flp") floppy = configSpec.deviceChange[2].device floppy.backing = None print('Reconfigure %s (1) adding a disk backed by snapshot of %s and (2) ' 'adding floppy backed by non-existent image. Expecting a failure' % (vm2Name, vm1Name)) try: vm.Reconfigure(vm2, configSpec) except Exception as e: pass else: raise Exception( 'Expected exception during %s reconfigure. But it succeeded instead' % vm2Name) print('Destroying %s' % vm2Name) vm.Destroy(vm2) print('Destroying %s' % vm1Name) vm.Destroy(vm1) hostSystem = host.GetHostSystem(si) datastoreBrowser = hostSystem.GetDatastoreBrowser() try: task.WaitForTask(datastoreBrowser.Search(vm1DirName)) except vim.fault.FileNotFound: pass else: raise Exception( "Expected that '%s' will be gone but it still present" % vm1DirName) try: task.WaitForTask(datastoreBrowser.Search(vm2DirName)) except vim.fault.FileNotFound: pass else: raise Exception( "Expected that '%s' will be gone but it still present" % vm2DirName)
def getObjMapping(vmName, desc, target=False): 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) lc1Name = vmName.replace('-', '-lc1-') lc1Ref = CreateLinkedClone(vmRef, lc1Name, ssName) lc2Name = vmName.replace('-', '-lc2-') lc2Ref = CreateLinkedClone(vmRef, lc2Name, ssName) global dstVmxId dstVmxId = [] vmConfigId = None lc1ConfigId = None lc2ConfigId = None if target: tgtName = vmName + '-tgt' tgtPath = DsNsMgrMkdir(vvolDs, tgtName) vmConfigId = tgtPath[tgtPath.rfind('/') + 1:] lc1TgtName = lc1Name + '-tgt' lc1TgtPath = DsNsMgrMkdir(vvolDs, lc1TgtName) lc1ConfigId = lc1TgtPath[lc1TgtPath.rfind('/') + 1:] lc2TgtName = lc2Name + '-tgt' lc2TgtPath = DsNsMgrMkdir(vvolDs, lc2TgtName) lc2ConfigId = lc2TgtPath[lc2TgtPath.rfind('/') + 1:] vmMap1 = {} addObjMappingForVm(vmName, vmRef, vmMap1, vmConfigId) addObjMappingForVm(lc1Name, lc1Ref, vmMap1, lc1ConfigId) vmMap2 = {} addObjMappingForVm(vmName, vmRef, vmMap2, vmConfigId) addObjMappingForVm(lc2Name, lc2Ref, vmMap2, lc2ConfigId) # Unregister VM to assume only vvol objects exists vm.PowerOff(vmRef) vmRef.Unregister() lc1Ref.Unregister() lc2Ref.Unregister() # returns the vmMap and a list of VMs created return [vmMap1, vmMap2], [vmName, lc1Name, lc2Name]
def TestRelocateWithSnapshotsWithNonHomeRedoLogDir(si, args): vm1name = 'dummy-' + ''.join(choice(letters + digits) for c in xrange(8)) print('# 1. Find the host and the target datastore(s)') host1 = [host1 for host1 in folder.GetHostAll() if not args.host or host1.name.startswith(args.host)][0] dc1 = host1.parent while True: if isinstance(dc1, vim.Datacenter) or not dc1: break dc1 = dc1.parent assert(dc1) dsHome = [ds for ds in host1.datastore if ds.name == args.dsHome][0] dsAux = [ds for ds in host1.datastore if ds.name == args.dsAux][0] dsTarget = [ds for ds in host1.datastore if ds.name == args.dsTarget][0] print('Using target host: %s' % host1.name) print('Using target datacenter: %s' % dc1.name) print('Using home datastore: %s' % dsHome.name) print('Using aux datastore: %s' % dsAux.name) print('Using target datastore: %s' % dsTarget.name) if args.interactive: raw_input('\nPress Enter to continue ...\n') ### print('# 2. Creating %s on %s' % (vm1name, dsHome.name)) vm1 = vm.CreateQuickDummy(vm1name, numScsiDisks=1, datastoreName=dsHome.name, vmxVersion='vmx-07') if args.interactive: raw_input('\nPress Enter to continue ...\n') ### print('# 3. Reconfigure VM for snapshot dir on %s' % dsAux.name) snapshotDirectory = '[%s] %s-snapshotDir' % (dsAux.name, vm1.name) try: print('Creating snapshot dir %s ... ' % snapshotDirectory, end=''); sys.stdout.flush() si.content.fileManager.MakeDirectory(snapshotDirectory, dc1) except: print('failed!') raise else: print('done') spec = vim.vm.ConfigSpec( files = vim.vm.FileInfo(snapshotDirectory = snapshotDirectory), extraConfig = [vim.option.OptionValue(key = 'snapshot.redoNotWithParent', value = 'true')]) try: print('Reconfiguring ... ', end=''); sys.stdout.flush() vm.Reconfigure(vm1, spec) except: print('failed!') raise else: print('done') if args.interactive: raw_input('\nPress Enter to continue ...\n') ### print('# 4. Create snapshots') s1 = None for snapshotName in ['S1', 'S1-1', 'S1-1-1', 'S1-1-1-1']: try: print('Creating snapshot %s ... ' % snapshotName, end=''); sys.stdout.flush() vm.CreateSnapshot(vm1, snapshotName, '', False, False) except: print('failed!') raise else: print('done') if not s1: s1 = vm1.snapshot.currentSnapshot print('Reverting to snapshot S1 ... ', end=''); sys.stdout.flush() vm.RevertSnapshot(s1) print('done') for snapshotName in ['S1-2', 'S1-2-1']: try: print('Creating snapshot %s ... ' % snapshotName, end=''); sys.stdout.flush() vm.CreateSnapshot(vm1, snapshotName, '', False, False) except: print('failed!') raise else: print('done') if args.interactive: raw_input('\nPress Enter to continue ...\n') ### print('# 5. Power cycle') try: print('Powering on ... ', end=''); sys.stdout.flush() vm.PowerOn(vm1) except: print('failed!') raise else: print('done') sleep(1) try: print('Powering off ... ', end=''); sys.stdout.flush() vm.PowerOff(vm1) except: print('failed!') raise else: print('done') sleep(1) try: print('Powering on ... ', end=''); sys.stdout.flush() vm.PowerOn(vm1) except: print('failed!') raise else: print('done') sleep(1) try: print('Suspending ... ', end=''); sys.stdout.flush() vm.Suspend(vm1) except: print('failed!') raise else: print('done') sleep(1) print('Current layout:') pprint(sorted(f1.name for f1 in vm1.layoutEx.file), width=1000) if args.norelocate: return if args.interactive: raw_input('\nPress Enter to continue ...\n') ### print('# 6. Relocate all to target %s' % dsTarget.name) spec = vim.vm.RelocateSpec( datastore = dsTarget, host = host1, disk = [vim.vm.RelocateSpec.DiskLocator(diskId = d1.key, datastore = dsTarget) \ for d1 in vm1.config.hardware.device \ if isinstance(d1, vim.vm.device.VirtualDisk) ]) try: print('Relocating ... ', end=''); sys.stdout.flush() vm.Relocate(vm1, spec) except: print('failed!') raise else: print('done') finally: print('Current layout:') pprint(sorted(f1.name for f1 in vm1.layoutEx.file), width=1000) if args.interactive: raw_input('\nPress Enter to continue ...\n')