Exemplo n.º 1
0
def TestHotPlugCpu(vm1, add, positive, opLabel):
    Log("Testing CPU hot " + opLabel + " for VM " + vm1.GetConfig().GetName())
    curCpu = vm1.GetConfig().GetHardware().GetNumCPU()
    newCpu = curCpu
    if add:
        newCpu += 1
    else:
        newCpu -= 1

    # Check for a valid CPU count
    if newCpu == 0:
        raise Exception("Cpu count cannot be zero")
    Log("Current cpu count : " + str(curCpu))

    # Making sure that hot plug cpu is not enabled
    Log("Powering off VM")
    vm.PowerOff(vm1)
    cspec = Vim.Vm.ConfigSpec()
    if add:
        cspec.SetCpuHotAddEnabled(False)
    else:
        cspec.SetCpuHotRemoveEnabled(False)
    vm.Reconfigure(vm1, cspec)
    Log("Powering on the VM")
    vm.PowerOn(vm1)

    # Negative test case - changing CPU count when not allowed
    Log("Attempting to change CPUs without setting enabled flag")
    ChangeCpu(vm1, newCpu, False)

    # Enabling CPU hot add/remove on the VM
    Log("Powering off VM")
    vm.PowerOff(vm1)
    Log("Enabling cpu hot plug")
    cspec = Vim.Vm.ConfigSpec()
    if add:
        cspec.SetCpuHotAddEnabled(True)
    else:
        cspec.SetCpuHotRemoveEnabled(True)
    vm.Reconfigure(vm1, cspec)
    Log("Powering on the VM")
    vm.PowerOn(vm1)

    # Verify reported CPU hot-plug enabled settings
    Log("Verifying if cpu hot plug enabled is populated")
    cfgInfo = vm1.GetConfig()
    if add and cfgInfo.GetCpuHotAddEnabled() != True or \
    (not add and cfgInfo.GetCpuHotRemoveEnabled() != True) :
        raise Exception("Cpu hot plug enabled not set correctly!")

    # Test CPU hot-plug
    ChangeCpu(vm1, newCpu, positive)
    if not positive:
        return
    curCpu = vm1.GetConfig().GetHardware().GetNumCPU()
    if curCpu != newCpu:
        raise Exception("Cpu count " + str(curCpu) + " not equal to " +
                        str(newCpu))
Exemplo n.º 2
0
 def testPowerCycle(self):
     vm.PowerOn(self.v1)
     time.sleep(2)
     vm.Suspend(self.v1)
     time.sleep(2)
     vm.PowerOn(self.v1)
     time.sleep(2)
     vm.Reset(self.v1)
     time.sleep(2)
     vm.PowerOff(self.v1)
     time.sleep(2)
Exemplo n.º 3
0
def powerOnVM(virtualMachine):
   vm.PowerOn(virtualMachine);
   while True:
      Log("Waiting for VM to get powered on");
      if virtualMachine.GetRuntime().GetPowerState() == Vim.VirtualMachine.PowerState.poweredOn:
         break
      time.sleep(3)
Exemplo n.º 4
0
def normalScene(vm1, numdisks, ctlrKeys, storage):
    AddDisks(vm1, 15, ctlrKeys)
    Log("Added 15 disks successfully")

    try:
        AddDisks(vm1, 16, ctlrKeys[:1])
    except Exception as e:
        Log("Hit an exception on add more than 15 disks as expected" + str(e))
    else:
        raise Exception(
            "Error: should not allow more than 15 disks by default")

    numCtlrs = len(ctlrKeys)
    for i in range(numCtlrs):
        advCfgKey = "scsi" + str(i) + ".maxTargets"
        SetExtraConfig(vm1, advCfgKey, "255")

    Log("Update maxTargets successfully")

    if numdisks < 16:
        numdisk = 1  # add one more disks for fun
    else:
        numdisks = numdisks - 15

    AddDisks(vm1, numdisks, ctlrKeys, 16, datastore=storage)
    if vm1.runtime.powerState != Vim.VirtualMachine.PowerState.poweredOn:
        vm.PowerOn(vm1)
    Log("Successfully added all disks")

    vm.PowerOff(vm1)
Exemplo n.º 5
0
def PowerOff(vm1):
    try:
        print "Power off"
        vm.PowerOn(vm1)
        time.sleep(5)
    except:
        pass
