Esempio n. 1
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
Esempio n. 2
0
def CreateVmSpec(vmName, dsName, backing, diskSize, vmVersion='vmx-09'):
    return vm.CreateQuickDummySpec(vmname=vmName,
                                   numScsiDisks=1,
                                   diskSizeInMB=diskSize,
                                   datastoreName=dsName,
                                   backingType=backing,
                                   thin=True,
                                   vmxVersion=vmVersion)
Esempio n. 3
0
def TestVQATCreateSpec(vmname, memSize):
    """
   Create a spec for a VQAT VM, with all memory reserved.
   """
    Log("Creating a spec")
    cfg = vm.CreateQuickDummySpec(vmname,
                                  vmxVersion="vmx-18",
                                  memory=memSize,
                                  guest="otherGuest")

    memoryAlloc = vim.ResourceAllocationInfo()
    memoryAlloc.SetReservation(memSize)
    cfg.SetMemoryAllocation(memoryAlloc)
    return cfg
Esempio n. 4
0
    def CreateVMOnHost(self, host, numVms):
        dcName = self.dc.name
        hostName = host.name
        vmName = "testvm_" + hostName
        compRes = host.GetParent()
        resPool = compRes.GetResourcePool()
        envBrowser = compRes.GetEnvironmentBrowser()
        configSpec = vm.CreateQuickDummySpec(vmName, envBrowser=envBrowser)
        vmFolder = self.dc.GetVmFolder()
        for i in range(0, numVms):
            vmName = "testvm_" + hostName + "_%d" % i
            configSpec.SetName(vmName)

            self.Log("Creating VM %s on host %s in DC %s started" % \
                     (vmName, hostName, dcName))
            t = vmFolder.CreateVm(configSpec, resPool, host)
            self.Log("Creating VM %s on host %s in DC %s done: %s" % \
                     (vmName, hostName, dcName, t))

            self.tasks.append(t)
Esempio n. 5
0
def CreateTestVm(si, dsName):
    # Create a VM for testing
    vmName = "TestStatsVm1"

    # Destroy old VMs
    for vm1 in si.content.rootFolder.childEntity[0].vmFolder.childEntity:
        if vm1.name == vmName:
            if vm1.runtime.powerState != vim.VirtualMachine.PowerState.poweredOff:
                vm.PowerOff(vm1)
            vm1.Destroy()

    spec = vm.CreateQuickDummySpec(vmName,
                                   nic=1,
                                   memory=32,
                                   datastoreName=dsName)
    resPool = invt.GetResourcePool(si=si)
    vmFolder = invt.GetVmFolder(si=si)
    t = vmFolder.CreateVm(spec, pool=resPool)
    WaitForTask(t)
    vm1 = t.info.result

    Log("Created VM %s on %s" % (vm1.name, resPool.owner.host[0].name))

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   vim.vm.Device.VirtualEthernetCard)
    if len(devices) < 1:
        raise Exception("Failed to find nic")

    # Reconfigure to add network
    cspec = vim.vm.ConfigSpec()
    devices[0].GetConnectable().SetStartConnected(True)
    devices[0].GetConnectable().SetConnected(True)
    vmconfig.AddDeviceToSpec(cspec, devices[0],
                             vim.vm.Device.VirtualDeviceSpec.Operation.edit)
    vm.Reconfigure(vm1, cspec)
    vm.PowerOn(vm1)
    return vm1
