Exemplo n.º 1
0
 def revert(vmname):
     context = None
     if inputs['ignore_ssl'] and hasattr(ssl, "_create_unverified_context"):
         context = ssl._create_unverified_context()
     si = connect.Connect(inputs['vcenter_ip'],
                          443,
                          inputs['vcenter_user'],
                          inputs['vcenter_password'],
                          sslContext=context)
     atexit.register(Disconnect, si)
     content = si.RetrieveContent()
     vm_name = vmname
     vm = get_obj(content, [vim.VirtualMachine], vm_name)
     if not vm:
         raise Exception("Virtual Machine %s doesn't exists" % vm_name)
     snapshot_name = inputs['snapshot_name']
     snap_obj = get_snapshots_by_name_recursively(
         vm.snapshot.rootSnapshotList, snapshot_name)
     if len(snap_obj) == 1:
         snap_obj = snap_obj[0].snapshot
         WaitForTask(snap_obj.RevertToSnapshot_Task())
         WaitForTask(vm.PowerOn())
     else:
         raise Exception(("No snapshots found with name: %s on VM: %s" %
                          (snapshot_name, vm.name)))
     return
Exemplo n.º 2
0
def main():
    supportedArgs = [(["s:", "host="], "localhost", "host name", "host"),
                     (["u:", "user="******"root", "User name", "user"),
                     (["p:", "pwd="], "", "Password", "pwd")]

    supportedToggles = [(["usage",
                          "help"], False, "Show usage information", "usage")]

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

    si = SmartConnect(host=args.GetKeyValue('host'),
                      user=args.GetKeyValue('user'),
                      pwd=args.GetKeyValue('pwd'))

    vm = CreateQuickDummy('vm-for-hostlog', numScsiDisks=1)
    try:
        disk = CheckDevice(vm.config, vim.vm.device.VirtualDisk)[0]
        diskName = disk.backing.fileName
        for dsUrl in vm.config.datastoreUrl:
            diskName = diskName.replace('[%s] ' % dsUrl.name, dsUrl.url + '/')
        hostlogOption = vim.option.OptionValue(key='migrate.hostlog',
                                               value=diskName)
        spec = vim.vm.ConfigSpec(extraConfig=[hostlogOption])
        WaitForTask(vm.Reconfigure(spec))
    except vmodl.fault.InvalidArgument as e:
        print("Hit %s as expected" % e)
    else:
        raise Exception("Failed to hit Reconfigure error changing hostlog")
    finally:
        WaitForTask(vm.Destroy())
Exemplo n.º 3
0
def TestNegVMCIDevice(vm1, isVMCIDefault):
    if not isVMCIDefault:
        devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                       Vim.Vm.Device.VirtualVMCIDevice)
        if len(devices) != 0:
            raise Exception("VMCI device found by default in VM")
        return
    failure = False
    Log("Adding new VMCI device to a VM")
    try:
        cspec = Vim.Vm.ConfigSpec()
        cpsec = vmconfig.AddVMCI(cspec)
        task = vm1.Reconfigure(cspec)
        WaitForTask(task)
    except Exception as e:
        Log("Verified request was rejected as expected.")
        failure = True
    if not failure:
        raise Exception("Adding VMCI device to VM was allowed!")

    Log("Attempt to remove VMCI device from VM")
    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualVMCIDevice)
    cspec = Vim.Vm.ConfigSpec()
    cpsec = vmconfig.RemoveDeviceFromSpec(cspec, devices[0])
    try:
        task = vm1.Reconfigure(cspec)
        WaitForTask(task)
    except Exception as e:
        Log("Verified request was rejected as expected.")
        return
    raise Exception("Did not hit an exception as expected")