Exemplo n.º 6
0
def TestEditSataCdrom(vm1):
    """
    Test reconfigures of SATA cdroms
    """
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddSataCtlr(cspec)
    vm.Reconfigure(vm1, cspec)

    Log("Add SATA cdrom.")
    AddSataCdrom(vm1)

    Log("Reconfigure cdrom backing.")
    TestReconfigCdromBacking(vm1)

    Log("Snapshot VM and revert to snapshot.")
    TestSnapshotCdrom(vm1)

    Log("Moving cdrom from SATA to IDE controller.")
    ideCtlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualIDEController)
    cdrom = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualCdrom)[0]
    TestMoveDevice(vm1, cdrom, ideCtlrs[0])

    Log("Remove cdrom.")
    RemoveSataCdrom(vm1)

    Log("Testing hot-add and hot-remove of SATA cdrom.")
    vm.PowerOn(vm1)
    AddSataCdrom(vm1)
    RemoveSataCdrom(vm1)
    vm.PowerOff(vm1)

    ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualSATAController)
    vm.RemoveDevice(vm1, ctlrs[0])
Exemplo n.º 7
0
def TestVQATReconfig(vm1):
    """
   Test add and remove for VQAT controller
   """
    Log("Adding VQAT")
    cspec = vim.vm.ConfigSpec()
    for i in range(MAX_QAT_DEV):
        AddVQAT(cspec)
    vm.Reconfigure(vm1, cspec)
    CheckQATPresent(vm1, MAX_QAT_DEV)

    TestAdd5thQAT(vm1)
    TestVQATRemoveInvalid(vm1)
    CheckQATPresent(vm1, MAX_QAT_DEV)
    TestVQATMove(vm1, -1)
    TestVQATMove(vm1, QAT_DEV_KEY)
    TestVQATMove(vm1, 100)

    vm.PowerOn(vm1)
    try:
        TestVQATRemoveInvalid(vm1)
        TestVQATHotRemove(vm1)
    finally:
        vm.PowerOff(vm1)
    # Remove QAT controller from VM
    Log("Removing QAT devices from VM")
    for i in range(MAX_QAT_DEV):
        RemoveDev(vm1, CreateVQAT(QAT_DEV_KEY + i))
    CheckQATNotPresent(vm1)
Exemplo n.º 8
0
def TestVTPMReconfig(vm1):
    """
    Test add and remove for vTPM controller
    """
    Log("Adding vTPM")
    cspec = vim.vm.ConfigSpec()
    AddVTPM(cspec)
    vm.Reconfigure(vm1, cspec)
    CheckTPMPresent(vm1)
    TestAdd2ndTPM(vm1)
    TestVTPMRemoveInvalid(vm1)
    CheckTPMPresent(vm1)
    TestVTPMMove(vm1, -1)
    TestVTPMMove(vm1, TPM_DEV_KEY)
    TestVTPMMove(vm1, 100)
    TestVTPMProps(vm1)

    vm.PowerOn(vm1)
    try:
        TestVTPMProps(vm1)
        TestVTPMRemoveInvalid(vm1)
        TestVTPMHotRemove(vm1)
    finally:
        vm.PowerOff(vm1)
    # Remove TPM controller from VM
    Log("Removing TPM device from VM")
    TestVTPMRemoveDev(vm1, CreateVTPM(TPM_DEV_KEY))
Exemplo n.º 9
0
    def __init__(self,
                 vmIn,
                 vStorageObject,
                 datastore,
                 fullTest=True,
                 powerOn=False):
        if not vmIn:
            self.vm = createDummyVm(datastore.name)
        else:
            self.vm = vmIn
            Logger("VMTest, vm = %s\n" % (self.vm.name))
        self.vsobj = vStorageObject
        self.ds = datastore
        self.fullTest = fullTest

        if self.vm != vm1 and not fullTest:
            # VM with one scsi controller and disk
            cspec = Vim.Vm.ConfigSpec()
            cspec = vmconfig.AddScsiCtlr(cspec, cfgInfo=self.vm.config)
            capacityKB = 10 * 1024
            # Add eager-zeroed disk so it can be enabled multi-writter
            vmconfig.AddScsiDisk(cspec,
                                 cfgInfo=self.vm.config,
                                 capacity=capacityKB,
                                 datastorename=self.ds.name,
                                 thin=False,
                                 scrub=True)
            InvokeAndTrack(self.vm.Reconfigure, cspec)

        if powerOn:
            Logger("Powering on VM ")
            vm.PowerOn(self.vm)
            time.sleep(2)
