Пример #1
0
    def _wait_for_updates(self, version='', max_object_updates=None, max_wait_seconds=None):

        try:
            if self.__api_version >= "4.1":
                request = VI.WaitForUpdatesExRequestMsg()
                options = request.new_options()
                if max_object_updates is not None:
                    options.set_element_maxObjectUpdates(max_object_updates)
                if max_wait_seconds is not None:
                    options.set_element_maxWaitSeconds(max_wait_seconds)
                request.set_element_options(options)
                method = self._proxy.WaitForUpdatesEx
            else:
                if max_wait_seconds is None:
                    print 'WaitForUpdates'
                    request = VI.WaitForUpdatesRequestMsg()
                    method = self._proxy.WaitForUpdates
                else:
                    print 'CheckForUpdates'
                    request = VI.CheckForUpdatesRequestMsg()
                    method = self._proxy.CheckForUpdates
            _this = request.new__this(self._do_service_content.PropertyCollector)
            _this.set_attribute_type(MORTypes.PropertyCollector)
            request.set_element__this(_this)
            request.set_element_version(version)
            retval = method(request)._returnval
            return retval

        except (VI.ZSI.FaultException), e:
            raise VIApiException(e)
Пример #2
0
    def __read_tasks(self, max_count, next_page):

        if not isinstance(max_count, int):
            raise VIException("max_count should be an integer",
                              FaultTypes.PARAMETER_ERROR)

        if next_page:
            request = VI.ReadNextTasksRequestMsg()
        else:
            request = VI.ReadPreviousTasksRequestMsg()

        _this = request.new__this(self._mor)
        _this.set_attribute_type(self._mor.get_attribute_type())
        request.set_element__this(_this)

        request.set_element_maxCount(max_count)
        try:
            if next_page:
                resp = self._server._proxy.ReadNextTasks(request)._returnval
            else:
                resp = self._server._proxy.ReadPreviousTasks(
                    request)._returnval

            ret = []
            for task in resp:
                ret.append(VITask(task.Task, self._server))

        except (VI.ZSI.FaultException) as e:
            raise VIApiException(e)

        return ret
Пример #3
0
def export(server, vm_obj):
    # Request an export
    request = VI.ExportVmRequestMsg()
    _this = request.new__this(vm_obj._mor)
    _this.set_attribute_type(vm_obj._mor.get_attribute_type())
    request.set_element__this(_this)
    ret = server._proxy.ExportVm(request)

    # List of urls to download
    mor = ret._returnval
    http = VIProperty(connection, ret._returnval)
    url = http.info.deviceUrl[0].url

    # TODO: actually download them.

    # Set to 100%
    request = VI.HttpNfcLeaseProgressRequestMsg()
    _this = request.new__this(mor)
    _this.set_attribute_type(MORTypes.HttpNfcLease)
    request.set_element__this(_this)
    request.set_element_percent(100)
    server._proxy.HttpNfcLeaseProgress(request)

    # Completes the request
    request = VI.HttpNfcLeaseCompleteRequestMsg()
    _this = request.new__this(mor)
    _this.set_attribute_type(MORTypes.HttpNfcLease)
    request.set_element__this(_this)
    server._proxy.HttpNfcLeaseComplete(request)
 def __read_events(self, max_count, next_page):
     """
     Reads the 'scrollable view' from the current position. 
     """
     
     if not isinstance(max_count, int):
         raise VIException("max_count should be an integer", 
                           FaultTypes.PARAMETER_ERROR)
     
     if next_page:
         request = VI.ReadNextEventsRequestMsg()
     else:
         request = VI.ReadPreviousEventsRequestMsg()
         
     _this = request.new__this(self._mor)
     _this.set_attribute_type(self._mor.get_attribute_type())
     request.set_element__this(_this)
     
     request.set_element_maxCount(max_count)
     try:
         if next_page:
             resp = self._server._proxy.ReadNextEvents(request)._returnval
         else:
             resp = self._server._proxy.ReadPreviousEvents(request)._returnval
         
         ret = []
         for event in resp:
             ret.append(VIProperty(self._server,event))
     
     except (VI.ZSI.FaultException), e:
         raise VIApiException(e)