Exemplo n.º 4
0
def CreateMultipleSoundCards(vm1):
    ## Test 6. Create two sound cards and verify the operation fails
    success = False
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddSoundCard(cspec, autodetect=False, type="ensoniq")
    cspec = vmconfig.AddSoundCard(cspec, autodetect=False, type="sb16")
    try:
        task = vm1.Reconfigure(cspec)
        WaitForTask(task)
    except Vim.Fault.TooManyDevices as e:
        success = True

    if success == True:
        success = False
        cspec = Vim.Vm.ConfigSpec()
        cspec = vmconfig.AddSoundCard(cspec, autodetect=False, type="ensoniq")
        try:
            task = vm1.Reconfigure(cspec)
            WaitForTask(task)
        except Vim.Fault.TooManyDevices as e:
            success = True

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualSoundCard)
    if len(devices) != 0:
        raise "Found sound card though operation should have failed!!"

    if (success == True):
        print("Successful failing to create 2 sound devices")
    else:
        print("Apparently didnt see expected exceptions")
Exemplo n.º 5
0
def ModifyVmfs(vmfs, mount):
   if mount:
      bt = time.time()
      task = storageSystem.MountVmfsVolumeEx([mnt.volume.uuid for mnt in vmfs])
      WaitForTask(task)
      print("Mount" + " " + str(len(vmfs)) + " volumes in " + str(time.time() - bt) + " sec")
      return task.info.result
   else:
      bt = time.time()
      task = storageSystem.UnmountVmfsVolumeEx([mnt.volume.uuid for mnt in vmfs])
      WaitForTask(task)
      print("Unmount" + " " + str(len(vmfs)) + " volumes in " + str(time.time() - bt) + " sec")
      return task.info.result
Exemplo n.º 6
0
   def TestMove(self):
      pathA = self.CreateSingle("MoveTest")
      pathB = self.MakeDsPath("MoveTest_move")
      Log("  Moving: " + pathA + " -> " + pathB)
      task = self._vdm.MoveVirtualDisk(pathA, self._dc,
                                       pathB, self._dc, True)
      WaitForTask(task, True)

      Log("  Moving back: " + pathB + " -> " + pathA)
      task = self._vdm.MoveVirtualDisk(pathB, self._dc,
                                       pathA, self._dc, True)
      WaitForTask(task, True)

      self.DeleteSingle(pathA)
Exemplo n.º 7
0
def EditExistingEnsoniqToSetAndUnsetAutodetect(vm1):
    # Test 9. Edit an ensoniq device and toggle  the device autodetect setting
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddSoundCard(cspec, autodetect=True, type="ensoniq")
    task = vm1.Reconfigure(cspec)
    WaitForTask(task)

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualEnsoniq1371,
                                   {"backing.useAutoDetect": True})
    if len(devices) != 1:
        raise "Failed to find added sound card"

    cspec = Vim.Vm.ConfigSpec()
    dev = devices[0]
    backing = dev.GetBacking()
    backing.SetUseAutoDetect(False)
    backing.SetDeviceName(
        vmconfig.GetDeviceName(None,
                               vmconfig.GetCfgTarget(None).GetSound))
    dev.SetBacking(backing)
    vmconfig.AddDeviceToSpec(cspec, dev,
                             Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
    task = vm1.Reconfigure(cspec)
    WaitForTask(task)

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualEnsoniq1371,
                                   {"backing.useAutoDetect": False})
    if len(devices) != 1:
        raise "Failed to find added sound card"

    cspec = Vim.Vm.ConfigSpec()
    dev = devices[0]
    backing = dev.GetBacking()
    backing.SetUseAutoDetect(True)
    dev.SetBacking(backing)
    vmconfig.AddDeviceToSpec(cspec, dev,
                             Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
    task = vm1.Reconfigure(cspec)
    WaitForTask(task)

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualEnsoniq1371,
                                   {"backing.useAutoDetect": True})
    if len(devices) != 1:
        raise "Failed to find added sound card"
    print("Toggling soundcard autodetect works!")
