コード例 #1
0
ファイル: vmops.py プロジェクト: ichaudhry786/vmware
class Vmops:
 client=None
 def connect(self):
     configuration=Config()
     server = configuration._config_value("general", "server")
     if server is None:
         raise ValueError("server must be supplied on command line"+"or in configuration file.")
     username = configuration._config_value("general", "username")
     if username is None:
         raise ValueError("username must be supplied on command line"
                      " or in configuration file.")
     password = configuration._config_value("general", "password")
     if password is None:
         raise ValueError("password must be supplied on command line"
                      " or in configuration file.")

     self.client=Client(server,username,password)


 def findVM(self,vmName):
     vm = self.client.find_entity_view("VirtualMachine",filter={"name": vmName})
     return vm


 def changevmConfig(self,vm_name,cpuCount):
    try:
     new_config = self.client.create("VirtualMachineConfigSpec")
     new_config.numCPUs = cpuCount
     new_config.cpuHotAddEnabled=True
     vm = VirtualMachine.get(self.client, name=vm_name)
     print("Reconfiguring %s" % vm_name)
     if vm.config.hardware.numCPU == cpuCount:
        print("Not reconfiguring %s as it already has 2 CPUs" % vm_name)
        sys.exit()
     task = vm.ReconfigVM_Task(spec=new_config)
     while task.info.state in ["queued", "running"]:
      print("Waiting 5 more seconds for VM creation")
      time.sleep(5)
      task.update()

     if task.info.state == "success":
      elapsed_time = task.info.completeTime - task.info.startTime
      print("Successfully reconfigured VM %s. Server took %s seconds." %
          (vm_name, elapsed_time.seconds))
     elif task.info.state == "error":
      print("ERROR: The task for reconfiguring the VM has finished with"
          " an error. If an error was reported it will follow.")
      print("ERROR: %s" % task.info.error.localizedMessage)
    except VimFault, e:
     print("Failed to reconfigure %s: " % e)
     sys.exit()
    except ObjectNotFoundError:
     print("ERROR: No VM found with name %s" % vm_name)
コード例 #2
0
ファイル: reconfig_vm.py プロジェクト: psav/psphere
    reconfig_vm test

