コード例 #1
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)
コード例 #2
0
ファイル: vi_managed_entity.py プロジェクト: dlopes7/pysphere
    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)
コード例 #3
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())
コード例 #4
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)
コード例 #5
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
コード例 #6
0
def destroy_object(mor):
    req = VI.Destroy_TaskRequestMsg()
    _this = req.new__this(mor)
    _this.set_attribute_type(mor.get_attribute_type())
    req.set_element__this(_this)

    task_mor = server._proxy.Destroy_Task(req)._returnval
    return VITask(task_mor, server)
コード例 #7
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
コード例 #8
0
def delete_vm(vm_name):
    vmlist = server.get_registered_vms()
    for vmname in vmlist:
        if vmname.find(vm_name) > 0:
            vm = server.get_vm_by_path(vmname)
            if vm.get_status() == 'POWERED ON':
                vm.power_off()
            request = VI.Destroy_TaskRequestMsg()
            _this = request.new__this(vm._mor)
            _this.set_attribute_type(vm._mor.get_attribute_type())
            request.set_element__this(_this)
            server._proxy.Destroy_Task(request)._returnval
コード例 #9
0
ファイル: install.py プロジェクト: autovmnet/kvm
def delete(serve, machine):
  
  request = VI.Destroy_TaskRequestMsg()

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

  request.set_element__this(_this)

  try:
    serve._proxy.Destroy_Task(request)
  except:
    response(False, log=55)
コード例 #10
0
ファイル: vmware.py プロジェクト: pombredanne/simplestack
def delete_vm(server, vm_obj):
    # Invoke Destroy_Task
    request = VI.Destroy_TaskRequestMsg()
    _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.Destroy_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:delete %s" % task.get_error_message())
コード例 #11
0
def delete_vm_by_name(name, server, remove_files=True):
    """Delete VM

    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.
    """
    # Import
    from pysphere import VITask
    from pysphere.resources import VimService_services as VI

    try:
        #Get VM
        vm = server.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 = server._proxy.Destroy_Task(request)._returnval
            task = VITask(ret, server)

            #Wait for the task to finish
            status = task.wait_for_state([task.STATE_SUCCESS,
                                          task.STATE_ERROR])
            if status == task.STATE_SUCCESS:
                print "VM successfully unregistered and deleted from datastore"
            elif status == task.STATE_ERROR:
                print "Error removing vm:", task.get_error_message()
        elif not remove_files:
            #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 = server._proxy.UnregisterVM(request)
            task = VITask(ret, server)

            print "Done."

    except (VI.ZSI.FaultException), e:
        raise VIApiException(e)
コード例 #12
0
def destroyGuest(host_con, guest_name):
    powerOffGuest(host_con, guest_name)
    try:
        vm = host_con.get_vm_by_name(guest_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 = host_con._proxy.Destroy_Task(request)._returnval
        task = VITask(ret, host_con)
        print 'Waiting for VM to be deleted'
        status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
        if status == task.STATE_SUCCESS:
            result = 'Succesfully removed guest: %s' % guest_name
        elif status == task.STATE_ERROR:
            result = 'Failed to remove VM: %s\n%s' % (guest_name,
                                                      task.get_error_message())
    except Exception as e:
        result = 'Failed to remove VM: %s\n%s' % (guest_name, str(e))
    return result
コード例 #13
0
    def delete_vm(self, vm_name):
        vm = self._get_vm(vm_name)

        if vm.is_powered_on():
            self.stop_vm(vm_name)

        # When pysphere moves up to 0.1.8, we can just do:
        # vm.destroy()
        request = VI.Destroy_TaskRequestMsg()
        _this = request.new__this(vm._mor)
        _this.set_attribute_type(vm._mor.get_attribute_type())
        request.set_element__this(_this)
        rtn = self.api._proxy.Destroy_Task(request)._returnval

        task = VITask(rtn, self.api)
        status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
        if status == task.STATE_SUCCESS:
            return True
        else:
            return False
コード例 #14
0
ファイル: vsphere.py プロジェクト: yairshemla/libcloud
    def destroy_node(self, node, ex_remove_files=True):
        """
        :param ex_remove_files: Remove all the files from the datastore.
        :type ex_remove_files: ``bool``
        """
        ex_remove_files = False
        vm = self._get_vm_for_node(node=node)

        server = self.connection.client

        # Based on code from
        # https://pypi.python.org/pypi/pyxenter
        if ex_remove_files:
            request = VI.Destroy_TaskRequestMsg()

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

            # pylint: disable=no-member
            ret = server._proxy.Destroy_Task(request)._returnva
            # pylint: enable=no-member
            task = VITask(ret, server)

            # Wait for the task to finish
            status = task.wait_for_state(
                [task.STATE_SUCCESS, task.STATE_ERROR])

            if status == task.STATE_ERROR:
                raise LibcloudError('Error destroying node: %s' %
                                    (task.get_error_message()))
        else:
            request = VI.UnregisterVMRequestMsg()

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

        return True
コード例 #15
0
ファイル: vm_helper.py プロジェクト: bradbann/vCenterAPI
 def vm_delete(self, vminstance):
     try:
         for vms in vminstance:
             vm = vms["obj"]
             if vm.is_powered_on(): vm.power_off(sync_run=False)
             # 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.server._proxy.Destroy_Task(request)._returnval
             # Wait for the task to finish
             task = VITask(ret, self.server)
             status = task.wait_for_state(
                 [task.STATE_SUCCESS, task.STATE_ERROR])
             #if status == task.STATE_SUCCESS:
             #   return True
             #elif status == task.STATE_ERROR:
             #   print "Error removing vm:", task.get_error_message()
             #  return False
         return True
     except Exception, e:
         return False
コード例 #16
0
address = get_arg('ip[ip]')

try:
    machine = serve.get_vm_by_name(address)
except:
    response(False)

try:
    status = machine.is_powered_on()
except:
    response(False)

if status:
    try:
        machine.power_off()
    except:
        response(False)

request = VI.Destroy_TaskRequestMsg()

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

request.set_element__this(_this)

try:
    serve._proxy.Destroy_Task(request)
except:
    response(False)

response(True)