Exemplo n.º 8
0
def EditFloppySetAndUnsetAutodetect(vm1):
    # Test 9. Edit a floppy device and toggle the device autodetect setting
    cspec = Vim.Vm.ConfigSpec()
    cspec = vmconfig.AddFloppy(cspec, autodetect=True)
    task = vm1.Reconfigure(cspec)
    WaitForTask(task)

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualFloppy,
                                   {"backing.useAutoDetect": True})
    if len(devices) != 1:
        raise "Failed to find added floppy"

    cspec = Vim.Vm.ConfigSpec()
    dev = devices[0]
    backing = dev.GetBacking()
    backing.SetUseAutoDetect(False)
    backing.SetDeviceName(
        vmconfig.GetDeviceName(None,
                               vmconfig.GetCfgTarget(None).GetFloppy))
    dev.SetBacking(backing)
    vmconfig.AddDeviceToSpec(cspec, dev,
                             Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
    task = vm1.Reconfigure(cspec)
    WaitForTask(task)

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualFloppy,
                                   {"backing.useAutoDetect": False})
    if len(devices) != 1:
        raise "Failed to find added floppy"

    cspec = Vim.Vm.ConfigSpec()
    dev = devices[0]
    backing = dev.GetBacking()
    backing.SetUseAutoDetect(True)
    dev.SetBacking(backing)
    vmconfig.AddDeviceToSpec(cspec, dev,
                             Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
    task = vm1.Reconfigure(cspec)
    WaitForTask(task)

    devices = vmconfig.CheckDevice(vm1.GetConfig(),
                                   Vim.Vm.Device.VirtualFloppy,
                                   {"backing.useAutoDetect": True})
    if len(devices) != 1:
        raise "Failed to find added floppy"
    print("Toggling floppy autodetect works!")
Exemplo n.º 9
0
    def clone_vm(self):
        """ Clone VM from a previously created template,
        template_name == vm_name without last 3 digits """
        log.subtask("clone virtual machine")
        log.info("- source: {0}".format(self.template_name))
        log.info("- destination: {0}".format(self.name))

        template_vm = self.get_vm(isTemplate=True)
        if template_vm:
            self._check_media()

            vm_clone_spec = vim.vm.CloneSpec(location=vim.vm.RelocateSpec(
                datastore=self.datastore, pool=self.resource_pool),
                                             powerOn=False,
                                             template=False)

            task = template_vm.CloneVM_Task(folder=self.datacenter.vmFolder,
                                            name=self.name,
                                            spec=vm_clone_spec)

            try:
                log.info("cloning...")
                WaitForTask(task)
                self.vm_obj = self.get_vm(isTemplate=False)
                log.info("cloning succeeded")
            except Exception as e:
                quit("cloning failed: {0}".format(e))
        else:
            quit("template not found: {0}".format(self.template_name))
Exemplo n.º 10
0
def create_vm(si, vm_name, datacenter_name, host_ip, datastore_name=None):

    content = si.RetrieveContent()
    destination_host = pchelper.get_obj(content, [vim.HostSystem], host_ip)
    source_pool = destination_host.parent.resourcePool
    if datastore_name is None:
        datastore_name = destination_host.datastore[0].name

    config = create_config_spec(datastore_name=datastore_name, name=vm_name)
    for child in content.rootFolder.childEntity:
        if child.name == datacenter_name:
            vm_folder = child.vmFolder  # child is a datacenter
            break
    else:
        print("Datacenter %s not found!" % datacenter_name)
        sys.exit(1)

    try:
        WaitForTask(
            vm_folder.CreateVm(config, pool=source_pool,
                               host=destination_host))
        print("VM created: %s" % vm_name)
    except vim.fault.DuplicateName:
        print("VM duplicate name: %s" % vm_name, file=sys.stderr)
    except vim.fault.AlreadyExists:
        print("VM name %s already exists." % vm_name, file=sys.stderr)
Exemplo n.º 11
0
    def add_pci_device(self, vm, pci_device):
        """
        Attaches PCI device to VM

        Args:
            vm (vim.VirtualMachine): VM instance
            pci_device (vim.vm.PciPassthroughInfo): PCI device to add

        """
        host = vm.runtime.host.name
        logger.info(
            f"Adding PCI device with ID:{pci_device.pciDevice.id} on host {host} to {vm.name}"
        )
        deviceId = hex(pci_device.pciDevice.deviceId % 2**16).lstrip("0x")
        backing = vim.VirtualPCIPassthroughDeviceBackingInfo(
            deviceId=deviceId,
            id=pci_device.pciDevice.id,
            systemId=pci_device.systemId,
            vendorId=pci_device.pciDevice.vendorId,
            deviceName=pci_device.pciDevice.deviceName,
        )

        hba_object = vim.VirtualPCIPassthrough(key=-100, backing=backing)
        new_device_config = vim.VirtualDeviceConfigSpec(device=hba_object)
        new_device_config.operation = "add"

        vmConfigSpec = vim.vm.ConfigSpec()
        vmConfigSpec.memoryReservationLockedToMax = True
        vmConfigSpec.deviceChange = [new_device_config]
        WaitForTask(vm.ReconfigVM_Task(spec=vmConfigSpec))
Exemplo n.º 12
0
def main():
    args = get_args()

    # connect to vc
    si = SmartConnect(host=args.params['hostname'],
                      user=args.params['username'],
                      pwd=args.params['password'],
                      port=args.params['port'])
    # disconnect vc
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    print('Searching for VM {}').format(args.params['name'])
    vm = get_obj(content, [vim.VirtualMachine], args.params['name'])

    cdrom = get_vm_cdrom_device(vm)

    if cdrom is not None:  # Remove it
        deviceSpec = vim.vm.device.VirtualDeviceSpec()
        deviceSpec.device = cdrom
        deviceSpec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
        configSpec = vim.vm.ConfigSpec(deviceChange=[deviceSpec])
        WaitForTask(vm.Reconfigure(configSpec))

        msg = ('CDROM successfully')
        args.exit_json(msg=msg, changed=True)
    else:
        msg = ("CDROM not found")
        args.fail_json(msg=msg, changed=False)
Exemplo n.º 13
0
def main():
    args = get_args()
    si = SmartConnect(host=args.params['hostname'],
                      user=args.params['username'],
                      pwd=args.params['password'],
                      port=args.params['port'])
    if args.params['datacenter']:
        dc = get_dc(si, args.params['datacenter'])
    else:
        dc = si.content.rootFolder.childEntity[0]
    dc = si.content.rootFolder.childEntity[0]  # first datacenter
    searchIndex = si.content.searchIndex
    vm = searchIndex.FindChild(dc.vmFolder, args.params['name'])

    #  vm = si.content.searchIndex.FindChild(dc.vmFolder, args.params['name'])

    #cdrom = get_vm_cdrom_device(vm_obj=vm)
    cdroms = find_device(vm, vim.vm.device.VirtualCdrom)
    op = vim.vm.device.VirtualDeviceSpec.Operation

    if cdrom is not None:  # Remove it
        deviceSpec = vim.vm.device.VirtualDeviceSpec()
        deviceSpec.device = cdrom
        deviceSpec.operation = op.remove
        configSpec = vim.vm.ConfigSpec(deviceChange=[deviceSpec])
        WaitForTask(vm.Reconfigure(configSpec))
Exemplo n.º 14
0
 def ShowDiskInfo(self, path, includeParents=True):
    Log("VirtualDiskManager: show query disk info")
    Log("Query disk info for " + path)
    task = self._vdm.QueryVirtualDiskInfo(path, self._dc, includeParents)
    WaitForTask(task, True)
    diskInfos = task.info.result
    Log("Result = \n" + `diskInfos`)
Exemplo n.º 15
0
def UnmountVolumes():
    sw = StopWatch()
    task = storageSystem.UnmountVmfsVolumeEx(volumeUUIDs)
    WaitForTask(task)
    sw.finish(" unmount VMFS volumes")  #TODO add str(len(volumeUUIDs))
    time.sleep(
        60)  # rest a bit, in case un-expected things happens to do next op
Exemplo n.º 16
0
 def TestEagerZero(self):
    Log("VirtualDiskManager: Eagerzero test")
    path = self.CreateSingle("EagerZeroTest", "preallocated")
    Log("  EagerZeroing: " + path)
    task = self._vdm.EagerZeroVirtualDisk(path)
    WaitForTask(task, True)
    self.DeleteSingle(path)
Exemplo n.º 17
0
	def resetVM(self, vm):
		try:
			t = vm.ResetVM_Task()
			WaitForTask(t)
			#self.wait(t.info)
		except Exception as e:
			print str(e)
Exemplo n.º 18
0
def create(content, snapShot, descript, dumpMemory, quiesce):
    """
    Creates snapshot of VM after finding context for it.
    Important: when called set dumpMemory and quiesce to False.
    """
    vm = getVM(content, [vim.VirtualMachine], "johnson")
    WaitForTask(vm.CreateSnapshot("helloworld", descript, dumpMemory, quiesce))
Exemplo n.º 19
0
def TestVQATDestroyVM(vm):
    """
   Destroy a VM.
   """
    Log("Destroying VM")
    task = vm.Destroy()
    WaitForTask(task)
def add_hosts_to_vc(dc,cluster,esx_hosts,esx_user,esx_pwd):
    host_objects = []
    folder = dc.hostFolder
    for ip in esx_hosts:
        # Get ESXi SSL thumbprints
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        wrappedSocket = ssl.wrap_socket(sock)
        wrappedSocket.connect((ip, 443))
        der_cert_bin = wrappedSocket.getpeercert(True)
        thumb_sha1 = hashlib.sha1(der_cert_bin).hexdigest()
        thumb = ':'.join(a + b for a, b in zip(thumb_sha1[::2], thumb_sha1[1::2]))
        print("Host thumbprint is ", thumb)

        connect_spec = vim.host.ConnectSpec(hostName=ip,
                                        userName=esx_user,
                                        password=esx_pwd,
                                        sslThumbprint=thumb,
                                        force=False)
        print("Adding Host ({}) to vCenter".format(ip))
        task = folder.AddStandaloneHost(connect_spec,
                                           vim.ComputeResource.ConfigSpec(),
                                           True)
        # Get host from task result
        WaitForTask(task)
        host_mo = task.info.result.host[0]
        #print("Created Host '{}' ({})".format(mo._moId, ip))
        print("Added Host '{}' ({} to vCenter)".format(host_mo._moId, host_mo.name))
        host_objects.append(host_mo)
    return host_objects
Exemplo n.º 21
0
 def delete(self, snapshot, removeChildren=False):
     try:
         log.info("delete snapshot")
         WaitForTask(snapshot.snapshot.RemoveSnapshot_Task(removeChildren))
     except:
         log.debug("Error irreconosible")
         raise
Exemplo n.º 22
0
def TestWithSnapshot(vm1):
    """ Verify that it is not possible to extend delta disk by changing
        capacityInBytes.
    """
    cspec = Vim.Vm.ConfigSpec()
    vmconfig.AddScsiDisk(cspec, cfgInfo = vm1.config)
    vm.Reconfigure(vm1, cspec)
    devices = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)
    if len(devices) != 1:
       raise Exception("Failed to find new disk!")

    # attempt to extend a disk with a parent
    Log("Creating a snapshot on the VM for negative disk extend test.")
    vm.CreateSnapshot(vm1, "dummy snapshot", "dummy desc", False, False)
    Log("Attempting to extend disk size of delta disk.")
    disk = vmconfig.CheckDevice(vm1.config, Vim.Vm.Device.VirtualDisk)[0]
    cspec = Vim.Vm.ConfigSpec()
    disk.capacityInBytes = disk.capacityInBytes + 1024
    vmconfig.AddDeviceToSpec(cspec, disk, Vim.Vm.Device.VirtualDeviceSpec.Operation.edit)
    task = vm1.Reconfigure(cspec)
    try:
       WaitForTask(task)
    except Exception as e:
       Log("Hit an exception extending delta disk as expected" + str(e))
    else:
       raise Exception("Error: Extending delta disk was allowed!")

    Log("Removing all snapshots on the VM.")
    vm.RemoveAllSnapshots(vm1)