Exemplo n.º 10
0
def TestSataCtlrReconfig(vm1):
    """
    Test add and remove for SATA controller
    """
    Log("Adding SATA controller to VM")
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddSataCtlr(cspec, cfgInfo = vm1.config)
    vm.Reconfigure(vm1, cspec)

    # Check for controller presence in VM's config
    ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualAHCIController)
    if len(ctlrs) != 1:
       raise Exception("Failed to find added SATA controller :" + str(len(ctlrs)))

    Log("Powering on VM " + vm1.config.GetName())
    vm.PowerOn(vm1)

    Log("Hot-add SATA controller to VM")
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddSataCtlr(cspec, cfgInfo = vm1.config)
    vm.Reconfigure(vm1, cspec)

    ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualAHCIController)
    if len(ctlrs) != 2:
       raise Exception("Failed to find added SATA controller :" + str(len(ctlrs)))

    vm.PowerOff(vm1)
    # Remove SATA controller from VM
    Log("Removing SATA controllers from VM")
    cspec = Vim.Vm.ConfigSpec()
    vmconfig.AddDeviceToSpec(cspec, ctlrs[0], Vim.Vm.Device.VirtualDeviceSpec.Operation.remove)
    vmconfig.AddDeviceToSpec(cspec, ctlrs[1], Vim.Vm.Device.VirtualDeviceSpec.Operation.remove)
    vm.Reconfigure(vm1, cspec)
Exemplo n.º 11
0
def main():
    """
   Simple command-line program for creating virtual machines on a
   system managed by hostd.
   """

    options = GetOptions()

    Connect(host=options.host, user=options.user, pwd=options.password)

    # Create vms
    envBrowser = GetEnv()
    cfgOption = envBrowser.QueryConfigOption(None, None)
    cfgTarget = envBrowser.QueryConfigTarget(None)
    for i in range(int(options.num_iterations)):
        vm1 = vm.CreateQuickDummy(options.vm_name + "_" + str(i),
                                  options.num_scsi_disks,
                                  options.num_ide_disks,
                                  datastoreName=options.datastore_name,
                                  cfgOption=cfgOption,
                                  cfgTarget=cfgTarget)

        for _ in range(int(options.num_power_cycles)):
            clock = StopWatch()
            vm.PowerOn(vm1)
            clock.finish("PowerOn done")
            clock = StopWatch()
            vm.PowerOff(vm1)
            clock.finish("PowerOff done")

        # Delete the vm as cleanup
        if not options.dont_delete:
            task = vm1.Destroy()
            WaitForTask(task)
Exemplo n.º 12
0
def PowerCycle(vm1):
   Log("Powercycle (on)")
   vm.PowerOn(vm1)
   time.sleep(2)
   Log("Powercycle (off)")
   vm.PowerOff(vm1)
   time.sleep(2)
Exemplo n.º 13
0
def TestVWDTReconfig(vm1):
    """
    Test add and remove for vWDT controller
    """
    Log("Adding vWDT")
    cspec = vim.vm.ConfigSpec()
    AddVWDT(cspec)
    vm.Reconfigure(vm1, cspec)
    CheckWDTPresent(vm1)
    TestAdd2ndWDT(vm1)
    TestVWDTRemoveInvalid(vm1)
    CheckWDTPresent(vm1)
    TestVWDTReplaceKey(vm1, -1)
    TestVWDTReplaceKey(vm1, WATCHDOGTIMER_DEV_KEY)
    TestVWDTReplaceKey(vm1, 100)

    vm.PowerOn(vm1)
    try:
        TestVWDTRemoveInvalid(vm1)
        TestVWDTHotRemove(vm1)
    finally:
        vm.PowerOff(vm1)
    # Remove vWDT controller from VM
    Log("Removing watchdog timer from VM")
    TestVWDTRemoveDev(vm1, CreateVWDT(WATCHDOGTIMER_DEV_KEY))
