Ejemplo n.º 1
0
def SetHostSwapPolicy(cr, policy = None, modify = True):
   cspec = Vim.ComputeResource.ConfigSpec()
   cspec.SetVmSwapPlacement(policy)
   try:
      vimutil.InvokeAndTrack(cr.ReconfigureEx, cspec, modify)
   except Exception as e:
      raise
Ejemplo n.º 2
0
def createSuitableVm(src, dest, vmname):
    # Find a shared datastore
    ds = getSharedDatastore(src, dest)
    if ds == None:
        logging.error(
            "Couldnt find a shared datastore between the two hosts; " +
            "VMotion not possible")
        sys.exit(-1)

    # Find the compute resource for the host
    cr = src.GetParent()

    # Find the datacenter for this host
    curr = src
    while not isinstance(curr, Vim.Datacenter):
        curr = curr.GetParent()
    vmFolder = curr.GetVmFolder()

    # Create the vm
    cspec = vm.CreateQuickDummySpec(vmname,
                                    numScsiDisks=1,
                                    memory=4,
                                    envBrowser=cr.GetEnvironmentBrowser(),
                                    datastoreName=ds.GetSummary().GetName())
    try:
        vimutil.InvokeAndTrack(vmFolder.CreateVm, cspec, cr.GetResourcePool(),
                               src)
    except Exception, e:
        raise
Ejemplo n.º 3
0
   def TestDestroyVvolDs(self):
      self.banner(self.TestDestroyVvolDs)
      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':
               raise Exception("create failed for host " + result.hostKey)

         for ds in self._host.GetConfigManager().GetDatastoreSystem().datastore:
            if ds.name.startswith('vvol-test-ds:'):
               vimutil.InvokeAndTrack(ds.Destroy)
               break

      except:
         VerboseLog(logTrivia, traceback.format_exc())
         ret=False
      finally:
         VerboseLog(logTrivia, "}")

      VerboseLog(logInfo, "passed" if ret else "failed");
Ejemplo n.º 4
0
def SetSwapPolicy(vm1, policy):
   cspec = Vim.Vm.ConfigSpec()
   cspec.SetSwapPlacement(policy)
   try:
      vimutil.InvokeAndTrack(vm1.Reconfigure, cspec)
   except Exception as e:
      raise
Ejemplo n.º 5
0
def RelocateTest(srcHost, 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='
    try:
        spec = CreateVmSpec(backingType + "Vm", dsName, backingType, diskSize,
                            vmx)
        vm1 = VmTest(spec, dc, srcHost, remove=False)
        vm.PowerOn(vm1)
        if (not host):
            resPool = destResPool
        else:
            resPool = host.GetParent().GetResourcePool()
        print("Vm migrate dest resoure pool is " + str(resPool))
        vimutil.InvokeAndTrack(vm1.Migrate, resPool, host, "defaultPriority")
        if str(vm1.GetResourcePool()) != str(resPool):
            raise AssertionError(msg + "FAILURE, wrong place " +
                                 str(vm1.GetResourcePool()) + "Expected " +
                                 str(resPool))
        '''
      relocSpec = Vim.Vm.RelocateSpec()
      relocSpec.SetPool(resPool)
      relocSpec.SetHost(host)
      vimutil.InvokeAndTrack(vm1.Relocate, relocSpec)
      '''
    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)