Пример #5
0
    def delete_vm_by_name(self, name, remove_files=True):
        """
        Unregisters a VM and remove it files from the datastore by name.
        @name is the VM name.
        @remove_files - if True (default) will delete VM files from datastore.
        """
        statusLine = ''
        success = False

        if not self.__logged:
            raise VIException("Must call 'connect' before invoking this method", FaultTypes.NOT_CONNECTED)
        try:
            # Get VM
            vm = self.get_vm_by_name(name)

            if remove_files:
                # Invoke Destroy_Task
                request = VI.Destroy_TaskRequestMsg()

                _this = request.new__this(vm._mor)
                _this.set_attribute_type(vm._mor.get_attribute_type())
                request.set_element__this(_this)
                ret = self._proxy.Destroy_Task(request)._returnval
                task = VITask(ret, self)
                
                # Wait for the task to finish
                status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])

                if status == task.STATE_SUCCESS:
                    statusLine = "VM successfully unregistered and deleted from datastore"
                    success = True

                elif status == task.STATE_ERROR:
                    statusLine = "Error removing vm: {}".format(task.get_error_message())
                    success = False

            else:
                # Invoke UnregisterVMRequestMsg
                request = VI.UnregisterVMRequestMsg()

                _this = request.new__this(vm._mor)
                _this.set_attribute_type(vm._mor.get_attribute_type())
                request.set_element__this(_this)
                ret = self._proxy.UnregisterVM(request)
                task = VITask(ret, self)

                statusLine = "VM successfully unregistered (files still on datastore)"
                success = True

        except VI.ZSI.FaultException as e:
            raise VIApiException(e)

        finally:
            return success, statusLine
Пример #6
0
def change_cpu(vminstance=None, cpu_number=None, cpu_core=None):
    '''Modify the number and core number of the virtual machine CPU'''
    vm_obj = vminstance
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm_obj._mor)
    _this.set_attribute_type(vm_obj._mor.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()

    if cpu_number is not None:
        spec.set_element_numCPUs(cpu_number)  # This sets CPU config to 2x1 (The two cpus are single-core)
    if cpu_core is not None:
        spec.set_element_numCoresPerSocket(cpu_core)  # This sets CPU config to 1x2 (instead of 2x2) 1 CPU dual-core

    request.set_element_spec(spec)
    ret = server._proxy.ReconfigVM_Task(request)._returnval
    task = VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    if status == task.STATE_SUCCESS:
        print "VM successfully reconfigured"
        return True
    elif status == task.STATE_ERROR:
        print "Error reconfiguring vm: %s" % task.get_error_message()
        return False
    server.disconnect()
Пример #7
0
def reconfig(server, vm, cdrom):

    request = VI.ReconfigVM_TaskRequestMsg()

    _this = request.new__this(vm._mor)
    _this.set_attribute_type(vm._mor.get_attribute_type())

    request.set_element__this(_this)

    spec = request.new_spec()

    dev_change = spec.new_deviceChange()
    dev_change.set_element_device(cdrom)
    dev_change.set_element_operation('edit')

    spec.set_element_deviceChange([dev_change])

    request.set_element_spec(spec)

    ret = server._proxy.ReconfigVM_Task(request)._returnval

    task = VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])

    if status == task.STATE_SUCCESS:
        return True

    return False
Пример #8
0
def create_dvswitch(vcenter, datacenter, name, uplinks=2):
    """Create a new DVS."""
    switch_folder = pysphere.VIProperty(vcenter, datacenter).networkFolder._obj
    request = VI.CreateDVS_TaskRequestMsg()
    _this = request.new__this(switch_folder)
    _this.set_attribute_type(switch_folder.get_attribute_type())
    request.set_element__this(_this)

    spec = request.new_spec()
    config = spec.new_configSpec()
    config.Name = name

    uplink_policy = (
        VI.ns0.DVSNameArrayUplinkPortPolicy_Def('uplink_policy').pyclass())
    uplink_policy.UplinkPortName = [
        'Uplink%d' % x for x in range(1, uplinks + 1)
    ]
    config.set_element_uplinkPortPolicy(uplink_policy)

    spec.set_element_configSpec(config)
    request.set_element_spec(spec)
    task = vcenter._proxy.CreateDVS_Task(request)._returnval
    vi_task = pysphere.VITask(task, vcenter)
    status = vi_task.wait_for_state(
        [vi_task.STATE_SUCCESS, vi_task.STATE_ERROR])
    if status == vi_task.STATE_ERROR:
        raise CreateDvSwitchError(vi_task.get_error_message())