Exemplo n.º 14
0
def RunCreateTest(name):
    vm1 = vm.CreateQuickDummy(name)
    vm.PowerOn(vm1)
    vm.PowerOff(vm1)
    cfgPath = vm1.GetConfig().GetFiles().GetVmPathName()
    vm1.Unregister()
    folder.Register(cfgPath)
    vm.Destroy(vm1)
Exemplo n.º 15
0
   def TestVmMigrate(self):
      self.banner(self.TestVmMigrate)

      if len(self._hosts) <= 1:
         VerboseLog(logInfo,"not enough hosts..skipping")

      vmname = "test_migrate_vvol_vm"
      self.CleanupVm(vmname)
      host1 = self._hosts[0]
      host2 = self._hosts[1]

      scId = self._sc
      spec = Vim.Host.DatastoreSystem.VvolDatastoreSpec()
      spec.SetScId(scId)
      spec.SetName("vvol-test-ds:%s" % random.randint(1,1000))

      ret=True
      try:
         VerboseLog(logTrivia, "{ Creating bulk: ")
         create_task = self._vasaMgr.CreateVVolDatastore(spec, self._hosts)
         task.WaitForTask(create_task)
         VerboseLog(logVerbose, create_task.info.result)
         for result in create_task.info.result :
            if result.result == 'fail':
               VerboseLog(logInfo, "create failed for host " + result.hostKey)
               raise Exception("unexpected failure")

         ds = create_task.info.result[0].ds;
         testvm = vm.CreateQuickDummy(vmname,
                                      host=host1,
                                      datastoreName=ds.name,
                                      dc=self._dc.name,
                                      numScsiDisks=1,
                                      memory=12)

         vm.PowerOn(testvm)

         migrate_task = testvm.Migrate(host2.parent.resourcePool, host2, Vim.VirtualMachine.MovePriority.highPriority, None)
         task.WaitForTask(migrate_task)

         vm.PowerOff(testvm)
         vm.Destroy(testvm)

         VerboseLog(logTrivia, "{ Removing bulk: ")
         delete_task = self._vasaMgr.RemoveVVolDatastore(ds, self._hosts)
         task.WaitForTask(delete_task)
         VerboseLog(logVerbose, delete_task.info.result)
         for result in delete_task.info.result :
            if result.result == 'fail':
               VerboseLog(logInfo, "remove failed for host " + result.hostKey)
               raise Exception("unexpected failure in bulk remove")

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

      VerboseLog(logInfo, "passed" if ret else "failed");
Exemplo n.º 16
0
 def on(self):
     try:
         for vmIter in self.vmList:
             vm.PowerOn(vmIter)
         self.success = True
         print self.getClientId() + " on successful"
     except:
         print self.getClientId() + " on failed"
         self.success = False
Exemplo n.º 17
0
def TestNoVQAT(vm1):
    """
   Test that hot-add of VQAT fails
   """
    CheckQATNotPresent(vm1)
    TestNoVQATRemove(vm1)
    vm.PowerOn(vm1)
    try:
        TestNoVQATRunning(vm1)
    finally:
        vm.PowerOff(vm1)
Exemplo n.º 18
0
def poweredOnScene(vm1, numdisks, ctlrKeys, storage):
    if numdisks > 15:
        numCtlrs = len(ctlrKeys)
        for i in range(numCtlrs):
            advCfgKey = "scsi" + str(i) + ".maxTargets"
            SetExtraConfig(vm1, advCfgKey, "255")
        Log("Update maxTargets successfully")

    vm.PowerOn(vm1)
    AddDisks(vm1, numdisks, ctlrKeys, -1, datastore=storage)
    vm.PowerOff(vm1)
Exemplo n.º 19
0
def TestNoVTPM(vm1):
    """
    Test that hot-add of vTPM fails
    """
    CheckTPMNotPresent(vm1)
    TestNoVTPMRemove(vm1)
    vm.PowerOn(vm1)
    try:
        TestNoVTPMRunning(vm1)
    finally:
        vm.PowerOff(vm1)