Esempio n. 6
0
def main():
    supportedArgs = [(["h:", "host="], "localhost", "Host name", "host"),
                     (["u:", "user="******"root", "User name", "user"),
                     (["p:", "pwd="], "", "Password", "pwd"),
                     (["v:", "vmname="], "VTPMTest",
                      "Name of the virtual machine", "vmname")]

    supportedToggles = [
        (["usage", "help"], False, "Show usage information", "usage"),
        (["runall", "r"], True, "Run all the tests", "runall"),
        (["nodelete"], False, "Dont delete vm on completion", "nodelete")
    ]

    args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles)
    if args.GetKeyValue("usage") == True:
        args.Usage()
        sys.exit(0)

    # Connect
    si = SmartConnect(host=args.GetKeyValue("host"),
                      user=args.GetKeyValue("user"),
                      pwd=args.GetKeyValue("pwd"))
    atexit.register(Disconnect, si)

    # Process command line
    vmname = args.GetKeyValue("vmname")
    runall = args.GetKeyValue("runall")
    noDelete = args.GetKeyValue("nodelete")
    status = "PASS"
    vm1 = None

    try:
        Log("Cleaning up VMs from previous runs...")
        vm.Delete(vmname, True)

        Log("Prepare host for crypto...")
        vimcrypto.CryptoEnableHost(host.GetHostSystem(si))

        Log("Adding key for encrypted VM...")
        cryptoMgr = si.RetrieveContent().cryptoManager
        keyId, cryptoKey = CreateKeyForVM(si)
        cryptoMgr.AddKeys([cryptoKey])

        ## vTPM requires hardware version 14.
        Log("Creating Hw14 VM...")
        cfg = vm.CreateQuickDummySpec(vmname,
                                      vmxVersion="vmx-14",
                                      memory=4,
                                      guest="otherGuest")
        cryptoSpec = vimcrypto.CreateCryptoSpecEncrypt(keyId, None)
        cfg.crypto = cryptoSpec
        AddVTPM(cfg)
        vm1 = vm.CreateFromSpec(cfg)
        TestVTPMProps(vm1)
        task = vm1.Destroy()
        WaitForTask(task)
        vm1 = None

        vm1 = vm.CreateQuickDummy(vmname,
                                  vmxVersion="vmx-14",
                                  memory=4,
                                  guest="otherGuest")

        Log("Encrypting VM...")
        vimcrypto.EncryptVM(vm1, keyId, None, disks=False)

        TestVTPMReconfig(vm1)
        TestNoVTPM(vm1)
        TestVTPMVDRemove(vm1)

        Log("Tests completed.")

    except Exception as e:
        status = "FAIL"
        Log("Caught exception : %s, %r" % (e, e))
        raise
    finally:
        # Delete the vm as cleanup
        if noDelete == False:
            if vm1 != None:
                task = vm1.Destroy()
                WaitForTask(task)
            vm1 = None

    Log("TEST RUN COMPLETE: " + status)
Esempio n. 7
0
def main():
    supportedArgs = [(["h:", "host="], "localhost", "Host name", "host"),
                     (["u:", "user="******"root", "User name", "user"),
                     (["p:", "pwd="], "", "Password", "pwd"),
                     (["v:", "vmname="], "VWDTTest",
                      "Name of the virtual machine", "vmname")]

    supportedToggles = [
        (["usage", "help"], False, "Show usage information", "usage"),
        (["runall", "r"], True, "Run all the tests", "runall"),
        (["nodelete"], False, "Dont delete vm on completion", "nodelete")
    ]

    args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles)
    if args.GetKeyValue("usage") == True:
        args.Usage()
        sys.exit(0)

    # Connect
    si = SmartConnect(host=args.GetKeyValue("host"),
                      user=args.GetKeyValue("user"),
                      pwd=args.GetKeyValue("pwd"))
    atexit.register(Disconnect, si)

    # Process command line
    vmname = args.GetKeyValue("vmname")
    runall = args.GetKeyValue("runall")
    noDelete = args.GetKeyValue("nodelete")
    status = "PASS"
    vm1 = None

    try:
        Log("Cleaning up VMs from previous runs...")
        vm.Delete(vmname, True)

        ## vWDT requires hardware version 17.
        Log("Creating Hw17 VM...")
        cfg = vm.CreateQuickDummySpec(vmname,
                                      vmxVersion="vmx-17",
                                      memory=4,
                                      guest="otherGuest")
        AddVWDT(cfg)
        vm1 = vm.CreateFromSpec(cfg)
        task = vm1.Destroy()
        WaitForTask(task)
        vm1 = None

        vm1 = vm.CreateQuickDummy(vmname,
                                  vmxVersion="vmx-17",
                                  memory=4,
                                  guest="otherGuest")

        TestVWDTReconfig(vm1)
        TestNoVWDT(vm1)
        TestVWDTVDRemove(vm1)

        TestVWDTRunOnBootAndRunning(vm1)

        Log("Tests completed.")

    except Exception as e:
        status = "FAIL"
        Log("Caught exception : %s, %r" % (e, e))
        raise
    finally:
        # Delete the vm as cleanup
        if noDelete == False:
            if vm1 != None:
                task = vm1.Destroy()
                WaitForTask(task)
            vm1 = None

    Log("TEST RUN COMPLETE: " + status)