Пример #9
0
def _build_create_vm_request(target_config, datastore, vm_name, memory,
                             num_cpus, osid, resource_pool, vmfolder, version):
    """Creates a new VM create request and populates the config field.

  Return:
    (CreateVM_TaskRequestMsg, CreateVM_TaskRequestMsg.config)
  """
    create_vm_request = VI.CreateVM_TaskRequestMsg()
    config = create_vm_request.new_config()
    config.set_element_version(version)

    vmfiles = config.new_files()
    vmfiles.set_element_vmPathName(datastore)
    config.set_element_files(vmfiles)
    config.set_element_name(vm_name)
    config.set_element_memoryMB(memory / 1024 / 1024)
    config.set_element_numCPUs(num_cpus)
    config.set_element_guestId(osid)
    config.set_element_firmware('efi')

    create_vm_request.set_element_config(config)

    # Reference to what vSphere refers to as a 'Folder' that will handle the call
    mor = create_vm_request.new__this(vmfolder)
    mor.set_attribute_type(vmfolder.get_attribute_type())
    create_vm_request.set_element__this(mor)

    # Set which resource pool to use
    mor = create_vm_request.new_pool(resource_pool)
    mor.set_attribute_type(resource_pool.get_attribute_type())
    create_vm_request.set_element_pool(mor)

    return create_vm_request, config
Пример #10
0
    def query_perf_provider_summary(self, entity):
        """Returns a ProviderSummary object for a ManagedObject for which 
        performance statistics can be queried. Also indicates whether current or
        summary statistics are supported. If the input managed entity is not a 
        performance provider, an InvalidArgument exception is thrown.
        entity [mor]: The ManagedObject for which available performance metrics
        are queried.
        """

        if not entity:
            raise VIException("No Entity specified.",
                              FaultTypes.PARAMETER_ERROR)

        try:
            request = VI.QueryPerfProviderSummaryRequestMsg()
            mor_qpps = request.new__this(self._mor)
            mor_qpps.set_attribute_type(self._mor.get_attribute_type())
            request.set_element__this(mor_qpps)

            qpps_entity = request.new_entity(entity)
            qpps_entity.set_attribute_type(entity.get_attribute_type())
            request.set_element_entity(qpps_entity)

            qpps = self._server._proxy.QueryPerfProviderSummary(
                request)._returnval
            return qpps

        except (VI.ZSI.FaultException) as e:
            raise VIApiException(e)
Пример #11
0
    def delete_instance(self, name=None):
        # Check if name is passed, if not extract from vm_json
        if not name:
            name = self.vm_json.get('name')

        # Initialise vcenter handle
        vcenter_handle = self.server
        try:
            vm = vcenter_handle.get_vm_by_name(name)
        except Exception:
            logger.info('VM %s not present in vCenter. This is OK' % name)
            return
        # Power off if not already
        if not vm.is_powered_off():
            vm.power_off()
        # Invoke Destroy_Task
        request = VI.Destroy_TaskRequestMsg()
        _this = request.new__this(vm._mor)
        _this.set_attribute_type(vm._mor.get_attribute_type())
        request.set_element__this(_this)
        ret = vcenter_handle._proxy.Destroy_Task(request)._returnval

        # Wait for the task to finish
        task = VITask(ret, vcenter_handle)

        status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
        if status == task.STATE_SUCCESS:
            logger.info('VM %s successfully deleted from disk' % name)
        elif status == task.STATE_ERROR:
            logger.info('Error removing vm: %s' % task.get_error_message())
Пример #12
0
def create_folder(viserver, root_folder, new_name):
    request = VI.CreateFolderRequestMsg()
    _this = request.new__this(root_folder)
    _this.set_attribute_type(root_folder.get_attribute_type())
    request.set_element__this(_this)
    request.set_element_name(new_name)
    viserver._proxy.CreateFolder(request)
Пример #13
0
def delete_vm(vm):
    vm_name = vm.get_property('name', from_cache=False)
    log("Preparing to delete VM %s..." % vm_name)
    vm_status = vm.get_status()
    log("VM status: %s" % vm_status)
    if vm_status == "POWERED OFF" or vm_status == "POWERING OFF":
        log("VM power state: %s" % vm_status)
    else:
        log("Powering off VM %s..." % vm_name)
        vm.power_off()

    log("Deleting VM %s..." % vm_name)
    request = VI.Destroy_TaskRequestMsg()
    _this = request.new__this(vm._mor)
    _this.set_attribute_type(vm._mor.get_attribute_type())
    request.set_element__this(_this)
    ret = server._proxy.Destroy_Task(request)._returnval

    # Wait for the delete task to finish
    task = VITask(ret, server)

    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    if status == task.STATE_SUCCESS:
        log("VM successfully deleted from disk.")
    elif status == task.STATE_ERROR:
        error_msg = "Error while deleting VM: " + task.get_error_message()
        raise Exception(error_msg)