Exemplo n.º 20
0
def getObjMapping(vmName, desc):
    Log("\nCreating VM object ID map on %s\n" % (desc))
    vmRef = CreateQuickDummy(vmName, datastoreName=vvolDsName, \
                             vmxVersion="vmx-13")

    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddScsiCtlr(cspec, cfgInfo=vmRef.config)
    capacityKB = 5 * 1024
    vmconfig.AddScsiDisk(cspec,
                         cfgInfo=vmRef.config,
                         capacity=capacityKB,
                         datastorename=vvolDsName,
                         thin=True,
                         scrub=False)
    InvokeAndTrack(vmRef.Reconfigure, cspec)

    vmRefs.append(vmRef)

    vm.PowerOn(vmRef)

    ssName = ("ss-%s" % random.randint(1, 1000))
    vm.CreateSnapshot(vmRef, ssName, "snaphost", memory=True, quiesce=False)

    global dstVmxId
    dstVmxId = []

    vmMap = {}
    for f1 in vmRef.layoutEx.file:
        if f1.type == "config":
            lastIdx = f1.name.rfind(".")

            lastIdx1 = f1.name.rfind("/")
            uuid = f1.name[f1.name.rfind("rfc4122."):lastIdx1]

        elif f1.backingObjectId:
            lastIdx = f1.name.rfind(".")
            uuid = f1.backingObjectId

        else:
            continue

        fname = vmName + f1.name[lastIdx:]
        vmMap[fname] = uuid
        Log("\n   adding %s - %s\n" % (fname, uuid))

        if fname.find(".vmx") != -1:
            dstVmxId.append(uuid)

    # Unregister VM to assume only vvol objects exists
    vm.PowerOff(vmRef)
    vmRef.Unregister()

    return vmMap
Exemplo n.º 21
0
def TestIllegalOptions(vm1):
    bldType = os.environ.get('VMBLD', '') or os.environ.get('BLDTYPE', '')
    if bldType != 'obj':
        Log('Test require obj build')
        return vm1
    vmname = vm1.GetSummary().GetConfig().GetName()
    cfg = vm1.GetSummary().GetConfig().GetVmPathName()
    vm.CreateSnapshot(vm1, "backup", "backup", False, False)
    for v in ['', ' with reload']:
        Log('Testing illegal config file modification%s' % v)
        for i in range(3):
            illegalOpt = Vim.Option.OptionValue(
                key='vmx.test.sandbox.illegalOption', value=str(i))
            nthWriteOpt = Vim.Option.OptionValue(
                key='vmx.test.sandbox.nthWrite', value='%d' % (2 + i))
            cspec = Vim.Vm.ConfigSpec(extraConfig=[nthWriteOpt, illegalOpt])
            task = vm.Reconfigure(vm1, cspec)
            vm.PowerOn(vm1)
            if v == ' with reload':
                try:
                    vm1.Reload()
                except:
                    Log('Illegal options detected before Reload')
                    pass
            time.sleep(10)
            if vm1.runtime.powerState != Vim.VirtualMachine.PowerState.poweredOff:
                raise Exception(
                    'VM unexpectedly still powered on (option %d)' % i)
            try:
                vm.PowerOn(vm1)
                raise Exception('PowerOn is allowed unexpectedly (option %d)' %
                                i)
            except:
                pass
            vm1.Unregister()
            folder.Register(cfg)
            vm1 = folder.Find(vmname)
            vm.RevertToCurrentSnapshot(vm1)
    return vm1
Exemplo n.º 22
0
    def SetupOtherHost(self):
        print(self._host + " " + self._user + " " + self._pwd)
        siOther = SmartConnect(host=self._host, user=self._user, pwd=self._pwd)
        self._vm = vm.CreateQuickDummy(self._vmName,
                                       numScsiDisks=1,
                                       datastoreName=self._ds)
        if self._vm == None:
            raise "Failed to create VM with specified video ram size"

        Log("Other Host: Power On VM")
        vm.PowerOn(self._vm)
        Log("Other Host: Take Snapshot (no memory)")
        vm.CreateSnapshot(self._vm, "pre vdm snap", "Pre VDM snapshot", False,
                          False)
Exemplo n.º 23
0
def suspendedScene(vm1, numdisks, ctlrKeys, storage):
    numCtlrs = len(ctlrKeys)
    for i in range(numCtlrs):
        advCfgKey = "scsi" + str(i) + ".maxTargets"
        SetExtraConfig(vm1, advCfgKey, "255")
    Log("Update maxTargets successfully")

    vm.PowerOn(vm1)
    vm.Suspend(vm1)
    try:
        AddDisks(vm1, numdisks, ctlrKeys, 0, datastore=storage)
    except Exception as e:
        Log("Testing rollback hit an exception as expected" + str(e))
    else:
        raise Exception("Error: should not allow passing suspended scene")