Ejemplo n.º 6
0
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])
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
0
def TestEarlyBinding(vmName, uuid):
    """
    Test early binding portgroup behaviour
    - Create a VM with a nic connecting to an early binding portgroup and start connected to true
      fails
    - Create a VM with a nic connecting to an early binding portgroup and start connected to false
      succeeds
    - Poweron the created VM succeds.
    - Reconfigure the VM to connect to an invalid port fails.
    - Hot add of device connected to an early binding portgroup fails.
    - Reconfigure the VM to connect to an early binding portgroup when device is not connected succeeds
    - Reconfigure a powered on VM to connect to an early binding portgroup when device is connected fails.
    """

    print("Testing early binding portgroup behaviour")
    cleanupvm(vmName)
    envBrowser = invt.GetEnv()
    config = vm.CreateQuickDummySpec(vmName)
    cfgOption = envBrowser.QueryConfigOption(None, None)
    # Add a earlybinding dvPortgroup backed nic.
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg2")
    try:
        vmFolder = invt.GetVmFolder()
        vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    except Vim.Fault.InvalidDeviceSpec:
        print("Caught invalid device backing as expected")
    print("Test 1: Creating a device backed by an early binding portgroup with"
          "startConnected = true fails as expected: PASS")
    config = vm.CreateQuickDummySpec(vmName)
    cfgOption = envBrowser.QueryConfigOption(None, None)
    # Add an earlybinding dvPortgroup backed nic.
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg2", False)
    vmFolder = invt.GetVmFolder()
    vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    myVm = folder.Find(vmName)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if not IsBackingPortNotAllocated(devices):
        print(devices)
        raise Exception ("Nic has a dvPort assigned to it or nic add failed")
    print("Test 2: Creating a device backed by and early binding portgroup with"
          "startConnected = false succeeds: PASS")
    myVm = folder.Find(vmName)
    vm.PowerOn(myVm)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("nic not present")
    if not IsBackingPortNotAllocated(devices):
        print(devices)
        raise Exception ("Nic has a dvPort assigned to it or nic add failed")
    print("Test 3: Power on VM succeeds: PASS")
    # Reconfigure the VM to connect to an invalid port.
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortKey("100")
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    try:
        task = myVm.Reconfigure(cspec)
        WaitForTask(task)
    except Vim.Fault.InvalidDeviceSpec:
        print("Caught invalid device backing")
    print("Test 4: Reconfig a VM to connect to an invalid dvPort fails as expected: PASS")

    # Add a device to connect to an early binding portgroup with no dvPort specified.
    config = Vim.Vm.ConfigSpec()
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg2")
    try:
        task = myVm.Reconfigure(config)
        WaitForTask(task)
    except Vim.Fault.InvalidDeviceSpec:
        print("Caught invalid device backing")
    print("Test 4: Hot add of a device to connect to an earlybinding portgroup fails as expected: PASS")

    # Reconfigure device to connect to an early binding portgroup.
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortgroupKey("pg2")
            device.GetBacking().GetPort().SetPortKey(None)
            device.GetBacking().GetPort().SetConnectionCookie(None)
            device.GetConnectable().SetConnected(True)
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    try:
        task = myVm.Reconfigure(cspec)
        WaitForTask(task)
    except Vim.Fault.InvalidDeviceSpec:
        print("Caught invalid device backing")
    print("Test 5: Reconfig a VM to connect to an early binding portgroup fails as expected: PASS")

    # Reconfigure a device to disconnected state and connect to an early binding dvPortgroup.
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortgroupKey("pg2")
            device.GetBacking().GetPort().SetPortKey(None)
            device.GetBacking().GetPort().SetConnectionCookie(None)
            device.GetConnectable().SetConnected(False)
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    task = myVm.Reconfigure(cspec)
    WaitForTask(task)
    if not IsBackingPortNotAllocated(devices):
        print(devices)
        raise Exception ("Nic has a dvPort assigned to it or nic add failed")
    print("Test6 complete: Reconfig powered on VM to connect to a earlybinding backing with device disconnected: PASS")
    print("EarlyBinding tests complete")