Пример #14
0
    def add_vdisk(self, vminstance, datastore_name, vdisk_size_gb):
        '''add disk'''
        vdisk_size_kb = vdisk_size_gb * 1024 * 1024
        vm = vminstance

        # Virtual device node number
        Unit_Number = ""
        Temp_Number = 1
        # find the device to be removed
        while True:
            dev = [
                dev for dev in vm.properties.config.hardware.device
                if dev._type == "VirtualDisk" and dev.unitNumber == Temp_Number
            ]
            if len(dev) == 0:
                Unit_Number = Temp_Number
                break
            else:
                Temp_Number += 1
                continue

        request = VI.ReconfigVM_TaskRequestMsg()
        _this = request.new__this(vm._mor)
        _this.set_attribute_type(vm._mor.get_attribute_type())
        request.set_element__this(_this)

        spec = request.new_spec()

        dc = spec.new_deviceChange()
        dc.Operation = "add"
        dc.FileOperation = "create"

        hd = VI.ns0.VirtualDisk_Def("hd").pyclass()
        hd.Key = -100
        hd.UnitNumber = Unit_Number
        hd.CapacityInKB = vdisk_size_kb
        hd.ControllerKey = 1000
        backing = VI.ns0.VirtualDiskFlatVer2BackingInfo_Def(
            "backing").pyclass()
        backing.FileName = "[%s]" % datastore_name
        backing.DiskMode = "persistent"
        backing.Split = False
        backing.WriteThrough = False
        backing.ThinProvisioned = False
        backing.EagerlyScrub = False
        hd.Backing = backing
        dc.Device = hd
        spec.DeviceChange = [dc]
        request.Spec = spec
        task = self.s._proxy.ReconfigVM_Task(request)._returnval
        vi_task = VITask(task, self.s)
        # Wait for task to finis
        status = vi_task.wait_for_state(
            [vi_task.STATE_SUCCESS, vi_task.STATE_ERROR])
        if status == vi_task.STATE_ERROR:
            print "ERROR: %s" % (vi_task.STATE_ERROR)
            return False
        else:
            return True
        self.s.disconnect()