Exemplo n.º 24
0
def TestHotPlugMemory(vm1, positive):
    Log("Testing memory hot add for VM " + vm1.GetConfig().GetName())
    curMB = vm1.GetConfig().GetHardware().GetMemoryMB()
    newMB = curMB + 30
    Log("Current memory: " + str(curMB) + " MB.")

    # Negative test case - changes memory when not allowed
    Log("Attempting to hot-add memory without setting enabled flag")
    ChangeMemory(vm1, newMB, False)

    # Enable memory hot add on VM
    Log("Powering off VM")
    vm.PowerOff(vm1)
    Log("Enabling memory hot add")
    cspec = Vim.Vm.ConfigSpec()
    cspec.SetMemoryHotAddEnabled(True)
    vm.Reconfigure(vm1, cspec)
    Log("Powering on the VM")
    vm.PowerOn(vm1)

    # Verify if memory values are reported correctly for the VM
    if positive:
        Log("Verifying if maxMemory and increment size are populated")
        cfgInfo = vm1.GetConfig()
        curMB = cfgInfo.GetHardware().GetMemoryMB()
        memGrow = cfgInfo.GetHotPlugMemoryIncrementSize()
        memLimit = cfgInfo.GetHotPlugMemoryLimit()
        memEnabled = cfgInfo.GetMemoryHotAddEnabled()
        Log("Memory enabled: " + str(memEnabled) + " Memory limit: " +
            str(memLimit) + " Memory grow step: " + str(memGrow))
        if not memEnabled or memLimit == None or memGrow == None:
            raise Exception("Memory values not being populated correctly.")
        newMB = curMB + memGrow

    # Test memory hot add
    Log("Testing hot add of memory")
    ChangeMemory(vm1, newMB, positive)
    if not positive:
        return
    curMB = vm1.GetConfig().GetHardware().GetMemoryMB()
    if curMB != newMB:
        raise Exception("Memory after hot-add: " + str(curMB) + " MB.")

    # Test some negative test cases
    Log("Testing invalid grow step")
    ChangeMemory(vm1, newMB + memGrow + 1, False)
    Log("Testing add of memory beyond published maximum")
    ChangeMemory(vm1, memLimit + 1, False)
Exemplo n.º 25
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)
Exemplo n.º 26
0
def main():
    """
   Simple command-line program for creating virtual machines on a
   system managed by hostd.
   """

    options = GetOptions()

    Connect(host=options.host,
            user=options.user,
            namespace=newestVersions.GetNamespace('vim'),
            pwd=options.password)

    # Create vms
    envBrowser = GetEnv()
    cfgOption = envBrowser.QueryConfigOption(None, None)
    cfgTarget = envBrowser.QueryConfigTarget(None)

    for i in range(int(options.num_iterations)):
        vm1 = vm.CreateQuickDummy(options.vm_name + "_" + str(i),
                                  options.num_scsi_disks,
                                  options.num_ide_disks,
                                  datastoreName=options.datastore_name,
                                  cfgOption=cfgOption,
                                  cfgTarget=cfgTarget)

        if options.opaquenetwork_id:
            config = Vim.Vm.ConfigSpec()
            config = vmconfig.AddOpaqueNetwork(config, cfgOption, opaqueNetworkId=options.opaquenetwork_id, \
                                               opaqueNetworkType=options.opaquenetwork_type, \
                                               externalId=options.externalID)
            vm.Reconfigure(vm1, config)

        for _ in range(int(options.num_power_cycles)):
            clock = StopWatch()
            vm.PowerOn(vm1)
            clock.finish("PowerOn done")
            clock = StopWatch()
            vm.PowerOff(vm1)
            clock.finish("PowerOff done")

        # Delete the vm as cleanup
        if not options.dont_delete:
            task = vm1.Destroy()
            WaitForTask(task)