Ejemplo n.º 9
0
def TestLateBinding(vmName, uuid):
    """
     Create a VM and connect it to a latebinding portgroup.
     Poweron the VM. Validate that a dvPort has not been allocated for the VM.
     Reconfig the VM to connect to a ephemeral dvPortgroup validate that the VM
     has a valid backing.
     Reconfigure the VM to connect back to the latebinding portgroup the reconfig
     should fail.
     Reconfigure the VM to connect back to the latebinding portgroup with the
     device disconnected the connect should succeed.
    """
    cleanupvm(vmName)
    print("Testing latebinding portgroup behaviour")
    envBrowser = invt.GetEnv()
    config = vm.CreateQuickDummySpec(vmName)
    cfgOption = envBrowser.QueryConfigOption(None, None)
    # Add a latebinding dvPortgroup backed nic.
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg4",
                                       type = 'vmxnet3')
    try:
        vmFolder = invt.GetVmFolder()
        vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    except Exception as e:
        raise
    myVm = folder.Find(vmName)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Failed to add nic")
    if not IsBackingPortNotAllocated(devices):
        raise Exception("dvPort allocated for a latebinding portgroup")
    print("Test1: Create VM with a latebinding portgroup backing: PASS")
    # power on the VM.
    vm.PowerOn(myVm)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Nic seems to be missing")
    if not IsBackingPortNotAllocated(devices):
        raise Exception("dvPort allocated for a latebinding portgroup after powerOn")
    print("Test2: Powering on a VM with a latebinding portgroup backing: PASS")

    # Reconfigure the VM to connect to an ephemeral backing.
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortgroupKey("pg3")
            device.GetBacking().GetPort().SetPortKey(None)
            device.GetBacking().GetPort().SetConnectionCookie(None)
            device.GetConnectable().SetConnected(True)
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    task = myVm.Reconfigure(cspec)
    WaitForTask(task)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Failed to edit nic")
    if not IsBackingValid(devices):
        raise Exception("Invalid backing allocated")
    print("Test3: Reconfig poweredon with a ephemeral backing from a latebinding backing allocates a port: PASS")

    #Reconfig the VM to connect to a latebinding backing.
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortgroupKey("pg4")
            device.GetBacking().GetPort().SetPortKey(None)
            device.GetBacking().GetPort().SetConnectionCookie(None)
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    try:
        task = myVm.Reconfigure(cspec)
        WaitForTask(task)
    except Vim.Fault.InvalidDeviceSpec:
        print("Caught invalid device backing")
    print("Test4: Reconfig powered on VM to connect to a latebinding backing fails as expected: PASS")

    # reconfigure the VM to connect to a latebinding portgroup and disconnect the device.
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortgroupKey("pg4")
            device.GetBacking().GetPort().SetPortKey(None)
            device.GetBacking().GetPort().SetConnectionCookie(None)
            device.GetConnectable().SetConnected(False)
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    task = myVm.Reconfigure(cspec)
    WaitForTask(task)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if not IsBackingPortNotAllocated(devices):
        print(devices)
        raise Exception ("Nic has a dvPort assigned to it or nic add failed")
    print("Test5: Reconfig powered on VM to connect to a latebinding backing with device disconnected: PASS")
    print("Late binding tests complete")