Пример #15
0
def enable_vmi(server, vm_obj):
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm_obj._mor)
    _this.set_attribute_type(vm_obj._mor.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()

    device_config_specs = []

    media_device = VirtualMachineVMIROM()
    media_device.set_element_key(11000)
    device_config_spec = spec.new_deviceChange()
    device_config_spec.set_element_operation('add')
    device_config_spec.set_element_device(media_device)
    device_config_specs.append(device_config_spec)

    spec.set_element_deviceChange(device_config_specs)

    request.set_element_spec(spec)
    ret = server._proxy.ReconfigVM_Task(request)._returnval

    # Wait for the task to finish
    task = VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    if status != task.STATE_SUCCESS:
        raise HypervisorError("Guest:update %s" % task.get_error_message())
Пример #16
0
def set_vm_reservation(server,types,vm_name,reservation,level):
    vm_mor = server.get_vm_by_name(vm_name)
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm_mor._mor)
    _this.set_attribute_type(vm_mor._mor.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()

    if types == 'cpu':
        spec.set_element_numCPUs(reservation)
    elif types == 'memory':
        spec.set_element_memoryMB(reservation)

    request.set_element_spec(spec)
    ret = server._proxy.ReconfigVM_Task(request)._returnval
    config_result = False
    task = VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    if status == task.STATE_SUCCESS:
        ret = "VM <" + vm_name + "> successfully reconfigured"
        config_result = True
    elif status == task.STATE_ERROR:
        #print "Error reconfiguring vm <" + vm_name + ">: %s" % task.get_error_message()
        #print task.get_info()
        #print task.get_result()
        #print task.get_state()
        #print task.info
        ret = "Error reconfiguring vm <" + vm_name + ">: %s" % task.get_error_message()
        config_result = False
    return config_result
Пример #17
0
def provision_vm(server, vm, vlan, datacenter):
    # Set VMs first NIC to the correct label
    hardware = pysphere.VIProperty(server, vm).config.hardware
    nic = next(
        (x._obj for x in hardware.device if x._type in NET_DEVICE_TYPES), None)
    if not nic:
        raise NicNotFoundError('No NIC found')

    # Only vCenter has the correct notion of a datacenter, so if talking to
    # an ESXi assume it is called ha-datacenter instead.
    dc = datacenter if 'vCenter' in server.get_server_type(
    ) else 'ha-datacenter'
    datacenter_props = _get_datacenter_props(server, dc)
    nic.set_element_backing(create_nic_backing(server, vlan, datacenter_props))

    # Submit reconfig request
    # Copy/paste from pysphere mailinglist
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm)
    _this.set_attribute_type(vm.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()
    dev_change = spec.new_deviceChange()
    dev_change.set_element_device(nic)
    dev_change.set_element_operation('edit')
    spec.set_element_deviceChange([dev_change])
    request.set_element_spec(spec)

    ret = server._proxy.ReconfigVM_Task(request)._returnval
    task = pysphere.VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    if task.get_state() == task.STATE_ERROR:
        raise ProvisionVmError(task.get_error_message())
Пример #18
0
    def query_perf_counter(self, counter_id):
        """Retrieves counter information for the list of counter IDs passed in.
        counter_id [list]: list of integers containing the counter IDs.
        """

        if counter_id:
            if not isinstance(counter_id, list):
                raise VIException("counter_id must be a list",
                                  FaultTypes.PARAMETER_ERROR)
        else:
            raise VIException("No counter_id specified.",
                              FaultTypes.PARAMETER_ERROR)

        try:
            request = VI.QueryPerfCounterRequestMsg()
            mor_qpc = request.new__this(self._mor)
            mor_qpc.set_attribute_type(self._mor.get_attribute_type())
            request.set_element__this(mor_qpc)

            request.set_element_counterId(counter_id)

            qpc = self._server._proxy.QueryPerfCounter(request)._returnval
            return qpc

        except (VI.ZSI.FaultException) as e:
            raise VIApiException(e)
Пример #19
0
def delete_vm(vsphere_client, module, guest, vm, force):
    try:

        if vm.is_powered_on():
            if force:
                try:
                    vm.power_off(sync_run=True)
                    vm.get_status()

                except Exception, e:
                    module.fail_json(
                        msg='Failed to shutdown vm %s: %s' % (guest, e))
            else:
                module.fail_json(
                    msg='You must use either shut the vm down first or '
                    'use force ')

        # Invoke Destroy_Task
        request = VI.Destroy_TaskRequestMsg()
        _this = request.new__this(vm._mor)
        _this.set_attribute_type(vm._mor.get_attribute_type())
        request.set_element__this(_this)
        ret = vsphere_client._proxy.Destroy_Task(request)._returnval
        task = VITask(ret, vsphere_client)

        # Wait for the task to finish
        status = task.wait_for_state(
            [task.STATE_SUCCESS, task.STATE_ERROR])
        if status == task.STATE_ERROR:
            vsphere_client.disconnect()
            module.fail_json(msg="Error removing vm: %s %s" %
                             task.get_error_message())
        module.exit_json(changed=True, changes="VM %s deleted" % guest)
Пример #20
0
def network_config(base_name, vlan_name, connect=True):
    vm = conn.get_vm_by_name(base_name)
    net_device = []
    for dev in vm.properties.config.hardware.device:
        if dev._type in [
                "VirtualE1000", "VirtualE1000e", "VirtualPCNet32",
                "VirtualVmxnet", "VirtualNmxnet2", "VirtualVmxnet3"
        ]:
            net_device.append(dev._obj)
    if len(net_device) == 0:
        raise Exception("The vm seems to lack a Virtual Nic")

    for dev_eth in net_device:
        dev_eth.Backing.set_element_deviceName(vlan_name)
        dev_eth.Connectable.Connected = connect

        request = VI.ReconfigVM_TaskRequestMsg()
        _this = request.new__this(vm._mor)
        _this.set_attribute_type(vm._mor.get_attribute_type())
        request.set_element__this(_this)
        spec = request.new_spec()
        dev_change = spec.new_deviceChange()
        dev_change.set_element_device(dev_eth)
        dev_change.set_element_operation('edit')
        spec.set_element_deviceChange([dev_change])
        request.set_element_spec(spec)
        ret = conn._proxy.ReconfigVM_Task(request)._returnval
        task = VITask(ret, conn)
        #task_status(task)
        print 'set vlan  %s' % dev_eth.Backing.DeviceName
        print 'set eth connected'
Пример #21
0
def ReconfigureVM(vm, cdrom):
    # create a new VM Reconfigure Task
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm._mor)
    _this.set_attribute_type(vm._mor.get_attribute_type())
    request.set_element__this(_this)

    # new device change spec
    spec = request.new_spec()
    dev_change = spec.new_deviceChange()
    dev_change.set_element_device(cdrom)
    dev_change.set_element_operation("edit")

    spec.set_element_deviceChange([dev_change])
    request.set_element_spec(spec)
    ret = server._proxy.ReconfigVM_Task(request)._returnval

    task = VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS,task.STATE_ERROR])
    if status == task.STATE_SUCCESS:
        print "%s: successfully reconfigured" % vm.properties.name
        return True
    elif status == task.STATE_ERROR:
        print "%s: Error reconfiguring vm"% vm.properties.name
        return False