Esempio n. 8
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()
Esempio n. 9
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")
Esempio n. 10
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")
Esempio n. 11
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")
Esempio n. 12
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")
Esempio n. 13
0
def main():
    global status
    supportedArgs = [
        (["H:", "host="], "localhost", "Host name", "host"),
        (["k:", "keep="], "0", "Keep configs", "keep"),
        (["e:", "useExisting="], False, "Use existing VM", "useExistingVm"),
        (["u:", "user="******"root", "User name", "user"),
        (["p:", "pwd="], "", "Password", "pwd"),
        (["v:",
          "VM name="], "vmotionErrs", "Name of the virtual machine", "vmname"),
        (["d:",
          "dsName="], None, "Target datastore for storage VMotions", "dsName"),
        (["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)

    # Process command line
    host = args.GetKeyValue("host")
    vmname = args.GetKeyValue("vmname")
    numiter = int(args.GetKeyValue("iter"))
    keep = int(args.GetKeyValue("keep"))
    useExistingVm = bool(args.GetKeyValue("useExistingVm"))
    dsName = args.GetKeyValue("dsName")

    for i in range(numiter):
        si = None
        try:
            # Connect to host
            si = SmartConnect(host=host,
                              user=args.GetKeyValue("user"),
                              pwd=args.GetKeyValue("pwd"))
            Log("Connected to Host")

            dsName = GetDatastore(si, dsName)
            Log('Using datastore: %s' % dsName)

            # Cleanup from previous runs
            if not useExistingVm:
                CleanupVm(vmname)
                CleanDirs(si, dsName, vmname)

            # Create new VM
            connect.SetSi(si)
            theVm = None
            if useExistingVm:
                theVm = folder.Find(vmname)
                if theVm == None:
                    raise Exception("No VM with name %s found!" % vmname)
                Log("Using VM %s" % vmname)
            else:
                Log("Creating VM %s" % vmname)
                # Short delay to avoid colliding with a cleanup.
                time.sleep(1)
                # XXX numScsiDisks=0. vm.Migrate() doesn't know about
                # xvmotion, so it fails to set up the disk copy spec
                theVm = vm.CreateQuickDummy(vmname,
                                            guest="winXPProGuest",
                                            memory=4,
                                            cdrom=0,
                                            numScsiDisks=0,
                                            datastoreName=dsName)

            if theVm.GetRuntime().GetPowerState() == PowerState.poweredOff:
                Log("Powering on VM.")
                vm.PowerOn(theVm)
            else:
                Log("VM already powered on.")

            srcDir = os.path.dirname(theVm.config.files.vmPathName)

            tests = [
                TestVmxFailTo,
                TestVmxFailToEvent,
                TestVmxFailInit,
                TestVmxFailFrom,
                TestVmxFailPrepareDst,
                TestVmxFailStart,
                TestVmxSuccess,  # Must be last: does not switch back to source
            ]
            for testClass in tests:
                Log("Creating dummy dest")
                dstPath = os.path.join(srcDir, testClass.name, vmname + ".vmx")
                dummySpec = vm.CreateQuickDummySpec(vmname,
                                                    guest="winXPProGuest",
                                                    memory=4,
                                                    cdrom=0,
                                                    numScsiDisks=0,
                                                    datastoreName=dsName)
                dummySpec.GetFiles().SetVmPathName(dstPath)
                dstVm = vm.CreateFromSpec(dummySpec)

                # Core of running an individual test
                theTest = testClass(theVm, dstVm)
                theTest.setup()
                Log("Attempt to vMotion with test '%s'" % str(theTest))
                try:
                    vm.Migrate(theVm,
                               si,
                               si,
                               vmotionType='vmotion',
                               unsharedSwap=True,
                               dstPath=dstPath)
                except Exception as e:
                    theTest.gotFailure(e)
                else:
                    theTest.gotSuccess()
                theTest.cleanup()

            if not useExistingVm:
                CleanupVm(vmname)
        except Exception as e:
            Log("Caught exception : %s" % e)
            excType, excValue, excTB = sys.exc_info()
            stackTrace = " ".join(
                traceback.format_exception(excType, excValue, excTB))
            Log(stackTrace)
            status = "FAIL"
            Disconnect(si)
            if IsTestEsx():
                ReportFiles('/vmfs/volumes/%s/%s' % (dsName, vmname))
            return
        if status == "PASS" and IsTestEsx(
        ) and 'test-esx-vmotionErrs' in vmname:
            CleanDirs(si, dsName, vmname)
        Disconnect(si)