Ejemplo n.º 10
0
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
Ejemplo n.º 11
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])
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
def main():
    supportedArgs = [(["h:", "VC host="], "localhost", "Host name", "host"),
                     (["u:", "user="******"root", "User name", "user"),
                     (["p:", "pwd="], "ca$hc0w", "Password", "pwd"),
                     (["v:", "vmname="], "VMotionTest",
                      "Name of the virtual machine", "vmname"),
                     (["i:", "numiter="], "1", "Number of iterations", "iter"),
                     (["s:", "source="], "", "Source host", "src"),
                     (["d:", "dest="], "", "Destination host", "dest")]
    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)

    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s')

    # Connect
    si = Connect(host=args.GetKeyValue("host"),
                 user=args.GetKeyValue("user"),
                 pwd=args.GetKeyValue("pwd"))

    if args.GetKeyValue("src") == "" or args.GetKeyValue("dest") == "":
        logging.error("Both source and destination hosts must be specified")
        args.Usage()
        sys.exit(-1)

    # Virtual machine name
    vmname = args.GetKeyValue("vmname")

    # Number of iterations to run
    iterations = int(args.GetKeyValue("iter"))

    searchIndex = si.RetrieveContent().GetSearchIndex()

    # Find the source host
    srcName = args.GetKeyValue("src")
    src = findHost(srcName, searchIndex)
    if src == None:
        logging.error("Couldnt find the source host: " + srcName)
        sys.exit(-1)

    # Find the destination host
    destName = args.GetKeyValue("dest")
    dest = findHost(destName, searchIndex)
    if dest == None:
        logging.error("Couldnt find the destination host: " + destName)
        sys.exit(-1)

    sourceHostName = src.GetSummary().GetConfig().GetName()
    destHostName = dest.GetSummary().GetConfig().GetName()

    # Find the virtual machine
    vmotionVM = None
    vms = src.GetVm()
    vmotionVM = searchHostForVm(vmname, src)
    if vmotionVM == None:
        vmotionVM = searchHostForVm(vmname, dest)
        if vmotionVM != None:
            # Switch up source and destination
            temp = src
            src = dest
            dest = temp

    # If the virtual machine doesnt exist, create it.
    create = 0
    if vmotionVM == None:
        vmotionVM = createSuitableVm(src, dest, vmname)
        create = 1
    else:
        # Verify the vm is on a datastore available on both hosts
        dsList = vmotionVM.GetDatastore()
        for ds in dsList:
            if len([a for a in src.GetDatastore() \
                    if a.GetSummary().GetUrl() == ds.GetSummary().GetUrl() ]) == 0:
                logging.error("Part of the virtual machine is on: " \
                              + ds.GetSummary().GetName() + " which is not accessible on: " \
                              + sourceHostName)
                sys.exit(-1)
            if len([a for a in dest.GetDatastore() \
                    if a.GetSummary().GetUrl() == ds.GetSummary().GetUrl() ]) == 0:
                logging.error("Part of the virtual machine is on: " \
                              + ds.GetSummary().GetName() + " which is not accessible on: " \
                              + destHostName)
                sys.exit(-1)

    # power it on
    if vmotionVM.GetRuntime().GetPowerState(
    ) != Vim.VirtualMachine.PowerState.poweredOn:
        vimutil.InvokeAndTrack(vmotionVM.PowerOn)

    # resource pools
    srcRp = src.GetParent().GetResourcePool()
    destRp = dest.GetParent().GetResourcePool()

    # All systems are go
    logging.info("Ready for vmotion")

    timetaken = datetime.timedelta()
    backwardsTime = datetime.timedelta()
    for i in range(iterations):
        # ping
        res = doVmotion(vmotionVM, dest, destHostName,
                        Vim.VirtualMachine.MovePriority.highPriority, destRp)
        if res[0] != None:
            print "Failure source: " + sourceHostName + ", destination: " + destHostName
            break
        timetaken = timetaken + res[1]

        # pong
        res = doVmotion(vmotionVM, src, sourceHostName,
                        Vim.VirtualMachine.MovePriority.highPriority, srcRp)
        if res[0] != None:
            print "Failure source: " + destHostName + ", destination: " + sourceHostName
            break
        backwardsTime = backwardsTime + res[1]
        logging.info("Iteration completed: " + str(i))

    logging.info("Summary: ")
    logging.info("Ping pongs requested (2 vmotions): " + str(iterations))
    logging.info("Virtual machine name: " + vmname)
    logging.info("Host 1: " + sourceHostName)
    logging.info("Host 2: " + destHostName)
    logging.info("Successful ping/pongs (2 vmotions): " + str(i + 1))
    logging.info("Avg. time going from source to destination (seconds): " + \
                 str(timetaken.seconds/iterations))
    logging.info("Avg. time going from destination to source (seconds): " + \
                 str(backwardsTime.seconds/iterations))
    logging.info("Total time: " + str(timetaken + backwardsTime))
    logging.info("Avg. time for vmotion (seconds): " + \
          str((backwardsTime + timetaken).seconds/(iterations * 2)))
    if create == 1:
        # Cleanup behind self
        vimutil.InvokeAndTrack(vmotionVM.PowerOff)
        vmotionVM.Destroy()