Пример #22
0
def validate_host(host_name, ovf_descriptor, server):
    u"""Analysis OVF file.

    @param host_name      Host name
    @param ovf_descriptor Data in OVF file
    @param server         Instance of VIServer

    @return Result of analysed OVF file.
    """
    # Import
    from pysphere.resources import VimService_services as VI

    hosts = server.get_hosts()
    host = [k for k, v in hosts.items() if v == host_name][0]
    if not host:
        raise ValueError("invalid ESX host name")
    ovf_manager = server._do_service_content.OvfManager
    request = VI.ValidateHostRequestMsg()
    _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)
    h = request.new_host(host)
    h.set_attribute_type(host.get_attribute_type())
    request.set_element_host(h)
    vhp = request.new_vhp()
    vhp.set_element_locale("")
    vhp.set_element_deploymentOption("")
    request.set_element_vhp(vhp)
    return server._proxy.ValidateHost(request)._returnval
Пример #23
0
def guest_command(serve, machine, program, command):

  request = VI.StartProgramInGuestRequestMsg()

  _this = request.new__this(machine._proc_mgr)
  _this.set_attribute_type(machine._proc_mgr.get_attribute_type())

  request.set_element__this(_this)

  vm = request.new_vm(machine._mor)
  vm.set_attribute_type(machine._mor.get_attribute_type())

  request.set_element_vm(vm)

  request.set_element_auth(machine._auth_obj)

  spec = request.new_spec()

  spec.set_element_programPath(program)
  spec.set_element_arguments(command)

  request.set_element_spec(spec)

  result = serve._proxy.StartProgramInGuest(request)._returnval

  return result