Exemplo n.º 23
0
   def TestCreateFileBackedWeirdPaths(self, cleanup=True):
      Log("VirtualDiskManager: Create file-backed tests with weird paths")
      spec = Vim.VirtualDiskManager.FileBackedVirtualDiskSpec()

      weirdNames = [
           # directory-looking path without vmdk extension handled like disks
           [True, "path without vmdk extension" , "novmdkext"],
           # created but disklib errored on reading disk info IIRC
           [False, "path with quotes and stuff", "\"\",.-.vmdk"],
           [False, "path with special characters",
                   "~!@#$%^&*-_=+[]\\{}|;:\",./<>?-.vmdk"],
           [False, "path with single quote not liked by vmfs",
                   "\"xxxquote.vmdk"],
           [False, "nonexistent directory path with trailing slash disallowed",
                   "withslash/"]
      ]

      for allow,desc,name in weirdNames:
         # @todo exercise disallowed ones too, but catch/match exceptions
         if allow:
            spec.SetDiskType("preallocated")
            spec.SetAdapterType("busLogic")
            spec.SetCapacityKb(long(50000))

            path = "[" + self._dsName + "] " + name
            Log("  Creating " + desc + " (" + path + ")")
            task = self._vdm.CreateVirtualDisk(path, None, spec)
            WaitForTask(task)
            Log("  Creating " + desc + " (" + path + ") Done.")

            if cleanup:
               task = self._vdm.DeleteVirtualDisk(path, None)
               Log("  Deleting " + desc + " (" + path + ") Done.")