Ejemplo n.º 15
0
def TestSimulatedVcClone(vmName, uuid):
    """
    Test the code paths that VC excercises during cloning a VM with
    a dvs backing.
    """
    print("Testing hostd code corresponding to clone")
    cleanupvm(vmName)
    envBrowser = invt.GetEnv()
    config = vm.CreateQuickDummySpec(vmName)
    cfgOption = envBrowser.QueryConfigOption(None, None)
    # Add a nic backed by a dvs portgroup pair.
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "invalidPg")
    try:
        vmFolder = invt.GetVmFolder()
        vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    except Vim.Fault.InvalidDeviceSpec:
        print("Test1: Caught invalid device spec as expected")
    else:
        raise "Test1: Create vm with invalid dvPortgroup backing didn't fail as expected"
    print("Test1: Create vm with invalid dvPortgroup backing failed as expected: PASS")

    config = vm.CreateQuickDummySpec(vmName)
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg1")
    try:
        vmFolder = invt.GetVmFolder()
        vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    except Exception:
        print("Failed to clone a VM to connect to a dvPortgroup")
        raise
    print("Test2: Create vm with valid dvPort backing: PASS")

    # Create a VM only specifying the dvs uuid in its backing.
    vm1 = folder.Find(vmName)
    vm.Destroy(vm1)
    config = vm.CreateQuickDummySpec(vmName)
    config = vmconfig.AddDvPortBacking(config, "", uuid, None, cfgOption, "")
    try:
        vmFolder = invt.GetVmFolder()
        vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    except Exception:
        print("Failed to clone a VM to connected to a standalone port")
        raise
    myVm = folder.Find(vmName)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if not IsBackingPortNotAllocated(devices):
        print(devices)
        raise Exception ("Nic has a dvPort assigned to it or nic add failed")
    print("Test3: Create vm with valid dvs uuid specified in the dvsbacking (standalone): PASS")

    # Reconfigure a VM only specifying a dvs uuid in its backing
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            cspec = Vim.Vm.ConfigSpec()
            device.GetConnectable().SetConnected(True)
            device.SetUnitNumber(9)
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.add)
            break
    try:
        task = myVm.Reconfigure(cspec)
        WaitForTask(task)
    except Exception:
        print("Test4: failed to add a device with only dvs backing specified")
    print("Test4: Reconfig VM specifying only the dvsUuid in backing: PASS")

    print("Testing simulate vc clone done")