"""

import sys
import time

from psphere.client import Client
from psphere.soap import VimFault
from psphere.managedobjects import VirtualMachine
from psphere.errors import ObjectNotFoundError

vm_name = sys.argv[1]

client = Client()
new_config = client.create("VirtualMachineConfigSpec")
new_config.numCPUs = 2

try:
    vm = VirtualMachine.get(client, name=vm_name)
except ObjectNotFoundError:
    print("ERROR: No VM found with name %s" % vm_name)

print("Reconfiguring %s" % vm_name)
if vm.config.hardware.numCPU == 2:
    print("Not reconfiguring %s as it already has 2 CPUs" % vm_name)
    sys.exit()

try:
    task = vm.ReconfigVM_Task(spec=new_config)
except VimFault, e:
コード例 #3
0
class VSphere(object):
    """
    Class represents a vSphere client.

    Example usage:
        my_client = sut.VSphere('16.xx.xx.xx', 'user1', 'passwd1')
        my_vm = my_client.get_vm('user1_vm1')
        my_client.power_on_vm(my_vm)
        my_client.end_session()
    """
    def __init__(self, vsphere_server, vsphere_username, vsphere_password):
        self.server = vsphere_server
        self.username = vsphere_username
        self.password = vsphere_password
        try:
            log._info("Attempting to connect to vCenter server: %s" %
                      (self.server))
            self.client = Client(self.server, self.username, self.password)
            log._info("CONNECTED to vCenter server: %s" % (self.server))
        except VimFault as e:
            log._warn("Failed to connect to vCenter: %s" % (e.fault_name))
            return False

    def end_session(self):
        """
        Terminates session with vSphere client
        """
        self.client.logout()

    def get_vm(self, vm_name):
        try:
            vm = VirtualMachine.get(self.client, name=vm_name)
        except ObjectNotFoundError:
            log._warn("Error finding VM '%s', does not exist within client" %
                      (vm_name))
            return False
        return vm

    def power_on_vm(self, vm_name):
        """
        Powers on a VM defined in the Client

        Params:
            - vm_name:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        vm = self.get_vm(vm_name)
        if vm.runtime.powerState == "poweredOn":
            log._warn("ERROR: %s is already powered on." % vm.name)
        else:
            try:
                log._info("Powering on %s" % vm.name)
                task = vm.PowerOnVM_Task()
            except VimFault as e:
                log._warn("ERROR: Failed to power on %s %s" % (vm.name, e))

    def power_off_vm(self, vm_name):
        """
        Powers off a VM defined in the Client

        Params:
            - vm:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        vm = self.get_vm(vm_name)
        if vm.runtime.powerState == "poweredOff":
            log._warn("ERROR: %s is already powered off." % vm.name)
        else:
            try:
                log._info("Powering off %s" % vm.name)
                task = vm.PowerOffVM_Task()
            except VimFault as e:
                log._warn("ERROR: Failed to power off %s %s" % (vm.name, e))

    def suspend_vm(self, vm):
        """
        Powers off a VM defined in the Client

        Params:
            - vm:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        if vm.runtime.powerState in ["poweredOff", "suspended"]:
            log._warn(
                "ERROR: %s is powered off or suspended. Cannot suspend." %
                vm.name)
        else:
            try:
                log._info("Suspending %s" % vm.name)
                task = vm.SuspendVM_Task()
            except VimFault as e:
                log._warn("ERROR: Failed to suspend %s %s" % (vm.name, e))

    def reset_vm(self, vm):
        """
        Resets the virtual machine

        Params:
            - vm:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        try:
            log._info("Restarting %s" % vm.name)
            task = vm.RestartVM_Task()
        except VimFault as e:
            log._warn("ERROR: Failed to restart %s %s" % (vm.name, e))

    def destroy_vm(self, vm_name):
        """
        Destroys VM*, deleting its contents and removing it from parent folder
        Params:
            - vm:  (str) The name of the virtual machine to be deleted.


        *Assumes proper permissions (VirtualMachine.Inventory.Delete)
        """
        vm = VirtualMachine.get(self.client, name=vm_name)

        try:
            log._info("Destroying %s" % vm.name)
            task = vm.Destroy_Task()
        except VimFault as e:
            log._warn("ERROR: Failed to destroy %s %s" % (vm.name, e))

    def clone_vm(self,
                 source_vm_name,
                 dest_vm_name,
                 power_on=False,
                 is_template=False):
        """
        Creates a clone of virtual machine 'vm'.  If the vm is a template,
        this method corresponds to deploying from a template

        Params:
            - (str)source_vm:     Name of Virtual machine (or template) to clone
            - (str)dest_vm_name:  Name of the new clone
        Optional:
            - power_on:     Option to power on the cloned vm after creation
            - is_template:  Option to mark cloned vm as a template


        * Assumes proper permissions.  The privilege required on the source
        virtual machine depends on the source and destination types:

        - source is virtual machine, destination is virtual machine - VirtualMachine.Provisioning.Clone
        - source is virtual machine, destination is template - VirtualMachine.Provisioning.CreateTemplateFromVM
        - source is template, destination is virtual machine - VirtualMachine.Provisioning.DeployTemplate
        - source is template, destination is template - VirtualMachine.Provisioning.CloneTemplate
        """
        # host_system = HostSystem.get(client, name=vm_host)

        # check to see if dest_vm already exists
        try:
            vm = VirtualMachine.get(self.client, name=dest_vm_name)
            if vm.name == dest_vm_name:
                log._warn("ERROR: Destination VM '%s' already exists." %
                          dest_vm_name)
                return False
        except ObjectNotFoundError:
            pass  # we want the object to not be found :)

        # also, check to see if the source vm exists
        try:
            source_vm = VirtualMachine.get(self.client, name=source_vm_name)
        except ObjectNotFoundError:
            log._warn("ERROR: No VM with name \"%s\" to clone" %
                      source_vm_name)
            return False

        vm_clone_spec = self.client.create("VirtualMachineCloneSpec")
        vm_reloc_spec = self.client.create("VirtualMachineRelocateSpec")
        vm_reloc_spec.datastore = source_vm.datastore  # [0]
        vm_reloc_spec.pool = source_vm.resourcePool
        vm_reloc_spec.host = None
        # vm_reloc_spec.disk = None #[]
        vm_reloc_spec.transform = None
        vm_clone_spec.powerOn = power_on
        vm_clone_spec.template = is_template
        vm_clone_spec.location = vm_reloc_spec
        vm_clone_spec.snapshot = None
        # Datacenter folder
        datacenter_folder = source_vm.parent.parent.vmFolder

        try:
            log._info("Attempting to clone %s" % source_vm.name)
            task = source_vm.CloneVM_Task(folder=datacenter_folder,
                                          name=dest_vm_name,
                                          spec=vm_clone_spec)
        except VimFault as e:
            log._warn("ERROR: Failed to clone '%s'" % e)
            return False
        while task.info.state in ["queued", "running"]:
            log._info("Waiting 5 more seconds for VM creation")
            time.sleep(5)
            task.update()

        if task.info.state == "success":
            elapsed_time = task.info.completeTime - task.info.startTime
            log._info(
                "Successfully cloned VM %s from %s. Server took %s seconds." %
                (dest_vm_name, source_vm_name, elapsed_time.seconds))
        elif task.info.state == "error":
            log._warn("ERROR: The task for cloning the VM has finished with"
                      " an error. If an error was reported it will follow.")
            try:
                log._warn("ERROR: %s" % task.info.error.localizedMessage)
            except AttributeError:
                log._warn("ERROR: There is no error message available.")
        else:
            log._warn("UNKNOWN: The task reports an unknown state %s" %
                      task.info.state)

    def deploy_from_ovf(self, ovf_path, vm_name):
        """
        Deploys a VM from an .ovf file
        """
        pass
        # def get_descriptor(ovf_path):
        # """
        # Opens .ovf file and returns descriptor
        # """
        # fh = open(ovf_path, "r")
        # ovf_descriptor = fh.read()
        # fh.close()
        # return ovf_descriptor

        # '''
        # https://groups.google.com/forum/#!topic/pysphere/NkTOy_GSaKw

        # def parse_descriptor(ovf_descriptor):
        # ovf_manager = s._do_service_content.OvfManager
        # request = VI.ParseDescriptorRequestMsg()
        # _this =request.new__this(ovf_manager)
        # _this.set_attribute_type(ovf_manager.get_attribute_type())
        # request.set_element__this(_this)
        # request.set_element_ovfDescriptor(ovf_descriptor)
        # pdp = request.new_pdp()
        # pdp.set_element_locale("")
        # pdp.set_element_deploymentOption("")
        # request.set_element_pdp(pdp)
        # return s._proxy.ParseDescriptor(request)._returnval
        # '''

        # def deploy(args):
        # """
        # """
        # ovfdesc = get_descriptor(ovf_path)

        # ovfmgr = self.client.sc.ovfManager

        # descriptor_info =  parse_descriptor(o)

        # descriptor_info = ovfmgr.ParseDescriptor(ovfdesc)
        # ovfimportresult = ovfmgr.CreateImportSpec(ovfDescriptor=ovfdesc, resourcePool=resourcepool, datastore=dstore, cisp=ocisp)

        # httpNfcLease = resourcepool.ImportVApp(spec=ovfimportresult.importSpec, folder=dl.vmFolder)

    def create_snapshot(self, vm_name, snapshot_name):
        """
        Creates a snapshot of 'vm' with name of 'snapshot_name'

        Both arguments are type 'str'
        """
        try:
            vm = VirtualMachine.get(self.client, vm_name)
        except ObjectNotFoundError:
            log._warn("ERROR: No VM with name \"%s\" to clone" %
                      source_vm_name)
            return False
        try:
            log._info("Creating snapshot for VM: %s" % vm.name)
            # task = vm.CreateSnapshot_Task(name=snapshot_name, memory=False, quiesce=False)
            task = vm.CreateSnapshot_Task(name=snapshot_name,
                                          memory=True,
                                          quiesce=True)
        except VimFault as e:
            log._warn("Failed to create snapshot %s: " % e)

        while task.info.state in ["queued", "running"]:
            log.info("Waiting 5 more seconds for VM snapshot to complete")
            time.sleep(5)
            task.update()

        if task.info.state == "success":
            elapsed_time = task.info.completeTime - task.info.startTime
            log._info(
                "Successfully create snapshot for VM %s. Processing took %s seconds."
                % (vm_name, elapsed_time.seconds))
        elif task.info.state == "error":
            log._warn(
                "ERROR: The task for creating the VM snapshot has finished with an error. If an error was reported it will follow."
            )
            try:
                log._warn("ERROR: %s" % task.info.error.localizedMessage)
            except AttributeError:
                log._warn("ERROR: There is no error message available.")
        else:
            log._warn("UNKNOWN: The task reports an unknown state %s" %
                      task.info.state)