Exemplo n.º 24
0
def main():
   supportedArgs = [ (["h:", "host="], "localhost", "Host name", "host"),
                     (["u:", "user="******"root", "User name", "user"),
                     (["p:", "pwd="], "", "Password", "pwd"),
                     (["v:", "vmname="], "SATATest", "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)

      ## Positive tests on a hwVersion 10 VM
      Log("Creating Hw10 VM..")
      vm1 = vm.CreateQuickDummy(vmname, vmxVersion = "vmx-10",
                                memory = 4, guest = "otherGuest")

      # Test add of SATA controller
      TestSataCtlrReconfig(vm1)

      # Mess with SATA disks
      TestEditSataDisk(vm1)

      # Mess with SATA cdroms
      TestEditSataCdrom(vm1)

      Log("Tests completed.")

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

   Log("TEST RUN COMPLETE: " + status)
Exemplo n.º 25
0
	def revertCurrentSnapshotVM(self, vm):
		try:
			t = vm.RevertToCurrentSnapshot_Task()
			WaitForTask(t)
			#self.wait(t.info)
		except Exception as e:
			print str(e)
Exemplo n.º 26
0
    def remove_snapshot_by_id(self,
                              snapshot_id,
                              vm_obj=None,
                              vm_name=None,
                              remove_children=True,
                              raise_not_found=False):
        """
        Remove a vm's snapshot by the snapshot ID

        The snapshot ID should be saved when creating a snapshot if you
        need to use it in this function.

        A snapshot obj in pyvmomi is like 'vim.vm.Snapshot:snapshot-1474',
        the snapshot ID is 'snapshot-1474'

        :param snapshot_id: a snapshot ID
        :param vm_obj: a vsphere vm object
        :param vm_name: a vm's name
        :param remove_children: whether to remove snapshot's children snapshots
        :param raise_not_found: whether to raise exception if snapshot_id not found
        """
        snap = self.find_snapshot_by_id(snapshot_id)
        if not snap:
            if raise_not_found:
                raise VSphereSnapNotFound(vm_obj.name, snapshot_id)
            else:
                logging.debug('Not found snapshot_id %s for VM %s',
                              snapshot_id, vm_obj.name)
                return

        logging.debug('Remove snapshot %s for VM %s', snap, vm_obj.name)
        WaitForTask(snap.Remove(removeChildren=remove_children))
Exemplo n.º 27
0
 def TestInflate(self):
    Log("VirtualDiskManager: Inflate test")
    path = self.CreateSingle("InflateTest", "thin")
    Log("  Inflating: " + path)
    task = self._vdm.InflateVirtualDisk(path)
    WaitForTask(task, True)
    self.DeleteSingle(path)
Exemplo n.º 28
0
    def change_vm_disk(self, disk_label, new_disk_size, vm_moId):
        si = self._connect_vc()
        content = si.RetrieveContent()
        vm_obj = self._get_obj_bymoId(content, [vim.VirtualMachine], vm_moId)
        try:
            virtual_disk_device = None
            if not vm_obj.rootSnapshot:
                for dev in vm_obj.config.hardware.device:
                    if isinstance(dev, vim.vm.device.VirtualDisk
                                  ) and dev.deviceInfo.label == disk_label:
                        virtual_disk_device = dev
                if not virtual_disk_device:
                    return RuntimeError(
                        'Virtual {} could not be found.'.format(disk_label))

                virtual_disk_spec = vim.vm.device.VirtualDeviceSpec()
                virtual_disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
                virtual_disk_spec.device = virtual_disk_device
                virtual_disk_spec.device.capacityInKB = int(
                    new_disk_size) * 1024 * 1024

                dev_changes = []
                dev_changes.append(virtual_disk_spec)
                spec = vim.vm.ConfigSpec()
                spec.deviceChange = dev_changes
                task = vm_obj.ReconfigVM_Task(spec=spec)
                # tasks.wait_for_tasks(si, [task])
                WaitForTask(task)
                return {'result': True}
        except Exception, e:
            error_msg = e.message if e.message else str(e)
            return {"result": False, "data": error_msg}
Exemplo n.º 29
0
    def add_disk(self, vm, size, disk_type="thin"):
        """
        Attaches disk to VM

        Args:
            vm (vim.VirtualMachine): VM instance
            size (int) : size of disk in GB
            disk_type (str) : disk type

        """
        logger.info(f"Adding disk to {vm.config.name}")
        spec = vim.vm.ConfigSpec()
        controller = self.get_controller_for_adding_disk(vm)
        unit_number = self.get_unit_number(vm)
        logger.info(f"Unit number for new disk: {unit_number}")

        device_changes = []
        new_disk_kb = int(size) * GB2KB
        disk_spec = vim.vm.device.VirtualDeviceSpec()
        disk_spec.fileOperation = "create"
        disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        disk_spec.device = vim.vm.device.VirtualDisk()
        disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo(
        )
        if disk_type == VM_DISK_TYPE:
            disk_spec.device.backing.thinProvisioned = True
        disk_spec.device.backing.diskMode = VM_DISK_MODE
        disk_spec.device.unitNumber = unit_number
        disk_spec.device.capacityInKB = new_disk_kb
        disk_spec.device.controllerKey = controller.key
        device_changes.append(disk_spec)
        spec.deviceChange = device_changes
        WaitForTask(vm.ReconfigVM_Task(spec=spec))
        logger.info(f"{size}GB disk added successfully to {vm.config.name}")
Exemplo n.º 30
0
def change_vcpu(vm, vcpu_nu):
    vcpu_nu = int(vcpu_nu)
    cspec = vim.vm.ConfigSpec()
    cspec.numCPUs = vcpu_nu
    cspec.numCoresPerSocket = 1
    WaitForTask(vm.Reconfigure(cspec))
    print("number of vCPU changed to %s" % vcpu_nu)