Exemplo n.º 27
0
def TogglePowerOp(toggle):
    """ Power On/Off a given VM """
    vm = GetVmByName(_vmName)
    if vm == None:
       print "Unable to find VM", _vmName
       return(1)   

    if toggle == "on":
	print "== Powering On VM"
	task = vm.PowerOn(None)
	if WaitForTask(task) == "error":
	    return(1)
	return(0)	
    else:
	print "== Powering Off VM"
	task = vm.PowerOff()
        if WaitForTask(task) == "error":
	    return(1)
	return(0)
Exemplo n.º 28
0
def TestEditSataDisk(vm1):
    """
    Test reconfigures of SATA disks
    """
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddSataCtlr(cspec)
    cspec = vmconfig.AddScsiCtlr(cspec)
    vm.Reconfigure(vm1, cspec)

    Log("Add SATA disk.")
    AddSataDisk(vm1)

    Log("Reconfigure disk capacity.")
    TestExtendDisk(vm1)

    Log("Snapshot and reconfigure delta disk.")
    TestReconfigDeltaDisk(vm1)

    Log("Move SATA disk to SCSI controller.")
    scsiCtlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualSCSIController)
    if len(scsiCtlrs) < 1:
       raise Exception("Failed to find SCSI controller!")
    disk = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)[0]
    TestMoveDevice(vm1, disk, scsiCtlrs[0])

    Log("Move SCSI disk to SATA controller.")
    ctlrs = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualSATAController)
    disk = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)[0]
    TestMoveDevice(vm1, disk, ctlrs[0])
    vm.RemoveDevice(vm1, scsiCtlrs[0])

    Log("Remove SATA disk.")
    RemoveSataDisk(vm1);

    Log("Testing hot-add and hot-remove of SATA disk.")
    vm.PowerOn(vm1)
    AddSataDisk(vm1)
    RemoveSataDisk(vm1);
    vm.PowerOff(vm1)

    vm.RemoveDevice(vm1, ctlrs[0])
Exemplo n.º 29
0
def init(hostname, user, passwd, vmname, vmxpath, guestuser, guestpwd,
         guestrootuser, guestrootpassword, powerOn=True, getIntCont=False):
   # Connect and get the Service Instance.
   # Make sure we get the proper version (dev).
   svcInst = SmartConnect(host=hostname, user=user, pwd=passwd)
   svcInstIntCont = ""
   if getIntCont:
      svcInstIntCont = svcInst.RetrieveInternalContent()

   # Find the vm if it's there.
   virtualMachine = folder.Find(vmname)

   # if it's not there, maybe we just rebooted and it lost its config,
   # so try to register and re-find.
   if virtualMachine == None:
      Log("Registering " + vmxpath)
      folder.Register(vmxpath)
      virtualMachine = folder.Find(vmname)

   # set up a guest auth object with root privs
   guestAdminAuth = ""
   if guestrootuser != "":
      guestAdminAuth = npAuth(username=guestrootuser, password=guestrootpassword,
                              interactiveSession=False)

   # set up a guest auth object (good and bad)
   guestAuth = npAuth(username=guestuser, password=guestpwd, interactiveSession=False)

   guestAuthBad = npAuth(username="******", password="******", interactiveSession=False)

   # power on the VM if needed
   if powerOn and virtualMachine.GetRuntime().GetPowerState() != Vim.VirtualMachine.PowerState.poweredOn:
      Log("Powering on")
      vm.PowerOn(virtualMachine)

   if not getIntCont:
      globs = [svcInst, virtualMachine, guestAdminAuth, guestAuth, guestAuthBad]
   else:
      globs = [svcInst, svcInstIntCont, virtualMachine, guestAdminAuth, guestAuth, guestAuthBad]

   return globs
Exemplo n.º 30
0
def testAddDisk(options, online, shared):
    name = getUniqueVmName()
    machine = folder.Find(name)
    if machine: vm.Destroy(machine)
    machine = vm.CreateQuickDummy(name,
                                  datastoreName=options.datastore,
                                  scsiCtlrs=1)
    Log("CreateVM(%s, %s)" % (name, options.datastore))

    if online:
        vm.PowerOn(machine)
        Log("PowerOn(%s)" % machine.name)

    addFlatDisk(options, machine, shared)
    addRdmDisk(options, machine, shared)

    if online:
        vm.PowerOff(machine)
        Log("PowerOff(%s)" % machine.name)

    vm.Destroy(machine)