Ejemplo n.º 16
0
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))
Ejemplo n.º 17
0
def TestEphemeral(vmName, uuid):
    """
    Test epehemeral portgroups.
    - Create a VM configure it to connect to an ephemeral portgroup.
    - Power on the VM and validate that backing is valid.
    - Hot add a nic to connect to an ephemeral portgroup and validate backing.
    - Poweroff and destroy the VM
    """
    print("Testing Ephemeral portgroup behaviour")
    cleanupvm(vmName)
    envBrowser = invt.GetEnv()
    config = vm.CreateQuickDummySpec(vmName)
    cfgOption = envBrowser.QueryConfigOption(None, None)
    # Add a latebinding dvPortgroup backed nic.
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg1")
    try:
        vmFolder = invt.GetVmFolder()
        vimutil.InvokeAndTrack(vmFolder.CreateVm, config, invt.GetResourcePool(), None)
    except Exception as e:
        raise
    myVm = folder.Find(vmName)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Failed to add nic")
    if not IsBackingPortNotAllocated(devices):
        print(devices)
        raise Exception ("Nic has a dvPort assigned to it or nic add failed")
    print("Test 1: Create a vm with an ephemeral portgroup backing: PASS")
    vm.PowerOn(myVm)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Failed to add nic")
    if not IsBackingValid(devices):
        raise Exception("Invalid backing allocated")
    print("Test 2: powerOn VM with a ephemeral backing: PASS")
    # Remove and add hot add a nic device to a powered on VM.
    vm.PowerOff(myVm)
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.remove)
            break
    task = myVm.Reconfigure(cspec)
    WaitForTask(task)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if IsBackingValid(devices):
        print(devices)
        raise Exception("Remove of device failed.")
    # powerOn the VM and hot add the nic.
    vm.PowerOn(myVm)
    config = Vim.Vm.ConfigSpec()
    config = vmconfig.AddDvPortBacking(config, "", uuid, 0, cfgOption, "pg1")
    task = myVm.Reconfigure(config)
    WaitForTask(task)
    devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Failed to add nic")
    if not IsBackingValid(devices):
        raise Exception("Invalid backing allocated")
    print("Test 3: remove and hot add nic to VM with a ephemeral backing: PASS")
    # Foundry issue wait for fix and then uncomment.
    time.sleep(10)
    for device in devices:
        if isinstance(device.GetBacking(),\
            Vim.Vm.Device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
            device.GetBacking().GetPort().SetPortgroupKey("pg3")
            device.GetBacking().GetPort().SetPortKey(None)
            device.GetBacking().GetPort().SetConnectionCookie(None)
            device.GetConnectable().SetConnected(True)
            cspec = Vim.Vm.ConfigSpec()
            vmconfig.AddDeviceToSpec(cspec, device, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
            break
    #task = myVm.Reconfigure(cspec)
    #WaitForTask(task)
    #devices = vmconfig.CheckDevice(myVm.GetConfig(), Vim.Vm.Device.VirtualEthernetCard)
    #if len(devices) < 1:
     #   raise Exception("Failed to edit nic")
    #if not IsBackingValid(devices):
     #   raise Exception("Invalid backing allocated")
    #print("Test4: Reconfig poweredon with a ephemeral backing: PASS")
    print("Ephemeral portgoup tests complete")
Ejemplo n.º 18
0
def main():
    global verbose
    # Process command line
    try:
        opts, args = getopt.getopt(sys.argv[1:], "bp:qs:d:uhv:c:n:m:", \
              ["source=", "dest=", "vc=", "vm=", "datacenter=", \
              "usage", "help", "cleanup", "verbose", "repeat=", \
              "network=", "numnics=", "numdisks=", "disksize=", "attachcdrom", \
              "maxfailures"])
    except getopt.GetoptError:
        Usage()
        sys.exit(-1)

    sourceHostName = None
    destHostName = None
    datacenterName = None
    vcName = None
    vmName = "DmotionTester"
    doCleanup = 0
    count = 1
    network = None
    numNics = 0
    numDisks = 1
    diskSize = 4
    attachCd = 0
    maxFailures = 0
    numFailures = 0

    for o, a in opts:
        if o in ("-s", "--source"):
            sourceHostName = a
        if o in ("-d", "--dest"):
            destHostName = a
        if o in ("-v", "--vc"):
            vcName = a
        if o in ("-c", "--datacenter"):
            datacenterName = a
        if o in ("-n", "--vm"):
            vmName = a
        if o in ("-q", "--cleanup"):
            doCleanup = 1
        if o in ("-b", "--verbose"):
            verbose = 1
            Log("Verbose level set")
        if o in ("-p", "--repeat"):
            count = int(a)
        if o == "--network":
            network = a
        if o == "--numnics":
            numNics = int(a)
        if o == "--numdisks":
            numDisks = int(a)
        if o == "--disksize":
            diskSize = int(a)
        if o == "--attachcdrom":
            attachCd = 1
        if o in ("-m", "--maxfailures"):
            maxFailures = int(a)
        if o in ("-u", "--usage", "-h", "--help"):
            Usage()
            sys.exit(0)

    if (None in (sourceHostName, destHostName, vcName, datacenterName)) \
     or (numNics > 0 and  network == None):
        print("VC Host    : %s" % vcName)
        print("Datacenter : %s" % datacenterName)
        print("Source host: %s" % sourceHostName)
        print("Dest host  : %s" % destHostName)
        Usage()
        sys.exit(-1)

    # Connect
    Log("Connecting to VirtualCenter: " + vcName)
    si = Connect(vcName, 902, "Administrator", "ca$hc0w", "vpxd")
    atexit.register(Disconnect, si)

    # Assumes no folderization inside the datacenter root host folder.
    Log("Locating source and destination hosts: " + sourceHostName + ", " +
        destHostName)
    hosts = GetHostFolder(datacenterName)
    sourceCrRef = FindChild(hosts, sourceHostName)
    destCrRef = FindChild(hosts, destHostName)

    # Get the environment browser for the source host
    browser = sourceCrRef.GetEnvironmentBrowser()

    # Get the datastore list for the dest host
    destDsList = destCrRef.GetDatastore()
    finalDs = None
    # Find a reasonable destination datastore ( > 4GB free and vmfs 3)
    for i in range(0, len(destDsList)):
        if (destDsList[i].GetCapability().GetDirectoryHierarchySupported()):
            if (destDsList[i].GetSummary().GetFreeSpace() >
                    4 * 1024 * 1024 * 1024):
                finalDs = destDsList[i]

    if finalDs == None:
        print("Failed to find a suitable datastore. quitting")
        sys.exit(-1)
    Log("Found a suitable destination datasource: " +
        finalDs.GetSummary().GetName())

    Log("Going to loop " + str(count) + " times")
    for i in range(0, count):
        # Create the virtual machine on source, power on the virtual machine\
        # and issue a relocate.
        try:
            vmNameNew = vmName
            if (count > 1):
                vmNameNew = vmName + str(i)
            Log("Creating virtual machine with name: " + vmNameNew)
            vm1 = vm.CreateQuickDummy(vmNameNew, numDisks, numNics, attachCd, \
                        sourceCrRef.GetHost()[0], sourceCrRef.GetResourcePool(), browser,
            diskSize, network)
            Log("Powering on... ")
            vm.PowerOn(vm1)
            time.sleep(2)
            relocSpec = Vim.Vm.RelocateSpec()
            relocSpec.SetDatastore(finalDs)
            relocSpec.SetHost(destCrRef.GetHost()[0])
            relocSpec.SetPool(destCrRef.GetResourcePool())
            Log("Invoking Dmotion... ")
            vimutil.InvokeAndTrack(vm1.Relocate, relocSpec)
            time.sleep(2)
            if doCleanup == 1:
                Log("Cleanup requested: Powering off")
                vimutil.InvokeAndTrack(vm1.PowerOff)
                Log("Destroying the successfully vmotioned virtual machine")
                vm1.Destroy()
                time.sleep(2)
        except Exception as e:
            print("Failed test due to exception")
            print("Info: ")
            print(e.__str__)
            if (numFailures >= maxFailures):
                raise
            else:
                numFailures = numFailures + 1
Ejemplo n.º 19
0
def TestCleanupLocks(dsName, remoteHost, remotePath):
    print("Create datastore ... ")
    ds = CreateNasDs(dsName, remoteHost, remotePath)
    if (not ds):
        raise Exception("TestCleanLocks datastore create failed with " +
                        dsName)

    print("create vm")
    vmName = "testvm2"
    vm1 = vm.CreateQuickDummy(vmname=vmName, datastoreName=dsName)
    if (not vm1):
        raise Exception("TestCleanLocks vm cannot be created " + vmName)
    print("create vm done")

    print("test remove file locks with vm ... ")
    try:
        vimutil.InvokeAndTrack(ds.CleanupLocks)
    except Vim.Fault.ResourceInUse as e:
        print("TestCleanupLocks with vm test succeeded with " + str(e))
    except Exception as e:
        print("TestCleanupLocks with vm failed with incorrect exception " +
              str(e))
    else:
        raise Exception(
            "TestCleanupLocks with vm failed because write action is allowd on read-only volume"
        )

    print("destroy vm")
    vm.Delete(vm1)
    print("destory vm done")

    print("test remove locks on datastore or subdirectory")
    try:
        vimutil.InvokeAndTrack(ds.CleanupLocks)
        print("TestCleanLocks positive test succeeds")
        vimutil.InvokeAndTrack(ds.CleanupLocks, "something")
        print("TestCleanLocks positive subdir test succeeds")
    except Exception as e:
        raise Exception("TestCleanLocks positive test failed " + str(e))
    finally:
        datastoreSystem.RemoveDatastore(ds)

    print("Create datastore ")
    ds = CreateNasDs(dsName, remoteHost, remotePath, accessMode="readOnly")
    if (not ds):
        raise Exception("TestCleanLocks readly datastore create failed with " +
                        dsName)
    "Create datastore done"

    print("test remove locks with read permission")
    try:
        vimutil.InvokeAndTrack(ds.CleanupLocks)
    except Vim.Fault.InaccessibleDatastore as e:
        print("TestCleanupLocks readonly test succeeded, with exception " +
              str(e))
    except Exception as e:
        print(
            "TestCleanupLocks readonly test failed with incorrect exception " +
            str(e))
    else:
        raise Exception(
            "TestCleanupLocks readonly test failed because write action is allowd on read-only volume"
        )
    finally:
        datastoreSystem.RemoveDatastore(ds)

    print("Test remove locks on vmfs")
    try:
        vmds = [
            ds for ds in datastoreSystem.datastore
            if isinstance(ds.info, Vim.Host.VmfsDatastoreInfo)
        ]
        vimutil.InvokeAndTrack(vmds[0].CleanupLocks)
        print("TestCleanLocks positive test on vmfs " + vmds[0].summary.name +
              " succeeds")
    except Exception as e:
        raise Exception("TestCleanLocks positive test on vmfs failed " +
                        str(e))