Пример #24
0
def add_nic(vm, vcenter, net_label="DEFAULT_LABEL"):
''' Adds a NIC to the host.  Returns a VITask object.
    @vm: A VIVirtualMachine object.
    @vcenter: An authenticated VIServer object.
    @net_label: The network label to apply to the NIC.
    '''

    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm._mor)
    _this.set_attribute_type(vm._mor.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()

    dev_change = spec.new_deviceChange()
    dev_change.set_element_operation("add")

    # We use a VMXNET3 controller here.  Introspect into
    # VI.ns0 for all available controller names.
    nic_ctlr = VI.ns0.VirtualVmxnet3_Def("nic_ctlr").pyclass()

    nic_backing = VI.ns0.VirtualEthernetCardNetworkBackingInfo_Def("nic_backing").pyclass()
    nic_backing.set_element_deviceName(net_label)
    nic_ctlr.set_element_addressType("generated")
    nic_ctlr.set_element_backing(nic_backing)
    nic_ctlr.set_element_key(4)
    dev_change.set_element_device(nic_ctlr)

    spec.set_element_deviceChange([dev_change])
    request.set_element_spec(spec)
    vcenter._proxy.ReconfigVM_Task(request)
Пример #25
0
    def destroy(self, sync_run=True):
        """
        Destroys this object, deleting its contents and removing it from its 
        parent folder (if any)
        * sync_run: (default True), If False does not wait for the task to
            finish and returns an instance of a VITask for the user to monitor
            its progress
        """
        try:
            request = VI.Destroy_TaskRequestMsg()
            _this = request.new__this(self._mor)
            _this.set_attribute_type(self._mor.get_attribute_type())
            request.set_element__this(_this)

            task = self._server._proxy.Destroy_Task(request)._returnval
            vi_task = VITask(task, self._server)
            if sync_run:
                status = vi_task.wait_for_state(
                    [vi_task.STATE_SUCCESS, vi_task.STATE_ERROR])
                if status == vi_task.STATE_ERROR:
                    raise VIException(vi_task.get_error_message(),
                                      FaultTypes.TASK_ERROR)
                return

            return vi_task
        except (VI.ZSI.FaultException) as e:
            raise VIApiException(e)
Пример #26
0
    def rename(self, new_name, sync_run=True):
        """
        Renames this managed entity.
          * new_name: Any / (slash), \ (backslash), character used in this name
            element will be escaped. Similarly, any % (percent) character used
            in this name element will be escaped, unless it is used to start an
            escape sequence. A slash is escaped as %2F or %2f. A backslash is
            escaped as %5C or %5c, and a percent is escaped as %25.
          * sync_run: (default True), If False does not wait for the task to
            finish and returns an instance of a VITask for the user to monitor
            its progress 
        """
        try:
            request = VI.Rename_TaskRequestMsg()
            _this = request.new__this(self._mor)
            _this.set_attribute_type(self._mor.get_attribute_type())
            request.set_element__this(_this)
            request.set_element_newName(new_name)

            task = self._server._proxy.Rename_Task(request)._returnval
            vi_task = VITask(task, self._server)
            if sync_run:
                status = vi_task.wait_for_state(
                    [vi_task.STATE_SUCCESS, vi_task.STATE_ERROR])
                if status == vi_task.STATE_ERROR:
                    raise VIException(vi_task.get_error_message(),
                                      FaultTypes.TASK_ERROR)
                return

            return vi_task

        except (VI.ZSI.FaultException) as e:
            raise VIApiException(e)
Пример #27
0
    def _create_filter(self, property_names=[],
                       from_node=None, obj_type='ManagedEntity', partial_updates=True):
        """Creates filter with given parameters and returns its MOR"""
        try:
            if not from_node:
                from_node = self._do_service_content.RootFolder

            elif isinstance(from_node, tuple) and len(from_node) == 2:
                from_node = VIMor(from_node[0], from_node[1])
            elif not VIMor.is_mor(from_node):
                raise VIException("from_node must be a MOR object or a "
                                  "(<str> mor_id, <str> mor_type) tuple",
                                  FaultTypes.PARAMETER_ERROR)

            request = VI.CreateFilterRequestMsg()
            _this = request.new__this(self._do_service_content.PropertyCollector)
            _this.set_attribute_type(MORTypes.PropertyCollector)
            request.set_element__this(_this)
            request.set_element_partialUpdates(partial_updates)

            spec = request.new_spec()
            propSet = spec.new_propSet()
            propSet.set_element_type(obj_type)
            propSet.set_element_pathSet(property_names)
            spec.set_element_propSet([propSet])

            objects_set = self._get_traversal_objects_set(spec, from_node)
            spec.set_element_objectSet(objects_set)
            request.set_element_spec(spec)

            mor = self._proxy.CreateFilter(request)._returnval
            return mor

        except (VI.ZSI.FaultException), e:
            raise VIApiException(e)
Пример #28
0
def disconnect_nic_from_network(vCenterserver,
                                username,
                                password,
                                datacentername,
                                vmname,
                                dvswitch_uuid,
                                portgroupKey,
                                network_name="VM Network",
                                nic_type="vmxnet3",
                                network_type="standard"):

    con = vs_connect(vCenterserver, username, password)
    vm_obj = con.get_vm_by_name(vmname, datacenter=datacentername)

    #Disconnect 3rd adaptar if its connected to network "VM Network"
    #network_name = "VM Network"
    device_name = "Network adapter 3"

    #Find Virtual Nic device
    net_device = None
    for dev in vmname.properties.config.hardware.device:
        if (dev._type in [
                "VirtualE1000", "VirtualE1000e", "VirtualPCNet32",
                "VirtualVmxnet", "VirtualNmxnet2", "VirtualVmxnet3"
        ] and dev.deviceInfo.label == network_name
                and dev.deviceInfo.summary == device_name):
            net_device = dev._obj
            break

    if not net_device:
        s.disconnect()
        raise Exception("The vm seems to lack a Virtual Nic")

    #Disconnect the device
    net_device.Connectable.Connected = True

    #Invoke ReconfigVM_Task
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vmname._mor)
    _this.set_attribute_type(vmname._mor.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()
    dev_change = spec.new_deviceChange()
    dev_change.set_element_device(net_device)
    dev_change.set_element_operation("edit")
    spec.set_element_deviceChange([dev_change])
    request.set_element_spec(spec)
    ret = s._proxy.ReconfigVM_Task(request)._returnval

    #Wait for the task to finish
    task = VITask(ret, s)

    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    if status == task.STATE_SUCCESS:
        print "VM successfully reconfigured"
    elif status == task.STATE_ERROR:
        print "Error reconfiguring vm:", task.get_error_message()

    s.disconnect()
Пример #29
0
    def deleteVm(self, vmName):
        """
        Delete the vm from disk according to the name passed as argument
        
        @param vmName: name of the virtual machine to delete
        @type vmName: string
        
        @return: True on success, False otherwise
        @rtype: boolean
        """
        ret = False
        if not self.__connected:
            return ret

        # log message
        content = {
            'vsphere-host': self.__host,
            'cmd': 'delete-vm',
            'vm-name': vmName
        }
        tpl = self.template(name=self.__class__.__name__.upper(),
                            content=content)
        self.logRequest(msg="delete vm", details=tpl)

        try:
            try:
                vm = self.__server.get_vm_by_name(vmName)
            except Exception as e:
                raise Exception("VM %s not found!" % vmName)

            request = VI.Destroy_TaskRequestMsg()
            _this = request.new__this(vm._mor)
            _this.set_attribute_type(vm._mor.get_attribute_type())

            request.set_element__this(_this)
            r = self.__server._proxy.Destroy_Task(request)._returnval
            task = VITask(r, self.__server)

            status = task.wait_for_state(
                [task.STATE_SUCCESS, task.STATE_ERROR])
            if status == task.STATE_ERROR:
                raise Exception("Error removing vm:", task.get_error_message())

            ret = True

            content = {
                "result": "success",
                "cmd": "delete-vm",
                'vm-name': vmName
            }
            tpl = self.template(name=self.__class__.__name__.upper(),
                                content=content)
            self.logResponse(msg="delete vm", details=tpl)
        except Exception as e:  # log message
            content = {"vsphere-error": "%s" % e, "cmd": "delete-vm"}
            tpl = self.template(name=self.__class__.__name__.upper(),
                                content=content)
            self.logResponse(msg="delete vm error", details=tpl)
        return ret
Пример #30
0
    def register_vm(self, path, name=None, sync_run=True, folder=None,
                    template=False, resourcepool=None, host=None):
        """Adds an existing virtual machine to the folder.
        @path: a datastore path to the virtual machine.
            Example "[datastore] path/to/machine.vmx".
        @name: the name to be assigned to the virtual machine.
            If this parameter is not set, the displayName configuration
            parameter of the virtual machine is used.
        @sync_run: if True (default) waits for the task to finish, and returns
            a VIVirtualMachine instance with the new VM (raises an exception if
            the task didn't succeed). If @sync_run is set to False the task is
            started and a VITask instance is returned
        @folder_name: folder in which to register the virtual machine.
        @template: Flag to specify whether or not the virtual machine
            should be marked as a template.
        @resourcepool: MOR of the resource pool to which the virtual machine should
            be attached. If imported as a template, this parameter is not set.
        @host: The target host on which the virtual machine will run. This
            parameter must specify a host that is a member of the ComputeResource
            indirectly specified by the pool. For a stand-alone host or a cluster
            with DRS, the parameter can be omitted, and the system selects a default.
        """
        if not folder:
            folders = self._get_managed_objects(MORTypes.Folder)
            folder = [_mor for _mor, _name in folders.iteritems()
                          if _name == 'vm'][0]
        try:
            request = VI.RegisterVM_TaskRequestMsg()
            _this = request.new__this(folder)
            _this.set_attribute_type(folder.get_attribute_type())
            request.set_element__this(_this)
            request.set_element_path(path)
            if name:
                request.set_element_name(name)
            request.set_element_asTemplate(template)
            if resourcepool:
                pool = request.new_pool(resourcepool)
                pool.set_attribute_type(resourcepool.get_attribute_type())
                request.set_element_pool(pool)
            if host:
                if not VIMor.is_mor(host):
                    host = VIMor(host, MORTypes.HostSystem)
                    hs = request.new_host(host)
                    hs.set_attribute_type(host.get_attribute_type())
                    request.set_element_host(hs)

            task = self._proxy.RegisterVM_Task(request)._returnval
            vi_task = VITask(task, self)
            if sync_run:
                status = vi_task.wait_for_state([vi_task.STATE_SUCCESS,
                                                 vi_task.STATE_ERROR])
                if status == vi_task.STATE_ERROR:
                    raise VITaskException(vi_task.info.error)
                return

            return vi_task

        except (VI.ZSI.FaultException), e:
            raise VIApiException(e)